Prompt specification
Build or customize the Three.js 3D scene "Delivery van loading teaching scene" 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: Delivery van loading teaching scene
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/delivery-van-loading-teaching-scene-x1711
Scene Description Prompt:
Pack labeled boxes into a voxel delivery van, comparing geometric fit rather than realistic loading safety. Use Three.js from cdnjs in standalone HTML.
Technical checks: Check each box against the actual cargo dimensions and the other boxes. Keep all packed boxes within the transparent compartment in both top and side views.
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 (delivery-van-loading-teaching-scene-x1711):
```html
<!doctype html>
<html lang="pt-BR">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>VoxelFit — Encaixe geométrico em van</title>
<style>
:root {
--ink: #17343a;
--muted: #64777c;
--line: #d9e3e6;
--panel: #f7fafb;
--teal: #176f78;
--teal-dark: #0f5159;
--orange: #ef8354;
--green: #25845f;
--red: #b94747;
--shadow: 0 14px 34px rgba(23, 52, 58, .13);
}
* { box-sizing: border-box; }
[hidden] { display: none !important; }
html, body {
width: 100%;
min-height: 100%;
margin: 0;
}
body {
color: var(--ink);
background: #eaf1f2;
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
overflow: hidden;
}
button, input, select { font: inherit; }
button { color: inherit; }
.app {
width: 100%;
height: 100dvh;
display: flex;
flex-direction: column;
}
.topbar {
min-height: 72px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 20px;
padding: 12px 22px;
color: white;
background: #153d43;
border-bottom: 1px solid rgba(255,255,255,.08);
z-index: 4;
}
.brand {
min-width: 0;
display: flex;
align-items: center;
gap: 13px;
}
.logo {
width: 38px;
height: 38px;
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 3px;
padding: 5px;
border: 1px solid rgba(255,255,255,.3);
border-radius: 10px;
background: rgba(255,255,255,.08);
transform: rotate(-2deg);
}
.logo i {
display: block;
background: #f3a15f;
border-radius: 2px;
}
.logo i:nth-child(2) { background: #75c9c4; }
.logo i:nth-child(3) { background: #75c9c4; }
.logo i:nth-child(4) { background: #f7d28a; }
.brand-copy { min-width: 0; }
.brand-copy h1 {
margin: 0;
font-size: 19px;
line-height: 1.1;
letter-spacing: .01em;
}
.brand-copy p {
margin: 4px 0 0;
color: #bcd2d5;
font-size: 12px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.top-actions {
display: flex;
align-items: center;
gap: 10px;
}
.scope-chip {
display: inline-flex;
align-items: center;
gap: 7px;
padding: 7px 10px;
color: #d8eeee;
background: rgba(255,255,255,.08);
border: 1px solid rgba(255,255,255,.12);
border-radius: 999px;
font-size: 11px;
font-weight: 700;
letter-spacing: .04em;
text-transform: uppercase;
}
.scope-chip::before {
content: "";
width: 7px;
height: 7px;
background: #74d1a8;
border-radius: 50%;
box-shadow: 0 0 0 3px rgba(116,209,168,.13);
}
.ghost-button {
min-height: 36px;
padding: 8px 13px;
border: 1px solid rgba(255,255,255,.2);
border-radius: 9px;
color: white;
background: rgba(255,255,255,.08);
cursor: pointer;
font-size: 12px;
font-weight: 750;
}
.ghost-button:hover { background: rgba(255,255,255,.15); }
.layout {
min-height: 0;
flex: 1;
display: grid;
grid-template-columns: 350px minmax(0, 1fr);
}
.sidebar {
min-height: 0;
overflow-y: auto;
padding: 17px;
background: var(--panel);
border-right: 1px solid var(--line);
scrollbar-width: thin;
}
.card {
margin-bottom: 13px;
padding: 15px;
background: white;
border: 1px solid var(--line);
border-radius: 14px;
box-shadow: 0 4px 16px rgba(23,52,58,.035);
}
.section-head {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 12px;
margin-bottom: 12px;
}
.section-head h2 {
margin: 0;
font-size: 13px;
letter-spacing: .045em;
text-transform: uppercase;
}
.section-head span {
color: var(--muted);
font-size: 11px;
}
.bay-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 8px;
}
.field label,
.dimension-field span {
display: block;
margin-bottom: 5px;
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: .06em;
text-transform: uppercase;
}
.field input,
.select-wrap select,
.dimension-field input {
width: 100%;
height: 36px;
padding: 7px 9px;
color: var(--ink);
background: #f8fbfb;
border: 1px solid #ccdadd;
border-radius: 8px;
outline: none;
font-weight: 750;
}
.field input:focus,
.select-wrap select:focus,
.dimension-field input:focus {
border-color: var(--teal);
box-shadow: 0 0 0 3px rgba(23,111,120,.12);
}
.select-wrap { margin-top: 10px; }
.select-wrap select { cursor: pointer; }
.mini-stats {
display: flex;
justify-content: space-between;
gap: 10px;
margin-top: 10px;
padding-top: 9px;
border-top: 1px dashed var(--line);
color: var(--muted);
font-size: 11px;
}
.mini-stats strong { color: var(--ink); }
.box-list {
display: grid;
gap: 7px;
}
.box-row {
display: grid;
grid-template-columns: minmax(108px, 1fr) auto;
align-items: center;
gap: 9px;
padding: 8px;
border: 1px solid #e0e9eb;
border-radius: 10px;
background: #fbfdfd;
transition: border-color .15s, background .15s, transform .15s;
}
.box-row.selected {
border-color: #e4a55e;
background: #fff9ef;
transform: translateX(2px);
}
.box-pick {
min-width: 0;
display: flex;
align-items: center;
gap: 7px;
padding: 0;
border: 0;
background: transparent;
cursor: pointer;
text-align: left;
}
.swatch {
width: 10px;
height: 30px;
flex: 0 0 auto;
border-radius: 4px;
box-shadow: inset 0 0 0 1px rgba(0,0,0,.08);
}
.box-code {
color: var(--muted);
font: 800 11px ui-monospace, SFMono-Regular, Menlo, monospace;
}
.box-name {
min-width: 0;
overflow: hidden;
color: var(--ink);
font-size: 12px;
font-weight: 800;
text-overflow: ellipsis;
white-space: nowrap;
}
.dimension-fields {
display: flex;
align-items: end;
gap: 3px;
}
.dimension-field { width: 43px; }
.dimension-field span {
margin-bottom: 2px;
text-align: center;
font-size: 8px;
}
.dimension-field input {
height: 30px;
padding: 4px 3px;
border-radius: 6px;
text-align: center;
font: 750 11px ui-monospace, SFMono-Regular, Menlo, monospace;
appearance: textfield;
-moz-appearance: textfield;
}
.dimension-field input::-webkit-inner-spin-button,
.dimension-field input::-webkit-outer-spin-button {
margin: 0;
-webkit-appearance: none;
}
.box-footer {
display: flex;
justify-content: space-between;
margin-top: 10px;
padding-top: 9px;
border-top: 1px dashed var(--line);
color: var(--muted);
font-size: 11px;
}
.switch-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 12px;
font-size: 12px;
font-weight: 750;
}
.switch {
position: relative;
width: 42px;
height: 24px;
flex: 0 0 auto;
}
.switch input {
position: absolute;
opacity: 0;
pointer-events: none;
}
.switch span {
position: absolute;
inset: 0;
border-radius: 999px;
background: #c8d5d8;
cursor: pointer;
transition: background .15s;
}
.switch span::after {
content: "";
position: absolute;
width: 18px;
height: 18px;
left: 3px;
top: 3px;
border-radius: 50%;
background: white;
box-shadow: 0 2px 5px rgba(0,0,0,.18);
transition: transform .15s;
}
.switch input:checked + span { background: var(--teal); }
.switch input:checked + span::after { transform: translateX(18px); }
.primary-button {
width: 100%;
min-height: 43px;
padding: 10px 13px;
border: 0;
border-radius: 10px;
color: white;
background: linear-gradient(135deg, var(--teal), #258993);
box-shadow: 0 7px 16px rgba(23,111,120,.2);
cursor: pointer;
font-size: 12px;
font-weight: 850;
letter-spacing: .02em;
}
.primary-button:hover { filter: brightness(1.06); }
.primary-button:disabled { opacity: .6; cursor: wait; }
.method-note {
margin: 11px 1px 0;
color: var(--muted);
font-size: 10.5px;
line-height: 1.45;
}
.method-note strong { color: var(--ink); }
.stage {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
background: #eaf1f2;
}
#canvasHost {
position: absolute;
inset: 0;
}
#canvasHost canvas {
width: 100%;
height: 100%;
display: block;
touch-action: none;
outline: none;
}
.viewbar {
position: absolute;
top: 18px;
left: 18px;
z-index: 2;
display: flex;
gap: 5px;
padding: 5px;
border: 1px solid rgba(23,52,58,.12);
border-radius: 12px;
background: rgba(255,255,255,.9);
box-shadow: var(--shadow);
backdrop-filter: blur(8px);
}
.view-button {
min-height: 34px;
padding: 7px 12px;
border: 0;
border-radius: 8px;
color: #53696e;
background: transparent;
cursor: pointer;
font-size: 11px;
font-weight: 850;
}
.view-button:hover { background: #eef4f5; }
.view-button.active {
color: white;
background: var(--teal-dark);
}
.selection-info {
position: absolute;
top: 18px;
right: 18px;
z-index: 2;
max-width: 330px;
padding: 10px 13px;
color: #38575c;
background: rgba(255,255,255,.9);
border: 1px solid rgba(23,52,58,.12);
border-radius: 10px;
box-shadow: var(--shadow);
font: 700 11px ui-monospace, SFMono-Regular, Menlo, monospace;
pointer-events: none;
}
.interaction-hint {
position: absolute;
top: 70px;
left: 20px;
z-index: 1;
color: rgba(23,52,58,.58);
font-size: 10px;
font-weight: 700;
pointer-events: none;
}
.axis-chip {
position: absolute;
top: 72px;
right: 20px;
z-index: 1;
color: rgba(23,52,58,.62);
font: 750 10px ui-monospace, SFMono-Regular, Menlo, monospace;
pointer-events: none;
}
.status-card {
position: absolute;
left: 18px;
bottom: 18px;
z-index: 3;
width: min(520px, calc(100% - 36px));
padding: 14px 15px;
border: 1px solid rgba(23,52,58,.13);
border-radius: 14px;
background: rgba(255,255,255,.94);
box-shadow: var(--shadow);
backdrop-filter: blur(10px);
}
.status-card.success { border-left: 5px solid var(--green); }
.status-card.error { border-left: 5px solid var(--red); }
.status-card.loading { border-left: 5px solid #d79541; }
.status-heading {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
}
.status-title-wrap {
min-width: 0;
display: flex;
align-items: center;
gap: 8px;
}
.status-dot {
width: 10px;
height: 10px;
flex: 0 0 auto;
border-radius: 50%;
background: #b7c4c7;
}
.success .status-dot { background: var(--green); }
.error .status-dot { background: var(--red); }
.loading .status-dot { background: #d79541; }
.status-title {
margin: 0;
font-size: 13px;
line-height: 1.25;
}
.audit-badge {
flex: 0 0 auto;
padding: 5px 7px;
border-radius: 6px;
color: #607378;
background: #edf3f4;
font: 800 8px ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: .04em;
}
.success .audit-badge { color: #247252; background: #e8f6ef; }
.error .audit-badge { color: #9b3f3f; background: #faecec; }
.status-message {
margin: 7px 0 11px 18px;
color: #64777c;
font-size: 10.5px;
line-height: 1.4;
}
.stats-grid {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 7px;
}
.stat {
min-width: 0;
padding: 8px 9px;
background: #f4f8f8;
border: 1px solid #e3ebed;
border-radius: 9px;
}
.stat strong {
display: block;
overflow: hidden;
color: var(--ink);
font-size: 15px;
line-height: 1.1;
text-overflow: ellipsis;
white-space: nowrap;
}
.stat span {
display: block;
margin-top: 3px;
color: var(--muted);
font-size: 8.5px;
font-weight: 800;
letter-spacing: .04em;
text-transform: uppercase;
}
.audit-button {
width: 100%;
margin-top: 9px;
padding: 8px;
border: 1px solid #cddbde;
border-radius: 8px;
color: #456267;
background: white;
cursor: pointer;
font-size: 10px;
font-weight: 850;
}
.audit-button:hover { border-color: var(--teal); color: var(--teal-dark); }
.empty-state {
position: absolute;
left: 50%;
top: 48%;
z-index: 2;
width: min(390px, calc(100% - 40px));
padding: 18px;
transform: translate(-50%, -50%);
border: 1px solid rgba(23,52,58,.13);
border-radius: 14px;
background: rgba(255,255,255,.92);
box-shadow: var(--shadow);
text-align: center;
pointer-events: none;
}
.empty-symbol {
width: 40px;
height: 40px;
display: grid;
place-items: center;
margin: 0 auto 9px;
border-radius: 10px;
color: #a24848;
background: #f9e8e8;
font-size: 20px;
font-weight: 900;
}
.empty-state h3 {
margin: 0;
font-size: 14px;
}
.empty-state p {
margin: 6px 0 0;
color: var(--muted);
font-size: 11px;
line-height: 1.45;
}
@media (max-width: 860px) {
body { overflow: auto; }
.app { height: auto; min-height: 100dvh; }
.topbar { padding: 11px 14px; }
.scope-chip { display: none; }
.layout { display: flex; flex-direction: column; }
.stage {
order: 0;
height: 64dvh;
min-height: 480px;
}
.sidebar {
order: 1;
overflow: visible;
border-right: 0;
border-top: 1px solid var(--line);
}
.status-card { bottom: 12px; left: 12px; width: calc(100% - 24px); }
.selection-info { top: 66px; left: 18px; right: auto; max-width: calc(100% - 36px); }
.interaction-hint { display: none; }
.axis-chip { top: 20px; right: 18px; }
}
@media (max-width: 520px) {
.brand-copy p { display: none; }
.brand-copy h1 { font-size: 16px; }
.ghost-button { padding: 7px 9px; font-size: 10px; }
.view-button { padding: 7px 9px; }
.stats-grid { grid-template-columns: repeat(2, 1fr); }
.status-card { padding: 12px; }
.audit-badge { display: none; }
}
</style>
</head>
<body>
<div class="app">
<header class="topbar">
<div class="brand">
<div class="logo" aria-hidden="true"><i></i><i></i><i></i><i></i></div>
<div class="brand-copy">
<h1>VoxelFit</h1>
<p>Caixas rotuladas em uma van de entrega voxel</p>
</div>
</div>
<div class="top-actions">
<span class="scope-chip">Encaixe geométrico</span>
<button id="resetBtn" class="ghost-button" type="button">Restaurar carga</button>
</div>
</header>
<main class="layout">
<aside class="sidebar">
<section class="card">
<div class="section-head">
<h2>Compartimento</h2>
<span>células voxel</span>
</div>
<div class="bay-grid">
<label class="field">
<span>X · largura</span>
<input id="bayW" type="number" min="1" max="10" step="1" value="8" aria-label="Largura do compartimento">
</label>
<label class="field">
<span>Y · altura</span>
<input id="bayH" type="number" min="1" max="10" step="1" value="5" aria-label="Altura do compartimento">
</label>
<label class="field">
<span>Z · profundidade</span>
<input id="bayD" type="number" min="1" max="10" step="1" value="6" aria-label="Profundidade do compartimento">
</label>
</div>
<div class="select-wrap">
<select id="presetSelect" aria-label="Preset do compartimento">
<option value="reference">Carga de referência · 8 × 5 × 6</option>
<option value="tall">Baú alto · 8 × 6 × 6</option>
<option value="narrow">Baú estreito · 6 × 6 × 6</option>
<option value="reject">Teste de recusa · 6 × 4 × 5</option>
<option value="custom">Personalizado</option>
</select>
</div>
<div class="mini-stats">
<span>Capacidade <strong id="bayCapacity">240</strong></span>
<span>Demanda <strong id="boxTotal">160</strong></span>
</div>
</section>
<section class="card">
<div class="section-head">
<h2>Caixas</h2>
<span>X × Y × Z</span>
</div>
<div id="boxList" class="box-list"></div>
<div class="box-footer">
<span>10 caixas rotuladas</span>
<span id="volumeRatio">67% do volume</span>
</div>
</section>
<section class="card">
<div class="switch-row">
<span>Permitir rotação de 90°</span>
<label class="switch">
<input id="rotationToggle" type="checkbox" checked aria-label="Permitir rotação das caixas">
<span></span>
</label>
</div>
<button id="packBtn" class="primary-button" type="button">Executar empacotamento</button>
<p class="method-note">
<strong>Critério:</strong> alinhamento aos eixos, contenção total e ausência de
sobreposição. Estabilidade, massa, centro de gravidade e amarração não são avaliados.
</p>
</section>
</aside>
<section id="stage" class="stage" aria-label="Visualização tridimensional da van">
<div id="canvasHost"></div>
<nav class="viewbar" aria-label="Vistas da câmera">
<button class="view-button active" data-view="iso" type="button">3/4</button>
<button class="view-button" data-view="top" type="button">Topo</button>
<button class="view-button" data-view="side" type="button">Lateral</button>
</nav>
<div class="interaction-hint">Arraste para orbitar · roda do mouse para zoom</div>
<div class="axis-chip">X largura · Y altura · Z profundidade</div>
<div id="selectionInfo" class="selection-info" hidden></div>
<section id="statusCard" class="status-card loading" aria-live="polite">
<div class="status-heading">
<div class="status-title-wrap">
<span class="status-dot"></span>
<h2 id="statusTitle" class="status-title">Calculando encaixe…</h2>
</div>
<span id="auditBadge" class="audit-badge">TESTE AABB</span>
</div>
<p id="statusMessage" class="status-message">Preparando a malha voxel.</p>
<div class="stats-grid">
<div class="stat"><strong id="packedStat">0/10</strong><span>embaladas</span></div>
<div class="stat"><strong id="volumeStat">0%</strong><span>ocupação</span></div>
<div class="stat"><strong id="outsideStat">0</strong><span>fora do baú</span></div>
<div class="stat"><strong id="collisionStat">0</strong><span>colisões</span></div>
</div>
<button id="auditBtn" class="audit-button" type="button">Auditar geometria renderizada</button>
</section>
<div id="emptyState" class="empty-state" hidden>
<div class="empty-symbol">×</div>
<h3 id="emptyTitle">Nenhum arranjo aceito</h3>
<p id="emptyText"></p>
</div>
</section>
</main>
</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 CELL = 0.46;
const BOX_GAP = 0.018;
const EPSILON = 0.003;
const initialBoxes = [
{ id: '01', name: 'Papel', color: '#f4a261', dims: [4, 3, 3] },
{ id: '02', name: 'Livros', color: '#e76f51', dims: [4, 3, 3] },
{ id: '03', name: 'Cozinha', color: '#e9c46a', dims: [2, 2, 3] },
{ id: '04', name: 'Eletro', color: '#2a9d8f', dims: [2, 2, 3] },
{ id: '05', name: 'Bebidas', color: '#55b89a', dims: [2, 2, 3] },
{ id: '06', name: 'Casa', color: '#8d6e9b', dims: [2, 2, 3] },
{ id: '07', name: 'Tecidos', color: '#ef8fa4', dims: [2, 3, 2] },
{ id: '08', name: 'Peças', color: '#457b9d', dims: [2, 3, 2] },
{ id: '09', name: 'Frágil', color: '#f2c14e', dims: [4, 1, 2] },
{ id: '10', name: 'Lastro', color: '#8d99ae', dims: [4, 1, 2] }
];
let boxes = initialBoxes.map(box => ({ ...box, dims: [...box.dims] }));
let bay = { w: 8, h: 5, d: 6 };
let allowRotation = true;
let currentPlacements = [];
let selectedIndex = null;
let packTimer = null;
let lastFailureReason = '';
let currentPreset = 'iso';
let baseViewHeight = 6;
const host = $('canvasHost');
const stage = $('stage');
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false,
powerPreference: 'high-performance'
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.05;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.domElement.setAttribute('aria-label', 'Cena 3D interativa da van e das caixas');
renderer.domElement.style.touchAction = 'none';
host.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xeaf1f2);
scene.fog = new THREE.Fog(0xeaf1f2, 21, 43);
const camera = new THREE.OrthographicCamera(-5, 5, 4, -4, 0.1, 100);
camera.position.set(8, 6, -9);
const cameraTarget = new THREE.Vector3();
const hemisphere = new THREE.HemisphereLight(0xf8fcff, 0x6c7c80, 2.15);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xffffff, 3.15);
sun.position.set(-6, 11, -7);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -9;
sun.shadow.camera.right = 9;
sun.shadow.camera.top = 9;
sun.shadow.camera.bottom = -9;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 32;
sun.shadow.bias = -0.0005;
scene.add(sun);
const fill = new THREE.DirectionalLight(0xbfe7ea, 1.2);
fill.position.set(7, 5, 8);
scene.add(fill);
const environment = new THREE.Group();
const vanGroup = new THREE.Group();
const boxesGroup = new THREE.Group();
scene.add(environment, vanGroup, boxesGroup);
const boxMeshes = [];
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(60, 60),
new THREE.MeshStandardMaterial({ color: 0xdde7e9, roughness: 0.96, metalness: 0 })
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.57;
ground.receiveShadow = true;
environment.add(ground);
const floorGrid = new THREE.GridHelper(40, 80, 0xaabfc3, 0xc8d7da);
floorGrid.position.y = -0.558;
floorGrid.material.transparent = true;
floorGrid.material.opacity = 0.48;
environment.add(floorGrid);
function volumeOf(dims) {
return dims[0] * dims[1] * dims[2];
}
function totalBoxVolume() {
return boxes.reduce((sum, box) => sum + volumeOf(box.dims), 0);
}
function capacity() {
return bay.w * bay.h * bay.d;
}
function disposeHierarchy(root) {
const geometries = new Set();
const materials = new Set();
const textures = new Set();
root.traverse(object => {
if (object.geometry) geometries.add(object.geometry);
const objectMaterials = Array.isArray(object.material)
? object.material
: object.material ? [object.material] : [];
for (const material of objectMaterials) {
materials.add(material);
if (material.map) textures.add(material.map);
}
});
textures.forEach(texture => texture.dispose());
materials.forEach(material => material.dispose());
geometries.forEach(geometry => geometry.dispose());
root.clear();
}
function addBoxMesh(parent, size, position, material, castShadow = true, receiveShadow = true) {
const mesh = new THREE.Mesh(new THREE.BoxGeometry(...size), material);
mesh.position.set(...position);
mesh.castShadow = castShadow;
mesh.receiveShadow = receiveShadow;
parent.add(mesh);
return mesh;
}
function rebuildVan() {
disposeHierarchy(vanGroup);
const width = bay.w * CELL;
const height = bay.h * CELL;
const depth = bay.d * CELL;
const frame = 0.09;
const floorMaterial = new THREE.MeshStandardMaterial({
color: 0xc5d3d7, roughness: 0.86, metalness: 0.04
});
const frameMaterial = new THREE.MeshStandardMaterial({
color: 0x246c74, roughness: 0.55, metalness: 0.18
});
const wallMaterial = new THREE.MeshStandardMaterial({
color: 0x70c7cf,
transparent: true,
opacity: 0.075,
roughness: 0.2,
metalness: 0,
depthWrite: false,
side: THREE.DoubleSide
});
addBoxMesh(
vanGroup,
[width + 0.14, 0.12, depth + 0.14],
[0, -0.06, 0],
floorMaterial
);
// Paredes transparentes: os limites interiores coincidem com a grade voxel.
addBoxMesh(vanGroup, [0.018, height, depth], [-width / 2, height / 2, 0], wallMaterial, false, false);
addBoxMesh(vanGroup, [0.018, height, depth], [ width / 2, height / 2, 0], wallMaterial, false, false);
addBoxMesh(vanGroup, [width, height, 0.018], [0, height / 2, -depth / 2], wallMaterial, false, false);
addBoxMesh(vanGroup, [width, height, 0.018], [0, height / 2, depth / 2], wallMaterial, false, false);
addBoxMesh(vanGroup, [width, 0.018, depth], [0, height, 0], wallMaterial, false, false);
// Estrutura da carroceria, com a face interna sobre o limite do baú.
for (const x of [-width / 2 - frame / 2, width / 2 + frame / 2]) {
for (const z of [-depth / 2 - frame / 2, depth / 2 + frame / 2]) {
addBoxMesh(vanGroup, [frame, height + frame, frame], [x, height / 2, z], frameMaterial);
}
for (const y of [-frame / 2, height + frame / 2]) {
addBoxMesh(vanGroup, [frame, frame, depth + frame * 2], [x, y, 0], frameMaterial);
}
}
for (const z of [-depth / 2 - frame / 2, depth / 2 + frame / 2]) {
for (const y of [-frame / 2, height + frame / 2]) {
addBoxMesh(vanGroup, [width + frame * 2, frame, frame], [0, y, z], frameMaterial);
}
}
// Grade visível no piso do compartimento.
const gridVertices = [];
for (let x = 0; x <= bay.w; x++) {
const wx = -width / 2 + x * CELL;
gridVertices.push(wx, 0.009, -depth / 2, wx, 0.009, depth / 2);
}
for (let z = 0; z <= bay.d; z++) {
const wz = -depth / 2 + z * CELL;
gridVertices.push(-width / 2, 0.009, wz, width / 2, 0.009, wz);
}
const gridGeometry = new THREE.BufferGeometry();
gridGeometry.setAttribute('position', new THREE.Float32BufferAttribute(gridVertices, 3));
const grid = new THREE.LineSegments(
gridGeometry,
new THREE.LineBasicMaterial({ color: 0x557278, transparent: true, opacity: 0.38 })
);
vanGroup.add(grid);
// Cab voxel procedural.
const cabWidth = Math.min(2.25, width * 0.78);
const front = depth / 2;
const cabOrange = new THREE.MeshStandardMaterial({ color: 0xef9657, roughness: 0.72 });
const cabLight = new THREE.MeshStandardMaterial({ color: 0xf2b16f, roughness: 0.75 });
const glass = new THREE.MeshStandardMaterial({
color: 0x254d5c, roughness: 0.22, metalness: 0.18
});
const dark = new THREE.MeshStandardMaterial({ color: 0x26383b, roughness: 0.8 });
const hub = new THREE.MeshStandardMaterial({ color: 0xb9c9cc, roughness: 0.45, metalness: 0.45 });
const lamp = new THREE.MeshStandardMaterial({
color: 0xffe49a, emissive: 0xd99b35, emissiveIntensity: 0.45, roughness: 0.35
});
addBoxMesh(vanGroup, [cabWidth, 1.05, 1.25], [0, 0.38, front + 0.72], cabOrange);
addBoxMesh(vanGroup, [cabWidth * 0.90, 0.78, 0.92], [0, 1.30, front + 0.67], cabLight);
addBoxMesh(
vanGroup,
[cabWidth * 0.72, 0.46, 0.026],
[0, 1.34, front + 1.137],
glass,
false
);
for (const side of [-1, 1]) {
addBoxMesh(
vanGroup,
[0.026, 0.42, 0.54],
[side * cabWidth * 0.45, 1.34, front + 0.69],
glass,
false
);
}
addBoxMesh(vanGroup, [cabWidth * 0.78, 0.13, 0.07], [0, 0.22, front + 1.39], dark);
for (const side of [-1, 1]) {
addBoxMesh(vanGroup, [0.25, 0.18, 0.05], [side * cabWidth * 0.30, 0.58, front + 1.37], lamp, false);
}
// Rodas quadradas, coerentes com o estilo voxel.
const wheelPositions = [-depth * 0.28, front + 0.72];
for (const side of [-1, 1]) {
for (const z of wheelPositions) {
addBoxMesh(vanGroup, [0.24, 0.48, 0.48], [side * (width / 2 + 0.02), -0.32, z], dark);
addBoxMesh(
vanGroup,
[0.045, 0.18, 0.18],
[side * (width / 2 + 0.155), -0.32, z],
hub,
false
);
}
}
}
function makeLabelTexture(box) {
const canvas = document.createElement('canvas');
canvas.width = 512;
canvas.height = 384;
const context = canvas.getContext('2d');
context.fillStyle = box.color;
context.fillRect(0, 0, canvas.width, canvas.height);
context.fillStyle = 'rgba(255,255,255,.13)';
for (let x = 0; x < canvas.width; x += 64) {
for (let y = 0; y < canvas.height; y += 64) {
if (((x + y) / 64) % 2 === 0) context.fillRect(x, y, 32, 32);
}
}
context.fillStyle = 'rgba(255,255,255,.93)';
context.fillRect(24, 24, 464, 336);
context.fillStyle = '#17343a';
context.font = '900 104px system-ui, sans-serif';
context.fillText(box.id, 48, 138);
context.font = '800 40px system-ui, sans-serif';
context.fillText(box.name.toUpperCase(), 48, 202);
context.font = '800 34px ui-monospace, monospace';
context.fillText(`${box.dims[0]} × ${box.dims[1]} × ${box.dims[2]}`, 48, 262);
context.fillStyle = '#527176';
context.font = '800 24px system-ui, sans-serif';
context.fillText('X LARG. Y ALT. Z PROF.', 48, 310);
context.fillStyle = '#176f78';
context.fillRect(48, 326, 104, 7);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.anisotropy = Math.min(8, renderer.capabilities.getMaxAnisotropy());
return texture;
}
function clearBoxes() {
disposeHierarchy(boxesGroup);
boxMeshes.length = 0;
selectedIndex = null;
$('selectionInfo').hidden = true;
document.querySelectorAll('.box-row').forEach(row => row.classList.remove('selected'));
}
function buildBoxes(placements) {
clearBoxes();
placements.forEach((placement, index) => {
if (!placement) return;
const box = boxes[index];
const size = placement.dims.map(value => value * CELL - BOX_GAP);
const center = new THREE.Vector3(
(placement.x + placement.dims[0] / 2 - bay.w / 2) * CELL,
(placement.y + placement.dims[1] / 2) * CELL,
(placement.z + placement.dims[2] / 2 - bay.d / 2) * CELL
);
const geometry = new THREE.BoxGeometry(...size);
const material = new THREE.MeshStandardMaterial({
map: makeLabelTexture(box),
roughness: 0.76,
metalness: 0,
emissive: 0x000000,
emissiveIntensity: 0
});
const mesh = new THREE.Mesh(geometry, material);
mesh.position.copy(center);
mesh.castShadow = true;
mesh.receiveShadow = true;
mesh.userData.boxIndex = index;
const edgeBase = new THREE.Color(box.color).multiplyScalar(0.58);
const edges = new THREE.LineSegments(
new THREE.EdgesGeometry(geometry, 24),
new THREE.LineBasicMaterial({ color: edgeBase, transparent: true, opacity: 0.78 })
);
edges.userData.edgeBase = edgeBase;
mesh.add(edges);
boxesGroup.add(mesh);
boxMeshes.push(mesh);
});
}
function orientationsFor(dims) {
if (!allowRotation) return [dims.slice()];
const permutations = [
[0,1,2], [0,2,1], [1,0,2], [1,2,0], [2,0,1], [2,1,0]
];
const seen = new Set();
const result = [];
for (const permutation of permutations) {
const orientation = permutation.map(index => dims[index]);
const key = orientation.join(',');
if (!seen.has(key)) {
seen.add(key);
result.push(orientation);
}
}
return result;
}
function packBoxes() {
const requestedVolume = totalBoxVolume();
const availableVolume = capacity();
if (requestedVolume > availableVolume) {
return {
ok: false,
reason: `O volume total das caixas é ${requestedVolume} células, mas o compartimento oferece apenas ${availableVolume}.`
};
}
const order = boxes
.map((box, index) => ({ box, index, volume: volumeOf(box.dims) }))
.sort((a, b) => b.volume - a.volume || a.index - b.index);
const occupied = new Uint8Array(availableVolume);
const placements = new Array(boxes.length);
const failedStates = new Set();
const deadline = performance.now() + 2200;
let nodes = 0;
let timedOut = false;
const indexOf = (x, y, z) => x + bay.w * (z + bay.d * y);
function canPlace(x, y, z, dims) {
for (let yy = y; yy < y + dims[1]; yy++) {
for (let zz = z; zz < z + dims[2]; zz++) {
for (let xx = x; xx < x + dims[0]; xx++) {
if (occupied[indexOf(xx, yy, zz)]) return false;
}
}
}
return true;
}
function mark(x, y, z, dims, value) {
for (let yy = y; yy < y + dims[1]; yy++) {
for (let zz = z; zz < z + dims[2]; zz++) {
for (let xx = x; xx < x + dims[0]; xx++) {
occupied[indexOf(xx, yy, zz)] = value;
}
}
}
}
function search(depth) {
if (performance.now() > deadline) {
timedOut = true;
return false;
}
if (depth === order.length) return true;
const stateKey = `${depth}|${occupied.join('')}`;
if (failedStates.has(stateKey)) return false;
nodes++;
const item = order[depth];
const orientations = orientationsFor(item.box.dims);
for (const orientation of orientations) {
const [dx, dy, dz] = orientation;
if (dx > bay.w || dy > bay.h || dz > bay.d) continue;
for (let y = 0; y <= bay.h - dy; y++) {
for (let z = 0; z <= bay.d - dz; z++) {
for (let x = 0; x <= bay.w - dx; x++) {
if (!canPlace(x, y, z, orientation)) continue;
mark(x, y, z, orientation, 1);
placements[item.index] = { x, y, z, dims: orientation.slice() };
if (search(depth + 1)) return true;
placements[item.index] = null;
mark(x, y, z, orientation, 0);
}
}
}
}
if (!timedOut) failedStates.add(stateKey);
return false;
}
const found = search(0);
if (!found) {
return {
ok: false,
reason: timedOut
? 'A busca excedeu o limite de cálculo. Reduza as caixas ou experimente outro compartimento.'
: 'Não existe uma disposição alinhada aos eixos que contenha todas as caixas. Volume disponível não garante encaixe.'
};
}
return { ok: true, placements };
}
function validateData(placements) {
const missing = placements.filter(Boolean).length !== boxes.length;
let outside = 0;
let collisions = 0;
const invalid = [];
placements.forEach((placement, index) => {
if (!placement) {
invalid.push(index);
return;
}
const [dx, dy, dz] = placement.dims;
if (
!Number.isInteger(placement.x) || !Number.isInteger(placement.y) || !Number.isInteger(placement.z) ||
!Number.isInteger(dx) || !Number.isInteger(dy) || !Number.isInteger(dz) ||
dx < 1 || dy < 1 || dz < 1 ||
placement.x < 0 || placement.y < 0 || placement.z < 0 ||
placement.x + dx > bay.w ||
placement.y + dy > bay.h ||
placement.z + dz > bay.d
) {
outside++;
invalid.push(index);
}
});
for (let i = 0; i < placements.length; i++) {
const a = placements[i];
if (!a || invalid.includes(i)) continue;
for (let j = i + 1; j < placements.length; j++) {
const b = placements[j];
if (!b || invalid.includes(j)) continue;
const overlapX = a.x < b.x + b.dims[0] && b.x < a.x + a.dims[0];
const overlapY = a.y < b.y + b.dims[1] && b.y < a.y + a.dims[1];
const overlapZ = a.z < b.z + b.dims[2] && b.z < a.z + a.dims[2];
if (overlapX && overlapY && overlapZ) collisions++;
}
}
return {
ok: !missing && outside === 0 && collisions === 0,
missing,
outside,
collisions,
invalid
};
}
function auditRenderedGeometry() {
const width = bay.w * CELL;
const height = bay.h * CELL;
const depth = bay.d * CELL;
const bounds = [];
let outside = 0;
let collisions = 0;
let geometryMismatch = 0;
boxMeshes.forEach((mesh, index) => {
mesh.updateWorldMatrix(true, true);
const bounds3D = new THREE.Box3().setFromObject(mesh);
bounds.push(bounds3D);
if (
bounds3D.min.x < -width / 2 - EPSILON ||
bounds3D.min.y < -EPSILON ||
bounds3D.min.z < -depth / 2 - EPSILON ||
bounds3D.max.x > width / 2 + EPSILON ||
bounds3D.max.y > height + EPSILON ||
bounds3D.max.z > depth / 2 + EPSILON
) {
outside++;
}
const placement = currentPlacements[index];
if (!placement) {
geometryMismatch++;
return;
}
const actualSize = bounds3D.getSize(new THREE.Vector3());
for (let axis = 0; axis < 3; axis++) {
const expected = placement.dims[axis] * CELL - BOX_GAP;
if (Math.abs(actualSize.getComponent(axis) - expected) > 0.012) {
geometryMismatch++;
break;
}
}
});
for (let i = 0; i < bounds.length; i++) {
for (let j = i + 1; j < bounds.length; j++) {
if (bounds[i].intersectsBox(bounds[j])) collisions++;
}
}
return {
count: boxMeshes.length,
outside,
collisions,
geometryMismatch
};
}
function renderBoxRows() {
const list = $('boxList');
list.replaceChildren();
boxes.forEach((box, index) => {
const row = document.createElement('div');
row.className = 'box-row';
const pick = document.createElement('button');
pick.type = 'button';
pick.className = 'box-pick';
pick.setAttribute('aria-label', `Selecionar caixa ${box.id}, ${box.name}`);
const swatch = document.createElement('span');
swatch.className = 'swatch';
swatch.style.background = box.color;
const code = document.createElement('span');
code.className = 'box-code';
code.textContent = box.id;
const name = document.createElement('span');
name.className = 'box-name';
name.textContent = box.name;
pick.append(swatch, code, name);
pick.addEventListener('click', () => selectBox(index));
const dimensions = document.createElement('div');
dimensions.className = 'dimension-fields';
['X', 'Y', 'Z'].forEach((axisName, axis) => {
const label = document.createElement('label');
label.className = 'dimension-field';
const caption = document.createElement('span');
caption.textContent = axisName;
const input = document.createElement('input');
input.type = 'number';
input.min = '1';
input.max = '10';
input.step = '1';
input.value = box.dims[axis];
input.setAttribute('aria-label', `Caixa ${box.id}, dimensão ${axisName}`);
input.addEventListener('change', event => {
const value = Number(event.target.value);
if (!Number.isInteger(value) || value < 1 || value > 10) {
event.target.value = boxes[index].dims[axis];
return;
}
boxes[index].dims[axis] = value;
updateTotals();
schedulePacking();
});
label.append(caption, input);
dimensions.append(label);
});
row.append(pick, dimensions);
list.append(row);
});
}
function syncInputs() {
$('bayW').value = bay.w;
$('bayH').value = bay.h;
$('bayD').value = bay.d;
$('rotationToggle').checked = allowRotation;
boxes.forEach((box, index) => {
const inputs = document.querySelectorAll(`.box-row:nth-child(${index + 1}) .dimension-field input`);
inputs.forEach((input, axis) => { input.value = box.dims[axis]; });
});
}
function updateTotals() {
const requested = totalBoxVolume();
$('bayCapacity').textContent = capacity();
$('boxTotal').textContent = requested;
$('volumeRatio').textContent = `${Math.round(requested / capacity() * 100)}% do volume`;
}
function selectBox(index) {
if (!currentPlacements[index]) return;
selectedIndex = index;
boxMeshes.forEach((mesh, meshIndex) => {
const selected = meshIndex === index;
mesh.material.emissive.set(selected ? 0x6b4d12 : 0x000000);
mesh.material.emissiveIntensity = selected ? 0.38 : 0;
const edge = mesh.children[0];
edge.material.color.copy(selected ? new THREE.Color(0xffc857) : edge.userData.edgeBase);
});
document.querySelectorAll('.box-row').forEach((row, rowIndex) => {
row.classList.toggle('selected', rowIndex === index);
});
const box = boxes[index];
const placement = currentPlacements[index];
const center = [
(placement.x + placement.dims[0] / 2 - bay.w / 2) * CELL,
(placement.y + placement.dims[1] / 2) * CELL,
(placement.z + placement.dims[2] / 2 - bay.d / 2) * CELL
].map(value => value.toFixed(2)).join(', ');
const info = $('selectionInfo');
info.textContent = `Caixa ${box.id} · célula (${placement.x}, ${placement.y}, ${placement.z}) · mundo (${center})`;
info.hidden = false;
}
function setBusyUI() {
currentPlacements = [];
clearBoxes();
const card = $('statusCard');
card.className = 'status-card loading';
$('statusTitle').textContent = 'Calculando encaixe…';
$('auditBadge').textContent = 'TESTE AABB';
$('statusMessage').textContent = 'Testando contenção e sobreposição na malha voxel.';
$('packedStat').textContent = `0/${boxes.length}`;
$('volumeStat').textContent = `${Math.round(totalBoxVolume() / capacity() * 100)}%`;
$('outsideStat').textContent = '0';
$('collisionStat').textContent = '0';
$('packBtn').disabled = true;
$('emptyState').hidden = true;
}
function showFailure(reason) {
currentPlacements = [];
clearBoxes();
lastFailureReason = reason;
const card = $('statusCard');
card.className = 'status-card error';
$('statusTitle').textContent = 'Sem encaixe geométrico';
$('auditBadge').textContent = 'TESTE AABB · REPROVADO';
$('statusMessage').textContent = reason;
$('packedStat').textContent = `0/${boxes.length}`;
$('volumeStat').textContent = `${Math.round(totalBoxVolume() / capacity() * 100)}%`;
$('outsideStat').textContent = '0';
$('collisionStat').textContent = '0';
$('packBtn').disabled = false;
$('emptyTitle').textContent = 'Nenhuma caixa foi exibida';
$('emptyText').textContent = 'O painel e a cena permanecem consistentes: só um arranjo aceito é renderizado.';
$('emptyState').hidden = false;
}
function showSuccess(audit) {
const card = $('statusCard');
card.className = 'status-card success';
$('statusTitle').textContent = 'Encaixe geométrico válido';
$('auditBadge').textContent = 'TESTE AABB · APROVADO';
$('statusMessage').textContent =
`${audit.count} caixas renderizadas · ${audit.outside} fora das paredes · ${audit.collisions} colisões. ` +
'Limites confirmados com o Box3 da geometria visível.';
$('packedStat').textContent = `${audit.count}/${boxes.length}`;
$('volumeStat').textContent = `${Math.round(totalBoxVolume() / capacity() * 100)}%`;
$('outsideStat').textContent = String(audit.outside);
$('collisionStat').textContent = String(audit.collisions);
$('packBtn').disabled = false;
$('emptyState').hidden = true;
lastFailureReason = '';
}
function runPackingNow() {
const result = packBoxes();
if (!result.ok) {
showFailure(result.reason);
return;
}
currentPlacements = result.placements;
buildBoxes(currentPlacements);
const dataAudit = validateData(currentPlacements);
if (!dataAudit.ok) {
showFailure(
`A auditoria dos dados reprovou o arranjo: ${dataAudit.outside} caixas fora dos limites e ` +
`${dataAudit.collisions} colisões na grade discreta.`
);
return;
}
const renderedAudit = auditRenderedGeometry();
if (
renderedAudit.count !== boxes.length ||
renderedAudit.outside !== 0 ||
renderedAudit.collisions !== 0 ||
renderedAudit.geometryMismatch !== 0
) {
showFailure(
`A geometria renderizada divergiu dos dados: ${renderedAudit.outside} caixas fora do volume, ` +
`${renderedAudit.collisions} sobreposições e ${renderedAudit.geometryMismatch} dimensões divergentes.`
);
return;
}
showSuccess(renderedAudit);
}
function schedulePacking(delay = 90) {
clearTimeout(packTimer);
setBusyUI();
rebuildVan();
if (currentPreset === 'free') refreshViewHeight();
else setCameraPreset(currentPreset);
packTimer = setTimeout(runPackingNow, delay);
}
function computeViewHeight(preset, aspect) {
const width = bay.w * CELL;
const height = bay.h * CELL;
const depth = bay.d * CELL;
let vertical;
let horizontal;
if (preset === 'top') {
vertical = depth + 2.1;
horizontal = width + 1.0;
} else if (preset === 'side') {
vertical = height + 1.5;
horizontal = depth + 2.1;
} else {
vertical = height + 2.0;
horizontal = width + depth + 2.4;
}
return Math.max(vertical, horizontal / Math.max(aspect, 0.4));
}
function updateProjection() {
const aspect = Math.max(0.4, host.clientWidth / Math.max(host.clientHeight, 1));
camera.left = -baseViewHeight * aspect / 2;
camera.right = baseViewHeight * aspect / 2;
camera.top = baseViewHeight / 2;
camera.bottom = -baseViewHeight / 2;
camera.updateProjectionMatrix();
}
function refreshViewHeight() {
if (currentPreset === 'free') return;
const aspect = Math.max(0.4, host.clientWidth / Math.max(host.clientHeight, 1));
baseViewHeight = computeViewHeight(currentPreset, aspect);
updateProjection();
}
function updateViewButtons() {
document.querySelectorAll('.view-button').forEach(button => {
button.classList.toggle('active', button.dataset.view === currentPreset);
});
}
function setCameraPreset(preset) {
currentPreset = preset;
const width = bay.w * CELL;
const height = bay.h * CELL;
const depth = bay.d * CELL;
if (preset === 'top') {
cameraTarget.set(0, 0, 0.45);
camera.position.set(0, 12, 0.451);
camera.up.set(0, 0, -1);
} else if (preset === 'side') {
cameraTarget.set(0, height * 0.48, 0.42);
camera.position.set(12, height * 0.48, 0.42);
camera.up.set(0, 1, 0);
} else {
cameraTarget.set(0, height * 0.42, 0.32);
camera.position.set(
cameraTarget.x + 8,
cameraTarget.y + 6,
cameraTarget.z - 9
);
camera.up.set(0, 1, 0);
}
camera.zoom = 1;
const aspect = Math.max(0.4, host.clientWidth / Math.max(host.clientHeight, 1));
baseViewHeight = computeViewHeight(preset, aspect);
camera.lookAt(cameraTarget);
updateProjection();
updateViewButtons();
}
function resize() {
const width = Math.max(1, host.clientWidth);
const height = Math.max(1, host.clientHeight);
renderer.setSize(width, height, false);
refreshViewHeight();
}
document.querySelectorAll('.view-button').forEach(button => {
button.addEventListener('click', () => setCameraPreset(button.dataset.view));
});
$('packBtn').addEventListener('click', () => schedulePacking(20));
$('auditBtn').addEventListener('click', () => {
if (!currentPlacements.length) {
showFailure(lastFailureReason || 'Não há um arranho válido para auditar.');
return;
}
const dataAudit = validateData(currentPlacements);
const renderedAudit = auditRenderedGeometry();
if (
!dataAudit.ok ||
renderedAudit.count !== boxes.length ||
renderedAudit.outside !== 0 ||
renderedAudit.collisions !== 0 ||
renderedAudit.geometryMismatch !== 0
) {
showFailure('A nova auditoria encontrou uma divergência e o arranjo foi removido da cena.');
} else {
showSuccess(renderedAudit);
}
});
['bayW', 'bayH', 'bayD'].forEach((id, axis) => {
$(id).addEventListener('change', event => {
const value = Number(event.target.value);
if (!Number.isInteger(value) || value < 1 || value > 10) {
event.target.value = bay[['w', 'h', 'd'][axis]];
return;
}
bay[['w', 'h', 'd'][axis]] = value;
$('presetSelect').value = 'custom';
updateTotals();
schedulePacking();
});
});
$('presetSelect').addEventListener('change', event => {
const presets = {
reference: [8, 5, 6],
tall: [8, 6, 6],
narrow: [6, 6, 6],
reject: [6, 4, 5]
};
const preset = presets[event.target.value];
if (!preset) return;
bay = { w: preset[0], h: preset[1], d: preset[2] };
syncInputs();
updateTotals();
schedulePacking();
});
$('rotationToggle').addEventListener('change', event => {
allowRotation = event.target.checked;
schedulePacking();
});
$('resetBtn').addEventListener('click', () => {
boxes = initialBoxes.map(box => ({ ...box, dims: [...box.dims] }));
bay = { w: 8, h: 5, d: 6 };
allowRotation = true;
$('presetSelect').value = 'reference';
syncInputs();
updateTotals();
setCameraPreset('iso');
schedulePacking(20);
});
// Controles de câmera implementados diretamente, sem addons.
let dragState = null;
renderer.domElement.addEventListener('pointerdown', event => {
if (event.button !== 0) return;
dragState = {
pointerId: event.pointerId,
x: event.clientX,
y: event.clientY,
startX: event.clientX,
startY: event.clientY,
moved: false
};
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener('pointermove', event => {
if (!dragState || dragState.pointerId !== event.pointerId) return;
const dx = event.clientX - dragState.x;
const dy = event.clientY - dragState.y;
dragState.x = event.clientX;
dragState.y = event.clientY;
if (Math.hypot(event.clientX - dragState.startX, event.clientY - dragState.startY) > 4) {
dragState.moved = true;
}
if (dragState.moved) {
const offset = camera.position.clone().sub(cameraTarget);
const spherical = new THREE.Spherical().setFromVector3(offset);
spherical.theta -= dx * 0.007;
spherical.phi = THREE.MathUtils.clamp(spherical.phi - dy * 0.007, 0.05, Math.PI - 0.05);
camera.position.copy(cameraTarget).add(new THREE.Vector3().setFromSpherical(spherical));
camera.up.set(0, 1, 0);
camera.lookAt(cameraTarget);
currentPreset = 'free';
updateViewButtons();
}
});
renderer.domElement.addEventListener('pointerup', event => {
if (!dragState || dragState.pointerId !== event.pointerId) return;
const wasMoved = dragState.moved;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
dragState = null;
if (!wasMoved) {
const rect = renderer.domElement.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);
const hit = raycaster.intersectObjects(boxMeshes, false)[0];
if (hit) selectBox(hit.object.userData.boxIndex);
}
});
renderer.domElement.addEventListener('pointercancel', () => { dragState = null; });
renderer.domElement.addEventListener('wheel', event => {
event.preventDefault();
camera.zoom = THREE.MathUtils.clamp(
camera.zoom * Math.exp(-event.deltaY * 0.001),
0.55,
3.2
);
updateProjection();
}, { passive: false });
renderer.domElement.addEventListener('contextmenu', event => event.preventDefault());
const resizeObserver = new ResizeObserver(resize);
resizeObserver.observe(host);
window.addEventListener('resize', resize);
renderBoxRows();
syncInputs();
updateTotals();
rebuildVan();
setCameraPreset('iso');
resize();
runPackingNow();
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```