diff --git a/cli/src/main.rs b/cli/src/main.rs index 25a72d17..a44159d5 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -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; @@ -111,6 +111,73 @@ struct Opt { /// Starting point , usefull only if try optimize path #[arg(long)] starting_point: Option, + /// 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, + /// With `--fit-to-area`, only shrink drawings that are too large; never enlarge small ones + #[arg(long)] + fit_shrink_only: Option, + /// Trace the outline of filled shapes that have no stroke, instead of ignoring them + /// + /// Useful for SVGs traced from images, which are often made of filled shapes only. + #[arg(long)] + fill_as_outline: Option, + /// Skip paths smaller than this many mm in both width and height (i.e. dithering specks) + /// + /// Measured on the final drawing, after scaling. + #[arg(long)] + min_shape_size: Option, + /// Simplify paths to within this many mm of the original, removing detail finer than the pen + /// + /// Measured on the final drawing, after scaling. Simplified paths use straight lines only. + /// A value around your pen width (i.e. 0.3) is a good start. + #[arg(long)] + simplify: Option, + /// 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, + /// What to do when the drawing goes past the edges of `--bed-size` + #[arg(long, value_enum)] + bed_check: Option, +} + +#[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 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; 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::() + .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<()> { @@ -191,6 +258,32 @@ 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(min_shape_size) = opt.min_shape_size { + assert!( + min_shape_size >= 0., + "--min-shape-size must not be negative" + ); + settings.conversion.inner.min_shape_size = Some(min_shape_size); + } + if let Some(simplify) = opt.simplify { + assert!(simplify >= 0., "--simplify must not be negative"); + settings.conversion.inner.simplify = Some(simplify); + } + if let Some(fill_as_outline) = opt.fill_as_outline { + settings.conversion.inner.fill_as_outline = fill_as_outline; + } + 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; @@ -358,7 +451,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( diff --git a/g_code/src/bounds.rs b/g_code/src/bounds.rs new file mode 100644 index 00000000..9ddc9282 --- /dev/null +++ b/g_code/src/bounds.rs @@ -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, + /// Bed width and height in millimeters (see [`crate::config::MachineConfig::bed_size`]). + pub bed_size: [Option; 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>, + bed_size: [Option; 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 { + 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()); + } +} diff --git a/g_code/src/config/mod.rs b/g_code/src/config/mod.rs index 728f3a68..ca91a451 100644 --- a/g_code/src/config/mod.rs +++ b/g_code/src/config/mod.rs @@ -109,6 +109,25 @@ pub struct MachineConfig { serde(default, deserialize_with = "deserialize_string_or_strings") )] pub end_sequence: Option, + /// 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; 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))] diff --git a/g_code/src/lib.rs b/g_code/src/lib.rs index 62fa8723..073d0af5 100644 --- a/g_code/src/lib.rs +++ b/g_code/src/lib.rs @@ -3,6 +3,7 @@ #![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::{ @@ -10,9 +11,15 @@ use svg2star::{ 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; @@ -29,6 +36,19 @@ pub fn svg_to_gcode<'a, 'input: 'a>( options: ConversionOptions, machine: Machine<'input>, ) -> Vec> { + 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>, Option>) { let gcode_turtle = self::turtle::GCodeTurtle { machine, tolerance: Decimal::from_f64(config.tolerance) @@ -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) } diff --git a/g_code/src/tests.rs b/g_code/src/tests.rs index 129befa3..79a3abe1 100644 --- a/g_code/src/tests.rs +++ b/g_code/src/tests.rs @@ -326,3 +326,57 @@ fn issue_105_optimize_path_order_does_not_shrink_output() { optimized_values.sort_by(f64::total_cmp); assert_eq!(normal_values, optimized_values); } + +fn convert_with(input: &str, inner: ConversionConfig) -> Vec> { + let gcode_config = GCodeConfig { + inner, + ..GCodeConfig::default() + }; + let document = roxmltree::Document::parse(input).unwrap(); + let machine = Machine::new(SupportedFunctionality::default(), None, None, None, None); + svg_to_gcode( + &document, + &gcode_config, + ConversionOptions::default(), + machine, + ) +} + +/// [`ConversionConfig::fill_as_outline`] draws filled shapes as if they were stroked. +#[test] +fn fill_as_outline_matches_stroked_equivalent() { + let filled = r##" + + + + + "##; + let stroked = r#" + + + + + "#; + + let outlined = convert_with( + filled, + ConversionConfig { + fill_as_outline: true, + ..ConversionConfig::default() + }, + ); + assert_close(outlined, convert_with(stroked, ConversionConfig::default())); + + // Off by default: only the explicitly stroked circle is drawn. + let default = convert_with(filled, ConversionConfig::default()); + let only_circle = r#" + + + + + "#; + assert_close( + default, + convert_with(only_circle, ConversionConfig::default()), + ); +} diff --git a/g_code/src/turtle.rs b/g_code/src/turtle.rs index bb2903de..b7ac5a0f 100644 --- a/g_code/src/turtle.rs +++ b/g_code/src/turtle.rs @@ -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, @@ -17,6 +17,8 @@ pub struct GCodeTurtle<'input> { pub tolerance: Decimal, pub feedrate: Decimal, pub program: Vec>, + /// Bounding box of everything drawn with the tool on, in millimeters. + pub bounds: Option>, } impl<'input> GCodeTurtle<'input> { @@ -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(); diff --git a/star/src/lower/mod.rs b/star/src/lower/mod.rs index d54d3733..098e1a9b 100644 --- a/star/src/lower/mod.rs +++ b/star/src/lower/mod.rs @@ -17,8 +17,8 @@ use crate::{ visit::ExpansionState, }, turtle::{ - CoordinateSystem, DpiConvertingTurtle, PreprocessTurtle, StrokeCollectingTurtle, Terrarium, - Turtle, + CleanupTurtle, CoordinateSystem, DpiConvertingTurtle, PreprocessTurtle, + StrokeCollectingTurtle, Terrarium, Turtle, elements::{Stroke, minimize_travel_time}, }, }; @@ -32,6 +32,8 @@ mod transform; mod units; mod visit; +pub use selector::validate as validate_selector_filter; + /// High-level output configuration #[derive(Debug, Clone, PartialEq)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] @@ -56,6 +58,31 @@ pub struct ConversionConfig { /// pub selector_filter: Option, pub starting_point: [Option; 2], + /// Uniformly scale the drawing so it fits within an area of this width and height in millimeters. + /// + /// The drawing's tight bounding box is scaled (up or down) while preserving its aspect ratio, + /// then placed with its corner at [`ConversionConfig::origin`] (an empty origin axis is treated as `0`). + /// + /// Setting an axis to `None` leaves that axis unconstrained. Setting both to `None` disables the behavior. + pub fit_to_area: [Option; 2], + /// Only shrink drawings that are too large for [`ConversionConfig::fit_to_area`]. + /// + /// Drawings that already fit keep their size, but are still moved to the origin. + pub fit_shrink_only: bool, + /// Trace the outline of filled shapes that have no stroke, so they are drawn instead of ignored. + /// + /// Useful for SVGs traced from images, which are often made of filled shapes only. + pub fill_as_outline: bool, + /// Skip paths whose width and height are both smaller than this, in millimeters. + /// + /// Removes specks such as dithering from traced images. Measured on the final drawing, + /// after scaling. `None` disables the behavior. + pub min_shape_size: Option, + /// Simplify paths so they stay within this distance of the original, in millimeters. + /// + /// Removes detail finer than the pen, such as wobble from tracing. Simplified paths are made of + /// straight lines only. Measured on the final drawing, after scaling. `None` disables the behavior. + pub simplify: Option, } const fn zero_origin() -> [Option; 2] { @@ -71,6 +98,11 @@ impl Default for ConversionConfig { optimize_path_order: false, selector_filter: None, starting_point: zero_origin(), + fit_to_area: [None; 2], + fit_shrink_only: false, + fill_as_outline: false, + min_shape_size: None, + simplify: None, } } } @@ -183,15 +215,7 @@ pub fn svg_to_turtle( visit::depth_first_visit(doc, &mut visitor); visitor.end(); - visitor - .terrarium - .finish() - .into_inner() - .into_inner() - // Include the origin so drawings within the page keep their layout. - .map_or_else(Box2D::default, |bb| { - Box2D::from_points([Point::zero(), bb.min, bb.max]) - }) + visitor.terrarium.finish().into_inner() }; // Convert from millimeters to user units @@ -199,27 +223,48 @@ pub fn svg_to_turtle( let starting_point = config.starting_point.map(|dim| dim.map(mm_to_user_units)); - let origin_transform = match config.origin { - [None, Some(origin_y)] => { - let bb = bounding_box_generator(); - Transform2D::translation(0., mm_to_user_units(origin_y - bb.min.y)) - } - [Some(origin_x), None] => { - let bb = bounding_box_generator(); - Transform2D::translation(mm_to_user_units(origin_x - bb.min.x), 0.) - } - [Some(origin_x), Some(origin_y)] => { - let bb = bounding_box_generator(); - Transform2D::translation( - mm_to_user_units(origin_x - bb.min.x), - mm_to_user_units(origin_y - bb.min.y), - ) + let origin_transform = if config.fit_to_area.iter().any(Option::is_some) { + fit_to_area_transform( + bounding_box_generator().into_stroke_bounding_box(), + config.fit_to_area, + config.fit_shrink_only, + config.origin, + mm_to_user_units, + ) + } else { + // Include the origin so drawings within the page keep their layout. + let page_bounding_box = || { + bounding_box_generator() + .into_inner() + .map_or_else(Box2D::default, |bb| { + Box2D::from_points([Point::zero(), bb.min, bb.max]) + }) + }; + match config.origin { + [None, Some(origin_y)] => { + let bb = page_bounding_box(); + Transform2D::translation(0., mm_to_user_units(origin_y - bb.min.y)) + } + [Some(origin_x), None] => { + let bb = page_bounding_box(); + Transform2D::translation(mm_to_user_units(origin_x - bb.min.x), 0.) + } + [Some(origin_x), Some(origin_y)] => { + let bb = page_bounding_box(); + Transform2D::translation( + mm_to_user_units(origin_x - bb.min.x), + mm_to_user_units(origin_y - bb.min.y), + ) + } + [None, None] => Transform2D::identity(), } - [None, None] => Transform2D::identity(), }; let mut conversion_visitor = ConversionVisitor { - terrarium: Terrarium::new(DpiConvertingTurtle::new(config.dpi, turtle)), + terrarium: Terrarium::new(DpiConvertingTurtle::new( + config.dpi, + CleanupTurtle::new(turtle, config.min_shape_size, config.simplify), + )), coordinate_system, config, options: options.clone(), @@ -257,7 +302,47 @@ pub fn svg_to_turtle( conversion_visitor.end(); conversion_visitor.terrarium.pop_transform(); - conversion_visitor.terrarium.finish().into_inner() + conversion_visitor + .terrarium + .finish() + .into_inner() + .into_inner() +} + +/// Builds a transform (in user units) that uniformly scales the drawing's bounding box `bb` (in mm) +/// to fit within `area` (in mm) and moves its corner to `origin` (in mm). +/// +/// Axes of `area` that are `None` do not constrain the scale. Degenerate (zero-size) axes are ignored. +/// With `shrink_only`, the scale never exceeds `1`. +fn fit_to_area_transform( + bb: Option>, + area: [Option; 2], + shrink_only: bool, + origin: [Option; 2], + mm_to_user_units: impl Fn(f64) -> f64, +) -> Transform2D { + let Some(bb) = bb else { + return Transform2D::identity(); + }; + let size = [bb.width(), bb.height()]; + let scale = area + .iter() + .zip(size) + .filter_map(|(target, actual)| match target { + Some(target) if *target > 0. && actual > f64::EPSILON => Some(target / actual), + _ => None, + }) + .reduce(f64::min) + .unwrap_or(1.); + let scale = if shrink_only { scale.min(1.) } else { scale }; + let [origin_x, origin_y] = origin.map(|o| o.unwrap_or(0.)); + + Transform2D::translation(-mm_to_user_units(bb.min.x), -mm_to_user_units(bb.min.y)) + .then_scale(scale, scale) + .then_translate(lyon_geom::vector( + mm_to_user_units(origin_x), + mm_to_user_units(origin_y), + )) } #[allow(clippy::too_many_arguments)] diff --git a/star/src/lower/selector.rs b/star/src/lower/selector.rs index 755e768a..e70f6c49 100644 --- a/star/src/lower/selector.rs +++ b/star/src/lower/selector.rs @@ -195,6 +195,20 @@ peg::parser!(grammar selector_parser() for str { { RelativeSelectorList(selectors) } }); +/// Checks that `input` is a selector [`crate::lower::ConversionConfig::selector_filter`] accepts. +/// +/// Returns a short, human readable error otherwise. +pub fn validate(input: &str) -> Result<(), String> { + selector_parser::selector_list(input) + .map(|_| ()) + .map_err(|e| { + format!( + "Invalid selector at character {}: expected {}", + e.location.column, e.expected + ) + }) +} + impl SelectorList { pub fn parse(input: &str) -> Result { selector_parser::selector_list(input) @@ -344,6 +358,14 @@ impl AttributeSelector { mod tests { use super::*; + #[test] + fn test_validate() { + assert!(validate(r#":not([d^=" M 0.00 0.00 L 683.00 0.00"])"#).is_ok()); + assert!(validate(r"g > path:not(#\#fafafcff)").is_ok()); + let err = validate("g >").unwrap_err(); + assert!(err.starts_with("Invalid selector at character"), "{err}"); + } + #[test] fn test_parse() { // (selector, whether expected to parse successfully) diff --git a/star/src/lower/visit.rs b/star/src/lower/visit.rs index aa1931e6..72e8a181 100644 --- a/star/src/lower/visit.rs +++ b/star/src/lower/visit.rs @@ -297,7 +297,13 @@ impl<'a, 'input, T: Turtle> XmlVisitor<'a, 'input> for ConversionVisitor<'a, 'in .filter(|_| has_fill_attr) .and_then(|attr| resolve_url_ref(node.document(), attr)); - if has_stroke_attr { + // Plotters can't fill, so optionally trace the outline of filled shapes instead. + let outline_fill = self.config.fill_as_outline + && has_fill_attr + && !has_stroke_attr + && !node.has_tag_name(LINE_TAG_NAME); + + if has_stroke_attr || outline_fill { self.comment(); self.terrarium.apply_path(segments.iter().copied()); } diff --git a/star/src/turtle/cleanup.rs b/star/src/turtle/cleanup.rs new file mode 100644 index 00000000..4ee1c95d --- /dev/null +++ b/star/src/turtle/cleanup.rs @@ -0,0 +1,264 @@ +use lyon_geom::{LineSegment, Point}; + +use super::{ + Turtle, + elements::{DrawCommand, ExactArc, Shape, Stroke}, +}; + +/// Wrapper turtle that cleans up strokes (in millimeters) before passing them on. +/// +/// - Drops strokes smaller than [`crate::lower::ConversionConfig::min_shape_size`], e.g. dithering specks. +/// - Simplifies strokes to within [`crate::lower::ConversionConfig::simplify`], removing detail finer than the pen. +#[derive(Debug)] +pub struct CleanupTurtle { + inner: T, + min_shape_size: Option, + simplify: Option, +} + +impl CleanupTurtle { + pub fn new(inner: T, min_shape_size: Option, simplify: Option) -> Self { + Self { + inner, + min_shape_size: min_shape_size.filter(|v| *v > 0.), + simplify: simplify.filter(|v| *v > 0.), + } + } + + pub fn into_inner(self) -> T { + self.inner + } +} + +impl Turtle for CleanupTurtle { + fn begin(&mut self) { + self.inner.begin(); + } + + fn end(&mut self) { + self.inner.end(); + } + + #[cfg(feature = "image")] + fn image(&mut self, image: super::elements::RasterImage) { + self.inner.image(image); + } + + fn fill(&mut self, shape: Shape) { + self.inner.fill(shape); + } + + fn stroke(&mut self, stroke: Stroke) { + if let Some(min_size) = self.min_shape_size { + let bbox = stroke.bounding_box(); + if bbox.width().max(bbox.height()) < min_size { + return; + } + } + match self.simplify { + Some(epsilon) => self.inner.stroke(simplify_stroke(&stroke, epsilon)), + None => self.inner.stroke(stroke), + } + } +} + +/// Flattens `stroke` into a polyline and simplifies it with the Douglas–Peucker algorithm, +/// so every original point stays within `epsilon` of the result. +pub fn simplify_stroke(stroke: &Stroke, epsilon: f64) -> Stroke { + // Flatten finely enough that flattening error is small next to the simplification error. + let flatten_tolerance = epsilon / 10.; + let mut points = vec![stroke.start_point()]; + let mut push = |segment: &LineSegment| points.push(segment.to); + for command in stroke.commands() { + match command { + DrawCommand::LineTo(line) => push(line), + DrawCommand::Arc(arc) => arc + .to_exact_arc() + .for_each_flattened(flatten_tolerance, &mut push), + DrawCommand::CubicBezier(cbs) => cbs.for_each_flattened(flatten_tolerance, &mut push), + DrawCommand::QuadraticBezier(qbs) => { + qbs.for_each_flattened(flatten_tolerance, &mut push); + } + } + } + + let simplified = if stroke.is_closed() && points.len() > 3 { + // Douglas–Peucker needs distinct endpoints, so split the loop at the point farthest from the start. + let start = points[0]; + let farthest = (1..points.len() - 1) + .max_by(|&a, &b| { + (points[a] - start) + .square_length() + .total_cmp(&(points[b] - start).square_length()) + }) + .unwrap(); + let mut first = douglas_peucker(&points[..=farthest], epsilon); + let second = douglas_peucker(&points[farthest..], epsilon); + first.extend_from_slice(&second[1..]); + first + } else { + douglas_peucker(&points, epsilon) + }; + + let commands = simplified + .windows(2) + .map(|pair| { + DrawCommand::LineTo(LineSegment { + from: pair[0], + to: pair[1], + }) + }) + .collect(); + Stroke::new( + simplified[0], + commands, + stroke.comment().map(ToOwned::to_owned), + ) +} + +/// Keeps the endpoints and recursively keeps the point farthest from the chord while it is over `epsilon` away. +fn douglas_peucker(points: &[Point], epsilon: f64) -> Vec> { + if points.len() < 3 { + return points.to_vec(); + } + let mut keep = vec![false; points.len()]; + keep[0] = true; + keep[points.len() - 1] = true; + let mut ranges = vec![(0, points.len() - 1)]; + while let Some((first, last)) = ranges.pop() { + let chord = LineSegment { + from: points[first], + to: points[last], + }; + let (index, distance) = (first + 1..last) + .map(|i| (i, chord.distance_to_point(points[i]))) + .max_by(|a, b| a.1.total_cmp(&b.1)) + .unwrap_or((first, 0.)); + if distance > epsilon { + keep[index] = true; + ranges.push((first, index)); + ranges.push((index, last)); + } + } + points + .iter() + .zip(keep) + .filter_map(|(point, keep)| keep.then_some(*point)) + .collect() +} + +#[cfg(test)] +mod tests { + use lyon_geom::{CubicBezierSegment, point}; + + use super::*; + + fn polyline(points: &[(f64, f64)]) -> Stroke { + let points: Vec<_> = points.iter().map(|&(x, y)| point(x, y)).collect(); + Stroke::new( + points[0], + points + .windows(2) + .map(|p| { + DrawCommand::LineTo(LineSegment { + from: p[0], + to: p[1], + }) + }) + .collect(), + None, + ) + } + + fn vertices(stroke: &Stroke) -> Vec<(f64, f64)> { + std::iter::once(stroke.start_point()) + .chain(stroke.commands().iter().map(DrawCommand::end_point)) + .map(|p| (p.x, p.y)) + .collect() + } + + #[test] + fn wobble_below_epsilon_is_removed_and_corners_kept() { + // A wobbly line along the bottom, then a sharp corner up. + let stroke = polyline(&[ + (0., 0.), + (1., 0.05), + (2., -0.05), + (3., 0.05), + (4., 0.), + (4., 4.), + ]); + assert_eq!( + vertices(&simplify_stroke(&stroke, 0.1)), + vec![(0., 0.), (4., 0.), (4., 4.)] + ); + // Small epsilon keeps the wobble. + assert_eq!(vertices(&simplify_stroke(&stroke, 0.01)).len(), 6); + } + + #[test] + fn closed_square_stays_closed() { + let stroke = polyline(&[ + (0., 0.), + (5., 0.02), + (10., 0.), + (10., 10.), + (0., 10.), + (0., 0.), + ]); + let simplified = simplify_stroke(&stroke, 0.1); + assert!(simplified.is_closed()); + assert_eq!( + vertices(&simplified), + vec![(0., 0.), (10., 0.), (10., 10.), (0., 10.), (0., 0.)] + ); + } + + #[test] + fn curves_stay_within_epsilon() { + let curve = CubicBezierSegment { + from: point(0., 0.), + ctrl1: point(0., 10.), + ctrl2: point(10., 10.), + to: point(10., 0.), + }; + let stroke = Stroke::new(curve.from, vec![DrawCommand::CubicBezier(curve)], None); + let epsilon = 0.2; + let simplified = simplify_stroke(&stroke, epsilon); + assert!(simplified.commands().len() > 2); + for i in 0..=100 { + let p = curve.sample(f64::from(i) / 100.); + let distance = simplified + .commands() + .iter() + .map(|c| match c { + DrawCommand::LineTo(line) => line.distance_to_point(p), + _ => unreachable!(), + }) + .fold(f64::INFINITY, f64::min); + assert!(distance <= epsilon * 1.1 + 1e-9, "{p:?} is {distance} away"); + } + } + + #[derive(Debug, Default)] + struct Collect(Vec); + impl Turtle for Collect { + fn begin(&mut self) {} + fn end(&mut self) {} + fn fill(&mut self, _shape: Shape) {} + fn stroke(&mut self, stroke: Stroke) { + self.0.push(stroke); + } + #[cfg(feature = "image")] + fn image(&mut self, _image: crate::turtle::elements::RasterImage) {} + } + + #[test] + fn small_strokes_are_dropped_by_width_or_height() { + let mut turtle = CleanupTurtle::new(Collect::default(), Some(2.), None); + turtle.stroke(polyline(&[(0., 0.), (1., 1.)])); // 1 x 1: dropped + turtle.stroke(polyline(&[(0., 0.), (3., 0.5)])); // 3 wide: kept + turtle.stroke(polyline(&[(0., 0.), (0.1, 2.5)])); // 2.5 tall: kept + assert_eq!(turtle.into_inner().0.len(), 2); + } +} diff --git a/star/src/turtle/mod.rs b/star/src/turtle/mod.rs index 49215808..06f3e30b 100644 --- a/star/src/turtle/mod.rs +++ b/star/src/turtle/mod.rs @@ -15,6 +15,7 @@ use crate::turtle::elements::{DrawCommand, FillRule, Stroke, clip::ClipStack}; /// Intermediate representation of elements used by a [`Turtle`]. pub mod elements; +mod cleanup; mod collect; mod dpi; @@ -22,8 +23,8 @@ mod preprocess; mod svg_preview; pub use self::{ - collect::StrokeCollectingTurtle, dpi::DpiConvertingTurtle, preprocess::PreprocessTurtle, - svg_preview::SvgPreviewTurtle, + cleanup::CleanupTurtle, collect::StrokeCollectingTurtle, dpi::DpiConvertingTurtle, + preprocess::PreprocessTurtle, svg_preview::SvgPreviewTurtle, }; /// The coordinate system expected by a [`Turtle`] implementation. @@ -770,6 +771,91 @@ mod tests { } } + /// [`ConversionConfig::fit_to_area`] uniformly scales the drawing into the area at the origin. + #[test] + fn test_fit_to_area_scales_and_positions_drawing() { + #[derive(Debug, Default)] + struct BoundsTurtle { + bounds: Option>, + } + impl Turtle for BoundsTurtle { + fn begin(&mut self) {} + fn end(&mut self) {} + fn stroke(&mut self, stroke: Stroke) { + let b = stroke.bounding_box(); + self.bounds = Some(match self.bounds { + Some(old) => lyon_geom::Box2D::from_points([old.min, old.max, b.min, b.max]), + None => b, + }); + } + fn fill(&mut self, _shape: Shape) {} + #[cfg(feature = "image")] + fn image(&mut self, _image: super::elements::RasterImage) {} + } + + // A 40mm x 20mm rectangle offset inside a 100mm page. + let doc = roxmltree::Document::parse( + r#" + "#, + ) + .unwrap(); + + for (area, origin, expected_min, expected_max) in [ + // Width-limited: 40 -> 200 (scale 5), height becomes 100 + ( + [Some(200.), Some(150.)], + [Some(0.), Some(0.)], + point(0., 0.), + point(200., 100.), + ), + // Height-limited, scaling down: 20 -> 10 (scale 0.5) + ( + [Some(200.), Some(10.)], + [Some(5.), Some(7.)], + point(5., 7.), + point(25., 17.), + ), + // Only width constrained, empty origin axes treated as 0 + ( + [Some(80.), None], + [None, None], + point(0., 0.), + point(80., 40.), + ), + ] { + for shrink_only in [false, true] { + // Shrink-only keeps the 40mm x 20mm size when the drawing already fits. + let (expected_min, expected_max) = + if shrink_only && expected_max.x - expected_min.x > 40. { + (expected_min, expected_min + lyon_geom::vector(40., 20.)) + } else { + (expected_min, expected_max) + }; + let config = ConversionConfig { + fit_to_area: area, + fit_shrink_only: shrink_only, + origin, + ..ConversionConfig::default() + }; + let bounds = svg_to_turtle( + &doc, + &config, + ConversionOptions::default(), + BoundsTurtle::default(), + CoordinateSystem::YUp, + ) + .bounds + .unwrap(); + assert!( + (bounds.min - expected_min).length() < 1e-6 + && (bounds.max - expected_max).length() < 1e-6, + "{area:?} {origin:?} shrink_only={shrink_only}: expected {expected_min:?}..{expected_max:?}, got {bounds:?}" + ); + } + } + } + /// [`ConversionConfig::origin`] shifts overflowing geometry relative to the coordinate system. #[test] fn test_origin_adheres_to_coordinate_system() { diff --git a/star/src/turtle/preprocess.rs b/star/src/turtle/preprocess.rs index cf62661b..ac5e6dbd 100644 --- a/star/src/turtle/preprocess.rs +++ b/star/src/turtle/preprocess.rs @@ -7,6 +7,8 @@ use super::{Turtle, elements::Shape}; #[derive(Debug, Default)] pub struct PreprocessTurtle { bounding_box: Option>, + /// Bounding box of strokes only, i.e. what a plotter actually draws. + stroke_bounding_box: Option>, } impl PreprocessTurtle { @@ -14,11 +16,22 @@ impl PreprocessTurtle { self.bounding_box } - fn expand(&mut self, bbox: Box2D) { - self.bounding_box = Some(match self.bounding_box { + /// Bounding box of strokes only, falling back to the bounding box of everything when there are none. + /// + /// Used by [`crate::lower::ConversionConfig::fit_to_area`] since fills and images are not plotted. + pub fn into_stroke_bounding_box(self) -> Option> { + self.stroke_bounding_box.or(self.bounding_box) + } + + fn union(existing: Option>, bbox: Box2D) -> Box2D { + match existing { Some(existing) => Box2D::from_points([existing.min, existing.max, bbox.min, bbox.max]), None => bbox, - }); + } + } + + fn expand(&mut self, bbox: Box2D) { + self.bounding_box = Some(Self::union(self.bounding_box, bbox)); } } @@ -37,6 +50,8 @@ impl Turtle for PreprocessTurtle { } fn stroke(&mut self, stroke: super::elements::Stroke) { - self.expand(stroke.bounding_box()); + let bbox = stroke.bounding_box(); + self.stroke_bounding_box = Some(Self::union(self.stroke_bounding_box, bbox)); + self.expand(bbox); } } diff --git a/web/src/forms/help.rs b/web/src/forms/help.rs new file mode 100644 index 00000000..5b072414 --- /dev/null +++ b/web/src/forms/help.rs @@ -0,0 +1,96 @@ +//! Longer help for settings that need more than a one-line description. + +use yew::prelude::*; + +use crate::ui::Help; + +/// Help for [`super::inputs::SelectorFilterInput`]. +#[function_component(SelectorFilterHelp)] +pub fn selector_filter_help() -> Html { + let examples = [ + ( + ":not(#background)", + "Skip the element with id \"background\".", + ), + ( + "#layer1 *", + "Only convert what is inside the element with id \"layer1\".", + ), + ( + ":not(g#hidden *)", + "Skip everything inside the group with id \"hidden\".", + ), + ( + ":not([fill=\"#ffffff\"])", + "Skip white-filled shapes (with \"Draw outlines of filled shapes\").", + ), + ( + ":not(.guide, .cut)", + "Skip elements with class \"guide\" or \"cut\".", + ), + ( + ":not([d^=\" M 0.00 0.00 L 683.00 0.00\"])", + "Skip the path whose data starts with this text, i.e. a page-sized background.", + ), + ]; + + html! { + +

+ {"Only SVG elements matching this CSS selector are converted. Use "} + {":not(...)"} + {" to convert everything except what you list."} +

+ + { for examples.iter().map(|(selector, meaning)| html! { + + }) } +
{ *selector }{ *meaning }
+

{"Finding what to target"}

+
    +
  • {"In Inkscape, open Edit › XML Editor (Ctrl+Shift+X) and click a shape to see its id, class and attributes."}
  • +
  • {"In a browser, open the SVG file, right-click a shape and choose Inspect."}
  • +
  • {"Shapes from image tracing usually have no id. Match them by an attribute instead, such as "}{"[fill=...]"}{" or the start of their path data with "}{"[d^=...]"}{"."}
  • +
  • {"Ids containing special characters need a backslash before them. For example, the id \"#fafafcff\" is written "}{"#\\#fafafcff"}{"."}
  • +
+

{"Supported"}

+
    +
  • {"Tag names, "}{"#id"}{", "}{".class"}{", "}{"*"}
  • +
  • {"Attributes: "}{"[a]"}{" "}{"[a=v]"}{" "}{"[a^=v]"}{" starts with, "}{"[a$=v]"}{" ends with, "}{"[a*=v]"}{" contains"}
  • +
  • {"Inside "}{"a b"}{", directly inside "}{"a > b"}{", and lists "}{"a, b"}
  • +
  • {":not()"}{", "}{":is()"}{" and "}{":has()"}
  • +
+

{"Not supported: "}{":first-child"}{", "}{":nth-child()"}{", "}{"+"}{" and "}{"~"}{"."}

+

{"Leave the field empty to convert everything. An invalid selector is marked in red and Save stays disabled until it is fixed."}

+
+ } +} + +/// Help for [`super::inputs::MinShapeSizeInput`] and [`super::inputs::SimplifyInput`]. +#[function_component(CleanupHelp)] +pub fn cleanup_help() -> Html { + html! { + +

