Prompt specification
Build or customize the Three.js 3D scene "Airship Cargo Loading Puzzle" 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: Airship Cargo Loading Puzzle
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/airship-cargo-loading-puzzle-x3475
Scene Description Prompt:
Pack oddly shaped crates into a fictional voxel airship, checking access, fit, and mass balance separately. Standalone HTML using Three.js from cdnjs.
Working Three.js Starter (airship-cargo-loading-puzzle-x3475):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Voxel Airship Cargo Planner</title>
<style>
:root {
--bg: #071019;
--panel: rgba(10, 20, 30, 0.91);
--panel-border: rgba(140, 195, 220, 0.18);
--text: #e7f2f7;
--muted: #8fa7b5;
--cyan: #65ddff;
--green: #61e6a1;
--amber: #ffc65a;
--red: #ff657a;
--line: rgba(150, 205, 225, 0.12);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
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;
}
#viewport {
position: fixed;
inset: 0;
}
#viewport canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
.topbar {
position: fixed;
z-index: 10;
top: 18px;
left: 22px;
right: 22px;
height: 58px;
display: flex;
align-items: center;
justify-content: space-between;
pointer-events: none;
}
.brand {
display: flex;
align-items: center;
gap: 13px;
pointer-events: auto;
}
.brand-mark {
width: 38px;
height: 38px;
display: grid;
place-items: center;
border: 1px solid rgba(101, 221, 255, 0.45);
background:
linear-gradient(135deg, rgba(101, 221, 255, 0.18), transparent),
rgba(5, 12, 18, 0.8);
box-shadow: 0 0 28px rgba(101, 221, 255, 0.1);
color: var(--cyan);
font-weight: 900;
letter-spacing: -2px;
}
.brand h1 {
margin: 0;
font-size: 15px;
line-height: 1.1;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.brand p {
margin: 5px 0 0;
color: var(--muted);
font: 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.top-actions {
display: flex;
gap: 8px;
pointer-events: auto;
}
.button {
border: 1px solid rgba(143, 191, 213, 0.24);
border-radius: 4px;
padding: 9px 12px;
color: #cfe3eb;
background: rgba(9, 19, 28, 0.84);
cursor: pointer;
transition:
border-color 160ms ease,
background 160ms ease,
transform 160ms ease;
font-size: 11px;
font-weight: 750;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.button:hover {
border-color: rgba(101, 221, 255, 0.65);
background: rgba(17, 38, 51, 0.92);
}
.button:active {
transform: translateY(1px);
}
.button.primary {
color: #06131b;
border-color: var(--cyan);
background: var(--cyan);
}
.button.primary:hover {
background: #8ceaff;
}
.button.danger:hover {
color: #fff;
border-color: var(--red);
background: rgba(117, 27, 45, 0.7);
}
.panel {
position: fixed;
z-index: 8;
top: 90px;
bottom: 22px;
width: 292px;
overflow: hidden;
border: 1px solid var(--panel-border);
border-radius: 7px;
background:
linear-gradient(160deg, rgba(25, 47, 60, 0.34), transparent 32%),
var(--panel);
box-shadow: 0 22px 70px rgba(0, 0, 0, 0.35);
backdrop-filter: blur(16px);
}
#manifest-panel {
left: 22px;
display: flex;
flex-direction: column;
}
#inspector-panel {
right: 22px;
width: 320px;
overflow-y: auto;
}
.panel-header {
padding: 16px 17px 14px;
border-bottom: 1px solid var(--line);
}
.eyebrow {
margin: 0 0 6px;
color: var(--cyan);
font: 10px/1.2 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.18em;
text-transform: uppercase;
}
.panel-header h2 {
margin: 0;
font-size: 17px;
font-weight: 760;
letter-spacing: 0.03em;
}
.panel-header .sub {
margin: 6px 0 0;
color: var(--muted);
font-size: 11px;
line-height: 1.45;
}
#manifest-list {
flex: 1;
overflow-y: auto;
padding: 9px;
}
.manifest-card {
position: relative;
display: grid;
grid-template-columns: 30px 1fr auto;
align-items: center;
gap: 10px;
margin-bottom: 7px;
padding: 11px 10px;
border: 1px solid transparent;
border-radius: 5px;
background: rgba(255, 255, 255, 0.025);
cursor: pointer;
transition: 150ms ease;
}
.manifest-card:hover {
background: rgba(101, 221, 255, 0.055);
}
.manifest-card.selected {
border-color: rgba(101, 221, 255, 0.48);
background: rgba(101, 221, 255, 0.08);
}
.crate-swatch {
width: 29px;
height: 29px;
display: grid;
place-items: center;
border: 1px solid rgba(255, 255, 255, 0.17);
color: #081018;
font: 800 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
clip-path: polygon(12% 0, 88% 0, 100% 22%, 100% 78%, 86% 100%, 14% 100%, 0 78%, 0 22%);
}
.manifest-card strong {
display: block;
font-size: 12px;
font-weight: 700;
}
.manifest-card small {
display: block;
margin-top: 4px;
color: var(--muted);
font: 9px/1.2 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.06em;
}
.status-pill {
min-width: 51px;
padding: 4px 6px;
border: 1px solid rgba(143, 167, 181, 0.23);
border-radius: 3px;
color: var(--muted);
text-align: center;
font: 8px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.08em;
}
.status-pill.good {
color: var(--green);
border-color: rgba(97, 230, 161, 0.32);
background: rgba(97, 230, 161, 0.06);
}
.status-pill.bad {
color: var(--red);
border-color: rgba(255, 101, 122, 0.35);
background: rgba(255, 101, 122, 0.06);
}
.status-pill.staged {
color: var(--amber);
border-color: rgba(255, 198, 90, 0.35);
background: rgba(255, 198, 90, 0.06);
}
.panel-footer {
display: grid;
gap: 8px;
padding: 13px;
border-top: 1px solid var(--line);
}
.panel-footer .button {
width: 100%;
}
.inspector-body {
padding: 15px;
}
.selected-crate {
display: grid;
grid-template-columns: 46px 1fr;
align-items: center;
gap: 12px;
margin-bottom: 14px;
}
.selected-crate .crate-swatch {
width: 46px;
height: 46px;
font-size: 13px;
}
.selected-crate h3 {
margin: 0 0 4px;
font-size: 16px;
}
.selected-crate p {
margin: 0;
color: var(--muted);
font: 10px/1.4 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.stat-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 7px;
margin-bottom: 14px;
}
.stat {
padding: 9px 8px;
border: 1px solid var(--line);
border-radius: 4px;
background: rgba(255, 255, 255, 0.025);
}
.stat span {
display: block;
color: var(--muted);
font: 8px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.stat strong {
display: block;
margin-top: 6px;
font: 700 12px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.section-label {
margin: 18px 0 8px;
color: var(--muted);
font: 9px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.15em;
text-transform: uppercase;
}
.check-card {
margin-bottom: 7px;
padding: 10px 11px;
border: 1px solid var(--line);
border-left-width: 3px;
border-radius: 4px;
background: rgba(255, 255, 255, 0.025);
}
.check-card.pass {
border-left-color: var(--green);
}
.check-card.fail {
border-left-color: var(--red);
}
.check-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.1em;
}
.check-heading em {
color: var(--green);
font: normal 800 9px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.check-card.fail .check-heading em {
color: var(--red);
}
.check-card p {
margin: 6px 0 0;
color: var(--muted);
font-size: 10px;
line-height: 1.42;
}
.axis-row {
display: grid;
grid-template-columns: 16px 1fr 34px 28px;
align-items: center;
gap: 6px;
margin-bottom: 6px;
}
.axis-row > span:first-child {
color: var(--cyan);
font: 800 11px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.axis-row > span:nth-child(3) {
color: #c8dce5;
text-align: right;
font: 11px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.nudge {
width: 28px;
height: 25px;
padding: 0;
border: 1px solid var(--line);
border-radius: 3px;
color: #d8e9ef;
background: rgba(255, 255, 255, 0.035);
cursor: pointer;
}
.nudge:hover {
border-color: var(--cyan);
}
.action-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 12px;
}
.action-row .button {
width: 100%;
}
.deploy {
width: 100%;
margin-top: 10px;
padding: 12px;
}
.hint {
margin: 11px 0 0;
color: #708a98;
font-size: 10px;
line-height: 1.5;
}
.bottom-strip {
position: fixed;
z-index: 7;
left: 50%;
bottom: 22px;
transform: translateX(-50%);
display: flex;
align-items: center;
gap: 18px;
padding: 10px 15px;
border: 1px solid var(--panel-border);
border-radius: 5px;
background: rgba(6, 14, 21, 0.78);
color: var(--muted);
backdrop-filter: blur(12px);
pointer-events: none;
font: 9px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.05em;
white-space: nowrap;
}
.legend-item {
display: flex;
align-items: center;
gap: 6px;
}
.legend-dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: currentColor;
box-shadow: 0 0 8px currentColor;
}
#toast {
position: fixed;
z-index: 30;
left: 50%;
top: 88px;
transform: translate(-50%, -12px);
max-width: 440px;
padding: 11px 16px;
border: 1px solid rgba(101, 221, 255, 0.35);
border-radius: 5px;
color: #dff8ff;
background: rgba(8, 23, 32, 0.95);
box-shadow: 0 12px 40px rgba(0, 0, 0, 0.4);
opacity: 0;
pointer-events: none;
transition: 180ms ease;
font-size: 11px;
text-align: center;
}
#toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
#toast.error {
color: #ffe0e5;
border-color: rgba(255, 101, 122, 0.55);
}
@media (max-width: 900px) {
.panel {
width: 250px;
}
#inspector-panel {
width: 270px;
}
.bottom-strip {
display: none;
}
.top-actions .button.optional {
display: none;
}
}
@media (max-width: 650px) {
.panel {
top: auto;
bottom: 12px;
width: calc(50vw - 16px);
height: 48vh;
}
#manifest-panel {
left: 12px;
}
#inspector-panel {
right: 12px;
}
.topbar {
top: 12px;
left: 12px;
right: 12px;
}
.brand p,
.top-actions .button:not(.primary) {
display: none;
}
}
</style>
</head>
<body>
<div id="viewport"></div>
<div class="topbar">
<div class="brand">
<div class="brand-mark">A</div>
<div>
<h1>Aerostat Cargo Planner</h1>
<p>Voxel vessel AS-09 · magnetic hold systems</p>
</div>
</div>
<div class="top-actions">
<button class="button optional" id="hull-button">Hull: cutaway</button>
<button class="button optional" id="top-button">Top view</button>
<button class="button" id="camera-button">Reset camera</button>
</div>
</div>
<aside class="panel" id="manifest-panel">
<div class="panel-header">
<p class="eyebrow">Cargo manifest</p>
<h2>Odd-form freight</h2>
<p class="sub">Select a crate, stage it on the deck, then deploy it.</p>
</div>
<div id="manifest-list"></div>
<div class="panel-footer">
<button class="button primary" id="autopack-button">Auto-pack hold</button>
<button class="button danger" id="clear-button">Clear hold</button>
</div>
</aside>
<aside class="panel" id="inspector-panel">
<div class="panel-header">
<p class="eyebrow">Loading inspector</p>
<h2>Independent validation</h2>
<p class="sub">
Fit, crew access, and mass balance are evaluated separately.
</p>
</div>
<div class="inspector-body">
<div class="selected-crate">
<div class="crate-swatch" id="selected-swatch">—</div>
<div>
<h3 id="selected-name">No crate selected</h3>
<p id="selected-code">Select cargo from the manifest</p>
</div>
</div>
<div class="stat-grid">
<div class="stat">
<span>Mass</span>
<strong id="stat-mass">—</strong>
</div>
<div class="stat">
<span>Voxels</span>
<strong id="stat-volume">—</strong>
</div>
<div class="stat">
<span>Footprint</span>
<strong id="stat-size">—</strong>
</div>
</div>
<div class="section-label">Validation</div>
<div class="check-card" id="fit-check">
<div class="check-heading">
<span>01 · PHYSICAL FIT</span>
<em>—</em>
</div>
<p>Waiting for a crate.</p>
</div>
<div class="check-card" id="access-check">
<div class="check-heading">
<span>02 · CREW ACCESS</span>
<em>—</em>
</div>
<p>Waiting for a crate.</p>
</div>
<div class="check-card" id="balance-check">
<div class="check-heading">
<span>03 · MASS BALANCE</span>
<em>—</em>
</div>
<p>Waiting for a crate.</p>
</div>
<div class="section-label">Deck coordinates</div>
<div class="axis-row">
<span>X</span>
<span></span>
<span id="pos-x">—</span>
<button class="nudge" data-axis="x" data-dir="-1">−</button>
<button class="nudge" data-axis="x" data-dir="1">+</button>
</div>
<div class="axis-row">
<span>Y</span>
<span></span>
<span id="pos-y">—</span>
<button class="nudge" data-axis="y" data-dir="-1">−</button>
<button class="nudge" data-axis="y" data-dir="1">+</button>
</div>
<div class="axis-row">
<span>Z</span>
<span></span>
<span id="pos-z">—</span>
<button class="nudge" data-axis="z" data-dir="-1">−</button>
<button class="nudge" data-axis="z" data-dir="1">+</button>
</div>
<div class="action-row">
<button class="button" id="rotate-button">Rotate 90°</button>
<button class="button" id="unload-button">Unload</button>
</div>
<button class="button primary deploy" id="deploy-button">Deploy crate</button>
<p class="hint">
Click the deck to stage a crate. Drag to orbit, right-drag to pan,
and use the wheel to zoom. Arrow keys nudge; R rotates; Enter deploys.
</p>
</div>
</aside>
<div class="bottom-strip">
<span class="legend-item" style="color: var(--green)">
<i class="legend-dot"></i> PASS
</span>
<span class="legend-item" style="color: var(--red)">
<i class="legend-dot"></i> CONFLICT
</span>
<span class="legend-item" style="color: var(--cyan)">
<i class="legend-dot"></i> CYAN BEACON = LOADED COM
</span>
<span>LEFT DRAG · ORBIT</span>
<span>RIGHT DRAG · PAN</span>
<span>WHEEL · ZOOM</span>
</div>
<div id="toast"></div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Configuration
// -------------------------------------------------------------------------
const BAY = {
x0: -5,
y0: -3,
z0: -2,
w: 11,
h: 6,
d: 5
};
BAY.x1 = BAY.x0 + BAY.w - 1;
BAY.y1 = BAY.y0 + BAY.h - 1;
BAY.z1 = BAY.z0 + BAY.d - 1;
const HATCH = {
x: BAY.x0,
y: BAY.y0,
z: Math.floor((BAY.z0 + BAY.z1) / 2)
};
const SHIP_MASS = 2100;
const SHIP_CENTER = new THREE.Vector3(0, -1, 0);
const BALANCE_TOLERANCE = {
x: 0.34,
y: 0.42,
z: 0.30
};
const COLORS = {
fit: 0x61e6a1,
access: 0x65ddff,
balance: 0xffc65a,
fail: 0xff657a
};
const cubeGeometry = new THREE.BoxGeometry(0.82, 0.82, 0.82);
const key = (x, y, z) => `${x},${y},${z}`;
function unionBoxes(boxes) {
const cells = new Set();
for (const [x0, x1, y0, y1, z0, z1] of boxes) {
for (let x = x0; x <= x1; x++) {
for (let y = y0; y <= y1; y++) {
for (let z = z0; z <= z1; z++) {
cells.add(key(x, y, z));
}
}
}
}
return [...cells].map((value) => value.split(",").map(Number));
}
const crateDefinitions = [
{
id: "A",
code: "AX-14 / GABLE",
name: "Gable Crate",
color: 0xe8aa4c,
mass: 396,
boxes: [
[0, 3, 0, 1, 0, 1],
[0, 1, 0, 1, 2, 2]
]
},
{
id: "B",
code: "BX-27 / HOOK",
name: "Hook Crate",
color: 0xd97962,
mass: 540,
boxes: [
[0, 3, 0, 2, 0, 1],
[0, 1, 0, 1, 2, 2]
]
},
{
id: "C",
code: "CX-03 / FORK",
name: "Fork Crate",
color: 0x7ac7bd,
mass: 720,
boxes: [
[0, 4, 0, 1, 0, 2],
[0, 1, 0, 2, 3, 4]
]
},
{
id: "D",
code: "DX-18 / CROS",
name: "Cross Crate",
color: 0x8f9dde,
mass: 576,
boxes: [
[0, 3, 0, 1, 0, 3],
[0, 1, 2, 3, 0, 1]
]
},
{
id: "E",
code: "EX-42 / DOGLEG",
name: "Dogleg Crate",
color: 0xbd87c8,
mass: 450,
boxes: [
[0, 2, 0, 2, 0, 1],
[2, 2, 0, 0, 1, 1],
[3, 4, 0, 1, 2, 3]
]
},
{
id: "F",
code: "FX-66 / CROWN",
name: "Crown Crate",
color: 0x64a8e8,
mass: 720,
boxes: [
[0, 3, 0, 2, 0, 1],
[1, 2, 0, 3, 2, 3],
[0, 1, 2, 3, 3, 4]
]
}
];
const crates = crateDefinitions.map((definition) => ({
...definition,
baseCells: unionBoxes(definition.boxes),
position: null,
orientation: 0,
group: null,
beacon: null
}));
let selectedId = crates[0].id;
let preview = null;
let autoPacking = false;
let hullCutaway = true;
// -------------------------------------------------------------------------
// Scene
// -------------------------------------------------------------------------
const viewport = document.querySelector("#viewport");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x071019);
scene.fog = new THREE.FogExp2(0x071019, 0.018);
const camera = new THREE.PerspectiveCamera(
46,
window.innerWidth / window.innerHeight,
0.1,
180
);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
viewport.appendChild(renderer.domElement);
const hemi = new THREE.HemisphereLight(0xaedfff, 0x17212a, 2.1);
scene.add(hemi);
const keyLight = new THREE.DirectionalLight(0xe5f6ff, 3.2);
keyLight.position.set(9, 15, 11);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -18;
keyLight.shadow.camera.right = 18;
keyLight.shadow.camera.top = 18;
keyLight.shadow.camera.bottom = -18;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 45;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x4ab8ff, 2.1);
rimLight.position.set(-12, 5, -9);
scene.add(rimLight);
const warmLight = new THREE.PointLight(0xffa64d, 40, 30, 2);
warmLight.position.set(0, -5, 8);
scene.add(warmLight);
const cameraState = {
target: new THREE.Vector3(0, -0.8, 0),
radius: 28,
theta: 0.72,
phi: 1.08
};
function updateCamera() {
const sinPhi = Math.sin(cameraState.phi);
camera.position.set(
cameraState.target.x +
cameraState.radius * sinPhi * Math.sin(cameraState.theta),
cameraState.target.y + cameraState.radius * Math.cos(cameraState.phi),
cameraState.target.z +
cameraState.radius * sinPhi * Math.cos(cameraState.theta)
);
camera.lookAt(cameraState.target);
}
function resetCamera() {
cameraState.target.set(0, -0.8, 0);
cameraState.radius = 28;
cameraState.theta = 0.72;
cameraState.phi = 1.08;
updateCamera();
}
updateCamera();
// -------------------------------------------------------------------------
// Voxel envelope
// -------------------------------------------------------------------------
const hullCells = new Set();
function insideEnvelope(x, y, z) {
const nx = x / 11.5;
const ny = y / 5.8;
const nz = z / 5.8;
return nx * nx + ny * ny + nz * nz <= 1;
}
for (let x = -11; x <= 11; x++) {
for (let y = -5; y <= 5; y++) {
for (let z = -5; z <= 5; z++) {
if (insideEnvelope(x, y, z)) {
hullCells.add(key(x, y, z));
}
}
}
}
const surfaceCells = [];
for (const cell of hullCells) {
const [x, y, z] = cell.split(",").map(Number);
const exposed =
!hullCells.has(key(x + 1, y, z)) ||
!hullCells.has(key(x - 1, y, z)) ||
!hullCells.has(key(x, y + 1, z)) ||
!hullCells.has(key(x, y - 1, z)) ||
!hullCells.has(key(x, y, z + 1)) ||
!hullCells.has(key(x, y, z - 1));
if (exposed) surfaceCells.push([x, y, z]);
}
const hullMaterial = new THREE.MeshStandardMaterial({
color: 0x6a9bad,
roughness: 0.62,
metalness: 0.18,
transparent: true,
opacity: 0.19,
depthWrite: false
});
const hull = new THREE.InstancedMesh(
new THREE.BoxGeometry(0.93, 0.93, 0.93),
hullMaterial,
surfaceCells.length
);
const instanceMatrix = new THREE.Matrix4();
const instanceColor = new THREE.Color();
surfaceCells.forEach(([x, y, z], index) => {
instanceMatrix.makeTranslation(x, y, z);
hull.setMatrixAt(index, instanceMatrix);
const variation = ((x * 17 + y * 11 + z * 5) % 7) / 7;
instanceColor.setHSL(0.54 + variation * 0.025, 0.28, 0.39 + variation * 0.08);
hull.setColorAt(index, instanceColor);
});
hull.instanceMatrix.needsUpdate = true;
if (hull.instanceColor) hull.instanceColor.needsUpdate = true;
hull.renderOrder = 1;
scene.add(hull);
// Brass ribs.
const ribMaterial = new THREE.LineBasicMaterial({
color: 0xd29a55,
transparent: true,
opacity: 0.68
});
for (const x of [-9, -5, -1, 3, 7, 10]) {
const points = [];
const radiusScale = Math.sqrt(Math.max(0.12, 1 - (x / 11.5) ** 2));
for (let index = 0; index <= 72; index++) {
const angle = (index / 72) * Math.PI * 2;
points.push(
new THREE.Vector3(
x,
Math.sin(angle) * 5.45 * radiusScale,
Math.cos(angle) * 5.45 * radiusScale
)
);
}
const geometry = new THREE.BufferGeometry().setFromPoints(points);
scene.add(new THREE.Line(geometry, ribMaterial));
}
// Gondola and keel.
const gondolaMaterial = new THREE.MeshStandardMaterial({
color: 0x263b48,
roughness: 0.7,
metalness: 0.42
});
const gondola = new THREE.Group();
for (let x = -5; x <= 4; x++) {
const beam = new THREE.Mesh(
new THREE.BoxGeometry(0.92, 0.58, 1.6),
gondolaMaterial
);
beam.position.set(x, -5.9, 0);
beam.castShadow = true;
gondola.add(beam);
}
const gondolaRail = new THREE.Mesh(
new THREE.BoxGeometry(9.2, 0.22, 2.1),
new THREE.MeshStandardMaterial({
color: 0xb98443,
roughness: 0.48,
metalness: 0.65
})
);
gondolaRail.position.set(-0.5, -6.25, 0);
gondola.add(gondolaRail);
scene.add(gondola);
// Side propellers.
const propellers = [];
const propellerMaterial = new THREE.MeshStandardMaterial({
color: 0xd6a153,
roughness: 0.35,
metalness: 0.75
});
for (const side of [-1, 1]) {
const propeller = new THREE.Group();
propeller.position.set(7.6, -0.4, side * 6.2);
const hub = new THREE.Mesh(
new THREE.CylinderGeometry(0.38, 0.38, 0.7, 10),
propellerMaterial
);
hub.rotation.x = Math.PI / 2;
propeller.add(hub);
for (let blade = 0; blade < 4; blade++) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(0.38, 3.4, 0.16),
propellerMaterial
);
mesh.position.y = 1.45;
mesh.rotation.z = (blade / 4) * Math.PI * 2;
propeller.add(mesh);
}
scene.add(propeller);
propellers.push(propeller);
}
// -------------------------------------------------------------------------
// Cargo bay frame and deck
// -------------------------------------------------------------------------
const bayGroup = new THREE.Group();
scene.add(bayGroup);
const bayWidth = BAY.w;
const bayHeight = BAY.h;
const bayDepth = BAY.d;
const bayBox = new THREE.BoxGeometry(bayWidth, bayHeight, bayDepth);
const bayEdges = new THREE.EdgesGeometry(bayBox);
const bayFrame = new THREE.LineSegments(
bayEdges,
new THREE.LineBasicMaterial({
color: 0x65ddff,
transparent: true,
opacity: 0.48
})
);
bayFrame.position.set(
BAY.x0 + bayWidth / 2,
BAY.y0 + bayHeight / 2,
BAY.z0 + bayDepth / 2
);
bayGroup.add(bayFrame);
const floorMaterial = new THREE.MeshStandardMaterial({
color: 0x102a36,
roughness: 0.76,
metalness: 0.34,
transparent: true,
opacity: 0.72
});
const floor = new THREE.Mesh(
new THREE.BoxGeometry(bayWidth, 0.08, bayDepth),
floorMaterial
);
floor.position.set(
BAY.x0 + bayWidth / 2,
BAY.y0 - 0.04,
BAY.z0 + bayDepth / 2
);
floor.receiveShadow = true;
bayGroup.add(floor);
const gridVertices = [];
for (let x = BAY.x0; x <= BAY.x1 + 1; x++) {
gridVertices.push(
x,
BAY.y0 + 0.015,
BAY.z0,
x,
BAY.y0 + 0.015,
BAY.z1 + 1
);
}
for (let z = BAY.z0; z <= BAY.z1 + 1; z++) {
gridVertices.push(
BAY.x0,
BAY.y0 + 0.015,
z,
BAY.x1 + 1,
BAY.y0 + 0.015,
z
);
}
const gridGeometry = new THREE.BufferGeometry();
gridGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(gridVertices, 3)
);
const deckGrid = new THREE.LineSegments(
gridGeometry,
new THREE.LineBasicMaterial({
color: 0x43879a,
transparent: true,
opacity: 0.34
})
);
bayGroup.add(deckGrid);
// Loading hatch marker.
const hatchMaterial = new THREE.MeshStandardMaterial({
color: 0xf4c657,
emissive: 0x8b5a12,
emissiveIntensity: 0.45,
roughness: 0.5,
metalness: 0.4
});
for (let y = 0; y < 3; y++) {
const block = new THREE.Mesh(
new THREE.BoxGeometry(0.22, 0.72, 2.2 - y * 0.35),
hatchMaterial
);
block.position.set(BAY.x0 - 0.12, BAY.y0 + y * 0.72, HATCH.z);
block.castShadow = true;
bayGroup.add(block);
}
// -------------------------------------------------------------------------
// Crate geometry helpers
// -------------------------------------------------------------------------
function cellsForOrientation(crate, orientation) {
let cells = crate.baseCells.map(([x, y, z]) => [x, y, z]);
for (let turn = 0; turn < orientation; turn++) {
cells = cells.map(([x, y, z]) => [z, y, -x]);
}
const minX = Math.min(...cells.map((cell) => cell[0]));
const minY = Math.min(...cells.map((cell) => cell[1]));
const minZ = Math.min(...cells.map((cell) => cell[2]));
cells = cells.map(([x, y, z]) => [
x - minX,
y - minY,
z - minZ
]);
const dims = {
x: Math.max(...cells.map((cell) => cell[0])) + 1,
y: Math.max(...cells.map((cell) => cell[1])) + 1,
z: Math.max(...cells.map((cell) => cell[2])) + 1
};
return { cells, dims };
}
function globalCells(crate, position, orientation) {
const rotated = cellsForOrientation(crate, orientation);
return {
...rotated,
cells: rotated.cells.map(([x, y, z]) => [
x + position.x,
y + position.y,
z + position.z
])
};
}
function createCrateGroup(crate, position, orientation) {
const group = new THREE.Group();
group.userData.crateId = crate.id;
const rotated = cellsForOrientation(crate, orientation);
const baseColor = new THREE.Color(crate.color);
for (const [x, y, z] of rotated.cells) {
const shade =
0.78 + ((x * 7 + y * 13 + z * 3 + crate.id.charCodeAt(0)) % 5) * 0.075;
const material = new THREE.MeshStandardMaterial({
color: baseColor.clone().multiplyScalar(shade),
roughness: 0.64,
metalness: 0.2
});
const voxel = new THREE.Mesh(cubeGeometry, material);
voxel.position.set(x + 0.5, y + 0.5, z + 0.5);
voxel.castShadow = true;
voxel.receiveShadow = true;
voxel.userData.crateId = crate.id;
group.add(voxel);
}
const beacon = new THREE.Mesh(
new THREE.BoxGeometry(0.17, 0.17, 0.17),
new THREE.MeshBasicMaterial({ color: COLORS.fit })
);
beacon.position.set(
rotated.dims.x / 2,
rotated.dims.y + 0.22,
rotated.dims.z / 2
);
beacon.userData.crateId = crate.id;
group.add(beacon);
crate.beacon = beacon;
group.position.set(position.x, position.y, position.z);
return group;
}
function rebuildCrate(crate) {
if (crate.group) {
scene.remove(crate.group);
crate.group.traverse((object) => {
if (object.isMesh && object.material && object.material !== cubeGeometry.material) {
object.material.dispose();
}
});
crate.group = null;
}
if (!crate.position) return;
crate.group = createCrateGroup(crate, crate.position, crate.orientation);
scene.add(crate.group);
}
const selectionOutline = new THREE.LineSegments(
new THREE.EdgesGeometry(new THREE.BoxGeometry(1, 1, 1)),
new THREE.LineBasicMaterial({
color: 0xffe29a,
transparent: true,
opacity: 0.9
})
);
selectionOutline.visible = false;
scene.add(selectionOutline);
const ghostGroup = new THREE.Group();
ghostGroup.visible = false;
scene.add(ghostGroup);
const ghostMaterial = new THREE.MeshBasicMaterial({
color: COLORS.fit,
transparent: true,
opacity: 0.3,
depthWrite: false,
depthTest: false
});
function rebuildGhost() {
while (ghostGroup.children.length) {
ghostGroup.remove(ghostGroup.children[0]);
}
if (!preview) return;
const crate = crates.find((item) => item.id === selectedId);
const rotated = cellsForOrientation(crate, preview.orientation);
for (const [x, y, z] of rotated.cells) {
const voxel = new THREE.Mesh(cubeGeometry, ghostMaterial);
voxel.position.set(x + 0.5, y + 0.5, z + 0.5);
ghostGroup.add(voxel);
}
ghostGroup.position.set(preview.position.x, preview.position.y, preview.position.z);
ghostGroup.renderOrder = 10;
}
// -------------------------------------------------------------------------
// Placement and validation
// -------------------------------------------------------------------------
function currentPlacements(excludeId = null) {
return crates
.filter((crate) => crate.position && crate.id !== excludeId)
.map((crate) => ({
crate,
position: { ...crate.position },
orientation: crate.orientation
}));
}
function assessFit(crate, position, orientation, otherPlacements) {
const shape = globalCells(crate, position, orientation);
const occupied = new Map();
for (const placement of otherPlacements) {
const placementShape = globalCells(
placement.crate,
placement.position,
placement.orientation
);
for (const [x, y, z] of placementShape.cells) {
occupied.set(key(x, y, z), placement.crate);
}
}
for (const [x, y, z] of shape.cells) {
if (
x < BAY.x0 ||
x > BAY.x1 ||
y < BAY.y0 ||
y > BAY.y1 ||
z < BAY.z0 ||
z > BAY.z1
) {
return {
pass: false,
message: "Crate exceeds the cargo-hold envelope.",
detail: `${shape.dims.x}×${shape.dims.y}×${shape.dims.z} footprint`
};
}
if (
!insideEnvelope(x + 0.5, y + 0.5, z + 0.5) &&
Math.abs(x + 0.5) < 6
) {
return {
pass: false,
message: "Crate intersects the pressure hull.",
detail: `${shape.dims.x}×${shape.dims.y}×${shape.dims.z} footprint`
};
}
if (x === HATCH.x && y === HATCH.y && z === HATCH.z) {
return {
pass: false,
message: "Crate blocks the aft loading hatch.",
detail: "The hatch cell must remain clear"
};
}
const collision = occupied.get(key(x, y, z));
if (collision) {
return {
pass: false,
message: `Voxel overlap with ${collision.name}.`,
detail: `Conflict at ${x}, ${y}, ${z}`
};
}
}
return {
pass: true,
message: "Crate fits inside the hold without collisions.",
detail: `${shape.cells.length} voxels · ${shape.dims.x}×${shape.dims.y}×${shape.dims.z}`
};
}
function assessAccess(placements) {
const occupied = new Map();
for (const placement of placements) {
const shape = globalCells(
placement.crate,
placement.position,
placement.orientation
);
for (const [x, y, z] of shape.cells) {
occupied.set(key(x, y, z), placement.crate.id);
}
}
const source = key(HATCH.x, HATCH.y, HATCH.z);
if (occupied.has(source)) {
return {
pass: false,
message: "The loading hatch is obstructed.",
detail: "No access path can begin"
};
}
const reachable = new Set([source]);
const queue = [{ x: HATCH.x, y: HATCH.y, z: HATCH.z }];
const directions = [
[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();
for (const [dx, dy, dz] of directions) {
const x = current.x + dx;
const y = current.y + dy;
const z = current.z + dz;
if (
x < BAY.x0 ||
x > BAY.x1 ||
y < BAY.y0 ||
y > BAY.y1 ||
z < BAY.z0 ||
z > BAY.z1
) {
continue;
}
const cellKey = key(x, y, z);
if (!occupied.has(cellKey) && !reachable.has(cellKey)) {
reachable.add(cellKey);
queue.push({ x, y, z });
}
}
}
const inaccessible = [];
for (const placement of placements) {
const shape = globalCells(
placement.crate,
placement.position,
placement.orientation
);
let accessible = false;
for (const [x, y, z] of shape.cells) {
for (const [dx, dy, dz] of directions) {
if (
reachable.has(key(x + dx, y + dy, z + dz)) &&
!occupied.has(key(x + dx, y + dy, z + dz))
) {
accessible = true;
break;
}
}
if (accessible) break;
}
if (!accessible) inaccessible.push(placement.crate.name);
}
if (inaccessible.length) {
return {
pass: false,
message: `${inaccessible.join(", ")} cannot be reached from the hatch.`,
detail: `${inaccessible.length} crate(s) blocked by cargo`
};
}
return {
pass: true,
message: "Every crate has a reachable service face.",
detail: `${placements.length} crates checked from aft hatch`
};
}
function cargoCenterOfMass(placements) {
if (!placements.length) {
return {
center: new THREE.Vector3(),
mass: 0
};
}
const weighted = new THREE.Vector3();
let totalMass = 0;
for (const placement of placements) {
const shape = globalCells(
placement.crate,
placement.position,
placement.orientation
);
const local = new THREE.Vector3();
for (const [x, y, z] of shape.cells) {
local.x += x + 0.5;
local.y += y + 0.5;
local.z += z + 0.5;
}
local.multiplyScalar(1 / shape.cells.length);
local.add(new THREE.Vector3(
placement.position.x,
placement.position.y,
placement.position.z
));
weighted.addScaledVector(local, placement.crate.mass);
totalMass += placement.crate.mass;
}
return {
center: weighted.multiplyScalar(1 / totalMass),
mass: totalMass
};
}
function assessBalance(placements) {
const cargo = cargoCenterOfMass(placements);
const totalMass = SHIP_MASS + cargo.mass;
const loadedCenter = SHIP_CENTER
.clone()
.multiplyScalar(SHIP_MASS)
.addScaledVector(cargo.center, cargo.mass)
.multiplyScalar(1 / totalMass);
const offset = {
x: loadedCenter.x - SHIP_CENTER.x,
y: loadedCenter.y - SHIP_CENTER.y,
z: loadedCenter.z - SHIP_CENTER.z
};
const failedAxes = [];
if (Math.abs(offset.x) > BALANCE_TOLERANCE.x) failedAxes.push("X");
if (Math.abs(offset.y) > BALANCE_TOLERANCE.y) failedAxes.push("Y");
if (Math.abs(offset.z) > BALANCE_TOLERANCE.z) failedAxes.push("Z");
return {
pass: failedAxes.length === 0,
offset,
loadedCenter,
cargoCenter: cargo.center,
cargoMass: cargo.mass,
message:
failedAxes.length === 0
? "Loaded center of mass is inside the trim envelope."
: `${failedAxes.join(" / ")} trim exceeds the permitted envelope.`,
detail: `Δ ${offset.x.toFixed(2)}, ${offset.y.toFixed(2)}, ${offset.z.toFixed(2)} m`
};
}
function evaluateCandidate(crate, position, orientation, otherPlacements) {
const candidate = {
crate,
position: { ...position },
orientation
};
const placements = [...otherPlacements, candidate];
return {
fit: assessFit(crate, position, orientation, otherPlacements),
access: assessAccess(placements),
balance: assessBalance(placements),
placements
};
}
function selectedEvaluation() {
const crate = crates.find((item) => item.id === selectedId);
if (!crate || !preview) return null;
return evaluateCandidate(
crate,
preview.position,
preview.orientation,
currentPlacements(crate.id)
);
}
// -------------------------------------------------------------------------
// Center-of-mass visualization
// -------------------------------------------------------------------------
const comMarker = new THREE.Mesh(
new THREE.SphereGeometry(0.18, 16, 16),
new THREE.MeshBasicMaterial({ color: COLORS.access })
);
scene.add(comMarker);
const cargoComMarker = new THREE.Mesh(
new THREE.SphereGeometry(0.11, 12, 12),
new THREE.MeshBasicMaterial({ color: COLORS.balance })
);
scene.add(cargoComMarker);
const comLine = new THREE.Line(
new THREE.BufferGeometry().setFromPoints([
SHIP_CENTER.clone(),
SHIP_CENTER.clone()
]),
new THREE.LineBasicMaterial({
color: COLORS.access,
transparent: true,
opacity: 0.85
})
);
scene.add(comLine);
const toleranceBox = new THREE.LineSegments(
new THREE.EdgesGeometry(
new THREE.BoxGeometry(
BALANCE_TOLERANCE.x * 2,
BALANCE_TOLERANCE.y * 2,
BALANCE_TOLERANCE.z * 2
)
),
new THREE.LineBasicMaterial({
color: COLORS.fit,
transparent: true,
opacity: 0.28
})
);
toleranceBox.position.copy(SHIP_CENTER);
scene.add(toleranceBox);
function updateBalanceVisuals(placements) {
const balance = assessBalance(placements);
comMarker.position.copy(balance.loadedCenter);
cargoComMarker.position.copy(balance.cargoCenter);
cargoComMarker.visible = placements.length > 0;
comLine.geometry.setFromPoints([
SHIP_CENTER.clone(),
balance.loadedCenter.clone()
]);
toleranceBox.visible = placements.length > 0;
}
// -------------------------------------------------------------------------
// UI
// -------------------------------------------------------------------------
const manifestList = document.querySelector("#manifest-list");
const toast = document.querySelector("#toast");
let toastTimer;
function showToast(message, isError = false) {
toast.textContent = message;
toast.classList.toggle("error", isError);
toast.classList.add("show");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => {
toast.classList.remove("show");
}, 2600);
}
function colorHex(color) {
return `#${new THREE.Color(color).getHexString()}`;
}
function crateStatus(crate) {
if (!crate.position) {
return { label: "UNPACKED", className: "" };
}
const evaluation = evaluateCandidate(
crate,
crate.position,
crate.orientation,
currentPlacements(crate.id)
);
if (!evaluation.fit.pass || !evaluation.access.pass || !evaluation.balance.pass) {
return { label: "CONFLICT", className: "bad" };
}
return { label: "STOWED", className: "good" };
}
function renderManifest() {
manifestList.innerHTML = crates
.map((crate) => {
const status = crateStatus(crate);
const selected = crate.id === selectedId ? " selected" : "";
return `
<div class="manifest-card${selected}" data-crate-id="${crate.id}">
<div class="crate-swatch" style="background:${colorHex(crate.color)}">
${crate.id}
</div>
<div>
<strong>${crate.name}</strong>
<small>${crate.code}</small>
</div>
<div class="status-pill ${status.className}">${status.label}</div>
</div>
`;
})
.join("");
}
function setCheck(element, result) {
element.classList.toggle("pass", result.pass);
element.classList.toggle("fail", !result.pass);
element.querySelector("em").textContent = result.pass ? "PASS" : "FAIL";
element.querySelector("p").textContent = `${result.message} ${result.detail || ""}`.trim();
}
function renderInspector() {
const crate = crates.find((item) => item.id === selectedId);
const evaluation = selectedEvaluation();
if (!crate) return;
document.querySelector("#selected-swatch").textContent = crate.id;
document.querySelector("#selected-swatch").style.background = colorHex(crate.color);
document.querySelector("#selected-name").textContent = crate.name;
document.querySelector("#selected-code").textContent = crate.code;
document.querySelector("#stat-mass").textContent = `${crate.mass} kg`;
document.querySelector("#stat-volume").textContent = `${crate.baseCells.length}`;
const shape = cellsForOrientation(crate, preview?.orientation ?? crate.orientation);
document.querySelector("#stat-size").textContent =
`${shape.dims.x}×${shape.dims.y}×${shape.dims.z}`;
if (evaluation) {
setCheck(document.querySelector("#fit-check"), evaluation.fit);
setCheck(document.querySelector("#access-check"), evaluation.access);
setCheck(document.querySelector("#balance-check"), evaluation.balance);
}
document.querySelector("#pos-x").textContent = preview?.position.x ?? "—";
document.querySelector("#pos-y").textContent = preview?.position.y ?? "—";
document.querySelector("#pos-z").textContent = preview?.position.z ?? "—";
const deployButton = document.querySelector("#deploy-button");
deployButton.disabled = !evaluation?.fit.pass;
deployButton.textContent = crate.position
? preview?.dirty
? "Commit move"
: "Crate deployed"
: "Deploy crate";
document.querySelector("#unload-button").disabled = !crate.position;
}
function updateSelectionOutline() {
const crate = crates.find((item) => item.id === selectedId);
if (!crate || !crate.position) {
selectionOutline.visible = false;
return;
}
const shape = cellsForOrientation(crate, crate.orientation);
selectionOutline.geometry.dispose();
selectionOutline.geometry = new THREE.EdgesGeometry(
new THREE.BoxGeometry(
shape.dims.x + 0.12,
shape.dims.y + 0.12,
shape.dims.z + 0.12
)
);
selectionOutline.position.set(
crate.position.x + shape.dims.x / 2,
crate.position.y + shape.dims.y / 2,
crate.position.z + shape.dims.z / 2
);
selectionOutline.visible = true;
}
function updateUI() {
renderManifest();
renderInspector();
updateSelectionOutline();
updateBalanceVisuals(currentPlacements());
}
function defaultPreview(crate) {
const shape = cellsForOrientation(crate, crate.orientation);
const x = Math.floor((BAY.x0 + BAY.x1 - shape.dims.x + 1) / 2);
const z = Math.floor((BAY.z0 + BAY.z1 - shape.dims.z + 1) / 2);
return {
position: {
x: crate.position?.x ?? x,
y: crate.position?.y ?? BAY.y0,
z: crate.position?.z ?? z
},
orientation: crate.orientation,
dirty: false
};
}
function selectCrate(id) {
const crate = crates.find((item) => item.id === id);
if (!crate) return;
selectedId = id;
preview = defaultPreview(crate);
ghostGroup.visible = false;
rebuildGhost();
updateUI();
}
function stagePreview() {
preview.dirty = true;
rebuildGhost();
ghostGroup.visible = true;
const evaluation = selectedEvaluation();
if (evaluation) {
ghostMaterial.color.setHex(
evaluation.fit.pass ? COLORS.fit : COLORS.fail
);
}
updateUI();
}
function clampPreviewToBay() {
const crate = crates.find((item) => item.id === selectedId);
const shape = cellsForOrientation(crate, preview.orientation);
preview.position.x = THREE.MathUtils.clamp(
preview.position.x,
BAY.x0,
BAY.x1 - shape.dims.x + 1
);
preview.position.y = THREE.MathUtils.clamp(
preview.position.y,
BAY.y0,
BAY.y1 - shape.dims.y + 1
);
preview.position.z = THREE.MathUtils.clamp(
preview.position.z,
BAY.z0,
BAY.z1 - shape.dims.z + 1
);
}
function deploySelected() {
const crate = crates.find((item) => item.id === selectedId);
if (!crate || !preview) return;
clampPreviewToBay();
const evaluation = selectedEvaluation();
if (!evaluation.fit.pass) {
showToast(evaluation.fit.message, true);
return;
}
crate.position = { ...preview.position };
crate.orientation = preview.orientation;
preview.dirty = false;
rebuildCrate(crate);
ghostGroup.visible = false;
updateUI();
if (!evaluation.access.pass || !evaluation.balance.pass) {
showToast(
`Crate deployed with independent warnings: ${
!evaluation.access.pass ? evaluation.access.message : evaluation.balance.message
}`,
true
);
} else {
showToast(`${crate.name} deployed. Fit, access, and balance all pass.`);
}
}
function unloadSelected() {
const crate = crates.find((item) => item.id === selectedId);
if (!crate) return;
crate.position = null;
crate.orientation = 0;
preview = defaultPreview(crate);
rebuildCrate(crate);
ghostGroup.visible = false;
updateUI();
showToast(`${crate.name} returned to the loading dock.`);
}
function clearHold(silent = false) {
for (const crate of crates) {
crate.position = null;
crate.orientation = 0;
rebuildCrate(crate);
}
selectedId = crates[0].id;
preview = defaultPreview(crates[0]);
ghostGroup.visible = false;
updateUI();
if (!silent) showToast("Cargo hold cleared.");
}
// -------------------------------------------------------------------------
// Automatic packing
// -------------------------------------------------------------------------
function manhattanDistance(a, b) {
return (
Math.abs(a[0] - b[0]) +
Math.abs(a[1] - b[1]) +
Math.abs(a[2] - b[2])
);
}
function findBestPlacement(crate, existingPlacements) {
let best = null;
for (let orientation = 0; orientation < 4; orientation++) {
const shape = cellsForOrientation(crate, orientation);
for (
let x = BAY.x0;
x <= BAY.x1 - shape.dims.x + 1;
x++
) {
for (
let y = BAY.y0;
y <= BAY.y1 - shape.dims.y + 1;
y++
) {
for (
let z = BAY.z0;
z <= BAY.z1 - shape.dims.z + 1;
z++
) {
const position = { x, y, z };
const fit = assessFit(
crate,
position,
orientation,
existingPlacements
);
if (!fit.pass) continue;
const evaluation = evaluateCandidate(
crate,
position,
orientation,
existingPlacements
);
const candidateShape = globalCells(
crate,
position,
orientation
);
const candidateCenter = new THREE.Vector3();
for (const cell of candidateShape.cells) {
candidateCenter.x += cell[0] + 0.5;
candidateCenter.y += cell[1] + 0.5;
candidateCenter.z += cell[2] + 0.5;
}
candidateCenter.multiplyScalar(1 / candidateShape.cells.length);
const existingCells = [];
for (const placement of existingPlacements) {
const existingShape = globalCells(
placement.crate,
placement.position,
placement.orientation
);
existingCells.push(...existingShape.cells);
}
let nearestDistance = 100;
if (existingCells.length) {
for (const cell of candidateShape.cells) {
let nearest = Infinity;
for (const existingCell of existingCells) {
nearest = Math.min(
nearest,
manhattanDistance(cell, existingCell)
);
}
nearestDistance = Math.min(nearestDistance, nearest);
}
}
const cargo = cargoCenterOfMass(existingPlacements);
const desiredCenter = new THREE.Vector3();
if (cargo.mass > 0) {
desiredCenter.set(
THREE.MathUtils.clamp(
SHIP_CENTER.x +
(SHIP_CENTER.x - cargo.center.x) * cargo.mass / crate.mass,
-2.8,
2.8
),
THREE.MathUtils.clamp(
SHIP_CENTER.y +
(SHIP_CENTER.y - cargo.center.y) * cargo.mass / crate.mass,
-2.8,
2.0
),
THREE.MathUtils.clamp(
SHIP_CENTER.z +
(SHIP_CENTER.z - cargo.center.z) * cargo.mass / crate.mass,
-2.0,
2.0
)
);
} else {
desiredCenter.set(0, -0.7, 0);
}
const correctionPenalty =
candidateCenter.distanceTo(desiredCenter) ** 2;
const balancePenalty =
Math.abs(evaluation.balance.offset.x) / BALANCE_TOLERANCE.x +
Math.abs(evaluation.balance.offset.y) / BALANCE_TOLERANCE.y +
Math.abs(evaluation.balance.offset.z) / BALANCE_TOLERANCE.z;
const contactPenalty = existingCells.length
? Math.abs(nearestDistance - 1) * 0.18
: 0;
const floorPenalty = (y - BAY.y0) * 0.16;
let score =
correctionPenalty * 4 +
balancePenalty * 18 +
contactPenalty +
floorPenalty;
if (!evaluation.access.pass) score += 6000;
if (!evaluation.balance.pass) score += 2500;
if (!best || score < best.score) {
best = {
score,
position,
orientation,
evaluation
};
}
}
}
}
}
return best;
}
async function autoPack() {
if (autoPacking) return;
autoPacking = true;
const button = document.querySelector("#autopack-button");
button.disabled = true;
button.textContent = "Packing…";
clearHold(true);
const order = ["C", "F", "B", "D", "A", "E"];
for (const id of order) {
const crate = crates.find((item) => item.id === id);
const existing = currentPlacements();
const best = findBestPlacement(crate, existing);
if (!best) {
showToast(`No legal position found for ${crate.name}.`, true);
continue;
}
crate.position = { ...best.position };
crate.orientation = best.orientation;
rebuildCrate(crate);
updateUI();
await new Promise((resolve) => setTimeout(resolve, 90));
}
selectedId = crates[0].id;
preview = defaultPreview(crates[0]);
updateUI();
const finalEvaluation = evaluateCandidate(
crates[0],
crates[0].position,
crates[0].orientation,
currentPlacements(crates[0].id)
);
const accessPass = finalEvaluation.access.pass;
const balancePass = finalEvaluation.balance.pass;
button.disabled = false;
button.textContent = "Auto-pack hold";
autoPacking = false;
showToast(
accessPass && balancePass
? "Hold packed. Physical fit, crew access, and mass balance all pass."
: "Hold packed, but one or more independent checks need attention.",
!(accessPass && balancePass)
);
}
// -------------------------------------------------------------------------
// Pointer interaction and camera controls
// -------------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointerNdc = new THREE.Vector2();
const deckPlane = new THREE.Plane(
new THREE.Vector3(0, 1, 0),
-BAY.y0
);
const deckHit = new THREE.Vector3();
const pointers = new Map();
let dragState = null;
function pointerToNdc(event) {
const rect = renderer.domElement.getBoundingClientRect();
pointerNdc.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointerNdc.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
}
function pickCrate(event) {
pointerToNdc(event);
raycaster.setFromCamera(pointerNdc, camera);
const visibleGroups = crates
.filter((crate) => crate.group)
.map((crate) => crate.group);
const hits = raycaster.intersectObjects(visibleGroups, true);
if (hits.length) {
const crateId = hits[0].object.userData.crateId;
if (crateId) {
selectCrate(crateId);
return true;
}
}
return false;
}
function stageAtPointer(event) {
if (!preview) return;
pointerToNdc(event);
raycaster.setFromCamera(pointerNdc, camera);
if (raycaster.ray.intersectPlane(deckPlane, deckHit)) {
preview.position.x = Math.floor(deckHit.x);
preview.position.z = Math.floor(deckHit.z);
clampPreviewToBay();
stagePreview();
}
}
function pointerDistance() {
if (!dragState?.start) return 0;
const dx = event.clientX - dragState.start.x;
const dy = event.clientY - dragState.start.y;
return Math.hypot(dx, dy);
}
renderer.domElement.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
renderer.domElement.addEventListener("pointerdown", (event) => {
renderer.domElement.setPointerCapture(event.pointerId);
pointers.set(event.pointerId, { x: event.clientX, y: event.clientY });
if (pointers.size === 1) {
dragState = {
mode: event.button === 2 ? "pan" : "orbit",
lastX: event.clientX,
lastY: event.clientY,
start: { x: event.clientX, y: event.clientY },
moved: false
};
} else if (pointers.size === 2) {
const values = [...pointers.values()];
dragState = {
mode: "pinch",
distance:
Math.hypot(values[0].x - values[1].x, values[0].y - values[1].y),
start: { x: event.clientX, y: event.clientY },
moved: true
};
}
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!pointers.has(event.pointerId)) return;
pointers.set(event.pointerId, { x: event.clientX, y: event.clientY });
if (!dragState) return;
if (dragState.mode === "orbit") {
const dx = event.clientX - dragState.lastX;
const dy = event.clientY - dragState.lastY;
cameraState.theta -= dx * 0.006;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi - dy * 0.006,
0.08,
Math.PI - 0.08
);
dragState.lastX = event.clientX;
dragState.lastY = event.clientY;
if (pointerDistance() > 4) dragState.moved = true;
} else if (dragState.mode === "pan") {
const dx = event.clientX - dragState.lastX;
const dy = event.clientY - dragState.lastY;
const forward = new THREE.Vector3();
camera.getWorldDirection(forward);
const right = new THREE.Vector3()
.crossVectors(forward, camera.up)
.normalize();
const up = new THREE.Vector3()
.crossVectors(right, forward)
.normalize();
const scale = cameraState.radius * 0.0016;
cameraState.target.addScaledVector(right, -dx * scale);
cameraState.target.addScaledVector(up, dy * scale);
dragState.lastX = event.clientX;
dragState.lastY = event.clientY;
if (pointerDistance() > 4) dragState.moved = true;
} else if (dragState.mode === "pinch" && pointers.size === 2) {
const values = [...pointers.values()];
const distance = Math.hypot(
values[0].x - values[1].x,
values[0].y - values[1].y
);
if (dragState.distance > 0) {
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * (dragState.distance / distance),
11,
48
);
}
dragState.distance = distance;
}
updateCamera();
});
renderer.domElement.addEventListener("pointerup", (event) => {
const wasClick =
event.pointerType === "mouse" &&
event.button === 0 &&
dragState?.mode === "orbit" &&
!dragState.moved &&
pointerDistance() < 6;
pointers.delete(event.pointerId);
if (wasClick) {
if (!pickCrate(event)) stageAtPointer(event);
}
if (pointers.size === 0) {
dragState = null;
} else if (pointers.size === 1) {
const [pointer] = pointers.values();
dragState = {
mode: "orbit",
lastX: pointer.x,
lastY: pointer.y,
start: { x: pointer.x, y: pointer.y },
moved: true
};
}
});
renderer.domElement.addEventListener("pointercancel", (event) => {
pointers.delete(event.pointerId);
if (!pointers.size) dragState = null;
});
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
11,
48
);
updateCamera();
},
{ passive: false }
);
// -------------------------------------------------------------------------
// UI events
// -------------------------------------------------------------------------
manifestList.addEventListener("click", (event) => {
const card = event.target.closest("[data-crate-id]");
if (card) selectCrate(card.dataset.crateId);
});
document.querySelector("#autopack-button").addEventListener("click", autoPack);
document.querySelector("#clear-button").addEventListener("click", () => clearHold());
document.querySelector("#deploy-button").addEventListener("click", deploySelected);
document.querySelector("#unload-button").addEventListener("click", unloadSelected);
document.querySelector("#rotate-button").addEventListener("click", () => {
if (!preview) return;
preview.orientation = (preview.orientation + 1) % 4;
const crate = crates.find((item) => item.id === selectedId);
const shape = cellsForOrientation(crate, preview.orientation);
if (!crate.position) {
preview.position.x = Math.floor(
(BAY.x0 + BAY.x1 - shape.dims.x + 1) / 2
);
preview.position.z = Math.floor(
(BAY.z0 + BAY.z1 - shape.dims.z + 1) / 2
);
}
clampPreviewToBay();
stagePreview();
});
document.querySelectorAll(".nudge").forEach((button) => {
button.addEventListener("click", () => {
if (!preview) return;
const axis = button.dataset.axis;
const direction = Number(button.dataset.dir);
preview.position[axis] += direction;
clampPreviewToBay();
stagePreview();
});
});
document.querySelector("#camera-button").addEventListener("click", resetCamera);
document.querySelector("#top-button").addEventListener("click", () => {
cameraState.target.set(0, -0.8, 0);
cameraState.radius = 25;
cameraState.theta = 0;
cameraState.phi = 0.08;
updateCamera();
});
document.querySelector("#hull-button").addEventListener("click", (event) => {
hullCutaway = !hullCutaway;
hullMaterial.opacity = hullCutaway ? 0.08 : 0.24;
event.currentTarget.textContent = hullCutaway
? "Hull: cutaway"
: "Hull: solid";
});
window.addEventListener("keydown", (event) => {
if (!preview || event.target.tagName === "INPUT") return;
const key = event.key.toLowerCase();
if (key === "r") {
document.querySelector("#rotate-button").click();
} else if (key === "enter") {
deploySelected();
} else if (key === "arrowleft") {
event.preventDefault();
preview.position.x -= 1;
clampPreviewToBay();
stagePreview();
} else if (key === "arrowright") {
event.preventDefault();
preview.position.x += 1;
clampPreviewToBay();
stagePreview();
} else if (key === "arrowdown") {
event.preventDefault();
preview.position.z -= 1;
clampPreviewToBay();
stagePreview();
} else if (key === "arrowup") {
event.preventDefault();
preview.position.z += 1;
clampPreviewToBay();
stagePreview();
}
});
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});
// -------------------------------------------------------------------------
// Background particles and animation loop
// -------------------------------------------------------------------------
const starPositions = [];
const starRandom = (() => {
let seed = 91273;
return () => {
seed = (seed * 16807) % 2147483647;
return (seed - 1) / 2147483646;
};
})();
for (let index = 0; index < 340; index++) {
starPositions.push(
(starRandom() - 0.5) * 110,
(starRandom() - 0.5) * 70,
(starRandom() - 0.5) * 110 - 20
);
}
const starsGeometry = new THREE.BufferGeometry();
starsGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(starPositions, 3)
);
scene.add(
new THREE.Points(
starsGeometry,
new THREE.PointsMaterial({
color: 0x7ea7bd,
size: 0.09,
transparent: true,
opacity: 0.65,
depthWrite: false
})
)
);
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const delta = Math.min(clock.getDelta(), 0.05);
for (const propeller of propellers) {
propeller.rotation.z += delta * 2.4;
}
comMarker.rotation.y += delta * 0.8;
comMarker.rotation.x += delta * 0.45;
if (ghostGroup.visible) {
ghostMaterial.opacity = 0.24 + Math.sin(clock.elapsedTime * 4) * 0.05;
}
renderer.render(scene, camera);
}
// Start with a completed demonstration load.
selectCrate(crates[0].id);
autoPack();
animate();
</script>
</body>
</html>
```