From c254062c1fe1bc15608210fc1a022aac7205eb42 Mon Sep 17 00:00:00 2001 From: Henry Date: Sat, 31 Oct 2026 15:11:02 +0800 Subject: [PATCH 1/4] Rename the project to CellSim: repository, site and the lab's screens The repository becomes Rockman6/CellSim, so the site moves to rockman6.github.io/CellSim/. Links in the README, the landing page, pyproject.toml, the conda-forge recipe and the lab's credits point there. The lab's title, loading screen and README say CellSim, and "Cell Sim" is spelled one way throughout. OLD/ and docs/archive/ keep the old name as the record they are; GitHub forwards those links. --- CHANGELOG.md | 4 ++++ README.md | 10 +++++----- packaging/conda-forge/meta.yaml | 6 +++--- pyproject.toml | 4 ++-- web/index.html | 6 +++--- web/lab3d/README.md | 14 +++++++------- web/lab3d/index.html | 14 +++++++------- web/lab3d/js/culture.js | 2 +- web/lab3d/js/engine-worker.js | 2 +- web/lab3d/js/engine.js | 8 ++++---- web/lab3d/js/journal.js | 4 ++-- web/lab3d/js/lab_engine.py | 2 +- web/lab3d/js/main.js | 12 ++++++------ web/lab3d/js/scope.js | 2 +- web/lab3d/js/tasks.js | 2 +- 15 files changed, 48 insertions(+), 44 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index be84a41..b4af1ab 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,10 @@ worker from the wheel the Lab installs, and the drops added in the lab set the dose (two 50 µL drops of 10 µM paclitaxel in 5.1 mL give 0.196 µM). Graphics presets from Low (older laptops, 30 fps) to Ultra. +**The repository is now `Rockman6/CellSim`**, and the site moved with it +to . GitHub forwards links to the +old repository name; links to the old site address no longer work. + ## 1.7.0 — a CDK4/6 inhibitor, and Rb as the mechanism **Palbociclib** (`mechanism = "cdk46"`): blocks cyclin D–CDK4/6, so Rb diff --git a/README.md b/README.md index 1c2e400..ea00c2e 100755 --- a/README.md +++ b/README.md @@ -4,9 +4,9 @@ simulator in Python. Open source, Apple-silicon and Linux, no GPU required.** -[![The 3D lab: a microscope bench and an incubator, with daylight through the windows](web/lab3d/screenshot.jpg)](https://rockman6.github.io/CellSim-3D-Multicellular-Biology-Drug-Testing-Simulator/lab3d/) +[![The 3D lab: a microscope bench and an incubator, with daylight through the windows](web/lab3d/screenshot.jpg)](https://rockman6.github.io/CellSim/lab3d/) -**[Walk into the lab →](https://rockman6.github.io/CellSim-3D-Multicellular-Biology-Drug-Testing-Simulator/lab3d/)** +**[Walk into the lab →](https://rockman6.github.io/CellSim/lab3d/)** — a biology lab you explore in first person, in your browser. Prepare slides of onion skin, your own cheek cells or a pondweed leaf and focus the microscope on them. Or treat living lung cancer cells with @@ -17,11 +17,11 @@ walk, left-click to take, right-click to use. Graphics presets run from older laptops to fast graphics cards. Source and controls: [`web/lab3d/`](web/lab3d/). -**[Run an experiment in your browser →](https://rockman6.github.io/CellSim-3D-Multicellular-Biology-Drug-Testing-Simulator/lab/)** +**[Run an experiment in your browser →](https://rockman6.github.io/CellSim/lab/)** — pick cells, a drug and a schedule, press Run. The real engine runs on your own machine; nothing to install. -**[Watch inside one cell →](https://rockman6.github.io/CellSim-3D-Multicellular-Biology-Drug-Testing-Simulator/lab/cell.html)** +**[Watch inside one cell →](https://rockman6.github.io/CellSim/lab/cell.html)** — every molecule the engine tracks, minute by minute, as a cell divides, arrests or dies. Type any drug name or structure: a drug whose target the engine models runs (labelled uncalibrated), any other is refused by name, @@ -29,7 +29,7 @@ and an impossible structure is rejected with the atom that breaks it. Or design your own: block or boost any molecule on the map and see what the cell does. -**[Open a simulated spheroid →](https://rockman6.github.io/CellSim-3D-Multicellular-Biology-Drug-Testing-Simulator/)** +**[Open a simulated spheroid →](https://rockman6.github.io/CellSim/)** (no install; the demo runs are simulated fresh on every deploy, so they show what the current code produces) diff --git a/packaging/conda-forge/meta.yaml b/packaging/conda-forge/meta.yaml index 94b316c..2a05979 100644 --- a/packaging/conda-forge/meta.yaml +++ b/packaging/conda-forge/meta.yaml @@ -65,7 +65,7 @@ test: - python {{ python_min }} about: - home: https://github.com/Rockman6/CellSim-3D-Multicellular-Biology-Drug-Testing-Simulator + home: https://github.com/Rockman6/CellSim summary: Mechanistic simulator of cultured cells under drug, with measured errors description: | CellSim simulates cultured cancer cells responding to a drug, from the @@ -82,8 +82,8 @@ about: license: MIT license_family: MIT license_file: LICENSE - doc_url: https://github.com/Rockman6/CellSim-3D-Multicellular-Biology-Drug-Testing-Simulator/blob/main/docs/VALIDATION.md - dev_url: https://github.com/Rockman6/CellSim-3D-Multicellular-Biology-Drug-Testing-Simulator + doc_url: https://github.com/Rockman6/CellSim/blob/main/docs/VALIDATION.md + dev_url: https://github.com/Rockman6/CellSim extra: recipe-maintainers: diff --git a/pyproject.toml b/pyproject.toml index dac85d9..561625b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -40,8 +40,8 @@ dependencies = ["numpy>=1.24", "scipy>=1.10"] plots = ["matplotlib>=3.7"] # cellsim.cell.viewer only [project.urls] -Homepage = "https://github.com/Rockman6/CellSim-3D-Multicellular-Biology-Drug-Testing-Simulator" -Changelog = "https://github.com/Rockman6/CellSim-3D-Multicellular-Biology-Drug-Testing-Simulator/blob/main/CHANGELOG.md" +Homepage = "https://github.com/Rockman6/CellSim" +Changelog = "https://github.com/Rockman6/CellSim/blob/main/CHANGELOG.md" [project.scripts] cellsim = "cellsim.cli:main" diff --git a/web/index.html b/web/index.html index dd52609..7b6ed6a 100644 --- a/web/index.html +++ b/web/index.html @@ -115,9 +115,9 @@

How far to trust it

development when re-measuring showed one rested on a single surviving lineage and the other on one random seed.