{"Both clean up drawings that have more detail than a pen can draw, such as images traced into SVG. Sizes are in millimeters on paper, after any scaling, so the same values work at any print size."}

+

{"Minimum shape size"}

+
    +
  • {"Skips each separate line whose width and height are both smaller than this. Each outline of a shape counts as one line, including the outlines of holes inside it."}
  • +
  • {"Use it to remove dithering specks and noise, which otherwise plot as many short, meaningless strokes."}
  • +
  • {"Try 1–3 mm. Values that are too large also remove real small details, such as the dots on an \"i\" or punctuation."}
  • +
+

{"Simplify"}

+
    +
  • {"Removes points while keeping every line within this distance of the original. Corners and the overall shape are kept."}
  • +
  • {"Use it to remove tracing wobble. G-Code files become much smaller and plotting is smoother and faster."}
  • +
  • {"Try about your pen width: 0.2–0.3 mm for a 0.3–0.5 mm pen. Larger values make curves look angular."}
  • +
  • {"Simplified lines are straight segments only, so \"Enable circular interpolation\" has no effect on them."}
  • +
  • {"Neighbouring shapes are simplified separately, so a shared edge can come out as two lines slightly apart. Use a smaller value if that shows."}
  • +
+

{"For traced images"}

+
    +
  • {"Tick \"Draw outlines of filled shapes\", then start with a minimum shape size of 2 mm and simplify at 0.3 mm."}
  • +
  • {"Save, compare the toolpath preview with the original, and adjust."}
  • +
