Prompt specification
Build or customize the Three.js 3D scene "Furniture balance classroom game" 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: Furniture balance classroom game
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/furniture-balance-classroom-game-x0228
Scene Description Prompt:
Build a self-contained HTML scene with Three.js from cdnjs featuring shelf stability. Build a toy-scale shelving challenge with configurable bases and blocks; users keep a visible center-of-mass marker within the support region while changing object placement. Voxel style.
Working Three.js Starter (furniture-balance-classroom-game-x0228):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Balance Lab — Voxel Shelf Stability</title>
<style>
:root {
--bg: #0c141c;
--panel: rgba(17, 27, 37, 0.9);
--panel-2: rgba(24, 37, 49, 0.85);
--line: rgba(169, 196, 214, 0.16);
--text: #e8f0f5;
--muted: #90a5b4;
--green: #7ee787;
--green-dark: rgba(126, 231, 135, 0.15);
--red: #ff716c;
--gold: #ffd166;
--blue: #67b7ff;
--radius: 16px;
}
* {
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,
select,
input {
font: inherit;
}
button,
select {
color: var(--text);
}
#scene {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
cursor: grab;
}
#scene.dragging {
cursor: grabbing;
}
.vignette {
position: fixed;
inset: 0;
pointer-events: none;
background:
radial-gradient(circle at 50% 45%, transparent 35%, rgba(4, 9, 14, 0.48) 100%),
linear-gradient(180deg, rgba(6, 12, 18, 0.12), transparent 25%);
}
.glass {
background: var(--panel);
border: 1px solid var(--line);
box-shadow:
0 18px 55px rgba(0, 0, 0, 0.28),
inset 0 1px 0 rgba(255, 255, 255, 0.035);
backdrop-filter: blur(16px);
-webkit-backdrop-filter: blur(16px);
}
.topbar {
position: fixed;
z-index: 5;
top: 18px;
left: 20px;
display: flex;
align-items: center;
gap: 12px;
pointer-events: none;
}
.logo-mark {
width: 38px;
height: 38px;
display: grid;
place-items: center;
border-radius: 10px;
color: #08120f;
background: var(--green);
box-shadow: 0 0 32px rgba(126, 231, 135, 0.24);
font-weight: 900;
font-size: 21px;
transform: rotate(-3deg);
}
.logo-copy small,
.eyebrow {
display: block;
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.logo-copy strong {
display: block;
margin-top: 3px;
font-size: 15px;
letter-spacing: 0.01em;
}
.panel {
position: fixed;
z-index: 6;
top: 78px;
bottom: 22px;
width: 286px;
padding: 17px;
border-radius: var(--radius);
overflow-y: auto;
scrollbar-width: thin;
scrollbar-color: #344756 transparent;
}
.panel::-webkit-scrollbar {
width: 5px;
}
.panel::-webkit-scrollbar-thumb {
background: #344756;
border-radius: 8px;
}
.panel-left {
left: 20px;
}
.panel-right {
right: 20px;
width: 278px;
}
.section + .section {
margin-top: 19px;
padding-top: 18px;
border-top: 1px solid var(--line);
}
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 12px;
color: #cbd9e2;
font-size: 11px;
font-weight: 850;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.section-title span {
color: #657b8a;
font-size: 9px;
letter-spacing: 0.08em;
}
.field {
margin-top: 13px;
}
.field:first-of-type {
margin-top: 0;
}
.field-label {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 7px;
color: #b6c7d3;
font-size: 11px;
font-weight: 700;
}
output {
color: var(--gold);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 10px;
}
select {
width: 100%;
height: 38px;
padding: 0 11px;
border: 1px solid var(--line);
border-radius: 9px;
outline: none;
background: #14212c;
font-size: 12px;
cursor: pointer;
}
select:focus,
button:focus-visible,
input:focus-visible {
outline: 2px solid rgba(103, 183, 255, 0.7);
outline-offset: 2px;
}
input[type="range"] {
width: 100%;
height: 4px;
margin: 5px 0;
border-radius: 999px;
appearance: none;
background: #263744;
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
width: 14px;
height: 14px;
appearance: none;
border: 2px solid #dbe8ef;
border-radius: 3px;
background: var(--blue);
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
}
input[type="range"]::-moz-range-thumb {
width: 11px;
height: 11px;
border: 2px solid #dbe8ef;
border-radius: 3px;
background: var(--blue);
}
.button-row {
display: flex;
gap: 8px;
margin-top: 12px;
}
button {
min-height: 36px;
padding: 0 12px;
border: 1px solid var(--line);
border-radius: 9px;
background: #182733;
font-size: 11px;
font-weight: 800;
cursor: pointer;
transition:
background 140ms ease,
transform 140ms ease,
border-color 140ms ease;
}
button:hover {
border-color: rgba(169, 196, 214, 0.32);
background: #213442;
}
button:active {
transform: translateY(1px);
}
button.primary {
width: 100%;
color: #07130d;
border-color: transparent;
background: var(--green);
}
button.primary:hover {
background: #9af2a1;
}
button.danger {
color: #ffaaa6;
}
button:disabled {
opacity: 0.35;
cursor: not-allowed;
}
.challenge-copy {
min-height: 49px;
margin: 11px 0;
color: var(--muted);
font-size: 11px;
line-height: 1.5;
}
.challenge-name {
color: var(--text);
font-size: 13px;
font-weight: 800;
}
.radar-wrap {
position: relative;
overflow: hidden;
margin-top: 12px;
border: 1px solid var(--line);
border-radius: 12px;
background: #0b151d;
}
#radar {
display: block;
width: 100%;
height: 132px;
}
.radar-legend {
position: absolute;
top: 8px;
left: 9px;
display: flex;
gap: 10px;
color: #748b9a;
font-size: 8px;
font-weight: 800;
letter-spacing: 0.07em;
text-transform: uppercase;
pointer-events: none;
}
.radar-legend i {
display: inline-block;
width: 6px;
height: 6px;
margin-right: 3px;
border-radius: 1px;
vertical-align: 1px;
}
.metrics {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 7px;
margin-top: 10px;
}
.metric {
padding: 9px 8px;
border: 1px solid var(--line);
border-radius: 9px;
background: rgba(8, 17, 24, 0.35);
}
.metric small {
display: block;
color: #6f8594;
font-size: 8px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.metric strong {
display: block;
margin-top: 4px;
color: #dce8ef;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 11px;
}
.selected-card {
display: flex;
align-items: center;
gap: 10px;
margin-bottom: 13px;
padding: 10px;
border: 1px solid var(--line);
border-radius: 11px;
background: rgba(8, 17, 24, 0.36);
}
.selected-swatch {
width: 31px;
height: 31px;
flex: 0 0 auto;
border-radius: 7px;
background: var(--gold);
box-shadow: inset -5px -5px 0 rgba(0, 0, 0, 0.12);
}
.selected-card strong {
display: block;
font-size: 12px;
}
.selected-card small {
display: block;
margin-top: 3px;
color: var(--muted);
font-size: 9px;
}
.swatches {
display: flex;
gap: 7px;
margin-top: 13px;
}
.swatch {
width: 25px;
height: 25px;
min-height: 0;
padding: 0;
border: 2px solid transparent;
border-radius: 6px;
box-shadow: inset -4px -4px 0 rgba(0, 0, 0, 0.13);
}
.swatch.active {
border-color: white;
transform: translateY(-1px);
}
.block-list {
display: grid;
gap: 7px;
}
.block-row {
width: 100%;
min-height: 42px;
display: flex;
align-items: center;
gap: 9px;
padding: 7px 9px;
text-align: left;
background: rgba(11, 20, 28, 0.48);
}
.block-row.active {
border-color: rgba(126, 231, 135, 0.45);
background: rgba(126, 231, 135, 0.08);
}
.block-row .mini-swatch {
width: 19px;
height: 19px;
flex: 0 0 auto;
border-radius: 4px;
background: var(--swatch);
box-shadow: inset -3px -3px 0 rgba(0, 0, 0, 0.13);
}
.block-row .row-copy {
flex: 1;
}
.block-row strong {
display: block;
font-size: 10px;
}
.block-row small {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 8px;
}
.block-row .row-x {
color: #78909f;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 9px;
}
.status-card {
position: fixed;
z-index: 7;
top: 18px;
left: 50%;
width: min(360px, calc(100vw - 660px));
min-width: 270px;
padding: 10px 13px;
border-radius: 13px;
transform: translateX(-50%);
pointer-events: none;
}
.status-main {
display: flex;
align-items: center;
gap: 10px;
}
.status-dot {
width: 12px;
height: 12px;
flex: 0 0 auto;
border-radius: 3px;
background: var(--green);
box-shadow: 0 0 16px rgba(126, 231, 135, 0.5);
transform: rotate(45deg);
}
.status-card.unstable .status-dot {
background: var(--red);
box-shadow: 0 0 16px rgba(255, 113, 108, 0.55);
}
.status-card.complete .status-dot {
background: var(--gold);
box-shadow: 0 0 16px rgba(255, 209, 102, 0.55);
}
.status-copy {
min-width: 0;
flex: 1;
}
.status-copy strong {
display: block;
color: var(--green);
font-size: 11px;
letter-spacing: 0.08em;
}
.status-card.unstable .status-copy strong {
color: var(--red);
}
.status-card.complete .status-copy strong {
color: var(--gold);
}
#marginText {
display: block;
margin-top: 2px;
overflow: hidden;
color: var(--muted);
font-size: 9px;
text-overflow: ellipsis;
white-space: nowrap;
}
.hold-wrap {
margin-top: 9px;
}
.hold-label {
display: flex;
justify-content: space-between;
margin-bottom: 4px;
color: #708796;
font-size: 8px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.hold-track {
height: 4px;
overflow: hidden;
border-radius: 999px;
background: #263541;
}
#holdBar {
width: 0;
height: 100%;
border-radius: inherit;
background: linear-gradient(90deg, #67b7ff, var(--green));
transition: width 80ms linear;
}
.help {
position: fixed;
z-index: 5;
bottom: 23px;
left: 50%;
padding: 9px 13px;
border: 1px solid var(--line);
border-radius: 999px;
color: #8fa5b3;
background: rgba(12, 21, 29, 0.74);
font-size: 9px;
font-weight: 700;
letter-spacing: 0.025em;
transform: translateX(-50%);
pointer-events: none;
white-space: nowrap;
}
.help b {
color: #d6e4ec;
}
.legend {
display: grid;
gap: 8px;
margin-top: 11px;
color: var(--muted);
font-size: 9px;
}
.legend div {
display: flex;
align-items: center;
gap: 8px;
}
.legend i {
width: 10px;
height: 10px;
border-radius: 2px;
background: var(--green);
box-shadow: 0 0 9px rgba(126, 231, 135, 0.25);
}
.legend i.gold {
background: var(--gold);
box-shadow: 0 0 9px rgba(255, 209, 102, 0.3);
}
.legend i.gray {
background: #536979;
box-shadow: none;
}
.toast {
position: fixed;
z-index: 20;
top: 105px;
left: 50%;
padding: 11px 16px;
border: 1px solid rgba(255, 209, 102, 0.35);
border-radius: 10px;
color: var(--gold);
background: rgba(23, 29, 31, 0.94);
font-size: 11px;
font-weight: 800;
opacity: 0;
transform: translate(-50%, -8px);
transition: 180ms ease;
pointer-events: none;
}
.toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
#loading {
position: fixed;
z-index: 100;
inset: 0;
display: grid;
place-items: center;
color: #a6bac7;
background: #0c141c;
font-size: 12px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
transition: opacity 300ms ease;
}
#loading.hidden {
opacity: 0;
pointer-events: none;
}
.spinner {
width: 24px;
height: 24px;
margin: 0 auto 12px;
border: 3px solid #263744;
border-top-color: var(--green);
border-radius: 50%;
animation: spin 0.8s linear infinite;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
@media (max-width: 1080px) {
.panel-left,
.panel-right {
width: 252px;
}
.status-card {
width: 280px;
}
}
@media (max-width: 820px) {
.panel {
top: 70px;
bottom: 14px;
width: 230px;
padding: 13px;
}
.panel-left {
left: 10px;
}
.panel-right {
right: 10px;
}
.status-card {
top: 70px;
left: auto;
right: 10px;
width: 230px;
min-width: 0;
transform: none;
}
.help {
display: none;
}
.logo-copy {
display: none;
}
}
</style>
</head>
<body>
<canvas id="scene"></canvas>
<div class="vignette"></div>
<div class="topbar">
<div class="logo-mark">B</div>
<div class="logo-copy">
<small>Balance Lab</small>
<strong>Voxel Shelf Stability</strong>
</div>
</div>
<div id="statusCard" class="status-card glass" aria-live="polite">
<div class="status-main">
<div class="status-dot"></div>
<div class="status-copy">
<strong id="statusLabel">BALANCED</strong>
<span id="marginText">Calculating center of mass…</span>
</div>
<div class="metric" style="min-width: 52px; padding: 7px">
<small>Time</small>
<strong id="timerText">0.0s</strong>
</div>
</div>
<div class="hold-wrap">
<div class="hold-label">
<span>Stable hold</span>
<span id="holdText">0.0 / 5.0s</span>
</div>
<div class="hold-track"><div id="holdBar"></div></div>
</div>
</div>
<aside class="panel panel-left glass">
<section class="section">
<div class="section-title">
Challenge <span>01</span>
</div>
<select id="challengeSelect" aria-label="Choose a challenge">
<option value="center">Center Out</option>
<option value="counter">Counterweight</option>
<option value="narrow">Narrow Base</option>
</select>
<div class="challenge-copy">
<div id="challengeName" class="challenge-name">Center Out</div>
<div id="challengeDescription">
Keep the gold center-of-mass marker inside the green support footprint.
</div>
</div>
<button id="startButton" class="primary">Start run</button>
<div class="metrics">
<div class="metric">
<small>Mass</small>
<strong id="massMetric">0.0 u</strong>
</div>
<div class="metric">
<small>COM X</small>
<strong id="comXMetric">0.00</strong>
</div>
<div class="metric">
<small>COM Z</small>
<strong id="comZMetric">0.00</strong>
</div>
</div>
<div class="radar-wrap">
<canvas id="radar" width="480" height="264"></canvas>
<div class="radar-legend">
<span><i style="background: #7ee787"></i>Support</span>
<span><i style="background: #ffd166"></i>COM</span>
</div>
</div>
</section>
<section class="section">
<div class="section-title">
Foundation <span>02</span>
</div>
<div class="field">
<label class="field-label" for="baseMode">
Base style
<output id="baseModeOut">Feet</output>
</label>
<select id="baseMode">
<option value="feet">Four voxel feet</option>
<option value="plinth">Solid plinth</option>
</select>
</div>
<div class="field">
<label class="field-label" for="baseX">
Base width
<output id="baseXOut"></output>
</label>
<input id="baseX" type="range" min="1.4" max="4.4" step="0.1" />
</div>
<div class="field">
<label class="field-label" for="baseD">
Base depth
<output id="baseDOut"></output>
</label>
<input id="baseD" type="range" min="1.2" max="3.2" step="0.1" />
</div>
<div class="field">
<label class="field-label" for="shelfW">
Shelf width
<output id="shelfWOut"></output>
</label>
<input id="shelfW" type="range" min="3" max="5.6" step="0.1" />
</div>
<div class="field">
<label class="field-label" for="shelfD">
Shelf depth
<output id="shelfDOut"></output>
</label>
<input id="shelfD" type="range" min="1.6" max="3.4" step="0.1" />
</div>
<div class="button-row">
<button id="resetLayout">Reset layout</button>
<button id="resetCamera">Reset view</button>
</div>
</section>
</aside>
<aside class="panel panel-right glass">
<section class="section">
<div class="section-title">
Block Config <span>03</span>
</div>
<div class="selected-card">
<div id="selectedSwatch" class="selected-swatch"></div>
<div>
<strong id="selectedName">Block A</strong>
<small id="selectedSummary">1.0 u · 0.6 × 0.7 × 0.6</small>
</div>
</div>
<div class="field">
<label class="field-label" for="blockMass">
Mass
<output id="blockMassOut"></output>
</label>
<input id="blockMass" type="range" min="0.2" max="5" step="0.1" />
</div>
<div class="field">
<label class="field-label" for="blockW">
Width
<output id="blockWOut"></output>
</label>
<input id="blockW" type="range" min="0.3" max="1.25" step="0.05" />
</div>
<div class="field">
<label class="field-label" for="blockH">
Height
<output id="blockHOut"></output>
</label>
<input id="blockH" type="range" min="0.3" max="1.6" step="0.05" />
</div>
<div class="field">
<label class="field-label" for="blockD">
Depth
<output id="blockDOut"></output>
</label>
<input id="blockD" type="range" min="0.3" max="1.15" step="0.05" />
</div>
<div class="swatches" id="swatches" aria-label="Block color">
<button class="swatch" data-color="#ff7b72" style="background:#ff7b72" aria-label="Coral"></button>
<button class="swatch" data-color="#ffd166" style="background:#ffd166" aria-label="Gold"></button>
<button class="swatch" data-color="#67d5b5" style="background:#67d5b5" aria-label="Mint"></button>
<button class="swatch" data-color="#67b7ff" style="background:#67b7ff" aria-label="Blue"></button>
<button class="swatch" data-color="#b892ff" style="background:#b892ff" aria-label="Purple"></button>
<button class="swatch" data-color="#e8edf1" style="background:#e8edf1" aria-label="White"></button>
</div>
<div class="button-row">
<button id="addBlock">Add block</button>
<button id="duplicateBlock">Duplicate</button>
<button id="deleteBlock" class="danger">Delete</button>
</div>
</section>
<section class="section">
<div class="section-title">
Block Bay <span id="blockCount">0 blocks</span>
</div>
<div id="blockList" class="block-list"></div>
</section>
<section class="section">
<div class="section-title">
Scene Legend <span>04</span>
</div>
<div class="legend">
<div><i></i>Green footprint = support region</div>
<div><i class="gold"></i>Gold cube = center of mass</div>
<div><i class="gray"></i>Gold floor square = COM projection</div>
</div>
</section>
</aside>
<div class="help">
<b>Drag blocks</b> to reposition · <b>Drag empty space</b> to orbit · <b>Scroll</b> to zoom
</div>
<div id="toast" class="toast"></div>
<div id="loading">
<div>
<div class="spinner"></div>
Loading balance lab
</div>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const $ = (selector) => document.querySelector(selector);
const canvas = $("#scene");
const ui = {
statusCard: $("#statusCard"),
statusLabel: $("#statusLabel"),
marginText: $("#marginText"),
timerText: $("#timerText"),
holdText: $("#holdText"),
holdBar: $("#holdBar"),
challengeSelect: $("#challengeSelect"),
challengeName: $("#challengeName"),
challengeDescription: $("#challengeDescription"),
startButton: $("#startButton"),
massMetric: $("#massMetric"),
comXMetric: $("#comXMetric"),
comZMetric: $("#comZMetric"),
radar: $("#radar"),
baseMode: $("#baseMode"),
baseModeOut: $("#baseModeOut"),
baseX: $("#baseX"),
baseD: $("#baseD"),
shelfW: $("#shelfW"),
shelfD: $("#shelfD"),
baseXOut: $("#baseXOut"),
baseDOut: $("#baseDOut"),
shelfWOut: $("#shelfWOut"),
shelfDOut: $("#shelfDOut"),
resetLayout: $("#resetLayout"),
resetCamera: $("#resetCamera"),
selectedName: $("#selectedName"),
selectedSummary: $("#selectedSummary"),
selectedSwatch: $("#selectedSwatch"),
blockMass: $("#blockMass"),
blockW: $("#blockW"),
blockH: $("#blockH"),
blockD: $("#blockD"),
blockMassOut: $("#blockMassOut"),
blockWOut: $("#blockWOut"),
blockHOut: $("#blockHOut"),
blockDOut: $("#blockDOut"),
addBlock: $("#addBlock"),
duplicateBlock: $("#duplicateBlock"),
deleteBlock: $("#deleteBlock"),
swatches: $("#swatches"),
blockList: $("#blockList"),
blockCount: $("#blockCount"),
toast: $("#toast")
};
const COLORS = {
green: 0x7ee787,
red: 0xff716c,
gold: 0xffd166,
blue: 0x67b7ff
};
const palette = [
"#ff7b72",
"#ffd166",
"#67d5b5",
"#67b7ff",
"#b892ff",
"#e8edf1"
];
const LEG_THICKNESS = 0.24;
const LEG_HEIGHT = 1.48;
const BOARD_THICKNESS = 0.18;
const SHELF_CENTER = LEG_HEIGHT + BOARD_THICKNESS / 2;
const SHELF_TOP = LEG_HEIGHT + BOARD_THICKNESS;
const HOLD_TARGET = 5;
const state = {
baseMode: "feet",
baseX: 3.8,
baseD: 2,
shelfW: 4.8,
shelfD: 2.6,
supportW: 3.32,
supportD: 1.52,
blocks: [],
selectedId: null,
nextId: 1,
stable: true,
margin: 0,
totalMass: 0,
com: new THREE.Vector3(),
challenge: "center",
running: false,
elapsed: 0,
hold: 0,
complete: false
};
const challengeDefinitions = {
center: {
name: "Center Out",
description:
"A balanced starter load. Keep the gold center-of-mass marker inside the green footprint for five seconds.",
config: {
baseMode: "feet",
baseX: 3.8,
baseD: 2,
shelfW: 4.8,
shelfD: 2.6
},
blocks: [
{ x: -0.86, z: 0, w: 0.8, h: 0.8, d: 0.8, mass: 1.4, color: "#ff7b72" },
{ x: 0.86, z: 0, w: 0.8, h: 1.05, d: 0.75, mass: 1.2, color: "#67b7ff" },
{ x: 0, z: 0.42, w: 0.7, h: 0.7, d: 0.65, mass: 0.9, color: "#67d5b5" }
]
},
counter: {
name: "Counterweight",
description:
"A heavy voxel pulls the load toward the left. Add or move blocks until the projected center of mass returns to the support area.",
config: {
baseMode: "feet",
baseX: 3.8,
baseD: 2,
shelfW: 4.8,
shelfD: 2.6
},
blocks: [
{ x: -1.25, z: 0, w: 0.85, h: 1.2, d: 0.85, mass: 4.2, color: "#ff7b72" },
{ x: 1.1, z: 0.15, w: 0.7, h: 0.7, d: 0.7, mass: 1.1, color: "#67b7ff" },
{ x: 0.3, z: -0.45, w: 0.6, h: 0.8, d: 0.6, mass: 0.8, color: "#ffd166" }
]
},
narrow: {
name: "Narrow Base",
description:
"The shelf is unchanged, but the support footprint is much smaller. Keep the load carefully centered.",
config: {
baseMode: "feet",
baseX: 2.15,
baseD: 1.45,
shelfW: 4.8,
shelfD: 2.6
},
blocks: [
{ x: -0.58, z: 0, w: 0.75, h: 0.8, d: 0.75, mass: 1.6, color: "#ff7b72" },
{ x: 0.58, z: 0, w: 0.75, h: 0.8, d: 0.75, mass: 1.6, color: "#67b7ff" },
{ x: 0, z: 0.3, w: 0.6, h: 1, d: 0.6, mass: 0.8, color: "#ffd166" }
]
}
};
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x0c141c);
scene.fog = new THREE.Fog(0x0c141c, 10, 24);
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
const camera = new THREE.PerspectiveCamera(
43,
window.innerWidth / window.innerHeight,
0.1,
80
);
const cameraState = {
azimuth: 0.72,
elevation: 0.5,
radius: 9.1,
target: new THREE.Vector3(0, 1.05, 0)
};
const hemisphere = new THREE.HemisphereLight(0xc8e6ff, 0x18201b, 2.2);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xfff0d0, 3.2);
keyLight.position.set(5, 9, 6);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -8;
keyLight.shadow.camera.right = 8;
keyLight.shadow.camera.top = 8;
keyLight.shadow.camera.bottom = -8;
keyLight.shadow.camera.near = 0.5;
keyLight.shadow.camera.far = 25;
keyLight.shadow.bias = -0.0004;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x5aa8ff, 1.5);
rimLight.position.set(-5, 4, -5);
scene.add(rimLight);
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(40, 40),
new THREE.MeshStandardMaterial({
color: 0x101a22,
roughness: 0.96,
metalness: 0.02
})
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -0.012;
floor.receiveShadow = true;
scene.add(floor);
const grid = new THREE.GridHelper(24, 48, 0x314553, 0x1c2a34);
grid.position.y = 0.003;
grid.material.transparent = true;
grid.material.opacity = 0.42;
scene.add(grid);
const blockGroup = new THREE.Group();
scene.add(blockGroup);
const boardMaterial = new THREE.MeshStandardMaterial({
color: 0xb88752,
roughness: 0.82,
metalness: 0.02
});
const board = new THREE.Mesh(
new THREE.BoxGeometry(1, 1, 1),
boardMaterial
);
board.castShadow = true;
board.receiveShadow = true;
scene.add(board);
const boardEdges = new THREE.LineSegments(
new THREE.EdgesGeometry(new THREE.BoxGeometry(1, 1, 1)),
new THREE.LineBasicMaterial({
color: 0x4d3421,
transparent: true,
opacity: 0.85
})
);
scene.add(boardEdges);
const legMaterial = new THREE.MeshStandardMaterial({
color: 0x31576a,
roughness: 0.72,
metalness: 0.08
});
const footMaterial = new THREE.MeshStandardMaterial({
color: 0x172b36,
roughness: 0.9
});
const legMeshes = [];
for (let i = 0; i < 4; i++) {
const leg = new THREE.Mesh(
new THREE.BoxGeometry(1, 1, 1),
legMaterial
);
leg.castShadow = true;
leg.receiveShadow = true;
scene.add(leg);
const foot = new THREE.Mesh(
new THREE.BoxGeometry(1, 1, 1),
footMaterial
);
foot.castShadow = true;
scene.add(foot);
legMeshes.push({ leg, foot });
}
const plinth = new THREE.Mesh(
new THREE.BoxGeometry(1, 1, 1),
new THREE.MeshStandardMaterial({
color: 0x284554,
roughness: 0.78
})
);
plinth.castShadow = true;
plinth.receiveShadow = true;
scene.add(plinth);
const supportFloorMaterial = new THREE.MeshBasicMaterial({
color: COLORS.green,
transparent: true,
opacity: 0.16,
depthWrite: false,
side: THREE.DoubleSide
});
const supportFloor = new THREE.Mesh(
new THREE.PlaneGeometry(1, 1),
supportFloorMaterial
);
supportFloor.rotation.x = -Math.PI / 2;
supportFloor.position.y = 0.012;
scene.add(supportFloor);
const supportShelfMaterial = new THREE.MeshBasicMaterial({
color: COLORS.green,
transparent: true,
opacity: 0.055,
depthWrite: false,
side: THREE.DoubleSide
});
const supportShelf = new THREE.Mesh(
new THREE.PlaneGeometry(1, 1),
supportShelfMaterial
);
supportShelf.rotation.x = -Math.PI / 2;
supportShelf.position.y = SHELF_TOP + 0.012;
scene.add(supportShelf);
function makeSupportLine() {
return new THREE.LineLoop(
new THREE.BufferGeometry(),
new THREE.LineBasicMaterial({
color: COLORS.green,
transparent: true,
opacity: 0.95,
depthTest: false
})
);
}
const supportFloorLine = makeSupportLine();
const supportShelfLine = makeSupportLine();
supportFloorLine.renderOrder = 8;
supportShelfLine.renderOrder = 8;
scene.add(supportFloorLine, supportShelfLine);
const comMaterial = new THREE.MeshBasicMaterial({
color: COLORS.gold,
depthTest: false,
depthWrite: false
});
const comMarker = new THREE.Mesh(
new THREE.BoxGeometry(0.18, 0.18, 0.18),
comMaterial
);
comMarker.renderOrder = 20;
scene.add(comMarker);
const comMarkerEdges = new THREE.LineSegments(
new THREE.EdgesGeometry(new THREE.BoxGeometry(0.24, 0.24, 0.24)),
new THREE.LineBasicMaterial({
color: 0xffffff,
transparent: true,
opacity: 0.85,
depthTest: false,
depthWrite: false
})
);
comMarkerEdges.renderOrder = 21;
comMarker.add(comMarkerEdges);
const projectionMaterial = new THREE.MeshBasicMaterial({
color: COLORS.gold,
transparent: true,
opacity: 0.92,
depthTest: false,
depthWrite: false
});
const projectionMarker = new THREE.Mesh(
new THREE.BoxGeometry(0.28, 0.025, 0.28),
projectionMaterial
);
projectionMarker.renderOrder = 22;
scene.add(projectionMarker);
const comLine = new THREE.Line(
new THREE.BufferGeometry(),
new THREE.LineDashedMaterial({
color: COLORS.gold,
transparent: true,
opacity: 0.8,
dashSize: 0.08,
gapSize: 0.055,
depthTest: false,
depthWrite: false
})
);
comLine.renderOrder = 19;
scene.add(comLine);
let pickables = [];
function lightenColor(hex, amount = 0.18) {
const color = new THREE.Color(hex);
color.lerp(new THREE.Color(0xffffff), amount);
return color;
}
function replaceLineGeometry(line, points) {
line.geometry.dispose();
line.geometry = new THREE.BufferGeometry().setFromPoints(points);
if (line.material.isLineDashedMaterial) {
line.computeLineDistances();
}
}
function replaceBoxEdges(line, width, height, depth) {
const geometry = new THREE.BoxGeometry(width, height, depth);
line.geometry.dispose();
line.geometry = new THREE.EdgesGeometry(geometry);
geometry.dispose();
}
function clamp(value, min, max) {
return Math.max(min, Math.min(max, value));
}
function blockName(id) {
return `Block ${String.fromCharCode(64 + id)}`;
}
function createBlockMesh(block) {
const group = new THREE.Group();
group.position.set(block.x, SHELF_TOP, block.z);
group.userData.blockId = block.id;
const bodyMaterial = new THREE.MeshStandardMaterial({
color: block.color,
roughness: 0.76,
metalness: 0.025
});
const body = new THREE.Mesh(
new THREE.BoxGeometry(block.w, block.h, block.d),
bodyMaterial
);
body.position.y = block.h / 2;
body.castShadow = true;
body.receiveShadow = true;
body.userData.blockId = block.id;
group.add(body);
const studMaterial = new THREE.MeshStandardMaterial({
color: lightenColor(block.color),
roughness: 0.72
});
const columns = Math.max(1, Math.min(3, Math.floor(block.w / 0.34)));
const rows = Math.max(1, Math.min(3, Math.floor(block.d / 0.34)));
const studSize = Math.min(0.13, (block.w / columns) * 0.35);
const studDepth = Math.min(0.13, (block.d / rows) * 0.35);
for (let x = 0; x < columns; x++) {
for (let z = 0; z < rows; z++) {
const stud = new THREE.Mesh(
new THREE.BoxGeometry(studSize, 0.075, studDepth),
studMaterial
);
stud.position.set(
-block.w / 2 + ((x + 0.5) * block.w) / columns,
block.h + 0.0375,
-block.d / 2 + ((z + 0.5) * block.d) / rows
);
stud.castShadow = true;
stud.userData.blockId = block.id;
group.add(stud);
}
}
const outline = new THREE.LineSegments(
new THREE.EdgesGeometry(new THREE.BoxGeometry(block.w, block.h, block.d)),
new THREE.LineBasicMaterial({
color: 0x14212a,
transparent: true,
opacity: 0.35
})
);
outline.position.y = block.h / 2;
group.add(outline);
group.userData.outline = outline;
block.mesh = group;
block.bodyMesh = body;
return group;
}
function rebuildBlockMeshes() {
for (const child of [...blockGroup.children]) {
blockGroup.remove(child);
child.traverse((object) => {
if (object.geometry) object.geometry.dispose();
if (object.material) {
const materials = Array.isArray(object.material)
? object.material
: [object.material];
materials.forEach((material) => material.dispose());
}
});
}
pickables = [];
for (const block of state.blocks) {
const mesh = createBlockMesh(block);
blockGroup.add(mesh);
pickables.push(block.bodyMesh);
}
updateSelectionVisuals();
}
function updateSelectionVisuals() {
for (const group of blockGroup.children) {
const selected = group.userData.blockId === state.selectedId;
const outline = group.userData.outline;
if (!outline) continue;
outline.visible = true;
outline.material.color.set(selected ? COLORS.gold : 0x14212a);
outline.material.opacity = selected ? 1 : 0.3;
}
}
function updateFoundation() {
board.scale.set(state.shelfW, BOARD_THICKNESS, state.shelfD);
board.position.set(0, SHELF_CENTER, 0);
replaceBoxEdges(
boardEdges,
state.shelfW,
BOARD_THICKNESS,
state.shelfD
);
boardEdges.position.copy(board.position);
const feetMode = state.baseMode === "feet";
const offsetX = state.baseX / 2 - LEG_THICKNESS / 2;
const offsetZ = state.baseD / 2 - LEG_THICKNESS / 2;
const positions = [
[-offsetX, -offsetZ],
[offsetX, -offsetZ],
[-offsetX, offsetZ],
[offsetX, offsetZ]
];
legMeshes.forEach(({ leg, foot }, index) => {
const [x, z] = positions[index];
leg.visible = feetMode;
foot.visible = feetMode;
leg.scale.set(LEG_THICKNESS, LEG_HEIGHT, LEG_THICKNESS);
leg.position.set(x, LEG_HEIGHT / 2, z);
foot.scale.set(
LEG_THICKNESS * 1.18,
0.08,
LEG_THICKNESS * 1.18
);
foot.position.set(x, 0.04, z);
});
plinth.visible = !feetMode;
plinth.scale.set(state.baseX, LEG_HEIGHT, state.baseD);
plinth.position.set(0, LEG_HEIGHT / 2, 0);
state.supportW = feetMode
? Math.max(0.18, state.baseX - LEG_THICKNESS * 2)
: Math.max(0.18, state.baseX - 0.08);
state.supportD = feetMode
? Math.max(0.18, state.baseD - LEG_THICKNESS * 2)
: Math.max(0.18, state.baseD - 0.08);
supportFloor.scale.set(state.supportW, state.supportD, 1);
supportShelf.scale.set(state.supportW, state.supportD, 1);
const halfX = state.supportW / 2;
const halfZ = state.supportD / 2;
replaceLineGeometry(supportFloorLine, [
new THREE.Vector3(-halfX, 0.025, -halfZ),
new THREE.Vector3(halfX, 0.025, -halfZ),
new THREE.Vector3(halfX, 0.025, halfZ),
new THREE.Vector3(-halfX, 0.025, halfZ)
]);
replaceLineGeometry(supportShelfLine, [
new THREE.Vector3(-halfX, SHELF_TOP + 0.023, -halfZ),
new THREE.Vector3(halfX, SHELF_TOP + 0.023, -halfZ),
new THREE.Vector3(halfX, SHELF_TOP + 0.023, halfZ),
new THREE.Vector3(-halfX, SHELF_TOP + 0.023, halfZ)
]);
for (const block of state.blocks) {
block.x = clamp(
block.x,
-state.shelfW / 2 + block.w / 2,
state.shelfW / 2 - block.w / 2
);
block.z = clamp(
block.z,
-state.shelfD / 2 + block.d / 2,
state.shelfD / 2 - block.d / 2
);
if (block.mesh) {
block.mesh.position.x = block.x;
block.mesh.position.z = block.z;
}
}
syncFoundationUI();
}
function updatePhysics() {
let totalMass = 0;
const com = new THREE.Vector3();
for (const block of state.blocks) {
totalMass += block.mass;
com.x += block.x * block.mass;
com.y += (SHELF_TOP + block.h / 2) * block.mass;
com.z += block.z * block.mass;
}
if (totalMass > 0) {
com.multiplyScalar(1 / totalMass);
}
state.totalMass = totalMass;
state.com.copy(com);
const halfX = state.supportW / 2;
const halfZ = state.supportD / 2;
const marginX = halfX - Math.abs(com.x);
const marginZ = halfZ - Math.abs(com.z);
state.margin = Math.min(marginX, marginZ);
state.stable = state.margin >= 0;
comMarker.position.copy(com);
projectionMarker.position.set(com.x, 0.035, com.z);
replaceLineGeometry(comLine, [
new THREE.Vector3(com.x, com.y, com.z),
new THREE.Vector3(com.x, 0.045, com.z)
]);
const supportColor = state.stable ? COLORS.green : COLORS.red;
supportFloorMaterial.color.setHex(supportColor);
supportShelfMaterial.color.setHex(supportColor);
supportFloorLine.material.color.setHex(supportColor);
supportShelfLine.material.color.setHex(supportColor);
supportFloorMaterial.opacity = state.stable ? 0.16 : 0.22;
supportShelfMaterial.opacity = state.stable ? 0.055 : 0.09;
updateHud();
drawRadar();
}
function updateHud() {
ui.statusCard.classList.toggle("unstable", !state.stable);
ui.statusCard.classList.toggle("complete", state.complete);
if (state.complete) {
ui.statusLabel.textContent = "CHALLENGE CLEAR";
} else if (state.stable) {
ui.statusLabel.textContent = "BALANCED";
} else {
ui.statusLabel.textContent = "TIPPING";
}
const marginText = Math.abs(state.margin).toFixed(2);
ui.marginText.textContent = state.stable
? `${marginText} u to the nearest support edge`
: `${marginText} u outside the support region`;
ui.massMetric.textContent = `${state.totalMass.toFixed(1)} u`;
ui.comXMetric.textContent = state.com.x.toFixed(2);
ui.comZMetric.textContent = state.com.z.toFixed(2);
ui.timerText.textContent = `${state.elapsed.toFixed(1)}s`;
ui.holdText.textContent = `${Math.min(HOLD_TARGET, state.hold).toFixed(1)} / ${HOLD_TARGET.toFixed(1)}s`;
ui.holdBar.style.width = `${clamp((state.hold / HOLD_TARGET) * 100, 0, 100)}%`;
if (state.running) {
ui.startButton.textContent = "Restart run";
} else if (state.complete) {
ui.startButton.textContent = "Run again";
} else {
ui.startButton.textContent = "Start run";
}
}
function drawRadar() {
const context = ui.radar.getContext("2d");
const width = ui.radar.width;
const height = ui.radar.height;
context.clearRect(0, 0, width, height);
const spanX = Math.max(state.shelfW, state.baseX) + 0.7;
const spanZ = Math.max(state.shelfD, state.baseD) + 0.7;
const scale = Math.min(
(width - 48) / spanX,
(height - 36) / spanZ
);
const mapX = (x) => width / 2 + x * scale;
const mapY = (z) => height / 2 + z * scale;
context.strokeStyle = "rgba(133, 160, 177, 0.13)";
context.lineWidth = 1;
for (let x = 0; x < width; x += 24) {
context.beginPath();
context.moveTo(x, 0);
context.lineTo(x, height);
context.stroke();
}
for (let y = 0; y < height; y += 24) {
context.beginPath();
context.moveTo(0, y);
context.lineTo(width, y);
context.stroke();
}
context.setLineDash([7, 7]);
context.strokeStyle = "rgba(156, 181, 197, 0.35)";
context.strokeRect(
mapX(-state.shelfW / 2),
mapY(-state.shelfD / 2),
state.shelfW * scale,
state.shelfD * scale
);
context.setLineDash([]);
const supportColor = state.stable ? "#7ee787" : "#ff716c";
context.fillStyle = state.stable
? "rgba(126, 231, 135, 0.15)"
: "rgba(255, 113, 108, 0.15)";
context.strokeStyle = supportColor;
context.lineWidth = 2;
context.fillRect(
mapX(-state.supportW / 2),
mapY(-state.supportD / 2),
state.supportW * scale,
state.supportD * scale
);
context.strokeRect(
mapX(-state.supportW / 2),
mapY(-state.supportD / 2),
state.supportW * scale,
state.supportD * scale
);
for (const block of state.blocks) {
context.fillStyle = block.color;
context.globalAlpha = 0.88;
context.fillRect(
mapX(block.x - block.w / 2),
mapY(block.z - block.d / 2),
block.w * scale,
block.d * scale
);
}
context.globalAlpha = 1;
const comX = mapX(state.com.x);
const comY = mapY(state.com.z);
context.save();
context.translate(comX, comY);
context.rotate(Math.PI / 4);
context.fillStyle = "#ffd166";
context.strokeStyle = "#ffffff";
context.lineWidth = 2;
context.shadowColor = "#ffd166";
context.shadowBlur = 12;
context.fillRect(-8, -8, 16, 16);
context.strokeRect(-8, -8, 16, 16);
context.restore();
}
function syncFoundationUI() {
ui.baseMode.value = state.baseMode;
ui.baseModeOut.textContent =
state.baseMode === "feet" ? "Feet" : "Plinth";
ui.baseX.value = state.baseX;
ui.baseD.value = state.baseD;
ui.shelfW.value = state.shelfW;
ui.shelfD.value = state.shelfD;
ui.baseXOut.textContent = `${state.baseX.toFixed(1)} u`;
ui.baseDOut.textContent = `${state.baseD.toFixed(1)} u`;
ui.shelfWOut.textContent = `${state.shelfW.toFixed(1)} u`;
ui.shelfDOut.textContent = `${state.shelfD.toFixed(1)} u`;
}
function selectedBlock() {
return state.blocks.find((block) => block.id === state.selectedId) || null;
}
function selectBlock(id) {
state.selectedId = id;
updateSelectionVisuals();
refreshInventory();
refreshBlockControls();
}
function refreshBlockControls() {
const block = selectedBlock();
if (!block) return;
ui.selectedName.textContent = blockName(block.id);
ui.selectedSummary.textContent =
`${block.mass.toFixed(1)} u · ` +
`${block.w.toFixed(2)} × ${block.h.toFixed(2)} × ${block.d.toFixed(2)}`;
ui.selectedSwatch.style.background = block.color;
ui.blockMass.value = block.mass;
ui.blockW.value = block.w;
ui.blockH.value = block.h;
ui.blockD.value = block.d;
ui.blockMassOut.textContent = `${block.mass.toFixed(1)} u`;
ui.blockWOut.textContent = `${block.w.toFixed(2)} u`;
ui.blockHOut.textContent = `${block.h.toFixed(2)} u`;
ui.blockDOut.textContent = `${block.d.toFixed(2)} u`;
for (const swatch of ui.swatches.querySelectorAll(".swatch")) {
swatch.classList.toggle(
"active",
swatch.dataset.color.toLowerCase() === block.color.toLowerCase()
);
}
}
function refreshInventory() {
ui.blockCount.textContent = `${state.blocks.length} block${state.blocks.length === 1 ? "" : "s"}`;
ui.blockList.innerHTML = state.blocks
.map(
(block) => `
<button
class="block-row ${block.id === state.selectedId ? "active" : ""}"
data-select="${block.id}"
>
<span class="mini-swatch" style="--swatch:${block.color}"></span>
<span class="row-copy">
<strong>${blockName(block.id)}</strong>
<small>${block.mass.toFixed(1)} u mass</small>
</span>
<span class="row-x">x ${block.x.toFixed(2)}</span>
</button>
`
)
.join("");
ui.deleteBlock.disabled = state.blocks.length <= 1;
ui.duplicateBlock.disabled = state.blocks.length >= 12;
}
function resetHold() {
state.hold = 0;
state.complete = false;
updateHud();
}
function changed() {
resetHold();
updatePhysics();
}
function addBlock() {
if (state.blocks.length >= 12) return;
const id = state.nextId++;
const block = {
id,
x: 0,
z: 0,
w: 0.65,
h: 0.75,
d: 0.65,
mass: 1,
color: palette[(id - 1) % palette.length]
};
state.blocks.push(block);
state.selectedId = id;
rebuildBlockMeshes();
refreshInventory();
refreshBlockControls();
changed();
}
function duplicateSelected() {
const source = selectedBlock();
if (!source || state.blocks.length >= 12) return;
const id = state.nextId++;
const duplicate = {
...source,
id,
x: clamp(
source.x + 0.42,
-state.shelfW / 2 + source.w / 2,
state.shelfW / 2 - source.w / 2
),
z: source.z
};
state.blocks.push(duplicate);
state.selectedId = id;
rebuildBlockMeshes();
refreshInventory();
refreshBlockControls();
changed();
}
function deleteSelected() {
if (state.blocks.length <= 1) return;
const index = state.blocks.findIndex(
(block) => block.id === state.selectedId
);
if (index < 0) return;
state.blocks.splice(index, 1);
state.selectedId = state.blocks[Math.max(0, index - 1)].id;
rebuildBlockMeshes();
refreshInventory();
refreshBlockControls();
changed();
}
function loadChallenge(key) {
const definition = challengeDefinitions[key];
if (!definition) return;
state.challenge = key;
Object.assign(state, definition.config);
state.blocks = definition.blocks.map((block) => ({
...block,
id: state.nextId++
}));
state.selectedId = state.blocks[0]?.id ?? null;
state.running = false;
state.elapsed = 0;
state.hold = 0;
state.complete = false;
ui.challengeName.textContent = definition.name;
ui.challengeDescription.textContent = definition.description;
updateFoundation();
rebuildBlockMeshes();
refreshInventory();
refreshBlockControls();
updatePhysics();
}
let toastTimer = 0;
function showToast(message) {
ui.toast.textContent = message;
ui.toast.classList.add("show");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => {
ui.toast.classList.remove("show");
}, 2200);
}
ui.challengeSelect.addEventListener("change", (event) => {
loadChallenge(event.target.value);
});
ui.startButton.addEventListener("click", () => {
state.running = true;
state.elapsed = 0;
state.hold = 0;
state.complete = false;
updateHud();
showToast("Run started — hold the COM inside the footprint.");
});
const foundationFields = [
["baseX", "baseX"],
["baseD", "baseD"],
["shelfW", "shelfW"],
["shelfD", "shelfD"]
];
for (const [inputId, key] of foundationFields) {
$(`#${inputId}`).addEventListener("input", (event) => {
state[key] = Number(event.target.value);
updateFoundation();
changed();
});
}
ui.baseMode.addEventListener("change", (event) => {
state.baseMode = event.target.value;
updateFoundation();
changed();
});
const blockFields = [
["blockMass", "mass"],
["blockW", "w"],
["blockH", "h"],
["blockD", "d"]
];
for (const [inputId, key] of blockFields) {
$(`#${inputId}`).addEventListener("input", (event) => {
const block = selectedBlock();
if (!block) return;
block[key] = Number(event.target.value);
if (key === "w" || key === "d") {
block.x = clamp(
block.x,
-state.shelfW / 2 + block.w / 2,
state.shelfW / 2 - block.w / 2
);
block.z = clamp(
block.z,
-state.shelfD / 2 + block.d / 2,
state.shelfD / 2 - block.d / 2
);
}
rebuildBlockMeshes();
refreshBlockControls();
changed();
});
}
ui.swatches.addEventListener("click", (event) => {
const button = event.target.closest("[data-color]");
const block = selectedBlock();
if (!button || !block) return;
block.color = button.dataset.color;
rebuildBlockMeshes();
refreshBlockControls();
changed();
});
ui.addBlock.addEventListener("click", addBlock);
ui.duplicateBlock.addEventListener("click", duplicateSelected);
ui.deleteBlock.addEventListener("click", deleteSelected);
ui.blockList.addEventListener("click", (event) => {
const button = event.target.closest("[data-select]");
if (!button) return;
selectBlock(Number(button.dataset.select));
});
ui.resetLayout.addEventListener("click", () => {
loadChallenge(state.challenge);
showToast("Challenge layout reset.");
});
function resetCamera() {
cameraState.azimuth = 0.72;
cameraState.elevation = 0.5;
cameraState.radius = 9.1;
cameraState.target.set(0, 1.05, 0);
updateCamera();
}
ui.resetCamera.addEventListener("click", resetCamera);
function updateCamera() {
const { azimuth, elevation, radius, target } = cameraState;
camera.position.set(
target.x + radius * Math.cos(elevation) * Math.sin(azimuth),
target.y + radius * Math.sin(elevation),
target.z + radius * Math.cos(elevation) * Math.cos(azimuth)
);
camera.lookAt(target);
}
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const dragPlane = new THREE.Plane(
new THREE.Vector3(0, 1, 0),
-SHELF_TOP
);
const planePoint = new THREE.Vector3();
let drag = null;
let orbit = null;
function setPointer(event) {
const rect = canvas.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
}
canvas.addEventListener("pointerdown", (event) => {
setPointer(event);
if (event.button === 0) {
const hits = raycaster.intersectObjects(pickables, false);
if (hits.length) {
const id = hits[0].object.userData.blockId;
const block = state.blocks.find((item) => item.id === id);
if (block && raycaster.ray.intersectPlane(dragPlane, planePoint)) {
selectBlock(id);
drag = {
id,
pointerId: event.pointerId,
offsetX: block.x - planePoint.x,
offsetZ: block.z - planePoint.z
};
canvas.setPointerCapture(event.pointerId);
canvas.classList.add("dragging");
event.preventDefault();
return;
}
}
}
orbit = {
pointerId: event.pointerId,
x: event.clientX,
y: event.clientY
};
canvas.setPointerCapture(event.pointerId);
canvas.classList.add("dragging");
});
canvas.addEventListener("pointermove", (event) => {
if (drag && event.pointerId === drag.pointerId) {
setPointer(event);
if (!raycaster.ray.intersectPlane(dragPlane, planePoint)) return;
const block = state.blocks.find((item) => item.id === drag.id);
if (!block) return;
block.x = clamp(
planePoint.x + drag.offsetX,
-state.shelfW / 2 + block.w / 2,
state.shelfW / 2 - block.w / 2
);
block.z = clamp(
planePoint.z + drag.offsetZ,
-state.shelfD / 2 + block.d / 2,
state.shelfD / 2 - block.d / 2
);
if (block.mesh) {
block.mesh.position.x = block.x;
block.mesh.position.z = block.z;
}
changed();
return;
}
if (orbit && event.pointerId === orbit.pointerId) {
const deltaX = event.clientX - orbit.x;
const deltaY = event.clientY - orbit.y;
orbit.x = event.clientX;
orbit.y = event.clientY;
cameraState.azimuth -= deltaX * 0.007;
cameraState.elevation = clamp(
cameraState.elevation + deltaY * 0.005,
0.2,
1.25
);
}
});
function endPointer(event) {
if (drag && event.pointerId === drag.pointerId) {
drag = null;
}
if (orbit && event.pointerId === orbit.pointerId) {
orbit = null;
}
canvas.classList.remove("dragging");
}
canvas.addEventListener("pointerup", endPointer);
canvas.addEventListener("pointercancel", endPointer);
canvas.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
5,
16
);
},
{ passive: false }
);
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
});
loadChallenge("center");
updateCamera();
let lastTime = performance.now();
renderer.setAnimationLoop((time) => {
const delta = Math.min(0.05, (time - lastTime) / 1000);
lastTime = time;
if (state.running) {
state.elapsed += delta;
if (state.stable) {
state.hold += delta;
} else {
state.hold = 0;
}
if (state.hold >= HOLD_TARGET) {
state.hold = HOLD_TARGET;
state.running = false;
state.complete = true;
showToast("Challenge clear — stable for five seconds!");
}
updateHud();
}
updateCamera();
renderer.render(scene, camera);
});
requestAnimationFrame(() => {
$("#loading").classList.add("hidden");
});
</script>
</body>
</html>
```