Prompt specification
Build or customize the Three.js 3D scene "Stack With a Marked Mass Center" 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: Stack With a Marked Mass Center
Category: Games & Play · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/stack-with-a-marked-mass-center-x3513
Scene Description Prompt:
Stack with a marked mass center. Build a small stack of equal-density blocks. Mark each supported substack's center of mass and compare its projection with the corresponding contact support region at every interface. Please build this with Three.js from cdnjs in one self-contained HTML file, using low-poly forms.
Working Three.js Starter (stack-with-a-marked-mass-center-x3513):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Stack Center of Mass and Support Regions</title>
<style>
:root {
color-scheme: dark;
--bg: #08111f;
--panel: rgba(10, 19, 34, 0.88);
--border: rgba(170, 205, 255, 0.18);
--text: #e7f0ff;
--muted: #9eb0ca;
--green: #56e39f;
--red: #ff5f78;
--gold: #ffd166;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
.glass {
background: var(--panel);
border: 1px solid var(--border);
box-shadow: 0 18px 55px rgba(0, 0, 0, 0.35);
backdrop-filter: blur(14px);
-webkit-backdrop-filter: blur(14px);
}
header {
position: fixed;
z-index: 5;
top: 18px;
left: 18px;
max-width: 420px;
padding: 15px 17px;
border-radius: 14px;
pointer-events: none;
}
header h1 {
margin: 0 0 5px;
font-size: 19px;
letter-spacing: 0.01em;
}
header p {
margin: 0;
color: var(--muted);
font-size: 13px;
line-height: 1.45;
}
#panel {
position: fixed;
z-index: 6;
top: 18px;
right: 18px;
width: min(430px, calc(100vw - 36px));
max-height: calc(100vh - 36px);
padding: 17px;
border-radius: 16px;
overflow: auto;
scrollbar-width: thin;
scrollbar-color: #425675 transparent;
}
#panel h2 {
margin: 0 0 5px;
font-size: 16px;
}
.subtle {
color: var(--muted);
font-size: 12px;
line-height: 1.5;
}
#summary {
margin: 13px 0;
padding: 11px 12px;
border: 1px solid var(--border);
border-radius: 11px;
font-weight: 700;
font-size: 14px;
}
.legend {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px 12px;
margin: 13px 0;
font-size: 12px;
color: #cbd8eb;
}
.legend-item {
display: flex;
align-items: center;
gap: 7px;
}
.swatch {
width: 13px;
height: 13px;
flex: 0 0 auto;
border-radius: 3px;
box-shadow: 0 0 10px currentColor;
}
.swatch.com {
color: var(--gold);
background: var(--gold);
clip-path: polygon(50% 0, 100% 50%, 50% 100%, 0 50%);
border-radius: 0;
}
.swatch.projection {
color: white;
background: white;
border-radius: 50%;
}
.swatch.stable {
color: var(--green);
background: var(--green);
}
.swatch.unstable {
color: var(--red);
background: var(--red);
}
.table-wrap {
overflow-x: auto;
margin: 8px 0 13px;
}
table {
width: 100%;
border-collapse: collapse;
font-size: 11px;
white-space: nowrap;
}
th {
color: var(--muted);
font-weight: 600;
text-align: left;
padding: 7px 6px;
border-bottom: 1px solid var(--border);
}
td {
padding: 8px 6px;
border-bottom: 1px solid rgba(170, 205, 255, 0.09);
vertical-align: middle;
}
tr:last-child td {
border-bottom: 0;
}
.stable-text {
color: var(--green);
font-weight: 800;
}
.unstable-text {
color: var(--red);
font-weight: 800;
}
.formula {
margin: 12px 0;
padding: 10px 11px;
border-left: 3px solid #6d8dff;
background: rgba(109, 141, 255, 0.08);
border-radius: 0 8px 8px 0;
color: #cbd8eb;
font-size: 11px;
line-height: 1.55;
}
.controls {
padding-top: 12px;
border-top: 1px solid var(--border);
}
.controls h3 {
margin: 0 0 10px;
font-size: 13px;
}
.slider-row {
display: grid;
grid-template-columns: 28px 1fr 53px;
align-items: center;
gap: 8px;
margin: 9px 0;
font-size: 12px;
}
.slider-row output {
color: var(--muted);
text-align: right;
font-variant-numeric: tabular-nums;
}
input[type="range"] {
width: 100%;
accent-color: #7394ff;
}
.button-row {
display: flex;
flex-wrap: wrap;
gap: 7px;
margin-top: 12px;
}
button {
border: 1px solid var(--border);
border-radius: 8px;
padding: 8px 10px;
color: var(--text);
background: rgba(117, 145, 190, 0.12);
cursor: pointer;
font: inherit;
font-size: 12px;
}
button:hover {
background: rgba(117, 145, 190, 0.24);
border-color: rgba(170, 205, 255, 0.35);
}
button.primary {
color: #07111f;
background: #8ba8ff;
border-color: #8ba8ff;
font-weight: 700;
}
#help {
position: fixed;
z-index: 5;
left: 18px;
bottom: 18px;
padding: 10px 13px;
border-radius: 10px;
color: #bfcee2;
font-size: 12px;
pointer-events: none;
}
@media (max-width: 760px) {
header {
max-width: calc(100vw - 36px);
}
header p {
display: none;
}
#panel {
top: auto;
bottom: 12px;
max-height: 48vh;
}
#help {
display: none;
}
}
</style>
</head>
<body>
<header class="glass">
<h1>Stack stability: center of mass vs. support region</h1>
<p>
Equal-density blocks are stacked with horizontal offsets. Gold markers show
the center of mass of every supported substack; white rings show its
vertical projection onto each interface.
</p>
</header>
<aside id="panel" class="glass">
<h2>Interface analysis</h2>
<div class="subtle">
Density is constant for all blocks. Block masses therefore differ with
their volumes.
</div>
<div id="summary"></div>
<div class="legend">
<div class="legend-item">
<span class="swatch com"></span>
Substack center of mass
</div>
<div class="legend-item">
<span class="swatch projection"></span>
COM projection
</div>
<div class="legend-item">
<span class="swatch stable"></span>
Projection inside patch
</div>
<div class="legend-item">
<span class="swatch unstable"></span>
Projection outside patch
</div>
</div>
<div class="table-wrap">
<table>
<thead>
<tr>
<th>Interface</th>
<th>Upper substack</th>
<th>COM x, z</th>
<th>Contact patch</th>
<th>Test</th>
</tr>
</thead>
<tbody id="results"></tbody>
</table>
</div>
<div class="formula">
<strong>Contact region:</strong> the overlap of the two facing block
footprints. At the ground, it is the footprint of block A.<br />
<strong>Stability test:</strong>
r = ∩(lower footprint, upper footprint), and the projection
(x<sub>COM</sub>, z<sub>COM</sub>) must lie inside r.
A red patch still shows the real geometric overlap; red means the
projected substack COM falls outside it.
</div>
<div class="controls">
<h3>Move upper blocks along X</h3>
<label class="slider-row">
<span>B</span>
<input id="bX" type="range" min="-3.2" max="3.5" step="0.01" />
<output id="bXValue"></output>
</label>
<label class="slider-row">
<span>C</span>
<input id="cX" type="range" min="-3.2" max="3.5" step="0.01" />
<output id="cXValue"></output>
</label>
<label class="slider-row">
<span>D</span>
<input id="dX" type="range" min="-3.2" max="3.5" step="0.01" />
<output id="dXValue"></output>
</label>
<div class="button-row">
<button id="balancedButton">Balanced stack</button>
<button id="offsetButton" class="primary">Offset example</button>
<button id="cameraButton">Reset camera</button>
</div>
</div>
</aside>
<div id="help" class="glass">
Drag: orbit · Shift/right-drag: pan · Wheel: zoom · Double-click: reset view
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// ------------------------------------------------------------
// Scene
// ------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x08111f);
scene.fog = new THREE.Fog(0x08111f, 14, 30);
const camera = new THREE.PerspectiveCamera(
42,
innerWidth / innerHeight,
0.1,
100
);
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
document.body.prepend(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0xa9d2ff, 0x182236, 2.1);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff1d7, 3.0);
sun.position.set(5, 10, 7);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -8;
sun.shadow.camera.right = 8;
sun.shadow.camera.top = 8;
sun.shadow.camera.bottom = -8;
sun.shadow.camera.near = 0.5;
sun.shadow.camera.far = 30;
sun.shadow.bias = -0.0004;
scene.add(sun);
const rim = new THREE.DirectionalLight(0x6a8cff, 1.5);
rim.position.set(-6, 4, -5);
scene.add(rim);
const ground = new THREE.Mesh(
new THREE.CircleGeometry(12, 48),
new THREE.MeshStandardMaterial({
color: 0x0d1929,
roughness: 0.95,
metalness: 0.02
})
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.018;
ground.receiveShadow = true;
scene.add(ground);
const grid = new THREE.GridHelper(24, 48, 0x34506f, 0x1a2d45);
grid.position.y = 0.001;
grid.material.transparent = true;
grid.material.opacity = 0.5;
scene.add(grid);
const blockGroup = new THREE.Group();
const overlayGroup = new THREE.Group();
scene.add(blockGroup, overlayGroup);
const density = 1.0;
// All blocks have the same height and density, but different footprints.
// Heights are computed by stacking the blocks without gaps.
const blocks = [
{
name: "A",
w: 3.4,
d: 2.2,
h: 0.9,
x: -0.2,
z: 0.0,
color: 0x527eff
},
{
name: "B",
w: 2.8,
d: 1.6,
h: 0.9,
x: 0.95,
z: 0.15,
color: 0x9b6cff
},
{
name: "C",
w: 3.0,
d: 1.4,
h: 0.9,
x: 1.65,
z: -0.05,
color: 0x00b8a9
},
{
name: "D",
w: 2.3,
d: 1.2,
h: 0.9,
x: 2.65,
z: 0.1,
color: 0xf59e0b
}
];
let accumulatedHeight = 0;
for (const block of blocks) {
block.mass = density * block.w * block.d * block.h;
block.y = accumulatedHeight + block.h / 2;
accumulatedHeight += block.h;
}
const visualBlocks = [];
function createLabelSprite(text, color = "#eaf3ff") {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 128;
const ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
const radius = 24;
const x = 8;
const y = 8;
const w = 496;
const h = 112;
ctx.beginPath();
ctx.moveTo(x + radius, y);
ctx.lineTo(x + w - radius, y);
ctx.quadraticCurveTo(x + w, y, x + w, y + radius);
ctx.lineTo(x + w, y + h - radius);
ctx.quadraticCurveTo(x + w, y + h, x + w - radius, y + h);
ctx.lineTo(x + radius, y + h);
ctx.quadraticCurveTo(x, y + h, x, y + h - radius);
ctx.lineTo(x, y + radius);
ctx.quadraticCurveTo(x, y, x + radius, y);
ctx.closePath();
ctx.fillStyle = "rgba(7, 15, 29, 0.82)";
ctx.fill();
ctx.strokeStyle = "rgba(190, 215, 255, 0.35)";
ctx.lineWidth = 3;
ctx.stroke();
ctx.font = "600 44px system-ui, sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillStyle = color;
ctx.fillText(text, 256, 66);
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(1.22, 0.305, 1);
sprite.renderOrder = 30;
return sprite;
}
function addBlock(block) {
const geometry = new THREE.BoxGeometry(block.w, block.h, block.d);
const material = new THREE.MeshStandardMaterial({
color: block.color,
roughness: 0.72,
metalness: 0.04,
flatShading: true
});
const mesh = new THREE.Mesh(geometry, material);
mesh.position.set(block.x, block.y, block.z);
mesh.castShadow = true;
mesh.receiveShadow = true;
const edges = new THREE.LineSegments(
new THREE.EdgesGeometry(geometry),
new THREE.LineBasicMaterial({
color: 0xd9e9ff,
transparent: true,
opacity: 0.38
})
);
edges.renderOrder = 2;
mesh.add(edges);
const label = createLabelSprite(
`${block.name} · m ${block.mass.toFixed(2)}`,
"#f3f7ff"
);
label.position.set(block.x, block.y + block.h / 2 + 0.2, block.z);
blockGroup.add(mesh, label);
visualBlocks.push({ block, mesh, label });
}
blocks.forEach(addBlock);
// ------------------------------------------------------------
// Geometry and stability calculations
// ------------------------------------------------------------
function footprint(block) {
return {
minX: block.x - block.w / 2,
maxX: block.x + block.w / 2,
minZ: block.z - block.d / 2,
maxZ: block.z + block.d / 2
};
}
function intersectFootprints(a, b) {
const minX = Math.max(a.minX, b.minX);
const maxX = Math.min(a.maxX, b.maxX);
const minZ = Math.max(a.minZ, b.minZ);
const maxZ = Math.min(a.maxZ, b.maxZ);
return {
minX,
maxX,
minZ,
maxZ,
w: maxX - minX,
d: maxZ - minZ,
centerX: (minX + maxX) / 2,
centerZ: (minZ + maxZ) / 2,
hasArea: maxX > minX && maxZ > minZ
};
}
function substackCenterOfMass(startIndex) {
let totalMass = 0;
let x = 0;
let y = 0;
let z = 0;
for (let i = startIndex; i < blocks.length; i++) {
const block = blocks[i];
totalMass += block.mass;
x += block.mass * block.x;
y += block.mass * block.y;
z += block.mass * block.z;
}
return {
x: x / totalMass,
y: y / totalMass,
z: z / totalMass,
mass: totalMass
};
}
function distanceToRectangle(x, z, rect) {
if (!rect.hasArea) {
return Math.hypot(
Math.max(rect.minX - x, 0, x - rect.maxX),
Math.max(rect.minZ - z, 0, z - rect.maxZ)
);
}
const dx = Math.max(rect.minX - x, 0, x - rect.maxX);
const dz = Math.max(rect.minZ - z, 0, z - rect.maxZ);
return Math.hypot(dx, dz);
}
function marginInsideRectangle(x, z, rect) {
return Math.min(
x - rect.minX,
rect.maxX - x,
z - rect.minZ,
rect.maxZ - z
);
}
function disposeObject(object) {
object.traverse((child) => {
if (child.geometry) {
child.geometry.dispose();
}
if (child.material) {
const materials = Array.isArray(child.material)
? child.material
: [child.material];
for (const material of materials) {
if (material.map) material.map.dispose();
material.dispose();
}
}
});
}
const pulseRings = [];
let analysisRows = [];
function addContactPatch(rect, interfaceY, stable) {
if (!rect.hasArea) return;
const color = stable ? 0x56e39f : 0xff5f78;
const patch = new THREE.Mesh(
new THREE.PlaneGeometry(rect.w, rect.d),
new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity: 0.38,
side: THREE.DoubleSide,
depthTest: false,
depthWrite: false
})
);
patch.rotation.x = -Math.PI / 2;
patch.position.set(
rect.centerX,
interfaceY + 0.018,
rect.centerZ
);
patch.renderOrder = 20;
overlayGroup.add(patch);
const y = interfaceY + 0.025;
const points = [
new THREE.Vector3(rect.minX, y, rect.minZ),
new THREE.Vector3(rect.maxX, y, rect.minZ),
new THREE.Vector3(rect.maxX, y, rect.maxZ),
new THREE.Vector3(rect.minX, y, rect.maxZ)
];
const border = new THREE.LineLoop(
new THREE.BufferGeometry().setFromPoints(points),
new THREE.LineBasicMaterial({
color,
transparent: true,
opacity: 0.95,
depthTest: false,
depthWrite: false
})
);
border.renderOrder = 21;
overlayGroup.add(border);
}
function addCOMMarker(com, interfaceY, stable, index) {
const markerColor = 0xffd166;
const projectionColor = stable ? 0xffffff : 0xff5f78;
// Actual center of mass of the upper substack.
const comMarker = new THREE.Mesh(
new THREE.OctahedronGeometry(0.13, 0),
new THREE.MeshBasicMaterial({
color: markerColor,
depthTest: false,
depthWrite: false
})
);
comMarker.position.set(com.x, com.y, com.z);
comMarker.renderOrder = 27;
overlayGroup.add(comMarker);
// Projection of the COM onto the interface plane.
const ring = new THREE.Mesh(
new THREE.RingGeometry(0.085, 0.135, 20),
new THREE.MeshBasicMaterial({
color: projectionColor,
side: THREE.DoubleSide,
depthTest: false,
depthWrite: false
})
);
ring.rotation.x = -Math.PI / 2;
ring.position.set(com.x, interfaceY + 0.04, com.z);
ring.renderOrder = 26;
ring.userData.phase = index * 0.9;
ring.userData.unstable = !stable;
pulseRings.push(ring);
overlayGroup.add(ring);
// Vertical plumb line between COM and its projection.
const lineGeometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(com.x, interfaceY + 0.04, com.z),
new THREE.Vector3(com.x, com.y, com.z)
]);
const line = new THREE.Line(
lineGeometry,
new THREE.LineDashedMaterial({
color: projectionColor,
dashSize: 0.1,
gapSize: 0.065,
transparent: true,
opacity: 0.9,
depthTest: false,
depthWrite: false
})
);
line.computeLineDistances();
line.renderOrder = 24;
overlayGroup.add(line);
const label = createLabelSprite(`Σ${index} COM`, "#ffd166");
label.scale.set(0.92, 0.23, 1);
label.position.set(com.x + 0.25, com.y + 0.28, com.z);
label.renderOrder = 31;
overlayGroup.add(label);
}
function interfaceName(index) {
if (index === 0) return "Ground / A";
return `${blocks[index - 1].name} / ${blocks[index].name}`;
}
function substackName(index) {
return blocks
.slice(index)
.map((block) => block.name)
.join(" + ");
}
function updateAnalysis() {
// Clear only the analysis overlays; the blocks and their labels remain.
for (const child of [...overlayGroup.children]) {
disposeObject(child);
overlayGroup.remove(child);
}
pulseRings.length = 0;
// Update block transforms.
for (const visual of visualBlocks) {
visual.mesh.position.x = visual.block.x;
visual.mesh.position.z = visual.block.z;
visual.label.position.x = visual.block.x;
visual.label.position.z = visual.block.z;
}
analysisRows = [];
for (let index = 0; index < blocks.length; index++) {
const com = substackCenterOfMass(index);
let contact;
let interfaceY;
if (index === 0) {
// Ground interface: support is the entire bottom footprint of A.
const a = footprint(blocks[0]);
contact = intersectFootprints(a, a);
interfaceY = 0;
} else {
// Block-to-block interface.
const lower = footprint(blocks[index - 1]);
const upper = footprint(blocks[index]);
contact = intersectFootprints(lower, upper);
interfaceY = blocks[index - 1].y + blocks[index - 1].h / 2;
}
const stable =
contact.hasArea &&
com.x >= contact.minX &&
com.x <= contact.maxX &&
com.z >= contact.minZ &&
com.z <= contact.maxZ;
const distance = distanceToRectangle(com.x, com.z, contact);
const margin = contact.hasArea
? marginInsideRectangle(com.x, com.z, contact)
: 0;
const row = {
index,
interfaceName: interfaceName(index),
substackName: substackName(index),
com,
contact,
interfaceY,
stable,
distance,
margin
};
analysisRows.push(row);
addContactPatch(contact, interfaceY, stable);
addCOMMarker(com, interfaceY, stable, index);
}
updateResultsPanel();
}
function updateResultsPanel() {
const tbody = document.getElementById("results");
tbody.replaceChildren();
let stableCount = 0;
for (const row of analysisRows) {
if (row.stable) stableCount++;
const tr = document.createElement("tr");
const patchText = row.contact.hasArea
? `${row.contact.w.toFixed(2)} × ${row.contact.d.toFixed(2)}`
: "no overlap";
const resultText = row.stable
? `Inside · ${row.margin.toFixed(2)} m`
: `Outside · ${row.distance.toFixed(2)} m`;
tr.innerHTML = `
<td>${row.interfaceName}</td>
<td>${row.substackName}</td>
<td>${row.com.x.toFixed(2)}, ${row.com.z.toFixed(2)}</td>
<td>${patchText}</td>
<td class="${row.stable ? "stable-text" : "unstable-text"}">
${resultText}
</td>
`;
tbody.appendChild(tr);
}
const summary = document.getElementById("summary");
const allStable = stableCount === analysisRows.length;
summary.innerHTML = `
<span class="${allStable ? "stable-text" : "unstable-text"}">
${stableCount} of ${analysisRows.length} interface tests pass
</span>
<div class="subtle" style="margin-top:4px; font-weight:400">
${
allStable
? "Every supported substack projects inside its contact region."
: "At least one upper substack projects outside its contact region."
}
</div>
`;
}
// ------------------------------------------------------------
// Direct camera controls: orbit, pan, zoom, and reset
// ------------------------------------------------------------
const cameraState = {
radius: 11.4,
theta: 0.73,
phi: 1.02,
target: new THREE.Vector3(0.65, 1.45, 0)
};
const defaultCameraState = {
radius: 11.4,
theta: 0.73,
phi: 1.02,
target: new THREE.Vector3(0.65, 1.45, 0)
};
function updateCamera() {
const sinPhi = Math.sin(cameraState.phi);
const cosPhi = Math.cos(cameraState.phi);
camera.position.set(
cameraState.target.x +
cameraState.radius * sinPhi * Math.sin(cameraState.theta),
cameraState.target.y + cameraState.radius * cosPhi,
cameraState.target.z +
cameraState.radius * sinPhi * Math.cos(cameraState.theta)
);
camera.lookAt(cameraState.target);
}
function resetCamera() {
cameraState.radius = defaultCameraState.radius;
cameraState.theta = defaultCameraState.theta;
cameraState.phi = defaultCameraState.phi;
cameraState.target.copy(defaultCameraState.target);
updateCamera();
}
const pointer = {
active: false,
mode: "orbit",
x: 0,
y: 0
};
renderer.domElement.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
renderer.domElement.addEventListener("pointerdown", (event) => {
pointer.active = true;
pointer.x = event.clientX;
pointer.y = event.clientY;
pointer.mode =
event.button === 2 || event.shiftKey ? "pan" : "orbit";
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!pointer.active) return;
const dx = event.clientX - pointer.x;
const dy = event.clientY - pointer.y;
pointer.x = event.clientX;
pointer.y = event.clientY;
if (pointer.mode === "orbit") {
cameraState.theta -= dx * 0.006;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi - dy * 0.006,
0.15,
Math.PI / 2.05
);
} else {
const forward = new THREE.Vector3()
.subVectors(cameraState.target, camera.position)
.normalize();
const right = new THREE.Vector3()
.crossVectors(forward, camera.up)
.normalize();
const up = new THREE.Vector3()
.crossVectors(right, forward)
.normalize();
const panScale = cameraState.radius * 0.0015;
cameraState.target.addScaledVector(right, -dx * panScale);
cameraState.target.addScaledVector(up, dy * panScale);
}
updateCamera();
});
function stopPointer(event) {
pointer.active = false;
if (event.pointerId !== undefined) {
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
}
renderer.domElement.addEventListener("pointerup", stopPointer);
renderer.domElement.addEventListener("pointercancel", stopPointer);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
4.5,
24
);
updateCamera();
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", resetCamera);
// ------------------------------------------------------------
// UI controls
// ------------------------------------------------------------
const sliders = {
B: document.getElementById("bX"),
C: document.getElementById("cX"),
D: document.getElementById("dX")
};
const outputs = {
B: document.getElementById("bXValue"),
C: document.getElementById("cXValue"),
D: document.getElementById("dXValue")
};
function syncSliderOutputs() {
for (const block of blocks.slice(1)) {
sliders[block.name].value = block.x;
outputs[block.name].value = `${block.x.toFixed(2)} m`;
}
}
for (const block of blocks.slice(1)) {
sliders[block.name].addEventListener("input", (event) => {
block.x = Number(event.target.value);
outputs[block.name].value = `${block.x.toFixed(2)} m`;
updateAnalysis();
});
}
const presets = {
balanced: [
{ name: "B", x: 0.15 },
{ name: "C", x: 0.5 },
{ name: "D", x: 0.85 }
],
offset: [
{ name: "B", x: 0.95 },
{ name: "C", x: 1.65 },
{ name: "D", x: 2.65 }
]
};
function applyPreset(name) {
for (const item of presets[name]) {
const block = blocks.find((candidate) => candidate.name === item.name);
block.x = item.x;
}
syncSliderOutputs();
updateAnalysis();
}
document
.getElementById("balancedButton")
.addEventListener("click", () => applyPreset("balanced"));
document
.getElementById("offsetButton")
.addEventListener("click", () => applyPreset("offset"));
document
.getElementById("cameraButton")
.addEventListener("click", resetCamera);
// ------------------------------------------------------------
// Resize and render loop
// ------------------------------------------------------------
window.addEventListener("resize", () => {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
});
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const elapsed = clock.getElapsedTime();
for (const ring of pulseRings) {
const amplitude = ring.userData.unstable ? 0.11 : 0.035;
const speed = ring.userData.unstable ? 5.0 : 2.2;
const scale =
1 + Math.sin(elapsed * speed + ring.userData.phase) * amplitude;
ring.scale.setScalar(scale);
}
renderer.render(scene, camera);
}
syncSliderOutputs();
updateAnalysis();
updateCamera();
animate();
</script>
</body>
</html>
```