Prompt specification
Build or customize the Three.js 3D scene "Ionic-lattice counting explorer" 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: Ionic-lattice counting explorer
Category: Science & Physics · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/ionic-lattice-counting-explorer-x1956
Scene Description Prompt:
Make a standalone HTML scene with Three.js from cdnjs that depicts an ionic crystal lattice. Let viewers inspect corner, edge, face, and interior site contributions in a chosen unit-cell model; count stoichiometry correctly and explicitly identify the selected crystal structure. Low-poly.
Working Three.js Starter (ionic-lattice-counting-explorer-x1956):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>NaCl Ionic Crystal Lattice</title>
<style>
:root {
color-scheme: dark;
--bg: #06111d;
--panel: rgba(9, 24, 38, 0.88);
--panel-border: rgba(157, 211, 232, 0.16);
--text: #eef8fb;
--muted: #91a8b6;
--cyan: #78d8f2;
--na: #ff806c;
--cl: #55e6ad;
--active: rgba(120, 216, 242, 0.14);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
color: var(--text);
}
button,
input,
select {
font: inherit;
}
#scene {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
outline: none;
}
.brand {
position: fixed;
z-index: 4;
top: 22px;
left: 24px;
pointer-events: none;
text-shadow: 0 2px 18px rgba(0, 0, 0, 0.65);
}
.eyebrow {
margin-bottom: 5px;
color: var(--cyan);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.19em;
text-transform: uppercase;
}
.brand h1 {
margin: 0;
font-size: clamp(23px, 3vw, 38px);
font-weight: 720;
letter-spacing: -0.035em;
}
.structure-line {
margin-top: 8px;
color: #bfd0d9;
font-size: 12px;
}
.structure-line strong {
color: #fff;
font-weight: 650;
}
.panel {
position: fixed;
z-index: 5;
top: 126px;
bottom: 20px;
left: 20px;
width: 365px;
padding: 17px;
overflow: auto;
border: 1px solid var(--panel-border);
border-radius: 18px;
background:
linear-gradient(160deg, rgba(21, 46, 63, 0.72), rgba(7, 20, 32, 0.92)),
var(--panel);
box-shadow:
0 24px 70px rgba(0, 0, 0, 0.34),
inset 0 1px rgba(255, 255, 255, 0.04);
backdrop-filter: blur(18px);
scrollbar-width: thin;
scrollbar-color: rgba(120, 216, 242, 0.25) transparent;
}
.section + .section {
margin-top: 19px;
padding-top: 18px;
border-top: 1px solid rgba(157, 211, 232, 0.11);
}
.section-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 11px;
}
.section h2 {
margin: 0;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.13em;
text-transform: uppercase;
color: #b8cad4;
}
.tag {
padding: 4px 8px;
border: 1px solid rgba(120, 216, 242, 0.22);
border-radius: 999px;
background: rgba(120, 216, 242, 0.08);
color: var(--cyan);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.06em;
}
.model-card {
padding: 13px;
border: 1px solid rgba(120, 216, 242, 0.14);
border-radius: 12px;
background: rgba(4, 14, 24, 0.35);
}
.model-card strong {
display: block;
margin-bottom: 4px;
font-size: 15px;
}
.model-card p {
margin: 0;
color: var(--muted);
font-size: 11px;
line-height: 1.55;
}
.model-card .model-meta {
display: flex;
flex-wrap: wrap;
gap: 6px;
margin-top: 10px;
}
.model-meta span {
padding: 4px 7px;
border-radius: 6px;
background: rgba(255, 255, 255, 0.055);
color: #c6d7df;
font-size: 10px;
}
.categories {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px;
}
.category-button {
position: relative;
min-height: 58px;
padding: 9px 10px;
border: 1px solid rgba(157, 211, 232, 0.13);
border-radius: 10px;
background: rgba(255, 255, 255, 0.035);
color: var(--text);
text-align: left;
cursor: pointer;
transition:
background 140ms ease,
border-color 140ms ease,
transform 140ms ease;
}
.category-button:hover {
border-color: rgba(120, 216, 242, 0.38);
background: rgba(120, 216, 242, 0.08);
transform: translateY(-1px);
}
.category-button.active {
border-color: rgba(120, 216, 242, 0.6);
background: var(--active);
box-shadow: inset 0 0 0 1px rgba(120, 216, 242, 0.08);
}
.category-button.all {
grid-column: 1 / -1;
min-height: 46px;
}
.category-button strong {
display: block;
font-size: 12px;
font-weight: 700;
}
.category-button span {
display: block;
margin-top: 4px;
color: var(--muted);
font-size: 10px;
}
.inspector {
padding: 13px;
border: 1px solid rgba(157, 211, 232, 0.14);
border-radius: 12px;
background:
linear-gradient(135deg, rgba(120, 216, 242, 0.065), transparent 65%),
rgba(3, 12, 21, 0.34);
}
.inspector-top {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
}
.mini-label {
color: var(--cyan);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.15em;
text-transform: uppercase;
}
.inspector h3 {
margin: 4px 0 0;
font-size: 16px;
font-weight: 680;
}
.detail-number {
min-width: 60px;
text-align: right;
}
.detail-number strong {
display: block;
font-size: 25px;
line-height: 1;
font-variant-numeric: tabular-nums;
}
.detail-number span {
display: block;
margin-top: 4px;
color: var(--muted);
font-size: 9px;
text-transform: uppercase;
letter-spacing: 0.06em;
}
.detail-species {
display: inline-block;
margin-top: 11px;
padding: 5px 8px;
border-radius: 6px;
background: rgba(255, 255, 255, 0.055);
color: #dce9ee;
font-size: 11px;
font-weight: 700;
}
.detail-formula {
margin-top: 10px;
color: #fff;
font-size: 13px;
font-weight: 650;
}
.inspector p {
margin: 8px 0 0;
color: var(--muted);
font-size: 11px;
line-height: 1.55;
}
.coord {
margin-top: 10px;
padding-top: 9px;
border-top: 1px solid rgba(157, 211, 232, 0.1);
color: #839ba9;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
line-height: 1.45;
}
.table-wrap {
overflow-x: auto;
border: 1px solid rgba(157, 211, 232, 0.11);
border-radius: 11px;
}
table {
width: 100%;
border-collapse: collapse;
font-size: 10px;
white-space: nowrap;
}
th,
td {
padding: 8px 7px;
border-bottom: 1px solid rgba(157, 211, 232, 0.08);
text-align: right;
}
th:first-child,
td:first-child {
text-align: left;
}
th {
color: #8fa7b4;
font-size: 8px;
letter-spacing: 0.08em;
text-transform: uppercase;
font-weight: 750;
}
tbody tr {
cursor: pointer;
transition: background 120ms ease;
}
tbody tr:hover,
tbody tr.active {
background: rgba(120, 216, 242, 0.09);
}
tbody tr:last-child td {
border-bottom: 0;
}
.ion-na {
color: var(--na);
font-weight: 750;
}
.ion-cl {
color: var(--cl);
font-weight: 750;
}
.formula-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.formula-card {
padding: 11px;
border: 1px solid rgba(157, 211, 232, 0.11);
border-radius: 10px;
background: rgba(4, 14, 24, 0.28);
}
.formula-card span {
display: block;
font-size: 11px;
font-weight: 750;
}
.formula-card strong {
display: block;
margin-top: 6px;
font-size: 23px;
font-variant-numeric: tabular-nums;
}
.formula-card small {
display: block;
margin-top: 4px;
color: var(--muted);
font-size: 9px;
}
.stoich-result {
margin: 10px 0 0;
padding: 10px;
border-left: 2px solid var(--cyan);
border-radius: 0 7px 7px 0;
background: rgba(120, 216, 242, 0.055);
color: #c9dbe2;
font-size: 10px;
line-height: 1.55;
}
.stoich-result strong {
color: #fff;
}
.fine-print {
margin: 9px 0 0;
color: #728b99;
font-size: 9px;
line-height: 1.5;
}
.controls {
position: fixed;
z-index: 6;
top: 20px;
right: 20px;
width: 228px;
padding: 12px;
border: 1px solid var(--panel-border);
border-radius: 14px;
background: rgba(8, 22, 35, 0.78);
box-shadow: 0 15px 45px rgba(0, 0, 0, 0.26);
backdrop-filter: blur(15px);
}
.controls-title {
margin-bottom: 9px;
color: #91a8b6;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.button-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px;
}
.control-button {
padding: 8px;
border: 1px solid rgba(157, 211, 232, 0.15);
border-radius: 8px;
background: rgba(255, 255, 255, 0.045);
color: #d8e6eb;
font-size: 10px;
cursor: pointer;
transition: 130ms ease;
}
.control-button:hover,
.control-button.active {
border-color: rgba(120, 216, 242, 0.45);
background: rgba(120, 216, 242, 0.11);
color: #fff;
}
.toggle {
display: flex;
align-items: center;
gap: 8px;
margin-top: 9px;
color: #a9bdc7;
font-size: 10px;
cursor: pointer;
}
.toggle input {
accent-color: var(--cyan);
}
.control-help {
margin-top: 10px;
padding-top: 9px;
border-top: 1px solid rgba(157, 211, 232, 0.1);
color: #728b99;
font-size: 9px;
line-height: 1.5;
}
.legend {
position: fixed;
z-index: 4;
right: 20px;
bottom: 20px;
padding: 11px 13px;
border: 1px solid var(--panel-border);
border-radius: 12px;
background: rgba(8, 22, 35, 0.74);
color: #9eb2bd;
font-size: 10px;
backdrop-filter: blur(14px);
pointer-events: none;
}
.legend-row {
display: flex;
align-items: center;
gap: 8px;
}
.legend-row + .legend-row {
margin-top: 6px;
}
.swatch {
width: 10px;
height: 10px;
border-radius: 50%;
box-shadow: 0 0 13px currentColor;
}
.swatch.na {
color: var(--na);
background: var(--na);
}
.swatch.cl {
color: var(--cl);
background: var(--cl);
}
.legend-note {
margin-top: 8px;
padding-top: 7px;
border-top: 1px solid rgba(157, 211, 232, 0.1);
color: #728b99;
font-size: 9px;
}
#tooltip {
position: fixed;
z-index: 20;
display: none;
max-width: 240px;
padding: 8px 10px;
border: 1px solid rgba(120, 216, 242, 0.24);
border-radius: 8px;
background: rgba(4, 14, 24, 0.94);
color: #d9e8ed;
font-size: 10px;
line-height: 1.5;
white-space: pre-line;
pointer-events: none;
box-shadow: 0 8px 30px rgba(0, 0, 0, 0.4);
}
#loading {
position: fixed;
z-index: 30;
inset: 0;
display: grid;
place-items: center;
background: var(--bg);
color: var(--cyan);
font-size: 11px;
letter-spacing: 0.13em;
text-transform: uppercase;
transition: opacity 300ms ease;
}
#loading.hidden {
opacity: 0;
pointer-events: none;
}
@media (max-width: 820px) {
.brand {
top: 13px;
left: 14px;
}
.brand h1 {
font-size: 23px;
}
.structure-line {
font-size: 10px;
}
.panel {
top: auto;
right: 10px;
bottom: 10px;
left: 10px;
width: auto;
max-height: 48vh;
padding: 13px;
border-radius: 15px;
}
.controls {
top: 12px;
right: 12px;
width: 185px;
padding: 9px;
}
.legend {
right: 12px;
bottom: calc(48vh + 20px);
}
}
@media (max-width: 520px) {
.brand {
max-width: calc(100vw - 210px);
}
.structure-line {
line-height: 1.4;
}
.legend {
display: none;
}
.controls {
width: 170px;
}
.control-help {
display: none;
}
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive three-dimensional NaCl rock-salt crystal lattice"></canvas>
<header class="brand">
<div class="eyebrow">Interactive crystallography</div>
<h1>Rock-salt ionic lattice</h1>
<div class="structure-line">
<strong>NaCl</strong> · B1 structure · Fm-3m (No. 225)
</div>
</header>
<aside class="panel" aria-label="Crystal structure information">
<section class="section">
<div class="section-head">
<h2>Chosen unit-cell model</h2>
<span class="tag">Z = 4</span>
</div>
<div class="model-card">
<strong>Conventional cubic cell</strong>
<p>
Origin-centered NaCl cell. Chloride occupies the FCC corner and
face-center sublattice; sodium occupies the edge-center and
body-center sites.
</p>
<div class="model-meta">
<span>a = 5.64 Å</span>
<span>6:6 coordination</span>
<span>4 NaCl units</span>
</div>
</div>
</section>
<section class="section">
<div class="section-head">
<h2>Inspect site class</h2>
</div>
<div class="categories" role="group" aria-label="Site contribution classes">
<button class="category-button all active" data-category="all" aria-pressed="true">
<strong>Whole cell</strong>
<span>27 drawn site markers · 8 effective ions</span>
</button>
<button class="category-button" data-category="corner" aria-pressed="false">
<strong>Corner</strong>
<span>8 markers × 1/8</span>
</button>
<button class="category-button" data-category="edge" aria-pressed="false">
<strong>Edge</strong>
<span>12 markers × 1/4</span>
</button>
<button class="category-button" data-category="face" aria-pressed="false">
<strong>Face</strong>
<span>6 markers × 1/2</span>
</button>
<button class="category-button" data-category="interior" aria-pressed="false">
<strong>Interior</strong>
<span>1 marker × 1</span>
</button>
</div>
</section>
<section class="section">
<div class="section-head">
<h2>Site inspector</h2>
</div>
<div class="inspector" aria-live="polite">
<div class="inspector-top">
<div>
<span class="mini-label">Current selection</span>
<h3 id="detailTitle">Whole conventional cell</h3>
</div>
<div class="detail-number">
<strong id="detailBadge">27</strong>
<span id="detailBadgeLabel">drawn markers</span>
</div>
</div>
<div class="detail-species" id="detailSpecies">4 Na⁺ + 4 Cl⁻</div>
<div class="detail-formula" id="detailFormula">Weighted cell contents: 8 ions</div>
<p id="detailNote">
Select a site class above, or click an ion in the scene.
</p>
<div class="coord" id="detailCoord">
Boundary markers are weighted by their fraction inside the cell.
</div>
</div>
</section>
<section class="section">
<div class="section-head">
<h2>Boundary ownership count</h2>
</div>
<div class="table-wrap">
<table>
<thead>
<tr>
<th>Site class</th>
<th>Markers</th>
<th>Each</th>
<th>Total</th>
<th>Ion</th>
</tr>
</thead>
<tbody>
<tr data-category="corner" tabindex="0">
<td>Corner</td>
<td>8</td>
<td>1/8</td>
<td>1</td>
<td class="ion-cl">Cl⁻</td>
</tr>
<tr data-category="edge" tabindex="0">
<td>Edge</td>
<td>12</td>
<td>1/4</td>
<td>3</td>
<td class="ion-na">Na⁺</td>
</tr>
<tr data-category="face" tabindex="0">
<td>Face</td>
<td>6</td>
<td>1/2</td>
<td>3</td>
<td class="ion-cl">Cl⁻</td>
</tr>
<tr data-category="interior" tabindex="0">
<td>Interior</td>
<td>1</td>
<td>1</td>
<td>1</td>
<td class="ion-na">Na⁺</td>
</tr>
</tbody>
</table>
</div>
<p class="fine-print">
The table contains 27 visible site markers in the selected cell, but
their shared boundary ownership produces only 8 effective ions.
</p>
</section>
<section class="section">
<div class="section-head">
<h2>Stoichiometry check</h2>
<span class="tag">1 : 1</span>
</div>
<div class="formula-grid">
<div class="formula-card">
<span class="ion-cl">Cl⁻</span>
<strong>4</strong>
<small>8(1/8) + 6(1/2)</small>
</div>
<div class="formula-card">
<span class="ion-na">Na⁺</span>
<strong>4</strong>
<small>12(1/4) + 1(1)</small>
</div>
</div>
<div class="stoich-result">
<strong>4 Na⁺ : 4 Cl⁻ = 1:1.</strong>
The conventional cell contains four NaCl formula units, so
<strong>Z = 4</strong>. A primitive cell contains one formula unit.
</div>
<p class="fine-print">
Ionic radii and bond lengths are visually stylized. Lines indicate
nearest-neighbor ionic contact guides, not separate molecular bonds.
</p>
</section>
</aside>
<section class="controls" aria-label="Scene controls">
<div class="controls-title">View controls</div>
<div class="button-row">
<button class="control-button" id="resetButton">Reset view</button>
<button class="control-button" id="rotateButton">Auto rotate</button>
</div>
<label class="toggle">
<input type="checkbox" id="neighborsToggle" checked>
Show neighboring lattice
</label>
<label class="toggle">
<input type="checkbox" id="cellToggle" checked>
Show unit-cell shell
</label>
<div class="control-help">
Drag: orbit · Wheel: zoom<br>
Shift/right-drag: pan · Click: inspect<br>
Keys: 1–4 classes · 0 all · R reset
</div>
</section>
<div class="legend" aria-hidden="true">
<div class="legend-row">
<span class="swatch na"></span>
<span>Na⁺ · sodium</span>
</div>
<div class="legend-row">
<span class="swatch cl"></span>
<span>Cl⁻ · chloride</span>
</div>
<div class="legend-note">Bright ions belong to the selected unit cell.</div>
</div>
<div id="tooltip"></div>
<div id="loading">Building crystal lattice…</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const $ = (id) => document.getElementById(id);
const canvas = $("scene");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.setClearColor(0x06111d, 1);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x06111d);
scene.fog = new THREE.FogExp2(0x06111d, 0.018);
const camera = new THREE.PerspectiveCamera(
45,
window.innerWidth / window.innerHeight,
0.1,
100
);
const view = {
theta: 0.72,
phi: 1.08,
radius: 10.2,
target: new THREE.Vector3()
};
const actual = {
theta: view.theta,
phi: view.phi,
radius: view.radius,
target: view.target.clone()
};
function updateCamera() {
const sinPhi = Math.sin(actual.phi);
camera.position.set(
actual.target.x + actual.radius * sinPhi * Math.sin(actual.theta),
actual.target.y + actual.radius * Math.cos(actual.phi),
actual.target.z + actual.radius * sinPhi * Math.cos(actual.theta)
);
camera.lookAt(actual.target);
camera.updateMatrixWorld();
}
updateCamera();
scene.add(new THREE.HemisphereLight(0xbfe8ff, 0x142332, 1.8));
const keyLight = new THREE.DirectionalLight(0xdff7ff, 2.5);
keyLight.position.set(5, 7, 5);
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x5b9fff, 1.35);
rimLight.position.set(-6, 2, -5);
scene.add(rimLight);
const warmLight = new THREE.PointLight(0xff9b80, 10, 18, 2);
warmLight.position.set(4, -2, 4);
scene.add(warmLight);
// The conventional cell uses scene units. Its true NaCl lattice
// constant is 5.64 angstroms, but scene radii are intentionally stylized.
const CELL_SIZE = 2.6;
const HALF_STEP = CELL_SIZE / 2;
const GRID_LIMIT = 3;
const species = {
Na: {
charge: "+",
color: 0xff806c,
radius: 0.17,
label: "Na⁺"
},
Cl: {
charge: "−",
color: 0x55e6ad,
radius: 0.23,
label: "Cl⁻"
}
};
const categoryMeta = {
corner: {
label: "Corner sites",
count: 8,
share: "1/8",
species: "Cl",
formula: "8 × 1/8 = 1 Cl⁻",
note:
"Each corner is shared by eight adjacent cubic cells, so one eighth of each corner ion belongs to this cell."
},
edge: {
label: "Edge-center sites",
count: 12,
share: "1/4",
species: "Na",
formula: "12 × 1/4 = 3 Na⁺",
note:
"Each edge center is shared by four adjacent cubic cells, so one quarter of each edge ion belongs to this cell."
},
face: {
label: "Face-center sites",
count: 6,
share: "1/2",
species: "Cl",
formula: "6 × 1/2 = 3 Cl⁻",
note:
"Each face center is shared by two adjacent cubic cells, so one half of each face ion belongs to this cell."
},
interior: {
label: "Interior site",
count: 1,
share: "1",
species: "Na",
formula: "1 × 1 = 1 Na⁺",
note:
"The body-center ion lies wholly inside the selected cell and is counted in full."
}
};
function classifyCentralSite(x, y, z) {
if (Math.abs(x) > 1 || Math.abs(y) > 1 || Math.abs(z) > 1) {
return null;
}
const boundaryCoordinateCount = [x, y, z]
.filter((value) => Math.abs(value) === 1).length;
if (boundaryCoordinateCount === 3) return "corner";
if (boundaryCoordinateCount === 2) return "edge";
if (boundaryCoordinateCount === 1) return "face";
return "interior";
}
// A half-cell grid with alternating parity reproduces the two
// interpenetrating FCC sublattices of the rock-salt structure.
const records = [];
for (let x = -GRID_LIMIT; x <= GRID_LIMIT; x++) {
for (let y = -GRID_LIMIT; y <= GRID_LIMIT; y++) {
for (let z = -GRID_LIMIT; z <= GRID_LIMIT; z++) {
const parityEven = (x + y + z) % 2 === 0;
const type = parityEven ? "Na" : "Cl";
const category = classifyCentralSite(x, y, z);
records.push({
type,
category,
grid: new THREE.Vector3(x, y, z),
position: new THREE.Vector3(
x * HALF_STEP,
y * HALF_STEP,
z * HALF_STEP
),
central: category !== null
});
}
}
}
const recordMap = new Map();
for (const record of records) {
recordMap.set(
`${record.grid.x},${record.grid.y},${record.grid.z}`,
record
);
}
const ionGeometry = new THREE.IcosahedronGeometry(1, 1);
const dummy = new THREE.Object3D();
const colorScratch = new THREE.Color();
const baseColor = new THREE.Color();
const dimColor = new THREE.Color(0x071522);
const white = new THREE.Color(0xffffff);
const ionMeshes = {};
for (const [type, config] of Object.entries(species)) {
const typeRecords = records.filter((record) => record.type === type);
const material = new THREE.MeshStandardMaterial({
color: 0xffffff,
vertexColors: true,
roughness: 0.58,
metalness: 0.07,
flatShading: true,
emissive: config.color,
emissiveIntensity: 0.055
});
const mesh = new THREE.InstancedMesh(
ionGeometry,
material,
typeRecords.length
);
mesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
mesh.frustumCulled = false;
mesh.userData.records = typeRecords;
ionMeshes[type] = mesh;
scene.add(mesh);
}
// Unit-cell shell.
const cellGroup = new THREE.Group();
scene.add(cellGroup);
const cellGeometry = new THREE.BoxGeometry(
CELL_SIZE,
CELL_SIZE,
CELL_SIZE
);
const cellFill = new THREE.Mesh(
cellGeometry,
new THREE.MeshBasicMaterial({
color: 0x75d7f0,
transparent: true,
opacity: 0.032,
side: THREE.DoubleSide,
depthWrite: false
})
);
cellGroup.add(cellFill);
const cellEdges = new THREE.LineSegments(
new THREE.EdgesGeometry(cellGeometry),
new THREE.LineBasicMaterial({
color: 0x8de6fa,
transparent: true,
opacity: 0.72
})
);
cellGroup.add(cellEdges);
// Nearest-neighbor contact guides.
const directions = [
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]
];
const centralBondPositions = [];
const outerBondPositions = [];
for (const record of records) {
for (const [dx, dy, dz] of directions) {
const neighbor = recordMap.get(
`${record.grid.x + dx},${record.grid.y + dy},${record.grid.z + dz}`
);
if (!neighbor) continue;
const bothCentral = record.central && neighbor.central;
if (bothCentral) {
centralBondPositions.push(
record.position.x, record.position.y, record.position.z,
neighbor.position.x, neighbor.position.y, neighbor.position.z
);
} else {
outerBondPositions.push(
record.position.x, record.position.y, record.position.z,
neighbor.position.x, neighbor.position.y, neighbor.position.z
);
}
}
}
const centralBonds = new THREE.LineSegments(
new THREE.BufferGeometry().setAttribute(
"position",
new THREE.Float32BufferAttribute(centralBondPositions, 3)
),
new THREE.LineBasicMaterial({
color: 0x75bfd2,
transparent: true,
opacity: 0.39,
depthWrite: false
})
);
cellGroup.add(centralBonds);
const outerBonds = new THREE.LineSegments(
new THREE.BufferGeometry().setAttribute(
"position",
new THREE.Float32BufferAttribute(outerBondPositions, 3)
),
new THREE.LineBasicMaterial({
color: 0x41697d,
transparent: true,
opacity: 0.16,
depthWrite: false
})
);
scene.add(outerBonds);
// Subtle background particles.
const particlePositions = [];
for (let i = 0; i < 180; i++) {
particlePositions.push(
(Math.random() - 0.5) * 28,
(Math.random() - 0.5) * 22,
(Math.random() - 0.5) * 28
);
}
const particleGeometry = new THREE.BufferGeometry();
particleGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(particlePositions, 3)
);
const particles = new THREE.Points(
particleGeometry,
new THREE.PointsMaterial({
color: 0x7eb8cc,
size: 0.035,
transparent: true,
opacity: 0.42,
depthWrite: false
})
);
scene.add(particles);
const selectedRing = new THREE.Mesh(
new THREE.IcosahedronGeometry(1, 1),
new THREE.MeshBasicMaterial({
color: 0xffffff,
wireframe: true,
transparent: true,
opacity: 0.85,
depthTest: false,
depthWrite: false
})
);
selectedRing.visible = false;
selectedRing.renderOrder = 20;
scene.add(selectedRing);
const hoverRing = new THREE.Mesh(
new THREE.IcosahedronGeometry(1, 1),
new THREE.MeshBasicMaterial({
color: 0xffffff,
wireframe: true,
transparent: true,
opacity: 0.4,
depthTest: false,
depthWrite: false
})
);
hoverRing.visible = false;
hoverRing.renderOrder = 19;
scene.add(hoverRing);
let currentCategory = "all";
let selectedRecord = null;
let showNeighbors = true;
let autoRotate = false;
function updateAppearance() {
for (const [type, mesh] of Object.entries(ionMeshes)) {
const typeRecords = mesh.userData.records;
const config = species[type];
baseColor.setHex(config.color);
typeRecords.forEach((record, index) => {
const isSelected = record === selectedRecord;
let active =
record.central &&
(currentCategory === "all" ||
record.category === currentCategory);
if (isSelected) active = true;
let scale = config.radius;
if (active) {
scale *= currentCategory === "all" ? 1.08 : 1.27;
} else if (record.central) {
scale *= 0.91;
} else {
scale *= 0.78;
}
if (isSelected) scale *= 1.16;
if (!record.central && !showNeighbors) scale = 0;
dummy.position.copy(record.position);
dummy.quaternion.identity();
dummy.scale.setScalar(scale);
dummy.updateMatrix();
mesh.setMatrixAt(index, dummy.matrix);
if (active) {
colorScratch.copy(baseColor).lerp(white, isSelected ? 0.24 : 0.08);
} else if (record.central) {
colorScratch.copy(baseColor).lerp(dimColor, 0.69);
} else {
colorScratch.copy(baseColor).lerp(dimColor, 0.82);
}
mesh.setColorAt(index, colorScratch);
});
mesh.instanceMatrix.needsUpdate = true;
if (mesh.instanceColor) {
mesh.instanceColor.needsUpdate = true;
}
}
outerBonds.visible = showNeighbors;
if (selectedRecord) {
const config = species[selectedRecord.type];
selectedRing.visible = true;
selectedRing.position.copy(selectedRecord.position);
selectedRing.scale.setScalar(config.radius * 1.85);
selectedRing.material.color.setHex(config.color);
} else {
selectedRing.visible = false;
}
}
function updateInspector() {
const title = $("detailTitle");
const badge = $("detailBadge");
const badgeLabel = $("detailBadgeLabel");
const speciesLine = $("detailSpecies");
const formula = $("detailFormula");
const note = $("detailNote");
const coordinate = $("detailCoord");
if (selectedRecord) {
const config = species[selectedRecord.type];
const fractional = selectedRecord.grid
.clone()
.multiplyScalar(0.5);
if (selectedRecord.central) {
const meta = categoryMeta[selectedRecord.category];
title.textContent = meta.label;
badge.textContent = meta.count;
badgeLabel.textContent = "class sites";
speciesLine.textContent = `${config.label} · ${meta.share} ownership each`;
formula.textContent = meta.formula;
note.textContent = meta.note;
coordinate.textContent =
`Fractional coordinate: ` +
`(${fractional.x.toFixed(2)}, ${fractional.y.toFixed(2)}, ` +
`${fractional.z.toFixed(2)})`;
} else {
title.textContent = "Neighboring lattice ion";
badge.textContent = "0";
badgeLabel.textContent = "counted here";
speciesLine.textContent = config.label;
formula.textContent = "Outside the selected unit cell";
note.textContent =
"This ion belongs to a neighboring cell and is shown only to make the extended lattice legible.";
coordinate.textContent =
`Grid coordinate: (${selectedRecord.grid.x}, ` +
`${selectedRecord.grid.y}, ${selectedRecord.grid.z})`;
}
return;
}
if (currentCategory === "all") {
title.textContent = "Whole conventional cell";
badge.textContent = "27";
badgeLabel.textContent = "drawn markers";
speciesLine.textContent = "4 Na⁺ + 4 Cl⁻";
formula.textContent = "Weighted cell contents: 8 ions";
note.textContent =
"The 27 site markers are ownership-weighted: corners contribute 1 ion, edges 3, faces 3, and the interior 1.";
coordinate.textContent =
"Click a category or an ion for its exact contribution.";
return;
}
const meta = categoryMeta[currentCategory];
const config = species[meta.species];
title.textContent = meta.label;
badge.textContent = meta.count;
badgeLabel.textContent = "drawn sites";
speciesLine.textContent = `${config.label} · ${meta.share} ownership each`;
formula.textContent = meta.formula;
note.textContent = meta.note;
coordinate.textContent =
`Class contribution: ${meta.count} × ${meta.share} = ` +
`${meta.formula.split("=").at(-1).trim()}`;
}
function setCategory(category) {
currentCategory = category;
selectedRecord = null;
hoverRing.visible = false;
document.querySelectorAll(".category-button").forEach((button) => {
const active = button.dataset.category === category;
button.classList.toggle("active", active);
button.setAttribute("aria-pressed", String(active));
});
document.querySelectorAll("tbody tr").forEach((row) => {
row.classList.toggle("active", row.dataset.category === category);
});
updateAppearance();
updateInspector();
}
document.querySelectorAll(".category-button").forEach((button) => {
button.addEventListener("click", () => {
setCategory(button.dataset.category);
});
});
document.querySelectorAll("tbody tr").forEach((row) => {
row.addEventListener("click", () => setCategory(row.dataset.category));
row.addEventListener("keydown", (event) => {
if (event.key === "Enter" || event.key === " ") {
event.preventDefault();
setCategory(row.dataset.category);
}
});
});
// Raycasting against instanced low-poly ions.
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
function recordAt(clientX, clientY) {
const rect = canvas.getBoundingClientRect();
pointer.x = ((clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
const intersections = raycaster.intersectObjects([
ionMeshes.Na,
ionMeshes.Cl
]);
for (const intersection of intersections) {
const mesh = intersection.object;
const record = mesh.userData.records[intersection.instanceId];
if (record) return record;
}
return null;
}
function showTooltip(record, clientX, clientY) {
const tooltip = $("tooltip");
const config = species[record.type];
if (record.central) {
const meta = categoryMeta[record.category];
tooltip.textContent =
`${config.label} · ${meta.label}\n` +
`Ownership: ${meta.share} per marker\n` +
`Class total: ${meta.formula}`;
} else {
tooltip.textContent =
`${config.label} · neighboring cell\n` +
`Not counted in the selected unit cell`;
}
tooltip.style.display = "block";
tooltip.style.left = `${Math.min(clientX + 13, window.innerWidth - 250)}px`;
tooltip.style.top = `${Math.min(clientY + 13, window.innerHeight - 80)}px`;
hoverRing.visible = true;
hoverRing.position.copy(record.position);
hoverRing.scale.setScalar(config.radius * 1.65);
hoverRing.material.color.setHex(config.color);
}
// Direct camera controls: no external controls addon.
let pointerDown = false;
let dragMode = "orbit";
let lastPointerX = 0;
let lastPointerY = 0;
let downPointerX = 0;
let downPointerY = 0;
const panRight = new THREE.Vector3();
const panUp = new THREE.Vector3();
canvas.addEventListener("pointerdown", (event) => {
pointerDown = true;
dragMode = event.button === 2 || event.shiftKey ? "pan" : "orbit";
lastPointerX = event.clientX;
lastPointerY = event.clientY;
downPointerX = event.clientX;
downPointerY = event.clientY;
canvas.setPointerCapture(event.pointerId);
$("tooltip").style.display = "none";
hoverRing.visible = false;
});
canvas.addEventListener("pointermove", (event) => {
if (pointerDown) {
const dx = event.clientX - lastPointerX;
const dy = event.clientY - lastPointerY;
if (dragMode === "orbit") {
view.theta -= dx * 0.006;
view.phi = THREE.MathUtils.clamp(
view.phi - dy * 0.006,
0.16,
Math.PI - 0.16
);
} else {
camera.updateMatrixWorld();
panRight.setFromMatrixColumn(camera.matrixWorld, 0);
panUp.setFromMatrixColumn(camera.matrixWorld, 1);
const panScale = view.radius * 0.00125;
view.target
.addScaledVector(panRight, -dx * panScale)
.addScaledVector(panUp, dy * panScale);
view.target.clampLength(0, 3.5);
}
lastPointerX = event.clientX;
lastPointerY = event.clientY;
return;
}
const record = recordAt(event.clientX, event.clientY);
if (record) {
showTooltip(record, event.clientX, event.clientY);
} else {
$("tooltip").style.display = "none";
hoverRing.visible = false;
}
});
canvas.addEventListener("pointerup", (event) => {
const movement = Math.hypot(
event.clientX - downPointerX,
event.clientY - downPointerY
);
pointerDown = false;
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
if (movement < 5) {
const record = recordAt(event.clientX, event.clientY);
selectedRecord = record;
updateAppearance();
updateInspector();
if (!record) {
$("tooltip").style.display = "none";
hoverRing.visible = false;
}
}
});
canvas.addEventListener("pointercancel", () => {
pointerDown = false;
});
canvas.addEventListener("pointerleave", () => {
if (!pointerDown) {
$("tooltip").style.display = "none";
hoverRing.visible = false;
}
});
canvas.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
view.radius = THREE.MathUtils.clamp(
view.radius * Math.exp(event.deltaY * 0.001),
4.8,
18
);
},
{ passive: false }
);
function resetView() {
view.theta = 0.72;
view.phi = 1.08;
view.radius = showNeighbors ? 10.2 : 6.4;
view.target.set(0, 0, 0);
}
$("resetButton").addEventListener("click", resetView);
$("rotateButton").addEventListener("click", () => {
autoRotate = !autoRotate;
$("rotateButton").classList.toggle("active", autoRotate);
});
$("neighborsToggle").addEventListener("change", (event) => {
showNeighbors = event.target.checked;
updateAppearance();
});
$("cellToggle").addEventListener("change", (event) => {
cellGroup.visible = event.target.checked;
});
window.addEventListener("keydown", (event) => {
if (event.target instanceof HTMLInputElement) return;
const keyMap = {
"0": "all",
"1": "corner",
"2": "edge",
"3": "face",
"4": "interior"
};
if (keyMap[event.key]) {
setCategory(keyMap[event.key]);
} else if (event.key.toLowerCase() === "r") {
resetView();
}
});
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
});
const clock = new THREE.Clock();
function animate() {
const dt = Math.min(clock.getDelta(), 0.05);
if (autoRotate && !pointerDown) {
view.theta += dt * 0.13;
}
const smoothing = 1 - Math.pow(0.001, dt);
actual.theta += (view.theta - actual.theta) * smoothing;
actual.phi += (view.phi - actual.phi) * smoothing;
actual.radius += (view.radius - actual.radius) * smoothing;
actual.target.lerp(view.target, smoothing);
updateCamera();
particles.rotation.y += dt * 0.008;
particles.rotation.x += dt * 0.003;
renderer.render(scene, camera);
}
setCategory("all");
renderer.setAnimationLoop(animate);
requestAnimationFrame(() => {
$("loading").classList.add("hidden");
setTimeout(() => $("loading").remove(), 350);
});
</script>
</body>
</html>
```