Prompt specification
Build or customize the Three.js 3D scene "Cargo Platform Balance Challenge" 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: Cargo Platform Balance Challenge
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/cargo-platform-balance-challenge-x3515
Scene Description Prompt:
Make a standalone HTML scene with Three.js from cdnjs that depicts center of mass and tipping stability. Build a fictional lift platform carrying movable crates with labeled masses. Require both total-load and center-of-mass constraints under an explicitly simplified game model. Voxel style.
Working Three.js Starter (cargo-platform-balance-challenge-x3515):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Balance Bay — Center-of-Mass Trainer</title>
<style>
:root {
--bg: #081018;
--panel: rgba(12, 21, 30, 0.9);
--panel-strong: rgba(16, 28, 39, 0.96);
--line: rgba(139, 170, 191, 0.22);
--text: #edf6fb;
--muted: #8da6b7;
--green: #5ee6a8;
--amber: #ffc857;
--red: #ff6470;
--cyan: #64d8ff;
--yellow: #ffe66d;
}
* { 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; }
#app {
position: fixed;
inset: 0;
isolation: isolate;
}
#scene {
display: block;
width: 100%;
height: 100%;
outline: none;
touch-action: none;
}
.topbar {
position: fixed;
z-index: 10;
top: 18px;
left: 20px;
right: 20px;
display: flex;
align-items: center;
justify-content: space-between;
pointer-events: none;
}
.brand {
display: flex;
align-items: center;
gap: 12px;
padding: 10px 14px 10px 10px;
border: 1px solid var(--line);
border-radius: 12px;
background: rgba(9, 17, 24, 0.82);
box-shadow: 0 12px 35px rgba(0, 0, 0, 0.22);
backdrop-filter: blur(14px);
pointer-events: auto;
}
.brand-mark {
display: grid;
place-items: center;
width: 42px;
height: 42px;
border-radius: 8px;
background: var(--yellow);
color: #17202a;
font-size: 25px;
font-weight: 900;
box-shadow: 0 0 25px rgba(255, 230, 109, 0.2);
}
.brand h1 {
margin: 0;
font-size: 18px;
line-height: 1;
letter-spacing: 0.08em;
}
.brand p {
margin: 5px 0 0;
color: var(--muted);
font: 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.11em;
text-transform: uppercase;
}
.status {
display: flex;
align-items: center;
gap: 9px;
min-width: 126px;
padding: 11px 15px;
border: 1px solid var(--line);
border-radius: 999px;
background: rgba(9, 17, 24, 0.86);
box-shadow: 0 12px 35px rgba(0, 0, 0, 0.22);
backdrop-filter: blur(14px);
pointer-events: auto;
font: 700 12px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.09em;
}
.status-dot {
width: 9px;
height: 9px;
border-radius: 2px;
background: var(--green);
box-shadow: 0 0 12px currentColor;
color: var(--green);
}
.status.stable { color: var(--green); }
.status.caution { color: var(--amber); }
.status.tipping,
.status.overload { color: var(--red); }
.status.caution .status-dot {
color: var(--amber);
background: var(--amber);
}
.status.tipping .status-dot,
.status.overload .status-dot {
color: var(--red);
background: var(--red);
animation: blink 0.65s steps(2) infinite;
}
@keyframes blink { 50% { opacity: 0.35; } }
.panel {
position: fixed;
z-index: 10;
width: 292px;
border: 1px solid var(--line);
border-radius: 13px;
background: var(--panel);
box-shadow: 0 20px 55px rgba(0, 0, 0, 0.28);
backdrop-filter: blur(16px);
overflow: hidden;
}
.panel::before {
content: "";
display: block;
height: 3px;
background: linear-gradient(90deg, var(--yellow), transparent 72%);
}
#stats {
top: 96px;
left: 20px;
}
#controls {
top: 96px;
right: 20px;
width: 276px;
}
.panel-inner { padding: 16px; }
.panel h2 {
margin: 0 0 13px;
font: 700 12px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.stat-line {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 12px;
margin-bottom: 9px;
}
.stat-line span {
color: var(--muted);
font: 600 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.08em;
}
.stat-line strong {
font: 700 15px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.bar {
height: 9px;
margin-bottom: 13px;
overflow: hidden;
border-radius: 3px;
background: #1d2a35;
box-shadow: inset 0 0 0 1px rgba(255,255,255,0.04);
}
.bar i {
display: block;
width: 0;
height: 100%;
background: var(--green);
transition: width 0.16s ease, background 0.16s ease;
}
.checks {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-bottom: 13px;
}
.check {
padding: 9px;
border: 1px solid var(--line);
border-radius: 7px;
background: rgba(255,255,255,0.025);
}
.check span {
display: block;
margin-bottom: 5px;
color: var(--muted);
font: 600 9px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.08em;
}
.check b {
color: var(--green);
font: 800 11px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.check b.fail { color: var(--red); }
.readouts {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-bottom: 11px;
}
.readout {
padding: 9px 10px;
border-left: 2px solid #344b5c;
background: rgba(255,255,255,0.025);
}
.readout span {
display: block;
margin-bottom: 5px;
color: var(--muted);
font: 600 9px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.08em;
}
.readout strong {
font: 700 12px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.balance-note {
padding: 10px;
border: 1px solid rgba(94, 230, 168, 0.22);
border-radius: 7px;
background: rgba(94, 230, 168, 0.06);
color: #b8d9c9;
font-size: 11px;
line-height: 1.45;
}
.balance-note.caution {
border-color: rgba(255, 200, 87, 0.3);
background: rgba(255, 200, 87, 0.07);
color: #e6d4a5;
}
.balance-note.tipping,
.balance-note.overload {
border-color: rgba(255, 100, 112, 0.35);
background: rgba(255, 100, 112, 0.08);
color: #efb4b9;
}
details {
margin-top: 13px;
padding-top: 12px;
border-top: 1px solid var(--line);
}
summary {
cursor: pointer;
color: #bed0dc;
font: 700 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.model-copy {
margin: 10px 0 0;
color: var(--muted);
font-size: 10.5px;
line-height: 1.55;
}
.model-copy strong { color: #d9e7ee; }
.selection {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
min-height: 45px;
margin-bottom: 12px;
padding: 10px;
border: 1px solid rgba(255,230,109,0.25);
border-radius: 7px;
background: rgba(255,230,109,0.045);
}
.selection span {
color: var(--muted);
font: 600 9px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.07em;
}
.selection strong {
display: block;
margin-top: 4px;
color: var(--yellow);
font: 800 14px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.dpad-wrap {
display: flex;
align-items: center;
justify-content: center;
gap: 13px;
margin: 13px 0 14px;
}
.dpad {
display: grid;
grid-template-columns: repeat(3, 39px);
grid-template-rows: repeat(3, 35px);
gap: 4px;
}
.dpad button,
.axis-note {
display: grid;
place-items: center;
border: 1px solid var(--line);
border-radius: 6px;
background: #182630;
color: #dceaf2;
cursor: pointer;
font: 800 13px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.dpad button:hover {
border-color: var(--yellow);
background: #25333e;
}
.dpad button:active { transform: translateY(1px); }
.dpad .up { grid-area: 1 / 2; }
.dpad .left { grid-area: 2 / 1; }
.dpad .center { grid-area: 2 / 2; color: #566d7d; }
.dpad .right { grid-area: 2 / 3; }
.dpad .down { grid-area: 3 / 2; }
.axis-note {
width: 54px;
height: 54px;
border-style: dashed;
color: var(--muted);
font-size: 9px;
text-align: center;
}
.button-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.action {
min-height: 38px;
padding: 9px 10px;
border: 1px solid var(--line);
border-radius: 7px;
background: #1a2934;
color: var(--text);
cursor: pointer;
font: 700 10px/1.1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.04em;
}
.action:hover:not(:disabled) {
border-color: #7fa4b9;
background: #233541;
}
.action.primary {
border-color: rgba(255,230,109,0.4);
background: rgba(255,230,109,0.12);
color: var(--yellow);
}
.action.danger:hover:not(:disabled) {
border-color: var(--red);
color: #ff9ba4;
}
.action:disabled {
cursor: not-allowed;
opacity: 0.35;
}
.wide { width: 100%; margin-top: 8px; }
.legend {
display: grid;
gap: 8px;
margin-top: 13px;
padding-top: 12px;
border-top: 1px solid var(--line);
}
.legend div {
display: flex;
align-items: center;
gap: 8px;
color: var(--muted);
font-size: 10px;
}
.swatch {
width: 11px;
height: 11px;
border-radius: 2px;
background: var(--yellow);
box-shadow: 0 0 10px rgba(255,230,109,0.25);
}
.swatch.support { background: var(--green); }
.swatch.warning { background: var(--amber); }
.bottom-hint {
position: fixed;
z-index: 8;
left: 50%;
bottom: 17px;
transform: translateX(-50%);
padding: 9px 13px;
border: 1px solid var(--line);
border-radius: 8px;
background: rgba(8, 16, 24, 0.82);
color: var(--muted);
font: 10px/1.4 ui-monospace, SFMono-Regular, Menlo, monospace;
text-align: center;
pointer-events: none;
white-space: nowrap;
}
.bottom-hint b { color: #dbe9f1; }
#toast {
position: fixed;
z-index: 30;
left: 50%;
bottom: 66px;
transform: translate(-50%, 12px);
padding: 10px 14px;
border: 1px solid rgba(255,230,109,0.35);
border-radius: 7px;
background: rgba(15, 25, 33, 0.96);
color: var(--yellow);
opacity: 0;
pointer-events: none;
font: 700 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
transition: opacity 0.16s ease, transform 0.16s ease;
}
#toast.visible {
opacity: 1;
transform: translate(-50%, 0);
}
#loading {
position: fixed;
z-index: 50;
inset: 0;
display: grid;
place-items: center;
background: var(--bg);
color: var(--yellow);
font: 700 12px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.12em;
}
@media (max-width: 760px) {
.topbar {
top: 10px;
left: 10px;
right: 10px;
}
.brand { padding: 8px; }
.brand-mark { width: 35px; height: 35px; }
.brand h1 { font-size: 14px; }
.brand p { font-size: 8px; }
.status { min-width: auto; padding: 10px; }
.status strong { display: none; }
#stats {
top: 69px;
left: 10px;
right: 10px;
width: auto;
max-height: 42vh;
overflow: auto;
}
#controls {
top: auto;
right: 10px;
bottom: 10px;
left: 10px;
width: auto;
max-height: 43vh;
overflow: auto;
}
.bottom-hint { display: none; }
.panel-inner { padding: 13px; }
}
</style>
</head>
<body>
<div id="app">
<canvas id="scene" aria-label="Interactive voxel lift balancing scene"></canvas>
<header class="topbar">
<div class="brand">
<div class="brand-mark">▦</div>
<div>
<h1>BALANCE BAY</h1>
<p>Center-of-mass trainer / Run 01</p>
</div>
</div>
<div id="statusChip" class="status stable" aria-live="polite">
<span class="status-dot"></span>
<strong id="statusText">STABLE</strong>
</div>
</header>
<section id="stats" class="panel">
<div class="panel-inner">
<h2>Load + Balance</h2>
<div class="stat-line">
<span>CARGO PAYLOAD</span>
<strong id="loadText">880 / 1200 KG</strong>
</div>
<div class="bar"><i id="loadBar"></i></div>
<div class="checks">
<div class="check">
<span>TOTAL LOAD</span>
<b id="loadCheck">PASS</b>
</div>
<div class="check">
<span>COM WINDOW</span>
<b id="comCheck">PASS</b>
</div>
</div>
<div class="readouts">
<div class="readout">
<span>SYSTEM COM X</span>
<strong id="comX">+0.22 m</strong>
</div>
<div class="readout">
<span>SYSTEM COM Z</span>
<strong id="comZ">+0.20 m</strong>
</div>
<div class="readout">
<span>EDGE MARGIN</span>
<strong id="comMargin">0.85 m</strong>
</div>
<div class="readout">
<span>SYSTEM MASS</span>
<strong id="systemMass">1230 kg</strong>
</div>
</div>
<div id="balanceNote" class="balance-note">
The projected system center of mass is inside the support footprint.
</div>
<details open>
<summary>Simplified game model</summary>
<div class="model-copy">
<strong>Goal:</strong> keep cargo at or below <strong>1,200 kg</strong>
and keep the combined system COM inside the green support polygon.<br /><br />
The unloaded rig has a fixed <strong>350 kg</strong> mass at the deck center.
System COM is calculated as
<strong>Σ(mass × position) ÷ Σmass</strong>.<br /><br />
Support limits are
<strong>|X| ≤ 1.75 m</strong> and
<strong>|Z| ≤ 1.05 m</strong>.
Less than 0.20 m of margin produces a caution.
Outside the polygon causes tipping.<br /><br />
This is a static balance model: acceleration, friction, dynamic load
transfer, and crate deformation are not simulated. Crates may not overlap.
</div>
</details>
</div>
</section>
<section id="controls" class="panel">
<div class="panel-inner">
<h2>Crate Handler</h2>
<div class="selection">
<span>SELECTED CRATE</span>
<strong id="selectedName">CRATE A</strong>
</div>
<div class="dpad-wrap">
<div class="dpad" aria-label="Crate movement controls">
<button class="up" data-move="0,-0.35" title="Move toward negative Z">↑</button>
<button class="left" data-move="-0.35,0" title="Move toward negative X">←</button>
<button class="center" disabled>•</button>
<button class="right" data-move="0.35,0" title="Move toward positive X">→</button>
<button class="down" data-move="0,0.35" title="Move toward positive Z">↓</button>
</div>
<div class="axis-note">DECK<br />X / Z</div>
</div>
<div class="button-row">
<button id="addCrate" class="action primary">ADD 160 KG</button>
<button id="removeCrate" class="action danger">REMOVE</button>
</div>
<button id="resetRun" class="action wide">RESET CARGO</button>
<button id="resetCamera" class="action wide">RESET CAMERA</button>
<div class="legend">
<div><span class="swatch"></span> Combined system center of mass</div>
<div><span class="swatch support"></span> Valid support footprint</div>
<div><span class="swatch warning"></span> Caution margin</div>
</div>
</div>
</section>
<div class="bottom-hint">
<b>Drag crates</b> to reposition · <b>Drag empty space</b> to orbit ·
<b>Scroll</b> to zoom · <b>Arrow keys</b> nudge
</div>
<div id="toast" role="status"></div>
<div id="loading">LOADING VOXEL LIFT…</div>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const $ = id => document.getElementById(id);
const canvas = $("scene");
// -------------------------------------------------------------------------
// Simplified static balance model
// -------------------------------------------------------------------------
const MODEL = Object.freeze({
cargoLimit: 1200,
platformMass: 350,
supportX: 1.75,
supportZ: 1.05,
warningMargin: 0.20,
deckWidth: 6.4,
deckDepth: 4.2,
deckThickness: 0.28,
deckY: 2.45,
crateSize: 1.0,
crateHeight: 0.88,
addMass: 160
});
const CRATE_Y = MODEL.deckThickness / 2 + MODEL.crateHeight / 2;
const MAX_CRATE_X = MODEL.deckWidth / 2 - MODEL.crateSize / 2 - 0.10;
const MAX_CRATE_Z = MODEL.deckDepth / 2 - MODEL.crateSize / 2 - 0.10;
const state = {
crates: [],
crateBodies: [],
selected: null,
nextCrate: 1,
metrics: null
};
// -------------------------------------------------------------------------
// Renderer, scene, and lighting
// -------------------------------------------------------------------------
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight, false);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x081018);
scene.fog = new THREE.Fog(0x081018, 18, 46);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
100
);
const cameraState = {
yaw: 0.72,
pitch: 0.48,
distance: 13.2,
target: new THREE.Vector3(0, 2.0, 0)
};
function applyCamera() {
const cp = Math.cos(cameraState.pitch);
const sp = Math.sin(cameraState.pitch);
const cy = Math.cos(cameraState.yaw);
const sy = Math.sin(cameraState.yaw);
camera.position.set(
cameraState.target.x + cameraState.distance * cp * sy,
cameraState.target.y + cameraState.distance * sp,
cameraState.target.z + cameraState.distance * cp * cy
);
camera.lookAt(cameraState.target);
}
applyCamera();
const hemisphere = new THREE.HemisphereLight(0xb9dcff, 0x18202a, 1.55);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xfff1cf, 3.3);
keyLight.position.set(7, 13, 6);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -12;
keyLight.shadow.camera.right = 12;
keyLight.shadow.camera.top = 12;
keyLight.shadow.camera.bottom = -12;
keyLight.shadow.camera.near = 0.5;
keyLight.shadow.camera.far = 35;
keyLight.shadow.bias = -0.0004;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x4aaeff, 1.15);
rimLight.position.set(-8, 6, -7);
scene.add(rimLight);
function standardMaterial(color, options = {}) {
return new THREE.MeshStandardMaterial({
color,
roughness: 0.82,
metalness: 0.05,
...options
});
}
function addBox(parent, w, h, d, material, x = 0, y = 0, z = 0) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(w, h, d),
material
);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
// -------------------------------------------------------------------------
// Voxel environment
// -------------------------------------------------------------------------
const groundMat = standardMaterial(0x101b24);
const ground = addBox(scene, 80, 0.12, 80, groundMat, 0, -0.08, 0);
ground.castShadow = false;
const grid = new THREE.GridHelper(60, 60, 0x284152, 0x162630);
grid.position.y = 0.005;
scene.add(grid);
function pseudoRandom(index) {
const value = Math.sin(index * 127.1 + 311.7) * 43758.5453;
return value - Math.floor(value);
}
const buildingMaterials = [
standardMaterial(0x172530),
standardMaterial(0x1b2b37),
standardMaterial(0x20323d),
standardMaterial(0x25343f)
];
const windowMat = standardMaterial(0x3c7187, {
emissive: 0x19495c,
emissiveIntensity: 0.65,
roughness: 0.45
});
for (let i = 0; i < 22; i++) {
const x = -18 + pseudoRandom(i + 4) * 36;
const z = -13 - pseudoRandom(i + 30) * 12;
const width = 1.3 + pseudoRandom(i + 60) * 2.4;
const depth = 1.3 + pseudoRandom(i + 90) * 2.1;
const height = 2.0 + pseudoRandom(i + 120) * 7.0;
addBox(
scene,
width,
height,
depth,
buildingMaterials[i % buildingMaterials.length],
x,
height / 2,
z
);
const cap = addBox(
scene,
width * 0.45,
0.35 + pseudoRandom(i + 150) * 0.7,
depth * 0.45,
buildingMaterials[(i + 1) % buildingMaterials.length],
x,
height + 0.3,
z
);
cap.castShadow = false;
if (i % 2 === 0) {
for (let j = 0; j < 3; j++) {
addBox(
scene,
0.12,
0.22,
0.04,
windowMat,
x - width * 0.25 + j * width * 0.25,
height * (0.45 + j * 0.12),
z + depth / 2 + 0.025
);
}
}
}
const baseMat = standardMaterial(0x293640);
const darkMetal = standardMaterial(0x18242d, {
metalness: 0.28,
roughness: 0.55
});
const steelMat = standardMaterial(0x60717c, {
metalness: 0.45,
roughness: 0.4
});
const yellowMat = standardMaterial(0xe0b847);
const blackMat = standardMaterial(0x111a20);
// Base and outrigger feet.
addBox(scene, 4.0, 0.42, 2.55, baseMat, 0, 0.23, 0);
addBox(scene, 3.3, 0.24, 1.9, darkMetal, 0, 0.52, 0);
for (const x of [-MODEL.supportX, MODEL.supportX]) {
for (const z of [-MODEL.supportZ, MODEL.supportZ]) {
addBox(scene, 0.66, 0.16, 0.56, blackMat, x, 0.08, z);
addBox(scene, 0.48, 0.08, 0.38, steelMat, x, 0.19, z);
}
}
// Central lift column.
addBox(scene, 0.88, 1.65, 0.88, darkMetal, 0, 1.12, 0);
addBox(scene, 0.58, 0.55, 0.58, steelMat, 0, 1.42, 0);
addBox(scene, 1.42, 0.20, 1.35, baseMat, 0, 1.98, 0);
// Voxel scissor braces.
const braceA = addBox(scene, 0.18, 2.45, 0.20, steelMat, -0.63, 1.19, 0.82);
braceA.rotation.z = -0.43;
const braceB = addBox(scene, 0.18, 2.45, 0.20, steelMat, 0.63, 1.19, 0.82);
braceB.rotation.z = 0.43;
const braceC = addBox(scene, 0.20, 2.25, 0.18, steelMat, -0.72, 1.14, -0.72);
braceC.rotation.x = 0.40;
const braceD = addBox(scene, 0.20, 2.25, 0.18, steelMat, 0.72, 1.14, -0.72);
braceD.rotation.x = -0.40;
const beaconMat = standardMaterial(0x5a4520, {
emissive: 0x281b08,
emissiveIntensity: 0.8
});
for (const x of [-MODEL.supportX, MODEL.supportX]) {
for (const z of [-MODEL.supportZ, MODEL.supportZ]) {
addBox(scene, 0.16, 0.12, 0.16, beaconMat, x, 0.68, z);
}
}
// -------------------------------------------------------------------------
// Lift deck
// -------------------------------------------------------------------------
const deckAssembly = new THREE.Group();
deckAssembly.position.y = MODEL.deckY;
scene.add(deckAssembly);
const deckMat = standardMaterial(0x46525d);
const deckTopMat = standardMaterial(0x303d47);
const deckEdgeMat = standardMaterial(0x697985);
addBox(
deckAssembly,
MODEL.deckWidth,
MODEL.deckThickness,
MODEL.deckDepth,
deckMat
);
addBox(
deckAssembly,
MODEL.deckWidth - 0.18,
0.035,
MODEL.deckDepth - 0.18,
deckTopMat,
0,
MODEL.deckThickness / 2 + 0.018,
0
);
// Voxel edge rails and hazard blocks.
for (const z of [-MODEL.deckDepth / 2 + 0.08, MODEL.deckDepth / 2 - 0.08]) {
addBox(
deckAssembly,
MODEL.deckWidth - 0.3,
0.09,
0.10,
deckEdgeMat,
0,
MODEL.deckThickness / 2 + 0.08,
z
);
}
for (const x of [-MODEL.deckWidth / 2 + 0.08, MODEL.deckWidth / 2 - 0.08]) {
addBox(
deckAssembly,
0.10,
0.09,
MODEL.deckDepth - 0.3,
deckEdgeMat,
x,
MODEL.deckThickness / 2 + 0.08,
0
);
}
for (let i = 0; i < 12; i++) {
addBox(
deckAssembly,
0.28,
0.045,
0.11,
i % 2 === 0 ? yellowMat : blackMat,
-MODEL.deckWidth / 2 + 0.38 + i * 0.49,
MODEL.deckThickness / 2 + 0.045,
MODEL.deckDepth / 2 - 0.035
);
}
// Deck grid.
const deckGridVertices = [];
const deckGridY = MODEL.deckThickness / 2 + 0.042;
for (let x = -2.4; x <= 2.41; x += 0.6) {
deckGridVertices.push(
x, deckGridY, -MODEL.deckDepth / 2 + 0.18,
x, deckGridY, MODEL.deckDepth / 2 - 0.18
);
}
for (let z = -1.8; z <= 1.81; z += 0.6) {
deckGridVertices.push(
-MODEL.deckWidth / 2 + 0.18, deckGridY, z,
MODEL.deckWidth / 2 - 0.18, deckGridY, z
);
}
const deckGridGeometry = new THREE.BufferGeometry();
deckGridGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(deckGridVertices, 3)
);
deckAssembly.add(
new THREE.LineSegments(
deckGridGeometry,
new THREE.LineBasicMaterial({
color: 0x5d6b75,
transparent: true,
opacity: 0.32
})
)
);
function rectangleLine(x, z, y, color, dashed = false) {
const points = [
new THREE.Vector3(-x, y, -z),
new THREE.Vector3(x, y, -z),
new THREE.Vector3(x, y, z),
new THREE.Vector3(-x, y, z),
new THREE.Vector3(-x, y, -z)
];
const geometry = new THREE.BufferGeometry().setFromPoints(points);
const material = dashed
? new THREE.LineDashedMaterial({
color,
dashSize: 0.16,
gapSize: 0.11,
transparent: true,
opacity: 0.85
})
: new THREE.LineBasicMaterial({ color });
const line = new THREE.Line(geometry, material);
if (dashed) line.computeLineDistances();
deckAssembly.add(line);
return line;
}
const supportLine = rectangleLine(
MODEL.supportX,
MODEL.supportZ,
MODEL.deckThickness / 2 + 0.065,
0x5ee6a8
);
const warningLine = rectangleLine(
MODEL.supportX - MODEL.warningMargin,
MODEL.supportZ - MODEL.warningMargin,
MODEL.deckThickness / 2 + 0.068,
0xffc857,
true
);
// -------------------------------------------------------------------------
// Crates
// -------------------------------------------------------------------------
const cratePalette = [
0xd9824a,
0x4ca6a0,
0x5d7ed8,
0xd8b84e,
0xa06bb8,
0xca626d
];
const bandMaterial = standardMaterial(0x27343d, {
roughness: 0.65
});
function createMassLabel(id, mass, color) {
const labelCanvas = document.createElement("canvas");
labelCanvas.width = 256;
labelCanvas.height = 96;
const context = labelCanvas.getContext("2d");
context.clearRect(0, 0, 256, 96);
context.fillStyle = "rgba(9, 17, 24, 0.94)";
context.fillRect(4, 4, 248, 88);
context.strokeStyle = `#${color.toString(16).padStart(6, "0")}`;
context.lineWidth = 5;
context.strokeRect(5, 5, 246, 86);
context.fillStyle = "#f5fbff";
context.font = "700 39px monospace";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(`${id} ${mass} kg`, 128, 49);
const texture = new THREE.CanvasTexture(labelCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
const sprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
})
);
sprite.scale.set(1.36, 0.51, 1);
sprite.renderOrder = 20;
return sprite;
}
function createCrate(id, mass, x, z, color) {
const group = new THREE.Group();
group.position.set(x, CRATE_Y, z);
deckAssembly.add(group);
const crate = {
id,
mass,
color,
group
};
const bodyMaterial = standardMaterial(color, {
emissive: 0x000000,
emissiveIntensity: 0
});
const body = addBox(
group,
MODEL.crateSize,
MODEL.crateHeight,
MODEL.crateSize,
bodyMaterial
);
body.userData.crate = crate;
state.crateBodies.push(body);
crate.body = body;
// Four voxel corner posts.
for (const postX of [-0.43, 0.43]) {
for (const postZ of [-0.43, 0.43]) {
addBox(
group,
0.12,
MODEL.crateHeight + 0.04,
0.12,
bandMaterial,
postX,
0,
postZ
);
}
}
// Front and back reinforcement rails.
for (const faceZ of [-0.515, 0.515]) {
for (const railY of [-0.29, 0.29]) {
addBox(
group,
0.96,
0.075,
0.045,
bandMaterial,
0,
railY,
faceZ
);
}
}
// Side reinforcement rails.
for (const faceX of [-0.515, 0.515]) {
for (const railY of [-0.29, 0.29]) {
addBox(
group,
0.045,
0.075,
0.96,
bandMaterial,
faceX,
railY,
0
);
}
}
// Top straps.
for (const strapX of [-0.29, 0.29]) {
addBox(
group,
0.075,
0.045,
0.98,
bandMaterial,
strapX,
MODEL.crateHeight / 2 + 0.025,
0
);
}
const edges = new THREE.LineSegments(
new THREE.EdgesGeometry(body.geometry),
new THREE.LineBasicMaterial({ color: 0x16212a })
);
group.add(edges);
crate.edges = edges;
const label = createMassLabel(id, mass, color);
label.position.set(0, MODEL.crateHeight / 2 + 0.40, 0);
group.add(label);
crate.label = label;
state.crates.push(crate);
return crate;
}
function updateCrateSelectionVisuals() {
for (const crate of state.crates) {
const selected = crate === state.selected;
crate.edges.material.color.setHex(selected ? 0xffe66d : 0x16212a);
crate.body.material.emissive.setHex(selected ? 0x392b08 : 0x000000);
crate.body.material.emissiveIntensity = selected ? 0.6 : 0;
crate.label.scale.set(selected ? 1.52 : 1.36, selected ? 0.57 : 0.51, 1);
}
}
function selectCrate(crate) {
state.selected = crate;
updateCrateSelectionVisuals();
updateUI();
}
function removeCrate(crate) {
const bodyIndex = state.crateBodies.indexOf(crate.body);
if (bodyIndex !== -1) state.crateBodies.splice(bodyIndex, 1);
const crateIndex = state.crates.indexOf(crate);
if (crateIndex !== -1) state.crates.splice(crateIndex, 1);
deckAssembly.remove(crate.group);
if (state.selected === crate) {
state.selected = state.crates[0] || null;
}
updateCrateSelectionVisuals();
updateSimulation();
}
// -------------------------------------------------------------------------
// Center-of-mass visualization
// -------------------------------------------------------------------------
const comMarkerMaterial = standardMaterial(0xffe66d, {
emissive: 0x8b6c00,
emissiveIntensity: 1.1,
roughness: 0.35
});
const comMarker = addBox(
deckAssembly,
0.17,
0.17,
0.17,
comMarkerMaterial
);
const beamGeometry = new THREE.BufferGeometry();
beamGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(new Float32Array(6), 3)
);
const comBeam = new THREE.Line(
beamGeometry,
new THREE.LineBasicMaterial({
color: 0xffe66d,
transparent: true,
opacity: 0.9
})
);
deckAssembly.add(comBeam);
const projectionGeometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(-0.17, 0, -0.17),
new THREE.Vector3(0.17, 0, -0.17),
new THREE.Vector3(0.17, 0, 0.17),
new THREE.Vector3(-0.17, 0, 0.17)
]);
const comProjection = new THREE.LineLoop(
projectionGeometry,
new THREE.LineBasicMaterial({ color: 0xffe66d })
);
deckAssembly.add(comProjection);
function calculateMetrics() {
let cargoMass = 0;
let momentX = 0;
let momentZ = 0;
for (const crate of state.crates) {
cargoMass += crate.mass;
momentX += crate.mass * crate.group.position.x;
momentZ += crate.mass * crate.group.position.z;
}
const totalMass = cargoMass + MODEL.platformMass;
const comX = totalMass > 0 ? momentX / totalMass : 0;
const comZ = totalMass > 0 ? momentZ / totalMass : 0;
const comY =
(MODEL.platformMass * MODEL.deckY +
cargoMass * (MODEL.deckY + CRATE_Y)) /
totalMass;
const margin = Math.min(
MODEL.supportX - Math.abs(comX),
MODEL.supportZ - Math.abs(comZ)
);
const loadViolation = cargoMass > MODEL.cargoLimit;
const comViolation = margin < 0;
const caution = !comViolation && margin < MODEL.warningMargin;
return {
cargoMass,
totalMass,
comX,
comY,
comZ,
margin,
loadViolation,
comViolation,
caution,
stable: !loadViolation && !comViolation && !caution
};
}
function updateCOMVisuals() {
const metrics = state.metrics;
const localY = metrics.comY - MODEL.deckY;
comMarker.position.set(metrics.comX, localY, metrics.comZ);
comProjection.position.set(
metrics.comX,
MODEL.deckThickness / 2 + 0.075,
metrics.comZ
);
const beamPositions = beamGeometry.attributes.position.array;
beamPositions[0] = metrics.comX;
beamPositions[1] = MODEL.deckThickness / 2 + 0.075;
beamPositions[2] = metrics.comZ;
beamPositions[3] = metrics.comX;
beamPositions[4] = localY;
beamPositions[5] = metrics.comZ;
beamGeometry.attributes.position.needsUpdate = true;
let statusColor = 0x5ee6a8;
if (metrics.loadViolation || metrics.comViolation) statusColor = 0xff6470;
else if (metrics.caution) statusColor = 0xffc857;
comMarkerMaterial.color.setHex(statusColor);
comMarkerMaterial.emissive.setHex(statusColor);
comBeam.material.color.setHex(statusColor);
comProjection.material.color.setHex(statusColor);
supportLine.material.color.setHex(statusColor);
warningLine.material.color.setHex(
metrics.comViolation ? 0xff6470 : 0xffc857
);
beaconMat.color.setHex(statusColor);
beaconMat.emissive.setHex(statusColor);
beaconMat.emissiveIntensity = metrics.comViolation ? 1.8 : 0.65;
}
// -------------------------------------------------------------------------
// UI
// -------------------------------------------------------------------------
let toastTimer = 0;
function showToast(message) {
const toast = $("toast");
toast.textContent = message;
toast.classList.add("visible");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => toast.classList.remove("visible"), 1400);
}
function formatSigned(value) {
return `${value >= 0 ? "+" : ""}${value.toFixed(2)} m`;
}
function updateUI() {
const metrics = state.metrics;
if (!metrics) return;
const status = metrics.loadViolation
? "overload"
: metrics.comViolation
? "tipping"
: metrics.caution
? "caution"
: "stable";
const statusText = metrics.loadViolation
? "OVER LOAD"
: metrics.comViolation
? "TIPPING"
: metrics.caution
? "CAUTION"
: "STABLE";
$("statusChip").className = `status ${status}`;
$("statusText").textContent = statusText;
$("loadText").textContent =
`${metrics.cargoMass} / ${MODEL.cargoLimit} KG`;
const loadPercent = Math.min(
100,
(metrics.cargoMass / MODEL.cargoLimit) * 100
);
$("loadBar").style.width = `${loadPercent}%`;
$("loadBar").style.background =
metrics.loadViolation ? "var(--red)" :
loadPercent > 85 ? "var(--amber)" :
"var(--green)";
$("loadCheck").textContent = metrics.loadViolation ? "FAIL" : "PASS";
$("loadCheck").classList.toggle("fail", metrics.loadViolation);
$("comCheck").textContent = metrics.comViolation ? "FAIL" : "PASS";
$("comCheck").classList.toggle("fail", metrics.comViolation);
$("comX").textContent = formatSigned(metrics.comX);
$("comZ").textContent = formatSigned(metrics.comZ);
$("comMargin").textContent =
metrics.margin < 0
? `${Math.abs(metrics.margin).toFixed(2)} m outside`
: `${metrics.margin.toFixed(2)} m`;
$("systemMass").textContent = `${Math.round(metrics.totalMass)} kg`;
const note = $("balanceNote");
note.className = "balance-note";
if (metrics.loadViolation) {
note.classList.add("overload");
note.textContent = "Payload limit exceeded. Remove cargo before continuing.";
} else if (metrics.comViolation) {
note.classList.add("tipping");
note.textContent =
"The system COM has left the support footprint. The lift is tipping.";
} else if (metrics.caution) {
note.classList.add("caution");
note.textContent =
"COM is inside the support polygon but within the 0.20 m caution margin.";
} else {
note.textContent =
"The projected system center of mass is safely inside the support footprint.";
}
$("selectedName").textContent = state.selected
? `${state.selected.id} · ${state.selected.mass} KG`
: "NO CRATE";
$("removeCrate").disabled = !state.selected;
$("addCrate").disabled =
metrics.cargoMass + MODEL.addMass > MODEL.cargoLimit;
}
function updateSimulation() {
state.metrics = calculateMetrics();
updateCOMVisuals();
updateUI();
}
// -------------------------------------------------------------------------
// Crate placement and movement
// -------------------------------------------------------------------------
function crateOverlaps(x, z, ignoredCrate = null) {
return state.crates.some(crate => {
if (crate === ignoredCrate) return false;
return (
Math.abs(crate.group.position.x - x) < 1.04 &&
Math.abs(crate.group.position.z - z) < 1.04
);
});
}
function moveCrate(crate, x, z) {
if (!crate) return false;
const clampedX = THREE.MathUtils.clamp(x, -MAX_CRATE_X, MAX_CRATE_X);
const clampedZ = THREE.MathUtils.clamp(z, -MAX_CRATE_Z, MAX_CRATE_Z);
if (crateOverlaps(clampedX, clampedZ, crate)) {
showToast("Movement blocked: crate footprints cannot overlap.");
return false;
}
crate.group.position.x = clampedX;
crate.group.position.z = clampedZ;
updateSimulation();
return true;
}
function moveSelected(dx, dz) {
if (!state.selected) return;
moveCrate(
state.selected,
state.selected.group.position.x + dx,
state.selected.group.position.z + dz
);
}
function findFreeSpot() {
const candidates = [];
for (let z = -1.35; z <= 1.36; z += 1.08) {
for (let x = -2.35; x <= 2.36; x += 1.08) {
candidates.push({ x, z });
}
}
candidates.sort((a, b) => {
const aDistance = Math.abs(a.x) + Math.abs(a.z);
const bDistance = Math.abs(b.x) + Math.abs(b.z);
return aDistance - bDistance;
});
return candidates.find(p => !crateOverlaps(p.x, p.z)) || null;
}
function addCrate() {
const currentMass = state.metrics.cargoMass;
if (currentMass + MODEL.addMass > MODEL.cargoLimit) {
showToast("Cannot add: the 1,200 kg payload limit would be exceeded.");
return;
}
const spot = findFreeSpot();
if (!spot) {
showToast("No free crate position on the deck.");
return;
}
const id = String.fromCharCode(64 + state.nextCrate++);
const color = cratePalette[(state.nextCrate - 2) % cratePalette.length];
const crate = createCrate(id, MODEL.addMass, spot.x, spot.z, color);
selectCrate(crate);
updateSimulation();
showToast(`${id} added: ${MODEL.addMass} kg.`);
}
function resetCargo() {
for (const crate of [...state.crates]) {
removeCrate(crate);
}
state.nextCrate = 1;
state.crates.length = 0;
state.crateBodies.length = 0;
createCrate("A", 280, -2.15, 0.75, cratePalette[0]);
createCrate("B", 360, 2.15, -0.75, cratePalette[1]);
createCrate("C", 240, 0.40, 1.25, cratePalette[2]);
state.selected = state.crates[0];
updateCrateSelectionVisuals();
updateSimulation();
showToast("Cargo layout reset.");
}
$("addCrate").addEventListener("click", addCrate);
$("removeCrate").addEventListener("click", () => {
if (!state.selected) return;
const removed = state.selected;
removeCrate(removed);
showToast(`${removed.id} removed.`);
});
$("resetRun").addEventListener("click", resetCargo);
$("resetCamera").addEventListener("click", () => {
cameraState.yaw = 0.72;
cameraState.pitch = 0.48;
cameraState.distance = 13.2;
cameraState.target.set(0, 2.0, 0);
applyCamera();
});
document.querySelectorAll("[data-move]").forEach(button => {
button.addEventListener("click", () => {
const [dx, dz] = button.dataset.move.split(",").map(Number);
moveSelected(dx, dz);
});
});
window.addEventListener("keydown", event => {
if (!state.selected) return;
const step = event.shiftKey ? 0.50 : 0.18;
if (event.key === "ArrowLeft") {
event.preventDefault();
moveSelected(-step, 0);
} else if (event.key === "ArrowRight") {
event.preventDefault();
moveSelected(step, 0);
} else if (event.key === "ArrowUp") {
event.preventDefault();
moveSelected(0, -step);
} else if (event.key === "ArrowDown") {
event.preventDefault();
moveSelected(0, step);
} else if (event.key === "Delete" || event.key === "Backspace") {
event.preventDefault();
const removed = state.selected;
removeCrate(removed);
showToast(`${removed.id} removed.`);
}
});
// -------------------------------------------------------------------------
// Custom camera and pointer interaction
// -------------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const dragPlane = new THREE.Plane();
const dragPoint = new THREE.Vector3();
const dragOffset = new THREE.Vector2();
let draggingCrate = false;
let orbiting = false;
let lastPointerX = 0;
let lastPointerY = 0;
function setPointer(event) {
const rect = canvas.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
}
canvas.addEventListener("pointerdown", event => {
if (event.button !== 0) return;
setPointer(event);
scene.updateMatrixWorld(true);
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObjects(state.crateBodies, false);
if (hits.length > 0) {
const crate = hits[0].object.userData.crate;
selectCrate(crate);
draggingCrate = true;
const deckNormal = new THREE.Vector3(0, 1, 0)
.applyQuaternion(deckAssembly.quaternion)
.normalize();
const crateWorldPosition = crate.group.getWorldPosition(
new THREE.Vector3()
);
dragPlane.setFromNormalAndCoplanarPoint(
deckNormal,
crateWorldPosition
);
raycaster.ray.intersectPlane(dragPlane, dragPoint);
const localPoint = deckAssembly.worldToLocal(dragPoint.clone());
dragOffset.set(
crate.group.position.x - localPoint.x,
crate.group.position.z - localPoint.z
);
canvas.style.cursor = "grabbing";
} else {
orbiting = true;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
canvas.style.cursor = "grabbing";
}
canvas.setPointerCapture(event.pointerId);
event.preventDefault();
});
canvas.addEventListener("pointermove", event => {
setPointer(event);
raycaster.setFromCamera(pointer, camera);
if (draggingCrate && state.selected) {
deckAssembly.updateMatrixWorld(true);
if (raycaster.ray.intersectPlane(dragPlane, dragPoint)) {
const localPoint = deckAssembly.worldToLocal(dragPoint.clone());
moveCrate(
state.selected,
localPoint.x + dragOffset.x,
localPoint.z + dragOffset.z
);
}
event.preventDefault();
} else if (orbiting) {
const dx = event.clientX - lastPointerX;
const dy = event.clientY - lastPointerY;
cameraState.yaw -= dx * 0.006;
cameraState.pitch = THREE.MathUtils.clamp(
cameraState.pitch + dy * 0.005,
0.18,
1.25
);
lastPointerX = event.clientX;
lastPointerY = event.clientY;
applyCamera();
event.preventDefault();
}
});
function endPointerInteraction(event) {
draggingCrate = false;
orbiting = false;
canvas.style.cursor = "default";
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
}
canvas.addEventListener("pointerup", endPointerInteraction);
canvas.addEventListener("pointercancel", endPointerInteraction);
canvas.addEventListener(
"wheel",
event => {
cameraState.distance = THREE.MathUtils.clamp(
cameraState.distance * Math.exp(event.deltaY * 0.001),
7,
22
);
applyCamera();
event.preventDefault();
},
{ passive: false }
);
// -------------------------------------------------------------------------
// Resize and animation
// -------------------------------------------------------------------------
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
camera.aspect = width / height;
camera.updateProjectionMatrix();
renderer.setSize(width, height, false);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
}
window.addEventListener("resize", resize);
resetCargo();
const clock = new THREE.Clock();
function animate() {
const elapsed = clock.getElapsedTime();
const metrics = state.metrics;
// Small visual lean makes an active tipping violation immediately readable.
let targetRotationX = 0;
let targetRotationZ = 0;
if (metrics.comViolation) {
const xExcess = Math.max(
0,
Math.abs(metrics.comX) - MODEL.supportX
);
const zExcess = Math.max(
0,
Math.abs(metrics.comZ) - MODEL.supportZ
);
targetRotationZ =
-Math.sign(metrics.comX) * Math.min(0.14, xExcess * 0.72);
targetRotationX =
Math.sign(metrics.comZ) * Math.min(0.10, zExcess * 0.65);
}
deckAssembly.rotation.x +=
(targetRotationX - deckAssembly.rotation.x) * 0.075;
deckAssembly.rotation.z +=
(targetRotationZ - deckAssembly.rotation.z) * 0.075;
const pulse = 1 + Math.sin(elapsed * 4.5) * 0.075;
comMarker.scale.setScalar(pulse);
renderer.render(scene, camera);
}
renderer.setAnimationLoop(animate);
$("loading").style.display = "none";
</script>
</body>
</html>
```