1use crate::bh::BhTree;
29use crate::ids::NodeId;
30use crate::model::KnowledgeGraph;
31use crate::rng::Rng;
32use crate::vec3::Vec3;
33use arc_flow_core::geometry::Vec2;
34use serde::{Deserialize, Serialize};
35use std::sync::Arc;
36
37#[derive(Clone, Debug)]
39pub struct LayoutConfig {
40 pub seed: u64,
42 pub max_iterations: u32,
44 pub theta: f32,
46 pub repulsion: f32,
48 pub spring_stiffness: f32,
50 pub gravity: f32,
52 pub damping: f32,
54 pub cool_factor: f32,
56 pub min_alpha: f32,
58 pub max_step: f32,
60 pub min_dist: f32,
62}
63
64impl Default for LayoutConfig {
65 fn default() -> Self {
66 Self {
67 seed: 0x5EED,
68 max_iterations: 600,
69 theta: 0.9,
70 repulsion: 20_000.0,
71 spring_stiffness: 0.02,
72 gravity: 0.005,
73 damping: 0.85,
74 cool_factor: 0.985,
75 min_alpha: 1e-3,
76 max_step: 40.0,
77 min_dist: 1.0,
78 }
79 }
80}
81
82#[derive(Clone, Debug, Default, Serialize, Deserialize)]
84pub struct GraphPayload {
85 pub node_ids: Vec<NodeId>,
86 pub weights: Vec<f32>,
88 pub pinned: Vec<bool>,
90 pub edges: Vec<(u32, u32, f32)>,
92}
93
94impl GraphPayload {
95 pub fn from_graph(graph: &KnowledgeGraph) -> Self {
97 let mut node_ids: Vec<NodeId> = graph.nodes().map(|n| n.id).collect();
98 node_ids.sort_unstable();
99 let mut slot_of = std::collections::BTreeMap::new();
100 for (i, id) in node_ids.iter().enumerate() {
101 slot_of.insert(*id, i as u32);
102 }
103 let mut weights = Vec::with_capacity(node_ids.len());
104 let mut pinned = Vec::with_capacity(node_ids.len());
105 for id in &node_ids {
106 let n = graph.node(*id).expect("slot built from the same graph");
107 weights.push(n.weight);
108 pinned.push(n.pinned);
109 }
110 let edges = graph
111 .edges()
112 .filter_map(|e| {
113 let s = slot_of.get(&e.source).copied()?;
114 let t = slot_of.get(&e.target).copied()?;
115 Some((s, t, e.weight))
116 })
117 .collect();
118 Self {
119 node_ids,
120 weights,
121 pinned,
122 edges,
123 }
124 }
125}
126
127#[derive(Clone, Debug)]
129pub struct LayoutSnapshot<P: Copy> {
130 pub positions: Arc<Vec<P>>,
132 pub iteration: u32,
133 pub alpha: f32,
134 pub cooled: bool,
135}
136
137pub trait LayoutSim: Send + 'static {
139 type Pos: Copy + Send + Sync + 'static;
140
141 fn new(config: LayoutConfig) -> Self;
142 fn rebuild(&mut self, payload: &GraphPayload);
144 fn incremental(&mut self, payload: &GraphPayload);
146 fn set_pinned(&mut self, id: NodeId, pinned: bool);
147 fn move_node(&mut self, id: NodeId, pos: Self::Pos);
149 fn step(&mut self);
150 fn is_cooled(&self) -> bool;
151 fn snapshot(&self) -> LayoutSnapshot<Self::Pos>;
152}
153
154#[derive(Clone, Debug)]
156struct SimPoint {
157 id: NodeId,
158 weight: f32,
159 pinned: bool,
160}
161
162#[derive(Clone, Debug)]
164struct SimCore {
165 nodes: Vec<SimPoint>,
166 edges: Vec<(u32, u32, f32)>,
168 config: LayoutConfig,
169 rng: Rng,
170 iteration: u32,
171 alpha: f32,
173 cooled: bool,
174}
175
176impl SimCore {
177 fn slot_of(&self, id: NodeId) -> Option<u32> {
179 self.nodes.iter().position(|n| n.id == id).map(|i| i as u32)
180 }
181
182 fn reheat(&mut self) {
184 self.alpha = self.alpha.max(0.25);
185 self.iteration = 0;
186 self.cooled = false;
187 }
188
189 fn new(config: LayoutConfig) -> Self {
190 let alpha = 1.0;
191 Self {
192 nodes: Vec::new(),
193 edges: Vec::new(),
194 rng: Rng::new(config.seed),
195 iteration: 0,
196 alpha,
197 cooled: false,
198 config,
199 }
200 }
201
202 fn rebuild<P: Copy, F>(&mut self, payload: &GraphPayload, place: F) -> Vec<P>
204 where
205 F: Fn(u32, u32, &mut Rng) -> P,
206 {
207 self.nodes.clear();
208 self.edges.clear();
209 self.rng = Rng::new(self.config.seed);
210 self.iteration = 0;
211 self.alpha = 1.0;
212 self.cooled = false;
213 let n = payload.node_ids.len() as u32;
214 let mut positions = Vec::with_capacity(payload.node_ids.len());
215 for (i, (id, w)) in payload.node_ids.iter().zip(&payload.weights).enumerate() {
216 positions.push(place(i as u32, n, &mut self.rng));
217 self.nodes.push(SimPoint {
218 id: *id,
219 weight: *w,
220 pinned: payload.pinned[i],
221 });
222 }
223 self.edges = payload.edges.clone();
224 positions
225 }
226
227 fn is_cooled(&self) -> bool {
228 self.cooled
229 }
230
231 fn wants_steps(&self) -> bool {
233 !self.cooled && self.iteration < self.config.max_iterations
234 }
235}
236
237pub struct ForceLayout2D {
243 core: SimCore,
244 positions: Vec<Vec2>,
245 velocities: Vec<Vec2>,
246 tree: BhTree<2>,
247 scratch: Vec<[f32; 2]>,
249 stack: Vec<i32>,
251}
252
253impl ForceLayout2D {
254 pub fn new(config: LayoutConfig) -> Self {
256 <Self as LayoutSim>::new(config)
257 }
258
259 pub fn rebuild(&mut self, payload: &GraphPayload) {
261 <Self as LayoutSim>::rebuild(self, payload)
262 }
263
264 pub fn incremental(&mut self, payload: &GraphPayload) {
266 <Self as LayoutSim>::incremental(self, payload)
267 }
268
269 pub fn step(&mut self) {
271 <Self as LayoutSim>::step(self)
272 }
273
274 pub fn is_cooled(&self) -> bool {
276 <Self as LayoutSim>::is_cooled(self)
277 }
278
279 pub fn snapshot(&self) -> LayoutSnapshot<Vec2> {
281 <Self as LayoutSim>::snapshot(self)
282 }
283
284 pub fn set_pinned(&mut self, id: NodeId, pinned: bool) {
286 <Self as LayoutSim>::set_pinned(self, id, pinned)
287 }
288
289 pub fn move_node(&mut self, id: NodeId, pos: Vec2) {
291 <Self as LayoutSim>::move_node(self, id, pos)
292 }
293
294 fn place(i: u32, n: u32, rng: &mut Rng) -> Vec2 {
295 let golden = 2.399_963_2;
297 let radius = 12.0 * (i as f32 + 0.5).sqrt() * (n as f32).max(1.0).sqrt().recip().max(0.05);
298 let angle = i as f32 * golden;
299 Vec2::new(
300 radius * angle.cos() + rng.next_symmetric(2.0),
301 radius * angle.sin() + rng.next_symmetric(2.0),
302 )
303 }
304
305 fn integrate_forces(&mut self, forces: &mut [[f32; 2]]) {
306 let cfg = self.core.config.clone();
307 let mut max_move = 0.0f32;
308 for (i, node) in self.core.nodes.iter().enumerate() {
309 if node.pinned {
310 continue;
311 }
312 let p = self.positions[i];
313 let f = forces[i];
314 let v = self.velocities[i];
315 let v2 = Vec2::new((v.x + f[0]) * cfg.damping, (v.y + f[1]) * cfg.damping);
316 let move_len = v2.length().min(cfg.max_step * self.core.alpha);
317 let dir = if v2.length() > 1e-9 {
318 v2.scale(1.0 / v2.length())
319 } else {
320 Vec2::ZERO
321 };
322 let step = dir.scale(move_len);
323 self.positions[i] = p.plus(step);
324 self.velocities[i] = v2;
325 max_move = max_move.max(move_len);
326 }
327 self.core.alpha *= self.core.config.cool_factor;
328 self.core.iteration += 1;
329 if self.core.alpha < self.core.config.min_alpha
330 || max_move < self.core.config.min_alpha * self.core.config.max_step
331 || self.core.iteration >= self.core.config.max_iterations
332 {
333 self.core.cooled = true;
334 }
335 }
336}
337
338impl LayoutSim for ForceLayout2D {
339 fn move_node(&mut self, id: NodeId, pos: Vec2) {
340 let Some(slot) = self.core.slot_of(id) else {
341 return;
342 };
343 if self.positions.get(slot as usize).is_none() {
344 return;
345 }
346 self.positions[slot as usize] = pos;
347 if let Some(v) = self.velocities.get_mut(slot as usize) {
348 *v = Vec2::ZERO;
349 }
350 self.core.reheat();
351 }
352 type Pos = Vec2;
353
354 fn new(config: LayoutConfig) -> Self {
355 Self {
356 tree: BhTree::with_capacity(1024, config.theta),
357 core: SimCore::new(config),
358 positions: Vec::new(),
359 velocities: Vec::new(),
360 scratch: Vec::new(),
361 stack: Vec::new(),
362 }
363 }
364
365 fn rebuild(&mut self, payload: &GraphPayload) {
366 let n = payload.node_ids.len();
367 let seed = &mut self.core;
368 let positions = seed.rebuild(payload, Self::place);
369 self.positions = positions;
370 self.velocities = vec![Vec2::ZERO; n];
371 self.tree = BhTree::with_capacity(n * 8, self.core.config.theta);
372 }
373
374 fn incremental(&mut self, payload: &GraphPayload) {
375 let mut remap: Vec<Option<u32>> = vec![None; payload.node_ids.len()];
377 for (old_slot, node) in self.core.nodes.iter().enumerate() {
378 if let Some(i) = payload.node_ids.iter().position(|id| *id == node.id) {
379 remap[i] = Some(old_slot as u32);
380 }
381 }
382 let old_positions = self.positions.clone();
383 let mut new_positions = Vec::with_capacity(payload.node_ids.len());
385 let mut new_velocities = Vec::with_capacity(payload.node_ids.len());
386 let mut new_nodes = Vec::with_capacity(payload.node_ids.len());
387 for (i, id) in payload.node_ids.iter().enumerate() {
388 match remap[i] {
389 Some(old) => {
390 new_positions.push(old_positions[old as usize]);
391 new_velocities.push(self.velocities[old as usize]);
392 let mut node = self.core.nodes[old as usize].clone();
393 node.pinned = payload.pinned[i];
394 new_nodes.push(node);
395 }
396 None => {
397 let near = payload
399 .edges
400 .iter()
401 .find_map(|&(s, t, _)| {
402 if t as usize == i {
403 remap[s as usize]
404 .and_then(|o| old_positions.get(o as usize).copied())
405 } else if s as usize == i {
406 remap[t as usize]
407 .and_then(|o| old_positions.get(o as usize).copied())
408 } else {
409 None
410 }
411 })
412 .unwrap_or_else(|| {
413 old_positions.first().copied().unwrap_or_else(|| {
414 Self::place(
415 i as u32,
416 payload.node_ids.len() as u32,
417 &mut self.core.rng,
418 )
419 })
420 });
421 let jitter = Vec2::new(
422 self.core.rng.next_symmetric(8.0),
423 self.core.rng.next_symmetric(8.0),
424 );
425 new_positions.push(near.plus(jitter));
426 new_velocities.push(Vec2::ZERO);
427 new_nodes.push(SimPoint {
428 id: *id,
429 weight: payload.weights[i],
430 pinned: payload.pinned[i],
431 });
432 }
433 }
434 }
435 self.core.nodes = new_nodes;
436 self.positions = new_positions;
437 self.velocities = new_velocities;
438 self.core.edges = payload.edges.clone();
439 self.core.cooled = false;
440 self.core.alpha = self.core.alpha.max(0.25); self.tree = BhTree::with_capacity(payload.node_ids.len() * 8, self.core.config.theta);
442 }
443
444 fn set_pinned(&mut self, id: NodeId, pinned: bool) {
445 if let Some(n) = self.core.nodes.iter_mut().find(|n| n.id == id) {
446 n.pinned = pinned;
447 }
448 }
449
450 fn step(&mut self) {
451 if !self.core.wants_steps() {
452 self.core.cooled = true;
453 return;
454 }
455 let cfg = self.core.config.clone();
456 let n = self.core.nodes.len();
457 self.scratch.clear();
459 self.scratch
460 .extend(self.positions.iter().map(|p| [p.x, p.y]));
461 let masses: Vec<f32> = self.core.nodes.iter().map(|n| n.weight.max(0.1)).collect();
462 self.tree.build(&self.scratch, &masses);
463
464 let mut forces = vec![[0.0f32; 2]; n];
465 for ((i, node), point) in self.core.nodes.iter().enumerate().zip(&self.scratch) {
466 if node.pinned {
467 continue;
468 }
469 self.tree.repulsion(
471 *point,
472 masses[i],
473 i as u32,
474 cfg.repulsion,
475 cfg.min_dist,
476 &mut self.stack,
477 &mut forces[i],
478 );
479 forces[i][0] += (0.0 - point[0]) * cfg.gravity;
481 forces[i][1] += (0.0 - point[1]) * cfg.gravity;
482 }
483 for &(s, t, w) in &self.core.edges {
485 let a = self.scratch[s as usize];
486 let b = self.scratch[t as usize];
487 let dx = b[0] - a[0];
488 let dy = b[1] - a[1];
489 let dist = (dx * dx + dy * dy).sqrt().max(cfg.min_dist);
490 let f = cfg.spring_stiffness * w * dist;
491 let ux = dx / dist;
492 let uy = dy / dist;
493 if !self.core.nodes[s as usize].pinned {
494 forces[s as usize][0] += ux * f;
495 forces[s as usize][1] += uy * f;
496 }
497 if !self.core.nodes[t as usize].pinned {
498 forces[t as usize][0] -= ux * f;
499 forces[t as usize][1] -= uy * f;
500 }
501 }
502 self.integrate_forces(&mut forces);
503 }
504
505 fn is_cooled(&self) -> bool {
506 self.core.is_cooled()
507 }
508
509 fn snapshot(&self) -> LayoutSnapshot<Vec2> {
510 LayoutSnapshot {
511 positions: Arc::new(self.positions.clone()),
512 iteration: self.core.iteration,
513 alpha: self.core.alpha,
514 cooled: self.core.cooled,
515 }
516 }
517}
518
519impl ForceLayout2D {
520 pub fn positions(&self) -> &[Vec2] {
522 &self.positions
523 }
524
525 pub fn iteration(&self) -> u32 {
527 self.core.iteration
528 }
529}
530
531pub struct ForceLayout3D {
537 core: SimCore,
538 positions: Vec<Vec3>,
539 velocities: Vec<Vec3>,
540 tree: BhTree<3>,
541 scratch: Vec<[f32; 3]>,
542 stack: Vec<i32>,
543}
544
545impl ForceLayout3D {
546 pub fn new(config: LayoutConfig) -> Self {
548 <Self as LayoutSim>::new(config)
549 }
550
551 pub fn rebuild(&mut self, payload: &GraphPayload) {
553 <Self as LayoutSim>::rebuild(self, payload)
554 }
555
556 pub fn incremental(&mut self, payload: &GraphPayload) {
558 <Self as LayoutSim>::incremental(self, payload)
559 }
560
561 pub fn step(&mut self) {
563 <Self as LayoutSim>::step(self)
564 }
565
566 pub fn is_cooled(&self) -> bool {
568 <Self as LayoutSim>::is_cooled(self)
569 }
570
571 pub fn snapshot(&self) -> LayoutSnapshot<Vec3> {
573 <Self as LayoutSim>::snapshot(self)
574 }
575
576 pub fn set_pinned(&mut self, id: NodeId, pinned: bool) {
578 <Self as LayoutSim>::set_pinned(self, id, pinned)
579 }
580
581 pub fn move_node(&mut self, id: NodeId, pos: Vec3) {
583 <Self as LayoutSim>::move_node(self, id, pos)
584 }
585
586 fn place(i: u32, n: u32, rng: &mut Rng) -> Vec3 {
587 let golden = 2.399_963_2;
588 let radius = 12.0 * (i as f32 + 0.5).sqrt() * (n as f32).max(1.0).sqrt().recip().max(0.05);
589 let angle = i as f32 * golden;
590 let z = rng.next_symmetric(radius * 0.8);
591 Vec3::new(
592 radius * angle.cos() + rng.next_symmetric(2.0),
593 radius * angle.sin() + rng.next_symmetric(2.0),
594 z,
595 )
596 }
597}
598
599impl LayoutSim for ForceLayout3D {
600 fn move_node(&mut self, id: NodeId, pos: Vec3) {
601 let Some(slot) = self.core.slot_of(id) else {
602 return;
603 };
604 if self.positions.get(slot as usize).is_none() {
605 return;
606 }
607 self.positions[slot as usize] = pos;
608 if let Some(v) = self.velocities.get_mut(slot as usize) {
609 *v = Vec3::ZERO;
610 }
611 self.core.reheat();
612 }
613
614 type Pos = Vec3;
615
616 fn new(config: LayoutConfig) -> Self {
617 Self {
618 tree: BhTree::with_capacity(1024, config.theta),
619 core: SimCore::new(config),
620 positions: Vec::new(),
621 velocities: Vec::new(),
622 scratch: Vec::new(),
623 stack: Vec::new(),
624 }
625 }
626
627 fn rebuild(&mut self, payload: &GraphPayload) {
628 let n = payload.node_ids.len();
629 let positions = self.core.rebuild(payload, Self::place);
630 self.positions = positions;
631 self.velocities = vec![Vec3::ZERO; n];
632 self.tree = BhTree::with_capacity(n * 8, self.core.config.theta);
633 }
634
635 fn incremental(&mut self, payload: &GraphPayload) {
636 let mut remap: Vec<Option<u32>> = vec![None; payload.node_ids.len()];
638 for (old_slot, node) in self.core.nodes.iter().enumerate() {
639 if let Some(i) = payload.node_ids.iter().position(|id| *id == node.id) {
640 remap[i] = Some(old_slot as u32);
641 }
642 }
643 let old_positions = self.positions.clone();
644 let mut new_positions = Vec::with_capacity(payload.node_ids.len());
645 let mut new_velocities = Vec::with_capacity(payload.node_ids.len());
646 let mut new_nodes = Vec::with_capacity(payload.node_ids.len());
647 for (i, id) in payload.node_ids.iter().enumerate() {
648 match remap[i] {
649 Some(old) => {
650 new_positions.push(old_positions[old as usize]);
651 new_velocities.push(self.velocities[old as usize]);
652 let mut node = self.core.nodes[old as usize].clone();
653 node.pinned = payload.pinned[i];
654 new_nodes.push(node);
655 }
656 None => {
657 let near = payload
658 .edges
659 .iter()
660 .find_map(|&(s, t, _)| {
661 if t as usize == i {
662 remap[s as usize]
663 .and_then(|o| old_positions.get(o as usize).copied())
664 } else if s as usize == i {
665 remap[t as usize]
666 .and_then(|o| old_positions.get(o as usize).copied())
667 } else {
668 None
669 }
670 })
671 .unwrap_or_else(|| {
672 old_positions.first().copied().unwrap_or_else(|| {
673 Self::place(
674 i as u32,
675 payload.node_ids.len() as u32,
676 &mut self.core.rng,
677 )
678 })
679 });
680 let jitter = Vec3::new(
681 self.core.rng.next_symmetric(8.0),
682 self.core.rng.next_symmetric(8.0),
683 self.core.rng.next_symmetric(8.0),
684 );
685 new_positions.push(near.plus(jitter));
686 new_velocities.push(Vec3::ZERO);
687 new_nodes.push(SimPoint {
688 id: *id,
689 weight: payload.weights[i],
690 pinned: payload.pinned[i],
691 });
692 }
693 }
694 }
695 self.core.nodes = new_nodes;
696 self.positions = new_positions;
697 self.velocities = new_velocities;
698 self.core.edges = payload.edges.clone();
699 self.core.cooled = false;
700 self.core.alpha = self.core.alpha.max(0.25);
701 self.tree = BhTree::with_capacity(payload.node_ids.len() * 8, self.core.config.theta);
702 }
703
704 fn set_pinned(&mut self, id: NodeId, pinned: bool) {
705 if let Some(n) = self.core.nodes.iter_mut().find(|n| n.id == id) {
706 n.pinned = pinned;
707 }
708 }
709
710 fn step(&mut self) {
711 if !self.core.wants_steps() {
712 self.core.cooled = true;
713 return;
714 }
715 let cfg = self.core.config.clone();
716 let n = self.core.nodes.len();
717 self.scratch.clear();
718 self.scratch
719 .extend(self.positions.iter().map(|p| [p.x, p.y, p.z]));
720 let masses: Vec<f32> = self.core.nodes.iter().map(|n| n.weight.max(0.1)).collect();
721 self.tree.build(&self.scratch, &masses);
722
723 let mut forces = vec![[0.0f32; 3]; n];
724 for ((i, node), point) in self.core.nodes.iter().enumerate().zip(&self.scratch) {
725 if node.pinned {
726 continue;
727 }
728 self.tree.repulsion(
729 *point,
730 masses[i],
731 i as u32,
732 cfg.repulsion,
733 cfg.min_dist,
734 &mut self.stack,
735 &mut forces[i],
736 );
737 forces[i][0] += (0.0 - point[0]) * cfg.gravity;
738 forces[i][1] += (0.0 - point[1]) * cfg.gravity;
739 forces[i][2] += (0.0 - point[2]) * cfg.gravity;
740 }
741 for &(s, t, w) in &self.core.edges {
742 let a = self.scratch[s as usize];
743 let b = self.scratch[t as usize];
744 let mut d = [0.0f32; 3];
745 let mut dist2 = 0.0;
746 for k in 0..3 {
747 d[k] = b[k] - a[k];
748 dist2 += d[k] * d[k];
749 }
750 let dist = dist2.sqrt().max(cfg.min_dist);
751 let f = cfg.spring_stiffness * w * dist;
752 for k in 0..3 {
753 let u = d[k] / dist;
754 if !self.core.nodes[s as usize].pinned {
755 forces[s as usize][k] += u * f;
756 }
757 if !self.core.nodes[t as usize].pinned {
758 forces[t as usize][k] -= u * f;
759 }
760 }
761 }
762
763 let mut max_move = 0.0f32;
765 for (i, node) in self.core.nodes.iter().enumerate() {
766 if node.pinned {
767 continue;
768 }
769 let p = self.positions[i];
770 let f = forces[i];
771 let v = self.velocities[i];
772 let v2 = Vec3::new(
773 (v.x + f[0]) * cfg.damping,
774 (v.y + f[1]) * cfg.damping,
775 (v.z + f[2]) * cfg.damping,
776 );
777 let speed = v2.length();
778 let move_len = speed.min(cfg.max_step * self.core.alpha);
779 let dir = if speed > 1e-9 {
780 v2.scale(1.0 / speed)
781 } else {
782 Vec3::ZERO
783 };
784 self.positions[i] = p.plus(dir.scale(move_len));
785 self.velocities[i] = v2;
786 max_move = max_move.max(move_len);
787 }
788 self.core.alpha *= self.core.config.cool_factor;
789 self.core.iteration += 1;
790 if self.core.alpha < self.core.config.min_alpha
791 || max_move < self.core.config.min_alpha * self.core.config.max_step
792 || self.core.iteration >= self.core.config.max_iterations
793 {
794 self.core.cooled = true;
795 }
796 }
797
798 fn is_cooled(&self) -> bool {
799 self.core.is_cooled()
800 }
801
802 fn snapshot(&self) -> LayoutSnapshot<Vec3> {
803 LayoutSnapshot {
804 positions: Arc::new(self.positions.clone()),
805 iteration: self.core.iteration,
806 alpha: self.core.alpha,
807 cooled: self.core.cooled,
808 }
809 }
810}
811
812impl ForceLayout3D {
813 pub fn positions(&self) -> &[Vec3] {
814 &self.positions
815 }
816
817 pub fn iteration(&self) -> u32 {
818 self.core.iteration
819 }
820}