Prompt specification
Build or customize the Three.js 3D scene "Cubes comparing surface area and volume" 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: Cubes comparing surface area and volume
Category: Biology & Nature · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/cubes-comparing-surface-area-and-volume-x0869
Scene Description Prompt:
Compare exact surface area and volume of low-poly cell-like cubes with gridded faces and removable blocks. Three.js from cdnjs, one HTML file.
Working Three.js Starter (cubes-comparing-surface-area-and-volume-x0869):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Voxel Compare — Exact Surface Area & Volume</title>
<style>
:root {
color-scheme: dark;
--bg: #07101d;
--panel: #0c1727;
--panel-2: #111e31;
--line: #213249;
--text: #eaf2ff;
--muted: #8fa4bd;
--a: #8b7cff;
--b: #28d7e5;
--accent: #ffc857;
--good: #4ade80;
--bad: #fb7185;
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button, input, select { font: inherit; }
button, select {
color: var(--text);
border: 1px solid var(--line);
background: #101d30;
}
button {
border-radius: 10px;
cursor: pointer;
transition: border-color .18s, background .18s, transform .18s;
}
button:hover:not(:disabled) {
border-color: #47617e;
background: #172840;
}
button:active:not(:disabled) { transform: translateY(1px); }
button:disabled {
opacity: .38;
cursor: not-allowed;
}
header {
height: 70px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 18px;
padding: 0 22px;
border-bottom: 1px solid var(--line);
background: rgba(8, 18, 32, .94);
}
.brand {
display: flex;
align-items: center;
gap: 13px;
min-width: 0;
}
.brand-icon {
position: relative;
width: 32px;
height: 32px;
transform: rotate(-12deg);
border: 2px solid var(--b);
border-radius: 7px;
box-shadow: inset 0 0 18px rgba(40, 215, 229, .12);
}
.brand-icon::before,
.brand-icon::after {
content: "";
position: absolute;
background: var(--b);
opacity: .6;
}
.brand-icon::before {
left: 50%;
top: 0;
width: 1px;
height: 100%;
}
.brand-icon::after {
left: 0;
top: 50%;
width: 100%;
height: 1px;
}
.brand h1 {
margin: 0;
font-size: 17px;
letter-spacing: .08em;
text-transform: uppercase;
white-space: nowrap;
}
.brand p {
margin: 3px 0 0;
color: var(--muted);
font-size: 12px;
}
.header-actions {
display: flex;
align-items: center;
gap: 10px;
}
.status {
display: inline-flex;
align-items: center;
gap: 7px;
color: #b9c8d9;
font-size: 11px;
letter-spacing: .08em;
text-transform: uppercase;
white-space: nowrap;
}
.status::before {
content: "";
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--good);
box-shadow: 0 0 12px rgba(74, 222, 128, .75);
}
.quiet-button {
height: 36px;
padding: 0 13px;
font-size: 12px;
}
.workspace {
display: grid;
grid-template-columns: 344px minmax(0, 1fr);
height: calc(100% - 70px);
}
aside {
min-height: 0;
overflow-y: auto;
border-right: 1px solid var(--line);
background: linear-gradient(180deg, #0b1626, #091321);
scrollbar-width: thin;
scrollbar-color: #29405b transparent;
}
.section {
padding: 19px 20px;
border-bottom: 1px solid var(--line);
}
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
margin: 0 0 13px;
color: #9eb2c8;
font-size: 11px;
font-weight: 700;
letter-spacing: .13em;
text-transform: uppercase;
}
.cell-card {
padding: 14px;
margin-bottom: 12px;
border: 1px solid var(--line);
border-radius: 14px;
background: rgba(17, 30, 49, .76);
}
.cell-card:last-child { margin-bottom: 0; }
.cell-head {
display: flex;
align-items: center;
gap: 10px;
margin-bottom: 12px;
}
.cell-badge {
display: grid;
place-items: center;
width: 27px;
height: 27px;
border-radius: 8px;
font-size: 12px;
font-weight: 800;
}
.cell-badge.a {
color: #fff;
background: rgba(139, 124, 255, .22);
border: 1px solid rgba(139, 124, 255, .65);
}
.cell-badge.b {
color: #06151a;
background: var(--b);
}
.cell-head strong {
display: block;
font-size: 13px;
}
.cell-head small {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 10px;
}
select {
width: 100%;
height: 38px;
padding: 0 10px;
border-radius: 9px;
outline: none;
}
.preset-grid {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 7px;
}
.preset-button {
min-height: 35px;
padding: 7px 9px;
color: #aebed0;
font-size: 11px;
}
.preset-button.active {
color: #dffcff;
border-color: rgba(40, 215, 229, .75);
background: rgba(40, 215, 229, .12);
box-shadow: inset 0 0 0 1px rgba(40, 215, 229, .08);
}
.range-head {
display: flex;
align-items: center;
justify-content: space-between;
margin: 16px 0 7px;
color: #afc0d3;
font-size: 11px;
}
.range-head output {
color: var(--text);
font-variant-numeric: tabular-nums;
}
input[type="range"] {
width: 100%;
accent-color: var(--b);
cursor: pointer;
}
.button-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 13px;
}
.button-row .wide { grid-column: 1 / -1; }
.action-button {
min-height: 37px;
padding: 8px 10px;
font-size: 11px;
font-weight: 650;
}
.action-button.primary {
color: #07151a;
border-color: var(--b);
background: var(--b);
}
.action-button.primary.active {
color: #221700;
border-color: var(--accent);
background: var(--accent);
box-shadow: 0 0 22px rgba(255, 200, 87, .18);
}
.edit-help {
margin: 9px 0 0;
color: var(--muted);
font-size: 10px;
line-height: 1.5;
}
.metric-pair {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 12px;
}
.metric-tile {
padding: 11px;
border-radius: 10px;
background: #091321;
border: 1px solid #1c2c40;
}
.metric-tile span {
display: block;
color: var(--muted);
font-size: 9px;
letter-spacing: .09em;
text-transform: uppercase;
}
.metric-tile strong {
display: block;
margin-top: 5px;
font-size: 18px;
font-variant-numeric: tabular-nums;
}
.metric-tile small {
color: var(--muted);
font-size: 10px;
}
table {
width: 100%;
border-collapse: collapse;
font-size: 11px;
}
th, td {
padding: 9px 5px;
border-bottom: 1px solid #1a293c;
text-align: right;
font-variant-numeric: tabular-nums;
}
th {
color: var(--muted);
font-size: 9px;
letter-spacing: .07em;
text-transform: uppercase;
}
th:first-child, td:first-child { text-align: left; }
tr:last-child td { border-bottom: 0; }
td.delta.positive { color: #ff9aaa; }
td.delta.negative { color: #67e8f9; }
td.delta.zero { color: var(--muted); }
.formula {
margin-top: 13px;
padding: 12px;
border: 1px solid #21334a;
border-radius: 10px;
color: #9fb2c7;
background: #081321;
font-size: 10px;
line-height: 1.55;
}
.formula code {
display: block;
margin-bottom: 5px;
color: #d7e7f8;
font-size: 11px;
}
.stats-line {
margin-top: 10px;
color: #6f859d;
font-size: 10px;
line-height: 1.5;
}
.stage {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
background:
radial-gradient(circle at 50% 34%, rgba(42, 78, 115, .15), transparent 45%),
#07101d;
}
canvas {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
outline: none;
}
.scene-title {
position: absolute;
z-index: 2;
top: 20px;
left: 22px;
pointer-events: none;
}
.scene-title h2 {
margin: 0;
font-size: 15px;
font-weight: 650;
letter-spacing: .02em;
}
.scene-title p {
margin: 5px 0 0;
color: var(--muted);
font-size: 10px;
}
.model-label {
position: absolute;
z-index: 3;
display: flex;
align-items: center;
gap: 7px;
padding: 7px 9px;
border: 1px solid rgba(255, 255, 255, .12);
border-radius: 9px;
color: #eaf2ff;
background: rgba(7, 16, 29, .88);
backdrop-filter: blur(8px);
font-size: 10px;
pointer-events: none;
transform: translate(-50%, -100%);
white-space: nowrap;
}
.model-label .dot {
width: 7px;
height: 7px;
border-radius: 50%;
}
.model-label.a .dot { background: var(--a); }
.model-label.b .dot { background: var(--b); }
.model-label b { color: #fff; font-weight: 650; }
.scene-hint {
position: absolute;
z-index: 3;
left: 50%;
bottom: 205px;
transform: translateX(-50%);
padding: 8px 12px;
border: 1px solid rgba(255, 255, 255, .09);
border-radius: 999px;
color: #9eb0c4;
background: rgba(6, 14, 25, .78);
font-size: 10px;
pointer-events: none;
white-space: nowrap;
}
.visual-compare {
position: absolute;
z-index: 4;
left: 18px;
right: 18px;
bottom: 18px;
display: grid;
grid-template-columns: 1fr 1fr;
gap: 12px;
padding: 14px;
border: 1px solid rgba(120, 148, 181, .24);
border-radius: 15px;
background: rgba(8, 18, 31, .88);
backdrop-filter: blur(14px);
box-shadow: 0 18px 50px rgba(0, 0, 0, .22);
}
.visual-metric {
min-width: 0;
padding: 0 5px;
}
.visual-head {
display: flex;
justify-content: space-between;
align-items: baseline;
margin-bottom: 10px;
color: #cbd8e7;
font-size: 11px;
font-weight: 650;
}
.visual-head span {
color: var(--muted);
font-size: 9px;
font-weight: 500;
}
.bar-row {
display: grid;
grid-template-columns: 14px minmax(50px, 1fr) 48px;
align-items: center;
gap: 7px;
margin: 6px 0;
color: var(--muted);
font-size: 9px;
}
.bar-row strong {
color: #e8f1fb;
text-align: right;
font-size: 10px;
font-variant-numeric: tabular-nums;
}
.bar {
height: 7px;
overflow: hidden;
border-radius: 999px;
background: #18273a;
}
.bar i {
display: block;
width: 0;
height: 100%;
border-radius: inherit;
transition: width .25s ease;
}
.bar i.ref { background: linear-gradient(90deg, #6f5ce7, #a293ff); }
.bar i.edit { background: linear-gradient(90deg, #159ba9, #49e6ef); }
.visual-delta {
display: inline-block;
margin-top: 7px;
padding: 4px 7px;
border-radius: 6px;
color: #aebed0;
background: #142238;
font-size: 9px;
font-variant-numeric: tabular-nums;
}
@media (max-width: 900px) {
html, body {
height: auto;
min-height: 100%;
overflow: auto;
}
header {
height: 64px;
padding: 0 14px;
}
.status { display: none; }
.workspace {
display: flex;
flex-direction: column;
height: auto;
}
.stage {
order: 0;
height: 66vh;
min-height: 500px;
}
aside {
order: 1;
overflow: visible;
border-right: 0;
border-top: 1px solid var(--line);
}
.brand p { display: none; }
}
@media (max-width: 560px) {
.header-actions .quiet-button { padding: 0 9px; }
.brand h1 { font-size: 13px; }
.visual-compare { grid-template-columns: 1fr; }
.scene-hint { bottom: 290px; }
.scene-title p { max-width: 240px; }
}
</style>
</head>
<body>
<header>
<div class="brand">
<div class="brand-icon" aria-hidden="true"></div>
<div>
<h1>Voxel Compare</h1>
<p>Exact cell geometry · editable unit blocks</p>
</div>
</div>
<div class="header-actions">
<span class="status">Exact unit-voxel math</span>
<button id="resetView" class="quiet-button">Reset view</button>
</div>
</header>
<main class="workspace">
<aside>
<section class="section">
<h2 class="section-title">Comparison cells</h2>
<div class="cell-card">
<div class="cell-head">
<span class="cell-badge a">A</span>
<div>
<strong>Reference cell</strong>
<small>Fixed 5 × 5 × 5 grid</small>
</div>
</div>
<select id="referencePreset" aria-label="Reference cell preset">
<option value="solid">Solid cube</option>
<option value="shell">Hollow shell</option>
<option value="frame">Open frame</option>
<option value="tunnel">Drilled tunnel</option>
</select>
<div class="metric-pair">
<div class="metric-tile">
<span>Surface area</span>
<strong id="refArea">—</strong>
<small>square units</small>
</div>
<div class="metric-tile">
<span>Volume</span>
<strong id="refVolume">—</strong>
<small>cubic units</small>
</div>
</div>
</div>
<div class="cell-card">
<div class="cell-head">
<span class="cell-badge b">B</span>
<div>
<strong>Editable cell</strong>
<small id="editDimensions">5 × 5 × 5 unit blocks</small>
</div>
</div>
<div id="presetButtons" class="preset-grid" aria-label="Editable cell preset">
<button class="preset-button" data-preset="solid">Solid cube</button>
<button class="preset-button" data-preset="shell">Hollow shell</button>
<button class="preset-button" data-preset="frame">Open frame</button>
<button class="preset-button" data-preset="tunnel">Drilled tunnel</button>
</div>
<div class="range-head">
<label for="cellSize">Cube grid size</label>
<output id="sizeOutput" for="cellSize">5 × 5 × 5</output>
</div>
<input id="cellSize" type="range" min="3" max="7" step="1" value="5">
<div class="button-row">
<button id="editMode" class="action-button primary wide">Enable block removal</button>
<button id="undo" class="action-button" disabled>Undo removal</button>
<button id="resetCell" class="action-button">Reset cell B</button>
</div>
<p id="editHelp" class="edit-help">
Enable removal, then click a visible unit block on Cell B.
</p>
<div class="metric-pair">
<div class="metric-tile">
<span>Surface area</span>
<strong id="editArea">—</strong>
<small>square units</small>
</div>
<div class="metric-tile">
<span>Volume</span>
<strong id="editVolume">—</strong>
<small>cubic units</small>
</div>
</div>
</div>
</section>
<section class="section">
<h2 class="section-title">
Exact comparison
<span id="manualCount">0 removals</span>
</h2>
<table>
<thead>
<tr>
<th>Metric</th>
<th>Cell A</th>
<th>Cell B</th>
<th>Δ B − A</th>
</tr>
</thead>
<tbody>
<tr>
<td>Area (u²)</td>
<td id="tableRefArea">—</td>
<td id="tableEditArea">—</td>
<td id="deltaArea" class="delta zero">—</td>
</tr>
<tr>
<td>Volume (u³)</td>
<td id="tableRefVolume">—</td>
<td id="tableEditVolume">—</td>
<td id="deltaVolume" class="delta zero">—</td>
</tr>
</tbody>
</table>
<div class="formula">
<code>Surface area = 6N − 2P</code>
N is the number of occupied unit cubes and P is the number of
face-adjacent cube pairs. Volume is exactly N cubic units.
<div id="refStats" class="stats-line"></div>
<div id="editStats" class="stats-line"></div>
</div>
</section>
<section class="section">
<div class="button-row" style="margin-top:0">
<button id="copyReference" class="action-button wide">
Copy Cell A → Cell B
</button>
</div>
<p class="edit-help">
Copying replaces Cell B with an exact voxel-for-voxel duplicate of
the reference, after which blocks can be removed manually.
</p>
</section>
</aside>
<section id="stage" class="stage" aria-label="Interactive 3D voxel comparison">
<canvas id="sceneCanvas" aria-label="Three-dimensional voxel comparison"></canvas>
<div class="scene-title">
<h2>Interactive cell geometry</h2>
<p>Gridded faces expose every unit block in the exact mesh.</p>
</div>
<div id="labelA" class="model-label a">
<span class="dot"></span> A · <b>Reference</b>
</div>
<div id="labelB" class="model-label b">
<span class="dot"></span> B · <b>Editable</b>
</div>
<div class="scene-hint">
Drag to orbit · Shift-drag to pan · Wheel to zoom · Click Cell B to remove a block
</div>
<div class="visual-compare">
<div class="visual-metric">
<div class="visual-head">Surface area <span>square units</span></div>
<div class="bar-row">
<span>A</span>
<div class="bar"><i id="barRefArea" class="ref"></i></div>
<strong id="valueRefArea">—</strong>
</div>
<div class="bar-row">
<span>B</span>
<div class="bar"><i id="barEditArea" class="edit"></i></div>
<strong id="valueEditArea">—</strong>
</div>
<span id="visualDeltaArea" class="visual-delta">Δ 0</span>
</div>
<div class="visual-metric">
<div class="visual-head">Volume <span>cubic units</span></div>
<div class="bar-row">
<span>A</span>
<div class="bar"><i id="barRefVolume" class="ref"></i></div>
<strong id="valueRefVolume">—</strong>
</div>
<div class="bar-row">
<span>B</span>
<div class="bar"><i id="barEditVolume" class="edit"></i></div>
<strong id="valueEditVolume">—</strong>
</div>
<span id="visualDeltaVolume" class="visual-delta">Δ 0</span>
</div>
</div>
</section>
</main>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Scene
// -------------------------------------------------------------------------
const canvas = document.getElementById("sceneCanvas");
const stage = document.getElementById("stage");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07101d);
scene.fog = new THREE.Fog(0x07101d, 18, 38);
const camera = new THREE.PerspectiveCamera(42, 1, 0.1, 100);
const hemisphere = new THREE.HemisphereLight(0xb9ddff, 0x172033, 1.8);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xffffff, 3.2);
keyLight.position.set(6, 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 = 12;
keyLight.shadow.camera.bottom = -12;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 35;
keyLight.shadow.bias = -0.00025;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x4edff0, 1.5);
rimLight.position.set(-8, 5, -7);
scene.add(rimLight);
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(40, 40),
new THREE.MeshStandardMaterial({
color: 0x081321,
roughness: 0.96,
metalness: 0.02
})
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -0.035;
floor.receiveShadow = true;
scene.add(floor);
const grid = new THREE.GridHelper(32, 32, 0x38516c, 0x20344b);
grid.position.y = -0.02;
grid.material.transparent = true;
grid.material.opacity = 0.25;
scene.add(grid);
const MODEL_SCALE = 0.52;
// -------------------------------------------------------------------------
// Exact voxel model utilities
// -------------------------------------------------------------------------
const keyOf = (x, y, z) => `${x},${y},${z}`;
const parseKey = key => key.split(",").map(Number);
function buildPreset(name, size) {
const voxels = new Set();
const last = size - 1;
const midpoint = Math.floor(size / 2);
// Tunnels are two blocks wide when the grid is large enough.
const tunnelX = size >= 4 ? [midpoint - 1, midpoint] : [midpoint];
const tunnelY = size >= 4 ? [midpoint - 1, midpoint] : [midpoint];
for (let x = 0; x < size; x++) {
for (let y = 0; y < size; y++) {
for (let z = 0; z < size; z++) {
const boundaryCount =
Number(x === 0 || x === last) +
Number(y === 0 || y === last) +
Number(z === 0 || z === last);
let occupied = true;
if (name === "shell") occupied = boundaryCount >= 1;
if (name === "frame") occupied = boundaryCount >= 2;
if (name === "tunnel") {
occupied = !(
tunnelX.includes(x) &&
tunnelY.includes(y)
);
}
if (occupied) voxels.add(keyOf(x, y, z));
}
}
}
return voxels;
}
function exactMetrics(voxels) {
const voxelCount = voxels.size;
let adjacentPairs = 0;
// Count each shared face once, using only the three positive directions.
for (const key of voxels) {
const [x, y, z] = parseKey(key);
if (voxels.has(keyOf(x + 1, y, z))) adjacentPairs++;
if (voxels.has(keyOf(x, y + 1, z))) adjacentPairs++;
if (voxels.has(keyOf(x, y, z + 1))) adjacentPairs++;
}
return {
voxelCount,
adjacentPairs,
area: 6 * voxelCount - 2 * adjacentPairs,
volume: voxelCount
};
}
// -------------------------------------------------------------------------
// Models
// -------------------------------------------------------------------------
const referenceModel = {
id: "reference",
name: "Reference",
color: 0x8b7cff,
presetName: "solid",
dims: [5, 5, 5],
voxels: buildPreset("solid", 5),
group: new THREE.Group(),
mesh: null,
lines: null,
instanceKeys: []
};
const editableModel = {
id: "editable",
name: "Editable",
color: 0x28d7e5,
presetName: "tunnel",
dims: [5, 5, 5],
template: buildPreset("tunnel", 5),
voxels: new Set(buildPreset("tunnel", 5)),
history: [],
group: new THREE.Group(),
mesh: null,
lines: null,
instanceKeys: []
};
scene.add(referenceModel.group);
scene.add(editableModel.group);
const boxGeometry = new THREE.BoxGeometry(1, 1, 1);
const edgesGeometry = new THREE.EdgesGeometry(boxGeometry);
const edgeTemplate = Array.from(edgesGeometry.attributes.position.array);
edgesGeometry.dispose();
function rebuildModelVisual(model) {
if (model.mesh) {
model.group.remove(model.mesh);
model.mesh.geometry.dispose();
model.mesh.material.dispose();
}
if (model.lines) {
model.group.remove(model.lines);
model.lines.geometry.dispose();
model.lines.material.dispose();
}
const material = new THREE.MeshStandardMaterial({
color: model.color,
roughness: 0.66,
metalness: 0.08,
flatShading: true
});
const mesh = new THREE.InstancedMesh(boxGeometry, material, model.voxels.size);
mesh.castShadow = true;
mesh.receiveShadow = true;
mesh.frustumCulled = false;
mesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
const dummy = new THREE.Object3D();
const linePositions = [];
model.instanceKeys = Array.from(model.voxels);
model.instanceKeys.forEach((key, index) => {
const [x, y, z] = parseKey(key);
const cx = x + 0.5;
const cy = y + 0.5;
const cz = z + 0.5;
dummy.position.set(cx, cy, cz);
dummy.updateMatrix();
mesh.setMatrixAt(index, dummy.matrix);
// Every unit cube contributes its 12 edges. Only visible edges remain
// visible because the solid meshes correctly occlude interior faces.
for (let i = 0; i < edgeTemplate.length; i += 3) {
linePositions.push(
edgeTemplate[i] + cx,
edgeTemplate[i + 1] + cy,
edgeTemplate[i + 2] + cz
);
}
});
mesh.instanceMatrix.needsUpdate = true;
mesh.computeBoundingSphere();
model.group.add(mesh);
model.mesh = mesh;
const lineGeometry = new THREE.BufferGeometry();
lineGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(linePositions, 3)
);
const lineMaterial = new THREE.LineBasicMaterial({
color: model.id === "reference" ? 0xd8d1ff : 0xb9fbff,
transparent: true,
opacity: model.id === "reference" ? 0.24 : 0.32,
depthWrite: false
});
const lines = new THREE.LineSegments(lineGeometry, lineMaterial);
lines.renderOrder = 2;
model.group.add(lines);
model.lines = lines;
}
function layoutModels() {
const referenceWidth = referenceModel.dims[0] * MODEL_SCALE;
const editableWidth = editableModel.dims[0] * MODEL_SCALE;
const gap = 1.15;
const totalWidth = referenceWidth + gap + editableWidth;
referenceModel.group.scale.setScalar(MODEL_SCALE);
editableModel.group.scale.setScalar(MODEL_SCALE);
referenceModel.group.position.set(
-totalWidth / 2 + referenceWidth / 2,
-referenceModel.dims[1] * MODEL_SCALE / 2,
0
);
editableModel.group.position.set(
totalWidth / 2 - editableWidth / 2,
-editableModel.dims[1] * MODEL_SCALE / 2,
0
);
}
const hoverMesh = new THREE.Mesh(
new THREE.BoxGeometry(1.025, 1.025, 1.025),
new THREE.MeshBasicMaterial({
color: 0xffc857,
wireframe: true,
transparent: true,
opacity: 0.95,
depthTest: false
})
);
hoverMesh.visible = false;
hoverMesh.renderOrder = 10;
editableModel.group.add(hoverMesh);
// -------------------------------------------------------------------------
// Interface state and updates
// -------------------------------------------------------------------------
const ui = {
referencePreset: document.getElementById("referencePreset"),
presetButtons: [...document.querySelectorAll("[data-preset]")],
size: document.getElementById("cellSize"),
sizeOutput: document.getElementById("sizeOutput"),
editMode: document.getElementById("editMode"),
undo: document.getElementById("undo"),
resetCell: document.getElementById("resetCell"),
copyReference: document.getElementById("copyReference"),
resetView: document.getElementById("resetView")
};
let removalMode = false;
function setRemovalMode(enabled) {
removalMode = enabled;
ui.editMode.classList.toggle("active", enabled);
ui.editMode.textContent = enabled
? "Removal mode active — click Cell B"
: "Enable block removal";
canvas.style.cursor = enabled ? "crosshair" : "grab";
document.getElementById("editHelp").textContent = enabled
? "Removal is active. Click any visible unit block on Cell B; use Undo to restore the last block."
: "Enable removal, then click a visible unit block on Cell B.";
if (!enabled) hoverMesh.visible = false;
}
function setPresetButtons() {
for (const button of ui.presetButtons) {
button.classList.toggle(
"active",
button.dataset.preset === editableModel.presetName
);
}
}
function signedDelta(value) {
if (value > 0) return `+${value.toLocaleString()}`;
if (value < 0) return `−${Math.abs(value).toLocaleString()}`;
return "0";
}
function deltaDescription(base, next) {
const difference = next - base;
const percentage = base === 0
? null
: (difference / base) * 100;
const amount = signedDelta(difference);
const percent = percentage === null
? "n/a"
: `${difference < 0 ? "−" : difference > 0 ? "+" : ""}${Math.abs(percentage).toFixed(1)}%`;
return `${amount} (${percent})`;
}
function setDeltaClass(element, difference) {
element.classList.remove("positive", "negative", "zero");
element.classList.add(
difference > 0 ? "positive" : difference < 0 ? "negative" : "zero"
);
}
function updateInterface() {
const reference = exactMetrics(referenceModel.voxels);
const editable = exactMetrics(editableModel.voxels);
document.getElementById("refArea").textContent = reference.area.toLocaleString();
document.getElementById("refVolume").textContent = reference.volume.toLocaleString();
document.getElementById("editArea").textContent = editable.area.toLocaleString();
document.getElementById("editVolume").textContent = editable.volume.toLocaleString();
document.getElementById("tableRefArea").textContent = reference.area.toLocaleString();
document.getElementById("tableEditArea").textContent = editable.area.toLocaleString();
document.getElementById("tableRefVolume").textContent = reference.volume.toLocaleString();
document.getElementById("tableEditVolume").textContent = editable.volume.toLocaleString();
const areaDifference = editable.area - reference.area;
const volumeDifference = editable.volume - reference.volume;
const areaDelta = document.getElementById("deltaArea");
const volumeDelta = document.getElementById("deltaVolume");
areaDelta.textContent = deltaDescription(reference.area, editable.area);
volumeDelta.textContent = deltaDescription(reference.volume, editable.volume);
setDeltaClass(areaDelta, areaDifference);
setDeltaClass(volumeDelta, volumeDifference);
document.getElementById("visualDeltaArea").textContent =
`Δ B − A: ${deltaDescription(reference.area, editable.area)}`;
document.getElementById("visualDeltaVolume").textContent =
`Δ B − A: ${deltaDescription(reference.volume, editable.volume)}`;
const maxArea = Math.max(reference.area, editable.area, 1);
const maxVolume = Math.max(reference.volume, editable.volume, 1);
document.getElementById("barRefArea").style.width = `${reference.area / maxArea * 100}%`;
document.getElementById("barEditArea").style.width = `${editable.area / maxArea * 100}%`;
document.getElementById("barRefVolume").style.width = `${reference.volume / maxVolume * 100}%`;
document.getElementById("barEditVolume").style.width = `${editable.volume / maxVolume * 100}%`;
document.getElementById("valueRefArea").textContent = reference.area.toLocaleString();
document.getElementById("valueEditArea").textContent = editable.area.toLocaleString();
document.getElementById("valueRefVolume").textContent = reference.volume.toLocaleString();
document.getElementById("valueEditVolume").textContent = editable.volume.toLocaleString();
document.getElementById("refStats").textContent =
`Cell A: ${reference.voxelCount} voxels · ${reference.adjacentPairs} shared faces`;
document.getElementById("editStats").textContent =
`Cell B: ${editable.voxelCount} voxels · ${editable.adjacentPairs} shared faces`;
document.getElementById("manualCount").textContent =
`${editableModel.history.length} removal${editableModel.history.length === 1 ? "" : "s"}`;
ui.undo.disabled = editableModel.history.length === 0;
const dimensions = editableModel.dims[0];
document.getElementById("editDimensions").textContent =
`${dimensions} × ${dimensions} × ${dimensions} unit blocks`;
ui.sizeOutput.textContent = `${dimensions} × ${dimensions} × ${dimensions}`;
document.querySelector("#labelA b").textContent = `Reference · ${reference.area} u²`;
document.querySelector("#labelB b").textContent = `Editable · ${editable.area} u²`;
setPresetButtons();
}
function applyEditablePreset(name, size = Number(ui.size.value)) {
editableModel.presetName = name;
editableModel.dims = [size, size, size];
editableModel.template = buildPreset(name, size);
editableModel.voxels = new Set(editableModel.template);
editableModel.history = [];
ui.size.value = String(size);
rebuildModelVisual(editableModel);
layoutModels();
updateInterface();
}
ui.referencePreset.addEventListener("change", event => {
referenceModel.presetName = event.target.value;
referenceModel.voxels = buildPreset(event.target.value, 5);
rebuildModelVisual(referenceModel);
layoutModels();
updateInterface();
});
ui.presetButtons.forEach(button => {
button.addEventListener("click", () => {
applyEditablePreset(button.dataset.preset);
});
});
ui.size.addEventListener("input", () => {
applyEditablePreset(editableModel.presetName, Number(ui.size.value));
});
ui.editMode.addEventListener("click", () => {
setRemovalMode(!removalMode);
});
ui.undo.addEventListener("click", () => {
const key = editableModel.history.pop();
if (key === undefined) return;
editableModel.voxels.add(key);
rebuildModelVisual(editableModel);
updateInterface();
});
ui.resetCell.addEventListener("click", () => {
editableModel.voxels = new Set(editableModel.template);
editableModel.history = [];
rebuildModelVisual(editableModel);
updateInterface();
});
ui.copyReference.addEventListener("click", () => {
const size = referenceModel.dims[0];
editableModel.presetName = referenceModel.presetName;
editableModel.dims = [size, size, size];
editableModel.template = new Set(referenceModel.voxels);
editableModel.voxels = new Set(editableModel.template);
editableModel.history = [];
ui.size.value = String(size);
rebuildModelVisual(editableModel);
layoutModels();
updateInterface();
});
// -------------------------------------------------------------------------
// Picking and block removal
// -------------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
function pickEditableBlock(clientX, clientY) {
if (!editableModel.mesh || editableModel.mesh.count === 0) return null;
const bounds = canvas.getBoundingClientRect();
pointer.x = ((clientX - bounds.left) / bounds.width) * 2 - 1;
pointer.y = -((clientY - bounds.top) / bounds.height) * 2 + 1;
editableModel.mesh.updateWorldMatrix(true, false);
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObject(editableModel.mesh, false);
if (!hits.length) return null;
const instanceId = hits[0].instanceId;
return editableModel.instanceKeys[instanceId] ?? null;
}
function updateHover(clientX, clientY) {
if (!removalMode) {
hoverMesh.visible = false;
return;
}
const key = pickEditableBlock(clientX, clientY);
if (!key) {
hoverMesh.visible = false;
return;
}
const [x, y, z] = parseKey(key);
hoverMesh.position.set(x + 0.5, y + 0.5, z + 0.5);
hoverMesh.visible = true;
}
function removePickedBlock(clientX, clientY) {
const key = pickEditableBlock(clientX, clientY);
if (!key || !editableModel.voxels.has(key)) return;
editableModel.voxels.delete(key);
editableModel.history.push(key);
rebuildModelVisual(editableModel);
updateInterface();
updateHover(clientX, clientY);
}
// -------------------------------------------------------------------------
// Direct camera controls: orbit, pan, zoom, and touch pinch
// -------------------------------------------------------------------------
const cameraState = {
theta: 0.72,
phi: 0.96,
radius: 13.5,
target: new THREE.Vector3(0, 1.15, 0)
};
function applyCamera() {
const sinPhi = Math.sin(cameraState.phi);
camera.position.set(
cameraState.target.x + cameraState.radius * sinPhi * Math.sin(cameraState.theta),
cameraState.target.y + cameraState.radius * Math.cos(cameraState.phi),
cameraState.target.z + cameraState.radius * sinPhi * Math.cos(cameraState.theta)
);
camera.lookAt(cameraState.target);
camera.updateMatrixWorld();
}
function resetCamera() {
cameraState.theta = 0.72;
cameraState.phi = 0.96;
cameraState.radius = 13.5;
cameraState.target.set(0, 1.15, 0);
applyCamera();
}
function panCamera(dx, dy) {
camera.updateMatrixWorld();
const right = new THREE.Vector3().setFromMatrixColumn(camera.matrixWorld, 0);
const up = new THREE.Vector3().setFromMatrixColumn(camera.matrixWorld, 1);
const scale = cameraState.radius * 0.00115;
cameraState.target.addScaledVector(right, -dx * scale);
cameraState.target.addScaledVector(up, dy * scale);
cameraState.target.x = THREE.MathUtils.clamp(cameraState.target.x, -10, 10);
cameraState.target.y = THREE.MathUtils.clamp(cameraState.target.y, -1, 8);
cameraState.target.z = THREE.MathUtils.clamp(cameraState.target.z, -10, 10);
applyCamera();
}
const activePointers = new Map();
let gesture = null;
function pointerDistance() {
const values = Array.from(activePointers.values());
if (values.length < 2) return 0;
return Math.hypot(
values[0].x - values[1].x,
values[0].y - values[1].y
);
}
canvas.addEventListener("pointerdown", event => {
canvas.setPointerCapture(event.pointerId);
activePointers.set(event.pointerId, { x: event.clientX, y: event.clientY });
if (activePointers.size === 1) {
gesture = {
startX: event.clientX,
startY: event.clientY,
moved: false,
mode: event.shiftKey || event.button === 2 ? "pan" : "orbit",
pinchStart: 0,
pinchRadius: cameraState.radius
};
} else if (activePointers.size === 2) {
gesture.moved = true;
gesture.pinchStart = pointerDistance();
gesture.pinchRadius = cameraState.radius;
}
});
canvas.addEventListener("pointermove", event => {
if (!activePointers.has(event.pointerId)) {
updateHover(event.clientX, event.clientY);
return;
}
const previous = activePointers.get(event.pointerId);
activePointers.set(event.pointerId, { x: event.clientX, y: event.clientY });
if (activePointers.size >= 2) {
const distance = pointerDistance();
if (gesture.pinchStart > 0) {
cameraState.radius = THREE.MathUtils.clamp(
gesture.pinchRadius * gesture.pinchStart / distance,
6.5,
30
);
applyCamera();
}
return;
}
if (!gesture) return;
const totalDistance = Math.hypot(
event.clientX - gesture.startX,
event.clientY - gesture.startY
);
if (totalDistance > 4) gesture.moved = true;
if (gesture.moved) {
const dx = event.clientX - previous.x;
const dy = event.clientY - previous.y;
if (gesture.mode === "pan") {
panCamera(dx, dy);
} else {
cameraState.theta -= dx * 0.006;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi - dy * 0.006,
0.22,
Math.PI - 0.22
);
applyCamera();
}
}
});
canvas.addEventListener("pointerup", event => {
const wasClick =
gesture &&
!gesture.moved &&
event.button === 0 &&
removalMode;
activePointers.delete(event.pointerId);
if (wasClick) removePickedBlock(event.clientX, event.clientY);
if (activePointers.size === 0) {
gesture = null;
canvas.style.cursor = removalMode ? "crosshair" : "grab";
}
});
canvas.addEventListener("pointercancel", event => {
activePointers.delete(event.pointerId);
if (activePointers.size === 0) gesture = null;
});
canvas.addEventListener("pointerleave", () => {
if (!activePointers.size) hoverMesh.visible = false;
});
canvas.addEventListener("contextmenu", event => event.preventDefault());
canvas.addEventListener("wheel", event => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
6.5,
30
);
applyCamera();
}, { passive: false });
ui.resetView.addEventListener("click", resetCamera);
// -------------------------------------------------------------------------
// Labels and resize
// -------------------------------------------------------------------------
const labelA = document.getElementById("labelA");
const labelB = document.getElementById("labelB");
const projected = new THREE.Vector3();
function positionLabel(element, model) {
projected.set(
model.dims[0] / 2,
model.dims[1] + 0.42,
model.dims[2] / 2
);
model.group.localToWorld(projected);
projected.project(camera);
const width = stage.clientWidth;
const height = stage.clientHeight;
element.style.left = `${(projected.x * 0.5 + 0.5) * width}px`;
element.style.top = `${(-projected.y * 0.5 + 0.5) * height}px`;
element.style.visibility =
projected.z >= -1 && projected.z <= 1 ? "visible" : "hidden";
}
function resize() {
const width = Math.max(1, stage.clientWidth);
const height = Math.max(1, stage.clientHeight);
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
}
new ResizeObserver(resize).observe(stage);
// -------------------------------------------------------------------------
// Initialize and render
// -------------------------------------------------------------------------
rebuildModelVisual(referenceModel);
rebuildModelVisual(editableModel);
layoutModels();
updateInterface();
setRemovalMode(false);
resize();
applyCamera();
renderer.setAnimationLoop(() => {
positionLabel(labelA, referenceModel);
positionLabel(labelB, editableModel);
renderer.render(scene, camera);
});
</script>
</body>
</html>
```