Prompt specification
Build or customize the Three.js 3D scene "Cell-grid local-neighborhood model" 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: Cell-grid local-neighborhood model
Category: Algorithms & Systems · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/cell-grid-local-neighborhood-model-x1857
Scene Description Prompt:
Make a standalone HTML scene with Three.js from cdnjs that depicts cellular automata with local update rules. Build a small grid of binary cells with one selected neighborhood highlighted; show how the next state is computed from an explicitly stated local rule. Low-poly.
Working Three.js Starter (cell-grid-local-neighborhood-model-x1857):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Local Rule Lab — Cellular Automata</title>
<style>
:root {
--bg: #071018;
--panel: rgba(10, 20, 29, 0.82);
--line: rgba(164, 210, 224, 0.17);
--text: #e7f4f6;
--muted: #8299a4;
--mint: #59efc0;
--amber: #ffc857;
--coral: #ff6b6b;
--mono: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
--sans: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background:
radial-gradient(circle at 55% 42%, #132c37 0%, #091720 45%, #050c12 100%);
color: var(--text);
font-family: var(--sans);
}
button {
font: inherit;
}
#scene {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
cursor: grab;
}
#scene:active {
cursor: grabbing;
}
.brand {
position: fixed;
top: 24px;
left: 24px;
z-index: 5;
pointer-events: none;
max-width: 330px;
}
.eyebrow {
display: flex;
align-items: center;
gap: 9px;
margin-bottom: 10px;
color: var(--mint);
font: 700 10px/1 var(--mono);
letter-spacing: 0.19em;
text-transform: uppercase;
}
.eyebrow::before {
content: "";
width: 20px;
height: 2px;
background: var(--mint);
box-shadow: 0 0 12px rgba(89, 239, 192, 0.75);
}
h1 {
margin: 0;
font-size: clamp(25px, 3vw, 42px);
line-height: 0.96;
letter-spacing: -0.055em;
font-weight: 780;
text-transform: uppercase;
}
.subtitle {
margin-top: 12px;
color: var(--muted);
font: 11px/1.55 var(--mono);
letter-spacing: 0.035em;
}
.legend {
display: flex;
gap: 15px;
margin-top: 15px;
color: #a9bdc5;
font: 10px/1 var(--mono);
letter-spacing: 0.08em;
text-transform: uppercase;
}
.legend span {
display: inline-flex;
align-items: center;
gap: 7px;
}
.legend i {
width: 8px;
height: 8px;
display: inline-block;
background: var(--mint);
box-shadow: 0 0 10px rgba(89, 239, 192, 0.5);
}
.legend .off {
background: #263b48;
box-shadow: none;
}
.panel {
position: fixed;
z-index: 6;
border: 1px solid var(--line);
background: var(--panel);
box-shadow:
0 20px 60px rgba(0, 0, 0, 0.28),
inset 0 1px 0 rgba(255, 255, 255, 0.035);
backdrop-filter: blur(15px);
-webkit-backdrop-filter: blur(15px);
}
.compute-panel {
top: 24px;
right: 24px;
width: 306px;
padding: 18px;
border-radius: 3px;
}
.panel-kicker {
color: var(--muted);
font: 700 9px/1 var(--mono);
letter-spacing: 0.18em;
text-transform: uppercase;
}
.compute-title {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 14px;
margin-top: 10px;
}
.compute-title h2 {
margin: 0;
font-size: 16px;
line-height: 1.1;
letter-spacing: -0.02em;
text-transform: uppercase;
}
.chip {
flex: 0 0 auto;
padding: 5px 7px;
border: 1px solid rgba(255, 200, 87, 0.26);
color: var(--amber);
background: rgba(255, 200, 87, 0.06);
font: 9px/1 var(--mono);
letter-spacing: 0.08em;
}
.matrix {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 6px;
width: 154px;
margin: 20px auto 16px;
}
.bit {
position: relative;
aspect-ratio: 1;
display: grid;
place-items: center;
border: 1px solid rgba(157, 191, 205, 0.12);
background: rgba(27, 43, 53, 0.62);
color: #718894;
font: 700 18px/1 var(--mono);
transition:
color 180ms ease,
background 180ms ease,
border-color 180ms ease,
transform 180ms ease;
}
.bit.on {
color: var(--mint);
border-color: rgba(89, 239, 192, 0.52);
background: rgba(89, 239, 192, 0.1);
box-shadow: inset 0 0 14px rgba(89, 239, 192, 0.05);
}
.bit.target {
color: var(--coral);
border-color: rgba(255, 107, 107, 0.65);
background: rgba(255, 107, 107, 0.08);
}
.bit.target::after {
content: "TARGET";
position: absolute;
left: 50%;
bottom: -13px;
transform: translateX(-50%);
color: var(--coral);
font: 700 7px/1 var(--mono);
letter-spacing: 0.08em;
}
.bit.off-grid {
opacity: 0.38;
}
.compute-meta {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-bottom: 12px;
}
.meta-cell {
padding: 10px;
border: 1px solid rgba(157, 191, 205, 0.1);
background: rgba(255, 255, 255, 0.018);
}
.meta-cell span {
display: block;
margin-bottom: 5px;
color: var(--muted);
font: 8px/1 var(--mono);
letter-spacing: 0.13em;
text-transform: uppercase;
}
.meta-cell strong {
font: 700 15px/1 var(--mono);
}
.next-row {
display: flex;
align-items: center;
justify-content: space-between;
padding: 12px 0;
border-top: 1px solid var(--line);
border-bottom: 1px solid var(--line);
}
.next-row span {
color: var(--muted);
font: 9px/1 var(--mono);
letter-spacing: 0.15em;
text-transform: uppercase;
}
#nextValue {
width: 42px;
height: 42px;
display: grid;
place-items: center;
border: 1px solid rgba(89, 239, 192, 0.45);
color: var(--mint);
background: rgba(89, 239, 192, 0.08);
font: 700 22px/1 var(--mono);
box-shadow: 0 0 22px rgba(89, 239, 192, 0.08);
}
#paritySentence {
margin-top: 12px;
color: #b6c7cd;
font: 10px/1.5 var(--mono);
}
.rule-panel {
left: 24px;
bottom: 24px;
width: 360px;
padding: 18px;
border-radius: 3px;
}
.rule-name {
margin: 9px 0 8px;
color: var(--amber);
font: 800 18px/1 var(--mono);
letter-spacing: 0.03em;
text-transform: uppercase;
}
.rule-copy {
margin: 0;
color: #9fb1b9;
font-size: 11px;
line-height: 1.55;
}
.equation {
margin-top: 14px;
padding: 11px 12px;
border-left: 2px solid var(--amber);
background: rgba(255, 200, 87, 0.055);
color: #f6d98e;
font: 11px/1.5 var(--mono);
}
.rule-notes {
display: flex;
flex-wrap: wrap;
gap: 7px;
margin-top: 12px;
}
.rule-notes span {
padding: 5px 6px;
border: 1px solid rgba(157, 191, 205, 0.12);
color: var(--muted);
font: 8px/1 var(--mono);
letter-spacing: 0.07em;
text-transform: uppercase;
}
.controls {
position: fixed;
z-index: 8;
left: 50%;
bottom: 24px;
transform: translateX(-50%);
display: flex;
align-items: stretch;
gap: 7px;
padding: 7px;
border: 1px solid var(--line);
background: rgba(8, 17, 24, 0.88);
box-shadow: 0 15px 50px rgba(0, 0, 0, 0.3);
backdrop-filter: blur(14px);
-webkit-backdrop-filter: blur(14px);
}
.controls button {
min-width: 76px;
height: 39px;
padding: 0 13px;
border: 1px solid rgba(157, 191, 205, 0.15);
border-radius: 1px;
background: rgba(255, 255, 255, 0.025);
color: #b9c9cf;
cursor: pointer;
font: 700 9px/1 var(--mono);
letter-spacing: 0.11em;
text-transform: uppercase;
transition:
color 160ms ease,
border-color 160ms ease,
background 160ms ease,
transform 160ms ease;
}
.controls button:hover {
color: #fff;
border-color: rgba(255, 255, 255, 0.32);
background: rgba(255, 255, 255, 0.06);
}
.controls button:active {
transform: translateY(1px);
}
.controls button.primary {
color: #071018;
border-color: var(--mint);
background: var(--mint);
}
.controls button.active {
color: var(--mint);
border-color: rgba(89, 239, 192, 0.55);
background: rgba(89, 239, 192, 0.09);
}
#status {
min-width: 91px;
height: 39px;
display: flex;
align-items: center;
justify-content: center;
gap: 7px;
padding: 0 10px;
color: var(--muted);
font: 8px/1 var(--mono);
letter-spacing: 0.09em;
}
#status::before {
content: "";
width: 6px;
height: 6px;
border-radius: 50%;
background: var(--mint);
box-shadow: 0 0 9px rgba(89, 239, 192, 0.7);
}
#status.busy::before {
background: var(--amber);
box-shadow: 0 0 9px rgba(255, 200, 87, 0.7);
animation: blink 500ms steps(2) infinite;
}
@keyframes blink {
50% { opacity: 0.2; }
}
.world-label {
position: fixed;
z-index: 4;
transform: translate(-50%, -50%);
pointer-events: none;
white-space: nowrap;
padding: 5px 7px;
border: 1px solid rgba(255, 107, 107, 0.38);
color: var(--coral);
background: rgba(9, 18, 25, 0.84);
font: 700 8px/1 var(--mono);
letter-spacing: 0.1em;
text-transform: uppercase;
}
#outputTag {
border-color: rgba(89, 239, 192, 0.4);
color: var(--mint);
}
.camera-hint {
position: fixed;
z-index: 4;
right: 24px;
bottom: 24px;
color: rgba(139, 164, 175, 0.72);
pointer-events: none;
font: 8px/1.5 var(--mono);
letter-spacing: 0.08em;
text-align: right;
text-transform: uppercase;
}
@media (max-width: 1100px) {
.controls {
left: auto;
right: 24px;
transform: none;
}
.camera-hint {
display: none;
}
}
@media (max-width: 760px) {
.brand {
top: 14px;
left: 14px;
}
.brand h1 {
font-size: 23px;
}
.brand .subtitle,
.brand .legend {
display: none;
}
.compute-panel {
top: 14px;
right: 14px;
width: 224px;
padding: 13px;
}
.matrix {
width: 108px;
gap: 4px;
margin: 17px auto 18px;
}
.bit {
font-size: 14px;
}
.compute-meta,
.compute-title .chip {
display: none;
}
.rule-panel {
left: 14px;
bottom: 80px;
width: calc(100% - 28px);
padding: 13px;
}
.rule-copy,
.rule-notes {
display: none;
}
.rule-name {
font-size: 14px;
}
.equation {
margin-top: 10px;
padding: 8px 10px;
font-size: 9px;
}
.controls {
left: 14px;
right: 14px;
bottom: 14px;
justify-content: center;
}
.controls button {
min-width: 0;
flex: 1;
padding: 0 8px;
}
#status {
display: none;
}
}
</style>
</head>
<body>
<header class="brand">
<div class="eyebrow">Automata / Local Computation</div>
<h1>Local<br />Rule Lab</h1>
<div class="subtitle">
Drag to orbit · wheel to zoom<br />
Click any cell to inspect its neighborhood
</div>
<div class="legend">
<span><i></i> Live / 1</span>
<span><i class="off"></i> Dead / 0</span>
</div>
</header>
<section class="panel compute-panel" aria-label="Selected cell computation">
<div class="panel-kicker">Selected neighborhood</div>
<div class="compute-title">
<h2>Moore / Radius 1</h2>
<div class="chip">8 INPUTS</div>
</div>
<div class="matrix" id="neighborhood" aria-label="3 by 3 binary neighborhood"></div>
<div class="compute-meta">
<div class="meta-cell">
<span>Neighbor sum</span>
<strong id="neighborCount">0</strong>
</div>
<div class="meta-cell">
<span>Target now</span>
<strong id="targetState">0</strong>
</div>
</div>
<div class="next-row">
<span>Next state</span>
<strong id="nextValue">0</strong>
<span id="stateLabel">OFF</span>
</div>
<div id="paritySentence">0 live neighbors → even → 0</div>
</section>
<section class="panel rule-panel" aria-label="Explicit update rule">
<div class="panel-kicker">Active local rule</div>
<div class="rule-name">Odd Parity</div>
<p class="rule-copy">
Each live neighbor contributes 1. The target becomes live only when
the sum of its eight neighbors is odd.
</p>
<div class="equation">
next(i) = (n₀ + n₁ + … + n₇) mod 2
</div>
<div class="rule-notes">
<span>Moore neighborhood</span>
<span>Center excluded</span>
<span>Off-grid = 0</span>
<span>Simultaneous update</span>
</div>
</section>
<nav class="controls" aria-label="Simulation controls">
<button id="stepButton" class="primary" type="button">Step</button>
<button id="playButton" type="button">Play</button>
<button id="seedButton" type="button">Reseed</button>
<button id="clearButton" type="button">Clear</button>
<div id="status">READY</div>
</nav>
<div id="selectedTag" class="world-label">Selected cell</div>
<div id="outputTag" class="world-label">Next / 0</div>
<div class="camera-hint">
Drag / orbit<br />
Wheel / zoom<br />
Double-click / reset
</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 GRID = 11;
const CELL_COUNT = GRID * GRID;
const SPACING = 1.05;
const CELL_SIZE = 0.86;
const BOARD_TOP = -0.08;
const OUTPUT_X = 8.15;
const OUTPUT_Z = 0.55;
const ALIVE = new THREE.Color(0x59efc0);
const DEAD = new THREE.Color(0x243746);
const AMBER = 0xffc857;
const CORAL = 0xff6b6b;
const scene = new THREE.Scene();
scene.fog = new THREE.Fog(0x071018, 25, 48);
const camera = new THREE.PerspectiveCamera(
42,
innerWidth / innerHeight,
0.1,
100
);
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true,
powerPreference: "high-performance"
});
renderer.domElement.id = "scene";
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
renderer.setClearColor(0x071018, 0);
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(
0x9dd9ee,
0x071018,
1.8
);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xd9f7ff, 3.2);
keyLight.position.set(-7, 13, 8);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -18;
keyLight.shadow.camera.right = 18;
keyLight.shadow.camera.top = 18;
keyLight.shadow.camera.bottom = -18;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 40;
keyLight.shadow.bias = -0.0008;
scene.add(keyLight);
const mintLight = new THREE.PointLight(0x59efc0, 24, 20, 2);
mintLight.position.set(2, 5, 5);
scene.add(mintLight);
const amberLight = new THREE.PointLight(0xffc857, 18, 16, 2);
amberLight.position.set(-6, 4, -4);
scene.add(amberLight);
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(90, 90),
new THREE.MeshStandardMaterial({
color: 0x07121a,
roughness: 0.96,
metalness: 0.02
})
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -0.56;
floor.receiveShadow = true;
scene.add(floor);
const board = new THREE.Mesh(
new THREE.BoxGeometry(
GRID * SPACING + 1.12,
0.38,
GRID * SPACING + 1.12
),
new THREE.MeshStandardMaterial({
color: 0x101c26,
roughness: 0.78,
metalness: 0.14,
flatShading: true
})
);
board.position.y = -0.33;
board.castShadow = true;
board.receiveShadow = true;
scene.add(board);
// Low-poly grid lines.
const gridPositions = [];
const gridSpan = GRID * SPACING;
const gridMin = -gridSpan / 2;
for (let i = 0; i <= GRID; i++) {
const p = gridMin + i * SPACING;
gridPositions.push(
p, BOARD_TOP + 0.012, gridMin,
p, BOARD_TOP + 0.012, gridMin + gridSpan,
gridMin, BOARD_TOP + 0.012, p,
gridMin + gridSpan, BOARD_TOP + 0.012, p
);
}
const gridGeometry = new THREE.BufferGeometry();
gridGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(gridPositions, 3)
);
const gridLines = new THREE.LineSegments(
gridGeometry,
new THREE.LineBasicMaterial({
color: 0x7ca0ad,
transparent: true,
opacity: 0.18
})
);
scene.add(gridLines);
// ------------------------------------------------------------
// Cellular state
// ------------------------------------------------------------
let cells = new Uint8Array(CELL_COUNT);
let selected = Math.floor(GRID / 2) * GRID + Math.floor(GRID / 2);
let seed = 0xc0ffee;
let playing = false;
let transitioning = false;
let autoTimer = null;
let outputNext = 0;
let outputPulseStart = -Infinity;
const cellGeometry = new THREE.BoxGeometry(1, 1, 1);
const cellMeshes = [];
for (let i = 0; i < CELL_COUNT; i++) {
const material = new THREE.MeshStandardMaterial({
color: DEAD,
emissive: 0x000000,
emissiveIntensity: 0,
roughness: 0.7,
metalness: 0.08,
flatShading: true
});
const mesh = new THREE.Mesh(cellGeometry, material);
mesh.scale.set(CELL_SIZE, 0.18, CELL_SIZE);
mesh.castShadow = true;
mesh.receiveShadow = true;
mesh.userData.index = i;
mesh.userData.pulseStart = -Infinity;
scene.add(mesh);
cellMeshes.push(mesh);
}
function cellPosition(index, y = 0) {
const row = Math.floor(index / GRID);
const col = index % GRID;
return new THREE.Vector3(
(col - (GRID - 1) / 2) * SPACING,
y,
(row - (GRID - 1) / 2) * SPACING
);
}
function validCell(row, col) {
return row >= 0 && row < GRID && col >= 0 && col < GRID;
}
function neighborSum(source, index) {
const row = Math.floor(index / GRID);
const col = index % GRID;
let sum = 0;
for (let dr = -1; dr <= 1; dr++) {
for (let dc = -1; dc <= 1; dc++) {
if (dr === 0 && dc === 0) continue;
const r = row + dr;
const c = col + dc;
if (validCell(r, c)) {
sum += source[r * GRID + c];
}
}
}
return sum;
}
function computeNextAt(source, index) {
return neighborSum(source, index) % 2 === 1 ? 1 : 0;
}
function computeAll(source) {
const result = new Uint8Array(CELL_COUNT);
for (let i = 0; i < CELL_COUNT; i++) {
result[i] = computeNextAt(source, i);
}
return result;
}
function applyImmediate(nextCells) {
const changed = new Set();
const now = performance.now();
for (let i = 0; i < CELL_COUNT; i++) {
if (cells[i] !== nextCells[i]) changed.add(i);
}
cells = nextCells;
for (const i of changed) {
cellMeshes[i].userData.pulseStart = now;
}
outputNext = computeNextAt(cells, selected);
updateComputationUI();
updateSelectionVisuals();
}
function reseed() {
seed = (seed + 0x9e3779b9) >>> 0;
let s = seed;
const next = new Uint8Array(CELL_COUNT);
for (let i = 0; i < CELL_COUNT; i++) {
s = (Math.imul(s, 1664525) + 1013904223) >>> 0;
next[i] = ((s >>> 24) / 255) < 0.43 ? 1 : 0;
}
applyImmediate(next);
}
function clearGrid() {
applyImmediate(new Uint8Array(CELL_COUNT));
}
// ------------------------------------------------------------
// Neighborhood visualization
// ------------------------------------------------------------
const neighborGroup = new THREE.Group();
const arrowGroup = new THREE.Group();
scene.add(neighborGroup, arrowGroup);
const edgeGeometry = new THREE.EdgesGeometry(cellGeometry);
const neighborLineMaterial = new THREE.LineBasicMaterial({
color: AMBER,
transparent: true,
opacity: 0.9
});
const selectedLineMaterial = new THREE.LineBasicMaterial({
color: CORAL,
transparent: true,
opacity: 1
});
const haloGeometry = new THREE.PlaneGeometry(
CELL_SIZE * 1.08,
CELL_SIZE * 1.08
);
const haloMaterial = new THREE.MeshBasicMaterial({
color: AMBER,
transparent: true,
opacity: 0.12,
depthWrite: false,
side: THREE.DoubleSide
});
const beamMaterial = new THREE.LineBasicMaterial({
color: AMBER,
transparent: true,
opacity: 0.28
});
const particleGeometry = new THREE.SphereGeometry(0.065, 6, 4);
const particleMaterial = new THREE.MeshBasicMaterial({
color: 0xffdd80
});
const marker = new THREE.Mesh(
new THREE.OctahedronGeometry(0.13, 0),
new THREE.MeshStandardMaterial({
color: CORAL,
emissive: CORAL,
emissiveIntensity: 0.8,
roughness: 0.5,
flatShading: true
})
);
marker.castShadow = true;
scene.add(marker);
const beamParticles = [];
let arrowCurve = null;
let arrowPulse = null;
function disposeOwnedGeometry(group) {
group.traverse((object) => {
if (object.userData.ownGeometry && object.geometry) {
object.geometry.dispose();
}
});
group.clear();
}
function rebuildNeighborhood() {
disposeOwnedGeometry(neighborGroup);
beamParticles.length = 0;
const row = Math.floor(selected / GRID);
const col = selected % GRID;
const center = cellPosition(selected, 0.73);
const selectedFrame = new THREE.LineSegments(
edgeGeometry,
selectedLineMaterial
);
selectedFrame.scale.set(
CELL_SIZE * 1.12,
0.9,
CELL_SIZE * 1.12
);
selectedFrame.position.set(
center.x,
BOARD_TOP + 0.34,
center.z
);
neighborGroup.add(selectedFrame);
for (let dr = -1; dr <= 1; dr++) {
for (let dc = -1; dc <= 1; dc++) {
if (dr === 0 && dc === 0) continue;
const r = row + dr;
const c = col + dc;
if (!validCell(r, c)) continue;
const index = r * GRID + c;
const position = cellPosition(index, 0);
const frame = new THREE.LineSegments(
edgeGeometry,
neighborLineMaterial
);
frame.scale.set(
CELL_SIZE * 1.07,
0.68,
CELL_SIZE * 1.07
);
frame.position.set(
position.x,
BOARD_TOP + 0.25,
position.z
);
neighborGroup.add(frame);
const halo = new THREE.Mesh(haloGeometry, haloMaterial);
halo.rotation.x = -Math.PI / 2;
halo.position.set(
position.x,
BOARD_TOP + 0.004,
position.z
);
neighborGroup.add(halo);
const start = cellPosition(index, 0.73);
const end = center.clone();
const lineGeometry = new THREE.BufferGeometry().setFromPoints([
start,
end
]);
lineGeometry.userData = {};
const line = new THREE.Line(lineGeometry, beamMaterial);
line.userData.ownGeometry = true;
neighborGroup.add(line);
const particle = new THREE.Mesh(
particleGeometry,
particleMaterial
);
neighborGroup.add(particle);
beamParticles.push({
mesh: particle,
start,
end,
offset: beamParticles.length / 8
});
}
}
}
// ------------------------------------------------------------
// Next-state output
// ------------------------------------------------------------
const outputGroup = new THREE.Group();
outputGroup.position.set(OUTPUT_X, 0, OUTPUT_Z);
scene.add(outputGroup);
const outputPlatform = new THREE.Mesh(
new THREE.CylinderGeometry(1.3, 1.52, 0.28, 8),
new THREE.MeshStandardMaterial({
color: 0x14242e,
roughness: 0.76,
metalness: 0.16,
flatShading: true
})
);
outputPlatform.position.y = -0.25;
outputPlatform.castShadow = true;
outputPlatform.receiveShadow = true;
outputGroup.add(outputPlatform);
const outputMaterial = new THREE.MeshStandardMaterial({
color: DEAD,
emissive: 0x000000,
emissiveIntensity: 0,
roughness: 0.62,
metalness: 0.1,
flatShading: true
});
const outputMesh = new THREE.Mesh(
new THREE.BoxGeometry(1.02, 1.02, 1.02),
outputMaterial
);
outputMesh.position.y = 0.47;
outputMesh.castShadow = true;
outputMesh.receiveShadow = true;
outputGroup.add(outputMesh);
const outputRingMaterial = new THREE.MeshBasicMaterial({
color: 0x3a5360,
transparent: true,
opacity: 0.8
});
const outputRing = new THREE.Mesh(
new THREE.TorusGeometry(0.82, 0.025, 4, 32),
outputRingMaterial
);
outputRing.rotation.x = Math.PI / 2;
outputRing.position.y = 1.08;
outputGroup.add(outputRing);
function rebuildArrow() {
disposeOwnedGeometry(arrowGroup);
arrowPulse = null;
const start = cellPosition(selected, 0.88);
const end = new THREE.Vector3(
OUTPUT_X - 1.2,
0.8,
OUTPUT_Z
);
const middleA = new THREE.Vector3(
start.x + (end.x - start.x) * 0.32,
2.15,
start.z * 0.68 + end.z * 0.32
);
const middleB = new THREE.Vector3(
start.x + (end.x - start.x) * 0.72,
1.6,
end.z + 0.65
);
arrowCurve = new THREE.CatmullRomCurve3([
start,
middleA,
middleB,
end
]);
const tube = new THREE.Mesh(
new THREE.TubeGeometry(arrowCurve, 36, 0.025, 4, false),
new THREE.MeshBasicMaterial({
color: AMBER,
transparent: true,
opacity: 0.72
})
);
tube.userData.ownGeometry = true;
arrowGroup.add(tube);
const cone = new THREE.Mesh(
new THREE.ConeGeometry(0.13, 0.34, 5),
new THREE.MeshBasicMaterial({ color: AMBER })
);
const t = 0.94;
cone.position.copy(arrowCurve.getPoint(t));
cone.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
arrowCurve.getTangent(t).normalize()
);
cone.userData.ownGeometry = true;
arrowGroup.add(cone);
arrowPulse = new THREE.Mesh(
particleGeometry,
particleMaterial
);
arrowGroup.add(arrowPulse);
}
function updateSelectionVisuals() {
rebuildNeighborhood();
rebuildArrow();
updateComputationUI();
}
// ------------------------------------------------------------
// DOM computation display
// ------------------------------------------------------------
const neighborhoodElement = document.getElementById("neighborhood");
const neighborCountElement = document.getElementById("neighborCount");
const targetStateElement = document.getElementById("targetState");
const nextValueElement = document.getElementById("nextValue");
const stateLabelElement = document.getElementById("stateLabel");
const paritySentenceElement = document.getElementById("paritySentence");
const selectedTag = document.getElementById("selectedTag");
const outputTag = document.getElementById("outputTag");
const statusElement = document.getElementById("status");
const matrixElements = [];
for (let i = 0; i < 9; i++) {
const element = document.createElement("div");
element.className = "bit";
neighborhoodElement.appendChild(element);
matrixElements.push(element);
}
function updateComputationUI() {
const row = Math.floor(selected / GRID);
const col = selected % GRID;
const sum = neighborSum(cells, selected);
const next = computeNextAt(cells, selected);
outputNext = next;
let elementIndex = 0;
for (let dr = -1; dr <= 1; dr++) {
for (let dc = -1; dc <= 1; dc++) {
const element = matrixElements[elementIndex++];
if (dr === 0 && dc === 0) {
element.textContent = "×";
element.className = "bit target";
element.title = "Target cell; its current value is not used by the rule";
continue;
}
const r = row + dr;
const c = col + dc;
const inside = validCell(r, c);
const value = inside ? cells[r * GRID + c] : 0;
element.textContent = String(value);
element.className = `bit ${value ? "on" : "off"}`;
if (!inside) element.classList.add("off-grid");
element.title = inside
? `Neighbor (${c}, ${r}) = ${value}`
: "Outside the grid; treated as 0";
}
}
neighborCountElement.textContent = String(sum);
targetStateElement.textContent = String(cells[selected]);
nextValueElement.textContent = String(next);
nextValueElement.style.color = next ? "var(--mint)" : "#78909b";
nextValueElement.style.borderColor = next
? "rgba(89,239,192,.45)"
: "rgba(157,191,205,.18)";
nextValueElement.style.background = next
? "rgba(89,239,192,.08)"
: "rgba(157,191,205,.03)";
stateLabelElement.textContent = next ? "ON" : "OFF";
paritySentenceElement.textContent =
`${sum} live neighbor${sum === 1 ? "" : "s"} → ` +
`${sum % 2 ? "odd" : "even"} → ${next}`;
selectedTag.textContent =
`Cell ${String(col + 1).padStart(2, "0")}:${String(row + 1).padStart(2, "0")}`;
outputTag.textContent = `Next / ${next}`;
}
// ------------------------------------------------------------
// Direct camera controls
// ------------------------------------------------------------
const cameraState = {
target: new THREE.Vector3(1.0, 0, 0),
radius: 20.5,
theta: 0.76,
phi: 0.82
};
function updateCamera() {
const sinPhi = Math.sin(cameraState.phi);
camera.position.set(
cameraState.target.x +
cameraState.radius * sinPhi * Math.sin(cameraState.theta),
cameraState.target.y +
cameraState.radius * Math.cos(cameraState.phi),
cameraState.target.z +
cameraState.radius * sinPhi * Math.cos(cameraState.theta)
);
camera.lookAt(cameraState.target);
camera.updateMatrixWorld();
}
function resetCamera() {
cameraState.target.set(1.0, 0, 0);
cameraState.radius = 20.5;
cameraState.theta = 0.76;
cameraState.phi = 0.82;
}
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
let pointerDown = null;
renderer.domElement.addEventListener("pointerdown", (event) => {
pointerDown = {
id: event.pointerId,
x: event.clientX,
y: event.clientY,
lastX: event.clientX,
lastY: event.clientY,
dragged: false
};
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!pointerDown || event.pointerId !== pointerDown.id) return;
const dx = event.clientX - pointerDown.lastX;
const dy = event.clientY - pointerDown.lastY;
pointerDown.lastX = event.clientX;
pointerDown.lastY = event.clientY;
if (
Math.hypot(
event.clientX - pointerDown.x,
event.clientY - pointerDown.y
) > 4
) {
pointerDown.dragged = true;
}
if (pointerDown.dragged) {
cameraState.theta -= dx * 0.006;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi - dy * 0.005,
0.35,
1.25
);
}
});
renderer.domElement.addEventListener("pointerup", (event) => {
if (!pointerDown || event.pointerId !== pointerDown.id) return;
if (!pointerDown.dragged) {
pointer.x = (event.clientX / innerWidth) * 2 - 1;
pointer.y = -(event.clientY / innerHeight) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObjects(cellMeshes, false);
if (hits.length) {
selected = hits[0].object.userData.index;
updateSelectionVisuals();
}
}
pointerDown = null;
});
renderer.domElement.addEventListener("pointercancel", () => {
pointerDown = null;
});
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius + event.deltaY * 0.012,
12,
34
);
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", resetCamera);
renderer.domElement.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
// ------------------------------------------------------------
// Simulation controls
// ------------------------------------------------------------
const stepButton = document.getElementById("stepButton");
const playButton = document.getElementById("playButton");
const seedButton = document.getElementById("seedButton");
const clearButton = document.getElementById("clearButton");
function setStatus(text, busy = false) {
statusElement.textContent = text;
statusElement.classList.toggle("busy", busy);
}
async function stepGrid() {
if (transitioning) return;
transitioning = true;
setStatus("COMPUTING", true);
// Preview the selected cell's next state before applying the grid.
outputNext = computeNextAt(cells, selected);
outputPulseStart = performance.now();
updateComputationUI();
await new Promise((resolve) => setTimeout(resolve, 460));
const next = computeAll(cells);
const changed = new Set();
const now = performance.now();
for (let i = 0; i < CELL_COUNT; i++) {
if (cells[i] !== next[i]) changed.add(i);
}
cells = next;
for (const i of changed) {
cellMeshes[i].userData.pulseStart = now;
}
outputNext = computeNextAt(cells, selected);
updateComputationUI();
transitioning = false;
setStatus(playing ? "RUNNING" : "READY");
}
function scheduleAuto() {
clearTimeout(autoTimer);
if (!playing) return;
autoTimer = setTimeout(async () => {
await stepGrid();
scheduleAuto();
}, 780);
}
stepButton.addEventListener("click", stepGrid);
playButton.addEventListener("click", () => {
playing = !playing;
playButton.textContent = playing ? "Pause" : "Play";
playButton.classList.toggle("active", playing);
setStatus(playing ? "RUNNING" : "READY");
scheduleAuto();
});
seedButton.addEventListener("click", reseed);
clearButton.addEventListener("click", clearGrid);
window.addEventListener("keydown", (event) => {
if (event.target instanceof HTMLButtonElement) return;
if (event.code === "Space") {
event.preventDefault();
stepGrid();
} else if (event.key.toLowerCase() === "r") {
reseed();
} else if (event.key.toLowerCase() === "c") {
clearGrid();
}
});
// ------------------------------------------------------------
// World-space labels
// ------------------------------------------------------------
function placeLabel(element, worldPosition) {
const projected = worldPosition.clone().project(camera);
if (projected.z < -1 || projected.z > 1) {
element.style.display = "none";
return;
}
element.style.display = "block";
element.style.left = `${(projected.x * 0.5 + 0.5) * innerWidth}px`;
element.style.top = `${(-projected.y * 0.5 + 0.5) * innerHeight}px`;
}
// ------------------------------------------------------------
// Animation
// ------------------------------------------------------------
const clock = new THREE.Clock();
let elapsed = 0;
function animate() {
requestAnimationFrame(animate);
const dt = Math.min(clock.getDelta(), 0.05);
elapsed += dt;
const now = performance.now();
const blend = 1 - Math.exp(-dt * 10);
// Animate all binary cells.
for (let i = 0; i < CELL_COUNT; i++) {
const mesh = cellMeshes[i];
const state = cells[i];
const targetHeight = state ? 0.5 : 0.17;
mesh.scale.y += (targetHeight - mesh.scale.y) * blend;
const pulseAge = THREE.MathUtils.clamp(
(now - mesh.userData.pulseStart) / 620,
0,
1
);
const pulse = Math.sin(pulseAge * Math.PI);
const horizontalScale = CELL_SIZE + pulse * 0.09;
mesh.scale.x += (horizontalScale - mesh.scale.x) * blend;
mesh.scale.z += (horizontalScale - mesh.scale.z) * blend;
mesh.position.y = BOARD_TOP + mesh.scale.y / 2;
const targetColor = state ? ALIVE : DEAD;
mesh.material.color.lerp(targetColor, blend);
const targetEmissive = state ? ALIVE : new THREE.Color(0x000000);
mesh.material.emissive.lerp(targetEmissive, blend);
mesh.material.emissiveIntensity = state ? 0.26 : 0;
}
// Selected target marker.
const markerPosition = cellPosition(selected, 1.05 + Math.sin(elapsed * 3) * 0.07);
marker.position.copy(markerPosition);
marker.rotation.y += dt * 1.8;
marker.rotation.x += dt * 0.9;
// Local input particles.
for (const particle of beamParticles) {
const t = (elapsed * 0.58 + particle.offset) % 1;
particle.mesh.position.lerpVectors(
particle.start,
particle.end,
t
);
particle.mesh.position.y += Math.sin(t * Math.PI) * 0.22;
}
// Arrow pulse.
if (arrowCurve && arrowPulse) {
const t = (elapsed * 0.38) % 1;
arrowPulse.position.copy(arrowCurve.getPoint(t));
}
// Output cube and ring.
const outputTarget = outputNext ? ALIVE : DEAD;
outputMaterial.color.lerp(outputTarget, blend);
outputMaterial.emissive.lerp(
outputNext ? ALIVE : new THREE.Color(0x000000),
blend
);
outputMaterial.emissiveIntensity = outputNext ? 0.45 : 0;
const outputPulseAge = THREE.MathUtils.clamp(
(now - outputPulseStart) / 650,
0,
1
);
const outputPulse = Math.sin(outputPulseAge * Math.PI);
outputMesh.scale.setScalar(1 + outputPulse * 0.14);
outputRing.rotation.z += dt * 0.6;
outputRingMaterial.color.lerp(
outputNext
? new THREE.Color(ALIVE)
: new THREE.Color(0x3a5360),
blend
);
updateCamera();
renderer.render(scene, camera);
placeLabel(
selectedTag,
markerPosition.clone().add(new THREE.Vector3(0, 0.22, 0))
);
placeLabel(
outputTag,
new THREE.Vector3(OUTPUT_X, 1.48, OUTPUT_Z)
);
}
window.addEventListener("resize", () => {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
});
// Initialize.
reseed();
updateSelectionVisuals();
updateCamera();
animate();
</script>
</body>
</html>
```