+
+ } +} diff --git a/web/src/forms/inputs.rs b/web/src/forms/inputs.rs index 4d3af7e7..797d30d0 100644 --- a/web/src/forms/inputs.rs +++ b/web/src/forms/inputs.rs @@ -1,6 +1,8 @@ use std::num::ParseFloatError; use paste::paste; +use svg2star::lower::validate_selector_filter; +use web_sys::HtmlInputElement; use yew::prelude::*; use yewdux::functional::{use_store, use_store_value}; @@ -80,4 +82,100 @@ form_input! { origin => 1, settings.conversion.inner.origin => 1, } + FitAreaWidth { + "Fit to area width (mm)", + "Scale the drawing to fit within this width, preserving aspect ratio. Leave empty to disable.", + fit_to_area => 0, + settings.conversion.inner.fit_to_area => 0, + } + FitAreaHeight { + "Fit to area height (mm)", + "Scale the drawing to fit within this height, preserving aspect ratio. Leave empty to disable.", + fit_to_area => 1, + settings.conversion.inner.fit_to_area => 1, + } + BedWidth { + "Bed width (mm)", + "Width of the machine's bed, starting at X 0. Leave empty to skip checking.", + bed_size => 0, + settings.machine.bed_size => 0, + } + BedHeight { + "Bed height (mm)", + "Height of the machine's bed, starting at Y 0. Leave empty to skip checking.", + bed_size => 1, + settings.machine.bed_size => 1, + } +} + +/// CSS selector choosing which SVG elements are converted. Empty disables filtering. +#[function_component(SelectorFilterInput)] +pub fn selector_filter_input() -> Html { + let app_state = use_store_value::(); + let (form_state, form_dispatch) = use_store::(); + let oninput = form_dispatch.reduce_mut_callback_with(|state, event: InputEvent| { + let value = event.target_unchecked_into::().value(); + state.selector_filter = if value.trim().is_empty() { + None + } else { + Some(validate_selector_filter(&value).map(|()| value)) + }; + }); + html! { + + + label="Selector filter" + desc="Only convert SVG elements matching this CSS selector (supports :not, :is and :has). Leave empty to convert everything." + placeholder={Some(":not(#background)".to_owned())} + default={app_state.settings.conversion.inner.selector_filter.clone()} + parsed={form_state.selector_filter.clone()} + oninput={oninput} + /> + + } +} + +/// Defines inputs for optional millimeter settings, where an empty field means disabled. +macro_rules! optional_mm_input { + ($($name: ident { $label: literal, $desc: literal, $field: ident, })*) => { + $( + paste! { + #[function_component([<$name Input>])] + pub fn [<$name:snake:lower _input>]() -> Html { + let app_state = use_store_value::(); + let (form_state, form_dispatch) = use_store::(); + let oninput = form_dispatch.reduce_mut_callback_with(|state, event: InputEvent| { + let value = event.target_unchecked_into::().value(); + state.$field = if value.trim().is_empty() { + None + } else { + Some(value.trim().parse::()) + }; + }); + html! { + + label=$label desc=$desc + default={app_state.settings.conversion.inner.$field} + parsed={form_state.$field.clone()} + oninput={oninput} + /> + + } + } + } + )* + }; +} + +optional_mm_input! { + MinShapeSize { + "Minimum shape size (mm)", + "Skip paths smaller than this in both width and height, such as dithering specks. Leave empty to disable.", + min_shape_size, + } + Simplify { + "Simplify (mm)", + "Remove detail finer than this, such as tracing wobble. Around your pen width is a good start. Leave empty to disable.", + simplify, + } } diff --git a/web/src/forms/mod.rs b/web/src/forms/mod.rs index 725cd612..2fa90e26 100644 --- a/web/src/forms/mod.rs +++ b/web/src/forms/mod.rs @@ -22,10 +22,16 @@ use crate::{ }; mod editors; +mod help; mod inputs; use editors::{BeginSequenceInput, EndSequenceInput, ToolOffSequenceInput, ToolOnSequenceInput}; -use inputs::{DpiInput, FeedrateInput, OriginXInput, OriginYInput, ToleranceInput}; +use help::{CleanupHelp, SelectorFilterHelp}; +use inputs::{ + BedHeightInput, BedWidthInput, DpiInput, FeedrateInput, FitAreaHeightInput, FitAreaWidthInput, + MinShapeSizeInput, OriginXInput, OriginYInput, SelectorFilterInput, SimplifyInput, + ToleranceInput, +}; #[function_component(SettingsForm)] pub fn settings_form() -> Html { @@ -39,6 +45,11 @@ pub fn settings_form() -> Html { .origin .iter() .all(|opt| opt.as_ref().is_some_and(Result::is_err)) + || form_state + .fit_to_area + .iter() + .chain(form_state.bed_size.iter()) + .any(|opt| opt.as_ref().is_some_and(Result::is_err)) || form_state .tool_on_sequence .as_ref() @@ -51,7 +62,14 @@ pub fn settings_form() -> Html { .begin_sequence .as_ref() .is_some_and(Result::is_err) - || form_state.end_sequence.as_ref().is_some_and(Result::is_err); + || form_state.end_sequence.as_ref().is_some_and(Result::is_err) + || form_state + .selector_filter + .as_ref() + .is_some_and(Result::is_err) + || [&form_state.min_shape_size, &form_state.simplify] + .iter() + .any(|opt| opt.as_ref().is_some_and(Result::is_err)); let close_ref = use_node_ref(); @@ -68,6 +86,19 @@ pub fn settings_form() -> Html { form.optimize_path_order = event.target_unchecked_into::().checked(); }); + let on_fill_as_outline_change = form_dispatch.reduce_mut_callback_with(|form, event: Event| { + form.fill_as_outline = event.target_unchecked_into::().checked(); + }); + + let on_fit_shrink_only_change = form_dispatch.reduce_mut_callback_with(|form, event: Event| { + form.fit_shrink_only = event.target_unchecked_into::().checked(); + }); + + let on_bed_check_warn_only_change = + form_dispatch.reduce_mut_callback_with(|form, event: Event| { + form.bed_check_warn_only = event.target_unchecked_into::().checked(); + }); + let on_checksums_change = form_dispatch.reduce_mut_callback_with(|form, event: Event| { form.checksums = event.target_unchecked_into::().checked(); }); @@ -130,6 +161,38 @@ pub fn settings_form() -> Html {
+
+ +
+
+ +
+
+ + + +
+
+ +
+
+ +
+
+ + + +
Html { />
+
+ + + +
Html {
+
+ + +
+
+ +
+
+ +
+
+ +
diff --git a/web/src/main.rs b/web/src/main.rs index 887644cc..50f54974 100644 --- a/web/src/main.rs +++ b/web/src/main.rs @@ -14,7 +14,7 @@ use getrandom as _; // activate wasm_js backend for wasm32-unknown-unknown use js_sys::Date; use log::Level; use roxmltree::{Document, ParsingOptions}; -use svg2gcode::{Machine, svg_to_gcode}; +use svg2gcode::{Machine, check_bed_bounds, config::BedCheck, svg_to_gcode_with_bounds}; use svg2star::{ lower::{ConversionOptions, svg_to_turtle}, turtle::{CoordinateSystem, SvgPreviewTurtle}, @@ -65,6 +65,9 @@ fn app() -> Html { let mut zip = ZipWriter::new(Cursor::new(vec![])); let opts = SimpleFileOptions::default().compression_method(CompressionMethod::Stored); + let mut bed_messages = vec![]; + let mut zipped_files = 0; + if app_store.svgs.len() > 1 { zip.add_directory("svg2gcode_output", opts).unwrap(); } @@ -118,8 +121,31 @@ fn app() -> Html { ) .unwrap(); - let program = - svg_to_gcode(&document, &app_store.settings.conversion, options, machine); + let (program, bounds) = svg_to_gcode_with_bounds( + &document, + &app_store.settings.conversion, + options, + machine, + ); + + if let Err(out_of_bounds) = + check_bed_bounds(bounds, app_store.settings.machine.bed_size) + { + match app_store.settings.machine.bed_check { + BedCheck::Error => { + bed_messages.push(format!( + "{}: {out_of_bounds}. Skipped, no G-Code was generated.", + svg.filename + )); + continue; + } + BedCheck::Warn => { + log::warn!("{}: {out_of_bounds}", svg.filename); + bed_messages + .push(format!("Warning for {}: {out_of_bounds}.", svg.filename)); + } + } + } let filepath = if app_store.svgs.len() > 1 { PathBuf::from("svg2gcode_output") @@ -152,6 +178,7 @@ fn app() -> Html { prompt_download(filepath, gcode.as_bytes()); } _multiple => { + zipped_files += 1; zip.start_file(filepath.to_string_lossy(), opts).unwrap(); format_gcode_io( @@ -172,7 +199,17 @@ fn app() -> Html { } } - if app_store.svgs.len() > 1 { + if !bed_messages.is_empty() { + let message = format!( + "The drawing does not fit on the machine's bed.\n\n{}\n\nAdjust the bed size, origin, or fit to area in Settings.", + bed_messages.join("\n\n") + ); + if let Some(window) = web_sys::window() { + let _ = window.alert_with_message(&message); + } + } + + if app_store.svgs.len() > 1 && zipped_files > 0 { zip.set_comment(format!( "Created with svg2gcode: https://sameer.github.io/svg2gcode/\n{}", env!("CARGO_PKG_DESCRIPTION") diff --git a/web/src/state.rs b/web/src/state.rs index ec3cd34a..57bb08a4 100644 --- a/web/src/state.rs +++ b/web/src/state.rs @@ -2,7 +2,8 @@ use std::{convert::TryInto, num::ParseFloatError}; use serde::{Deserialize, Serialize}; use svg2gcode::config::{ - ConversionConfig, MachineConfig, PostprocessConfig, Settings, SupportedFunctionality, Version, + BedCheck, ConversionConfig, MachineConfig, PostprocessConfig, Settings, SupportedFunctionality, + Version, }; use svgtypes::Length; use thiserror::Error; @@ -25,6 +26,14 @@ pub struct FormState { pub line_numbers: bool, pub newline_before_comment: bool, pub starting_point: [Option>; 2], + pub fit_to_area: [Option>; 2], + pub fit_shrink_only: bool, + pub fill_as_outline: bool, + pub selector_filter: Option>, + pub min_shape_size: Option>, + pub simplify: Option>, + pub bed_size: [Option>; 2], + pub bed_check_warn_only: bool, } impl Default for FormState { @@ -40,6 +49,8 @@ pub enum FormStateConversionError { Float(#[from] ParseFloatError), #[error("could not parse gcode: {0}")] GCode(String), + #[error("{0}")] + Selector(String), } impl TryInto for &FormState { @@ -56,11 +67,23 @@ impl TryInto for &FormState { ], extra_attribute_name: None, optimize_path_order: self.optimize_path_order, - selector_filter: None, + selector_filter: self + .selector_filter + .clone() + .transpose() + .map_err(FormStateConversionError::Selector)?, starting_point: [ self.starting_point[0].clone().transpose()?, self.starting_point[1].clone().transpose()?, ], + fit_to_area: [ + self.fit_to_area[0].clone().transpose()?, + self.fit_to_area[1].clone().transpose()?, + ], + fit_shrink_only: self.fit_shrink_only, + fill_as_outline: self.fill_as_outline, + min_shape_size: self.min_shape_size.clone().transpose()?, + simplify: self.simplify.clone().transpose()?, }, tolerance: self.tolerance.clone()?, feedrate: self.feedrate.clone()?, @@ -89,6 +112,15 @@ impl TryInto for &FormState { .clone() .transpose() .map_err(FormStateConversionError::GCode)?, + bed_size: [ + self.bed_size[0].clone().transpose()?, + self.bed_size[1].clone().transpose()?, + ], + bed_check: if self.bed_check_warn_only { + BedCheck::Warn + } else { + BedCheck::Error + }, }, postprocess: PostprocessConfig { checksums: self.checksums, @@ -126,6 +158,20 @@ impl From<&Settings> for FormState { settings.conversion.inner.starting_point[0].map(Ok), settings.conversion.inner.starting_point[1].map(Ok), ], + fit_to_area: [ + settings.conversion.inner.fit_to_area[0].map(Ok), + settings.conversion.inner.fit_to_area[1].map(Ok), + ], + fit_shrink_only: settings.conversion.inner.fit_shrink_only, + fill_as_outline: settings.conversion.inner.fill_as_outline, + selector_filter: settings.conversion.inner.selector_filter.clone().map(Ok), + min_shape_size: settings.conversion.inner.min_shape_size.map(Ok), + simplify: settings.conversion.inner.simplify.map(Ok), + bed_size: [ + settings.machine.bed_size[0].map(Ok), + settings.machine.bed_size[1].map(Ok), + ], + bed_check_warn_only: settings.machine.bed_check == BedCheck::Warn, } } } diff --git a/web/src/ui/mod.rs b/web/src/ui/mod.rs index 40d3674c..e3b56661 100644 --- a/web/src/ui/mod.rs +++ b/web/src/ui/mod.rs @@ -690,3 +690,23 @@ pub fn card(props: &CardProps) -> Html {
} } + +#[derive(Properties, PartialEq, Clone)] +pub struct HelpProps { + pub title: &'static str, + #[prop_or_default] + pub children: Children, +} + +/// Collapsible help text, closed until clicked. +#[function_component(Help)] +pub fn help(props: &HelpProps) -> Html { + html! { +
+ { props.title } +
+ { for props.children.iter() } +
+
+ } +} diff --git a/web/style/main.scss b/web/style/main.scss index 42344df8..5e9dbef4 100644 --- a/web/style/main.scss +++ b/web/style/main.scss @@ -39,3 +39,57 @@ div.input-group, div.has-icon-right { flex: auto; } + +details.help { + margin: -0.2rem 0 0.8rem; + font-size: 0.7rem; + + summary { + cursor: pointer; + color: #5755d9; + user-select: none; + + &::before { + content: "? "; + font-weight: bold; + } + } + + .help-body { + margin-top: 0.4rem; + padding: 0.5rem 0.75rem; + border-left: 0.15rem solid #5755d9; + background: #f7f8f9; + + p, + ul { + margin: 0 0 0.5rem; + } + + li { + margin-top: 0.15rem; + } + + ul { + margin-left: 1rem; + } + + code { + white-space: pre-wrap; + word-break: break-all; + } + + table { + width: 100%; + margin-bottom: 0.5rem; + border-collapse: collapse; + font-size: inherit; + + td { + padding: 0.15rem 0.3rem; + vertical-align: top; + border-bottom: 1px solid #e7e9ed; + } + } + } +}