Prompt specification
Build or customize the Three.js 3D scene "Packing search playground" inside the active workspace.
Engineering Constraints:
1. Runtime & Orbit: Use Three.js r160 with OrbitControls (damping enabled) and ACESFilmicToneMapping.
2. Frame Timing: Drive all motion strictly with clock.getDelta() so animation speed is FPS-independent.
3. Viewport Hygiene: Handle window resize cleanly, cap DPR at Math.min(window.devicePixelRatio, 2), and dispose geometries/materials/renderer on unmount.
Scene Metadata:
Scene: Packing search playground
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/packing-search-playground-x1712
Scene Description Prompt:
Make a standalone HTML scene with Three.js from cdnjs that depicts geometric packing within a bounded container. Let users rotate and place a small fixed set of blocks, then compare with an exhaustive solution for that bounded instance; report feasibility separately from optimality. Voxel style.
Working Three.js Starter (packing-search-playground-x1712):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Voxel Packing Lab</title>
<style>
:root {
color-scheme: dark;
--bg: #08111f;
--panel: rgba(12, 23, 39, 0.91);
--panel-border: rgba(148, 163, 184, 0.23);
--text: #e5edf8;
--muted: #94a3b8;
--good: #5eead4;
--warn: #fbbf24;
--bad: #fb7185;
--blue: #60a5fa;
}
* { 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;
}
canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
#stage {
position: fixed;
inset: 0;
}
.panel {
position: fixed;
z-index: 10;
background: var(--panel);
border: 1px solid var(--panel-border);
border-radius: 14px;
box-shadow: 0 18px 50px rgba(0, 0, 0, 0.32);
backdrop-filter: blur(14px);
}
#controls {
top: 16px;
left: 16px;
width: 306px;
max-height: calc(100vh - 32px);
overflow: auto;
padding: 17px;
}
#metrics {
top: 16px;
right: 16px;
width: 310px;
padding: 15px;
}
h1 {
margin: 0;
font-size: 20px;
letter-spacing: -0.02em;
}
h2 {
margin: 0 0 8px;
font-size: 13px;
text-transform: uppercase;
letter-spacing: 0.09em;
color: #cbd5e1;
}
p {
margin: 0;
color: var(--muted);
font-size: 12px;
line-height: 1.45;
}
.subtitle {
margin-top: 5px;
}
.rule {
height: 1px;
margin: 14px 0;
background: var(--panel-border);
}
.goal {
padding: 10px;
border: 1px solid rgba(96, 165, 250, 0.2);
border-radius: 10px;
background: rgba(96, 165, 250, 0.07);
}
.piece-list {
display: grid;
gap: 7px;
margin-top: 9px;
}
.piece-button {
width: 100%;
display: flex;
align-items: center;
gap: 9px;
padding: 9px 10px;
border: 1px solid var(--panel-border);
border-radius: 9px;
background: rgba(255, 255, 255, 0.025);
color: var(--text);
cursor: pointer;
text-align: left;
}
.piece-button:hover {
background: rgba(255, 255, 255, 0.065);
}
.piece-button.selected {
border-color: var(--blue);
background: rgba(96, 165, 250, 0.11);
box-shadow: inset 0 0 0 1px rgba(96, 165, 250, 0.15);
}
.swatch {
width: 13px;
height: 13px;
flex: 0 0 auto;
border-radius: 3px;
box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.25);
}
.piece-name {
font-size: 12px;
font-weight: 700;
}
.piece-meta {
margin-left: auto;
font-size: 10px;
color: var(--muted);
}
.row {
display: flex;
gap: 7px;
margin-top: 8px;
}
button {
font: inherit;
}
.action {
flex: 1;
padding: 8px 9px;
border: 1px solid var(--panel-border);
border-radius: 8px;
color: var(--text);
background: rgba(255, 255, 255, 0.045);
cursor: pointer;
font-size: 11px;
font-weight: 650;
}
.action:hover:not(:disabled) {
background: rgba(255, 255, 255, 0.09);
}
.action:disabled {
opacity: 0.42;
cursor: not-allowed;
}
.action.primary {
color: #071827;
background: var(--good);
border-color: var(--good);
}
.action.primary:hover:not(:disabled) {
background: #7be8d7;
}
.action.blue {
color: #071827;
background: var(--blue);
border-color: var(--blue);
}
.label-row {
display: flex;
justify-content: space-between;
align-items: center;
margin: 12px 0 5px;
font-size: 11px;
color: #cbd5e1;
}
.label-row output {
color: var(--muted);
font-variant-numeric: tabular-nums;
}
input[type="range"] {
width: 100%;
accent-color: var(--blue);
}
.small {
font-size: 10px;
color: var(--muted);
line-height: 1.45;
}
.check-row {
display: flex;
align-items: center;
gap: 7px;
margin-top: 11px;
color: #cbd5e1;
font-size: 11px;
}
input[type="checkbox"] {
accent-color: var(--good);
}
#action-status {
min-height: 34px;
margin-top: 11px;
padding: 8px 9px;
border-radius: 8px;
border: 1px solid var(--panel-border);
color: #cbd5e1;
font-size: 11px;
line-height: 1.4;
}
.metric {
padding: 11px 0;
border-bottom: 1px solid var(--panel-border);
}
.metric:last-child {
border-bottom: 0;
}
.metric-title {
font-size: 10px;
letter-spacing: 0.08em;
text-transform: uppercase;
color: var(--muted);
}
.metric-value {
margin-top: 3px;
font-size: 18px;
font-weight: 760;
}
.metric-value[data-state="good"] { color: var(--good); }
.metric-value[data-state="warn"] { color: var(--warn); }
.metric-value[data-state="bad"] { color: var(--bad); }
.metric-value[data-state="muted"] { color: #cbd5e1; }
.metric-detail {
margin-top: 3px;
color: var(--muted);
font-size: 10px;
line-height: 1.4;
}
#hint {
position: fixed;
z-index: 5;
bottom: 15px;
left: 50%;
transform: translateX(-50%);
max-width: min(720px, calc(100vw - 32px));
padding: 8px 12px;
border-radius: 999px;
border: 1px solid var(--panel-border);
background: rgba(8, 17, 31, 0.78);
color: #94a3b8;
font-size: 10px;
text-align: center;
pointer-events: none;
}
@media (max-width: 820px) {
#controls {
width: 268px;
padding: 13px;
}
#metrics {
width: 250px;
padding: 12px;
}
h1 { font-size: 17px; }
}
@media (max-width: 620px) {
#controls {
top: 8px;
left: 8px;
width: calc(100vw - 16px);
max-height: 48vh;
}
#metrics {
top: auto;
right: 8px;
bottom: 48px;
width: calc(100vw - 16px);
}
#hint { display: none; }
}
</style>
</head>
<body>
<div id="stage"></div>
<section id="controls" class="panel">
<h1>Voxel Packing Lab</h1>
<p class="subtitle">Place three physical tetrominoes inside a bounded 4 × 3 × 3 container.</p>
<div class="rule"></div>
<div class="goal">
<h2>Exact comparison goal</h2>
<p>
Feasibility asks whether every required block is inside the container with no overlap.
Optimality separately asks whether your occupied bounding-box volume matches the
exhaustive minimum.
</p>
</div>
<div class="rule"></div>
<h2>1. Choose a block</h2>
<div id="piece-list" class="piece-list"></div>
<div class="label-row">
<span>Current orientation</span>
<output id="orientation-output">—</output>
</div>
<div class="row">
<button class="action" data-axis="x">Rotate X</button>
<button class="action" data-axis="y">Rotate Y</button>
<button class="action" data-axis="z">Rotate Z</button>
</div>
<div class="label-row">
<span>Placement layer</span>
<output id="layer-output">Layer 0</output>
</div>
<input id="layer" type="range" min="0" max="2" value="0" step="1">
<div class="row">
<button id="remove-piece" class="action">Remove selected</button>
<button id="clear-pieces" class="action">Clear all</button>
</div>
<div class="rule"></div>
<h2>2. Exact bounded search</h2>
<p>
The solver enumerates all distinct legal rotations and translations inside the
fixed container, rejecting overlaps. It proves the minimum occupied-envelope
volume by exhaustive search.
</p>
<div class="row">
<button id="solve" class="action primary">Solve exhaustively</button>
<button id="load-best" class="action blue" disabled>Load optimum</button>
</div>
<label class="check-row">
<input id="show-best" type="checkbox">
Show exhaustive optimum in the scene
</label>
<div id="action-status">Hover the highlighted layer, then click to place the selected block.</div>
</section>
<aside id="metrics" class="panel">
<div class="metric">
<div class="metric-title">Feasibility</div>
<div id="feasibility-state" class="metric-value" data-state="warn">Incomplete</div>
<div id="feasibility-detail" class="metric-detail">0 of 3 blocks placed.</div>
</div>
<div class="metric">
<div class="metric-title">Optimality</div>
<div id="optimality-state" class="metric-value" data-state="muted">Not checked</div>
<div id="optimality-detail" class="metric-detail">Run the exhaustive solver to compare.</div>
</div>
<div class="metric">
<div class="metric-title">Occupied envelope</div>
<div id="envelope-state" class="metric-value" data-state="muted">—</div>
<div id="envelope-detail" class="metric-detail">Your current arrangement.</div>
</div>
<div class="metric">
<div class="metric-title">Exhaustive result</div>
<div id="solver-detail" class="metric-detail">Not run.</div>
</div>
</aside>
<div id="hint">
Drag: orbit · Right/middle drag: pan · Wheel: zoom · Click: place/move ·
R/Y: rotate Y · X: rotate X · Z: rotate Z · Delete: remove selected
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Fixed bounded instance
// -------------------------------------------------------------------------
const SIZE = Object.freeze({ x: 4, y: 3, z: 3 });
const VOXEL_SIZE = 0.82;
const PIECES = [
{
id: "L4",
name: "L tetromino",
color: 0x5eead4,
base: [
[0, 0, 0],
[1, 0, 0],
[2, 0, 0],
[0, 1, 0]
]
},
{
id: "T4",
name: "T tetromino",
color: 0xf59e0b,
base: [
[0, 0, 0],
[1, 0, 0],
[2, 0, 0],
[1, 1, 0]
]
},
{
id: "I4",
name: "I tetromino",
color: 0x8b5cf6,
base: [
[0, 0, 0],
[1, 0, 0],
[2, 0, 0],
[3, 0, 0]
]
}
];
const cellKey = (x, y, z) => `${x},${y},${z}`;
function normalizeShape(cells) {
const min = [Infinity, Infinity, Infinity];
for (const [x, y, z] of cells) {
min[0] = Math.min(min[0], x);
min[1] = Math.min(min[1], y);
min[2] = Math.min(min[2], z);
}
return cells
.map(([x, y, z]) => [x - min[0], y - min[1], z - min[2]])
.sort((a, b) => a[0] - b[0] || a[1] - b[1] || a[2] - b[2]);
}
function shapeKey(cells) {
return JSON.stringify(cells);
}
function shapeDimensions(cells) {
return [
Math.max(...cells.map(c => c[0])) + 1,
Math.max(...cells.map(c => c[1])) + 1,
Math.max(...cells.map(c => c[2])) + 1
];
}
const PERMUTATIONS = [
[0, 1, 2], [0, 2, 1], [1, 0, 2],
[1, 2, 0], [2, 0, 1], [2, 1, 0]
];
function permutationParity(p) {
let inversions = 0;
for (let i = 0; i < 3; i++) {
for (let j = i + 1; j < 3; j++) {
if (p[i] > p[j]) inversions++;
}
}
return inversions % 2 === 0 ? 1 : -1;
}
function generateOrientations(base) {
const seen = new Set();
const result = [];
for (const p of PERMUTATIONS) {
for (let signBits = 0; signBits < 8; signBits++) {
const signs = [
signBits & 1 ? -1 : 1,
signBits & 2 ? -1 : 1,
signBits & 4 ? -1 : 1
];
// Proper 90-degree cube rotations only; no reflections.
const determinant =
permutationParity(p) * signs[0] * signs[1] * signs[2];
if (determinant !== 1) continue;
const rotated = base.map(([x, y, z]) => [
signs[0] * [x, y, z][p[0]],
signs[1] * [x, y, z][p[1]],
signs[2] * [x, y, z][p[2]]
]);
const normalized = normalizeShape(rotated);
const key = shapeKey(normalized);
if (!seen.has(key)) {
seen.add(key);
result.push(normalized);
}
}
}
return result;
}
function rotateShape(shape, axis) {
let rotated;
if (axis === "x") {
rotated = shape.map(([x, y, z]) => [x, -z, y]);
} else if (axis === "y") {
rotated = shape.map(([x, y, z]) => [z, y, -x]);
} else {
rotated = shape.map(([x, y, z]) => [-y, x, z]);
}
return normalizeShape(rotated);
}
for (const piece of PIECES) {
piece.orientations = generateOrientations(piece.base);
piece.orientationIndex = 0;
}
function makePlacements(pieceIndex) {
const piece = PIECES[pieceIndex];
const placements = [];
piece.orientations.forEach((shape, orientationIndex) => {
const [dx, dy, dz] = shapeDimensions(shape);
for (let az = 0; az <= SIZE.z - dz; az++) {
for (let ay = 0; ay <= SIZE.y - dy; ay++) {
for (let ax = 0; ax <= SIZE.x - dx; ax++) {
const cells = shape.map(([x, y, z]) => [
ax + x,
ay + y,
az + z
]);
let mask = 0n;
for (const [x, y, z] of cells) {
const index = x + SIZE.x * (y + SIZE.y * z);
mask |= 1n << BigInt(index);
}
placements.push({
pieceIndex,
orientationIndex,
ax,
ay,
az,
cells,
mask,
bbox: {
minX: ax,
minY: ay,
minZ: az,
maxX: ax + dx - 1,
maxY: ay + dy - 1,
maxZ: az + dz - 1
}
});
}
}
}
});
return placements;
}
const allPlacements = PIECES.map((_, i) => makePlacements(i));
// -------------------------------------------------------------------------
// Scene
// -------------------------------------------------------------------------
const stage = document.getElementById("stage");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x08111f);
scene.fog = new THREE.Fog(0x08111f, 15, 30);
const camera = new THREE.PerspectiveCamera(
45,
innerWidth / innerHeight,
0.1,
100
);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
stage.appendChild(renderer.domElement);
scene.add(new THREE.HemisphereLight(0xbdd8ff, 0x172033, 2.0));
const keyLight = new THREE.DirectionalLight(0xffffff, 2.8);
keyLight.position.set(5, 9, 7);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(1024, 1024);
keyLight.shadow.camera.left = -6;
keyLight.shadow.camera.right = 6;
keyLight.shadow.camera.top = 6;
keyLight.shadow.camera.bottom = -6;
keyLight.shadow.normalBias = 0.025;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x60a5fa, 1.3);
rimLight.position.set(-5, 3, -6);
scene.add(rimLight);
const userGroup = new THREE.Group();
const previewGroup = new THREE.Group();
const bestGroup = new THREE.Group();
scene.add(userGroup, previewGroup, bestGroup);
const voxelGeometry = new THREE.BoxGeometry(
VOXEL_SIZE, VOXEL_SIZE, VOXEL_SIZE
);
const voxelEdgeGeometry = new THREE.EdgesGeometry(voxelGeometry);
const voxelEdgeMaterial = new THREE.LineBasicMaterial({
color: 0x07111d,
transparent: true,
opacity: 0.65
});
const pieceMaterials = PIECES.map(piece => new THREE.MeshStandardMaterial({
color: piece.color,
roughness: 0.72,
metalness: 0.04,
flatShading: true
}));
const validGhostMaterial = new THREE.MeshBasicMaterial({
color: 0x5eead4,
transparent: true,
opacity: 0.34,
depthWrite: false
});
const invalidGhostMaterial = new THREE.MeshBasicMaterial({
color: 0xfb7185,
transparent: true,
opacity: 0.27,
depthWrite: false
});
const bestLineMaterial = new THREE.LineBasicMaterial({
color: 0x67e8f9,
transparent: true,
opacity: 0.9
});
const bestFillMaterial = new THREE.MeshBasicMaterial({
color: 0x22d3ee,
transparent: true,
opacity: 0.08,
depthWrite: false
});
function cellToWorld(cell) {
const [x, y, z] = cell;
return new THREE.Vector3(
-SIZE.x / 2 + x + 0.5,
-SIZE.y / 2 + y + 0.5,
-SIZE.z / 2 + z + 0.5
);
}
function clearGroup(group) {
while (group.children.length) {
group.remove(group.children[0]);
}
}
function addSolidVoxel(group, cell, pieceIndex) {
const mesh = new THREE.Mesh(voxelGeometry, pieceMaterials[pieceIndex]);
mesh.position.copy(cellToWorld(cell));
mesh.castShadow = true;
mesh.receiveShadow = true;
const edges = new THREE.LineSegments(
voxelEdgeGeometry,
voxelEdgeMaterial
);
mesh.add(edges);
group.add(mesh);
}
function addBestVoxel(cell) {
const group = new THREE.Group();
group.position.copy(cellToWorld(cell));
const fill = new THREE.Mesh(voxelGeometry, bestFillMaterial);
const edges = new THREE.LineSegments(
voxelEdgeGeometry,
bestLineMaterial
);
group.add(fill, edges);
bestGroup.add(group);
}
// Container frame and voxel lattice.
const frameGeometry = new THREE.EdgesGeometry(
new THREE.BoxGeometry(SIZE.x, SIZE.y, SIZE.z)
);
const frame = new THREE.LineSegments(
frameGeometry,
new THREE.LineBasicMaterial({
color: 0x94a3b8,
transparent: true,
opacity: 0.62
})
);
scene.add(frame);
const gridPositions = [];
function addLine(a, b) {
gridPositions.push(a[0], a[1], a[2], b[0], b[1], b[2]);
}
for (let y = 0; y <= SIZE.y; y++) {
const wy = -SIZE.y / 2 + y;
const x0 = -SIZE.x / 2;
const x1 = SIZE.x / 2;
const z0 = -SIZE.z / 2;
const z1 = SIZE.z / 2;
addLine([x0, wy, z0], [x1, wy, z0]);
addLine([x1, wy, z0], [x1, wy, z1]);
addLine([x1, wy, z1], [x0, wy, z1]);
addLine([x0, wy, z1], [x0, wy, z0]);
}
for (let x = 0; x <= SIZE.x; x++) {
for (let z = 0; z <= SIZE.z; z++) {
const wx = -SIZE.x / 2 + x;
const wz = -SIZE.z / 2 + z;
addLine(
[wx, -SIZE.y / 2, wz],
[wx, SIZE.y / 2, wz]
);
}
}
const gridGeometry = new THREE.BufferGeometry();
gridGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(gridPositions, 3)
);
const grid = new THREE.LineSegments(
gridGeometry,
new THREE.LineBasicMaterial({
color: 0x64748b,
transparent: true,
opacity: 0.18
})
);
scene.add(grid);
const layerPlane = new THREE.Mesh(
new THREE.PlaneGeometry(SIZE.x, SIZE.z),
new THREE.MeshBasicMaterial({
color: 0x60a5fa,
transparent: true,
opacity: 0.075,
side: THREE.DoubleSide,
depthWrite: false
})
);
layerPlane.rotation.x = -Math.PI / 2;
scene.add(layerPlane);
// -------------------------------------------------------------------------
// Direct camera controls: orbit, pan, zoom
// -------------------------------------------------------------------------
const cameraState = {
target: new THREE.Vector3(0, 0, 0),
radius: 10.5,
theta: 0.68,
phi: 1.03
};
function updateCamera() {
const { radius, theta, phi, target } = cameraState;
const sinPhi = Math.sin(phi);
camera.position.set(
target.x + radius * sinPhi * Math.sin(theta),
target.y + radius * Math.cos(phi),
target.z + radius * sinPhi * Math.cos(theta)
);
camera.lookAt(target);
}
function panCamera(dx, dy) {
const forward = cameraState.target.clone()
.sub(camera.position)
.normalize();
const right = new THREE.Vector3()
.crossVectors(forward, camera.up)
.normalize();
const screenUp = new THREE.Vector3()
.crossVectors(right, forward)
.normalize();
const scale = cameraState.radius * 0.0014;
cameraState.target
.addScaledVector(right, -dx * scale)
.addScaledVector(screenUp, dy * scale);
cameraState.target.x = THREE.MathUtils.clamp(
cameraState.target.x, -5, 5
);
cameraState.target.y = THREE.MathUtils.clamp(
cameraState.target.y, -3, 3
);
cameraState.target.z = THREE.MathUtils.clamp(
cameraState.target.z, -5, 5
);
}
const canvas = renderer.domElement;
const raycaster = new THREE.Raycaster();
const pointerNDC = new THREE.Vector2();
const planeIntersection = new THREE.Vector3();
const placementPlane = new THREE.Plane(new THREE.Vector3(0, 1, 0), 0);
let pointerInside = false;
let drag = null;
function updatePointerNDC(event) {
const rect = canvas.getBoundingClientRect();
pointerNDC.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointerNDC.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
}
canvas.addEventListener("contextmenu", event => event.preventDefault());
canvas.addEventListener("pointerdown", event => {
updatePointerNDC(event);
pointerInside = true;
drag = {
button: event.button,
lastX: event.clientX,
lastY: event.clientY,
startX: event.clientX,
startY: event.clientY,
moved: false
};
canvas.setPointerCapture(event.pointerId);
updatePreview();
});
canvas.addEventListener("pointermove", event => {
updatePointerNDC(event);
pointerInside = true;
if (!drag) {
updatePreview();
return;
}
const dx = event.clientX - drag.lastX;
const dy = event.clientY - drag.lastY;
drag.lastX = event.clientX;
drag.lastY = event.clientY;
const totalDistance = Math.hypot(
event.clientX - drag.startX,
event.clientY - drag.startY
);
if (totalDistance > 4) drag.moved = true;
if (drag.moved) {
if (drag.button === 0) {
cameraState.theta -= dx * 0.006;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi - dy * 0.006,
0.18,
Math.PI - 0.18
);
} else {
panCamera(dx, dy);
}
}
});
canvas.addEventListener("pointerup", event => {
if (drag && !drag.moved && drag.button === 0) {
tryPlaceAtPreview();
}
drag = null;
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
updatePreview();
});
canvas.addEventListener("pointercancel", () => {
drag = null;
});
canvas.addEventListener("pointerleave", () => {
if (!drag) {
pointerInside = false;
clearGroup(previewGroup);
}
});
canvas.addEventListener("wheel", event => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
6,
24
);
}, { passive: false });
// -------------------------------------------------------------------------
// User arrangement
// -------------------------------------------------------------------------
let selectedPiece = 0;
let selectedLayer = 0;
let hoverCell = null;
let previewCells = [];
let previewValid = false;
let solverResult = null;
const userPlacements = [null, null, null];
const pieceList = document.getElementById("piece-list");
const layerInput = document.getElementById("layer");
const layerOutput = document.getElementById("layer-output");
const orientationOutput = document.getElementById("orientation-output");
const actionStatus = document.getElementById("action-status");
const pieceButtons = PIECES.map((piece, index) => {
const button = document.createElement("button");
button.className = "piece-button";
button.type = "button";
button.innerHTML = `
<span class="swatch" style="background:#${piece.color.toString(16).padStart(6, "0")}"></span>
<span class="piece-name">${piece.name}</span>
<span class="piece-meta">${piece.id}</span>
`;
button.addEventListener("click", () => {
selectedPiece = index;
updateSelectionUI();
updatePreview();
});
pieceList.appendChild(button);
return button;
});
function updateSelectionUI() {
pieceButtons.forEach((button, index) => {
button.classList.toggle("selected", index === selectedPiece);
});
const piece = PIECES[selectedPiece];
const orientation = piece.orientations[piece.orientationIndex];
const dimensions = shapeDimensions(orientation);
orientationOutput.textContent =
`${piece.orientationIndex + 1}/${piece.orientations.length} · ` +
`${dimensions[0]}×${dimensions[1]}×${dimensions[2]}`;
layerOutput.textContent = `Layer ${selectedLayer}`;
layerPlane.position.y = -SIZE.y / 2 + selectedLayer + 0.007;
layerPlane.material.color.setHex(piece.color);
}
function currentShape() {
const piece = PIECES[selectedPiece];
return piece.orientations[piece.orientationIndex];
}
function cellsAreInBounds(cells) {
return cells.every(([x, y, z]) =>
x >= 0 && x < SIZE.x &&
y >= 0 && y < SIZE.y &&
z >= 0 && z < SIZE.z
);
}
function occupiedCellsExcluding(pieceIndex) {
const occupied = new Set();
for (let i = 0; i < userPlacements.length; i++) {
if (i === pieceIndex) continue;
const placement = userPlacements[i];
if (!placement) continue;
for (const cell of placement.cells) {
occupied.add(cellKey(...cell));
}
}
return occupied;
}
function updatePreview() {
clearGroup(previewGroup);
previewCells = [];
previewValid = false;
if (!pointerInside || !hoverCell) return;
const shape = currentShape();
const occupied = occupiedCellsExcluding(selectedPiece);
previewCells = shape.map(([x, y, z]) => [
hoverCell.x + x,
selectedLayer + y,
hoverCell.z + z
]);
const inBounds = cellsAreInBounds(previewCells);
const collision = previewCells.some(cell =>
occupied.has(cellKey(...cell))
);
previewValid = inBounds && !collision;
const material = previewValid
? validGhostMaterial
: invalidGhostMaterial;
for (const cell of previewCells) {
const voxel = new THREE.Mesh(voxelGeometry, material);
voxel.position.copy(cellToWorld(cell));
previewGroup.add(voxel);
}
}
function updateHoverCell() {
if (!pointerInside) {
hoverCell = null;
return;
}
raycaster.setFromCamera(pointerNDC, camera);
const planeY = -SIZE.y / 2 + selectedLayer + 0.007;
placementPlane.constant = -planeY;
if (!raycaster.ray.intersectPlane(
placementPlane,
planeIntersection
)) {
hoverCell = null;
return;
}
const gx = Math.floor(planeIntersection.x + SIZE.x / 2);
const gz = Math.floor(planeIntersection.z + SIZE.z / 2);
if (
gx >= 0 && gx < SIZE.x &&
gz >= 0 && gz < SIZE.z
) {
hoverCell = { x: gx, z: gz };
} else {
hoverCell = null;
}
}
function tryPlaceAtPreview() {
updateHoverCell();
updatePreview();
if (!hoverCell || !previewCells.length) {
actionStatus.textContent =
"Click over the highlighted placement layer to place the selected block.";
return;
}
if (!previewValid) {
const inBounds = cellsAreInBounds(previewCells);
actionStatus.textContent = inBounds
? "That placement overlaps another block. Choose an empty region."
: "That rotation does not fit at this layer. Rotate it or choose a lower layer.";
return;
}
const shape = currentShape();
userPlacements[selectedPiece] = {
pieceIndex: selectedPiece,
orientationIndex: PIECES[selectedPiece].orientationIndex,
ax: hoverCell.x,
ay: selectedLayer,
az: hoverCell.z,
cells: previewCells.map(cell => [...cell]),
bbox: {
minX: hoverCell.x,
minY: selectedLayer,
minZ: hoverCell.z,
maxX: hoverCell.x + shapeDimensions(shape)[0] - 1,
maxY: selectedLayer + shapeDimensions(shape)[1] - 1,
maxZ: hoverCell.z + shapeDimensions(shape)[2] - 1
}
};
actionStatus.textContent =
`${PIECES[selectedPiece].name} placed at ` +
`x=${hoverCell.x}, y=${selectedLayer}, z=${hoverCell.z}.`;
syncUserScene();
}
function rotateSelected(axis) {
const piece = PIECES[selectedPiece];
const current = piece.orientations[piece.orientationIndex];
const rotated = rotateShape(current, axis);
const nextIndex = piece.orientations.findIndex(
shape => shapeKey(shape) === shapeKey(rotated)
);
if (nextIndex < 0) return;
piece.orientationIndex = nextIndex;
if (userPlacements[selectedPiece]) {
userPlacements[selectedPiece] = null;
actionStatus.textContent =
"Selected block was removed so it could be rotated. Click to place it again.";
} else {
actionStatus.textContent =
`Rotated ${piece.name} around ${axis.toUpperCase()}.`;
}
updateSelectionUI();
syncUserScene();
updatePreview();
}
layerInput.addEventListener("input", () => {
selectedLayer = Number(layerInput.value);
updateSelectionUI();
updateHoverCell();
updatePreview();
});
document.querySelectorAll("[data-axis]").forEach(button => {
button.addEventListener("click", () => {
rotateSelected(button.dataset.axis);
});
});
document.getElementById("remove-piece").addEventListener("click", () => {
if (!userPlacements[selectedPiece]) {
actionStatus.textContent = "That block is not currently placed.";
return;
}
userPlacements[selectedPiece] = null;
actionStatus.textContent = `${PIECES[selectedPiece].name} removed.`;
syncUserScene();
updatePreview();
});
document.getElementById("clear-pieces").addEventListener("click", () => {
userPlacements.fill(null);
actionStatus.textContent = "All user placements cleared.";
syncUserScene();
updatePreview();
});
window.addEventListener("keydown", event => {
if (["INPUT", "TEXTAREA", "SELECT"].includes(event.target.tagName)) {
return;
}
const key = event.key.toLowerCase();
if (key === "r" || key === "y") rotateSelected("y");
if (key === "x") rotateSelected("x");
if (key === "z") rotateSelected("z");
if (event.key === "Delete" || event.key === "Backspace") {
event.preventDefault();
document.getElementById("remove-piece").click();
}
});
// -------------------------------------------------------------------------
// Arrangement evaluation
// -------------------------------------------------------------------------
function unionBBox(a, b) {
if (!a) return { ...b };
return {
minX: Math.min(a.minX, b.minX),
minY: Math.min(a.minY, b.minY),
minZ: Math.min(a.minZ, b.minZ),
maxX: Math.max(a.maxX, b.maxX),
maxY: Math.max(a.maxY, b.maxY),
maxZ: Math.max(a.maxZ, b.maxZ)
};
}
function bboxVolume(bbox) {
if (!bbox) return 0;
return (
(bbox.maxX - bbox.minX + 1) *
(bbox.maxY - bbox.minY + 1) *
(bbox.maxZ - bbox.minZ + 1)
);
}
function bboxDimensions(bbox) {
if (!bbox) return [0, 0, 0];
return [
bbox.maxX - bbox.minX + 1,
bbox.maxY - bbox.minY + 1,
bbox.maxZ - bbox.minZ + 1
];
}
function evaluateUserArrangement() {
const occupied = new Map();
let overlap = false;
let outOfBounds = false;
let bbox = null;
let placedCount = 0;
for (const placement of userPlacements) {
if (!placement) continue;
placedCount++;
bbox = unionBBox(bbox, placement.bbox);
for (const cell of placement.cells) {
const key = cellKey(...cell);
if (!cellsAreInBounds([cell])) outOfBounds = true;
if (occupied.has(key)) overlap = true;
occupied.set(key, true);
}
}
const feasible =
placedCount === PIECES.length && !overlap && !outOfBounds;
return {
placedCount,
overlap,
outOfBounds,
feasible,
bbox,
volume: bboxVolume(bbox),
dimensions: bboxDimensions(bbox)
};
}
function setMetricState(element, text, state) {
element.textContent = text;
element.dataset.state = state;
}
function syncUserScene() {
clearGroup(userGroup);
for (let pieceIndex = 0; pieceIndex < userPlacements.length; pieceIndex++) {
const placement = userPlacements[pieceIndex];
if (!placement) continue;
for (const cell of placement.cells) {
addSolidVoxel(userGroup, cell, pieceIndex);
}
}
updateMetrics();
}
function updateMetrics() {
const evaluation = evaluateUserArrangement();
if (evaluation.overlap) {
setMetricState(
document.getElementById("feasibility-state"),
"Invalid",
"bad"
);
document.getElementById("feasibility-detail").textContent =
"Two or more occupied voxel cells overlap.";
} else if (evaluation.outOfBounds) {
setMetricState(
document.getElementById("feasibility-state"),
"Invalid",
"bad"
);
document.getElementById("feasibility-detail").textContent =
"At least one occupied voxel is outside the container.";
} else if (!evaluation.feasible) {
setMetricState(
document.getElementById("feasibility-state"),
"Incomplete",
"warn"
);
document.getElementById("feasibility-detail").textContent =
`${evaluation.placedCount} of ${PIECES.length} blocks placed.`;
} else {
setMetricState(
document.getElementById("feasibility-state"),
"Feasible",
"good"
);
document.getElementById("feasibility-detail").textContent =
"All 3 blocks are inside the container with no overlap.";
}
if (!solverResult) {
setMetricState(
document.getElementById("optimality-state"),
"Not checked",
"muted"
);
document.getElementById("optimality-detail").textContent =
"Run the exhaustive solver to compare.";
} else if (!solverResult.feasible) {
setMetricState(
document.getElementById("optimality-state"),
"No packing",
"bad"
);
document.getElementById("optimality-detail").textContent =
"The exhaustive search found no legal packing of all blocks.";
} else if (!evaluation.feasible) {
setMetricState(
document.getElementById("optimality-state"),
"Not assessed",
"muted"
);
document.getElementById("optimality-detail").textContent =
"Complete a feasible arrangement before assessing optimality.";
} else if (evaluation.volume === solverResult.bestVolume) {
setMetricState(
document.getElementById("optimality-state"),
"Optimal",
"good"
);
document.getElementById("optimality-detail").textContent =
"Your occupied envelope matches the exhaustive minimum. Ties are also optimal.";
} else {
setMetricState(
document.getElementById("optimality-state"),
"Suboptimal",
"warn"
);
document.getElementById("optimality-detail").textContent =
`Your envelope is ${evaluation.volume - solverResult.bestVolume} voxel³ larger than the exact optimum.`;
}
if (evaluation.bbox) {
setMetricState(
document.getElementById("envelope-state"),
`${evaluation.volume} voxel³`,
evaluation.feasible ? "good" : "warn"
);
document.getElementById("envelope-detail").textContent =
`Current bounds: ${evaluation.dimensions.join(" × ")} in X × Y × Z order.`;
} else {
setMetricState(
document.getElementById("envelope-state"),
"—",
"muted"
);
document.getElementById("envelope-detail").textContent =
"Place at least one block.";
}
if (solverResult?.feasible && evaluation.feasible) {
const gap = evaluation.volume - solverResult.bestVolume;
document.getElementById("envelope-detail").textContent +=
gap === 0
? " Exact optimum matched."
: ` Exact optimum: ${solverResult.bestVolume} voxel³; gap: ${gap}.`;
}
}
// -------------------------------------------------------------------------
// Exhaustive solver
//
// Objective:
// Place every required block without overlap, then minimize the volume
// of the axis-aligned bounding box containing all occupied cells.
//
// The search is exhaustive for the fixed bounded instance. A branch can
// be pruned only after its already-occupied envelope is no smaller than
// the best complete solution already found; adding cells cannot shrink
// that envelope.
// -------------------------------------------------------------------------
function runExhaustiveSolver() {
const pieceOrder = [0, 1, 2].sort(
(a, b) => allPlacements[a].length - allPlacements[b].length
);
let bestVolume = Infinity;
let bestPlacements = null;
let searchStates = 0;
function search(depth, usedMask, bbox, chosen) {
searchStates++;
if (depth === pieceOrder.length) {
const volume = bboxVolume(bbox);
if (volume < bestVolume) {
bestVolume = volume;
bestPlacements = chosen.map(placement =>
placement ? {
...placement,
cells: placement.cells.map(cell => [...cell]),
bbox: { ...placement.bbox }
} : null
);
}
return;
}
const pieceIndex = pieceOrder[depth];
for (const placement of allPlacements[pieceIndex]) {
if ((usedMask & placement.mask) !== 0n) continue;
const nextBBox = unionBBox(bbox, placement.bbox);
const nextVolume = bboxVolume(nextBBox);
// Union envelopes never shrink, so this branch cannot improve.
if (nextVolume >= bestVolume) continue;
chosen[pieceIndex] = placement;
search(
depth + 1,
usedMask | placement.mask,
nextBBox,
chosen
);
chosen[pieceIndex] = null;
}
}
search(0, 0n, null, [null, null, null]);
const legalPlacementCount = allPlacements.reduce(
(sum, placements) => sum + placements.length,
0
);
if (!bestPlacements) {
return {
feasible: false,
bestVolume: null,
bestDimensions: null,
bestPlacements: null,
legalPlacementCount,
searchStates
};
}
const finalBBox = bestPlacements.reduce(
(bbox, placement) => unionBBox(bbox, placement.bbox),
null
);
return {
feasible: true,
bestVolume,
bestDimensions: bboxDimensions(finalBBox),
bestPlacements,
legalPlacementCount,
searchStates
};
}
function drawBestArrangement() {
clearGroup(bestGroup);
if (!solverResult?.bestPlacements) return;
for (const placement of solverResult.bestPlacements) {
for (const cell of placement.cells) {
addBestVoxel(cell);
}
}
bestGroup.visible = document.getElementById("show-best").checked;
}
document.getElementById("solve").addEventListener("click", () => {
const button = document.getElementById("solve");
button.disabled = true;
button.textContent = "Searching…";
actionStatus.textContent =
"Enumerating every legal bounded placement and overlap-free combination…";
// Yield once so the searching state is painted before the exact scan.
setTimeout(() => {
try {
solverResult = runExhaustiveSolver();
if (solverResult.feasible) {
document.getElementById("solver-detail").textContent =
`Exact optimum: ${solverResult.bestVolume} voxel³ ` +
`(${solverResult.bestDimensions.join("×")}). ` +
`${solverResult.legalPlacementCount} legal placements; ` +
`${solverResult.searchStates.toLocaleString()} search states.`;
document.getElementById("load-best").disabled = false;
actionStatus.textContent =
"Exhaustive search complete. Load the optimum or compare your envelope.";
} else {
document.getElementById("solver-detail").textContent =
`No feasible packing exists. ${solverResult.legalPlacementCount} ` +
`legal placements were exhaustively considered.`;
actionStatus.textContent =
"The exhaustive search proved that no legal packing exists.";
}
drawBestArrangement();
syncUserScene();
} catch (error) {
console.error(error);
actionStatus.textContent =
"The solver encountered an unexpected error. See the console.";
document.getElementById("solver-detail").textContent =
"Solver error; no optimality claim is being made.";
} finally {
button.disabled = false;
button.textContent = "Solve exhaustively";
}
}, 30);
});
document.getElementById("load-best").addEventListener("click", () => {
if (!solverResult?.bestPlacements) return;
for (let i = 0; i < PIECES.length; i++) {
const placement = solverResult.bestPlacements[i];
userPlacements[i] = placement ? {
pieceIndex: i,
orientationIndex: placement.orientationIndex,
ax: placement.ax,
ay: placement.ay,
az: placement.az,
cells: placement.cells.map(cell => [...cell]),
bbox: { ...placement.bbox }
} : null;
}
bestGroup.visible = false;
actionStatus.textContent =
"Loaded the exhaustive optimum into the user arrangement.";
syncUserScene();
updatePreview();
});
document.getElementById("show-best").addEventListener("change", event => {
bestGroup.visible = event.target.checked;
});
// -------------------------------------------------------------------------
// Resize and render loop
// -------------------------------------------------------------------------
window.addEventListener("resize", () => {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
});
function animate() {
updateCamera();
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
updateSelectionUI();
syncUserScene();
animate();
</script>
</body>
</html>
```