Prompt specification
Build or customize the Three.js 3D scene "Pack a hold under geometric constraints" 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: Pack a hold under geometric constraints
Category: Art & Culture · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/pack-a-hold-under-geometric-constraints-x2608
Scene Description Prompt:
Pack a hold under geometric constraints. Let users arrange simplified amphora cargo in a fictional hold. Count stored units, maintain clearance, and show how alternating rows change packing without claiming exact ancient practice. Please build this with Three.js from cdnjs in one self-contained HTML file, using low-poly forms.
Working Three.js Starter (pack-a-hold-under-geometric-constraints-x2608):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Hold Lab — Fictional Amphora Packing</title>
<style>
:root {
color-scheme: dark;
--bg: #071014;
--panel: #0c171c;
--panel-2: #101e24;
--line: rgba(177, 218, 218, 0.14);
--text: #e8f1ef;
--muted: #8ca4a5;
--teal: #65d3c2;
--teal-dark: #183f3c;
--orange: #f2a35d;
--red: #f06e67;
--green: #77d69c;
--radius: 12px;
}
* {
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,
input {
font: inherit;
}
button {
color: inherit;
}
#app {
display: grid;
grid-template-rows: 64px minmax(0, 1fr);
width: 100%;
height: 100dvh;
}
header {
position: relative;
z-index: 20;
display: flex;
align-items: center;
justify-content: space-between;
gap: 20px;
padding: 0 22px;
border-bottom: 1px solid var(--line);
background:
linear-gradient(90deg, rgba(101, 211, 194, 0.07), transparent 42%),
#091216;
}
.brand {
display: flex;
align-items: center;
min-width: 0;
gap: 13px;
}
.brand-mark {
position: relative;
flex: 0 0 auto;
width: 30px;
height: 38px;
border: 2px solid var(--teal);
border-radius: 48% 48% 35% 35%;
transform: scale(0.72);
}
.brand-mark::before,
.brand-mark::after {
content: "";
position: absolute;
top: 6px;
width: 11px;
height: 13px;
border: 2px solid var(--teal);
border-bottom: 0;
border-radius: 50% 50% 0 0;
}
.brand-mark::before {
left: -9px;
}
.brand-mark::after {
right: -9px;
}
.brand-title {
display: flex;
flex-direction: column;
line-height: 1.15;
}
.brand-title strong {
font-size: 15px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.brand-title span {
margin-top: 4px;
color: var(--muted);
font-size: 11px;
letter-spacing: 0.05em;
}
.header-right {
display: flex;
align-items: center;
gap: 14px;
}
.concept-badge {
padding: 7px 10px;
border: 1px solid rgba(242, 163, 93, 0.35);
border-radius: 999px;
color: #f5bf8c;
background: rgba(242, 163, 93, 0.07);
font-size: 10px;
font-weight: 750;
letter-spacing: 0.12em;
text-transform: uppercase;
white-space: nowrap;
}
.engine-label {
color: var(--muted);
font-size: 11px;
letter-spacing: 0.05em;
white-space: nowrap;
}
main {
display: grid;
grid-template-columns: minmax(0, 1fr) 350px;
min-height: 0;
}
#stage {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
background:
radial-gradient(circle at 50% 30%, rgba(34, 78, 82, 0.15), transparent 55%),
#071014;
}
#canvas-host {
position: absolute;
inset: 0;
}
#canvas-host canvas {
display: block;
width: 100%;
height: 100%;
outline: none;
touch-action: none;
}
.hud {
position: absolute;
z-index: 5;
top: 16px;
left: 16px;
display: flex;
flex-wrap: wrap;
gap: 8px;
pointer-events: none;
}
.metric {
min-width: 94px;
padding: 10px 12px;
border: 1px solid var(--line);
border-radius: 10px;
background: rgba(8, 18, 22, 0.82);
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
backdrop-filter: blur(10px);
}
.metric span {
display: block;
margin-bottom: 3px;
color: var(--muted);
font-size: 9px;
font-weight: 700;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.metric strong {
display: inline-block;
font-size: 20px;
font-variant-numeric: tabular-nums;
}
.metric small {
margin-left: 4px;
color: var(--muted);
font-size: 10px;
}
.mode-switch {
position: absolute;
z-index: 6;
top: 16px;
right: 16px;
display: flex;
padding: 4px;
border: 1px solid var(--line);
border-radius: 10px;
background: rgba(8, 18, 22, 0.86);
backdrop-filter: blur(10px);
}
.mode-switch button {
padding: 7px 10px;
border: 0;
border-radius: 7px;
background: transparent;
color: var(--muted);
cursor: pointer;
font-size: 11px;
font-weight: 700;
}
.mode-switch button.active {
color: #08201d;
background: var(--teal);
}
.view-controls {
position: absolute;
z-index: 6;
bottom: 58px;
left: 50%;
display: flex;
gap: 6px;
padding: 5px;
border: 1px solid var(--line);
border-radius: 11px;
background: rgba(8, 18, 22, 0.88);
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.25);
transform: translateX(-50%);
backdrop-filter: blur(10px);
}
.view-controls button {
padding: 8px 11px;
border: 0;
border-radius: 7px;
background: transparent;
color: var(--muted);
cursor: pointer;
font-size: 11px;
font-weight: 650;
white-space: nowrap;
}
.view-controls button:hover {
color: var(--text);
background: rgba(255, 255, 255, 0.06);
}
.stage-help {
position: absolute;
z-index: 5;
bottom: 18px;
left: 18px;
max-width: min(520px, calc(100% - 36px));
color: var(--muted);
font-size: 11px;
line-height: 1.45;
pointer-events: none;
}
.stage-help kbd {
padding: 2px 5px;
border: 1px solid var(--line);
border-radius: 4px;
color: var(--text);
background: rgba(255, 255, 255, 0.05);
font: inherit;
}
.disclaimer {
position: absolute;
z-index: 5;
right: 18px;
bottom: 17px;
max-width: 310px;
padding: 9px 11px;
border: 1px solid rgba(242, 163, 93, 0.22);
border-radius: 9px;
color: #c9b39f;
background: rgba(37, 27, 20, 0.68);
font-size: 10px;
line-height: 1.45;
pointer-events: none;
backdrop-filter: blur(8px);
}
#toast {
position: absolute;
z-index: 12;
top: 92px;
left: 50%;
max-width: calc(100% - 32px);
padding: 9px 13px;
border: 1px solid var(--line);
border-radius: 999px;
color: var(--text);
background: rgba(9, 22, 27, 0.94);
box-shadow: 0 12px 35px rgba(0, 0, 0, 0.3);
font-size: 11px;
opacity: 0;
pointer-events: none;
transform: translate(-50%, -8px);
transition: opacity 160ms ease, transform 160ms ease;
}
#toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
#toast.good {
border-color: rgba(119, 214, 156, 0.42);
}
#toast.bad {
border-color: rgba(240, 110, 103, 0.48);
}
.dimension-label {
position: absolute;
z-index: 4;
padding: 4px 7px;
border: 1px solid rgba(101, 211, 194, 0.24);
border-radius: 6px;
color: #a7d8d1;
background: rgba(7, 16, 20, 0.78);
font-size: 10px;
font-variant-numeric: tabular-nums;
pointer-events: none;
transform: translate(-50%, -50%);
}
aside {
position: relative;
z-index: 15;
min-height: 0;
overflow-y: auto;
border-left: 1px solid var(--line);
background:
linear-gradient(180deg, rgba(101, 211, 194, 0.035), transparent 22%),
var(--panel);
scrollbar-width: thin;
scrollbar-color: #29464b transparent;
}
.panel-section {
padding: 19px 20px;
border-bottom: 1px solid var(--line);
}
.panel-section:last-child {
border-bottom: 0;
}
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 15px;
}
.section-title h2 {
margin: 0;
font-size: 11px;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.section-title span {
color: var(--muted);
font-size: 10px;
}
.control {
margin-bottom: 16px;
}
.control:last-child {
margin-bottom: 0;
}
.control-head {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 8px;
}
.control-head label {
color: #b9c8c8;
font-size: 12px;
}
.control-value {
min-width: 66px;
padding: 4px 7px;
border: 1px solid var(--line);
border-radius: 6px;
color: var(--teal);
background: rgba(101, 211, 194, 0.05);
font-size: 11px;
text-align: right;
font-variant-numeric: tabular-nums;
}
input[type="range"] {
width: 100%;
height: 4px;
margin: 5px 0;
border-radius: 999px;
outline: none;
appearance: none;
background: linear-gradient(
90deg,
var(--teal) 0%,
var(--teal) var(--range-progress, 50%),
#203338 var(--range-progress, 50%),
#203338 100%
);
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
width: 15px;
height: 15px;
border: 3px solid #0b171b;
border-radius: 50%;
appearance: none;
background: var(--teal);
box-shadow: 0 0 0 1px rgba(101, 211, 194, 0.4);
}
input[type="range"]::-moz-range-thumb {
width: 11px;
height: 11px;
border: 3px solid #0b171b;
border-radius: 50%;
background: var(--teal);
box-shadow: 0 0 0 1px rgba(101, 211, 194, 0.4);
}
.switch-row {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 16px;
margin-bottom: 14px;
}
.switch-copy strong {
display: block;
margin-bottom: 4px;
color: #dce8e6;
font-size: 12px;
font-weight: 650;
}
.switch-copy small {
display: block;
color: var(--muted);
font-size: 10px;
line-height: 1.4;
}
.switch {
position: relative;
flex: 0 0 auto;
width: 38px;
height: 22px;
}
.switch input {
position: absolute;
width: 1px;
height: 1px;
opacity: 0;
}
.switch-track {
position: absolute;
inset: 0;
border: 1px solid #355057;
border-radius: 999px;
background: #14252a;
cursor: pointer;
transition: 160ms ease;
}
.switch-track::after {
content: "";
position: absolute;
top: 3px;
left: 3px;
width: 14px;
height: 14px;
border-radius: 50%;
background: #789093;
transition: 160ms ease;
}
.switch input:checked + .switch-track {
border-color: var(--teal);
background: var(--teal-dark);
}
.switch input:checked + .switch-track::after {
background: var(--teal);
transform: translateX(16px);
}
.button-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.button-grid.three {
grid-template-columns: repeat(3, 1fr);
}
.btn {
min-height: 36px;
padding: 8px 10px;
border: 1px solid var(--line);
border-radius: 8px;
background: #142329;
color: #d7e4e2;
cursor: pointer;
font-size: 11px;
font-weight: 650;
transition: border-color 140ms ease, background 140ms ease, transform 140ms ease;
}
.btn:hover:not(:disabled) {
border-color: rgba(101, 211, 194, 0.42);
background: #193039;
}
.btn:active:not(:disabled) {
transform: translateY(1px);
}
.btn.primary {
border-color: rgba(101, 211, 194, 0.42);
color: #07201d;
background: var(--teal);
}
.btn.primary:hover:not(:disabled) {
background: #7ce0d1;
}
.btn.danger {
color: #f5a19c;
}
.btn:disabled {
opacity: 0.35;
cursor: not-allowed;
}
.comparison {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px;
}
.comparison-card {
padding: 12px;
border: 1px solid var(--line);
border-radius: 9px;
background: rgba(255, 255, 255, 0.025);
}
.comparison-card.active {
border-color: rgba(101, 211, 194, 0.38);
background: rgba(101, 211, 194, 0.06);
}
.comparison-card span {
display: block;
color: var(--muted);
font-size: 9px;
font-weight: 700;
letter-spacing: 0.09em;
text-transform: uppercase;
}
.comparison-card strong {
display: block;
margin-top: 7px;
font-size: 22px;
font-variant-numeric: tabular-nums;
}
.comparison-card small {
display: block;
margin-top: 3px;
color: var(--muted);
font-size: 9px;
}
.comparison-note {
margin: 10px 0 0;
color: var(--muted);
font-size: 10px;
line-height: 1.5;
}
.delta {
color: var(--orange);
}
.selection-empty {
padding: 13px;
border: 1px dashed var(--line);
border-radius: 9px;
color: var(--muted);
font-size: 11px;
line-height: 1.5;
text-align: center;
}
.selection-info {
display: none;
}
.selection-info.visible {
display: block;
}
.selection-empty.hidden {
display: none;
}
.selection-summary {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 12px;
padding: 11px;
border: 1px solid rgba(101, 211, 194, 0.24);
border-radius: 9px;
background: rgba(101, 211, 194, 0.05);
}
.selection-summary strong {
display: block;
font-size: 12px;
}
.selection-summary small {
display: block;
margin-top: 3px;
color: var(--muted);
font-size: 10px;
}
.valid-dot {
width: 9px;
height: 9px;
border-radius: 50%;
background: var(--green);
box-shadow: 0 0 0 4px rgba(119, 214, 156, 0.1);
}
.valid-dot.invalid {
background: var(--red);
box-shadow: 0 0 0 4px rgba(240, 110, 103, 0.1);
}
.model-specs {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 13px;
}
.spec {
padding: 9px 10px;
border: 1px solid var(--line);
border-radius: 8px;
background: rgba(255, 255, 255, 0.02);
}
.spec span {
display: block;
color: var(--muted);
font-size: 9px;
text-transform: uppercase;
}
.spec strong {
display: block;
margin-top: 4px;
font-size: 11px;
}
.fine-print {
margin: 0;
color: #9f9290;
font-size: 10px;
line-height: 1.55;
}
@media (max-width: 900px) {
#app {
grid-template-rows: 56px minmax(0, 1fr);
}
header {
padding: 0 14px;
}
.engine-label {
display: none;
}
main {
grid-template-columns: 1fr;
grid-template-rows: 58% 42%;
}
aside {
border-top: 1px solid var(--line);
border-left: 0;
}
.metric {
min-width: 74px;
padding: 8px 9px;
}
.metric strong {
font-size: 16px;
}
.mode-switch {
top: auto;
right: 12px;
bottom: 104px;
}
.disclaimer {
display: none;
}
.stage-help {
right: 12px;
bottom: 12px;
left: 12px;
max-width: none;
}
.view-controls {
bottom: 48px;
}
}
@media (max-width: 520px) {
.concept-badge {
display: none;
}
.brand-title span {
display: none;
}
.hud {
top: 10px;
left: 10px;
right: 10px;
}
.metric {
flex: 1 1 70px;
min-width: 0;
}
.metric small {
display: none;
}
.view-controls button {
padding: 7px 9px;
}
.panel-section {
padding: 16px;
}
}
</style>
</head>
<body>
<div id="app">
<header>
<div class="brand">
<div class="brand-mark" aria-hidden="true"></div>
<div class="brand-title">
<strong>Hold Lab</strong>
<span>Fictional cargo geometry study</span>
</div>
</div>
<div class="header-right">
<span class="engine-label">LOW-POLY · THREE.JS CORE</span>
<span class="concept-badge">Concept model</span>
</div>
</header>
<main>
<section id="stage" aria-label="Interactive 3D cargo hold">
<div id="canvas-host"></div>
<div class="hud">
<div class="metric">
<span>Stored</span>
<strong id="storedCount">0</strong>
<small>units</small>
</div>
<div class="metric">
<span>Layers</span>
<strong id="layerCount">0</strong>
<small>used</small>
</div>
<div class="metric">
<span>Envelope use</span>
<strong id="volumeUse">0%</strong>
</div>
<div class="metric">
<span>Clearance</span>
<strong id="clearanceMetric">0.12</strong>
<small>m</small>
</div>
</div>
<div class="mode-switch" aria-label="Interaction mode">
<button id="arrangeMode" class="active" type="button">Arrange</button>
<button id="inspectMode" type="button">Inspect</button>
</div>
<div class="view-controls" aria-label="Camera views">
<button type="button" data-view="orbit">3D view</button>
<button type="button" data-view="top">Top</button>
<button type="button" data-view="fit">Fit hold</button>
</div>
<div class="stage-help" id="stageHelp">
Drag a vessel to arrange · drag empty space to orbit · wheel to zoom ·
<kbd>R</kbd> rotate · arrows nudge
</div>
<div class="disclaimer">
Fictional hold and stylized cargo. Dimensions and row patterns are
illustrative—not a reconstruction or claim about exact ancient practice.
</div>
<div id="toast" role="status" aria-live="polite"></div>
<div class="dimension-label" id="lengthLabel">9.2 m</div>
<div class="dimension-label" id="beamLabel">4.2 m</div>
<div class="dimension-label" id="depthLabel">2.7 m</div>
</section>
<aside>
<section class="panel-section">
<div class="section-title">
<h2>Hold envelope</h2>
<span>Concept metres</span>
</div>
<div class="control">
<div class="control-head">
<label for="lengthRange">Length</label>
<output class="control-value" id="lengthValue">9.2 m</output>
</div>
<input
id="lengthRange"
type="range"
min="6"
max="14"
step="0.1"
value="9.2"
>
</div>
<div class="control">
<div class="control-head">
<label for="beamRange">Beam</label>
<output class="control-value" id="beamValue">4.2 m</output>
</div>
<input
id="beamRange"
type="range"
min="2.5"
max="6"
step="0.1"
value="4.2"
>
</div>
<div class="control">
<div class="control-head">
<label for="depthRange">Depth</label>
<output class="control-value" id="depthValue">2.7 m</output>
</div>
<input
id="depthRange"
type="range"
min="1.4"
max="4"
step="0.1"
value="2.7"
>
</div>
<div class="control">
<div class="control-head">
<label for="clearanceRange">Minimum clearance</label>
<output class="control-value" id="clearanceValue">0.12 m</output>
</div>
<input
id="clearanceRange"
type="range"
min="0.04"
max="0.28"
step="0.01"
value="0.12"
>
</div>
</section>
<section class="panel-section">
<div class="section-title">
<h2>Packing pattern</h2>
<span>Model only</span>
</div>
<div class="switch-row">
<div class="switch-copy">
<strong>Stagger alternate rows</strong>
<small>Offset every second row by half a cargo pitch.</small>
</div>
<label class="switch">
<input id="staggerToggle" type="checkbox" checked>
<span class="switch-track"></span>
</label>
</div>
<div class="switch-row">
<div class="switch-copy">
<strong>Show cargo envelopes</strong>
<small>Display simplified rectangular collision envelopes.</small>
</div>
<label class="switch">
<input id="envelopeToggle" type="checkbox" checked>
<span class="switch-track"></span>
</label>
</div>
<div class="button-grid">
<button class="btn primary" id="autoPackButton" type="button">
Auto-pack
</button>
<button class="btn" id="addCargoButton" type="button">
Add amphora
</button>
<button class="btn danger" id="clearButton" type="button">
Clear hold
</button>
</div>
</section>
<section class="panel-section">
<div class="section-title">
<h2>Row comparison</h2>
<span>Same clearance</span>
</div>
<div class="comparison">
<div class="comparison-card" id="alignedCard">
<span>Aligned rows</span>
<strong id="alignedCount">0</strong>
<small>maximum units</small>
</div>
<div class="comparison-card active" id="staggeredCard">
<span>Staggered rows</span>
<strong id="staggeredCount">0</strong>
<small>maximum units</small>
</div>
</div>
<p class="comparison-note">
Difference:
<strong class="delta" id="rowDelta">0 units</strong>.
Edge fit changes when alternate rows are shifted; this is a geometric
comparison, not an ancient loading rule.
</p>
</section>
<section class="panel-section">
<div class="section-title">
<h2>Selected vessel</h2>
<span id="selectionId">None</span>
</div>
<div class="selection-empty" id="selectionEmpty">
Select a vessel in Arrange mode to rotate, move between layers, or
remove it.
</div>
<div class="selection-info" id="selectionInfo">
<div class="selection-summary">
<div>
<strong id="selectionTitle">Amphora 001</strong>
<small id="selectionPosition">Layer 1 · Row 1</small>
</div>
<span class="valid-dot" id="validDot"></span>
</div>
<div class="button-grid three">
<button class="btn" id="rotateButton" type="button">Rotate</button>
<button class="btn" id="layerDownButton" type="button">Layer −</button>
<button class="btn" id="layerUpButton" type="button">Layer +</button>
</div>
</div>
<div class="model-specs">
<div class="spec">
<span>Cargo envelope</span>
<strong>0.78 × 0.36 m</strong>
</div>
<div class="spec">
<span>Vertical envelope</span>
<strong>0.36 m</strong>
</div>
</div>
</section>
<section class="panel-section">
<div class="section-title">
<h2>Interpretation</h2>
<span>Read the model</span>
</div>
<p class="fine-print">
“Envelope use” divides the simplified rectangular cargo volume by
hold volume. Clearances are enforced between cargo, walls, and
layers. Amphora shape, dimensions, and arrangement are deliberately
simplified for spatial exploration and do not establish historical
maritime practice.
</p>
</section>
</aside>
</main>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// State and constants
// -------------------------------------------------------------------------
const $ = (id) => document.getElementById(id);
const host = $("canvas-host");
const stage = $("stage");
const CARGO = Object.freeze({
length: 0.78,
width: 0.36,
height: 0.36
});
const PALETTE = [
0xb65f3d,
0xc8794e,
0xa94d35,
0xd18b5c,
0x9d563e,
0xbe704a
];
const state = {
hold: {
length: 9.2,
beam: 4.2,
depth: 2.7
},
clearance: 0.12,
stagger: true,
mode: "arrange",
showEnvelopes: true
};
let cargo = [];
let selectedIndex = -1;
let hoverIndex = -1;
let holdGroup = null;
let repackTimer = null;
let toastTimer = null;
// -------------------------------------------------------------------------
// Renderer, scene, and lighting
// -------------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x071014);
scene.fog = new THREE.Fog(0x071014, 18, 40);
const camera = new THREE.PerspectiveCamera(42, 1, 0.1, 100);
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.2;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.domElement.setAttribute(
"aria-label",
"Interactive low-poly cargo hold visualization"
);
host.appendChild(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(
0xbad8d4,
0x18201f,
1.65
);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xffe0be, 3.2);
keyLight.position.set(7, 12, 7);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -15;
keyLight.shadow.camera.right = 15;
keyLight.shadow.camera.top = 15;
keyLight.shadow.camera.bottom = -15;
keyLight.shadow.camera.near = 0.5;
keyLight.shadow.camera.far = 40;
keyLight.shadow.bias = -0.0008;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x6dc9c3, 1.8);
rimLight.position.set(-8, 5, -9);
scene.add(rimLight);
// -------------------------------------------------------------------------
// Instanced low-poly amphora geometry
// -------------------------------------------------------------------------
const profile = [
new THREE.Vector2(0.055, -0.39),
new THREE.Vector2(0.12, -0.34),
new THREE.Vector2(0.175, -0.2),
new THREE.Vector2(0.18, 0.02),
new THREE.Vector2(0.15, 0.19),
new THREE.Vector2(0.085, 0.29),
new THREE.Vector2(0.065, 0.39)
];
const bodyGeometry = new THREE.LatheGeometry(profile, 8);
const handleGeometry = new THREE.TorusGeometry(0.072, 0.018, 4, 8);
const mouthGeometry = new THREE.CylinderGeometry(
0.071,
0.063,
0.045,
8,
1,
false
);
const bodyMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.88,
metalness: 0,
flatShading: true
});
const handleMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.9,
metalness: 0,
flatShading: true
});
const mouthMaterial = new THREE.MeshStandardMaterial({
color: 0x6d3425,
roughness: 0.95,
metalness: 0,
flatShading: true
});
const instanceCapacity = Math.ceil(Number($("lengthRange").max) / CARGO.width) * Math.ceil(Number($("beamRange").max) / CARGO.width) * Math.ceil(Number($("depthRange").max) / CARGO.height);
const bodyMesh = new THREE.InstancedMesh(
bodyGeometry,
bodyMaterial,
instanceCapacity
);
bodyMesh.count = 0;
bodyMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
bodyMesh.castShadow = true;
bodyMesh.receiveShadow = true;
bodyMesh.frustumCulled = false;
scene.add(bodyMesh);
const handleMesh = new THREE.InstancedMesh(
handleGeometry,
handleMaterial,
instanceCapacity * 2
);
handleMesh.count = 0;
handleMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
handleMesh.castShadow = true;
handleMesh.frustumCulled = false;
scene.add(handleMesh);
const mouthMesh = new THREE.InstancedMesh(
mouthGeometry,
mouthMaterial,
instanceCapacity
);
mouthMesh.count = 0;
mouthMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
mouthMesh.castShadow = true;
mouthMesh.frustumCulled = false;
scene.add(mouthMesh);
const envelopeMesh = new THREE.InstancedMesh(
new THREE.BoxGeometry(1, 1, 1),
new THREE.MeshBasicMaterial({
color: 0x77dacb,
transparent: true,
opacity: 0.1,
wireframe: true,
depthWrite: false
}),
instanceCapacity
);
envelopeMesh.count = 0;
envelopeMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
envelopeMesh.frustumCulled = false;
envelopeMesh.renderOrder = 2;
scene.add(envelopeMesh);
const selectionMarker = new THREE.LineSegments(
new THREE.EdgesGeometry(new THREE.BoxGeometry(1, 1, 1)),
new THREE.LineBasicMaterial({
color: 0xf2a35d,
transparent: true,
opacity: 0.95
})
);
selectionMarker.visible = false;
selectionMarker.renderOrder = 3;
scene.add(selectionMarker);
// The amphora profile is upright in local space. This rotation lays it
// horizontally, with its long axis along local X.
const bodyLocalMatrix = new THREE.Matrix4().makeRotationZ(-Math.PI / 2);
const tempMatrix = new THREE.Matrix4();
const tempMatrix2 = new THREE.Matrix4();
const tempPosition = new THREE.Vector3();
const tempScale = new THREE.Vector3();
const tempQuaternion = new THREE.Quaternion();
const yawQuaternion = new THREE.Quaternion();
const instanceColor = new THREE.Color();
const handleColor = new THREE.Color();
// -------------------------------------------------------------------------
// Camera controls implemented without addons
// -------------------------------------------------------------------------
const view = {
theta: 0.82,
phi: 0.88,
radius: 13,
target: new THREE.Vector3(0, 1, 0),
desiredTheta: 0.82,
desiredPhi: 0.88,
desiredRadius: 13,
desiredTarget: new THREE.Vector3(0, 1, 0)
};
function updateCamera() {
view.theta += (view.desiredTheta - view.theta) * 0.12;
view.phi += (view.desiredPhi - view.phi) * 0.12;
view.radius += (view.desiredRadius - view.radius) * 0.12;
view.target.lerp(view.desiredTarget, 0.12);
const sinPhi = Math.sin(view.phi);
camera.position.set(
view.target.x + view.radius * sinPhi * Math.sin(view.theta),
view.target.y + view.radius * Math.cos(view.phi),
view.target.z + view.radius * sinPhi * Math.cos(view.theta)
);
camera.lookAt(view.target);
}
function setView(kind) {
const size = Math.max(
state.hold.length,
state.hold.beam,
state.hold.depth * 1.5
);
view.desiredTarget.set(0, state.hold.depth * 0.35, 0);
if (kind === "top") {
view.desiredTheta = 0;
view.desiredPhi = 0.075;
view.desiredRadius = size * 0.95;
} else if (kind === "fit") {
view.desiredTheta = 0.82;
view.desiredPhi = 0.88;
view.desiredRadius = size * 1.18;
} else {
view.desiredTheta = 0.82;
view.desiredPhi = 0.88;
view.desiredRadius = size * 1.18;
}
}
// -------------------------------------------------------------------------
// Hold construction
// -------------------------------------------------------------------------
function disposeGroup(group) {
if (!group) return;
group.traverse((object) => {
if (object.geometry) object.geometry.dispose();
if (object.material) {
const materials = Array.isArray(object.material)
? object.material
: [object.material];
materials.forEach((material) => material.dispose());
}
});
scene.remove(group);
}
function rebuildHold() {
disposeGroup(holdGroup);
holdGroup = new THREE.Group();
const { length, beam, depth } = state.hold;
const deckMaterialA = new THREE.MeshStandardMaterial({
color: 0x40352c,
roughness: 0.95,
metalness: 0,
flatShading: true
});
const deckMaterialB = new THREE.MeshStandardMaterial({
color: 0x493b30,
roughness: 0.95,
metalness: 0,
flatShading: true
});
const frameMaterial = new THREE.MeshStandardMaterial({
color: 0x2a2521,
roughness: 0.9,
metalness: 0,
flatShading: true
});
const wallMaterial = new THREE.MeshStandardMaterial({
color: 0x5f9f9d,
transparent: true,
opacity: 0.075,
roughness: 0.7,
side: THREE.DoubleSide,
depthWrite: false
});
const plankCount = Math.max(8, Math.ceil(beam / 0.27));
const plankWidth = beam / plankCount;
for (let i = 0; i < plankCount; i++) {
const plank = new THREE.Mesh(
new THREE.BoxGeometry(length, 0.07, plankWidth - 0.014),
i % 2 ? deckMaterialA : deckMaterialB
);
plank.position.set(
0,
-0.035,
-beam / 2 + (i + 0.5) * plankWidth
);
plank.receiveShadow = true;
holdGroup.add(plank);
}
const sideWall = new THREE.Mesh(
new THREE.BoxGeometry(length, depth, 0.035),
wallMaterial
);
sideWall.position.set(0, depth / 2, -beam / 2);
holdGroup.add(sideWall);
const oppositeWall = sideWall.clone();
oppositeWall.position.z = beam / 2;
holdGroup.add(oppositeWall);
const endWall = new THREE.Mesh(
new THREE.BoxGeometry(0.035, depth, beam),
wallMaterial
);
endWall.position.set(-length / 2, depth / 2, 0);
holdGroup.add(endWall);
const oppositeEnd = endWall.clone();
oppositeEnd.position.x = length / 2;
holdGroup.add(oppositeEnd);
const railThickness = 0.085;
for (const z of [-beam / 2, beam / 2]) {
const rail = new THREE.Mesh(
new THREE.BoxGeometry(length + 0.12, railThickness, railThickness),
frameMaterial
);
rail.position.set(0, depth, z);
rail.castShadow = true;
holdGroup.add(rail);
}
for (const x of [-length / 2, length / 2]) {
const rail = new THREE.Mesh(
new THREE.BoxGeometry(railThickness, railThickness, beam + 0.12),
frameMaterial
);
rail.position.set(x, depth, 0);
rail.castShadow = true;
holdGroup.add(rail);
}
const ribCount = Math.max(3, Math.round(length / 1.6));
for (let i = 0; i <= ribCount; i++) {
const x = -length / 2 + (i / ribCount) * length;
for (const z of [-beam / 2, beam / 2]) {
const post = new THREE.Mesh(
new THREE.BoxGeometry(0.075, depth, 0.075),
frameMaterial
);
post.position.set(x, depth / 2, z);
post.castShadow = true;
holdGroup.add(post);
}
}
const gridPoints = [];
const gridStep = 0.5;
for (let x = -length / 2; x <= length / 2 + 0.001; x += gridStep) {
gridPoints.push(
new THREE.Vector3(x, 0.006, -beam / 2),
new THREE.Vector3(x, 0.006, beam / 2)
);
}
for (let z = -beam / 2; z <= beam / 2 + 0.001; z += gridStep) {
gridPoints.push(
new THREE.Vector3(-length / 2, 0.006, z),
new THREE.Vector3(length / 2, 0.006, z)
);
}
const gridGeometry = new THREE.BufferGeometry().setFromPoints(gridPoints);
const grid = new THREE.LineSegments(
gridGeometry,
new THREE.LineBasicMaterial({
color: 0x84aaa5,
transparent: true,
opacity: 0.13
})
);
holdGroup.add(grid);
const clearance = state.clearance;
const clearancePoints = [
new THREE.Vector3(
-length / 2 + clearance,
0.012,
-beam / 2 + clearance
),
new THREE.Vector3(
length / 2 - clearance,
0.012,
-beam / 2 + clearance
),
new THREE.Vector3(
length / 2 - clearance,
0.012,
beam / 2 - clearance
),
new THREE.Vector3(
-length / 2 + clearance,
0.012,
beam / 2 - clearance
),
new THREE.Vector3(
-length / 2 + clearance,
0.012,
-beam / 2 + clearance
)
];
const clearanceLine = new THREE.Line(
new THREE.BufferGeometry().setFromPoints(clearancePoints),
new THREE.LineDashedMaterial({
color: 0x65d3c2,
dashSize: 0.14,
gapSize: 0.09,
transparent: true,
opacity: 0.5
})
);
clearanceLine.computeLineDistances();
holdGroup.add(clearanceLine);
const outlinePoints = [
new THREE.Vector3(-length / 2, depth, -beam / 2),
new THREE.Vector3(length / 2, depth, -beam / 2),
new THREE.Vector3(length / 2, depth, beam / 2),
new THREE.Vector3(-length / 2, depth, beam / 2),
new THREE.Vector3(-length / 2, depth, -beam / 2)
];
holdGroup.add(
new THREE.Line(
new THREE.BufferGeometry().setFromPoints(outlinePoints),
new THREE.LineBasicMaterial({
color: 0x8bc8c1,
transparent: true,
opacity: 0.4
})
)
);
scene.add(holdGroup);
$("lengthLabel").textContent = `${length.toFixed(1)} m`;
$("beamLabel").textContent = `${beam.toFixed(1)} m`;
$("depthLabel").textContent = `${depth.toFixed(1)} m`;
}
// -------------------------------------------------------------------------
// Packing geometry
// -------------------------------------------------------------------------
function layerY(layer) {
return (
state.clearance +
CARGO.height / 2 +
layer * (CARGO.height + state.clearance)
);
}
function getLayerCount() {
const usable =
state.hold.depth -
2 * state.clearance -
CARGO.height;
if (usable < 0) return 0;
return (
Math.floor(usable / (CARGO.height + state.clearance)) + 1
);
}
function getCargoDimensions(item) {
return item.rotation % 2 === 0
? { x: CARGO.length, z: CARGO.width }
: { x: CARGO.width, z: CARGO.length };
}
function withinHorizontalBounds(x, z, dimensions) {
const halfLength = state.hold.length / 2 - state.clearance;
const halfBeam = state.hold.beam / 2 - state.clearance;
return (
x - dimensions.x / 2 >= -halfLength &&
x + dimensions.x / 2 <= halfLength &&
z - dimensions.z / 2 >= -halfBeam &&
z + dimensions.z / 2 <= halfBeam
);
}
function buildPlan(staggered) {
const result = [];
const effectiveLength =
state.hold.length - 2 * state.clearance;
const effectiveBeam =
state.hold.beam - 2 * state.clearance;
if (
effectiveLength <= 0 ||
effectiveBeam <= 0 ||
state.hold.depth <= 0
) {
return result;
}
const pitchX = CARGO.length + state.clearance;
const pitchZ = CARGO.width + state.clearance;
const perRow = Math.max(
0,
Math.floor(
(effectiveLength + state.clearance) / pitchX
)
);
const rowCount = Math.max(
0,
Math.floor(
(effectiveBeam + state.clearance) / pitchZ
)
);
const layers = getLayerCount();
const xStart =
-effectiveLength / 2 + CARGO.length / 2;
for (let layer = 0; layer < layers; layer++) {
for (let row = 0; row < rowCount; row++) {
const z =
-effectiveBeam / 2 +
CARGO.width / 2 +
row * pitchZ;
let offset = 0;
if (staggered && row % 2 === 1) {
const positive = [];
const negative = [];
for (let j = 0; j < perRow; j++) {
const positiveX = xStart + pitchX / 2 + j * pitchX;
const negativeX = xStart - pitchX / 2 + j * pitchX;
if (
withinHorizontalBounds(
positiveX,
z,
{ x: CARGO.length, z: CARGO.width }
)
) {
positive.push(positiveX);
}
if (
withinHorizontalBounds(
negativeX,
z,
{ x: CARGO.length, z: CARGO.width }
)
) {
negative.push(negativeX);
}
}
if (positive.length >= negative.length) {
offset = pitchX / 2;
} else {
offset = -pitchX / 2;
}
}
for (let j = 0; j < perRow; j++) {
const x = xStart + offset + j * pitchX;
if (
!withinHorizontalBounds(
x,
z,
{ x: CARGO.length, z: CARGO.width }
)
) {
continue;
}
result.push({
x,
z,
y: layerY(layer),
layer,
rotation: 0
});
}
}
}
return result;
}
function validateCargo(item, ignoredIndex = -1) {
const dimensions = getCargoDimensions(item);
if (!withinHorizontalBounds(item.x, item.z, dimensions)) {
return {
ok: false,
reason: "Outside the wall clearance boundary"
};
}
if (
item.layer < 0 ||
item.layer >= getLayerCount()
) {
return {
ok: false,
reason: "Outside the available layer range"
};
}
for (let i = 0; i < cargo.length; i++) {
if (i === ignoredIndex) continue;
const other = cargo[i];
const otherDimensions = getCargoDimensions(other);
const verticalSeparated =
item.y + CARGO.height / 2 + state.clearance <=
other.y - CARGO.height / 2 ||
other.y + CARGO.height / 2 + state.clearance <=
item.y - CARGO.height / 2;
if (verticalSeparated) continue;
const overlapX =
Math.abs(item.x - other.x) <
(dimensions.x + otherDimensions.x) / 2 +
state.clearance;
const overlapZ =
Math.abs(item.z - other.z) <
(dimensions.z + otherDimensions.z) / 2 +
state.clearance;
if (overlapX && overlapZ) {
return {
ok: false,
reason: "Too close to another cargo envelope"
};
}
}
return { ok: true, reason: "Clearance maintained" };
}
function autoPack(showMessage = true) {
const plan = buildPlan(state.stagger);
cargo = plan.map((item, index) => ({
...item,
id: index,
color: PALETTE[(index * 7 + 3) % PALETTE.length],
valid: true
}));
selectedIndex = -1;
updateCargoInstances();
updateSelectionPanel();
updateMetrics();
if (showMessage) {
showToast(
`${cargo.length} vessels packed with ${
state.stagger ? "staggered" : "aligned"
} rows.`,
"good"
);
}
}
// -------------------------------------------------------------------------
// Cargo rendering
// -------------------------------------------------------------------------
function updateCargoInstances() {
const count = cargo.length;
bodyMesh.count = count;
handleMesh.count = count * 2;
mouthMesh.count = count;
envelopeMesh.count = count;
for (let i = 0; i < count; i++) {
const item = cargo[i];
yawQuaternion.setFromAxisAngle(
new THREE.Vector3(0, 1, 0),
item.rotation * Math.PI / 2
);
tempPosition.set(item.x, item.y, item.z);
tempScale.set(1, 1, 1);
const rootMatrix = tempMatrix.compose(
tempPosition,
yawQuaternion,
tempScale
);
const worldBodyMatrix = tempMatrix2.multiplyMatrices(
rootMatrix,
bodyLocalMatrix
);
bodyMesh.setMatrixAt(i, worldBodyMatrix);
const handleLeft = new THREE.Matrix4().makeTranslation(
-0.112,
0.225,
0
);
const handleRight = new THREE.Matrix4().makeTranslation(
0.112,
0.225,
0
);
const handleLeftMatrix = new THREE.Matrix4().multiplyMatrices(
worldBodyMatrix,
handleLeft
);
const handleRightMatrix = new THREE.Matrix4().multiplyMatrices(
worldBodyMatrix,
handleRight
);
handleMesh.setMatrixAt(i * 2, handleLeftMatrix);
handleMesh.setMatrixAt(i * 2 + 1, handleRightMatrix);
const mouthLocal = new THREE.Matrix4().makeTranslation(
0,
0.398,
0
);
const mouthMatrix = new THREE.Matrix4().multiplyMatrices(
worldBodyMatrix,
mouthLocal
);
mouthMesh.setMatrixAt(i, mouthMatrix);
instanceColor.setHex(item.color);
if (!item.valid) {
instanceColor.setHex(0xf06e67);
} else if (i === selectedIndex) {
instanceColor.lerp(new THREE.Color(0xffffff), 0.32);
} else if (i === hoverIndex) {
instanceColor.lerp(new THREE.Color(0xffffff), 0.13);
}
bodyMesh.setColorAt(i, instanceColor);
handleColor.copy(instanceColor).multiplyScalar(0.82);
handleMesh.setColorAt(i * 2, handleColor);
handleMesh.setColorAt(i * 2 + 1, handleColor);
const envelopeScale = new THREE.Matrix4().makeScale(
CARGO.length,
CARGO.height,
CARGO.width
);
const envelopeMatrix = new THREE.Matrix4().multiplyMatrices(
rootMatrix,
envelopeScale
);
envelopeMesh.setMatrixAt(i, envelopeMatrix);
}
bodyMesh.instanceMatrix.needsUpdate = true;
handleMesh.instanceMatrix.needsUpdate = true;
mouthMesh.instanceMatrix.needsUpdate = true;
envelopeMesh.instanceMatrix.needsUpdate = true;
if (bodyMesh.instanceColor) {
bodyMesh.instanceColor.needsUpdate = true;
}
if (handleMesh.instanceColor) {
handleMesh.instanceColor.needsUpdate = true;
}
if (mouthMesh.instanceColor) {
mouthMesh.instanceColor.needsUpdate = true;
}
envelopeMesh.visible = state.showEnvelopes;
updateSelectionMarker();
}
function updateSelectionMarker() {
if (selectedIndex < 0 || !cargo[selectedIndex]) {
selectionMarker.visible = false;
return;
}
const item = cargo[selectedIndex];
selectionMarker.visible = true;
selectionMarker.position.set(item.x, item.y, item.z);
selectionMarker.rotation.set(0, item.rotation * Math.PI / 2, 0);
selectionMarker.scale.set(
CARGO.length + 0.025,
CARGO.height + 0.025,
CARGO.width + 0.025
);
selectionMarker.material.color.setHex(
item.valid ? 0xf2a35d : 0xf06e67
);
}
// -------------------------------------------------------------------------
// Metrics and selection UI
// -------------------------------------------------------------------------
function updateMetrics() {
const alignedCount = buildPlan(false).length;
const staggeredCount = buildPlan(true).length;
$("storedCount").textContent = cargo.length;
$("layerCount").textContent = new Set(
cargo.map((item) => item.layer)
).size;
$("clearanceMetric").textContent = state.clearance.toFixed(2);
const holdVolume =
state.hold.length *
state.hold.beam *
state.hold.depth;
const cargoVolume =
cargo.length *
CARGO.length *
CARGO.width *
CARGO.height;
const usage = holdVolume > 0 ? (cargoVolume / holdVolume) * 100 : 0;
$("volumeUse").textContent = `${usage.toFixed(1)}%`;
$("alignedCount").textContent = alignedCount;
$("staggeredCount").textContent = staggeredCount;
$("alignedCard").classList.toggle(
"active",
!state.stagger
);
$("staggeredCard").classList.toggle(
"active",
state.stagger
);
const difference = staggeredCount - alignedCount;
const percentage = alignedCount
? (difference / alignedCount) * 100
: 0;
$("rowDelta").textContent =
`${difference >= 0 ? "+" : ""}${difference} units ` +
`(${percentage >= 0 ? "+" : ""}${percentage.toFixed(1)}%)`;
}
function selectCargo(index) {
selectedIndex = index;
updateCargoInstances();
updateSelectionPanel();
}
function updateSelectionPanel() {
const hasSelection =
selectedIndex >= 0 && cargo[selectedIndex];
$("selectionEmpty").classList.toggle(
"hidden",
hasSelection
);
$("selectionInfo").classList.toggle(
"visible",
hasSelection
);
$("rotateButton").disabled = !hasSelection;
$("layerDownButton").disabled = !hasSelection;
$("layerUpButton").disabled = !hasSelection;
if (!hasSelection) {
$("selectionId").textContent = "None";
return;
}
const item = cargo[selectedIndex];
$("selectionId").textContent = `#${String(item.id + 1).padStart(3, "0")}`;
$("selectionTitle").textContent =
`Amphora ${String(item.id + 1).padStart(3, "0")}`;
const row =
Math.floor(
(item.z + state.hold.beam / 2) /
(CARGO.width + state.clearance)
) + 1;
$("selectionPosition").textContent =
`Layer ${item.layer + 1} · Row ${row} · ` +
`${item.rotation ? "Rotated 90°" : "Long axis"}`;
$("validDot").classList.toggle(
"invalid",
!item.valid
);
$("layerDownButton").disabled =
item.layer <= 0;
$("layerUpButton").disabled =
item.layer >= getLayerCount() - 1;
}
function showToast(message, kind = "") {
const toast = $("toast");
toast.textContent = message;
toast.className = `show ${kind}`;
clearTimeout(toastTimer);
toastTimer = setTimeout(() => {
toast.className = "";
}, 2400);
}
// -------------------------------------------------------------------------
// Editing selected cargo
// -------------------------------------------------------------------------
function rotateSelected() {
if (selectedIndex < 0) return;
const item = cargo[selectedIndex];
const oldRotation = item.rotation;
item.rotation = 1 - item.rotation;
const validation = validateCargo(item, selectedIndex);
if (!validation.ok) {
item.rotation = oldRotation;
showToast(validation.reason, "bad");
return;
}
item.valid = true;
updateCargoInstances();
updateSelectionPanel();
showToast("Vessel rotated; clearance maintained.", "good");
}
function changeSelectedLayer(delta) {
if (selectedIndex < 0) return;
const item = cargo[selectedIndex];
const oldLayer = item.layer;
const oldY = item.y;
item.layer += delta;
item.y = layerY(item.layer);
const validation = validateCargo(item, selectedIndex);
if (!validation.ok) {
item.layer = oldLayer;
item.y = oldY;
showToast(validation.reason, "bad");
return;
}
item.valid = true;
updateCargoInstances();
updateSelectionPanel();
showToast("Layer changed; clearance maintained.", "good");
}
function deleteSelected() {
if (selectedIndex < 0) return;
cargo.splice(selectedIndex, 1);
cargo.forEach((item, index) => {
item.id = index;
});
selectedIndex = -1;
updateCargoInstances();
updateSelectionPanel();
updateMetrics();
showToast("Vessel removed from the hold.");
}
function addCargo() {
const layers = getLayerCount();
if (layers === 0) {
showToast("The hold is too shallow for a cargo layer.", "bad");
return;
}
const effectiveLength =
state.hold.length - 2 * state.clearance;
const effectiveBeam =
state.hold.beam - 2 * state.clearance;
const pitchX = CARGO.length + state.clearance;
const pitchZ = CARGO.width + state.clearance;
for (let layer = 0; layer < layers; layer++) {
for (let row = 0; row * pitchZ < effectiveBeam; row++) {
const z =
-effectiveBeam / 2 +
CARGO.width / 2 +
row * pitchZ;
for (
let column = 0;
column * pitchX < effectiveLength;
column++
) {
const x =
-effectiveLength / 2 +
CARGO.length / 2 +
column * pitchX;
const candidate = {
x,
z,
y: layerY(layer),
layer,
rotation: 0,
color: PALETTE[cargo.length % PALETTE.length],
valid: true
};
if (validateCargo(candidate).ok) {
candidate.id = cargo.length;
cargo.push(candidate);
selectCargo(cargo.length - 1);
updateMetrics();
showToast("Amphora added. Drag it to arrange.", "good");
return;
}
}
}
}
showToast(
"No clear placement was found at the configured clearance.",
"bad"
);
}
function clearHold() {
cargo = [];
selectedIndex = -1;
hoverIndex = -1;
updateCargoInstances();
updateSelectionPanel();
updateMetrics();
showToast("Hold cleared.");
}
// -------------------------------------------------------------------------
// Raycasting and direct manipulation
// -------------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const dragPlane = new THREE.Plane();
const dragPoint = new THREE.Vector3();
const dragOffset = new THREE.Vector3();
let pointerState = {
down: false,
mode: null,
lastX: 0,
lastY: 0,
originalX: 0,
originalZ: 0
};
function setPointerFromEvent(event) {
const rect = renderer.domElement.getBoundingClientRect();
pointer.x =
((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y =
-((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
}
renderer.domElement.addEventListener("pointerdown", (event) => {
if (event.button !== 0 && event.button !== 2) return;
renderer.domElement.setPointerCapture(event.pointerId);
setPointerFromEvent(event);
pointerState.down = true;
pointerState.lastX = event.clientX;
pointerState.lastY = event.clientY;
pointerState.mode = "orbit";
if (state.mode === "arrange" && event.button === 0) {
const hits = raycaster.intersectObject(bodyMesh, false);
if (hits.length && hits[0].instanceId < cargo.length) {
const index = hits[0].instanceId;
selectCargo(index);
const item = cargo[index];
dragPlane.set(
new THREE.Vector3(0, 1, 0),
-item.y
);
if (raycaster.ray.intersectPlane(dragPlane, dragPoint)) {
dragOffset.set(
item.x - dragPoint.x,
0,
item.z - dragPoint.z
);
} else {
dragOffset.set(0, 0, 0);
}
pointerState.mode = "cargo";
pointerState.originalX = item.x;
pointerState.originalZ = item.z;
renderer.domElement.style.cursor = "grabbing";
}
}
});
renderer.domElement.addEventListener("pointermove", (event) => {
setPointerFromEvent(event);
if (
pointerState.down &&
pointerState.mode === "cargo" &&
selectedIndex >= 0
) {
const item = cargo[selectedIndex];
if (raycaster.ray.intersectPlane(dragPlane, dragPoint)) {
const snap = 0.05;
item.x =
Math.round(
(dragPoint.x + dragOffset.x) / snap
) * snap;
item.z =
Math.round(
(dragPoint.z + dragOffset.z) / snap
) * snap;
const validation = validateCargo(item, selectedIndex);
item.valid = validation.ok;
updateCargoInstances();
updateSelectionPanel();
}
return;
}
if (pointerState.down && pointerState.mode === "orbit") {
const dx = event.clientX - pointerState.lastX;
const dy = event.clientY - pointerState.lastY;
view.desiredTheta -= dx * 0.006;
view.desiredPhi = THREE.MathUtils.clamp(
view.desiredPhi + dy * 0.005,
0.075,
1.42
);
}
pointerState.lastX = event.clientX;
pointerState.lastY = event.clientY;
if (state.mode === "arrange" && !pointerState.down) {
const hits = raycaster.intersectObject(bodyMesh, false);
const nextHover =
hits.length && hits[0].instanceId < cargo.length
? hits[0].instanceId
: -1;
if (nextHover !== hoverIndex) {
hoverIndex = nextHover;
renderer.domElement.style.cursor =
hoverIndex >= 0 ? "grab" : "default";
updateCargoInstances();
}
}
});
function endPointer(event) {
if (!pointerState.down) return;
if (
pointerState.mode === "cargo" &&
selectedIndex >= 0
) {
const item = cargo[selectedIndex];
if (!item.valid) {
item.x = pointerState.originalX;
item.z = pointerState.originalZ;
item.valid = true;
updateCargoInstances();
updateSelectionPanel();
showToast(
"Placement blocked: the vessel would break clearance.",
"bad"
);
} else {
showToast("Placement accepted; clearance maintained.", "good");
}
}
pointerState.down = false;
pointerState.mode = null;
renderer.domElement.style.cursor =
state.mode === "arrange" ? "default" : "grab";
if (event && renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", endPointer);
renderer.domElement.addEventListener("pointercancel", endPointer);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
view.desiredRadius = THREE.MathUtils.clamp(
view.desiredRadius * Math.exp(event.deltaY * 0.001),
3.5,
30
);
},
{ passive: false }
);
renderer.domElement.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
// -------------------------------------------------------------------------
// Keyboard editing
// -------------------------------------------------------------------------
window.addEventListener("keydown", (event) => {
const tag = document.activeElement?.tagName;
if (["INPUT", "TEXTAREA", "SELECT"].includes(tag)) return;
if (event.key.toLowerCase() === "r") {
rotateSelected();
return;
}
if (event.key === "Delete" || event.key === "Backspace") {
event.preventDefault();
deleteSelected();
return;
}
if (event.key === "Escape") {
selectCargo(-1);
return;
}
if (
selectedIndex < 0 ||
![
"ArrowLeft",
"ArrowRight",
"ArrowUp",
"ArrowDown"
].includes(event.key)
) {
return;
}
event.preventDefault();
const item = cargo[selectedIndex];
const oldX = item.x;
const oldZ = item.z;
const step = event.shiftKey ? 0.2 : 0.05;
if (event.key === "ArrowLeft") item.x -= step;
if (event.key === "ArrowRight") item.x += step;
if (event.key === "ArrowUp") item.z -= step;
if (event.key === "ArrowDown") item.z += step;
const validation = validateCargo(item, selectedIndex);
if (!validation.ok) {
item.x = oldX;
item.z = oldZ;
showToast(validation.reason, "bad");
return;
}
item.valid = true;
updateCargoInstances();
updateSelectionPanel();
});
// -------------------------------------------------------------------------
// UI bindings
// -------------------------------------------------------------------------
function updateRangeProgress(input) {
const min = Number(input.min);
const max = Number(input.max);
const value = Number(input.value);
const progress = ((value - min) / (max - min)) * 100;
input.style.setProperty("--range-progress", `${progress}%`);
}
function bindRange(
inputId,
outputId,
apply,
formatter,
needsRebuild = false
) {
const input = $(inputId);
const output = $(outputId);
const commit = () => {
output.textContent = formatter(Number(input.value));
updateRangeProgress(input);
apply(Number(input.value));
if (needsRebuild) rebuildHold();
clearTimeout(repackTimer);
repackTimer = setTimeout(() => autoPack(false), 140);
};
input.addEventListener("input", commit);
updateRangeProgress(input);
}
bindRange(
"lengthRange",
"lengthValue",
(value) => {
state.hold.length = value;
},
(value) => `${value.toFixed(1)} m`,
true
);
bindRange(
"beamRange",
"beamValue",
(value) => {
state.hold.beam = value;
},
(value) => `${value.toFixed(1)} m`,
true
);
bindRange(
"depthRange",
"depthValue",
(value) => {
state.hold.depth = value;
},
(value) => `${value.toFixed(1)} m`,
true
);
bindRange(
"clearanceRange",
"clearanceValue",
(value) => {
state.clearance = value;
},
(value) => `${value.toFixed(2)} m`,
true
);
$("staggerToggle").addEventListener("change", (event) => {
state.stagger = event.target.checked;
autoPack();
});
$("envelopeToggle").addEventListener("change", (event) => {
state.showEnvelopes = event.target.checked;
envelopeMesh.visible = state.showEnvelopes;
});
$("autoPackButton").addEventListener("click", () => autoPack());
$("addCargoButton").addEventListener("click", addCargo);
$("clearButton").addEventListener("click", clearHold);
$("rotateButton").addEventListener("click", rotateSelected);
$("layerDownButton").addEventListener("click", () =>
changeSelectedLayer(-1)
);
$("layerUpButton").addEventListener("click", () =>
changeSelectedLayer(1)
);
function setMode(mode) {
state.mode = mode;
$("arrangeMode").classList.toggle("active", mode === "arrange");
$("inspectMode").classList.toggle("active", mode === "inspect");
renderer.domElement.style.cursor =
mode === "inspect" ? "grab" : "default";
$("stageHelp").innerHTML =
mode === "arrange"
? "Drag a vessel to arrange · drag empty space to orbit · wheel to zoom · <kbd>R</kbd> rotate · arrows nudge"
: "Drag to orbit · wheel to zoom · use Arrange mode to move cargo";
if (mode === "inspect") {
selectCargo(-1);
}
}
$("arrangeMode").addEventListener("click", () => setMode("arrange"));
$("inspectMode").addEventListener("click", () => setMode("inspect"));
document.querySelectorAll("[data-view]").forEach((button) => {
button.addEventListener("click", () => {
setView(button.dataset.view);
});
});
// -------------------------------------------------------------------------
// Dimension labels and resizing
// -------------------------------------------------------------------------
function projectLabel(element, position) {
const projected = position.clone().project(camera);
const visible = projected.z >= -1 && projected.z <= 1;
element.style.display = visible ? "block" : "none";
if (!visible) return;
element.style.left = `${(projected.x * 0.5 + 0.5) * host.clientWidth}px`;
element.style.top = `${(-projected.y * 0.5 + 0.5) * host.clientHeight}px`;
}
function updateDimensionLabels() {
const { length, beam, depth } = state.hold;
projectLabel(
$("lengthLabel"),
new THREE.Vector3(0, 0.12, beam / 2 + 0.55)
);
projectLabel(
$("beamLabel"),
new THREE.Vector3(length / 2 + 0.55, 0.12, 0)
);
projectLabel(
$("depthLabel"),
new THREE.Vector3(-length / 2, depth / 2, beam / 2)
);
}
const resizeObserver = new ResizeObserver(() => {
const width = host.clientWidth;
const height = host.clientHeight;
if (!width || !height) return;
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
});
resizeObserver.observe(host);
// -------------------------------------------------------------------------
// Start
// -------------------------------------------------------------------------
rebuildHold();
setView("fit");
autoPack(false);
setMode("arrange");
function animate() {
requestAnimationFrame(animate);
updateCamera();
renderer.render(scene, camera);
updateDimensionLabels();
}
animate();
</script>
</body>
</html>
```