Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 81 additions & 5 deletions cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,12 @@ use g_code::{
emit::{FormatOptions, format_gcode_io},
parse::snippet_parser,
};
use log::{error, info};
use log::{error, info, warn};
use roxmltree::ParsingOptions;
use svg2gcode::{
Machine,
config::{ConversionOptions, Settings, SupportedFunctionality, Version},
svg_to_gcode,
Machine, check_bed_bounds,
config::{BedCheck, ConversionOptions, Settings, SupportedFunctionality, Version},
svg_to_gcode_with_bounds,
};
use svgtypes::LengthListParser;

Expand Down Expand Up @@ -111,6 +111,57 @@ struct Opt {
/// Starting point , usefull only if try optimize path
#[arg(long)]
starting_point: Option<String>,
/// Scale the drawing to fit within an area of this width and height in mm (i.e. 200,150)
///
/// The aspect ratio is preserved and the drawing's corner is placed at `--origin`.
/// Leave an axis empty to leave it unconstrained (i.e. "200," or ",150").
#[arg(long)]
fit_to_area: Option<String>,
/// With `--fit-to-area`, only shrink drawings that are too large; never enlarge small ones
#[arg(long)]
fit_shrink_only: Option<bool>,
/// Width and height of the machine's bed in mm (i.e. 300,200), starting at 0,0
///
/// The drawing is checked against it after conversion; see `--bed-check`.
/// Leave an axis empty to skip checking it (i.e. "300," or ",200").
#[arg(long)]
bed_size: Option<String>,
/// What to do when the drawing goes past the edges of `--bed-size`
#[arg(long, value_enum)]
bed_check: Option<BedCheckArg>,
}

#[derive(Debug, Clone, Copy, clap::ValueEnum)]
enum BedCheckArg {
/// Refuse to write g-code (default)
Error,
/// Write g-code anyway and print a warning
Warn,
}

impl From<BedCheckArg> for BedCheck {
fn from(arg: BedCheckArg) -> Self {
match arg {
BedCheckArg::Error => BedCheck::Error,
BedCheckArg::Warn => BedCheck::Warn,
}
}
}

/// Parses "width,height" in mm, where either may be empty.
fn parse_area(value: &str, what: &str) -> [Option<f64>; 2] {
let mut area = [None; 2];
for (i, dimension) in value.split(',').take(2).enumerate() {
let dimension = dimension.trim();
if !dimension.is_empty() {
let dimension = dimension
.parse::<f64>()
.unwrap_or_else(|_| panic!("could not parse {what} dimension"));
assert!(dimension > 0., "{what} dimensions must be positive");
area[i] = Some(dimension);
}
}
area
}

fn main() -> io::Result<()> {
Expand Down Expand Up @@ -191,6 +242,18 @@ fn main() -> io::Result<()> {
}
}
}
if let Some(fit_to_area) = opt.fit_to_area {
settings.conversion.inner.fit_to_area = parse_area(&fit_to_area, "area");
}
if let Some(fit_shrink_only) = opt.fit_shrink_only {
settings.conversion.inner.fit_shrink_only = fit_shrink_only;
}
if let Some(bed_size) = opt.bed_size {
settings.machine.bed_size = parse_area(&bed_size, "bed");
}
if let Some(bed_check) = opt.bed_check {
settings.machine.bed_check = bed_check.into();
}

