Prompt specification
Build or customize the Three.js 3D scene "Adapt a Shared Game Layout" 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: Adapt a Shared Game Layout
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/adapt-a-shared-game-layout-x3684
Scene Description Prompt:
Make a standalone HTML scene with Three.js from cdnjs that depicts characters with varied ages, proportions, and mobility. Create a fictional family game setup with adjustable height, spacing, and seated participation. Test explicit geometric access constraints while allowing several valid arrangements. Voxel style.
Technical checks: Use the actual footprints of the cart and lanes in the obstruction tests. Evaluate each lane separately across the spacing settings and show valid feasible configurations.
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 (adapt-a-shared-game-layout-x3684):
```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="#17313d">
<link rel="icon" href="data:,">
<title>Trilha da Família — Oficina de Acesso</title>
<style>
:root {
--ink: #18313d;
--muted: #667985;
--paper: #fbf7ec;
--panel: rgba(251, 247, 236, 0.96);
--line: #d9dfd8;
--green: #287a68;
--green-soft: #dff1e8;
--red: #b9433b;
--red-soft: #f9e1dc;
--amber: #c77a25;
--amber-soft: #f8ead5;
--blue: #357b9a;
--blue-soft: #dfedf3;
--shadow: 0 16px 45px rgba(20, 47, 57, 0.16);
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #dce8e6;
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
button, input { font: inherit; }
button {
color: inherit;
cursor: pointer;
}
#app {
display: grid;
grid-template-columns: minmax(0, 1fr) 410px;
width: 100%;
height: 100%;
}
#stage {
position: relative;
min-width: 0;
overflow: hidden;
background: linear-gradient(180deg, #d8e8e6 0%, #eef1e7 100%);
}
#viewport {
position: absolute;
inset: 0;
}
#viewport canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
outline: none;
}
.stage-heading {
position: absolute;
top: 24px;
left: 26px;
z-index: 3;
max-width: min(560px, calc(100% - 52px));
pointer-events: none;
}
.eyebrow {
display: inline-flex;
align-items: center;
gap: 7px;
padding: 6px 10px;
border: 1px solid rgba(24, 49, 61, 0.13);
border-radius: 8px;
background: rgba(255, 255, 255, 0.72);
color: #49616c;
font-size: 10px;
font-weight: 850;
letter-spacing: 0.15em;
text-transform: uppercase;
backdrop-filter: blur(8px);
}
.stage-heading h1 {
margin: 10px 0 4px;
font-size: clamp(27px, 3vw, 43px);
line-height: 1;
letter-spacing: -0.045em;
text-shadow: 0 2px 0 rgba(255, 255, 255, 0.55);
}
.stage-heading p {
max-width: 530px;
margin: 9px 0 0;
color: #4d6872;
font-size: 13px;
line-height: 1.45;
text-shadow: 0 1px 0 rgba(255, 255, 255, 0.6);
}
.stage-stats {
position: absolute;
top: 24px;
right: 24px;
z-index: 3;
display: flex;
flex-direction: column;
align-items: flex-end;
gap: 8px;
pointer-events: none;
}
.stat-pill {
padding: 8px 11px;
border: 1px solid rgba(24, 49, 61, 0.12);
border-radius: 9px;
background: rgba(255, 255, 255, 0.76);
color: #4b626c;
font-size: 11px;
font-weight: 750;
box-shadow: 0 6px 20px rgba(37, 69, 78, 0.08);
backdrop-filter: blur(8px);
}
.stage-help {
position: absolute;
left: 24px;
bottom: 22px;
z-index: 3;
display: flex;
align-items: center;
gap: 10px;
padding: 9px 12px;
border: 1px solid rgba(24, 49, 61, 0.12);
border-radius: 10px;
background: rgba(255, 255, 255, 0.74);
color: #536a73;
font-size: 11px;
box-shadow: 0 7px 22px rgba(37, 69, 78, 0.08);
backdrop-filter: blur(8px);
pointer-events: none;
}
.mouse-icon {
width: 15px;
height: 20px;
border: 2px solid #60757e;
border-radius: 8px;
position: relative;
}
.mouse-icon::after {
content: "";
position: absolute;
top: 3px;
left: 5px;
width: 2px;
height: 5px;
border-radius: 2px;
background: #60757e;
}
#panel {
position: relative;
z-index: 5;
height: 100%;
padding: 22px 20px 28px;
overflow-y: auto;
overscroll-behavior: contain;
background: var(--panel);
border-left: 1px solid rgba(29, 57, 66, 0.12);
box-shadow: -14px 0 40px rgba(36, 66, 76, 0.11);
scrollbar-width: thin;
scrollbar-color: #afbbb5 transparent;
}
.panel-title {
margin: 6px 0 5px;
font-size: 25px;
line-height: 1.08;
letter-spacing: -0.035em;
}
.panel-intro {
margin: 0 0 16px;
color: var(--muted);
font-size: 12px;
line-height: 1.5;
}
.objective {
margin-bottom: 16px;
padding: 11px 12px;
border-left: 4px solid var(--amber);
border-radius: 8px;
background: var(--amber-soft);
color: #74512a;
font-size: 11px;
line-height: 1.45;
}
.status-card {
padding: 13px;
border: 1px solid var(--line);
border-radius: 13px;
background: rgba(255, 255, 255, 0.78);
box-shadow: 0 7px 22px rgba(34, 65, 73, 0.06);
}
.status-top {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
}
.status-badge {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 6px 9px;
border-radius: 999px;
font-size: 10px;
font-weight: 850;
letter-spacing: 0.07em;
text-transform: uppercase;
}
.status-badge.valid {
color: var(--green);
background: var(--green-soft);
}
.status-badge.invalid {
color: var(--red);
background: var(--red-soft);
}
.status-score {
color: var(--muted);
font-size: 11px;
font-weight: 700;
}
.status-summary {
margin: 10px 0 3px;
font-size: 15px;
font-weight: 850;
letter-spacing: -0.015em;
}
.status-issue {
min-height: 32px;
margin: 0;
color: var(--muted);
font-size: 11px;
line-height: 1.4;
}
.section-title {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 10px;
margin: 19px 0 9px;
}
.section-title h3 {
margin: 0;
font-size: 12px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.section-title small {
color: var(--muted);
font-size: 10px;
}
.lane-list {
display: grid;
gap: 6px;
}
.lane-row {
display: grid;
grid-template-columns: 68px 53px 1fr;
align-items: center;
gap: 7px;
min-height: 36px;
padding: 7px 9px;
border: 1px solid #e0e5df;
border-radius: 9px;
background: rgba(255, 255, 255, 0.63);
font-size: 11px;
}
.lane-row.bad {
border-color: #edc4bd;
background: var(--red-soft);
}
.lane-name {
font-weight: 800;
}
.lane-count {
justify-self: start;
padding: 3px 6px;
border-radius: 5px;
color: var(--green);
background: var(--green-soft);
font-size: 10px;
font-weight: 850;
}
.lane-row.bad .lane-count {
color: var(--red);
background: rgba(255, 255, 255, 0.7);
}
.lane-detail {
overflow: hidden;
color: var(--muted);
text-overflow: ellipsis;
white-space: nowrap;
}
.lane-row.bad .lane-detail {
color: #8b3e38;
}
.geometry-note {
margin-top: 8px;
padding: 8px 10px;
border-radius: 8px;
background: var(--blue-soft);
color: #416779;
font-size: 10px;
line-height: 1.45;
}
.control-block {
padding: 13px;
border: 1px solid var(--line);
border-radius: 13px;
background: rgba(255, 255, 255, 0.68);
}
.control-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 7px;
}
.control-row label {
font-size: 12px;
font-weight: 800;
}
output {
min-width: 64px;
padding: 4px 7px;
border-radius: 6px;
background: #edf0e9;
color: #3c5964;
font-size: 11px;
font-weight: 850;
text-align: center;
}
input[type="range"] {
width: 100%;
height: 20px;
margin: 0 0 14px;
accent-color: var(--green);
cursor: pointer;
}
input[type="range"]:last-child { margin-bottom: 0; }
.small-note {
margin: -3px 0 12px;
color: var(--muted);
font-size: 10px;
line-height: 1.4;
}
.button-row {
display: flex;
flex-wrap: wrap;
gap: 7px;
}
.btn {
min-height: 34px;
padding: 8px 10px;
border: 1px solid #cfd8d1;
border-radius: 8px;
background: #fffefa;
color: #36535e;
font-size: 11px;
font-weight: 800;
transition: transform 120ms ease, background 120ms ease, border-color 120ms ease;
}
.btn:hover {
transform: translateY(-1px);
border-color: #9fb3aa;
background: #f4f7f0;
}
.btn:active { transform: translateY(0); }
.btn.primary {
border-color: var(--green);
background: var(--green);
color: white;
}
.btn.primary:hover { background: #226c5d; }
.btn.active {
border-color: #71a394;
background: var(--green-soft);
color: #256455;
}
.btn:disabled {
cursor: wait;
opacity: 0.55;
transform: none;
}
.segmented {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 5px;
margin-top: 8px;
}
.segmented .btn {
padding-inline: 5px;
font-size: 10px;
}
.candidate-card {
margin-top: 14px;
padding: 13px;
border: 1px solid var(--line);
border-radius: 13px;
background: rgba(255, 255, 255, 0.68);
}
.candidate-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 9px;
}
.candidate-head strong {
font-size: 13px;
}
.candidate-count {
color: var(--green);
font-size: 19px;
font-weight: 900;
letter-spacing: -0.04em;
}
.audit-callout {
margin: 9px 0;
padding: 9px 10px;
border-radius: 8px;
background: var(--green-soft);
color: #286555;
font-size: 10px;
font-weight: 750;
line-height: 1.45;
}
.audit-callout.fail {
background: var(--red-soft);
color: #943d37;
}
.audit-table {
width: 100%;
border-collapse: collapse;
font-size: 10px;
}
.audit-table th {
padding: 5px 4px;
color: #839197;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.06em;
text-align: left;
text-transform: uppercase;
}
.audit-table td {
padding: 6px 4px;
border-top: 1px solid #e4e8e2;
color: #526871;
}
.audit-table td:nth-child(2) {
color: var(--green);
font-weight: 850;
}
.direction-audit {
margin-top: 9px;
padding: 8px 10px;
border-radius: 8px;
background: #f0f2ec;
color: #607078;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 9px;
line-height: 1.5;
}
.family-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 6px;
}
.person-row {
display: grid;
grid-template-columns: 8px 1fr auto;
align-items: center;
gap: 7px;
min-height: 49px;
padding: 7px;
border: 1px solid #dce2dc;
border-radius: 9px;
background: rgba(255, 255, 255, 0.68);
text-align: left;
}
.person-row:hover { border-color: #aebeb6; }
.person-row.blocked {
border-color: #e9b4ad;
background: var(--red-soft);
}
.person-dot {
width: 8px;
height: 30px;
border-radius: 3px;
}
.person-copy {
min-width: 0;
}
.person-copy b {
display: block;
font-size: 11px;
}
.person-copy small {
display: block;
overflow: hidden;
margin-top: 2px;
color: var(--muted);
font-size: 8px;
text-overflow: ellipsis;
white-space: nowrap;
}
.posture-tag {
padding: 4px 5px;
border-radius: 5px;
background: #edf0ea;
color: #60727a;
font-size: 8px;
font-weight: 850;
text-transform: uppercase;
}
.person-row.blocked .posture-tag {
background: #fff7f5;
color: var(--red);
}
.readout {
margin-top: 8px;
padding: 9px 10px;
border: 1px dashed #cbd4ce;
border-radius: 8px;
color: #536a74;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 9px;
line-height: 1.55;
}
.action-message {
min-height: 15px;
margin-top: 8px;
color: var(--muted);
font-size: 10px;
line-height: 1.4;
}
.camera-buttons {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 6px;
}
#loading {
position: absolute;
inset: 0;
z-index: 8;
display: grid;
place-items: center;
background: #dce8e6;
color: #48636d;
font-size: 13px;
font-weight: 800;
letter-spacing: 0.05em;
text-transform: uppercase;
}
#loading.hidden { display: none; }
@media (max-width: 920px) {
html, body { overflow: auto; }
#app { display: block; height: auto; }
#stage { height: 62vh; min-height: 470px; }
#panel {
height: auto;
overflow: visible;
border-top: 1px solid rgba(29, 57, 66, 0.12);
border-left: 0;
box-shadow: none;
}
.stage-stats { display: none; }
.stage-heading { top: 18px; left: 18px; }
.stage-help { left: 18px; bottom: 15px; }
}
@media (max-width: 520px) {
#panel { padding: 18px 14px 24px; }
.family-grid { grid-template-columns: 1fr; }
.stage-heading p { max-width: 90%; }
.lane-row { grid-template-columns: 58px 48px 1fr; }
}
</style>
</head>
<body>
<div id="app">
<main id="stage">
<div id="viewport"></div>
<div class="stage-heading">
<div class="eyebrow">Oficina de acesso e razonamento espacial</div>
<h1>Trilha da Família</h1>
<p>Monte a ordem da rodada para que cada pessoa alcance o tabuleiro sem conflito entre corpos, rutas e o carrinho de regras.</p>
</div>
<div class="stage-stats">
<div class="stat-pill" id="stageFamilyStat">8 pessoas · 5 sentadas</div>
<div class="stat-pill" id="stageMeasureStat">Mesa 0,76 m · Espaço 0,32 m</div>
</div>
<div class="stage-help">
<span class="mouse-icon"></span>
<span>Arraste para orbitar · roda para aproximar</span>
</div>
<div id="loading">Preparando a mesa da família…</div>
</main>
<aside id="panel">
<div class="eyebrow">Cenário de jogo fictício</div>
<h2 class="panel-title">Uma mesa, oito histórias</h2>
<p class="panel-intro">Bebês, crianças, adolescentes, adultos e idosos ocupam a mesma mesa. Cadeiras, bengala, cadeira de rodas eolveores são voxels, mas os testes usam os volumes reais da cena.</p>
<div class="objective">
<strong>Objetivo didático:</strong> comparar arranjos e escolher uma ordem em que as oitoparticipações permaneçam acessíveis, usando registros espaciais explícitos.
</div>
<div class="status-card" aria-live="polite">
<div class="status-top">
<span class="status-badge invalid" id="currentBadge">Testando</span>
<span class="status-score" id="currentScore">—</span>
</div>
<div class="status-summary" id="currentSummary">Calculando acessos…</div>
<p class="status-issue" id="currentIssue">Lendo a geometria visível dos participantes.</p>
</div>
<div class="section-title">
<h3>Teste das quatro faixas</h3>
<small>acesso atual</small>
</div>
<div class="lane-list">
<div class="lane-row" id="lane-N">
<span class="lane-name">Norte</span>
<span class="lane-count">—</span>
<span class="lane-detail">medindo</span>
</div>
<div class="lane-row" id="lane-E">
<span class="lane-name">Leste</span>
<span class="lane-count">—</span>
<span class="lane-detail">medindo</span>
</div>
<div class="lane-row" id="lane-S">
<span class="lane-name">Sul</span>
<span class="lane-count">—</span>
<span class="lane-detail">medindo</span>
</div>
<div class="lane-row" id="lane-W">
<span class="lane-name">Oeste</span>
<span class="lane-count">—</span>
<span class="lane-detail">medindo</span>
</div>
</div>
<div class="geometry-note">
<strong>Geometria explícita:</strong> rotas e obstáculos são caixas <code>THREE.Box3</code> com limites mín./máx. O carrinho só bloqueia quando sua caixa medida cruza a faixa ou a zona de manobra real.
</div>
<div class="section-title">
<h3>Ajustes da mesa</h3>
<small>escala real em metros</small>
</div>
<div class="control-block">
<div class="control-row">
<label for="heightRange">Altura do tabuleiro</label>
<output id="heightOutput">0,76 m</output>
</div>
<input id="heightRange" type="range" min="0.58" max="0.98" step="0.01" value="0.76">
<div class="control-row">
<label for="spacingRange">Espaço entre lugares</label>
<output id="spacingOutput">0,32 m</output>
</div>
<input id="spacingRange" type="range" min="0.08" max="0.95" step="0.01" value="0.32">
<p class="small-note">A mesa acompanha o perímetro para preservar a folga escolhida entre lugares.</p>
<div class="button-row">
<button class="btn" id="moveCartButton" type="button">Carrinho: Leste</button>
<button class="btn" id="debugButton" type="button">Ver volumes AABB</button>
</div>
</div>
<div class="candidate-card">
<div class="candidate-head">
<strong>24 ordens testadas</strong>
<span class="candidate-count" id="candidateCount">—</span>
</div>
<div class="button-row">
<button class="btn primary" id="applyValidButton" type="button">Aplicar ordem válida</button>
<button class="btn" id="auditButton" type="button">Auditar 5 espaços</button>
</div>
<div class="action-message" id="actionMessage" aria-live="polite"></div>
<div class="audit-callout" id="auditCallout">Executando a auditoria geométrica…</div>
<table class="audit-table" aria-label="Resultado por espaçamento">
<thead>
<tr><th>Espaço</th><th>Válidas</th><th>Bloqueio observado</th></tr>
</thead>
<tbody id="auditRows"></tbody>
</table>
<div class="direction-audit" id="directionAudit">
Direção: aguardando teste com o carrinho em N, L, S e O.
</div>
</div>
<div class="section-title">
<h3>Participação sentada</h3>
<small id="seatedCount">5 de 8 sentadas</small>
</div>
<div class="segmented">
<button class="btn" id="allSeatedButton" type="button">Todos sentados</button>
<button class="btn" id="mixedButton" type="button">Modo misto</button>
<button class="btn" id="allStandingButton" type="button">Em pé</button>
</div>
<div class="family-grid" id="familyGrid" style="margin-top:8px"></div>
<div class="section-title">
<h3>Câmera e diagnóstico</h3>
<small>sem controles externos</small>
</div>
<div class="camera-buttons">
<button class="btn active" id="cameraGeneral" type="button">Geral</button>
<button class="btn" id="cameraTop" type="button">Topo</button>
<button class="btn" id="cameraAccess" type="button">Acesso</button>
</div>
<div class="readout" id="geometryReadout">AABB do carrinho: aguardando medição.</div>
</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 $ = id => document.getElementById(id);
const viewport = $("viewport");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xdce8e6);
scene.fog = new THREE.Fog(0xdce8e6, 8, 16);
const camera = new THREE.PerspectiveCamera(42, 1, 0.05, 40);
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false });
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
viewport.appendChild(renderer.domElement);
const hemi = new THREE.HemisphereLight(0xf8fff5, 0x6c7c78, 2.2);
scene.add(hemi);
const sun = new THREE.DirectionalLight(0xfff2d8, 3.1);
sun.position.set(4.5, 8, 5.5);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -6;
sun.shadow.camera.right = 6;
sun.shadow.camera.top = 6;
sun.shadow.camera.bottom = -6;
sun.shadow.camera.near = 0.5;
sun.shadow.camera.far = 20;
sun.shadow.bias = -0.00025;
scene.add(sun);
const fill = new THREE.DirectionalLight(0xbfe4ef, 1.15);
fill.position.set(-5, 4, -3);
scene.add(fill);
const UNIT_BOX = new THREE.BoxGeometry(1, 1, 1);
UNIT_BOX.computeBoundingBox();
const standard = (color, extra = {}) => new THREE.MeshStandardMaterial({
color,
roughness: 0.82,
metalness: 0.0,
flatShading: true,
...extra
});
const M = {
floorA: standard(0xe6ece3),
floorB: standard(0xdde6dc),
floorBase: standard(0xcbd7cd),
rug: standard(0xc7d7c8),
rugBorder: standard(0x8eafa2),
table: standard(0xd9a85f),
tableEdge: standard(0xf0c67e),
tableLeg: standard(0x315b5c),
chair: standard(0x527d78),
chairSeat: standard(0x7ca39a),
chairDark: standard(0x263c43),
wheel: standard(0x172a30),
wheelHub: standard(0x73b9b0),
cart: standard(0xe06d54),
cartTop: standard(0xf4b36a),
cartMetal: standard(0x455b5f),
boardBase: standard(0x365d66),
boardDark: standard(0x24464e),
white: standard(0xf7f1df),
black: standard(0x243238),
green: standard(0x4d9a72),
red: standard(0xcd665d),
blue: standard(0x538ca5),
yellow: standard(0xe3b84f),
purple: standard(0x876b9c),
plant: standard(0x4f8f62),
plantLight: standard(0x76ae70),
pot: standard(0xb96f52)
};
function block(parent, sx, sy, sz, x, y, z, material, options = {}) {
const mesh = new THREE.Mesh(UNIT_BOX, material);
mesh.scale.set(sx, sy, sz);
mesh.position.set(x, y, z);
mesh.castShadow = options.cast !== false;
mesh.receiveShadow = options.receive !== false;
if (options.noBounds) mesh.userData.noBounds = true;
parent.add(mesh);
return mesh;
}
function actuallyVisible(object) {
let node = object;
while (node) {
if (!node.visible) return false;
node = node.parent;
}
return true;
}
// Every measured volume is a true THREE.Box3 built from visible mesh bounds.
// No polygon or shape is ever passed to an intersection test.
function boundsOf(root) {
const result = new THREE.Box3();
root.updateWorldMatrix(true, true);
root.traverse(object => {
if (!object.isMesh || object.userData.noBounds || !actuallyVisible(object)) return;
if (!object.geometry.boundingBox) object.geometry.computeBoundingBox();
const localBounds = object.geometry.boundingBox.clone();
result.union(localBounds.applyMatrix4(object.matrixWorld));
});
return result;
}
function formatMeters(value) {
return `${value.toFixed(2).replace(".", ",")} m`;
}
function formatBounds(box) {
const f = n => n.toFixed(2).replace(".", ",");
return `x[${f(box.min.x)}, ${f(box.max.x)}] · y[${f(box.min.y)}, ${f(box.max.y)}] · z[${f(box.min.z)}, ${f(box.max.z)}]`;
}
function makeTextSprite(text, background = "#ffffff", foreground = "#18313d") {
const canvas = document.createElement("canvas");
canvas.width = 320;
canvas.height = 72;
const context = canvas.getContext("2d");
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = background;
context.fillRect(0, 0, canvas.width, canvas.height);
context.fillStyle = foreground;
context.font = "800 29px system-ui, sans-serif";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, canvas.width / 2, canvas.height / 2 + 1);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
texture.magFilter = THREE.LinearFilter;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(0.76, 0.17, 1);
sprite.renderOrder = 30;
return sprite;
}
function repaintSprite(sprite, text, background, foreground) {
const canvas = document.createElement("canvas");
canvas.width = 320;
canvas.height = 72;
const context = canvas.getContext("2d");
context.fillStyle = background;
context.fillRect(0, 0, canvas.width, canvas.height);
context.fillStyle = foreground;
context.font = "800 29px system-ui, sans-serif";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, canvas.width / 2, canvas.height / 2 + 1);
const oldTexture = sprite.material.map;
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
texture.magFilter = THREE.LinearFilter;
sprite.material.map = texture;
sprite.material.needsUpdate = true;
if (oldTexture) oldTexture.dispose();
}
function buildEnvironment() {
block(scene, 13, 0.12, 13, 0, -0.09, 0, M.floorBase, { cast: false });
for (let x = -7; x <= 7; x++) {
for (let z = -7; z <= 7; z++) {
const material = (x + z) % 2 === 0 ? M.floorA : M.floorB;
const tile = block(
scene,
0.53,
0.035,
0.53,
x * 0.55,
0.006,
z * 0.55,
material,
{ cast: false }
);
tile.receiveShadow = true;
}
}
const plant = new THREE.Group();
plant.position.set(-3.45, 0, -2.7);
scene.add(plant);
block(plant, 0.48, 0.42, 0.48, 0, 0.21, 0, M.pot);
block(plant, 0.12, 1.0, 0.12, 0, 0.84, 0, M.plant);
block(plant, 0.68, 0.16, 0.22, -0.16, 1.05, 0, M.plantLight);
block(plant, 0.22, 0.16, 0.64, 0.15, 0.92, 0.03, M.plant);
block(plant, 0.5, 0.14, 0.18, 0.12, 1.25, -0.04, M.plantLight);
const toyStack = new THREE.Group();
toyStack.position.set(3.2, 0, -2.65);
scene.add(toyStack);
block(toyStack, 0.42, 0.42, 0.42, 0, 0.21, 0, M.red);
block(toyStack, 0.36, 0.36, 0.36, 0.04, 0.6, 0.03, M.blue);
block(toyStack, 0.31, 0.31, 0.31, -0.03, 0.92, -0.02, M.yellow);
}
let tableTop;
let tableTrim = [];
let tableLegs = [];
let boardRoot;
let rug;
let rugBorder = [];
function buildTableAndBoard() {
rugBorder = [
block(scene, 1, 0.026, 0.055, 0, 0.027, 0.62, M.rugBorder, { cast: false }),
block(scene, 1, 0.026, 0.055, 0, 0.027, -0.62, M.rugBorder, { cast: false }),
block(scene, 0.055, 0.026, 1, 0.62, 0.027, 0, M.rugBorder, { cast: false }),
block(scene, 0.055, 0.026, 1, -0.62, 0.027, 0, M.rugBorder, { cast: false })
];
rug = block(scene, 1, 0.026, 1, 0, 0.026, 0, M.rug, { cast: false });
tableTop = block(scene, 1, 0.09, 1, 0, 0.71, 0, M.table);
tableTrim = [
block(scene, 1, 0.055, 0.055, 0, 0.70, 0.55, M.tableEdge),
block(scene, 1, 0.055, 0.055, 0, 0.70, -0.55, M.tableEdge),
block(scene, 0.055, 0.055, 1, 0.55, 0.70, 0, M.tableEdge),
block(scene, 0.055, 0.055, 1, -0.55, 0.70, 0, M.tableEdge)
];
tableLegs = Array.from({ length: 4 }, () =>
block(scene, 0.13, 0.67, 0.13, 0.4, 0.335, 0.4, M.tableLeg)
);
boardRoot = new THREE.Group();
scene.add(boardRoot);
block(boardRoot, 1.08, 0.035, 1.08, 0, 0, 0, M.boardBase);
const tileColors = [M.green, M.blue, M.yellow, M.red, M.purple];
for (let row = 0; row < 5; row++) {
for (let column = 0; column < 5; column++) {
const onPath = row === column || (row + column === 4) || (row === 2 && column !== 2);
const material = onPath ? tileColors[(row + column) % tileColors.length] : M.boardDark;
block(
boardRoot,
0.17,
0.028,
0.17,
(column - 2) * 0.205,
0.034,
(row - 2) * 0.205,
material
);
}
}
block(boardRoot, 0.12, 0.12, 0.12, -0.31, 0.10, 0.30, M.red);
block(boardRoot, 0.09, 0.09, 0.09, 0.16, 0.09, -0.16, M.blue);
block(boardRoot, 0.10, 0.10, 0.10, 0.34, 0.09, 0.08, M.yellow);
block(boardRoot, 0.08, 0.15, 0.08, -0.10, 0.12, -0.31, M.green);
const die = new THREE.Group();
die.position.set(0.38, 0.105, 0.36);
boardRoot.add(die);
block(die, 0.16, 0.16, 0.16, 0, 0, 0, M.white);
block(die, 0.025, 0.012, 0.025, -0.035, 0.084, -0.035, M.black);
block(die, 0.025, 0.012, 0.025, 0.035, 0.084, 0.035, M.black);
block(die, 0.025, 0.012, 0.025, 0, 0.086, 0, M.black);
}
const cart = new THREE.Group();
function buildCart() {
scene.add(cart);
block(cart, 0.31, 0.30, 0.46, 0, 0.47, 0, M.cart);
block(cart, 0.36, 0.055, 0.50, 0, 0.66, 0, M.cartTop);
block(cart, 0.26, 0.045, 0.28, 0, 0.71, -0.02, M.white);
block(cart, 0.045, 0.24, 0.045, 0.15, 0.83, -0.17, M.cartMetal);
block(cart, 0.045, 0.24, 0.045, -0.15, 0.83, -0.17, M.cartMetal);
block(cart, 0.34, 0.045, 0.045, 0, 0.94, -0.17, M.cartMetal);
for (const x of [-0.17, 0.17]) {
for (const z of [-0.17, 0.17]) {
block(cart, 0.07, 0.17, 0.17, x, 0.14, z, M.wheel);
}
}
const label = makeTextSprite("REGRAS", "#f7c77c", "#473324");
label.position.set(0, 0.56, 0.242);
label.scale.set(0.37, 0.12, 1);
cart.add(label);
}
const PEOPLE_DEFS = [
{
id: "bia", name: "Bia", age: 6, shirt: "#efb63f", skin: "#9a6547", hair: "#38251f",
heightScale: 0.68, widthScale: 0.78, accessWidth: 0.30, mobility: "passos curtos",
seated: true
},
{
id: "leo", name: "Léo", age: 10, shirt: "#4d91a5", skin: "#d59a72", hair: "#5b3826",
heightScale: 0.77, widthScale: 0.82, accessWidth: 0.32, mobility: "agilidade",
seated: false
},
{
id: "rosa", name: "Rosa", age: 67, shirt: "#9b719a", skin: "#c88361", hair: "#d6d0c4",
heightScale: 0.91, widthScale: 1.04, accessWidth: 0.36, turnSize: 0.46,
mobility: "marcha apoiada", seated: true
},
{
id: "nina", name: "Nina", age: 29, shirt: "#dd6557", skin: "#6f4637", hair: "#241d1b",
heightScale: 0.96, widthScale: 0.90, accessWidth: 0.42, turnSize: 0.54,
mobility: "cadeira de rodas", seated: true, alwaysSeated: true
},
{
id: "ravi", name: "Ravi", age: 15, shirt: "#4b9873", skin: "#a56d4b", hair: "#24201d",
heightScale: 0.89, widthScale: 0.89, accessWidth: 0.34, mobility: "passada longa",
seated: false
},
{
id: "maya", name: "Maya", age: 36, shirt: "#d78a45", skin: "#b97854", hair: "#4a2f27",
heightScale: 1.00, widthScale: 1.00, accessWidth: 0.34, mobility: "sem restrições",
seated: false
},
{
id: "artur", name: "Artur", age: 73, shirt: "#6d718f", skin: "#d2a07d", hair: "#ded8cb",
heightScale: 0.92, widthScale: 1.02, accessWidth: 0.38, turnSize: 0.48,
mobility: "bengala", seated: true
},
{
id: "caio", name: "Caio", age: 5, shirt: "#5e9d65", skin: "#744733", hair: "#2e211d",
heightScale: 0.62, widthScale: 0.72, accessWidth: 0.30, mobility: "pequeno tamanho",
seated: true
}
];
const defaultOrder = ["bia", "leo", "rosa", "nina", "ravi", "maya", "artur", "caio"];
const mixedSeated = { bia: true, leo: false, rosa: true, nina: true, ravi: false, maya: false, artur: true, caio: true };
const state = {
height: 0.76,
spacing: 0.32,
order: defaultOrder.slice(),
seated: { ...mixedSeated },
cartSide: "E",
debug: false,
auditRunning: false,
auditQueued: false,
auditRows: [],
directionRows: [],
auditPass: false
};
const peopleRoot = new THREE.Group();
scene.add(peopleRoot);
const personById = new Map();
function buildHead(body, person, centerY, size) {
const skin = person.def.skinMaterial;
const hair = person.def.hairMaterial;
block(body, size, size, size * 0.90, 0, centerY, 0, skin);
block(body, size * 1.03, size * 0.22, size * 0.96, 0, centerY + size * 0.40, -0.015, hair);
block(body, size * 0.96, size * 0.62, size * 0.16, 0, centerY + size * 0.10, -size * 0.40, hair);
block(body, size * 0.13, size * 0.13, 0.025, -size * 0.19, centerY + size * 0.02, size * 0.46, M.black);
block(body, size * 0.13, size * 0.13, 0.025, size * 0.19, centerY + size * 0.02, size * 0.46, M.black);
}
function buildFurniture(person) {
const furniture = person.furniture;
if (person.def.id === "nina") {
block(furniture, 0.36, 0.065, 0.36, 0, 0.445, 0, M.chairSeat);
block(furniture, 0.36, 0.38, 0.065, 0, 0.67, -0.18, M.chair);
for (const x of [-0.225, 0.225]) {
block(furniture, 0.07, 0.34, 0.34, x, 0.235, -0.02, M.wheel);
block(furniture, 0.075, 0.12, 0.12, x + Math.sign(x) * 0.005, 0.235, -0.02, M.wheelHub);
block(furniture, 0.055, 0.10, 0.055, x, 0.09, 0.20, M.chairDark);
}
block(furniture, 0.42, 0.045, 0.045, 0, 0.91, -0.22, M.chairDark);
} else {
block(furniture, 0.42, 0.07, 0.40, 0, 0.435, 0, M.chairSeat);
block(furniture, 0.42, 0.36, 0.065, 0, 0.67, -0.19, M.chair);
for (const x of [-0.17, 0.17]) {
for (const z of [-0.15, 0.15]) {
block(furniture, 0.045, 0.40, 0.045, x, 0.20, z, M.chair);
}
}
}
}
function buildBody(person) {
const body = person.body;
const h = person.def.heightScale;
const w = person.def.widthScale;
const shirt = person.def.shirtMaterial;
const trousers = person.def.trouserMaterial;
const skin = person.def.skinMaterial;
let shoulderY;
let labelY;
if (person.seated) {
const torsoHeight = 0.46 * h;
shoulderY = 0.51 + torsoHeight;
const torsoWidth = 0.31 * w + 0.015;
const torsoDepth = 0.23;
block(body, 0.29 * w, 0.12, 0.24, 0, 0.505, 0.01, trousers);
block(body, torsoWidth, torsoHeight, torsoDepth, 0, shoulderY - torsoHeight / 2, 0, shirt);
for (const x of [-0.09 * w, 0.09 * w]) {
block(body, 0.105, 0.105, 0.29, x, 0.46, 0.16, trousers);
block(body, 0.095, 0.28, 0.095, x, 0.285, 0.285, trousers);
block(body, 0.11, 0.075, 0.18, x, 0.075, 0.315, M.black);
}
for (const x of [-torsoWidth / 2 - 0.045, torsoWidth / 2 + 0.045]) {
block(body, 0.085, 0.23, 0.10, x, shoulderY - 0.105, 0, shirt);
block(body, 0.085, 0.085, 0.23, x, shoulderY - 0.225, 0.105, skin);
}
const headSize = 0.25 * (0.72 + 0.28 * h);
const headY = shoulderY + 0.145 * h;
block(body, 0.09 * h, 0.08, 0.09 * h, 0, shoulderY + 0.04, 0, skin);
buildHead(body, person, headY, headSize);
labelY = headY + headSize * 0.57;
} else {
const hipY = 0.78 * h;
const torsoHeight = 0.48 * h;
shoulderY = hipY + torsoHeight;
const torsoWidth = 0.32 * w + 0.015;
const torsoDepth = 0.23;
block(body, 0.29 * w, 0.14, 0.23, 0, hipY, 0, trousers);
block(body, torsoWidth, torsoHeight, torsoDepth, 0, hipY + torsoHeight / 2, 0, shirt);
const legHeight = 0.70 * h;
for (const x of [-0.09 * w, 0.09 * w]) {
block(body, 0.115, legHeight, 0.13, x, 0.08 + legHeight / 2, 0, trousers);
block(body, 0.125, 0.085, 0.205, x, 0.075, 0.035, M.black);
}
for (const x of [-torsoWidth / 2 - 0.045, torsoWidth / 2 + 0.045]) {
block(body, 0.085, 0.34 * h, 0.10, x, shoulderY - 0.16 * h, 0, shirt);
block(body, 0.075, 0.23, 0.075, x, shoulderY - 0.43 * h, 0.01, skin);
}
const headSize = 0.25 * (0.72 + 0.28 * h);
const headY = shoulderY + 0.145 * h;
block(body, 0.09 * h, 0.08, 0.09 * h, 0, shoulderY + 0.04, 0, skin);
buildHead(body, person, headY, headSize);
labelY = headY + headSize * 0.57;
}
if (person.def.id === "artur") {
block(body, 0.035, person.seated ? 0.76 : 0.84, 0.035, 0.24, person.seated ? 0.39 : 0.42, 0.11, M.tableLeg);
block(body, 0.06, 0.05, 0.06, 0.24, 0.025, 0.11, M.black);
}
person.shoulder = new THREE.Object3D();
person.shoulder.position.set(0, shoulderY, 0);
body.add(person.shoulder);
person.labelY = labelY;
}
function rebuildPerson(person) {
person.furniture.clear();
person.body.clear();
person.seated = person.def.alwaysSeated ? true : !!state.seated[person.def.id];
if (person.seated) buildFurniture(person);
person.furniture.visible = person.seated;
buildBody(person);
repaintSprite(person.label, `${person.def.name} · ${person.def.age}`, person.def.shirt, "#ffffff");
person.label.position.set(0, person.labelY + 0.22, 0);
person.alert.position.set(0, person.labelY + 0.44, 0);
}
function buildPeople() {
for (const def of PEOPLE_DEFS) {
def.shirtMaterial = standard(def.shirt);
def.skinMaterial = standard(def.skin);
def.hairMaterial = standard(def.hair);
def.trouserMaterial = standard(def.id === "nina" ? "#394d59" : "#465b63");
const root = new THREE.Group();
peopleRoot.add(root);
const furniture = new THREE.Group();
const body = new THREE.Group();
root.add(furniture, body);
const label = makeTextSprite(`${def.name} · ${def.age}`, def.shirt, "#ffffff");
const alert = makeTextSprite("!", "#c94d43", "#ffffff");
alert.scale.set(0.19, 0.15, 1);
root.add(label, alert);
const indicatorMaterial = standard(0x5a9b78, { emissive: 0x1f4d3d, emissiveIntensity: 0.15 });
const indicator = block(root, 0.50, 0.012, 0.50, 0, 0.018, 0, indicatorMaterial, {
noBounds: true,
cast: false
});
const person = {
def,
root,
furniture,
body,
label,
alert,
indicator,
seated: state.seated[def.id],
shoulder: null,
labelY: 1
};
rebuildPerson(person);
personById.set(def.id, person);
}
}
const SEAT_SPECS = [
{ side: "N", sign: -1 },
{ side: "N", sign: 1 },
{ side: "E", sign: -1 },
{ side: "E", sign: 1 },
{ side: "S", sign: -1 },
{ side: "S", sign: 1 },
{ side: "W", sign: -1 },
{ side: "W", sign: 1 }
];
const sideNames = { N: "Norte", E: "Leste", S: "Sul", W: "Oeste" };
const sideShort = { N: "N", E: "L", S: "S", W: "O" };
let seats = [];
let tableSize = 1.2;
const laneMarkerGroups = {};
const laneMarkerMaterials = {};
function buildLaneMarkers() {
for (const side of ["N", "E", "S", "W"]) {
const group = new THREE.Group();
const material = standard(0x70a8b8, { emissive: 0x1b5367, emissiveIntensity: 0.12 });
laneMarkerMaterials[side] = material;
for (let i = 0; i < 4; i++) {
block(group, 0.13, 0.014, 0.13, 0, 0, 0, material, { cast: false });
}
laneMarkerGroups[side] = group;
scene.add(group);
}
}
function updateLaneMarkers() {
const half = tableSize / 2;
for (const side of ["N", "E", "S", "W"]) {
const group = laneMarkerGroups[side];
group.children.forEach((marker, index) => {
const distance = half + 0.30 + index * 0.20;
if (side === "N") marker.position.set(0, 0.04, distance);
if (side === "S") marker.position.set(0, 0.04, -distance);
if (side === "E") marker.position.set(distance, 0.04, 0);
if (side === "W") marker.position.set(-distance, 0.04, 0);
});
}
}
function updateTableAndSeats() {
tableSize = 0.88 + state.spacing;
const half = tableSize / 2;
tableTop.scale.set(tableSize, 0.09, tableSize);
tableTop.position.y = state.height - 0.045;
tableTrim[0].scale.set(tableSize, 0.055, 0.055);
tableTrim[0].position.set(0, state.height - 0.055, half - 0.03);
tableTrim[1].scale.set(tableSize, 0.055, 0.055);
tableTrim[1].position.set(0, state.height - 0.055, -half + 0.03);
tableTrim[2].scale.set(0.055, 0.055, tableSize);
tableTrim[2].position.set(half - 0.03, state.height - 0.055, 0);
tableTrim[3].scale.set(0.055, 0.055, tableSize);
tableTrim[3].position.set(-half + 0.03, state.height - 0.055, 0);
const legHeight = Math.max(0.12, state.height - 0.09);
const legOffset = half - 0.14;
const legPositions = [
[-legOffset, -legOffset],
[legOffset, -legOffset],
[-legOffset, legOffset],
[legOffset, legOffset]
];
tableLegs.forEach((leg, index) => {
leg.scale.set(0.13, legHeight, 0.13);
leg.position.set(legPositions[index][0], legHeight / 2, legPositions[index][1]);
});
boardRoot.scale.set(tableSize / 1.20, 1, tableSize / 1.20);
boardRoot.position.y = state.height + 0.008;
rug.scale.set(tableSize + 1.42, 0.026, tableSize + 1.42);
rugBorder[0].scale.set(tableSize + 1.42, 0.026, 0.055);
rugBorder[0].position.z = (tableSize + 1.42) / 2;
rugBorder[1].scale.set(tableSize + 1.42, 0.026, 0.055);
rugBorder[1].position.z = -(tableSize + 1.42) / 2;
rugBorder[2].scale.set(0.055, 0.026, tableSize + 1.42);
rugBorder[2].position.x = (tableSize + 1.42) / 2;
rugBorder[3].scale.set(0.055, 0.026, tableSize + 1.42);
rugBorder[3].position.x = -(tableSize + 1.42) / 2;
seats = SEAT_SPECS.map((spec, index) => ({
index,
side: spec.side,
sign: spec.sign,
tangent: spec.sign * (0.44 + state.spacing) / 2,
tableEdge: half
}));
updateLaneMarkers();
}
function placeOrder(order) {
order.forEach((id, index) => {
const person = personById.get(id);
const seat = seats[index];
const offset = person.seated ? (person.def.id === "nina" ? 0.41 : 0.37) : 0.48;
const normal = seat.tableEdge + offset;
if (seat.side === "N") {
person.root.position.set(seat.tangent, 0, normal);
person.root.rotation.y = Math.PI;
} else if (seat.side === "S") {
person.root.position.set(seat.tangent, 0, -normal);
person.root.rotation.y = 0;
} else if (seat.side === "E") {
person.root.position.set(normal, 0, seat.tangent);
person.root.rotation.y = -Math.PI / 2;
} else {
person.root.position.set(-normal, 0, seat.tangent);
person.root.rotation.y = Math.PI / 2;
}
});
}
function seatIndex(side, sign = 1) {
return seats.findIndex(seat => seat.side === side && seat.sign === sign);
}
function updateCart() {
const positiveSeat = seats[seatIndex(state.cartSide, 1)];
if (!positiveSeat) return;
const normal = positiveSeat.tableEdge + 0.78;
const tangent = positiveSeat.tangent + 0.50;
if (state.cartSide === "N") {
cart.position.set(tangent, 0, normal);
cart.rotation.y = 0;
} else if (state.cartSide === "S") {
cart.position.set(tangent, 0, -normal);
cart.rotation.y = Math.PI;
} else if (state.cartSide === "E") {
cart.position.set(normal, 0, tangent);
cart.rotation.y = -Math.PI / 2;
} else {
cart.position.set(-normal, 0, tangent);
cart.rotation.y = Math.PI / 2;
}
}
function makeRouteBox(seat, person, turning = false) {
const halfWidth = turning ? person.def.turnSize / 2 : person.def.accessWidth / 2;
const tangent = turning
? seat.tangent + Math.sign(seat.tangent || 1) * 0.28
: seat.tangent;
const near = seat.tableEdge + (turning ? 0.38 : 0.025);
const far = seat.tableEdge + 1.12;
let minX, maxX, minZ, maxZ;
if (seat.side === "N") {
minX = tangent - halfWidth; maxX = tangent + halfWidth;
minZ = near; maxZ = far;
} else if (seat.side === "S") {
minX = tangent - halfWidth; maxX = tangent + halfWidth;
minZ = -far; maxZ = -near;
} else if (seat.side === "E") {
minX = near; maxX = far;
minZ = tangent - halfWidth; maxZ = tangent + halfWidth;
} else {
minX = -far; maxX = -near;
minZ = tangent - halfWidth; maxZ = tangent + halfWidth;
}
return new THREE.Box3(
new THREE.Vector3(minX, 0, minZ),
new THREE.Vector3(maxX, 2.30, maxZ)
);
}
function uniqueBlockers(blockers) {
const seen = new Set();
return blockers.filter(blocker => {
const key = `${blocker.kind}|${blocker.label}|${blocker.context || ""}`;
if (seen.has(key)) return false;
seen.add(key);
return true;
});
}
function validateOrder(order) {
placeOrder(order);
scene.updateMatrixWorld(true);
const tableObstacles = [
{ kind: "table", label: "tampo da mesa", box: boundsOf(tableTop) },
...tableLegs.map((leg, index) => ({
kind: "table",
label: `pé da mesa ${index + 1}`,
box: boundsOf(leg)
}))
];
const occupancy = order.map(id => boundsOf(personById.get(id).root));
const cartBox = boundsOf(cart);
const accesses = [];
const issues = [];
const cartHitSides = new Set();
order.forEach((id, index) => {
const person = personById.get(id);
const seat = seats[index];
const primary = makeRouteBox(seat, person, false);
const turning = person.def.turnSize ? makeRouteBox(seat, person, true) : null;
const blockers = [];
const inspectRoute = (route, context) => {
if (!route) return;
for (const obstacle of tableObstacles) {
if (route.intersectsBox(obstacle.box)) {
blockers.push({ kind: obstacle.kind, label: obstacle.label, context });
}
}
for (let other = 0; other < occupancy.length; other++) {
if (other === index) continue;
if (route.intersectsBox(occupancy[other])) {
blockers.push({
kind: "occupancy",
label: `ocupação de ${personById.get(order[other]).def.name}`,
context
});
}
}
if (route.intersectsBox(cartBox)) {
blockers.push({ kind: "cart", label: "carrinho de regras", context });
}
};
inspectRoute(primary, "rota de acesso");
inspectRoute(turning, "zona de manobra");
const unique = uniqueBlockers(blockers);
for (const blocker of unique) {
if (blocker.kind === "cart") cartHitSides.add(seat.side);
}
const shoulderPosition = person.shoulder.getWorldPosition(new THREE.Vector3());
const lowerReach = shoulderPosition.y - (person.seated ? 0.43 : 0.52);
const upperReach = shoulderPosition.y + 0.18;
const reachesTable = state.height >= lowerReach && state.height <= upperReach;
if (!reachesTable) {
issues.push({
type: "reach",
person: id,
side: seat.side,
blockers: [{
kind: "reach",
label: "altura do tabuleiro fora do alcance",
context: "alcance"
}]
});
}
if (unique.length) {
issues.push({
type: "access",
person: id,
side: seat.side,
blockers: unique
});
}
accesses.push({
person: id,
seat,
primary,
turning,
blockers: unique,
ok: unique.length === 0 && reachesTable
});
});
for (let i = 0; i < occupancy.length; i++) {
for (let j = i + 1; j < occupancy.length; j++) {
if (occupancy[i].intersectsBox(occupancy[j])) {
issues.push({
type: "overlap",
person: order[i],
other: order[j],
side: seats[i].side,
blockers: [{
kind: "overlap",
label: `volume de ${personById.get(order[j]).def.name}`,
context: "ocupações sobrepostas"
}]
});
}
}
}
occupancy.forEach((box, index) => {
if (box.intersectsBox(cartBox)) {
issues.push({
type: "cart-overlap",
person: order[index],
side: seats[index].side,
blockers: [{
kind: "cart",
label: "carrinho de regras",
context: "colisão física"
}]
});
cartHitSides.add(seats[index].side);
}
});
const laneStats = {};
for (const side of ["N", "E", "S", "W"]) {
const sideAccesses = accesses.filter(access => access.seat.side === side);
laneStats[side] = {
total: sideAccesses.length,
valid: sideAccesses.filter(access => access.ok).length,
accesses: sideAccesses
};
}
return {
valid: issues.length === 0,
issues,
accesses,
occupancy,
cartBox,
laneStats,
cartHitSides
};
}
const debugGroup = new THREE.Group();
debugGroup.visible = false;
scene.add(debugGroup);
function clearDebugGroup() {
while (debugGroup.children.length) {
const child = debugGroup.children.pop();
child.traverse(object => {
if (object.geometry) object.geometry.dispose();
if (object.material) {
if (Array.isArray(object.material)) object.material.forEach(material => material.dispose());
else object.material.dispose();
}
});
}
}
function addDebugBox(box, color, opacity = 0.08) {
const size = box.getSize(new THREE.Vector3());
const center = box.getCenter(new THREE.Vector3());
const geometry = new THREE.BoxGeometry(1, 1, 1);
const fill = new THREE.Mesh(
geometry,
new THREE.MeshBasicMaterial({ color, transparent: true, opacity, depthWrite: false })
);
fill.position.copy(center);
fill.scale.copy(size);
debugGroup.add(fill);
const edgeGeometry = new THREE.EdgesGeometry(new THREE.BoxGeometry(1, 1, 1));
const edges = new THREE.LineSegments(
edgeGeometry,
new THREE.LineBasicMaterial({ color, transparent: true, opacity: 0.92 })
);
edges.position.copy(center);
edges.scale.copy(size);
debugGroup.add(edges);
}
function updateDebug() {
clearDebugGroup();
debugGroup.visible = state.debug;
if (!state.debug || !state.currentValidation) return;
addDebugBox(boundsOf(tableTop), 0x3c9b70, 0.06);
addDebugBox(state.currentValidation.cartBox, 0xe57c32, 0.16);
for (const access of state.currentValidation.accesses) {
addDebugBox(access.primary, 0x3e8db0, 0.045);
if (access.turning) addDebugBox(access.turning, 0xa15d9b, 0.09);
}
}
function updateIndicators(validation) {
const statusById = {};
validation.accesses.forEach(access => { statusById[access.person] = access.ok; });
for (const person of personById.values()) {
const ok = statusById[person.def.id] !== false;
person.alert.visible = !ok;
person.indicator.material.color.setHex(ok ? 0x5a9b78 : 0xc94d43);
person.indicator.material.emissive.setHex(ok ? 0x1f4d3d : 0x6d1e19);
}
}
function describeIssue(issue) {
if (!issue) return "Nenhum conflito detectado.";
const name = personById.get(issue.person)?.def.name || issue.person;
if (issue.type === "overlap") {
return `${name}: volume sobreposto a ${personById.get(issue.other).def.name}.`;
}
const details = issue.blockers.map(blocker => blocker.label).join(", ");
return `${name}: ${details}.`;
}
function renderCurrent() {
const validation = state.currentValidation;
if (!validation) return;
const good = validation.accesses.filter(access => access.ok).length;
$("currentBadge").textContent = validation.valid ? "Arranjo válido" : "Ajuste necessário";
$("currentBadge").className = `status-badge ${validation.valid ? "valid" : "invalid"}`;
$("currentScore").textContent = `${good}/${validation.accesses.length} acessos`;
$("currentSummary").textContent = validation.valid
? "Todas asEight participações têm rota válida."
: `${validation.issues.length} conflito${validation.issues.length === 1 ? "" : "s"} geométrico${validation.issues.length === 1 ? "" : "s"} detectado${validation.issues.length === 1 ? "" : "s"}.`;
$("currentIssue").textContent = describeIssue(validation.issues[0]);
for (const side of ["N", "E", "S", "W"]) {
const row = $(`lane-${side}`);
const stats = validation.laneStats[side];
const count = row.querySelector(".lane-count");
const detail = row.querySelector(".lane-detail");
const blocked = stats.valid < stats.total;
row.classList.toggle("bad", blocked);
count.textContent = `${stats.valid}/${stats.total}`;
const blockerNames = [];
for (const access of stats.accesses) {
if (access.ok) continue;
const name = personById.get(access.person).def.name;
for (const blocker of access.blockers) {
blockerNames.push(`${name} · ${blocker.label}`);
}
}
detail.textContent = blocked ? blockerNames.join(" / ") : "faixa livre";
laneMarkerMaterials[side].color.setHex(blocked ? 0xd47a43 : 0x70a8b8);
laneMarkerMaterials[side].emissive.setHex(blocked ? 0x6f321b : 0x1b5367);
}
$("geometryReadout").textContent = `AABB real do carrinho: ${formatBounds(validation.cartBox)}\nRotas: THREE.Box3(min, max) · interseção: intersectsBox().`;
const seatedCount = Object.values(state.seated).filter(Boolean).length + (state.seated.nina ? 0 : 1);
$("seatedCount").textContent = `${seatedCount} de 8 sentadas`;
$("stageFamilyStat").textContent = `8 pessoas · ${seatedCount} sentadas`;
$("stageMeasureStat").textContent = `Mesa ${formatMeters(state.height)} · Espaço ${formatMeters(state.spacing)}`;
$("heightOutput").textContent = formatMeters(state.height);
$("spacingOutput").textContent = formatMeters(state.spacing);
$("moveCartButton").textContent = `Carrinho: ${sideNames[state.cartSide]}`;
const currentAudit = state.auditRows.find(row => Math.abs(row.spacing - state.spacing) < 0.0001);
$("candidateCount").textContent = currentAudit ? `${currentAudit.validCount}/24` : "—";
for (const person of personById.values()) {
const button = document.querySelector(`[data-person="${person.def.id}"]`);
if (!button) continue;
const blocked = validation.accesses.some(access => access.person === person.def.id && !access.ok);
button.classList.toggle("blocked", blocked);
const tag = button.querySelector(".posture-tag");
tag.textContent = person.def.alwaysSeated ? "Rodas" : (person.seated ? "Sentada" : "Em pé");
}
}
function renderAudit() {
$("auditRows").innerHTML = state.auditRows.map(row => `
<tr>
<td>${row.spacing.toFixed(2).replace(".", ",")} m</td>
<td>${row.validCount}/24</td>
<td>${row.blockers || "—"}</td>
</tr>
`).join("");
if (state.auditRunning) {
$("auditCallout").className = "audit-callout";
$("auditCallout").textContent = "Executando a auditoria geométrica…";
} else if (state.auditPass) {
$("auditCallout").className = "audit-callout";
$("auditCallout").textContent = "OK: os cinco espaçamentos mantêm várias ordens válidas; o carrinho cruza somente a faixa testada.";
} else {
$("auditCallout").className = "audit-callout fail";
$("auditCallout").textContent = "A auditoria encontrou uma inconsistência. Consulte a geometria destacada.";
}
if (state.directionRows.length) {
$("directionAudit").textContent = state.directionRows.map(row => {
const hits = row.hits.length ? row.hits.map(side => sideShort[side]).join("+") : "—";
return `${sideShort[row.tested]}→${hits}${row.pass ? " OK" : " falha"}`;
}).join(" · ");
}
}
function shuffleWithSeed(array, seed) {
const result = array.slice();
let value = seed >>> 0;
const random = () => {
value = (value * 1664525 + 1013904223) >>> 0;
return value / 4294967296;
};
for (let i = result.length - 1; i > 0; i--) {
const j = Math.floor(random() * (i + 1));
[result[i], result[j]] = [result[j], result[i]];
}
return result;
}
function generateCandidateOrders(base) {
const result = [];
const seen = new Set();
const add = order => {
const key = order.join("|");
if (seen.has(key)) return;
seen.add(key);
result.push(order.slice());
};
const swap = (array, a, b) => {
const copy = array.slice();
[copy[a], copy[b]] = [copy[b], copy[a]];
return copy;
};
add(base);
const blockedSeat = seatIndex(state.cartSide, 1);
const ninaIndex = base.indexOf("nina");
const arturIndex = base.indexOf("artur");
add(swap(base, ninaIndex, blockedSeat));
let alternateSeat = (blockedSeat + 3) % base.length;
add(swap(base, ninaIndex, alternateSeat));
add(swap(base, arturIndex, blockedSeat));
let seed = 7319;
let attempts = 0;
while (result.length < 24 && attempts < 500) {
add(shuffleWithSeed(base, seed++));
attempts++;
}
return result;
}
function applyScene() {
updateTableAndSeats();
updateCart();
state.currentValidation = validateOrder(state.order);
updateIndicators(state.currentValidation);
updateDebug();
renderCurrent();
}
async function runFullAudit() {
if (state.auditRunning) {
state.auditQueued = true;
return;
}
state.auditRunning = true;
$("auditButton").disabled = true;
renderAudit();
const snapshot = {
height: state.height,
spacing: state.spacing,
cartSide: state.cartSide,
order: state.order.slice()
};
const candidates = generateCandidateOrders(snapshot.order);
const spacingRows = [];
await new Promise(resolve => setTimeout(resolve, 30));
try {
for (const spacing of [0.08, 0.25, 0.48, 0.70, 0.95]) {
state.spacing = spacing;
updateTableAndSeats();
updateCart();
let validCount = 0;
const observedBlockers = new Set();
for (const candidate of candidates) {
const validation = validateOrder(candidate);
if (validation.valid) {
validCount++;
} else {
for (const access of validation.accesses) {
for (const blocker of access.blockers) observedBlockers.add(blocker.label);
}
for (const issue of validation.issues) {
if (issue.type === "overlap") observedBlockers.add("ocupações sobrepostas");
if (issue.type === "reach") observedBlockers.add("alcance");
}
}
}
const blockerText = observedBlockers.size
? [...observedBlockers].slice(0, 2).join(", ")
: "—";
spacingRows.push({ spacing, validCount, blockers: blockerText });
}
state.spacing = snapshot.spacing;
updateTableAndSeats();
const directionRows = [];
for (const side of ["N", "E", "S", "W"]) {
state.cartSide = side;
updateCart();
const targetSeat = seatIndex(side, 1);
const testOrder = snapshot.order.slice();
const ninaIndex = testOrder.indexOf("nina");
testOrder.splice(ninaIndex, 1);
testOrder.splice(targetSeat, 0, "nina");
const validation = validateOrder(testOrder);
const hits = new Set(validation.cartHitSides);
directionRows.push({
tested: side,
hits: [...hits],
pass: hits.size === 1 && hits.has(side)
});
}
state.height = snapshot.height;
state.spacing = snapshot.spacing;
state.cartSide = snapshot.cartSide;
state.order = snapshot.order.slice();
state.auditRows = spacingRows;
state.directionRows = directionRows;
state.auditPass =
spacingRows.every(row => row.validCount >= 2) &&
directionRows.every(row => row.pass);
applyScene();
renderAudit();
console.info("Auditoria AABB concluída", {
espacamentos: spacingRows,
direcoes: directionRows,
aprovado: state.auditPass
});
} finally {
state.auditRunning = false;
$("auditButton").disabled = false;
renderAudit();
if (state.auditQueued) {
state.auditQueued = false;
setTimeout(runFullAudit, 60);
}
}
}
let auditTimer = null;
function scheduleAudit() {
clearTimeout(auditTimer);
auditTimer = setTimeout(runFullAudit, 220);
}
function applyValidOrder() {
const candidates = generateCandidateOrders(state.order);
let chosen = null;
let fallback = null;
let fallbackIssueCount = Infinity;
for (const candidate of candidates) {
const validation = validateOrder(candidate);
if (validation.valid && !chosen) chosen = candidate;
if (!fallback || validation.issues.length < fallbackIssueCount) {
fallback = candidate;
fallbackIssueCount = validation.issues.length;
}
}
if (chosen || fallback) {
state.order = (chosen || fallback).slice();
applyScene();
$("actionMessage").textContent = chosen
? "Ordem válida aplicada: todas as rotas e ocupações passaram."
: "Nenhuma das 24 ordens是完全 válida; foi aplicada a de menor conflito.";
scheduleAudit();
}
}
function buildFamilyControls() {
const grid = $("familyGrid");
for (const person of personById.values()) {
const button = document.createElement("button");
button.type = "button";
button.className = "person-row";
button.dataset.person = person.def.id;
button.innerHTML = `
<span class="person-dot" style="background:${person.def.shirt}"></span>
<span class="person-copy">
<b>${person.def.name} · ${person.def.age} anos</b>
<small>${person.def.mobility}</small>
</span>
<span class="posture-tag">${person.seated ? "Sentada" : "Em pé"}</span>
`;
button.addEventListener("click", () => {
if (person.def.alwaysSeated) {
$("actionMessage").textContent = "Nina permanece sentada para preservar o uso da cadeira de rodas.";
return;
}
state.seated[person.def.id] = !state.seated[person.def.id];
rebuildPerson(person);
applyScene();
scheduleAudit();
});
grid.appendChild(button);
}
}
function setPostureMode(mode) {
for (const def of PEOPLE_DEFS) {
if (def.alwaysSeated) {
state.seated[def.id] = true;
} else if (mode === "seated") {
state.seated[def.id] = true;
} else if (mode === "standing") {
state.seated[def.id] = false;
} else {
state.seated[def.id] = mixedSeated[def.id];
}
}
for (const person of personById.values()) rebuildPerson(person);
applyScene();
scheduleAudit();
}
const cameraState = {
yaw: 0.72,
pitch: 0.62,
radius: 6.35,
target: new THREE.Vector3(0, 0.62, 0)
};
function updateCamera() {
const horizontal = cameraState.radius * Math.cos(cameraState.pitch);
camera.position.set(
cameraState.target.x + horizontal * Math.sin(cameraState.yaw),
cameraState.target.y + cameraState.radius * Math.sin(cameraState.pitch),
cameraState.target.z + horizontal * Math.cos(cameraState.yaw)
);
camera.lookAt(cameraState.target);
}
function setCameraView(view) {
const activeButtons = [$("cameraGeneral"), $("cameraTop"), $("cameraAccess")];
activeButtons.forEach(button => button.classList.remove("active"));
if (view === "top") {
cameraState.yaw = 0;
cameraState.pitch = 1.43;
cameraState.radius = 5.6 + tableSize * 0.45;
cameraState.target.set(0, 0.35, 0);
$("cameraTop").classList.add("active");
} else if (view === "access") {
cameraState.yaw = -Math.PI / 2;
cameraState.pitch = 0.42;
cameraState.radius = 4.8 + tableSize * 0.35;
cameraState.target.set(tableSize * 0.18, 0.58, 0);
$("cameraAccess").classList.add("active");
} else {
cameraState.yaw = 0.72;
cameraState.pitch = 0.62;
cameraState.radius = 6.35;
cameraState.target.set(0, 0.62, 0);
$("cameraGeneral").classList.add("active");
}
updateCamera();
}
let dragging = false;
let pointerX = 0;
let pointerY = 0;
renderer.domElement.addEventListener("pointerdown", event => {
dragging = true;
pointerX = event.clientX;
pointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", event => {
if (!dragging) return;
const dx = event.clientX - pointerX;
const dy = event.clientY - pointerY;
pointerX = event.clientX;
pointerY = event.clientY;
cameraState.yaw -= dx * 0.006;
cameraState.pitch = THREE.MathUtils.clamp(cameraState.pitch + dy * 0.004, 0.22, 1.46);
updateCamera();
});
renderer.domElement.addEventListener("pointerup", event => {
dragging = false;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
});
renderer.domElement.addEventListener("pointercancel", () => { dragging = false; });
renderer.domElement.addEventListener("wheel", event => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(cameraState.radius + event.deltaY * 0.0045, 3.4, 10.5);
updateCamera();
}, { passive: false });
function resize() {
const width = Math.max(1, viewport.clientWidth);
const height = Math.max(1, viewport.clientHeight);
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
updateCamera();
}
$("heightRange").addEventListener("input", event => {
state.height = Number(event.target.value);
applyScene();
scheduleAudit();
});
$("spacingRange").addEventListener("input", event => {
state.spacing = Number(event.target.value);
applyScene();
scheduleAudit();
});
$("moveCartButton").addEventListener("click", () => {
const sides = ["N", "E", "S", "W"];
state.cartSide = sides[(sides.indexOf(state.cartSide) + 1) % sides.length];
applyScene();
$("actionMessage").textContent = `Carrinho movido para ${sideNames[state.cartSide]}; o teste usa a nova caixa medida.`;
scheduleAudit();
});
$("debugButton").addEventListener("click", () => {
state.debug = !state.debug;
$("debugButton").classList.toggle("active", state.debug);
$("debugButton").textContent = state.debug ? "Ocultar volumes AABB" : "Ver volumes AABB";
updateDebug();
});
$("applyValidButton").addEventListener("click", applyValidOrder);
$("auditButton").addEventListener("click", runFullAudit);
$("allSeatedButton").addEventListener("click", () => setPostureMode("seated"));
$("mixedButton").addEventListener("click", () => setPostureMode("mixed"));
$("allStandingButton").addEventListener("click", () => setPostureMode("standing"));
$("cameraGeneral").addEventListener("click", () => setCameraView("general"));
$("cameraTop").addEventListener("click", () => setCameraView("top"));
$("cameraAccess").addEventListener("click", () => setCameraView("access"));
buildEnvironment();
buildTableAndBoard();
buildCart();
buildLaneMarkers();
buildPeople();
buildFamilyControls();
applyScene();
resize();
if ("ResizeObserver" in window) {
new ResizeObserver(resize).observe(viewport);
} else {
window.addEventListener("resize", resize);
}
renderer.setAnimationLoop(() => {
updateCamera();
renderer.render(scene, camera);
});
requestAnimationFrame(() => {
$("loading").classList.add("hidden");
runFullAudit();
});
</script>
</body>
</html>
```