Prompt specification
Build or customize the Three.js 3D scene "Cosmology Analogy Exhibition" 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: Cosmology Analogy Exhibition
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/cosmology-analogy-exhibition-x3771
Scene Description Prompt:
Build an exhibit comparing expanding grids and local bound objects with explicit explanatory limits. Avoid claiming the analogy fully represents spacetime or the behavior of bound systems. Build this with Three.js from cdnjs as a voxel scene in one self-contained HTML file.
Working Three.js Starter (cosmology-analogy-exhibition-x3771):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Scale & Locality — Expanding Grids and Local Bound Objects</title>
<style>
:root {
color-scheme: dark;
--bg: #050c14;
--panel: rgba(10, 21, 33, 0.86);
--panel-border: rgba(147, 197, 220, 0.16);
--text: #e8f3f7;
--muted: #91a8b6;
--cyan: #52dcff;
--cyan-soft: rgba(82, 220, 255, 0.13);
--amber: #ffb85c;
--amber-soft: rgba(255, 184, 92, 0.12);
--warning: #ffd786;
--danger: #ff9e7a;
}
* {
box-sizing: border-box;
}
html,
body {
margin: 0;
min-height: 100%;
background: var(--bg);
color: var(--text);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
body {
overflow: hidden;
}
button,
input,
select {
font: inherit;
}
button,
select {
color: var(--text);
}
#app {
display: grid;
grid-template-rows: 72px minmax(320px, 1fr) 278px;
width: 100%;
height: 100dvh;
min-height: 680px;
overflow: hidden;
background:
radial-gradient(circle at 18% 10%, rgba(27, 117, 153, 0.12), transparent 34%),
radial-gradient(circle at 84% 16%, rgba(161, 93, 29, 0.10), transparent 32%),
var(--bg);
}
header {
position: relative;
z-index: 5;
display: flex;
align-items: center;
justify-content: space-between;
gap: 24px;
padding: 0 24px;
border-bottom: 1px solid var(--panel-border);
background: rgba(5, 12, 20, 0.88);
backdrop-filter: blur(14px);
}
.brand {
display: flex;
align-items: center;
gap: 13px;
min-width: 0;
}
.brand-mark {
position: relative;
width: 36px;
height: 36px;
flex: 0 0 auto;
border: 1px solid rgba(82, 220, 255, 0.45);
border-radius: 9px;
background:
linear-gradient(90deg, transparent 47%, rgba(82, 220, 255, 0.42) 48% 52%, transparent 53%),
linear-gradient(transparent 47%, rgba(82, 220, 255, 0.42) 48% 52%, transparent 53%),
var(--cyan-soft);
box-shadow: 0 0 24px rgba(82, 220, 255, 0.09);
}
.brand-mark::after {
content: "";
position: absolute;
width: 6px;
height: 6px;
top: 7px;
right: 7px;
border-radius: 2px;
background: var(--amber);
box-shadow: 0 0 12px rgba(255, 184, 92, 0.8);
}
h1 {
margin: 0;
font-size: 17px;
line-height: 1.1;
letter-spacing: 0.02em;
}
.subtitle {
margin: 5px 0 0;
color: var(--muted);
font-size: 12px;
letter-spacing: 0.025em;
}
.scope-badge {
flex: 0 0 auto;
padding: 8px 12px;
border: 1px solid rgba(255, 215, 134, 0.27);
border-radius: 999px;
color: var(--warning);
background: rgba(255, 215, 134, 0.06);
font-size: 11px;
letter-spacing: 0.055em;
text-transform: uppercase;
}
#stage {
position: relative;
min-height: 0;
overflow: hidden;
isolation: isolate;
}
#stage canvas {
position: absolute;
inset: 0;
display: block;
width: 100%;
height: 100%;
outline: none;
touch-action: none;
}
.split-line {
position: absolute;
z-index: 2;
top: 0;
bottom: 0;
left: 50%;
width: 1px;
pointer-events: none;
background: linear-gradient(
transparent,
rgba(157, 203, 222, 0.22) 15%,
rgba(157, 203, 222, 0.22) 85%,
transparent
);
}
.scene-label {
position: absolute;
z-index: 3;
top: 16px;
width: calc(50% - 30px);
pointer-events: none;
}
.scene-label.left {
left: 18px;
}
.scene-label.right {
right: 18px;
text-align: right;
}
.eyebrow {
display: block;
margin-bottom: 6px;
color: var(--muted);
font-size: 10px;
font-weight: 700;
letter-spacing: 0.15em;
text-transform: uppercase;
}
.scene-label h2 {
margin: 0;
font-size: clamp(18px, 2.2vw, 28px);
letter-spacing: -0.025em;
}
.scene-label.left h2 {
color: var(--cyan);
}
.scene-label.right h2 {
color: var(--amber);
}
.scene-label p {
margin: 7px 0 0;
color: var(--muted);
font-size: 12px;
line-height: 1.45;
}
.tag {
display: inline-block;
margin-top: 9px;
padding: 5px 8px;
border: 1px solid var(--panel-border);
border-radius: 6px;
color: #aec2ce;
background: rgba(7, 16, 26, 0.62);
font-size: 10px;
letter-spacing: 0.04em;
}
.metric-card {
position: absolute;
z-index: 3;
bottom: 17px;
width: calc(50% - 30px);
padding: 12px 14px;
border: 1px solid var(--panel-border);
border-radius: 11px;
pointer-events: none;
background: var(--panel);
box-shadow: 0 12px 40px rgba(0, 0, 0, 0.2);
backdrop-filter: blur(12px);
}
.metric-card.left {
left: 18px;
border-left: 2px solid var(--cyan);
}
.metric-card.right {
right: 18px;
border-right: 2px solid var(--amber);
text-align: right;
}
.metric-title {
color: var(--muted);
font-size: 10px;
font-weight: 700;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.metric-main {
display: flex;
align-items: baseline;
gap: 7px;
margin-top: 5px;
font-variant-numeric: tabular-nums;
}
.metric-card.right .metric-main {
justify-content: flex-end;
}
.metric-main strong {
font-size: 22px;
line-height: 1;
font-weight: 650;
}
.metric-card.left .metric-main strong {
color: var(--cyan);
}
.metric-card.right .metric-main strong {
color: var(--amber);
}
.metric-main span {
color: var(--muted);
font-size: 11px;
}
.metric-secondary {
margin-top: 6px;
color: var(--muted);
font-size: 11px;
line-height: 1.4;
}
.interaction-hint {
position: absolute;
z-index: 3;
left: 50%;
bottom: 18px;
transform: translateX(-50%);
padding: 7px 10px;
border: 1px solid rgba(151, 188, 205, 0.12);
border-radius: 999px;
color: rgba(185, 204, 214, 0.7);
background: rgba(5, 12, 20, 0.58);
pointer-events: none;
font-size: 10px;
white-space: nowrap;
}
.deck {
position: relative;
z-index: 5;
display: grid;
grid-template-columns: 260px minmax(0, 1fr) minmax(0, 1fr);
grid-template-rows: auto 1fr;
gap: 12px;
padding: 13px 18px 15px;
border-top: 1px solid var(--panel-border);
background: rgba(5, 12, 20, 0.95);
}
.controls,
.model-card,
.scope-note {
border: 1px solid var(--panel-border);
border-radius: 12px;
background: rgba(12, 25, 38, 0.72);
}
.controls {
grid-column: 1;
grid-row: 1 / 3;
padding: 14px;
}
.control-title {
margin: 0 0 11px;
color: #c8d9e2;
font-size: 11px;
font-weight: 750;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.button-row {
display: flex;
gap: 7px;
margin-bottom: 13px;
}
button {
min-height: 34px;
padding: 7px 10px;
border: 1px solid rgba(150, 196, 216, 0.2);
border-radius: 7px;
background: rgba(145, 194, 215, 0.09);
cursor: pointer;
font-size: 11px;
transition:
background 140ms ease,
border-color 140ms ease,
transform 140ms ease;
}
button:hover {
border-color: rgba(82, 220, 255, 0.48);
background: rgba(82, 220, 255, 0.12);
}
button:active {
transform: translateY(1px);
}
button.primary {
flex: 1;
color: #061018;
border-color: transparent;
background: var(--cyan);
font-weight: 750;
}
button.primary:hover {
background: #8ae9ff;
}
.control-label {
display: flex;
justify-content: space-between;
gap: 10px;
margin: 10px 0 7px;
color: var(--muted);
font-size: 10px;
letter-spacing: 0.06em;
text-transform: uppercase;
}
input[type="range"] {
width: 100%;
height: 5px;
margin: 4px 0 0;
border-radius: 999px;
accent-color: var(--cyan);
cursor: pointer;
}
select {
width: 100%;
min-height: 32px;
padding: 5px 8px;
border: 1px solid rgba(150, 196, 216, 0.2);
border-radius: 7px;
background: #0c1926;
font-size: 11px;
}
.check-row {
display: flex;
align-items: center;
gap: 8px;
margin-top: 12px;
color: #b7c9d3;
font-size: 11px;
}
.check-row input {
accent-color: var(--amber);
}
.legend {
display: grid;
gap: 7px;
margin-top: 14px;
padding-top: 12px;
border-top: 1px solid rgba(151, 188, 205, 0.12);
color: var(--muted);
font-size: 10px;
line-height: 1.35;
}
.legend-item {
display: flex;
align-items: center;
gap: 8px;
}
.swatch {
width: 11px;
height: 11px;
flex: 0 0 auto;
border-radius: 2px;
}
.swatch.cyan {
background: var(--cyan);
box-shadow: 0 0 10px rgba(82, 220, 255, 0.45);
}
.swatch.amber {
background: var(--amber);
box-shadow: 0 0 10px rgba(255, 184, 92, 0.45);
}
.swatch.bond {
height: 2px;
border-radius: 0;
background: #f6a949;
}
.model-card {
padding: 13px 15px;
}
.model-card.grid {
grid-column: 2;
grid-row: 1;
border-top: 2px solid var(--cyan);
}
.model-card.bound {
grid-column: 3;
grid-row: 1;
border-top: 2px solid var(--amber);
}
.model-card h3 {
display: flex;
align-items: center;
gap: 8px;
margin: 0 0 7px;
font-size: 12px;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.model-card.grid h3 {
color: var(--cyan);
}
.model-card.bound h3 {
color: var(--amber);
}
.model-card p {
margin: 5px 0;
color: #adc1cc;
font-size: 11px;
line-height: 1.45;
}
.model-card .limit {
color: #d4dee4;
}
.limit strong {
color: var(--warning);
font-weight: 750;
}
.scope-note {
grid-column: 2 / 4;
grid-row: 2;
display: flex;
align-items: flex-start;
gap: 10px;
padding: 11px 14px;
border-color: rgba(255, 215, 134, 0.23);
background: rgba(255, 215, 134, 0.055);
color: #d8e0e5;
font-size: 10.5px;
line-height: 1.45;
}
.scope-note .scope-mark {
flex: 0 0 auto;
margin-top: 1px;
color: var(--warning);
font-size: 13px;
font-weight: 800;
}
.scope-note strong {
color: var(--warning);
}
.fallback {
position: absolute;
inset: 0;
display: grid;
place-items: center;
padding: 30px;
color: var(--danger);
text-align: center;
background: var(--bg);
}
@media (max-width: 980px) {
body {
overflow: auto;
}
#app {
height: auto;
min-height: 100dvh;
grid-template-rows: 72px 560px auto;
overflow: visible;
}
.deck {
grid-template-columns: 1fr;
grid-template-rows: auto;
}
.controls,
.model-card.grid,
.model-card.bound,
.scope-note {
grid-column: 1;
grid-row: auto;
}
.controls {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px 18px;
}
.control-title,
.button-row,
.legend {
grid-column: 1 / 3;
}
.model-card.grid {
border-top: 1px solid var(--panel-border);
border-left: 2px solid var(--cyan);
}
.model-card.bound {
border-top: 1px solid var(--panel-border);
border-left: 2px solid var(--amber);
}
}
@media (max-width: 620px) {
header {
padding: 0 14px;
}
.scope-badge {
display: none;
}
.subtitle {
max-width: 230px;
font-size: 10px;
}
#app {
grid-template-rows: 66px 540px auto;
}
.scene-label {
width: calc(50% - 20px);
}
.scene-label.left {
left: 11px;
}
.scene-label.right {
right: 11px;
}
.scene-label h2 {
font-size: 17px;
}
.scene-label p,
.tag {
display: none;
}
.metric-card {
width: calc(50% - 20px);
bottom: 11px;
padding: 10px;
}
.metric-card.left {
left: 10px;
}
.metric-card.right {
right: 10px;
}
.metric-main strong {
font-size: 17px;
}
.interaction-hint {
display: none;
}
.controls {
display: block;
}
.legend {
margin-top: 12px;
}
}
@media (prefers-reduced-motion: reduce) {
button {
transition: none;
}
}
</style>
</head>
<body>
<div id="app">
<header>
<div class="brand">
<div class="brand-mark" aria-hidden="true"></div>
<div>
<h1>Scale & Locality</h1>
<p class="subtitle">Expanding grids compared with locally constrained voxel objects</p>
</div>
</div>
<div class="scope-badge">Conceptual comparison · not an equivalence</div>
</header>
<main id="stage" aria-label="Interactive voxel exhibit">
<div class="split-line" aria-hidden="true"></div>
<section class="scene-label left">
<span class="eyebrow">01 · Global coordinate rule</span>
<h2>Expanding grid</h2>
<p>Every coordinate separation is multiplied by one common factor.</p>
<span class="tag">125 rigid voxels · no connecting constraints</span>
</section>
<section class="scene-label right">
<span class="eyebrow">02 · Neighboring-pair rule</span>
<h2>Local bound object</h2>
<p>Only nearby pairs exert constraints on one another.</p>
<span class="tag">125 rigid voxels · 300 local toy bonds</span>
</section>
<section class="metric-card left" aria-live="polite">
<div class="metric-title">Selected neighboring gap</div>
<div class="metric-main">
<strong id="gridSpacing">0.44</strong>
<span>world units</span>
</div>
<div class="metric-secondary">
Coordinate dilation: <span id="gridRatio">1.00×</span>
</div>
</section>
<section class="metric-card right" aria-live="polite">
<div class="metric-title">Mean nearest-neighbor bond</div>
<div class="metric-main">
<strong id="bondLength">0.44</strong>
<span>world units</span>
</div>
<div class="metric-secondary">
Maximum local strain: <span id="bondStrain">0.0%</span>
</div>
</section>
<div class="interaction-hint">Drag to orbit · wheel to zoom · Shift-drag to pan</div>
</main>
<section class="deck" aria-label="Exhibit controls and explanatory limits">
<div class="controls">
<h2 class="control-title">Exhibit controls</h2>
<div class="button-row">
<button class="primary" id="playButton" type="button">Pause</button>
<button id="resetButton" type="button">Restart</button>
</div>
<label class="control-label" for="timeline">
<span>Expansion stage</span>
<output id="stageOutput" for="timeline">22%</output>
</label>
<input
id="timeline"
type="range"
min="0"
max="100"
value="22"
step="0.1"
aria-label="Expansion stage"
/>
<label class="control-label" for="speed">
<span>Playback speed</span>
</label>
<select id="speed">
<option value="0.5">0.5×</option>
<option value="1" selected>1×</option>
<option value="1.5">1.5×</option>
<option value="2">2×</option>
</select>
<label class="check-row">
<input id="showBonds" type="checkbox" checked />
Show local bond constraints
</label>
<button id="cameraButton" type="button" style="width: 100%; margin-top: 10px;">
Reset camera
</button>
<div class="legend" aria-label="Scene legend">
<div class="legend-item">
<span class="swatch cyan" aria-hidden="true"></span>
Free lattice elements
</div>
<div class="legend-item">
<span class="swatch amber" aria-hidden="true"></span>
Constrained object elements
</div>
<div class="legend-item">
<span class="swatch bond" aria-hidden="true"></span>
Pairwise toy constraint
</div>
</div>
</div>
<article class="model-card grid">
<h3>What the expanding grid demonstrates</h3>
<p>
A deliberately global transformation scales all coordinate separations
while leaving the individual voxel shapes unchanged. The highlighted
line marks one neighboring gap.
</p>
<p class="limit">
<strong>Explicit limit:</strong> coordinate dilation is not a spacetime
field equation. This exhibit includes no dynamical metric, light cones,
geodesics, gravitational dynamics, or observer-dependent measurements.
</p>
</article>
<article class="model-card bound">
<h3>What the local bound object demonstrates</h3>
<p>
Chosen neighboring pairs resist changes in their rest length. The
cluster can move and rotate while its internal distances remain
approximately stable and locally stressed.
</p>
<p class="limit">
<strong>Explicit limit:</strong> toy springs are not electromagnetism,
the strong interaction, or a relativistic theory. This model cannot
derive real mass, charge, stability, or bound-system behavior.
</p>
</article>
<div class="scope-note">
<span class="scope-mark" aria-hidden="true">!</span>
<div>
<strong>Interpret these as two limited demonstrations, not as complete
or competing descriptions of reality.</strong>
The expanding lattice is a visualization of one imposed scaling rule;
the bound cluster is a visualization of selected local constraints.
Neither panel is a model of spacetime, and neither should be treated as
an explanation of how actual cosmic expansion or actual matter binds.
</div>
</div>
</section>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const stage = document.getElementById("stage");
const playButton = document.getElementById("playButton");
const resetButton = document.getElementById("resetButton");
const cameraButton = document.getElementById("cameraButton");
const timeline = document.getElementById("timeline");
const stageOutput = document.getElementById("stageOutput");
const speedSelect = document.getElementById("speed");
const showBonds = document.getElementById("showBonds");
const gridSpacingOutput = document.getElementById("gridSpacing");
const gridRatioOutput = document.getElementById("gridRatio");
const bondLengthOutput = document.getElementById("bondLength");
const bondStrainOutput = document.getElementById("bondStrain");
let renderer;
try {
renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
} catch (error) {
const fallback = document.createElement("div");
fallback.className = "fallback";
fallback.textContent =
"WebGL could not be initialized. This exhibit requires a browser with WebGL support.";
stage.appendChild(fallback);
throw error;
}
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.domElement.setAttribute("aria-label", "Voxel comparison scene");
renderer.domElement.tabIndex = 0;
stage.prepend(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x050c14);
scene.fog = new THREE.FogExp2(0x050c14, 0.027);
const camera = new THREE.PerspectiveCamera(
42,
1,
0.1,
100
);
const hemisphere = new THREE.HemisphereLight(0xc4efff, 0x07101b, 2.15);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xffffff, 2.5);
keyLight.position.set(5, 10, 8);
scene.add(keyLight);
const cyanLight = new THREE.PointLight(0x26c8ff, 24, 13, 2);
cyanLight.position.set(-5, 2.5, 3.5);
scene.add(cyanLight);
const amberLight = new THREE.PointLight(0xffa63d, 22, 12, 2);
amberLight.position.set(5, 2.4, 3);
scene.add(amberLight);
const N = 5;
const COUNT = N * N * N;
const REST_LENGTH = 0.44;
const VOXEL_SIZE = 0.17;
const LEFT_X = -4.9;
const RIGHT_X = 4.9;
const MAX_DILATION = 2.35;
const indexOf = (x, y, z) => x + N * y + N * N * z;
// A quiet, axis-aligned reference floor.
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(36, 24),
new THREE.MeshStandardMaterial({
color: 0x07121d,
roughness: 0.95,
metalness: 0.05
})
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -3.05;
scene.add(floor);
const floorGrid = new THREE.GridHelper(30, 60, 0x2c6479, 0x153747);
floorGrid.position.y = -3.035;
floorGrid.material.transparent = true;
floorGrid.material.opacity = 0.19;
scene.add(floorGrid);
function addExhibitRing(x, radius, color) {
const ring = new THREE.Mesh(
new THREE.RingGeometry(radius - 0.025, radius + 0.025, 96),
new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity: 0.43,
side: THREE.DoubleSide
})
);
ring.rotation.x = -Math.PI / 2;
ring.position.set(x, -3.02, 0);
scene.add(ring);
}
addExhibitRing(LEFT_X, 2.7, 0x52dcff);
addExhibitRing(RIGHT_X, 1.85, 0xffb85c);
const gridGroup = new THREE.Group();
gridGroup.position.x = LEFT_X;
scene.add(gridGroup);
const boundGroup = new THREE.Group();
boundGroup.position.x = RIGHT_X;
scene.add(boundGroup);
const dummy = new THREE.Object3D();
function createVoxelMesh(color) {
const geometry = new THREE.BoxGeometry(
VOXEL_SIZE,
VOXEL_SIZE,
VOXEL_SIZE
);
const material = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.48,
metalness: 0.18
});
const mesh = new THREE.InstancedMesh(geometry, material, COUNT);
mesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
mesh.frustumCulled = false;
mesh.castShadow = false;
mesh.receiveShadow = false;
return mesh;
}
const gridMesh = createVoxelMesh();
gridGroup.add(gridMesh);
const boundMesh = createVoxelMesh();
boundGroup.add(boundMesh);
// Shared initial coordinates for both panels.
const basePositions = new Float32Array(COUNT * 3);
for (let x = 0; x < N; x++) {
for (let y = 0; y < N; y++) {
for (let z = 0; z < N; z++) {
const i = indexOf(x, y, z);
const p = i * 3;
basePositions[p] = (x - (N - 1) / 2) * REST_LENGTH;
basePositions[p + 1] = (y - (N - 1) / 2) * REST_LENGTH;
basePositions[p + 2] = (z - (N - 1) / 2) * REST_LENGTH;
const gridColor = new THREE.Color().setHSL(
0.52 + 0.035 * z + 0.012 * y,
0.72,
0.57
);
gridMesh.setColorAt(i, gridColor);
const boundColor = new THREE.Color().setHSL(
0.075 + 0.028 * y + 0.012 * x,
0.82,
0.59
);
boundMesh.setColorAt(i, boundColor);
}
}
}
gridMesh.instanceColor.needsUpdate = true;
boundMesh.instanceColor.needsUpdate = true;
// A transparent coordinate cage is only a visual guide, not a physical wall.
const cage = new THREE.LineSegments(
new THREE.EdgesGeometry(new THREE.BoxGeometry(1, 1, 1)),
new THREE.LineBasicMaterial({
color: 0x52dcff,
transparent: true,
opacity: 0.22
})
);
gridGroup.add(cage);
// Highlight one neighboring gap in the expanding lattice.
const measurementGeometry = new THREE.BufferGeometry();
measurementGeometry.setAttribute(
"position",
new THREE.BufferAttribute(new Float32Array(18), 3)
);
const measurement = new THREE.LineSegments(
measurementGeometry,
new THREE.LineBasicMaterial({
color: 0xb3f2ff,
transparent: true,
opacity: 0.92
})
);
gridGroup.add(measurement);
const measuredA = indexOf(1, 0, 2);
const measuredB = indexOf(2, 0, 2);
// Local spring-lattice state for the bound object.
const positions = new Float32Array(basePositions);
const velocities = new Float32Array(COUNT * 3);
const forces = new Float32Array(COUNT * 3);
const bonds = [];
for (let x = 0; x < N; x++) {
for (let y = 0; y < N; y++) {
for (let z = 0; z < N; z++) {
const i = indexOf(x, y, z);
const p = i * 3;
velocities[p] =
0.12 * Math.sin(i * 1.73 + x * 0.61 + y * 1.19 + z * 2.07);
velocities[p + 1] =
0.12 * Math.sin(i * 2.11 + x * 1.31 + y * 0.47 + z * 1.73);
velocities[p + 2] =
0.12 * Math.sin(i * 1.37 + x * 0.91 + y * 2.29 + z * 0.53);
if (x < N - 1) {
bonds.push([i, indexOf(x + 1, y, z)]);
}
if (y < N - 1) {
bonds.push([i, indexOf(x, y + 1, z)]);
}
if (z < N - 1) {
bonds.push([i, indexOf(x, y, z + 1)]);
}
}
}
}
// Remove the arbitrary mean initial velocity.
let meanVelocity = [0, 0, 0];
for (let i = 0; i < COUNT; i++) {
const p = i * 3;
meanVelocity[0] += velocities[p];
meanVelocity[1] += velocities[p + 1];
meanVelocity[2] += velocities[p + 2];
}
for (let axis = 0; axis < 3; axis++) {
meanVelocity[axis] /= COUNT;
}
for (let i = 0; i < COUNT; i++) {
const p = i * 3;
velocities[p] -= meanVelocity[0];
velocities[p + 1] -= meanVelocity[1];
velocities[p + 2] -= meanVelocity[2];
}
const bondPositions = new Float32Array(bonds.length * 2 * 3);
const bondGeometry = new THREE.BufferGeometry();
bondGeometry.setAttribute(
"position",
new THREE.BufferAttribute(bondPositions, 3)
);
const bondLines = new THREE.LineSegments(
bondGeometry,
new THREE.LineBasicMaterial({
color: 0xffb85c,
transparent: true,
opacity: 0.78
})
);
bondLines.frustumCulled = false;
boundGroup.add(bondLines);
const SPRING_STIFFNESS = 62;
const SPRING_DAMPING = 4.2;
const FIXED_STEP = 1 / 90;
function resetBoundObject() {
positions.set(basePositions);
velocities.fill(0);
for (let i = 0; i < COUNT; i++) {
const p = i * 3;
velocities[p] =
0.12 * Math.sin(i * 1.73 + (i % N) * 0.61);
velocities[p + 1] =
0.12 * Math.sin(i * 2.11 + Math.floor(i / N) * 0.47);
velocities[p + 2] =
0.12 * Math.sin(i * 1.37 + Math.floor(i / (N * N)) * 0.53);
}
meanVelocity = [0, 0, 0];
for (let i = 0; i < COUNT; i++) {
const p = i * 3;
meanVelocity[0] += velocities[p];
meanVelocity[1] += velocities[p + 1];
meanVelocity[2] += velocities[p + 2];
}
for (let axis = 0; axis < 3; axis++) {
meanVelocity[axis] /= COUNT;
}
for (let i = 0; i < COUNT; i++) {
const p = i * 3;
velocities[p] -= meanVelocity[0];
velocities[p + 1] -= meanVelocity[1];
velocities[p + 2] -= meanVelocity[2];
}
}
function simulateBoundObject(dt) {
forces.fill(0);
for (const [a, b] of bonds) {
const ap = a * 3;
const bp = b * 3;
const dx = positions[bp] - positions[ap];
const dy = positions[bp + 1] - positions[ap + 1];
const dz = positions[bp + 2] - positions[ap + 2];
const distance = Math.max(
1e-6,
Math.sqrt(dx * dx + dy * dy + dz * dz)
);
const ux = dx / distance;
const uy = dy / distance;
const uz = dz / distance;
const relativeSpeed =
(velocities[bp] - velocities[ap]) * ux +
(velocities[bp + 1] - velocities[ap + 1]) * uy +
(velocities[bp + 2] - velocities[ap + 2]) * uz;
const force =
SPRING_STIFFNESS * (distance - REST_LENGTH) +
SPRING_DAMPING * relativeSpeed;
forces[ap] += force * ux;
forces[ap + 1] += force * uy;
forces[ap + 2] += force * uz;
forces[bp] -= force * ux;
forces[bp + 1] -= force * uy;
forces[bp + 2] -= force * uz;
}
const globalDamping = Math.exp(-0.72 * dt);
for (let i = 0; i < COUNT; i++) {
const p = i * 3;
velocities[p] =
(velocities[p] + forces[p] * dt) * globalDamping;
velocities[p + 1] =
(velocities[p + 1] + forces[p + 1] * dt) * globalDamping;
velocities[p + 2] =
(velocities[p + 2] + forces[p + 2] * dt) * globalDamping;
// Safety clamp keeps the educational simulation stable.
velocities[p] = THREE.MathUtils.clamp(velocities[p], -1.4, 1.4);
velocities[p + 1] = THREE.MathUtils.clamp(velocities[p + 1], -1.4, 1.4);
velocities[p + 2] = THREE.MathUtils.clamp(velocities[p + 2], -1.4, 1.4);
positions[p] += velocities[p] * dt;
positions[p + 1] += velocities[p + 1] * dt;
positions[p + 2] += velocities[p + 2] * dt;
}
// Keep the toy object's center of mass at its exhibit position.
const center = [0, 0, 0];
const centerVelocity = [0, 0, 0];
for (let i = 0; i < COUNT; i++) {
const p = i * 3;
center[0] += positions[p];
center[1] += positions[p + 1];
center[2] += positions[p + 2];
centerVelocity[0] += velocities[p];
centerVelocity[1] += velocities[p + 1];
centerVelocity[2] += velocities[p + 2];
}
for (let axis = 0; axis < 3; axis++) {
center[axis] /= COUNT;
centerVelocity[axis] /= COUNT;
}
for (let i = 0; i < COUNT; i++) {
const p = i * 3;
positions[p] -= center[0];
positions[p + 1] -= center[1];
positions[p + 2] -= center[2];
velocities[p] -= centerVelocity[0];
velocities[p + 1] -= centerVelocity[1];
velocities[p + 2] -= centerVelocity[2];
}
}
function smoothStep(t) {
return t * t * (3 - 2 * t);
}
function updateGrid(progress) {
const eased = smoothStep(progress);
const dilation = 1 + (MAX_DILATION - 1) * eased;
const spacing = REST_LENGTH * dilation;
for (let i = 0; i < COUNT; i++) {
const p = i * 3;
dummy.position.set(
basePositions[p] * dilation,
basePositions[p + 1] * dilation,
basePositions[p + 2] * dilation
);
dummy.rotation.set(0, 0, 0);
dummy.scale.set(1, 1, 1);
dummy.updateMatrix();
gridMesh.setMatrixAt(i, dummy.matrix);
}
gridMesh.instanceMatrix.needsUpdate = true;
const extent = (N - 1) * spacing;
cage.scale.set(
extent + VOXEL_SIZE,
extent + VOXEL_SIZE,
extent + VOXEL_SIZE
);
const a = measuredA * 3;
const b = measuredB * 3;
const ax = basePositions[a] * dilation;
const ay = basePositions[a + 1] * dilation;
const az = basePositions[a + 2] * dilation;
const bx = basePositions[b] * dilation;
const by = basePositions[b + 1] * dilation;
const bz = basePositions[b + 2] * dilation;
const m = measurementGeometry.attributes.position.array;
const tick = 0.075;
// Main measured segment.
m[0] = ax;
m[1] = ay;
m[2] = az;
m[3] = bx;
m[4] = by;
m[5] = bz;
// End ticks.
m[6] = ax;
m[7] = ay - tick;
m[8] = az;
m[9] = ax;
m[10] = ay + tick;
m[11] = az;
m[12] = bx;
m[13] = by - tick;
m[14] = bz;
m[15] = bx;
m[16] = by + tick;
m[17] = bz;
measurementGeometry.attributes.position.needsUpdate = true;
gridSpacingOutput.textContent = spacing.toFixed(2);
gridRatioOutput.textContent = `${dilation.toFixed(2)}×`;
}
function updateBoundObject(simulationTime) {
for (let i = 0; i < COUNT; i++) {
const p = i * 3;
dummy.position.set(
positions[p],
positions[p + 1],
positions[p + 2]
);
dummy.rotation.set(0, 0, 0);
dummy.scale.set(1, 1, 1);
dummy.updateMatrix();
boundMesh.setMatrixAt(i, dummy.matrix);
}
boundMesh.instanceMatrix.needsUpdate = true;
let lengthSum = 0;
let maximumStrain = 0;
let bondIndex = 0;
for (const [a, b] of bonds) {
const ap = a * 3;
const bp = b * 3;
const dx = positions[bp] - positions[ap];
const dy = positions[bp + 1] - positions[ap + 1];
const dz = positions[bp + 2] - positions[ap + 2];
const length = Math.sqrt(dx * dx + dy * dy + dz * dz);
lengthSum += length;
maximumStrain = Math.max(
maximumStrain,
Math.abs(length - REST_LENGTH) / REST_LENGTH
);
bondPositions[bondIndex++] = positions[ap];
bondPositions[bondIndex++] = positions[ap + 1];
bondPositions[bondIndex++] = positions[ap + 2];
bondPositions[bondIndex++] = positions[bp];
bondPositions[bondIndex++] = positions[bp + 1];
bondPositions[bondIndex++] = positions[bp + 2];
}
bondGeometry.attributes.position.needsUpdate = true;
const meanLength = lengthSum / bonds.length;
bondLengthOutput.textContent = meanLength.toFixed(2);
bondStrainOutput.textContent = `${(maximumStrain * 100).toFixed(1)}%`;
// A modest global translation emphasizes that this whole cluster can
// move while only its internal neighboring pairs are constrained.
boundGroup.position.set(
RIGHT_X + Math.sin(simulationTime * 0.42) * 0.1,
-0.08 + Math.sin(simulationTime * 0.31) * 0.08,
0
);
boundGroup.rotation.set(
Math.sin(simulationTime * 0.23) * 0.025,
simulationTime * 0.1,
Math.sin(simulationTime * 0.19) * 0.018
);
}
// ---------------------------------------------------------------------
// Direct camera controls: no addons or examples modules are used.
// ---------------------------------------------------------------------
const cameraTarget = new THREE.Vector3(0, -0.2, 0);
let cameraYaw = 0;
let cameraPitch = 0.29;
let cameraRadius = 20;
let fittedRadius = 20;
function updateCamera() {
const horizontal = cameraRadius * Math.cos(cameraPitch);
camera.position.set(
cameraTarget.x + Math.sin(cameraYaw) * horizontal,
cameraTarget.y + Math.sin(cameraPitch) * cameraRadius,
cameraTarget.z + Math.cos(cameraYaw) * horizontal
);
camera.lookAt(cameraTarget);
camera.updateMatrixWorld();
}
function resetCamera() {
cameraYaw = 0;
cameraPitch = 0.29;
cameraRadius = fittedRadius;
cameraTarget.set(0, -0.2, 0);
updateCamera();
}
const pointers = new Map();
let pinchDistance = 0;
function getPinchDistance() {
const values = [...pointers.values()];
if (values.length < 2) return 0;
return Math.hypot(
values[0].x - values[1].x,
values[0].y - values[1].y
);
}
renderer.domElement.addEventListener("pointerdown", (event) => {
renderer.domElement.setPointerCapture(event.pointerId);
pointers.set(event.pointerId, { x: event.clientX, y: event.clientY });
if (pointers.size === 2) {
pinchDistance = getPinchDistance();
}
});
renderer.domElement.addEventListener("pointermove", (event) => {
const previous = pointers.get(event.pointerId);
if (!previous) return;
const dx = event.clientX - previous.x;
const dy = event.clientY - previous.y;
previous.x = event.clientX;
previous.y = event.clientY;
if (pointers.size >= 2) {
const distance = getPinchDistance();
if (distance > 0 && pinchDistance > 0) {
cameraRadius = THREE.MathUtils.clamp(
cameraRadius * (pinchDistance / distance),
10,
42
);
}
pinchDistance = distance;
return;
}
if (event.shiftKey || (event.buttons & 2)) {
const right = new THREE.Vector3().setFromMatrixColumn(
camera.matrix,
0
);
const up = new THREE.Vector3().setFromMatrixColumn(
camera.matrix,
1
);
cameraTarget
.addScaledVector(right, -dx * cameraRadius * 0.0014)
.addScaledVector(up, dy * cameraRadius * 0.0014);
} else {
cameraYaw -= dx * 0.005;
cameraPitch = THREE.MathUtils.clamp(
cameraPitch + dy * 0.004,
0.04,
1.08
);
}
});
function releasePointer(event) {
pointers.delete(event.pointerId);
pinchDistance = pointers.size >= 2 ? getPinchDistance() : 0;
}
renderer.domElement.addEventListener("pointerup", releasePointer);
renderer.domElement.addEventListener("pointercancel", releasePointer);
renderer.domElement.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraRadius = THREE.MathUtils.clamp(
cameraRadius * Math.exp(event.deltaY * 0.001),
10,
42
);
},
{ passive: false }
);
// ---------------------------------------------------------------------
// State and interface.
// ---------------------------------------------------------------------
const reducedMotion = window.matchMedia(
"(prefers-reduced-motion: reduce)"
).matches;
let playing = !reducedMotion;
let progress = Number(timeline.value) / 100;
let simulationTime = 0;
let physicsAccumulator = 0;
let lastTime = performance.now();
let lastMetricUpdate = 0;
function updatePlayButton() {
playButton.textContent = playing
? "Pause"
: progress >= 0.999
? "Replay"
: "Play";
}
playButton.addEventListener("click", () => {
if (!playing && progress >= 0.999) {
progress = 0;
timeline.value = 0;
resetBoundObject();
simulationTime = 0;
}
playing = !playing;
updatePlayButton();
});
resetButton.addEventListener("click", () => {
progress = 0;
timeline.value = 0;
simulationTime = 0;
physicsAccumulator = 0;
resetBoundObject();
playing = !reducedMotion;
updatePlayButton();
});
cameraButton.addEventListener("click", resetCamera);
timeline.addEventListener("input", () => {
progress = Number(timeline.value) / 100;
playing = false;
updatePlayButton();
});
showBonds.addEventListener("change", () => {
bondLines.visible = showBonds.checked;
});
window.addEventListener("keydown", (event) => {
if (
event.target instanceof HTMLInputElement ||
event.target instanceof HTMLSelectElement ||
event.target instanceof HTMLButtonElement
) {
return;
}
if (event.code === "Space") {
event.preventDefault();
playButton.click();
}
if (event.key.toLowerCase() === "r") {
resetButton.click();
}
});
function resize() {
const width = Math.max(1, stage.clientWidth);
const height = Math.max(1, stage.clientHeight);
const aspect = width / height;
renderer.setSize(width, height, false);
camera.aspect = aspect;
camera.updateProjectionMatrix();
fittedRadius = THREE.MathUtils.clamp(
18.8 * Math.max(1, 1.12 / aspect),
18.8,
35
);
if (Math.abs(cameraRadius - fittedRadius) < 0.001) {
cameraRadius = fittedRadius;
}
}
new ResizeObserver(resize).observe(stage);
resize();
resetCamera();
updatePlayButton();
renderer.setAnimationLoop((now) => {
const delta = Math.min(0.05, Math.max(0, (now - lastTime) / 1000));
lastTime = now;
if (playing) {
const speed = Number(speedSelect.value);
progress = Math.min(1, progress + delta * 0.045 * speed);
timeline.value = String(progress * 100);
stageOutput.textContent = `${Math.round(progress * 100)}%`;
if (progress >= 1 && playButton.textContent === "Pause") {
playButton.textContent = "Replay";
}
simulationTime += delta;
physicsAccumulator += delta;
while (physicsAccumulator >= FIXED_STEP) {
simulateBoundObject(FIXED_STEP);
physicsAccumulator -= FIXED_STEP;
}
} else {
stageOutput.textContent = `${Math.round(progress * 100)}%`;
}
updateGrid(progress);
updateBoundObject(simulationTime);
updateCamera();
if (now - lastMetricUpdate > 90) {
lastMetricUpdate = now;
stageOutput.textContent = `${Math.round(progress * 100)}%`;
}
renderer.render(scene, camera);
});
</script>
</body>
</html>
```