The viewer renders simulation output and runs no biology of its own.
diff --git a/web/lab3d/README.md b/web/lab3d/README.md index d062d47..367a4b1 100644 --- a/web/lab3d/README.md +++ b/web/lab3d/README.md @@ -1,13 +1,13 @@ -# CellSim Lab +# CellSim -A biology lab you walk into in first person. Prepare slides of onion skin, cheek cells or a pondweed leaf, then focus a microscope on them. Or grow living A549 lung cancer cells, treat them with a drug and incubate them. The living cells are simulated by the Cell Sim engine (`cellsim.cell.dish`), running in the browser. +A biology lab you walk into in first person. Prepare slides of onion skin, cheek cells or a pondweed leaf, then focus a microscope on them. Or grow living A549 lung cancer cells, treat them with a drug and incubate them. The living cells are simulated by the CellSim engine (`cellsim.cell.dish`), running in the browser. ## Run it Browsers block 3D models and the engine on pages opened straight from a file, so serve the `web` folder: ```bash -cd "Cell Sim/web" +cd CellSim/web python3 -m http.server 8000 ``` @@ -16,7 +16,7 @@ Then open . The engine uses the wheel in `../lab/wheel/` (the same one the Lab page uses). GitHub Pages builds it on every deploy. To build it locally: ```bash -cd "Cell Sim" +cd CellSim python -m pip wheel --no-deps --no-build-isolation -w web/lab/wheel . cd web/lab/wheel && ls -t cellsim-*-py3-none-any.whl | head -1 > LATEST ``` @@ -57,7 +57,7 @@ Settings → Graphics: **Auto** picks a preset from the graphics chip. | High | Sharper shadows, four lamps | | Ultra | Full resolution, 4096 px shadows, all six lamps, no frame cap | -The game stops drawing when nothing moves, and the Cell Sim engine (about 150 MB of memory) only loads once a culture dish needs it. +The game stops drawing when nothing moves, and the CellSim engine (about 150 MB of memory) only loads once a culture dish needs it. ## What's where @@ -70,7 +70,7 @@ The game stops drawing when nothing moves, and the Cell Sim engine (about 150 MB | `js/props.js` | Equipment built in code: slides, bottles, beakers, dishes, the pondweed tank, tools | | `js/liquids.js` | Volumes, colour mixing and drug dilution | | `js/scope.js`, `js/specimens.js`, `js/culture.js` | The view through the eyepiece | -| `js/engine.js`, `js/engine-worker.js`, `js/lab_engine.py` | The Cell Sim engine, in a background worker | +| `js/engine.js`, `js/engine-worker.js`, `js/lab_engine.py` | The CellSim engine, in a background worker | | `js/tasks.js`, `js/journal.js` | Experiments and the lab journal | | `assets/` | Models, textures and lighting (`downloads/` holds the raw Sketchfab files and is not committed) | @@ -81,7 +81,7 @@ The game stops drawing when nothing moves, and the Cell Sim engine (about 150 MB ## Credits -- **Cell engine:** Cell Sim (MIT), in the browser via Pyodide. +- **Cell engine:** CellSim (MIT), in the browser via Pyodide. - **3D engine:** three.js r160 (MIT). - **Poly Haven (CC0):** yellow onion, metal stool, steel shelves, fluorescent lights, drawer cabinet, clipboard, stationery, wall clock, magnifying glass, binder notebook, metal office desk, floor tiles, painted plaster, and the hospital room HDRI. - **Sketchfab (CC Attribution 4.0):** diff --git a/web/lab3d/index.html b/web/lab3d/index.html index 3c9b2aa..184c4a1 100644 --- a/web/lab3d/index.html +++ b/web/lab3d/index.html @@ -3,8 +3,8 @@ - -CellSim Lab + +CellSim @@ -35,9 +35,9 @@ + + + + + + diff --git a/web/lab3d/js/assets.js b/web/lab3d/js/assets.js index 02fea8c..f3a0b32 100644 --- a/web/lab3d/js/assets.js +++ b/web/lab3d/js/assets.js @@ -3,6 +3,7 @@ import * as THREE from "three"; import { GLTFLoader } from "three/addons/loaders/GLTFLoader.js"; import { OBJLoader } from "three/addons/loaders/OBJLoader.js"; import { RGBELoader } from "three/addons/loaders/RGBELoader.js"; +import { mergeGeometries } from "three/addons/utils/BufferGeometryUtils.js"; // Poly Haven models (CC0), glTF at 1k textures. const GLTF = ["yellow_onion", "metal_stool_01", "steel_frame_shelves_01", "mounted_fluorescent_lights", "drawer_cabinet", @@ -85,7 +86,42 @@ export function link(object, key, value) { Object.defineProperty(object.userData, key, { value, writable: true, configurable: true, enumerable: false }); } +/* Merge every mesh under a static object that shares a material into one, + baking in their transforms: a ceiling light made of 14 parts becomes 3 + draws. Only for things that never move part by part. */ +export function flatten(object) { + object.updateMatrixWorld(true); + const inv = new THREE.Matrix4().copy(object.matrixWorld).invert(); + const byMat = new Map(), all = []; + object.traverse((m) => { + if (!m.isMesh || m.isInstancedMesh || Array.isArray(m.material)) return; + all.push(m); + if (!byMat.has(m.material)) byMat.set(m.material, []); + byMat.get(m.material).push(m); + }); + if (all.length < 3) return object; + const out = []; + for (const [mat, list] of byMat) { + const geos = list.map((m) => { + const geo = (m.geometry.index ? m.geometry.toNonIndexed() : m.geometry.clone()).applyMatrix4(new THREE.Matrix4().multiplyMatrices(inv, m.matrixWorld)); + for (const k of Object.keys(geo.attributes)) if (!["position", "normal", "uv"].includes(k)) geo.deleteAttribute(k); + if (!geo.attributes.uv) geo.setAttribute("uv", new THREE.Float32BufferAttribute(new Float32Array(geo.attributes.position.count * 2), 2)); + if (!geo.attributes.normal) geo.computeVertexNormals(); + return geo; + }); + const merged = mergeGeometries(geos, false); + if (!merged) return object; + const mm = new THREE.Mesh(merged, mat); + mm.castShadow = list.some((m) => m.castShadow); mm.receiveShadow = true; + out.push(mm); + } + while (object.children.length) object.remove(object.children[0]); + for (const m of out) object.add(m); + return object; +} + export function enableShadows(object) { - object.traverse((m) => { if (m.isMesh) { m.castShadow = true; m.receiveShadow = true; } }); + // Not the soft contact shadows or the invisible aiming boxes: they would cast square shadows. + object.traverse((m) => { if (m.isMesh && m.name !== "shadow" && m.name !== "hitbox") { m.castShadow = true; m.receiveShadow = true; } }); return object; } diff --git a/web/lab3d/js/audio.js b/web/lab3d/js/audio.js new file mode 100644 index 0000000..afe786c --- /dev/null +++ b/web/lab3d/js/audio.js @@ -0,0 +1,71 @@ +// Sound effects, made in code (no files to download): footsteps on a tiled +// floor, picking things up and putting them down, glass, a drip, a pipette +// click. The audio context starts on your first click, as browsers require. +import { settings } from "./settings.js"; + +let ctx = null, master = null, noise = null; + +export function unlockAudio() { + if (ctx || !settings.sound) return; + try { + ctx = new (window.AudioContext || window.webkitAudioContext)(); + master = ctx.createGain(); + master.gain.value = 0.55; + master.connect(ctx.destination); + // One second of white noise, reused by every footstep. + noise = ctx.createBuffer(1, ctx.sampleRate, ctx.sampleRate); + const d = noise.getChannelData(0); + for (let i = 0; i < d.length; i++) d[i] = Math.random() * 2 - 1; + } catch (e) { ctx = null; } +} + +function ready() { + if (!settings.sound || !ctx) return false; + if (ctx.state === "suspended") ctx.resume(); + return true; +} + +function env(gain, t, attack, decay, peak) { + gain.gain.setValueAtTime(0.0001, t); + gain.gain.exponentialRampToValueAtTime(peak, t + attack); + gain.gain.exponentialRampToValueAtTime(0.0001, t + attack + decay); +} + +function burst({ f = 1200, q = 1.2, peak = 0.2, decay = 0.07, offset = Math.random() * 0.8 } = {}) { + const t = ctx.currentTime; + const src = ctx.createBufferSource(), bp = ctx.createBiquadFilter(), g = ctx.createGain(); + src.buffer = noise; + bp.type = "bandpass"; bp.frequency.value = f; bp.Q.value = q; + env(g, t, 0.004, decay, peak); + src.connect(bp).connect(g).connect(master); + src.start(t, offset, decay + 0.02); +} + +function tone({ f = 800, to = f, type = "sine", peak = 0.12, decay = 0.08, attack = 0.003 } = {}) { + const t = ctx.currentTime; + const o = ctx.createOscillator(), g = ctx.createGain(); + o.type = type; + o.frequency.setValueAtTime(f, t); + if (to !== f) o.frequency.exponentialRampToValueAtTime(to, t + attack + decay); + env(g, t, attack, decay, peak); + o.connect(g).connect(master); + o.start(t); o.stop(t + attack + decay + 0.03); +} + +export const sfx = { + // A shoe on hard floor tiles: a low thud and a short, bright scuff. + step(loud = 0.6) { + if (!ready()) return; + const v = 0.06 + loud * 0.12; + burst({ f: 180 + Math.random() * 60, q: 0.9, peak: v, decay: 0.05 }); + burst({ f: 2200 + Math.random() * 900, q: 1.6, peak: v * 0.35, decay: 0.035 }); + }, + take() { if (ready()) { burst({ f: 900, q: 2, peak: 0.08, decay: 0.04 }); tone({ f: 520, to: 700, peak: 0.04, decay: 0.05 }); } }, + place() { if (ready()) burst({ f: 420, q: 1.4, peak: 0.16, decay: 0.06 }); }, + glass() { if (ready()) { tone({ f: 3100 + Math.random() * 300, type: "sine", peak: 0.05, decay: 0.18 }); tone({ f: 4700, peak: 0.02, decay: 0.12 }); } }, + drip() { if (ready()) tone({ f: 1500, to: 520, peak: 0.08, decay: 0.07 }); }, + click() { if (ready()) { burst({ f: 3200, q: 3, peak: 0.07, decay: 0.02 }); tone({ f: 1900, peak: 0.03, decay: 0.03 }); } }, + pour() { if (ready()) burst({ f: 700, q: 0.6, peak: 0.07, decay: 0.45 }); }, + ok() { if (ready()) { tone({ f: 880, peak: 0.05, decay: 0.09 }); setTimeout(() => ready() && tone({ f: 1320, peak: 0.045, decay: 0.12 }), 90); } }, + warn() { if (ready()) tone({ f: 330, to: 260, type: "triangle", peak: 0.06, decay: 0.14 }); }, +}; diff --git a/web/lab3d/js/finder.js b/web/lab3d/js/finder.js new file mode 100644 index 0000000..92d9eb2 --- /dev/null +++ b/web/lab3d/js/finder.js @@ -0,0 +1,237 @@ +// Find anything in the lab by name, typos and all. Every item and every piece +// of furniture is scored against what you typed: whole words, the start of a +// word, and spelling mistakes (one wrong, missing, extra or swapped letter in +// every four still matches). Each result says where the thing is now. +import * as THREE from "three"; + +// Other words people use for things, by item or furniture kind. +const ALIASES = { + goggles: ["safety glasses", "glasses", "eye protection"], + sink: ["tap", "faucet", "wash hands", "water"], + microscope: ["scope", "eyepiece", "magnify"], + incubator: ["cells", "culture", "warm", "37"], + glassbin: ["bin", "trash", "waste", "rubbish", "garbage", "sharps"], + dropper: ["stain", "bottle", "drops"], + stock: ["refill", "reagent", "big bottle"], + drug: ["medicine", "chemo", "cytotoxic", "treatment"], + dish: ["cells", "culture", "petri dish", "cancer cells", "a549"], + plate: ["6 well plate", "well plate", "wells", "multiwell"], + pipette: ["pipette", "pipettor", "p200"], + tipbox: ["pipette tips", "tips"], + tipwaste: ["tip bin", "waste", "used tips"], + platereader: ["reader", "plate reader", "viability", "results"], + hemocytometer: ["haemocytometer", "counting chamber", "neubauer", "cell counter"], + tube: ["microtube", "eppendorf", "tube"], + trypsin: ["detach", "trypsin edta"], + tank: ["elodea", "pondweed", "plant", "leaf", "aquarium"], + onion: ["bulb", "vegetable"], + redonion: ["red onion", "purple onion", "osmosis"], + rootonion: ["roots", "root tip", "mitosis", "growing onion"], + waterbath: ["water bath", "heater", "60"], + watchglass: ["watch glass", "acid dish"], + slidebox: ["slides", "glass slide", "microscope slide"], + slide: ["glass slide", "microscope slide"], + coverbox: ["coverslip", "cover slips", "cover glass"], + coverslip: ["coverslip", "cover glass"], + towels: ["tissue", "paper", "blot", "kitchen roll"], + swabcup: ["cotton bud", "q tip", "swab", "cotton swab"], + swab: ["cotton bud", "q tip"], + forceps: ["tweezers", "pincers", "tongs"], + scalpel: ["knife", "blade", "cutter"], + lens: ["magnifying glass", "magnifier"], + pencilcup: ["pen", "pencil", "marker"], + pencil: ["pen", "marker"], + sanitizer: ["hand gel", "alcohol gel", "clean hands"], + journal: ["notebook", "notes", "results", "data"], + clipboard: ["method", "instructions", "worksheet"], + beaker: ["glass", "container", "cup"], + tile: ["white tile", "work surface"], + drawer: ["spares", "storage", "cabinet"], + stool: ["chair", "seat"], + door: ["exit", "leave", "way out"], + switch: ["lights", "lamp", "light switch"], + clock: ["time"], + whiteboard: ["board", "method", "instructions"], + blinds: ["window", "curtain", "shade", "sunlight"], +}; + +export function norm(s) { + return String(s).toLowerCase().normalize("NFKD").replace(/[̀-ͯ]/g, "").replace(/[^a-z0-9µ ]+/g, " ").replace(/\s+/g, " ").trim(); +} + +// Optimal string alignment distance: Levenshtein plus swapped neighbours. +function osa(a, b) { + const m = a.length, n = b.length; + if (!m) return n; + if (!n) return m; + let p2 = null, p1 = Array.from({ length: n + 1 }, (_, j) => j), cur; + for (let i = 1; i <= m; i++) { + cur = [i]; + for (let j = 1; j <= n; j++) { + const cost = a[i - 1] === b[j - 1] ? 0 : 1; + let v = Math.min(p1[j] + 1, cur[j - 1] + 1, p1[j - 1] + cost); + if (p2 && i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) v = Math.min(v, p2[j - 2] + 1); + cur[j] = v; + } + p2 = p1; p1 = cur; + } + return p1[n]; +} + +// How well one typed word matches one word of a name: 1 is exact. +function wordScore(q, w) { + if (q === w) return 1; + if (w.startsWith(q)) return q.length >= 3 ? 0.96 : 0.7 + 0.08 * q.length; + const full = 1 - osa(q, w) / Math.max(q.length, w.length); + let pre = 0; + if (q.length >= 3) for (const len of [q.length - 1, q.length, q.length + 1]) { + if (len < 2 || len > w.length) continue; + pre = Math.max(pre, 1 - osa(q, w.slice(0, len)) / Math.max(q.length, len)); + } + return Math.max(full, pre * 0.93); +} + +export function similarity(query, terms) { + const q = norm(query); + if (!q) return 0; + const qWords = q.split(" "), qJoined = q.replace(/ /g, ""); + let best = 0; + for (const t of terms) { + if (t === q) return 1; + let s = t.includes(q) ? 0.94 : 0; + const tJoined = t.replace(/ /g, ""); + s = Math.max(s, 1 - osa(qJoined, tJoined) / Math.max(qJoined.length, tJoined.length)); + const words = t.split(" "); + let sum = 0; + for (const a of qWords) { let m = 0; for (const w of words) m = Math.max(m, wordScore(a, w)); sum += m; } + s = Math.max(s, (sum / qWords.length) * 0.97); + best = Math.max(best, s); + } + return best; +} + +/* ---------- where things are ---------- */ +const PLACES = { + drawer: "against the back wall: spare slides, cover slips and stains", sink: "set into the big bench", + door: "in the corner by the whiteboard", switch: "on the wall by the door", clock: "on the wall above the big bench", + whiteboard: "on the wall by the teacher's desk", blinds: "on the windows", glassbin: "on the floor by the bench arm", stool: "by the benches", +}; + +function zone(game, p) { + const room = game.room; + if (p.y < 0.15) return "on the floor"; + if (Math.abs(p.y - room.TABLE_Y) < 0.12 && (p.z < -1.25 || p.x < -3.95)) { + if (p.x > -1.1 && p.z < -1.6) return "on the big bench, by the sink"; + if (p.x < -3.95) return "on the big bench, by the windows"; + return "on the big bench"; + } + const B = room.BENCH; + if (Math.abs(p.x - B.x) < B.w / 2 + 0.1 && Math.abs(p.z - B.z) < B.d / 2 + 0.1) return "on the microscope bench"; + if (p.x > 3.2 && p.z < -1.2) return "on the teacher's desk"; + if (p.x < -2.9 && p.z > 3.2) return "on the steel shelves"; + return "in the lab"; +} + +function entry(game, { name, kind, object, item, where }) { + const extra = ALIASES[kind] || []; + const sol = item && item.solution ? [item.solution] : []; + const terms = [...new Set([name, ...extra, ...sol].map(norm).filter(Boolean))]; + return { name, kind, object, item, where, terms }; +} + +// Everything you could be looking for, with where it is right now. +export function buildIndex(game) { + const out = []; + const room = game.room; + for (const it of game.items) { + const slot = game.inv.slots.indexOf(it); + if (slot >= 0) { out.push(entry(game, { name: it.name, kind: it.kind, item: it, object: null, where: slot < 9 ? `in your hotbar, slot ${slot + 1}` : "in your inventory (E)" })); continue; } + if (it === game.stageItem) { out.push(entry(game, { name: it.name, kind: it.kind, item: it, object: room.scope, where: "on the microscope stage" })); continue; } + if (game.incubator.dishes.includes(it)) { out.push(entry(game, { name: it.name, kind: it.kind, item: it, object: room.incubator, where: "inside the incubator" })); continue; } + if (!it.obj.parent) continue; // used up or thrown away + out.push(entry(game, { name: it.name, kind: it.kind, item: it, object: it.obj, where: zone(game, it.obj.getWorldPosition(new THREE.Vector3())) })); + } + const seen = new Map(); + for (const t of room.targets) { + const d = t.userData.target; + if (!d) continue; + const key = d.kind === "drawer" ? "drawer" : d.name; + const p = t.getWorldPosition(new THREE.Vector3()); + const dist = p.distanceTo(game.player.pos); + // Four stools or three blinds: keep the nearest of each. + if (seen.has(key) && seen.get(key).dist <= dist) continue; + const e = entry(game, { name: d.kind === "drawer" ? "Drawer cabinet" : d.name, kind: d.kind, object: d.kind === "drawer" ? room.cabinet : t, where: PLACES[d.kind] || zone(game, p) }); + e.dist = dist; + seen.set(key, e); + } + out.push(...seen.values()); + return out; +} + +export function search(game, query, max = 7) { + const list = buildIndex(game); + const pos = game.player.pos; + return list + .map((e) => ({ ...e, score: similarity(query, e.terms), dist: e.object ? e.object.getWorldPosition(new THREE.Vector3()).distanceTo(pos) : 0 })) + .filter((e) => e.score >= (norm(query).length <= 3 ? 0.7 : 0.62)) + .sort((a, b) => b.score - a.score || a.dist - b.dist) + .slice(0, max); +} + +/* ---------- following a marker to it ---------- */ +const $ = (id) => document.getElementById(id); + +export class Tracker { + constructor(game) { + this.game = game; + this.target = null; + this.box = new THREE.Box3(); + this.v = new THREE.Vector3(); + } + start(e) { + this.target = e; + this.game.outliner.set("track", e.object); + $("trackName").textContent = e.name; + $("trackMarker").hidden = false; + this.game.dirty = true; + } + stop() { + if (!this.target) return; + this.target = null; + this.game.outliner.set("track", null); + $("trackMarker").hidden = true; + this.game.dirty = true; + } + // Is the thing you aim at the thing you were looking for? + reached(aim) { + const t = this.target; + if (!t || !aim) return false; + if (t.item && aim.item === t.item) return true; + if (aim.furniture && aim.furniture === t.object) return true; + if (aim.furniture && t.object && aim.furniture.parent === t.object) return true; + return false; + } + update(camera) { + const t = this.target; + if (!t) return; + const c = this.box.setFromObject(t.object).getCenter(this.v); + const dist = c.distanceTo(camera.position); + $("trackDist").textContent = `${dist < 10 ? dist.toFixed(1) : dist.toFixed(0)} m`; + const p = c.clone().project(camera); + const behind = c.clone().applyMatrix4(camera.matrixWorldInverse).z > 0; + const W = innerWidth, H = innerHeight, m = 48; + let x = (p.x * 0.5 + 0.5) * W, y = (-p.y * 0.5 + 0.5) * H; + const on = !behind && x > m && x < W - m && y > m && y < H - m; + const el = $("trackMarker"); + el.classList.toggle("edge", !on); + if (!on) { + // Pin it to the screen edge, pointing the way to turn. + let dx = x - W / 2, dy = y - H / 2; + if (behind) { dx = -dx; dy = -dy; if (Math.abs(dx) < 1 && Math.abs(dy) < 1) dy = H; } + const k = Math.min((W / 2 - m) / Math.max(1e-3, Math.abs(dx)), (H / 2 - m) / Math.max(1e-3, Math.abs(dy))); + x = W / 2 + dx * k; y = H / 2 + dy * k; + el.style.setProperty("--a", `${Math.atan2(dy, dx)}rad`); + } + el.style.transform = `translate(${x.toFixed(0)}px, ${y.toFixed(0)}px)`; + } +} diff --git a/web/lab3d/js/hud.js b/web/lab3d/js/hud.js index afc8f61..620d9f1 100644 --- a/web/lab3d/js/hud.js +++ b/web/lab3d/js/hud.js @@ -13,7 +13,7 @@ export const HUD = { const el = $("prompt"); if (!actions || (!actions.left && !actions.right)) { el.innerHTML = ""; return; } let h = actions.target ? `${esc(actions.target)}` : ""; - if (actions.right) h += `Right${esc(actions.right.label)}`; + if (actions.right) h += `Right${esc(actions.right.label)}`; if (actions.left) h += `Left${esc(actions.left.label)}`; el.innerHTML = h; }, diff --git a/web/lab3d/js/items.js b/web/lab3d/js/items.js index 1512cd1..b965d37 100644 --- a/web/lab3d/js/items.js +++ b/web/lab3d/js/items.js @@ -5,8 +5,9 @@ import * as P from "./props.js"; import { Container, SOLUTIONS, fmtVol } from "./liquids.js"; import { fit, enableShadows, link } from "./assets.js"; -const DROP = 0.05; // mL in one drop from a dropper or pipette +const DROP = 0.05; // mL in one drop from a dropper bottle const HIT_MAT = new THREE.MeshBasicMaterial({ visible: false }); +export const SOFTEN_S = 20; // seconds in warm acid, standing in for 5 minutes let uid = 0; export class Item { @@ -20,50 +21,78 @@ export class Item { Object.assign(this, extra); link(obj, "item", this); // An invisible box a little wider than the item, so thin things like - // forceps or a cover slip are easy to aim at. + // forceps or a cover slip are easy to aim at, and a soft shadow under it. + // Big open things (the water bath) get no box: it would hide what's inside them. const b = new THREE.Box3().setFromObject(obj); if (!b.isEmpty()) { const size = b.getSize(new THREE.Vector3()), c = b.getCenter(new THREE.Vector3()); - const hit = new THREE.Mesh(new THREE.BoxGeometry(Math.max(size.x + 0.012, 0.03), Math.max(size.y + 0.003, 0.012), Math.max(size.z + 0.012, 0.03)), HIT_MAT); + const hit = extra.hitbox === false ? new THREE.Object3D() : new THREE.Mesh(new THREE.BoxGeometry(Math.max(size.x + 0.012, 0.03), Math.max(size.y + 0.003, 0.012), Math.max(size.z + 0.012, 0.03)), HIT_MAT); hit.position.set(c.x, b.min.y + Math.max(size.y + 0.003, 0.012) / 2, c.z); hit.name = "hitbox"; obj.add(hit); + const sh = P.contactShadow(size.x, size.z); + sh.position.set(c.x, b.min.y + 0.0004, c.z); + obj.add(sh); + link(obj, "blob", sh); + this.foot = Math.max(0.012, Math.hypot(size.x, size.z) / 2 * 0.8); } obj.traverse((m) => { if (m.isMesh) link(m, "itemRoot", obj); }); } refresh() { if (this.liquid) this.liquid.update(this.container); if (this.kind === "slide") P.updateSlideLook(this); + if (this.kind === "pipette") P.updatePipetteLook(this); + if (this.kind === "plate") for (const w of this.wells) w.liquid.update(w.container); + if (this.kind === "hemocytometer") this.obj.userData.wet.visible = !this.container.empty; + if (this.kind === "tipbox" && this.state.left != null) this.obj.userData.tips.count = this.state.left; } info() { if (this.kind === "slide") return slideInfo(this); - if (this.kind === "dish") return `${this.container.describe()} · ${this.state.t} h in culture${drugText(this.container)}`; + if (this.kind === "dish") return `${this.state.detached ? `Cells in suspension: ${fmtVol(this.container.volume)}` : this.container.describe()} · ${this.state.t} h in culture${drugText(this.container)}`; + if (this.kind === "plate") { const n = this.state.wells.filter((w) => w.events.length).length; return `${this.state.t} h in culture · ${n} of 6 wells treated`; } + if (this.kind === "pipette") return pipetteInfo(this); + if (this.kind === "hemocytometer") return this.container.empty ? "Empty: load 10 µL of stained cells" : `Loaded: ${this.container.describe()}`; if (this.container) return this.container.describe(); - if (this.kind === "forceps" && this.state.carry) return `Holding ${this.state.carry === "onion" ? "a thin layer of onion skin" : "one pondweed leaf"}`; + if (this.kind === "forceps" && this.state.carry) return `Holding ${CARRY[this.state.carry]}`; if (this.kind === "swab") return this.state.used ? "Used: drop it in the disinfectant" : this.state.cells ? "Has cheek cells on it" : "Clean"; if (this.kind === "slidebox") return `${this.state.left} clean slides left`; if (this.kind === "coverbox") return `${this.state.left} cover slips left`; + if (this.kind === "tipbox") return `${this.state.left} sterile tips left`; return ""; } } -// Lower-case a name for a sentence, but keep names like "Dish A" as they are. -function lower(it) { return it.kind === "dish" ? it.name : it.name.toLowerCase(); } +const CARRY = { onion: "a thin layer of onion skin", elodea: "one pondweed leaf", redonion: "a thin layer of red onion skin", root: "a 5 mm root tip", "root-soft": "a softened root tip" }; + +// Lower-case a name for a sentence, but keep names like "Dish A" as they +// are, and units and acronyms (1 M, EDTA, A549) in capitals. +export function sentence(name) { return name.replace(/\b([A-Z])([a-z]+)\b/g, (w, a, b) => a.toLowerCase() + b); } +function lower(it) { return it.kind === "dish" || it.kind === "plate" ? it.name : sentence(it.name); } +const lowName = (solution) => sentence(P.shortName(solution)); function drugText(c) { const d = c.drugs(); - const parts = Object.entries(d).filter(([, v]) => v > 1e-4).map(([k, v]) => `${k} ${v < 0.1 ? v.toFixed(3) : v.toFixed(2)} µM`); + const parts = Object.entries(d).filter(([, v]) => v > 1e-5).map(([k, v]) => `${k} ${fmtConc(v)}`); return parts.length ? ` · ${parts.join(", ")}` : ""; } +export function fmtConc(uM) { return uM >= 0.1 ? `${uM.toFixed(2)} µM` : uM >= 0.001 ? `${(uM * 1000).toFixed(uM >= 0.01 ? 0 : 1)} nM` : `${(uM * 1000).toFixed(2)} nM`; } function slideInfo(s) { const st = s.state, bits = []; - bits.push(st.sample ? { onion: "Onion skin", cheek: "Cheek cells", elodea: "Pondweed leaf" }[st.sample] : "No sample"); + bits.push(st.sample ? { onion: "Onion skin", cheek: "Cheek cells", elodea: "Pondweed leaf", redonion: "Red onion skin", root: st.softened ? "Softened root tip" : "Root tip" }[st.sample] : "No sample"); if (!s.container.empty) bits.push(s.container.describe()); bits.push(st.cover ? (st.cover === "angle" ? "cover slip, no bubbles" : "cover slip, air bubbles") : "no cover slip"); + if (st.squashed) bits.push("squashed"); + if (st.edge) bits.push(`a drop of ${lowName(st.edge)} waiting at the edge`); return bits.join(" · "); } +function pipetteInfo(p) { + const st = p.state; + const tip = !st.tip ? "no tip: fit one from the tip box" : st.load && !st.load.empty ? `holding ${fmtVol(st.load.volume)} of ${sentence(st.load.describe().split(" · ")[1])}` : st.used ? `used tip (it touched ${st.usedName})` : "clean tip"; + return `Set to ${Math.round(st.vol)} µL · ${tip} · R: set the volume`; +} + /* ---------- making items ---------- */ function liquidItem(kind, name, made, extra) { return new Item(kind, name, made.obj, { container: made.container, liquid: made.liquid, ...extra }); @@ -71,12 +100,13 @@ function liquidItem(kind, name, made, extra) { export function newSlide() { const it = new Item("slide", "Glass slide", P.makeSlide(), { container: new Container(0.4) }); - it.state = { sample: null, cover: null, label: "" }; + it.state = { sample: null, cover: null, label: "", osmo: [] }; return it; } export function newCoverSlip() { return new Item("coverslip", "Cover slip", P.makeCoverSlip()); } export function newSwab() { const it = new Item("swab", "Cotton swab", P.makeSwab()); it.state = { cells: false, used: false }; return it; } export function newPencil() { return new Item("pencil", "Pencil", P.makePencil()); } +function dropper(s, v) { return liquidItem("dropper", `${P.shortName(s)} dropper bottle`, P.makeDropperBottle(s, v), { solution: s }); } export function createItems(game, assets, room) { const Y = room.TABLE_Y, B = room.BENCH.h; @@ -90,10 +120,11 @@ export function createItems(game, assets, room) { const cbox = put(new Item("coverbox", "Cover slips", P.makeBox({ w: 0.032, h: 0.014, d: 0.032, color: 0xdfe6ea, labelLines: ["Cover slips"] })), -2.6, Y, -1.9); cbox.state.left = 20; put(new Item("towels", "Paper towels", P.makePaperTowels()), -1.95, Y, -1.98); - const stains = [["water", 25], ["saline", 25], ["iodine", 22], ["mb", 22]]; - stains.forEach(([s, v], i) => put(liquidItem("dropper", `${P.shortName(s)} dropper bottle`, P.makeDropperBottle(s, v), { solution: s }), -1.82 + i * 0.075, Y, -1.66)); + [["water", 25], ["saline", 25], ["iodine", 22], ["mb", 22], ["salt", 25]].forEach(([s, v], i) => put(dropper(s, v), -1.82 + i * 0.075, Y, -1.66)); const onionObj = enableShadows(fit(assets.gltf.yellow_onion, { height: 0.085 })); put(new Item("onion", "Onion", onionObj), -3.25, Y, -1.7).state.cut = false; + const red = enableShadows(fit(P.makeRedOnion(assets.gltf.yellow_onion.clone()), { height: 0.08 })); + put(new Item("redonion", "Red onion", red), -3.42, Y, -1.95, 1.2).state.cut = false; put(new Item("scalpel", "Scalpel", P.makeScalpel()), -3.02, Y, -1.52, 0.3); put(new Item("forceps", "Forceps", P.makeForceps()), -2.95, Y, -1.45, 0.2); put(new Item("swabcup", "Cup of cotton swabs", P.makeSwabCup()), -3.55, Y, -1.66); @@ -106,18 +137,45 @@ export function createItems(game, assets, room) { put(new Item("pencilcup", "Pens and pencils", cup, { pickable: false }), -0.95, Y, -1.9, 0.4); put(new Item("sanitizer", "Hand sanitizer", P.makeSanitizer(), { pickable: false }), 0.05, Y, -2.35); + // Root tip station, on the bench arm by the windows: onion roots, acid, a warm bath. + const rooted = P.makeRootedOnion(enableShadows(fit(assets.gltf.yellow_onion.clone(), { height: 0.07 }))); + const ro = put(liquidItem("rootonion", "Onion with roots", rooted, { pickable: false }), -4.45, Y, 0.05); + ro.state = { cut: 0 }; + const bath = put(new Item("waterbath", "Water bath (60 °C)", P.makeWaterBath(), { pickable: false, hitbox: false }), -4.5, Y, 0.62, Math.PI / 2); + put(liquidItem("watchglass", "Watch glass", P.makeWatchGlass()), -4.5, Y + bath.obj.userData.shelfY, 0.62).state = {}; + put(dropper("hcl", 25), -4.18, Y, 0.36); + put(dropper("toluidine", 22), -4.18, Y, 0.47); + // Stock bottles on the steel shelves. const shelfLevels = findShelfLevels(game, room.shelves); - const stocks = [["water", 480], ["saline", 450], ["iodine", 400], ["mb", 400], ["ethanol", 450]]; + const stocks = [["water", 480], ["saline", 450], ["iodine", 400], ["mb", 400], ["ethanol", 450], ["salt", 450]]; stocks.forEach(([s, v], i) => { const lvl = shelfLevels[Math.min(shelfLevels.length - 1, 1 + Math.floor(i / 3))]; put(liquidItem("stock", `${P.shortName(s)} stock bottle`, P.makeStockBottle(s, v), { solution: s }), -3.95 + (i % 3) * 0.32, lvl, 3.66); }); - // The microscope bench: drug stocks and the goggles. + // The microscope bench: drug stocks and goggles, and the cell culture kit: + // micropipette and tips, trypsin, trypan blue, a hemocytometer, a plate reader. [["paclitaxel", -2.1], ["doxorubicin", -1.98], ["cisplatin", -1.86]].forEach(([d, x]) => put(liquidItem("drug", `${P.shortName(d)} vial`, P.makeDrugVial(d, 8), { solution: d }), x, B, 0.68)); + put(dropper("trypan", 20), -1.74, B, 0.68); put(new Item("goggles", "Safety goggles", P.makeGoggles()), -0.42, B, 1.15, -0.4); + const pip = put(new Item("pipette", "Micropipette", P.makeMicropipette()), -2.02, B, 1.13, 0.1); + pip.state = { vol: 20, tip: false, load: null, used: null }; + pip.refresh(); + const tipbox = new Item("tipbox", "Box of pipette tips", P.makeTipBox(), { pickable: false }); + tipbox.state.left = 96; + put(tipbox, -2.2, B, 0.92); + put(new Item("tipwaste", "Tip waste", P.makeTipWaste(), { pickable: false }), -1.76, B, 1.19); + put(liquidItem("trypsin", "Trypsin-EDTA bottle", P.makeStockBottle("trypsin", 80, { capacity: 100, scale: 0.6 }), { solution: "trypsin" }), -2.27, B, 1.2); + const rack = put(new Item("tuberack", "Tube rack", P.makeTubeRack(), { pickable: false }), -1.95, B, 0.93); + const tubes = [["TB", "Trypan blue tube", "trypan", 0.01], ["1", "Empty tube", null, 0]]; + tubes.forEach(([lab, name, sol, v], i) => { + const t = put(liquidItem("tube", name, P.makeMicrotube(lab, sol, v)), 0, 0, 0); + seatInRack(rack, t, i); + }); + put(liquidItem("hemocytometer", "Hemocytometer", { obj: P.makeHemocytometer(), container: new Container(0.02), liquid: null }), -1.25, B, 1.18, 0.2); + put(new Item("platereader", "Plate reader", P.makePlateReader(), { pickable: false }), -1.45, B, 0.78); // On the teacher's desk: the journal and the method sheet. const journal = enableShadows(fit(assets.gltf.binder_notebook, { maxDim: 0.32 })); @@ -126,8 +184,8 @@ export function createItems(game, assets, room) { const clip = enableShadows(fit(assets.gltf.clipboard, { maxDim: 0.34, rotX: -Math.PI / 2 })); put(new Item("clipboard", "Method sheet", clip, { pickable: false }), 3.8, room.deskTop, -1.95, -0.3); - // Two culture dishes waiting in the incubator: A to treat, B as the control. - const dishes = ["Dish A", "Dish B"].map((name, i) => { + // In the incubator: Dish A to treat, Dish B as the control, and a 6-well plate. + const dishes = ["Dish A", "Dish B"].map((name) => { const it = liquidItem("dish", name, P.makeCultureDish(name), {}); it.state = { label: name, seed: 11, t: 0, events: [], snap: null, header: null, series: [], line: "A549" }; enableShadows(it.obj); @@ -135,7 +193,24 @@ export function createItems(game, assets, room) { items.push(it); return it; }); - return { items, dishes }; + const made = P.makeWellPlate("Plate 1"); + const plate = new Item("plate", "Plate 1", made.obj, { wells: made.wells }); + plate.state = { t: 0, seed: 21, line: "A549", wells: made.wells.map(() => ({ events: [], result: null })) }; + enableShadows(plate.obj); + plate.refresh(); + items.push(plate); + return { items, dishes, plate }; +} + +// Put a microtube upright in hole i of the rack. +export function seatInRack(rack, tube, i) { + const h = P.RACK_HOLES[i]; + rack.obj.updateMatrixWorld(true); + const p = rack.obj.localToWorld(h.clone().setY(0.012)); + tube.obj.position.copy(p); + tube.obj.rotation.set(0, 0, 0); + tube.state.rackHole = i; + if (tube.obj.userData.blob) tube.obj.userData.blob.visible = false; } // Shelf heights, found by dropping a ray down through the shelf unit. @@ -159,19 +234,24 @@ function findShelfLevels(game, shelves) { export function getActions(game, held, hit) { let t = hit && hit.item, f = hit && hit.furniture; const out = { left: null, right: null, target: t ? t.name : f ? f.userData.target.name : "" }; + if (t && t.kind === "plate" && hit.point) out.target = `${t.name} · well ${P.WELLS[P.wellAt(t.obj, t.obj.worldToLocal(hit.point.clone()))]}`; if (t && t.pickable) out.left = { label: `Take ${lower(t)}`, run: () => game.take(t) }; // A slide or dish on the stage counts as the microscope for right-click. if (t && t === game.stageItem) { out.target = `Microscope · ${t.name}`; out.right = held ? null : furnitureAction(game, game.room.scope); out.left = { label: `Take the ${lower(t)} off the stage`, run: () => game.takeFromStage() }; - return out; + return tidy(out); } if (f && f.userData.target.kind === "microscope" && game.stageItem) out.left = { label: `Take the ${lower(game.stageItem)} off the stage`, run: () => game.takeFromStage() }; if (f && f.userData.target.kind === "drawer" && f.userData.open && f.userData.spare) out.left = { label: `Take ${f.userData.spare.label}`, run: () => game.takeSpare(f) }; out.right = rightAction(game, held, t, f, hit); - // "the Dish A" reads badly: names don't take "the". - for (const a of [out.left, out.right]) if (a) a.label = a.label.replace(/\bthe (Dish [AB])\b/g, "$1"); + return tidy(out); +} + +// "the Dish A" reads badly: names don't take "the". +function tidy(out) { + for (const a of [out.left, out.right]) if (a) a.label = a.label.replace(/\bthe (Dish [AB]|Plate 1)\b/g, "$1"); return out; } @@ -179,7 +259,7 @@ function rightAction(game, held, t, f, hit) { const k = held && held.kind; // Using what you hold on an item. if (held && t) { - const r = useOnItem(game, held, t); + const r = useOnItem(game, held, t, hit); if (r) return r; } if (held && f) { @@ -203,32 +283,137 @@ function rightAction(game, held, t, f, hit) { if (k === "swab" && !held.state.cells && !held.state.used) return { label: "Rub the inside of your cheek", run: () => { held.state.cells = true; game.emit("swabbed"); game.toast("Cheek cells collected on the swab"); } }; if (k === "lens") return { label: "Look closely (hold)", whileHeld: true, start: () => (game.player.zoom = 3.2), end: () => (game.player.zoom = 1) }; } - // Putting it down. - if (held && hit && hit.surface) return { label: `Put the ${lower(held)} down`, run: () => game.place(held, hit.point) }; + // Putting it down: only on clear bench, or a slide onto the tile. + if (held && hit && hit.surface && (!hit.item || hit.item.kind === "tile")) { + const block = game.placeBlocked(held, hit.point, hit.item); + if (block) return { label: `No room here: ${lower(block)} is in the way`, blocked: true, run: () => game.toast("Aim at a clear spot on the bench.", "warn") }; + return { label: `Put the ${lower(held)} down`, place: true, run: () => game.place(held, hit.point) }; + } + if (k === "pipette" && !t && !f) return { label: `Set the volume (now ${Math.round(held.state.vol)} µL)`, run: () => game.openPipette(held) }; if (f && held) return furnitureAction(game, f); if (t && held) { const r = itemAction(game, t); if (r) return r; } return null; } -function useOnItem(game, held, t) { +/* ---------- the micropipette ---------- */ +// Containers a pipette can draw from or dispense into, with what to call them. +function pipetteTarget(t, hit) { + if (t.kind === "plate") { + const i = P.wellAt(t.obj, t.obj.worldToLocal(hit.point.clone())); + return { container: t.wells[i].container, name: `well ${P.WELLS[i]}`, well: i }; + } + if (t.kind === "hemocytometer") return { container: t.container, name: "the hemocytometer", chamber: true }; + if (t.container && ["drug", "dropper", "stock", "tube", "dish", "beaker", "trypsin", "watchglass"].includes(t.kind)) return { container: t.container, name: t.kind === "dish" ? t.name : `the ${lower(t)}` }; + return null; +} + +function pipetteOn(game, p, t, hit) { + const st = p.state, vol = st.vol / 1000; + if (t.kind === "tipbox") { + if (st.tip) return { label: "There's already a tip on: eject it into the tip waste", run: () => game.toast("Aim at the tip waste and right-click to eject the old tip.", "warn") }; + return { label: "Press the pipette into a fresh tip", run: () => { + if (t.state.left <= 0) return game.toast("The tip box is empty.", "warn"); + t.state.left--; t.refresh(); + Object.assign(st, { tip: true, load: null, used: null, usedName: "" }); p.refresh(); game.sfx("click"); game.emit("tip"); + } }; + } + if (t.kind === "tipwaste") { + if (!st.tip) return { label: "Tip waste: used tips go here", run: () => game.toast("Fit a tip from the tip box first.") }; + return { label: "Eject the tip into the tip waste", run: () => { Object.assign(st, { tip: false, load: null, used: null }); p.refresh(); game.sfx("click"); game.emit("tip-eject"); } }; + } + const tg = pipetteTarget(t, hit); + if (!tg) return null; + if (!st.tip) return { label: "Fit a tip first (from the tip box)", run: () => game.toast("Never put a bare pipette into a liquid: press it into a tip from the tip box first.", "warn") }; + const loaded = st.load && !st.load.empty; + if (!loaded) { + const what = tg.container.dominant(); + if (!what || tg.container.empty) return { label: `${cap(tg.name)} is empty`, run: () => game.toast("There's nothing to draw up.", "warn") }; + return { label: `Draw up ${Math.round(st.vol)} µL from ${tg.name}`, run: () => { + // One tip per solution: a used tip would carry the last liquid into this one. + if (st.used && st.used !== tg.container) return game.toast(`Eject this tip and fit a fresh one first: it has touched ${st.usedName}, and would carry it into ${tg.name}.`, "warn"); + if (tg.container.volume < vol - 1e-9) return game.toast(`There's only ${fmtVol(tg.container.volume)} left in ${tg.name}.`, "warn"); + st.load = new Container(0.2); + tg.container.pour(st.load, vol); + st.used = tg.container; st.usedName = tg.name; + if (t.kind === "dish" && !t.state.detached && st.load.c.cells == null) game.toast("That's only medium: the cells are stuck to the dish. Trypsin lifts them off.", "warn"); + p.refresh(); t.refresh(); game.sfx("click"); + game.emit(`draw:${what}`); + } }; + } + return { label: `Dispense ${fmtVol(st.load.volume)} into ${tg.name}`, run: () => { + if (tg.chamber && t.container.volume >= 0.0095) return game.toast("The chamber is already full: one 10 µL load is enough.", "warn"); + const v = st.load.volume; + st.load.pour(tg.container, v); + // After dispensing into something, the tip has touched it too. + st.used = tg.container; st.usedName = tg.name; + p.refresh(); t.refresh(); game.sfx("drip"); + if (tg.well != null) game.wellDosed(t, tg.well); + else if (t.kind === "dish") game.dishDosed(t); + else if (tg.chamber) { game.emit("hemo-loaded"); game.toast("The liquid runs under the cover glass and fills the chamber."); } + else if (t.kind === "tube" && t.container.c.trypan && t.container.c.cells) { game.emit("trypan-mixed"); game.toast("Cells and trypan blue, mixed 1:1. Dead cells take up the blue; live ones keep it out."); } + } }; +} +function cap(s) { return s.charAt(0).toUpperCase() + s.slice(1); } + +function useOnItem(game, held, t, hit) { const k = held.kind; const slide = t.kind === "slide"; + if (k === "pipette") { const r = pipetteOn(game, held, t, hit); if (r) return r; } if (k === "slide" && t.kind === "tile") return { label: "Put the slide on the white tile", run: () => { game.place(held, tileTop(t)); game.emit("slide-on-tile"); } }; - if (slide && k === "forceps" && held.state.carry) return { label: `Lay the ${held.state.carry === "onion" ? "onion skin" : "leaf"} flat on the slide`, run: () => { + if (k === "tube" && t.kind === "tuberack") return { label: "Put the tube in the rack", run: () => { + const used = new Set(game.items.filter((x) => x.kind === "tube" && x.obj.parent && x !== held).map((x) => x.state.rackHole)); + const free = P.RACK_HOLES.findIndex((_, i) => !used.has(i)); + if (free < 0) return game.toast("The rack is full.", "warn"); + game.place(held, t.obj.position.clone()); seatInRack(t, held, free); game.afterAction(); + } }; + if (slide && k === "forceps" && held.state.carry) return { label: `Lay the ${CARRY[held.state.carry].replace(/^(a|one) /, "")} flat on the slide`, run: () => { if (t.state.sample) return game.toast("This slide already has a sample. Rinse it at the sink first.", "warn"); - t.state.sample = held.state.carry; held.state.carry = null; t.refresh(); game.emit(`sample:${t.state.sample}`); + const c = held.state.carry; + t.state.sample = c === "root-soft" ? "root" : c; t.state.softened = c === "root-soft"; held.state.carry = null; t.refresh(); + game.emit(`sample:${t.state.sample}`); if (t.state.sample === "elodea" && t.container.empty) game.toast("Tip: a leaf goes into a drop of water, or it dries out.", "warn"); + if (c === "root") game.toast("This root tip hasn't been softened: its cells will stay stuck together.", "warn"); } }; - if (t.kind === "onion" && k === "scalpel") return { label: "Cut a small piece from the onion", run: () => { t.state.cut = true; game.emit("onion-cut"); game.toast("Onion cut. Now peel the thin inner skin with the forceps."); } }; - if (t.kind === "onion" && k === "forceps") return { label: "Peel a thin layer of skin", run: () => { - if (!t.state.cut) return game.toast("Cut the onion with the scalpel first.", "warn"); + if ((t.kind === "onion" || t.kind === "redonion") && k === "scalpel") return { label: `Cut a small piece from the ${lower(t)}`, run: () => { t.state.cut = true; game.emit(`${t.kind}-cut`); game.sfx("place"); game.toast("Cut. Now peel the thin skin with the forceps."); } }; + if ((t.kind === "onion" || t.kind === "redonion") && k === "forceps") return { label: t.kind === "redonion" ? "Peel the thin red skin from the outside" : "Peel a thin layer of skin", run: () => { + if (!t.state.cut) return game.toast("Cut it with the scalpel first.", "warn"); if (held.state.carry) return game.toast("The forceps are already holding something.", "warn"); - held.state.carry = "onion"; game.toast("A see-through layer of onion skin, one cell thick"); + held.state.carry = t.kind; game.toast(t.kind === "redonion" ? "A see-through layer of red cells, one cell thick" : "A see-through layer of onion skin, one cell thick"); } }; if (t.kind === "tank" && k === "forceps") return { label: "Pull off one small leaf", run: () => { if (held.state.carry) return game.toast("The forceps are already holding something.", "warn"); held.state.carry = "elodea"; game.toast("One young pondweed leaf, two cells thick"); } }; + if (t.kind === "rootonion" && k === "scalpel") return { label: "Cut off the last 5 mm of a root", run: () => { + const roots = t.obj.userData.roots; + if (t.state.cut >= roots.length) return game.toast("No roots left to cut.", "warn"); + roots[t.state.cut].scale.y = 0.72; roots[t.state.cut].position.y = (0.075 - 0.008) * 0.28; // shorter from the tip, still attached at the top + t.state.cut++; t.state.loose = (t.state.loose || 0) + 1; + game.emit("root-cut"); game.toast("Cut. The 5 mm tip is where the cells divide. Pick it up with the forceps."); + } }; + if (t.kind === "rootonion" && k === "forceps") return { label: "Pick up the cut root tip", run: () => { + if (!t.state.loose) return game.toast("Cut a root tip with the scalpel first.", "warn"); + if (held.state.carry) return game.toast("The forceps are already holding something.", "warn"); + t.state.loose--; held.state.carry = "root"; game.toast("Holding a 5 mm root tip. Soften it in the warm acid."); + } }; + if (t.kind === "watchglass") { + if (k === "dropper" && held.solution === "hcl") return { label: "Add a drop of 1 M hydrochloric acid", run: () => { + held.container.pour(t.container, DROP); held.refresh(); t.refresh(); game.sfx("drip"); + if (t.container.volume >= 0.149) game.emit("acid"); + } }; + if (k === "forceps" && held.state.carry === "root") return { label: "Put the root tip in the warm acid", run: () => { + if (!t.container.c.hcl || t.container.volume < 0.099) return game.toast("Add at least 2 drops of hydrochloric acid to the watch glass first.", "warn"); + if (!game.inWaterBath(t)) return game.toast("Stand the watch glass on the shelf in the water bath first: the acid works at 60 °C.", "warn"); + held.state.carry = null; t.state.root = performance.now(); game.emit("root-acid"); + game.toast(`The acid breaks down what glues the cells together. Leave it ${SOFTEN_S} s (5 minutes, sped up).`); + } }; + if (k === "forceps" && !held.state.carry && t.state.root) return { label: "Take the root tip out of the acid", run: () => { + const left = SOFTEN_S - (performance.now() - t.state.root) / 1000; + if (left > 0) return game.toast(`Not soft yet: ${Math.ceil(left)} s more.`, "warn"); + t.state.root = null; held.state.carry = "root-soft"; game.emit("root-soft"); + game.toast("Soft and pale. Lay it on a slide."); + } }; + } if (slide && k === "swab" && held.state.cells) return { label: "Smear the swab across the slide", run: () => { if (t.state.sample) return game.toast("This slide already has a sample.", "warn"); t.state.sample = "cheek"; held.state.cells = false; held.state.used = true; t.refresh(); game.emit("sample:cheek"); @@ -237,52 +422,92 @@ function useOnItem(game, held, t) { if (t.kind === "beaker" && k === "swab" && t.container.c.disinfectant) return { label: "Drop the swab in the disinfectant", run: () => { game.dispose(held); game.emit("dispose:swab"); } }; if (slide && (k === "dropper" || k === "drug")) { if (k === "drug") return { label: "Drugs go in the culture dish", run: () => game.toast("Cytotoxic drugs are only for the living cells in a culture dish.", "warn") }; - return { label: t.state.cover ? `Add a drop of ${P.shortName(held.solution).toLowerCase()} at the edge of the cover slip` : `Add one drop of ${P.shortName(held.solution).toLowerCase()}`, run: () => { + if (held.solution === "hcl") return { label: "Acid goes in the watch glass", run: () => game.toast("The acid softens a root tip in the watch glass, in the water bath.", "warn") }; + return { label: t.state.cover ? `Add a drop of ${lowName(held.solution)} at the edge of the cover slip` : `Add one drop of ${lowName(held.solution)}`, run: () => { if (held.container.empty) return game.toast("This bottle is empty. Refill it from the stock bottle on the shelf.", "warn"); const before = t.container.volume; held.container.pour(t.container, DROP); if (t.container.volume - before < 1e-6) return game.toast("The slide can't hold any more. Blot it with a paper towel.", "warn"); - held.refresh(); t.refresh(); + held.refresh(); t.refresh(); game.sfx("drip"); game.emit(`drop:${held.solution}`); - if (t.state.cover) game.toast("The stain runs under the cover slip"); + if (t.state.cover) { + t.state.edge = held.solution; + game.toast(t.state.sample === "redonion" ? "Now touch a paper towel to the opposite edge to draw it under the cover slip." : "The stain runs under the cover slip"); + } } }; } - if (t.kind === "dish" && k === "drug") return { label: `Add one drop of ${P.shortName(held.solution).toLowerCase()} to ${t.name}`, run: () => { + if (t.kind === "dish" && k === "drug") return { label: `Add one drop of ${lowName(held.solution)} to ${t.name}`, run: () => { if (held.container.empty) return game.toast("The vial is empty.", "warn"); held.container.pour(t.container, DROP); - held.refresh(); t.refresh(); + held.refresh(); t.refresh(); game.sfx("drip"); game.dishDosed(t); } }; if (t.kind === "dish" && k === "dropper") return { label: "Stains are for slides", run: () => game.toast("A stain would kill the living cells. Use it on slides only.", "warn") }; + if (t.kind === "dish" && k === "trypsin") return { label: `Add trypsin to lift the cells off ${t.name}`, run: () => { + if (t.state.detached) return game.toast("The cells are already in suspension."); + // Pour off the medium, trypsin for 5 minutes, then fresh medium stops it. + held.container.take(0.5); held.refresh(); + t.container = new Container(5.2, { cells: 1 }); + t.container.meta = { dish: t.id }; + t.liquid.update(t.container); + t.state.detached = true; + game.emit("trypsin"); game.sfx("pour"); + game.toast("Medium off, 0.5 mL trypsin, 5 minutes at 37 °C: the cells round up and float. Fresh medium stops the trypsin: 1 mL of cell suspension."); + } }; if (slide && k === "coverslip") return { label: "Lower the cover slip: hold for slow, tap to drop", hold: 1.1, run: (slow) => { if (t.state.cover) return game.toast("This slide already has a cover slip.", "warn"); - t.state.cover = slow ? "angle" : "flat"; game.dispose(held, { quiet: true }); t.refresh(); + t.state.cover = slow ? "angle" : "flat"; game.dispose(held, { quiet: true }); t.refresh(); game.sfx("glass"); + t.state.osmo.push({ t: performance.now(), osm: t.container.osmolarity() }); + t.state.mediumName = t.container.dominant(); game.emit(`cover:${t.state.cover}`); game.toast(slow ? "Lowered slowly at an angle: no air bubbles" : "Dropped flat: that trapped air bubbles", slow ? "good" : "warn"); } }; if (slide && k === "pencil") return { label: "Label the frosted end", run: () => { - t.state.label = t.state.sample ? { onion: "Onion", cheek: "Cheek", elodea: "Leaf" }[t.state.sample] : "Slide"; t.refresh(); game.emit("label"); } }; - if (slide && k === "towels") return { label: "Blot away the extra liquid", run: () => { - const extra = t.container.volume - DROP; - if (extra <= 0.001) return game.toast("There's no extra liquid to blot."); - t.container.take(extra); t.refresh(); game.toast("Blotted. The cover slip sits flat now."); - } }; + t.state.label = t.state.sample ? { onion: "Onion", cheek: "Cheek", elodea: "Leaf", redonion: "Red onion", root: "Root tip" }[t.state.sample] : "Slide"; t.refresh(); game.emit("label"); } }; + if (slide && k === "towels") { + if (t.state.sample === "root" && t.state.cover && !t.state.squashed) return { label: "Squash: press down hard through the folded towel (hold)", hold: 1.0, run: (full) => { + if (!full) return game.toast("Press harder: hold right-click until the ring fills.", "warn"); + t.state.squashed = true; t.refresh(); game.emit("squash"); + game.toast(t.state.softened ? "Squashed flat: the cells spread out into a single layer." : "Squashed, but the unsoftened tip stays in a clump.", t.state.softened ? "good" : "warn"); + } }; + if (t.state.cover && t.state.edge) return { label: "Draw the drop under the cover slip with the towel", run: () => { + // The towel soaks up the old liquid as the new drop runs in from the other side. + const old = t.container.take(t.container.volume); + const edge = t.state.edge; + t.container = new Container(0.4, { [edge]: DROP * 0.85 }); + for (const kk in old) t.container.add(kk, (old[kk] / Math.max(1e-9, Object.values(old).reduce((a, b) => a + b, 0))) * DROP * 0.15); + t.state.edge = null; + t.state.osmo.push({ t: performance.now(), osm: t.container.osmolarity() }); + t.state.mediumName = edge; + t.refresh(); game.emit(`irrigate:${edge}`); + game.toast(`The towel draws the ${lowName(edge)} under the cover slip. Watch the cells.`); + } }; + return { label: "Blot away the extra liquid", run: () => { + const extra = t.container.volume - DROP; + if (extra <= 0.001) return game.toast("There's no extra liquid to blot."); + t.container.take(extra); t.refresh(); game.toast("Blotted. The cover slip sits flat now."); + } }; + } if ((k === "stock" && t.kind === "dropper") || (k === "dropper" && t.kind === "stock")) { const stock = k === "stock" ? held : t, bottle = k === "stock" ? t : held; if (stock.solution !== bottle.solution) return { label: "Different solutions", run: () => game.toast("Only refill a bottle from the stock of the same solution.", "warn") }; return { label: "Refill the dropper bottle from the stock", run: () => { const v = stock.container.pour(bottle.container, bottle.container.capacity - bottle.container.volume); - stock.refresh(); bottle.refresh(); game.toast(`Refilled with ${fmtVol(v)}`); + stock.refresh(); bottle.refresh(); game.sfx("pour"); game.toast(`Refilled with ${fmtVol(v)}`); } }; } if ((k === "stock" && t.kind === "beaker") || (k === "beaker" && t.kind === "stock")) { const from = k === "stock" ? held : t, to = k === "stock" ? t : held; - return { label: `Pour 20 mL of ${P.shortName(from.solution).toLowerCase()} into the beaker`, run: () => { - const v = from.container.pour(to.container, 20); from.refresh(); to.refresh(); + return { label: `Pour 20 mL of ${lowName(from.solution)} into the beaker`, run: () => { + const v = from.container.pour(to.container, 20); from.refresh(); to.refresh(); game.sfx("pour"); game.toast(v > 0 ? `Poured ${fmtVol(v)}. The beaker now holds ${to.container.describe()}` : "The beaker is full."); } }; } - if (k === "dropper" && t.kind === "beaker") return { label: `Add a drop to the beaker`, run: () => { held.container.pour(t.container, DROP); held.refresh(); t.refresh(); } }; + if (k === "dropper" && t.kind === "beaker") return { label: `Add a drop to the beaker`, run: () => { held.container.pour(t.container, DROP); held.refresh(); t.refresh(); game.sfx("drip"); } }; + if (k === "plate" && t.kind === "platereader") return { label: "Slide the plate into the reader", run: () => game.readPlate(held, t) }; + if (k === "watchglass" && t.kind === "waterbath") return { label: "Stand the watch glass on the shelf in the warm water", run: () => { + game.place(held, t.obj.position.clone().setY(t.obj.position.y + t.obj.userData.shelfY)); + } }; return null; } @@ -290,11 +515,12 @@ function tileTop(tile) { return tile.obj.position.clone().add(new THREE.Vector3( function useOnFurniture(game, held, f) { const kind = f.userData.target.kind, k = held.kind; - if (kind === "microscope" && (k === "slide" || k === "dish") && !game.stageItem) return { label: `Clip the ${lower(held)} onto the stage`, run: () => game.putOnStage(held) }; - if (kind === "incubator" && k === "dish") return { label: `Put ${held.name} in the incubator`, run: () => game.putInIncubator(held) }; + if (kind === "microscope" && ["slide", "dish", "plate", "hemocytometer"].includes(k) && !game.stageItem) return { label: `Clip the ${lower(held)} onto the stage`, run: () => game.putOnStage(held) }; + if (kind === "incubator" && (k === "dish" || k === "plate")) return { label: `Put ${held.name} in the incubator`, run: () => game.putInIncubator(held) }; if (kind === "glassbin" && (k === "slide" || k === "coverslip")) return { label: `Throw the ${lower(held)} into the glass waste`, run: () => { game.dispose(held); game.emit(`dispose:${k}`); } }; + if (kind === "glassbin" && k === "pipette" && held.state.tip) return { label: "Tips go in the tip waste", run: () => game.toast("Plastic tips go in the tip waste on the microscope bench, not the glass bin.", "warn") }; if (kind === "sink" && k === "slide") return { label: "Rinse the slide clean", run: () => { - held.state = { sample: null, cover: null, label: "" }; held.container = new Container(0.4); held.refresh(); game.runTap(); game.toast("Rinsed and dried. A clean slide again."); + held.state = { sample: null, cover: null, label: "", osmo: [] }; held.container = new Container(0.4); held.refresh(); game.runTap(); game.toast("Rinsed and dried. A clean slide again."); } }; if (kind === "sink" && k === "beaker") return { label: "Fill the beaker with tap water", run: () => { held.container.add("tap", 200); held.refresh(); game.runTap(); } }; return null; @@ -305,7 +531,7 @@ function furnitureAction(game, f) { switch (t.kind) { case "microscope": return game.stageItem ? { label: "Look through the eyepiece", run: () => game.enterScope() } - : { label: "Look through the eyepiece", run: () => game.toast("Clip a slide or a culture dish onto the stage first.", "warn") }; + : { label: "Look through the eyepiece", run: () => game.toast("Clip a slide, a dish, a plate or the hemocytometer onto the stage first.", "warn") }; case "incubator": return { label: "Open the incubator", run: () => game.openIncubator() }; case "sink": return { label: "Wash your hands", run: () => { game.runTap(); game.washHands(); } }; case "door": return { label: "Leave the lab", run: () => game.leave() }; @@ -335,9 +561,22 @@ function itemAction(game, t) { case "journal": return { label: "Open your lab journal", run: () => game.openJournal() }; case "clipboard": return { label: "Read the method sheet", run: () => game.openReader() }; case "tank": return { label: "Pondweed: take a leaf with the forceps", run: () => game.toast("Hold the forceps, then right-click the tank.") }; - case "onion": return { label: "Onion: cut it with the scalpel", run: () => game.toast(t.state.cut ? "Peel the thin inner skin with the forceps." : "Hold the scalpel, then right-click the onion.") }; + case "onion": case "redonion": return { label: `${t.name}: cut it with the scalpel`, run: () => game.toast(t.state.cut ? "Peel the thin skin with the forceps." : "Hold the scalpel, then right-click the onion.") }; + case "rootonion": return { label: "Roots: cut a tip with the scalpel", run: () => game.toast("Hold the scalpel and right-click the onion to cut a root tip, then pick it up with the forceps.") }; + case "waterbath": return { label: "Water bath: 60 °C", run: () => game.toast("Warm acid softens a root tip in 5 minutes. The watch glass sits on the shelf inside.") }; + case "watchglass": return { label: t.state.root ? "Root tip softening in warm acid" : "Watch glass", run: () => { + if (!t.state.root) return game.toast("Add 1 M hydrochloric acid, then put a root tip in it with the forceps."); + const left = SOFTEN_S - (performance.now() - t.state.root) / 1000; + game.toast(left > 0 ? `Softening: ${Math.ceil(left)} s more.` : "Soft now. Take it out with the forceps."); + } }; case "slide": return { label: "Slide: add a sample, a drop, a cover slip", run: () => game.toast("Hold forceps, a swab, a dropper bottle or a cover slip, then right-click the slide.") }; case "dish": return { label: `${t.name}: ${t.state.t} h in culture`, run: () => game.toast("Clip the dish onto the microscope stage to look at the cells.") }; + case "plate": return { label: `${t.name}: ${t.state.t} h in culture`, run: () => game.toast("Hold the micropipette with a tip and right-click a well to add a drug to it.") }; + case "tipbox": return { label: `Pipette tips: ${t.state.left} left`, run: () => game.toast("Hold the micropipette, then right-click the box to fit a tip.") }; + case "tipwaste": return { label: "Tip waste", run: () => game.toast("Hold the micropipette with a used tip and right-click here to eject it.") }; + case "tuberack": return { label: "Tube rack", run: () => game.toast("Hold a microtube and right-click the rack to stand it in a hole.") }; + case "platereader": return { label: "Plate reader: hold a plate to read it", run: () => game.toast("Bring the 6-well plate from the incubator, then right-click the reader.") }; + case "hemocytometer": return { label: "Hemocytometer", run: () => game.toast("Load 10 µL of cells mixed with trypan blue with the micropipette, then clip it onto the microscope.") }; } return null; } diff --git a/web/lab3d/js/journal.js b/web/lab3d/js/journal.js index eded4fb..9630929 100644 --- a/web/lab3d/js/journal.js +++ b/web/lab3d/js/journal.js @@ -1,18 +1,23 @@ -// The lab journal: tasks, what you observed on each slide, and the growth -// curves the CellSim engine produced for each culture dish. -import { SPECIMENS } from "./specimens.js"; +// The lab journal: tasks, what you observed on each slide, the growth curves +// and dose–response the CellSim engine produced, and your own results. +import { SPECIMENS, STAGES } from "./specimens.js"; +import { WELLS } from "./props.js"; +import { fmtConc } from "./items.js"; const KEY = "cellsim-lab:journal:v1"; const FACTS = { onion: { kind: "plant", shape: "Long bricks in neat rows", wall: "Yes", chloro: "None", vacuole: "Yes, large" }, elodea: { kind: "plant", shape: "Small bricks, full of green dots", wall: "Yes", chloro: "Yes, many", vacuole: "Yes, large" }, cheek: { kind: "animal", shape: "Flat and irregular", wall: "No", chloro: "None", vacuole: "No" }, + redonion: { kind: "plant", shape: "Long bricks, red sap", wall: "Yes", chloro: "None", vacuole: "Yes, red" }, + root: { kind: "plant", shape: "Small boxes, big nuclei", wall: "Yes", chloro: "None", vacuole: "Small" }, }; export class Journal { constructor() { try { this.data = JSON.parse(localStorage.getItem(KEY)) || {}; } catch (e) { this.data = {}; } this.data.obs = this.data.obs || {}; + this.data.results = this.data.results || {}; } save() { try { localStorage.setItem(KEY, JSON.stringify(this.data)); } catch (e) { /* private window */ } } observe(spec, patch) { @@ -21,14 +26,15 @@ export class Journal { for (const k of ["stain", "cover", "size"]) if (patch[k] != null) d[k] = patch[k]; this.save(); } - render(tab, tasks, dishes) { + result(key, value) { this.data.results[key] = { ...value, at: Date.now() }; this.save(); } + render(tab, tasks, dishes, plate) { if (tab === "tasks") { const v = tasks.view(); if (!v) return `

