diff --git a/AGENTS.md b/AGENTS.md index 2c8246b4..ea3a23f4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -41,7 +41,7 @@ Releases: follow [the release procedure](docs/releasing.md) and `scripts/Publish - `OpenNest.Core`: domain (`Nest -> Plate -> Part -> Drawing -> CNC.Program`), geometry, cutting strategies and diagnostics. Angles are radians; use `Tolerance.Epsilon` for geometry comparisons. `OpenNest.Math` shadows `System.Math`, so qualify the latter. - `OpenNest.Engine`: whole-job API in `Jobs/`, interactive proposals via `PlateFillService`, fill strategies, best-fit pairs, packing, sequencing and rapid planning. `INestingEngine.Solve(NestJob)` returns stock IDs/poses; boundary adapters map drawings and materialize results. `NestJobRunner` validates its candidates before committing demand/stock accounting. Do not assume arbitrary plug-in output or interactive paths received that validation. Job identity is reference-based, not drawing-name-based. - Built-in whole-job engines live in `OpenNest.Engine/NestingEngines//`, named for the jobs they suit; see [nesting engines](docs/nesting-engines.md). A change must beat that engine's current benchmark result with every layout valid. External plug-ins implement `INestingEngine` with a public parameterless constructor and load from `Engines/` beside the host; keep their projects out of this solution. -- `OpenNest.IO`: ACadSharp import/export and ZIP-based `.nest` persistence; depends on Core only (an IO.Tests guard enforces it). Best fits persist only when callers pass `BestFitCacheStore.Shared` as `NestReader`/`NestWriter.BestFitStore`. All DXF-to-Drawing conversion goes through `CadImporter`: `Import` + `BuildDrawing` for editable/reporting flows, `ImportDrawing` for headless callers. Preserve source offsets, entity IDs, suppressed entities and bends. Bend repair is opt-in, requires explicit source units and may not alter cut geometry or unrelated marks. +- `OpenNest.IO`: ACadSharp and SVG import/export and ZIP-based `.nest` persistence; depends on Core only (an IO.Tests guard enforces it). Best fits persist only when callers pass `BestFitCacheStore.Shared` as `NestReader`/`NestWriter.BestFitStore`. All DXF-to-Drawing conversion goes through `CadImporter`: `Import` + `BuildDrawing` for editable/reporting flows, `ImportDrawing` for headless callers. Preserve source offsets, entity IDs, suppressed entities and bends. Bend repair is opt-in, requires explicit source units and may not alter cut geometry or unrelated marks. - `OpenNest`: WinForms UI (`Forms/`, `Controls/PlateView`, `Actions/`). `OpenNest.Data` holds cross-platform persistence; new-nest defaults live in `%APPDATA%\OpenNest\defaults.json` (in Database mode, the server's shared copy once it holds one). WinForms `Properties.Settings` persist to `%APPDATA%\OpenNest\user-settings.json` through `AppDataSettingsProvider`, never inside the Velopack install folder; `OpenNest.WinForms.Tests` redirects them to a temp file, so a test run never writes the user's settings. Posts live in `Posts/OpenNest.Posts./` and deploy to the desktop output's `Posts/` directory. Desktop nest edits go through `BeginChange`/`RecordChange`; see [undo and redo](docs/undo-redo.md). - `OpenNest.Desktop` (net8.0): toolkit-neutral desktop logic shared by the WinForms app and `OpenNest.Avalonia`, the cross-platform desktop in progress. It must not reference WinForms/WindowsDesktop, `System.Drawing.Common` or Avalonia (`OpenNest.Desktop.Tests` guards this, including transitive packages); put toolkit-specific rendering, dialogs and settings behind adapters in the front ends. - `OpenNest.Console`, `OpenNest.Mcp`, `OpenNest.Api`: front ends; `OpenNest.Benchmark`: whole-job engine comparisons; `OpenNest.Gpu`: GPU evaluators; `OpenNest.Training`: ML data collection and the Python sketch-search prototype (`sketch-search/README.md`). Benchmark timing comparisons require `--parallel 1`; validate layouts and fulfillment, not just elapsed time. @@ -64,6 +64,7 @@ Releases: follow [the release procedure](docs/releasing.md) and `scripts/Publish Read the relevant contract before changing its behavior: - [Nest file format](docs/nest-file-format.md) +- [SVG import and export](docs/svg-import-export.md): SVG numbers are not drawing units; import never guesses a scale - [Irregular stock](docs/irregular-stock.md): outlined sheets, what honors the outline and what refuses it - [Directional slides](docs/geometry/directional-slides.md) and [pair-spacing limits](docs/geometry/pair-spacing.md) - [Lead-in placement](docs/geometry/lead-in-placement.md) (including the planner's eroded pierce for cutouts too small for their lead-in and the stop at a feature's center line) and [pierce zones](docs/geometry/pierce-zone.md): opt-in `PierceDiameter` clearance, the hole pole fallback and the planner's perimeter scrap fallback diff --git a/OpenNest.Console/Program.cs b/OpenNest.Console/Program.cs index 9f8c450e..45cd4231 100644 --- a/OpenNest.Console/Program.cs +++ b/OpenNest.Console/Program.cs @@ -275,6 +275,9 @@ static class NestConsole _ => BendRepairUnits.Unspecified, }; break; + case "--svg-units-per-inch" when i + 1 < args.Length: + o.SvgUnitsPerInch = double.Parse(args[++i], CultureInfo.InvariantCulture); + break; case "--drawing" when i + 1 < args.Length: o.DrawingName = args[++i]; break; @@ -405,9 +408,10 @@ static class NestConsole return stock; } - static bool IsCadFile(string path) => - path.EndsWith(".dxf", StringComparison.OrdinalIgnoreCase) - || path.EndsWith(".dwg", StringComparison.OrdinalIgnoreCase); + static bool IsCadFile(string path) => CadFormats.IsCadFile(path); + + static Units DrawingUnits(Options options) => + options.CadUnits == BendRepairUnits.Millimeters ? Units.Millimeters : Units.Inches; static Nest LoadOrCreateNest(Options options) { @@ -453,7 +457,7 @@ static class NestConsole // DXF-only mode: create a fresh nest. if (dxfFiles.Count == 0) { - Console.Error.WriteLine("Error: no nest (.nest) or CAD (.dxf/.dwg) files specified"); + Console.Error.WriteLine("Error: no nest (.nest) or CAD (.dxf/.dwg/.svg) files specified"); return null; } @@ -500,8 +504,12 @@ static class NestConsole MaxEndpointMovementMillimeters = options.RepairBendsMillimeters.Value, } : null, + DrawingUnits = DrawingUnits(options), + SvgUserUnitsPerInch = options.SvgUnitsPerInch, } ); + foreach (var warning in result.Warnings) + Console.Error.WriteLine($"Warning: {Path.GetFileName(path)}: {warning}"); foreach (var report in result.BendRepairReports) Console.WriteLine( $"Bend repair {Path.GetFileName(path)} #{report.BendIndex + 1}: {report.Status}: {report.Reason} ({report.OriginalStart} -> {report.Start}; {report.OriginalEnd} -> {report.End})" @@ -551,7 +559,16 @@ static class NestConsole if (options.OutlineFile != null) { // The outline is the sheet: its bounds replace any size given. - plate.Outline = SheetOutline.FromGeometry(CadImporter.Import(options.OutlineFile).Entities); + plate.Outline = SheetOutline.FromGeometry( + CadImporter.Import( + options.OutlineFile, + new CadImportOptions + { + DrawingUnits = DrawingUnits(options), + SvgUserUnitsPerInch = options.SvgUnitsPerInch, + } + ).Entities + ); Console.WriteLine($"Outline: {options.OutlineFile} ({plate.Outline})"); } } @@ -1009,7 +1026,7 @@ static class NestConsole Usage: OpenNest.Console [options] Arguments: - input-files One or more .nest nest files or .dxf/.dwg drawing files + input-files One or more .nest nest files or .dxf/.dwg/.svg drawing files Modes: Load nest and fill (existing behavior) @@ -1018,7 +1035,9 @@ static class NestConsole Options: --repair-bends-mm Opt-in endpoint/tick repair, limit >0.001 to 3.175 physical mm - --cad-units inches|mm Explicit source coordinate units required for bend repair + --cad-units inches|mm Explicit source coordinate units required for bend repair; + also the units SVGs import in (default inches) + --svg-units-per-inch N SVG units per inch, for a file without a real-world size --drawing Drawing name to fill with (default: first drawing) --plate Plate index to fill (default: 0) --quantity Max parts to place (default: 0 = unlimited) @@ -1091,5 +1110,6 @@ static class NestConsole public bool AllPlates; public double? RepairBendsMillimeters; public BendRepairUnits CadUnits; + public double? SvgUnitsPerInch; } } diff --git a/OpenNest.IO/CadFormats.cs b/OpenNest.IO/CadFormats.cs new file mode 100644 index 00000000..f2671401 --- /dev/null +++ b/OpenNest.IO/CadFormats.cs @@ -0,0 +1,21 @@ +using System; +using System.IO; + +namespace OpenNest.IO +{ + /// The drawing file types reads. + public static class CadFormats + { + public const string OpenFileFilter = + "CAD Files (*.dxf;*.dwg;*.svg)|*.dxf;*.dwg;*.svg|" + + "DXF Files (*.dxf)|*.dxf|DWG Files (*.dwg)|*.dwg|SVG Files (*.svg)|*.svg"; + + public static bool IsCadFile(string path) + { + var extension = Path.GetExtension(path); + return extension.Equals(".dxf", StringComparison.OrdinalIgnoreCase) + || extension.Equals(".dwg", StringComparison.OrdinalIgnoreCase) + || extension.Equals(".svg", StringComparison.OrdinalIgnoreCase); + } + } +} diff --git a/OpenNest.IO/CadImportOptions.cs b/OpenNest.IO/CadImportOptions.cs index 8904712d..8e326bfb 100644 --- a/OpenNest.IO/CadImportOptions.cs +++ b/OpenNest.IO/CadImportOptions.cs @@ -34,6 +34,18 @@ namespace OpenNest.IO /// public string Customer { get; set; } + /// + /// The units of the drawing being built. An SVG's real-world size is converted to + /// these; DXF and DWG numbers are taken as they are. + /// + public Units DrawingUnits { get; set; } = Units.Inches; + + /// + /// How many of an SVG's user units make an inch, used only when the file does not state + /// its real-world size. Null makes such a file fail rather than guess its scale. + /// + public double? SvgUserUnitsPerInch { get; set; } + /// /// Returns a default options instance. /// diff --git a/OpenNest.IO/CadImportResult.cs b/OpenNest.IO/CadImportResult.cs index 46dfafa6..9da37b66 100644 --- a/OpenNest.IO/CadImportResult.cs +++ b/OpenNest.IO/CadImportResult.cs @@ -48,5 +48,10 @@ namespace OpenNest.IO /// that need access to non-geometry entities (e.g., text annotations). /// public CadDocument Document { get; set; } + + /// + /// Source content the import left out, worded for the user. + /// + public List Warnings { get; set; } = new List(); } } diff --git a/OpenNest.IO/CadImporter.cs b/OpenNest.IO/CadImporter.cs index 397c0a74..908726f1 100644 --- a/OpenNest.IO/CadImporter.cs +++ b/OpenNest.IO/CadImporter.cs @@ -29,7 +29,9 @@ namespace OpenNest.IO { options ??= CadImportOptions.Default; - var dxf = Dxf.Import(path, preserveRepairMarks: options.BendRepair != null); + var dxf = Svg.IsSvg(path) + ? Svg.Import(path, options) + : Dxf.Import(path, preserveRepairMarks: options.BendRepair != null); var cleanup = options.BendRepair == null @@ -91,6 +93,7 @@ namespace OpenNest.IO SourcePath = path, Name = options.Name ?? Path.GetFileNameWithoutExtension(path), Document = dxf.Document, + Warnings = dxf.Warnings, }; } diff --git a/OpenNest.IO/Dxf.cs b/OpenNest.IO/Dxf.cs index c78e15ab..0941ba76 100644 --- a/OpenNest.IO/Dxf.cs +++ b/OpenNest.IO/Dxf.cs @@ -217,7 +217,7 @@ namespace OpenNest.IO string.Equals(name, "ETCH", StringComparison.OrdinalIgnoreCase) || string.Equals(name, "SCRIBE", StringComparison.OrdinalIgnoreCase); - private static bool IsNonCutLayer(string layerName) + internal static bool IsNonCutLayer(string layerName) { // Etch/scribe marks are never cut geometry — drop them on default import. return string.Equals(layerName, "BEND", StringComparison.OrdinalIgnoreCase) diff --git a/OpenNest.IO/DxfImportResult.cs b/OpenNest.IO/DxfImportResult.cs index 3feaed70..7d1efe96 100644 --- a/OpenNest.IO/DxfImportResult.cs +++ b/OpenNest.IO/DxfImportResult.cs @@ -8,5 +8,6 @@ namespace OpenNest.IO { public List Entities { get; set; } = new(); public CadDocument Document { get; set; } + public List Warnings { get; set; } = new(); } } diff --git a/OpenNest.IO/Svg.cs b/OpenNest.IO/Svg.cs new file mode 100644 index 00000000..60b81da3 --- /dev/null +++ b/OpenNest.IO/Svg.cs @@ -0,0 +1,241 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Text; +using System.Xml.Linq; +using OpenNest.CNC; +using OpenNest.Converters; +using OpenNest.Geometry; +using OpenNest.Math; + +namespace OpenNest.IO +{ + /// + /// SVG import and export. Unlike a DXF, an SVG's numbers are not drawing units, so both + /// directions take the of the drawing; see docs/svg-import-export.md. + /// + public static class Svg + { + internal const string PlateLayerName = "PLATE"; + + private static readonly XNamespace Ns = "http://www.w3.org/2000/svg"; + + #region Import + + public static bool IsSvg(string path) => + Path.GetExtension(path).Equals(".svg", StringComparison.OrdinalIgnoreCase); + + /// + /// Imports an SVG in . Throws + /// when the file does not state its real-world size + /// and is not set: a guessed scale + /// would silently produce wrong-size parts. + /// + public static DxfImportResult Import(string path, CadImportOptions options) => + SvgReader.Read(path, options); + + /// + /// The file's width and height in its own numbers when it does not state its + /// real-world size, or null when it does and no scale is needed. + /// + public static (double Width, double Height)? UndeclaredSize(string path) => + SvgReader.UndeclaredSize(path); + + #endregion + + #region Export + + public static void ExportProgram(Program program, string path, Units units) + { + using var stream = File.Create(path); + ExportProgram(program, stream, units); + } + + public static void ExportProgram(Program program, Stream stream, Units units) => + ExportEntities(ConvertProgram.ToGeometry(program), stream, units); + + public static void ExportPlate(Plate plate, string path, Units units) + { + using var stream = File.Create(path); + ExportPlate(plate, stream, units); + } + + public static void ExportPlate(Plate plate, Stream stream, Units units) + { + var entities = PlateOutline(plate); + + foreach (var part in plate.Parts) + { + var geometry = ConvertProgram.ToGeometry(part.Program); + foreach (var entity in geometry) + entity.Offset(part.Location); + entities.AddRange(geometry); + } + + ExportEntities(entities, stream, units); + } + + /// + /// Writes entities as one group per layer, with the document's physical size stated in + /// so one user unit is exactly one drawing unit. + /// + public static void ExportEntities(IEnumerable entities, string path, Units units) + { + using var stream = File.Create(path); + ExportEntities(entities, stream, units); + } + + public static void ExportEntities(IEnumerable entities, Stream stream, Units units) + { + var list = entities.ToList(); + var bounds = list.Count > 0 ? list.GetBoundingBox() : new Box(0, 0, 1, 1); + // Half of each stroke falls outside the outermost geometry; keep it on the page. + var margin = System.Math.Max(System.Math.Max(bounds.Length, bounds.Width), 1) * 0.01; + + var left = bounds.Left - margin; + var top = -bounds.Top - margin; + var width = bounds.Length + margin * 2; + var height = bounds.Width + margin * 2; + var unit = UnitsHelper.GetShortString(units); + + var root = new XElement( + Ns + "svg", + new XAttribute("version", "1.1"), + new XAttribute("width", Number(width) + unit), + new XAttribute("height", Number(height) + unit), + new XAttribute( + "viewBox", + $"{Number(left)} {Number(top)} {Number(width)} {Number(height)}" + ), + new XAttribute("fill", "none") + ); + + foreach (var layer in list.GroupBy(e => e.Layer?.Name ?? Layer.Default.Name)) + root.Add(LayerGroup(layer.Key, layer.ToList())); + + new XDocument(new XDeclaration("1.0", "utf-8", null), root).Save(stream); + } + + private static XElement LayerGroup(string name, List entities) + { + var group = new XElement( + Ns + "g", + new XAttribute("data-layer", name), + new XAttribute("stroke", StrokeOf(name)), + new XAttribute("stroke-width", "1"), + new XAttribute("vector-effect", "non-scaling-stroke") + ); + + var data = new StringBuilder(); + var position = Vector.Invalid; + + foreach (var entity in entities) + { + switch (entity) + { + case Line line: + MoveTo(data, line.StartPoint, ref position); + data.Append($"L{Point(line.EndPoint)}"); + position = line.EndPoint; + break; + + case Arc arc when arc.StartPoint().DistanceTo(arc.EndPoint()) < Tolerance.Epsilon: + group.Add(CircleElement(arc.Center, arc.Radius)); + break; + + case Arc arc: + MoveTo(data, arc.StartPoint(), ref position); + var large = arc.SweepAngle() > System.Math.PI ? 1 : 0; + // The Y flip keeps how an arc looks, and SVG's positive sweep is clockwise. + var sweep = arc.IsReversed ? 1 : 0; + var radius = Number(arc.Radius); + data.Append($"A{radius} {radius} 0 {large} {sweep} {Point(arc.EndPoint())}"); + position = arc.EndPoint(); + break; + + case Circle circle: + group.Add(CircleElement(circle.Center, circle.Radius)); + break; + } + } + + if (data.Length > 0) + group.Add(new XElement(Ns + "path", new XAttribute("d", data.ToString()))); + + return group; + } + + private static void MoveTo(StringBuilder data, Vector point, ref Vector position) + { + if (!position.IsValid() || position.DistanceTo(point) >= Tolerance.Epsilon) + data.Append($"M{Point(point)}"); + position = point; + } + + private static XElement CircleElement(Vector center, double radius) => + new XElement( + Ns + "circle", + new XAttribute("cx", Number(center.X)), + new XAttribute("cy", Number(-center.Y)), + new XAttribute("r", Number(radius)) + ); + + private static string StrokeOf(string layer) + { + if (string.Equals(layer, SpecialLayers.Rapid.Name, StringComparison.OrdinalIgnoreCase)) + return "#808080"; + if (string.Equals(layer, SpecialLayers.Scribe.Name, StringComparison.OrdinalIgnoreCase)) + return "#c000c0"; + if (string.Equals(layer, PlateLayerName, StringComparison.OrdinalIgnoreCase)) + return "#0080c0"; + return "#000000"; + } + + private static string Point(Vector point) => $"{Number(point.X)} {Number(-point.Y)}"; + + private static string Number(double value) => + value.ToString("R", CultureInfo.InvariantCulture); + + private static List PlateOutline(Plate plate) + { + var entities = new List(); + if (plate.Quadrant < 1 || plate.Quadrant > 4) + return entities; + + var signX = plate.Quadrant is 1 or 4 ? 1 : -1; + var signY = plate.Quadrant is 1 or 2 ? 1 : -1; + var length = plate.Size.Length * signX; + var width = plate.Size.Width * signY; + var layer = new Layer(PlateLayerName) { IsVisible = true }; + + void Rectangle(double x1, double y1, double x2, double y2) + { + var corners = new[] + { + new Vector(x1, y1), + new Vector(x1, y2), + new Vector(x2, y2), + new Vector(x2, y1), + }; + for (var i = 0; i < corners.Length; i++) + entities.Add( + new Line(corners[i], corners[(i + 1) % corners.Length]) { Layer = layer } + ); + } + + Rectangle(0, 0, length, width); + Rectangle( + plate.EdgeSpacing.Left, + plate.EdgeSpacing.Bottom, + length - plate.EdgeSpacing.Right, + width - plate.EdgeSpacing.Top + ); + + return entities; + } + + #endregion + } +} diff --git a/OpenNest.IO/SvgReader.cs b/OpenNest.IO/SvgReader.cs new file mode 100644 index 00000000..92fe4bbf --- /dev/null +++ b/OpenNest.IO/SvgReader.cs @@ -0,0 +1,908 @@ +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; +using System.Xml; +using System.Xml.Linq; +using OpenNest.Geometry; +using OpenNest.Math; + +namespace OpenNest.IO +{ + /// + /// Converts an SVG file's path geometry into entities: centerlines only, since stroke + /// widths and fills do not describe a cut. Anything else is reported as a warning. + /// + internal sealed class SvgReader + { + private const double CssPixelsPerInch = 96; + private const double MillimetersPerInch = 25.4; + private const int MinCurveSegments = 8; + private const int MaxCurveSegments = 512; + + // Bounded so a hostile file's entities cannot expand without limit. + private const long MaxCharactersFromEntities = 1_000_000; + + private static readonly Regex Length = new Regex( + @"^\s*([+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?)\s*([a-zA-Z%]*)\s*$", + RegexOptions.CultureInvariant, + TimeSpan.FromSeconds(1) + ); + + private static readonly Regex HiddenStyle = new Regex( + @"(?:^|;)\s*(?:display\s*:\s*none|visibility\s*:\s*(?:hidden|collapse))", + RegexOptions.CultureInvariant | RegexOptions.IgnoreCase, + TimeSpan.FromSeconds(1) + ); + + private static readonly HashSet IgnoredElements = new HashSet + { + "clipPath", "defs", "desc", "filter", "linearGradient", "marker", "mask", + "metadata", "pattern", "radialGradient", "script", "style", "symbol", "title", + }; + + private readonly XElement root; + private readonly double tolerance; + private readonly XNamespace svgNamespace; + private readonly Dictionary elementsById; + private readonly Dictionary layers = new Dictionary( + StringComparer.OrdinalIgnoreCase + ); + private readonly Dictionary skipped = new Dictionary(); + private readonly List lines = new List(); + private readonly List arcs = new List(); + private readonly List circles = new List(); + private readonly HashSet activeUses = new HashSet(); + + private SvgReader(XElement root, double tolerance) + { + this.root = root; + this.tolerance = tolerance; + svgNamespace = root.Name.Namespace; + elementsById = root + .DescendantsAndSelf() + .Where(e => e.Attribute("id") != null) + .GroupBy(e => e.Attribute("id").Value) + .ToDictionary(g => g.Key, g => g.First()); + } + + public static DxfImportResult Read(string path, CadImportOptions options) + { + var root = Load(path); + var perInch = DrawingUnitsPerInch(options.DrawingUnits); + var scale = DeclaredScale(root) + ?? ExplicitScale(options.SvgUserUnitsPerInch) + ?? throw new InvalidDataException( + $"\"{Path.GetFileName(path)}\" does not state its real-world size, " + + "so its scale would be a guess. Choose how many of its units make an inch." + ); + + var tolerance = options.DrawingUnits == Units.Millimeters ? 0.025 : 0.001; + var reader = new SvgReader(root, tolerance); + var transform = SvgTransform.Scale(scale.X * perInch, -scale.Y * perInch); + return reader.Convert(transform); + } + + public static (double Width, double Height)? UndeclaredSize(string path) + { + var root = Load(path); + if (DeclaredScale(root) != null) + return null; + + var entities = new SvgReader(root, 0.001) + .Convert(SvgTransform.Scale(1, -1)) + .Entities; + if (entities.Count == 0) + return (0, 0); + + var bounds = entities.GetBoundingBox(); + return (bounds.Length, bounds.Width); + } + + private static XElement Load(string path) + { + // Older Illustrator files declare their namespaces as DTD entities, so a DTD has to + // parse; it just may not fetch anything or expand without limit. + var settings = new XmlReaderSettings + { + DtdProcessing = DtdProcessing.Parse, + XmlResolver = null, + MaxCharactersFromEntities = MaxCharactersFromEntities, + }; + + try + { + using var reader = XmlReader.Create(path, settings); + var root = XDocument.Load(reader).Root; + if (root?.Name.LocalName != "svg") + throw new InvalidDataException($"\"{Path.GetFileName(path)}\" is not an SVG file."); + return root; + } + catch (XmlException ex) + { + throw new InvalidDataException( + $"\"{Path.GetFileName(path)}\" is not valid SVG: {ex.Message}", + ex + ); + } + } + + private static double DrawingUnitsPerInch(Units units) => + units == Units.Millimeters ? MillimetersPerInch : 1; + + private static Vector? ExplicitScale(double? userUnitsPerInch) + { + if (userUnitsPerInch == null) + return null; + if (!(userUnitsPerInch > 0) || double.IsInfinity(userUnitsPerInch.Value)) + throw new ArgumentOutOfRangeException( + nameof(userUnitsPerInch), + userUnitsPerInch, + "SVG units per inch must be positive." + ); + return new Vector(1 / userUnitsPerInch.Value, 1 / userUnitsPerInch.Value); + } + + /// + /// Inches per user unit, from the root's width and height. Only absolute units count: + /// "px" is left out because applications disagree on what it means (a CSS pixel is + /// 1/96 in, but Illustrator writes px at 72 per inch). + /// + private static Vector? DeclaredScale(XElement root) + { + var width = PhysicalInches(root.Attribute("width")?.Value); + var height = PhysicalInches(root.Attribute("height")?.Value); + if (width == null && height == null) + return null; + + var viewBox = ParseViewBox(root.Attribute("viewBox")?.Value); + if (viewBox == null) + return new Vector(1 / CssPixelsPerInch, 1 / CssPixelsPerInch); + + var scaleX = width / viewBox.Value.Width; + var scaleY = height / viewBox.Value.Height; + var aspect = root.Attribute("preserveAspectRatio")?.Value.Trim() ?? string.Empty; + if (scaleX != null && scaleY != null && aspect.StartsWith("none", StringComparison.Ordinal)) + return new Vector(scaleX.Value, scaleY.Value); + + // The default aspect handling fits the view box uniformly inside the page. + var scale = System.Math.Min(scaleX ?? double.MaxValue, scaleY ?? double.MaxValue); + return new Vector(scale, scale); + } + + private static double? PhysicalInches(string text) + { + if (text == null) + return null; + var match = Length.Match(text); + if (!match.Success) + return null; + + var value = double.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture); + if (value <= 0) + return null; + + return match.Groups[2].Value switch + { + "in" => value, + "cm" => value / 2.54, + "mm" => value / MillimetersPerInch, + "Q" => value / (MillimetersPerInch * 4), + "pt" => value / 72, + "pc" => value / 6, + _ => null, + }; + } + + private static (double Width, double Height)? ParseViewBox(string text) + { + if (string.IsNullOrWhiteSpace(text)) + return null; + var values = ParseNumbers(text); + return values.Length == 4 && values[2] > 0 && values[3] > 0 + ? (values[2], values[3]) + : null; + } + + internal static double[] ParseNumbers(string text) + { + var scanner = new PathScanner(text); + var values = new List(); + while (scanner.HasNumber) + values.Add(scanner.ReadNumber()); + return values.ToArray(); + } + + private DxfImportResult Convert(SvgTransform transform) + { + WalkChildren(root, transform, Layer.Default); + + GeometryOptimizer.Optimize(lines); + GeometryOptimizer.Optimize(arcs); + GeometryOptimizer.Deduplicate(circles); + GeometryOptimizer.Deduplicate(circles, arcs); + + var entities = new List(); + entities.AddRange(circles); + entities.AddRange(lines); + entities.AddRange(arcs); + + return new DxfImportResult + { + Entities = entities, + Warnings = skipped + .OrderBy(s => s.Key, StringComparer.Ordinal) + .Select(s => $"Skipped {s.Value} <{s.Key}> element(s); convert them to paths to import them.") + .ToList(), + }; + } + + private void WalkChildren(XElement parent, SvgTransform transform, Layer layer) + { + foreach (var child in parent.Elements()) + Walk(child, transform, layer); + } + + private void Walk(XElement element, SvgTransform parent, Layer parentLayer) + { + if (element.Name.Namespace != svgNamespace) + return; + + var name = element.Name.LocalName; + if (IgnoredElements.Contains(name) || IsHidden(element)) + return; + + var transform = parent.Then(SvgTransform.Parse(element.Attribute("transform")?.Value)); + switch (name) + { + case "g": + case "a": + case "switch": + var layer = LayerOf(element, parentLayer); + if (!IsSkippedLayer(layer.Name)) + WalkChildren(element, transform, layer); + break; + + case "use": + WalkUse(element, transform, parentLayer); + break; + + case "path": + ReadPath(element.Attribute("d")?.Value, transform, parentLayer); + break; + + case "rect": + ReadShape(element, RectPath(element), transform, parentLayer); + break; + + case "line": + ReadShape(element, LinePath(element), transform, parentLayer); + break; + + case "polyline": + ReadPath(PointsPath(element, close: false), transform, parentLayer); + break; + + case "polygon": + ReadPath(PointsPath(element, close: true), transform, parentLayer); + break; + + case "circle": + ReadEllipse(element, Measure(element, "r"), Measure(element, "r"), transform, parentLayer); + break; + + case "ellipse": + ReadEllipse(element, Measure(element, "rx"), Measure(element, "ry"), transform, parentLayer); + break; + + default: + Skip(name); + break; + } + } + + private void Skip(string name) + { + skipped.TryGetValue(name, out var count); + skipped[name] = count + 1; + } + + private static bool IsHidden(XElement element) + { + var style = element.Attribute("style")?.Value; + return element.Attribute("display")?.Value.Trim() == "none" + || element.Attribute("visibility")?.Value.Trim() is "hidden" or "collapse" + || (style != null && HiddenStyle.IsMatch(style)); + } + + /// + /// A group names a layer through OpenNest's data-layer, an Inkscape layer label, or an + /// id on a top-level group (how Illustrator writes its layers). + /// + private Layer LayerOf(XElement group, Layer parent) + { + var name = group.Attribute("data-layer")?.Value; + name ??= group.Attributes().FirstOrDefault(a => a.Name.LocalName == "groupmode") != null + ? group.Attributes().FirstOrDefault(a => a.Name.LocalName == "label")?.Value + : null; + if (name == null && group.Parent == root) + name = group.Attribute("id")?.Value; + if (string.IsNullOrWhiteSpace(name)) + return parent; + + if (!layers.TryGetValue(name, out var layer)) + { + layer = new Layer(name) { Color = Color.White, IsVisible = true }; + layers.Add(name, layer); + } + + return layer; + } + + // Rapids and the plate outline are what OpenNest's own export adds around the part. + private static bool IsSkippedLayer(string name) => + Dxf.IsNonCutLayer(name) + || string.Equals(name, SpecialLayers.Rapid.Name, StringComparison.OrdinalIgnoreCase) + || string.Equals(name, Svg.PlateLayerName, StringComparison.OrdinalIgnoreCase); + + private void WalkUse(XElement use, SvgTransform transform, Layer layer) + { + var href = use.Attributes().FirstOrDefault(a => a.Name.LocalName == "href")?.Value; + if (href == null || !href.StartsWith('#') + || !elementsById.TryGetValue(href[1..], out var target)) + return; + + if (target.Name.LocalName == "symbol" || !activeUses.Add(use)) + { + Skip("use"); + return; + } + + var placed = transform.Then(SvgTransform.Translate( + Measure(use, "x") ?? 0, + Measure(use, "y") ?? 0 + )); + Walk(target, placed, layer); + activeUses.Remove(use); + } + + /// The attribute in user units, or null when missing or relative to the viewport. + private static double? Measure(XElement element, string attribute) + { + var text = element.Attribute(attribute)?.Value; + if (text == null) + return null; + var match = Length.Match(text); + if (!match.Success) + return null; + + var value = double.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture); + return match.Groups[2].Value switch + { + "" or "px" => value, + "in" => value * CssPixelsPerInch, + "cm" => value * CssPixelsPerInch / 2.54, + "mm" => value * CssPixelsPerInch / MillimetersPerInch, + "Q" => value * CssPixelsPerInch / (MillimetersPerInch * 4), + "pt" => value * CssPixelsPerInch / 72, + "pc" => value * CssPixelsPerInch / 6, + _ => null, + }; + } + + private static bool HasRelativeSize(XElement element, params string[] attributes) => + attributes.Any(a => element.Attribute(a) != null && Measure(element, a) == null); + + private void ReadShape(XElement element, string data, SvgTransform transform, Layer layer) + { + if (data == null) + Skip(element.Name.LocalName); + else + ReadPath(data, transform, layer); + } + + private static string RectPath(XElement rect) + { + if (HasRelativeSize(rect, "x", "y", "width", "height", "rx", "ry")) + return null; + + var x = Measure(rect, "x") ?? 0; + var y = Measure(rect, "y") ?? 0; + var width = Measure(rect, "width") ?? 0; + var height = Measure(rect, "height") ?? 0; + if (width <= 0 || height <= 0) + return string.Empty; + + var rx = Measure(rect, "rx") ?? Measure(rect, "ry") ?? 0; + var ry = Measure(rect, "ry") ?? rx; + rx = System.Math.Min(rx, width / 2); + ry = System.Math.Min(ry, height / 2); + + var data = new StringBuilder(); + void Add(FormattableString text) => data.Append(FormattableString.Invariant(text)); + + if (rx <= 0 || ry <= 0) + { + Add($"M{x:R} {y:R}H{x + width:R}V{y + height:R}H{x:R}Z"); + return data.ToString(); + } + + var corner = FormattableString.Invariant($"A{rx:R} {ry:R} 0 0 1 "); + Add($"M{x + rx:R} {y:R}H{x + width - rx:R}"); + data.Append(corner); + Add($"{x + width:R} {y + ry:R}V{y + height - ry:R}"); + data.Append(corner); + Add($"{x + width - rx:R} {y + height:R}H{x + rx:R}"); + data.Append(corner); + Add($"{x:R} {y + height - ry:R}V{y + ry:R}"); + data.Append(corner); + Add($"{x + rx:R} {y:R}Z"); + return data.ToString(); + } + + private static string LinePath(XElement line) + { + if (HasRelativeSize(line, "x1", "y1", "x2", "y2")) + return null; + + var x1 = Measure(line, "x1") ?? 0; + var y1 = Measure(line, "y1") ?? 0; + var x2 = Measure(line, "x2") ?? 0; + var y2 = Measure(line, "y2") ?? 0; + return FormattableString.Invariant($"M{x1:R} {y1:R}L{x2:R} {y2:R}"); + } + + private static string PointsPath(XElement element, bool close) + { + var points = element.Attribute("points")?.Value; + if (string.IsNullOrWhiteSpace(points)) + return null; + + // Point lists use the same number grammar as path data. + return "M" + points + (close ? "Z" : string.Empty); + } + + private void ReadEllipse( + XElement element, + double? rx, + double? ry, + SvgTransform transform, + Layer layer + ) + { + if (rx == null || ry == null || HasRelativeSize(element, "cx", "cy")) + { + Skip(element.Name.LocalName); + return; + } + + if (rx <= 0 || ry <= 0) + return; + + var center = new Vector(Measure(element, "cx") ?? 0, Measure(element, "cy") ?? 0); + if (rx.Value.IsEqualTo(ry.Value) && transform.IsSimilarity) + AddCircle(transform.Apply(center), rx.Value * transform.ScaleFactor, layer); + else + AddEllipticalArc(center, rx.Value, ry.Value, 0, 0, Angle.TwoPI, transform, layer); + } + + private void AddCircle(Vector center, double radius, Layer layer) => + circles.Add(Tag(new Circle(center, radius), layer)); + + private void ReadPath(string data, SvgTransform t, Layer layer) + { + if (string.IsNullOrWhiteSpace(data)) + return; + + var scanner = new PathScanner(data); + var current = Vector.Zero; + var start = Vector.Zero; + var control = Vector.Zero; + var previous = '\0'; + var command = '\0'; + + while (true) + { + if (!scanner.HasCommand && !scanner.HasNumber) + break; + + if (scanner.HasCommand) + command = scanner.ReadCommand(); + else if (command is '\0' or 'Z' or 'z') + throw scanner.Error(); + else if (command == 'M') + command = 'L'; + else if (command == 'm') + command = 'l'; + + if (previous == '\0' && command is not ('M' or 'm')) + throw scanner.Error(); + + var relative = char.IsLower(command); + var origin = relative ? current : Vector.Zero; + + Vector Next() => scanner.ReadPoint() + origin; + + switch (char.ToUpperInvariant(command)) + { + case 'M': + current = start = Next(); + break; + + case 'Z': + AddLine(current, start, t, layer); + current = start; + break; + + case 'L': + { + var end = Next(); + AddLine(current, end, t, layer); + current = end; + break; + } + + case 'H': + { + var end = new Vector(scanner.ReadNumber() + origin.X, current.Y); + AddLine(current, end, t, layer); + current = end; + break; + } + + case 'V': + { + var end = new Vector(current.X, scanner.ReadNumber() + origin.Y); + AddLine(current, end, t, layer); + current = end; + break; + } + + case 'C': + { + var c1 = Next(); + control = Next(); + var end = Next(); + AddCubic(current, c1, control, end, t, layer); + current = end; + break; + } + + case 'S': + { + var c1 = previous is 'C' or 'c' or 'S' or 's' + ? current * 2 - control + : current; + control = Next(); + var end = Next(); + AddCubic(current, c1, control, end, t, layer); + current = end; + break; + } + + case 'Q': + { + control = Next(); + var end = Next(); + AddQuadratic(current, control, end, t, layer); + current = end; + break; + } + + case 'T': + { + control = previous is 'Q' or 'q' or 'T' or 't' + ? current * 2 - control + : current; + var end = Next(); + AddQuadratic(current, control, end, t, layer); + current = end; + break; + } + + case 'A': + { + var rx = System.Math.Abs(scanner.ReadNumber()); + var ry = System.Math.Abs(scanner.ReadNumber()); + var rotation = scanner.ReadNumber() * System.Math.PI / 180; + var large = scanner.ReadFlag(); + var sweep = scanner.ReadFlag(); + var end = Next(); + AddSvgArc(current, rx, ry, rotation, large, sweep, end, t, layer); + current = end; + break; + } + + default: + throw scanner.Error(); + } + + previous = command; + } + } + + private void AddLine(Vector from, Vector to, SvgTransform t, Layer layer) + { + var start = t.Apply(from); + var end = t.Apply(to); + if (start.DistanceTo(end) >= Tolerance.Epsilon) + lines.Add(Tag(new Line(start, end), layer)); + } + + private void AddQuadratic(Vector p0, Vector c, Vector p1, SvgTransform t, Layer layer) => + AddCubic(p0, p0 + (c - p0) * (2.0 / 3), p1 + (c - p1) * (2.0 / 3), p1, t, layer); + + /// + /// Samples the curve within half the tolerance and fits arcs and lines through the + /// samples within the other half, so the result stays within the tolerance. + /// + private void AddCubic(Vector p0, Vector c1, Vector c2, Vector p1, SvgTransform t, Layer layer) + { + var a = t.Apply(p0); + var b = t.Apply(c1); + var c = t.Apply(c2); + var d = t.Apply(p1); + + var bend = System.Math.Max(Length2(a - b * 2 + c), Length2(b - c * 2 + d)); + if (bend < Tolerance.Epsilon) + { + AddLine(p0, p1, t, layer); + return; + } + + // A cubic's chord error over n segments is at most 6 * bend / (8 * n^2). + var segments = (int)System.Math.Ceiling(System.Math.Sqrt(6 * bend / (8 * (tolerance / 2)))); + segments = System.Math.Clamp(segments, MinCurveSegments, MaxCurveSegments); + + var points = new List(segments + 1) { a }; + for (var i = 1; i < segments; i++) + { + var u = (double)i / segments; + var v = 1 - u; + points.Add( + a * (v * v * v) + b * (3 * v * v * u) + c * (3 * v * u * u) + d * (u * u * u) + ); + } + points.Add(d); + + AddFitted(SplineConverter.Convert(points, false, tolerance / 2), layer); + } + + private static double Length2(Vector v) => System.Math.Sqrt(v.X * v.X + v.Y * v.Y); + + /// The SVG endpoint-to-center arc conversion (SVG 2 appendix B.2.4). + private void AddSvgArc( + Vector from, + double rx, + double ry, + double rotation, + bool large, + bool sweep, + Vector to, + SvgTransform t, + Layer layer + ) + { + if (from.DistanceTo(to) < Tolerance.Epsilon) + return; + + if (rx < Tolerance.Epsilon || ry < Tolerance.Epsilon) + { + AddLine(from, to, t, layer); + return; + } + + var cos = System.Math.Cos(rotation); + var sin = System.Math.Sin(rotation); + var halfX = (from.X - to.X) / 2; + var halfY = (from.Y - to.Y) / 2; + var x = cos * halfX + sin * halfY; + var y = -sin * halfX + cos * halfY; + + // Radii too small to reach both endpoints scale up until they just do. + var fit = x * x / (rx * rx) + y * y / (ry * ry); + if (fit > 1) + { + rx *= System.Math.Sqrt(fit); + ry *= System.Math.Sqrt(fit); + } + + var numerator = rx * rx * ry * ry - rx * rx * y * y - ry * ry * x * x; + var denominator = rx * rx * y * y + ry * ry * x * x; + var factor = System.Math.Sqrt(System.Math.Max(0, numerator / denominator)); + if (large == sweep) + factor = -factor; + + var centerX = factor * rx * y / ry; + var centerY = -factor * ry * x / rx; + var center = new Vector( + cos * centerX - sin * centerY + (from.X + to.X) / 2, + sin * centerX + cos * centerY + (from.Y + to.Y) / 2 + ); + + var startAngle = System.Math.Atan2((y - centerY) / ry, (x - centerX) / rx); + var endAngle = System.Math.Atan2((-y - centerY) / ry, (-x - centerX) / rx); + var delta = endAngle - startAngle; + if (sweep && delta < 0) + delta += Angle.TwoPI; + else if (!sweep && delta > 0) + delta -= Angle.TwoPI; + + AddEllipticalArc(center, rx, ry, rotation, startAngle, delta, t, layer); + } + + /// + /// Adds part of an ellipse after the transform, which can change its axes: the output + /// axes are where the transformed ellipse is widest and narrowest, then the parameter + /// is shifted to them and mirrored when the transform flipped the ellipse's direction. + /// + private void AddEllipticalArc( + Vector center, + double rx, + double ry, + double rotation, + double start, + double delta, + SvgTransform t, + Layer layer + ) + { + var cos = System.Math.Cos(rotation); + var sin = System.Math.Sin(rotation); + var axisX = t.ApplyLinear(new Vector(rx * cos, rx * sin)); + var axisY = t.ApplyLinear(new Vector(-ry * sin, ry * cos)); + + var offset = 0.5 * System.Math.Atan2( + 2 * (axisX.X * axisY.X + axisX.Y * axisY.Y), + axisX.X * axisX.X + axisX.Y * axisX.Y - axisY.X * axisY.X - axisY.Y * axisY.Y + ); + var major = axisX * System.Math.Cos(offset) + axisY * System.Math.Sin(offset); + var minor = axisY * System.Math.Cos(offset) - axisX * System.Math.Sin(offset); + + var semiMajor = Length2(major); + var semiMinor = Length2(minor); + if (semiMajor < Tolerance.Epsilon || semiMinor < Tolerance.Epsilon) + return; + + var direction = major.X * minor.Y - major.Y * minor.X >= 0 ? 1 : -1; + var from = direction * (start - offset); + var to = direction * (start + delta - offset); + + AddFitted( + EllipseConverter.Convert( + t.Apply(center), + semiMajor, + semiMinor, + System.Math.Atan2(major.Y, major.X), + System.Math.Min(from, to), + System.Math.Max(from, to), + tolerance + ), + layer + ); + } + + private void AddFitted(List entities, Layer layer) + { + foreach (var entity in entities) + { + if (entity is Line line) + lines.Add(Tag(line, layer)); + else if (entity is Arc arc) + arcs.Add(Tag(arc, layer)); + } + } + + private static T Tag(T entity, Layer layer) + where T : Entity + { + entity.Layer = layer; + entity.Color = layer.Color; + return entity; + } + + /// Reads SVG's number grammar, where separators are optional ("1-2.5.5"). + private sealed class PathScanner + { + private readonly string text; + private int position; + + public PathScanner(string text) + { + this.text = text; + } + + public bool HasCommand + { + get + { + SkipSeparators(); + return position < text.Length && char.IsAsciiLetter(text[position]); + } + } + + public bool HasNumber + { + get + { + SkipSeparators(); + return position < text.Length + && (char.IsAsciiDigit(text[position]) || text[position] is '+' or '-' or '.'); + } + } + + public char ReadCommand() => text[position++]; + + public InvalidDataException Error() => + new InvalidDataException($"Malformed SVG path data at position {position}."); + + public Vector ReadPoint() + { + var x = ReadNumber(); + var y = ReadNumber(); + return new Vector(x, y); + } + + public bool ReadFlag() + { + SkipSeparators(); + if (position >= text.Length || text[position] is not ('0' or '1')) + throw Error(); + return text[position++] == '1'; + } + + public double ReadNumber() + { + SkipSeparators(); + var begin = position; + + if (position < text.Length && text[position] is '+' or '-') + position++; + var digits = SkipDigits(); + if (position < text.Length && text[position] == '.') + { + position++; + digits += SkipDigits(); + } + if (digits == 0) + throw Error(); + + if (position < text.Length && text[position] is 'e' or 'E') + { + var mark = position++; + if (position < text.Length && text[position] is '+' or '-') + position++; + if (SkipDigits() == 0) + position = mark; + } + + return double.Parse( + text.AsSpan(begin, position - begin), + NumberStyles.Float, + CultureInfo.InvariantCulture + ); + } + + private int SkipDigits() + { + var begin = position; + while (position < text.Length && char.IsAsciiDigit(text[position])) + position++; + return position - begin; + } + + private void SkipSeparators() + { + while ( + position < text.Length + && (char.IsWhiteSpace(text[position]) || text[position] == ',') + ) + position++; + } + } + } +} diff --git a/OpenNest.IO/SvgTransform.cs b/OpenNest.IO/SvgTransform.cs new file mode 100644 index 00000000..c8d21c1d --- /dev/null +++ b/OpenNest.IO/SvgTransform.cs @@ -0,0 +1,137 @@ +using System; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Text.RegularExpressions; +using OpenNest.Geometry; + +namespace OpenNest.IO +{ + /// An SVG affine matrix: x' = A*x + C*y + E, y' = B*x + D*y + F. + internal readonly struct SvgTransform + { + private const double SimilarityTolerance = 1e-9; + + private static readonly Regex Function = new Regex( + @"([a-zA-Z]+)\s*\(([^)]*)\)", + RegexOptions.CultureInvariant, + TimeSpan.FromSeconds(1) + ); + + public static readonly SvgTransform Identity = new SvgTransform(1, 0, 0, 1, 0, 0); + + public SvgTransform(double a, double b, double c, double d, double e, double f) + { + A = a; + B = b; + C = c; + D = d; + E = e; + F = f; + } + + public double A { get; } + public double B { get; } + public double C { get; } + public double D { get; } + public double E { get; } + public double F { get; } + + /// True when circles stay circles. + public bool IsSimilarity + { + get + { + var lengthX = A * A + B * B; + var lengthY = C * C + D * D; + var size = System.Math.Max(lengthX, lengthY); + return System.Math.Abs(lengthX - lengthY) <= SimilarityTolerance * size + && System.Math.Abs(A * C + B * D) <= SimilarityTolerance * size; + } + } + + public double ScaleFactor => System.Math.Sqrt(A * A + B * B); + + public Vector Apply(Vector p) => + new Vector(A * p.X + C * p.Y + E, B * p.X + D * p.Y + F); + + /// Applies the linear part only, for directions rather than positions. + public Vector ApplyLinear(Vector v) => new Vector(A * v.X + C * v.Y, B * v.X + D * v.Y); + + /// This transform applied after . + public SvgTransform Then(SvgTransform inner) => + new SvgTransform( + A * inner.A + C * inner.B, + B * inner.A + D * inner.B, + A * inner.C + C * inner.D, + B * inner.C + D * inner.D, + A * inner.E + C * inner.F + E, + B * inner.E + D * inner.F + F + ); + + public static SvgTransform Translate(double x, double y) => + new SvgTransform(1, 0, 0, 1, x, y); + + public static SvgTransform Scale(double x, double y) => + new SvgTransform(x, 0, 0, y, 0, 0); + + /// Parses a transform list, applied left to right as nested coordinate systems. + public static SvgTransform Parse(string text) + { + var result = Identity; + if (string.IsNullOrWhiteSpace(text)) + return result; + + foreach (Match match in Function.Matches(text)) + { + var values = SvgReader.ParseNumbers(match.Groups[2].Value); + result = result.Then(ParseFunction(match.Groups[1].Value, values, text)); + } + + return result; + } + + private static SvgTransform ParseFunction(string name, double[] v, string text) + { + switch (name) + { + case "matrix" when v.Length == 6: + return new SvgTransform(v[0], v[1], v[2], v[3], v[4], v[5]); + + case "translate" when v.Length is 1 or 2: + return Translate(v[0], v.Length == 2 ? v[1] : 0); + + case "scale" when v.Length is 1 or 2: + return Scale(v[0], v.Length == 2 ? v[1] : v[0]); + + case "rotate" when v.Length == 1: + return Rotation(v[0]); + + case "rotate" when v.Length == 3: + return Translate(v[1], v[2]) + .Then(Rotation(v[0])) + .Then(Translate(-v[1], -v[2])); + + case "skewX" when v.Length == 1: + return new SvgTransform(1, 0, Tan(v[0]), 1, 0, 0); + + case "skewY" when v.Length == 1: + return new SvgTransform(1, Tan(v[0]), 0, 1, 0, 0); + + default: + throw new InvalidDataException($"Unsupported SVG transform \"{text}\"."); + } + } + + private static SvgTransform Rotation(double degrees) + { + var radians = degrees * System.Math.PI / 180; + var cos = System.Math.Cos(radians); + var sin = System.Math.Sin(radians); + return new SvgTransform(cos, sin, -sin, cos, 0, 0); + } + + private static double Tan(double degrees) => + System.Math.Tan(degrees * System.Math.PI / 180); + } +} diff --git a/OpenNest.Mcp/Tools/InputTools.cs b/OpenNest.Mcp/Tools/InputTools.cs index 444176ae..0e45f511 100644 --- a/OpenNest.Mcp/Tools/InputTools.cs +++ b/OpenNest.Mcp/Tools/InputTools.cs @@ -110,11 +110,13 @@ namespace OpenNest.Mcp.Tools } [McpServerTool(Name = "import_dxf")] - [Description("Import a DXF file as a new drawing. Returns drawing name and bounding box.")] + [Description("Import a DXF, DWG or SVG file as a new drawing. Returns drawing name and bounding box.")] public string ImportDxf( - [Description("Absolute path to the DXF file")] string path, + [Description("Absolute path to the drawing file")] string path, [Description("Name for the drawing (defaults to filename without extension)")] - string name = null + string name = null, + [Description("How many of an SVG's units make an inch; required only when the file does not state its real-world size")] + double? svgUnitsPerInch = null ) { if (!File.Exists(path)) @@ -122,7 +124,15 @@ namespace OpenNest.Mcp.Tools try { - var drawing = CadImporter.ImportDrawing(path, new CadImportOptions { Name = name }); + var drawing = CadImporter.ImportDrawing( + path, + new CadImportOptions + { + Name = name, + DrawingUnits = _session.Nest?.Units ?? default, + SvgUserUnitsPerInch = svgUnitsPerInch, + } + ); _session.Drawings.Add(drawing); var bbox = drawing.Program.BoundingBox(); diff --git a/OpenNest.Tests/IO/SvgExportTests.cs b/OpenNest.Tests/IO/SvgExportTests.cs new file mode 100644 index 00000000..10d80efd --- /dev/null +++ b/OpenNest.Tests/IO/SvgExportTests.cs @@ -0,0 +1,147 @@ +using System; +using System.IO; +using System.Linq; +using System.Xml.Linq; +using OpenNest.CNC; +using OpenNest.Converters; +using OpenNest.Geometry; +using OpenNest.IO; +using Xunit; + +namespace OpenNest.Tests.IO +{ + public class SvgExportTests : IDisposable + { + private readonly string folder = Directory.CreateTempSubdirectory("svg-export-tests").FullName; + + public void Dispose() => Directory.Delete(folder, true); + + private string PathFor(string name) => Path.Combine(folder, name); + + private static Drawing Plated() + { + // A 10 x 4 slot: lines and two half circles, with a hole. + var entities = new Entity[] + { + new Line(new Vector(2, 0), new Vector(8, 0)), + new Arc(new Vector(8, 2), 2, -System.Math.PI / 2, System.Math.PI / 2), + new Line(new Vector(8, 4), new Vector(2, 4)), + new Arc(new Vector(2, 2), 2, System.Math.PI / 2, -System.Math.PI / 2), + new Circle(new Vector(5, 2), 1), + }; + foreach (var entity in entities) + entity.Layer = Layer.Default; + + return new Drawing("slot", ConvertGeometry.ToProgram(entities.ToList())); + } + + [Theory] + [InlineData(Units.Inches)] + [InlineData(Units.Millimeters)] + public void ProgramRoundTripsAtTheSameSizeAndArea(Units units) + { + var drawing = Plated(); + var path = PathFor("slot.svg"); + + Svg.ExportProgram(drawing.Program, path, units); + var imported = CadImporter.ImportDrawing(path, new CadImportOptions { DrawingUnits = units }); + + var original = drawing.Program.BoundingBox(); + var box = imported.Program.BoundingBox(); + Assert.Equal(original.Length, box.Length, 6); + Assert.Equal(original.Width, box.Width, 6); + Assert.Equal(drawing.Area, imported.Area, 6); + } + + [Fact] + public void ExportStatesPhysicalSizeSoNoScaleIsNeeded() + { + var path = PathFor("slot.svg"); + + Svg.ExportProgram(Plated().Program, path, Units.Millimeters); + + Assert.Null(Svg.UndeclaredSize(path)); + Assert.EndsWith("mm", XDocument.Load(path).Root.Attribute("width").Value); + } + + [Fact] + public void InchExportReadsAtMillimeters() + { + var path = PathFor("slot.svg"); + + Svg.ExportProgram(Plated().Program, path, Units.Inches); + var imported = CadImporter.Import(path, new CadImportOptions { DrawingUnits = Units.Millimeters }); + + Assert.Equal(254, imported.Bounds.Length, 6); + } + + [Fact] + public void ExportUsesInvariantNumbers() + { + var culture = System.Threading.Thread.CurrentThread.CurrentCulture; + System.Threading.Thread.CurrentThread.CurrentCulture = + System.Globalization.CultureInfo.GetCultureInfo("de-DE"); + try + { + var path = PathFor("slot.svg"); + Svg.ExportEntities(new[] { new Line(0.5, 0.5, 1.5, 0.5) }, path, Units.Inches); + + Assert.DoesNotContain("0,5", File.ReadAllText(path)); + Assert.Equal(1, CadImporter.Import(path).Bounds.Length, 6); + } + finally + { + System.Threading.Thread.CurrentThread.CurrentCulture = culture; + } + } + + [Fact] + public void ReversedArcRoundTripsOnItsOwnSide() + { + var arc = new Arc(new Vector(0, 0), 1, System.Math.PI, 0, true); + var path = PathFor("arc.svg"); + + Svg.ExportEntities(new[] { arc }, path, Units.Inches); + var bounds = CadImporter.Import(path).Bounds; + + // Clockwise from 180 to 0 degrees is the top half. + Assert.Equal(1, bounds.Top, 6); + Assert.Equal(0, bounds.Bottom, 6); + } + + [Fact] + public void PlateExportPlacesPartsAndKeepsThemOnReimport() + { + var drawing = Plated(); + var plate = new Plate(100, 50) { Quadrant = 1 }; + var part = new Part(drawing); + part.Location = new Vector(20, 30); + plate.Parts.Add(part); + var path = PathFor("plate.svg"); + + Svg.ExportPlate(plate, path, Units.Inches); + + var root = XDocument.Load(path).Root; + var layers = root.Elements().Select(g => g.Attribute("data-layer").Value).ToList(); + Assert.Contains("PLATE", layers); + Assert.Contains("RAPID", layers); + + // The plate and rapids are not part geometry. + var imported = CadImporter.Import(path).Bounds; + var expected = part.BoundingBox; + Assert.Equal(expected.Left, imported.Left, 6); + Assert.Equal(expected.Bottom, imported.Bottom, 6); + Assert.Equal(expected.Length, imported.Length, 6); + } + + [Fact] + public void EmptyPlateStillWritesAValidFile() + { + var path = PathFor("empty.svg"); + + Svg.ExportEntities(Array.Empty(), path, Units.Inches); + + Assert.Empty(CadImporter.Import(path).Entities); + } + } +} diff --git a/OpenNest.Tests/IO/SvgImportTests.cs b/OpenNest.Tests/IO/SvgImportTests.cs new file mode 100644 index 00000000..0e22a135 --- /dev/null +++ b/OpenNest.Tests/IO/SvgImportTests.cs @@ -0,0 +1,477 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using OpenNest.Converters; +using OpenNest.Geometry; +using OpenNest.IO; +using Xunit; + +namespace OpenNest.Tests.IO +{ + public class SvgImportTests : IDisposable + { + private const double Precision = 0.002; + private const string SquarePath = ""; + + private readonly string folder = Directory.CreateTempSubdirectory("svg-tests").FullName; + + public void Dispose() => Directory.Delete(folder, true); + + private string Write(string content) + { + var path = Path.Combine(folder, Guid.NewGuid() + ".svg"); + File.WriteAllText(path, content); + return path; + } + + private static string Svg(string body, string attributes = "width='10in' height='10in' viewBox='0 0 10 10'") => + $"{body}"; + + private CadImportResult Import(string content, CadImportOptions options = null) => + CadImporter.Import(Write(content), options ?? new CadImportOptions()); + + private static (double Length, double Width) Size(CadImportResult result) => + (result.Bounds.Length, result.Bounds.Width); + + [Theory] + [InlineData("width='10in' height='10in' viewBox='0 0 100 100'", 1.0)] + [InlineData("width='254mm' height='254mm' viewBox='0 0 10 10'", 10.0)] + [InlineData("width='25.4cm' height='25.4cm' viewBox='0 0 10 10'", 10.0)] + [InlineData("width='720pt' height='720pt' viewBox='0 0 10 10'", 10.0)] + [InlineData("width='60pc' height='60pc' viewBox='0 0 10 10'", 10.0)] + // Without a view box user units are CSS pixels, whatever unit the page is in. + [InlineData("width='1in' height='1in'", 10.0 / 96)] + public void DeclaredSizeGivesRealWorldScale(string attributes, double expected) + { + var (length, width) = Size(Import(Svg(SquarePath, attributes))); + + Assert.Equal(expected, length, 6); + Assert.Equal(expected, width, 6); + } + + [Fact] + public void ConvertsToMillimeterDrawings() + { + var result = Import(Svg(SquarePath), new CadImportOptions { DrawingUnits = Units.Millimeters }); + + Assert.Equal(254, result.Bounds.Length, 6); + } + + [Theory] + [InlineData("viewBox='0 0 10 10'")] + [InlineData("width='100%' height='100%' viewBox='0 0 10 10'")] + [InlineData("width='100px' height='100px' viewBox='0 0 10 10'")] + [InlineData("width='100' height='100' viewBox='0 0 10 10'")] + [InlineData("")] + public void UndeclaredSizeRefusesToGuess(string attributes) + { + var path = Write(Svg(SquarePath, attributes)); + + var error = Assert.Throws(() => CadImporter.Import(path)); + Assert.Contains("real-world size", error.Message); + Assert.Equal((10, 10), OpenNest.IO.Svg.UndeclaredSize(path)); + } + + [Theory] + [InlineData(96, 10.0 / 96)] + [InlineData(72, 10.0 / 72)] + [InlineData(1, 10.0)] + public void ExplicitScaleAppliesToUndeclaredFiles(double unitsPerInch, double expected) + { + var result = Import( + Svg(SquarePath, "viewBox='0 0 10 10'"), + new CadImportOptions { SvgUserUnitsPerInch = unitsPerInch } + ); + + Assert.Equal(expected, result.Bounds.Length, 6); + } + + [Fact] + public void DeclaredSizeBeatsExplicitScale() + { + var result = Import(Svg(SquarePath), new CadImportOptions { SvgUserUnitsPerInch = 96 }); + + Assert.Equal(10, result.Bounds.Length, 6); + Assert.Null(OpenNest.IO.Svg.UndeclaredSize(Write(Svg(SquarePath)))); + } + + [Fact] + public void NonUniformPageFitsViewBoxUniformly() + { + var result = Import(Svg(SquarePath, "width='20in' height='10in' viewBox='0 0 10 10'")); + + Assert.Equal((10, 10), Size(result)); + } + + [Fact] + public void PreserveAspectRatioNoneStretches() + { + var result = Import(Svg( + SquarePath, + "width='20in' height='10in' viewBox='0 0 10 10' preserveAspectRatio='none'" + )); + + Assert.Equal((20, 10), Size(result)); + } + + [Fact] + public void FlipsYSoTheDrawingIsNotMirrored() + { + var result = Import(Svg("")); + + // The wide edge is at the top of the page, so it is the high Y edge in OpenNest. + var top = result.Entities.OfType().Single(l => + System.Math.Abs(l.StartPoint.Y - l.EndPoint.Y) < 1e-9 + ); + Assert.Equal(result.Bounds.Top, top.StartPoint.Y, 6); + } + + [Fact] + public void BasicShapesImport() + { + var result = Import(Svg( + "" + + "" + + "" + + "" + + "" + )); + + Assert.Single(result.Entities.OfType()); + Assert.Equal(1, result.Entities.OfType().Single().Radius, 9); + Assert.Equal(10, result.Entities.OfType().Count()); + } + + [Fact] + public void RoundedRectKeepsItsCorners() + { + var result = Import(Svg("")); + + Assert.Equal(4, result.Entities.OfType().Count()); + var corners = result.Entities.OfType().ToList(); + Assert.Equal(4, corners.Count); + Assert.All(corners, a => Assert.Equal(1, a.Radius, 6)); + Assert.Equal((10, 6), Size(result)); + AssertClosed(result.Entities); + } + + [Fact] + public void AttributeUnitsResolveAgainstCssPixels() + { + // Inside a 96-per-inch page, 1in is 96 user units: one real inch. + var result = Import(Svg( + "", + "width='100in' height='100in' viewBox='0 0 9600 9600'" + )); + + Assert.Equal(1, result.Entities.OfType().Single().Radius, 6); + } + + [Theory] + [InlineData("M0 0 10 0 10 10z", 3)] + [InlineData("m0 0 10 0 0 10z", 3)] + [InlineData("M0,0L10,0L10,10Z", 3)] + [InlineData("M0 0h10v10h-10", 3)] + [InlineData("M0-1.5.5.5", 1)] + public void PathGrammar(string data, int lines) + { + Assert.Equal(lines, Import(Svg($"")).Entities.OfType().Count()); + } + + [Fact] + public void ImplicitLineAfterRelativeMoveIsRelative() + { + var result = Import(Svg("")); + + Assert.Equal((2, 2), Size(result)); + } + + [Fact] + public void CompactArcFlagsParse() + { + var result = Import(Svg("")); + + Assert.Equal(1, result.Entities.OfType().Single().Radius, 6); + } + + [Theory] + [InlineData("L1 1")] + [InlineData("M0 0L1")] + [InlineData("M0 0Q1 1")] + [InlineData("M0 0A1 1 0 2 0 1 1")] + [InlineData("M0 0Y1 1")] + public void MalformedPathIsRejectedRatherThanPartlyImported(string data) + { + var path = Write(Svg($"")); + + Assert.Throws(() => CadImporter.Import(path)); + } + + [Fact] + public void CircularArcKeepsItsSweepDirection() + { + // Sweep 1 from (0,0) to (2,0) passes through y=-1 on the page, so y=+1 in OpenNest. + var result = Import(Svg("")); + + var arc = result.Entities.OfType().Single(); + Assert.Equal(1, arc.Radius, 6); + Assert.Equal(1, result.Bounds.Top, 6); + Assert.Equal(0, result.Bounds.Bottom, 6); + } + + [Fact] + public void LargeArcFlagTakesTheLongWay() + { + var result = Import(Svg("")); + + Assert.True(result.Entities.OfType().Single().SweepAngle() > System.Math.PI); + } + + [Fact] + public void TooSmallArcRadiusScalesUp() + { + var result = Import(Svg("")); + + Assert.Equal(5, result.Entities.OfType().Single().Radius, 6); + } + + [Fact] + public void TwoHalfArcsMakeAWholeHole() + { + var result = Import(Svg("")); + + Assert.Equal((10, 10), Size(result)); + AssertArea(result, System.Math.PI * 25); + } + + [Fact] + public void IllustratorStyleBezierCircleFitsTheCircle() + { + const double k = 0.5522847498 * 5; + var data = FormattableString.Invariant( + $"M5 0C{5 + k} 0 10 {5 - k} 10 5S{5 + k} 10 5 10S0 {5 + k} 0 5S{5 - k} 0 5 0Z" + ); + + var result = Import(Svg($"")); + + Assert.Equal(10, result.Bounds.Length, 2); + AssertClosed(result.Entities); + AssertArea(result, System.Math.PI * 25); + } + + [Fact] + public void QuadraticAndSmoothQuadraticStayOnTheCurve() + { + var result = Import(Svg("")); + + Assert.Equal(20, result.Bounds.Length, 3); + Assert.Equal(10, result.Bounds.Width, 2); + } + + [Fact] + public void TransformsNestInOrder() + { + var result = Import(Svg( + "" + + "" + )); + + Assert.Equal(102, result.Bounds.Left, 6); + Assert.Equal(2, result.Bounds.Length, 6); + } + + [Fact] + public void RotateAboutPointKeepsThePoint() + { + var result = Import(Svg("")); + + Assert.Equal(0, result.Bounds.Left, 6); + Assert.Equal(2, result.Bounds.Right, 6); + } + + [Fact] + public void UniformScaleKeepsACircle() + { + var result = Import(Svg("")); + + Assert.Equal(6, result.Entities.OfType().Single().Radius, 6); + } + + [Fact] + public void NonUniformScaleMakesACircleAnEllipse() + { + var result = Import(Svg("")); + + Assert.Empty(result.Entities.OfType()); + Assert.Equal(20, result.Bounds.Length, 2); + Assert.Equal(10, result.Bounds.Width, 2); + AssertArea(result, System.Math.PI * 50); + } + + [Fact] + public void RotatedEllipseKeepsItsAxes() + { + var result = Import(Svg("")); + + Assert.Equal(6, result.Bounds.Length, 2); + Assert.Equal(12, result.Bounds.Width, 2); + } + + [Fact] + public void EllipticalArcEndsWhereItsNeighborsStart() + { + var result = Import(Svg("")); + + AssertClosed(result.Entities); + } + + [Fact] + public void HiddenAndDefinitionContentIsIgnored() + { + var result = Import(Svg( + "" + + "" + + "" + + "" + + "" + + SquarePath + )); + + Assert.Equal((10, 10), Size(result)); + Assert.Empty(result.Warnings); + } + + [Fact] + public void UseCopiesTheTargetAtItsOffset() + { + var result = Import(Svg( + "" + + "" + )); + + Assert.Equal(5, result.Bounds.Left, 6); + Assert.Equal(12, result.Bounds.Right, 6); + } + + [Fact] + public void SelfReferencingUseDoesNotHang() + { + var result = Import(Svg("" + SquarePath)); + + Assert.Equal((10, 10), Size(result)); + Assert.Contains(result.Warnings, w => w.Contains("")); + } + + [Fact] + public void UnsupportedContentIsReported() + { + var result = Import(Svg("hellox" + SquarePath)); + + Assert.Contains(result.Warnings, w => w.Contains("2 ")); + Assert.Contains(result.Warnings, w => w.Contains("1 ")); + } + + [Fact] + public void LayersComeFromGroups() + { + var result = Import(Svg( + "" + + "" + + "" + + "" + )); + + var names = result.Entities.Select(e => e.Layer.Name).Distinct().OrderBy(n => n); + Assert.Equal(new[] { "One", "Three", "Two" }, names); + Assert.All(result.Entities, e => Assert.True(e.Layer.IsVisible)); + } + + [Fact] + public void NonCutLayersAreDropped() + { + var result = Import(Svg( + "" + + "" + + "" + + "" + + SquarePath + )); + + Assert.Equal((10, 10), Size(result)); + } + + [Fact] + public void ImportedDrawingIsStableAcrossImports() + { + var path = Write(Svg(SquarePath)); + + var first = CadImporter.Import(path); + var second = CadImporter.Import(path); + + Assert.Equal(first.Entities.Select(e => e.Id), second.Entities.Select(e => e.Id)); + } + + [Fact] + public void BuildsADrawingWithAProgram() + { + var drawing = CadImporter.ImportDrawing(Write(Svg(SquarePath))); + + Assert.NotEmpty(drawing.Program.Codes); + Assert.Equal(100, drawing.Area, 6); + Assert.Empty(drawing.SuppressedEntityIds); + } + + [Fact] + public void IllustratorEntityNamespacesParse() + { + var path = Write( + "]>" + + "" + + SquarePath + + "" + ); + + Assert.Equal(10, CadImporter.Import(path).Bounds.Length, 6); + } + + [Fact] + public void EntityExpansionBombIsRejected() + { + var entities = ""; + var previous = "a"; + for (var i = 0; i < 9; i++) + { + var name = "e" + i; + var refs = string.Concat(Enumerable.Repeat($"&{previous};", 10)); + entities += $""; + previous = name; + } + + var path = Write($"&{previous};"); + + Assert.Throws(() => CadImporter.Import(path)); + } + + [Fact] + public void OtherXmlIsNotAnSvg() + { + var path = Write(""); + + Assert.Throws(() => CadImporter.Import(path)); + } + + private static void AssertClosed(IEnumerable entities) + { + var shapes = ShapeBuilder.GetShapes(entities.ToList()); + Assert.Single(shapes); + Assert.True(shapes[0].IsClosed()); + } + + private static void AssertArea(CadImportResult result, double expected) + { + var drawing = CadImporter.BuildDrawing(result, result.Entities, result.Bends, 1, null, null); + Assert.Equal(expected, drawing.Area, 0.1); + } + } +} diff --git a/OpenNest.WinForms.Tests/Forms/CadConverterSvgTests.cs b/OpenNest.WinForms.Tests/Forms/CadConverterSvgTests.cs new file mode 100644 index 00000000..9802de24 --- /dev/null +++ b/OpenNest.WinForms.Tests/Forms/CadConverterSvgTests.cs @@ -0,0 +1,48 @@ +using System; +using System.IO; +using OpenNest.Forms; +using OpenNest.IO; +using Xunit; + +namespace OpenNest.WinForms.Tests.Forms; + +public class CadConverterSvgTests +{ + [Fact] + public void ScaleFormDefaultsToCssPixels() + { + using var form = new SvgScaleForm("part.svg", 96, 48, Units.Inches); + + Assert.Equal(96, form.UserUnitsPerInch); + } + + [Fact] + public void ResolveLeavesOtherFilesAlone() + { + var options = new CadImportOptions(); + + Assert.True(SvgScaleForm.TryResolve(null, "part.dxf", options)); + Assert.Null(options.SvgUserUnitsPerInch); + } + + [Fact] + public void ResolveDoesNotAskWhenTheFileStatesItsSize() + { + var path = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + ".svg"); + File.WriteAllText( + path, + "" + ); + try + { + var options = new CadImportOptions(); + + Assert.True(SvgScaleForm.TryResolve(null, path, options)); + Assert.Null(options.SvgUserUnitsPerInch); + } + finally + { + File.Delete(path); + } + } +} diff --git a/OpenNest/Forms/CadConverterForm.cs b/OpenNest/Forms/CadConverterForm.cs index 8f027725..62ae0b0a 100644 --- a/OpenNest/Forms/CadConverterForm.cs +++ b/OpenNest/Forms/CadConverterForm.cs @@ -93,18 +93,25 @@ namespace OpenNest.Forms #region File Import - public void AddFile(string file) => AddFile(file, 0, null); + /// The units of the nest receiving the drawings; SVGs import in these. + internal Units DrawingUnits { get; set; } - private void AddFile(string file, int detectorIndex, string detectorName) + public void AddFile(string file) => AddFile(file, NewImportOptions(0, null)); + + private CadImportOptions NewImportOptions(int detectorIndex, string detectorName) => + new CadImportOptions + { + BendDetectorName = detectorIndex == 0 ? null : detectorName, + DrawingUnits = DrawingUnits, + }; + + private void AddFile(string file, CadImportOptions options) { try { - var options = new CadImportOptions - { - BendDetectorName = detectorIndex == 0 ? null : detectorName, - }; - var result = CadImporter.Import(file, options); + if (result.Warnings.Count > 0) + ReportImportWarnings(file, result.Warnings); if (result.Entities.Count == 0) return; @@ -142,16 +149,41 @@ namespace OpenNest.Forms MessageBox.Show($"Error importing \"{file}\": {error.Message}"); } + internal virtual void ReportImportWarnings(string file, IReadOnlyList warnings) + { + MessageBox.Show($"\"{Path.GetFileName(file)}\" was only partly imported:\n\n{string.Join("\n", warnings)}"); + } + + /// Asks for any SVG's scale; false skips the file. + internal virtual bool ResolveScale(string file, CadImportOptions options) => + // Files can arrive before this form is shown, and a hidden owner cannot host a dialog. + SvgScaleForm.TryResolve(Visible ? this : null, file, options); + public void AddFiles(IEnumerable files) { - var fileArray = files.ToArray(); - // Capture UI state on main thread before entering parallel loop + // Capture UI state and ask about scale on the main thread before the parallel loop var detectorIndex = cboBendDetector.SelectedIndex; var detectorName = cboBendDetector.SelectedItem?.ToString(); + var imports = new List<(string File, CadImportOptions Options)>(); + foreach (var file in files) + { + var options = NewImportOptions(detectorIndex, detectorName); + try + { + if (!ResolveScale(file, options)) + continue; + } + catch (InvalidDataException ex) + { + ReportImportFailure(file, ex); + continue; + } + imports.Add((file, options)); + } System.Threading.Tasks.Task.Run(() => { - Parallel.ForEach(fileArray, file => AddFile(file, detectorIndex, detectorName)); + Parallel.ForEach(imports, import => AddFile(import.File, import.Options)); }); } @@ -1085,14 +1117,9 @@ namespace OpenNest.Forms if (e.Data.GetDataPresent(DataFormats.FileDrop)) { var files = (string[])e.Data.GetData(DataFormats.FileDrop); - var dxfFiles = files - .Where(f => - f.EndsWith(".dxf", StringComparison.OrdinalIgnoreCase) - || f.EndsWith(".dwg", StringComparison.OrdinalIgnoreCase) - ) - .ToArray(); - if (dxfFiles.Length > 0) - AddFiles(dxfFiles); + var cadFiles = files.Where(CadFormats.IsCadFile).ToArray(); + if (cadFiles.Length > 0) + AddFiles(cadFiles); } } @@ -1160,6 +1187,8 @@ namespace OpenNest.Forms entityView1.Invalidate(); } + private const int SvgExportFilterIndex = 8; + private void OnExportDxfClick(object sender, EventArgs e) { var item = CurrentItem; @@ -1175,13 +1204,20 @@ namespace OpenNest.Forms + "DXF 2007 (*.dxf)|*.dxf|" + "DXF 2004 (*.dxf)|*.dxf|" + "DXF 2000 (*.dxf)|*.dxf|" - + "DXF R14 (*.dxf)|*.dxf", + + "DXF R14 (*.dxf)|*.dxf|" + + "SVG (*.svg)|*.svg", FileName = Path.ChangeExtension(item.Name, ".dxf"), }; if (dlg.ShowDialog() != DialogResult.OK) return; + if (dlg.FilterIndex == SvgExportFilterIndex) + { + Svg.ExportEntities(item.Entities, Path.ChangeExtension(dlg.FileName, ".svg"), DrawingUnits); + return; + } + var version = dlg.FilterIndex switch { 2 => ACadSharp.ACadVersion.AC1027, diff --git a/OpenNest/Forms/EditNestForm.cs b/OpenNest/Forms/EditNestForm.cs index fb08d8e2..9e0f03ca 100644 --- a/OpenNest/Forms/EditNestForm.cs +++ b/OpenNest/Forms/EditNestForm.cs @@ -599,8 +599,7 @@ namespace OpenNest.Forms { var dlg = new OpenFileDialog(); dlg.Multiselect = true; - dlg.Filter = - "CAD Files (*.dxf;*.dwg)|*.dxf;*.dwg|DXF Files (*.dxf)|*.dxf|DWG Files (*.dwg)|*.dwg"; + dlg.Filter = CadFormats.OpenFileFilter; if (dlg.ShowDialog() != DialogResult.OK) return; @@ -611,7 +610,7 @@ namespace OpenNest.Forms /// Converts in the CAD converter and adds the drawings it returns. internal void ImportFiles(string[] files) { - using var converter = new CadConverterForm(); + using var converter = new CadConverterForm { DrawingUnits = Nest.Units }; converter.AddFiles(files); if (converter.ShowDialog() != DialogResult.OK) @@ -650,7 +649,8 @@ namespace OpenNest.Forms { Filter = "DXF file (*.dxf)|*.dxf|" + "Image as displayed (*.jpg)|*.jpg|" - + "Locations and rotations (*.txt)|*.txt", + + "Locations and rotations (*.txt)|*.txt|" + + "SVG file (*.svg)|*.svg", FileName = suggestedFileName, AddExtension = true, DefaultExt = ".", @@ -706,6 +706,9 @@ namespace OpenNest.Forms } } break; + case 4: + Svg.ExportPlate(plate, destination, Nest.Units); + break; default: throw new ArgumentException("Unsupported plate export format.", nameof(filterIndex)); } @@ -1529,7 +1532,7 @@ namespace OpenNest.Forms NestWriter.GetProgramText(program) + "\0" + NestWriter.GetSubProgramsText(program); var snapshot = DrawingProgramSnapshot.Capture(editedDrawings, ProgramText); var loaded = editedDrawings.Select(d => ProgramText(d.Program)).ToList(); - using var converter = new CadConverterForm(); + using var converter = new CadConverterForm { DrawingUnits = Nest.Units }; // LoadDrawings can edit live programs even when the dialog is canceled. PlateView.InvalidateOverlapCheck(); converter.LoadDrawings(editedDrawings); diff --git a/OpenNest/Forms/EditPlateForm.cs b/OpenNest/Forms/EditPlateForm.cs index a111debe..467cfad8 100644 --- a/OpenNest/Forms/EditPlateForm.cs +++ b/OpenNest/Forms/EditPlateForm.cs @@ -232,15 +232,18 @@ namespace OpenNest.Forms using var dialog = new OpenFileDialog { Title = "Import Sheet Outline", - Filter = "CAD Files (*.dxf;*.dwg)|*.dxf;*.dwg|DXF Files (*.dxf)|*.dxf|DWG Files (*.dwg)|*.dwg", + Filter = CadFormats.OpenFileFilter, }; if (dialog.ShowDialog(this) != DialogResult.OK) return; try { - Outline = SheetOutline.FromGeometry(CadImporter.Import(dialog.FileName).Entities); + var options = new CadImportOptions { DrawingUnits = Units }; + if (!SvgScaleForm.TryResolve(this, dialog.FileName, options)) + return; + Outline = SheetOutline.FromGeometry(CadImporter.Import(dialog.FileName, options).Entities); } - catch (Exception exception) when (exception is ArgumentException or IOException or InvalidOperationException) + catch (Exception exception) when (exception is ArgumentException or IOException or InvalidOperationException or InvalidDataException) { MessageBox.Show(this, $"The file does not hold a sheet outline: {exception.Message}", "Import Sheet Outline", MessageBoxButtons.OK, MessageBoxIcon.Warning); diff --git a/OpenNest/Forms/SvgScaleForm.Designer.cs b/OpenNest/Forms/SvgScaleForm.Designer.cs new file mode 100644 index 00000000..19a4cd49 --- /dev/null +++ b/OpenNest/Forms/SvgScaleForm.Designer.cs @@ -0,0 +1,147 @@ +namespace OpenNest.Forms +{ + partial class SvgScaleForm + { + private System.ComponentModel.IContainer components = null; + + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + private void InitializeComponent() + { + this.labelMessage = new System.Windows.Forms.Label(); + this.radioPixels = new System.Windows.Forms.RadioButton(); + this.radioPoints = new System.Windows.Forms.RadioButton(); + this.radioMillimeters = new System.Windows.Forms.RadioButton(); + this.radioInches = new System.Windows.Forms.RadioButton(); + this.labelSize = new System.Windows.Forms.Label(); + this.buttonOk = new System.Windows.Forms.Button(); + this.buttonCancel = new System.Windows.Forms.Button(); + this.SuspendLayout(); + // + // labelMessage + // + this.labelMessage.Location = new System.Drawing.Point(12, 9); + this.labelMessage.Name = "labelMessage"; + this.labelMessage.Size = new System.Drawing.Size(376, 34); + this.labelMessage.TabIndex = 0; + // + // radioPixels + // + this.radioPixels.AutoSize = true; + this.radioPixels.Checked = true; + this.radioPixels.Location = new System.Drawing.Point(15, 50); + this.radioPixels.Name = "radioPixels"; + this.radioPixels.Size = new System.Drawing.Size(250, 19); + this.radioPixels.TabIndex = 1; + this.radioPixels.TabStop = true; + this.radioPixels.Text = "1/96 inch (web and Inkscape pixels)"; + this.radioPixels.UseVisualStyleBackColor = true; + this.radioPixels.CheckedChanged += new System.EventHandler(this.UpdateSize); + // + // radioPoints + // + this.radioPoints.AutoSize = true; + this.radioPoints.Location = new System.Drawing.Point(15, 75); + this.radioPoints.Name = "radioPoints"; + this.radioPoints.Size = new System.Drawing.Size(250, 19); + this.radioPoints.TabIndex = 2; + this.radioPoints.Text = "1/72 inch (Illustrator points)"; + this.radioPoints.UseVisualStyleBackColor = true; + this.radioPoints.CheckedChanged += new System.EventHandler(this.UpdateSize); + // + // radioMillimeters + // + this.radioMillimeters.AutoSize = true; + this.radioMillimeters.Location = new System.Drawing.Point(15, 100); + this.radioMillimeters.Name = "radioMillimeters"; + this.radioMillimeters.Size = new System.Drawing.Size(100, 19); + this.radioMillimeters.TabIndex = 3; + this.radioMillimeters.Text = "1 millimeter"; + this.radioMillimeters.UseVisualStyleBackColor = true; + this.radioMillimeters.CheckedChanged += new System.EventHandler(this.UpdateSize); + // + // radioInches + // + this.radioInches.AutoSize = true; + this.radioInches.Location = new System.Drawing.Point(15, 125); + this.radioInches.Name = "radioInches"; + this.radioInches.Size = new System.Drawing.Size(70, 19); + this.radioInches.TabIndex = 4; + this.radioInches.Text = "1 inch"; + this.radioInches.UseVisualStyleBackColor = true; + this.radioInches.CheckedChanged += new System.EventHandler(this.UpdateSize); + // + // labelSize + // + this.labelSize.Location = new System.Drawing.Point(12, 155); + this.labelSize.Name = "labelSize"; + this.labelSize.Size = new System.Drawing.Size(376, 20); + this.labelSize.TabIndex = 5; + // + // buttonOk + // + this.buttonOk.DialogResult = System.Windows.Forms.DialogResult.OK; + this.buttonOk.Location = new System.Drawing.Point(232, 185); + this.buttonOk.Name = "buttonOk"; + this.buttonOk.Size = new System.Drawing.Size(75, 25); + this.buttonOk.TabIndex = 6; + this.buttonOk.Text = "OK"; + this.buttonOk.UseVisualStyleBackColor = true; + // + // buttonCancel + // + this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; + this.buttonCancel.Location = new System.Drawing.Point(313, 185); + this.buttonCancel.Name = "buttonCancel"; + this.buttonCancel.Size = new System.Drawing.Size(75, 25); + this.buttonCancel.TabIndex = 7; + this.buttonCancel.Text = "Skip File"; + this.buttonCancel.UseVisualStyleBackColor = true; + // + // SvgScaleForm + // + this.AcceptButton = this.buttonOk; + this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.CancelButton = this.buttonCancel; + this.ClientSize = new System.Drawing.Size(400, 222); + this.Controls.Add(this.buttonCancel); + this.Controls.Add(this.buttonOk); + this.Controls.Add(this.labelSize); + this.Controls.Add(this.radioInches); + this.Controls.Add(this.radioMillimeters); + this.Controls.Add(this.radioPoints); + this.Controls.Add(this.radioPixels); + this.Controls.Add(this.labelMessage); + this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; + this.MaximizeBox = false; + this.MinimizeBox = false; + this.Name = "SvgScaleForm"; + this.ShowInTaskbar = false; + this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; + this.Text = "SVG Scale"; + this.ResumeLayout(false); + this.PerformLayout(); + } + + #endregion + + private System.Windows.Forms.Label labelMessage; + private System.Windows.Forms.RadioButton radioPixels; + private System.Windows.Forms.RadioButton radioPoints; + private System.Windows.Forms.RadioButton radioMillimeters; + private System.Windows.Forms.RadioButton radioInches; + private System.Windows.Forms.Label labelSize; + private System.Windows.Forms.Button buttonOk; + private System.Windows.Forms.Button buttonCancel; + } +} diff --git a/OpenNest/Forms/SvgScaleForm.cs b/OpenNest/Forms/SvgScaleForm.cs new file mode 100644 index 00000000..6490266c --- /dev/null +++ b/OpenNest/Forms/SvgScaleForm.cs @@ -0,0 +1,93 @@ +using System; +using System.IO; +using System.Windows.Forms; +using OpenNest.IO; + +namespace OpenNest.Forms +{ + /// + /// Asks what an SVG's numbers mean when the file does not state its real-world size, + /// showing the size each choice gives so a wrong one is obvious before importing. + /// + public partial class SvgScaleForm : Form + { + private const double CssPixelsPerInch = 96; + private const double IllustratorPointsPerInch = 72; + private const double UnitsPerInchAtOneMillimeter = 25.4; + private const double UnitsPerInchAtOneInch = 1; + + private readonly double fileWidth; + private readonly double fileHeight; + private readonly Units units; + + public SvgScaleForm(string fileName, double width, double height, Units units) + { + InitializeComponent(); + fileWidth = width; + fileHeight = height; + this.units = units; + labelMessage.Text = $"\"{fileName}\" does not state its real-world size. What is one of its units?"; + UpdateSize(this, EventArgs.Empty); + } + + public double UserUnitsPerInch + { + get + { + if (radioPoints.Checked) + return IllustratorPointsPerInch; + if (radioMillimeters.Checked) + return UnitsPerInchAtOneMillimeter; + if (radioInches.Checked) + return UnitsPerInchAtOneInch; + return CssPixelsPerInch; + } + } + + /// + /// Fills in when + /// needs it; false when the user cancels. Anything else + /// imports unchanged, and an unreadable file fails in the import that follows. + /// + public static bool TryResolve(IWin32Window owner, string path, CadImportOptions options) + { + if (!Svg.IsSvg(path)) + return true; + + (double Width, double Height)? size; + try + { + size = Svg.UndeclaredSize(path); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + return true; + } + + if (size == null) + return true; + + using var form = new SvgScaleForm( + Path.GetFileName(path), + size.Value.Width, + size.Value.Height, + options.DrawingUnits + ); + if (form.ShowDialog(owner) != DialogResult.OK) + return false; + + options.SvgUserUnitsPerInch = form.UserUnitsPerInch; + return true; + } + + private void UpdateSize(object sender, EventArgs e) + { + var perInch = units == Units.Millimeters ? 25.4 : 1; + var scale = perInch / UserUnitsPerInch; + var format = units == Units.Millimeters ? "F1" : "F3"; + var unit = UnitsHelper.GetShortString(units); + labelSize.Text = + $"Imported size: {(fileWidth * scale).ToString(format)} x {(fileHeight * scale).ToString(format)} {unit}"; + } + } +} diff --git a/docs/svg-import-export.md b/docs/svg-import-export.md new file mode 100644 index 00000000..ec4ba4af --- /dev/null +++ b/docs/svg-import-export.md @@ -0,0 +1,33 @@ +# SVG import and export + +`OpenNest.IO.Svg` reads and writes SVG alongside DXF and DWG. Everything goes through `CadImporter`, so an SVG drawing behaves like any other import after loading. `.svg` is not in `DrawingFileIndex`: BOM imports still look for DXF and DWG only. + +## Scale + +A DXF's numbers are taken as drawing units. An SVG's are not, so import converts to `CadImportOptions.DrawingUnits` (the nest's units in the desktop app) and never guesses. + +The root element states a real-world size only when `width` or `height` uses an absolute unit: `in`, `cm`, `mm`, `Q`, `pt` or `pc`. Then: + +- With a `viewBox`, inches per user unit is the page size over the view box size. Mismatched aspect ratios fit uniformly, as browsers do, unless `preserveAspectRatio` starts with `none`. +- Without one, a user unit is a CSS pixel, 1/96 inch. + +Everything else does not count: a missing size, percentages and `px` or bare numbers. `px` is excluded on purpose, because a CSS pixel is 1/96 inch but Illustrator writes px at 72 per inch. + +With no stated size, `CadImportOptions.SvgUserUnitsPerInch` supplies the scale, and without it the import throws `InvalidDataException`. A stated size always wins over that option. The desktop app asks with `SvgScaleForm`, which shows the size each choice produces; the console takes `--svg-units-per-inch` (`--cad-units mm` sets the drawing units) and MCP's `import_dxf` takes `svgUnitsPerInch`. + +## What import reads + +Import takes path centerlines: `path`, `rect` (with rounded corners), `circle`, `ellipse`, `line`, `polyline`, `polygon`, `g` and `use`. Stroke widths and fills are ignored. Transforms are applied before an entity type is chosen, so a circle under a non-uniform scale becomes an ellipse. + +- SVG's Y axis points down, so import negates Y. The view box origin is not subtracted, which keeps OpenNest's own exports at their original coordinates. +- Circular arcs stay arcs. Ellipses go through `EllipseConverter`, and Bézier curves are sampled and fitted by `SplineConverter`, both within 0.001 in or 0.025 mm. +- Malformed path data fails the import instead of importing part of a shape. +- Elements with `display` none or `visibility` hidden or collapse are skipped, as are definition elements such as `defs` and `clipPath`. `