1use std::path::{Path, PathBuf};
13
14use printobserver_types::PrintId;
15
16pub const OUTLINE_DIRECTIONS: usize = 64;
18
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
21pub enum ExtrusionKind {
22 Wall,
24 SparseInfill,
26 SolidInfill,
29 TopSolidInfill,
31 Support,
33 Bridge,
35 Overhang,
37 Other,
40}
41
42impl ExtrusionKind {
43 #[must_use]
45 pub fn of_type(name: &str) -> Self {
46 match name {
47 "External perimeter" | "Perimeter" => Self::Wall,
48 "Internal infill" => Self::SparseInfill,
49 "Solid infill" | "Gap fill" => Self::SolidInfill,
50 "Top solid infill" => Self::TopSolidInfill,
51 "Support material" | "Support material interface" => Self::Support,
52 "Bridge infill" => Self::Bridge,
53 "Overhang perimeter" => Self::Overhang,
54 _ => Self::Other,
55 }
56 }
57
58 #[must_use]
60 pub const fn is_support(self) -> bool {
61 matches!(self, Self::Support)
62 }
63
64 #[must_use]
67 pub const fn is_infill(self) -> bool {
68 matches!(
69 self,
70 Self::SparseInfill | Self::SolidInfill | Self::TopSolidInfill
71 )
72 }
73
74 #[must_use]
77 pub const fn name(self) -> &'static str {
78 match self {
79 Self::Wall => "wall",
80 Self::SparseInfill => "sparse infill",
81 Self::SolidInfill => "solid infill",
82 Self::TopSolidInfill => "top solid infill",
83 Self::Support => "support",
84 Self::Bridge => "bridge",
85 Self::Overhang => "overhang",
86 Self::Other => "skirt, brim or other",
87 }
88 }
89
90 #[must_use]
92 pub const fn short_name(self) -> &'static str {
93 match self {
94 Self::Wall => "wall",
95 Self::SparseInfill => "sparse",
96 Self::SolidInfill => "solid",
97 Self::TopSolidInfill => "top solid",
98 Self::Support => "support",
99 Self::Bridge => "bridge",
100 Self::Overhang => "overhang",
101 Self::Other => "other",
102 }
103 }
104}
105
106#[derive(Debug, Clone, PartialEq)]
110pub struct ObjectOutline {
111 pub hull_mm: Vec<[f32; 2]>,
113}
114
115#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
117pub struct LayerRef(pub(crate) usize);
118
119impl LayerRef {
120 #[must_use]
123 pub const fn of_index(index: usize) -> Self {
124 Self(index)
125 }
126
127 #[must_use]
129 pub const fn index(self) -> usize {
130 self.0
131 }
132}
133
134#[derive(Debug, Clone, Copy, PartialEq)]
136pub struct ToolpathSegment {
137 pub from_mm: [f32; 2],
139 pub to_mm: [f32; 2],
141 pub kind: ExtrusionKind,
143 pub width_mm: f32,
146 pub ends_at: u64,
149}
150
151impl ToolpathSegment {
152 #[must_use]
154 pub fn length_mm(&self) -> f64 {
155 let dx = f64::from(self.to_mm[0]) - f64::from(self.from_mm[0]);
156 let dy = f64::from(self.to_mm[1]) - f64::from(self.from_mm[1]);
157 dx.hypot(dy)
158 }
159
160 #[must_use]
162 pub const fn sent_by(&self, file_position_bytes: u64) -> bool {
163 self.ends_at <= file_position_bytes
164 }
165}
166
167#[derive(Debug, Clone, PartialEq)]
169pub struct LayerToolpath {
170 pub z_mm: f32,
172 pub segments: Vec<ToolpathSegment>,
174}
175
176impl LayerToolpath {
177 #[must_use]
181 pub fn carries_object_extrusion(&self) -> bool {
182 self.segments
183 .iter()
184 .any(|segment| !segment.kind.is_support())
185 }
186
187 #[must_use]
191 pub fn progress(&self, file_position_bytes: u64) -> LayerProgress {
192 let mut progress = LayerProgress::default();
193 for segment in &self.segments {
194 let length = segment.length_mm();
195 progress.total_mm += length;
196 let (kinds, sent) = if segment.sent_by(file_position_bytes) {
197 (&mut progress.kinds_sent, length)
198 } else {
199 (&mut progress.kinds_left, 0.0)
200 };
201 progress.sent_mm += sent;
202 if !kinds.contains(&segment.kind) {
203 kinds.push(segment.kind);
204 }
205 }
206 progress
207 }
208}
209
210#[derive(Debug, Clone, Default, PartialEq)]
212pub struct LayerProgress {
213 pub sent_mm: f64,
215 pub total_mm: f64,
217 pub kinds_sent: Vec<ExtrusionKind>,
220 pub kinds_left: Vec<ExtrusionKind>,
223}
224
225impl LayerProgress {
226 #[must_use]
229 pub fn percent_sent(&self) -> u32 {
230 if self.total_mm <= 0.0 {
231 return 0;
232 }
233 #[expect(
234 clippy::cast_possible_truncation,
235 clippy::cast_sign_loss,
236 reason = "a share of 0 to 100 percent, rounded"
237 )]
238 let percent = (100.0 * self.sent_mm / self.total_mm)
239 .round()
240 .clamp(0.0, 100.0) as u32;
241 percent
242 }
243}
244
245#[derive(Debug, Clone, PartialEq)]
249pub struct LayerFacts {
250 pub number: usize,
252 pub count: usize,
254 pub z_mm: f64,
256 pub expected_colour: Option<String>,
261 pub change: Option<ChangeFact>,
263 pub progress: LayerProgress,
265}
266
267#[derive(Debug, Clone, PartialEq)]
269pub struct ChangeFact {
270 pub just_made: bool,
272 pub number: u32,
274 pub colour_change: bool,
276 pub layer: u32,
278 pub z_mm: f64,
280 pub colour: Option<String>,
282}
283
284impl LayerFacts {
285 #[must_use]
290 pub fn lines(&self) -> Vec<String> {
291 let colour = self.expected_colour.as_deref().map_or_else(
292 || "no colour expected".to_owned(),
293 |c| format!("expect {c}"),
294 );
295 let change = self
296 .change
297 .as_ref()
298 .map_or_else(|| "no change ahead".to_owned(), ChangeFact::line);
299 let named = |kinds: &[ExtrusionKind]| {
300 if kinds.is_empty() {
301 "nothing".to_owned()
302 } else {
303 kinds
304 .iter()
305 .map(|kind| kind.short_name())
306 .collect::<Vec<_>>()
307 .join(", ")
308 }
309 };
310 vec![
311 format!(
312 "layer {}/{}, Z {:.2} mm, {colour}; {change}",
313 self.number, self.count, self.z_mm
314 ),
315 format!(
316 "{}% sent by length, bold: {}",
317 self.progress.percent_sent(),
318 named(&self.progress.kinds_sent)
319 ),
320 format!("to print, grey: {}", named(&self.progress.kinds_left)),
321 ]
322 }
323}
324
325impl ChangeFact {
326 #[must_use]
328 pub fn line(&self) -> String {
329 let what = if self.colour_change {
330 "colour change"
331 } else {
332 "pause"
333 };
334 let to = self
335 .colour
336 .as_deref()
337 .map_or_else(String::new, |colour| format!(", to {colour}"));
338 if self.just_made {
339 format!("{what} {} just made{to}", self.number)
340 } else {
341 format!(
342 "{what} {} next: layer {}, Z {:.2} mm{to}",
343 self.number, self.layer, self.z_mm
344 )
345 }
346 }
347}
348
349#[derive(Debug, Clone, PartialEq, Eq)]
351pub enum SpoolError {
352 NoSpool,
354 UnknownLayer,
356 Io {
358 detail: String,
360 },
361}
362
363impl core::fmt::Display for SpoolError {
364 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
365 match self {
366 Self::NoSpool => formatter.write_str("the print's G-code was indexed with no spool"),
367 Self::UnknownLayer => formatter.write_str("no such layer in the print's index"),
368 Self::Io { detail } => write!(formatter, "the print's G-code spool: {detail}"),
369 }
370 }
371}
372
373impl std::error::Error for SpoolError {}
374
375#[must_use]
377pub fn spool_path(directory: &Path, print_id: PrintId) -> PathBuf {
378 directory.join(format!("{print_id}{SPOOL_SUFFIX}"))
379}
380
381pub(crate) const SPOOL_SUFFIX: &str = ".gcode";
383
384fn direction(k: usize) -> [f64; 2] {
386 let angle = core::f64::consts::TAU * f64::from(u32::try_from(k).unwrap_or(0))
387 / f64::from(u32::try_from(OUTLINE_DIRECTIONS).unwrap_or(1));
388 [angle.cos(), angle.sin()]
389}
390
391#[derive(Debug, Clone, PartialEq)]
396pub(crate) struct Reach {
397 extent: [f64; OUTLINE_DIRECTIONS],
399 any: bool,
401 inside: ([f64; 2], f64),
405}
406
407impl Default for Reach {
408 fn default() -> Self {
409 Self {
410 extent: [f64::NEG_INFINITY; OUTLINE_DIRECTIONS],
411 any: false,
412 inside: ([0.0, 0.0], -1.0),
413 }
414 }
415}
416
417fn directions() -> &'static [[f64; 2]; OUTLINE_DIRECTIONS] {
419 static HELD: std::sync::OnceLock<[[f64; 2]; OUTLINE_DIRECTIONS]> = std::sync::OnceLock::new();
420 HELD.get_or_init(|| {
421 let mut held = [[0.0; 2]; OUTLINE_DIRECTIONS];
422 let mut k = 0;
423 while k < OUTLINE_DIRECTIONS {
424 held[k] = direction(k);
425 k += 1;
426 }
427 held
428 })
429}
430
431impl Reach {
432 pub(crate) fn point(&mut self, x: f64, y: f64) {
435 let ([cx, cy], radius) = self.inside;
436 let (dx, dy) = (x - cx, y - cy);
437 if radius > 0.0 && dx * dx + dy * dy < radius * radius {
438 return;
439 }
440 let held = directions();
441 self.any = true;
442 let mut grew = false;
445 let mut k = 0;
446 while k < OUTLINE_DIRECTIONS {
447 let along = held[k][0] * x + held[k][1] * y;
448 if along > self.extent[k] {
449 self.extent[k] = along;
450 grew = true;
451 }
452 k += 1;
453 }
454 if grew {
455 self.refit_inside();
456 }
457 }
458
459 fn refit_inside(&mut self) {
463 let quarter = OUTLINE_DIRECTIONS / 4;
464 let (right, up) = (self.extent[0], self.extent[quarter]);
465 let (left, down) = (-self.extent[2 * quarter], -self.extent[3 * quarter]);
466 if !(right.is_finite() && up.is_finite() && left.is_finite() && down.is_finite()) {
467 return;
468 }
469 let centre = [f64::midpoint(right, left), f64::midpoint(up, down)];
470 let held = directions();
471 let mut radius = f64::INFINITY;
472 let mut k = 0;
473 while k < OUTLINE_DIRECTIONS {
474 let gap = self.extent[k] - (held[k][0] * centre[0] + held[k][1] * centre[1]);
475 radius = radius.min(gap);
476 k += 1;
477 }
478 self.inside = (centre, radius);
479 }
480
481 pub(crate) fn arc(&mut self, centre: [f64; 2], radius: f64, from: f64, sweep: f64) {
486 let tau = core::f64::consts::TAU;
487 let held = directions();
488 for (k, unit) in held.iter().enumerate() {
489 let angle = tau * f64::from(u32::try_from(k).unwrap_or(0))
490 / f64::from(u32::try_from(OUTLINE_DIRECTIONS).unwrap_or(1));
491 if (angle - from).rem_euclid(tau) <= sweep + 1e-9 {
492 let along = unit[0] * centre[0] + unit[1] * centre[1] + radius;
493 if along > self.extent[k] {
494 self.extent[k] = along;
495 self.any = true;
496 }
497 }
498 }
499 self.refit_inside();
500 }
501
502 pub(crate) fn outline(&self) -> Option<ObjectOutline> {
505 if !self.any {
506 return None;
507 }
508 let far = 1e6;
510 let mut polygon = vec![[-far, -far], [far, -far], [far, far], [-far, far]];
511 for (unit, extent) in directions().iter().zip(self.extent) {
512 polygon = clip(&polygon, *unit, extent);
513 if polygon.is_empty() {
514 return None;
515 }
516 }
517 let mut hull: Vec<[f32; 2]> = Vec::with_capacity(polygon.len());
518 for [x, y] in polygon {
519 #[expect(
520 clippy::cast_possible_truncation,
521 reason = "bed millimetres are far inside f32's range; the outline is drawn, not measured"
522 )]
523 let vertex = [x as f32, y as f32];
524 let repeats = hull.last().is_some_and(|last: &[f32; 2]| {
525 (last[0] - vertex[0]).abs() < 1e-4 && (last[1] - vertex[1]).abs() < 1e-4
526 });
527 if !repeats {
528 hull.push(vertex);
529 }
530 }
531 while hull.len() > 1
532 && hull.first().zip(hull.last()).is_some_and(|(first, last)| {
533 (first[0] - last[0]).abs() < 1e-4 && (first[1] - last[1]).abs() < 1e-4
534 })
535 {
536 hull.pop();
537 }
538 Some(ObjectOutline { hull_mm: hull })
539 }
540}
541
542fn clip(polygon: &[[f64; 2]], unit: [f64; 2], extent: f64) -> Vec<[f64; 2]> {
545 let inside = |p: [f64; 2]| unit[0] * p[0] + unit[1] * p[1] - extent;
546 let mut kept = Vec::with_capacity(polygon.len() + 1);
547 for (at, point) in polygon.iter().enumerate() {
548 let next = polygon[(at + 1) % polygon.len()];
549 let (here, there) = (inside(*point), inside(next));
550 if here <= 0.0 {
551 kept.push(*point);
552 }
553 if (here <= 0.0) != (there <= 0.0) {
554 let t = here / (here - there);
555 kept.push([
556 point[0] + t * (next[0] - point[0]),
557 point[1] + t * (next[1] - point[1]),
558 ]);
559 }
560 }
561 kept
562}
563
564#[cfg(test)]
565mod tests {
566 use super::{ExtrusionKind, OUTLINE_DIRECTIONS, Reach};
567
568 fn area(hull: &[[f32; 2]]) -> f64 {
570 let mut twice = 0.0;
571 for (at, a) in hull.iter().enumerate() {
572 let b = hull[(at + 1) % hull.len()];
573 twice += f64::from(a[0]) * f64::from(b[1]) - f64::from(b[0]) * f64::from(a[1]);
574 }
575 twice / 2.0
576 }
577
578 #[test]
579 fn an_outline_holds_every_point_counter_clockwise_and_is_bounded() {
580 let mut reach = Reach::default();
581 let points = [
582 [10.0, 10.0],
583 [30.0, 12.0],
584 [25.0, 40.0],
585 [12.0, 33.0],
586 [20.0, 20.0],
587 ];
588 for [x, y] in points {
589 reach.point(x, y);
590 }
591 let outline = reach.outline().expect("points were given");
592 assert!(outline.hull_mm.len() <= OUTLINE_DIRECTIONS);
593 assert!(area(&outline.hull_mm) > 0.0, "counter-clockwise");
594 for [x, y] in points {
595 for (at, a) in outline.hull_mm.iter().enumerate() {
596 let b = outline.hull_mm[(at + 1) % outline.hull_mm.len()];
597 let cross = (f64::from(b[0]) - f64::from(a[0])) * (y - f64::from(a[1]))
598 - (f64::from(b[1]) - f64::from(a[1])) * (x - f64::from(a[0]));
599 assert!(cross >= -1e-3, "({x}, {y}) lies inside every edge");
600 }
601 }
602 }
603
604 #[test]
605 fn an_arc_reaches_the_part_of_its_circle_it_sweeps() {
606 let mut reach = Reach::default();
607 reach.point(10.0, 0.0);
608 reach.point(0.0, 10.0);
609 reach.arc([0.0, 0.0], 10.0, 0.0, core::f64::consts::FRAC_PI_2);
610 let outline = reach.outline().expect("points were given");
611 let furthest = outline
612 .hull_mm
613 .iter()
614 .map(|[x, y]| f64::from(*x).hypot(f64::from(*y)))
615 .fold(0.0, f64::max);
616 assert!((10.0..10.1).contains(&furthest), "{furthest}");
617 }
618
619 #[test]
620 fn no_point_is_no_outline_and_types_map_to_kinds() {
621 assert!(Reach::default().outline().is_none());
622 assert_eq!(ExtrusionKind::of_type("Perimeter"), ExtrusionKind::Wall);
623 assert_eq!(
624 ExtrusionKind::of_type("Gap fill"),
625 ExtrusionKind::SolidInfill
626 );
627 assert_eq!(
628 ExtrusionKind::of_type("Internal infill"),
629 ExtrusionKind::SparseInfill
630 );
631 assert_eq!(
632 ExtrusionKind::of_type("Top solid infill"),
633 ExtrusionKind::TopSolidInfill
634 );
635 assert_eq!(
636 ExtrusionKind::of_type("Support material interface"),
637 ExtrusionKind::Support
638 );
639 assert_eq!(ExtrusionKind::of_type("Skirt/Brim"), ExtrusionKind::Other);
640 }
641}