1#[cfg(test)]
32mod tests;
33
34pub const NODE_WIDTH: f64 = 180.0;
36pub const NODE_HEIGHT: f64 = 44.0;
38const GAP: f64 = 32.0;
40const DUMMY_GAP: f64 = 16.0;
42const LAYER_GAP: f64 = 56.0;
44pub const MARGIN: f64 = 16.0;
46const SWEEPS: usize = 12;
48const PLACEMENTS: usize = 8;
50pub const GROUP_PAD: f64 = 10.0;
52pub const GROUP_LABEL: f64 = 22.0;
54const SEPARATIONS: usize = 24;
56
57#[derive(Debug, Clone, Copy, PartialEq, Eq)]
59pub struct GroupSpec {
60 pub parent: Option<usize>,
62}
63
64#[derive(Debug, Clone, Copy, PartialEq)]
66pub struct GroupBox {
67 pub group: usize,
69 pub left: f64,
71 pub top: f64,
73 pub width: f64,
75 pub height: f64,
77 pub depth: usize,
79}
80
81#[derive(Debug, Clone, Copy, PartialEq)]
83pub struct Placed {
84 pub x: f64,
86 pub y: f64,
88 pub layer: usize,
90}
91
92#[derive(Debug, Clone, PartialEq)]
97pub struct Route {
98 pub edge: usize,
100 pub from: usize,
102 pub to: usize,
104 pub points: Vec<(f64, f64)>,
106}
107
108#[derive(Debug, Clone, PartialEq)]
110pub struct Layout {
111 pub nodes: Vec<Placed>,
113 pub routes: Vec<Route>,
116 pub boxes: Vec<GroupBox>,
118 pub side: Option<SideBox>,
120 pub width: f64,
122 pub height: f64,
124}
125
126#[derive(Debug, Clone, Copy, PartialEq)]
128pub struct SideBox {
129 pub left: f64,
131 pub top: f64,
133 pub width: f64,
135 pub height: f64,
137}
138
139const TRACK: f64 = 6.0;
141
142#[derive(Debug, Clone, Copy, PartialEq, Eq)]
144enum Item {
145 Node(usize),
146 Dummy,
147}
148
149impl Item {
150 const fn width(self) -> f64 {
151 match self {
152 Self::Node(_) => NODE_WIDTH,
153 Self::Dummy => 0.0,
154 }
155 }
156}
157
158struct Layered {
160 items: Vec<Item>,
161 paths: Vec<Vec<usize>>,
163 layer_of: Vec<usize>,
164 layers: Vec<Vec<usize>>,
166 up: Vec<Vec<usize>>,
168 down: Vec<Vec<usize>>,
169 chains: Vec<(usize, Vec<usize>)>,
171}
172
173#[must_use]
175pub fn layout(count: usize, edges: &[(usize, usize)]) -> Layout {
176 layout_grouped(count, edges, &[], &vec![None; count])
177}
178
179#[must_use]
182pub fn layout_grouped(
183 count: usize,
184 edges: &[(usize, usize)],
185 groups: &[GroupSpec],
186 node_group: &[Option<usize>],
187) -> Layout {
188 layout_sided(count, edges, groups, node_group, &[])
189}
190
191#[must_use]
194pub fn layout_sided(
195 count: usize,
196 edges: &[(usize, usize)],
197 groups: &[GroupSpec],
198 node_group: &[Option<usize>],
199 sides: &[(usize, usize)],
200) -> Layout {
201 let layer = layers(count, edges);
202 let lanes = side_lanes(count, sides, &layer);
203 let aside = |n: usize| lanes.get(n).copied().flatten();
204 let paths: Vec<Vec<usize>> = (0..count)
205 .map(|n| {
206 if aside(n).is_some() {
207 Vec::new()
208 } else {
209 group_path(groups, node_group.get(n).copied().flatten())
210 }
211 })
212 .collect();
213 let deepest = paths.iter().map(Vec::len).max().unwrap_or(0);
214 let layer_gap = LAYER_GAP + to_f64(deepest.saturating_sub(1)) * (GROUP_PAD + GROUP_LABEL);
216 let bands = deepest.max(usize::from(lanes.iter().any(Option::is_some)));
218 let top = MARGIN + to_f64(bands) * GROUP_LABEL;
219 let mut graph = layered(count, &task_edges(count, edges, &lanes), &layer, paths);
220 for row in &mut graph.layers {
221 row.retain(|&i| i >= count || aside(i).is_none());
222 }
223 let in_tasks = |i: usize| i >= count || aside(i).is_none();
224 for l in 0..graph.layers.len() {
225 let keys: Vec<f64> = (0..graph.layers[l].len()).map(to_f64).collect();
226 arrange(&mut graph, l, &keys);
227 }
228 reduce_crossings(&mut graph);
229 let mut x = place(&graph);
230 separate(&graph, groups, &mut x);
231 let y = |l: usize| top + NODE_HEIGHT / 2.0 + to_f64(l) * (NODE_HEIGHT + layer_gap);
232 let mut boxes = group_boxes(&graph, groups, &x, &y);
233 squeeze(&graph, &mut x, &mut boxes);
234 let left = boxes
236 .iter()
237 .map(|b| b.left)
238 .chain(
239 graph
240 .items
241 .iter()
242 .enumerate()
243 .filter(|(i, _)| in_tasks(*i))
244 .map(|(i, item)| x[i] - item.width() / 2.0),
245 )
246 .fold(f64::INFINITY, f64::min);
247 let side = SideFrame::of(&lanes);
248 if left.is_finite() {
249 let shift = side.tasks_left() - left;
250 for value in &mut x {
251 *value += shift;
252 }
253 for group_box in &mut boxes {
254 group_box.left += shift;
255 }
256 }
257 let nodes = (0..count)
258 .map(|n| Placed {
259 x: aside(n).map_or(x[n], |(lane, _)| SideFrame::lane_x(lane)),
260 y: y(layer[n]),
261 layer: layer[n],
262 })
263 .collect::<Vec<_>>();
264 let mut routes = chain_routes(&graph, &x, &y);
265 routes.extend(side_routes(edges, &nodes, &lanes, &side, layer_gap));
266 routes.sort_by_key(|route| route.edge);
267 let side_box = side.frame(&nodes, &lanes);
268 let right = graph
269 .items
270 .iter()
271 .enumerate()
272 .filter(|(i, _)| in_tasks(*i))
273 .map(|(i, item)| x[i] + item.width() / 2.0)
274 .chain(boxes.iter().map(|b| b.left + b.width))
275 .chain(side_box.map(|b| b.left + b.width))
276 .fold(0.0_f64, f64::max);
277 let bottom = boxes
278 .iter()
279 .map(|b| b.top + b.height)
280 .chain(side_box.map(|b| b.top + b.height))
281 .fold(0.0_f64, f64::max);
282 let depth = layer.iter().copied().max().map_or(0, |l| l + 1);
283 Layout {
284 nodes,
285 routes,
286 boxes,
287 side: side_box,
288 width: right + MARGIN,
289 height: if depth == 0 {
290 2.0 * MARGIN
291 } else {
292 (y(depth - 1) + NODE_HEIGHT / 2.0).max(bottom) + MARGIN
293 },
294 }
295}
296
297fn task_edges(
300 count: usize,
301 edges: &[(usize, usize)],
302 lanes: &[Option<(usize, usize)>],
303) -> Vec<(usize, usize)> {
304 let aside = |n: usize| lanes.get(n).copied().flatten().is_some();
305 edges
306 .iter()
307 .map(|&(f, t)| {
308 if aside(f) || aside(t) {
309 (count, count)
310 } else {
311 (f, t)
312 }
313 })
314 .collect()
315}
316
317fn chain_routes(graph: &Layered, x: &[f64], y: &impl Fn(usize) -> f64) -> Vec<Route> {
319 graph
320 .chains
321 .iter()
322 .map(|(edge, chain)| {
323 let (from, to) = (chain[0], chain[chain.len() - 1]);
324 let mut points = vec![(x[from], y(graph.layer_of[from]) + NODE_HEIGHT / 2.0)];
325 for &i in &chain[1..chain.len() - 1] {
326 let middle = y(graph.layer_of[i]);
327 points.push((x[i], middle - NODE_HEIGHT / 2.0));
328 points.push((x[i], middle + NODE_HEIGHT / 2.0));
329 }
330 points.push((x[to], y(graph.layer_of[to]) - NODE_HEIGHT / 2.0));
331 Route {
332 edge: *edge,
333 from,
334 to,
335 points,
336 }
337 })
338 .collect()
339}
340
341fn side_lanes(
344 count: usize,
345 sides: &[(usize, usize)],
346 layer: &[usize],
347) -> Vec<Option<(usize, usize)>> {
348 let mut lanes = vec![None; count];
349 let mut ends: Vec<usize> = Vec::new();
351 let mut order: Vec<usize> = (0..sides.len())
352 .filter(|&r| sides[r].0 < count && sides[r].1 < count && sides[r].0 != sides[r].1)
353 .collect();
354 order.sort_by_key(|&r| (layer[sides[r].0], r));
355 for (resource, r) in order.into_iter().enumerate() {
356 let (setup, cleanup) = sides[r];
357 if lanes[setup].is_some() || lanes[cleanup].is_some() {
358 continue; }
360 let (first, last) = (
361 layer[setup].min(layer[cleanup]),
362 layer[setup].max(layer[cleanup]),
363 );
364 let lane = ends
365 .iter()
366 .position(|&end| end < first)
367 .unwrap_or(ends.len());
368 if lane == ends.len() {
369 ends.push(last);
370 } else {
371 ends[lane] = last;
372 }
373 lanes[setup] = Some((lane, resource));
374 lanes[cleanup] = Some((lane, resource));
375 }
376 lanes
377}
378
379fn side_routes(
383 edges: &[(usize, usize)],
384 nodes: &[Placed],
385 lanes: &[Option<(usize, usize)>],
386 side: &SideFrame,
387 layer_gap: f64,
388) -> Vec<Route> {
389 let aside = |n: usize| lanes.get(n).copied().flatten();
390 let edge_y = NODE_HEIGHT / 2.0 + layer_gap / 2.0;
391 let mut routes = Vec::new();
392 for (edge, &(from, to)) in edges.iter().enumerate() {
393 let (Some(a), Some(b)) = (nodes.get(from), nodes.get(to)) else {
394 continue;
395 };
396 if a.layer >= b.layer {
397 continue;
398 }
399 let (start, end) = (aside(from), aside(to));
400 let track = match (start, end) {
401 (Some((_, resource)), _) => 2 * resource,
402 (None, Some((_, resource))) => 2 * resource + 1,
403 (None, None) => continue,
404 };
405 let (top, bottom) = (b.y - NODE_HEIGHT / 2.0, a.y + NODE_HEIGHT / 2.0);
406 let own = matches!((start, end), (Some((_, r)), Some((_, s))) if r == s);
408 let points = if own {
409 vec![(a.x, bottom), (b.x, top)]
410 } else {
411 let (below, above, cx) = (a.y + edge_y, b.y - edge_y, side.track_x(track));
414 vec![
415 (a.x, bottom),
416 (a.x, below),
417 (cx, below),
418 (cx, above),
419 (b.x, above),
420 (b.x, top),
421 ]
422 };
423 routes.push(Route {
424 edge,
425 from,
426 to,
427 points,
428 });
429 }
430 routes
431}
432
433struct SideFrame {
436 lanes: usize,
437 resources: usize,
438}
439
440impl SideFrame {
441 fn of(lanes: &[Option<(usize, usize)>]) -> Self {
442 let most = |pick: fn(&(usize, usize)) -> usize| {
443 lanes.iter().flatten().map(pick).max().map_or(0, |m| m + 1)
444 };
445 Self {
446 lanes: most(|p| p.0),
447 resources: most(|p| p.1),
448 }
449 }
450
451 fn right(&self) -> f64 {
453 MARGIN
454 + 2.0 * GROUP_PAD
455 + to_f64(self.lanes) * NODE_WIDTH
456 + to_f64(self.lanes.saturating_sub(1)) * GAP
457 }
458
459 fn lane_x(lane: usize) -> f64 {
460 MARGIN + GROUP_PAD + NODE_WIDTH / 2.0 + to_f64(lane) * (NODE_WIDTH + GAP)
461 }
462
463 fn track_x(&self, track: usize) -> f64 {
464 self.right() + TRACK * to_f64(track + 1)
465 }
466
467 fn tasks_left(&self) -> f64 {
469 if self.lanes == 0 {
470 MARGIN
471 } else {
472 self.track_x(2 * self.resources) + GAP
473 }
474 }
475
476 fn frame(&self, nodes: &[Placed], lanes: &[Option<(usize, usize)>]) -> Option<SideBox> {
478 let ys = || {
479 nodes
480 .iter()
481 .zip(lanes)
482 .filter(|(_, lane)| lane.is_some())
483 .map(|(n, _)| n.y)
484 };
485 let first = ys().fold(f64::INFINITY, f64::min);
486 let last = ys().fold(f64::NEG_INFINITY, f64::max);
487 if self.lanes == 0 || !first.is_finite() {
488 return None;
489 }
490 let top = first - NODE_HEIGHT / 2.0 - GROUP_PAD - GROUP_LABEL;
491 Some(SideBox {
492 left: MARGIN,
493 top,
494 width: self.right() - MARGIN,
495 height: last + NODE_HEIGHT / 2.0 + GROUP_PAD - top,
496 })
497 }
498}
499
500fn group_path(groups: &[GroupSpec], innermost: Option<usize>) -> Vec<usize> {
502 let mut path = Vec::new();
503 let mut at = innermost.filter(|&g| g < groups.len());
504 while let Some(g) = at {
505 if path.contains(&g) || path.len() > groups.len() {
506 break; }
508 path.push(g);
509 at = groups[g].parent.filter(|&p| p < groups.len());
510 }
511 path.reverse();
512 path
513}
514
515pub(crate) fn layers(count: usize, edges: &[(usize, usize)]) -> Vec<usize> {
518 let mut upstream = vec![0_usize; count];
519 let mut downstream = vec![Vec::new(); count];
520 for &(from, to) in edges
521 .iter()
522 .filter(|(f, t)| f != t && *f < count && *t < count)
523 {
524 upstream[to] += 1;
525 downstream[from].push(to);
526 }
527 let mut layer = vec![0_usize; count];
528 let mut done = vec![false; count];
529 let mut ready: Vec<usize> = (0..count).filter(|&n| upstream[n] == 0).collect();
530 while let Some(n) = ready.pop() {
531 done[n] = true;
532 for &d in &downstream[n] {
533 layer[d] = layer[d].max(layer[n] + 1);
534 upstream[d] -= 1;
535 if upstream[d] == 0 {
536 ready.push(d);
537 }
538 }
539 }
540 let below = layer.iter().copied().max().unwrap_or(0) + 1;
541 for n in (0..count).filter(|&n| !done[n]) {
542 layer[n] = below;
543 }
544 layer
545}
546
547fn layered(
548 count: usize,
549 edges: &[(usize, usize)],
550 layer: &[usize],
551 mut paths: Vec<Vec<usize>>,
552) -> Layered {
553 let mut items: Vec<Item> = (0..count).map(Item::Node).collect();
554 let mut layer_of = layer.to_vec();
555 let mut chains = Vec::new();
556 for (edge, &(from, to)) in edges.iter().enumerate() {
557 if from >= count || to >= count || layer[from] >= layer[to] {
558 continue;
559 }
560 let shared: Vec<usize> = paths[from]
562 .iter()
563 .zip(&paths[to])
564 .take_while(|(a, b)| a == b)
565 .map(|(a, _)| *a)
566 .collect();
567 let mut chain = vec![from];
568 for l in layer[from] + 1..layer[to] {
569 items.push(Item::Dummy);
570 layer_of.push(l);
571 paths.push(shared.clone());
572 chain.push(items.len() - 1);
573 }
574 chain.push(to);
575 chains.push((edge, chain));
576 }
577 let depth = layer_of.iter().copied().max().map_or(0, |l| l + 1);
578 let mut layers = vec![Vec::new(); depth];
579 for (i, &l) in layer_of.iter().enumerate() {
580 layers[l].push(i);
581 }
582 let mut up = vec![Vec::new(); items.len()];
583 let mut down = vec![Vec::new(); items.len()];
584 for (_, chain) in &chains {
585 for pair in chain.windows(2) {
586 down[pair[0]].push(pair[1]);
587 up[pair[1]].push(pair[0]);
588 }
589 }
590 Layered {
591 items,
592 paths,
593 layer_of,
594 layers,
595 up,
596 down,
597 chains,
598 }
599}
600
601fn reduce_crossings(graph: &mut Layered) {
603 let mut best = graph.layers.clone();
604 let mut fewest = crossings(graph);
605 for _ in 0..SWEEPS {
606 for l in 1..graph.layers.len() {
607 reorder(graph, l, true);
608 }
609 for l in (0..graph.layers.len().saturating_sub(1)).rev() {
610 reorder(graph, l, false);
611 }
612 let now = crossings(graph);
613 if now < fewest {
614 fewest = now;
615 best.clone_from(&graph.layers);
616 }
617 if fewest == 0 {
618 break;
619 }
620 }
621 graph.layers = best;
622}
623
624fn reorder(graph: &mut Layered, l: usize, by_up: bool) {
627 let position = positions(graph);
628 let keys: Vec<(f64, usize)> = graph.layers[l]
629 .iter()
630 .enumerate()
631 .map(|(place, &i)| {
632 let near = if by_up { &graph.up[i] } else { &graph.down[i] };
633 let key = if near.is_empty() {
634 to_f64(place)
635 } else {
636 near.iter().map(|&n| to_f64(position[n])).sum::<f64>() / to_f64(near.len())
637 };
638 (key, i)
639 })
640 .collect();
641 let mut wanted = vec![0.0; graph.items.len()];
642 for (key, i) in &keys {
643 wanted[*i] = *key;
644 }
645 let keys: Vec<f64> = graph.layers[l].iter().map(|&i| wanted[i]).collect();
646 arrange(graph, l, &keys);
647}
648
649fn arrange(graph: &mut Layered, l: usize, keys: &[f64]) {
653 let members: Vec<(usize, f64)> = graph.layers[l]
654 .iter()
655 .copied()
656 .zip(keys.iter().copied())
657 .collect();
658 graph.layers[l] = arrange_level(&graph.paths, &members, 0);
659}
660
661type Unit = (f64, usize, Option<usize>, Vec<(usize, f64)>);
664
665fn arrange_level(paths: &[Vec<usize>], members: &[(usize, f64)], depth: usize) -> Vec<usize> {
666 let mut units: Vec<Unit> = Vec::new();
668 for (place, &(item, key)) in members.iter().enumerate() {
669 match paths[item].get(depth) {
670 None => units.push((key, place, None, vec![(item, key)])),
671 Some(&group) => match units.iter_mut().find(|u| u.2 == Some(group)) {
672 Some(unit) => unit.3.push((item, key)),
673 None => units.push((key, place, Some(group), vec![(item, key)])),
674 },
675 }
676 }
677 for unit in &mut units {
678 if unit.2.is_some() {
679 unit.0 = unit.3.iter().map(|(_, k)| k).sum::<f64>() / to_f64(unit.3.len());
680 }
681 }
682 let mut grouped: Vec<usize> = (0..units.len()).filter(|&u| units[u].2.is_some()).collect();
686 grouped.sort_by_key(|&u| units[u].2);
687 let mut floor = f64::NEG_INFINITY;
688 for &u in &grouped {
689 floor = floor.max(units[u].0);
690 units[u].0 = floor;
691 }
692 units.sort_by(|a, b| {
693 a.0.total_cmp(&b.0).then_with(|| match (a.2, b.2) {
694 (Some(x), Some(y)) => x.cmp(&y),
695 _ => a.1.cmp(&b.1),
696 })
697 });
698 units
699 .into_iter()
700 .flat_map(|(_, _, group, inside)| match group {
701 None => inside.into_iter().map(|(i, _)| i).collect::<Vec<_>>(),
702 Some(_) => arrange_level(paths, &inside, depth + 1),
703 })
704 .collect()
705}
706
707fn positions(graph: &Layered) -> Vec<usize> {
709 let mut position = vec![0; graph.items.len()];
710 for layer in &graph.layers {
711 for (place, &i) in layer.iter().enumerate() {
712 position[i] = place;
713 }
714 }
715 position
716}
717
718fn crossings(graph: &Layered) -> usize {
720 let position = positions(graph);
721 let mut total = 0;
722 for layer in &graph.layers {
723 let edges: Vec<(usize, usize)> = layer
724 .iter()
725 .flat_map(|&i| graph.down[i].iter().map(move |&d| (i, d)))
726 .map(|(a, b)| (position[a], position[b]))
727 .collect();
728 for (k, a) in edges.iter().enumerate() {
729 total += edges[k + 1..]
730 .iter()
731 .filter(|b| (a.0 < b.0 && a.1 > b.1) || (a.0 > b.0 && a.1 < b.1))
732 .count();
733 }
734 }
735 total
736}
737
738fn place(graph: &Layered) -> Vec<f64> {
740 let mut x = vec![0.0; graph.items.len()];
741 for layer in &graph.layers {
742 let mut at = 0.0;
743 for &i in layer {
744 x[i] = at + graph.items[i].width() / 2.0;
745 at += graph.items[i].width() + gap(graph.items[i]);
746 }
747 }
748 for _ in 0..PLACEMENTS {
749 for l in 1..graph.layers.len() {
750 fit(graph, l, &graph.up, &mut x);
751 }
752 for l in (0..graph.layers.len().saturating_sub(1)).rev() {
753 fit(graph, l, &graph.down, &mut x);
754 }
755 }
756 x
757}
758
759fn separate(graph: &Layered, groups: &[GroupSpec], x: &mut [f64]) {
770 let paths: Vec<Vec<usize>> = (0..groups.len())
771 .map(|g| group_path(groups, Some(g)))
772 .collect();
773 for _ in 0..SEPARATIONS * groups.len() {
774 align_groups(graph, groups, x);
775 let mut moved = false;
776 for (g, path) in paths.iter().enumerate() {
777 moved |= clear(graph, g, path, x);
778 }
779 if !moved {
780 break;
781 }
782 }
783}
784
785fn align_groups(graph: &Layered, groups: &[GroupSpec], x: &mut [f64]) {
788 let mut order: Vec<(Vec<usize>, usize)> = (0..groups.len())
789 .map(|g| (group_path(groups, Some(g)), g))
790 .collect();
791 order.sort_by(|a, b| a.0.cmp(&b.0));
792 for (_, g) in order {
793 align_group(graph, g, x);
794 }
795}
796
797fn align_group(graph: &Layered, g: usize, x: &mut [f64]) {
801 let mut bands: Vec<(usize, usize, f64)> = Vec::new();
803 for (layer_index, layer) in graph.layers.iter().enumerate() {
804 let Some(at) = layer.iter().position(|&i| graph.paths[i].contains(&g)) else {
805 continue;
806 };
807 let holds_nested = layer[at..].iter().any(|&other| {
808 let path = &graph.paths[other];
809 path.contains(&g) && path.last() != Some(&g)
810 });
811 if holds_nested {
812 continue;
813 }
814 let item = layer[at];
815 let left = x[item] - graph.items[item].width() / 2.0;
816 bands.push((layer_index, at, left));
817 }
818 let Some(target) = bands.iter().map(|&(_, _, left)| left).reduce(f64::max) else {
819 return;
820 };
821 for (layer_index, at, left) in bands {
822 let by = target - left;
823 if by <= 1e-9 {
824 continue;
825 }
826 shift_from(&graph.layers[layer_index], at, by, x);
827 }
828}
829
830fn belongs_left(item: &[usize], group: &[usize]) -> bool {
833 item.iter()
834 .zip(group)
835 .find(|(a, b)| a != b)
836 .is_some_and(|(a, b)| a < b)
837}
838
839fn clear(graph: &Layered, g: usize, path: &[usize], x: &mut [f64]) -> bool {
841 let inside = |i: usize| graph.paths[i].contains(&g);
842 let mut moved = false;
843 for layer in &graph.layers {
844 let Some((left, right, first, last)) = group_spans_of(graph, g, x) else {
846 return moved;
847 };
848 let Some(&head) = layer.first() else {
849 continue;
850 };
851 if !(first..=last).contains(&graph.layer_of[head]) {
852 continue;
853 }
854 let block = layer.iter().position(|&i| inside(i));
855 if let Some(start) = block
856 && start > 0
857 {
858 let before = layer[start - 1];
859 let reach = x[before] + graph.items[before].width() / 2.0 + gap(graph.items[before]);
860 if reach > left + 1e-9 {
861 shift_group(graph, g, reach - left, x);
862 moved = true;
863 continue;
864 }
865 }
866 let split = block.unwrap_or_else(|| {
869 layer
870 .iter()
871 .rposition(|&i| belongs_left(&graph.paths[i], path))
872 .map_or(0, |k| k + 1)
873 });
874 if block.is_none() && split > 0 {
875 let reach = layer[..split]
876 .iter()
877 .map(|&i| x[i] + graph.items[i].width() / 2.0 + gap(graph.items[i]))
878 .fold(f64::NEG_INFINITY, f64::max);
879 if reach > left + 1e-9 {
880 shift_group(graph, g, reach - left, x);
882 moved = true;
883 continue;
884 }
885 }
886 let outside = layer.iter().enumerate().skip(split).find(|&(_, &i)| {
887 !inside(i)
888 && x[i] + graph.items[i].width() / 2.0 > left + 1e-9
889 && x[i] - graph.items[i].width() / 2.0 < right - 1e-9
890 });
891 if let Some((k, &i)) = outside {
892 let wanted = right + gap(graph.items[i]).min(GAP);
893 let edge = x[i] - graph.items[i].width() / 2.0;
894 let by = wanted - edge;
895 if by > 1e-9 {
896 shift_out(graph, layer, k, path, by, x);
897 moved = true;
898 }
899 }
900 }
901 moved
902}
903
904fn squeeze(graph: &Layered, x: &mut [f64], boxes: &mut [GroupBox]) {
909 let mut taken: Vec<(f64, f64)> = graph
911 .items
912 .iter()
913 .enumerate()
914 .map(|(i, item)| (x[i] - item.width() / 2.0, x[i] + item.width() / 2.0))
915 .chain(boxes.iter().flat_map(|b| {
916 let right = b.left + b.width;
917 [(b.left, b.left), (right, right)]
918 }))
919 .collect();
920 taken.sort_by(|a, b| a.0.total_cmp(&b.0));
921 let mut cuts: Vec<(f64, f64)> = Vec::new();
923 let mut reach = f64::NEG_INFINITY;
924 for (start, end) in taken {
925 if reach.is_finite() && start - reach > GAP + 1e-9 {
926 cuts.push((reach, start - reach - GAP));
927 }
928 reach = reach.max(end);
929 }
930 if cuts.is_empty() {
931 return;
932 }
933 let moved = |at: f64| {
934 at - cuts
935 .iter()
936 .filter(|&&(from, _)| from < at - 1e-9)
937 .map(|&(_, by)| by)
938 .sum::<f64>()
939 };
940 for value in x.iter_mut() {
941 *value = moved(*value);
942 }
943 for group_box in boxes.iter_mut() {
944 let right = moved(group_box.left + group_box.width);
945 group_box.left = moved(group_box.left);
946 group_box.width = right - group_box.left;
947 }
948}
949
950fn shift_from(layer: &[usize], k: usize, by: f64, x: &mut [f64]) {
952 for &i in &layer[k..] {
953 x[i] += by;
954 }
955}
956
957fn shift_group(graph: &Layered, g: usize, by: f64, x: &mut [f64]) {
960 let ancestors = graph
961 .paths
962 .iter()
963 .find_map(|path| {
964 path.iter()
965 .position(|&at| at == g)
966 .map(|at| path[..at].to_vec())
967 })
968 .unwrap_or_default();
969 shift_closure(graph, &[g], &[], &ancestors, by, x);
970}
971
972fn shift_out(
975 graph: &Layered,
976 layer: &[usize],
977 k: usize,
978 cleared: &[usize],
979 by: f64,
980 x: &mut [f64],
981) {
982 let mut start = Vec::new();
983 let mut bare = Vec::new();
984 for &item in &layer[k..] {
985 match graph.paths[item].iter().find(|&&h| !cleared.contains(&h)) {
986 Some(&group) => {
987 if !start.contains(&group) {
988 start.push(group);
989 }
990 }
991 None => bare.push(item),
992 }
993 }
994 shift_closure(graph, &start, &bare, cleared, by, x);
995}
996
997fn shift_closure(
1000 graph: &Layered,
1001 start: &[usize],
1002 bare: &[usize],
1003 blocked: &[usize],
1004 by: f64,
1005 x: &mut [f64],
1006) {
1007 if by <= 1e-9 {
1008 return;
1009 }
1010 let group_count = graph
1011 .paths
1012 .iter()
1013 .flat_map(|path| path.iter().copied())
1014 .max()
1015 .map_or(0, |group| group + 1);
1016 let mut taken = vec![false; group_count];
1017 let mut queued = vec![false; group_count];
1018 let mut moved = vec![false; graph.items.len()];
1019 let mut queue = Vec::new();
1020 for &group in start {
1021 if group < group_count && !queued[group] {
1022 queued[group] = true;
1023 queue.push(group);
1024 }
1025 }
1026 for &item in bare {
1027 moved[item] = true;
1028 }
1029 while let Some(group) = queue.pop() {
1030 if taken[group] {
1031 continue;
1032 }
1033 taken[group] = true;
1034 for layer in &graph.layers {
1035 let Some(at) = layer
1036 .iter()
1037 .position(|&item| graph.paths[item].contains(&group))
1038 else {
1039 continue;
1040 };
1041 for &item in &layer[at..] {
1042 if moved[item] {
1043 continue;
1044 }
1045 moved[item] = true;
1046 take_group(
1047 graph,
1048 layer,
1049 item,
1050 blocked,
1051 &taken,
1052 &moved,
1053 &mut queued,
1054 &mut queue,
1055 );
1056 }
1057 }
1058 }
1059 for (item, moves) in moved.iter().enumerate() {
1060 if *moves {
1061 x[item] += by;
1062 }
1063 }
1064}
1065
1066#[expect(
1069 clippy::too_many_arguments,
1070 reason = "the closure's flags, each borrowed differently"
1071)]
1072fn take_group(
1073 graph: &Layered,
1074 layer: &[usize],
1075 item: usize,
1076 blocked: &[usize],
1077 taken: &[bool],
1078 moved: &[bool],
1079 queued: &mut [bool],
1080 queue: &mut Vec<usize>,
1081) {
1082 for &group in graph.paths[item].iter().rev() {
1083 if group >= taken.len() || taken[group] || blocked.contains(&group) {
1084 break;
1085 }
1086 let starts = layer
1087 .iter()
1088 .find(|&&other| graph.paths[other].contains(&group))
1089 .is_some_and(|&other| moved[other]);
1090 if !starts {
1091 continue;
1092 }
1093 if !queued[group] {
1094 queued[group] = true;
1095 queue.push(group);
1096 }
1097 break;
1098 }
1099}
1100
1101fn group_spans_of(graph: &Layered, group: usize, x: &[f64]) -> Option<(f64, f64, usize, usize)> {
1103 let mut span: Option<(f64, f64, usize, usize)> = None;
1104 for (item, path) in graph.paths.iter().enumerate() {
1105 let Some(depth) = path.iter().position(|&h| h == group) else {
1106 continue;
1107 };
1108 let half = graph.items[item].width() / 2.0;
1109 let pad = to_f64(path.len() - depth) * GROUP_PAD;
1110 let left = x[item] - half - pad;
1111 let right = x[item] + half + pad;
1112 let layer = graph.layer_of[item];
1113 span = Some(match span {
1114 None => (left, right, layer, layer),
1115 Some((lo, hi, first, last)) => (
1116 lo.min(left),
1117 hi.max(right),
1118 first.min(layer),
1119 last.max(layer),
1120 ),
1121 });
1122 }
1123 span
1124}
1125
1126fn group_spans(
1129 graph: &Layered,
1130 group_count: usize,
1131 x: &[f64],
1132) -> Vec<Option<(f64, f64, usize, usize)>> {
1133 (0..group_count)
1134 .map(|g| group_spans_of(graph, g, x))
1135 .collect()
1136}
1137
1138fn group_boxes(
1140 graph: &Layered,
1141 groups: &[GroupSpec],
1142 x: &[f64],
1143 y: &impl Fn(usize) -> f64,
1144) -> Vec<GroupBox> {
1145 let spans = group_spans(graph, groups.len(), x);
1146 let mut boxes: Vec<GroupBox> = Vec::new();
1147 for (g, span) in spans.iter().enumerate() {
1148 let Some((left, right, first, last)) = *span else {
1149 continue;
1150 };
1151 let depth = group_path(groups, Some(g)).len() - 1;
1152 let below = graph
1154 .paths
1155 .iter()
1156 .filter_map(|p| p.iter().position(|&h| h == g).map(|at| p.len() - at))
1157 .max()
1158 .unwrap_or(1);
1159 let top = y(first) - NODE_HEIGHT / 2.0 - to_f64(below) * GROUP_LABEL;
1160 let bottom = y(last) + NODE_HEIGHT / 2.0 + to_f64(below) * GROUP_PAD;
1161 boxes.push(GroupBox {
1162 group: g,
1163 left,
1164 top,
1165 width: right - left,
1166 height: bottom - top,
1167 depth,
1168 });
1169 }
1170 boxes.sort_by_key(|b| (b.depth, b.group));
1171 boxes
1172}
1173
1174const fn gap(item: Item) -> f64 {
1175 match item {
1176 Item::Node(_) => GAP,
1177 Item::Dummy => DUMMY_GAP,
1178 }
1179}
1180
1181fn fit(graph: &Layered, l: usize, near: &[Vec<usize>], x: &mut [f64]) {
1185 let layer = &graph.layers[l];
1186 let mut offset = Vec::with_capacity(layer.len());
1187 let mut at = 0.0;
1188 for (k, &i) in layer.iter().enumerate() {
1189 if k > 0 {
1190 let before = graph.items[layer[k - 1]];
1191 at += before.width() / 2.0 + gap(before) + graph.items[i].width() / 2.0;
1192 }
1193 offset.push(at);
1194 }
1195 let mut blocks: Vec<(f64, f64, usize)> = Vec::new();
1197 for (k, &i) in layer.iter().enumerate() {
1198 let wanted = if near[i].is_empty() {
1199 x[i]
1200 } else {
1201 near[i].iter().map(|&n| x[n]).sum::<f64>() / to_f64(near[i].len())
1202 };
1203 blocks.push((wanted - offset[k], 1.0, 1));
1204 while blocks.len() > 1 {
1205 let (sum, n, _) = blocks[blocks.len() - 1];
1206 let (before_sum, before_n, _) = blocks[blocks.len() - 2];
1207 if before_sum / before_n <= sum / n {
1208 break;
1209 }
1210 let last = blocks.pop().expect("two blocks");
1211 let previous = blocks.last_mut().expect("two blocks");
1212 previous.0 += last.0;
1213 previous.1 += last.1;
1214 previous.2 += last.2;
1215 }
1216 }
1217 let mut k = 0;
1218 for (sum, n, items) in blocks {
1219 for _ in 0..items {
1220 x[layer[k]] = offset[k] + sum / n;
1221 k += 1;
1222 }
1223 }
1224}
1225
1226fn to_f64(n: usize) -> f64 {
1227 f64::from(u32::try_from(n).unwrap_or(u32::MAX))
1228}