use std::path::{Path, PathBuf};
use printobserver_types::PrintId;
pub const OUTLINE_DIRECTIONS: usize = 64;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ExtrusionKind {
Wall,
Infill,
Support,
Bridge,
Overhang,
Other,
}
impl ExtrusionKind {
#[must_use]
pub fn of_type(name: &str) -> Self {
match name {
"External perimeter" | "Perimeter" => Self::Wall,
"Internal infill" | "Solid infill" | "Top solid infill" | "Gap fill" => Self::Infill,
"Support material" | "Support material interface" => Self::Support,
"Bridge infill" => Self::Bridge,
"Overhang perimeter" => Self::Overhang,
_ => Self::Other,
}
}
#[must_use]
pub const fn is_support(self) -> bool {
matches!(self, Self::Support)
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct ObjectOutline {
pub hull_mm: Vec<[f32; 2]>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct LayerRef(pub(crate) usize);
impl LayerRef {
#[must_use]
pub const fn of_index(index: usize) -> Self {
Self(index)
}
#[must_use]
pub const fn index(self) -> usize {
self.0
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ToolpathSegment {
pub from_mm: [f32; 2],
pub to_mm: [f32; 2],
pub kind: ExtrusionKind,
}
#[derive(Debug, Clone, PartialEq)]
pub struct LayerToolpath {
pub z_mm: f32,
pub segments: Vec<ToolpathSegment>,
}
impl LayerToolpath {
#[must_use]
pub fn carries_object_extrusion(&self) -> bool {
self.segments
.iter()
.any(|segment| !segment.kind.is_support())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SpoolError {
NoSpool,
UnknownLayer,
Io {
detail: String,
},
}
impl core::fmt::Display for SpoolError {
fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::NoSpool => formatter.write_str("the print's G-code was indexed with no spool"),
Self::UnknownLayer => formatter.write_str("no such layer in the print's index"),
Self::Io { detail } => write!(formatter, "the print's G-code spool: {detail}"),
}
}
}
impl std::error::Error for SpoolError {}
#[must_use]
pub fn spool_path(directory: &Path, print_id: PrintId) -> PathBuf {
directory.join(format!("{print_id}{SPOOL_SUFFIX}"))
}
pub(crate) const SPOOL_SUFFIX: &str = ".gcode";
fn direction(k: usize) -> [f64; 2] {
let angle = core::f64::consts::TAU * f64::from(u32::try_from(k).unwrap_or(0))
/ f64::from(u32::try_from(OUTLINE_DIRECTIONS).unwrap_or(1));
[angle.cos(), angle.sin()]
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct Reach {
extent: [f64; OUTLINE_DIRECTIONS],
any: bool,
inside: ([f64; 2], f64),
}
impl Default for Reach {
fn default() -> Self {
Self {
extent: [f64::NEG_INFINITY; OUTLINE_DIRECTIONS],
any: false,
inside: ([0.0, 0.0], -1.0),
}
}
}
fn directions() -> &'static [[f64; 2]; OUTLINE_DIRECTIONS] {
static HELD: std::sync::OnceLock<[[f64; 2]; OUTLINE_DIRECTIONS]> = std::sync::OnceLock::new();
HELD.get_or_init(|| {
let mut held = [[0.0; 2]; OUTLINE_DIRECTIONS];
let mut k = 0;
while k < OUTLINE_DIRECTIONS {
held[k] = direction(k);
k += 1;
}
held
})
}
impl Reach {
pub(crate) fn point(&mut self, x: f64, y: f64) {
let ([cx, cy], radius) = self.inside;
let (dx, dy) = (x - cx, y - cy);
if radius > 0.0 && dx * dx + dy * dy < radius * radius {
return;
}
let held = directions();
self.any = true;
let mut grew = false;
let mut k = 0;
while k < OUTLINE_DIRECTIONS {
let along = held[k][0] * x + held[k][1] * y;
if along > self.extent[k] {
self.extent[k] = along;
grew = true;
}
k += 1;
}
if grew {
self.refit_inside();
}
}
fn refit_inside(&mut self) {
let quarter = OUTLINE_DIRECTIONS / 4;
let (right, up) = (self.extent[0], self.extent[quarter]);
let (left, down) = (-self.extent[2 * quarter], -self.extent[3 * quarter]);
if !(right.is_finite() && up.is_finite() && left.is_finite() && down.is_finite()) {
return;
}
let centre = [f64::midpoint(right, left), f64::midpoint(up, down)];
let held = directions();
let mut radius = f64::INFINITY;
let mut k = 0;
while k < OUTLINE_DIRECTIONS {
let gap = self.extent[k] - (held[k][0] * centre[0] + held[k][1] * centre[1]);
radius = radius.min(gap);
k += 1;
}
self.inside = (centre, radius);
}
pub(crate) fn arc(&mut self, centre: [f64; 2], radius: f64, from: f64, sweep: f64) {
let tau = core::f64::consts::TAU;
let held = directions();
for (k, unit) in held.iter().enumerate() {
let angle = tau * f64::from(u32::try_from(k).unwrap_or(0))
/ f64::from(u32::try_from(OUTLINE_DIRECTIONS).unwrap_or(1));
if (angle - from).rem_euclid(tau) <= sweep + 1e-9 {
let along = unit[0] * centre[0] + unit[1] * centre[1] + radius;
if along > self.extent[k] {
self.extent[k] = along;
self.any = true;
}
}
}
self.refit_inside();
}
pub(crate) fn outline(&self) -> Option<ObjectOutline> {
if !self.any {
return None;
}
let far = 1e6;
let mut polygon = vec![[-far, -far], [far, -far], [far, far], [-far, far]];
for (unit, extent) in directions().iter().zip(self.extent) {
polygon = clip(&polygon, *unit, extent);
if polygon.is_empty() {
return None;
}
}
let mut hull: Vec<[f32; 2]> = Vec::with_capacity(polygon.len());
for [x, y] in polygon {
#[expect(
clippy::cast_possible_truncation,
reason = "bed millimetres are far inside f32's range; the outline is drawn, not measured"
)]
let vertex = [x as f32, y as f32];
let repeats = hull.last().is_some_and(|last: &[f32; 2]| {
(last[0] - vertex[0]).abs() < 1e-4 && (last[1] - vertex[1]).abs() < 1e-4
});
if !repeats {
hull.push(vertex);
}
}
while hull.len() > 1
&& hull.first().zip(hull.last()).is_some_and(|(first, last)| {
(first[0] - last[0]).abs() < 1e-4 && (first[1] - last[1]).abs() < 1e-4
})
{
hull.pop();
}
Some(ObjectOutline { hull_mm: hull })
}
}
fn clip(polygon: &[[f64; 2]], unit: [f64; 2], extent: f64) -> Vec<[f64; 2]> {
let inside = |p: [f64; 2]| unit[0] * p[0] + unit[1] * p[1] - extent;
let mut kept = Vec::with_capacity(polygon.len() + 1);
for (at, point) in polygon.iter().enumerate() {
let next = polygon[(at + 1) % polygon.len()];
let (here, there) = (inside(*point), inside(next));
if here <= 0.0 {
kept.push(*point);
}
if (here <= 0.0) != (there <= 0.0) {
let t = here / (here - there);
kept.push([
point[0] + t * (next[0] - point[0]),
point[1] + t * (next[1] - point[1]),
]);
}
}
kept
}
#[cfg(test)]
mod tests {
use super::{ExtrusionKind, OUTLINE_DIRECTIONS, Reach};
fn area(hull: &[[f32; 2]]) -> f64 {
let mut twice = 0.0;
for (at, a) in hull.iter().enumerate() {
let b = hull[(at + 1) % hull.len()];
twice += f64::from(a[0]) * f64::from(b[1]) - f64::from(b[0]) * f64::from(a[1]);
}
twice / 2.0
}
#[test]
fn an_outline_holds_every_point_counter_clockwise_and_is_bounded() {
let mut reach = Reach::default();
let points = [
[10.0, 10.0],
[30.0, 12.0],
[25.0, 40.0],
[12.0, 33.0],
[20.0, 20.0],
];
for [x, y] in points {
reach.point(x, y);
}
let outline = reach.outline().expect("points were given");
assert!(outline.hull_mm.len() <= OUTLINE_DIRECTIONS);
assert!(area(&outline.hull_mm) > 0.0, "counter-clockwise");
for [x, y] in points {
for (at, a) in outline.hull_mm.iter().enumerate() {
let b = outline.hull_mm[(at + 1) % outline.hull_mm.len()];
let cross = (f64::from(b[0]) - f64::from(a[0])) * (y - f64::from(a[1]))
- (f64::from(b[1]) - f64::from(a[1])) * (x - f64::from(a[0]));
assert!(cross >= -1e-3, "({x}, {y}) lies inside every edge");
}
}
}
#[test]
fn an_arc_reaches_the_part_of_its_circle_it_sweeps() {
let mut reach = Reach::default();
reach.point(10.0, 0.0);
reach.point(0.0, 10.0);
reach.arc([0.0, 0.0], 10.0, 0.0, core::f64::consts::FRAC_PI_2);
let outline = reach.outline().expect("points were given");
let furthest = outline
.hull_mm
.iter()
.map(|[x, y]| f64::from(*x).hypot(f64::from(*y)))
.fold(0.0, f64::max);
assert!((10.0..10.1).contains(&furthest), "{furthest}");
}
#[test]
fn no_point_is_no_outline_and_types_map_to_kinds() {
assert!(Reach::default().outline().is_none());
assert_eq!(ExtrusionKind::of_type("Perimeter"), ExtrusionKind::Wall);
assert_eq!(ExtrusionKind::of_type("Gap fill"), ExtrusionKind::Infill);
assert_eq!(
ExtrusionKind::of_type("Support material interface"),
ExtrusionKind::Support
);
assert_eq!(ExtrusionKind::of_type("Skirt/Brim"), ExtrusionKind::Other);
}
}