Prompt specification
Build or customize the Three.js 3D scene "Lunchbox packing station" 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: Lunchbox packing station
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/lunchbox-packing-station-x0151
Scene Description Prompt:
Lunchbox packing station. Arrange divided lunchboxes with sandwich halves, fruit, and reusable cups; users place items into compartments while the lid visibly tests whether the chosen heights fit. Please build this with Three.js from cdnjs in one self-contained HTML file, using visible voxel blocks.
Working Three.js Starter (lunchbox-packing-station-x0151):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pack Lab — Voxel Lunchbox Station</title>
<style>
:root {
--ink: #26352f;
--muted: #6f7972;
--paper: #f8f5ed;
--mint: #8fc6a3;
--coral: #f28e79;
--mustard: #f2c35b;
--shadow: 0 12px 32px rgba(46, 57, 49, 0.13);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #e8e4da;
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
button {
font: inherit;
}
#scene {
position: fixed;
inset: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
outline: none;
}
.ui {
position: fixed;
inset: 0;
pointer-events: none;
}
.panel,
button,
.item-card {
pointer-events: auto;
}
.header {
position: absolute;
top: 20px;
left: 22px;
display: flex;
align-items: center;
gap: 13px;
padding: 11px 15px 11px 11px;
border: 1px solid rgba(67, 79, 70, 0.1);
border-radius: 16px;
background: rgba(248, 245, 237, 0.92);
box-shadow: var(--shadow);
backdrop-filter: blur(12px);
}
.brand-mark {
position: relative;
width: 43px;
height: 43px;
border-radius: 10px;
background: #30473d;
overflow: hidden;
}
.brand-mark i {
position: absolute;
display: block;
width: 9px;
height: 9px;
background: var(--mint);
box-shadow:
11px 0 var(--mustard),
22px 0 var(--coral),
0 11px var(--coral),
11px 11px var(--mint),
22px 11px var(--mustard),
0 22px var(--mustard),
11px 22px var(--coral),
22px 22px var(--mint);
}
.brand-mark i {
left: 6px;
top: 5px;
}
.brand h1 {
margin: 0;
font-size: 17px;
line-height: 1;
letter-spacing: 0.08em;
}
.brand p {
margin: 5px 0 0;
color: var(--muted);
font-size: 11px;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.box-tabs {
position: absolute;
top: 24px;
left: 50%;
display: flex;
gap: 7px;
transform: translateX(-50%);
padding: 6px;
border: 1px solid rgba(67, 79, 70, 0.1);
border-radius: 14px;
background: rgba(248, 245, 237, 0.9);
box-shadow: var(--shadow);
backdrop-filter: blur(12px);
}
.box-tab {
min-width: 116px;
padding: 9px 12px;
border: 0;
border-radius: 10px;
background: transparent;
color: var(--ink);
text-align: left;
cursor: pointer;
transition: background 160ms ease, transform 160ms ease;
}
.box-tab:hover {
transform: translateY(-1px);
background: rgba(38, 53, 47, 0.05);
}
.box-tab.active {
background: #30473d;
color: white;
}
.tab-name {
display: flex;
align-items: center;
gap: 7px;
font-size: 12px;
font-weight: 750;
}
.tab-dot {
width: 10px;
height: 10px;
border-radius: 3px;
background: var(--mint);
}
.tab-meta {
display: block;
margin-top: 3px;
color: var(--muted);
font-size: 10px;
}
.box-tab.active .tab-meta {
color: rgba(255, 255, 255, 0.68);
}
.inventory {
position: absolute;
top: 92px;
right: 20px;
width: 296px;
max-height: calc(100vh - 116px);
padding: 17px;
overflow: auto;
border: 1px solid rgba(67, 79, 70, 0.1);
border-radius: 18px;
background: rgba(248, 245, 237, 0.94);
box-shadow: var(--shadow);
backdrop-filter: blur(14px);
}
.eyebrow {
margin: 0 0 5px;
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.14em;
text-transform: uppercase;
}
.inventory h2 {
margin: 0;
font-size: 21px;
letter-spacing: -0.03em;
}
.inventory > p {
margin: 6px 0 14px;
color: var(--muted);
font-size: 12px;
line-height: 1.45;
}
.item-list {
display: grid;
gap: 8px;
}
.item-card {
position: relative;
display: grid;
grid-template-columns: 54px 1fr auto;
align-items: center;
gap: 11px;
width: 100%;
min-height: 68px;
padding: 8px 10px 8px 7px;
border: 1px solid rgba(48, 71, 61, 0.12);
border-radius: 13px;
background: #fffdf8;
color: var(--ink);
text-align: left;
cursor: grab;
box-shadow: 0 4px 0 rgba(48, 71, 61, 0.06);
transition:
transform 140ms ease,
border-color 140ms ease,
opacity 140ms ease,
background 140ms ease;
}
.item-card:hover {
transform: translateY(-2px);
border-color: rgba(48, 71, 61, 0.3);
}
.item-card:active {
cursor: grabbing;
transform: translateY(1px);
}
.item-card.pending {
border-color: #3f7560;
background: #eef8f1;
box-shadow: 0 0 0 3px rgba(143, 198, 163, 0.35);
}
.item-card.packed {
opacity: 0.48;
cursor: default;
box-shadow: none;
}
.item-card.packed:hover {
transform: none;
}
.item-name {
display: block;
font-size: 13px;
font-weight: 750;
}
.item-meta {
display: block;
margin-top: 3px;
color: var(--muted);
font-size: 10px;
}
.stock {
min-width: 43px;
padding: 5px 7px;
border-radius: 8px;
background: #edf0e9;
color: var(--muted);
font-size: 9px;
font-weight: 750;
text-align: center;
text-transform: uppercase;
}
.pending .stock {
background: #dceee2;
color: #315d48;
}
.icon {
position: relative;
display: block;
width: 52px;
height: 52px;
border-radius: 11px;
background-color: #ebe7dc;
background-image:
linear-gradient(45deg, rgba(255,255,255,.22) 25%, transparent 25%),
linear-gradient(-45deg, rgba(255,255,255,.22) 25%, transparent 25%);
background-size: 12px 12px;
}
.icon-sandwich i {
position: absolute;
left: 9px;
width: 34px;
height: 8px;
background: #d89d55;
box-shadow:
0 8px 0 #f0b961,
0 16px 0 #e58d55,
0 24px 0 #c98748;
}
.icon-sandwich i::after {
content: "";
position: absolute;
left: -3px;
top: 8px;
width: 40px;
height: 4px;
background: #77a85d;
box-shadow: 0 5px 0 #dc6653;
}
.icon-sandwich i {
top: 7px;
}
.icon-fruit i {
position: absolute;
left: 13px;
top: 11px;
width: 25px;
height: 25px;
background: #ec8c3c;
box-shadow:
-5px 5px 0 #d97931,
5px 5px 0 #d97931,
5px 10px 0 #ec8c3c,
0 10px 0 #f3a34e,
-5px 15px 0 #d97931,
5px 15px 0 #d97931,
0 20px 0 #d97931;
}
.icon-fruit i::after {
content: "";
position: absolute;
left: 10px;
top: -9px;
width: 7px;
height: 10px;
background: #557348;
}
.icon-cup i {
position: absolute;
left: 13px;
top: 9px;
width: 23px;
height: 34px;
background: #579f9a;
box-shadow:
23px 5px 0 #579f9a,
23px 14px 0 #579f9a,
23px 23px 0 #579f9a,
12px -4px 0 #8bc5bd,
0 -4px 0 #8bc5bd,
-4px 4px 0 #8bc5bd;
}
.icon-cup i::after {
content: "";
position: absolute;
left: 3px;
top: 3px;
width: 17px;
height: 6px;
background: #304f4e;
}
.tip {
margin-top: 14px;
padding: 11px 12px;
border-radius: 11px;
background: #ece9df;
color: var(--muted);
font-size: 10px;
line-height: 1.5;
}
.tip strong {
color: var(--ink);
}
.status-card {
position: absolute;
left: 22px;
bottom: 22px;
width: 348px;
padding: 17px;
border: 1px solid rgba(67, 79, 70, 0.1);
border-radius: 18px;
background: rgba(248, 245, 237, 0.94);
box-shadow: var(--shadow);
backdrop-filter: blur(14px);
}
.status-top {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 15px;
}
.status-title {
display: flex;
align-items: center;
gap: 8px;
margin: 0;
font-size: 17px;
}
.selected-swatch {
width: 12px;
height: 12px;
border-radius: 4px;
background: var(--mint);
}
.clearance {
flex: none;
padding: 6px 8px;
border-radius: 8px;
background: #e8eee8;
color: #4b6658;
font-size: 10px;
font-weight: 800;
text-transform: uppercase;
}
.status-sub {
margin: 6px 0 0;
color: var(--muted);
font-size: 11px;
}
.compartment-dots {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 5px;
margin: 14px 0 12px;
}
.compartment-dots span {
height: 8px;
border-radius: 3px;
background: #dde1d9;
transition: background 160ms ease, transform 160ms ease;
}
.compartment-dots span.filled {
background: #4c7763;
transform: scaleY(1.15);
}
.status-message {
min-height: 34px;
margin: 0 0 12px;
color: var(--muted);
font-size: 12px;
line-height: 1.45;
}
.status-message strong {
color: var(--ink);
}
.status-actions {
display: grid;
grid-template-columns: 1.4fr 1fr 1fr;
gap: 7px;
}
.action {
min-height: 40px;
padding: 8px 10px;
border: 1px solid rgba(48, 71, 61, 0.12);
border-radius: 10px;
background: #fffdf8;
color: var(--ink);
font-size: 11px;
font-weight: 750;
cursor: pointer;
transition: transform 130ms ease, background 130ms ease;
}
.action:hover {
transform: translateY(-1px);
background: #f0eee6;
}
.action.primary {
border-color: #30473d;
background: #30473d;
color: white;
}
.action.primary:hover {
background: #3e5c4e;
}
.utility {
position: absolute;
right: 22px;
bottom: 22px;
display: flex;
gap: 8px;
pointer-events: auto;
}
.utility button {
min-height: 39px;
padding: 8px 12px;
border: 1px solid rgba(67, 79, 70, 0.1);
border-radius: 10px;
background: rgba(248, 245, 237, 0.9);
color: var(--ink);
box-shadow: var(--shadow);
font-size: 10px;
font-weight: 750;
cursor: pointer;
}
.help {
position: absolute;
left: 50%;
bottom: 24px;
transform: translateX(-50%);
padding: 8px 12px;
border-radius: 9px;
background: rgba(38, 53, 47, 0.76);
color: rgba(255, 255, 255, 0.88);
font-size: 10px;
letter-spacing: 0.02em;
backdrop-filter: blur(8px);
}
.toast {
position: absolute;
left: 50%;
top: 90px;
max-width: 360px;
padding: 10px 14px;
border-radius: 10px;
background: #263a32;
color: white;
box-shadow: var(--shadow);
font-size: 12px;
opacity: 0;
transform: translate(-50%, -8px);
transition: opacity 170ms ease, transform 170ms ease;
pointer-events: none;
}
.toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
#loading {
position: fixed;
inset: 0;
z-index: 50;
display: grid;
place-items: center;
background: #e8e4da;
color: #496257;
font-size: 12px;
font-weight: 800;
letter-spacing: 0.15em;
text-transform: uppercase;
}
#loading[hidden] {
display: none;
}
@media (max-width: 900px) {
.box-tabs {
top: 84px;
}
.inventory {
top: 146px;
width: 270px;
}
.help {
display: none;
}
}
@media (max-width: 680px) {
.header {
top: 10px;
left: 10px;
padding: 8px 11px 8px 8px;
}
.brand-mark {
width: 34px;
height: 34px;
transform: scale(.82);
transform-origin: left center;
}
.brand h1 {
font-size: 14px;
}
.brand p {
display: none;
}
.box-tabs {
top: 62px;
width: calc(100% - 20px);
justify-content: stretch;
}
.box-tab {
min-width: 0;
flex: 1;
padding: 8px;
}
.tab-name {
font-size: 10px;
}
.inventory {
top: auto;
right: 10px;
bottom: 10px;
left: 10px;
width: auto;
max-height: 188px;
padding: 12px;
}
.inventory > p,
.tip,
.eyebrow {
display: none;
}
.inventory h2 {
margin-bottom: 9px;
font-size: 16px;
}
.item-list {
display: flex;
overflow-x: auto;
padding-bottom: 4px;
}
.item-card {
flex: 0 0 205px;
min-height: 62px;
}
.status-card {
right: 10px;
bottom: 210px;
left: 10px;
width: auto;
padding: 13px;
}
.status-message {
min-height: 0;
margin-bottom: 8px;
}
.compartment-dots {
margin: 9px 0;
}
.utility {
display: none;
}
.toast {
top: 120px;
width: calc(100% - 40px);
text-align: center;
}
}
</style>
</head>
<body>
<div id="scene"></div>
<div class="ui">
<header class="header panel">
<div class="brand-mark"><i></i></div>
<div class="brand">
<h1>PACK / LAB</h1>
<p>Voxel lunchbox station</p>
</div>
</header>
<nav class="box-tabs" aria-label="Choose a lunchbox">
<button class="box-tab active" data-box="0">
<span class="tab-name"><i class="tab-dot"></i>Mint box</span>
<span class="tab-meta">1.02 clearance · 0/4</span>
</button>
<button class="box-tab" data-box="1">
<span class="tab-name"><i class="tab-dot" style="background:var(--coral)"></i>Coral box</span>
<span class="tab-meta">1.28 clearance · 0/4</span>
</button>
<button class="box-tab" data-box="2">
<span class="tab-name"><i class="tab-dot" style="background:var(--mustard)"></i>Amber box</span>
<span class="tab-meta">0.82 clearance · 0/4</span>
</button>
</nav>
<aside class="inventory panel" aria-label="Lunchbox items">
<p class="eyebrow">Supply shelf</p>
<h2>Pack your tray</h2>
<p>Drag an item into a compartment, or tap an item and then tap a compartment.</p>
<div class="item-list">
<button class="item-card" draggable="true" data-item="sandwich-1">
<span class="icon icon-sandwich"><i></i></span>
<span>
<span class="item-name">Sandwich half</span>
<span class="item-meta">Whole-grain · low profile</span>
</span>
<span class="stock">Drag</span>
</button>
<button class="item-card" draggable="true" data-item="sandwich-2">
<span class="icon icon-sandwich"><i></i></span>
<span>
<span class="item-name">Sandwich half</span>
<span class="item-meta">Veggie · low profile</span>
</span>
<span class="stock">Drag</span>
</button>
<button class="item-card" draggable="true" data-item="fruit-1">
<span class="icon icon-fruit"><i></i></span>
<span>
<span class="item-name">Orange</span>
<span class="item-meta">Bright fruit · medium</span>
</span>
<span class="stock">Drag</span>
</button>
<button class="item-card" draggable="true" data-item="fruit-2">
<span class="icon icon-fruit"><i></i></span>
<span>
<span class="item-name">Apple</span>
<span class="item-meta">Bright fruit · medium</span>
</span>
<span class="stock">Drag</span>
</button>
<button class="item-card" draggable="true" data-item="cup-1">
<span class="icon icon-cup"><i></i></span>
<span>
<span class="item-name">Reusable cup</span>
<span class="item-meta">Tall item · height test</span>
</span>
<span class="stock">Drag</span>
</button>
</div>
<div class="tip">
<strong>Tip:</strong> Tap a packed item in the scene to return it to the shelf.
Drag packed items between compartments.
</div>
</aside>
<section class="status-card panel" aria-live="polite">
<div class="status-top">
<div>
<h2 class="status-title">
<i class="selected-swatch"></i>
<span id="selected-name">Mint box</span>
</h2>
<p class="status-sub" id="selected-sub">Lid space 1.02 · 0 of 4 compartments packed</p>
</div>
<span class="clearance" id="clearance-badge">1.02 high</span>
</div>
<div class="compartment-dots" id="compartment-dots">
<span></span><span></span><span></span><span></span>
</div>
<p class="status-message" id="status-message">
Add food, then test the lid to see whether everything fits.
</p>
<div class="status-actions">
<button class="action primary" id="test-lid">Test lid</button>
<button class="action" id="open-lid">Open lid</button>
<button class="action" id="empty-box">Empty box</button>
</div>
</section>
<div class="utility">
<button id="reset-camera">Reset view</button>
</div>
<div class="help">Right-drag to orbit · Shift-drag to pan · Scroll to zoom</div>
<div class="toast" id="toast" role="status"></div>
</div>
<div id="loading">Building lunchboxes…</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Core setup
// -------------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xe8e4da);
scene.fog = new THREE.Fog(0xe8e4da, 18, 34);
const camera = new THREE.PerspectiveCamera(42, innerWidth / innerHeight, 0.1, 80);
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.domElement.setAttribute("aria-label", "Interactive 3D lunchbox packing station");
renderer.domElement.tabIndex = 0;
document.getElementById("scene").appendChild(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0xfff8e9, 0x809083, 2.0);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xfff4d9, 3.3);
keyLight.position.set(-5, 11, 8);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -12;
keyLight.shadow.camera.right = 12;
keyLight.shadow.camera.top = 10;
keyLight.shadow.camera.bottom = -10;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 30;
keyLight.shadow.bias = -0.0005;
scene.add(keyLight);
const fillLight = new THREE.DirectionalLight(0xcce6ff, 1.2);
fillLight.position.set(8, 6, -7);
scene.add(fillLight);
const UNIT_BOX = new THREE.BoxGeometry(1, 1, 1);
const clock = new THREE.Clock();
const BASE_TOP = 0.15;
const BOX_W = 3.48;
const BOX_D = 2.61;
const TILE = 0.29;
const LID_THICKNESS = 0.14;
const OPEN_ANGLE = 1.15;
const COMP_X = 0.755;
const COMP_Z = 0.5625;
const material = (color, extra = {}) =>
new THREE.MeshStandardMaterial({
color,
roughness: 0.78,
metalness: 0,
...extra
});
const M = {
tableA: material(0xd7c9aa),
tableB: material(0xe0d4b9),
wall: material(0xdce4da),
wallAlt: material(0xe8eee5),
tray: material(0xe9e1cc),
dark: material(0x30473d),
bread: material(0xd89d55),
breadLight: material(0xe9b969),
breadDark: material(0xb97b3f),
tomato: material(0xdd6653),
lettuce: material(0x73a653),
cheese: material(0xf1c65d),
orange: material(0xec8c3c),
orangeLight: material(0xf3a34e),
apple: material(0xd8584c),
appleLight: material(0xeb6d59),
stem: material(0x6b5839),
leaf: material(0x5b844c),
cup: material(0x579f9a),
cupLight: material(0x8bc5bd),
cupDark: material(0x304f4e),
warning: new THREE.MeshBasicMaterial({ color: 0xff4f45 }),
green: new THREE.MeshBasicMaterial({ color: 0x75d39a })
};
function block(parent, sx, sy, sz, x, y, z, mat, castShadow = true) {
const mesh = new THREE.Mesh(UNIT_BOX, mat);
mesh.scale.set(sx, sy, sz);
mesh.position.set(x, y, z);
mesh.castShadow = castShadow;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
// -------------------------------------------------------------------------
// Voxel environment
// -------------------------------------------------------------------------
const environment = new THREE.Group();
scene.add(environment);
for (let i = 0; i < 18; i++) {
for (let j = 0; j < 11; j++) {
block(
environment,
0.79, 0.28, 0.79,
(i - 8.5) * 0.8,
-0.14,
(j - 5) * 0.8,
(i + j) % 2 ? M.tableA : M.tableB,
false
);
}
}
for (let i = 0; i < 18; i++) {
for (let j = 0; j < 4; j++) {
block(
environment,
0.78, 0.78, 0.25,
(i - 8.5) * 0.8,
0.39 + j * 0.79,
-4.85,
(i + j) % 3 === 0 ? M.wallAlt : M.wall,
false
);
}
}
// Small supply crates, made only from blocks.
function makeCrate(x, z, color) {
const crate = new THREE.Group();
crate.position.set(x, 0, z);
const mat = material(color);
for (let i = 0; i < 4; i++) {
for (let j = 0; j < 3; j++) {
block(crate, 0.2, 0.5, 0.2, (i - 1.5) * 0.22, 0.25, (j - 1) * 0.22, mat);
}
}
block(crate, 0.92, 0.12, 0.68, 0, 0.08, 0, M.tray);
environment.add(crate);
}
makeCrate(-6.7, -3.65, 0x9eb99e);
makeCrate(6.25, -3.6, 0xd7a16d);
// -------------------------------------------------------------------------
// Item definitions and voxel models
// -------------------------------------------------------------------------
const ITEM_TYPES = {
sandwich: {
label: "Sandwich half",
height: 0.38,
width: 1.24,
depth: 0.91
},
fruit: {
label: "Fruit",
height: 0.76,
width: 0.72,
depth: 0.72
},
cup: {
label: "Reusable cup",
height: 1.16,
width: 0.84,
depth: 0.76
}
};
const ITEMS = {
"sandwich-1": { type: "sandwich", variant: "grain", name: "Whole-grain half" },
"sandwich-2": { type: "sandwich", variant: "veggie", name: "Veggie half" },
"fruit-1": { type: "fruit", variant: "orange", name: "Orange" },
"fruit-2": { type: "fruit", variant: "apple", name: "Apple" },
"cup-1": { type: "cup", variant: "teal", name: "Reusable cup" }
};
function makeSandwich(variant) {
const group = new THREE.Group();
const bread = variant === "veggie" ? M.breadLight : M.bread;
const cell = 0.17;
const cells = [];
for (let ix = 0; ix < 7; ix++) {
for (let iz = 0; iz < 5; iz++) {
if (ix + iz <= 8) cells.push([ix, iz]);
}
}
for (const [ix, iz] of cells) {
const x = (ix - 3) * cell;
const z = (iz - 2) * cell;
block(group, cell, 0.10, cell, x, 0.05, z, M.breadDark);
block(group, cell, 0.035, cell, x, 0.1175, z, M.tomato);
block(group, cell, 0.04, cell, x, 0.155, z, M.lettuce);
block(group, cell, 0.025, cell, x, 0.1875, z, M.cheese);
block(group, cell, 0.14, cell, x, 0.27, z, bread);
}
// A few sesame voxels on the top slice.
block(group, 0.035, 0.018, 0.055, -0.28, 0.348, -0.10, M.breadLight);
block(group, 0.035, 0.018, 0.055, 0.08, 0.348, 0.13, M.breadLight);
block(group, 0.035, 0.018, 0.055, 0.31, 0.348, -0.13, M.breadLight);
return group;
}
function makeFruit(variant) {
const group = new THREE.Group();
const main = variant === "apple" ? M.apple : M.orange;
const light = variant === "apple" ? M.appleLight : M.orangeLight;
const cell = 0.2;
for (let layer = 0; layer < 2; layer++) {
for (let ix = -1; ix <= 1; ix++) {
for (let iz = -1; iz <= 1; iz++) {
if (Math.abs(ix) === 1 && Math.abs(iz) === 1) continue;
block(
group,
cell, 0.18, cell,
ix * cell,
0.09 + layer * 0.18,
iz * cell,
(ix + iz + layer) % 2 ? main : light
);
}
}
}
for (let ix = 0; ix < 2; ix++) {
for (let iz = 0; iz < 2; iz++) {
block(
group,
cell, 0.18, cell,
(ix - 0.5) * cell,
0.45,
(iz - 0.5) * cell,
(ix + iz) % 2 ? main : light
);
}
}
block(group, 0.075, 0.15, 0.075, 0.02, 0.66, 0, M.stem);
block(group, 0.19, 0.055, 0.09, 0.11, 0.71, 0.02, M.leaf);
return group;
}
function makeCup() {
const group = new THREE.Group();
const cell = 0.23;
// Bottom.
for (let ix = -1; ix <= 1; ix++) {
for (let iz = -1; iz <= 1; iz++) {
block(group, cell, 0.13, cell, ix * cell, 0.065, iz * cell, M.cup);
}
}
// Four voxel rings.
for (let layer = 0; layer < 4; layer++) {
const y = 0.13 + layer * 0.235 + 0.1175;
for (let ix = -1; ix <= 1; ix++) {
for (let iz = -1; iz <= 1; iz++) {
if (Math.abs(ix) !== 1 && Math.abs(iz) !== 1) continue;
block(group, cell, 0.235, cell, ix * cell, y, iz * cell, M.cup);
}
}
}
// Light rim and dark opening.
for (let ix = -1; ix <= 1; ix++) {
for (let iz = -1; iz <= 1; iz++) {
if (Math.abs(ix) !== 1 && Math.abs(iz) !== 1) continue;
block(group, cell, 0.09, cell, ix * cell, 1.08, iz * cell, M.cupLight);
}
}
block(group, 0.49, 0.035, 0.49, 0, 1.105, 0, M.cupDark);
// Square handle.
block(group, 0.12, 0.16, 0.12, 0.42, 0.25, 0, M.cup);
block(group, 0.12, 0.16, 0.12, 0.42, 0.49, 0, M.cup);
block(group, 0.12, 0.16, 0.12, 0.42, 0.73, 0, M.cup);
block(group, 0.21, 0.12, 0.12, 0.34, 0.25, 0, M.cupLight);
block(group, 0.21, 0.12, 0.12, 0.34, 0.73, 0, M.cupLight);
return group;
}
function makeItemModel(itemId) {
const item = ITEMS[itemId];
if (item.type === "sandwich") return makeSandwich(item.variant);
if (item.type === "fruit") return makeFruit(item.variant);
return makeCup();
}
// -------------------------------------------------------------------------
// Lunchboxes, compartments, and hinged voxel lids
// -------------------------------------------------------------------------
const boxes = [];
const pickMeshes = [];
const placed = new Map();
const warningMarkers = new Map();
const BOX_CONFIGS = [
{ name: "Mint box", color: 0x8fc6a3, clearance: 1.02, x: -4.2 },
{ name: "Coral box", color: 0xf28e79, clearance: 1.28, x: -0.2 },
{ name: "Amber box", color: 0xf2c35b, clearance: 0.82, x: 3.8 }
];
function makeLunchbox(config, id) {
const root = new THREE.Group();
root.position.set(config.x, 0, 0);
scene.add(root);
const rimMat = material(config.color, {
emissive: 0x000000,
emissiveIntensity: 0.25
});
const lidMat = material(config.color, {
roughness: 0.62,
emissive: 0x000000,
emissiveIntensity: 0.18
});
// Tiled floor.
for (let i = 0; i < 12; i++) {
for (let j = 0; j < 9; j++) {
block(
root,
TILE - 0.012, 0.14, TILE - 0.012,
(i - 5.5) * TILE,
0.07,
(j - 4) * TILE,
M.tray,
false
);
}
}
// Outer rim.
for (let i = 0; i < 12; i++) {
const x = (i - 5.5) * TILE;
block(root, TILE - 0.012, 0.22, TILE - 0.012, x, 0.25, -BOX_D / 2 + TILE / 2, rimMat);
block(root, TILE - 0.012, 0.22, TILE - 0.012, x, 0.25, BOX_D / 2 - TILE / 2, rimMat);
}
for (let j = 1; j < 8; j++) {
const z = (j - 4) * TILE;
block(root, TILE - 0.012, 0.22, TILE - 0.012, -BOX_W / 2 + TILE / 2, 0.25, z, rimMat);
block(root, TILE - 0.012, 0.22, TILE - 0.012, BOX_W / 2 - TILE / 2, 0.25, z, rimMat);
}
// Cross dividers.
for (let j = 0; j < 9; j++) {
block(root, 0.11, 0.14, TILE - 0.01, 0, 0.21, (j - 4) * TILE, rimMat);
}
for (let i = 0; i < 12; i++) {
block(root, TILE - 0.01, 0.14, 0.11, (i - 5.5) * TILE, 0.21, 0, rimMat);
}
// Hinged lid. The front edge is the hinge.
const lidPivot = new THREE.Group();
lidPivot.position.set(
0,
BASE_TOP + config.clearance + LID_THICKNESS / 2,
BOX_D / 2
);
lidPivot.rotation.x = OPEN_ANGLE;
root.add(lidPivot);
for (let i = 0; i < 12; i++) {
for (let j = 0; j < 9; j++) {
block(
lidPivot,
TILE - 0.012, LID_THICKNESS, TILE - 0.012,
(i - 5.5) * TILE,
0,
-(j + 0.5) * TILE,
lidMat
);
}
}
// Small block handle.
block(lidPivot, 0.68, 0.12, 0.16, 0, 0.15, -BOX_D * 0.62, M.dark);
block(lidPivot, 0.16, 0.18, 0.16, -0.28, 0.11, -BOX_D * 0.62, M.dark);
block(lidPivot, 0.16, 0.18, 0.16, 0.28, 0.11, -BOX_D * 0.62, M.dark);
// Visible hinge blocks.
for (let i = 0; i < 5; i++) {
block(
root,
0.18, 0.18, 0.2,
(i - 2) * 0.42,
BASE_TOP + config.clearance + 0.06,
BOX_D / 2,
M.dark
);
}
// Invisible raycast surfaces for the four compartments.
for (let comp = 0; comp < 4; comp++) {
const cx = comp % 2 === 0 ? -COMP_X : COMP_X;
const cz = comp < 2 ? -COMP_Z : COMP_Z;
const pickMat = new THREE.MeshBasicMaterial({
color: config.color,
transparent: true,
opacity: 0.012,
depthWrite: false,
side: THREE.DoubleSide
});
const pick = new THREE.Mesh(new THREE.PlaneGeometry(1.34, 0.96), pickMat);
pick.rotation.x = -Math.PI / 2;
pick.position.set(cx, BASE_TOP + 0.012, cz);
pick.renderOrder = 3;
pick.userData = { boxId: id, comp };
root.add(pick);
pickMeshes.push(pick);
}
// Small status beacon in front of each box.
const beacon = new THREE.Group();
beacon.position.set(BOX_W / 2 - 0.2, 0.45, BOX_D / 2 + 0.32);
const beaconMat = material(0xbac4b9, { emissive: 0x000000 });
block(beacon, 0.13, 0.13, 0.13, 0, 0, 0, beaconMat);
block(beacon, 0.11, 0.11, 0.11, 0, 0.15, 0, beaconMat);
block(beacon, 0.09, 0.09, 0.09, 0, 0.28, 0, beaconMat);
root.add(beacon);
const box = {
id,
name: config.name,
color: config.color,
clearance: config.clearance,
x: config.x,
root,
rimMat,
lidMat,
lidPivot,
beacon,
beaconMat,
compartments: [null, null, null, null],
lidAngle: OPEN_ANGLE,
lidTarget: OPEN_ANGLE,
result: null
};
boxes.push(box);
return box;
}
BOX_CONFIGS.forEach((config, id) => makeLunchbox(config, id));
// Selected-box corner brackets.
const selection = new THREE.Group();
const selectionMat = material(0x8fc6a3, {
emissive: 0x8fc6a3,
emissiveIntensity: 0.22
});
for (const sx of [-1, 1]) {
for (const sz of [-1, 1]) {
const x = sx * (BOX_W / 2 + 0.23);
const z = sz * (BOX_D / 2 + 0.23);
block(selection, 0.32, 0.055, 0.08, x - sx * 0.12, 0.025, z, selectionMat, false);
block(selection, 0.08, 0.055, 0.32, x, 0.025, z - sz * 0.12, selectionMat, false);
}
}
scene.add(selection);
const selectionPlate = new THREE.Mesh(
new THREE.PlaneGeometry(BOX_W + 0.45, BOX_D + 0.45),
new THREE.MeshBasicMaterial({
color: 0x8fc6a3,
transparent: true,
opacity: 0.12,
depthWrite: false
})
);
selectionPlate.rotation.x = -Math.PI / 2;
selectionPlate.position.y = 0.008;
scene.add(selectionPlate);
// -------------------------------------------------------------------------
// Custom camera controls, implemented without Three.js addons
// -------------------------------------------------------------------------
const cameraState = {
theta: 0.64,
phi: 0.80,
radius: 15.7,
target: new THREE.Vector3(-0.65, 0.55, 0)
};
function updateCamera() {
const s = Math.sin(cameraState.phi);
camera.position.set(
cameraState.target.x + cameraState.radius * s * Math.sin(cameraState.theta),
cameraState.target.y + cameraState.radius * Math.cos(cameraState.phi),
cameraState.target.z + cameraState.radius * s * Math.cos(cameraState.theta)
);
camera.lookAt(cameraState.target);
}
function resetCamera() {
cameraState.theta = 0.64;
cameraState.phi = 0.80;
cameraState.radius = 15.7;
cameraState.target.set(-0.65, 0.55, 0);
updateCamera();
}
updateCamera();
let orbitDrag = null;
renderer.domElement.addEventListener("contextmenu", event => event.preventDefault());
renderer.domElement.addEventListener("pointerdown", event => {
if (event.button === 2 || (event.button === 0 && event.shiftKey)) {
orbitDrag = {
x: event.clientX,
y: event.clientY,
pan: event.button === 1
};
renderer.domElement.setPointerCapture(event.pointerId);
event.preventDefault();
}
});
renderer.domElement.addEventListener("pointermove", event => {
if (!orbitDrag) return;
const dx = event.clientX - orbitDrag.x;
const dy = event.clientY - orbitDrag.y;
orbitDrag.x = event.clientX;
orbitDrag.y = event.clientY;
if (orbitDrag.pan) {
const right = new THREE.Vector3().setFromMatrixColumn(camera.matrix, 0);
const up = new THREE.Vector3().setFromMatrixColumn(camera.matrix, 1);
cameraState.target.addScaledVector(right, -dx * 0.008);
cameraState.target.addScaledVector(up, dy * 0.008);
} else {
cameraState.theta -= dx * 0.006;
cameraState.phi = THREE.MathUtils.clamp(cameraState.phi + dy * 0.005, 0.38, 1.25);
}
updateCamera();
});
renderer.domElement.addEventListener("pointerup", event => {
if (orbitDrag) {
orbitDrag = null;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
});
renderer.domElement.addEventListener("wheel", event => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius + event.deltaY * 0.008,
9.5,
24
);
updateCamera();
}, { passive: false });
document.getElementById("reset-camera").addEventListener("click", resetCamera);
// -------------------------------------------------------------------------
// Picking and packing state
// -------------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const dragPlane = new THREE.Plane(new THREE.Vector3(0, 1, 0), -(BASE_TOP + 0.16));
const planeHit = new THREE.Vector3();
let selectedBox = 0;
let pendingItem = null;
let hoveredComp = null;
let itemDrag = null;
function updatePointer(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);
}
function getCompAt(event) {
updatePointer(event);
const hits = raycaster.intersectObjects(pickMeshes, false);
if (!hits.length) return null;
return hits[0].object.userData;
}
function refreshCompartmentVisuals() {
for (const pick of pickMeshes) {
const { boxId, comp } = pick.userData;
const box = boxes[boxId];
const occupied = Boolean(box.compartments[comp]);
const isHovered = hoveredComp && hoveredComp.boxId === boxId && hoveredComp.comp === comp;
const isSelected = boxId === selectedBox;
pick.material.color.set(
isHovered && pendingItem ? 0x68c78e :
occupied ? 0xe6b34b :
box.color
);
pick.material.opacity =
isHovered ? (pendingItem ? 0.38 : 0.24) :
occupied ? 0.07 :
isSelected ? 0.045 : 0.012;
}
}
function setHovered(comp) {
const same =
(!comp && !hoveredComp) ||
(comp && hoveredComp && comp.boxId === hoveredComp.boxId && comp.comp === hoveredComp.comp);
if (!same) {
hoveredComp = comp;
refreshCompartmentVisuals();
}
}
function centerFor(box, comp) {
return new THREE.Vector3(
box.x + (comp % 2 === 0 ? -COMP_X : COMP_X),
BASE_TOP,
comp < 2 ? -COMP_Z : COMP_Z
);
}
function findItemId(object) {
while (object) {
if (object.userData && object.userData.itemId) return object.userData.itemId;
object = object.parent;
}
return null;
}
function hitItem(event) {
updatePointer(event);
const roots = [...placed.values()].map(entry => entry.group);
if (!roots.length) return null;
const hits = raycaster.intersectObjects(roots, true);
if (!hits.length) return null;
const itemId = findItemId(hits[0].object);
return itemId ? { itemId, point: hits[0].point } : null;
}
function toast(message) {
const element = document.getElementById("toast");
element.textContent = message;
element.classList.add("show");
clearTimeout(toast.timer);
toast.timer = setTimeout(() => element.classList.remove("show"), 2300);
}
function selectBox(id) {
selectedBox = id;
const box = boxes[id];
selection.position.x = box.x;
selectionPlate.position.x = box.x;
selectionMat.color.set(box.color);
selectionMat.emissive.set(box.color);
selectionPlate.material.color.set(box.color);
for (const candidate of boxes) {
candidate.rimMat.emissive.set(candidate.id === id ? candidate.color : 0x000000);
candidate.rimMat.emissiveIntensity = candidate.id === id ? 0.28 : 0;
}
refreshCompartmentVisuals();
renderUI();
}
function removeWarningMarkers(boxId) {
for (const [itemId, marker] of warningMarkers) {
const placement = placed.get(itemId);
if (!placement || placement.boxId === boxId) {
scene.remove(marker);
warningMarkers.delete(itemId);
}
}
}
function openBox(box, notify = false) {
box.lidTarget = OPEN_ANGLE;
box.result = null;
box.lidMat.color.set(box.color);
box.lidMat.emissive.set(0x000000);
box.beaconMat.color.set(0xbac4b9);
box.beaconMat.emissive.set(0x000000);
removeWarningMarkers(box.id);
if (notify) {
toast(`${box.name} is open and ready to pack.`);
}
}
function makeWarningFrame(itemId) {
const def = ITEM_TYPES[ITEMS[itemId].type];
const marker = new THREE.Group();
const sx = def.width / 2 + 0.035;
const sz = def.depth / 2 + 0.035;
for (const x of [-sx, sx]) {
for (const z of [-sz, sz]) {
for (const y of [0.03, def.height + 0.025]) {
block(marker, 0.075, 0.075, 0.075, x, y, z, M.warning, false);
}
}
}
return marker;
}
function showWarnings(box) {
removeWarningMarkers(box.id);
if (!box.result || box.result.kind !== "tall") return;
for (const itemId of box.result.offenders) {
const placement = placed.get(itemId);
if (!placement) continue;
const marker = makeWarningFrame(itemId);
marker.position.copy(placement.group.position);
scene.add(marker);
warningMarkers.set(itemId, marker);
}
}
function placeItem(itemId, boxId, comp) {
const box = boxes[boxId];
const existing = placed.get(itemId);
if (!ITEMS[itemId] || !box || comp < 0 || comp > 3) return false;
if (existing && existing.boxId === boxId && existing.comp === comp) {
return false;
}
if (box.compartments[comp] && box.compartments[comp] !== itemId) {
toast("That compartment is already occupied.");
return false;
}
let group = existing?.group;
if (existing) {
boxes[existing.boxId].compartments[existing.comp] = null;
openBox(boxes[existing.boxId]);
} else {
group = makeItemModel(itemId);
group.userData.itemId = itemId;
scene.add(group);
}
box.compartments[comp] = itemId;
group.position.copy(centerFor(box, comp));
placed.set(itemId, { boxId, comp, group });
openBox(box);
pendingItem = null;
refreshCompartmentVisuals();
renderUI();
toast(`${ITEMS[itemId].name} packed into the ${box.name.toLowerCase()}.`);
return true;
}
function returnItem(itemId) {
const placement = placed.get(itemId);
if (!placement) return;
const box = boxes[placement.boxId];
box.compartments[placement.comp] = null;
scene.remove(placement.group);
placed.delete(itemId);
openBox(box);
refreshCompartmentVisuals();
renderUI();
toast(`${ITEMS[itemId].name} returned to the shelf.`);
}
function moveItem(itemId, target) {
const placement = placed.get(itemId);
if (!placement) return false;
const targetBox = boxes[target.boxId];
const occupant = targetBox.compartments[target.comp];
if (occupant && occupant !== itemId) {
toast("That compartment is already occupied.");
return false;
}
const oldBox = boxes[placement.boxId];
oldBox.compartments[placement.comp] = null;
targetBox.compartments[target.comp] = itemId;
placement.boxId = target.boxId;
placement.comp = target.comp;
placement.group.position.copy(centerFor(targetBox, target.comp));
placed.set(itemId, placement);
openBox(oldBox);
openBox(targetBox);
refreshCompartmentVisuals();
renderUI();
return true;
}
function clearBox(box) {
const ids = [...box.compartments].filter(Boolean);
for (const itemId of ids) {
const placement = placed.get(itemId);
if (placement) scene.remove(placement.group);
placed.delete(itemId);
}
box.compartments = [null, null, null, null];
openBox(box);
refreshCompartmentVisuals();
renderUI();
toast(`${box.name} emptied.`);
}
// -------------------------------------------------------------------------
// Lid height testing
// -------------------------------------------------------------------------
function lidClearanceAt(box, itemId, angle) {
const placement = placed.get(itemId);
if (!placement) return Infinity;
const itemLocalZ = placement.group.position.z - box.root.position.z;
const distanceFromHinge = BOX_D / 2 - itemLocalZ;
return box.clearance
+ distanceFromHinge * Math.sin(angle)
+ (LID_THICKNESS / 2) * (1 - Math.cos(angle));
}
function solveCollisionAngle(box, itemId) {
const def = ITEM_TYPES[ITEMS[itemId].type];
const requiredExtra = def.height - box.clearance;
if (requiredExtra <= 0) return 0;
let low = 0;
let high = OPEN_ANGLE;
if (lidClearanceAt(box, itemId, high) < def.height) {
return high;
}
for (let i = 0; i < 32; i++) {
const mid = (low + high) / 2;
if (lidClearanceAt(box, itemId, mid) >= def.height) {
high = mid;
} else {
low = mid;
}
}
return high;
}
function testLid(box) {
const itemIds = box.compartments.filter(Boolean);
const offenders = itemIds.filter(itemId => {
return ITEM_TYPES[ITEMS[itemId].type].height > box.clearance + 0.0001;
});
if (!offenders.length) {
box.result = {
kind: "fit",
offenders: []
};
box.lidTarget = 0;
box.lidMat.color.set(0x79c98f);
box.lidMat.emissive.set(0x315f3b);
box.beaconMat.color.set(0x65c883);
box.beaconMat.emissive.set(0x255a34);
removeWarningMarkers(box.id);
toast("The lid closed cleanly. Everything fits.");
} else {
const stopAngle = Math.max(...offenders.map(itemId => solveCollisionAngle(box, itemId)));
box.result = {
kind: "tall",
offenders,
stopAngle
};
box.lidTarget = stopAngle;
box.lidMat.color.set(0xf06d60);
box.lidMat.emissive.set(0x6d1f19);
box.beaconMat.color.set(0xff5d50);
box.beaconMat.emissive.set(0x6e1c15);
showWarnings(box);
const tallest = offenders.reduce((best, itemId) => {
const height = ITEM_TYPES[ITEMS[itemId].type].height;
return height > best.height ? { itemId, height } : best;
}, { itemId: null, height: 0 });
const excess = tallest.height - box.clearance;
toast(`${ITEMS[tallest.itemId].name} is ${excess.toFixed(2)} too tall. The lid stopped safely.`);
}
renderUI();
}
// -------------------------------------------------------------------------
// Inventory interaction
// -------------------------------------------------------------------------
const cards = [...document.querySelectorAll(".item-card")];
function refreshCards() {
for (const card of cards) {
const itemId = card.dataset.item;
const isPacked = placed.has(itemId);
card.classList.toggle("packed", isPacked);
card.classList.toggle("pending", pendingItem === itemId);
card.draggable = !isPacked;
card.setAttribute("aria-disabled", String(isPacked));
card.querySelector(".stock").textContent =
isPacked ? "Packed" : pendingItem === itemId ? "Tap box" : "Drag";
}
}
for (const card of cards) {
card.addEventListener("click", () => {
const itemId = card.dataset.item;
if (placed.has(itemId)) {
toast("That item is already packed. Tap it in the scene to return it.");
return;
}
pendingItem = pendingItem === itemId ? null : itemId;
refreshCards();
refreshCompartmentVisuals();
renderUI();
if (pendingItem) {
toast(`Tap a compartment to place the ${ITEMS[itemId].name.toLowerCase()}.`);
}
});
card.addEventListener("dragstart", event => {
const itemId = card.dataset.item;
if (placed.has(itemId)) {
event.preventDefault();
return;
}
event.dataTransfer.effectAllowed = "move";
event.dataTransfer.setData("text/plain", itemId);
pendingItem = itemId;
refreshCards();
refreshCompartmentVisuals();
});
card.addEventListener("dragend", () => {
refreshCards();
refreshCompartmentVisuals();
});
}
renderer.domElement.addEventListener("dragover", event => {
event.preventDefault();
event.dataTransfer.dropEffect = "move";
setHovered(getCompAt(event));
});
renderer.domElement.addEventListener("dragleave", () => {
if (!itemDrag) setHovered(null);
});
renderer.domElement.addEventListener("drop", event => {
event.preventDefault();
const itemId = event.dataTransfer.getData("text/plain");
const target = getCompAt(event);
setHovered(null);
if (!ITEMS[itemId]) return;
if (!target) {
toast("Drop the item directly into a compartment.");
return;
}
selectBox(target.boxId);
placeItem(itemId, target.boxId, target.comp);
});
// -------------------------------------------------------------------------
// Canvas click and item dragging
// -------------------------------------------------------------------------
renderer.domElement.addEventListener("pointerdown", event => {
if (event.button !== 0 || event.shiftKey) return;
const hit = hitItem(event);
if (!hit) return;
const placement = placed.get(hit.itemId);
itemDrag = {
itemId: hit.itemId,
startX: event.clientX,
startY: event.clientY,
moved: false,
originalPosition: placement.group.position.clone()
};
renderer.domElement.setPointerCapture(event.pointerId);
renderer.domElement.style.cursor = "grabbing";
event.preventDefault();
});
renderer.domElement.addEventListener("pointermove", event => {
if (itemDrag) {
const distance = Math.hypot(
event.clientX - itemDrag.startX,
event.clientY - itemDrag.startY
);
if (distance > 5) itemDrag.moved = true;
if (itemDrag.moved) {
updatePointer(event);
if (raycaster.ray.intersectPlane(dragPlane, planeHit)) {
const placement = placed.get(itemDrag.itemId);
placement.group.position.x = planeHit.x;
placement.group.position.z = planeHit.z;
placement.group.position.y = BASE_TOP + 0.12;
}
setHovered(getCompAt(event));
}
return;
}
const target = getCompAt(event);
setHovered(target);
renderer.domElement.style.cursor = target ? "crosshair" : "default";
});
renderer.domElement.addEventListener("pointerup", event => {
if (itemDrag) {
const drag = itemDrag;
itemDrag = null;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
renderer.domElement.style.cursor = "default";
if (!drag.moved) {
returnItem(drag.itemId);
} else {
const target = getCompAt(event);
if (!target || !moveItem(drag.itemId, target)) {
const placement = placed.get(drag.itemId);
placement.group.position.copy(drag.originalPosition);
}
}
setHovered(null);
return;
}
const target = getCompAt(event);
if (target) {
selectBox(target.boxId);
if (pendingItem) {
placeItem(pendingItem, target.boxId, target.comp);
}
}
});
renderer.domElement.addEventListener("pointercancel", () => {
if (itemDrag) {
const placement = placed.get(itemDrag.itemId);
placement.group.position.copy(itemDrag.originalPosition);
}
itemDrag = null;
setHovered(null);
});
renderer.domElement.addEventListener("pointerleave", () => {
if (!itemDrag) setHovered(null);
});
// -------------------------------------------------------------------------
// UI
// -------------------------------------------------------------------------
function renderUI() {
const box = boxes[selectedBox];
const count = box.compartments.filter(Boolean).length;
document.getElementById("selected-name").textContent = box.name;
document.getElementById("selected-sub").textContent =
`Lid space ${box.clearance.toFixed(2)} · ${count} of 4 compartments packed`;
document.getElementById("clearance-badge").textContent =
`${box.clearance.toFixed(2)} high`;
document.querySelector(".selected-swatch").style.background =
`#${new THREE.Color(box.color).getHexString()}`;
const dots = [...document.querySelectorAll("#compartment-dots span")];
dots.forEach((dot, index) => dot.classList.toggle("filled", Boolean(box.compartments[index])));
const message = document.getElementById("status-message");
if (pendingItem) {
message.innerHTML =
`<strong>${ITEMS[pendingItem].name} selected.</strong> Tap a compartment to place it.`;
} else if (box.result?.kind === "fit") {
message.innerHTML =
`<strong>Clear fit.</strong> The lid closed cleanly over every packed item.`;
} else if (box.result?.kind === "tall") {
const offender = box.result.offenders[0];
const height = ITEM_TYPES[ITEMS[offender].type].height;
const excess = height - box.clearance;
message.innerHTML =
`<strong>Too tall by ${excess.toFixed(2)}.</strong> ` +
`The red lid stopped before hitting the ${ITEMS[offender].name.toLowerCase()}.`;
} else if (count === 0) {
message.innerHTML =
`Add food, then <strong>test the lid</strong> to see whether everything fits.`;
} else {
message.innerHTML =
`<strong>${count} compartment${count === 1 ? "" : "s"} packed.</strong> ` +
`Test the lid whenever you are ready.`;
}
for (const tab of document.querySelectorAll(".box-tab")) {
const id = Number(tab.dataset.box);
const candidate = boxes[id];
const occupied = candidate.compartments.filter(Boolean).length;
tab.classList.toggle("active", id === selectedBox);
tab.querySelector(".tab-meta").textContent =
`${candidate.clearance.toFixed(2)} clearance · ${occupied}/4`;
}
refreshCards();
}
document.querySelectorAll(".box-tab").forEach(tab => {
tab.addEventListener("click", () => selectBox(Number(tab.dataset.box)));
});
document.getElementById("test-lid").addEventListener("click", () => {
testLid(boxes[selectedBox]);
});
document.getElementById("open-lid").addEventListener("click", () => {
openBox(boxes[selectedBox], true);
renderUI();
});
document.getElementById("empty-box").addEventListener("click", () => {
clearBox(boxes[selectedBox]);
});
window.addEventListener("keydown", event => {
if (event.key === "Escape") {
pendingItem = null;
refreshCards();
refreshCompartmentVisuals();
renderUI();
}
});
// -------------------------------------------------------------------------
// Resize and animation
// -------------------------------------------------------------------------
window.addEventListener("resize", () => {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
});
function animate() {
requestAnimationFrame(animate);
const dt = Math.min(clock.getDelta(), 0.05);
const time = clock.elapsedTime;
const ease = 1 - Math.exp(-dt * 7);
for (const box of boxes) {
box.lidAngle += (box.lidTarget - box.lidAngle) * ease;
if (Math.abs(box.lidTarget - box.lidAngle) < 0.0005) {
box.lidAngle = box.lidTarget;
}
box.lidPivot.rotation.x = box.lidAngle;
box.beacon.children[2].position.y = 0.28 + Math.sin(time * 4 + box.id) * 0.035;
box.beacon.rotation.y = Math.sin(time * 0.8 + box.id) * 0.06;
}
for (const marker of warningMarkers.values()) {
const pulse = 1 + Math.sin(time * 8) * 0.08;
marker.scale.setScalar(pulse);
marker.rotation.y = Math.sin(time * 2) * 0.035;
}
selectionPlate.material.opacity = 0.1 + Math.sin(time * 2.2) * 0.025;
renderer.render(scene, camera);
}
selectBox(0);
renderUI();
animate();
document.getElementById("loading").hidden = true;
</script>
</body>
</html>
```