connector-routing 0.1.1

Connector routing for diagrams and schematics: many orthogonal connectors at once with bend, length and crossing costs, negotiated congestion, rip-up and reroute, and nudging
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
//! The [`Scene`]: obstacles, ports and their incrementally maintained orthogonal
//! visibility graph (Wybrow, Marriott and Stuckey 2009).
//!
//! The interesting points are the obstacle corners and the ports. Through every
//! interesting point outside all obstacle interiors runs a maximal obstacle-free
//! horizontal and vertical segment; the graph's vertices are the intersections of
//! these segments and its edges join consecutive intersections along a segment.
//!
//! ```mermaid
//! flowchart LR
//!     M[obstacle or port change] --> A[affected segments]
//!     A --> R[remove segments and their vertices]
//!     R --> U[apply the change]
//!     U --> G[recompute segments of affected generators]
//!     G --> I[insert segments, link intersections]
//! ```

mod segments;

use alloc::collections::BTreeMap;
use alloc::vec::Vec;

use crate::error::Error;
use crate::geom::{DirSet, Point, Rect};
use crate::graph::{RoutingGraph, VertexId};

use segments::Segments;

/// An obstacle of a [`Scene`]. Stable until the obstacle is removed; ids of removed
/// obstacles are reused.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ObstacleId(pub(crate) u32);

impl ObstacleId {
    /// The slot index.
    #[must_use]
    pub const fn index(self) -> usize {
        self.0 as usize
    }
}

/// A port of a [`Scene`]. Stable until the port is removed; ids of removed ports are
/// reused.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct PortId(pub(crate) u32);

impl PortId {
    /// The slot index.
    #[must_use]
    pub const fn index(self) -> usize {
        self.0 as usize
    }
}

/// A connection point: where connectors start or end, and in which directions.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Port {
    /// The position. Must not lie in the open interior of an obstacle.
    pub point: Point,
    /// The directions a connector may leave the port in. A connector ending here
    /// arrives moving opposite to one of them. Never empty.
    pub directions: DirSet,
}

impl Port {
    /// A port at `point` that may be left in any direction in `directions`.
    #[must_use]
    pub fn new(point: Point, directions: impl Into<DirSet>) -> Self {
        Self {
            point,
            directions: directions.into(),
        }
    }

    /// A port at `point` that may be left in any direction.
    #[must_use]
    pub fn free(point: Point) -> Self {
        Self::new(point, DirSet::ALL)
    }

    /// The interesting points the port adds to the visibility graph: its point, and for
    /// each allowed direction `d` the point one unit away in `d` and its two
    /// neighbours one unit to either side (its *stubs*).
    ///
    /// The stubs are not in Wybrow et al. (2009). Without them the graph can miss the
    /// optimum when a port direction forces a turn right next to the port: the first or
    /// last segment cannot shrink to nothing, so the segments after it need lines one
    /// unit away, ahead of the port and beside it (found by the brute-force comparison).
    pub fn interesting_points(&self) -> impl Iterator<Item = Point> + '_ {
        let p = self.point;
        core::iter::once(p).chain(self.directions.iter().flat_map(move |d| {
            let (dx, dy) = d.delta();
            let ahead = Point::new(p.x + dx, p.y + dy);
            [
                ahead,
                Point::new(ahead.x + dy, ahead.y + dx),
                Point::new(ahead.x - dy, ahead.y - dx),
            ]
        }))
    }
}

/// A slot arena with stable indices and reuse of freed slots.
#[derive(Debug, Clone)]
pub(crate) struct Arena<T> {
    /// The slots; `None` for freed ones.
    slots: Vec<Option<T>>,
    /// Freed slot indices.
    free: Vec<u32>,
}

impl<T> Default for Arena<T> {
    fn default() -> Self {
        Self {
            slots: Vec::new(),
            free: Vec::new(),
        }
    }
}

impl<T> Arena<T> {
    /// Stores `value` and returns its slot.
    fn insert(&mut self, value: T) -> u32 {
        if let Some(index) = self.free.pop() {
            self.slots[index as usize] = Some(value);
            return index;
        }

        self.slots.push(Some(value));

        u32::try_from(self.slots.len() - 1).expect("fewer than 2^32 slots")
    }