if let Some(line_numbers) = opt.line_numbers {
settings.postprocess.line_numbers = line_numbers;
Expand Down Expand Up @@ -358,7 +421,20 @@ fn main() -> io::Result<()> {
)
.unwrap();

let program = svg_to_gcode(&document, &settings.conversion, options, machine);
let (program, bounds) =
svg_to_gcode_with_bounds(&document, &settings.conversion, options, machine);

if let Err(out_of_bounds) = check_bed_bounds(bounds, settings.machine.bed_size) {
match settings.machine.bed_check {
BedCheck::Error => {
error!(
"{out_of_bounds}. No g-code was written. Try --fit-to-area or --origin to move the drawing onto the bed, or --bed-check warn to write it anyway."
);
std::process::exit(1);
}
BedCheck::Warn => warn!("{out_of_bounds}"),
}
}

if let Some(out_path) = opt.out {
format_gcode_io(
Expand Down
122 changes: 122 additions & 0 deletions g_code/src/bounds.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
use std::fmt;

use lyon_geom::Box2D;

/// Allowance for floating point noise, in millimeters.
const EPSILON: f64 = 1e-6;

/// The drawing extends past the edges of the machine's bed.
#[derive(Debug, Clone, PartialEq)]
pub struct OutOfBounds {
/// Bounding box of the drawing in millimeters.
pub bounds: Box2D<f64>,
/// Bed width and height in millimeters (see [`crate::config::MachineConfig::bed_size`]).
pub bed_size: [Option<f64>; 2],
/// How far the drawing goes past each edge, in millimeters, as `(edge, overshoot)`.
pub overshoot: Vec<(&'static str, f64)>,
}

impl fmt::Display for OutOfBounds {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let bed = self
.bed_size
.map(|dim| dim.map_or_else(|| "any".to_owned(), |d| format!("{d}")));
write!(
f,
"drawing spans X {:.3}..{:.3} mm, Y {:.3}..{:.3} mm, which does not fit the {} x {} mm bed (",
self.bounds.min.x,
self.bounds.max.x,
self.bounds.min.y,
self.bounds.max.y,
bed[0],
bed[1],
)?;
for (i, (edge, overshoot)) in self.overshoot.iter().enumerate() {
if i > 0 {
f.write_str(", ")?;
}
write!(f, "{overshoot:.3} mm past the {edge} edge")?;
}
f.write_str(")")
}
}

impl std::error::Error for OutOfBounds {}

/// Checks that `bounds` lies within a bed spanning from `(0, 0)` to `bed_size`, in millimeters.
///
/// An axis of `bed_size` that is `None` is not checked. Nothing drawn (`bounds` is `None`) always fits.
pub fn check_bed_bounds(
bounds: Option<Box2D<f64>>,
bed_size: [Option<f64>; 2],
) -> Result<(), OutOfBounds> {
let Some(bounds) = bounds else {
return Ok(());
};
let [width, height] = bed_size;
let mut overshoot = vec![];
if let Some(width) = width {
if bounds.min.x < -EPSILON {
overshoot.push(("left", -bounds.min.x));
}
if bounds.max.x > width + EPSILON {
overshoot.push(("right", bounds.max.x - width));
}
}
if let Some(height) = height {
if bounds.min.y < -EPSILON {
overshoot.push(("bottom", -bounds.min.y));
}
if bounds.max.y > height + EPSILON {
overshoot.push(("top", bounds.max.y - height));
}
}
if overshoot.is_empty() {
Ok(())
} else {
Err(OutOfBounds {
bounds,
bed_size,
overshoot,
})
}
}

#[cfg(test)]
mod tests {
use lyon_geom::point;

use super::*;

fn bbox(min: (f64, f64), max: (f64, f64)) -> Box2D<f64> {
Box2D::new(point(min.0, min.1), point(max.0, max.1))
}

#[test]
fn inside_bed_is_ok() {
assert!(
check_bed_bounds(Some(bbox((0., 0.), (300., 200.))), [Some(300.), Some(200.)]).is_ok()
);
assert!(check_bed_bounds(None, [Some(1.), Some(1.)]).is_ok());
assert!(check_bed_bounds(Some(bbox((-5., -5.), (900., 900.))), [None, None]).is_ok());
}

#[test]
fn outside_bed_reports_each_edge() {
let err = check_bed_bounds(
Some(bbox((-2., 1.), (310., 250.))),
[Some(300.), Some(200.)],
)
.unwrap_err();
assert_eq!(
err.overshoot,
vec![("left", 2.), ("right", 10.), ("top", 50.)]
);
assert!(err.to_string().contains("10.000 mm past the right edge"));
}

#[test]
fn unchecked_axis_is_ignored() {
assert!(check_bed_bounds(Some(bbox((0., -50.), (100., 500.))), [Some(100.), None]).is_ok());
}
}
19 changes: 19 additions & 0 deletions g_code/src/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,25 @@ pub struct MachineConfig {
serde(default, deserialize_with = "deserialize_string_or_strings")
)]
pub end_sequence: Option<String>,
/// Width and height of the machine's bed in millimeters, starting at `(0, 0)`.
///
/// When set, the drawing is checked against it after conversion (see [`MachineConfig::bed_check`]).
/// Setting an axis to `None` disables the check for that axis.
pub bed_size: [Option<f64>; 2],
/// What to do when the drawing extends past [`MachineConfig::bed_size`].
pub bed_check: BedCheck,
}

/// What to do when the drawing does not fit on the machine's bed.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "lowercase"))]
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub enum BedCheck {
/// Refuse to produce g-code.
#[default]
Error,
/// Produce g-code anyway, but warn about it.
Warn,
}

#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
Expand Down
29 changes: 25 additions & 4 deletions g_code/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,23 @@
#![cfg_attr(not(test), deny(unused_crate_dependencies))]

use g_code::emit::Token;
use lyon_geom::Box2D;
use roxmltree::Document;
use rust_decimal::{Decimal, prelude::FromPrimitive};
use svg2star::{
lower::{ConversionOptions, svg_to_turtle},
turtle::CoordinateSystem,
};

pub use self::{machine::Machine, turtle::GCodeTurtle};
pub use self::{
bounds::{OutOfBounds, check_bed_bounds},
machine::Machine,
turtle::GCodeTurtle,
};
use crate::config::GCodeConfig;

/// Checks that generated paths stay within the machine's bed.
mod bounds;
pub mod config;
/// Emulates the generic state of an arbitrary machine that runs G-Code.
pub mod machine;
Expand All @@ -29,6 +36,19 @@ pub fn svg_to_gcode<'a, 'input: 'a>(
options: ConversionOptions,
machine: Machine<'input>,
) -> Vec<Token<'input>> {
svg_to_gcode_with_bounds(doc, config, options, machine).0
}

