Mat2Bot / explore /viewer.js
Babu09's picture
Mat2Bot front: one box, the story (no engine code)
67fee72 verified
Raw History Blame Contribute Delete
14.3 kB
// 3D views for the explorer: measured crystal structures, and a beaker where salt dissolves and crystallises.
// three.js (MIT) is bundled under lib/. Every view pauses when it is off screen, and none moves on its own when the
// reader has asked for reduced motion.
import * as THREE from "three";
export const reducedMotion = matchMedia("(prefers-reduced-motion: reduce)").matches;
export function webglOK() {
try {
const c = document.createElement("canvas");
return !!(c.getContext("webgl2") || c.getContext("webgl"));
} catch {
return false;
}
}
const crystalCache = new Map();
export async function loadCrystal(name) {
if (!crystalCache.has(name)) crystalCache.set(name, fetch(`data/crystal-${name}.json`).then((r) => r.json()));
return crystalCache.get(name);
}
const ease = (t) => (t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2);
class Stage {
constructor(canvas, { fov = 32 } = {}) {
this.canvas = canvas;
this.renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: true, powerPreference: "low-power" });
this.renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
this.renderer.outputColorSpace = THREE.SRGBColorSpace;
this.renderer.toneMapping = THREE.ACESFilmicToneMapping;
this.scene = new THREE.Scene();
this.camera = new THREE.PerspectiveCamera(fov, 1, 0.1, 1000);
this.scene.add(new THREE.HemisphereLight(0xe8eeff, 0x20263f, 1.6));
const key = new THREE.DirectionalLight(0xffffff, 2.4);
key.position.set(6, 9, 8);
this.scene.add(key);
const rim = new THREE.DirectionalLight(0x7f9cff, 1.2);
rim.position.set(-7, -2, -6);
this.scene.add(rim);
this.onScreen = true;
this.running = true;
this.dirty = true;
new ResizeObserver(() => this.resize()).observe(canvas);
new IntersectionObserver((es) => { this.onScreen = es.some((e) => e.isIntersecting); }, { threshold: 0.01 }).observe(canvas);
this.resize();
this.frame = this.frame.bind(this);
requestAnimationFrame(this.frame);
}
resize() {
const w = this.canvas.clientWidth || 320;
const h = this.canvas.clientHeight || 320;
this.renderer.setSize(w, h, false);
this.camera.aspect = w / h;
this.camera.updateProjectionMatrix();
this.fit();
this.dirty = true;
}
fit() {}
tick() { return false; }
pause() { this.running = false; }
play() { this.running = true; this.last = undefined; this.dirty = true; }
frame(t) {
requestAnimationFrame(this.frame);
if (!this.onScreen || !this.running) return;
const dt = Math.min(0.05, (t - (this.last ?? t)) / 1000);
this.last = t;
if (this.tick(dt, t) || this.dirty) {
this.renderer.render(this.scene, this.camera);
this.dirty = false;
}
}
// drag to turn (a vertical swipe still scrolls the page on a phone)
draggable(target) {
let down = null;
const el = this.canvas;
el.style.touchAction = "pan-y";
el.addEventListener("pointerdown", (e) => { down = { x: e.clientX, y: e.clientY }; this.held = true; });
window.addEventListener("pointerup", () => { down = null; this.held = false; });
el.addEventListener("pointermove", (e) => {
if (!down) return;
target.rotation.y += (e.clientX - down.x) * 0.01;
target.rotation.x = Math.max(-1.2, Math.min(1.2, target.rotation.x + (e.clientY - down.y) * 0.006));
down = { x: e.clientX, y: e.clientY };
this.dirty = true;
});
}
}
function buildCrystal(d) {
const g = new THREE.Group();
const sphere = new THREE.SphereGeometry(1, 36, 24);
const byElement = {};
for (const [el, x, y, z] of d.atoms) (byElement[el] ||= []).push([x, y, z]);
const m = new THREE.Matrix4();
for (const [el, pts] of Object.entries(byElement)) {
const st = d.style[el];
const mat = new THREE.MeshStandardMaterial({ color: st.color, roughness: 0.32, metalness: 0.08, emissive: st.color, emissiveIntensity: 0.06 });
const mesh = new THREE.InstancedMesh(sphere, mat, pts.length);
pts.forEach((p, i) => { m.makeScale(st.r, st.r, st.r); m.setPosition(p[0], p[1], p[2]); mesh.setMatrixAt(i, m); });
g.add(mesh);
}
if (d.bonds.length) {
const cyl = new THREE.CylinderGeometry(0.085, 0.085, 1, 12, 1, true);
const mat = new THREE.MeshStandardMaterial({ color: 0xd7deeb, roughness: 0.45, metalness: 0.15 });
const mesh = new THREE.InstancedMesh(cyl, mat, d.bonds.length);
const up = new THREE.Vector3(0, 1, 0), a = new THREE.Vector3(), b = new THREE.Vector3(), mid = new THREE.Vector3();
const dir = new THREE.Vector3(), q = new THREE.Quaternion(), s = new THREE.Vector3();
d.bonds.forEach(([i, j], k) => {
a.set(d.atoms[i][1], d.atoms[i][2], d.atoms[i][3]);
b.set(d.atoms[j][1], d.atoms[j][2], d.atoms[j][3]);
mid.addVectors(a, b).multiplyScalar(0.5);
dir.subVectors(b, a);
s.set(1, dir.length(), 1);
q.setFromUnitVectors(up, dir.normalize());
m.compose(mid, q, s);
mesh.setMatrixAt(k, m);
});
g.add(mesh);
}
const pos = [];
for (const [p, q] of d.edges) pos.push(...p, ...q);
const lines = new THREE.BufferGeometry();
lines.setAttribute("position", new THREE.Float32BufferAttribute(pos, 3));
g.add(new THREE.LineSegments(lines, new THREE.LineBasicMaterial({ color: 0xa9bbff, transparent: true, opacity: 0.4 })));
let r = 0;
for (const [el, x, y, z] of d.atoms) r = Math.max(r, Math.hypot(x, y, z) + d.style[el].r);
g.userData.radius = r;
return g;
}
export class CrystalView extends Stage {
constructor(canvas, { autoRotate = true, speed = 0.22, zoom = 1 } = {}) {
super(canvas);
this.auto = autoRotate && !reducedMotion;
this.speed = speed;
this.zoom = zoom;
this.turn = new THREE.Group();
this.turn.rotation.set(0.42, -0.62, 0);
this.scene.add(this.turn);
this.draggable(this.turn);
this.current = null;
this.swap = null;
}
async show(name) {
const d = await loadCrystal(name);
if (this.current?.userData.name === name) return;
const g = buildCrystal(d);
g.userData.name = name;
g.scale.setScalar(reducedMotion ? 1 : 0.001);
this.turn.add(g);
this.swap = { from: this.current, to: g, t: reducedMotion ? 1 : 0 };
this.current = g;
this.fit();
this.dirty = true;
return d;
}
fit() {
const r = this.current?.userData.radius || 6;
const vfov = (this.camera.fov * Math.PI) / 180;
const hfov = 2 * Math.atan(Math.tan(vfov / 2) * this.camera.aspect);
const dist = (r / Math.sin(Math.min(vfov, hfov) / 2)) * 1.04 / this.zoom;
this.camera.position.set(0, 0, dist);
this.camera.lookAt(0, 0, 0);
this.camera.near = dist / 50;
this.camera.far = dist * 4;
this.camera.updateProjectionMatrix();
}
tick(dt, now) {
let moved = false;
if (this.swap) {
const s = this.swap;
s.t0 ??= now;
s.t = reducedMotion ? 1 : Math.min(1, (now - s.t0) / 700); // by the clock: as quick on a slow device
const k = ease(s.t);
s.to.scale.setScalar(Math.max(0.001, k));
if (s.from) s.from.scale.setScalar(Math.max(0.001, 1 - k));
if (s.t >= 1) {
if (s.from) this.turn.remove(s.from);
this.swap = null;
}
moved = true;
}
if (this.auto && !this.held) {
this.turn.rotation.y += dt * this.speed;
moved = true;
}
return moved;
}
}
// A beaker of salt water: hot, every ion wanders; cooled, the extra salt has nowhere to go and the ions lock into a
// rock-salt crystal, layer by layer, while some stay dissolved.
export class Beaker extends Stage {
constructor(canvas, { onTemperature = () => {} } = {}) {
super(canvas, { fov: 30 });
this.onTemperature = onTemperature;
this.R = 2.6;
this.H = 5.2;
this.group = new THREE.Group();
this.scene.add(this.group);
this.draggable(this.group);
const glass = new THREE.MeshStandardMaterial({ color: 0xbfd4ff, transparent: true, opacity: 0.13, roughness: 0.1, metalness: 0, side: THREE.DoubleSide, depthWrite: false });
const wall = new THREE.Mesh(new THREE.CylinderGeometry(this.R, this.R, this.H, 64, 1, true), glass);
this.group.add(wall);
const base = new THREE.Mesh(new THREE.CircleGeometry(this.R, 64), glass);
base.rotation.x = -Math.PI / 2;
base.position.y = -this.H / 2;
this.group.add(base);
const rim = new THREE.Mesh(new THREE.TorusGeometry(this.R, 0.05, 12, 96), new THREE.MeshStandardMaterial({ color: 0xdbe6ff, roughness: 0.2 }));
rim.rotation.x = Math.PI / 2;
rim.position.y = this.H / 2;
this.group.add(rim);
this.level = this.H / 2 - 0.9;
this.water = new THREE.Mesh(new THREE.CylinderGeometry(this.R - 0.02, this.R - 0.02, this.level + this.H / 2, 64, 1, false),
new THREE.MeshStandardMaterial({ color: 0x4f8dff, transparent: true, opacity: 0.12, roughness: 0.05, depthWrite: false }));
this.water.position.y = (this.level - this.H / 2) / 2;
this.group.add(this.water);
// the crystal's sites (rock salt: neighbours alternate) and the ions
const n = 4, a = 0.64;
this.sites = [];
for (let j = 0; j < n; j++) for (let i = 0; i < n; i++) for (let k = 0; k < n; k++) {
this.sites.push({ p: new THREE.Vector3((i - (n - 1) / 2) * a, -this.H / 2 + 0.38 + j * a, (k - (n - 1) / 2) * a), type: (i + j + k) % 2 });
}
const ions = [];
for (const s of this.sites) ions.push({ type: s.type, site: s });
for (let i = 0; i < 24; i++) ions.push({ type: i % 2, site: null }); // these stay dissolved
const sph = new THREE.SphereGeometry(1, 20, 14);
this.mesh = [0, 1].map((t) => {
const mat = new THREE.MeshStandardMaterial({ color: t ? 0x43d17a : 0xb77cff, roughness: 0.3, metalness: 0.05, emissive: t ? 0x43d17a : 0xb77cff, emissiveIntensity: 0.12 });
const count = ions.filter((x) => x.type === t).length;
const mesh = new THREE.InstancedMesh(sph, mat, count);
this.group.add(mesh);
return mesh;
});
this.ions = ions.map((x) => ({ ...x, pos: this.randomPoint(), vel: new THREE.Vector3(), r: x.type ? 0.235 : 0.18, delay: 0, home: 0 })); // Cl- larger than K+
const edges = [];
for (const s of this.sites) for (const o of this.sites) {
const d = s.p.distanceTo(o.p);
if (d > a * 0.99 && d < a * 1.01 && s.p.x + s.p.y * 7 + s.p.z * 49 < o.p.x + o.p.y * 7 + o.p.z * 49) edges.push(s.p.x, s.p.y, s.p.z, o.p.x, o.p.y, o.p.z);
}
const lg = new THREE.BufferGeometry();
lg.setAttribute("position", new THREE.Float32BufferAttribute(edges, 3));
this.lattice = new THREE.LineSegments(lg, new THREE.LineBasicMaterial({ color: 0xf2f5ff, transparent: true, opacity: 0 }));
this.group.add(this.lattice);
this.cold = false;
this.T = 60;
this.group.rotation.set(0.32, 0.5, 0);
this.m = new THREE.Matrix4();
this.place();
}
randomPoint() {
const r = Math.sqrt(Math.random()) * (this.R - 0.45), th = Math.random() * Math.PI * 2;
return new THREE.Vector3(r * Math.cos(th), -this.H / 2 + 0.4 + Math.random() * (this.level + this.H / 2 - 0.8), r * Math.sin(th));
}
fit() {
this.camera.position.set(0, 0.6, 15.5 / Math.min(1, this.camera.aspect * 1.05));
this.camera.lookAt(0, -0.2, 0);
}
cool() {
if (this.cold) return;
this.cold = true;
const order = this.ions.filter((x) => x.site).sort((p, q) => p.site.p.y - q.site.p.y || p.site.p.length() - q.site.p.length());
order.forEach((x, i) => { x.delay = reducedMotion ? 0 : 0.2 + i * 0.04; x.home = 0; });
this.since = performance.now();
this.tempFrom = this.T; this.tempTo = 20; this.tempT = reducedMotion ? 1 : 0;
}
heat() {
if (!this.cold) return;
this.cold = false;
for (const x of this.ions) { x.home = 0; x.vel.set((Math.random() - 0.5) * 2, Math.random() * 1.5, (Math.random() - 0.5) * 2); }
this.since = performance.now();
this.tempFrom = this.T; this.tempTo = 60; this.tempT = reducedMotion ? 1 : 0;
}
place() {
const count = [0, 0];
for (const x of this.ions) {
this.m.makeScale(x.r, x.r, x.r);
this.m.setPosition(x.pos);
this.mesh[x.type].setMatrixAt(count[x.type]++, this.m);
}
this.mesh.forEach((m) => { m.instanceMatrix.needsUpdate = true; });
}
tick(dt, now) {
const since = (now - (this.since ?? now)) / 1000; // seconds since the last cool or heat, by the clock
const step = Math.min(0.25, (now - (this.prev ?? now)) / 1000);
this.prev = now;
if (this.tempT !== undefined && this.tempT < 1) {
this.tempT = reducedMotion ? 1 : Math.min(1, since / 2.6);
this.T = this.tempFrom + (this.tempTo - this.tempFrom) * ease(this.tempT);
this.onTemperature(this.T);
}
let settled = 0;
const speed = 0.6 + (this.T - 20) / 40 * 1.4;
const lo = -this.H / 2 + 0.35, hi = this.level - 0.3;
for (const x of this.ions) {
if (this.cold && x.site) {
if (since >= x.delay) {
x.home = Math.min(1, x.home + step * 1.6);
x.pos.lerp(x.site.p, reducedMotion ? 1 : 1 - Math.exp(-step * 5 * (0.3 + x.home)));
if (x.pos.distanceTo(x.site.p) < 0.05) settled++;
continue;
}
}
x.vel.x += (Math.random() - 0.5) * 9 * dt * speed;
x.vel.y += (Math.random() - 0.5) * 9 * dt * speed;
x.vel.z += (Math.random() - 0.5) * 9 * dt * speed;
x.vel.multiplyScalar(Math.exp(-dt * 1.6));
x.pos.addScaledVector(x.vel, dt * speed);
const rr = Math.hypot(x.pos.x, x.pos.z), max = this.R - 0.4;
if (rr > max) { x.pos.x *= max / rr; x.pos.z *= max / rr; x.vel.x *= -0.6; x.vel.z *= -0.6; }
if (x.pos.y < lo) { x.pos.y = lo; x.vel.y = Math.abs(x.vel.y); }
if (x.pos.y > hi) { x.pos.y = hi; x.vel.y = -Math.abs(x.vel.y); }
}
const crystal = this.sites.length;
const want = this.cold ? Math.max(0, (settled - crystal * 0.6) / (crystal * 0.4)) * 0.85 : 0;
this.lattice.material.opacity += (want - this.lattice.material.opacity) * Math.min(1, step * 4);
this.lattice.visible = this.lattice.material.opacity > 0.01; // a line at zero opacity still shows in some renderers
if (!reducedMotion && !this.held) this.group.rotation.y += dt * 0.12;
this.place();
return true;
}
}