    /// Removes and returns the value in slot `index`.
    fn remove(&mut self, index: u32) -> Option<T> {
        let value = self.slots.get_mut(index as usize)?.take()?;
        self.free.push(index);

        Some(value)
    }

    /// The value in slot `index`.
    pub(crate) fn get(&self, index: u32) -> Option<&T> {
        self.slots.get(index as usize)?.as_ref()
    }

    /// The live values with their slots, in slot order.
    pub(crate) fn iter(&self) -> impl Iterator<Item = (u32, &T)> + '_ {
        self.slots.iter().enumerate().filter_map(|(i, slot)| {
            slot.as_ref()
                .map(|value| (u32::try_from(i).expect("fewer than 2^32 slots"), value))
        })
    }

    /// One more than the largest slot index ever used.
    pub(crate) fn capacity(&self) -> usize {
        self.slots.len()
    }
}

/// Obstacles, ports and their orthogonal visibility graph, updated incrementally.
///
/// # Examples
///
/// ```
/// use connector_routing::{DirSet, Point, Port, Rect, Scene};
///
/// let mut scene = Scene::new();
/// let box_a = scene.add_obstacle(Rect::new(0, 0, 10, 10))?;
/// let port = scene.add_port(Port::new(Point::new(10, 5), DirSet::RIGHT))?;
/// assert!(scene.port_vertex(port).is_some());
///
/// // Moving the box updates the graph in place.
/// scene.move_obstacle(box_a, Rect::new(0, 0, 10, 12))?;
/// assert_eq!(scene.obstacle(box_a), Some(Rect::new(0, 0, 10, 12)));
/// # Ok::<(), connector_routing::Error>(())
/// ```
#[derive(Debug, Clone, Default)]
pub struct Scene {
    /// The obstacles.
    obstacles: Arena<Rect>,
    /// The ports.
    ports: Arena<Port>,
    /// How many obstacle corners and ports sit at each interesting point.
    generators: BTreeMap<Point, u32>,
    /// The routing frame: the bounding box of the interesting points grown by one unit.
    /// Its corners are extra interesting points, so routes can leave the bounding box
    /// (a port on the outer side of the outermost obstacle must). `None` without
    /// interesting points.
    frame: Option<Rect>,
    /// The interesting segments and the visibility graph.
    segments: Segments,
}

impl Scene {
    /// Creates an empty scene.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Builds a scene from all obstacles and ports at once, faster than adding them one
    /// by one. Ids are assigned in input order.
    ///
    /// # Errors
    ///
    /// [`Error::CoordinateOutOfRange`] for a coordinate beyond
    /// [`MAX_COORD`](crate::MAX_COORD), [`Error::PortWithoutDirections`] for a port that
    /// allows no direction.
    pub fn build(
        obstacles: impl IntoIterator<Item = Rect>,
        ports: impl IntoIterator<Item = Port>,
    ) -> Result<Self, Error> {
        let mut scene = Self::new();
        for rect in obstacles {
            check_rect(&rect)?;
            scene.obstacles.insert(rect);
            for corner in rect.corners() {
                *scene.generators.entry(corner).or_default() += 1;
            }
        }

        for port in ports {
            check_port(&port)?;
            scene.ports.insert(port);
            for p in port.interesting_points() {
                *scene.generators.entry(p).or_default() += 1;
            }
        }

        let rects = scene.rects();
        scene.frame = frame_of(&scene.generators);
        let mut points: Vec<Point> = scene.generators.keys().copied().collect();
        points.extend(scene.frame.iter().flat_map(Rect::corners));
        scene.segments.build(&rects, &points);

        Ok(scene)
    }

    /// The routing graph: the orthogonal visibility graph of the scene.
    #[must_use]
    pub fn graph(&self) -> &RoutingGraph {
        self.segments.graph()
    }

    /// The obstacle `id`, if it exists.
    #[must_use]
    pub fn obstacle(&self, id: ObstacleId) -> Option<Rect> {
        self.obstacles.get(id.0).copied()
    }