/// Like [`svg_to_gcode`], but also returns the bounding box (in mm) of everything drawn with the tool on.
///
/// Pass the bounding box to [`check_bed_bounds`] to verify it fits on the machine's bed.
/// It is `None` when nothing was drawn.
pub fn svg_to_gcode_with_bounds<'a, 'input: 'a>(
doc: &'a Document,
config: &GCodeConfig,
options: ConversionOptions,
machine: Machine<'input>,
) -> (Vec<Token<'input>>, Option<Box2D<f64>>) {
let gcode_turtle = self::turtle::GCodeTurtle {
machine,
tolerance: Decimal::from_f64(config.tolerance)
Expand All @@ -38,13 +58,14 @@ pub fn svg_to_gcode<'a, 'input: 'a>(
.unwrap_or_default()
.normalize(),
program: vec![],
bounds: None,
};
svg_to_turtle(
let turtle = svg_to_turtle(
doc,
&config.inner,
options,
gcode_turtle,
CoordinateSystem::YUp,
)
.program
);
(turtle.program, turtle.bounds)
}
9 changes: 8 additions & 1 deletion g_code/src/turtle.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::{borrow::Cow, fmt::Debug};

use ::g_code::{command, emit::Token};
use lyon_geom::{LineSegment, Point, SvgArc};
use lyon_geom::{Box2D, LineSegment, Point, SvgArc};
use rust_decimal::{Decimal, prelude::*};
use svg2star::turtle::{
Turtle,
Expand All @@ -17,6 +17,8 @@ pub struct GCodeTurtle<'input> {
pub tolerance: Decimal,
pub feedrate: Decimal,
pub program: Vec<Token<'input>>,
/// Bounding box of everything drawn with the tool on, in millimeters.
pub bounds: Option<Box2D<f64>>,
}

impl<'input> GCodeTurtle<'input> {
Expand Down Expand Up @@ -146,6 +148,11 @@ impl Turtle for GCodeTurtle<'_> {

fn stroke(&mut self, stroke: Stroke) {
let start = stroke.start_point();
let stroke_bounds = stroke.bounding_box();
self.bounds = Some(match self.bounds {
Some(b) => Box2D::from_points([b.min, b.max, stroke_bounds.min, stroke_bounds.max]),
None => stroke_bounds,
});

self.tool_off();

Expand Down
Loading