Free roam: no task list. Pick an experiment from the title screen to get one.

`; return `

${v.title}

    ${v.steps.map((s) => `
  1. ${s.text}
  2. `).join("")}
${v.finished ? `

Experiment complete.

` : ""}`; } if (tab === "obs") { - const order = ["onion", "elodea", "cheek"], o = this.data.obs; + const order = ["onion", "redonion", "elodea", "root", "cheek"], o = this.data.obs; const seen = (s) => (o[s]?.mag || 0) >= 100; const rows = [ ["Stain", (s) => o[s]?.stain || "—"], @@ -42,16 +48,50 @@ export class Journal { ]; return `
${order.map((s) => ``).join("")}${rows.map(([l, f]) => `${order.map((s) => ``).join("")}`).join("")}
${SPECIMENS[s].name}
${FACTS[s].kind} cell
${l}${f(s)}
-

Rows fill in once you've seen a sample in focus at 100× or more. These slides are drawn from measured cell sizes; they are not simulated.

`; + ${this.mitosisHTML()}${this.osmosisHTML()} +

Rows fill in once you've seen a sample in focus at 100× or more. These slides are drawn from measured cell sizes and stage proportions; they are not simulated by CellSim.

`; } - // Culture: live cell count over time for each dish, straight from the engine. + // Culture: dose–response, cell counts, and live cells over time, all from the engine. + const parts = [this.doseHTML(plate), this.countHTML()]; const withData = dishes.filter((d) => d.state.series.length); - if (!withData.length) return `

No culture data yet. Look at a dish under the microscope, or incubate one, and the CellSim engine's counts appear here.

`; - return chart(withData) + withData.map((d) => { - const last = d.state.series[d.state.series.length - 1]; - const drugs = d.state.events.length ? d.state.events.map((e) => `${e.t} h: ${Object.entries(e.conc).map(([k, v]) => `${k} ${v.toFixed(2)} µM`).join(", ")}`).join(" · ") : "no drug"; - return `

${d.name}: ${last.n_live} live cells at ${d.state.t} h (started with ${d.state.series[0].n_live}) · ${last.n_apoptotic} apoptotic · treatment: ${drugs}

`; - }).join("") + `

Every number here comes from cellsim.cell.dish, running in your browser.

`; + if (withData.length) { + parts.push(`

Growth

` + chart(withData) + withData.map((d) => { + const last = d.state.series[d.state.series.length - 1]; + const drugs = d.state.events.length ? d.state.events.map((e) => `${e.t} h: ${Object.entries(e.conc).map(([k, v]) => `${k} ${fmtConc(v)}`).join(", ")}`).join(" · ") : "no drug"; + return `

${d.name}: ${last.n_live} live cells at ${d.state.t} h (started with ${d.state.series[0].n_live}) · ${last.n_apoptotic} apoptotic · treatment: ${drugs}

`; + }).join("")); + } + const body = parts.filter(Boolean).join(""); + if (!body) return `

No culture data yet. Look at a dish under the microscope, incubate one, or read the 6-well plate, and the CellSim engine's numbers appear here.

`; + return body + `

Every number here comes from cellsim.cell.dish, running in your browser.

`; + } + + mitosisHTML() { + const m = this.data.results.mitosis; + if (!m || !m.total) return ""; + const dividing = m.total - m.counts[0]; + return `

Mitosis in the root tip

You classified ${m.total} cells: ${STAGES.map((s, i) => `${s.toLowerCase()} ${m.counts[i]}`).join(", ")}. + Mitotic index = dividing ÷ all = ${dividing} ÷ ${m.total} = ${(dividing / m.total * 100).toFixed(1)} %. You got ${m.right} of ${m.total} right first time.

+

In a growing onion root tip about 10–15 % of cells near the tip are dividing. Prophase is the longest stage, so it is the one you see most.

`; + } + osmosisHTML() { + const o = this.data.results.osmosis; + if (!o || !o.log?.length) return ""; + return `

Osmosis in red onion cells

    ${o.log.map((e) => `
  • ${e}
  • `).join("")}
+

Water moves out of the cells into a more concentrated solution, so the protoplast shrinks from the wall (plasmolysis); in pure water it moves back in. The wall stops the cell bursting.

`; + } + countHTML() { + const c = this.data.results.count; + if (!c) return ""; + return `

Cell count

${c.text}

`; + } + doseHTML(plate) { + if (!plate || !plate.state.read) return ""; + const st = plate.state, r = st.read; + const rows = r.wells.map((w, i) => `${WELLS[i]}${w.dose > 0 ? `${w.drug} ${fmtConc(w.dose)}` : "none (control)"}${w.live}${w.viability.toFixed(0)} %`).join(""); + return `

Dose–response · ${plate.name} at ${r.t} h

${doseChart(r)} +

${r.ic50 ? `IC50 ≈ ${fmtConc(r.ic50)} of ${r.drug}: the dose that leaves half as many live cells as the control.` : r.note}

