use crate::bh::BhTree;
use crate::ids::NodeId;
use crate::model::KnowledgeGraph;
use crate::rng::Rng;
use crate::vec3::Vec3;
use arc_flow_core::geometry::Vec2;
use serde::{Deserialize, Serialize};
use std::sync::Arc;
#[derive(Clone, Debug)]
pub struct LayoutConfig {
pub seed: u64,
pub max_iterations: u32,
pub theta: f32,
pub repulsion: f32,
pub spring_stiffness: f32,
pub gravity: f32,
pub damping: f32,
pub cool_factor: f32,
pub min_alpha: f32,
pub max_step: f32,
pub min_dist: f32,
}
impl Default for LayoutConfig {
fn default() -> Self {
Self {
seed: 0x5EED,
max_iterations: 600,
theta: 0.9,
repulsion: 20_000.0,
spring_stiffness: 0.02,
gravity: 0.005,
damping: 0.85,
cool_factor: 0.985,
min_alpha: 1e-3,
max_step: 40.0,
min_dist: 1.0,
}
}
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct GraphPayload {
pub node_ids: Vec<NodeId>,
pub weights: Vec<f32>,
pub pinned: Vec<bool>,
pub edges: Vec<(u32, u32, f32)>,
}
impl GraphPayload {
pub fn from_graph(graph: &KnowledgeGraph) -> Self {
let mut node_ids: Vec<NodeId> = graph.nodes().map(|n| n.id).collect();
node_ids.sort_unstable();
let mut slot_of = std::collections::BTreeMap::new();
for (i, id) in node_ids.iter().enumerate() {
slot_of.insert(*id, i as u32);
}
let mut weights = Vec::with_capacity(node_ids.len());
let mut pinned = Vec::with_capacity(node_ids.len());
for id in &node_ids {
let n = graph.node(*id).expect("slot built from the same graph");
weights.push(n.weight);
pinned.push(n.pinned);
}
let edges = graph
.edges()
.filter_map(|e| {
let s = slot_of.get(&e.source).copied()?;
let t = slot_of.get(&e.target).copied()?;
Some((s, t, e.weight))
})
.collect();
Self {
node_ids,
weights,
pinned,
edges,
}
}
}
#[derive(Clone, Debug)]
pub struct LayoutSnapshot<P: Copy> {
pub positions: Arc<Vec<P>>,
pub iteration: u32,
pub alpha: f32,
pub cooled: bool,
}
pub trait LayoutSim: Send + 'static {
type Pos: Copy + Send + Sync + 'static;
fn new(config: LayoutConfig) -> Self;
fn rebuild(&mut self, payload: &GraphPayload);
fn incremental(&mut self, payload: &GraphPayload);
fn set_pinned(&mut self, id: NodeId, pinned: bool);
fn move_node(&mut self, id: NodeId, pos: Self::Pos);
fn step(&mut self);
fn is_cooled(&self) -> bool;
fn snapshot(&self) -> LayoutSnapshot<Self::Pos>;
}
#[derive(Clone, Debug)]
struct SimPoint {
id: NodeId,
weight: f32,
pinned: bool,
}
#[derive(Clone, Debug)]
struct SimCore {
nodes: Vec<SimPoint>,
edges: Vec<(u32, u32, f32)>,
config: LayoutConfig,
rng: Rng,
iteration: u32,
alpha: f32,
cooled: bool,
}
impl SimCore {
fn slot_of(&self, id: NodeId) -> Option<u32> {
self.nodes.iter().position(|n| n.id == id).map(|i| i as u32)
}
fn reheat(&mut self) {
self.alpha = self.alpha.max(0.25);
self.iteration = 0;
self.cooled = false;
}
fn new(config: LayoutConfig) -> Self {
let alpha = 1.0;
Self {
nodes: Vec::new(),
edges: Vec::new(),
rng: Rng::new(config.seed),
iteration: 0,
alpha,
cooled: false,
config,
}
}
fn rebuild<P: Copy, F>(&mut self, payload: &GraphPayload, place: F) -> Vec<P>
where
F: Fn(u32, u32, &mut Rng) -> P,
{
self.nodes.clear();
self.edges.clear();
self.rng = Rng::new(self.config.seed);
self.iteration = 0;
self.alpha = 1.0;
self.cooled = false;
let n = payload.node_ids.len() as u32;
let mut positions = Vec::with_capacity(payload.node_ids.len());
for (i, (id, w)) in payload.node_ids.iter().zip(&payload.weights).enumerate() {
positions.push(place(i as u32, n, &mut self.rng));
self.nodes.push(SimPoint {
id: *id,
weight: *w,
pinned: payload.pinned[i],
});
}
self.edges = payload.edges.clone();
positions
}
fn is_cooled(&self) -> bool {
self.cooled
}
fn wants_steps(&self) -> bool {
!self.cooled && self.iteration < self.config.max_iterations
}
}
pub struct ForceLayout2D {
core: SimCore,
positions: Vec<Vec2>,
velocities: Vec<Vec2>,
tree: BhTree<2>,
scratch: Vec<[f32; 2]>,
stack: Vec<i32>,
}
impl ForceLayout2D {
pub fn new(config: LayoutConfig) -> Self {
<Self as LayoutSim>::new(config)
}
pub fn rebuild(&mut self, payload: &GraphPayload) {
<Self as LayoutSim>::rebuild(self, payload)
}
pub fn incremental(&mut self, payload: &GraphPayload) {
<Self as LayoutSim>::incremental(self, payload)
}
pub fn step(&mut self) {
<Self as LayoutSim>::step(self)
}
pub fn is_cooled(&self) -> bool {
<Self as LayoutSim>::is_cooled(self)
}
pub fn snapshot(&self) -> LayoutSnapshot<Vec2> {
<Self as LayoutSim>::snapshot(self)
}
pub fn set_pinned(&mut self, id: NodeId, pinned: bool) {
<Self as LayoutSim>::set_pinned(self, id, pinned)
}
pub fn move_node(&mut self, id: NodeId, pos: Vec2) {
<Self as LayoutSim>::move_node(self, id, pos)
}
fn place(i: u32, n: u32, rng: &mut Rng) -> Vec2 {
let golden = 2.399_963_2;
let radius = 12.0 * (i as f32 + 0.5).sqrt() * (n as f32).max(1.0).sqrt().recip().max(0.05);
let angle = i as f32 * golden;
Vec2::new(
radius * angle.cos() + rng.next_symmetric(2.0),
radius * angle.sin() + rng.next_symmetric(2.0),
)
}
fn integrate_forces(&mut self, forces: &mut [[f32; 2]]) {
let cfg = self.core.config.clone();
let mut max_move = 0.0f32;
for (i, node) in self.core.nodes.iter().enumerate() {
if node.pinned {
continue;
}
let p = self.positions[i];
let f = forces[i];
let v = self.velocities[i];
let v2 = Vec2::new((v.x + f[0]) * cfg.damping, (v.y + f[1]) * cfg.damping);
let move_len = v2.length().min(cfg.max_step * self.core.alpha);
let dir = if v2.length() > 1e-9 {
v2.scale(1.0 / v2.length())
} else {
Vec2::ZERO
};
let step = dir.scale(move_len);
self.positions[i] = p.plus(step);
self.velocities[i] = v2;
max_move = max_move.max(move_len);
}
self.core.alpha *= self.core.config.cool_factor;
self.core.iteration += 1;
if self.core.alpha < self.core.config.min_alpha
|| max_move < self.core.config.min_alpha * self.core.config.max_step
|| self.core.iteration >= self.core.config.max_iterations
{
self.core.cooled = true;
}
}
}
impl LayoutSim for ForceLayout2D {
fn move_node(&mut self, id: NodeId, pos: Vec2) {
let Some(slot) = self.core.slot_of(id) else {
return;
};
if self.positions.get(slot as usize).is_none() {
return;
}
self.positions[slot as usize] = pos;
if let Some(v) = self.velocities.get_mut(slot as usize) {
*v = Vec2::ZERO;
}
self.core.reheat();
}
type Pos = Vec2;
fn new(config: LayoutConfig) -> Self {
Self {
tree: BhTree::with_capacity(1024, config.theta),
core: SimCore::new(config),
positions: Vec::new(),
velocities: Vec::new(),
scratch: Vec::new(),
stack: Vec::new(),
}
}
fn rebuild(&mut self, payload: &GraphPayload) {
let n = payload.node_ids.len();
let seed = &mut self.core;
let positions = seed.rebuild(payload, Self::place);
self.positions = positions;
self.velocities = vec![Vec2::ZERO; n];
self.tree = BhTree::with_capacity(n * 8, self.core.config.theta);
}
fn incremental(&mut self, payload: &GraphPayload) {
let mut remap: Vec<Option<u32>> = vec![None; payload.node_ids.len()];
for (old_slot, node) in self.core.nodes.iter().enumerate() {
if let Some(i) = payload.node_ids.iter().position(|id| *id == node.id) {
remap[i] = Some(old_slot as u32);
}
}
let old_positions = self.positions.clone();
let mut new_positions = Vec::with_capacity(payload.node_ids.len());
let mut new_velocities = Vec::with_capacity(payload.node_ids.len());
let mut new_nodes = Vec::with_capacity(payload.node_ids.len());
for (i, id) in payload.node_ids.iter().enumerate() {
match remap[i] {
Some(old) => {
new_positions.push(old_positions[old as usize]);
new_velocities.push(self.velocities[old as usize]);
let mut node = self.core.nodes[old as usize].clone();
node.pinned = payload.pinned[i];
new_nodes.push(node);
}
None => {
let near = payload
.edges
.iter()
.find_map(|&(s, t, _)| {
if t as usize == i {
remap[s as usize]
.and_then(|o| old_positions.get(o as usize).copied())
} else if s as usize == i {
remap[t as usize]
.and_then(|o| old_positions.get(o as usize).copied())
} else {
None
}
})
.unwrap_or_else(|| {
old_positions.first().copied().unwrap_or_else(|| {
Self::place(
i as u32,
payload.node_ids.len() as u32,
&mut self.core.rng,
)
})
});
let jitter = Vec2::new(
self.core.rng.next_symmetric(8.0),
self.core.rng.next_symmetric(8.0),
);
new_positions.push(near.plus(jitter));
new_velocities.push(Vec2::ZERO);
new_nodes.push(SimPoint {
id: *id,
weight: payload.weights[i],
pinned: payload.pinned[i],
});
}
}
}
self.core.nodes = new_nodes;
self.positions = new_positions;
self.velocities = new_velocities;
self.core.edges = payload.edges.clone();
self.core.cooled = false;
self.core.alpha = self.core.alpha.max(0.25); self.tree = BhTree::with_capacity(payload.node_ids.len() * 8, self.core.config.theta);
}
fn set_pinned(&mut self, id: NodeId, pinned: bool) {
if let Some(n) = self.core.nodes.iter_mut().find(|n| n.id == id) {
n.pinned = pinned;
}
}
fn step(&mut self) {
if !self.core.wants_steps() {
self.core.cooled = true;
return;
}
let cfg = self.core.config.clone();
let n = self.core.nodes.len();
self.scratch.clear();
self.scratch
.extend(self.positions.iter().map(|p| [p.x, p.y]));
let masses: Vec<f32> = self.core.nodes.iter().map(|n| n.weight.max(0.1)).collect();
self.tree.build(&self.scratch, &masses);
let mut forces = vec![[0.0f32; 2]; n];
for ((i, node), point) in self.core.nodes.iter().enumerate().zip(&self.scratch) {
if node.pinned {
continue;
}
self.tree.repulsion(
*point,
masses[i],
i as u32,
cfg.repulsion,
cfg.min_dist,
&mut self.stack,
&mut forces[i],
);
forces[i][0] += (0.0 - point[0]) * cfg.gravity;
forces[i][1] += (0.0 - point[1]) * cfg.gravity;
}
for &(s, t, w) in &self.core.edges {
let a = self.scratch[s as usize];
let b = self.scratch[t as usize];
let dx = b[0] - a[0];
let dy = b[1] - a[1];
let dist = (dx * dx + dy * dy).sqrt().max(cfg.min_dist);
let f = cfg.spring_stiffness * w * dist;
let ux = dx / dist;
let uy = dy / dist;
if !self.core.nodes[s as usize].pinned {
forces[s as usize][0] += ux * f;
forces[s as usize][1] += uy * f;
}
if !self.core.nodes[t as usize].pinned {
forces[t as usize][0] -= ux * f;
forces[t as usize][1] -= uy * f;
}
}
self.integrate_forces(&mut forces);
}
fn is_cooled(&self) -> bool {
self.core.is_cooled()
}
fn snapshot(&self) -> LayoutSnapshot<Vec2> {
LayoutSnapshot {
positions: Arc::new(self.positions.clone()),
iteration: self.core.iteration,
alpha: self.core.alpha,
cooled: self.core.cooled,
}
}
}
impl ForceLayout2D {
pub fn positions(&self) -> &[Vec2] {
&self.positions
}
pub fn iteration(&self) -> u32 {
self.core.iteration
}
}
pub struct ForceLayout3D {
core: SimCore,
positions: Vec<Vec3>,
velocities: Vec<Vec3>,
tree: BhTree<3>,
scratch: Vec<[f32; 3]>,
stack: Vec<i32>,
}
impl ForceLayout3D {
pub fn new(config: LayoutConfig) -> Self {
<Self as LayoutSim>::new(config)
}
pub fn rebuild(&mut self, payload: &GraphPayload) {
<Self as LayoutSim>::rebuild(self, payload)
}
pub fn incremental(&mut self, payload: &GraphPayload) {
<Self as LayoutSim>::incremental(self, payload)
}
pub fn step(&mut self) {
<Self as LayoutSim>::step(self)
}
pub fn is_cooled(&self) -> bool {
<Self as LayoutSim>::is_cooled(self)
}
pub fn snapshot(&self) -> LayoutSnapshot<Vec3> {
<Self as LayoutSim>::snapshot(self)
}
pub fn set_pinned(&mut self, id: NodeId, pinned: bool) {
<Self as LayoutSim>::set_pinned(self, id, pinned)
}
pub fn move_node(&mut self, id: NodeId, pos: Vec3) {
<Self as LayoutSim>::move_node(self, id, pos)
}
fn place(i: u32, n: u32, rng: &mut Rng) -> Vec3 {
let golden = 2.399_963_2;
let radius = 12.0 * (i as f32 + 0.5).sqrt() * (n as f32).max(1.0).sqrt().recip().max(0.05);
let angle = i as f32 * golden;
let z = rng.next_symmetric(radius * 0.8);
Vec3::new(
radius * angle.cos() + rng.next_symmetric(2.0),
radius * angle.sin() + rng.next_symmetric(2.0),
z,
)
}
}
impl LayoutSim for ForceLayout3D {
fn move_node(&mut self, id: NodeId, pos: Vec3) {
let Some(slot) = self.core.slot_of(id) else {
return;
};
if self.positions.get(slot as usize).is_none() {
return;
}
self.positions[slot as usize] = pos;
if let Some(v) = self.velocities.get_mut(slot as usize) {
*v = Vec3::ZERO;
}
self.core.reheat();
}
type Pos = Vec3;
fn new(config: LayoutConfig) -> Self {
Self {
tree: BhTree::with_capacity(1024, config.theta),
core: SimCore::new(config),
positions: Vec::new(),
velocities: Vec::new(),
scratch: Vec::new(),
stack: Vec::new(),
}
}
fn rebuild(&mut self, payload: &GraphPayload) {
let n = payload.node_ids.len();
let positions = self.core.rebuild(payload, Self::place);
self.positions = positions;
self.velocities = vec![Vec3::ZERO; n];
self.tree = BhTree::with_capacity(n * 8, self.core.config.theta);
}
fn incremental(&mut self, payload: &GraphPayload) {
let mut remap: Vec<Option<u32>> = vec![None; payload.node_ids.len()];
for (old_slot, node) in self.core.nodes.iter().enumerate() {
if let Some(i) = payload.node_ids.iter().position(|id| *id == node.id) {
remap[i] = Some(old_slot as u32);
}
}
let old_positions = self.positions.clone();
let mut new_positions = Vec::with_capacity(payload.node_ids.len());
let mut new_velocities = Vec::with_capacity(payload.node_ids.len());
let mut new_nodes = Vec::with_capacity(payload.node_ids.len());
for (i, id) in payload.node_ids.iter().enumerate() {
match remap[i] {
Some(old) => {
new_positions.push(old_positions[old as usize]);
new_velocities.push(self.velocities[old as usize]);
let mut node = self.core.nodes[old as usize].clone();
node.pinned = payload.pinned[i];
new_nodes.push(node);
}
None => {
let near = payload
.edges
.iter()
.find_map(|&(s, t, _)| {
if t as usize == i {
remap[s as usize]
.and_then(|o| old_positions.get(o as usize).copied())
} else if s as usize == i {
remap[t as usize]
.and_then(|o| old_positions.get(o as usize).copied())
} else {
None
}
})
.unwrap_or_else(|| {
old_positions.first().copied().unwrap_or_else(|| {
Self::place(
i as u32,
payload.node_ids.len() as u32,
&mut self.core.rng,
)
})
});
let jitter = Vec3::new(
self.core.rng.next_symmetric(8.0),
self.core.rng.next_symmetric(8.0),
self.core.rng.next_symmetric(8.0),
);
new_positions.push(near.plus(jitter));
new_velocities.push(Vec3::ZERO);
new_nodes.push(SimPoint {
id: *id,
weight: payload.weights[i],
pinned: payload.pinned[i],
});
}
}
}
self.core.nodes = new_nodes;
self.positions = new_positions;
self.velocities = new_velocities;
self.core.edges = payload.edges.clone();
self.core.cooled = false;
self.core.alpha = self.core.alpha.max(0.25);
self.tree = BhTree::with_capacity(payload.node_ids.len() * 8, self.core.config.theta);
}
fn set_pinned(&mut self, id: NodeId, pinned: bool) {
if let Some(n) = self.core.nodes.iter_mut().find(|n| n.id == id) {
n.pinned = pinned;
}
}
fn step(&mut self) {
if !self.core.wants_steps() {
self.core.cooled = true;
return;
}
let cfg = self.core.config.clone();
let n = self.core.nodes.len();
self.scratch.clear();
self.scratch
.extend(self.positions.iter().map(|p| [p.x, p.y, p.z]));
let masses: Vec<f32> = self.core.nodes.iter().map(|n| n.weight.max(0.1)).collect();
self.tree.build(&self.scratch, &masses);
let mut forces = vec![[0.0f32; 3]; n];
for ((i, node), point) in self.core.nodes.iter().enumerate().zip(&self.scratch) {
if node.pinned {
continue;
}
self.tree.repulsion(
*point,
masses[i],
i as u32,
cfg.repulsion,
cfg.min_dist,
&mut self.stack,
&mut forces[i],
);
forces[i][0] += (0.0 - point[0]) * cfg.gravity;
forces[i][1] += (0.0 - point[1]) * cfg.gravity;
forces[i][2] += (0.0 - point[2]) * cfg.gravity;
}
for &(s, t, w) in &self.core.edges {
let a = self.scratch[s as usize];
let b = self.scratch[t as usize];
let mut d = [0.0f32; 3];
let mut dist2 = 0.0;
for k in 0..3 {
d[k] = b[k] - a[k];
dist2 += d[k] * d[k];
}
let dist = dist2.sqrt().max(cfg.min_dist);
let f = cfg.spring_stiffness * w * dist;
for k in 0..3 {
let u = d[k] / dist;
if !self.core.nodes[s as usize].pinned {
forces[s as usize][k] += u * f;
}
if !self.core.nodes[t as usize].pinned {
forces[t as usize][k] -= u * f;
}
}
}
let mut max_move = 0.0f32;
for (i, node) in self.core.nodes.iter().enumerate() {
if node.pinned {
continue;
}
let p = self.positions[i];
let f = forces[i];
let v = self.velocities[i];
let v2 = Vec3::new(
(v.x + f[0]) * cfg.damping,
(v.y + f[1]) * cfg.damping,
(v.z + f[2]) * cfg.damping,
);
let speed = v2.length();
let move_len = speed.min(cfg.max_step * self.core.alpha);
let dir = if speed > 1e-9 {
v2.scale(1.0 / speed)
} else {
Vec3::ZERO
};
self.positions[i] = p.plus(dir.scale(move_len));
self.velocities[i] = v2;
max_move = max_move.max(move_len);
}
self.core.alpha *= self.core.config.cool_factor;
self.core.iteration += 1;
if self.core.alpha < self.core.config.min_alpha
|| max_move < self.core.config.min_alpha * self.core.config.max_step
|| self.core.iteration >= self.core.config.max_iterations
{
self.core.cooled = true;
}
}
fn is_cooled(&self) -> bool {
self.core.is_cooled()
}
fn snapshot(&self) -> LayoutSnapshot<Vec3> {
LayoutSnapshot {
positions: Arc::new(self.positions.clone()),
iteration: self.core.iteration,
alpha: self.core.alpha,
cooled: self.core.cooled,
}
}
}
impl ForceLayout3D {
pub fn positions(&self) -> &[Vec3] {
&self.positions
}
pub fn iteration(&self) -> u32 {
self.core.iteration
}
}