Skip to main content

arc_graph_core/
layout.rs

1//! 力导向布局引擎(方案 §4)。
2//!
3//! 模型:库仑式排斥(Barnes–Hut 近似,`bh::BhTree`)+ 胡克弹簧(沿边)+
4//! 向心重力 + 速度阻尼 + 逐级冷却。固定随机种子保证可复现;
5//! 支持固定节点(`pinned`)、增量加点、冷却停止。
6//!
7//! # 使用示例(2D,同步逐步)
8//!
9//! ```
10//! use arc_graph_core::{GraphPayload, KnowledgeGraph, LayoutConfig, ForceLayout2D};
11//!
12//! let mut g = KnowledgeGraph::new();
13//! let a = g.add_node("A", None);
14//! let b = g.add_node("B", None);
15//! g.add_edge(a, b, 1.0, None).unwrap();
16//!
17//! let payload = GraphPayload::from_graph(&g);
18//! let mut layout = ForceLayout2D::new(LayoutConfig::default());
19//! layout.rebuild(&payload);
20//!
21//! while !layout.is_cooled() {
22//!     layout.step();
23//! }
24//! let positions = layout.positions(); // &arc_flow_core::geometry::Vec2,直接交给视图层
25//! assert_eq!(positions.len(), 2);
26//! ```
27
28use 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/// 布局参数。默认值适合百到万级节点的知识图谱;视觉调参走 arc-tokens(G3/G4)。
38#[derive(Clone, Debug)]
39pub struct LayoutConfig {
40    /// 随机种子:同种子 → 同初始位置 → 同布局(方案 §4 可复现要求)。
41    pub seed: u64,
42    /// 最大迭代步数(冷却兜底上限)。
43    pub max_iterations: u32,
44    /// Barnes–Hut 打开精度(盒边长 / 距离);0.9 兼顾精度与速度,1e-9 ≈ 暴力。
45    pub theta: f32,
46    /// 排斥强度(库仑式 F = strength·m_i·m_j/d²)。
47    pub repulsion: f32,
48    /// 弹簧刚度(胡克 F = stiffness·weight·d)。
49    pub spring_stiffness: f32,
50    /// 向心重力加速度。
51    pub gravity: f32,
52    /// 速度阻尼(0–1,越大越快停)。
53    pub damping: f32,
54    /// 冷却系数:每步 alpha 乘以该值。
55    pub cool_factor: f32,
56    /// alpha 低于该值视为冷却结束。
57    pub min_alpha: f32,
58    /// 单步最大位移(防爆炸)。
59    pub max_step: f32,
60    /// 软化距离:两点间最小有效距离。
61    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/// 布局输入快照:与维度无关的槽位化图数据(节点按 `NodeId` 升序,槽位稳定)。
83#[derive(Clone, Debug, Default, Serialize, Deserialize)]
84pub struct GraphPayload {
85    pub node_ids: Vec<NodeId>,
86    /// 节点质量(模型 `Node.weight`,已净化 ≥ 0)。
87    pub weights: Vec<f32>,
88    /// 固定标志。
89    pub pinned: Vec<bool>,
90    /// 边(槽位对 + 权重)。
91    pub edges: Vec<(u32, u32, f32)>,
92}
93
94impl GraphPayload {
95    /// 从模型图构建槽位快照。节点按 ID 升序 → 槽位与遍历顺序稳定可复现。
96    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/// 一次布局状态快照:视图层每帧拷贝它渲染(方案 §4「每帧只拷贝坐标快照」)。
128#[derive(Clone, Debug)]
129pub struct LayoutSnapshot<P: Copy> {
130    /// 与 `GraphPayload.node_ids` 槽位一一对应。
131    pub positions: Arc<Vec<P>>,
132    pub iteration: u32,
133    pub alpha: f32,
134    pub cooled: bool,
135}
136
137/// 后台线程引擎所需的统一接口(`worker::LayoutWorker` 泛型驱动)。
138pub trait LayoutSim: Send + 'static {
139    type Pos: Copy + Send + Sync + 'static;
140
141    fn new(config: LayoutConfig) -> Self;
142    /// 全量重建(丢弃旧位置)。
143    fn rebuild(&mut self, payload: &GraphPayload);
144    /// 增量并入:保留已有节点位置,新节点放在邻居附近。
145    fn incremental(&mut self, payload: &GraphPayload);
146    fn set_pinned(&mut self, id: NodeId, pinned: bool);
147    /// 直接设置节点位置(拖动节点);同时清零速度。
148    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/// 单个仿真节点。
155#[derive(Clone, Debug)]
156struct SimPoint {
157    id: NodeId,
158    weight: f32,
159    pinned: bool,
160}
161
162/// 布局仿真公共骨架(维度无关的部分),2D / 3D 各自持有并复用。
163#[derive(Clone, Debug)]
164struct SimCore {
165    nodes: Vec<SimPoint>,
166    /// 边:槽位对 + 权重。
167    edges: Vec<(u32, u32, f32)>,
168    config: LayoutConfig,
169    rng: Rng,
170    iteration: u32,
171    /// 冷却系数(1.0 → min_alpha)。
172    alpha: f32,
173    cooled: bool,
174}
175
176impl SimCore {
177    /// 节点 id → 槽位(线性扫描;拖动是低频交互,不值得维护反查表)。
178    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    /// 交互回温沿用增量布局的 0.25 起点,并重置本轮迭代预算。
183    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    /// 全量重建:初始位置由种子决定(黄金角螺旋 + 抖动,确定性)。
203    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    /// 一步是否仍在活动(未冷却且未超上限)。
232    fn wants_steps(&self) -> bool {
233        !self.cooled && self.iteration < self.config.max_iterations
234    }
235}
236
237// ---------------------------------------------------------------------------
238// 2D
239// ---------------------------------------------------------------------------
240
241/// 2D 力导向布局(四叉树 Barnes–Hut)。
242pub struct ForceLayout2D {
243    core: SimCore,
244    positions: Vec<Vec2>,
245    velocities: Vec<Vec2>,
246    tree: BhTree<2>,
247    /// 每步的世界坐标点集(喂给 BH 树)。
248    scratch: Vec<[f32; 2]>,
249    /// BH 遍历栈(跨步复用,避免每节点分配)。
250    stack: Vec<i32>,
251}
252
253impl ForceLayout2D {
254    /// 便捷构造(`LayoutSim::new` 的固有形式,调用方无需 import trait)。
255    pub fn new(config: LayoutConfig) -> Self {
256        <Self as LayoutSim>::new(config)
257    }
258
259    /// 全量重建。见 [`LayoutSim::rebuild`]。
260    pub fn rebuild(&mut self, payload: &GraphPayload) {
261        <Self as LayoutSim>::rebuild(self, payload)
262    }
263
264    /// 增量并入。见 [`LayoutSim::incremental`]。
265    pub fn incremental(&mut self, payload: &GraphPayload) {
266        <Self as LayoutSim>::incremental(self, payload)
267    }
268
269    /// 一步迭代。见 [`LayoutSim::step`]。
270    pub fn step(&mut self) {
271        <Self as LayoutSim>::step(self)
272    }
273
274    /// 是否已冷却。见 [`LayoutSim::is_cooled`]。
275    pub fn is_cooled(&self) -> bool {
276        <Self as LayoutSim>::is_cooled(self)
277    }
278
279    /// 状态快照。见 [`LayoutSim::snapshot`]。
280    pub fn snapshot(&self) -> LayoutSnapshot<Vec2> {
281        <Self as LayoutSim>::snapshot(self)
282    }
283
284    /// 固定 / 解除固定节点。见 [`LayoutSim::set_pinned`]。
285    pub fn set_pinned(&mut self, id: NodeId, pinned: bool) {
286        <Self as LayoutSim>::set_pinned(self, id, pinned)
287    }
288
289    /// 便捷形式(拖动节点),调用方无需 import [`LayoutSim`]。
290    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        // 黄金角螺旋:均匀铺开 + 确定性抖动,避免初始重叠。
296        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        // 旧槽位 → 旧位置;把新 payload 的槽位对齐到现有仿真槽位。
376        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        // 未变化的节点位置不动;新节点稍后补。
384        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                    // 首个邻居附近落点(确定性抖动)。
398                    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); // 增量后小幅回温,只局部调整
441        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        // 重建 BH 树(复用分配)。
458        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            // 排斥(Barnes–Hut)。
470            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            // 向心重力。
480            forces[i][0] += (0.0 - point[0]) * cfg.gravity;
481            forces[i][1] += (0.0 - point[1]) * cfg.gravity;
482        }
483        // 弹簧吸引(胡克:F = stiffness · weight · d)。
484        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    /// 当前槽位坐标(与 `GraphPayload.node_ids` 对齐)。
521    pub fn positions(&self) -> &[Vec2] {
522        &self.positions
523    }
524
525    /// 当前迭代步数。
526    pub fn iteration(&self) -> u32 {
527        self.core.iteration
528    }
529}
530
531// ---------------------------------------------------------------------------
532// 3D
533// ---------------------------------------------------------------------------
534
535/// 3D 力导向布局(八叉树 Barnes–Hut),CPU 投影视图(G5)的数据源。
536pub 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    /// 便捷构造(`LayoutSim::new` 的固有形式,调用方无需 import trait)。
547    pub fn new(config: LayoutConfig) -> Self {
548        <Self as LayoutSim>::new(config)
549    }
550
551    /// 全量重建。见 [`LayoutSim::rebuild`]。
552    pub fn rebuild(&mut self, payload: &GraphPayload) {
553        <Self as LayoutSim>::rebuild(self, payload)
554    }
555
556    /// 增量并入。见 [`LayoutSim::incremental`]。
557    pub fn incremental(&mut self, payload: &GraphPayload) {
558        <Self as LayoutSim>::incremental(self, payload)
559    }
560
561    /// 一步迭代。见 [`LayoutSim::step`]。
562    pub fn step(&mut self) {
563        <Self as LayoutSim>::step(self)
564    }
565
566    /// 是否已冷却。见 [`LayoutSim::is_cooled`]。
567    pub fn is_cooled(&self) -> bool {
568        <Self as LayoutSim>::is_cooled(self)
569    }
570
571    /// 状态快照。见 [`LayoutSim::snapshot`]。
572    pub fn snapshot(&self) -> LayoutSnapshot<Vec3> {
573        <Self as LayoutSim>::snapshot(self)
574    }
575
576    /// 固定 / 解除固定节点。见 [`LayoutSim::set_pinned`]。
577    pub fn set_pinned(&mut self, id: NodeId, pinned: bool) {
578        <Self as LayoutSim>::set_pinned(self, id, pinned)
579    }
580
581    /// 便捷形式(拖动节点),调用方无需 import [`LayoutSim`]。
582    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        // 与 2D 相同的槽位对齐逻辑(维度差异只在坐标类型)。
637        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        // 积分(与 2D 相同的冷却收敛判据)。
764        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}