Prompt specification
Build or customize the Three.js 3D scene "Changing Density Changes the Solution" 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: Changing Density Changes the Solution
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/changing-density-changes-the-solution-x3516
Scene Description Prompt:
Use Three.js from cdnjs to create a balance puzzle where geometry stays fixed while one crate's mass changes. Recompute the center of mass and show why a previously valid arrangement can fail. Deliver one self-contained HTML file with visible voxel blocks.
Working Three.js Starter (changing-density-changes-the-solution-x3516):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Voxel Balance — Mass Shift Puzzle</title>
<style>
:root {
--bg: #09111d;
--panel: rgba(13, 23, 38, 0.9);
--panel-border: rgba(150, 190, 225, 0.16);
--text: #eaf3ff;
--muted: #91a7bf;
--cyan: #50d9ff;
--amber: #ffd166;
--green: #62e6a7;
--red: #ff647c;
}
* {
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 {
font: inherit;
}
#scene {
position: fixed;
inset: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
cursor: grab;
touch-action: none;
}
#scene canvas:active {
cursor: grabbing;
}
.overlay {
position: fixed;
inset: 0;
pointer-events: none;
}
.brand {
position: absolute;
top: 24px;
left: 26px;
max-width: 520px;
pointer-events: none;
}
.eyebrow {
color: var(--cyan);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.2em;
text-transform: uppercase;
}
h1 {
margin: 7px 0 4px;
font-size: clamp(25px, 3vw, 42px);
line-height: 1;
letter-spacing: -0.045em;
}
.subtitle {
margin: 0;
color: var(--muted);
font-size: 14px;
}
.panel {
pointer-events: auto;
border: 1px solid var(--panel-border);
border-radius: 16px;
background: var(--panel);
box-shadow:
0 18px 55px rgba(0, 0, 0, 0.3),
inset 0 1px rgba(255, 255, 255, 0.035);
backdrop-filter: blur(14px);
}
.controls {
position: absolute;
bottom: 24px;
left: 24px;
width: 350px;
padding: 18px;
}
.panel-title {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 7px;
}
.panel-title h2 {
margin: 0;
font-size: 16px;
letter-spacing: -0.015em;
}
.lock {
color: var(--green);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.challenge {
margin: 0 0 16px;
color: var(--muted);
font-size: 13px;
line-height: 1.45;
}
.mass-row {
display: flex;
align-items: baseline;
justify-content: space-between;
margin-bottom: 8px;
}
.mass-row label {
color: var(--muted);
font-size: 12px;
font-weight: 700;
letter-spacing: 0.04em;
text-transform: uppercase;
}
#massValue {
color: var(--amber);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 23px;
font-weight: 800;
}
input[type="range"] {
width: 100%;
height: 8px;
margin: 8px 0 4px;
appearance: none;
border-radius: 999px;
outline: none;
background:
linear-gradient(
90deg,
var(--green) 0%,
var(--green) 30%,
var(--amber) 30%,
var(--amber) 78%,
var(--red) 78%,
var(--red) 100%
);
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
width: 21px;
height: 21px;
appearance: none;
border: 3px solid #111b2a;
border-radius: 50%;
background: #ffffff;
box-shadow: 0 0 0 2px var(--amber);
}
input[type="range"]::-moz-range-thumb {
width: 16px;
height: 16px;
border: 3px solid #111b2a;
border-radius: 50%;
background: #ffffff;
box-shadow: 0 0 0 2px var(--amber);
}
.range-labels {
display: flex;
justify-content: space-between;
color: #6f849a;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
}
.button-row {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
gap: 8px;
margin-top: 16px;
}
button {
min-height: 37px;
border: 1px solid rgba(160, 195, 225, 0.18);
border-radius: 9px;
color: var(--text);
background: rgba(255, 255, 255, 0.055);
font-size: 11px;
font-weight: 800;
cursor: pointer;
transition:
transform 120ms ease,
background 120ms ease,
border-color 120ms ease;
}
button:hover {
transform: translateY(-1px);
border-color: rgba(160, 195, 225, 0.35);
background: rgba(255, 255, 255, 0.1);
}
button:active {
transform: translateY(0);
}
button.primary {
border-color: rgba(98, 230, 167, 0.32);
color: #b8ffdd;
background: rgba(98, 230, 167, 0.1);
}
button.danger {
border-color: rgba(255, 100, 124, 0.34);
color: #ffb6c2;
background: rgba(255, 100, 124, 0.1);
}
.fixed-note {
margin-top: 13px;
padding-top: 12px;
border-top: 1px solid rgba(150, 190, 225, 0.11);
color: #7f95ad;
font-size: 11px;
line-height: 1.5;
}
.fixed-note strong {
color: #bed0e2;
}
.readout {
position: absolute;
top: 24px;
right: 24px;
width: 355px;
padding: 18px;
}
.status-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 16px;
}
.status-row h2 {
margin: 0;
font-size: 17px;
}
.badge {
padding: 7px 10px;
border: 1px solid rgba(98, 230, 167, 0.35);
border-radius: 999px;
color: var(--green);
background: rgba(98, 230, 167, 0.1);
font-size: 10px;
font-weight: 900;
letter-spacing: 0.12em;
}
.badge.failing {
border-color: rgba(255, 100, 124, 0.4);
color: var(--red);
background: rgba(255, 100, 124, 0.11);
}
.metric-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px;
}
.metric {
min-height: 72px;
padding: 11px;
border: 1px solid rgba(150, 190, 225, 0.09);
border-radius: 11px;
background: rgba(255, 255, 255, 0.025);
}
.metric span {
display: block;
margin-bottom: 7px;
color: var(--muted);
font-size: 10px;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.metric strong {
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 17px;
}
.gauge-block {
margin-top: 16px;
}
.gauge-heading {
display: flex;
justify-content: space-between;
margin-bottom: 9px;
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.07em;
text-transform: uppercase;
}
.gauge {
position: relative;
height: 34px;
border: 1px solid rgba(150, 190, 225, 0.12);
border-radius: 9px;
background:
linear-gradient(
90deg,
rgba(255, 100, 124, 0.12),
rgba(255, 255, 255, 0.035) 32%,
rgba(255, 255, 255, 0.035) 68%,
rgba(255, 100, 124, 0.12)
);
overflow: hidden;
}
.support-window {
position: absolute;
top: 0;
bottom: 0;
left: 22.222%;
width: 55.556%;
border-right: 1px solid rgba(98, 230, 167, 0.5);
border-left: 1px solid rgba(98, 230, 167, 0.5);
background: rgba(98, 230, 167, 0.17);
}
.gauge-center {
position: absolute;
top: 0;
bottom: 0;
left: 50%;
width: 1px;
background: rgba(255, 255, 255, 0.3);
}
.gauge-dot {
position: absolute;
top: 50%;
width: 13px;
height: 13px;
border: 2px solid #0b1422;
border-radius: 50%;
transform: translate(-50%, -50%);
transition: left 80ms linear;
}
#currentDot {
z-index: 3;
background: var(--amber);
box-shadow: 0 0 13px rgba(255, 209, 102, 0.75);
}
#baselineDot {
z-index: 2;
width: 11px;
height: 11px;
border-color: var(--cyan);
background: var(--cyan);
box-shadow: 0 0 10px rgba(80, 217, 255, 0.55);
}
.gauge-labels {
display: flex;
justify-content: space-between;
margin-top: 5px;
color: #6f849a;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
}
.legend {
display: flex;
gap: 15px;
margin-top: 8px;
color: var(--muted);
font-size: 10px;
}
.legend-item {
display: flex;
align-items: center;
gap: 6px;
}
.legend-swatch {
width: 8px;
height: 8px;
border-radius: 50%;
}
.legend-swatch.current {
background: var(--amber);
}
.legend-swatch.saved {
background: var(--cyan);
}
.legend-swatch.support {
background: var(--green);
}
.equation {
margin-top: 14px;
padding: 10px;
border-radius: 9px;
color: #bcd0e2;
background: rgba(0, 0, 0, 0.2);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
line-height: 1.5;
overflow-wrap: anywhere;
}
.result {
margin: 13px 0 0;
color: #a9bed2;
font-size: 12px;
line-height: 1.52;
}
.model-note {
margin: 13px 0 0;
padding-top: 12px;
border-top: 1px solid rgba(150, 190, 225, 0.11);
color: #71869d;
font-size: 10px;
line-height: 1.5;
}
.view-hint {
position: absolute;
right: 26px;
bottom: 24px;
padding: 9px 12px;
border: 1px solid rgba(150, 190, 225, 0.11);
border-radius: 999px;
color: #8197ae;
background: rgba(9, 17, 29, 0.72);
font-size: 10px;
letter-spacing: 0.04em;
}
#resetView {
position: absolute;
top: 24px;
right: 404px;
min-height: 34px;
padding: 0 13px;
pointer-events: auto;
}
#loading {
position: fixed;
inset: 0;
z-index: 20;
display: grid;
place-items: center;
color: var(--cyan);
background: var(--bg);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 13px;
letter-spacing: 0.08em;
}
@media (max-width: 900px) {
.brand {
top: 16px;
left: 16px;
max-width: calc(100% - 32px);
}
.readout {
top: 112px;
right: 12px;
width: 320px;
padding: 14px;
}
.controls {
bottom: 12px;
left: 12px;
width: 330px;
padding: 14px;
}
#resetView {
display: none;
}
.view-hint {
display: none;
}
}
@media (max-width: 620px) {
.readout {
top: 116px;
right: 10px;
width: calc(100% - 20px);
max-height: 43vh;
overflow: auto;
}
.controls {
bottom: 10px;
left: 10px;
width: calc(100% - 20px);
}
.challenge,
.fixed-note,
.model-note {
display: none;
}
.metric-grid {
grid-template-columns: repeat(4, 1fr);
}
.metric {
min-height: 62px;
padding: 8px;
}
.metric strong {
font-size: 13px;
}
}
</style>
</head>
<body>
<div id="scene"></div>
<div class="overlay">
<header class="brand">
<div class="eyebrow">Balance Laboratory / Mass Shift</div>
<h1>One crate changes. The layout does not.</h1>
<p class="subtitle">
Raise voxel crate B's mass and watch the combined center of mass cross the support window.
</p>
</header>
<button id="resetView" type="button">Reset view</button>
<section class="panel controls">
<div class="panel-title">
<h2>Adjustable voxel crate B</h2>
<span class="lock">Geometry locked</span>
</div>
<p class="challenge">
Goal: make B heavier without moving a voxel, and find the largest mass that still
keeps the board supported.
</p>
<div class="mass-row">
<label for="massSlider">Crate B mass</label>
<output id="massValue">11.05 kg</output>
</div>
<input
id="massSlider"
type="range"
min="2"
max="34"
step="0.01"
value="11.05"
aria-label="Adjustable crate mass"
/>
<div class="range-labels">
<span>2 kg</span>
<span>critical: 27.00 kg</span>
<span>34 kg</span>
</div>
<div class="button-row">
<button id="validBtn" class="primary" type="button">Valid setup</button>
<button id="nudgeBtn" type="button">+5 kg</button>
<button id="failBtn" class="danger" type="button">Make it fail</button>
</div>
<div class="fixed-note">
<strong>Fixed arrangement:</strong>
A = 20 kg at −2.05 m, B at +1.05 m, C = 12 kg at +2.45 m.
The beam contributes 8 kg centered over the pivot.
</div>
</section>
<section class="panel readout" aria-live="polite">
<div class="status-row">
<h2 id="statusTitle">Centered</h2>
<span id="statusBadge" class="badge">STABLE</span>
</div>
<div class="metric-grid">
<div class="metric">
<span>Combined COM x</span>
<strong id="comValue">0.000 m</strong>
</div>
<div class="metric">
<span>From pivot</span>
<strong id="pivotValue">0.000 m</strong>
</div>
<div class="metric">
<span>Total mass</span>
<strong id="totalValue">51.05 kg</strong>
</div>
<div class="metric">
<span>Tipping moment</span>
<strong id="momentValue">0.0 N·m</strong>
</div>
</div>
<div class="gauge-block">
<div class="gauge-heading">
<span>COM position</span>
<span id="directionValue">Balanced</span>
</div>
<div class="gauge">
<div class="support-window"></div>
<div class="gauge-center"></div>
<div id="baselineDot" class="gauge-dot"></div>
<div id="currentDot" class="gauge-dot"></div>
</div>
<div class="gauge-labels">
<span>−0.45 m</span>
<span>0</span>
<span>+0.45 m</span>
</div>
<div class="legend">
<span class="legend-item">
<span class="legend-swatch current"></span> Current COM
</span>
<span class="legend-item">
<span class="legend-swatch saved"></span> Saved COM
</span>
<span class="legend-item">
<span class="legend-swatch support"></span> Support window
</span>
</div>
</div>
<div id="equation" class="equation"></div>
<p id="resultText" class="result"></p>
<p class="model-note">
Model: the beam's COM is at the fulcrum, and a 0.50 m support window is
centered at x = 0. The arrangement is supported while |COM x| ≤ 0.25 m.
The displayed moment is the level-board moment M·g·x̄.
</p>
</section>
<div class="view-hint">Drag to orbit · Scroll to zoom · Double-click to reset</div>
</div>
<div id="loading">Loading Three.js core…</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const sceneHost = document.getElementById("scene");
const loading = document.getElementById("loading");
// ---------------------------------------------------------------------
// Renderer, scene, lighting
// ---------------------------------------------------------------------
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false
});
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.15;
sceneHost.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x09111d);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
100
);
const cameraTarget = new THREE.Vector3(0, 1.75, 0);
const cameraState = {
radius: 13.4,
theta: 0.67,
phi: 1.05
};
function updateCamera() {
const spherical = new THREE.Spherical(
cameraState.radius,
cameraState.phi,
cameraState.theta
);
camera.position.setFromSpherical(spherical).add(cameraTarget);
camera.lookAt(cameraTarget);
}
function resetCamera() {
cameraState.radius = 13.4;
cameraState.theta = 0.67;
cameraState.phi = 1.05;
updateCamera();
}
updateCamera();
const hemisphere = new THREE.HemisphereLight(0xc8e4ff, 0x182032, 2.1);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xffffff, 3.1);
keyLight.position.set(6, 12, 8);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -10;
keyLight.shadow.camera.right = 10;
keyLight.shadow.camera.top = 10;
keyLight.shadow.camera.bottom = -10;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 30;
keyLight.shadow.bias = -0.00025;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x4aa8ff, 1.5);
rimLight.position.set(-8, 6, -7);
scene.add(rimLight);
const warmLight = new THREE.PointLight(0xff9b54, 18, 12, 2);
warmLight.position.set(5, 5, 3);
scene.add(warmLight);
// ---------------------------------------------------------------------
// Floor and grid
// ---------------------------------------------------------------------
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(60, 60),
new THREE.MeshStandardMaterial({
color: 0x0c1523,
roughness: 1,
metalness: 0
})
);
ground.rotation.x = -Math.PI / 2;
ground.receiveShadow = true;
scene.add(ground);
const grid = new THREE.GridHelper(
40,
40,
0x31506a,
0x18283a
);
grid.position.y = 0.012;
grid.material.transparent = true;
grid.material.opacity = 0.48;
scene.add(grid);
const floorRing = new THREE.Mesh(
new THREE.RingGeometry(2.2, 2.24, 64),
new THREE.MeshBasicMaterial({
color: 0x285170,
transparent: true,
opacity: 0.42,
side: THREE.DoubleSide
})
);
floorRing.rotation.x = -Math.PI / 2;
floorRing.position.y = 0.018;
scene.add(floorRing);
// ---------------------------------------------------------------------
// Shared materials and helpers
// ---------------------------------------------------------------------
const boardMaterial = new THREE.MeshStandardMaterial({
color: 0x27384d,
roughness: 0.82,
metalness: 0.06
});
const deckMaterial = new THREE.MeshStandardMaterial({
color: 0x354c66,
roughness: 0.76,
metalness: 0.05
});
const supportMaterial = new THREE.MeshStandardMaterial({
color: 0x253448,
roughness: 0.9
});
const supportAccentMaterial = new THREE.MeshStandardMaterial({
color: 0x4b647e,
roughness: 0.85
});
function addBox(parent, size, position, material, castShadow = true) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(size[0], size[1], size[2]),
material
);
mesh.position.set(position[0], position[1], position[2]);
mesh.castShadow = castShadow;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
// ---------------------------------------------------------------------
// Voxel-style fulcrum. It remains world-fixed while the beam rotates.
// ---------------------------------------------------------------------
const fulcrum = new THREE.Group();
scene.add(fulcrum);
addBox(
fulcrum,
[1.9, 0.28, 2.6],
[0, 0.14, 0],
supportMaterial
);
addBox(
fulcrum,
[1.45, 0.28, 2.15],
[0, 0.42, 0],
supportAccentMaterial
);
addBox(
fulcrum,
[1.0, 0.28, 1.7],
[0, 0.70, 0],
supportMaterial
);
addBox(
fulcrum,
[0.65, 1.25, 1.3],
[0, 1.465, 0],
supportAccentMaterial
);
addBox(
fulcrum,
[0.58, 0.28, 1.15],
[0, 2.23, 0],
supportMaterial
);
addBox(
fulcrum,
[0.55, 0.06, 1.1],
[0, 2.40, 0],
new THREE.MeshStandardMaterial({
color: 0x62e6a7,
emissive: 0x123c2c,
emissiveIntensity: 0.55,
roughness: 0.65
}),
false
);
// ---------------------------------------------------------------------
// Beam group: all crates and COM markers are children, so their local
// geometry never changes when the beam tilts.
// ---------------------------------------------------------------------
const board = new THREE.Group();
board.position.y = 2.65;
scene.add(board);
addBox(board, [8.8, 0.5, 3.3], [0, 0, 0], boardMaterial);
addBox(board, [8.55, 0.1, 3.05], [0, 0.29, 0], deckMaterial);
addBox(board, [8.8, 0.12, 0.12], [0, -0.05, 1.65], boardMaterial);
// Visible support window centered on the pivot.
const supportStrip = addBox(
board,
[0.5, 0.025, 3.08],
[0, 0.355, 0],
new THREE.MeshBasicMaterial({
color: 0x62e6a7,
transparent: true,
opacity: 0.23,
depthWrite: false
}),
false
);
addBox(
board,
[0.035, 0.035, 3.08],
[0, 0.375, 0],
new THREE.MeshBasicMaterial({ color: 0x91f4c4 }),
false
);
const boltMaterial = new THREE.MeshStandardMaterial({
color: 0x9eb0c3,
roughness: 0.55,
metalness: 0.45
});
for (const x of [-3.9, -2.1, 0, 2.1, 3.9]) {
addBox(board, [0.11, 0.11, 0.055], [x, -0.03, 1.69], boltMaterial);
}
// ---------------------------------------------------------------------
// Canvas sprite labels
// ---------------------------------------------------------------------
function roundedRect(ctx, x, y, width, height, radius) {
const r = Math.min(radius, width / 2, height / 2);
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.arcTo(x + width, y, x + width, y + height, r);
ctx.arcTo(x + width, y + height, x, y + height, r);
ctx.arcTo(x, y + height, x, y, r);
ctx.arcTo(x, y, x + width, y, r);
ctx.closePath();
}
function createLabel(text, accent = "#50d9ff", widthScale = 1.75) {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 128;
const ctx = canvas.getContext("2d");
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(widthScale, widthScale * 0.25, 1);
sprite.renderOrder = 20;
function draw(nextText) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
roundedRect(ctx, 9, 12, 494, 104, 22);
ctx.fillStyle = "rgba(8, 17, 29, 0.90)";
ctx.fill();
ctx.strokeStyle = accent;
ctx.lineWidth = 4;
ctx.stroke();
ctx.fillStyle = accent;
roundedRect(ctx, 22, 31, 8, 66, 4);
ctx.fill();
ctx.font = "700 47px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillStyle = "#edf7ff";
ctx.fillText(nextText, 264, 65, 450);
texture.needsUpdate = true;
}
draw(text);
return {
sprite,
draw
};
}
// ---------------------------------------------------------------------
// Instanced voxel crates
// ---------------------------------------------------------------------
const VOXEL_SPACING = 0.27;
const VOXEL_SIZE = 0.245;
const CRATE_HEIGHT = 0.785;
const CRATE_BASE_Y = 0.34;
function createVoxelCrate(name, x, mass, colorHex, accentHex) {
const group = new THREE.Group();
group.position.set(x, CRATE_BASE_Y + CRATE_HEIGHT / 2 + 0.03, 0);
board.add(group);
const nx = 4;
const ny = 3;
const nz = 3;
const count = nx * ny * nz;
const geometry = new THREE.BoxGeometry(
VOXEL_SIZE,
VOXEL_SIZE,
VOXEL_SIZE
);
const material = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.78,
metalness: 0.02
});
const mesh = new THREE.InstancedMesh(geometry, material, count);
mesh.castShadow = true;
mesh.receiveShadow = true;
const dummy = new THREE.Object3D();
const cells = [];
let index = 0;
for (let ix = 0; ix < nx; ix++) {
for (let iy = 0; iy < ny; iy++) {
for (let iz = 0; iz < nz; iz++) {
dummy.position.set(
(ix - (nx - 1) / 2) * VOXEL_SPACING,
(iy - (ny - 1) / 2) * VOXEL_SPACING,
(iz - (nz - 1) / 2) * VOXEL_SPACING
);
dummy.updateMatrix();
mesh.setMatrixAt(index, dummy.matrix);
const shade = [-0.055, 0.015, 0.065][(ix + iy + iz) % 3];
cells.push({ shade });
const color = new THREE.Color(colorHex).offsetHSL(0, 0, shade);
mesh.setColorAt(index, color);
index++;
}
}
}
mesh.instanceMatrix.needsUpdate = true;
mesh.instanceColor.needsUpdate = true;
mesh.computeBoundingSphere();
group.add(mesh);
const label = createLabel(
`${name} · ${mass.toFixed(2)} kg`,
accentHex,
name === "B" ? 1.9 : 1.7
);
label.sprite.position.set(0, name === "B" ? 0.72 : 0.6, 0);
group.add(label.sprite);
return {
name,
group,
mesh,
cells,
label,
baseColor: new THREE.Color(colorHex)
};
}
const crateA = createVoxelCrate("A", -2.05, 20, 0x4f8cff, "#77adff");
const crateB = createVoxelCrate("B", 1.05, 11.05, 0xf59e0b, "#ffd166");
const crateC = createVoxelCrate("C", 2.45, 12, 0x45c987, "#81efb3");
function tintCrate(crate, colorHex) {
const base = new THREE.Color(colorHex);
crate.cells.forEach((cell, index) => {
const color = base.clone().offsetHSL(0, 0, cell.shade);
crate.mesh.setColorAt(index, color);
});
crate.mesh.instanceColor.needsUpdate = true;
}
// ---------------------------------------------------------------------
// Center-of-mass markers, saved COM, and moment arrow
// ---------------------------------------------------------------------
const FRONT_Z = 1.82;
const MARKER_Y = 0.58;
const comMarkerMaterial = new THREE.MeshBasicMaterial({
color: 0xffd166
});
const comMarker = new THREE.Mesh(
new THREE.OctahedronGeometry(0.115),
comMarkerMaterial
);
comMarker.position.set(0, MARKER_Y, FRONT_Z);
board.add(comMarker);
const savedMarker = new THREE.Mesh(
new THREE.BoxGeometry(0.15, 0.15, 0.15),
new THREE.MeshBasicMaterial({
color: 0x50d9ff,
wireframe: true,
transparent: true,
opacity: 0.9
})
);
savedMarker.position.set(0, MARKER_Y, FRONT_Z);
board.add(savedMarker);
const comLabel = createLabel("COM", "#ffd166", 0.82);
comLabel.sprite.position.set(0, MARKER_Y + 0.26, FRONT_Z);
board.add(comLabel.sprite);
const comArrow = new THREE.ArrowHelper(
new THREE.Vector3(1, 0, 0),
new THREE.Vector3(0, MARKER_Y, FRONT_Z),
0.1,
0x62e6a7,
0.07,
0.045
);
comArrow.visible = false;
board.add(comArrow);
const shiftLine = new THREE.Line(
new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(0, MARKER_Y, FRONT_Z),
new THREE.Vector3(0, MARKER_Y, FRONT_Z)
]),
new THREE.LineBasicMaterial({
color: 0x50d9ff,
transparent: true,
opacity: 0.75
})
);
board.add(shiftLine);
// ---------------------------------------------------------------------
// Physics / puzzle model
// ---------------------------------------------------------------------
const PHYSICS = {
gravity: 9.81,
beamMass: 8,
beamX: 0,
supportHalfWidth: 0.25,
maximumTilt: 0.23,
validMass: 11.05
};
let currentMass = PHYSICS.validMass;
let currentCOM = 0;
let savedCOM = 0;
let targetTilt = 0;
function calculateBalance(mass) {
const totalMass =
PHYSICS.beamMass +
crateA.cells.length * 0 + // Keep crate references explicit below.
20 +
mass +
12;
const numerator =
PHYSICS.beamMass * PHYSICS.beamX +
20 * -2.05 +
mass * 1.05 +
12 * 2.45;
const com = numerator / totalMass;
const moment = totalMass * PHYSICS.gravity * com;
const stable = Math.abs(com) <= PHYSICS.supportHalfWidth + 1e-8;
return {
totalMass,
numerator,
com,
moment,
stable
};
}
const initialBalance = calculateBalance(PHYSICS.validMass);
savedCOM = initialBalance.com;
const criticalMass =
(11.6 + PHYSICS.supportHalfWidth * 40) /
(1.05 - PHYSICS.supportHalfWidth);
// ---------------------------------------------------------------------
// DOM references and live readouts
// ---------------------------------------------------------------------
const massSlider = document.getElementById("massSlider");
const massValue = document.getElementById("massValue");
const validBtn = document.getElementById("validBtn");
const nudgeBtn = document.getElementById("nudgeBtn");
const failBtn = document.getElementById("failBtn");
const statusTitle = document.getElementById("statusTitle");
const statusBadge = document.getElementById("statusBadge");
const comValue = document.getElementById("comValue");
const pivotValue = document.getElementById("pivotValue");
const totalValue = document.getElementById("totalValue");
const momentValue = document.getElementById("momentValue");
const directionValue = document.getElementById("directionValue");
const equation = document.getElementById("equation");
const resultText = document.getElementById("resultText");
const currentDot = document.getElementById("currentDot");
const baselineDot = document.getElementById("baselineDot");
const GAUGE_MIN = -0.45;
const GAUGE_MAX = 0.45;
function gaugePosition(value) {
return THREE.MathUtils.clamp(
((value - GAUGE_MIN) / (GAUGE_MAX - GAUGE_MIN)) * 100,
0,
100
);
}
function signed(value, digits) {
const rounded = Number(value.toFixed(digits));
return `${rounded >= 0 ? "+" : ""}${rounded.toFixed(digits)}`;
}
function updateShiftLine() {
shiftLine.geometry.dispose();
shiftLine.geometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(savedCOM, MARKER_Y, FRONT_Z),
new THREE.Vector3(currentCOM, MARKER_Y, FRONT_Z)
]);
}
function updatePhysics() {
const balance = calculateBalance(currentMass);
currentCOM = balance.com;
const beyondSupport = Math.abs(currentCOM) - PHYSICS.supportHalfWidth;
const shift = currentCOM - savedCOM;
if (balance.stable) {
targetTilt = 0;
} else {
targetTilt =
-Math.sign(currentCOM) *
Math.min(
PHYSICS.maximumTilt,
0.04 + beyondSupport * 2.4
);
}
massValue.textContent = `${currentMass.toFixed(2)} kg`;
massSlider.value = currentMass.toFixed(2);
crateB.label.draw(`B · ${currentMass.toFixed(2)} kg`);
const warningMix = THREE.MathUtils.clamp(
(currentMass - criticalMass) / (34 - criticalMass),
0,
1
);
const crateColor = new THREE.Color(0xf59e0b).lerp(
new THREE.Color(0xff4d6d),
warningMix
);
tintCrate(crateB, crateColor.getHex());
if (!balance.stable) {
statusTitle.textContent = "TIPPING";
statusBadge.textContent = "FAILS";
statusBadge.classList.add("failing");
comMarkerMaterial.color.setHex(0xff647c);
} else {
statusTitle.textContent =
Math.abs(currentCOM) < 0.015 ? "Centered" : "Supported";
statusBadge.textContent = "STABLE";
statusBadge.classList.remove("failing");
comMarkerMaterial.color.setHex(0xffd166);
}
comValue.textContent = `${signed(currentCOM, 3)} m`;
pivotValue.textContent = `${Math.abs(currentCOM).toFixed(3)} m`;
totalValue.textContent = `${balance.totalMass.toFixed(2)} kg`;
momentValue.textContent = `${Math.abs(balance.moment).toFixed(1)} N·m`;
directionValue.textContent = !balance.stable
? `${currentCOM > 0 ? "Clockwise" : "Counter-clockwise"}`
: balance.moment > 0.01
? "Clockwise tendency"
: balance.moment < -0.01
? "Counter-clockwise tendency"
: "Balanced";
equation.textContent =
`x̄ = (1.05 × ${currentMass.toFixed(2)} − 11.60) / ` +
`(40 + ${currentMass.toFixed(2)}) = ${signed(currentCOM, 3)} m`;
currentDot.style.left = `${gaugePosition(currentCOM)}%`;
baselineDot.style.left = `${gaugePosition(savedCOM)}%`;
comMarker.position.x = currentCOM;
comLabel.sprite.position.x = currentCOM;
comArrow.visible = Math.abs(currentCOM) > 0.005;
if (comArrow.visible) {
const direction = new THREE.Vector3(Math.sign(currentCOM), 0, 0);
const length = Math.abs(currentCOM);
comArrow.setDirection(direction);
comArrow.setLength(
length,
Math.min(0.1, length * 0.45),
Math.min(0.075, length * 0.3)
);
comArrow.setColor(balance.stable ? 0x62e6a7 : 0xff647c);
}
updateShiftLine();
if (!balance.stable) {
const side = currentCOM > 0 ? "right" : "left";
const directionWord =
balance.moment > 0 ? "clockwise" : "counter-clockwise";
resultText.textContent =
`Crate B gained ${(currentMass - PHYSICS.validMass).toFixed(2)} kg ` +
`without moving. The COM shifted ${Math.abs(shift).toFixed(3)} m ` +
`${shift >= 0 ? "right" : "left"} and is now ` +
`${beyondSupport.toFixed(3)} m beyond the ${side} edge of support. ` +
`The ${Math.abs(balance.moment).toFixed(1)} N·m ${directionWord} ` +
`moment tips the board, so the previously valid arrangement fails.`;
} else if (Math.abs(currentCOM) < 0.015) {
resultText.textContent =
`The combined COM is essentially over the fulcrum. ` +
`The arrangement is centered inside the 0.50 m support window. ` +
`No crate changed position; only B's mass changed.`;
} else {
resultText.textContent =
`The combined COM is ${Math.abs(currentCOM).toFixed(3)} m from ` +
`the pivot and remains inside the support window. ` +
`The load is supported, although the tipping tendency is now ` +
`${directionValue.textContent.toLowerCase()}.`;
}
}
massSlider.addEventListener("input", () => {
currentMass = Number(massSlider.value);
updatePhysics();
});
validBtn.addEventListener("click", () => {
currentMass = PHYSICS.validMass;
updatePhysics();
});
nudgeBtn.addEventListener("click", () => {
currentMass = Math.min(34, currentMass + 5);
updatePhysics();
});
failBtn.addEventListener("click", () => {
currentMass = 30;
updatePhysics();
});
// ---------------------------------------------------------------------
// Direct camera controls: no addons or external control scripts.
// ---------------------------------------------------------------------
const canvas = renderer.domElement;
let dragging = false;
let pointerX = 0;
let pointerY = 0;
canvas.addEventListener("pointerdown", (event) => {
if (event.pointerType === "mouse" && event.button !== 0) return;
dragging = true;
pointerX = event.clientX;
pointerY = event.clientY;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (!dragging) return;
const dx = event.clientX - pointerX;
const dy = event.clientY - pointerY;
pointerX = event.clientX;
pointerY = event.clientY;
cameraState.theta -= dx * 0.006;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi - dy * 0.005,
0.35,
1.45
);
updateCamera();
});
function endDrag(event) {
dragging = false;
if (
event.pointerType !== "mouse" &&
canvas.hasPointerCapture(event.pointerId)
) {
canvas.releasePointerCapture(event.pointerId);
}
}
canvas.addEventListener("pointerup", endDrag);
canvas.addEventListener("pointercancel", endDrag);
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
8.5,
22
);
updateCamera();
},
{ passive: false }
);
canvas.addEventListener("dblclick", resetCamera);
document.getElementById("resetView").addEventListener("click", resetCamera);
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
});
// ---------------------------------------------------------------------
// Animation
// ---------------------------------------------------------------------
updatePhysics();
let previousTime = performance.now();
function animate(time) {
const dt = Math.min(0.05, (time - previousTime) / 1000);
previousTime = time;
const smoothing = 1 - Math.exp(-5 * dt);
board.rotation.z += (targetTilt - board.rotation.z) * smoothing;
renderer.render(scene, camera);
}
renderer.setAnimationLoop(animate);
loading.remove();
</script>
</body>
</html>
```