+
${rows}
WellDrugLive cellsViability
`; } } @@ -70,3 +110,23 @@ function chart(dishes) { }).join(""); return `${ticksN}${ticksT}${lines}live cells`; } + +// Viability against dose on a log scale, with the 50 % line and the IC50. +function doseChart(r) { + const pts = r.wells.filter((w) => w.dose > 0).sort((a, b) => a.dose - b.dose); + if (!pts.length) return ""; + const W = 640, H = 260, L = 50, B = 34, T = 14, Rr = 40; + const lo = Math.floor(Math.log10(pts[0].dose)), hi = Math.ceil(Math.log10(pts[pts.length - 1].dose) + 0.01); + const x = (d) => L + ((Math.log10(d) - lo) / Math.max(1, hi - lo)) * (W - L - Rr), y = (v) => H - B - (Math.min(v, 120) / 120) * (H - B - T); + let g = ""; + for (let e = lo; e <= hi; e++) g += `${fmtConc(10 ** e)}`; + for (const v of [0, 50, 100]) g += `${v}%`; + g += ``; + g += ``; + const line = pts.map((p) => `${x(p.dose).toFixed(1)},${y(p.viability).toFixed(1)}`).join(" "); + g += ``; + g += pts.map((p) => ``).join(""); + if (r.ic50) g += `IC50`; + g += `live cells, % of control`; + return `${g}`; +} diff --git a/web/lab3d/js/liquids.js b/web/lab3d/js/liquids.js index 201293d..d5fa5c3 100644 --- a/web/lab3d/js/liquids.js +++ b/web/lab3d/js/liquids.js @@ -3,15 +3,22 @@ // and drug concentrations dilute by volume, which is what the engine gets. import * as THREE from "three"; +// osm is osmolarity (osmol/L), used for osmosis in onion cells. export const SOLUTIONS = { - water: { name: "Distilled water", color: "#d7ebf2", strength: 0.02, alpha: 0.22 }, - tap: { name: "Tap water", color: "#d2e6ee", strength: 0.02, alpha: 0.22 }, - saline: { name: "Saline 0.9%", color: "#dcecf2", strength: 0.02, alpha: 0.22 }, - iodine: { name: "Iodine solution", color: "#8a4a12", strength: 1, alpha: 0.9, stain: "iodine" }, - mb: { name: "Methylene blue", color: "#1b48b0", strength: 1.3, alpha: 0.92, stain: "mb" }, + water: { name: "Distilled water", color: "#d7ebf2", strength: 0.02, alpha: 0.22, osm: 0 }, + tap: { name: "Tap water", color: "#d2e6ee", strength: 0.02, alpha: 0.22, osm: 0.01 }, + saline: { name: "Saline 0.9%", color: "#dcecf2", strength: 0.02, alpha: 0.22, osm: 0.29 }, + salt: { name: "Salt solution 1 M", color: "#e4eef0", strength: 0.02, alpha: 0.24, osm: 1.86, note: "1 mol/L NaCl" }, + iodine: { name: "Iodine solution", color: "#8a4a12", strength: 1, alpha: 0.9, stain: "iodine", glass: "amber", osm: 0.05 }, + mb: { name: "Methylene blue", color: "#1b48b0", strength: 1.3, alpha: 0.92, stain: "mb", glass: "blue", osm: 0.03 }, + toluidine: { name: "Toluidine blue 0.05%", color: "#3b2f8f", strength: 1.3, alpha: 0.92, stain: "toluidine", glass: "amber", osm: 0.03, note: "Stains DNA" }, + hcl: { name: "Hydrochloric acid 1 M", color: "#eef2e4", strength: 0.02, alpha: 0.24, hazard: "!", osm: 2, note: "CORROSIVE" }, ethanol: { name: "Ethanol 70%", color: "#e9f1f3", strength: 0.01, alpha: 0.18 }, disinfectant: { name: "Disinfectant 1%", color: "#bfe3a6", strength: 0.3, alpha: 0.5 }, - medium: { name: "Culture medium (phenol red)", color: "#dc4a63", strength: 0.6, alpha: 0.7 }, + medium: { name: "Culture medium (phenol red)", color: "#dc4a63", strength: 0.6, alpha: 0.7, osm: 0.3 }, + trypsin: { name: "Trypsin-EDTA 0.25%", color: "#e98a96", strength: 0.3, alpha: 0.5, osm: 0.3, cap: 0xd8342a, note: "Detaches cells" }, + trypan: { name: "Trypan blue 0.4%", color: "#2c3d9e", strength: 1.2, alpha: 0.9, osm: 0.3, note: "Stains dead cells" }, + cells: { name: "Cell suspension", color: "#e7a3ad", strength: 0.4, alpha: 0.6, osm: 0.3 }, // Drug stocks. µM is the stock concentration; the dish dilutes it. paclitaxel: { name: "Paclitaxel 10 µM", color: "#f2f1ea", strength: 0.01, alpha: 0.25, drug: "paclitaxel", uM: 10 }, doxorubicin: { name: "Doxorubicin 20 µM", color: "#cf2a1e", strength: 0.9, alpha: 0.8, drug: "doxorubicin", uM: 20 }, @@ -49,8 +56,18 @@ export class Container { const got = this.take(Math.min(mL, room)); let moved = 0; for (const k in got) moved += other.add(k, got[k]); + // Which dish a cell suspension came from travels with it. + if (this.meta && got.cells) other.meta = { ...this.meta }; return moved; } + // Osmolarity of the mixture, osmol/L, weighted by volume. + osmolarity() { + const v = this.volume; + if (v <= 0) return 0; + let o = 0; + for (const k in this.c) o += (SOLUTIONS[k]?.osm ?? 0.3) * this.c[k]; + return o / v; + } dominant() { let best = null, w = 0; for (const k in this.c) { const s = this.c[k] * (SOLUTIONS[k]?.strength ?? 0.05); if (s > w) { w = s; best = k; } } @@ -93,7 +110,8 @@ export class Container { export function fmtVol(mL) { if (mL >= 10) return `${mL.toFixed(0)} mL`; if (mL >= 1) return `${mL.toFixed(1)} mL`; - return `${(mL * 1000).toFixed(0)} µL`; + if (mL >= 0.001) return `${(mL * 1000).toFixed(0)} µL`; + return `${(mL * 1000).toFixed(1)} µL`; } /* A liquid column inside a cylindrical vessel: its height follows the fill diff --git a/web/lab3d/js/main.js b/web/lab3d/js/main.js index deccc22..9090047 100644 --- a/web/lab3d/js/main.js +++ b/web/lab3d/js/main.js @@ -1,25 +1,31 @@ // CellSim: starts the renderer, loads the lab, and runs the game. import * as THREE from "three"; -import { loadAssets } from "./assets.js"; +import { loadAssets, enableShadows } from "./assets.js"; import { buildRoom } from "./room.js"; import { Player } from "./player.js"; -import { createItems, getActions, Item } from "./items.js"; +import { createItems, getActions, Item, fmtConc, sentence } from "./items.js"; import { HUD } from "./hud.js"; import { Tasks, EXPERIMENTS } from "./tasks.js"; import { Journal } from "./journal.js"; import { createScope } from "./scope.js"; import { Engine } from "./engine.js"; +import { Outliner } from "./outline.js"; +import { search, buildIndex, norm, Tracker } from "./finder.js"; +import { sfx, unlockAudio } from "./audio.js"; import { settings, saveSettings, detectPreset, activePreset } from "./settings.js"; import * as P from "./props.js"; const $ = (id) => document.getElementById(id); -const REACH = 2.6; +const REACH = 2.4; +const DISH_AREA_UM2 = 2.15e9; // growth area of a 60 mm dish, 21.5 cm² +const GLASSY = new Set(["slide", "coverslip", "beaker", "dropper", "stock", "drug", "dish", "tube", "hemocytometer", "watchglass", "trypsin", "plate"]); const TIPS = [ "Left-click takes things into your pocket. Right-click uses them.", + "Can't find something? Press F and type its name. Typos are fine.", "Lower a cover slip slowly by holding right-click: a flat drop traps air bubbles.", "Start every slide with the 4× lens, then go up one lens at a time.", "The living cells in the incubator are simulated by the CellSim engine, cell by cell.", - "Dish B is your control: treat Dish A, keep B untreated, and compare.", + "A fresh pipette tip for every solution, or you carry one into the next.", "Low graphics saves battery: no shadows, 30 frames a second, and no drawing when nothing moves.", ]; @@ -48,12 +54,17 @@ class Game { r.toneMapping = THREE.ACESFilmicToneMapping; r.toneMappingExposure = 1.0; r.shadowMap.type = THREE.PCFSoftShadowMap; + // The lab barely moves, so the sun's shadows are redrawn only when something does. + r.shadowMap.autoUpdate = false; + this.shadowsDirty = true; + r.info.autoReset = false; // F3 counts the whole frame, outline pass included this.scene = new THREE.Scene(); this.scene.background = new THREE.Color(0x222629); this.camera = new THREE.PerspectiveCamera(settings.fov, 1, 0.03, 60); this.scene.add(this.camera); this.hand = new THREE.Group(); this.camera.add(this.hand); + this.outliner = new Outliner(r, { scale: this.preset.key === "low" ? 0.4 : 0.6 }); this.resize(); addEventListener("resize", () => this.resize()); @@ -70,25 +81,34 @@ class Game { this.room = buildRoom(this.scene, assets, this.preset); this.player = new Player(this.camera); + this.player.onStep = (loud) => sfx.step(loud); this.inv = new Inventory(); this.selected = 0; - this.tasks = new Tasks((key) => { HUD.tasks(this.tasks.view()); if (key) HUD.toast("Step done ✓", "good"); }); + this.tasks = new Tasks((key) => { HUD.tasks(this.tasks.view()); if (key) { HUD.toast("Step done ✓", "good"); sfx.ok(); } }); this.journal = new Journal(); this.engine = new Engine((state, text) => HUD.engine(state, text)); const made = createItems(this, assets, this.room); this.items = made.items; - this.incubator = { dishes: [...made.dishes] }; + this.plate = made.plate; + this.incubator = { dishes: [...made.dishes, made.plate] }; this.dishes = made.dishes; this.stageItem = null; this.lightsOn = true; this.anims = []; this.iconCache = new Map(); + this.tracker = new Tracker(this); + this.ghost = new THREE.Mesh(new THREE.RingGeometry(0.86, 1, 40), new THREE.MeshBasicMaterial({ color: 0x58c46e, transparent: true, opacity: 0.75, depthWrite: false, polygonOffset: true, polygonOffsetFactor: -4 })); + this.ghost.rotation.x = -Math.PI / 2; + this.ghost.visible = false; + this.ghost.raycast = () => {}; + this.scene.add(this.ghost); this.scope = createScope({ resolution: this.preset.key === "low" ? 560 : this.preset.key === "ultra" ? 1024 : 768, onFocus: (obj, spec) => this.onFocus(obj, spec), onExit: () => this.exitScope(), - toast: (t, k) => HUD.toast(t, k), + toast: (t, k) => this.toast(t, k), observe: (s, p) => this.journal.observe(s, p), + onEvent: (name, data) => this.onScopeEvent(name, data), }); for (const b of this.room.blinds) this.setBlinds(b, false, true); this.applyPreset(); @@ -107,11 +127,12 @@ class Game { /* ---------- graphics ---------- */ resize() { - const w = innerWidth, h = innerHeight; - this.renderer.setPixelRatio(Math.min(devicePixelRatio || 1, this.preset.pixelRatio)); + const w = innerWidth, h = innerHeight, pr = Math.min(devicePixelRatio || 1, this.preset.pixelRatio); + this.renderer.setPixelRatio(pr); this.renderer.setSize(w, h, false); this.camera.aspect = w / h; this.camera.updateProjectionMatrix(); + this.outliner.resize(w, h, pr); this.dirty = true; } applyPreset() { @@ -129,6 +150,7 @@ class Game { room.hemi.intensity = p.env ? 0.35 : 1.25; room.lamps.forEach((l, i) => (l.visible = this.lightsOn && i < p.lamps)); this.scene.traverse((o) => { if (o.material) (Array.isArray(o.material) ? o.material : [o.material]).forEach((m) => (m.needsUpdate = true)); }); + this.shadowsDirty = true; this.resize(); $("qualityNote").textContent = `Using ${p.label} graphics${settings.quality === "auto" ? ` (picked for ${this.detected.gpu || "this computer"})` : ""}. ${p.fps ? `Capped at ${p.fps} fps.` : "No frame cap."}`; } @@ -156,9 +178,9 @@ class Game { this.player.pitch = -0.12; HUD.tasks(this.tasks.view()); this.updateHotbar(); - if (id === "culture") this.engine.start().catch(() => {}); + if (["culture", "dose", "count"].includes(id)) this.engine.start().catch(() => {}); if (lock) this.lock(); - HUD.toast("WASD to walk, mouse to look. Left-click takes, right-click uses."); + HUD.toast("WASD to walk, mouse to look. Left-click takes, right-click uses. F finds anything."); } lock() { if (this.screen === "play" && !this.ui) this.canvas.requestPointerLock?.()?.catch?.(() => {}); } openUI(id) { @@ -202,20 +224,22 @@ class Game { const a = b.dataset.pause; if (a === "resume") { this.closeAllUI(); this.lock(); } else if (a === "journal") this.openJournal(); + else if (a === "finder") { this.closeAllUI(); this.openFinder(); } else if (a === "title") { this.closeAllUI(); this.leave(); } else this.openUI(a); }); for (const b of document.querySelectorAll("[data-back]")) b.addEventListener("click", () => { this.closeUI(); if (!this.ui && this.screen === "play") this.lock(); }); // Settings - const q = $("setQuality"), fps = $("setFps"), sens = $("setSens"), fov = $("setFov"), inv = $("setInvert"), bob = $("setBob"); - q.value = settings.quality; fps.value = settings.fps; sens.value = settings.sensitivity; fov.value = settings.fov; inv.checked = settings.invertY; bob.checked = settings.bob; + const q = $("setQuality"), fps = $("setFps"), sens = $("setSens"), fov = $("setFov"), inv = $("setInvert"), bob = $("setBob"), snd = $("setSound"); + q.value = settings.quality; fps.value = settings.fps; sens.value = settings.sensitivity; fov.value = settings.fov; inv.checked = settings.invertY; bob.checked = settings.bob; snd.checked = settings.sound; const onSet = () => { - Object.assign(settings, { quality: q.value, fps: fps.value, sensitivity: +sens.value, fov: +fov.value, invertY: inv.checked, bob: bob.checked }); + Object.assign(settings, { quality: q.value, fps: fps.value, sensitivity: +sens.value, fov: +fov.value, invertY: inv.checked, bob: bob.checked, sound: snd.checked }); saveSettings(); + if (settings.sound) unlockAudio(); this.preset = activePreset(this.detected.pick); this.applyPreset(); }; - for (const el of [q, fps, sens, fov, inv, bob]) el.addEventListener("change", onSet); + for (const el of [q, fps, sens, fov, inv, bob, snd]) el.addEventListener("change", onSet); // Credits $("creditsBody").innerHTML = CREDITS; // Journal tabs @@ -243,10 +267,38 @@ class Game { if (b.dataset.inc === "wait") this.incubate(+b.dataset.h); else if (b.dataset.inc === "take") { const d = this.incubator.dishes.find((x) => x.id === b.dataset.id); - if (d && this.give(d)) this.emit("dish-taken"); // take() also removes it from the incubator + if (d && this.give(d)) this.emit(d.kind === "plate" ? "plate-taken" : "dish-taken"); // take() also removes it from the incubator this.renderIncubator(); } }); + // Find anything + const inp = $("findInput"); + inp.addEventListener("input", () => { this.findSel = 0; this.renderFind(); }); + inp.addEventListener("keydown", (e) => { + const n = (this.findList || []).length; + if (e.key === "ArrowDown") { e.preventDefault(); this.findSel = Math.min(n - 1, (this.findSel || 0) + 1); this.renderFind(false); } + else if (e.key === "ArrowUp") { e.preventDefault(); this.findSel = Math.max(0, (this.findSel || 0) - 1); this.renderFind(false); } + else if (e.key === "Enter") { e.preventDefault(); if (n) this.chooseFind(this.findSel || 0); } + }); + $("findResults").addEventListener("click", (e) => { const li = e.target.closest("[data-i]"); if (li) this.chooseFind(+li.dataset.i); }); + $("finder").addEventListener("click", (e) => { if (e.target.id === "finder") { this.closeUI(); this.lock(); } }); + // Micropipette volume + const setVol = (v) => { + const p = this.pipItem; + if (!p) return; + p.state.vol = THREE.MathUtils.clamp(Math.round(v), 2, 200); + p.refresh(); + $("pipVol").textContent = p.state.vol; $("pipRange").value = p.state.vol; + HUD.held(this.held); + sfx.click(); + if (p.state.vol === 10) this.emit("vol:10"); + }; + $("pipRange").addEventListener("input", (e) => setVol(+e.target.value)); + $("pipettePanel").addEventListener("click", (e) => { + const b = e.target.closest("[data-pip],[data-pipset]"); + if (!b || !this.pipItem) return; + setVol(b.dataset.pipset ? +b.dataset.pipset : this.pipItem.state.vol + +b.dataset.pip); + }); } renderExperiments() { @@ -257,7 +309,7 @@ class Game { bindInput() { const c = this.canvas; - c.addEventListener("click", () => { if (this.screen === "play" && !document.pointerLockElement) this.lock(); }); + c.addEventListener("click", () => { unlockAudio(); if (this.screen === "play" && !document.pointerLockElement) this.lock(); }); document.addEventListener("pointerlockchange", () => { this.locked = document.pointerLockElement === c; if (!this.locked && this.screen === "play" && !this.ui && !this.unlockingForUI) this.openUI("pause"); @@ -274,6 +326,7 @@ class Game { document.addEventListener("mouseup", (e) => { if (this.locked && e.button === 2) this.release(); }); document.addEventListener("wheel", (e) => { if (!this.locked) return; this.select((this.selected + (e.deltaY > 0 ? 1 : 8)) % 9); }, { passive: true }); document.addEventListener("keydown", (e) => { + unlockAudio(); if (e.code === "F3") { e.preventDefault(); $("debug").hidden = !$("debug").hidden; return; } if (this.screen === "scope") { if (e.code === "Escape") this.exitScope(); return; } if (this.screen !== "play") return; @@ -285,6 +338,8 @@ class Game { else if (e.code === "KeyQ") this.dropHeld(); else if (e.code === "KeyE") this.openInventory(); else if (e.code === "KeyJ") this.openJournal(); + else if (e.code === "KeyF") { e.preventDefault(); this.tracker.target ? this.tracker.stop() : this.openFinder(); } + else if (e.code === "KeyR" && this.held?.kind === "pipette") this.openPipette(this.held); else this.player.keys.add(e.code); this.lastInput = performance.now(); }); @@ -303,10 +358,12 @@ class Game { updateHotbar() { HUD.hotbar(this.inv, this.selected, (it) => this.iconFor(it)); HUD.held(this.held); - // Show the selected item in your hand. + // Show the selected item in your hand. It casts no shadow there: the + // shadows are only redrawn when something in the lab moves. while (this.hand.children.length) this.hand.remove(this.hand.children[0]); const it = this.held; if (it) { + it.obj.userData.pose?.("hand"); if (!it.size) { it.obj.removeFromParent(); it.obj.position.set(0, 0, 0); it.obj.rotation.set(0, 0, 0); it.obj.scale.setScalar(1); @@ -316,8 +373,10 @@ class Game { const size = it.size; const s = THREE.MathUtils.clamp(0.15 / Math.max(size.x, size.y, size.z, 0.001), 0.5, 2.4); it.obj.position.set(0.2, -0.2, -0.42); - it.obj.rotation.set(0.15, -0.5, 0); - it.obj.scale.setScalar(s); + it.obj.rotation.set(it.kind === "pipette" ? 0.05 : 0.15, -0.5, it.kind === "pipette" ? 0.25 : 0); + it.obj.scale.setScalar(it.kind === "pipette" ? 1.1 : s); + it.obj.traverse((m) => { if (m.isMesh) m.castShadow = false; }); + if (it.obj.userData.blob) it.obj.userData.blob.visible = false; this.hand.add(it.obj); } this.dirty = true; @@ -326,43 +385,65 @@ class Game { if (it === this.stageItem) { this.stageItem = null; } const empty = !this.held; const i = this.inv.add(it, empty ? this.selected : null); - if (i < 0) { HUD.toast("Your pockets are full. Put something down first (Q).", "warn"); return false; } + if (i < 0) { this.toast("Your pockets are full. Put something down first (Q).", "warn"); return false; } it.obj.removeFromParent(); it.obj.scale.setScalar(1); + it.size = null; + if (it.kind === "tube") it.state.rackHole = null; this.refreshPickRoots(); this.updateHotbar(); HUD.itemName(it.name); - if (it.kind === "dish" && this.incubator.dishes.includes(it)) this.incubator.dishes.splice(this.incubator.dishes.indexOf(it), 1); + if (this.incubator.dishes.includes(it)) this.incubator.dishes.splice(this.incubator.dishes.indexOf(it), 1); + this.shadowsDirty = true; + sfx.take(); return true; } give(it) { if (!this.items.includes(it)) this.items.push(it); return this.take(it); } place(it, point) { this.inv.remove(it); it.obj.removeFromParent(); + it.obj.userData.pose?.("rest"); it.obj.scale.setScalar(1); it.obj.position.copy(point); it.obj.rotation.set(0, this.player.yaw + Math.PI / 2, 0); + enableShadows(it.obj); + if (it.obj.userData.blob) it.obj.userData.blob.visible = true; this.scene.add(it.obj); this.refreshPickRoots(); this.updateHotbar(); + this.shadowsDirty = true; + GLASSY.has(it.kind) ? sfx.glass() : sfx.place(); } dropHeld() { const it = this.held; if (!it) return; const hit = this.aim; - if (hit && hit.surface) this.place(it, hit.point); + if (hit && hit.surface && (!hit.item || hit.item.kind === "tile") && !this.placeBlocked(it, hit.point, hit.item)) this.place(it, hit.point); else { const f = new THREE.Vector3(-Math.sin(this.player.yaw), 0, -Math.cos(this.player.yaw)); this.place(it, this.player.pos.clone().addScaledVector(f, 0.6).setY(0)); } } + // Something already standing where you're about to put an item down. + placeBlocked(held, p, onItem) { + const r = held.foot || 0.03; + for (const it of this.items) { + if (it === held || it === onItem || it.obj.parent !== this.scene) continue; + if (it.kind === "tube" && it.state.rackHole != null) continue; + const q = it.obj.position; + if (q.y > p.y + 0.02 || q.y < p.y - 0.25) continue; // on another surface + if (Math.hypot(q.x - p.x, q.z - p.z) < (r + (it.foot || 0.03)) * 0.8) return it; + } + return null; + } dispose(it, { quiet = false } = {}) { this.inv.remove(it); it.obj.removeFromParent(); this.items.splice(this.items.indexOf(it), 1); this.refreshPickRoots(); this.updateHotbar(); - if (!quiet) HUD.toast(`${it.name} thrown away`); + this.shadowsDirty = true; + if (!quiet) this.toast(`${it.name} thrown away`); } openInventory() { this.invPick = null; HUD.inventoryGrids(this.inv, null, (it) => this.iconFor(it)); $("wearing").textContent = this.player.goggles ? "Wearing: safety goggles" : "Not wearing goggles"; this.openUI("inventory"); } @@ -380,11 +461,13 @@ class Game { } const o = it.obj.clone(); o.position.set(0, 0, 0); o.rotation.set(0, 0.6, 0); o.scale.setScalar(1); + o.traverse((m) => { if (m.name === "shadow") m.visible = false; }); this.iconScene.add(o); this.iconScene.environment = this.envMap; const b = new THREE.Box3().setFromObject(o), c = b.getCenter(new THREE.Vector3()), sz = b.getSize(new THREE.Vector3()).length(); this.iconCam.position.copy(c).add(new THREE.Vector3(0.45, 0.55, 0.9).multiplyScalar(sz * 1.25)); this.iconCam.lookAt(c); + const auto = r.shadowMap.autoUpdate; r.setRenderTarget(this.iconRT); r.setClearColor(0x000000, 0); r.clear(); @@ -392,6 +475,7 @@ class Game { const px = new Uint8Array(N * N * 4); r.readRenderTargetPixels(this.iconRT, 0, 0, N, N, px); r.setRenderTarget(null); + r.shadowMap.autoUpdate = auto; this.iconScene.remove(o); const cv = document.createElement("canvas"); cv.width = cv.height = N; const g = cv.getContext("2d"), img = g.createImageData(N, N); @@ -416,7 +500,7 @@ class Game { if (!shown(o)) continue; // rays hit hidden meshes too; skip them const up = h.face && h.face.normal.clone().transformDirection(o.matrixWorld).y > 0.7; const itemRoot = o.userData.itemRoot; - // Items count as surfaces too, so you can set one thing on another. + // Items count as surfaces too, so you can set a slide on the tile. if (itemRoot && itemRoot.userData.item) return { item: itemRoot.userData.item, point: h.point, dist: h.distance, surface: up }; let t = o; while (t && !t.userData.target) t = t.parent; @@ -426,6 +510,24 @@ class Game { } return null; } + // The white outline, the crosshair, and the ring where a held item would go. + updateAimCues() { + const a = this.actions, aim = this.aim; + const useful = !!(a && (a.left || a.right)); + const obj = !useful || !aim ? null : aim.item ? (aim.item === this.stageItem ? this.room.scope : aim.item.obj) : aim.furniture || null; + if (this.outliner.set("hover", obj)) this.dirty = true; + const ch = (this.crosshair = this.crosshair || document.querySelector(".crosshair")); + ch.classList.toggle("on", useful && !a.right?.blocked); + ch.classList.toggle("blocked", !!a?.right?.blocked); + const ring = a && (a.right?.place || a.right?.blocked) && aim?.point; + if (ring) { + this.ghost.position.copy(aim.point).y += 0.0015; + this.ghost.scale.setScalar(this.held?.foot || 0.03); + this.ghost.material.color.set(a.right.blocked ? 0xff7466 : 0x58c46e); + } + if (!!ring !== this.ghost.visible || ring) this.dirty = true; + this.ghost.visible = !!ring; + } press(button) { if (!button) return; const a = this.actions; @@ -442,9 +544,68 @@ class Game { if (this.holding) { const h = this.holding; this.holding = null; HUD.hold(null); h.act.run(h.t >= h.act.hold); this.afterAction(); } if (this.holdingLens) { this.holdingLens.end(); this.holdingLens = null; } } - afterAction() { this.updateHotbar(); this.refreshPickRoots(); this.dirty = true; } + afterAction() { this.updateHotbar(); this.refreshPickRoots(); this.dirty = true; this.shadowsDirty = true; } emit(ev) { this.tasks.event(ev); } - toast(text, kind) { HUD.toast(text, kind); } + toast(text, kind) { HUD.toast(text, kind); if (kind === "warn") sfx.warn(); } + sfx(name) { sfx[name]?.(); } + + /* ---------- finding things ---------- */ + openFinder() { + if (this.screen !== "play") return; + this.openUI("finder"); + const inp = $("findInput"); + inp.value = ""; + this.findSel = 0; + this.renderFind(); + setTimeout(() => inp.focus(), 0); + } + renderFind(rebuild = true) { + const q = $("findInput").value; + let head = ""; + if (rebuild) { + if (q.trim()) this.findList = search(this, q); + else { + // Nothing typed yet: what the current step needs. + const v = this.tasks.view(); + const step = v && !v.finished ? v.steps[v.now].text : ""; + const words = new Set(norm(step).split(" ").map((w) => w.replace(/s$/, ""))); + const pos = this.player.pos; + this.findList = step ? buildIndex(this) + .filter((e) => e.terms.some((t) => t.length > 3 && t.split(" ").every((w) => words.has(w.replace(/s$/, ""))))) + .map((e) => ({ ...e, dist: e.object ? e.object.getWorldPosition(new THREE.Vector3()).distanceTo(pos) : 0 })) + .sort((a, b) => a.dist - b.dist).slice(0, 5) : []; + this.findHead = this.findList.length ? "For this step" : ""; + } + } + head = q.trim() ? "" : this.findHead; + const list = this.findList || []; + const sel = Math.min(this.findSel || 0, Math.max(0, list.length - 1)); + $("findResults").innerHTML = list.length + ? (head ? `
  • ${head}
  • ` : "") + list.map((e, i) => `
  • ${esc(e.name)}${esc(capital(e.where || "in the lab"))}${e.object ? `${e.dist.toFixed(1)} m` : "with you"}
  • `).join("") + : `
  • ${q.trim() ? "Nothing like that in the lab. Try another word." : "Type what you're looking for."}
  • `; + } + chooseFind(i) { + const e = (this.findList || [])[i]; + if (!e) return; + this.closeUI(); + if (!e.object) { + const slot = this.inv.slots.indexOf(e.item); + if (slot >= 0 && slot < 9) { this.select(slot); this.toast(`${e.name} is in your hotbar, slot ${slot + 1}: it's in your hand now.`); } + else this.toast(`${e.name} is in your inventory. Press E to move it to your hotbar.`); + } else { + this.tracker.start(e); + this.toast(`Follow the blue marker to the ${sentence(e.name)} (${e.where || "in the lab"}). Press F to stop.`); + } + this.lock(); + } + + /* ---------- the micropipette ---------- */ + openPipette(p) { + this.pipItem = p; + $("pipVol").textContent = Math.round(p.state.vol); + $("pipRange").value = p.state.vol; + this.openUI("pipettePanel"); + } /* ---------- lab equipment ---------- */ wearGoggles(it) { @@ -452,12 +613,13 @@ class Game { $("goggleFrame").hidden = false; this.dispose(it, { quiet: true }); this.emit("goggles"); - HUD.toast("Goggles on", "good"); + this.toast("Goggles on", "good"); } - washHands() { this.player.cleanHands = true; this.emit("hands"); HUD.toast("Hands clean", "good"); } + washHands() { this.player.cleanHands = true; this.emit("hands"); this.toast("Hands clean", "good"); } runTap() { const w = this.room.water; w.visible = true; + sfx.pour(); clearTimeout(this.tapT); this.tapT = setTimeout(() => { w.visible = false; this.dirty = true; }, 1600); } @@ -467,6 +629,7 @@ class Game { this.room.tubeMat.color.set(this.lightsOn ? 0xf4f7ff : 0x3a3d40); this.room.lightSwitch.userData.rocker.rotation.x = this.lightsOn ? 0 : 0.3; this.room.hemi.intensity = (this.preset.env ? 0.35 : 1.25) * (this.lightsOn ? 1 : 0.4); + sfx.click(); } setBlinds(b, down, instant) { const stack = b.userData.stack; @@ -476,6 +639,7 @@ class Game { else this.tween(0.6, stack.scale.y, sy, (v) => { stack.scale.y = v; }); const open = this.room.blinds.filter((x) => !x.userData.down).length; this.room.sun.intensity = 0.6 + (open / this.room.blinds.length) * 2.6; + this.shadowsDirty = true; } toggleBlinds(b) { this.setBlinds(b, !b.userData.down); } toggleDrawer(d) { @@ -483,16 +647,23 @@ class Game { if (!d.userData.spare) d.userData.spare = { ...SPARES[d.userData.target.index % SPARES.length], left: 3 }; const from = d.position.z, to = d.userData.closedZ + (d.userData.open ? 0.3 : 0); this.tween(0.35, from, to, (v) => (d.position.z = v)); - if (d.userData.open && d.userData.spare) HUD.toast(`Inside: ${d.userData.spare.label} (left-click to take)`); + sfx.place(); + if (d.userData.open && d.userData.spare) this.toast(`Inside: ${d.userData.spare.label} (left-click to take)`); } takeSpare(d) { const s = d.userData.spare; - if (!s || s.left <= 0) return HUD.toast("This drawer is empty."); + if (!s || s.left <= 0) return this.toast("This drawer is empty."); s.left--; this.give(s.make()); if (s.left <= 0) d.userData.spare = { ...s, label: "nothing left", left: 0 }; } tween(dur, a, b, fn) { this.anims.push({ t: 0, dur, a, b, fn }); } + inWaterBath(wg) { + const bath = this.items.find((i) => i.kind === "waterbath"); + if (!bath || wg.obj.parent !== this.scene) return false; + const a = wg.obj.position, b = bath.obj.position; + return Math.hypot(a.x - b.x, a.z - b.z) < 0.12 && a.y > b.y + 0.05; + } putOnStage(it) { this.inv.remove(it); @@ -501,10 +672,12 @@ class Game { it.obj.scale.setScalar(1); it.obj.position.copy(scope.userData.stage); it.obj.rotation.set(0, Math.PI / 2, 0); + if (it.obj.userData.blob) it.obj.userData.blob.visible = false; scope.add(it.obj); this.stageItem = it; - this.emit(it.kind === "dish" ? "dish-stage" : "stage"); - HUD.toast(`${it.name} clipped onto the stage. Right-click the microscope to look.`); + this.emit({ dish: "dish-stage", plate: "plate-stage", hemocytometer: "hemo-stage" }[it.kind] || "stage"); + this.toast(`${it.name} clipped onto the stage. Right-click the microscope to look.`); + sfx.glass(); this.afterAction(); } takeFromStage() { if (this.stageItem) this.take(this.stageItem); } @@ -519,13 +692,19 @@ class Game { $("scope").hidden = false; if (it.kind === "slide") { const st = it.state, stain = it.container.stain() || "water"; - const names = { onion: "Onion skin", cheek: "Cheek cells", elodea: "Pondweed leaf" }; - const stainName = stain === "iodine" ? "Iodine" : stain === "mb" ? "Methylene blue" : it.container.empty ? "Dry" : "Water"; - this.scope.open({ kind: "slide", title: `${st.sample ? names[st.sample] : "Empty slide"} · ${stainName.toLowerCase()}`, stainName, - prep: { specimen: st.sample, stain, cover: st.cover || "none" } }); + const names = { onion: "Onion skin", cheek: "Cheek cells", elodea: "Pondweed leaf", redonion: "Red onion skin", root: "Root tip squash" }; + const stainName = { iodine: "Iodine", mb: "Methylene blue", toluidine: "Toluidine blue" }[stain] || (it.container.empty ? "Dry" : P.shortName(it.container.dominant())); + st.tally = st.tally || { counts: [0, 0, 0, 0, 0], total: 0, right: 0, named: new Set() }; + const last = st.osmo[st.osmo.length - 1]; + this.scope.open({ kind: "slide", title: `${st.sample ? names[st.sample] : "Empty slide"} · ${sentence(stainName)}`, stainName, tally: st.tally, + medium: last ? `${sentence(P.shortName(st.mediumName || "water"))} (${last.osm.toFixed(2)} osmol/L)` : "nothing", + prep: { specimen: st.sample, stain, cover: st.cover || "none", softened: st.softened, squashed: st.squashed, osmo: st.osmo } }); return; } + if (it.kind === "hemocytometer") return this.enterHemo(it); + if (it.kind === "plate") return this.enterWell(it, it.state.view || 0); // A living culture: show what the engine says the dish looks like now. + if (it.state.detached) return this.scope.open({ kind: "wait", title: it.name, text: "The cells are floating in suspension now. Count them in the hemocytometer." }); this.scope.open({ kind: "wait", title: it.name, text: this.engine.version ? "Simulating the cells…" : "Starting the CellSim engine (the first time downloads Python, about 30 s)…" }); try { await this.simulate(it); @@ -539,6 +718,49 @@ class Game { const tint = `#${color.clone().lerp(new THREE.Color(0xe8e4dc), 0.82).getHexString()}`; return { kind: "culture", title: `${d.name} · A549 · ${d.state.events.length ? "treated" : "untreated"}`, header: d.state.header, snap: d.state.snap, time: d.state.t, tint }; } + // One well of the 6-well plate, simulated on its own. + async enterWell(plate, i) { + plate.state.view = i; + const st = plate.state, ws = st.wells[i]; + const conc = ws.events.length ? ws.events[ws.events.length - 1].conc : {}; + const label = Object.keys(conc).length ? Object.entries(conc).map(([k, v]) => `${k} ${fmtConc(v)}`).join(", ") : "no drug"; + const base = { title: `${plate.name} · well ${P.WELLS[i]} · ${label}`, wells: P.WELLS, well: i }; + this.scope.open({ kind: "wait", ...base, text: this.engine.version ? "Simulating the cells in this well…" : "Starting the CellSim engine…" }); + try { + if (!ws.result || ws.result.t !== st.t) { + const out = await this.runWell(plate, i); + ws.result = { header: out.header, snap: out.snap, t: st.t }; + } + if (this.screen !== "scope" || this.stageItem !== plate || st.view !== i) return; + this.scope.open({ kind: "culture", ...base, header: ws.result.header, snap: ws.result.snap, time: st.t, tint: "#e6d6d9", keepView: true }); + } catch (e) { + this.scope.open({ kind: "wait", ...base, text: `The engine could not run: ${e.message}` }); + } + } + runWell(plate, i) { + const st = plate.state, ws = st.wells[i]; + const drugs = [...new Set(ws.events.flatMap((e) => Object.keys(e.conc)))]; + return this.engine.dish({ label: `well ${P.WELLS[i]}`, line: st.line, drugs, events: ws.events, t: st.t, n_seed: 40, grid: 40, seed: st.seed, every: 12 }); + } + // The hemocytometer: cells from a dish's suspension, at the engine's count. + async enterHemo(it) { + const c = it.container; + const title = "Hemocytometer"; + const dish = this.items.find((d) => d.id === c.meta?.dish); + if (c.empty || !dish || !c.c.cells) return this.scope.open({ kind: "wait", title, text: c.empty ? "The chamber is empty. Load 10 µL of cells mixed with trypan blue first." : "There are no cells in this liquid. Lift cells off a dish with trypsin first." }); + this.scope.open({ kind: "wait", title, text: this.engine.version ? "Getting the dish's cells from the engine…" : "Starting the CellSim engine (the first time downloads Python, about 30 s)…" }); + try { + await this.simulate(dish); + } catch (e) { return this.scope.open({ kind: "wait", title, text: `The engine could not run: ${e.message}` }); } + const last = dish.state.series[dish.state.series.length - 1]; + const h = dish.state.header, patch = (h.grid_shape[0] * h.spacing_um) * (h.grid_shape[1] * h.spacing_um); + const scale = DISH_AREA_UM2 / patch; // the engine simulates one patch of the dish + const live = last.n_live * scale, dead = (last.n_apoptotic + last.n_necrotic) * scale + live * 0.04; // trypsin kills a few + const frac = c.c.cells / c.volume; // 1 mL of suspension, diluted in the chamber liquid + it.state.counted = it.state.counted || new Set(); + const hemo = { livePerMl: live * frac, deadPerMl: dead * frac, trypan: !!c.c.trypan, dilution: 1 / frac, t: dish.state.t, dish: dish.name, seed: 7 + dish.state.t, counted: it.state.counted }; + if (this.screen === "scope" && this.stageItem === it) this.scope.open({ kind: "hemo", title: `Hemocytometer · ${dish.name} cells at ${dish.state.t} h`, hemo }); + } exitScope() { this.screen = "play"; $("scope").hidden = true; @@ -547,16 +769,36 @@ class Game { this.dirty = true; } onFocus(obj, spec) { - if (spec.kind === "slide") this.emit(`focus:${obj}`); + if (spec.kind === "slide" || spec.kind === "hemo") this.emit(`focus:${obj}`); else { const d = this.stageItem; - if (obj >= 10) { + if (obj >= 10 && d && d.kind === "dish") { this.emit("observe:culture"); - if (d && d.state.t > 0 && d.state.events.length) this.emit("observe:after"); - if (d && d.name === "Dish B" && d.state.t > 0) this.emit("compare"); + if (d.state.t > 0 && d.state.events.length) this.emit("observe:after"); + if (d.name === "Dish B" && d.state.t > 0) this.emit("compare"); } } } + onScopeEvent(name, data) { + const it = this.stageItem; + if (name === "well" && it?.kind === "plate") this.enterWell(it, data); + else if (name === "classify") { + this.journal.result("mitosis", { counts: data.counts, total: data.total, right: data.right }); + if (data.total >= 25) this.emit("classify:25"); + if (data.counts.slice(1).every((n) => n > 0)) this.emit("stages:all"); + } else if (name === "count:4") this.emit("count:4"); + else if (name === "count") { + const e = (n) => `${(n / 10 ** Math.floor(Math.log10(n || 1))).toFixed(1)} × 10^${Math.floor(Math.log10(n || 1))}`; + this.journal.result("count", { text: `${data.dish} at ${data.t} h: you counted ${data.live} live and ${data.dead} dead cells in 4 squares, so ${e(data.perMl)} live cells per mL and ${data.viab.toFixed(0)} % viability. The engine's dish really held ${e(data.truePerMl)} live cells per mL.` }); + this.emit("count:done"); + } else if (name === "osmo" && it?.kind === "slide") { + const st = it.state, last = st.osmo[st.osmo.length - 1]; + const log = (this.journal.data.results.osmosis?.log || []).slice(-8); + const where = `${P.shortName(st.mediumName || "water")} (${last ? last.osm.toFixed(2) : "?"} osmol/L)`; + if (data >= 0.6 && !st.plas) { st.plas = true; log.push(`In ${where}: ${(data * 100).toFixed(0)} % of the cells in view plasmolysed.`); this.journal.result("osmosis", { log }); this.emit("osmo:plasmolysed"); } + if (st.plas && data <= 0.1 && last && last.osm < 0.3) { st.plas = false; log.push(`Back in ${where}: the cells swelled against their walls again.`); this.journal.result("osmosis", { log }); this.emit("osmo:recovered"); } + } + } // Run the engine for a dish up to its current time. async simulate(d) { @@ -572,41 +814,114 @@ class Game { if (ev) ev.conc = conc; else st.events.push({ t: st.t, conc }); st.needs = true; this.emit("drug-drop"); - HUD.toast(`${d.name} now has ${Object.entries(conc).map(([k, v]) => `${k} ${v.toFixed(2)} µM`).join(", ")}`); + this.toast(`${d.name} now has ${Object.entries(conc).map(([k, v]) => `${k} ${fmtConc(v)}`).join(", ")}`); + } + wellDosed(plate, i) { + const st = plate.state, ws = st.wells[i], conc = plate.wells[i].container.drugs(); + const ev = ws.events.find((e) => e.t === st.t); + if (ev) ev.conc = conc; else ws.events.push({ t: st.t, conc }); + ws.result = null; st.read = null; + const treated = st.wells.filter((w) => w.events.length); + const doses = new Set(treated.map((w) => Object.values(w.events[w.events.length - 1].conc).reduce((a, b) => a + b, 0).toPrecision(2))); + if (doses.size >= 3) this.emit("dose:3"); + if (doses.size >= 3 && treated.length < 6) this.emit("control"); + if (treated.length === 6) this.toast("Every well has a drug now: with no untreated control, there's nothing to compare against.", "warn"); + this.toast(`Well ${P.WELLS[i]}: ${Object.entries(conc).map(([k, v]) => `${k} ${fmtConc(v)}`).join(", ")}`); } putInIncubator(d) { this.inv.remove(d); d.obj.removeFromParent(); this.incubator.dishes.push(d); this.afterAction(); - HUD.toast(`${d.name} is in the incubator. Right-click it to let time pass.`); + this.toast(`${d.name} is in the incubator. Right-click it to let time pass.`); } openIncubator() { this.renderIncubator(); this.openUI("incubatorPanel"); } renderIncubator() { const ds = this.incubator.dishes; - $("incubatorBody").innerHTML = (ds.length ? ds.map((d) => `
    ${d.name}${d.state.t} h in culture · ${d.state.events.length ? "treated" : "no drug"} + const what = (d) => d.kind === "plate" ? `${d.state.wells.filter((w) => w.events.length).length} of 6 wells treated` : d.state.detached ? "cells lifted off" : d.state.events.length ? "treated" : "no drug"; + $("incubatorBody").innerHTML = (ds.length ? ds.map((d) => `
    ${d.name}${d.state.t} h in culture · ${what(d)}
    `).join("") : `

    The incubator is empty.

    `) + - (ds.length ? `

    Let time pass for every dish inside

    ${[6, 12, 24].map((h) => ``).join("")}
    ` : "") + - `

    ${this.engine.version ? `CellSim ${this.engine.version} simulates each dish.` : "The CellSim engine starts the first time you incubate or look at a dish."}

    `; + (ds.length ? `

    Let time pass for everything inside

    ${[6, 12, 24, 72].map((h) => ``).join("")}
    ` : "") + + `

    ${this.engine.version ? `CellSim ${this.engine.version} simulates each dish and well.` : "The CellSim engine starts the first time you incubate or look at a dish."}

    `; } async incubate(h) { const ds = [...this.incubator.dishes]; for (const d of ds) { d.state.t += h; d.state.needs = true; } this.renderIncubator(); - if (ds.some((d) => d.state.events.length)) this.emit("incubate"); + if (ds.some((d) => d.kind === "dish" && d.state.events.length)) this.emit("incubate"); + if (ds.some((d) => d.kind === "plate" && d.state.t >= 72 && d.state.wells.some((w) => w.events.length))) this.emit("incubate:72"); try { for (const d of ds) { + if (d.kind !== "dish" || d.state.detached) continue; await this.simulate(d); const last = d.state.series[d.state.series.length - 1]; - HUD.toast(`${d.name} at ${d.state.t} h: ${last.n_live} live cells, ${last.n_apoptotic} dying`, "good"); + this.toast(`${d.name} at ${d.state.t} h: ${last.n_live} live cells, ${last.n_apoptotic} dying`, "good"); } - } catch (e) { HUD.toast(`The engine could not run: ${e.message}`, "warn"); } + for (const d of ds) if (d.kind === "plate") this.toast(`${d.name} at ${d.state.t} h. Read it in the plate reader to see how each well did.`, "good"); + } catch (e) { this.toast(`The engine could not run: ${e.message}`, "warn"); } this.renderIncubator(); } + // The plate reader: every well simulated to now, live cells relative to the untreated wells. + async readPlate(plate, reader) { + if (this.reading) return; + const show = reader.obj.userData.screen, st = plate.state; + if (st.t < 24) this.toast("The drug has barely had time to act: 72 h in the incubator gives a clear result.", "warn"); + this.reading = true; + this.inv.remove(plate); + plate.obj.removeFromParent(); + plate.obj.userData.pose?.("rest"); + plate.obj.position.copy(reader.obj.localToWorld(new THREE.Vector3(-0.06, 0.044, 0.19))); + plate.obj.rotation.set(0, reader.obj.rotation.y, 0); + enableShadows(plate.obj); + if (plate.obj.userData.blob) plate.obj.userData.blob.visible = true; + this.scene.add(plate.obj); + this.afterAction(); + sfx.click(); + try { + const wells = []; + for (let i = 0; i < 6; i++) { + show([`READING ${P.WELLS[i]}`, `${i + 1} of 6 wells`], "#f0b44c"); + this.dirty = true; + const out = await this.runWell(plate, i); + st.wells[i].result = { header: out.header, snap: out.snap, t: st.t }; + const last = out.series[out.series.length - 1], ev = st.wells[i].events; + const conc = ev.length ? ev[ev.length - 1].conc : {}; + const dose = Object.values(conc).reduce((a, b) => a + b, 0); + wells.push({ live: last.n_live, dose, drug: Object.keys(conc).filter((k) => conc[k] > 0).join(" + ") || "none" }); + } + const ctrl = wells.filter((w) => w.dose <= 0); + const base = ctrl.length ? ctrl.reduce((a, w) => a + w.live, 0) / ctrl.length : Math.max(...wells.map((w) => w.live)); + for (const w of wells) w.viability = (w.live / Math.max(1, base)) * 100; + const treated = wells.filter((w) => w.dose > 0).sort((a, b) => a.dose - b.dose); + const drugs = [...new Set(treated.map((w) => w.drug))]; + let ic50 = null, note = ""; + for (let k = 0; k + 1 < treated.length; k++) { + const a = treated[k], b = treated[k + 1]; + if (a.viability >= 50 && b.viability < 50) { + const la = Math.log10(a.dose), lb = Math.log10(b.dose); + ic50 = 10 ** (la + ((a.viability - 50) * (lb - la)) / (a.viability - b.viability)); + break; + } + } + if (!ic50) note = !treated.length ? "No well had a drug in it." : treated.every((w) => w.viability >= 50) ? "Every dose left more than half the cells alive: try higher doses (a bigger volume)." : treated[0].viability < 50 ? "Even the lowest dose killed more than half the cells: try smaller volumes." : "The curve doesn't cross 50 % cleanly. Try doses spread over a wider range."; + if (!ctrl.length) note += " There was no untreated well, so viability is relative to the best well."; + if (drugs.length > 1) note += " The wells had different drugs: use one drug for a clean curve."; + st.read = { t: st.t, wells, ic50, drug: drugs.join(", ") || "none", note: note.trim() }; + show(["DONE", ic50 ? `IC50 ${fmtConc(ic50)}` : "See the journal"], "#7dffb0"); + this.emit("read"); + this.toast(`Plate read. Open the journal (J), Cell culture tab, for the dose–response curve.`, "good"); + } catch (e) { + show(["ERROR", "Engine failed"], "#ff7466"); + this.toast(`The engine could not run: ${e.message}`, "warn"); + } + this.reading = false; + this.dirty = true; + } openJournal() { this.journalTab = this.journalTab || "tasks"; this.renderJournal(); this.openUI("journal"); } renderJournal() { for (const b of document.querySelectorAll("[data-tab]")) b.setAttribute("aria-selected", String(b.dataset.tab === this.journalTab)); - $("journalBody").innerHTML = this.journal.render(this.journalTab, this.tasks, this.dishes); + $("journalBody").innerHTML = this.journal.render(this.journalTab, this.tasks, this.dishes, this.plate); + if (this.journalTab === "culture" && this.plate.state.read) this.emit("dr-curve"); } openReader() { const e = this.tasks.exp; @@ -618,6 +933,7 @@ class Game { leave() { this.journal.save(); this.player.keys.clear(); + this.tracker.stop(); this.showTitle(); $("mainMenu").querySelector('[data-menu="experiments"]').textContent = "Start a new experiment"; } @@ -637,6 +953,7 @@ class Game { a.fn(a.a + (a.b - a.a) * k, k); if (a.t >= 1) this.anims.splice(i, 1); animating = true; + this.shadowsDirty = true; } if (this.screen === "scope") { this.scope.update(dt); this.lastDraw = now; return; } if (this.screen === "title") { @@ -658,9 +975,17 @@ class Game { this.actions = getActions(this, this.held, this.aim); this.tick = (this.tick || 0) + 1; const live = this.locked || this.forceLock; + if (!live) this.actions = { target: "" }; + this.updateAimCues(); const sig = live ? `${this.actions.left?.label}|${this.actions.right?.label}|${this.actions.target}` : "unlocked"; if (sig !== this.promptSig) { this.promptSig = sig; HUD.prompt(live ? this.actions : { target: "Click to look around" }); } + if (this.tracker.target) { + const t = this.tracker.target; + if (this.tracker.reached(this.aim)) { this.toast(`Found it: the ${sentence(t.name)}`, "good"); this.tracker.stop(); } + else if (t.item && !t.item.obj.parent) this.tracker.stop(); + } } + if (this.tracker.target) this.tracker.update(this.camera); if (this.holding) { this.holding.t += dt; HUD.hold(Math.min(1, this.holding.t / this.holding.act.hold)); @@ -674,7 +999,11 @@ class Game { this.debug(now, dt); } render(now) { + if (this.shadowsDirty && this.preset.shadows) this.renderer.shadowMap.needsUpdate = true; + this.shadowsDirty = false; + this.renderer.info.reset(); this.renderer.render(this.scene, this.camera); + if (this.screen === "play") this.outliner.draw(this.scene, this.camera); this.lastDraw = now; this.dirty = false; this.frames = (this.frames || 0) + 1; @@ -701,12 +1030,15 @@ function shown(o) { for (let x = o; x; x = x.parent) if (!x.visible) return false; return true; } +function esc(s) { return String(s).replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c]); } +function capital(s) { return s.charAt(0).toUpperCase() + s.slice(1); } const SPARES = [ { label: "a new box of slides", make: () => { const it = new Item("slidebox", "Box of slides", P.makeBox({ w: 0.085, h: 0.03, d: 0.035, color: 0x2a5fb0, labelLines: ["Microscope slides", "76 × 26 mm"] })); it.state.left = 10; return it; } }, { label: "a new pack of cover slips", make: () => { const it = new Item("coverbox", "Cover slips", P.makeBox({ w: 0.032, h: 0.014, d: 0.032, color: 0xdfe6ea, labelLines: ["Cover slips"] })); it.state.left = 20; return it; } }, { label: "a fresh 30 mL bottle of iodine", make: () => { const m = P.makeDropperBottle("iodine", 30); return new Item("dropper", "Iodine dropper bottle", m.obj, { container: m.container, liquid: m.liquid, solution: "iodine" }); } }, { label: "a fresh 30 mL bottle of methylene blue", make: () => { const m = P.makeDropperBottle("mb", 30); return new Item("dropper", "Methylene blue dropper bottle", m.obj, { container: m.container, liquid: m.liquid, solution: "mb" }); } }, + { label: "a fresh bottle of toluidine blue", make: () => { const m = P.makeDropperBottle("toluidine", 30); return new Item("dropper", "Toluidine blue dropper bottle", m.obj, { container: m.container, liquid: m.liquid, solution: "toluidine" }); } }, ]; const CREDITS = ` @@ -715,7 +1047,8 @@ const CREDITS = `

    Models, textures and lighting from Poly Haven (CC0): yellow onion, metal stool, steel shelves, fluorescent lights, drawer cabinet, clipboard, stationery, wall clock, magnifying glass, binder notebook, metal office desk, floor tiles, painted plaster, hospital room HDRI.

    Models from Sketchfab (CC Attribution 4.0): "Chemistry Lab Table" by Jawahar Yokesh · "lab bench" by Konstantin_Keller (the incubator) · "Compound Microscope" by kg007 · "Door Classroom" by Mehdi Shahsavan.

    -

    Built in code: the room, slides, cover slips, bottles, beakers, culture dishes, the pondweed tank, the lab tools, the safety goggles, the hand sanitizer and the window blinds.

    `; +

    Built in code: the room, slides, cover slips, bottles, beakers, culture dishes, the 6-well plate, the micropipette and tips, microtubes, the hemocytometer, the plate reader, the water bath, the pondweed tank, the lab tools, the safety goggles, the hand sanitizer and the window blinds. The sound effects are made in code too.

    +

    Not simulated: the onion, root tip, red onion, cheek and pondweed slides are drawn at measured sizes and stage proportions; osmosis follows a simple osmotic model. The living A549 cells are CellSim's.

    `; new Game().boot().catch((e) => { console.error(e); diff --git a/web/lab3d/js/outline.js b/web/lab3d/js/outline.js new file mode 100644 index 0000000..a7d866e --- /dev/null +++ b/web/lab3d/js/outline.js @@ -0,0 +1,100 @@ +// Outlines around whole objects: white for what you aim at, blue for what you +// searched for. The objects are drawn flat into a small mask with no depth +// test, so a searched-for object shows through walls; one full-screen pass +// then draws the mask's edges over the finished frame. Works for any shape, +// and costs nothing while nothing is outlined. +import * as THREE from "three"; + +const HOVER = 2, TRACK = 3; // render layers used only by the mask pass + +const EDGE = /* glsl */ ` + uniform sampler2D mask; + uniform vec2 texel; + uniform vec3 hoverColor; + uniform vec3 trackColor; + uniform float fill; + varying vec2 vUv; + void main() { + vec2 c = texture2D(mask, vUv).rg; + vec2 m = vec2(0.0); + for (int i = 0; i < 8; i++) { + float a = float(i) * 0.785398; + vec2 d = vec2(cos(a), sin(a)) * texel; + m = max(m, texture2D(mask, vUv + d * 1.5).rg); + m = max(m, texture2D(mask, vUv + d * 3.0).rg * 0.7); + } + vec2 edge = clamp(m - c, 0.0, 1.0); + vec4 col = vec4(trackColor, 1.0) * c.g * fill; + col = mix(col, vec4(trackColor, 1.0), edge.g); + col = mix(col, vec4(hoverColor, 0.85), edge.r); + gl_FragColor = col; + }`; + +export class Outliner { + constructor(renderer, { scale = 0.5 } = {}) { + this.r = renderer; + this.scale = scale; + this.rt = new THREE.WebGLRenderTarget(2, 2, { depthBuffer: false }); + this.mats = { + [HOVER]: new THREE.MeshBasicMaterial({ color: 0xff0000, depthTest: false, depthWrite: false }), + [TRACK]: new THREE.MeshBasicMaterial({ color: 0x00ff00, depthTest: false, depthWrite: false, transparent: true, blending: THREE.AdditiveBlending }), + }; + this.quadMat = new THREE.ShaderMaterial({ + uniforms: { + mask: { value: this.rt.texture }, texel: { value: new THREE.Vector2(0.5, 0.5) }, + hoverColor: { value: new THREE.Color(0xffffff) }, trackColor: { value: new THREE.Color(0x5b8cff) }, fill: { value: 0.22 }, + }, + vertexShader: "varying vec2 vUv; void main() { vUv = uv; gl_Position = vec4(position.xy, 0.0, 1.0); }", + fragmentShader: EDGE, + transparent: true, depthTest: false, depthWrite: false, + }); + this.quad = new THREE.Mesh(new THREE.PlaneGeometry(2, 2), this.quadMat); + this.quad.frustumCulled = false; + this.ortho = new THREE.OrthographicCamera(-1, 1, 1, -1, 0, 1); + this.obj = { [HOVER]: null, [TRACK]: null }; + this.cc = new THREE.Color(); + } + get active() { return !!(this.obj[HOVER] || this.obj[TRACK]); } + // Outline `obj` (or nothing) as the aimed-at or the searched-for object. + set(kind, obj) { + const L = kind === "hover" ? HOVER : TRACK; + if (this.obj[L] === obj) return false; + if (this.obj[L]) this.obj[L].traverse((m) => m.layers.disable(L)); + this.obj[L] = obj || null; + if (obj) obj.traverse((m) => { if (m.isMesh && m.name !== "hitbox" && m.name !== "shadow" && m.material && m.material.visible !== false) m.layers.enable(L); }); + return true; + } + resize(w, h, pixelRatio) { + const s = this.scale * pixelRatio; + this.rt.setSize(Math.max(2, Math.round(w * s)), Math.max(2, Math.round(h * s))); + this.quadMat.uniforms.texel.value.set(1 / this.rt.width, 1 / this.rt.height); + } + // Call right after the frame is drawn. + draw(scene, camera) { + if (!this.active) return; + const r = this.r; + const bg = scene.background, layers = camera.layers.mask, autoClear = r.autoClear, autoShadow = r.shadowMap.autoUpdate; + r.getClearColor(this.cc); + const clearAlpha = r.getClearAlpha(); + scene.background = null; + r.shadowMap.autoUpdate = false; + r.autoClear = false; + r.setRenderTarget(this.rt); + r.setClearColor(0x000000, 0); + r.clear(true, false, false); + for (const L of [HOVER, TRACK]) { + if (!this.obj[L]) continue; + camera.layers.set(L); + scene.overrideMaterial = this.mats[L]; + r.render(scene, camera); + } + scene.overrideMaterial = null; + camera.layers.mask = layers; + scene.background = bg; + r.setRenderTarget(null); + r.setClearColor(this.cc, clearAlpha); + r.render(this.quad, this.ortho); + r.autoClear = autoClear; + r.shadowMap.autoUpdate = autoShadow; + } +} diff --git a/web/lab3d/js/player.js b/web/lab3d/js/player.js index 80dd92e..74c0e5f 100644 --- a/web/lab3d/js/player.js +++ b/web/lab3d/js/player.js @@ -1,23 +1,31 @@ -// First-person movement: WASD, mouse look, jump, sneak and sprint, with -// simple circle-against-box collision so you can't walk through benches. +// First-person movement: WASD, mouse look, jump, sneak and sprint. You speed +// up and slow down over a fraction of a second instead of starting and +// stopping dead, slide along benches instead of sticking to them, and the +// head bob follows your stride, with a footstep at each step. import * as THREE from "three"; import { settings } from "./settings.js"; -const EYE = 1.62, SNEAK_EYE = 1.38, SIT_EYE = 1.22, RADIUS = 0.26; +const EYE = 1.62, SNEAK_EYE = 1.36, SIT_EYE = 1.22, RADIUS = 0.26; +const SPEED = { sneak: 1.0, walk: 2.1, sprint: 3.9 }; // m/s: a brisk indoor walk +const ACCEL = 11, BRAKE = 14, STRIDE = 0.72; // m/s², m/s², metres per step export class Player { constructor(camera) { this.camera = camera; this.pos = new THREE.Vector3(3, 0, 2.9); + this.vel = new THREE.Vector2(); this.yaw = 2.35; this.pitch = -0.12; this.vy = 0; this.keys = new Set(); this.eye = EYE; - this.bob = 0; + this.phase = 0; // stride phase, in steps + this.sway = 0; + this.dip = 0; // the knees bending when you land this.sitting = null; this.zoom = 1; this.moved = false; + this.onStep = null; // (loudness 0..1) for footstep sounds } look(dx, dy) { const k = 0.0022 * settings.sensitivity; @@ -28,6 +36,7 @@ export class Player { const p = stool.position; this.sitting = stool; this.pos.set(p.x, 0, p.z); + this.vel.set(0, 0); } update(dt, colliders) { const k = this.keys; @@ -36,47 +45,90 @@ export class Player { if (k.has("KeyS")) fz -= 1; if (k.has("KeyA")) fx -= 1; if (k.has("KeyD")) fx += 1; - const moving = fx || fz; - if (moving && this.sitting) this.sitting = null; // walking stands you up + const input = fx || fz; + if (input && this.sitting) this.sitting = null; // walking stands you up const sneak = k.has("ShiftLeft") || k.has("ShiftRight"); - const sprint = !sneak && (k.has("ControlLeft") || k.has("ControlRight")); - const speed = sneak ? 1.2 : sprint ? 4.4 : 2.6; + const sprint = !sneak && fz > 0 && (k.has("ControlLeft") || k.has("ControlRight")); + const top = sneak ? SPEED.sneak : sprint ? SPEED.sprint : SPEED.walk; + // The velocity you want, in world space (forward is -z when yaw = 0). + const want = new THREE.Vector2(); + if (input && !this.sitting) { + const len = Math.hypot(fx, fz), sin = Math.sin(this.yaw), cos = Math.cos(this.yaw); + want.set(((fx * cos - fz * sin) / len) * top, ((-fx * sin - fz * cos) / len) * top); + } + const ground = this.pos.y <= 0.0001; + const rate = (want.lengthSq() > 0 ? ACCEL : BRAKE) * (ground ? 1 : 0.25); + const dv = want.clone().sub(this.vel), step = rate * dt; + if (dv.length() <= step) this.vel.copy(want); else this.vel.addScaledVector(dv.normalize(), step); this.moved = false; - if (moving) { - const len = Math.hypot(fx, fz); - const sin = Math.sin(this.yaw), cos = Math.cos(this.yaw); - // Forward is -z when yaw = 0. - const vx = ((fx * cos - fz * sin) / len) * speed * dt; - const vz = ((-fx * sin - fz * cos) / len) * speed * dt; - this.tryMove(vx, 0, colliders); - this.tryMove(0, vz, colliders); - this.bob += dt * (sprint ? 13 : 9); + const speed = this.vel.length(); + if (speed > 0.001) { + const before = this.pos.clone(); + this.pos.x += this.vel.x * dt; + this.pos.z += this.vel.y * dt; + this.collide(colliders); + // Lose the speed you pushed into a wall, so you slide along it. + const moved = this.pos.clone().sub(before); + if (dt > 0) this.vel.set(moved.x / dt, moved.z / dt).clampLength(0, top + 0.01); + if (ground) this.stride(Math.hypot(moved.x, moved.z), speed / SPEED.walk); this.moved = true; - } + } else this.vel.set(0, 0); // Gravity and jumping. - if (k.has("Space") && this.pos.y <= 0.0001 && !this.sitting) this.vy = 3.6; + if (k.has("Space") && ground && !this.sitting) this.vy = 3.6; if (this.vy !== 0 || this.pos.y > 0) { + const wasUp = this.pos.y > 0; this.vy -= 9.8 * dt; this.pos.y = Math.max(0, this.pos.y + this.vy * dt); - if (this.pos.y === 0) this.vy = 0; + if (this.pos.y === 0) { + if (wasUp) { this.dip = Math.min(0.09, -this.vy * 0.022); this.onStep?.(0.9); } + this.vy = 0; + } this.moved = true; } + // Eye height: standing, sneaking or sitting, plus the landing dip. const targetEye = this.sitting ? SIT_EYE : sneak ? SNEAK_EYE : EYE; - this.eye += (targetEye - this.eye) * Math.min(1, dt * 10); - const bobY = settings.bob && moving && this.pos.y === 0 ? Math.sin(this.bob) * 0.025 : 0; + if (Math.abs(targetEye - this.eye) > 0.001) this.moved = true; + this.eye += (targetEye - this.eye) * Math.min(1, dt * 9); + if (this.dip > 0.0005) { this.dip *= Math.exp(-dt * 9); this.moved = true; } else this.dip = 0; + // Head bob: down at each footfall, a little side to side, scaled by speed. + const amp = settings.bob && ground ? Math.min(1.3, speed / SPEED.walk) : 0; + const s = Math.sin(this.phase * Math.PI); + const bobY = amp * (0.016 * (s * s) - 0.008); + this.sway += ((amp ? Math.sin(this.phase * Math.PI * 0.5 + 0.4) * 0.011 * amp : 0) - this.sway) * Math.min(1, dt * 10); const cam = this.camera; - cam.position.set(this.pos.x, this.pos.y + this.eye + bobY, this.pos.z); - cam.rotation.set(this.pitch, this.yaw, 0, "YXZ"); + const sin = Math.sin(this.yaw), cos = Math.cos(this.yaw); + cam.position.set(this.pos.x + cos * this.sway, this.pos.y + this.eye + bobY - this.dip, this.pos.z - sin * this.sway); + cam.rotation.set(this.pitch, this.yaw, amp ? -this.sway * 0.25 : 0, "YXZ"); const fov = settings.fov / this.zoom; if (Math.abs(cam.fov - fov) > 0.01) { cam.fov += (fov - cam.fov) * Math.min(1, dt * 12); cam.updateProjectionMatrix(); this.moved = true; } } - tryMove(dx, dz, colliders) { - const nx = this.pos.x + dx, nz = this.pos.z + dz; - for (const c of colliders) { - if (c.top !== undefined && this.pos.y > c.top - 0.05) continue; // jumping over low things - const cx = Math.max(c.x0, Math.min(nx, c.x1)), cz = Math.max(c.z0, Math.min(nz, c.z1)); - if ((nx - cx) ** 2 + (nz - cz) ** 2 < RADIUS * RADIUS) return; + // Advance the stride; a footstep sounds each time a foot comes down. + stride(dist, loud) { + const before = Math.floor(this.phase); + this.phase += dist / STRIDE; + if (Math.floor(this.phase) !== before) this.onStep?.(Math.min(1, 0.35 + 0.5 * loud)); + } + // Push the body (a circle) out of every box it overlaps. Doing it twice + // settles corners, where two boxes push at once. + collide(colliders) { + for (let pass = 0; pass < 2; pass++) { + for (const c of colliders) { + if (c.top !== undefined && this.pos.y > c.top - 0.05) continue; // jumping over low things + const cx = Math.max(c.x0, Math.min(this.pos.x, c.x1)), cz = Math.max(c.z0, Math.min(this.pos.z, c.z1)); + let dx = this.pos.x - cx, dz = this.pos.z - cz; + const d2 = dx * dx + dz * dz; + if (d2 >= RADIUS * RADIUS) continue; + if (d2 < 1e-10) { + // The centre is inside the box: leave by the nearest side. + const opts = [[c.x0 - RADIUS - this.pos.x, 0], [c.x1 + RADIUS - this.pos.x, 0], [0, c.z0 - RADIUS - this.pos.z], [0, c.z1 + RADIUS - this.pos.z]]; + opts.sort((a, b) => Math.abs(a[0] + a[1]) - Math.abs(b[0] + b[1])); + this.pos.x += opts[0][0]; this.pos.z += opts[0][1]; + continue; + } + const d = Math.sqrt(d2), push = RADIUS - d; + this.pos.x += (dx / d) * push; + this.pos.z += (dz / d) * push; + } } - this.pos.x = nx; this.pos.z = nz; } } diff --git a/web/lab3d/js/props.js b/web/lab3d/js/props.js index 2dda981..37426a5 100644 --- a/web/lab3d/js/props.js +++ b/web/lab3d/js/props.js @@ -1,16 +1,23 @@ // Small lab equipment built in code at real size (metres), so each piece can // hold a liquid that drains and changes colour. Every prop's origin is the -// middle of its base, so it can be set down on any surface. +// middle of its base, so it can be set down on any surface. Glassware has +// real wall thickness and a rounded lip, which is what makes glass read as +// glass: thick bright edges, thin clear walls. import * as THREE from "three"; import { Container, SOLUTIONS, liquidColumn } from "./liquids.js"; import { link } from "./assets.js"; +import { mergeGeometries } from "three/addons/utils/BufferGeometryUtils.js"; const V2 = THREE.Vector2; export const MAT = { - glass: () => new THREE.MeshPhysicalMaterial({ color: 0xffffff, roughness: 0.04, metalness: 0, transparent: true, opacity: 0.22, ior: 1.5, clearcoat: 1, clearcoatRoughness: 0.05, depthWrite: false, side: THREE.DoubleSide }), - amber: () => new THREE.MeshPhysicalMaterial({ color: 0x6b3510, roughness: 0.08, transparent: true, opacity: 0.72, clearcoat: 1, depthWrite: false }), - blueGlass: () => new THREE.MeshPhysicalMaterial({ color: 0x1d3f8c, roughness: 0.08, transparent: true, opacity: 0.7, clearcoat: 1, depthWrite: false }), + // forceSinglePass: both faces in one draw, not two (three.js draws + // see-through two-sided things twice otherwise). + glass: () => new THREE.MeshPhysicalMaterial({ color: 0xffffff, roughness: 0.03, metalness: 0, transparent: true, opacity: 0.17, ior: 1.5, clearcoat: 1, clearcoatRoughness: 0.04, envMapIntensity: 1.4, depthWrite: false, side: THREE.DoubleSide, forceSinglePass: true }), + plasticClear: () => new THREE.MeshPhysicalMaterial({ color: 0xf4f8fa, roughness: 0.12, transparent: true, opacity: 0.22, clearcoat: 0.6, depthWrite: false, side: THREE.DoubleSide, forceSinglePass: true }), + amber: () => new THREE.MeshPhysicalMaterial({ color: 0x6b3510, roughness: 0.06, transparent: true, opacity: 0.74, clearcoat: 1, envMapIntensity: 1.3, depthWrite: false }), + blueGlass: () => new THREE.MeshPhysicalMaterial({ color: 0x1d3f8c, roughness: 0.06, transparent: true, opacity: 0.72, clearcoat: 1, envMapIntensity: 1.3, depthWrite: false }), steel: () => new THREE.MeshStandardMaterial({ color: 0xc9ced3, metalness: 1, roughness: 0.28 }), + brushed: () => new THREE.MeshStandardMaterial({ color: 0xb8bdc2, metalness: 0.9, roughness: 0.42 }), rubber: () => new THREE.MeshStandardMaterial({ color: 0x202326, roughness: 0.75 }), plastic: (c) => new THREE.MeshStandardMaterial({ color: c, roughness: 0.45 }), paper: (c = 0xf6f4ee) => new THREE.MeshStandardMaterial({ color: c, roughness: 0.9 }), @@ -23,8 +30,35 @@ function mesh(geo, mat, cast = true) { return m; } +/* Merge a group's plain child meshes that share a material into one mesh + each. It looks the same and costs one draw call instead of many, which + matters on older laptops. Meshes with their own material are left alone. */ +function compact(g) { + const byMat = new Map(); + for (const m of g.children) { + if (!m.isMesh || m.isInstancedMesh || m.children.length || !m.visible) continue; + if (!byMat.has(m.material)) byMat.set(m.material, []); + byMat.get(m.material).push(m); + } + for (const [mat, list] of byMat) { + if (list.length < 2) continue; + const geos = list.map((m) => { + m.updateMatrix(); + const geo = (m.geometry.index ? m.geometry.toNonIndexed() : m.geometry.clone()).applyMatrix4(m.matrix); + for (const k of Object.keys(geo.attributes)) if (!["position", "normal", "uv"].includes(k)) geo.deleteAttribute(k); + if (!geo.attributes.uv) geo.setAttribute("uv", new THREE.Float32BufferAttribute(new Float32Array(geo.attributes.position.count * 2), 2)); + return geo; + }); + const merged = mergeGeometries(geos, false); + if (!merged) continue; + for (const m of list) g.remove(m); + g.add(mesh(merged, mat, list.some((m) => m.castShadow))); + } + return g; +} + // A label printed on paper, as a canvas texture. -export function labelTexture(lines, { w = 256, h = 128, bg = "#f7f5ef", fg = "#1d2326", band = null, size = 30 } = {}) { +export function labelTexture(lines, { w = 256, h = 128, bg = "#f7f5ef", fg = "#1d2326", band = null, size = 30, hazard = null } = {}) { const c = document.createElement("canvas"); c.width = w; c.height = h; const g = c.getContext("2d"); @@ -38,6 +72,15 @@ export function labelTexture(lines, { w = 256, h = 128, bg = "#f7f5ef", fg = "#1 g.font = `${i === 0 ? 700 : 500} ${s}px "IBM Plex Sans", Helvetica, sans-serif`; g.fillText(t, w / 2, h * (band ? 0.6 : 0.5) + (i - (n - 1) / 2) * size * 0.95, w - 12); }); + // A small hazard diamond in the corner: red rim, black symbol. + if (hazard) { + const d = h * 0.26, x = w - d * 0.85, y = h - d * 0.85; + g.save(); g.translate(x, y); g.rotate(Math.PI / 4); + g.fillStyle = "#fff"; g.fillRect(-d / 2, -d / 2, d, d); + g.lineWidth = d * 0.12; g.strokeStyle = "#d1242a"; g.strokeRect(-d / 2, -d / 2, d, d); + g.restore(); + g.fillStyle = "#111"; g.font = `700 ${d * 0.6}px sans-serif`; g.fillText(hazard, x, y + d * 0.04); + } const t = new THREE.CanvasTexture(c); t.colorSpace = THREE.SRGBColorSpace; t.anisotropy = 4; @@ -48,34 +91,153 @@ function lathe(points, segments = 32) { return new THREE.LatheGeometry(points.map(([r, y]) => new V2(r, y)), segments); } +/* A vessel with real walls: `outer` runs from the middle of the base out and + up to the rim; the inside follows it `t` in, and a rounded lip joins them. */ +function vessel(outer, t, segments = 40) { + const pts = outer.map(([r, y]) => [r, y]); + const [rt, yt] = outer[outer.length - 1]; + pts.push([rt - t * 0.15, yt + t * 0.45], [rt - t * 0.5, yt + t * 0.55], [rt - t * 0.85, yt + t * 0.45]); + for (let i = outer.length - 1; i >= 1; i--) { + const [r, y] = outer[i]; + pts.push([Math.max(0.0002, r - t), Math.max(y, t)]); + } + pts.push([0.0001, t]); + return lathe(pts, segments); +} + +// Push the rim out into a pouring spout, centred on +z. +function addSpout(geo, yFrom, yTo, amount) { + const p = geo.attributes.position; + for (let i = 0; i < p.count; i++) { + const y = p.getY(i); + if (y < yFrom) continue; + const x = p.getX(i), z = p.getZ(i), r = Math.hypot(x, z); + if (r < 1e-5) continue; + const w = Math.max(0, 1 - Math.abs(Math.atan2(x, z)) / 0.5); + const k = amount * w * w * Math.min(1, (y - yFrom) / (yTo - yFrom)); + p.setXYZ(i, (x / r) * (r + k), y + k * 0.4, (z / r) * (r + k)); + } + geo.computeVertexNormals(); +} + +// A screw cap with grip ribs round its side. +function ribbedCap(r, h, color, ribs = 30) { + const geo = new THREE.CylinderGeometry(r, r, h, ribs * 4, 1); + const p = geo.attributes.position; + for (let i = 0; i < p.count; i++) { + const x = p.getX(i), z = p.getZ(i), rr = Math.hypot(x, z); + if (rr < r * 0.98) continue; // leave the flat top and bottom alone + const k = 1 + 0.045 * Math.max(0, Math.cos(Math.atan2(x, z) * ribs)); + p.setX(i, x * k); p.setZ(i, z * k); + } + geo.computeVertexNormals(); + return mesh(geo, MAT.plastic(color)); +} + +// White enamel scale marks printed on glass, every `step` up to `max`. +function scaleMarks(r, h, max, step, { unit = "mL", y0 = 0.1, span = 0.8, arc = 0.75 } = {}) { + const c = document.createElement("canvas"); + c.width = 96; c.height = 384; + const g = c.getContext("2d"); + g.fillStyle = "rgba(255,255,255,0.95)"; + g.font = "600 22px 'IBM Plex Sans', sans-serif"; + const n = Math.round(max / step); + for (let i = 1; i <= n; i++) { + const y = 384 * (1 - y0) - (i / n) * 384 * span; + const major = i % 2 === 0 || n <= 5; + g.fillRect(0, y - 1.5, major ? 38 : 22, 3); + if (major) g.fillText(`${i * step}`, 44, y + 7); + } + g.fillText(unit, 44, 384 * (1 - y0) - 384 * span - 26); + const t = new THREE.CanvasTexture(c); + t.colorSpace = THREE.SRGBColorSpace; + const m = mesh(new THREE.CylinderGeometry(r + 0.0002, r + 0.0002, h, 24, 1, true, -arc / 2, arc), new THREE.MeshBasicMaterial({ map: t, transparent: true, depthWrite: false }), false); + m.position.y = h / 2; + return m; +} + +// A rounded rectangle outline, for extruded trays, tiles and boxes. +function roundedRect(w, d, r) { + const s = new THREE.Shape(), x = -w / 2, y = -d / 2; + r = Math.min(r, w / 2, d / 2); + s.moveTo(x + r, y); s.lineTo(x + w - r, y); s.quadraticCurveTo(x + w, y, x + w, y + r); + s.lineTo(x + w, y + d - r); s.quadraticCurveTo(x + w, y + d, x + w - r, y + d); + s.lineTo(x + r, y + d); s.quadraticCurveTo(x, y + d, x, y + d - r); + s.lineTo(x, y + r); s.quadraticCurveTo(x, y, x + r, y); + return s; +} + +// A box with softly rounded edges, origin at the middle of its base. +export function roundedBoxGeometry(w, h, d, r = Math.min(w, d) * 0.08, bevel = Math.min(h * 0.25, r * 0.6, 0.002)) { + const geo = new THREE.ExtrudeGeometry(roundedRect(w - 2 * bevel, d - 2 * bevel, Math.max(0.0002, r - bevel)), + { depth: Math.max(0.0001, h - 2 * bevel), bevelEnabled: bevel > 0, bevelThickness: bevel, bevelSize: bevel, bevelSegments: 2, curveSegments: 6 }); + geo.rotateX(-Math.PI / 2); + geo.translate(0, bevel, 0); + return geo; +} + +/* A soft dark patch under a thing standing on a surface: on every graphics + setting, it is what makes objects sit on the bench instead of floating. */ +let shadowTex = null, shadowMat = null; +export function contactShadow(w, d) { + if (!shadowTex) { + const c = document.createElement("canvas"); + c.width = c.height = 64; + const g = c.getContext("2d"); + const grd = g.createRadialGradient(32, 32, 4, 32, 32, 32); + grd.addColorStop(0, "rgba(0,0,0,0.85)"); grd.addColorStop(0.55, "rgba(0,0,0,0.35)"); grd.addColorStop(1, "rgba(0,0,0,0)"); + g.fillStyle = grd; g.fillRect(0, 0, 64, 64); + shadowTex = new THREE.CanvasTexture(c); + shadowMat = new THREE.MeshBasicMaterial({ map: shadowTex, color: 0x000000, transparent: true, opacity: 0.5, depthWrite: false, polygonOffset: true, polygonOffsetFactor: -2 }); + } + const m = new THREE.Mesh(new THREE.PlaneGeometry(1, 1), shadowMat); + m.rotation.x = -Math.PI / 2; + m.scale.set(w * 1.45 + 0.01, d * 1.45 + 0.01, 1); + m.position.y = 0.0004; + m.renderOrder = 1; + m.name = "shadow"; + m.raycast = () => {}; + return m; +} + /* ---------- slide, cover slip and their boxes ---------- */ export function makeSlide() { const g = new THREE.Group(); const L = 0.076, W = 0.026, T = 0.001; - const glass = mesh(new THREE.BoxGeometry(L, T, W), MAT.glass()); - glass.position.y = T / 2; - const frost = mesh(new THREE.BoxGeometry(0.02, T * 1.05, W), MAT.paper(0xeef0ef)); - frost.position.set(-L / 2 + 0.01, T / 2, 0); + const glass = mesh(roundedBoxGeometry(L, T, W, 0.0008, 0.0003), MAT.glass()); + const frost = mesh(new THREE.BoxGeometry(0.02, T * 1.05, W - 0.0004), MAT.paper(0xeef0ef)); + frost.position.set(-L / 2 + 0.0105, T / 2, 0); g.add(glass, frost); // The sample, the drop of liquid and the cover slip, shown as they are added. const sample = mesh(new THREE.CircleGeometry(0.0065, 24), new THREE.MeshStandardMaterial({ color: 0xe9dfc8, roughness: 0.6, transparent: true, opacity: 0.75 }), false); sample.rotation.x = -Math.PI / 2; sample.position.set(0.008, T + 0.0002, 0); sample.visible = false; const drop = mesh(new THREE.SphereGeometry(1, 20, 10, 0, Math.PI * 2, 0, Math.PI / 2), new THREE.MeshPhysicalMaterial({ color: 0xd7ebf2, roughness: 0.05, transparent: true, opacity: 0.5, clearcoat: 1, depthWrite: false }), false); drop.position.set(0.008, T, 0); drop.visible = false; drop.renderOrder = 3; drop.scale.setScalar(0.003); - const cover = mesh(new THREE.BoxGeometry(0.022, 0.0003, 0.022), MAT.glass(), false); - cover.position.set(0.008, T + 0.0007, 0); cover.visible = false; + const cover = mesh(roundedBoxGeometry(0.022, 0.00025, 0.022, 0.0004, 0.0001), MAT.glass(), false); + cover.position.set(0.008, T + 0.0005, 0); cover.visible = false; const label = mesh(new THREE.PlaneGeometry(0.018, 0.022), new THREE.MeshStandardMaterial({ transparent: true, roughness: 0.9 }), false); - label.rotation.x = -Math.PI / 2; label.position.set(-L / 2 + 0.01, T * 1.1, 0); label.visible = false; + label.rotation.x = -Math.PI / 2; label.position.set(-L / 2 + 0.0105, T * 1.1, 0); label.visible = false; g.add(sample, drop, cover, label); link(g, "parts", { sample, drop, cover, label }); return g; } +const SAMPLE_LOOK = { + elodea: { color: 0x4a9a3e, sx: 1.2, sz: 0.55 }, cheek: { color: 0xf0dcd4, sx: 1, sz: 1 }, onion: { color: 0xece3cf, sx: 1, sz: 1 }, + redonion: { color: 0xb3416d, sx: 1, sz: 0.9 }, root: { color: 0xf2efe6, sx: 0.55, sz: 0.2 }, +}; export function updateSlideLook(slide) { const { sample, drop, cover, label } = slide.obj.userData.parts; const s = slide.state; sample.visible = !!s.sample; - if (s.sample) sample.material.color.set(s.sample === "elodea" ? 0x4a9a3e : s.sample === "cheek" ? 0xf0dcd4 : 0xece3cf); + if (s.sample) { + const look = SAMPLE_LOOK[s.sample] || SAMPLE_LOOK.onion; + sample.material.color.set(look.color); + // A squashed root tip spreads into a thin pale smear. + const k = s.squashed ? 1.7 : 1; + sample.scale.set(look.sx * k, look.sz * k * (s.squashed ? 2.4 : 1), 1); + if (s.sample === "root" && slide.container.stain() === "toluidine") sample.material.color.set(0x7d5aa6); + } const v = slide.container.volume; drop.visible = v > 0.001; if (drop.visible) { @@ -83,11 +245,9 @@ export function updateSlideLook(slide) { drop.material.color.copy(color); drop.material.opacity = Math.min(0.9, 0.3 + alpha * 0.6); const r = 0.0035 + Math.sqrt(v) * 0.012; // a 50 µL drop is about 6 mm across - const flat = s.cover ? 0.04 : 1; - drop.scale.set(s.cover ? 0.0105 : r, s.cover ? 0.0003 : r * 0.35 * flat, s.cover ? 0.0105 : r); + drop.scale.set(s.cover ? 0.0105 : r, s.cover ? 0.0003 : r * 0.35, s.cover ? 0.0105 : r); } cover.visible = !!s.cover; - cover.rotation.z = 0; if (s.label && !label.material.map) { label.material.map = labelTexture([s.label], { w: 128, h: 160, bg: "#eef0ef", size: 26 }); label.material.needsUpdate = true; @@ -95,66 +255,81 @@ export function updateSlideLook(slide) { label.visible = !!s.label; } +// A cardboard or plastic box with a lid seam and a printed label on the front and top. export function makeBox({ w, h, d, color, labelLines, band }) { const g = new THREE.Group(); - const body = mesh(new THREE.BoxGeometry(w, h, d), MAT.plastic(color)); - body.position.y = h / 2; - g.add(body); + const mat = MAT.plastic(color); + mat.roughness = 0.7; + const body = mesh(roundedBoxGeometry(w, h * 0.72, d, 0.0015, 0.0006), mat); + const lid = mesh(roundedBoxGeometry(w + 0.0012, h * 0.34, d + 0.0012, 0.0018, 0.0007), mat); + lid.position.y = h * 0.66; + g.add(body, lid); if (labelLines) { - const lab = mesh(new THREE.PlaneGeometry(w * 0.8, h * 0.7), new THREE.MeshStandardMaterial({ map: labelTexture(labelLines, { band }), roughness: 0.85 }), false); - lab.position.set(0, h / 2, d / 2 + 0.0006); - g.add(lab); + const tex = labelTexture(labelLines, { band }); + const front = mesh(new THREE.PlaneGeometry(w * 0.82, h * 0.5), new THREE.MeshStandardMaterial({ map: tex, roughness: 0.85 }), false); + front.position.set(0, h * 0.36, d / 2 + 0.0004); + const top = mesh(new THREE.PlaneGeometry(w * 0.82, d * 0.7), new THREE.MeshStandardMaterial({ map: tex, roughness: 0.85 }), false); + top.rotation.x = -Math.PI / 2; top.position.y = h + 0.0002; + g.add(front, top); } - return g; + return compact(g); } export function makeCoverSlip() { const g = new THREE.Group(); - const s = mesh(new THREE.BoxGeometry(0.022, 0.0004, 0.022), MAT.glass(), false); - s.position.y = 0.0002; + const s = mesh(roundedBoxGeometry(0.022, 0.0004, 0.022, 0.0004, 0.00012), MAT.glass(), false); g.add(s); return g; } /* ---------- bottles and beakers ---------- */ -// A 30 mL dropper bottle with a rubber bulb; its liquid follows the volume. +function bottleGlass(solution) { + const kind = SOLUTIONS[solution]?.glass; + return kind === "amber" ? MAT.amber() : kind === "blue" ? MAT.blueGlass() : MAT.glass(); +} + +// A 30 mL dropper bottle: glass with a ribbed collar, a rubber teat, and the +// glass dropper tube visible inside. Its liquid follows the volume. export function makeDropperBottle(solution, volume = 25) { const s = SOLUTIONS[solution]; const g = new THREE.Group(); - const glassMat = solution === "iodine" ? MAT.amber() : solution === "mb" ? MAT.blueGlass() : MAT.glass(); const r = 0.0175, h = 0.062; - g.add(mesh(lathe([[0.0001, 0], [r, 0], [r, h], [r * 0.55, h + 0.009], [0.0075, h + 0.012], [0.0075, h + 0.016]]), glassMat)); - const cap = mesh(new THREE.CylinderGeometry(0.0095, 0.0095, 0.012, 24), MAT.rubber()); - cap.position.y = h + 0.022; - const bulb = mesh(new THREE.SphereGeometry(0.0085, 20, 14), MAT.rubber()); - bulb.scale.y = 1.35; bulb.position.y = h + 0.037; - g.add(cap, bulb); - const lab = mesh(new THREE.CylinderGeometry(r + 0.0004, r + 0.0004, 0.03, 32, 1, true, -0.9, 1.8), new THREE.MeshStandardMaterial({ map: labelTexture([shortName(solution)], { size: 34, band: s.color }), roughness: 0.85 }), false); - lab.position.y = 0.03; + g.add(mesh(vessel([[0.0001, 0], [r - 0.0022, 0], [r, 0.0022], [r, h], [r * 0.86, h + 0.006], [r * 0.52, h + 0.0105], [0.0079, h + 0.0125], [0.0079, h + 0.019]], 0.0013), bottleGlass(solution))); + const collar = ribbedCap(0.0097, 0.012, 0x24282c, 24); + collar.position.y = h + 0.024; + const teat = mesh(lathe([[0.0001, 0], [0.0062, 0], [0.0068, 0.004], [0.0083, 0.01], [0.0085, 0.016], [0.0069, 0.022], [0.0036, 0.0262], [0.0001, 0.027]], 24), MAT.rubber()); + teat.position.y = h + 0.029; + const tube = mesh(new THREE.CylinderGeometry(0.0017, 0.0011, h + 0.02, 12, 1, true), MAT.glass(), false); + tube.position.y = (h + 0.02) / 2 + 0.009; + g.add(collar, teat, tube); + const lab = mesh(new THREE.CylinderGeometry(r + 0.0004, r + 0.0004, 0.032, 32, 1, true, -0.95, 1.9), new THREE.MeshStandardMaterial({ map: labelTexture([shortName(solution), s.note || "30 mL"], { size: 34, band: s.color, hazard: s.hazard }), roughness: 0.85 }), false); + lab.position.y = 0.031; g.add(lab); - const liq = liquidColumn({ radius: r - 0.0015, bottom: 0.002, depth: h - 0.004 }); + const liq = liquidColumn({ radius: r - 0.0016, bottom: 0.0014, depth: h - 0.003 }); g.add(liq.mesh); const container = new Container(30, { [solution]: volume }); liq.update(container); return { obj: g, container, liquid: liq }; } -// A 500 mL screw-cap reagent bottle with a printed label. -export function makeStockBottle(solution, volume = 450) { +// A 500 mL screw-cap reagent bottle with a pour ring, scale and a printed label. +export function makeStockBottle(solution, volume = 450, { capacity = 500, scale = 1 } = {}) { const s = SOLUTIONS[solution]; const g = new THREE.Group(); - const r = 0.042, h = 0.15; - const glassMat = solution === "iodine" ? MAT.amber() : MAT.glass(); - g.add(mesh(lathe([[0.0001, 0], [r, 0.002], [r, h], [0.03, h + 0.018], [0.016, h + 0.025], [0.016, h + 0.035]], 40), glassMat)); - const cap = mesh(new THREE.CylinderGeometry(0.019, 0.019, 0.022, 28), MAT.plastic(0x2a5fb0)); - cap.position.y = h + 0.046; - g.add(cap); - const lab = mesh(new THREE.CylinderGeometry(r + 0.0006, r + 0.0006, 0.07, 40, 1, true, -1.1, 2.2), new THREE.MeshStandardMaterial({ map: labelTexture([shortName(solution), "Stock · 500 mL"], { w: 320, h: 160, band: s.color, size: 36 }), roughness: 0.85 }), false); - lab.position.y = 0.065; + const r = 0.042 * scale, h = 0.15 * scale; + g.add(mesh(vessel([[0.0001, 0], [r - 0.004, 0], [r, 0.004], [r, h], [r * 0.9, h + 0.012 * scale], [r * 0.66, h + 0.022 * scale], [0.02 * scale, h + 0.028 * scale], [0.02 * scale, h + 0.04 * scale]], 0.0022 * scale, 48), bottleGlass(solution))); + const ring = mesh(new THREE.CylinderGeometry(0.0235 * scale, 0.0235 * scale, 0.006 * scale, 32), MAT.plastic(0xf0f0ea)); + ring.position.y = h + 0.03 * scale; + const cap = ribbedCap(0.0245 * scale, 0.024 * scale, s.cap || 0x2a5fb0, 36); + cap.position.y = h + 0.045 * scale; + g.add(ring, cap); + g.add(scaleMarks(r, h, capacity, capacity / 5, { y0: 0.12, span: 0.78, arc: 0.55 })); + const lab = mesh(new THREE.CylinderGeometry(r + 0.0006, r + 0.0006, 0.07 * scale, 40, 1, true, Math.PI - 1.1, 2.2), new THREE.MeshStandardMaterial({ map: labelTexture([shortName(solution), s.note || `Stock · ${capacity} mL`], { w: 320, h: 160, band: s.color, size: 36, hazard: s.hazard }), roughness: 0.85 }), false); + lab.position.y = 0.065 * scale; g.add(lab); - const liq = liquidColumn({ radius: r - 0.002, bottom: 0.003, depth: h - 0.006 }); + const liq = liquidColumn({ radius: r - 0.0026 * scale, bottom: 0.0024 * scale, depth: h - 0.006 * scale }); g.add(liq.mesh); - const container = new Container(500, { [solution]: volume }); + const container = new Container(capacity, { [solution]: volume }); liq.update(container); return { obj: g, container, liquid: liq }; } @@ -164,37 +339,33 @@ export function makeDrugVial(drug, volume = 8) { const s = SOLUTIONS[drug]; const g = new THREE.Group(); const r = 0.012, h = 0.045; - g.add(mesh(lathe([[0.0001, 0], [r, 0], [r, h], [0.007, h + 0.006], [0.007, h + 0.01]]), MAT.amber())); - const cap = mesh(new THREE.CylinderGeometry(0.0085, 0.0085, 0.01, 20), MAT.plastic(0xd8d8d2)); - cap.position.y = h + 0.015; - const tip = mesh(new THREE.ConeGeometry(0.004, 0.012, 16), MAT.plastic(0xd8d8d2)); - tip.position.y = h + 0.026; + g.add(mesh(vessel([[0.0001, 0], [r - 0.0015, 0], [r, 0.0015], [r, h], [r * 0.86, h + 0.004], [0.0068, h + 0.007], [0.0068, h + 0.012]], 0.001), MAT.amber())); + const cap = ribbedCap(0.0085, 0.01, 0xe9e9e3, 20); + cap.position.y = h + 0.017; + const tip = mesh(lathe([[0.0001, 0], [0.0042, 0], [0.0024, 0.008], [0.0011, 0.013], [0.0001, 0.0135]], 16), MAT.plastic(0xe9e9e3)); + tip.position.y = h + 0.022; g.add(cap, tip); - const lab = mesh(new THREE.CylinderGeometry(r + 0.0004, r + 0.0004, 0.028, 32, 1, true, -1, 2), new THREE.MeshStandardMaterial({ map: labelTexture([shortName(drug), `${s.uM} µM · CYTOTOXIC`], { w: 256, h: 128, band: "#d8342a", size: 30 }), roughness: 0.85 }), false); + const lab = mesh(new THREE.CylinderGeometry(r + 0.0004, r + 0.0004, 0.028, 32, 1, true, -1, 2), new THREE.MeshStandardMaterial({ map: labelTexture([shortName(drug), `${s.uM} µM · CYTOTOXIC`], { w: 256, h: 128, band: "#d8342a", size: 30, hazard: "!" }), roughness: 0.85 }), false); lab.position.y = 0.024; g.add(lab); - const liq = liquidColumn({ radius: r - 0.0012, bottom: 0.0015, depth: h - 0.003 }); + const liq = liquidColumn({ radius: r - 0.0012, bottom: 0.0012, depth: h - 0.003 }); g.add(liq.mesh); const container = new Container(10, { [drug]: volume }); liq.update(container); return { obj: g, container, liquid: liq }; } -// A 250 mL low-form beaker with a pouring lip and printed scale. +// A 250 mL low-form beaker with a pouring spout and an enamel scale. export function makeBeaker(contents = {}, capacity = 250) { const g = new THREE.Group(); const r = 0.035, h = 0.095; - g.add(mesh(lathe([[0.0001, 0], [r, 0], [r, h], [r + 0.003, h + 0.003]], 40), MAT.glass())); - const grad = document.createElement("canvas"); - grad.width = 64; grad.height = 256; - const gg = grad.getContext("2d"); - gg.fillStyle = "rgba(255,255,255,0.9)"; - for (let i = 1; i <= 5; i++) { const y = 256 - i * 44; gg.fillRect(0, y, i % 2 ? 22 : 34, 3); gg.font = "18px sans-serif"; if (i % 2 === 0) gg.fillText(`${i * 50}`, 30, y + 6); } - const gt = new THREE.CanvasTexture(grad); - const marks = mesh(new THREE.CylinderGeometry(r + 0.0003, r + 0.0003, h, 24, 1, true, -0.35, 0.7), new THREE.MeshBasicMaterial({ map: gt, transparent: true, depthWrite: false }), false); - marks.position.y = h / 2; + const geo = vessel([[0.0001, 0], [r - 0.003, 0], [r, 0.003], [r, h - 0.002], [r + 0.0022, h + 0.0015]], 0.0016, 48); + addSpout(geo, h - 0.012, h + 0.003, 0.007); + g.add(mesh(geo, MAT.glass())); + const marks = scaleMarks(r, h, capacity, 50, { y0: 0.04, span: capacity / 300 * 0.92, arc: 0.7 }); + marks.rotation.y = Math.PI; g.add(marks); - const liq = liquidColumn({ radius: r - 0.0015, bottom: 0.0015, depth: h - 0.004 }); + const liq = liquidColumn({ radius: r - 0.0018, bottom: 0.0017, depth: h - 0.006 }); g.add(liq.mesh); const container = new Container(capacity, contents); liq.update(container); @@ -202,22 +373,415 @@ export function makeBeaker(contents = {}, capacity = 250) { } /* ---------- culture dish ---------- */ -export function makeCultureDish(name) { +// A 60 mm polystyrene culture dish with its lid on and a handwritten label. +export function makeCultureDish(name, line = "A549 lung cells") { const g = new THREE.Group(); - const r = 0.03, h = 0.013; - const base = mesh(lathe([[0.0001, 0], [r, 0], [r, h * 0.8]], 48), MAT.glass(), false); - const lid = mesh(lathe([[0.0001, h + 0.001], [r + 0.0015, h + 0.001], [r + 0.0015, h * 0.45]], 48), MAT.glass(), false); + const r = 0.03, h = 0.0125; + const base = mesh(vessel([[0.0001, 0], [r - 0.0008, 0], [r, 0.0008], [r, h]], 0.0008, 56), MAT.plasticClear(), false); + const lid = mesh(lathe([[0.0001, h + 0.0016], [r + 0.0016, h + 0.0016], [r + 0.0019, h + 0.0012], [r + 0.0019, h * 0.45], [r + 0.0012, h * 0.45], [r + 0.0012, h + 0.0009], [0.0001, h + 0.0009]], 56), MAT.plasticClear(), false); g.add(base, lid); - const lab = mesh(new THREE.PlaneGeometry(0.03, 0.012), new THREE.MeshStandardMaterial({ map: labelTexture([name, "A549 lung cells"], { w: 256, h: 100, size: 30 }), roughness: 0.9, transparent: true }), false); - lab.rotation.x = -Math.PI / 2; lab.position.y = h + 0.0013; + const lab = mesh(new THREE.PlaneGeometry(0.03, 0.012), new THREE.MeshStandardMaterial({ map: labelTexture([name, line], { w: 256, h: 100, size: 30 }), roughness: 0.9, transparent: true }), false); + lab.rotation.x = -Math.PI / 2; lab.position.y = h + 0.0019; g.add(lab); - const liq = liquidColumn({ radius: r - 0.0012, bottom: 0.0008, depth: 0.004 }); + const liq = liquidColumn({ radius: r - 0.0012, bottom: 0.0009, depth: 0.003 }); g.add(liq.mesh); const container = new Container(5.2, { medium: 5 }); liq.update(container); return { obj: g, container, liquid: liq }; } +/* ---------- 6-well plate ---------- */ +// A standard 6-well plate (127.8 × 85.5 mm), each well with 2 mL of medium. +// Wells are A1–A3 along the far row and B1–B3 along the near one. +export const WELLS = ["A1", "A2", "A3", "B1", "B2", "B3"]; +export function makeWellPlate(name) { + const g = new THREE.Group(); + const W = 0.1278, D = 0.0855, H = 0.0205, R = 0.0178, pitch = 0.039; + const clear = MAT.plasticClear(); + const wall = new THREE.Shape(); wall.copy(roundedRect(W, D, 0.005)); + wall.holes.push(roundedRect(W - 0.0024, D - 0.0024, 0.004)); + const skirt = new THREE.ExtrudeGeometry(wall, { depth: H, bevelEnabled: false, curveSegments: 6 }); + skirt.rotateX(-Math.PI / 2); + g.add(mesh(skirt, clear, false)); + const deckShape = roundedRect(W - 0.0024, D - 0.0024, 0.004); + const centres = WELLS.map((_, i) => new THREE.Vector3((i % 3 - 1) * pitch, 0, (i < 3 ? -0.5 : 0.5) * pitch)); + for (const c of centres) { const hole = new THREE.Path(); hole.absarc(c.x, -c.z, R, 0, Math.PI * 2, true); deckShape.holes.push(hole); } + const deck = new THREE.ExtrudeGeometry(deckShape, { depth: 0.0012, bevelEnabled: false, curveSegments: 24 }); + deck.rotateX(-Math.PI / 2); deck.translate(0, H - 0.0012, 0); + g.add(mesh(deck, clear, false)); + const wells = centres.map((c, i) => { + const wallM = mesh(new THREE.CylinderGeometry(R, R, H - 0.0015, 40, 1, true), clear, false); + wallM.position.set(c.x, 0.0015 + (H - 0.0015) / 2, c.z); + const floor = mesh(new THREE.CircleGeometry(R, 40), clear, false); + floor.rotation.x = -Math.PI / 2; floor.position.set(c.x, 0.0015, c.z); + g.add(wallM, floor); + const liq = liquidColumn({ radius: R - 0.0004, bottom: 0.0016, depth: 0.0035, segments: 32 }); + liq.mesh.position.x = c.x; liq.mesh.position.z = c.z; + g.add(liq.mesh); + const container = new Container(3, { medium: 2 }); + liq.update(container); + return { name: WELLS[i], centre: c, container, liquid: liq }; + }); + // Moulded letters and numbers along the edges, and a label on the lid. + const c = document.createElement("canvas"); + c.width = 512; c.height = 342; + const x = c.getContext("2d"); + x.fillStyle = "rgba(255,255,255,0.85)"; x.font = "600 26px 'IBM Plex Sans', sans-serif"; x.textAlign = "center"; x.textBaseline = "middle"; + [0, 1, 2].forEach((k) => x.fillText(`${k + 1}`, 256 + (k - 1) * 156, 16)); + ["A", "B"].forEach((k, j) => x.fillText(k, 14, 171 + (j - 0.5) * 156)); + x.fillStyle = "#f7f5ef"; x.fillRect(300, 300, 200, 38); + x.fillStyle = "#1d2326"; x.font = "700 24px 'IBM Plex Sans', sans-serif"; x.fillText(name, 400, 320); + const tex = new THREE.CanvasTexture(c); tex.colorSpace = THREE.SRGBColorSpace; + const print = mesh(new THREE.PlaneGeometry(W - 0.003, D - 0.003), new THREE.MeshBasicMaterial({ map: tex, transparent: true, depthWrite: false }), false); + print.rotation.x = -Math.PI / 2; print.position.y = H + 0.0026; + const lidTop = mesh(roundedBoxGeometry(W + 0.002, 0.0011, D + 0.002, 0.006, 0.0003), clear, false); + lidTop.position.y = H + 0.0014; + g.add(lidTop, print); + compact(g); + link(g, "wells", wells); + return { obj: g, wells }; +} + +// The well nearest a point given in the plate's own space. +export function wellAt(plateObj, localPoint) { + let best = 0, d2 = Infinity; + plateObj.userData.wells.forEach((w, i) => { const d = (w.centre.x - localPoint.x) ** 2 + (w.centre.z - localPoint.z) ** 2; if (d < d2) { d2 = d; best = i; } }); + return best; +} + +/* ---------- micropipette, tips and tip waste ---------- */ +// A 2–200 µL air-displacement micropipette. Its display shows the set volume; +// a yellow tip appears when one is fitted, with any liquid drawn up in it. +export function makeMicropipette() { + const g = new THREE.Group(); + const body = new THREE.Group(); + g.add(body); + const grey = MAT.plastic(0xdfe3e7), blue = MAT.plastic(0x41607f), white = MAT.plastic(0xf3f4f2); + grey.roughness = 0.35; blue.roughness = 0.4; + body.add(mesh(lathe([[0.0001, 0], [0.0023, 0], [0.0031, 0.02], [0.0046, 0.045], [0.0001, 0.045]], 24), grey)); + body.add(mesh(lathe([[0.0001, 0.045], [0.0058, 0.045], [0.0064, 0.05], [0.0064, 0.074], [0.0001, 0.074]], 24), white)); + body.add(mesh(lathe([[0.0001, 0.074], [0.0098, 0.076], [0.0112, 0.1], [0.0126, 0.15], [0.0122, 0.185], [0.0106, 0.196], [0.0001, 0.197]], 32), blue)); + const hook = mesh(roundedBoxGeometry(0.008, 0.012, 0.016, 0.003, 0.0015), blue); + hook.position.set(0, 0.168, 0.016); + const ejector = mesh(roundedBoxGeometry(0.006, 0.01, 0.01, 0.002, 0.001), white); + ejector.position.set(0, 0.188, -0.013); + const rod = mesh(new THREE.CylinderGeometry(0.0028, 0.0028, 0.016, 12), grey); + rod.position.y = 0.205; + const button = mesh(lathe([[0.0001, 0], [0.0069, 0], [0.0071, 0.006], [0.0062, 0.01], [0.0001, 0.0105]], 24), MAT.plastic(0xf2c230)); + button.position.y = 0.212; + body.add(hook, ejector, rod, button); + // The volume counter, behind a small window on the handle. + const dc = document.createElement("canvas"); + dc.width = 128; dc.height = 48; + const dtex = new THREE.CanvasTexture(dc); dtex.colorSpace = THREE.SRGBColorSpace; + const display = mesh(new THREE.PlaneGeometry(0.012, 0.0045), new THREE.MeshBasicMaterial({ map: dtex }), false); + display.position.set(0, 0.128, 0.0122); + body.add(display); + const tip = mesh(lathe([[0.0004, -0.052], [0.0009, -0.05], [0.0024, -0.012], [0.0029, 0.002], [0.0029, 0.009]], 20), new THREE.MeshPhysicalMaterial({ color: 0xf6d34a, roughness: 0.2, transparent: true, opacity: 0.55, depthWrite: false, side: THREE.DoubleSide, forceSinglePass: true }), false); + tip.visible = false; + const load = mesh(new THREE.ConeGeometry(0.0016, 0.012, 14), new THREE.MeshPhysicalMaterial({ color: 0xffffff, transparent: true, opacity: 0.85, depthWrite: false }), false); + load.rotation.x = Math.PI; load.position.y = -0.044; load.visible = false; + body.add(tip, load); + compact(body); + link(g, "parts", { body, tip, load, dc, dtex }); + link(g, "pose", (p) => { + // Lying on the bench, or upright in the hand. + if (p === "hand") { body.rotation.set(0, 0, 0); body.position.set(0, 0, 0); } + else { body.rotation.set(0, 0, -Math.PI / 2); body.position.set(-0.1, 0.0126, 0); } + }); + g.userData.pose("rest"); + return g; +} + +export function updatePipetteLook(it) { + const { tip, load, dc, dtex } = it.obj.userData.parts; + const st = it.state; + tip.visible = !!st.tip; + load.visible = !!(st.tip && st.load && !st.load.empty); + if (load.visible) { const { color } = st.load.color(); load.material.color.copy(color); } + if (st.shown !== st.vol) { + st.shown = st.vol; + const g = dc.getContext("2d"); + g.fillStyle = "#e9ecd8"; g.fillRect(0, 0, 128, 48); + g.fillStyle = "#1a1d1f"; g.font = "600 38px 'IBM Plex Mono', monospace"; g.textAlign = "center"; g.textBaseline = "middle"; + g.fillText(String(Math.round(st.vol)).padStart(3, "0"), 64, 26); + dtex.needsUpdate = true; + } +} + +// A rack of 96 yellow 200 µL tips with its lid open. +export function makeTipBox() { + const g = new THREE.Group(); + const W = 0.08, D = 0.122, H = 0.055; + g.add(mesh(roundedBoxGeometry(W, H, D, 0.004, 0.0015), new THREE.MeshPhysicalMaterial({ color: 0x2f74c8, roughness: 0.3, transparent: true, opacity: 0.85 }))); + const rack = mesh(roundedBoxGeometry(W - 0.003, 0.003, D - 0.003, 0.003, 0.0008), MAT.plastic(0xf1f2ef)); + rack.position.y = H; + g.add(rack); + const tipGeo = lathe([[0.0004, -0.04], [0.0009, -0.038], [0.0024, -0.005], [0.0029, 0.006], [0.0029, 0.012], [0.0025, 0.012]], 10); + const tips = new THREE.InstancedMesh(tipGeo, new THREE.MeshStandardMaterial({ color: 0xf6d34a, roughness: 0.35, transparent: true, opacity: 0.9 }), 96); + const m4 = new THREE.Matrix4(); + let k = 0; + for (let i = 0; i < 12; i++) for (let j = 0; j < 8; j++) tips.setMatrixAt(k++, m4.makeTranslation((j - 3.5) * 0.009, H + 0.003, (i - 5.5) * 0.009)); + tips.castShadow = true; + g.add(tips); + const lid = mesh(roundedBoxGeometry(W + 0.002, 0.016, D + 0.002, 0.004, 0.0012), MAT.plasticClear(), false); + const hinge = new THREE.Group(); + hinge.position.set(0, H + 0.003, -D / 2); + lid.position.z = D / 2 + 0.001; + lid.rotation.x = Math.PI; + hinge.add(lid); + hinge.rotation.x = -1.95; + g.add(hinge); + link(g, "tips", tips); + return g; +} + +export function makeTipWaste() { + const g = new THREE.Group(); + g.add(mesh(vessel([[0.0001, 0], [0.034, 0], [0.037, 0.003], [0.04, 0.09]], 0.002, 32), MAT.plastic(0xf2f3f1))); + const lab = mesh(new THREE.CylinderGeometry(0.0395, 0.038, 0.035, 32, 1, true, -0.9, 1.8), new THREE.MeshStandardMaterial({ map: labelTexture(["Used tips", "Tip waste"], { band: "#d8342a" }), roughness: 0.85 }), false); + lab.position.y = 0.05; + g.add(lab); + // A few used tips already inside. + const yellow = MAT.plastic(0xf6d34a); + for (let i = 0; i < 7; i++) { + const t = mesh(new THREE.ConeGeometry(0.0028, 0.05, 10), yellow, false); + t.position.set(Math.cos(i * 2.3) * 0.015, 0.025, Math.sin(i * 2.3) * 0.015); + t.rotation.set(Math.PI + Math.sin(i) * 0.6, i, Math.cos(i * 1.7) * 0.6); + g.add(t); + } + return compact(g); +} + +/* ---------- plate reader ---------- */ +export function makePlateReader() { + const g = new THREE.Group(); + const W = 0.36, H = 0.16, D = 0.3; + g.add(mesh(roundedBoxGeometry(W, H, D, 0.02, 0.006), MAT.plastic(0xe8eaec))); + const slot = mesh(roundedBoxGeometry(0.16, 0.026, 0.004, 0.004, 0.001), MAT.plastic(0x23272b), false); + slot.position.set(-0.06, 0.035, D / 2); + const tray = mesh(roundedBoxGeometry(0.15, 0.006, 0.05, 0.003, 0.001), MAT.plastic(0x30353a)); + tray.position.set(-0.06, 0.04, D / 2 + 0.02); + g.add(slot, tray); + const c = document.createElement("canvas"); + c.width = 256; c.height = 128; + const tex = new THREE.CanvasTexture(c); tex.colorSpace = THREE.SRGBColorSpace; + const screen = mesh(new THREE.PlaneGeometry(0.09, 0.045), new THREE.MeshBasicMaterial({ map: tex, toneMapped: false }), false); + screen.position.set(0.1, H * 0.62, D / 2 + 0.0008); + g.add(screen); + const go = MAT.plastic(0x58c46e), grey = MAT.plastic(0x8a9096); + for (let i = 0; i < 3; i++) { + const b = mesh(new THREE.CylinderGeometry(0.006, 0.006, 0.004, 16), i === 0 ? go : grey); + b.rotation.x = Math.PI / 2; b.position.set(0.075 + i * 0.022, H * 0.3, D / 2 + 0.002); + g.add(b); + } + const lab = mesh(new THREE.PlaneGeometry(0.14, 0.022), new THREE.MeshStandardMaterial({ map: labelTexture(["Plate reader", "Cell viability"], { w: 320, h: 64, size: 26, bg: "#e8eaec" }), roughness: 0.6 }), false); + lab.position.set(-0.06, H * 0.75, D / 2 + 0.0008); + g.add(lab); + const show = (lines, color = "#7dffb0") => { + const x = c.getContext("2d"); + x.fillStyle = "#11171a"; x.fillRect(0, 0, 256, 128); + x.fillStyle = color; x.font = "600 30px 'IBM Plex Mono', monospace"; + lines.forEach((t, i) => x.fillText(t, 14, 44 + i * 40)); + tex.needsUpdate = true; + }; + show(["READY", "Insert a plate"]); + link(g, "screen", show); + return compact(g); +} + +/* ---------- hemocytometer and microtubes ---------- */ +// A Neubauer counting chamber: a thick glass slide with two mirrored, ruled +// counting areas under a thick cover glass. +export function makeHemocytometer() { + const g = new THREE.Group(); + const L = 0.075, W = 0.032, T = 0.004; + g.add(mesh(roundedBoxGeometry(L, T, W, 0.001, 0.0004), MAT.glass())); + const c = document.createElement("canvas"); + c.width = 128; c.height = 128; + const x = c.getContext("2d"); + x.fillStyle = "#cfd6da"; x.fillRect(0, 0, 128, 128); + x.strokeStyle = "rgba(40,50,58,0.75)"; x.lineWidth = 1; + for (let i = 0; i <= 12; i++) { x.beginPath(); x.moveTo(16 + i * 8, 16); x.lineTo(16 + i * 8, 112); x.stroke(); x.beginPath(); x.moveTo(16, 16 + i * 8); x.lineTo(112, 16 + i * 8); x.stroke(); } + const tex = new THREE.CanvasTexture(c); + const mirror = new THREE.MeshStandardMaterial({ map: tex, metalness: 0.9, roughness: 0.15 }), slot = MAT.plastic(0x5c666c); + for (const s of [-1, 1]) { + const pad = mesh(new THREE.PlaneGeometry(0.012, 0.009), mirror, false); + pad.rotation.x = -Math.PI / 2; pad.position.set(0.004, T + 0.0001, s * 0.0065); + const groove = mesh(new THREE.PlaneGeometry(0.022, 0.0012), slot, false); + groove.rotation.x = -Math.PI / 2; groove.position.set(0.004, T + 0.00012, s * 0.0118); + g.add(pad, groove); + } + const mid = mesh(new THREE.PlaneGeometry(0.022, 0.0012), slot, false); + mid.rotation.x = -Math.PI / 2; mid.position.set(0.004, T + 0.00012, 0); + g.add(mid); + const cover = mesh(roundedBoxGeometry(0.022, 0.0006, 0.026, 0.0005, 0.0002), MAT.glass(), false); + cover.position.set(0.004, T + 0.0002, 0); + g.add(cover); + const wet = mesh(new THREE.PlaneGeometry(0.0115, 0.0085), new THREE.MeshPhysicalMaterial({ color: 0x8fb4e8, transparent: true, opacity: 0.5, roughness: 0.05, depthWrite: false }), false); + wet.rotation.x = -Math.PI / 2; wet.position.set(0.004, T + 0.00015, -0.0065); wet.visible = false; + g.add(wet); + const lab = mesh(new THREE.PlaneGeometry(0.02, 0.024), new THREE.MeshStandardMaterial({ map: labelTexture(["Neubauer", "0.1 mm"], { w: 128, h: 150, size: 24, bg: "#eef0ef" }), roughness: 0.9 }), false); + lab.rotation.x = -Math.PI / 2; lab.position.set(-0.025, T + 0.0001, 0); + g.add(lab); + compact(g); + link(g, "wet", wet); + return g; +} + +// A 1.5 mL microtube with its cap shut; small volumes sit in its cone. +export function makeMicrotube(label, solution = null, volume = 0) { + const g = new THREE.Group(); + g.add(mesh(vessel([[0.0001, 0], [0.0009, 0.0006], [0.0034, 0.012], [0.0046, 0.019], [0.0047, 0.037], [0.0053, 0.038]], 0.0005, 24), MAT.plasticClear(), false)); + const cap = mesh(lathe([[0.0001, 0.0405], [0.0057, 0.0405], [0.0058, 0.0385], [0.0047, 0.0385], [0.0047, 0.034], [0.0001, 0.034]], 24), new THREE.MeshPhysicalMaterial({ color: 0xf6f8f9, roughness: 0.2, transparent: true, opacity: 0.6 }), false); + const hinge = mesh(new THREE.BoxGeometry(0.004, 0.0012, 0.004), MAT.plasticClear(), false); + hinge.position.set(0, 0.0385, 0.0065); + g.add(cap, hinge); + const top = mesh(new THREE.CircleGeometry(0.0045, 20), new THREE.MeshBasicMaterial({ map: labelTexture([label], { w: 96, h: 96, size: 40, bg: "#fafafa" }) }), false); + top.rotation.x = -Math.PI / 2; top.position.y = 0.0407; + g.add(top); + // Liquid in the cone: a cone's volume goes with height cubed. + const mat = new THREE.MeshPhysicalMaterial({ color: 0xffffff, roughness: 0.1, transparent: true, opacity: 0.85, depthWrite: false }); + const cone = new THREE.Mesh(new THREE.ConeGeometry(1, 1, 18, 1), mat); + cone.rotation.x = Math.PI; + cone.renderOrder = 3; + g.add(cone); + const liquid = { + mesh: cone, + update(container) { + const v = container.volume; + cone.visible = v > 1e-5; + const h = Math.min(0.03, 0.012 * Math.cbrt(v / 0.03)); + const r = Math.min(0.0044, 0.0034 * (h / 0.012)); + cone.scale.set(r, h, r); + cone.position.y = 0.0006 + h / 2; + const { color, alpha } = container.color(); + mat.color.copy(color); mat.opacity = Math.min(0.95, 0.35 + alpha); + }, + }; + const container = new Container(1.5, solution ? { [solution]: volume } : {}); + liquid.update(container); + return { obj: g, container, liquid }; +} + +// A white rack for microtubes, two rows of five holes. +export const RACK_HOLES = Array.from({ length: 10 }, (_, i) => new THREE.Vector3(((i % 5) - 2) * 0.016, 0.03, (i < 5 ? -0.5 : 0.5) * 0.016)); +export function makeTubeRack() { + const g = new THREE.Group(); + g.add(mesh(roundedBoxGeometry(0.092, 0.03, 0.04, 0.003, 0.0012), MAT.plastic(0xf2f3ef))); + const c = document.createElement("canvas"); + c.width = 368; c.height = 160; + const x = c.getContext("2d"); + x.fillStyle = "#f2f3ef"; x.fillRect(0, 0, 368, 160); + for (const h of RACK_HOLES) { x.fillStyle = "#2a2d30"; x.beginPath(); x.arc(184 + h.x / 0.092 * 368, 80 + h.z / 0.04 * 160, 22, 0, Math.PI * 2); x.fill(); } + const t = new THREE.CanvasTexture(c); t.colorSpace = THREE.SRGBColorSpace; + const top = mesh(new THREE.PlaneGeometry(0.088, 0.038), new THREE.MeshStandardMaterial({ map: t, roughness: 0.6 }), false); + top.rotation.x = -Math.PI / 2; top.position.y = 0.0302; + g.add(top); + return g; +} + +/* ---------- water bath and watch glass ---------- */ +// A small stainless water bath held at 60 °C, with a perforated shelf just +// under the water for a watch glass. +export function makeWaterBath() { + const g = new THREE.Group(); + const W = 0.34, H = 0.17, D = 0.24, t = 0.006; + const steel = MAT.brushed(); + g.add(mesh(roundedBoxGeometry(W, 0.012, D, 0.012, 0.003), steel)); + for (const [w, d, x, z] of [[W, t, 0, -D / 2 + t / 2], [W, t, 0, D / 2 - t / 2], [t, D, -W / 2 + t / 2, 0], [t, D, W / 2 - t / 2, 0]]) { + const wall = mesh(new THREE.BoxGeometry(w, H, d), steel); + wall.position.set(x, H / 2, z); + g.add(wall); + } + const water = mesh(new THREE.PlaneGeometry(W - 2 * t, D - 2 * t), new THREE.MeshPhysicalMaterial({ color: 0xa9cdd2, roughness: 0.04, transparent: true, opacity: 0.55, clearcoat: 1, depthWrite: false }), false); + water.rotation.x = -Math.PI / 2; water.position.y = H - 0.035; + water.renderOrder = 2; + water.raycast = () => {}; // aim straight through the water at what's on the shelf + const shelf = mesh(new THREE.BoxGeometry(W * 0.6, 0.003, D * 0.6), steel, false); + shelf.position.y = H - 0.04; + g.add(water, shelf); + const c = document.createElement("canvas"); + c.width = 256; c.height = 96; + const x = c.getContext("2d"); + x.fillStyle = "#12181b"; x.fillRect(0, 0, 256, 96); + x.fillStyle = "#ff9d5c"; x.font = "600 44px 'IBM Plex Mono', monospace"; x.fillText("60.0°C", 16, 52); + x.fillStyle = "#9fe0ff"; x.font = "500 22px 'IBM Plex Mono', monospace"; x.fillText("SET 60.0", 18, 84); + const tex = new THREE.CanvasTexture(c); tex.colorSpace = THREE.SRGBColorSpace; + const panel = mesh(new THREE.PlaneGeometry(0.08, 0.03), new THREE.MeshBasicMaterial({ map: tex, toneMapped: false }), false); + panel.position.set(-0.08, H * 0.5, D / 2 + 0.0008); + g.add(panel); + compact(g); + link(g, "shelfY", H - 0.0385); + return g; +} + +export function makeWatchGlass() { + const g = new THREE.Group(); + const pts = []; + for (let i = 0; i <= 10; i++) { const r = 0.0001 + (i / 10) * 0.038; pts.push([r, 0.0012 + 6.5 * r * r]); } + for (let i = 10; i >= 0; i--) { const r = 0.0001 + (i / 10) * 0.038 - (i ? 0.0004 : 0); pts.push([Math.max(0.0001, r), 6.5 * r * r]); } + g.add(mesh(lathe(pts, 40), MAT.glass())); + const mat = new THREE.MeshPhysicalMaterial({ color: 0xffffff, roughness: 0.05, transparent: true, opacity: 0.6, depthWrite: false }); + const pool = new THREE.Mesh(new THREE.CylinderGeometry(1, 0.6, 1, 28), mat); + pool.renderOrder = 3; + g.add(pool); + const liquid = { + mesh: pool, + update(container) { + const v = container.volume; + pool.visible = v > 1e-4; + const r = Math.min(0.03, 0.012 * Math.sqrt(v)); + pool.scale.set(r, Math.max(0.0005, 0.0025 * Math.sqrt(v)), r); + pool.position.y = 0.0014 + pool.scale.y / 2; + const { color, alpha } = container.color(); + mat.color.copy(color); mat.opacity = Math.min(0.9, 0.3 + alpha); + }, + }; + const container = new Container(5, {}); + liquid.update(container); + return { obj: g, container, liquid }; +} + +/* ---------- onions ---------- */ +// An onion sitting on a jar of water, with white roots growing down into it. +export function makeRootedOnion(onionModel) { + const g = new THREE.Group(); + const r = 0.03, h = 0.075; + g.add(mesh(vessel([[0.0001, 0], [r - 0.003, 0], [r, 0.003], [r, h - 0.006], [r - 0.004, h - 0.002], [r - 0.0035, h + 0.004]], 0.0018, 40), MAT.glass())); + const liq = liquidColumn({ radius: r - 0.002, bottom: 0.0019, depth: h - 0.012 }); + g.add(liq.mesh); + const container = new Container(150, { tap: 120 }); + liq.update(container); + onionModel.position.y = h - 0.012; + g.add(onionModel); + const rootMat = new THREE.MeshStandardMaterial({ color: 0xf4f1e6, roughness: 0.55 }); + const roots = []; + for (let i = 0; i < 14; i++) { + const a = i * 2.4, rr = 0.004 + (i % 4) * 0.002; + const top = new THREE.Vector3(Math.cos(a) * rr, h - 0.008, Math.sin(a) * rr); + const len = 0.035 + ((i * 37) % 11) * 0.0025; + const pts = [top]; + for (let k = 1; k <= 4; k++) pts.push(new THREE.Vector3(top.x + Math.cos(a) * 0.003 * k + Math.sin(i + k) * 0.0015, top.y - (len * k) / 4, top.z + Math.sin(a) * 0.003 * k + Math.cos(i * 2 + k) * 0.0015)); + const tipGeo = new THREE.SphereGeometry(0.001, 8, 6).translate(pts[4].x, pts[4].y, pts[4].z); + const root = mesh(mergeGeometries([new THREE.TubeGeometry(new THREE.CatmullRomCurve3(pts), 10, 0.0007, 5), tipGeo]), rootMat, false); + g.add(root); + roots.push(root); + } + link(g, "roots", roots); + return { obj: g, container, liquid: liq }; +} + +// The same onion model, tinted to the purple-red of a red onion. +export function makeRedOnion(onionModel) { + onionModel.traverse((m) => { + if (!m.isMesh) return; + m.material = m.material.clone(); + m.material.color = new THREE.Color(0xb1446e); + }); + return onionModel; +} + /* ---------- pondweed tank ---------- */ export function makeTank() { const g = new THREE.Group(); @@ -261,15 +825,14 @@ export function makeTank() { const lab = mesh(new THREE.PlaneGeometry(0.12, 0.05), new THREE.MeshStandardMaterial({ map: labelTexture(["Pondweed", "Elodea"], { w: 256, h: 110, size: 34 }), roughness: 0.9 }), false); lab.position.set(0, h - 0.04, d / 2 + 0.001); g.add(lab); - return g; + return compact(g); } /* ---------- tools ---------- */ +// A glazed white ceramic tile with rounded edges. export function makeTile() { const g = new THREE.Group(); - const t = mesh(new THREE.BoxGeometry(0.15, 0.006, 0.15), new THREE.MeshPhysicalMaterial({ color: 0xf7f7f4, roughness: 0.15, clearcoat: 0.8 })); - t.position.y = 0.003; - g.add(t); + g.add(mesh(roundedBoxGeometry(0.15, 0.006, 0.15, 0.004, 0.0018), new THREE.MeshPhysicalMaterial({ color: 0xf7f7f4, roughness: 0.12, clearcoat: 0.9, clearcoatRoughness: 0.08 }))); return g; } @@ -287,64 +850,111 @@ export function makeSwab({ used = false } = {}) { export function makeSwabCup() { const g = new THREE.Group(); g.add(mesh(lathe([[0.0001, 0], [0.026, 0], [0.033, 0.09], [0.031, 0.09], [0.024, 0.004], [0.0001, 0.004]], 32), MAT.plastic(0xf2f4f6))); + const stickMat = MAT.paper(0xf3efe4), tipMat = MAT.paper(0xffffff); for (let i = 0; i < 6; i++) { const s = makeSwab(); s.rotation.z = Math.PI / 2 - 0.08 * (i - 2.5); s.rotation.y = i * 1.05; s.position.set(Math.cos(i) * 0.008, 0.07, Math.sin(i) * 0.008); - g.add(s); + s.updateMatrix(); + for (const m of [...s.children]) { m.applyMatrix4(s.matrix); m.material = m === s.userData.tip ? tipMat : stickMat; g.add(m); } } const lab = mesh(new THREE.PlaneGeometry(0.05, 0.03), new THREE.MeshStandardMaterial({ map: labelTexture(["Sterile swabs"], { w: 256, h: 140, size: 30 }), roughness: 0.9 }), false); lab.position.set(0, 0.045, 0.0305); lab.rotation.x = -0.08; g.add(lab); - return g; + return compact(g); } +// Fine-pointed steel forceps: two tapered arms joined at the back, with +// ridged grips, their tips just touching. export function makeForceps() { const g = new THREE.Group(); + const L = 0.115; + const arm = new THREE.Shape(); + arm.moveTo(0, -0.0024); arm.lineTo(L * 0.62, -0.0021); arm.quadraticCurveTo(L * 0.9, -0.0012, L, -0.00035); + arm.lineTo(L, 0.00035); arm.quadraticCurveTo(L * 0.9, 0.0012, L * 0.62, 0.0021); arm.lineTo(0, 0.0024); arm.lineTo(0, -0.0024); + const geo = new THREE.ExtrudeGeometry(arm, { depth: 0.0009, bevelEnabled: true, bevelThickness: 0.0002, bevelSize: 0.0002, bevelSegments: 1, curveSegments: 8 }); + geo.rotateX(-Math.PI / 2); + geo.translate(-L / 2, 0, 0); + const steel = MAT.steel(); for (const s of [-1, 1]) { - const arm = mesh(new THREE.BoxGeometry(0.11, 0.0015, 0.004), MAT.steel()); - arm.position.set(0, 0.002, s * 0.003); - arm.rotation.y = s * 0.04; - g.add(arm); + const a = mesh(geo, steel); + a.position.set(0, s > 0 ? 0.0034 : 0.0011, 0); + a.rotation.z = s * 0.028; + g.add(a); + for (let i = 0; i < 6; i++) { + const ridge = mesh(new THREE.BoxGeometry(0.0009, 0.00025, 0.0042), steel, false); + ridge.position.set(-0.012 + i * 0.0026, (s > 0 ? 0.0034 : 0.0011) + (s > 0 ? 0.0012 : -0.0001), 0); + g.add(ridge); + } } - return g; + const back = mesh(new THREE.BoxGeometry(0.006, 0.0035, 0.0048), steel); + back.position.set(-L / 2 + 0.003, 0.0026, 0); + g.add(back); + return compact(g); } +// A scalpel: flat steel handle with a gripped section and a curved blade. export function makeScalpel() { const g = new THREE.Group(); - const handle = mesh(new THREE.BoxGeometry(0.11, 0.003, 0.009), MAT.steel()); - handle.position.y = 0.0015; - const blade = mesh(new THREE.BoxGeometry(0.028, 0.0006, 0.007), new THREE.MeshStandardMaterial({ color: 0xe2e6ea, metalness: 1, roughness: 0.15 })); - blade.position.set(0.068, 0.0015, 0.0005); - g.add(handle, blade); - return g; + const steel = MAT.steel(); + const handle = mesh(roundedBoxGeometry(0.105, 0.0028, 0.0085, 0.002, 0.0008), steel); + g.add(handle); + const grip = MAT.brushed(); + for (let i = 0; i < 9; i++) { + const ridge = mesh(new THREE.BoxGeometry(0.0012, 0.0004, 0.0074), grip, false); + ridge.position.set(-0.025 + i * 0.0035, 0.003, 0); + g.add(ridge); + } + const b = new THREE.Shape(); + b.moveTo(0, -0.0028); b.lineTo(0.018, -0.0028); b.quadraticCurveTo(0.03, -0.0026, 0.036, 0.0032); + b.quadraticCurveTo(0.024, 0.0038, 0.012, 0.0034); b.lineTo(0, 0.0034); b.lineTo(0, -0.0028); + const bg = new THREE.ExtrudeGeometry(b, { depth: 0.0004, bevelEnabled: false, curveSegments: 10 }); + bg.rotateX(-Math.PI / 2); + const blade = mesh(bg, new THREE.MeshStandardMaterial({ color: 0xe6eaee, metalness: 1, roughness: 0.12 })); + blade.position.set(0.05, 0.0012, 0); + g.add(blade); + return compact(g); } +// A sharpened yellow pencil with a ferrule and an eraser. export function makePencil() { const g = new THREE.Group(); const body = mesh(new THREE.CylinderGeometry(0.0036, 0.0036, 0.15, 6), MAT.plastic(0xf2c230)); body.rotation.z = Math.PI / 2; body.position.y = 0.0036; - const tip = mesh(new THREE.ConeGeometry(0.0036, 0.016, 6), MAT.plastic(0xe7c49a)); - tip.rotation.z = -Math.PI / 2; tip.position.set(0.083, 0.0036, 0); - g.add(body, tip); + const wood = mesh(new THREE.ConeGeometry(0.0036, 0.016, 6), MAT.plastic(0xe7c49a)); + wood.rotation.z = -Math.PI / 2; wood.position.set(0.083, 0.0036, 0); + const lead = mesh(new THREE.ConeGeometry(0.0011, 0.005, 8), MAT.plastic(0x2a2a2c)); + lead.rotation.z = -Math.PI / 2; lead.position.set(0.0889, 0.0036, 0); + const ferrule = mesh(new THREE.CylinderGeometry(0.0038, 0.0038, 0.008, 16), MAT.brushed()); + ferrule.rotation.z = Math.PI / 2; ferrule.position.set(-0.079, 0.0036, 0); + const eraser = mesh(new THREE.CylinderGeometry(0.0035, 0.0035, 0.008, 16), MAT.plastic(0xe58a8a)); + eraser.rotation.z = Math.PI / 2; eraser.position.set(-0.087, 0.0036, 0); + g.add(body, wood, lead, ferrule, eraser); return g; } +// A stack of folded paper towels, each sheet a little out of line. export function makePaperTowels() { const g = new THREE.Group(); - const stack = mesh(new THREE.BoxGeometry(0.21, 0.03, 0.11), MAT.paper(0xf2efe6)); - stack.position.y = 0.015; - g.add(stack); - return g; + const paper = MAT.paper(0xf2efe6); + for (let i = 0; i < 8; i++) { + const s = mesh(roundedBoxGeometry(0.21, 0.0034, 0.11, 0.004, 0.0012), paper, i === 7); + s.position.set(Math.sin(i * 2.1) * 0.0025, i * 0.0036, Math.cos(i * 1.7) * 0.002); + s.rotation.y = Math.sin(i * 3.3) * 0.02; + g.add(s); + } + const fold = mesh(new THREE.BoxGeometry(0.0015, 0.0005, 0.108), MAT.paper(0xe4e0d6), false); + fold.position.set(0.02, 0.0292, 0); + g.add(fold); + return compact(g); } export function makeGlassBin() { const g = new THREE.Group(); - const body = mesh(new THREE.BoxGeometry(0.3, 0.36, 0.3), MAT.plastic(0xe9eaea)); - body.position.y = 0.18; - const lid = mesh(new THREE.BoxGeometry(0.31, 0.02, 0.31), MAT.plastic(0xf0c419)); - lid.position.y = 0.37; + const body = mesh(roundedBoxGeometry(0.3, 0.36, 0.3, 0.02, 0.006), MAT.plastic(0xe9eaea)); + const lid = mesh(roundedBoxGeometry(0.31, 0.022, 0.31, 0.022, 0.006), MAT.plastic(0xf0c419)); + lid.position.y = 0.355; const lab = mesh(new THREE.PlaneGeometry(0.22, 0.12), new THREE.MeshStandardMaterial({ map: labelTexture(["Glass waste", "Slides and cover slips only"], { w: 320, h: 170, band: "#f0c419", size: 36 }), roughness: 0.9 }), false); lab.position.set(0, 0.22, 0.1506); g.add(body, lid, lab); @@ -355,7 +965,7 @@ export function makeGlassBin() { export function makeGoggles() { const g = new THREE.Group(); const r = 0.085, h = 0.05, th = 1.15; // lens radius, height, half the wrap angle - const lens = mesh(new THREE.CylinderGeometry(r, r, h, 40, 1, true, -th, th * 2), new THREE.MeshPhysicalMaterial({ color: 0xcfe9f2, roughness: 0.05, transparent: true, opacity: 0.45, clearcoat: 1, depthWrite: false, side: THREE.DoubleSide }), false); + const lens = mesh(new THREE.CylinderGeometry(r, r, h, 40, 1, true, -th, th * 2), new THREE.MeshPhysicalMaterial({ color: 0xcfe9f2, roughness: 0.05, transparent: true, opacity: 0.45, clearcoat: 1, depthWrite: false, side: THREE.DoubleSide, forceSinglePass: true }), false); const frameMat = new THREE.MeshStandardMaterial({ color: 0x2f6fb8, roughness: 0.45, side: THREE.DoubleSide }); // The soft frame: a flat curved strip along the top and bottom of the lens. for (const y of [-h / 2, h / 2]) { @@ -384,7 +994,7 @@ export function makeGoggles() { g.add(lens, strap); // Centre the goggles over their footprint, resting on the lower rim. for (const c of g.children) c.position.add(new THREE.Vector3(0, h / 2 + 0.004, -r * 0.2)); - return g; + return compact(g); } // A white pump bottle of alcohol gel. @@ -473,8 +1083,9 @@ export function makeWhiteboard(lines) { g.add(frame, board, tray); return g; } - export function shortName(solution) { return { water: "Distilled water", tap: "Tap water", saline: "Saline 0.9%", iodine: "Iodine", mb: "Methylene blue", ethanol: "Ethanol 70%", - disinfectant: "Disinfectant", medium: "Medium", paclitaxel: "Paclitaxel", doxorubicin: "Doxorubicin", cisplatin: "Cisplatin" }[solution] || solution; + disinfectant: "Disinfectant", medium: "Medium", paclitaxel: "Paclitaxel", doxorubicin: "Doxorubicin", cisplatin: "Cisplatin", + salt: "Salt solution 1 M", hcl: "Hydrochloric acid 1 M", toluidine: "Toluidine blue", trypsin: "Trypsin-EDTA", trypan: "Trypan blue 0.4%", + cells: "Cell suspension" }[solution] || solution; } diff --git a/web/lab3d/js/room.js b/web/lab3d/js/room.js index 2eb4733..aac00cf 100644 --- a/web/lab3d/js/room.js +++ b/web/lab3d/js/room.js @@ -1,7 +1,7 @@ // The lab room: walls with real window openings, floor, ceiling, lights and // furniture. Furniture that does something is tagged with userData.target. import * as THREE from "three"; -import { fit, setMaterial, enableShadows, link } from "./assets.js"; +import { fit, setMaterial, enableShadows, link, flatten } from "./assets.js"; import { makeWhiteboard, makeLightSwitch, makeGlassBin, makeBlinds, MAT } from "./props.js"; export const ROOM = { x0: -5, x1: 5, z0: -4, z1: 4, h: 3.0 }; @@ -184,7 +184,7 @@ export function buildRoom(scene, assets, preset) { target(inc, { kind: "incubator", name: "Incubator" }); /* ---------- teacher's desk, journal and whiteboard ---------- */ - const desk = enableShadows(fit(assets.gltf.metal_office_desk, { height: 0.79, rotY: -Math.PI / 2 })); + const desk = flatten(enableShadows(fit(assets.gltf.metal_office_desk, { height: 0.79, rotY: -Math.PI / 2 }))); desk.position.set(3.95, 0, -2.3); add(desk); surface(desk); const deskBox = collide(desk); @@ -205,7 +205,7 @@ export function buildRoom(scene, assets, preset) { target(board, { kind: "whiteboard", name: "Whiteboard" }); /* ---------- storage ---------- */ - const shelves = enableShadows(fit(assets.gltf.steel_frame_shelves_01, { height: 2.14 })); + const shelves = flatten(enableShadows(fit(assets.gltf.steel_frame_shelves_01, { height: 2.14 }))); shelves.position.set(-3.6, 0, 3.7); add(shelves); surface(shelves); collide(shelves); const cabinet = enableShadows(fit(assets.gltf.drawer_cabinet, { height: 1.88, rotY: Math.PI })); @@ -217,7 +217,7 @@ export function buildRoom(scene, assets, preset) { /* ---------- stools ---------- */ const stools = [[-1.15, 1.75], [0.0, 1.75], [-2.3, -0.9], [-3.4, -0.9]].map(([x, z], i) => { - const s = enableShadows(fit(i === 0 ? assets.gltf.metal_stool_01 : assets.gltf.metal_stool_01.clone(), { height: 0.88 })); + const s = flatten(enableShadows(fit(i === 0 ? assets.gltf.metal_stool_01 : assets.gltf.metal_stool_01.clone(), { height: 0.88 }))); s.position.set(x, 0, z); add(s); target(s, { kind: "stool", name: "Lab stool" }); @@ -261,7 +261,7 @@ export function buildRoom(scene, assets, preset) { /* ---------- ceiling lights ---------- */ const fixturePos = [[-3, -2.2], [0, -2.2], [3, -2.2], [-3, 1.6], [0, 1.6], [3, 1.6]]; const fixtures = fixturePos.map(([x, z], i) => { - const f = fit(i === 0 ? assets.gltf.mounted_fluorescent_lights : assets.gltf.mounted_fluorescent_lights.clone(), { maxDim: 1.2 }); + const f = flatten(fit(i === 0 ? assets.gltf.mounted_fluorescent_lights : assets.gltf.mounted_fluorescent_lights.clone(), { maxDim: 1.2 })); f.position.set(x, R.h - 0.08, z); add(f); return f; diff --git a/web/lab3d/js/scope.js b/web/lab3d/js/scope.js index 595508a..6a558b0 100644 --- a/web/lab3d/js/scope.js +++ b/web/lab3d/js/scope.js @@ -1,20 +1,28 @@ // Looking through the eyepiece: objective lenses, coarse and fine focus, -// light and diaphragm, moving the slide, measuring, and inspecting a -// living cell's engine state. -import { makeField, SPECIMENS, FOV_UM } from "./specimens.js"; +// light and diaphragm, moving the slide, measuring, inspecting a living +// cell's engine state, naming the stage of dividing cells, and counting +// cells in a hemocytometer. +import { makeField, makeHemoField, SPECIMENS, FOV_UM, STAGES, CORNERS } from "./specimens.js"; import { makeCultureField } from "./culture.js"; const $ = (id) => document.getElementById(id); const FOCUS_AT = { 4: 60, 10: 61.5, 40: 62.4 }; // nearly parfocal, like a real microscope const DEPTH = { 4: 5, 10: 2.6, 40: 1.1 }; // depth of field shrinks at high power const STEP = { coarse: 2.5, fine: 0.25 }; +const STAGE_NOTES = [ + "Interphase: one round nucleus with a dark nucleolus; the DNA is spread out, not yet visible as chromosomes.", + "Prophase: the chromosomes condense into tangled threads inside the nucleus.", + "Metaphase: the chromosomes line up across the middle of the cell.", + "Anaphase: the two sets of chromosomes are pulled apart, towards the ends of the cell.", + "Telophase: two new nuclei form at the ends, and a cell plate grows between them.", +]; -export function createScope({ onFocus, onExit, toast, observe, resolution = 720 }) { +export function createScope({ onFocus, onExit, toast, observe, onEvent = () => {}, resolution = 720 }) { const canvas = $("field"), ep = $("eyepiece"), msg = $("epMsg"); const W = resolution; canvas.width = W; canvas.height = W; const ctx = canvas.getContext("2d"); - const s = { spec: null, field: null, obj: 4, focus: 28, light: 0.7, diaphragm: 0.35, cx: 0, cy: 0, t: 0, dirty: true, done: {}, told: {} }; + const s = { spec: null, field: null, obj: 4, focus: 28, light: 0.7, diaphragm: 0.35, cx: 0, cy: 0, t: 0, dirty: true, done: {}, told: {}, sel: null, osmoT: 0 }; const offBy = () => Math.abs(s.focus - FOCUS_AT[s.obj]) / DEPTH[s.obj]; const inFocus = () => offBy() < 0.8; @@ -28,20 +36,33 @@ export function createScope({ onFocus, onExit, toast, observe, resolution = 720 $("cultureTime").textContent = ""; ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.fillStyle = "#cfc9c0"; ctx.fillRect(0, 0, W, W); msg.textContent = spec.text; msg.hidden = false; - $("cellCard").hidden = true; $("measureBtn").hidden = true; + for (const id of ["cellCard", "measureBtn", "classifyPanel", "countPanel", "osmoReadout", "measurePanel"]) $(id).hidden = true; + $("wellPick").hidden = !spec.wells; return; } msg.textContent = "Nothing here. Drag to move the slide."; + const keep = s.spec && spec.keepView && s.spec.kind === spec.kind; s.spec = spec; - s.field = spec.kind === "culture" ? makeCultureField(spec.header, spec.snap, { tint: spec.tint }) : makeField(spec.prep); - Object.assign(s, { obj: 4, focus: 28, cx: 0, cy: 0, t: 0, dirty: true, done: {}, told: {} }); + s.field = spec.kind === "culture" ? makeCultureField(spec.header, spec.snap, { tint: spec.tint }) : spec.kind === "hemo" ? makeHemoField(spec.hemo) : makeField(spec.prep); + if (!keep) Object.assign(s, { obj: 4, focus: 28, cx: 0, cy: 0, done: {}, told: {} }); + Object.assign(s, { t: 0, dirty: true, sel: null }); $("scopeTitle").textContent = spec.title; $("cultureTime").textContent = spec.kind === "culture" ? ` · ${spec.time} h in culture` : ""; $("measurePanel").hidden = true; $("measureLine").hidden = true; $("cellCard").hidden = true; $("mCount").value = ""; $("mResult").textContent = ""; - $("measureBtn").hidden = spec.kind === "culture" || !spec.prep.specimen; + $("measureBtn").hidden = spec.kind !== "slide" || !spec.prep.specimen; + $("classifyPanel").hidden = !s.field.classify; + $("countPanel").hidden = !s.field.hemo; + $("osmoReadout").hidden = !s.field.osmosis; + $("wellPick").hidden = !spec.wells; + if (spec.wells) renderWells(); + if (s.field.classify) { $("clsResult").textContent = ""; renderTally(); } + // Which cells were counted or named is kept by index: the field is drawn fresh each time, from the same seed. + if (s.field.hemo) { s.field.cells.forEach((c, i) => (c.counted = spec.hemo.counted.has(i))); $("countResult").textContent = ""; renderCount(); } + if (s.field.classify) s.field.cells.forEach((c, i) => { if (spec.tally.named.has(i)) c.named = true; }); + if (s.field.classify && s.field.clumped) toast(s.field.soft ? "The cells are piled in layers. Squash the slide under a paper towel to spread them out." : "The cells are stuck together in clumps: the root tip wasn't softened in warm acid.", "warn"); sync(); apply(); } @@ -76,8 +97,9 @@ export function createScope({ onFocus, onExit, toast, observe, resolution = 720 if (p.cover === "flat" && !s.told.bubble && bubbleInView()) { s.told.bubble = true; toast("The circles with thick dark rims are air bubbles, from dropping the cover slip flat.", "warn"); } if (p.specimen && p.stain !== SPECIMENS[p.specimen].best && !s.told.stain) { s.told.stain = true; - toast(p.specimen === "cheek" ? "Hard to see? Cheek cells are almost clear. Methylene blue would stain them." - : p.specimen === "onion" ? "The nuclei are faint. Iodine stains onion cells best." : "A stain darkens the chloroplasts. Plain water shows the green best.", "warn"); + toast({ cheek: "Hard to see? Cheek cells are almost clear. Methylene blue would stain them.", onion: "The nuclei are faint. Iodine stains onion cells best.", + root: "The chromosomes are faint. Toluidine blue stains DNA dark purple.", redonion: "No stain needed: the red sap already shows each cell.", + elodea: "A stain darkens the chloroplasts. Plain water shows the green best." }[p.specimen], "warn"); } } msg.hidden = onSample() || !s.field; @@ -90,9 +112,12 @@ export function createScope({ onFocus, onExit, toast, observe, resolution = 720 } function renderTasks() { - const T = [[4, "Focus with the 4× lens (coarse knob)"], [10, "Switch to 10× and sharpen"], [40, "Switch to 40×, fine knob only"]]; - $("scopeTasks").innerHTML = T.map(([k, t]) => `
  • ${t}
  • `).join("") + - (s.spec && s.spec.kind === "culture" ? `
  • Click a cell to see what the engine says about it
  • ` : ""); + const T = s.spec && s.spec.kind === "hemo" + ? [[4, "Find the ruled grid with the 4× lens"], [10, "Switch to 10×: one corner square fills the view"]] + : [[4, "Focus with the 4× lens (coarse knob)"], [10, "Switch to 10× and sharpen"], [40, "Switch to 40×, fine knob only"]]; + const extra = !s.spec ? "" : s.spec.kind === "culture" ? `
  • Click a cell to see what the engine says about it
  • ` + : s.field?.classify ? `
  • Click a cell, then pick its stage below
  • ` : s.field?.hemo ? `
  • Click each cell in the four corner squares
  • ` : ""; + $("scopeTasks").innerHTML = T.map(([k, t]) => `
  • ${t}
  • `).join("") + extra; } function focusStep(kind, dir) { @@ -120,7 +145,7 @@ export function createScope({ onFocus, onExit, toast, observe, resolution = 720 $("diaphragm").addEventListener("input", (e) => { s.diaphragm = e.target.value / 100; apply(); }); ep.addEventListener("wheel", (e) => { e.preventDefault(); focusStep(e.shiftKey ? "coarse" : "fine", e.deltaY < 0 ? 1 : -1); }, { passive: false }); - // Drag to move the slide; a click without dragging inspects a cell. + // Drag to move the slide; a click without dragging picks a cell. let drag = null; ep.addEventListener("pointerdown", (e) => { drag = { x: e.clientX, y: e.clientY, moved: 0 }; ep.setPointerCapture(e.pointerId); }); ep.addEventListener("pointermove", (e) => { @@ -133,15 +158,21 @@ export function createScope({ onFocus, onExit, toast, observe, resolution = 720 drag.x = e.clientX; drag.y = e.clientY; s.dirty = true; }); ep.addEventListener("pointerup", (e) => { - if (drag && drag.moved < 5 && s.field && s.field.pickCell) inspect(e); + if (drag && drag.moved < 5 && s.field && s.field.pickCell) pick(e); drag = null; check(); }); - function inspect(e) { + function pick(e) { const r = ep.getBoundingClientRect(); const k = fov() / r.width; const x = s.cx + (e.clientX - r.left - r.width / 2) * k, y = s.cy + (e.clientY - r.top - r.height / 2) * k; const c = s.field.pickCell(x, y); + if (s.field.classify) return selectCell(c); + if (s.field.hemo) return countCell(c); + inspect(c); + } + + function inspect(c) { const card = $("cellCard"); if (!c) { card.hidden = true; return; } const fate = c.c3 > 0.35 ? "dying (apoptosis switched on)" : c.phase === 3 ? "dividing" : c.gs < 0.05 ? "waiting: no room to divide" : "growing"; @@ -153,6 +184,86 @@ export function createScope({ onFocus, onExit, toast, observe, resolution = 720 card.hidden = false; } + /* ---------- naming the stage of dividing cells ---------- */ + $("clsButtons").innerHTML = STAGES.map((n, i) => ``).join(""); + function selectCell(c) { + if (!c) { s.sel = null; s.dirty = true; return; } + if (s.obj < 40) toast("Use the 40× lens to see the chromosomes well enough.", "warn"); + s.sel = c; s.dirty = true; + $("clsResult").textContent = c.named != null ? `Already named: ${STAGES[c.stage]}.` : "Which stage is this cell in?"; + } + $("clsButtons").addEventListener("click", (e) => { + const b = e.target.closest("[data-stage]"); + if (!b || !s.field?.classify) return; + const c = s.sel; + if (!c) return toast("Click a cell in the eyepiece first."); + if (c.named != null) return toast("You've already named that one. Pick another cell."); + const guess = +b.dataset.stage, right = guess === c.stage; + c.named = guess; + const t = s.spec.tally; + t.named.add(s.field.cells.indexOf(c)); + t.counts[c.stage]++; t.total++; if (right) t.right++; + $("clsResult").innerHTML = `${right ? "Right. " : `Not quite: that one is in ${STAGES[c.stage].toLowerCase()}. `}${STAGE_NOTES[c.stage]}`; + renderTally(); + onEvent("classify", t); + s.sel = null; s.dirty = true; + }); + function renderTally() { + const t = s.spec.tally, dividing = t.total - t.counts[0]; + $("clsTally").innerHTML = t.total + ? `${STAGES.map((n, i) => `${n} ${t.counts[i]}`).join(" · ")}
    Mitotic index: ${dividing} ÷ ${t.total} = ${(dividing / t.total * 100).toFixed(1)} %` + : "None named yet."; + } + + /* ---------- counting cells in the hemocytometer ---------- */ + function countCell(c) { + if (!c) return; + if (c.sq < 0) return toast("That cell is outside the four corner squares. Count only those.", "warn"); + c.counted = !c.counted; + const i = s.field.cells.indexOf(c); + if (c.counted) s.spec.hemo.counted.add(i); else s.spec.hemo.counted.delete(i); + s.dirty = true; + renderCount(); + const got = CORNERS.map((_, i) => s.field.cells.filter((x) => x.sq === i && x.counted).length); + const truth = s.field.truth.map((q) => q.live + q.dead); + if (got.every((n, i) => n >= truth[i] - 1 && truth[i] > 0)) onEvent("count:4"); + } + function counts() { + return CORNERS.map((_, i) => ({ live: s.field.cells.filter((x) => x.sq === i && x.counted && !(x.dead && s.spec.hemo.trypan)).length, dead: s.field.cells.filter((x) => x.sq === i && x.counted && x.dead && s.spec.hemo.trypan).length })); + } + function renderCount() { + const c = counts(); + $("countTable").innerHTML = `LiveDead (blue)` + CORNERS.map((q, i) => `${q.name}${c[i].live}${c[i].dead}`).join(""); + } + $("countCalc").addEventListener("click", () => { + if (!s.field?.hemo) return; + const c = counts(), h = s.spec.hemo; + const live = c.reduce((a, q) => a + q.live, 0), dead = c.reduce((a, q) => a + q.dead, 0); + if (!live && !dead) return ($("countResult").textContent = "Click the cells in the corner squares first."); + const empty = c.filter((q) => !q.live && !q.dead).length; + const perSq = live / 4, perMl = perSq * 1e4 * h.dilution; + const viab = live + dead ? (live / (live + dead)) * 100 : 0; + const truth = s.field.truth, tl = truth.reduce((a, q) => a + q.live, 0), td = truth.reduce((a, q) => a + q.dead, 0); + const html = `Live cells: ${live} in 4 squares = ${perSq.toFixed(1)} per square.
    × 104 (each square holds 0.1 µL) × ${h.dilution} (${h.trypan ? "diluted 1:1 in trypan blue" : "dilution"}) = ${fmt(perMl)} live cells per mL.
    + ${h.trypan ? `Viability: ${live} ÷ ${live + dead} = ${viab.toFixed(0)} %.` : "No trypan blue: you can't tell live from dead."}
    + In the squares there were ${tl} live and ${td} dead cells. The suspension really holds ${fmt(h.livePerMl * h.dilution)} live cells per mL, from the CellSim engine's dish at ${h.t} h. + Cells land in the chamber at random, so a count of ${live} is uncertain by about ±${Math.round(Math.sqrt(live))} (the square root of the count); counting more squares narrows it. + ${empty ? `
    Count all four squares for a fair average (${empty} still empty).` : ""}`; + $("countResult").innerHTML = html; + onEvent("count", { live, dead, perMl, viab, truePerMl: h.livePerMl * h.dilution, t: h.t, dish: h.dish }); + }); + function fmt(n) { if (n <= 0) return "0"; const e = Math.floor(Math.log10(n)); return `${(n / 10 ** e).toFixed(1)} × 10${e}`; } + + /* ---------- wells of a plate ---------- */ + function renderWells() { + const sp = s.spec; + $("wellPick").innerHTML = sp.wells.map((w, i) => ``).join(""); + } + $("wellPick").addEventListener("click", (e) => { + const b = e.target.closest("[data-well]"); + if (b) onEvent("well", +b.dataset.well); + }); + $("measureBtn").addEventListener("click", () => { const show = $("measurePanel").hidden; $("measurePanel").hidden = !show; $("measureLine").hidden = !show; @@ -176,6 +287,19 @@ export function createScope({ onFocus, onExit, toast, observe, resolution = 720 if (!s.dirty) return; s.dirty = false; s.field.draw(ctx, W, view); + // A ring round the cell you picked, drawn in the field's own µm space. + if (s.sel) { + const k = W / view.fov; + ctx.lineWidth = Math.max(1.5, 2 / k); ctx.strokeStyle = "#f0b44c"; + ctx.beginPath(); ctx.arc(s.sel.x, s.sel.y, Math.max(14, s.sel.w || 10), 0, Math.PI * 2); ctx.stroke(); + } + if (s.field.osmosis && s.field.lastShrunk) { + const { shrunk, of } = s.field.lastShrunk; + $("osmoReadout").innerHTML = `In view: ${shrunk} of ${of} cells plasmolysed · under the cover slip: ${s.spec.medium}`; + const now = performance.now(); + if (of >= 4 && inFocus() && s.obj >= 10 && now - s.osmoT > 400) { s.osmoT = now; onEvent("osmo", shrunk / of); } + } } - return { open, update }; + // state is for automated checks, like window.lab. + return { open, update, get spec() { return s.spec; }, get state() { return s; } }; } diff --git a/web/lab3d/js/settings.js b/web/lab3d/js/settings.js index 4920737..9a10cbb 100644 --- a/web/lab3d/js/settings.js +++ b/web/lab3d/js/settings.js @@ -11,7 +11,7 @@ export const PRESETS = { ultra: { label: "Ultra", pixelRatio: 2, shadows: true, shadowSize: 4096, env: true, lamps: 6, fps: 0, maxAniso: 16 }, }; -const DEFAULTS = { quality: "auto", fps: "preset", sensitivity: 1, fov: 72, invertY: false, bob: true }; +const DEFAULTS = { quality: "auto", fps: "preset", sensitivity: 1, fov: 72, invertY: false, bob: true, sound: true }; export const settings = (() => { try { return { ...DEFAULTS, ...(JSON.parse(localStorage.getItem(KEY)) || {}) }; } catch (e) { return { ...DEFAULTS }; } diff --git a/web/lab3d/js/specimens.js b/web/lab3d/js/specimens.js index 576b715..f70dd2e 100644 --- a/web/lab3d/js/specimens.js +++ b/web/lab3d/js/specimens.js @@ -41,6 +41,28 @@ function rng(seed) { sizeRange: [45, 75], measureWhat: "across", }, + root: { + name: "Onion root tip", + kind: "plant", + best: "toluidine", + seed: 53, + placeText: "Cut the last 5 mm of a root, soften it in warm acid, stain it and squash it flat under the cover slip.", + stainTip: "Tip: toluidine blue stains DNA, so the chromosomes of dividing cells show dark purple.", + sizeText: "about 15–25 µm across near the tip", + sizeRange: [12, 30], + measureWhat: "across", + }, + redonion: { + name: "Red onion skin", + kind: "plant", + best: "water", + seed: 71, + placeText: "Peel the thin skin from the outside of a red onion scale; its cells are coloured by red sap in the vacuole.", + stainTip: "Tip: no stain needed. The red sap shows each protoplast.", + sizeText: "about 200–400 µm long", + sizeRange: [200, 400], + measureWhat: "long", + }, elodea: { name: "Pondweed leaf", kind: "plant", @@ -455,9 +477,292 @@ function rng(seed) { }; } + // ---------- onion root tip squash (mitosis) ---------- + // Stage shares in a growing onion root's meristem: about 12 % of cells are + // dividing; prophase is the longest stage and anaphase the shortest. + export const STAGES = ["Interphase", "Prophase", "Metaphase", "Anaphase", "Telophase"]; + const STAGE_SHARE = [0.875, 0.06, 0.025, 0.015, 0.025]; + const ROOT_STYLE = { + toluidine: { cyto: "rgba(176,170,222,0.30)", wall: "rgba(88,74,150,0.55)", nuc: "rgba(64,36,128,0.82)", chrom: "rgba(42,18,96,0.95)" }, + water: { cyto: "rgba(226,222,208,0.16)", wall: "rgba(130,124,108,0.32)", nuc: "rgba(150,144,128,0.26)", chrom: "rgba(118,112,98,0.45)" }, + iodine: { cyto: "rgba(226,190,112,0.28)", wall: "rgba(146,96,30,0.6)", nuc: "rgba(132,78,20,0.6)", chrom: "rgba(100,56,12,0.8)" }, + mb: { cyto: "rgba(150,180,226,0.24)", wall: "rgba(60,92,160,0.5)", nuc: "rgba(30,56,146,0.78)", chrom: "rgba(18,38,110,0.92)" }, + }; + + function pickStage(r, share) { + let u = r(), k = 0; + while (k < share.length - 1 && u > share[k]) { u -= share[k]; k++; } + return k; + } + + function rootField(prep) { + const r = rng(53); + const soft = !!prep.softened, squashed = !!prep.squashed; + // A squash spreads the tip into a broad, loose patch; unsquashed it stays a narrow dark rod. + const halfW = squashed ? 650 : 260; + const outline = noisyOutline(r, squashed ? 1500 : 1300, halfW, 60, 0.12); + const cells = []; + for (let y = -halfW - 60; y < halfW + 60; y += 17) { + let x = -1700 + r() * 20; + while (x < 1700) { + const zoneCap = x < -1050, zoneElong = x > 350; + const L = zoneElong ? 34 + r() * 22 : zoneCap ? 26 + r() * 10 : 17 + r() * 5; + const H = zoneCap ? 22 + r() * 6 : 15 + r() * 3; + const cx = x + L / 2, cy = y + (squashed && soft ? (r() - 0.5) * 7 : 0); + if (inPoly(cx, cy, outline)) { + const share = zoneCap ? [1, 0, 0, 0, 0] : zoneElong ? [0.985, 0.006, 0.003, 0.002, 0.004] : STAGE_SHARE; + cells.push({ + x: cx, y: cy, w: L - (squashed && soft ? 3 + r() * 3 : 1), h: H - (squashed && soft ? 2 + r() * 2 : 1), + a: (r() - 0.5) * (squashed && soft ? 0.5 : 0.08), stage: pickStage(r, share), k: r(), zone: zoneCap ? "cap" : zoneElong ? "elongation" : "meristem", + }); + } + x += L; + } + } + for (const c of cells) { c.x0 = c.x - c.w; c.x1 = c.x + c.w; c.y0 = c.y - c.h; c.y1 = c.y + c.h; } + const bubbles = makeBubbles(r, prep.cover, outline); + const dust = makeDust(r); + const st = ROOT_STYLE[prep.stain] || ROOT_STYLE.water; + // Without acid the cells stay stuck together, and without squashing they lie in thick layers. + const clumped = !soft || !squashed; + + function drawChromosomes(ctx, c, s) { + const n = c.w * 0.3; + ctx.fillStyle = st.chrom; ctx.strokeStyle = st.chrom; + ctx.lineWidth = Math.max(1.1, 0.7 / s); ctx.lineCap = "round"; + if (c.stage === 1) { // prophase: chromatin condensing into threads inside the nucleus + ctx.beginPath(); ctx.ellipse(0, 0, n * 0.95, c.h * 0.36, 0, 0, Math.PI * 2); ctx.fillStyle = st.nuc; ctx.globalAlpha = 0.45; ctx.fill(); ctx.globalAlpha = 1; + for (let i = 0; i < 7; i++) { + const a = c.k * 9 + i * 0.9; + ctx.beginPath(); + ctx.moveTo(Math.cos(a) * n * 0.6, Math.sin(a) * c.h * 0.22); + ctx.quadraticCurveTo(Math.cos(a + 1.4) * n * 0.2, Math.sin(a + 2) * c.h * 0.3, Math.cos(a + 2.6) * n * 0.7, Math.sin(a + 3) * c.h * 0.25); + ctx.stroke(); + } + } else if (c.stage === 2) { // metaphase: lined up across the middle + for (let i = -4; i <= 4; i++) { ctx.beginPath(); ctx.moveTo(-1.8, i * c.h * 0.075); ctx.lineTo(1.8, i * c.h * 0.075 + 0.6); ctx.stroke(); } + } else if (c.stage === 3) { // anaphase: two sets pulled apart towards the ends + const gap = 3 + c.k * 4; + for (const side of [-1, 1]) for (let i = -3; i <= 3; i++) { + ctx.beginPath(); ctx.moveTo(side * (gap + 3.2), i * c.h * 0.08); ctx.lineTo(side * gap, i * c.h * 0.05 + 0.4); ctx.stroke(); + } + } else if (c.stage === 4) { // telophase: two new nuclei and the cell plate between them + for (const side of [-1, 1]) { ctx.beginPath(); ctx.ellipse(side * c.w * 0.5, 0, c.w * 0.2, c.h * 0.3, 0, 0, Math.PI * 2); ctx.fill(); } + ctx.strokeStyle = st.wall; ctx.beginPath(); ctx.moveTo(0, -c.h * 0.55); ctx.lineTo(0, c.h * 0.55); ctx.stroke(); + } + } + + return { + bubbles, + inSample: (x, y) => inPoly(x, y, outline), + animated: () => false, + classify: true, + draw(ctx, W, v) { + const s = begin(ctx, W, v); + const vr = viewRect(v); + if (clumped) { + // Layers of cells on top of each other: a dark smear with outlines here and there. + ctx.fillStyle = st.cyto.replace(/[\d.]+\)$/, "0.75)"); + ctx.beginPath(); tracePoly(ctx, outline); ctx.fill(); + } + const vis = cells.filter((c) => visible(c, vr)); + for (const c of vis) { + ctx.save(); ctx.translate(c.x, c.y); ctx.rotate(c.a); + ctx.beginPath(); ctx.rect(-c.w / 2, -c.h / 2, c.w, c.h); + ctx.fillStyle = st.cyto; ctx.fill(); + ctx.lineWidth = Math.max(1, 0.6 / s); ctx.strokeStyle = st.wall; ctx.stroke(); + if (c.stage === 0 || s < 0.25) { + ctx.beginPath(); ctx.ellipse(c.w * 0.05 * (c.k - 0.5), 0, Math.min(5.5, c.w * 0.3), Math.min(4.6, c.h * 0.32), 0, 0, Math.PI * 2); + ctx.fillStyle = st.nuc; ctx.fill(); + if (s > 0.6 && c.stage === 0) { ctx.fillStyle = st.chrom; ctx.beginPath(); ctx.arc(1, -0.6, 1.3, 0, Math.PI * 2); ctx.fill(); } + } else drawChromosomes(ctx, c, s); + ctx.restore(); + } + drawDust(ctx, dust, vr, s); + drawBubbles(ctx, bubbles, vr, s); + }, + pickCell(x, y) { + let best = null, d2 = 144; + for (const c of cells) { const d = (c.x - x) ** 2 + (c.y - y) ** 2; if (d < d2) { d2 = d; best = c; } } + return best; + }, + clumped, + soft, + cells, + }; + } + + // ---------- red onion skin, for osmosis ---------- + /* Each cell's protoplast holds its volume where the cell sap's osmolarity + (about 0.55 osmol/L, varying cell to cell) matches the liquid outside. + In a stronger solution water leaves, the protoplast shrinks away from the + wall (plasmolysis) and its red sap darkens; in water it swells back + against the wall. A simple osmotic model, not the CellSim engine. */ + export const RED_ONION = { sap: 0.55, spread: 0.18, minV: 0.28, tau: 7 }; + + export function protoplastVolume(sapOsm, history, now) { + const target = (o) => (o <= sapOsm ? 1 : Math.max(RED_ONION.minV, sapOsm / o)); + let V = 1; + for (let i = 0; i < history.length; i++) { + const h = history[i], end = i + 1 < history.length ? history[i + 1].t : now; + const T = target(h.osm); + V = T + (V - T) * Math.exp(-Math.max(0, end - h.t) / (RED_ONION.tau * 1000)); + } + return V; + } + + function redOnionField(prep) { + const r = rng(71); + const outline = noisyOutline(r, 3200, 2200, 80, 0.13); + const cells = brickCells(r, { + x0: -3600, x1: 3600, y0: -2600, y1: 2600, h0: 56, hVar: 16, L0: 210, LVar: 150, slant: 24, + keep: (x, y) => inPoly(x, y, outline), + }); + for (const c of cells) { + c.sap = RED_ONION.sap * (1 + (r() - 0.5) * 2 * RED_ONION.spread); + c.cx = (c.left + c.right) / 2; c.cy = (c.top + c.bot) / 2; + c.tone = 0.75 + r() * 0.5; + c.nx = c.left + (c.right - c.left) * (0.15 + r() * 0.7); + } + const bubbles = makeBubbles(r, prep.cover, outline); + const dust = makeDust(r); + const hist = prep.osmo || []; + const lastChange = hist.length ? hist[hist.length - 1].t : 0; + return { + bubbles, + inSample: (x, y) => inPoly(x, y, outline), + animated: () => performance.now() - lastChange < RED_ONION.tau * 5000, + osmosis: true, + draw(ctx, W, v) { + const s = begin(ctx, W, v); + const vr = viewRect(v); + const now = performance.now(); + const vis = cells.filter((c) => visible(c, vr)); + let shrunk = 0; + for (const c of vis) { + const V = protoplastVolume(c.sap, hist, now); + if (V < 0.97) shrunk++; + // The protoplast: the cell outline drawn smaller about its centre. + const k = Math.sqrt(V), w = (c.right - c.left) / 2, h = (c.bot - c.top) / 2; + const kx = Math.max(0.2, 1 - (1 - k) * 1.12), ky = Math.max(0.25, 1 - (1 - k) * 0.85); + ctx.beginPath(); + if (V > 0.985) tracePoly(ctx, c.poly); + else { + const rad = Math.min(w * kx, h * ky) * 0.9; + roundRect(ctx, c.cx - w * kx, c.cy - h * ky, 2 * w * kx, 2 * h * ky, rad); + } + const a = Math.min(0.85, (0.34 + 0.18 * c.tone) / Math.max(0.35, V)); + ctx.fillStyle = `rgba(168,32,${92 + Math.round(30 * c.tone)},${a.toFixed(3)})`; + ctx.fill(); + if (V <= 0.985 && s > 0.12) { ctx.lineWidth = Math.max(1, 0.6 / s); ctx.strokeStyle = "rgba(110,18,66,0.7)"; ctx.stroke(); } + } + ctx.lineWidth = Math.max(2.2, 0.9 / s); + ctx.strokeStyle = "rgba(122,86,96,0.55)"; + ctx.lineJoin = "round"; + ctx.beginPath(); + for (const c of vis) tracePoly(ctx, c.poly); + ctx.stroke(); + if (s > 0.25) { + ctx.fillStyle = "rgba(90,70,80,0.35)"; + for (const c of vis) { ctx.beginPath(); ctx.ellipse(c.nx, c.top + 9, 7, 5, 0, 0, Math.PI * 2); ctx.fill(); } + } + drawDust(ctx, dust, vr, s); + drawBubbles(ctx, bubbles, vr, s); + this.lastShrunk = { shrunk, of: vis.length }; + }, + }; + } + + function roundRect(ctx, x, y, w, h, r) { + r = Math.max(0, Math.min(r, w / 2, h / 2)); + ctx.moveTo(x + r, y); ctx.arcTo(x + w, y, x + w, y + h, r); ctx.arcTo(x + w, y + h, x, y + h, r); + ctx.arcTo(x, y + h, x, y, r); ctx.arcTo(x, y, x + w, y, r); ctx.closePath(); + } + + // ---------- hemocytometer ---------- + /* An improved Neubauer chamber: a 3 × 3 mm ruled grid of 1 mm squares, + 0.1 mm deep, so each large square holds 0.1 µL. The four corner squares + are ruled into 4 × 4; the centre into 5 × 5 groups with triple lines. + Cells sit at random, as they settle in a real chamber, at the density of + the suspension: live ones bright with a dark rim, dead ones blue if the + sample was mixed with trypan blue. */ + export const CORNERS = [{ name: "Top left", x: -1500, y: -1500 }, { name: "Top right", x: 500, y: -1500 }, { name: "Bottom left", x: -1500, y: 500 }, { name: "Bottom right", x: 500, y: 500 }]; + + export function makeHemoField({ livePerMl, deadPerMl, trypan, seed = 7 }) { + const r = rng(seed); + const perUm2 = (n) => n * 1e-4 / 1e6; // cells per µm² of a 0.1 mm deep chamber + const cells = []; + const area = 3800 * 3800; + for (const [rate, dead] of [[perUm2(livePerMl), false], [perUm2(deadPerMl), true]]) { + // A Poisson number of cells over the area, then uniform positions. + const mean = rate * area; + let n = Math.round(mean + Math.sqrt(mean) * gauss(r)); + for (let i = 0; i < Math.max(0, n); i++) cells.push({ x: (r() - 0.5) * 3800, y: (r() - 0.5) * 3800, d: dead ? 15 + r() * 4 : 12 + r() * 4, dead, k: r(), counted: false }); + } + const dust = makeDust(r); + const squareOf = (c) => CORNERS.findIndex((q) => c.x >= q.x && c.x < q.x + 1000 && c.y >= q.y && c.y < q.y + 1000); + for (const c of cells) c.sq = squareOf(c); + const truth = CORNERS.map((_, i) => ({ live: cells.filter((c) => c.sq === i && !c.dead).length, dead: cells.filter((c) => c.sq === i && c.dead).length })); + + function lines(ctx, s) { + const thin = Math.max(0.8, 0.6 / s); + ctx.strokeStyle = "rgba(54,60,66,0.75)"; + const line = (x0, y0, x1, y1, w = thin) => { ctx.lineWidth = w; ctx.beginPath(); ctx.moveTo(x0, y0); ctx.lineTo(x1, y1); ctx.stroke(); }; + for (let i = 0; i <= 3; i++) { + const p = -1500 + i * 1000; + for (const d of [-6, 0, 6]) { line(p + d, -1500, p + d, 1500); line(-1500, p + d, 1500, p + d); } + } + for (const q of CORNERS) for (let i = 1; i < 4; i++) { line(q.x + i * 250, q.y, q.x + i * 250, q.y + 1000); line(q.x, q.y + i * 250, q.x + 1000, q.y + i * 250); } + // The centre square: 25 groups of 200 µm, each ruled into 16 small squares. + for (let i = 1; i < 5; i++) for (const d of [-4, 0, 4]) { line(-500 + i * 200 + d, -500, -500 + i * 200 + d, 500); line(-500, -500 + i * 200 + d, 500, -500 + i * 200 + d); } + if (s > 0.12) for (let i = 1; i < 20; i++) if (i % 4) { line(-500 + i * 50, -500, -500 + i * 50, 500); line(-500, -500 + i * 50, 500, -500 + i * 50); } + } + + return { + bubbles: [], + inSample: (x, y) => Math.abs(x) < 1900 && Math.abs(y) < 1900, + animated: () => false, + hemo: true, + truth, + cells, + draw(ctx, W, v) { + const s = W / v.fov; + ctx.setTransform(1, 0, 0, 1, 0, 0); + ctx.fillStyle = "#eef0ec"; ctx.fillRect(0, 0, W, W); + ctx.setTransform(s, 0, 0, s, W / 2 - v.cx * s, W / 2 - v.cy * s); + const vr = viewRect(v); + // The ruled area is a little darker, and so are the corner squares to count. + ctx.fillStyle = "rgba(200,206,206,0.35)"; ctx.fillRect(-1500, -1500, 3000, 3000); + lines(ctx, s); + for (const c of cells) { + if (c.x < vr.l - 20 || c.x > vr.r + 20 || c.y < vr.t - 20 || c.y > vr.b + 20) continue; + const R = Math.max(c.d / 2, 1.4 / s); + ctx.beginPath(); ctx.arc(c.x, c.y, R, 0, Math.PI * 2); + if (c.dead && trypan) { ctx.fillStyle = "rgba(38,66,168,0.85)"; ctx.fill(); ctx.lineWidth = Math.max(0.8, 0.5 / s); ctx.strokeStyle = "rgba(20,30,90,0.9)"; ctx.stroke(); } + else { + ctx.fillStyle = c.dead ? "rgba(196,198,190,0.8)" : "rgba(252,252,246,0.95)"; ctx.fill(); + ctx.lineWidth = Math.max(1, R * 0.28); ctx.strokeStyle = c.dead ? "rgba(90,92,86,0.55)" : "rgba(40,42,40,0.7)"; ctx.stroke(); + if (s > 0.5 && !c.dead) { ctx.beginPath(); ctx.arc(c.x - R * 0.3, c.y - R * 0.3, R * 0.35, 0, Math.PI * 2); ctx.fillStyle = "rgba(255,255,255,0.9)"; ctx.fill(); } + } + if (c.counted) { ctx.lineWidth = Math.max(1.4, 1.2 / s); ctx.strokeStyle = "#2fbf5a"; ctx.beginPath(); ctx.arc(c.x, c.y, R + Math.max(2.5, 2 / s), 0, Math.PI * 2); ctx.stroke(); } + } + drawDust(ctx, dust, vr, s); + }, + pickCell(x, y) { + let best = null, d2 = 13 * 13; + for (const c of cells) { const d = (c.x - x) ** 2 + (c.y - y) ** 2; if (d < d2) { d2 = d; best = c; } } + return best; + }, + }; + } + + function gauss(r) { return Math.sqrt(-2 * Math.log(r() + 1e-12)) * Math.cos(2 * Math.PI * r()); } + export function makeField(prep) { if (prep.specimen === "onion") return onionField(prep); if (prep.specimen === "cheek") return cheekField(prep); if (prep.specimen === "elodea") return elodeaField(prep); + if (prep.specimen === "root") return rootField(prep); + if (prep.specimen === "redonion") return redOnionField(prep); return emptyField(prep); } diff --git a/web/lab3d/js/tasks.js b/web/lab3d/js/tasks.js index bc8a39d..4bc9431 100644 --- a/web/lab3d/js/tasks.js +++ b/web/lab3d/js/tasks.js @@ -66,6 +66,72 @@ export const EXPERIMENTS = { ["compare", "Incubate Dish B (no drug) for the same time and look at it too"], ], }, + dose: { + title: "Dose–response curve", tag: "Simulated by CellSim", blurb: "Treat the six wells of a plate with rising doses of a drug, incubate for 72 h and find the dose that kills half the cells (the IC50).", + steps: [ + ["goggles", "Put on the safety goggles"], + ["hands", "Wash your hands"], + ["plate-taken", "Open the incubator and take out Plate 1"], + ["tip", "Hold the micropipette and fit a tip from the tip box"], + ["dose:3", "Dose 3 or more wells, each with a different volume of one drug (R sets the volume; a fresh tip for every well)"], + ["control", "Leave at least one well untreated: it is the control"], + ["incubate:72", "Put the plate back in the incubator and let 72 h pass"], + ["read", "Slide the plate into the plate reader on the microscope bench"], + ["dr-curve", "Open the journal (J), Cell culture tab: find the IC50 on the curve"], + ], + }, + count: { + title: "Counting cells", tag: "Simulated by CellSim", blurb: "Lift living cells off a dish, stain them with trypan blue and count them in a hemocytometer: how many cells, and how many alive?", + steps: [ + ["goggles", "Put on the safety goggles"], + ["hands", "Wash your hands"], + ["dish-taken", "Open the incubator and take out a dish"], + ["trypsin", "Hold the trypsin bottle and right-click the dish to lift the cells off"], + ["tip", "Fit a tip on the micropipette and set it to 10 µL (press R)"], + ["trypan-mixed", "Draw up 10 µL of cells and add them to the trypan blue tube in the rack"], + ["hemo-loaded", "With a fresh tip, draw up 10 µL of the mix and load the hemocytometer"], + ["hemo-stage", "Clip the hemocytometer onto the microscope stage"], + ["focus:10", "Focus at 10× on the grid"], + ["count:4", "Click every cell in the four corner squares to count it"], + ["count:done", "Work out the cells per mL and how many are alive"], + ], + }, + mitosis: { + title: "Mitosis in a root tip", tag: "Plant cells dividing", blurb: "Soften an onion root tip in warm acid, stain and squash it, then find cells in every stage of mitosis.", + steps: [ + ["goggles", "Put on the safety goggles: you'll use acid"], + ["hands", "Wash your hands"], + ["root-cut", "By the windows: cut the last 5 mm off a root with the scalpel, and pick it up with the forceps"], + ["acid", "Add 3 drops of 1 M hydrochloric acid to the watch glass in the water bath"], + ["root-acid", "Put the root tip in the warm acid with the forceps"], + ["root-soft", "When it's soft (5 minutes, 20 s here), take it out with the forceps"], + ["sample:root", "Lay it on a clean slide"], + ["drop:toluidine", "Add one drop of toluidine blue"], + ["cover:angle", "Lower a cover slip slowly (hold right-click)"], + ["squash", "Hold the paper towels and press down hard on the cover slip (hold right-click)"], + ["stage", "Clip the slide onto the microscope stage"], + ["focus:40", "Find the small cells just behind the tip at 400×"], + ["classify:25", "Click 25 cells and say which stage of mitosis each is in"], + ["stages:all", "Find one cell in each stage: prophase, metaphase, anaphase and telophase"], + ], + }, + osmosis: { + title: "Osmosis in red onion cells", tag: "Plant cells, water", blurb: "Watch red onion cells shrink away from their walls in salt water, then swell back in pure water.", + steps: [ + ["goggles", "Put on the safety goggles"], + ["hands", "Wash your hands"], + ["slide-on-tile", "Take a clean slide and put it on the white tile"], + ["redonion-cut", "Cut the red onion with the scalpel"], + ["sample:redonion", "Peel the thin red skin with the forceps and lay it on the slide"], + ["drop:water", "Add one drop of distilled water"], + ["cover:angle", "Lower a cover slip slowly (hold right-click)"], + ["stage", "Clip it onto the stage and focus at 100×: red sap fills each cell"], + ["irrigate:salt", "Off the stage, add a drop of salt solution at one edge, then draw it under with a paper towel"], + ["osmo:plasmolysed", "Look again: the cells shrink away from their walls"], + ["irrigate:water", "Draw distilled water under the same way"], + ["osmo:recovered", "Watch the cells swell back against their walls"], + ], + }, }; export class Tasks { From e9eb69e5e923ceda6608c7d4f04e919322c09795 Mon Sep 17 00:00:00 2001 From: Henry Date: Mon, 2 Nov 2026 15:21:56 +0800 Subject: [PATCH 4/4] README: lead with what CellSim is and how to try it The README opened on a dense status block and a reference table, so a visitor had to read far to learn what CellSim is or how to try it. It now says that in plain words first, then: the four browser tools, the 3D lab's experiments (marked drawn or simulated), what the engine does, what it is and isn't good for, and how far to trust it. The Python and docking quickstarts, the full capability table, the roadmap and the contributor notes follow, with every number and caveat kept. --- README.md | 324 ++++++++++++++++++++++++++++-------------------------- 1 file changed, 171 insertions(+), 153 deletions(-) diff --git a/README.md b/README.md index 7cf2aaf..509093c 100755 --- a/README.md +++ b/README.md @@ -1,126 +1,125 @@ # CellSim -**A physics-first, uncertainty-honest in-silico cell and drug-response -simulator in Python. Open source, Apple-silicon and Linux, no GPU -required.** +**CellSim simulates living cells and how they respond to drugs.** Each +simulated cell grows, copies its DNA, divides, repairs damage or dies, +and a drug changes those decisions from inside the cell. You can walk +into a 3D lab and use it, run experiments on a web page, or call it from +Python. + +Free and open source (MIT). Runs on an ordinary laptop, no graphics card +needed. [![The 3D lab: a microscope bench and an incubator, with daylight through the windows](web/lab3d/screenshot.jpg)](https://rockman6.github.io/CellSim/lab3d/) -**[Walk into the lab →](https://rockman6.github.io/CellSim/lab3d/)** -— a biology lab you explore in first person, in your browser. Prepare -slides of onion skin, your own cheek cells, a pondweed leaf or red onion -(and watch osmosis), squash a root tip and find every stage of mitosis. -Or work with living lung cancer cells: treat them with paclitaxel, -doxorubicin or cisplatin, pipette a dose–response plate and read off the -IC50, or count them in a hemocytometer. Those cells are simulated by -this engine, on your own machine. Press F to find anything in the lab. Use a computer with a keyboard and mouse: WASD to -walk, left-click to take, right-click to use. Graphics presets run from -older laptops to fast graphics cards. Source and controls: -[`web/lab3d/`](web/lab3d/). - -**[Run an experiment in your browser →](https://rockman6.github.io/CellSim/lab/)** -— pick cells, a drug and a schedule, press Run. The real engine runs on -your own machine; nothing to install. - -**[Watch inside one cell →](https://rockman6.github.io/CellSim/lab/cell.html)** -— every molecule the engine tracks, minute by minute, as a cell divides, -arrests or dies. Type any drug name or structure: a drug whose target the -engine models runs (labelled uncalibrated), any other is refused by name, -and an impossible structure is rejected with the atom that breaks it. Or -design your own: block or boost any molecule on the map and see what the -cell does. - -**[Open a simulated spheroid →](https://rockman6.github.io/CellSim/)** -(no install; the demo runs are simulated fresh on every deploy, so they -show what the current code produces) +## Try it in your browser -```bash -pip install cellsim -``` +Nothing to install: the engine runs on your own computer, and nothing is +uploaded. The first visit downloads Python and the engine (about 40 MB), +so allow a minute or two. + +| | | +|---|---| +| **[Walk into the lab →](https://rockman6.github.io/CellSim/lab3d/)** | A biology lab in first person. Prepare slides and use the microscope, or treat living cancer cells and count them. Needs a keyboard and mouse. | +| **[Run an experiment →](https://rockman6.github.io/CellSim/lab/)** | Pick cells, a drug and a dosing schedule, press Run, and see how the colony responds. | +| **[Watch inside one cell →](https://rockman6.github.io/CellSim/lab/cell.html)** | Every molecule the engine tracks, minute by minute, as one cell divides, stops or dies. Type any drug's name, or design your own. | +| **[Open a simulated tumour →](https://rockman6.github.io/CellSim/)** | 3D tumour spheroids grown by the engine, simulated again every time the site is updated. | + +## The 3D lab + +Walk with **W A S D** and the mouse. **Left-click** picks things up, +**right-click** uses them, and **1–9** choose what's in your hand. Press +**F** and type a name to find anything (spelling mistakes are fine). +Each experiment gives you its steps one at a time. -CellSim is converging on one product: an interactive dish. Pick a cell -line and a drug, set a dose schedule, watch the colony respond, and get a -dose-response curve whose error bar has been checked against public -cell-line data. The molecular layer (docking, ADMET, quantum descriptors) -feeds that engine as an input with provenance and a measured accuracy -flag; it is not the product on its own. - -> **Status (October 2026).** Phases 0–2 of the [plan](docs/PLAN.md) are -> done and Phase 3 is in review. The smoke suite is green, the repository -> has one identity, and `cellsim/cell/` holds a validated drug-response -> engine that runs well-mixed or in space. -> -> **Phase 1 closed with a negative result that set the direction.** The -> engine reproduces each drug's potency scale, but predicting *which -> cell line* is more sensitive turned out to be unreachable: eleven -> canonical markers, fitted optimally across 156–683 lines, explain only -> 9–20 % of the difference between lines. So per-line ranking is out of -> scope, and Phase 2 aimed at what mechanism is actually good for — -> **within-line dynamics**: dose schedule, wash-out, resistance under -> selection, combination timing. -> -> **Phase 2 built the dish.** `cellsim dish` grows those cells in space — -> a monolayer with contact inhibition, or a spheroid with oxygen and drug -> diffusing in, hypoxic quiescence and a necrotic core — and -> [`web/viewer/`](web/viewer/) renders the per-cell stream in a browser. -> Every Phase-2 claim was re-measured over seeds and doses before the -> dish was built on it; one was retracted and one qualified. -> -> **Phase 3 found the exception to the Phase-1 result.** Across ten drugs -> and 91 held-out predictions the conclusion holds — except for the one -> drug whose target is part of the modelled mechanism. An MDM2 inhibitor -> works by stabilising p53, and the engine calls all eleven lines -> correctly (a constant gets five), including HeLa, whose TP53 is -> wild-type by sequence but whose p53 is degraded by HPV E6 rather than -> by MDM2. So: no ranking lines for cytotoxic drugs, but yes for a drug -> whose mechanism is modelled. Every number is in -> [`docs/VALIDATION.md`](docs/VALIDATION.md), misses included. -> -> The 2026 C++/Metal prototype lives in [`OLD/`](OLD/) as a biology -> reference; it still builds and passes its 8 headless benchmarks, but -> its UI is retired and a new interface is planned on top of the Python -> engine. - -## What works today - -| Layer | What you can run | How it is validated | +| Experiment | What you do | The cells | |---|---|---| -| Docking triage (`cellsim dock`) | SMILES list + receptor PDB → ranked CSV with ΔG ± CI, pose-trust (UFF strain), PoseBusters, ADMET, one triage column | 15-cocrystal blind re-dock, structures and SMILES fetched from RCSB: top-3 pose recovery 87 %, top-1 73 %, PoseBusters validity 100 % | -| Target-class reliability (`cellsim/uq`) | Measured docking error per receptor family, so every ΔG carries an **accuracy** flag, not just seed scatter | trypsin-like 0.9, kinase ATP-site 2.2, ultra-tight binders 5.0 kcal/mol MAE (n = 4–6 each) | -| ADMET descriptors (`cellsim admet`, `profile`) | Lipinski, TPSA, QED, ESOL logS, BBB / hERG / Ames rule flags, one-page profile PNG | Published formulae, cited at the point of use in `cellsim/chem/admet.py` | -| CYP3A4 site of metabolism (`cellsim som`) | xTB C–H bond-dissociation ranking with a heme-accessibility re-rank | 2/3 on the bundled literature set; blind to N-dealkylation. **Advisory only.** | -| Knock a gene out (`api.knockout`) | 13 pathway genes — knockout, knockdown or overexpression — and what the rest of the network does without them | TP53 loss lands where the p53-mutant lines are; PUMA/BAX/CASP3 knockouts are identical because they are one pathway; ABCB1 protects doxorubicin and **not** cisplatin, which it does not transport | -| Starve a tumour (`api.starve`) | Glucose as a second diffusing nutrient. Starved cells burn more oxygen (Casciari 1992), so lowering glucose thins the viable rim through hypoxia | **Directions validated** against Mueller-Klieser 1986: the rim thins from 175 to 111 µm across the published 16.5–0.8 mM range. Magnitudes unchecked — the published rim widths are image-only | -| Cells that crawl (`DishParams.migration_*`) | A random walk on the lattice, optionally up the oxygen gradient | Matches D = k·h²/4 to within 1 % at 2 hops/h | -| Immune killing (`api.killing`) | Effector cells on a tumour monolayer. Each contact delivers a *sublethal* hit; a target dies after three within ~50 min, so killing needs several cells working together (Weigelin et al. 2021) | **Mechanism validated**: hits per kill falls from 418 at E:T 0.1 to 4.1 at E:T 3, and lysis responds to the repair window in the right direction. Absolute lysis against a measured killing curve not yet checked | -| Your own plate (`cellsim plate`) | Read a plate-reader export (grid or tidy), normalise to the plate's own controls, fit a dose-response curve, and get GR metrics comparable across lines | Coverage measured against known IC50s: a nominal 95 % interval contains the truth ~90 % of the time on ten concentrations — and only **68 % on five**, which is flagged. Flat plates are refused; ranges that clip the response are marked extrapolated | -| Calibrated uncertainty (`scripts/calibrate_cell_uncertainty.py`) | Every predicted IC50 comes with an interval whose coverage has been scored | Leave-one-drug-out: ±2.6× covers 64 % (68 % nominal), ±4.8× covers 85 % (90 %), ±6.5× covers 95 % (95 %). Wide on purpose — GDSC's own replicate screens disagree by a median 5.3× | -| Cell drug-response engine (`cellsim cell-sim`, `cellsim cell-stream`) | Pick a cell line, a drug and a **dose schedule**; get the colony over time, viability, and a per-cell state stream (JSON Lines) for a UI. Built for *within-line* questions: schedule, wash-out, resistance, combinations | Each drug's potency scale is right (A549 cisplatin 10.9 µM vs 9.8 measured; 20/25 held-out predictions inside GDSC's replicate span). **Ranking one cell line against another is explicitly out of scope** — measured as unreachable from canonical markers ([why](docs/VALIDATION.md)). | -| Spatial dish (`cellsim dish`) and web viewer (`web/viewer/`) | Grow cells as a monolayer or a spheroid under a dose schedule; oxygen and drug fields, contact inhibition, hypoxic quiescence, necrosis, clones. Open the JSON Lines stream in the viewer: 3-D cells coloured by phase, p53, caspase-3, oxygen or lineage, time scrubbing, charts, CSV export | Field solvers match closed forms (Grimes's 233 µm oxygen limit; the analytic slab profile). Re-running the Cell Tracking Challenge HeLa movie: colony size within 3–4 % at 46 h. Spheroid growth **calibrated** on DLD-1 (one constant). **Open misses:** the spheroid's necrotic core is too large, and real HeLa splits into fast cyclers and non-dividers, which the engine does not ([details](docs/VALIDATION.md)). | -| Cell-level PK/PD modules (`cellsim/cell`) | Occupancy, permeation, pH trapping, efflux, binding sink, tissue penetration, fate, resistance, clearance, cell cycle, lattice agents | Each module is checked against its analytic limit (22 tests). | -| Alchemical FEP (`cellsim/fep`) | Hydration and binding ΔG scaffolds on openmmtools + MBAR | **Experimental, not a product path.** FreeSolv-12 MAE 1.42 kcal/mol on 10/12 with a size-dependent bias (no barostat). Binding ΔG has never produced a number on a real binder. | - -The full set of numbers, with reproducers and caveats, is in +| Onion skin | Peel one layer of cells, stain it with iodine, focus up to 400× | Drawn | +| Your cheek cells | Swab your cheek, smear it on a slide, stain it blue | Drawn | +| Pondweed leaf | Watch the chloroplasts stream round each cell | Drawn | +| Mitosis in a root tip | Soften a root tip in warm acid, stain and squash it, then name the stage of each cell | Drawn | +| Osmosis in red onion | Draw salt water under the cover slip and watch the cells shrink from their walls | Drawn | +| Living cancer cells | Treat a dish of lung cancer cells with a drug, incubate it, compare it with an untreated dish | **Simulated** | +| Dose–response curve | Pipette rising doses into a 6-well plate, incubate for 72 h, read off the IC50 | **Simulated** | +| Counting cells | Stain cells with trypan blue and count the live and dead ones in a hemocytometer | **Simulated** | + +*Drawn* slides show cells at their real sizes but are not simulated. +*Simulated* cells come from the CellSim engine, cell by cell. Graphics +settings run from older laptops to fast graphics cards. Source, +controls and credits: [`web/lab3d/`](web/lab3d/). + +## What the engine does + +- **Each cell runs its own machinery:** a cell cycle (G1, S, G2, M), a + DNA-damage alarm (the ATM–p53–MDM2 circuit), and the switch that makes + a badly damaged cell kill itself (apoptosis). +- **Drugs act from inside the cell.** How fast a drug gets in, is pumped + out and binds sets its concentration inside each cell, and that drives + the damage and the decisions. +- **Cells live in a dish.** Mixed freely, one simulation gives a whole + dose–response curve. Placed on a grid, they grow as a flat layer or as + a 3D spheroid, with oxygen and drug seeping in from outside, cells + short of oxygen further in, and a dead core. + +## What it is good for, and what it isn't + +**Good for questions about one kind of cell:** whether to give a drug as +a short pulse or keep it on, how long cells take to recover once the drug +is washed out, whether two drugs help or hinder each other, which cells a +treatment leaves behind, and how deep a drug gets into a tumour. + +**Not for ranking cell lines against each other for ordinary +chemotherapy.** This was measured, not assumed: eleven standard markers, +fitted as well as possible across 156–683 cell lines, explain only +9–20 % of the differences between lines. + +**The exception is a drug whose target is part of the modelled +machinery.** An MDM2 inhibitor works by stabilising p53, and for it the +engine calls all eleven test lines correctly, where always guessing the +same answer gets five. That includes HeLa, whose p53 gene is normal but +whose p53 protein is destroyed by a virus protein (HPV E6) instead of by +MDM2. + +## How far to trust it + +- **Every fitted number is named and counted:** one potency constant per + drug and one spatial constant for the dish. Everything else is a + published measurement, cited where it is used. +- **It is checked against real data.** Each drug's potency comes out about + right: for cisplatin on A549 cells the engine gives an IC50 of 10.9 µM + against 9.8 µM measured, and 20 of 25 predictions it was not fitted to + fall inside the spread of repeated lab screens. Colony growth matches a + real HeLa time-lapse within 3–4 % at 46 h, and oxygen and drug + diffusion match exact solutions. +- **The misses are published too.** The spheroid's dead core comes out + too large, and real HeLa cells split into fast dividers and + non-dividers, which the engine does not do. Results are re-measured + across random seeds and doses before anything is built on them; during + development one was withdrawn and another narrowed. +- **An IC50 from the engine moves 10–20 % between random seeds,** because + it depends on which resistant cells happened to be drawn. Two IC50s + closer than that are not different; `ic50_spread()` measures it. + +Every number, with how to reproduce it and its caveats: [`docs/VALIDATION.md`](docs/VALIDATION.md). -## Quickstart: simulate cells in one minute +## Use it from Python The cell simulator needs only NumPy and SciPy, so it installs with plain -pip — no conda, no compilers, no chemistry stack. (Checked in CI on a bare -virtual environment: `tests/test_pip_install.py`.) +pip: no conda, no compilers. (CI checks this on a bare virtual +environment: `tests/test_pip_install.py`.) ```bash pip install cellsim # or: pip install -e . from a checkout -# A dose-response curve and an IC50 for one line and drug. +# A dose-response curve and an IC50 for one cell line and drug. cellsim cell-sim --line A549 --drug cisplatin --hours 72 # Grow a spheroid for five days and watch oxygen run out in its core. cellsim dish --line DLD-1 --geometry spheroid --hours 120 \ --cells 3000 --grid 48 --every 8 --out spheroid.jsonl -# Open spheroid.jsonl in web/viewer/index.html (no server needed for a -# local file: use the "Open .jsonl" button). +# Then open spheroid.jsonl in web/viewer/index.html with its +# "Open .jsonl" button (no server needed for a local file). ``` In a notebook, `cellsim.api` returns tidy tables (a `pandas.DataFrame` @@ -129,36 +128,32 @@ when pandas is installed, a list of dicts otherwise): ```python from cellsim.api import curve, exposure, washout, combination, spheroid -curve("A549", "paclitaxel") # viability vs concentration, with IC50 -exposure("A549", "paclitaxel") # concentration needed for half kill at - # each exposure time — the schedule question +curve("A549", "paclitaxel") # viability against concentration, with the IC50 +exposure("A549", "paclitaxel") # the concentration for half kill at each + # exposure time: the scheduling question washout("A549", "cisplatin", 20.0, 12.0) # a 12 h pulse, then recovery -combination("A549", "cisplatin", "paclitaxel", 10.0, 0.03) # vs independent action -spheroid("DLD-1", days=6) # size, hypoxia, necrotic core over time +combination("A549", "cisplatin", "paclitaxel", 10.0, 0.03) # against independent action +spheroid("DLD-1", days=6) # size, hypoxia and necrotic core over time ``` -[`docs/cell_tutorial.md`](docs/cell_tutorial.md) walks through a real -question end to end — *should I pulse this drug or leave it on?* — with -every command run and its actual output. +`exposure()` returns `inf` where no concentration reaches half kill. +That is the honest answer for a taxane given for three hours, and the +reason total exposure (AUC) is the wrong measure for that class of drug. -`ic50_spread()` is worth running before quoting any IC50 from this -engine: the number moves 10–20 % between seeds, because a population's -IC50 is set by which resistant lineages were drawn rather than by how -many cells were counted ([why](docs/VALIDATION.md)). Two numbers that -differ by less than that do not differ. +[`docs/cell_tutorial.md`](docs/cell_tutorial.md) works through one real +question end to end, *should I pulse this drug or leave it on?*, with +every command and its actual output. -`exposure()` is the one worth knowing about: it returns `inf` where no -concentration reaches half kill, which is the honest answer for a taxane -given for three hours, and the reason AUC is the wrong exposure metric -for that class. +## Docking and the molecular tools -The molecular layers (docking, MD, FEP, quantum) need the conda stack -below. - -## Quickstart: first docking screen in five minutes +CellSim also has a molecular layer: docking, drug-likeness (ADMET) and +quantum descriptors. It feeds the cell engine as an input, labelled with +where each number came from and how accurate that kind of number has +proved to be. It is not the main product. It needs the conda +environment: ```bash -# 1. One-time environment (conda or mamba). +# 1. One-time setup (conda or mamba). mamba env create -f environment.yml conda activate cellsim pip install -e . # registers the `cellsim` command @@ -174,65 +169,88 @@ cellsim dock \ ``` You get a ranked CSV (`triage`, `dG_kcalmol`, `Kd_human`, `strain_band`, -`pocket_ok`, ADMET columns) plus one-page profile PNGs for the top hits. -Omit `--center` / `--box` for any other receptor and fpocket finds the -site. `cellsim help` lists every subcommand; +`pocket_ok`, ADMET columns) and a one-page profile picture for each top +hit. Leave out `--center` / `--box` for any other receptor and fpocket +finds the binding site. `cellsim help` lists every command; [`docs/docking_tutorial.md`](docs/docking_tutorial.md) walks through a -full screen and, in §8, says which target classes to trust. +full screen and, in §8, says which kinds of target to trust. -## Where this is going +## Everything it can do, and how each part was checked -| Phase | Deliverable | Target | +| Part | What you can run | How it is validated | |---|---|---| -| 0 — done | July fixes merged, CI green, one identity, honest validation page | Oct 2026 | -| 1 — closed, with a finding | Single-cell drug-response engine with one state object and one integrator: cell cycle and p53 axis ported from `OLD/`, death that actually executes, `cellsim/cell` PK on top. Calibrated against GDSC for cisplatin, doxorubicin and paclitaxel (ten drugs by Phase 3). Headless state stream for any UI. Closed early: the per-line prediction it aimed at was measured to be unreachable | Oct 2026 | -| 2 — code done | The dish: spatial colony, diffusion, drug penetration, contact inhibition, validated on the CTC HeLa movie and calibrated on DLD-1 spheroids; web viewer reading the engine stream. Outside users still to find | Apr 2027 | -| 3 — in review | Ten drugs × ten lines, combinations and evolved resistance, calibrated uncertainty with coverage, JOSS paper, conda-forge | Oct 2027 | -| 4 — started | **Your own cells**: `cellsim plate` reads a plate-reader export and fits it with a measured error bar; next, fit this line's own simulator constants and give predictions as bands rather than lines ([plan](docs/PLAN.md)) | 2028 | +| Cell drug-response engine (`cellsim cell-sim`, `cellsim cell-stream`) | Pick a cell line, a drug and a **dose schedule**; get the colony over time, viability, and a per-cell state stream (JSON Lines) for a UI. Built for *within-line* questions: schedule, wash-out, resistance, combinations | Each drug's potency scale is right (A549 cisplatin 10.9 µM vs 9.8 measured; 20/25 held-out predictions inside GDSC's replicate span). **Ranking one cell line against another is explicitly out of scope**, measured as unreachable from canonical markers ([why](docs/VALIDATION.md)) | +| Spatial dish (`cellsim dish`) and web viewer (`web/viewer/`) | Grow cells as a monolayer or a spheroid under a dose schedule: oxygen and drug fields, contact inhibition, hypoxic quiescence, necrosis, clones. The viewer shows 3D cells coloured by phase, p53, caspase-3, oxygen or lineage, with time scrubbing, charts and CSV export | Field solvers match closed forms (Grimes's 233 µm oxygen limit; the analytic slab profile). Re-running the Cell Tracking Challenge HeLa movie: colony size within 3–4 % at 46 h. Spheroid growth **calibrated** on DLD-1 (one constant). **Open misses:** the necrotic core is too large, and real HeLa splits into fast cyclers and non-dividers, which the engine does not ([details](docs/VALIDATION.md)) | +| Calibrated uncertainty (`scripts/calibrate_cell_uncertainty.py`) | Every predicted IC50 comes with an interval whose coverage has been scored | Leave-one-drug-out: ±2.6× covers 64 % (68 % nominal), ±4.8× covers 85 % (90 %), ±6.5× covers 95 % (95 %). Wide on purpose: GDSC's own replicate screens disagree by a median 5.3× | +| Your own plate (`cellsim plate`) | Read a plate-reader export (grid or tidy), normalise to the plate's own controls, fit a dose-response curve, and get GR metrics comparable across lines | Coverage measured against known IC50s: a nominal 95 % interval contains the truth ~90 % of the time on ten concentrations, and only **68 % on five**, which is flagged. Flat plates are refused; ranges that clip the response are marked extrapolated | +| Knock a gene out (`api.knockout`) | 13 pathway genes, knocked out, knocked down or overexpressed, and what the rest of the network does without them | TP53 loss lands where the p53-mutant lines are; PUMA/BAX/CASP3 knockouts are identical because they are one pathway; ABCB1 protects against doxorubicin and **not** cisplatin, which it does not transport | +| Starve a tumour (`api.starve`) | Glucose as a second diffusing nutrient. Starved cells burn more oxygen (Casciari 1992), so lowering glucose thins the viable rim through hypoxia | **Directions validated** against Mueller-Klieser 1986: the rim thins from 175 to 111 µm across the published 16.5–0.8 mM range. Magnitudes unchecked: the published rim widths are image-only | +| Cells that crawl (`DishParams.migration_*`) | A random walk on the lattice, optionally up the oxygen gradient | Matches D = k·h²/4 to within 1 % at 2 hops/h | +| Immune killing (`api.killing`) | Effector cells on a tumour monolayer. Each contact delivers a *sublethal* hit; a target dies after three within ~50 min, so killing needs several cells working together (Weigelin et al. 2021) | **Mechanism validated**: hits per kill falls from 418 at E:T 0.1 to 4.1 at E:T 3, and lysis responds to the repair window in the right direction. Absolute lysis against a measured killing curve not yet checked | +| Cell-level PK/PD modules (`cellsim/cell`) | Occupancy, permeation, pH trapping, efflux, binding sink, tissue penetration, fate, resistance, clearance, cell cycle, lattice agents | Each module is checked against its analytic limit (22 tests) | +| Docking triage (`cellsim dock`) | SMILES list + receptor PDB → ranked CSV with ΔG ± CI, pose-trust (UFF strain), PoseBusters, ADMET, one triage column | 15-cocrystal blind re-dock, structures and SMILES fetched from RCSB: top-3 pose recovery 87 %, top-1 73 %, PoseBusters validity 100 % | +| Target-class reliability (`cellsim/uq`) | Measured docking error per receptor family, so every ΔG carries an **accuracy** flag, not just seed scatter | trypsin-like 0.9, kinase ATP-site 2.2, ultra-tight binders 5.0 kcal/mol MAE (n = 4–6 each) | +| ADMET descriptors (`cellsim admet`, `profile`) | Lipinski, TPSA, QED, ESOL logS, BBB / hERG / Ames rule flags, one-page profile PNG | Published formulae, cited at the point of use in `cellsim/chem/admet.py` | +| CYP3A4 site of metabolism (`cellsim som`) | xTB C–H bond-dissociation ranking with a heme-accessibility re-rank | 2/3 on the bundled literature set; blind to N-dealkylation. **Advisory only** | +| Alchemical FEP (`cellsim/fep`) | Hydration and binding ΔG scaffolds on openmmtools + MBAR | **Experimental, not a product path.** FreeSolv-12 MAE 1.42 kcal/mol on 10/12 with a size-dependent bias (no barostat). Binding ΔG has never produced a number on a real binder | -Details, the keep/kill list and success metrics: [`docs/PLAN.md`](docs/PLAN.md). +## Where it's going -## Layout +As of October 2026, phases 0–2 of the [plan](docs/PLAN.md) are done and +phase 3 is in review. + +| Phase | What it delivers | Target | +|---|---|---| +| 0, done | Fixes merged, CI green, one identity, an honest validation page | Oct 2026 | +| 1, closed with a finding | The single-cell drug-response engine: cell cycle and p53 circuit, death that actually happens, drug uptake on top, calibrated against GDSC. Closed early: the per-line prediction it aimed at was measured to be unreachable | Oct 2026 | +| 2, code done | The dish: a spatial colony with diffusion, drug penetration and contact inhibition, validated on the HeLa movie and calibrated on DLD-1 spheroids, with the web viewer. Outside users still to find | Apr 2027 | +| 3, in review | Ten drugs × ten lines, combinations and evolved resistance, uncertainty with measured coverage, a JOSS paper, conda-forge | Oct 2027 | +| 4, started | **Your own cells:** `cellsim plate` reads a plate-reader export and fits it with a measured error bar; next, fit a line's own simulator constants and predict bands, not lines | 2028 | + +Details, what was kept and dropped, and how success is measured: +[`docs/PLAN.md`](docs/PLAN.md). + +## For contributors ``` cellsim/ + cell/ the cell engine: cycle, p53, death, drug uptake, the dish dock/ Vina + Meeko + PoseBusters + fpocket, batch screen, triage, strain, off-target chem/ SMILES → OpenFF Sage + AM1-BCC; ADMET descriptors; profile dashboards uq/ Monte-Carlo, Sobol, split-conformal, target-class reliability table quantum/ xTB GFN2, CYP3A4 site-of-metabolism (advisory), PySCF hook - cell/ cell-level PK/PD modules (Phase 1 engine grows here) bridge/ binding ΔG → rate-law priors with provenance and accuracy cache/ content-addressed SQLite cache for every expensive physics call fep/ alchemical ΔG scaffolds (experimental; see VALIDATION.md) md/ OpenMM ligand / protein MD helpers benchmarks/ every input needed to reproduce a number in docs/VALIDATION.md -tests/ one folder per src/ module; each file is a standalone gate -scripts/ the `cellsim` CLI dispatcher, fetchers, benchmark runners, doctor -docs/ plan, validation, docking tutorial, archive of the 2026 campaign docs +tests/ one folder per module; each file is a standalone gate +scripts/ the `cellsim` command, fetchers, benchmark runners, doctor +docs/ plan, validation, tutorials, archive of the 2026 campaign docs web/ the site: lab3d/ (the 3D lab), lab/ (the Lab and Inside a cell), viewer/ and demo/ -OLD/ frozen 2026 C++/Metal prototype, its 6 headless validators and scripts (see OLD/README.md) +OLD/ the frozen 2026 C++/Metal prototype and its headless validators (see OLD/README.md) ``` -## Validation and CI - Every push and pull request runs [`smoke.yml`](.github/workflows/smoke.yml): 54 gates across chem, MD, docking, FEP scaffolds, quantum, UQ, bridge, cell and cache, about 15 minutes on a 2-core runner. A regression in any -gate blocks merge. Numbers that take hours (FEP sampling, scale tests) -run only on `workflow_dispatch` and are reported in +gate blocks the merge. Numbers that take hours (FEP sampling, scale +tests) run only on request and are reported in [`docs/VALIDATION.md`](docs/VALIDATION.md) with the commit that produced them. ## History, briefly -v1.0 (March 2026) was a real-time C++/Metal 3D cell simulator with drug -PK/PD. In April 2026 the project restarted around a non-AI molecular -stack after a critique of circular validation; that stack is the -`src/` tree above. The July 2026 fixes corrected the docking numbers and -the FEP binding path. In October 2026 the project was refocused on the -single product described at the top. The complete record, including the -original roadmap, the professor debrief, and every benchmark post-mortem, -is preserved in [`docs/archive/campaign1/`](docs/archive/campaign1/). +Version 1.0 (March 2026) was a real-time C++/Metal 3D cell simulator +with drug kinetics. In April 2026 the project restarted around a +non-AI molecular stack, after a critique of circular validation. The +July 2026 fixes corrected the docking numbers and the FEP binding path. +In October 2026 it was refocused on the cell engine and the dish, and +the 3D lab became its front door. The original prototype is kept in +[`OLD/`](OLD/) as a biology reference; it still builds and passes its +headless benchmarks. The full record, including the original roadmap +and every benchmark post-mortem, is in +[`docs/archive/campaign1/`](docs/archive/campaign1/). ## License