    /// Every obstacle with its id, in id order.
    pub fn obstacles(&self) -> impl Iterator<Item = (ObstacleId, Rect)> + '_ {
        self.obstacles.iter().map(|(i, r)| (ObstacleId(i), *r))
    }

    /// One more than the largest obstacle index ever used.
    #[must_use]
    pub fn obstacle_capacity(&self) -> usize {
        self.obstacles.capacity()
    }

    /// The rectangles of all obstacles.
    #[must_use]
    pub fn rects(&self) -> Vec<Rect> {
        self.obstacles.iter().map(|(_, r)| *r).collect()
    }

    /// The port `id`, if it exists.
    #[must_use]
    pub fn port(&self, id: PortId) -> Option<Port> {
        self.ports.get(id.0).copied()
    }

    /// Every port with its id, in id order.
    pub fn ports(&self) -> impl Iterator<Item = (PortId, Port)> + '_ {
        self.ports.iter().map(|(i, p)| (PortId(i), *p))
    }

    /// The graph vertex of port `id`, or `None` if the port does not exist or lies
    /// inside an obstacle.
    #[must_use]
    pub fn port_vertex(&self, id: PortId) -> Option<VertexId> {
        self.graph().vertex_at(self.port(id)?.point)
    }

    /// Whether `p` lies in the open interior of some obstacle.
    #[must_use]
    pub fn is_blocked(&self, p: Point) -> bool {
        self.obstacles.iter().any(|(_, r)| r.interior_contains(p))
    }

    /// Adds an obstacle and updates the graph.
    ///
    /// # Errors
    ///
    /// [`Error::CoordinateOutOfRange`] for a coordinate beyond
    /// [`MAX_COORD`](crate::MAX_COORD).
    pub fn add_obstacle(&mut self, rect: Rect) -> Result<ObstacleId, Error> {
        check_rect(&rect)?;
        let mut id = ObstacleId(0);
        self.change(&[rect], |scene| {
            id = ObstacleId(scene.obstacles.insert(rect));
            scene.add_generators(&rect.corners());
        });

        Ok(id)
    }

    /// Removes an obstacle and updates the graph. Returns its rectangle.
    ///
    /// # Errors
    ///
    /// [`Error::UnknownObstacle`] if `id` names no obstacle.
    pub fn remove_obstacle(&mut self, id: ObstacleId) -> Result<Rect, Error> {
        let rect = self.obstacle(id).ok_or(Error::UnknownObstacle)?;
        self.change(&[rect], |scene| {
            scene.obstacles.remove(id.0);
            scene.remove_generators(&rect.corners());
        });

        Ok(rect)
    }

    /// Moves or resizes an obstacle and updates the graph.
    ///
    /// # Errors
    ///
    /// [`Error::UnknownObstacle`] if `id` names no obstacle,
    /// [`Error::CoordinateOutOfRange`] for a coordinate beyond
    /// [`MAX_COORD`](crate::MAX_COORD).
    pub fn move_obstacle(&mut self, id: ObstacleId, rect: Rect) -> Result<(), Error> {
        let old = self.obstacle(id).ok_or(Error::UnknownObstacle)?;
        check_rect(&rect)?;
        self.change(&[old, rect], |scene| {
            scene.obstacles.slots[id.index()] = Some(rect);
            scene.remove_generators(&old.corners());
            scene.add_generators(&rect.corners());
        });

        Ok(())
    }

    /// Adds a port and updates the graph.
    ///
    /// A port inside an obstacle is accepted (the obstacle may move away later) but has
    /// no vertex until then.
    ///
    /// # Errors
    ///
    /// [`Error::CoordinateOutOfRange`] for a coordinate beyond
    /// [`MAX_COORD`](crate::MAX_COORD), [`Error::PortWithoutDirections`] for a port that
    /// allows no direction.
    pub fn add_port(&mut self, port: Port) -> Result<PortId, Error> {
        check_port(&port)?;
        let id = PortId(self.ports.insert(port));
        for p in port.interesting_points() {
            self.add_point_generator(p);
        }

        Ok(id)
    }

    /// Removes a port and updates the graph. Returns it.
    ///
    /// # Errors
    ///
    /// [`Error::UnknownPort`] if `id` names no port.
    pub fn remove_port(&mut self, id: PortId) -> Result<Port, Error> {
        let port = self.ports.remove(id.0).ok_or(Error::UnknownPort)?;
        for p in port.interesting_points() {
            self.remove_point_generator(p);
        }

        Ok(port)
    }

    /// Applies an obstacle change whose old and new rectangles are `regions`.
    ///
    /// Removes the segments the regions affect, runs `apply`, and recomputes the
    /// segments of every generator that lost its segment.
    fn change(&mut self, regions: &[Rect], apply: impl FnOnce(&mut Self)) {
        let mut affected = self.segments.take_affected(regions);
        apply(self);
        affected.extend(
            self.generators
                .keys()
                .copied()
                .filter(|p| regions.iter().any(|r| r.contains(*p))),
        );

        let rects = self.rects();
        let frame: Vec<Point> = self.frame.iter().flat_map(Rect::corners).collect();
        affected.retain(|p| self.generators.contains_key(p) || frame.contains(p));
        affected.sort_unstable();
        affected.dedup();
        self.segments.restore(&rects, &affected);
        self.refresh_frame();
    }

    /// The routing frame: the bounding box of every obstacle corner and port, grown by
    /// one unit on each side. `None` for an empty scene.
    ///
    /// Its corners are interesting points of the graph. One unit suffices: clamping an
    /// optimal route into the frame never makes it longer or adds bends, and a route
    /// needs no line further out (checked against brute force).
    #[must_use]
    pub fn frame(&self) -> Option<Rect> {
        self.frame
    }

    /// Recomputes the routing frame and replaces its corner generators if it changed.
    fn refresh_frame(&mut self) {
        let frame = frame_of(&self.generators);
        if frame == self.frame {
            return;
        }

        // An old corner can have become a real interesting point when the box grew.
        for corner in self.frame.iter().flat_map(Rect::corners) {
            if !self.generators.contains_key(&corner) {
                self.segments.drop_generator(corner);
            }
        }

        self.frame = frame;
        let rects = self.rects();
        let corners: Vec<Point> = frame.iter().flat_map(Rect::corners).collect();
        self.segments.restore(&rects, &corners);
    }

    /// Counts one more use of each point as an interesting point.
    fn add_generators(&mut self, points: &[Point]) {
        for &p in points {
            *self.generators.entry(p).or_default() += 1;
        }
    }

    /// Counts one use less of each point; a point at zero is no longer interesting.
    fn remove_generators(&mut self, points: &[Point]) {
        for p in points {
            let count = self.generators.get_mut(p).expect("a counted generator");
            *count -= 1;
            if *count == 0 {
                self.generators.remove(p);
            }
        }
    }

    /// Adds one use of `p` as an interesting point, creating its segments if new.
    fn add_point_generator(&mut self, p: Point) {
        let count = self.generators.entry(p).or_default();
        *count += 1;
        if *count == 1 {
            let rects = self.rects();
            self.segments.restore(&rects, &[p]);
        }

        self.refresh_frame();
    }

    /// Removes one use of `p`; drops it from its segments when the last use goes.
    fn remove_point_generator(&mut self, p: Point) {
        self.remove_generators(&[p]);
        if !self.generators.contains_key(&p) {
            self.segments.drop_generator(p);
        }

        self.refresh_frame();
    }
}

/// The bounding box of the interesting points grown by one unit, or `None` if there are
/// none.
fn frame_of(generators: &BTreeMap<Point, u32>) -> Option<Rect> {
    let mut points = generators.keys();
    let first = *points.next()?;
    let (mut lo, mut hi) = (first, first);
    for p in points {
        lo = Point::new(lo.x.min(p.x), lo.y.min(p.y));
        hi = Point::new(hi.x.max(p.x), hi.y.max(p.y));
    }

    Some(Rect::new(lo.x - 1, lo.y - 1, hi.x + 1, hi.y + 1))
}

/// Checks that both corners of `rect` are in range.
fn check_rect(rect: &Rect) -> Result<(), Error> {
    for p in [rect.min, rect.max] {
        if !p.is_in_range() {
            return Err(Error::CoordinateOutOfRange(p));
        }
    }

    Ok(())
}

/// Checks that a port is in range and allows a direction.
fn check_port(port: &Port) -> Result<(), Error> {
    if !port.point.is_in_range() {
        return Err(Error::CoordinateOutOfRange(port.point));
    }

    if port.directions.is_empty() {
        return Err(Error::PortWithoutDirections(port.point));
    }

    Ok(())
}