From 922b5b42ec0dcd5fc90bff9b9e792198651bb6ef Mon Sep 17 00:00:00 2001 From: Nicolas Godzik Date: Wed, 4 Nov 2026 19:38:34 +0100 Subject: [PATCH 1/6] Turn the camera only while the window has the pointer and the focus The camera turned with the mouse's motion while the left button was held, and that motion is the device's, reported wherever the pointer is. A press in the window let go outside it is never seen to end: from then on every move of the mouse across the screen turned the camera, which is how recordings left behind other windows came out turned half way through. Co-Authored-By: Claude Opus 5.5 --- viewer/src/orbit.rs | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/viewer/src/orbit.rs b/viewer/src/orbit.rs index 4574018..bd56549 100644 --- a/viewer/src/orbit.rs +++ b/viewer/src/orbit.rs @@ -2,6 +2,7 @@ use bevy::input::mouse::{AccumulatedMouseMotion, AccumulatedMouseScroll, MouseScrollUnit}; use bevy::prelude::*; +use bevy::window::PrimaryWindow; use bevy_egui::EguiContexts; use cellweave_engine::Scenario; @@ -66,15 +67,28 @@ impl Orbit { } } -/// Turn and zoom from the mouse, unless the pointer is over the panel. +/// Turn and zoom from the mouse, unless the pointer is over the panel or +/// away from the window. +/// +/// The mouse's motion is the device's, reported wherever the pointer is, +/// and a button pressed in the window and let go outside it is never seen +/// to be let go: without the window's focus and the pointer on it, the +/// camera would turn with every move of the mouse across the screen. pub fn steer( mut orbit: ResMut, buttons: Res>, motion: Res, scroll: Res, + windows: Query<&Window, With>, mut contexts: EguiContexts, mut camera: Query<&mut Transform, With>, ) -> Result { + let held = windows + .single() + .is_ok_and(|window| window.focused && window.cursor_position().is_some()); + if !held { + return Ok(()); + } let ctx = contexts.ctx_mut()?; if ctx.is_pointer_over_egui() || ctx.egui_wants_pointer_input() { return Ok(()); From 8edeb76e06c2755fed69a8d75f0a257bac6a4026 Mon Sep 17 00:00:00 2001 From: Nicolas Godzik Date: Thu, 5 Nov 2026 19:59:23 +0100 Subject: [PATCH 2/6] Add a term that switches a node off, and read a network's terms as they push inhibited_by joins the catalogue of terms: - rate * source * self, the mirror of activated_by, with the same optional Hill response. It is what a kinase that inactivates its target does, or a protein that marks another for destruction, and the catalogue had no way to say it. Network::influences returns every term of a cell's own network as it stands under given inputs: the node it moves, its kind, what it reads, its rate, and what it adds to the node's rate of change now. Every term's contribution is worked out in one place, term_rate, for the derivatives and for this view alike; the built-in network still matches the numbers captured before it was a file, bit for bit. Simulation::inputs gives what a cell reads from where it sits, the fields averaged over its pixels; the step builds its inputs through the same function. DEATH_THRESHOLD, QUIESCENCE_THRESHOLD and DIVISION_RATIO are public, so that a picture of a cell can say how far it is from each. No run changes. Co-Authored-By: Claude Opus 5.5 --- crates/core/src/network.rs | 15 ++ crates/engine/src/coupling.rs | 21 +- crates/engine/src/lib.rs | 2 +- crates/engine/src/network.rs | 329 +++++++++++++++++++++++++------- crates/engine/src/simulation.rs | 67 +++++-- 5 files changed, 352 insertions(+), 82 deletions(-) diff --git a/crates/core/src/network.rs b/crates/core/src/network.rs index d316cb6..834f84a 100644 --- a/crates/core/src/network.rs +++ b/crates/core/src/network.rs @@ -61,6 +61,20 @@ pub enum Term { #[serde(default)] hill: Option, }, + /// `- rate * source * self`, Hill in place of `source` when `hill` is set. + /// The source switches this node off, in proportion to how much there is + /// of each: MDM2 marking p53 for destruction, a cyclin-dependent kinase + /// phosphorylating RB. The mirror of `ActivatedBy`, and like it the usual + /// shape of one protein acting on another, here to undo it. + InhibitedBy { + /// Node or input that switches it off. + source: String, + /// How fast, per unit time. + rate: f64, + /// Cooperative response instead of a proportional one. + #[serde(default)] + hill: Option, + }, /// `rate * (1 - source) * (1 - self)`. The node accumulates when the source /// is scarce: HIF-1α as oxygen falls, whose destruction slows rather than /// whose production rises. @@ -125,6 +139,7 @@ impl Term { pub fn source(&self) -> Option<&str> { match self { Self::ActivatedBy { source, .. } + | Self::InhibitedBy { source, .. } | Self::ActivatedByAbsenceOf { source, .. } | Self::ProducedBy { source, .. } | Self::DamagedBelow { source, .. } diff --git a/crates/engine/src/coupling.rs b/crates/engine/src/coupling.rs index 6a9c4de..d078543 100644 --- a/crates/engine/src/coupling.rs +++ b/crates/engine/src/coupling.rs @@ -8,7 +8,7 @@ use crate::cpm::{CpmLattice, OBSTACLE}; use crate::pde::ScalarField; -use cellweave_core::{CellKind, DiffusionField}; +use cellweave_core::{CellId, CellKind, DiffusionField}; /// Whether a cell of this kind draws on the field at all. A dead cell does /// not, and neither does one breaking up in apoptosis. @@ -181,6 +181,25 @@ pub fn mean_per_cell(field: &ScalarField, lattice: &CpmLattice) -> Vec { .collect() } +/// The mean of `field` over the pixels of one cell, or zero for a cell that +/// holds none: [`mean_per_cell`] for a single cell, as a picture of one cell +/// asks for it. +pub fn mean_in(field: &ScalarField, lattice: &CpmLattice, id: CellId) -> f64 { + let (sum, count) = lattice + .grid + .iter() + .enumerate() + .filter(|&(_, &occupant)| occupant == id.0) + .fold((0.0, 0u32), |(sum, count), (i, _)| { + (sum + field.value_at(i), count + 1) + }); + if count == 0 { + 0.0 + } else { + sum / f64::from(count) + } +} + #[cfg(test)] mod tests { #![allow(clippy::unwrap_used)] diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index d1d3ba7..ed7f394 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -20,7 +20,7 @@ pub mod vessels; pub use cpm::CpmLattice; pub use evolution::CloneRecord; pub use measure::{DEPTH_SHARE, Measurements}; -pub use network::{Mutation, Network}; +pub use network::{Influence, Mutation, Network}; pub use pde::ScalarField; pub use simulation::{Fate, Scenario, Simulation}; pub use sisters::SisterFates; diff --git a/crates/engine/src/network.rs b/crates/engine/src/network.rs index fe823d2..bdf1b04 100644 --- a/crates/engine/src/network.rs +++ b/crates/engine/src/network.rs @@ -7,7 +7,7 @@ use std::sync::Arc; -use cellweave_core::network::{INPUT_NAMES, Term}; +use cellweave_core::network::{Hill, INPUT_NAMES, Term}; use cellweave_core::{ CellInputs, CellMechanics, CellweaveError, Concentration, MechanicsSpec, NetworkSpec, ProteinState, SignalingNetwork, TimeStep, Volume, @@ -39,6 +39,30 @@ fn input_source(name: &str) -> Option { } } +/// A Hill response as the loop needs it, refused unless both its exponent +/// and its half-maximal level are positive. +fn hill_of(hill: Option<&Hill>, node: &str) -> Result, CellweaveError> { + match hill { + Some(h) if h.n <= 0.0 || h.k <= 0.0 => Err(CellweaveError::Config(format!( + "node `{node}` has a Hill term with n = {} and k = {}; both must be positive", + h.n, h.k + ))), + Some(h) => Ok(Some((h.n, h.k))), + None => Ok(None), + } +} + +/// What a term reading `s` responds to: `s` itself, or its Hill response. +fn driver(s: f64, hill: Option<(f64, f64)>) -> f64 { + match hill { + None => s, + Some((n, half)) => { + let sn = s.max(0.0).powf(n); + sn / (half.powf(n) + sn) + } + } +} + /// A term with its source resolved and its shape reduced to what the loop needs. #[derive(Debug, Clone, Copy)] enum Compiled { @@ -48,6 +72,12 @@ enum Compiled { rate: f64, hill: Option<(f64, f64)>, }, + /// `- rate * f(source) * self`, `f` being Hill when `hill` is set. + InhibitedBy { + source: Source, + rate: f64, + hill: Option<(f64, f64)>, + }, /// `rate * (1 - source) * (1 - self)`. ActivatedByAbsenceOf { source: Source, rate: f64 }, /// `rate * source`. @@ -75,6 +105,7 @@ impl Compiled { fn rate_mut(&mut self) -> &mut f64 { match self { Compiled::ActivatedBy { rate, .. } + | Compiled::InhibitedBy { rate, .. } | Compiled::ActivatedByAbsenceOf { rate, .. } | Compiled::ProducedBy { rate, .. } | Compiled::Decays { rate } @@ -84,10 +115,30 @@ impl Compiled { } } + /// The rate this term moves its node at. + fn rate(self) -> f64 { + let mut term = self; + *term.rate_mut() + } + + /// The source this term reads, if it reads one. + fn source(&self) -> Option { + match *self { + Compiled::ActivatedBy { source, .. } + | Compiled::InhibitedBy { source, .. } + | Compiled::ActivatedByAbsenceOf { source, .. } + | Compiled::ProducedBy { source, .. } + | Compiled::DamagedBelow { source, .. } + | Compiled::DamagedAbove { source, .. } => Some(source), + Compiled::Decays { .. } | Compiled::RelaxesTo { .. } => None, + } + } + /// The kind of term, as a network file names it. fn kind(&self) -> &'static str { match self { Compiled::ActivatedBy { .. } => "activated_by", + Compiled::InhibitedBy { .. } => "inhibited_by", Compiled::ActivatedByAbsenceOf { .. } => "activated_by_absence_of", Compiled::ProducedBy { .. } => "produced_by", Compiled::Decays { .. } => "decays", @@ -170,6 +221,24 @@ impl std::fmt::Display for Mutation { } } +/// One term of one node as it stands: an arrow in a picture of the network, +/// and how hard it is pushing. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Influence<'a> { + /// The node the term moves, by its index in [`Network::node_names`]. + pub node: usize, + /// The kind of term, as a network file names it. + pub kind: &'static str, + /// The node or input it reads, by the name a file gives it; `None` for a + /// term that reads nothing, turnover or a set point. + pub source: Option<&'a str>, + /// Its rate, as the file gave it or as mutations left it. + pub rate: f64, + /// What it adds to the node's rate of change now: positive when it + /// raises the node, negative when it lowers it. + pub now: f64, +} + /// A protein network, ready to run. /// /// Cheap to clone, which is what a dividing cell does: a daughter is a copy of @@ -265,29 +334,20 @@ impl Network { let mut compiled = Vec::with_capacity(node.terms.len()); for term in &node.terms { compiled.push(match term { - Term::ActivatedBy { source, rate, hill } => { - let hill = match hill { - Some(h) if h.n <= 0.0 || h.k <= 0.0 => { - return Err(CellweaveError::Config(format!( - "node `{}` has a Hill term with n = {} and k = {}; both must be positive", - node.name, h.n, h.k - ))); - } - Some(h) => Some((h.n, h.k)), - None => None, - }; - Compiled::ActivatedBy { - source: resolve(source, &node.name)?, - rate: *rate, - hill, - } - } - Term::ActivatedByAbsenceOf { source, rate } => { - Compiled::ActivatedByAbsenceOf { - source: resolve(source, &node.name)?, - rate: *rate, - } - } + Term::ActivatedBy { source, rate, hill } => Compiled::ActivatedBy { + source: resolve(source, &node.name)?, + rate: *rate, + hill: hill_of(hill.as_ref(), &node.name)?, + }, + Term::InhibitedBy { source, rate, hill } => Compiled::InhibitedBy { + source: resolve(source, &node.name)?, + rate: *rate, + hill: hill_of(hill.as_ref(), &node.name)?, + }, + Term::ActivatedByAbsenceOf { source, rate } => Compiled::ActivatedByAbsenceOf { + source: resolve(source, &node.name)?, + rate: *rate, + }, Term::ProducedBy { source, rate } => Compiled::ProducedBy { source: resolve(source, &node.name)?, rate: *rate, @@ -628,52 +688,87 @@ impl Network { let own = state[i]; let mut rate = 0.0; for term in node_terms { - rate += match *term { - Compiled::ActivatedBy { - source, - rate: k, - hill, - } => { - let s = Self::read(state, inputs, source); - let driver = match hill { - None => s, - Some((n, half)) => { - let sn = s.max(0.0).powf(n); - sn / (half.powf(n) + sn) - } - }; - k * driver * (1.0 - own) - } - Compiled::ActivatedByAbsenceOf { source, rate: k } => { - k * (1.0 - Self::read(state, inputs, source)) * (1.0 - own) - } - Compiled::ProducedBy { source, rate: k } => { - k * Self::read(state, inputs, source) - } - Compiled::Decays { rate: k } => -k * own, - Compiled::RelaxesTo { value, rate: k } => -k * (own - value), - Compiled::DamagedBelow { - source, - threshold, - rate: k, - } => { - let s = Self::read(state, inputs, source); - -k * ((threshold - s) / threshold).max(0.0) - } - Compiled::DamagedAbove { - source, - threshold, - rate: k, - } => { - let s = Self::read(state, inputs, source); - -k * ((s - threshold) / threshold).max(0.0) - } - }; + rate += Self::term_rate(*term, own, state, inputs); } out[i] = rate; } } + /// What one term adds to the rate of change of its node, `own` being the + /// node's value. + fn term_rate(term: Compiled, own: f64, state: &[f64], inputs: &CellInputs) -> f64 { + match term { + Compiled::ActivatedBy { + source, + rate: k, + hill, + } => k * driver(Self::read(state, inputs, source), hill) * (1.0 - own), + Compiled::InhibitedBy { + source, + rate: k, + hill, + } => -k * driver(Self::read(state, inputs, source), hill) * own, + Compiled::ActivatedByAbsenceOf { source, rate: k } => { + k * (1.0 - Self::read(state, inputs, source)) * (1.0 - own) + } + Compiled::ProducedBy { source, rate: k } => k * Self::read(state, inputs, source), + Compiled::Decays { rate: k } => -k * own, + Compiled::RelaxesTo { value, rate: k } => -k * (own - value), + Compiled::DamagedBelow { + source, + threshold, + rate: k, + } => { + let s = Self::read(state, inputs, source); + -k * ((threshold - s) / threshold).max(0.0) + } + Compiled::DamagedAbove { + source, + threshold, + rate: k, + } => { + let s = Self::read(state, inputs, source); + -k * ((s - threshold) / threshold).max(0.0) + } + } + } + + /// Every term of every node as it stands, under `inputs`: what a picture + /// of the network draws as its arrows, and how hard each is pushing. + /// + /// The terms are this network's own, as mutations left them, so a cell + /// that lost a link or gained one shows it. + pub fn influences(&self, inputs: &CellInputs) -> Vec> { + let state: Vec = self.state.values.iter().map(|c| c.0).collect(); + self.terms + .iter() + .enumerate() + .flat_map(|(node, terms)| { + let state = &state; + terms.iter().map(move |term| Influence { + node, + kind: term.kind(), + source: term.source().map(|s| self.source_name(s)), + rate: term.rate(), + now: Self::term_rate(*term, state[node], state, inputs), + }) + }) + .collect() + } + + /// The name a file gives a source. + fn source_name(&self, source: Source) -> &str { + match source { + Source::Oxygen => "oxygen", + Source::Egf => "egf", + Source::Crowding => "crowding", + Source::Stress => "stress", + Source::Waste => "waste", + Source::NecroticFactor => "necrotic_factor", + Source::Node(i) => &self.names[i], + } + } + /// Classic RK4 over `dt`. /// /// Four evaluations, the middle two at the half step, blended one, two, two, @@ -973,7 +1068,7 @@ mod tests { // second order error of the scheme is about the curvature times half the // step, and the curvature here is of order one. let dt = 1e-6; - let cases: [(&str, Term, f64, f64, f64); 7] = [ + let cases: [(&str, Term, f64, f64, f64); 8] = [ // rate * source * (1 - self), with source 0.5 and self 0.25 ( "activated_by", @@ -986,6 +1081,18 @@ mod tests { 0.5, 2.0 * 0.5 * 0.75, ), + // - rate * source * self, with source 0.5 and self 0.6 + ( + "inhibited_by", + Term::InhibitedBy { + source: "egf".into(), + rate: 2.0, + hill: None, + }, + 0.6, + 0.5, + -2.0 * 0.5 * 0.6, + ), // rate * (1 - source) * (1 - self) ( "activated_by_absence_of", @@ -1068,6 +1175,96 @@ mod tests { } } + #[test] + fn an_inhibition_switches_sharply_with_a_hill_response_and_never_below_zero() { + // Half way at a source of 0.4, steeply: well below it the node is + // barely touched, well above it switched off at nearly the full rate. + let hill = Some(Hill { n: 4.0, k: 0.4 }); + let slope = |egf: f64| { + let dt = 1e-6; + let mut spec = one_node(vec![Term::InhibitedBy { + source: "egf".into(), + rate: 1.0, + hill, + }]); + spec.nodes[0].initial = 0.5; + let mut net = Network::from_spec(&spec, 100).unwrap(); + net.step(TimeStep(dt), &at(0.0, egf)); + (net.state().values[0].0 - 0.5) / dt + }; + assert!(slope(0.1).abs() < 0.01, "below k: {}", slope(0.1)); + assert!( + (slope(0.4) + 0.25).abs() < 1e-5, + "at k, half: {}", + slope(0.4) + ); + assert!(slope(1.6) < -0.49, "above k: {}", slope(1.6)); + + // Proportional to the node itself, so it empties the node without + // ever taking it past zero. + let mut spec = one_node(vec![Term::InhibitedBy { + source: "egf".into(), + rate: 2.0, + hill: None, + }]); + spec.nodes[0].initial = 0.5; + let mut net = Network::from_spec(&spec, 100).unwrap(); + for _ in 0..50 { + net.step(TimeStep(1.0), &at(0.0, 1.0)); + let level = net.state().values[0].0; + assert!(level >= 0.0, "below zero: {level}"); + } + assert!(net.state().values[0].0 < 1e-12, "switched off"); + } + + #[test] + fn a_picture_of_the_network_reads_every_term_as_it_pushes_now() { + let net = ras_erk(); + let inputs = at(0.2, 0.2); + let influences = net.influences(&inputs); + let terms: usize = RAS_ERK.matches("kind =").count(); + assert_eq!(influences.len(), terms, "one per term of the file"); + + // ERK, switched on by RAS: 0.8 * ras * (1 - erk), at the start. + let erk = net.node_names().iter().position(|n| n == "erk").unwrap(); + let from_ras = influences + .iter() + .find(|i| i.node == erk && i.source == Some("ras")) + .unwrap(); + assert_eq!(from_ras.kind, "activated_by"); + assert_eq!(from_ras.rate, 0.8); + assert!((from_ras.now - 0.8 * 0.05 * 0.95).abs() < 1e-12); + + // HIF-1a reads an input by its name, and its turnover reads nothing. + let hif = net.node_names().iter().position(|n| n == "hif1").unwrap(); + assert!( + influences + .iter() + .any(|i| i.node == hif && i.source == Some("oxygen")) + ); + assert!( + influences + .iter() + .any(|i| i.node == hif && i.kind == "decays" && i.source.is_none() && i.now < 0.0) + ); + + // The terms, summed, are the network's rate of change. + let mut slopes = vec![0.0; net.node_names().len()]; + let state: Vec = net.state().values.iter().map(|c| c.0).collect(); + Network::derivatives(&net.terms, &state, &inputs, &mut slopes); + for (node, slope) in slopes.iter().enumerate() { + let sum: f64 = influences + .iter() + .filter(|i| i.node == node) + .map(|i| i.now) + .sum(); + assert!( + (sum - slope).abs() < 1e-12, + "node {node}: {sum} against {slope}" + ); + } + } + #[test] fn a_node_reads_the_waste_around_its_cell() { let dt = 1e-6; diff --git a/crates/engine/src/simulation.rs b/crates/engine/src/simulation.rs index 8989bf4..2f5ea43 100644 --- a/crates/engine/src/simulation.rs +++ b/crates/engine/src/simulation.rs @@ -23,7 +23,7 @@ use rand::{RngExt, SeedableRng}; use crate::coupling::{ apply_background_uptake, apply_production, apply_uptake, hold_medium_bath, hold_vessels_at, - hold_vessels_by, mean_per_cell, + hold_vessels_by, mean_in, mean_per_cell, }; use crate::cpm::{CpmLattice, OBSTACLE}; use crate::evolution::CloneRecord; @@ -39,8 +39,10 @@ use crate::vessels::{Capillary, Tip, Vessels}; /// attributed to what was changed. pub const DEFAULT_SEED: u64 = 42; -/// A cell divides once it reaches this multiple of its lineage's reference volume. -const DIVISION_RATIO: f64 = 1.4; +/// A cell divides once it reaches this multiple of its lineage's reference +/// volume. Public, as the two thresholds below, so that a picture of a cell +/// can say how far it is from each. +pub const DIVISION_RATIO: f64 = 1.4; /// Monte Carlo steps between two checks for cells ready to divide, in a tissue /// grown from one cell. @@ -109,10 +111,14 @@ const OXYGEN_WARMUP_MAX_STEPS: usize = 2_000_000; const NETWORK_TIME_PER_MCS: u32 = 8; /// Survival signal below which a cell is necrotic. -const DEATH_THRESHOLD: f64 = 0.25; +pub const DEATH_THRESHOLD: f64 = 0.25; /// Hypoxia response above which a cell stops dividing while staying alive. -const QUIESCENCE_THRESHOLD: f64 = 0.45; +pub const QUIESCENCE_THRESHOLD: f64 = 0.45; + +/// The growth factor every cell reads, wherever it sits: no field carries +/// it, so it is the same for all of them. +const EGF: f64 = 0.2; /// Pixels a necrotic cell gives up per lattice step until nothing is left. /// @@ -1178,15 +1184,13 @@ impl Simulation { ) { continue; } - let inputs = CellInputs { - o2: Concentration(local_o2[i + 1]), - egf: Concentration(0.2), - vegf: Concentration(0.0), - crowding: Concentration(crowding(&self.lattice, id, net)), - stress: Concentration(local_stress.as_ref().map_or(0.0, |s| s[i + 1])), - waste: Concentration(local_waste.as_ref().map_or(0.0, |w| w[i + 1])), - necrotic_factor: Concentration(local_factor.as_ref().map_or(0.0, |f| f[i + 1])), - }; + let inputs = cell_inputs( + local_o2[i + 1], + crowding(&self.lattice, id, net), + local_stress.as_ref().map_or(0.0, |s| s[i + 1]), + local_waste.as_ref().map_or(0.0, |w| w[i + 1]), + local_factor.as_ref().map_or(0.0, |f| f[i + 1]), + ); for _ in 0..NETWORK_TIME_PER_MCS { net.step(TimeStep(1.0), &inputs); } @@ -2281,6 +2285,27 @@ impl Simulation { self.networks.get(slot)?.as_ref() } + /// What cell `id` reads from where it sits: the oxygen, the stress, the + /// waste and the necrotic factor averaged over the pixels it holds now, + /// in the fields as the last step left them, how squeezed it is, and the + /// growth factor. `None` for the medium, an obstacle, or a cell that is + /// gone. + /// + /// What its network last read, give or take the pixels it has gained or + /// lost since. + pub fn inputs(&self, id: CellId) -> Option { + let net = self.network(id)?; + let mean = + |field: Option<&ScalarField>| field.map_or(0.0, |f| mean_in(f, &self.lattice, id)); + Some(cell_inputs( + mean(Some(&self.oxygen)), + crowding(&self.lattice, id, net), + mean(self.stress.as_ref()), + mean(self.waste.as_ref()), + mean(self.necrotic_factor.as_ref()), + )) + } + /// The clone a cell belongs to, or `None` for the medium or an obstacle. A /// cell that is gone keeps the clone it had. pub fn clone_of(&self, id: CellId) -> Option { @@ -2481,6 +2506,20 @@ fn vegf_decay(angiogenesis: &Angiogenesis) -> f64 { /// What a cell can sense of its neighbours' pressure is its own spread: a cell /// pressed small by the tissue around it has less room than it was born to, /// and that is the signal contact inhibition in an epithelium runs on. +/// What a network reads, from the local levels of the fields and how +/// squeezed its cell is. +fn cell_inputs(o2: f64, crowding: f64, stress: f64, waste: f64, factor: f64) -> CellInputs { + CellInputs { + o2: Concentration(o2), + egf: Concentration(EGF), + vegf: Concentration(0.0), + crowding: Concentration(crowding), + stress: Concentration(stress), + waste: Concentration(waste), + necrotic_factor: Concentration(factor), + } +} + fn crowding(lattice: &CpmLattice, id: CellId, net: &Network) -> f64 { let volume = lattice.volume(id).map_or(0, |v| v.0); let reference = f64::from(net.reference_volume().max(1)); From f41cf350b272030abeacc43737722246c236d783 Mon Sep 17 00:00:00 2001 From: Nicolas Godzik Date: Thu, 5 Nov 2026 19:59:32 +0100 Subject: [PATCH 3/6] Open a cell in the viewer: its network as it stands, and what it decides A click on a cell, one that does not drag, opens a window beside the tissue. It draws the cell's own network, laid out from the network itself: what the cell reads in the first column, each protein one column past the furthest of what it reads, a link that closes a loop set aside and drawn back under the boxes. Each protein is a box in the colour the tissue takes when coloured by it; each term that reads something is an arrow, green where it switches on, red where it switches off, dashed where it acts by an absence, as thick as it pushes now. The proteins that answer the simulation's questions say so underneath. Below, the window says in words whether the cell divides and why, how large it asks to be, whether it is alive and its chance of apoptosis, and plots the deciding proteins since the cell was opened. Hovering over a protein lists its terms as they push; clicking it colours the tissue by it. The open cell is outlined in white and ringed by a halo, and the camera can follow it, keeping it in what the window leaves of the screen. --open, --open-at, --follow, --protein and --window do from the command line what the mouse does, so that a recording can open a cell. Co-Authored-By: Claude Opus 5.5 --- viewer/src/diagram.rs | 437 ++++++++++++++++++++++ viewer/src/inspect.rs | 846 ++++++++++++++++++++++++++++++++++++++++++ viewer/src/main.rs | 65 +++- viewer/src/orbit.rs | 33 +- viewer/src/paint.rs | 50 ++- viewer/src/panel.rs | 2 +- viewer/src/relief.rs | 14 + 7 files changed, 1429 insertions(+), 18 deletions(-) create mode 100644 viewer/src/diagram.rs create mode 100644 viewer/src/inspect.rs diff --git a/viewer/src/diagram.rs b/viewer/src/diagram.rs new file mode 100644 index 0000000..bbbc78c --- /dev/null +++ b/viewer/src/diagram.rs @@ -0,0 +1,437 @@ +//! A cell's network drawn as a diagram: what it reads on the left, each +//! protein in a column by how many relays it sits from what it reads, and +//! every term that reads something as an arrow, as thick as it pushes. +//! +//! The layout is worked out from the network itself, not drawn by hand, so +//! that any network a configuration names, and any cell whose mutations +//! rewired it, is drawn as it is. + +use bevy_egui::egui::{self, Color32, Pos2, Rect, Sense, Shape, Stroke, Vec2}; +use cellweave_core::network::INPUT_NAMES; + +use crate::inspect::Link; +use crate::paint; + +/// Room per column and per row, and the size of a protein's box. +const COLUMN: f32 = 90.0; +const ROW: f32 = 60.0; +const BOX: Vec2 = Vec2::new(76.0, 36.0); +/// Room around the whole, for the arrows that loop back under a row. +const MARGIN: f32 = 18.0; + +/// A rate of change, per unit of network time, at which an arrow is drawn +/// at its thickest. +const FULL_PUSH: f64 = 0.15; + +/// Activation, inhibition and damage: green, red, and a darker red. +const ACTIVATES: Color32 = Color32::from_rgb(90, 205, 150); +const INHIBITS: Color32 = Color32::from_rgb(240, 95, 90); +const DAMAGES: Color32 = Color32::from_rgb(190, 60, 120); + +/// Where everything goes, in the diagram's own coordinates. +pub struct Layout { + /// The inputs the network reads, by name, in the engine's order. + pub inputs: Vec<&'static str>, + /// The centre of each input, then of each node, in that order. + pub centres: Vec, + /// The column of each, the same order. + columns: Vec, + /// The size of the whole. + pub size: Vec2, +} + +impl Layout { + /// Lay out `nodes` proteins and what `links` say they read. + pub fn of(nodes: usize, names: &[String], links: &[Link]) -> Self { + let inputs: Vec<&'static str> = INPUT_NAMES + .iter() + .copied() + .filter(|input| links.iter().any(|l| l.source.as_deref() == Some(*input))) + .collect(); + let vertices = inputs.len() + nodes; + let index = |name: &str| { + inputs.iter().position(|i| *i == name).or_else(|| { + names + .iter() + .position(|n| n == name) + .map(|n| inputs.len() + n) + }) + }; + let mut edges: Vec<(usize, usize)> = links + .iter() + .filter_map(|l| Some((index(l.source.as_deref()?)?, inputs.len() + l.node))) + .filter(|(from, to)| from != to) + .collect(); + edges.sort_unstable(); + edges.dedup(); + + let columns = columns(vertices, inputs.len(), &edges); + let rows = rows(&columns, &edges); + let tallest = rows.iter().copied().fold(0, usize::max) + 1; + let mut per_column = vec![0usize; columns.iter().copied().max().unwrap_or(0) + 1]; + for &c in &columns { + per_column[c] += 1; + } + let centres = (0..vertices) + .map(|v| { + // Each column centred on the tallest one. + let offset = (tallest - per_column[columns[v]]) as f32 / 2.0; + Pos2::new( + MARGIN + BOX.x / 2.0 + columns[v] as f32 * COLUMN, + MARGIN + BOX.y / 2.0 + (rows[v] as f32 + offset) * ROW, + ) + }) + .collect(); + Self { + inputs, + centres, + columns, + size: Vec2::new( + 2.0 * MARGIN + BOX.x + (per_column.len() - 1) as f32 * COLUMN, + 2.0 * MARGIN + BOX.y + (tallest - 1) as f32 * ROW + 16.0, + ), + } + } + + /// The vertex a term's source is, if it reads one. + fn source_of(&self, link: &Link, names: &[String]) -> Option { + let name = link.source.as_deref()?; + self.inputs.iter().position(|i| *i == name).or_else(|| { + names + .iter() + .position(|n| n == name) + .map(|n| self.inputs.len() + n) + }) + } +} + +/// The column of every vertex: inputs in the first, and each node one past +/// the furthest of what it reads, once the links that close a loop back are +/// set aside. A node that reads nothing goes in the second. +fn columns(vertices: usize, inputs: usize, edges: &[(usize, usize)]) -> Vec { + let mut after: Vec> = vec![Vec::new(); vertices]; + for &(from, to) in edges { + after[from].push(to); + } + // A depth first walk from the inputs, then from whatever it missed: an + // edge to a vertex still on the walk's path is one that loops back. + let mut state = vec![0u8; vertices]; + let mut back = Vec::new(); + fn walk(v: usize, after: &[Vec], state: &mut [u8], back: &mut Vec<(usize, usize)>) { + state[v] = 1; + for &next in &after[v] { + match state[next] { + 0 => walk(next, after, state, back), + 1 => back.push((v, next)), + _ => {} + } + } + state[v] = 2; + } + for v in 0..vertices { + if state[v] == 0 { + walk(v, &after, &mut state, &mut back); + } + } + let forward: Vec<(usize, usize)> = edges + .iter() + .copied() + .filter(|e| !back.contains(e)) + .collect(); + let mut column: Vec = (0..vertices).map(|v| usize::from(v >= inputs)).collect(); + // The longest path, by relaxing every edge as many times as there are + // vertices: a graph this small needs no cleverer order. + for _ in 0..vertices { + for &(from, to) in &forward { + if to >= inputs { + column[to] = column[to].max(column[from] + 1); + } + } + } + column +} + +/// The row of every vertex within its column, ordered so that each sits +/// near what it is linked to: a few sweeps, each sorting a column by the +/// mean row of its neighbours. +fn rows(columns: &[usize], edges: &[(usize, usize)]) -> Vec { + let n = columns.len(); + let mut row = vec![0.0f32; n]; + let count = columns.iter().copied().max().unwrap_or(0) + 1; + let mut members: Vec> = vec![Vec::new(); count]; + for v in 0..n { + members[columns[v]].push(v); + } + for list in &members { + for (r, &v) in list.iter().enumerate() { + row[v] = r as f32; + } + } + for _ in 0..6 { + for list in &mut members { + let mean = |v: usize| { + let (sum, k) = edges + .iter() + .filter_map(|&(a, b)| match (a == v, b == v) { + (true, false) => Some(row[b]), + (false, true) => Some(row[a]), + _ => None, + }) + .fold((0.0, 0), |(s, k), r| (s + r, k + 1)); + if k == 0 { row[v] } else { sum / k as f32 } + }; + let mut keyed: Vec<(f32, usize)> = list.iter().map(|&v| (mean(v), v)).collect(); + keyed.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1))); + *list = keyed.into_iter().map(|(_, v)| v).collect(); + for (r, &v) in list.iter().enumerate() { + row[v] = r as f32; + } + } + } + row.into_iter().map(|r| r as usize).collect() +} + +/// What a click on the diagram asked for. +pub enum Clicked { + /// Nothing. + Nothing, + /// The protein with this index. + Node(usize), +} + +/// Draw the diagram, scaled to fit `width`, and say what was clicked. +/// +/// `levels` are the proteins' levels, `reads` the inputs' values by name, +/// `badges` a short role label per protein, and `chosen` the protein the +/// tissue is coloured by, if one is. +#[allow(clippy::too_many_arguments)] +pub fn draw( + ui: &mut egui::Ui, + layout: &Layout, + names: &[String], + levels: &[f64], + links: &[Link], + reads: &dyn Fn(&str) -> f64, + badges: &[Option<(String, bool)>], + chosen: Option, + explain: &dyn Fn(usize) -> String, +) -> Clicked { + let scale = (ui.available_width() / layout.size.x).min(1.0); + let (whole, _) = ui.allocate_exact_size(layout.size * scale, Sense::hover()); + let painter = ui.painter_at(whole); + let at = |p: Pos2| whole.min + (p.to_vec2() * scale); + let half = BOX * scale / 2.0; + let boxed = |v: usize| Rect::from_center_size(at(layout.centres[v]), BOX * scale); + let inputs = layout.inputs.len(); + + // Arrows first, under the boxes. + for link in links { + let Some(from) = layout.source_of(link, names) else { + continue; + }; + let to = inputs + link.node; + if from == to { + continue; + } + let strength = ((link.now.abs() / FULL_PUSH) as f32).min(1.0); + let (colour, dashed, bar) = match link.kind { + "activated_by" | "produced_by" => (ACTIVATES, false, false), + "activated_by_absence_of" => (ACTIVATES, true, false), + "inhibited_by" => (INHIBITS, false, true), + _ => (DAMAGES, true, true), + }; + let colour = colour.gamma_multiply(0.35 + 0.65 * strength); + let stroke = Stroke::new((1.0 + 3.5 * strength) * scale.max(0.6), colour); + let (a, b) = (at(layout.centres[from]), at(layout.centres[to])); + let forward = layout.columns[to] > layout.columns[from]; + let points = if forward { + let start = a + Vec2::new(half.x, 0.0); + let end = b - Vec2::new(half.x + 4.0 * scale, 0.0); + let bend = (end.x - start.x) / 2.0; + [ + start, + start + Vec2::new(bend, 0.0), + end - Vec2::new(bend, 0.0), + end, + ] + } else { + // A loop back, under both boxes. + let start = a + Vec2::new(0.0, half.y); + let end = b + Vec2::new(0.0, half.y + 4.0 * scale); + let drop = Vec2::new(0.0, 0.9 * ROW * scale); + [start, start + drop, end + drop, end] + }; + let curve = egui::epaint::CubicBezierShape::from_points_stroke( + points, + false, + Color32::TRANSPARENT, + stroke, + ) + .flatten(Some(0.5)); + if dashed { + painter.extend(Shape::dashed_line(&curve, stroke, 5.0 * scale, 4.0 * scale)); + } else { + painter.add(Shape::line(curve.clone(), stroke)); + } + let (Some(&tip), Some(&before)) = (curve.last(), curve.iter().rev().nth(2)) else { + continue; + }; + let along = (tip - before).normalized(); + let across = along.rot90(); + let size = (5.0 + 2.0 * strength) * scale.max(0.6); + if bar { + painter.line_segment([tip + across * size, tip - across * size], stroke); + } else { + painter.add(Shape::convex_polygon( + vec![ + tip + along * size, + tip + across * size * 0.7, + tip - across * size * 0.7, + ], + colour, + Stroke::NONE, + )); + } + } + + let font = |size: f32| egui::FontId::proportional(size * scale.max(0.7)); + let mut clicked = Clicked::Nothing; + for (i, input) in layout.inputs.iter().enumerate() { + let rect = boxed(i); + let value = reads(input); + painter.rect_filled(rect, rect.height() / 2.0, fill(value)); + painter.text( + rect.center(), + egui::Align2::CENTER_CENTER, + format!("{}\n{value:.2}", label(input)), + font(12.5), + ink(value), + ); + ui.interact(rect, ui.id().with(("input", i)), Sense::hover()) + .on_hover_text(format!( + "{}: read from outside the cell, {value:.2} where it sits now.", + label(input) + )); + } + for (n, name) in names.iter().enumerate() { + let rect = boxed(inputs + n); + let value = levels.get(n).copied().unwrap_or(0.0); + painter.rect_filled(rect, 5.0 * scale, fill(value)); + if chosen == Some(n) { + painter.rect_stroke( + rect.expand(2.0), + 6.0 * scale, + Stroke::new(2.0, Color32::WHITE), + egui::StrokeKind::Outside, + ); + } + painter.text( + rect.center(), + egui::Align2::CENTER_CENTER, + format!("{}\n{value:.2}", label(name)), + font(13.0), + ink(value), + ); + if let Some(Some((badge, on))) = badges.get(n) { + painter.text( + rect.center_bottom() + Vec2::new(0.0, 2.0), + egui::Align2::CENTER_TOP, + badge, + font(11.5), + if *on { + Color32::from_rgb(255, 210, 120) + } else { + Color32::from_gray(150) + }, + ); + } + let response = ui + .interact(rect, ui.id().with(("node", n)), Sense::click()) + .on_hover_text(explain(n)); + if response.clicked() { + clicked = Clicked::Node(n); + } + } + clicked +} + +/// The colour of a level, the ramp the tissue's protein view uses, so that +/// a box and the cells coloured by the same protein match. +fn fill(value: f64) -> Color32 { + let [r, g, b, _] = paint::bytes(paint::ramp(value as f32)); + Color32::from_rgb(r, g, b) +} + +/// Text that reads on that colour: dark on the bright end of the ramp. +fn ink(value: f64) -> Color32 { + if value > 0.72 { + Color32::from_gray(20) + } else { + Color32::from_gray(235) + } +} + +/// How a protein or an input is written for a reader rather than in a +/// file: the usual name where there is one, the file's name otherwise. +pub fn label(name: &str) -> String { + match name { + "oxygen" => "O₂", + "egf" => "EGF", + "crowding" => "crowding", + "stress" => "stress", + "waste" => "waste", + "necrotic_factor" => "necrotic f.", + "egfr" => "EGFR", + "ras" => "RAS", + "raf" => "RAF", + "mek" => "MEK", + "erk" => "ERK", + "hif1" => "HIF-1α", + "vegf" => "VEGF", + "bcl2" => "BCL2", + "bax" => "BAX", + "mdm2" => "MDM2", + "notch" => "NOTCH", + "rb" => "RB", + "e2f" => "E2F", + "cyclin_d" => "cyclin D", + "cyclin_e" => "cyclin E", + "pdl1" => "PD-L1", + other => other, + } + .to_owned() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn link(node: usize, source: &str) -> Link { + Link { + node, + kind: "activated_by", + source: Some(source.to_owned()), + rate: 1.0, + now: 0.0, + } + } + + #[test] + fn a_relay_steps_one_column_further_and_a_loop_back_does_not_push_it() { + // egf -> a -> b -> c, and c back onto b. + let names: Vec = ["a", "b", "c"].iter().map(|s| (*s).to_owned()).collect(); + let links = vec![link(0, "egf"), link(1, "a"), link(2, "b"), link(1, "c")]; + let layout = Layout::of(3, &names, &links); + assert_eq!(layout.inputs, vec!["egf"]); + assert_eq!(layout.columns, vec![0, 1, 2, 3]); + } + + #[test] + fn a_node_that_reads_nothing_sits_beside_the_inputs() { + let names: Vec = ["a", "b"].iter().map(|s| (*s).to_owned()).collect(); + let links = vec![link(1, "a")]; + let layout = Layout::of(2, &names, &links); + assert!(layout.inputs.is_empty()); + assert_eq!(layout.columns, vec![1, 2]); + } +} diff --git a/viewer/src/inspect.rs b/viewer/src/inspect.rs new file mode 100644 index 0000000..3420a42 --- /dev/null +++ b/viewer/src/inspect.rs @@ -0,0 +1,846 @@ +//! One cell opened: click a cell, and a window beside the tissue shows its +//! network as it stands, every protein at its level and every link as hard +//! as it pushes, what the cell reads from where it sits, and what it does +//! with it. +//! +//! Nothing in the window is drawn for the picture's sake: every number is +//! read from the simulation, between two batches, as the census is. + +use bevy::prelude::*; +use bevy::window::PrimaryWindow; +use bevy_egui::{EguiContexts, egui}; +use cellweave_core::{CellId, CellInputs, Roles, SignalingNetwork}; +use cellweave_engine::Fate; +use cellweave_engine::cpm::OBSTACLE; +use cellweave_engine::simulation::{DEATH_THRESHOLD, DIVISION_RATIO, QUIESCENCE_THRESHOLD}; +use egui_plot::{Legend, Line, Plot, PlotPoints}; + +use crate::diagram::{self, Clicked, Layout}; +use crate::orbit::Orbit; +use crate::paint::{self, View}; +use crate::relief::Relief; +use crate::runner::Runner; + +/// Pixels the pointer may move between press and release for the two to +/// be a click on a cell rather than a turn of the camera. +const CLICK: f32 = 5.0; + +/// Readings kept at most; past this every other one is dropped, as the +/// panel's history is. +const HISTORY_LIMIT: usize = 1500; + +/// How quickly the camera catches up with the cell it follows, per second. +const FOLLOW: f32 = 4.0; + +/// How high above the tissue the halo around the open cell floats, in +/// pixels: over the tallest dome a living cell makes. +const HALO_HEIGHT: f32 = 6.5; + +/// How bright the halo is, in HDR units: enough to bloom. +const HALO_GLOW: f32 = 6.0; + +/// How wide the window opens: room at full size for a network of nine +/// columns, the fuller cell's. +const WIDTH: f32 = 860.0; + +/// One term of the cell's network, as it stood when last read. +#[derive(Debug, Clone)] +pub struct Link { + /// The node it moves, by index. + pub node: usize, + /// Its kind, as a network file names it. + pub kind: &'static str, + /// What it reads, by name, if anything. + pub source: Option, + /// Its rate. + pub rate: f64, + /// What it adds to the node's rate of change. + pub now: f64, +} + +/// The cell as it was last read. +#[derive(Debug, Clone)] +pub struct Reading { + /// The step it was read at. + pub mcs: u64, + /// Its proteins, by name, and their levels. + pub names: Vec, + pub levels: Vec, + /// Every term, as it pushes. + pub links: Vec, + /// What it reads from where it sits. + pub inputs: CellInputs, + /// What it is doing; `None` once it is gone. + pub fate: Option, + /// Its size, what it is trying to be, and the size its lineage divides + /// against. + pub volume: u32, + pub target: u32, + pub reference: u32, + /// Its clone. + pub clone: Option, + /// Its centre, in pixels. + pub centre: Option, +} + +/// Which cell is open, and what was read of it. +#[derive(Resource, Default)] +pub struct Inspected { + /// The run it belongs to, by its place on screen, and the cell. + pub cell: Option<(usize, CellId)>, + /// A pixel clicked, waiting for its run to be back from the pool to say + /// which cell holds it. + clicked: Option<(usize, u32, u32)>, + /// Keep the camera on the cell. + pub follow: bool, + /// The latest reading, kept once the cell is gone. + pub reading: Option, + /// Every reading's levels, oldest first. + pub history: Vec<(u64, Vec)>, + /// The generation last read. + seen: Option, + /// Where a press of the left button began. + pressed_at: Option, + /// A pixel of the first run to open once it reaches a step, asked for + /// on the command line. + opening: Option<(u32, u32, u64)>, + /// Where the window's left edge is, as a share of the screen's width, + /// so that a cell followed can be kept in what it leaves uncovered. + covered_from: Option, +} + +impl Inspected { + /// The cell open in the run at `index`, if there is one. + pub fn in_run(&self, index: usize) -> Option { + self.cell.filter(|(i, _)| *i == index).map(|(_, id)| id) + } + + /// Open the cell under pixel `(x, y)` of the first run once it reaches + /// `step`, following it with the camera if `follow`. + pub fn opening(self, x: u32, y: u32, step: u64, follow: bool) -> Self { + Self { + opening: Some((x, y, step)), + follow, + ..self + } + } + + fn close(&mut self) { + self.cell = None; + self.reading = None; + self.history.clear(); + self.seen = None; + self.follow = false; + } +} + +/// A click that does not drag picks the pixel under the pointer, on +/// whichever run it falls; the cell holding it is found once that run is +/// back from the pool. +#[allow(clippy::too_many_arguments)] +pub fn pick( + buttons: Res>, + windows: Query<&Window, With>, + cameras: Query<(&Camera, &GlobalTransform), With>, + sides: Query<(&Runner, &Relief, &GlobalTransform)>, + mut contexts: EguiContexts, + mut inspected: ResMut, +) -> Result { + let Ok(window) = windows.single() else { + return Ok(()); + }; + let Some(cursor) = window.cursor_position() else { + return Ok(()); + }; + let ctx = contexts.ctx_mut()?; + if ctx.is_pointer_over_egui() || ctx.egui_wants_pointer_input() { + inspected.pressed_at = None; + return Ok(()); + } + if buttons.just_pressed(MouseButton::Left) { + inspected.pressed_at = Some(cursor); + } + if !buttons.just_released(MouseButton::Left) { + return Ok(()); + } + let Some(start) = inspected.pressed_at.take() else { + return Ok(()); + }; + if start.distance(cursor) > CLICK { + return Ok(()); + } + let Ok((camera, eye)) = cameras.single() else { + return Ok(()); + }; + let Ok(ray) = camera.viewport_to_world(eye, cursor) else { + return Ok(()); + }; + match hit(ray, &sides) { + Some(pixel) => inspected.clicked = Some(pixel), + None => inspected.close(), + } + Ok(()) +} + +/// The first pixel of any run's surface the ray meets, and the run's +/// place: a march down the ray from above the tallest dome to the plane, +/// stopping where it passes under the surface. +fn hit( + ray: Ray3d, + sides: &Query<(&Runner, &Relief, &GlobalTransform)>, +) -> Option<(usize, u32, u32)> { + let (origin, direction) = (ray.origin, *ray.direction); + if direction.y >= 0.0 { + return None; + } + let top = 10.0; + let t0 = ((top - origin.y) / direction.y).max(0.0); + let t1 = -origin.y / direction.y; + let steps = 400; + for k in 0..=steps { + let point = origin + direction * (t0 + (t1 - t0) * k as f32 / steps as f32); + for (runner, relief, place) in sides { + let (w, h) = relief.size(); + let local = point - place.translation(); + let x = local.x + w as f32 / 2.0; + let y = local.z + h as f32 / 2.0; + if x < 0.0 || y < 0.0 || x >= w as f32 || y >= h as f32 { + continue; + } + let (x, y) = (x as usize, y as usize); + if point.y <= relief.height(x, y) + 0.05 { + return Some((runner.index, x as u32, y as u32)); + } + } + } + None +} + +/// Read the open cell, each time its run is back from the pool with a new +/// state, and find the cell a click asked for. +pub fn read(runners: Query<&Runner>, mut inspected: ResMut) { + if let Some((x, y, step)) = inspected.opening + && runners + .iter() + .find(|r| r.index == 0) + .and_then(Runner::latest) + .is_some_and(|m| m.mcs >= step) + { + inspected.opening = None; + inspected.clicked = Some((0, x, y)); + } + if let Some((index, x, y)) = inspected.clicked { + let Some(runner) = runners.iter().find(|r| r.index == index) else { + inspected.clicked = None; + return; + }; + let Some(sim) = runner.idle() else { + return; + }; + inspected.clicked = None; + let occupant = sim.lattice().occupant(x, y); + let id = CellId(occupant); + if occupant == 0 || occupant == OBSTACLE || sim.network(id).is_none() { + inspected.close(); + return; + } + let follow = inspected.follow; + inspected.close(); + inspected.cell = Some((index, id)); + inspected.follow = follow; + } + + let Some((index, id)) = inspected.cell else { + return; + }; + let Some(runner) = runners.iter().find(|r| r.index == index) else { + return; + }; + if inspected + .seen + .is_some_and(|seen| runner.restarted_since(seen)) + { + inspected.close(); + return; + } + let Some(sim) = runner.idle() else { + return; + }; + if inspected.seen == Some(runner.generation()) { + return; + } + inspected.seen = Some(runner.generation()); + let mcs = runner.latest().map_or(0, |m| m.mcs); + + let (Some(net), Some(inputs)) = (sim.network(id), sim.inputs(id)) else { + // Gone: the last reading stays, marked as such. + if let Some(reading) = inspected.reading.as_mut() { + reading.fate = None; + } + return; + }; + let lattice = sim.lattice(); + let (w, _) = lattice.dims(); + let pixels = lattice.pixels_of(&[id]).pop().unwrap_or_default(); + let centre = (!pixels.is_empty()).then(|| { + let sum = pixels.iter().fold(Vec2::ZERO, |sum, &i| { + sum + Vec2::new((i % w as usize) as f32, (i / w as usize) as f32) + }); + sum / pixels.len() as f32 + }); + let levels: Vec = net.state().values.iter().map(|c| c.0).collect(); + let reading = Reading { + mcs, + names: net.node_names().to_vec(), + levels: levels.clone(), + links: net + .influences(&inputs) + .into_iter() + .map(|i| Link { + node: i.node, + kind: i.kind, + source: i.source.map(str::to_owned), + rate: i.rate, + now: i.now, + }) + .collect(), + inputs, + fate: sim.fate(id), + volume: lattice.volume(id).map_or(0, |v| v.0), + target: lattice.target_volume(id).map_or(0, |v| v.0), + reference: net.reference_volume(), + clone: sim.clone_of(id).map(|c| c.0), + centre, + }; + inspected.reading = Some(reading); + inspected.history.push((mcs, levels)); + if inspected.history.len() > HISTORY_LIMIT { + let last = inspected.history.len() - 1; + let mut k = 0; + inspected.history.retain(|_| { + let keep = k % 2 == 0 || k == last; + k += 1; + keep + }); + } +} + +/// A ring of light over the open cell, so it can be found in the tissue at +/// any zoom: the white membrane alone is lost on a dome seen from afar. +#[derive(Component)] +pub struct Halo; + +/// Make the halo, hidden until a cell is opened. +pub fn spawn_halo( + mut commands: Commands, + mut meshes: ResMut>, + mut materials: ResMut>, +) { + commands.spawn(( + Halo, + Mesh3d(meshes.add(Annulus::new(0.82, 1.0))), + // Unlit, its colour is what it gives off: above one, it blooms. + MeshMaterial3d(materials.add(StandardMaterial { + base_color: Color::linear_rgb(HALO_GLOW, HALO_GLOW * 0.85, HALO_GLOW * 0.55), + unlit: true, + ..default() + })), + // An annulus lies in the plane facing +Z; the tissue faces +Y. + Transform::from_rotation(Quat::from_rotation_x(-std::f32::consts::FRAC_PI_2)), + Visibility::Hidden, + )); +} + +/// Put the halo over the open cell, as wide as the cell, easing towards +/// where the cell has moved since the last batch. +pub fn halo( + time: Res