Skip to main content

printobserver_core/
toolpath.rs

1//! The planned geometry of a print, read from its G-code by the one read the
2//! [`GcodeIndex`](crate::GcodeIndex) makes: each object's footprint outline,
3//! and one layer's toolpath read back from the print's spool.
4//!
5//! The index's single streamed read of a print's file also copies its bytes
6//! to a per-print spool file and records each layer's byte range, so a
7//! toolpath is read from that range of the spool and never from a second read
8//! of the printer's file. The core alone reads G-code; what leaves it is
9//! segments in bed millimetres, each with the [`ExtrusionKind`] its
10//! `;TYPE:` maps to.
11
12use std::path::{Path, PathBuf};
13
14use printobserver_types::PrintId;
15
16/// How many directions an outline is bounded in: its most vertices.
17pub const OUTLINE_DIRECTIONS: usize = 64;
18
19/// What a toolpath segment lays, from `PrusaSlicer`'s `;TYPE:` label.
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
21pub enum ExtrusionKind {
22    /// `External perimeter` and `Perimeter`.
23    Wall,
24    /// `Internal infill`, `Solid infill`, `Top solid infill` and `Gap fill`.
25    Infill,
26    /// `Support material` and `Support material interface`.
27    Support,
28    /// `Bridge infill`.
29    Bridge,
30    /// `Overhang perimeter`.
31    Overhang,
32    /// Anything else: the skirt or brim, the slicer's own start and end
33    /// G-code, or an unlabelled move.
34    Other,
35}
36
37impl ExtrusionKind {
38    /// The kind a `;TYPE:` label names.
39    #[must_use]
40    pub fn of_type(name: &str) -> Self {
41        match name {
42            "External perimeter" | "Perimeter" => Self::Wall,
43            "Internal infill" | "Solid infill" | "Top solid infill" | "Gap fill" => Self::Infill,
44            "Support material" | "Support material interface" => Self::Support,
45            "Bridge infill" => Self::Bridge,
46            "Overhang perimeter" => Self::Overhang,
47            _ => Self::Other,
48        }
49    }
50
51    /// Whether this kind holds the part up rather than making it.
52    #[must_use]
53    pub const fn is_support(self) -> bool {
54        matches!(self, Self::Support)
55    }
56}
57
58/// One object's footprint: an outward bound of the convex hull of every
59/// extrusion move laying it, in bed millimetres, counter-clockwise, with at
60/// most [`OUTLINE_DIRECTIONS`] vertices.
61#[derive(Debug, Clone, PartialEq)]
62pub struct ObjectOutline {
63    /// The vertices, counter-clockwise.
64    pub hull_mm: Vec<[f32; 2]>,
65}
66
67/// One layer of an index, as the index that answered it numbers it.
68#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
69pub struct LayerRef(pub(crate) usize);
70
71impl LayerRef {
72    /// The layer at one place among a file's layers, the first being 0; an
73    /// index answers [`SpoolError::UnknownLayer`] for one it does not have.
74    #[must_use]
75    pub const fn of_index(index: usize) -> Self {
76        Self(index)
77    }
78
79    /// Its place among the file's layers, the first being 0.
80    #[must_use]
81    pub const fn index(self) -> usize {
82        self.0
83    }
84}
85
86/// One extrusion move, or one chord of an arc, of a layer.
87#[derive(Debug, Clone, Copy, PartialEq)]
88pub struct ToolpathSegment {
89    /// Where it starts, in bed millimetres.
90    pub from_mm: [f32; 2],
91    /// Where it ends.
92    pub to_mm: [f32; 2],
93    /// What it lays.
94    pub kind: ExtrusionKind,
95}
96
97/// Every extrusion move of one layer, in file order.
98#[derive(Debug, Clone, PartialEq)]
99pub struct LayerToolpath {
100    /// The layer's height, from its `;Z:`; 0 when the file states none.
101    pub z_mm: f32,
102    /// Its segments.
103    pub segments: Vec<ToolpathSegment>,
104}
105
106impl LayerToolpath {
107    /// Whether any segment is object extrusion: anything but supports, as
108    /// `GcodeIndex::object_layer_at_or_below` reads it, so an `Other` segment
109    /// (skirt, brim or custom G-code) counts.
110    #[must_use]
111    pub fn carries_object_extrusion(&self) -> bool {
112        self.segments
113            .iter()
114            .any(|segment| !segment.kind.is_support())
115    }
116}
117
118/// Why a layer's toolpath could not be read back.
119#[derive(Debug, Clone, PartialEq, Eq)]
120pub enum SpoolError {
121    /// The index was built with no spool beside it.
122    NoSpool,
123    /// The layer is not one of this index's.
124    UnknownLayer,
125    /// The spool could not be read, or is shorter than the index recorded.
126    Io {
127        /// What the filesystem said.
128        detail: String,
129    },
130}
131
132impl core::fmt::Display for SpoolError {
133    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
134        match self {
135            Self::NoSpool => formatter.write_str("the print's G-code was indexed with no spool"),
136            Self::UnknownLayer => formatter.write_str("no such layer in the print's index"),
137            Self::Io { detail } => write!(formatter, "the print's G-code spool: {detail}"),
138        }
139    }
140}
141
142impl std::error::Error for SpoolError {}
143
144/// The spool file of one print under a spool directory.
145#[must_use]
146pub fn spool_path(directory: &Path, print_id: PrintId) -> PathBuf {
147    directory.join(format!("{print_id}{SPOOL_SUFFIX}"))
148}
149
150/// What every spool file's name ends in.
151pub(crate) const SPOOL_SUFFIX: &str = ".gcode";
152
153/// The unit vectors an outline is bounded along, counter-clockwise from +X.
154fn direction(k: usize) -> [f64; 2] {
155    let angle = core::f64::consts::TAU * f64::from(u32::try_from(k).unwrap_or(0))
156        / f64::from(u32::try_from(OUTLINE_DIRECTIONS).unwrap_or(1));
157    [angle.cos(), angle.sin()]
158}
159
160/// How far an outline reaches along each of its directions: the support
161/// function of every point it was given. Its polygon is the intersection of
162/// one half-plane per direction, so it holds every point and only grows
163/// outward from the hull.
164#[derive(Debug, Clone, PartialEq)]
165pub(crate) struct Reach {
166    /// The furthest point's projection on each direction.
167    extent: [f64; OUTLINE_DIRECTIONS],
168    /// Whether any point was given.
169    any: bool,
170    /// A circle inside the polygon so far: its centre and radius. A point
171    /// within it reaches no further in any direction, so it is passed over
172    /// without the per-direction work, which is most of a print's moves.
173    inside: ([f64; 2], f64),
174}
175
176impl Default for Reach {
177    fn default() -> Self {
178        Self {
179            extent: [f64::NEG_INFINITY; OUTLINE_DIRECTIONS],
180            any: false,
181            inside: ([0.0, 0.0], -1.0),
182        }
183    }
184}
185
186/// The directions, computed once.
187fn directions() -> &'static [[f64; 2]; OUTLINE_DIRECTIONS] {
188    static HELD: std::sync::OnceLock<[[f64; 2]; OUTLINE_DIRECTIONS]> = std::sync::OnceLock::new();
189    HELD.get_or_init(|| {
190        let mut held = [[0.0; 2]; OUTLINE_DIRECTIONS];
191        let mut k = 0;
192        while k < OUTLINE_DIRECTIONS {
193            held[k] = direction(k);
194            k += 1;
195        }
196        held
197    })
198}
199
200impl Reach {
201    /// Push every direction's extent out to `(x, y)`; a point inside the
202    /// cached inner circle cannot move any extent, so it is skipped.
203    pub(crate) fn point(&mut self, x: f64, y: f64) {
204        let ([cx, cy], radius) = self.inside;
205        let (dx, dy) = (x - cx, y - cy);
206        if radius > 0.0 && dx * dx + dy * dy < radius * radius {
207            return;
208        }
209        let held = directions();
210        self.any = true;
211        // A plain loop: this runs for every extrusion move of a print that
212        // the circle inside does not hold.
213        let mut grew = false;
214        let mut k = 0;
215        while k < OUTLINE_DIRECTIONS {
216            let along = held[k][0] * x + held[k][1] * y;
217            if along > self.extent[k] {
218                self.extent[k] = along;
219                grew = true;
220            }
221            k += 1;
222        }
223        if grew {
224            self.refit_inside();
225        }
226    }
227
228    /// The circle inside the polygon about the middle of its extents: the
229    /// nearest of its half-planes from that centre. The four axis directions
230    /// are among the directions, a quarter turn apart.
231    fn refit_inside(&mut self) {
232        let quarter = OUTLINE_DIRECTIONS / 4;
233        let (right, up) = (self.extent[0], self.extent[quarter]);
234        let (left, down) = (-self.extent[2 * quarter], -self.extent[3 * quarter]);
235        if !(right.is_finite() && up.is_finite() && left.is_finite() && down.is_finite()) {
236            return;
237        }
238        let centre = [f64::midpoint(right, left), f64::midpoint(up, down)];
239        let held = directions();
240        let mut radius = f64::INFINITY;
241        let mut k = 0;
242        while k < OUTLINE_DIRECTIONS {
243            let gap = self.extent[k] - (held[k][0] * centre[0] + held[k][1] * centre[1]);
244            radius = radius.min(gap);
245            k += 1;
246        }
247        self.inside = (centre, radius);
248    }
249
250    /// Push out the extents of the directions whose circle point the arc
251    /// sweeps over: `sweep` radians counter-clockwise from the angle `from`
252    /// about `centre`. The arc's ends are not reached here; the caller gives
253    /// them to `point`.
254    pub(crate) fn arc(&mut self, centre: [f64; 2], radius: f64, from: f64, sweep: f64) {
255        let tau = core::f64::consts::TAU;
256        let held = directions();
257        for (k, unit) in held.iter().enumerate() {
258            let angle = tau * f64::from(u32::try_from(k).unwrap_or(0))
259                / f64::from(u32::try_from(OUTLINE_DIRECTIONS).unwrap_or(1));
260            if (angle - from).rem_euclid(tau) <= sweep + 1e-9 {
261                let along = unit[0] * centre[0] + unit[1] * centre[1] + radius;
262                if along > self.extent[k] {
263                    self.extent[k] = along;
264                    self.any = true;
265                }
266            }
267        }
268        self.refit_inside();
269    }
270
271    /// The outline's polygon, counter-clockwise; nothing when no point was
272    /// given.
273    pub(crate) fn outline(&self) -> Option<ObjectOutline> {
274        if !self.any {
275            return None;
276        }
277        // A box far past any bed, clipped by each half-plane in turn.
278        let far = 1e6;
279        let mut polygon = vec![[-far, -far], [far, -far], [far, far], [-far, far]];
280        for (unit, extent) in directions().iter().zip(self.extent) {
281            polygon = clip(&polygon, *unit, extent);
282            if polygon.is_empty() {
283                return None;
284            }
285        }
286        let mut hull: Vec<[f32; 2]> = Vec::with_capacity(polygon.len());
287        for [x, y] in polygon {
288            #[expect(
289                clippy::cast_possible_truncation,
290                reason = "bed millimetres are far inside f32's range; the outline is drawn, not measured"
291            )]
292            let vertex = [x as f32, y as f32];
293            let repeats = hull.last().is_some_and(|last: &[f32; 2]| {
294                (last[0] - vertex[0]).abs() < 1e-4 && (last[1] - vertex[1]).abs() < 1e-4
295            });
296            if !repeats {
297                hull.push(vertex);
298            }
299        }
300        while hull.len() > 1
301            && hull.first().zip(hull.last()).is_some_and(|(first, last)| {
302                (first[0] - last[0]).abs() < 1e-4 && (first[1] - last[1]).abs() < 1e-4
303            })
304        {
305            hull.pop();
306        }
307        Some(ObjectOutline { hull_mm: hull })
308    }
309}
310
311/// One Sutherland–Hodgman step: what of a convex polygon lies on the side of
312/// `unit · p <= extent`.
313fn clip(polygon: &[[f64; 2]], unit: [f64; 2], extent: f64) -> Vec<[f64; 2]> {
314    let inside = |p: [f64; 2]| unit[0] * p[0] + unit[1] * p[1] - extent;
315    let mut kept = Vec::with_capacity(polygon.len() + 1);
316    for (at, point) in polygon.iter().enumerate() {
317        let next = polygon[(at + 1) % polygon.len()];
318        let (here, there) = (inside(*point), inside(next));
319        if here <= 0.0 {
320            kept.push(*point);
321        }
322        if (here <= 0.0) != (there <= 0.0) {
323            let t = here / (here - there);
324            kept.push([
325                point[0] + t * (next[0] - point[0]),
326                point[1] + t * (next[1] - point[1]),
327            ]);
328        }
329    }
330    kept
331}
332
333#[cfg(test)]
334mod tests {
335    use super::{ExtrusionKind, OUTLINE_DIRECTIONS, Reach};
336
337    /// Signed area of a polygon: positive when counter-clockwise.
338    fn area(hull: &[[f32; 2]]) -> f64 {
339        let mut twice = 0.0;
340        for (at, a) in hull.iter().enumerate() {
341            let b = hull[(at + 1) % hull.len()];
342            twice += f64::from(a[0]) * f64::from(b[1]) - f64::from(b[0]) * f64::from(a[1]);
343        }
344        twice / 2.0
345    }
346
347    #[test]
348    fn an_outline_holds_every_point_counter_clockwise_and_is_bounded() {
349        let mut reach = Reach::default();
350        let points = [
351            [10.0, 10.0],
352            [30.0, 12.0],
353            [25.0, 40.0],
354            [12.0, 33.0],
355            [20.0, 20.0],
356        ];
357        for [x, y] in points {
358            reach.point(x, y);
359        }
360        let outline = reach.outline().expect("points were given");
361        assert!(outline.hull_mm.len() <= OUTLINE_DIRECTIONS);
362        assert!(area(&outline.hull_mm) > 0.0, "counter-clockwise");
363        for [x, y] in points {
364            for (at, a) in outline.hull_mm.iter().enumerate() {
365                let b = outline.hull_mm[(at + 1) % outline.hull_mm.len()];
366                let cross = (f64::from(b[0]) - f64::from(a[0])) * (y - f64::from(a[1]))
367                    - (f64::from(b[1]) - f64::from(a[1])) * (x - f64::from(a[0]));
368                assert!(cross >= -1e-3, "({x}, {y}) lies inside every edge");
369            }
370        }
371    }
372
373    #[test]
374    fn an_arc_reaches_the_part_of_its_circle_it_sweeps() {
375        let mut reach = Reach::default();
376        reach.point(10.0, 0.0);
377        reach.point(0.0, 10.0);
378        reach.arc([0.0, 0.0], 10.0, 0.0, core::f64::consts::FRAC_PI_2);
379        let outline = reach.outline().expect("points were given");
380        let furthest = outline
381            .hull_mm
382            .iter()
383            .map(|[x, y]| f64::from(*x).hypot(f64::from(*y)))
384            .fold(0.0, f64::max);
385        assert!((10.0..10.1).contains(&furthest), "{furthest}");
386    }
387
388    #[test]
389    fn no_point_is_no_outline_and_types_map_to_kinds() {
390        assert!(Reach::default().outline().is_none());
391        assert_eq!(ExtrusionKind::of_type("Perimeter"), ExtrusionKind::Wall);
392        assert_eq!(ExtrusionKind::of_type("Gap fill"), ExtrusionKind::Infill);
393        assert_eq!(
394            ExtrusionKind::of_type("Support material interface"),
395            ExtrusionKind::Support
396        );
397        assert_eq!(ExtrusionKind::of_type("Skirt/Brim"), ExtrusionKind::Other);
398    }
399}