Prompt specification
Build or customize the Three.js 3D scene "Packing With an Unloading Order" 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: Packing With an Unloading Order
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/packing-with-an-unloading-order-x3476
Scene Description Prompt:
I'd like to see this as a voxel Three.js scene: packing with an unloading order. Create a bounded cargo puzzle requiring all crates to fit and remain removable in a stated order. Validate extraction paths rather than accepting only a filled silhouette. Use cdnjs and return one self-contained HTML file.
Working Three.js Starter (packing-with-an-unloading-order-x3476):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Voxel Cargo — Ordered Extraction</title>
<style>
:root {
--bg: #071019;
--panel: rgba(12, 24, 35, 0.92);
--panel-solid: #0c1823;
--line: rgba(156, 202, 219, 0.16);
--line-strong: rgba(156, 202, 219, 0.3);
--text: #e9f3f5;
--muted: #829aa4;
--cyan: #49dbc7;
--cyan-dark: #173c3d;
--orange: #ffac55;
--red: #ff657a;
--green: #8ee36b;
}
* { box-sizing: border-box; }
html, body {
margin: 0;
width: 100%;
height: 100%;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button { font: inherit; }
button:focus-visible {
outline: 2px solid var(--cyan);
outline-offset: 2px;
}
[hidden] { display: none !important; }
#app {
width: 100%;
height: 100%;
display: grid;
grid-template-columns: 304px minmax(0, 1fr);
grid-template-rows: 66px minmax(0, 1fr);
background:
radial-gradient(circle at 75% 10%, rgba(37, 100, 112, 0.12), transparent 38%),
#071019;
}
header {
grid-column: 1 / -1;
display: flex;
align-items: center;
justify-content: space-between;
gap: 24px;
padding: 0 22px;
border-bottom: 1px solid var(--line);
background: rgba(7, 16, 25, 0.9);
z-index: 20;
}
.brand {
display: flex;
align-items: center;
gap: 13px;
min-width: 0;
}
.brand-mark {
position: relative;
width: 30px;
height: 30px;
border: 1px solid var(--cyan);
background:
linear-gradient(90deg, transparent 45%, var(--line-strong) 46%, var(--line-strong) 54%, transparent 55%),
linear-gradient(transparent 45%, var(--line-strong) 46%, var(--line-strong) 54%, transparent 55%);
box-shadow: inset 0 0 18px rgba(73, 219, 199, 0.08), 0 0 18px rgba(73, 219, 199, 0.08);
transform: rotate(30deg) skew(-8deg, -8deg);
}
.brand h1 {
margin: 0;
font-size: 15px;
letter-spacing: 0.15em;
font-weight: 800;
white-space: nowrap;
}
.brand p {
margin: 4px 0 0;
color: var(--muted);
font-size: 10px;
letter-spacing: 0.18em;
text-transform: uppercase;
}
.header-stats {
display: flex;
align-items: center;
gap: 22px;
}
.header-stat {
text-align: right;
}
.header-stat span {
display: block;
color: var(--muted);
font-size: 9px;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.header-stat strong {
display: block;
margin-top: 3px;
font-size: 13px;
letter-spacing: 0.04em;
}
#statusPill {
min-width: 140px;
padding: 9px 12px;
border: 1px solid var(--line-strong);
color: var(--cyan);
background: rgba(73, 219, 199, 0.06);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.12em;
text-align: center;
text-transform: uppercase;
}
#statusPill.warning {
color: var(--orange);
border-color: rgba(255, 172, 85, 0.35);
background: rgba(255, 172, 85, 0.06);
}
#statusPill.error {
color: var(--red);
border-color: rgba(255, 101, 122, 0.4);
background: rgba(255, 101, 122, 0.07);
}
aside {
min-height: 0;
display: flex;
flex-direction: column;
border-right: 1px solid var(--line);
background: rgba(8, 18, 27, 0.95);
z-index: 10;
}
.brief {
padding: 20px 18px 16px;
border-bottom: 1px solid var(--line);
}
.eyebrow {
color: var(--cyan);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
.brief h2 {
margin: 8px 0 8px;
font-size: 19px;
line-height: 1.18;
letter-spacing: -0.025em;
}
.brief p {
margin: 0;
color: var(--muted);
font-size: 12px;
line-height: 1.55;
}
.brief strong { color: #d7e7ea; }
.manifest-head {
display: flex;
align-items: center;
justify-content: space-between;
padding: 15px 18px 10px;
}
.manifest-head h3 {
margin: 0;
color: #c6d8dd;
font-size: 10px;
letter-spacing: 0.16em;
text-transform: uppercase;
}
#manifestCount {
color: var(--muted);
font-size: 10px;
font-variant-numeric: tabular-nums;
}
#manifest {
min-height: 0;
overflow-y: auto;
padding: 0 10px 14px;
scrollbar-width: thin;
scrollbar-color: #29404c transparent;
}
.cargo-card {
position: relative;
display: grid;
grid-template-columns: 33px 44px minmax(0, 1fr) auto;
align-items: center;
gap: 10px;
width: 100%;
min-height: 64px;
margin: 5px 0;
padding: 9px 10px;
border: 1px solid transparent;
border-radius: 7px;
color: var(--text);
background: transparent;
cursor: pointer;
text-align: left;
transition: 140ms ease;
}
.cargo-card:hover {
border-color: var(--line);
background: rgba(255, 255, 255, 0.025);
}
.cargo-card.selected {
border-color: rgba(73, 219, 199, 0.48);
background: linear-gradient(90deg, rgba(73, 219, 199, 0.11), rgba(73, 219, 199, 0.025));
box-shadow: inset 3px 0 0 var(--cargo-color);
}
.cargo-card.placed .order-badge {
background: var(--cargo-color);
color: #081318;
}
.cargo-card.unloaded { opacity: 0.55; }
.order-badge {
display: grid;
place-items: center;
width: 29px;
height: 29px;
border: 1px solid var(--line-strong);
border-radius: 5px;
color: #a9c0c8;
background: #0c1922;
font-size: 11px;
font-weight: 900;
font-variant-numeric: tabular-nums;
}
.footprint {
display: grid;
gap: 2px;
justify-content: center;
align-content: center;
width: 40px;
height: 40px;
}
.footprint i {
display: block;
width: 6px;
height: 6px;
border-radius: 1px;
background: var(--cargo-color);
box-shadow: 0 0 8px color-mix(in srgb, var(--cargo-color) 30%, transparent);
}
.cargo-copy { min-width: 0; }
.cargo-copy strong {
display: block;
overflow: hidden;
font-size: 11px;
letter-spacing: 0.07em;
text-overflow: ellipsis;
white-space: nowrap;
}
.cargo-copy span {
display: block;
margin-top: 4px;
color: var(--muted);
font-size: 9px;
letter-spacing: 0.06em;
}
.cargo-state {
color: var(--muted);
font-size: 8px;
font-weight: 800;
letter-spacing: 0.08em;
text-align: right;
text-transform: uppercase;
}
.cargo-card.placed .cargo-state { color: var(--green); }
.side-footer {
margin-top: auto;
padding: 13px 18px 16px;
border-top: 1px solid var(--line);
color: var(--muted);
font-size: 10px;
line-height: 1.6;
}
.side-footer b {
color: #c7d9de;
font-weight: 700;
}
main {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
}
#scene {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#scene:active { cursor: grabbing; }
.scene-top {
position: absolute;
top: 18px;
left: 20px;
right: 20px;
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 20px;
pointer-events: none;
}
.bay-label {
padding: 11px 13px;
border: 1px solid var(--line);
border-radius: 6px;
background: rgba(7, 16, 25, 0.72);
backdrop-filter: blur(8px);
}
.bay-label span {
display: block;
color: var(--muted);
font-size: 8px;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.bay-label strong {
display: block;
margin-top: 4px;
font-size: 12px;
letter-spacing: 0.08em;
}
.density {
min-width: 150px;
padding: 11px 13px;
border: 1px solid var(--line);
border-radius: 6px;
background: rgba(7, 16, 25, 0.72);
backdrop-filter: blur(8px);
}
.density-row {
display: flex;
justify-content: space-between;
gap: 15px;
color: var(--muted);
font-size: 9px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.density-row strong {
color: var(--text);
font-variant-numeric: tabular-nums;
}
.meter {
height: 3px;
margin-top: 9px;
overflow: hidden;
background: rgba(255, 255, 255, 0.08);
}
.meter > div {
width: 0;
height: 100%;
background: linear-gradient(90deg, #32bba9, var(--cyan));
transition: width 180ms ease;
}
.toolbar {
position: absolute;
left: 50%;
bottom: 19px;
transform: translateX(-50%);
display: flex;
align-items: center;
gap: 8px;
max-width: calc(100% - 30px);
padding: 9px;
border: 1px solid var(--line-strong);
border-radius: 9px;
background: rgba(9, 20, 29, 0.91);
box-shadow: 0 14px 50px rgba(0, 0, 0, 0.32);
backdrop-filter: blur(13px);
z-index: 8;
}
.tool-group {
display: flex;
align-items: center;
gap: 4px;
padding-right: 8px;
border-right: 1px solid var(--line);
}
.tool-group:last-child {
padding-right: 0;
border-right: 0;
}
.tool-label {
margin: 0 4px 0 2px;
color: var(--muted);
font-size: 8px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
button.tool {
min-height: 32px;
padding: 0 10px;
border: 1px solid var(--line);
border-radius: 5px;
color: #c8d9de;
background: #101f2a;
cursor: pointer;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.07em;
text-transform: uppercase;
transition: 120ms ease;
white-space: nowrap;
}
button.tool:hover:not(:disabled) {
color: #fff;
border-color: rgba(73, 219, 199, 0.45);
background: #142a36;
}
button.tool:disabled {
opacity: 0.32;
cursor: not-allowed;
}
button.tool.active {
color: #071419;
border-color: var(--cyan);
background: var(--cyan);
}
button.tool.primary {
color: #09161c;
border-color: var(--cyan);
background: var(--cyan);
}
button.tool.primary:hover:not(:disabled) {
background: #6ce5d3;
}
button.tool.warn {
color: var(--orange);
border-color: rgba(255, 172, 85, 0.35);
}
.controls-note {
position: absolute;
left: 20px;
bottom: 21px;
color: rgba(170, 197, 205, 0.58);
font-size: 9px;
line-height: 1.5;
pointer-events: none;
}
.controls-note kbd {
padding: 2px 4px;
border: 1px solid var(--line);
border-radius: 3px;
color: #b8ccd2;
background: rgba(12, 25, 35, 0.75);
font: inherit;
}
#selectionInfo {
position: absolute;
left: 20px;
top: 92px;
max-width: 250px;
padding: 9px 11px;
border-left: 2px solid var(--cyan);
color: #a9c0c8;
background: rgba(7, 16, 25, 0.64);
font-size: 9px;
line-height: 1.55;
pointer-events: none;
}
#selectionInfo strong {
color: #e8f2f4;
letter-spacing: 0.06em;
}
#resultPanel {
position: absolute;
top: 92px;
right: 20px;
width: min(325px, calc(100% - 40px));
max-height: calc(100% - 180px);
overflow: auto;
border: 1px solid var(--line-strong);
border-radius: 8px;
background: rgba(9, 20, 29, 0.94);
box-shadow: 0 18px 60px rgba(0, 0, 0, 0.4);
backdrop-filter: blur(15px);
z-index: 12;
}
.result-head {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 15px;
padding: 15px;
border-bottom: 1px solid var(--line);
}
.result-head h3 {
margin: 5px 0 0;
font-size: 15px;
letter-spacing: 0.02em;
}
#closeResult {
width: 27px;
height: 27px;
border: 1px solid var(--line);
border-radius: 4px;
color: var(--muted);
background: transparent;
cursor: pointer;
}
#resultRows { padding: 7px 13px 13px; }
.result-row {
display: grid;
grid-template-columns: 27px minmax(0, 1fr) auto;
align-items: center;
gap: 9px;
min-height: 40px;
border-bottom: 1px solid rgba(255, 255, 255, 0.045);
}
.result-row:last-child { border-bottom: 0; }
.result-row .num {
display: grid;
place-items: center;
width: 23px;
height: 23px;
border: 1px solid var(--line);
border-radius: 4px;
color: var(--muted);
font-size: 9px;
font-weight: 900;
}
.result-row strong {
display: block;
font-size: 10px;
letter-spacing: 0.07em;
}
.result-row small {
display: block;
margin-top: 3px;
color: var(--muted);
font-size: 8px;
}
.route-state {
color: var(--green);
font-size: 8px;
font-weight: 900;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.route-state.blocked { color: var(--red); }
.result-error {
margin: 10px 0 3px;
padding: 10px;
border: 1px solid rgba(255, 101, 122, 0.28);
color: #ff9aaa;
background: rgba(255, 101, 122, 0.06);
font-size: 10px;
line-height: 1.5;
}
#toast {
position: absolute;
left: 50%;
top: 22px;
transform: translate(-50%, -12px);
max-width: min(520px, calc(100% - 40px));
padding: 10px 15px;
border: 1px solid var(--line-strong);
border-radius: 6px;
color: #d9e8eb;
background: rgba(9, 20, 29, 0.94);
box-shadow: 0 12px 40px rgba(0, 0, 0, 0.35);
font-size: 10px;
line-height: 1.5;
opacity: 0;
pointer-events: none;
transition: 180ms ease;
z-index: 30;
}
#toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
#toast.error {
border-color: rgba(255, 101, 122, 0.4);
color: #ffabb7;
}
#hoverTip {
position: absolute;
z-index: 15;
max-width: 210px;
padding: 7px 9px;
border: 1px solid var(--line-strong);
border-radius: 4px;
color: #d6e5e8;
background: rgba(8, 18, 27, 0.94);
font-size: 9px;
line-height: 1.4;
pointer-events: none;
}
.completion {
position: absolute;
inset: 0;
display: grid;
place-items: center;
background: rgba(4, 10, 15, 0.62);
pointer-events: none;
z-index: 25;
}
.completion-card {
width: min(390px, calc(100% - 40px));
padding: 27px;
border: 1px solid rgba(142, 227, 107, 0.4);
border-radius: 10px;
background: rgba(10, 23, 29, 0.96);
box-shadow: 0 25px 100px rgba(0, 0, 0, 0.5);
text-align: center;
}
.completion-check {
display: grid;
place-items: center;
width: 48px;
height: 48px;
margin: 0 auto 15px;
border: 1px solid var(--green);
border-radius: 50%;
color: var(--green);
font-size: 25px;
}
.completion-card h2 {
margin: 8px 0;
font-size: 24px;
}
.completion-card p {
margin: 0;
color: var(--muted);
font-size: 12px;
line-height: 1.6;
}
@media (max-width: 1050px) {
#app { grid-template-columns: 264px minmax(0, 1fr); }
.controls-note { display: none; }
.toolbar { bottom: 13px; }
button.tool { padding: 0 8px; }
}
@media (max-width: 760px) {
#app {
grid-template-columns: 1fr;
grid-template-rows: 58px minmax(300px, 58vh) minmax(190px, 1fr);
}
header { padding: 0 12px; }
.brand p, .header-stat { display: none; }
#statusPill { min-width: 112px; font-size: 8px; }
aside {
grid-row: 3;
border-right: 0;
border-top: 1px solid var(--line);
}
.brief, .side-footer { display: none; }
.manifest-head { padding: 9px 13px 4px; }
#manifest {
display: flex;
gap: 6px;
overflow-x: auto;
overflow-y: hidden;
padding: 4px 10px 10px;
}
.cargo-card {
flex: 0 0 238px;
margin: 0;
min-height: 60px;
}
.scene-top { top: 10px; left: 10px; right: 10px; }
.density { min-width: 120px; }
#selectionInfo { left: 10px; top: 74px; }
#resultPanel { top: 72px; right: 10px; }
.toolbar {
width: calc(100% - 20px);
max-width: none;
overflow-x: auto;
justify-content: flex-start;
bottom: 10px;
}
.tool-group { flex: 0 0 auto; }
}
</style>
</head>
<body>
<div id="app">
<header>
<div class="brand">
<div class="brand-mark" aria-hidden="true"></div>
<div>
<h1>VOXEL CARGO</h1>
<p>Ordered extraction / Bay 07</p>
</div>
</div>
<div class="header-stats">
<div class="header-stat">
<span>Mission</span>
<strong>Pack · Extract · Certify</strong>
</div>
<div class="header-stat">
<span>Hold</span>
<strong>7 × 5 × 4 cells</strong>
</div>
<div id="statusPill">Awaiting packing</div>
</div>
</header>
<aside>
<section class="brief">
<div class="eyebrow">Loading Directive 07</div>
<h2>Fill the hold without trapping the cargo.</h2>
<p>
Place all <strong>seven voxel modules</strong> inside the bounded hold.
Every module must remain removable through the orange side gate in the
numbered unloading order.
</p>
</section>
<div class="manifest-head">
<h3>Unloading Manifest</h3>
<span id="manifestCount">0 / 7 placed</span>
</div>
<div id="manifest"></div>
<div class="side-footer">
<b>Certification:</b> a complete silhouette is not enough. The game
simulates each crate through the actual hold and verifies a
collision-free extraction route in manifest order.
</div>
</aside>
<main>
<canvas id="scene" aria-label="Interactive voxel cargo hold"></canvas>
<div class="scene-top">
<div class="bay-label">
<span>Active hold</span>
<strong>BAY 07 / ORANGE SLIDE GATE</strong>
</div>
<div class="density">
<div class="density-row">
<span>Cargo density</span>
<strong id="densityValue">0%</strong>
</div>
<div class="meter"><div id="densityBar"></div></div>
</div>
</div>
<div id="selectionInfo">
Select a manifest module. Click a hold cell to place it.
</div>
<div class="controls-note">
<kbd>drag</kbd> orbit <kbd>wheel</kbd> zoom<br />
<kbd>right-drag</kbd> pan <kbd>R</kbd> rotate <kbd>1–4</kbd> deck
</div>
<div class="toolbar">
<div class="tool-group">
<span class="tool-label">Deck</span>
<button class="tool active" data-layer="0">1</button>
<button class="tool" data-layer="1">2</button>
<button class="tool" data-layer="2">3</button>
<button class="tool" data-layer="3">4</button>
</div>
<div class="tool-group">
<button class="tool" id="rotateBtn" disabled>Rotate R</button>
<button class="tool" id="liftBtn" disabled>Lift</button>
</div>
<div class="tool-group">
<button class="tool" id="hintBtn">Hint</button>
<button class="tool" id="clearBtn">Clear</button>
</div>
<div class="tool-group">
<button class="tool" id="checkBtn">Check paths</button>
<button class="tool primary" id="runBtn">Run unload</button>
</div>
</div>
<section id="resultPanel" hidden>
<div class="result-head">
<div>
<div class="eyebrow">Extraction audit</div>
<h3 id="resultTitle">Route audit</h3>
</div>
<button id="closeResult" aria-label="Close result panel">×</button>
</div>
<div id="resultRows"></div>
</section>
<div id="hoverTip" hidden></div>
<div id="toast" role="status" aria-live="polite"></div>
<div class="completion" id="completion" hidden>
<div class="completion-card">
<div class="completion-check">✓</div>
<div class="eyebrow">Manifest complete</div>
<h2>Hold certified clear.</h2>
<p>
Every module fit inside the hold and left through the side gate in
the required order.
</p>
</div>
</div>
</main>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
/* --------------------------------------------------------------------------
Puzzle data
-------------------------------------------------------------------------- */
const W = 7;
const D = 5;
const H = 4;
const HOLD_VOLUME = W * D * H;
const cargos = [
{
id: "FLANGE-8",
order: 1,
dims: [2, 3, 2],
color: 0x49dbc7,
orientation: 0,
pos: null,
done: false
},
{
id: "BLOCK-6",
order: 2,
dims: [2, 2, 3],
color: 0xffb454,
orientation: 0,
pos: null,
done: false
},
{
id: "RELAY-3",
order: 3,
dims: [3, 2, 2],
color: 0x668fff,
orientation: 0,
pos: null,
done: false
},
{
id: "KITE-4",
order: 4,
dims: [3, 3, 2],
color: 0xaa7cff,
orientation: 0,
pos: null,
done: false
},
{
id: "PYLON-9",
order: 5,
dims: [3, 2, 3],
color: 0xff657a,
orientation: 0,
pos: null,
done: false
},
{
id: "ORB-7",
order: 6,
dims: [2, 3, 2],
color: 0x9de24f,
orientation: 0,
pos: null,
done: false
},
{
id: "CAP-2",
order: 7,
dims: [2, 2, 2],
color: 0xffd166,
orientation: 0,
pos: null,
done: false
}
];
const orderedCargos = [...cargos].sort((a, b) => a.order - b.order);
const solution = {
"FLANGE-8": [5, 2, 0],
"BLOCK-6": [3, 2, 0],
"RELAY-3": [3, 0, 0],
"KITE-4": [0, 0, 0],
"PYLON-9": [0, 3, 0],
"ORB-7": [0, 0, 2],
"CAP-2": [3, 0, 2]
};
const canvas = document.getElementById("scene");
const manifestEl = document.getElementById("manifest");
const manifestCountEl = document.getElementById("manifestCount");
const statusPillEl = document.getElementById("statusPill");
const densityValueEl = document.getElementById("densityValue");
const densityBarEl = document.getElementById("densityBar");
const selectionInfoEl = document.getElementById("selectionInfo");
const resultPanelEl = document.getElementById("resultPanel");
const resultTitleEl = document.getElementById("resultTitle");
const resultRowsEl = document.getElementById("resultRows");
const toastEl = document.getElementById("toast");
const hoverTipEl = document.getElementById("hoverTip");
const completionEl = document.getElementById("completion");
const rotateBtn = document.getElementById("rotateBtn");
const liftBtn = document.getElementById("liftBtn");
const hintBtn = document.getElementById("hintBtn");
const clearBtn = document.getElementById("clearBtn");
const checkBtn = document.getElementById("checkBtn");
const runBtn = document.getElementById("runBtn");
let selectedId = null;
let selectedLayer = 0;
let hoverCell = null;
let animating = false;
let completed = false;
let toastTimer = 0;
const cargoGroups = new Map();
const pathLines = [];
/* --------------------------------------------------------------------------
Three.js setup
-------------------------------------------------------------------------- */
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
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.1;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x071019);
scene.fog = new THREE.Fog(0x071019, 22, 42);
const camera = new THREE.OrthographicCamera(-8, 8, 6, -6, 0.1, 100);
const cameraTarget = new THREE.Vector3(0, 0, 1.45);
let cameraYaw = 0.68;
let cameraPitch = 0.68;
let cameraZoom = 1;
const hemisphere = new THREE.HemisphereLight(0xbfefff, 0x162028, 2.2);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xd9f7ff, 3.1);
keyLight.position.set(7, -9, 13);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -12;
keyLight.shadow.camera.right = 12;
keyLight.shadow.camera.top = 12;
keyLight.shadow.camera.bottom = -12;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 35;
keyLight.shadow.bias = -0.0004;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x4ee4d1, 1.15);
rimLight.position.set(-8, 7, 6);
scene.add(rimLight);
const orangeLight = new THREE.PointLight(0xff9c43, 8, 12, 2);
orangeLight.position.set(W / 2 + 2, 0, 2);
scene.add(orangeLight);
const voxelGeometry = new THREE.BoxGeometry(0.91, 0.91, 0.91);
const floorGeometry = new THREE.BoxGeometry(0.94, 0.94, 0.1);
const ghostMaterial = new THREE.MeshStandardMaterial({
color: 0x55e0bd,
transparent: true,
opacity: 0.3,
depthWrite: false,
roughness: 0.7,
emissive: 0x1b6b5d,
emissiveIntensity: 0.35
});
const ghostGroup = new THREE.Group();
scene.add(ghostGroup);
let ghostCargoId = null;
const layerPlane = new THREE.Mesh(
new THREE.PlaneGeometry(W, D),
new THREE.MeshBasicMaterial({
color: 0x49dbc7,
transparent: true,
opacity: 0.035,
depthWrite: false,
side: THREE.DoubleSide
})
);
layerPlane.visible = false;
scene.add(layerPlane);
buildBay();
function buildBay() {
const group = new THREE.Group();
scene.add(group);
const floorMaterial = new THREE.MeshStandardMaterial({
color: 0x10232d,
roughness: 0.88,
metalness: 0.04
});
const alternateMaterial = new THREE.MeshStandardMaterial({
color: 0x122a34,
roughness: 0.88,
metalness: 0.04
});
for (let x = 0; x < W; x++) {
for (let y = 0; y < D; y++) {
const tile = new THREE.Mesh(
floorGeometry,
(x + y) % 2 ? floorMaterial : alternateMaterial
);
tile.position.set(x - W / 2 + 0.5, y - D / 2 + 0.5, -0.07);
tile.receiveShadow = true;
group.add(tile);
}
}
const gridPoints = [];
for (let x = 0; x <= W; x++) {
gridPoints.push(
new THREE.Vector3(x - W / 2, -D / 2, 0.015),
new THREE.Vector3(x - W / 2, D / 2, 0.015)
);
}
for (let y = 0; y <= D; y++) {
gridPoints.push(
new THREE.Vector3(-W / 2, y - D / 2, 0.015),
new THREE.Vector3(W / 2, y - D / 2, 0.015)
);
}
const gridGeometry = new THREE.BufferGeometry().setFromPoints(gridPoints);
const grid = new THREE.LineSegments(
gridGeometry,
new THREE.LineBasicMaterial({
color: 0x4f7885,
transparent: true,
opacity: 0.27
})
);
group.add(grid);
const wallMaterial = new THREE.MeshStandardMaterial({
color: 0x17313d,
transparent: true,
opacity: 0.11,
depthWrite: false,
side: THREE.DoubleSide
});
const backWall = new THREE.Mesh(
new THREE.BoxGeometry(W + 0.25, 0.08, H),
wallMaterial
);
backWall.position.set(0, D / 2 + 0.03, H / 2);
group.add(backWall);
const leftWall = new THREE.Mesh(
new THREE.BoxGeometry(0.08, D + 0.25, H),
wallMaterial
);
leftWall.position.set(-W / 2 - 0.03, 0, H / 2);
group.add(leftWall);
const frameMaterial = new THREE.MeshStandardMaterial({
color: 0x35525c,
emissive: 0x0a171b,
roughness: 0.45,
metalness: 0.45
});
const postGeometry = new THREE.BoxGeometry(0.11, 0.11, H + 0.16);
for (const x of [-W / 2, W / 2]) {
for (const y of [-D / 2, D / 2]) {
const post = new THREE.Mesh(postGeometry, frameMaterial);
post.position.set(x, y, H / 2);
post.castShadow = true;
group.add(post);
}
}
const topFramePoints = [
new THREE.Vector3(-W / 2, -D / 2, H),
new THREE.Vector3(W / 2, -D / 2, H),
new THREE.Vector3(W / 2, -D / 2, H),
new THREE.Vector3(W / 2, D / 2, H),
new THREE.Vector3(W / 2, D / 2, H),
new THREE.Vector3(-W / 2, D / 2, H),
new THREE.Vector3(-W / 2, D / 2, H),
new THREE.Vector3(-W / 2, -D / 2, H)
];
const topFrame = new THREE.LineSegments(
new THREE.BufferGeometry().setFromPoints(topFramePoints),
new THREE.LineBasicMaterial({ color: 0x6b929d, transparent: true, opacity: 0.55 })
);
group.add(topFrame);
// Orange extraction gate at +X.
const gateMaterial = new THREE.MeshStandardMaterial({
color: 0xffa34e,
emissive: 0xff7624,
emissiveIntensity: 0.55,
roughness: 0.38,
metalness: 0.38
});
const gateVerticalGeometry = new THREE.BoxGeometry(0.14, 0.12, H + 0.22);
for (const y of [-D / 2, D / 2]) {
const bar = new THREE.Mesh(gateVerticalGeometry, gateMaterial);
bar.position.set(W / 2 + 0.12, y, H / 2);
group.add(bar);
}
const gateHorizontalGeometry = new THREE.BoxGeometry(0.14, D + 0.24, 0.12);
for (const z of [0, H]) {
const bar = new THREE.Mesh(gateHorizontalGeometry, gateMaterial);
bar.position.set(W / 2 + 0.12, 0, z);
group.add(bar);
}
const arrowShaft = new THREE.Mesh(
new THREE.BoxGeometry(1.1, 0.13, 0.13),
gateMaterial
);
arrowShaft.position.set(W / 2 + 1.05, 0, 1.5);
group.add(arrowShaft);
const arrowHead = new THREE.Mesh(
new THREE.ConeGeometry(0.28, 0.62, 4),
gateMaterial
);
arrowHead.rotation.z = -Math.PI / 2;
arrowHead.position.set(W / 2 + 1.87, 0, 1.5);
group.add(arrowHead);
const exitLabel = makeTextSprite("EXIT", "#ffb35f", 0x1d120b);
exitLabel.scale.set(1.35, 0.47, 1);
exitLabel.position.set(W / 2 + 1.15, -0.6, 2.22);
group.add(exitLabel);
const shadow = new THREE.Mesh(
new THREE.PlaneGeometry(30, 30),
new THREE.ShadowMaterial({ color: 0x000000, opacity: 0.28 })
);
shadow.rotation.x = -Math.PI / 2;
shadow.position.z = -0.14;
shadow.receiveShadow = true;
group.add(shadow);
}
function makeTextSprite(text, foreground = "#e9f3f5", background = "#0b1b24") {
const labelCanvas = document.createElement("canvas");
labelCanvas.width = 256;
labelCanvas.height = 112;
const ctx = labelCanvas.getContext("2d");
ctx.clearRect(0, 0, 256, 112);
ctx.fillStyle = background;
ctx.globalAlpha = 0.94;
ctx.beginPath();
ctx.roundRect(7, 7, 242, 98, 18);
ctx.fill();
ctx.globalAlpha = 1;
ctx.strokeStyle = foreground;
ctx.globalAlpha = 0.65;
ctx.lineWidth = 4;
ctx.stroke();
ctx.globalAlpha = 1;
ctx.fillStyle = foreground;
ctx.font = "800 48px system-ui, sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text, 128, 59);
const texture = new THREE.CanvasTexture(labelCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.userData.texture = texture;
return sprite;
}
/* --------------------------------------------------------------------------
Cargo geometry and state
-------------------------------------------------------------------------- */
function dimensions(cargo) {
const [a, b, h] = cargo.dims;
return cargo.orientation % 2
? { w: b, d: a, h }
: { w: a, d: b, h };
}
function cargoVolume(cargo) {
return cargo.dims[0] * cargo.dims[1] * cargo.dims[2];
}
function worldPosition(x, y, z = 0) {
return new THREE.Vector3(x - W / 2, y - D / 2, z);
}
function cellKey(x, y, z) {
return `${x},${y},${z}`;
}
function cargoCells(cargo, x, y, z) {
const { w, d, h } = dimensions(cargo);
const cells = [];
for (let ix = 0; ix < w; ix++) {
for (let iy = 0; iy < d; iy++) {
for (let iz = 0; iz < h; iz++) {
cells.push([x + ix, y + iy, z + iz]);
}
}
}
return cells;
}
function makeOrderBadge(cargo) {
const badgeCanvas = document.createElement("canvas");
badgeCanvas.width = 128;
badgeCanvas.height = 128;
const ctx = badgeCanvas.getContext("2d");
const color = `#${cargo.color.toString(16).padStart(6, "0")}`;
ctx.fillStyle = "#071219";
ctx.globalAlpha = 0.9;
ctx.beginPath();
ctx.roundRect(10, 10, 108, 108, 22);
ctx.fill();
ctx.globalAlpha = 1;
ctx.strokeStyle = color;
ctx.lineWidth = 6;
ctx.stroke();
ctx.fillStyle = color;
ctx.font = "900 61px system-ui, sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(String(cargo.order).padStart(2, "0"), 64, 66);
const texture = new THREE.CanvasTexture(badgeCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
const sprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthWrite: false
})
);
sprite.scale.set(0.62, 0.62, 1);
sprite.userData.texture = texture;
return sprite;
}
function removeCargoGroup(cargo) {
const group = cargoGroups.get(cargo.id);
if (!group) return;
scene.remove(group);
if (group.userData.material) {
group.userData.material.dispose();
}
if (group.userData.badge?.userData.texture) {
group.userData.badge.userData.texture.dispose();
group.userData.badge.material.dispose();
}
if (group.userData.edgeGeometry) {
group.userData.edgeGeometry.dispose();
}
if (group.userData.edgeMaterial) {
group.userData.edgeMaterial.dispose();
}
cargoGroups.delete(cargo.id);
}
function buildCargoGroup(cargo) {
removeCargoGroup(cargo);
const { w, d, h } = dimensions(cargo);
const group = new THREE.Group();
const material = new THREE.MeshStandardMaterial({
color: cargo.color,
emissive: cargo.color,
emissiveIntensity: 0.045,
roughness: 0.58,
metalness: 0.08
});
for (let x = 0; x < w; x++) {
for (let y = 0; y < d; y++) {
for (let z = 0; z < h; z++) {
const cube = new THREE.Mesh(voxelGeometry, material);
cube.position.set(x + 0.5, y + 0.5, z + 0.5);
cube.castShadow = true;
cube.receiveShadow = true;
cube.userData.cargoId = cargo.id;
group.add(cube);
}
}
}
const edgeGeometry = new THREE.EdgesGeometry(
new THREE.BoxGeometry(w + 0.02, d + 0.02, h + 0.02)
);
const edgeMaterial = new THREE.LineBasicMaterial({
color: cargo.color,
transparent: true,
opacity: 0.62
});
const edges = new THREE.LineSegments(edgeGeometry, edgeMaterial);
edges.position.set(w / 2, d / 2, h / 2);
group.add(edges);
const badge = makeOrderBadge(cargo);
badge.position.set(w / 2, d / 2, h + 0.38);
group.add(badge);
group.userData.material = material;
group.userData.edgeGeometry = edgeGeometry;
group.userData.edgeMaterial = edgeMaterial;
group.userData.badge = badge;
cargoGroups.set(cargo.id, group);
scene.add(group);
placeCargoGroup(cargo);
return group;
}
function placeCargoGroup(cargo) {
const group = cargoGroups.get(cargo.id);
if (!group || !cargo.pos) return;
const [x, y, z] = cargo.pos;
group.position.copy(worldPosition(x, y, z));
}
function rebuildGhost(cargo) {
while (ghostGroup.children.length) {
ghostGroup.remove(ghostGroup.children[0]);
}
ghostCargoId = cargo?.id ?? null;
if (!cargo) return;
const { w, d, h } = dimensions(cargo);
for (let x = 0; x < w; x++) {
for (let y = 0; y < d; y++) {
for (let z = 0; z < h; z++) {
const cube = new THREE.Mesh(voxelGeometry, ghostMaterial);
cube.position.set(x + 0.5, y + 0.5, z + 0.5);
ghostGroup.add(cube);
}
}
}
}
function buildManifest() {
manifestEl.innerHTML = "";
for (const cargo of orderedCargos) {
const card = document.createElement("button");
card.className = "cargo-card";
card.type = "button";
card.dataset.cargoId = cargo.id;
card.style.setProperty("--cargo-color", `#${cargo.color.toString(16).padStart(6, "0")}`);
const order = document.createElement("span");
order.className = "order-badge";
order.textContent = String(cargo.order).padStart(2, "0");
const footprint = document.createElement("span");
footprint.className = "footprint";
const copy = document.createElement("span");
copy.className = "cargo-copy";
copy.innerHTML = `<strong>${cargo.id}</strong><span></span>`;
const state = document.createElement("span");
state.className = "cargo-state";
state.textContent = "Staged";
card.append(order, footprint, copy, state);
card.addEventListener("click", () => selectCargo(cargo.id));
manifestEl.appendChild(card);
}
updateManifest();
}
function updateFootprint(card, cargo) {
const footprint = card.querySelector(".footprint");
const { w, d } = dimensions(cargo);
footprint.style.gridTemplateColumns = `repeat(${w}, 6px)`;
footprint.innerHTML = "";
for (let y = 0; y < d; y++) {
for (let x = 0; x < w; x++) {
const cell = document.createElement("i");
footprint.appendChild(cell);
}
}
}
function updateManifest() {
for (const card of manifestEl.querySelectorAll(".cargo-card")) {
const cargo = cargos.find(c => c.id === card.dataset.cargoId);
const selected = selectedId === cargo.id;
const placed = Boolean(cargo.pos);
card.classList.toggle("selected", selected);
card.classList.toggle("placed", placed);
card.classList.toggle("unloaded", cargo.done);
const state = card.querySelector(".cargo-state");
state.textContent = cargo.done
? "Unloaded"
: placed
? `Deck ${cargo.pos[2] + 1}`
: "Staged";
const { w, d, h } = dimensions(cargo);
card.querySelector(".cargo-copy span").textContent =
`${w} × ${d} × ${h} / ${cargoVolume(cargo)} vox`;
updateFootprint(card, cargo);
}
const placedCount = cargos.filter(c => c.pos).length;
manifestCountEl.textContent = `${placedCount} / ${cargos.length} placed`;
const volume = cargos.reduce((sum, cargo) => {
return sum + (cargo.pos ? cargoVolume(cargo) : 0);
}, 0);
const density = Math.round((volume / HOLD_VOLUME) * 100);
densityValueEl.textContent = `${density}%`;
densityBarEl.style.width = `${density}%`;
const selected = cargos.find(c => c.id === selectedId);
rotateBtn.disabled = !selected || animating || completed;
liftBtn.disabled = !selected || !selected.pos || animating || completed;
if (selected) {
const { w, d, h } = dimensions(selected);
selectionInfoEl.innerHTML =
`<strong>${selected.id}</strong> · ${w} × ${d} × ${h}<br>` +
(selected.pos
? `Placed at X${selected.pos[0] + 1}, Y${selected.pos[1] + 1}, deck ${selected.pos[2] + 1}.`
: `Choose deck ${selectedLayer + 1}, then click a hold cell.`);
} else {
selectionInfoEl.textContent =
"Select a manifest module. Click a hold cell to place it.";
}
if (completed) {
setStatus("Manifest complete", "success");
} else if (animating) {
setStatus("Unloading in sequence", "warning");
} else if (placedCount === cargos.length) {
setStatus("Ready for path check", "warning");
} else {
setStatus("Awaiting packing", "normal");
}
}
/* --------------------------------------------------------------------------
Placement validation
-------------------------------------------------------------------------- */
function buildOccupancy() {
const occupancy = new Map();
for (const cargo of cargos) {
if (!cargo.pos) continue;
const [x, y, z] = cargo.pos;
for (const [cx, cy, cz] of cargoCells(cargo, x, y, z)) {
occupancy.set(cellKey(cx, cy, cz), cargo.id);
}
}
return occupancy;
}
function validatePlacement(cargo, x, y, z) {
const { w, d, h } = dimensions(cargo);
if (x < 0 || y < 0 || z < 0 || x + w > W || y + d > D || z + h > H) {
return { ok: false, reason: "Outside the bounded hold" };
}
const occupancy = buildOccupancy();
for (const [cx, cy, cz] of cargoCells(cargo, x, y, z)) {
if (occupancy.has(cellKey(cx, cy, cz))) {
return { ok: false, reason: "Overlaps another module" };
}
}
for (let ix = 0; ix < w; ix++) {
for (let iy = 0; iy < d; iy++) {
if (z > 0 && !occupancy.has(cellKey(x + ix, y + iy, z - 1))) {
return { ok: false, reason: "Unsupported: place a module underneath" };
}
}
}
return { ok: true, reason: "Stable placement" };
}
function hasDependents(cargoId) {
for (const other of cargos) {
if (!other.pos || other.id === cargoId) continue;
const { w, d } = dimensions(other);
const [x, y, z] = other.pos;
for (let ix = 0; ix < w; ix++) {
for (let iy = 0; iy < d; iy++) {
if (z > 0) {
const below = buildOccupancy().get(cellKey(x + ix, y + iy, z - 1));
if (below === cargoId) return true;
}
}
}
}
return false;
}
function selectCargo(id) {
if (animating || completed) return;
selectedId = id;
const cargo = cargos.find(c => c.id === id);
selectedLayer = cargo?.pos ? cargo.pos[2] : 0;
rebuildGhost(cargo);
updateManifest();
updateGhost();
}
function placeSelectedAt(x, y, z) {
const cargo = cargos.find(c => c.id === selectedId);
if (!cargo || cargo.pos || completed || animating) return;
const validation = validatePlacement(cargo, x, y, z);
if (!validation.ok) {
toast(validation.reason, true);
return;
}
cargo.pos = [x, y, z];
cargo.done = false;
buildCargoGroup(cargo);
updateManifest();
updateGhost();
toast(`${cargo.id} secured on deck ${z + 1}.`);
}
function liftSelected() {
const cargo = cargos.find(c => c.id === selectedId);
if (!cargo?.pos || animating || completed) return;
if (hasDependents(cargo.id)) {
toast("Lift the modules stacked on this one first.", true);
return;
}
cargo.pos = null;
cargo.done = false;
removeCargoGroup(cargo);
selectedLayer = 0;
rebuildGhost(cargo);
updateManifest();
updateGhost();
}
function rotateSelected() {
const cargo = cargos.find(c => c.id === selectedId);
if (!cargo || animating || completed) return;
if (cargo.pos) {
if (hasDependents(cargo.id)) {
toast("Lift the modules stacked on this one first.", true);
return;
}
cargo.pos = null;
removeCargoGroup(cargo);
selectedLayer = 0;
}
cargo.orientation = (cargo.orientation + 1) % 2;
rebuildGhost(cargo);
updateManifest();
updateGhost();
}
function setLayer(layer) {
if (animating || completed) return;
selectedLayer = THREE.MathUtils.clamp(layer, 0, H - 1);
document.querySelectorAll("[data-layer]").forEach(button => {
button.classList.toggle("active", Number(button.dataset.layer) === selectedLayer);
});
updateGhost();
}
/* --------------------------------------------------------------------------
Extraction-path solver
-------------------------------------------------------------------------- */
function collidesWithOccupancy(cargo, x, y, z, occupancy) {
const { w, d, h } = dimensions(cargo);
if (x < 0 || y < 0 || z < 0 || x + w > W || y + d > D || z + h > H) {
return true;
}
for (let ix = 0; ix < w; ix++) {
for (let iy = 0; iy < d; iy++) {
for (let iz = 0; iz < h; iz++) {
if (occupancy.has(cellKey(x + ix, y + iy, z + iz))) {
return true;
}
}
}
}
return false;
}
function findExtractionPath(cargo, start, occupancy) {
const { w } = dimensions(cargo);
const startKey = `${start.x},${start.y},${start.z}`;
const queue = [{ x: start.x, y: start.y, z: start.z }];
const cameFrom = new Map([[startKey, null]]);
const visited = new Set([startKey]);
const neighbors = [
[1, 0, 0],
[-1, 0, 0],
[0, 1, 0],
[0, -1, 0],
[0, 0, 1],
[0, 0, -1]
];
while (queue.length) {
const current = queue.shift();
// The side gate spans the complete usable Y/Z face.
// Reaching the +X boundary aligns the module with the gate.
if (current.x + w === W) {
const path = [];
let key = `${current.x},${current.y},${current.z}`;
while (key !== null) {
const [x, y, z] = key.split(",").map(Number);
path.push({ x, y, z });
key = cameFrom.get(key);
}
path.reverse();
return path;
}
for (const [dx, dy, dz] of neighbors) {
const next = {
x: current.x + dx,
y: current.y + dy,
z: current.z + dz
};
const key = `${next.x},${next.y},${next.z}`;
if (visited.has(key)) continue;
if (collidesWithOccupancy(cargo, next.x, next.y, next.z, occupancy)) continue;
visited.add(key);
cameFrom.set(key, `${current.x},${current.y},${current.z}`);
queue.push(next);
}
}
return null;
}
function computeExtractionPlan() {
const result = {
valid: false,
errors: [],
paths: [],
blocked: null
};
const missing = cargos.filter(c => !c.pos);
if (missing.length) {
result.errors.push(`${missing.length} module${missing.length > 1 ? "s are" : " is"} not placed.`);
}
const occupancy = buildOccupancy();
for (const cargo of cargos) {
if (!cargo.pos) continue;
const [x, y, z] = cargo.pos;
const { w, d, h } = dimensions(cargo);
if (x < 0 || y < 0 || z < 0 || x + w > W || y + d > D || z + h > H) {
result.errors.push(`${cargo.id} extends outside the hold.`);
continue;
}
let overlap = false;
for (const [cx, cy, cz] of cargoCells(cargo, x, y, z)) {
const owner = occupancy.get(cellKey(cx, cy, cz));
if (owner && owner !== cargo.id) {
overlap = true;
break;
}
}
if (overlap) {
result.errors.push(`${cargo.id} overlaps another module.`);
continue;
}
for (let ix = 0; ix < w; ix++) {
for (let iy = 0; iy < d; iy++) {
if (z > 0 && !occupancy.has(cellKey(x + ix, y + iy, z - 1))) {
result.errors.push(`${cargo.id} is unsupported.`);
ix = w;
iy = d;
}
}
}
}
if (result.errors.length) return result;
// Remove each cargo from the occupancy set in the stated unloading order.
// The BFS then searches the actual remaining hold for a collision-free path.
for (const cargo of orderedCargos) {
const [x, y, z] = cargo.pos;
for (const [cx, cy, cz] of cargoCells(cargo, x, y, z)) {
occupancy.delete(cellKey(cx, cy, cz));
}
const path = findExtractionPath(
cargo,
{ x, y, z },
occupancy
);
if (!path) {
result.blocked = cargo;
result.errors.push(
`${cargo.id} has no collision-free route to the side gate at unload step ${cargo.order}.`
);
return result;
}
result.paths.push({ cargo, path });
}
result.valid = true;
return result;
}
function clearPathLines() {
for (const line of pathLines) {
scene.remove(line);
line.geometry.dispose();
line.material.dispose();
}
pathLines.length = 0;
}
function drawPathLines(plan) {
clearPathLines();
for (const item of plan.paths) {
const points = item.path.map(p => worldPosition(p.x, p.y, p.z));
const last = points[points.length - 1].clone();
last.x = W / 2 + dimensions(item.cargo).w + 1;
points.push(last);
const geometry = new THREE.BufferGeometry().setFromPoints(points);
const material = new THREE.LineBasicMaterial({
color: item.cargo.color,
transparent: true,
opacity: 0.82
});
const line = new THREE.Line(geometry, material);
line.renderOrder = 5;
scene.add(line);
pathLines.push(line);
}
}
function showResult(plan) {
resultPanelEl.hidden = false;
resultRowsEl.innerHTML = "";
if (plan.valid) {
resultTitleEl.textContent = "Path certificate";
} else {
resultTitleEl.textContent = plan.blocked ? "Route blocked" : "Packing invalid";
}
for (const error of plan.errors) {
const errorEl = document.createElement("div");
errorEl.className = "result-error";
errorEl.textContent = error;
resultRowsEl.appendChild(errorEl);
}
for (const item of plan.paths) {
const row = document.createElement("div");
row.className = "result-row";
const num = document.createElement("span");
num.className = "num";
num.textContent = String(item.cargo.order).padStart(2, "0");
const copy = document.createElement("span");
copy.innerHTML =
`<strong>${item.cargo.id}</strong>` +
`<small>${item.path.length - 1} transit cells to gate</small>`;
const state = document.createElement("span");
state.className = "route-state";
state.textContent = "Clear";
row.append(num, copy, state);
resultRowsEl.appendChild(row);
}
}
/* --------------------------------------------------------------------------
Unload animation
-------------------------------------------------------------------------- */
function tweenPosition(object, target, duration) {
return new Promise(resolve => {
const from = object.position.clone();
const start = performance.now();
function frame(now) {
const t = Math.min(1, (now - start) / duration);
const eased = t < 0.5
? 2 * t * t
: 1 - Math.pow(-2 * t + 2, 2) / 2;
object.position.lerpVectors(from, target, eased);
if (t < 1) {
requestAnimationFrame(frame);
} else {
object.position.copy(target);
resolve();
}
}
requestAnimationFrame(frame);
});
}
async function runUnload() {
if (animating || completed) return;
const plan = computeExtractionPlan();
showResult(plan);
drawPathLines(plan);
if (!plan.valid) {
toast(plan.errors[0] || "No valid extraction sequence.", true);
setStatus("Audit failed", "error");
return;
}
animating = true;
updateManifest();
for (const item of plan.paths) {
const cargo = item.cargo;
const group = cargoGroups.get(cargo.id);
if (!group) continue;
group.userData.material.emissiveIntensity = 0.32;
for (let i = 1; i < item.path.length; i++) {
const point = item.path[i];
const target = worldPosition(point.x, point.y, point.z);
await tweenPosition(group, target, 48);
}
const exitTarget = worldPosition(
W + dimensions(cargo).w + 1,
cargo.pos[1],
cargo.pos[2]
);
await tweenPosition(group, exitTarget, 720);
cargo.done = true;
removeCargoGroup(cargo);
updateManifest();
}
animating = false;
completed = true;
updateManifest();
completionEl.hidden = false;
resultTitleEl.textContent = "Certificate issued";
setStatus("Manifest complete", "success");
}
/* --------------------------------------------------------------------------
Camera and pointer interaction
-------------------------------------------------------------------------- */
const raycaster = new THREE.Raycaster();
const pointerNDC = new THREE.Vector2();
let pointerDown = null;
function resize() {
const width = canvas.clientWidth;
const height = canvas.clientHeight;
const aspect = width / Math.max(1, height);
const viewHeight = 9.6 * cameraZoom;
camera.left = (-viewHeight * aspect) / 2;
camera.right = (viewHeight * aspect) / 2;
camera.top = viewHeight / 2;
camera.bottom = -viewHeight / 2;
camera.updateProjectionMatrix();
renderer.setSize(width, height, false);
}
function updateCamera() {
const radius = 20;
const horizontal = Math.cos(cameraPitch) * radius;
camera.position.set(
cameraTarget.x + Math.sin(cameraYaw) * horizontal,
cameraTarget.y - Math.cos(cameraYaw) * horizontal,
cameraTarget.z + Math.sin(cameraPitch) * radius
);
camera.lookAt(cameraTarget);
}
function setPointerFromEvent(event) {
const rect = canvas.getBoundingClientRect();
pointerNDC.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointerNDC.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
}
function getCargoHit(event) {
setPointerFromEvent(event);
raycaster.setFromCamera(pointerNDC, camera);
const groups = [...cargoGroups.values()];
const hits = raycaster.intersectObjects(groups, true);
for (const hit of hits) {
if (hit.object.userData.cargoId) {
return hit.object.userData.cargoId;
}
}
return null;
}
function getHoverCell(event) {
const cargo = cargos.find(c => c.id === selectedId);
if (!cargo || cargo.pos) return null;
setPointerFromEvent(event);
raycaster.setFromCamera(pointerNDC, camera);
const plane = new THREE.Plane(
new THREE.Vector3(0, 0, 1),
-selectedLayer
);
const point = new THREE.Vector3();
if (!raycaster.ray.intersectPlane(plane, point)) return null;
const x = Math.floor(point.x + W / 2);
const y = Math.floor(point.y + D / 2);
if (x < 0 || x >= W || y < 0 || y >= D) return null;
return { x, y, z: selectedLayer };
}
function updateGhost() {
const cargo = cargos.find(c => c.id === selectedId);
if (!cargo || cargo.pos || completed || animating) {
ghostGroup.visible = false;
layerPlane.visible = false;
hoverTipEl.hidden = true;
return;
}
layerPlane.visible = true;
layerPlane.position.z = selectedLayer;
if (!hoverCell) {
ghostGroup.visible = false;
hoverTipEl.hidden = true;
return;
}
const { x, y, z } = hoverCell;
const validation = validatePlacement(cargo, x, y, z);
const { w, d, h } = dimensions(cargo);
ghostGroup.visible = true;
ghostGroup.position.copy(worldPosition(x, y, z));
ghostMaterial.color.setHex(validation.ok ? 0x55e0bd : 0xff657a);
ghostMaterial.emissive.setHex(validation.ok ? 0x1b6b5d : 0x6b1420);
hoverTipEl.hidden = false;
hoverTipEl.innerHTML =
`<strong>${cargo.id}</strong> · ${w} × ${d} × ${h}<br>` +
`${validation.reason}`;
}
function updateHoverTipPosition(event) {
const rect = canvas.getBoundingClientRect();
const x = event.clientX - rect.left + 14;
const y = event.clientY - rect.top + 14;
hoverTipEl.style.left = `${Math.min(x, rect.width - 220)}px`;
hoverTipEl.style.top = `${Math.min(y, rect.height - 70)}px`;
}
canvas.addEventListener("pointerdown", event => {
if (animating || completed) return;
const cargoHit = getCargoHit(event);
pointerDown = {
x: event.clientX,
y: event.clientY,
lastX: event.clientX,
lastY: event.clientY,
moved: false,
button: event.button,
cargoHit
};
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", event => {
if (pointerDown) {
const dx = event.clientX - pointerDown.lastX;
const dy = event.clientY - pointerDown.lastY;
const totalDistance = Math.hypot(
event.clientX - pointerDown.x,
event.clientY - pointerDown.y
);
if (totalDistance > 4) pointerDown.moved = true;
if (pointerDown.moved && pointerDown.button === 0 && !pointerDown.cargoHit) {
cameraYaw -= dx * 0.007;
cameraPitch = THREE.MathUtils.clamp(cameraPitch + dy * 0.006, 0.28, 1.25);
updateCamera();
} else if (pointerDown.moved && pointerDown.button === 2) {
const right = new THREE.Vector3();
const up = new THREE.Vector3();
camera.matrixWorld.extractBasis(right, up, new THREE.Vector3());
cameraTarget.addScaledVector(right, -dx * 0.012 * cameraZoom);
cameraTarget.addScaledVector(up, dy * 0.012 * cameraZoom);
updateCamera();
}
pointerDown.lastX = event.clientX;
pointerDown.lastY = event.clientY;
}
hoverCell = getHoverCell(event);
updateGhost();
updateHoverTipPosition(event);
});
canvas.addEventListener("pointerup", event => {
if (!pointerDown) return;
const wasClick = !pointerDown.moved;
const wasRight = pointerDown.button === 2;
pointerDown = null;
if (!wasClick || wasRight) return;
const cargoHit = getCargoHit(event);
if (cargoHit) {
selectCargo(cargoHit);
return;
}
hoverCell = getHoverCell(event);
if (hoverCell) {
placeSelectedAt(hoverCell.x, hoverCell.y, hoverCell.z);
} else {
selectedId = null;
rebuildGhost(null);
updateManifest();
updateGhost();
}
});
canvas.addEventListener("pointerleave", () => {
if (!pointerDown) {
hoverCell = null;
updateGhost();
}
});
canvas.addEventListener("contextmenu", event => event.preventDefault());
canvas.addEventListener("wheel", event => {
event.preventDefault();
cameraZoom = THREE.MathUtils.clamp(
cameraZoom * Math.exp(event.deltaY * 0.001),
0.65,
1.75
);
resize();
}, { passive: false });
/* --------------------------------------------------------------------------
UI actions
-------------------------------------------------------------------------- */
document.querySelectorAll("[data-layer]").forEach(button => {
button.addEventListener("click", () => setLayer(Number(button.dataset.layer)));
});
rotateBtn.addEventListener("click", rotateSelected);
liftBtn.addEventListener("click", liftSelected);
hintBtn.addEventListener("click", () => {
if (animating || completed) return;
for (const cargo of cargos) {
removeCargoGroup(cargo);
cargo.done = false;
cargo.orientation = 0;
cargo.pos = [...solution[cargo.id]];
buildCargoGroup(cargo);
}
selectedId = null;
rebuildGhost(null);
clearPathLines();
resultPanelEl.hidden = true;
completionEl.hidden = true;
completed = false;
updateManifest();
updateGhost();
toast("Reference load plan restored. Change the arrangement to test a new route.");
});
clearBtn.addEventListener("click", () => {
if (animating) return;
for (const cargo of cargos) {
removeCargoGroup(cargo);
cargo.pos = null;
cargo.done = false;
}
selectedId = null;
selectedLayer = 0;
rebuildGhost(null);
clearPathLines();
resultPanelEl.hidden = true;
completionEl.hidden = true;
completed = false;
updateManifest();
updateGhost();
toast("Hold cleared. All modules returned to the manifest.");
});
checkBtn.addEventListener("click", () => {
if (animating || completed) return;
const plan = computeExtractionPlan();
showResult(plan);
drawPathLines(plan);
if (plan.valid) {
setStatus("Paths verified", "success");
toast("Every module has a collision-free route in unloading order.");
} else {
setStatus("Audit failed", "error");
toast(plan.errors[0] || "The current arrangement cannot be certified.", true);
}
});
runBtn.addEventListener("click", runUnload);
document.getElementById("closeResult").addEventListener("click", () => {
resultPanelEl.hidden = true;
});
window.addEventListener("keydown", event => {
if (event.target instanceof HTMLInputElement) return;
if (event.key.toLowerCase() === "r") {
rotateSelected();
} else if (event.key === "Delete" || event.key === "Backspace") {
event.preventDefault();
liftSelected();
} else if (["1", "2", "3", "4"].includes(event.key)) {
setLayer(Number(event.key) - 1);
} else if (event.key === "Escape") {
selectedId = null;
rebuildGhost(null);
updateManifest();
updateGhost();
}
});
/* --------------------------------------------------------------------------
Feedback and initialization
-------------------------------------------------------------------------- */
function setStatus(text, type = "normal") {
statusPillEl.textContent = text;
statusPillEl.classList.toggle("warning", type === "warning");
statusPillEl.classList.toggle("error", type === "error");
}
function toast(message, isError = false) {
clearTimeout(toastTimer);
toastEl.textContent = message;
toastEl.classList.toggle("error", isError);
toastEl.classList.add("show");
toastTimer = setTimeout(() => {
toastEl.classList.remove("show");
}, 3300);
}
const resizeObserver = new ResizeObserver(resize);
resizeObserver.observe(canvas);
buildManifest();
resize();
updateCamera();
renderer.setAnimationLoop(() => renderer.render(scene, camera));
toast("Select a module from the manifest, then click a hold cell.");
</script>
</body>
</html>
```