Prompt specification
Build or customize the Three.js 3D scene "Crystal growth rule playground" 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: Crystal growth rule playground
Category: Science & Physics · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/crystal-growth-rule-playground-x1948
Scene Description Prompt:
Make a low-poly Three.js scene in a self-contained HTML file using cdnjs: crystal growth rule playground. Use a small explicitly defined lattice-attachment toy model with adjustable attachment probability; display resulting shapes and avoid presenting them as quantitative predictions for real crystallization.
Working Three.js Starter (crystal-growth-rule-playground-x1948):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Crystal Growth Rule Playground</title>
<style>
:root {
color-scheme: dark;
--bg: #071018;
--panel: rgba(12, 25, 36, 0.82);
--panel-strong: rgba(12, 25, 36, 0.94);
--line: rgba(155, 207, 226, 0.16);
--text: #eef8fb;
--muted: #91a9b4;
--cyan: #69d8e9;
--violet: #a88cff;
--gold: #ffd166;
--danger: #ff8e83;
}
* {
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;
}
body::after {
content: "";
position: fixed;
inset: 0;
z-index: 2;
pointer-events: none;
background:
radial-gradient(circle at 50% 43%, transparent 25%, rgba(2, 8, 13, 0.18) 72%),
linear-gradient(180deg, rgba(4, 11, 17, 0.05), rgba(4, 11, 17, 0.28));
}
#stage {
position: fixed;
inset: 0;
display: block;
width: 100%;
height: 100%;
touch-action: none;
outline: none;
}
.brand {
position: fixed;
z-index: 4;
top: 18px;
left: 20px;
display: flex;
align-items: center;
gap: 12px;
pointer-events: none;
}
.brand-mark {
display: grid;
width: 42px;
height: 42px;
place-items: center;
border: 1px solid rgba(105, 216, 233, 0.35);
border-radius: 12px;
color: var(--cyan);
background: rgba(10, 29, 40, 0.64);
box-shadow: 0 0 28px rgba(105, 216, 233, 0.09);
font-size: 24px;
}
.brand span,
.brand strong {
display: block;
}
.brand span {
color: var(--cyan);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.2em;
}
.brand strong {
margin-top: 3px;
font-size: 17px;
font-weight: 650;
letter-spacing: -0.015em;
}
.disclaimer-badge {
position: fixed;
z-index: 4;
top: 21px;
right: 20px;
padding: 9px 13px;
border: 1px solid rgba(255, 209, 102, 0.3);
border-radius: 999px;
color: #ffe3a3;
background: rgba(45, 35, 15, 0.62);
backdrop-filter: blur(12px);
font-size: 11px;
font-weight: 750;
letter-spacing: 0.04em;
pointer-events: none;
}
.panel {
position: fixed;
z-index: 5;
border: 1px solid var(--line);
border-radius: 18px;
background: var(--panel);
box-shadow:
0 24px 70px rgba(0, 0, 0, 0.28),
inset 0 1px rgba(255, 255, 255, 0.025);
backdrop-filter: blur(18px) saturate(120%);
}
.controls {
top: 88px;
left: 20px;
width: 318px;
max-height: calc(100vh - 112px);
overflow: auto;
padding: 18px;
scrollbar-width: thin;
scrollbar-color: rgba(105, 216, 233, 0.3) transparent;
}
.section-label {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 15px;
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.status {
display: inline-flex;
align-items: center;
gap: 6px;
color: var(--muted);
letter-spacing: 0.06em;
}
.status::before {
content: "";
width: 6px;
height: 6px;
border-radius: 50%;
background: currentColor;
box-shadow: 0 0 10px currentColor;
}
.status[data-state="growing"] {
color: var(--cyan);
}
.status[data-state="complete"] {
color: var(--gold);
}
.status[data-state="stalled"] {
color: var(--danger);
}
.control-group {
margin-bottom: 17px;
}
.control-heading {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 12px;
margin-bottom: 8px;
}
.control-heading label {
color: #dbe9ed;
font-size: 12px;
font-weight: 650;
}
.control-heading output {
color: var(--cyan);
font-variant-numeric: tabular-nums;
font-size: 12px;
font-weight: 800;
}
.control-heading small {
color: var(--muted);
font-size: 10px;
}
input[type="range"] {
width: 100%;
height: 4px;
margin: 5px 0;
border-radius: 999px;
outline: none;
appearance: none;
background:
linear-gradient(90deg, var(--cyan) var(--fill, 48%), rgba(255, 255, 255, 0.1) var(--fill, 48%));
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
width: 15px;
height: 15px;
border: 2px solid #dffbff;
border-radius: 50%;
appearance: none;
background: #4fc6d8;
box-shadow: 0 0 14px rgba(105, 216, 233, 0.45);
}
input[type="range"]::-moz-range-thumb {
width: 13px;
height: 13px;
border: 2px solid #dffbff;
border-radius: 50%;
background: #4fc6d8;
box-shadow: 0 0 14px rgba(105, 216, 233, 0.45);
}
.range-labels {
display: flex;
justify-content: space-between;
margin-top: 6px;
color: #708793;
font-size: 9px;
}
.presets {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 6px;
margin-top: 10px;
}
.preset {
padding: 8px 4px;
border: 1px solid rgba(157, 202, 217, 0.14);
border-radius: 9px;
color: #a9bec7;
background: rgba(255, 255, 255, 0.035);
font: inherit;
font-size: 10px;
cursor: pointer;
transition: 140ms ease;
}
.preset:hover,
.preset.active {
border-color: rgba(105, 216, 233, 0.42);
color: #e6fbff;
background: rgba(105, 216, 233, 0.1);
}
.preset span {
display: block;
margin-bottom: 2px;
color: var(--cyan);
font-size: 11px;
font-weight: 800;
}
.seed-row {
display: grid;
grid-template-columns: 1fr 38px;
gap: 7px;
}
.seed-row input {
min-width: 0;
width: 100%;
padding: 9px 10px;
border: 1px solid rgba(157, 202, 217, 0.15);
border-radius: 9px;
outline: none;
color: var(--text);
background: rgba(2, 10, 16, 0.42);
font: inherit;
font-size: 12px;
font-variant-numeric: tabular-nums;
}
.seed-row input:focus {
border-color: rgba(105, 216, 233, 0.5);
}
.icon-button {
border: 1px solid rgba(157, 202, 217, 0.15);
border-radius: 9px;
color: #d9edf3;
background: rgba(255, 255, 255, 0.04);
font: inherit;
cursor: pointer;
}
.icon-button:hover {
border-color: rgba(105, 216, 233, 0.38);
background: rgba(105, 216, 233, 0.09);
}
.buttons {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 16px;
}
.button {
min-height: 38px;
padding: 9px 10px;
border: 1px solid rgba(157, 202, 217, 0.16);
border-radius: 10px;
color: #d9edf3;
background: rgba(255, 255, 255, 0.04);
font: inherit;
font-size: 11px;
font-weight: 750;
cursor: pointer;
transition: transform 120ms ease, background 140ms ease, border-color 140ms ease;
}
.button:hover {
transform: translateY(-1px);
border-color: rgba(105, 216, 233, 0.36);
background: rgba(105, 216, 233, 0.08);
}
.button.primary {
border-color: rgba(105, 216, 233, 0.5);
color: #062028;
background: linear-gradient(135deg, #70dceb, #8dc7f5);
box-shadow: 0 8px 24px rgba(73, 190, 214, 0.15);
}
.button.primary:hover {
background: linear-gradient(135deg, #8be6f3, #a8d8ff);
}
.button.wide {
grid-column: 1 / -1;
}
.stats {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 1px;
overflow: hidden;
margin-top: 16px;
border: 1px solid rgba(157, 202, 217, 0.1);
border-radius: 11px;
background: rgba(157, 202, 217, 0.1);
}
.stat {
padding: 10px 11px;
background: rgba(6, 17, 25, 0.86);
}
.stat span,
.stat strong {
display: block;
}
.stat span {
margin-bottom: 3px;
color: #748e9a;
font-size: 9px;
font-weight: 750;
letter-spacing: 0.09em;
text-transform: uppercase;
}
.stat strong {
color: #e5f5f8;
font-size: 16px;
font-variant-numeric: tabular-nums;
}
.model-note {
margin: 14px 0 0;
padding: 10px 11px;
border-left: 2px solid rgba(255, 209, 102, 0.55);
border-radius: 0 8px 8px 0;
color: #a9bbc2;
background: rgba(255, 209, 102, 0.045);
font-size: 10px;
line-height: 1.5;
}
.model-note strong {
color: #ffe2a0;
}
.rules {
top: 88px;
right: 20px;
width: 304px;
padding: 15px 17px;
color: #b5c8cf;
font-size: 11px;
line-height: 1.55;
}
.rules summary {
color: #dceef3;
font-size: 12px;
font-weight: 750;
cursor: pointer;
list-style: none;
}
.rules summary::-webkit-details-marker {
display: none;
}
.rules summary::after {
content: "+";
float: right;
color: var(--cyan);
font-size: 17px;
line-height: 1;
}
.rules[open] summary::after {
content: "−";
}
.rules ol {
margin: 14px 0 12px;
padding-left: 19px;
}
.rules li {
margin-bottom: 8px;
padding-left: 2px;
}
.rules b {
color: #e5f4f7;
}
.formula {
margin: 12px 0;
padding: 10px;
border: 1px solid rgba(105, 216, 233, 0.12);
border-radius: 9px;
color: #a9ebf2;
background: rgba(105, 216, 233, 0.045);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 10px;
text-align: center;
}
.rules .warning {
margin: 0;
padding-top: 12px;
border-top: 1px solid rgba(157, 202, 217, 0.1);
color: #c9b985;
}
.camera-hint {
position: fixed;
z-index: 4;
bottom: 18px;
left: 50%;
padding: 8px 12px;
border: 1px solid rgba(157, 202, 217, 0.12);
border-radius: 999px;
color: #79929d;
background: rgba(5, 14, 21, 0.66);
backdrop-filter: blur(10px);
font-size: 10px;
pointer-events: none;
transform: translateX(-50%);
white-space: nowrap;
}
@media (max-width: 900px) {
.brand {
top: 12px;
left: 12px;
}
.brand-mark {
width: 36px;
height: 36px;
}
.brand strong {
font-size: 14px;
}
.disclaimer-badge {
top: 15px;
right: 12px;
padding: 7px 10px;
font-size: 9px;
}
.controls {
top: 64px;
left: 12px;
width: min(310px, calc(100vw - 24px));
max-height: calc(100vh - 136px);
padding: 15px;
}
.rules {
top: auto;
right: 12px;
bottom: 54px;
left: 12px;
width: auto;
max-height: 45vh;
overflow: auto;
}
.camera-hint {
bottom: 13px;
font-size: 9px;
}
}
@media (max-width: 470px) {
.brand span {
font-size: 8px;
}
.brand strong {
max-width: 190px;
}
.disclaimer-badge {
max-width: 115px;
text-align: center;
}
}
</style>
</head>
<body>
<canvas id="stage" aria-label="Interactive low-poly crystal growth scene"></canvas>
<header class="brand">
<div class="brand-mark" aria-hidden="true">◇</div>
<div>
<span>LATTICE LAB</span>
<strong>Crystal Growth Rule Playground</strong>
</div>
</header>
<div class="disclaimer-badge">Toy model · not predictive</div>
<section class="panel controls" aria-label="Playground controls">
<div class="section-label">
<span>Rule parameters</span>
<span id="status" class="status" data-state="paused">Paused</span>
</div>
<div class="control-group">
<div class="control-heading">
<label for="probability">Attachment probability <small>p</small></label>
<output id="probOut" for="probability">48%</output>
</div>
<input id="probability" type="range" min="0" max="1" step="0.01" value="0.48" />
<div class="range-labels">
<span>0 · no attachments</span>
<span>1 · all eligible</span>
</div>
<div class="presets" aria-label="Comparison presets">
<button class="preset" data-p="0.18"><span>18%</span>open</button>
<button class="preset active" data-p="0.48"><span>48%</span>mixed</button>
<button class="preset" data-p="0.82"><span>82%</span>dense</button>
</div>
</div>
<div class="control-group">
<div class="control-heading">
<label for="budget">Cell budget</label>
<output id="budgetOut" for="budget">90 cells</output>
</div>
<input id="budget" type="range" min="20" max="120" step="1" value="90" />
</div>
<div class="control-group">
<div class="control-heading">
<label for="delay">Round delay</label>
<output id="delayOut" for="delay">550 ms</output>
</div>
<input id="delay" type="range" min="120" max="1200" step="10" value="550" />
</div>
<div class="control-group">
<div class="control-heading">
<label for="seed">Random seed</label>
<small>Same seed + p = same run</small>
</div>
<div class="seed-row">
<input id="seed" type="number" min="0" max="4294967295" step="1" value="1847" />
<button id="shuffle" class="icon-button" title="Choose a new seed" aria-label="Choose a new seed">↻</button>
</div>
</div>
<div class="buttons">
<button id="play" class="button primary">Pause</button>
<button id="step" class="button">Step once</button>
<button id="reset" class="button wide">Reset to seed</button>
</div>
<div class="stats" aria-label="Current toy-model counts">
<div class="stat">
<span>Occupied sites</span>
<strong id="siteCount">1</strong>
</div>
<div class="stat">
<span>Growth rounds</span>
<strong id="roundCount">0</strong>
</div>
<div class="stat">
<span>Frontier sites</span>
<strong id="frontierCount">6</strong>
</div>
<div class="stat">
<span>Axis bonds</span>
<strong id="bondCount">0</strong>
</div>
</div>
<p class="model-note">
<strong>Illustrative rule only.</strong>
These shapes are not quantitative predictions of real crystallization.
The model has no thermodynamics, kinetics, anisotropy, solvent, or nucleation physics.
</p>
</section>
<details id="about" class="panel rules" open>
<summary>How this toy rule works</summary>
<ol>
<li>
Use a <b>simple cubic lattice</b>: integer points
<b>(x, y, z)</b> with each coordinate from −3 through 3.
</li>
<li>
Begin with one occupied <b>seed site</b> at <b>(0, 0, 0)</b>.
</li>
<li>
A <b>frontier site</b> is an empty lattice site that shares one of the
six axis edges with an occupied site.
</li>
<li>
In each round, test every frontier site independently. Each attaches
with probability <b>p</b>; all successful attachments happen simultaneously.
</li>
<li>
Stop at the cell budget, when no frontier remains, or when a round
produces no attachments.
</li>
</ol>
<div class="formula">O ← O ∪ A · A ⊂ F · P(q ∈ A) = p</div>
<p>
Changing <b>p</b> affects subsequent rounds. The preset buttons reset the
same seed, making their outcomes directly comparable.
</p>
<p class="warning">
This is a deliberately small attachment-rule toy. Apparent morphology,
counts, rates, and geometry must not be interpreted as predictions of
laboratory or industrial crystallization.
</p>
</details>
<div class="camera-hint">Drag to orbit · wheel to zoom · double-click to recenter</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// ---------------------------------------------------------------------
// Constants and DOM
// ---------------------------------------------------------------------
const LATTICE_LIMIT = 3;
const SPACING = 0.92;
const MAX_CELLS = 120;
const MAX_BONDS = MAX_CELLS * 3;
const canvas = document.querySelector("#stage");
const probabilityInput = document.querySelector("#probability");
const probabilityOutput = document.querySelector("#probOut");
const budgetInput = document.querySelector("#budget");
const budgetOutput = document.querySelector("#budgetOut");
const delayInput = document.querySelector("#delay");
const delayOutput = document.querySelector("#delayOut");
const seedInput = document.querySelector("#seed");
const playButton = document.querySelector("#play");
const stepButton = document.querySelector("#step");
const resetButton = document.querySelector("#reset");
const shuffleButton = document.querySelector("#shuffle");
const statusElement = document.querySelector("#status");
const siteCountElement = document.querySelector("#siteCount");
const roundCountElement = document.querySelector("#roundCount");
const frontierCountElement = document.querySelector("#frontierCount");
const bondCountElement = document.querySelector("#bondCount");
const aboutPanel = document.querySelector("#about");
if (window.matchMedia("(max-width: 900px)").matches) {
aboutPanel.open = false;
}
// ---------------------------------------------------------------------
// Renderer, scene, camera, and lights
// ---------------------------------------------------------------------
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight, false);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x071018);
scene.fog = new THREE.FogExp2(0x071018, 0.035);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
100
);
const cameraTarget = new THREE.Vector3(0, 0.05, 0);
let cameraTheta = 0.72;
let cameraPhi = 1.08;
let cameraRadius = 10.2;
function updateCamera() {
const sinPhi = Math.sin(cameraPhi);
camera.position.set(
cameraTarget.x + cameraRadius * sinPhi * Math.sin(cameraTheta),
cameraTarget.y + cameraRadius * Math.cos(cameraPhi),
cameraTarget.z + cameraRadius * sinPhi * Math.cos(cameraTheta)
);
camera.lookAt(cameraTarget);
}
updateCamera();
const hemisphere = new THREE.HemisphereLight(0xa9eaff, 0x10131d, 1.5);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xffe8c5, 3.1);
keyLight.position.set(5, 8, 6);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(1024, 1024);
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 25;
keyLight.shadow.camera.left = -6;
keyLight.shadow.camera.right = 6;
keyLight.shadow.camera.top = 6;
keyLight.shadow.camera.bottom = -6;
scene.add(keyLight);
const cyanLight = new THREE.PointLight(0x45cbe8, 15, 16, 2);
cyanLight.position.set(-4, 2.5, 3);
scene.add(cyanLight);
const violetLight = new THREE.PointLight(0x8f74ff, 12, 15, 2);
violetLight.position.set(4, -1, -3);
scene.add(violetLight);
// ---------------------------------------------------------------------
// Environment: floor, grid, lattice point cloud, cage, and dust
// ---------------------------------------------------------------------
const floor = new THREE.Mesh(
new THREE.CircleGeometry(5.5, 64),
new THREE.MeshStandardMaterial({
color: 0x0b1720,
roughness: 0.92,
metalness: 0.04
})
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -3.32;
floor.receiveShadow = true;
scene.add(floor);
const grid = new THREE.GridHelper(10, 20, 0x315c6b, 0x18313d);
grid.position.y = -3.30;
grid.material.transparent = true;
grid.material.opacity = 0.42;
scene.add(grid);
for (const radius of [2.2, 3.6, 5.0]) {
const ring = new THREE.Mesh(
new THREE.RingGeometry(radius - 0.012, radius + 0.012, 96),
new THREE.MeshBasicMaterial({
color: 0x4c8fa2,
transparent: true,
opacity: 0.17,
side: THREE.DoubleSide,
depthWrite: false
})
);
ring.rotation.x = -Math.PI / 2;
ring.position.y = -3.29;
scene.add(ring);
}
const latticePositions = [];
for (let x = -LATTICE_LIMIT; x <= LATTICE_LIMIT; x++) {
for (let y = -LATTICE_LIMIT; y <= LATTICE_LIMIT; y++) {
for (let z = -LATTICE_LIMIT; z <= LATTICE_LIMIT; z++) {
latticePositions.push(x * SPACING, y * SPACING, z * SPACING);
}
}
}
const latticeGeometry = new THREE.BufferGeometry();
latticeGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(latticePositions, 3)
);
const latticePoints = new THREE.Points(
latticeGeometry,
new THREE.PointsMaterial({
color: 0x82b4c5,
size: 0.035,
transparent: true,
opacity: 0.17,
depthWrite: false,
sizeAttenuation: true
})
);
scene.add(latticePoints);
const cageSize = (LATTICE_LIMIT * 2 + 1) * SPACING + 0.52;
const cageBox = new THREE.BoxGeometry(cageSize, cageSize, cageSize);
const cageEdges = new THREE.EdgesGeometry(cageBox);
cageBox.dispose();
const cage = new THREE.LineSegments(
cageEdges,
new THREE.LineDashedMaterial({
color: 0x6d9eaf,
transparent: true,
opacity: 0.13,
dashSize: 0.12,
gapSize: 0.10
})
);
cage.computeLineDistances();
scene.add(cage);
const dustPositions = new Float32Array(150 * 3);
for (let i = 0; i < 150; i++) {
const radius = 7 + Math.random() * 9;
const theta = Math.random() * Math.PI * 2;
const vertical = Math.random() * 2 - 1;
const radial = Math.sqrt(1 - vertical * vertical);
dustPositions[i * 3] = Math.cos(theta) * radial * radius;
dustPositions[i * 3 + 1] = vertical * radius * 0.65;
dustPositions[i * 3 + 2] = Math.sin(theta) * radial * radius;
}
const dustGeometry = new THREE.BufferGeometry();
dustGeometry.setAttribute(
"position",
new THREE.BufferAttribute(dustPositions, 3)
);
const dust = new THREE.Points(
dustGeometry,
new THREE.PointsMaterial({
color: 0x7fb7c7,
size: 0.035,
transparent: true,
opacity: 0.28,
depthWrite: false
})
);
scene.add(dust);
// ---------------------------------------------------------------------
// Cluster rendering: one faceted marker per occupied lattice site
// ---------------------------------------------------------------------
const markerGeometry = new THREE.OctahedronGeometry(0.34, 0);
const markerMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.28,
metalness: 0.23,
flatShading: true,
emissive: 0x07141d,
emissiveIntensity: 0.32
});
const markerMesh = new THREE.InstancedMesh(
markerGeometry,
markerMaterial,
MAX_CELLS
);
markerMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
markerMesh.castShadow = true;
markerMesh.receiveShadow = true;
markerMesh.frustumCulled = false;
scene.add(markerMesh);
const bondGeometry = new THREE.CylinderGeometry(0.024, 0.024, 1, 6, 1);
const bondMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.55,
metalness: 0.12,
emissive: 0x0b202b,
emissiveIntensity: 0.38
});
const bondMesh = new THREE.InstancedMesh(
bondGeometry,
bondMaterial,
MAX_BONDS
);
bondMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
bondMesh.frustumCulled = false;
scene.add(bondMesh);
const dummy = new THREE.Object3D();
const yAxis = new THREE.Vector3(0, 1, 0);
const bondDirection = new THREE.Vector3();
// ---------------------------------------------------------------------
// Explicit toy model
//
// L = {(x,y,z) : x,y,z are integers in [-3,3]}
// O = occupied sites, initially {(0,0,0)}
// F = vacant sites axis-adjacent to at least one site in O
// In each round, every q in F independently attaches with probability p.
// All attachments are applied simultaneously.
// ---------------------------------------------------------------------
const DIRECTIONS = [
[1, 0, 0],
[-1, 0, 0],
[0, 1, 0],
[0, -1, 0],
[0, 0, 1],
[0, 0, -1]
];
const POSITIVE_DIRECTIONS = [
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]
];
let cells = [];
let occupied = new Set();
let modelRandom = Math.random;
let probability = Number(probabilityInput.value);
let budget = Number(budgetInput.value);
let delay = Number(delayInput.value);
let round = 0;
let running = false;
let status = "paused";
let nextRoundAt = 0;
let bondCount = 0;
function siteKey(x, y, z) {
return `${x},${y},${z}`;
}
function isInsideLattice(x, y, z) {
return (
x >= -LATTICE_LIMIT &&
x <= LATTICE_LIMIT &&
y >= -LATTICE_LIMIT &&
y <= LATTICE_LIMIT &&
z >= -LATTICE_LIMIT &&
z <= LATTICE_LIMIT
);
}
function mulberry32(seed) {
let state = seed >>> 0;
return function () {
state += 0x6d2b79f5;
let value = state;
value = Math.imul(value ^ (value >>> 15), value | 1);
value ^= value + Math.imul(value ^ (value >>> 7), value | 61);
return ((value ^ (value >>> 14)) >>> 0) / 4294967296;
};
}
function getFrontier() {
const frontier = new Set();
for (const cell of cells) {
for (const [dx, dy, dz] of DIRECTIONS) {
const x = cell.x + dx;
const y = cell.y + dy;
const z = cell.z + dz;
const key = siteKey(x, y, z);
if (
isInsideLattice(x, y, z) &&
!occupied.has(key)
) {
frontier.add(key);
}
}
}
return frontier;
}
function getCellColor(cell) {
if (cell.round === 0) {
return new THREE.Color(0xffd166);
}
const vertical = (cell.y + LATTICE_LIMIT) / (LATTICE_LIMIT * 2);
const depth = (cell.z + LATTICE_LIMIT) / (LATTICE_LIMIT * 2);
const hue = (0.51 + vertical * 0.23 + depth * 0.045) % 1;
return new THREE.Color().setHSL(hue, 0.73, 0.58);
}
function rebuildVisuals() {
markerMesh.count = cells.length;
for (let i = 0; i < cells.length; i++) {
const cell = cells[i];
dummy.position.set(
cell.x * SPACING,
cell.y * SPACING,
cell.z * SPACING
);
dummy.quaternion.identity();
dummy.scale.setScalar(1);
dummy.updateMatrix();
markerMesh.setMatrixAt(i, dummy.matrix);
markerMesh.setColorAt(i, cell.color);
}
markerMesh.instanceMatrix.needsUpdate = true;
if (markerMesh.instanceColor) {
markerMesh.instanceColor.needsUpdate = true;
}
bondMesh.count = 0;
bondCount = 0;
for (const cell of cells) {
for (const [dx, dy, dz] of POSITIVE_DIRECTIONS) {
const neighborX = cell.x + dx;
const neighborY = cell.y + dy;
const neighborZ = cell.z + dz;
if (!occupied.has(siteKey(neighborX, neighborY, neighborZ))) {
continue;
}
dummy.position.set(
(cell.x + neighborX) * 0.5 * SPACING,
(cell.y + neighborY) * 0.5 * SPACING,
(cell.z + neighborZ) * 0.5 * SPACING
);
bondDirection
.set(
neighborX - cell.x,
neighborY - cell.y,
neighborZ - cell.z
)
.normalize();
dummy.quaternion.setFromUnitVectors(yAxis, bondDirection);
dummy.scale.set(1, SPACING, 1);
dummy.updateMatrix();
bondMesh.setMatrixAt(bondMesh.count, dummy.matrix);
const bondColor = cell.color.clone().lerp(
new THREE.Color(0x8edfff),
0.28
);
bondMesh.setColorAt(bondMesh.count, bondColor);
bondMesh.count++;
bondCount++;
}
}
bondMesh.instanceMatrix.needsUpdate = true;
if (bondMesh.instanceColor) {
bondMesh.instanceColor.needsUpdate = true;
}
refreshStatistics();
}
function refreshStatistics() {
siteCountElement.textContent = cells.length.toString();
roundCountElement.textContent = round.toString();
frontierCountElement.textContent = getFrontier().size.toString();
bondCountElement.textContent = bondCount.toString();
}
function refreshStatus() {
const labels = {
growing: "Growing",
paused: "Paused",
complete: "Budget reached",
stalled: "No attachments"
};
statusElement.textContent = labels[status];
statusElement.dataset.state = status;
const terminal = status === "complete" || status === "stalled";
playButton.textContent = running
? "Pause"
: terminal
? "Run again"
: "Start";
stepButton.disabled = terminal;
}
function advanceRound() {
if (cells.length >= budget) {
running = false;
status = "complete";
refreshStatus();
return;
}
const candidates = Array.from(getFrontier());
if (candidates.length === 0) {
running = false;
status = "stalled";
refreshStatus();
return;
}
const additions = [];
// Every frontier site receives an independent Bernoulli trial.
for (const key of candidates) {
if (modelRandom() < probability) {
additions.push(key);
}
}
if (additions.length === 0) {
running = false;
status = "stalled";
refreshStatus();
return;
}
const remaining = budget - cells.length;
// If the cell budget is reached during a round, retain a random subset.
if (additions.length > remaining) {
for (let i = additions.length - 1; i > 0; i--) {
const j = Math.floor(modelRandom() * (i + 1));
[additions[i], additions[j]] = [addions[j], additions[i]];
}
additions.length = remaining;
}
const revealAt = performance.now();
// Simultaneous application: every addition uses the pre-round frontier.
for (const key of additions) {
const [x, y, z] = key.split(",").map(Number);
const cell = {
x,
y,
z,
round: round + 1,
revealAt
};
cell.color = getCellColor(cell);
cells.push(cell);
occupied.add(key);
}
round++;
if (cells.length >= budget) {
running = false;
status = "complete";
}
rebuildVisuals();
refreshStatus();
}
function resetModel(startRunning = false) {
const parsedSeed = Number.parseInt(seedInput.value, 10);
const safeSeed = Number.isFinite(parsedSeed)
? parsedSeed >>> 0
: 1847;
modelRandom = mulberry32(safeSeed);
cells = [];
occupied = new Set();
round = 0;
bondCount = 0;
const seedCell = {
x: 0,
y: 0,
z: 0,
round: 0,
revealAt: performance.now()
};
seedCell.color = getCellColor(seedCell);
cells.push(seedCell);
occupied.add(siteKey(0, 0, 0));
running = startRunning;
status = startRunning ? "growing" : "paused";
nextRoundAt = performance.now() + delay;
rebuildVisuals();
refreshStatus();
}
// ---------------------------------------------------------------------
// UI events
// ---------------------------------------------------------------------
function updateRangeFill(input) {
const minimum = Number(input.min);
const maximum = Number(input.max);
const value = Number(input.value);
const percent = ((value - minimum) / (maximum - minimum)) * 100;
input.style.setProperty("--fill", `${percent}%`);
}
function syncProbability(value) {
probability = Number(value);
probabilityInput.value = probability.toString();
probabilityOutput.textContent = `${Math.round(probability * 100)}%`;
updateRangeFill(probabilityInput);
document.querySelectorAll(".preset").forEach((button) => {
button.classList.toggle(
"active",
Math.abs(Number(button.dataset.p) - probability) < 0.001
);
});
// A failed zero-probability round can be resumed with a larger p.
if (status === "stalled" && probability > 0) {
status = "paused";
refreshStatus();
}
}
probabilityInput.addEventListener("input", () => {
syncProbability(probabilityInput.value);
});
budgetInput.addEventListener("input", () => {
budget = Number(budgetInput.value);
budgetOutput.textContent = `${budget} cells`;
updateRangeFill(budgetInput);
if (status === "complete" && cells.length < budget) {
status = "paused";
refreshStatus();
}
});
delayInput.addEventListener("input", () => {
delay = Number(delayInput.value);
delayOutput.textContent = `${delay} ms`;
updateRangeFill(delayInput);
nextRoundAt = performance.now() + delay;
});
document.querySelectorAll(".preset").forEach((button) => {
button.addEventListener("click", () => {
syncProbability(button.dataset.p);
resetModel(true);
});
});
playButton.addEventListener("click", () => {
if (running) {
running = false;
status = "paused";
} else if (status === "complete" || status === "stalled") {
resetModel(true);
} else {
running = true;
status = "growing";
nextRoundAt = performance.now() + delay;
}
refreshStatus();
});
stepButton.addEventListener("click", () => {
running = false;
advanceRound();
});
resetButton.addEventListener("click", () => {
resetModel(false);
});
seedInput.addEventListener("change", () => {
resetModel(false);
});
shuffleButton.addEventListener("click", () => {
const current = Number.parseInt(seedInput.value, 10) >>> 0;
const next = (Math.imul(current, 1664525) + 1013904223) >>> 0;
seedInput.value = next.toString();
resetModel(true);
});
// ---------------------------------------------------------------------
// Direct camera controls: no examples/addons are imported
// ---------------------------------------------------------------------
let dragging = false;
let previousX = 0;
let previousY = 0;
let activePointerId = null;
canvas.addEventListener("pointerdown", (event) => {
if (event.button !== 0) return;
dragging = true;
activePointerId = event.pointerId;
previousX = event.clientX;
previousY = event.clientY;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (!dragging || event.pointerId !== activePointerId) return;
const deltaX = event.clientX - previousX;
const deltaY = event.clientY - previousY;
previousX = event.clientX;
previousY = event.clientY;
cameraTheta -= deltaX * 0.006;
cameraPhi = THREE.MathUtils.clamp(
cameraPhi - deltaY * 0.005,
0.22,
Math.PI - 0.22
);
});
function endDrag(event) {
if (event.pointerId !== activePointerId) return;
dragging = false;
activePointerId = null;
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
}
canvas.addEventListener("pointerup", endDrag);
canvas.addEventListener("pointercancel", endDrag);
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraRadius = THREE.MathUtils.clamp(
cameraRadius * Math.exp(event.deltaY * 0.001),
6.1,
20
);
},
{ passive: false }
);
canvas.addEventListener("dblclick", () => {
cameraTheta = 0.72;
cameraPhi = 1.08;
cameraRadius = 10.2;
cameraTarget.set(0, 0.05, 0);
});
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight, false);
});
// ---------------------------------------------------------------------
// Animation
// ---------------------------------------------------------------------
function animateMarkers(now) {
markerMesh.count = cells.length;
for (let i = 0; i < cells.length; i++) {
const cell = cells[i];
const progress = THREE.MathUtils.clamp(
(now - cell.revealAt) / 420,
0,
1
);
const eased = 1 - Math.pow(1 - progress, 3);
const scale = 0.12 + eased * 0.88;
dummy.position.set(
cell.x * SPACING,
cell.y * SPACING,
cell.z * SPACING
);
dummy.quaternion.identity();
dummy.scale.setScalar(scale);
dummy.updateMatrix();
markerMesh.setMatrixAt(i, dummy.matrix);
}
markerMesh.instanceMatrix.needsUpdate = true;
}
function animate(now) {
requestAnimationFrame(animate);
if (running && now >= nextRoundAt) {
advanceRound();
nextRoundAt = now + delay;
}
animateMarkers(now);
updateCamera();
dust.rotation.y = now * 0.000018;
dust.rotation.x = Math.sin(now * 0.00007) * 0.08;
renderer.render(scene, camera);
}
syncProbability(probability);
budgetOutput.textContent = `${budget} cells`;
delayOutput.textContent = `${delay} ms`;
updateRangeFill(probabilityInput);
updateRangeFill(budgetInput);
updateRangeFill(delayInput);
resetModel(true);
requestAnimationFrame(animate);
</script>
</body>
</html>
```