diff --git a/AGENTS.md b/AGENTS.md
index 135336c3..e63c6670 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -66,6 +66,7 @@ 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. It also covers the CAD Converter's DXF/DWG/SVG export, whose bends import reads back
+- [Separating parts](docs/separate-parts.md): the CAD Converter splits a file drawing several parts into one drawing per part (`PartBodies`), keeping IDs and refusing a breakoff or tabbed cutout that spans parts
- [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.Core/Geometry/PartBodies.cs b/OpenNest.Core/Geometry/PartBodies.cs
new file mode 100644
index 00000000..9312e9cd
--- /dev/null
+++ b/OpenNest.Core/Geometry/PartBodies.cs
@@ -0,0 +1,229 @@
+using System.Collections.Generic;
+using System.Linq;
+
+namespace OpenNest.Geometry
+{
+ /// A name a source file gives to the geometry inside a region, such as an SVG group's title.
+ public sealed record LabeledRegion(string Name, Box Bounds);
+
+ ///
+ /// The separate parts drawn in one set of entities. Every closed outline that no other outline
+ /// holds starts a part; the outlines directly inside it are its holes, and an outline inside one
+ /// of those holes starts another part. Entities that are not outlines (open paths, marks, bend
+ /// lines, text) belong to the innermost part around them, or to the nearest part when none is.
+ ///
+ public sealed class PartBodies
+ {
+ private readonly List
bodies;
+ private readonly Dictionary outlineOwners = new();
+
+ private PartBodies(List bodies)
+ {
+ this.bodies = bodies;
+ for (var i = 0; i < bodies.Count; i++)
+ foreach (var shape in bodies[i].Contours)
+ foreach (var entity in shape.Entities)
+ outlineOwners[entity] = i;
+ }
+
+ /// The number of parts found; fewer than two means there is nothing to separate.
+ public int Count => bodies.Count;
+
+ /// The bounds of part 's outer outline.
+ public Box Bounds(int index) => bodies[index].Outer.BoundingBox;
+
+ ///
+ /// Finds the parts outlined by : the cut entities, without marks or
+ /// display-only geometry. Parts are numbered in reading order, top row first, left to right.
+ ///
+ public static PartBodies Find(IEnumerable outlines)
+ {
+ var closed = ShapeBuilder
+ .GetShapes(outlines.Where(e => e is Line or Arc or Circle))
+ .Where(s => s.IsClosed())
+ .Select(s => new Contour(s, s.ToPolygon()))
+ .Where(c => c.Polygon.Vertices.Count >= 3)
+ .ToList();
+
+ foreach (var contour in closed)
+ contour.Parent = closed
+ .Where(other => other != contour && Holds(other, contour))
+ .OrderBy(other => other.Shape.BoundingBox.Area())
+ .FirstOrDefault();
+ foreach (var contour in closed)
+ for (var parent = contour.Parent; parent != null; parent = parent.Parent)
+ contour.Depth++;
+
+ var bodies = closed
+ .Where(c => c.Depth % 2 == 0)
+ .Select(c => new Body(c))
+ .ToList();
+ foreach (var hole in closed.Where(c => c.Depth % 2 == 1))
+ bodies.First(b => b.OuterContour == hole.Parent).Contours.Add(hole.Shape);
+
+ return new PartBodies(ReadingOrder(bodies));
+ }
+
+ /// The part an entity belongs to, or -1 when no part was found.
+ public int IndexOf(Entity entity)
+ {
+ if (outlineOwners.TryGetValue(entity, out var owner))
+ return owner;
+ return IndexOf(RepresentativePoint(entity));
+ }
+
+ /// The innermost part whose outer outline holds , else the nearest part.
+ public int IndexOf(Vector point)
+ {
+ var best = -1;
+ for (var i = 0; i < bodies.Count; i++)
+ {
+ var body = bodies[i];
+ if (!body.Outer.BoundingBox.Contains(point) || !body.Polygon.ContainsPoint(point))
+ continue;
+ if (best < 0 || body.Depth > bodies[best].Depth)
+ best = i;
+ }
+ if (best >= 0)
+ return best;
+
+ var nearest = double.MaxValue;
+ for (var i = 0; i < bodies.Count; i++)
+ {
+ var distance = DistanceTo(bodies[i].Outer.BoundingBox, point);
+ if (distance < nearest)
+ {
+ nearest = distance;
+ best = i;
+ }
+ }
+ return best;
+ }
+
+ /// Splits by part, keeping their order; one list per part.
+ public List> Group(IEnumerable entities)
+ {
+ var groups = bodies.Select(_ => new List()).ToList();
+ if (groups.Count == 0)
+ return groups;
+ foreach (var entity in entities)
+ groups[IndexOf(entity)].Add(entity);
+ return groups;
+ }
+
+ ///
+ /// The name give part : the smallest labeled
+ /// region that holds its whole outline and no other part's, or null when there is none.
+ ///
+ public string NameOf(int index, IEnumerable labels)
+ {
+ if (labels == null)
+ return null;
+ var bounds = Bounds(index);
+ var others = Enumerable.Range(0, Count).Where(i => i != index).Select(Bounds).ToList();
+ return labels
+ .Where(l => !string.IsNullOrWhiteSpace(l.Name) && l.Bounds != null)
+ .Where(l => Holds(l.Bounds, bounds) && !others.Any(o => Holds(l.Bounds, o)))
+ .OrderBy(l => l.Bounds.Area())
+ .Select(l => l.Name.Trim())
+ .FirstOrDefault();
+ }
+
+ // Within the contour chaining tolerance, so a label region drawn exactly on a part's
+ // outline still holds it.
+ private static bool Holds(Box outer, Box inner)
+ {
+ var tolerance = Math.Tolerance.ChainTolerance;
+ return inner.Left >= outer.Left - tolerance
+ && inner.Right <= outer.Right + tolerance
+ && inner.Bottom >= outer.Bottom - tolerance
+ && inner.Top <= outer.Top + tolerance;
+ }
+
+ // A contour holds another when its bounds hold the other's and its polygon holds most of
+ // the other's vertices: a vertex lying on a shared edge cannot decide it alone.
+ private static bool Holds(Contour outer, Contour inner)
+ {
+ var outerBox = outer.Shape.BoundingBox;
+ var innerBox = inner.Shape.BoundingBox;
+ if (!Holds(outerBox, innerBox) || outerBox.Area() <= innerBox.Area())
+ return false;
+
+ var vertices = inner.Polygon.Vertices;
+ var step = System.Math.Max(1, vertices.Count / 16);
+ var inside = 0;
+ var tested = 0;
+ for (var i = 0; i < vertices.Count; i += step)
+ {
+ tested++;
+ if (outer.Polygon.ContainsPoint(vertices[i]))
+ inside++;
+ }
+ return inside * 2 > tested;
+ }
+
+ private static Vector RepresentativePoint(Entity entity) =>
+ entity switch
+ {
+ Line line => line.MidPoint,
+ Circle circle => circle.Center,
+ _ => entity.BoundingBox.Center,
+ };
+
+ private static double DistanceTo(Box box, Vector point)
+ {
+ var dx = System.Math.Max(0, System.Math.Max(box.Left - point.X, point.X - box.Right));
+ var dy = System.Math.Max(0, System.Math.Max(box.Bottom - point.Y, point.Y - box.Top));
+ return System.Math.Sqrt(dx * dx + dy * dy);
+ }
+
+ // Rows from the top: a part joins the current row while its center lies within the height
+ // of the row's first part; each row reads left to right.
+ private static List ReadingOrder(List bodies)
+ {
+ var remaining = bodies.OrderByDescending(b => b.Outer.BoundingBox.Top).ToList();
+ var ordered = new List();
+ while (remaining.Count > 0)
+ {
+ var first = remaining[0].Outer.BoundingBox;
+ var row = remaining
+ .Where(b => b.Outer.BoundingBox.Center.Y >= first.Bottom && b.Outer.BoundingBox.Center.Y <= first.Top)
+ .ToList();
+ if (row.Count == 0)
+ row.Add(remaining[0]);
+ ordered.AddRange(row.OrderBy(b => b.Outer.BoundingBox.Left));
+ remaining.RemoveAll(row.Contains);
+ }
+ return ordered;
+ }
+
+ private sealed class Contour
+ {
+ public Contour(Shape shape, Polygon polygon)
+ {
+ Shape = shape;
+ Polygon = polygon;
+ }
+
+ public Shape Shape { get; }
+ public Polygon Polygon { get; }
+ public Contour Parent { get; set; }
+ public int Depth { get; set; }
+ }
+
+ private sealed class Body
+ {
+ public Body(Contour outer)
+ {
+ OuterContour = outer;
+ Contours.Add(outer.Shape);
+ }
+
+ public Contour OuterContour { get; }
+ public Shape Outer => OuterContour.Shape;
+ public Polygon Polygon => OuterContour.Polygon;
+ public int Depth => OuterContour.Depth;
+ public List Contours { get; } = new();
+ }
+ }
+}
diff --git a/OpenNest.IO/CadImportResult.cs b/OpenNest.IO/CadImportResult.cs
index b4fd651c..4b86d4fc 100644
--- a/OpenNest.IO/CadImportResult.cs
+++ b/OpenNest.IO/CadImportResult.cs
@@ -31,6 +31,12 @@ namespace OpenNest.IO
///
public List Bends { get; set; } = new List();
+ ///
+ /// Names the file gives to regions of its geometry, such as SVG element titles; used to
+ /// name the parts when a file holding several is separated. Empty when the file has none.
+ ///
+ public List Labels { get; set; } = new List();
+
public List BendRepairReports { get; set; } =
new List();
diff --git a/OpenNest.IO/CadImporter.cs b/OpenNest.IO/CadImporter.cs
index 35eb4934..02bd2ea2 100644
--- a/OpenNest.IO/CadImporter.cs
+++ b/OpenNest.IO/CadImporter.cs
@@ -96,6 +96,7 @@ namespace OpenNest.IO
Entities = dxf.Entities,
RawEntities = dxf.RawEntities,
Bends = bends,
+ Labels = dxf.Labels ?? new List(),
BendRepairReports = repairReports,
Bounds = dxf.Entities.GetBoundingBox(),
SourcePath = path,
diff --git a/OpenNest.IO/DxfImportResult.cs b/OpenNest.IO/DxfImportResult.cs
index f3148132..c2d4778f 100644
--- a/OpenNest.IO/DxfImportResult.cs
+++ b/OpenNest.IO/DxfImportResult.cs
@@ -21,6 +21,10 @@ namespace OpenNest.IO
/// detected from instead.
///
public List Bends { get; set; }
+
+ /// Names the file gives to regions of its geometry, such as SVG titles; empty when none.
+ public List Labels { get; set; } = new();
+
public List Warnings { get; set; } = new();
}
}
diff --git a/OpenNest.IO/SvgReader.cs b/OpenNest.IO/SvgReader.cs
index edf078c8..da272ae2 100644
--- a/OpenNest.IO/SvgReader.cs
+++ b/OpenNest.IO/SvgReader.cs
@@ -58,6 +58,7 @@ namespace OpenNest.IO
private readonly List arcs = new List();
private readonly List circles = new List();
private readonly List bends = new List();
+ private readonly List labels = new List();
private readonly HashSet activeUses = new HashSet();
private SvgReader(XElement root, double tolerance)
@@ -244,6 +245,7 @@ namespace OpenNest.IO
Entities = entities,
RawEntities = raw,
Bends = bends,
+ Labels = labels,
Warnings = skipped
.OrderBy(s => s.Key, StringComparer.Ordinal)
.Select(s => $"Skipped {s.Value} <{s.Key}> element(s); convert them to paths to import them.")
@@ -266,6 +268,31 @@ namespace OpenNest.IO
if (IgnoredElements.Contains(name) || IsHidden(element))
return;
+ var title = element.Element(svgNamespace + "title")?.Value;
+ if (!string.IsNullOrWhiteSpace(title))
+ {
+ var counts = (lines.Count, arcs.Count, circles.Count);
+ WalkElement(element, name, parent, parentLayer);
+ AddLabel(title, counts);
+ return;
+ }
+
+ WalkElement(element, name, parent, parentLayer);
+ }
+
+ // An element's title names the geometry it draws, as the region that geometry covers.
+ private void AddLabel(string title, (int Lines, int Arcs, int Circles) before)
+ {
+ var added = lines.Skip(before.Lines).Cast()
+ .Concat(arcs.Skip(before.Arcs))
+ .Concat(circles.Skip(before.Circles))
+ .ToList();
+ if (added.Count > 0)
+ labels.Add(new LabeledRegion(title.Trim(), added.GetBoundingBox()));
+ }
+
+ private void WalkElement(XElement element, string name, SvgTransform parent, Layer parentLayer)
+ {
var transform = parent.Then(SvgTransform.Parse(element.Attribute("transform")?.Value));
switch (name)
{
diff --git a/OpenNest.Tests/Geometry/PartBodiesTests.cs b/OpenNest.Tests/Geometry/PartBodiesTests.cs
new file mode 100644
index 00000000..ce49559c
--- /dev/null
+++ b/OpenNest.Tests/Geometry/PartBodiesTests.cs
@@ -0,0 +1,115 @@
+using OpenNest.Geometry;
+
+namespace OpenNest.Tests.Geometry;
+
+public class PartBodiesTests
+{
+ private static List Rect(double x, double y, double w, double h) =>
+ [
+ new Line(x, y, x + w, y),
+ new Line(x + w, y, x + w, y + h),
+ new Line(x + w, y + h, x, y + h),
+ new Line(x, y + h, x, y),
+ ];
+
+ [Fact]
+ public void OnePart_WithHoles_IsOneBody()
+ {
+ var entities = Rect(0, 0, 10, 10);
+ entities.Add(new Circle(new Vector(3, 3), 1));
+ entities.AddRange(Rect(6, 6, 2, 2));
+
+ var bodies = PartBodies.Find(entities);
+
+ Assert.Equal(1, bodies.Count);
+ Assert.Single(bodies.Group(entities));
+ }
+
+ [Fact]
+ public void SideBySideParts_AreSeparate_EachKeepingItsHole()
+ {
+ var left = Rect(0, 0, 10, 10);
+ var leftHole = new Circle(new Vector(5, 8), 0.5);
+ var right = Rect(20, 0, 5, 12);
+ var rightHole = new Circle(new Vector(22.5, 10), 0.5);
+ var entities = right.Concat(left).Append(rightHole).Append(leftHole).ToList();
+
+ var bodies = PartBodies.Find(entities);
+ var groups = bodies.Group(entities);
+
+ Assert.Equal(2, bodies.Count);
+ // Reading order: the taller right part's top is higher, but both share a row, so left first.
+ Assert.Equal(left.Append(leftHole), groups[0]);
+ Assert.Equal(right.Append(rightHole), groups[1]);
+ }
+
+ [Fact]
+ public void PartInsideAHole_IsItsOwnPart()
+ {
+ var ring = Rect(0, 0, 20, 20);
+ var hole = Rect(5, 5, 10, 10);
+ var island = Rect(8, 8, 4, 4);
+ var islandHole = new Circle(new Vector(10, 10), 0.5);
+ var entities = ring.Concat(hole).Concat(island).Append(islandHole).ToList();
+
+ var bodies = PartBodies.Find(entities);
+ var groups = bodies.Group(entities);
+
+ Assert.Equal(2, bodies.Count);
+ Assert.Contains(groups, g => g.SequenceEqual(ring.Concat(hole)));
+ Assert.Contains(groups, g => g.SequenceEqual(island.Append(islandHole)));
+ }
+
+ [Fact]
+ public void Marks_GoToThePartAroundThem_OrTheNearestOne()
+ {
+ var a = Rect(0, 0, 10, 10);
+ var b = Rect(20, 0, 10, 10);
+ var etch = new Line(2, 5, 8, 5) { Layer = new Layer("ETCH") };
+ var stray = new Line(31, 5, 33, 5);
+ var bodies = PartBodies.Find(a.Concat(b));
+
+ Assert.Equal(0, bodies.IndexOf(etch));
+ Assert.Equal(1, bodies.IndexOf(stray));
+ Assert.Equal(1, bodies.IndexOf(new Vector(25, 5)));
+ }
+
+ [Fact]
+ public void OpenGeometry_IsNotAPart()
+ {
+ var entities = Rect(0, 0, 10, 10);
+ entities.Add(new Line(20, 0, 30, 0));
+ entities.Add(new Line(30, 0, 30, 10));
+
+ Assert.Equal(1, PartBodies.Find(entities).Count);
+ }
+
+ [Fact]
+ public void Rows_ReadTopToBottom_LeftToRight()
+ {
+ var bottomLeft = Rect(0, 0, 5, 5);
+ var topRight = Rect(10, 10, 5, 5);
+ var topLeft = Rect(0, 10, 5, 5);
+ var bodies = PartBodies.Find(bottomLeft.Concat(topRight).Concat(topLeft));
+
+ Assert.Equal(0, bodies.IndexOf(topLeft[0]));
+ Assert.Equal(1, bodies.IndexOf(topRight[0]));
+ Assert.Equal(2, bodies.IndexOf(bottomLeft[0]));
+ }
+
+ [Fact]
+ public void NameOf_TakesTheSmallestLabelHoldingOnlyThatPart()
+ {
+ var bodies = PartBodies.Find(Rect(0, 0, 10, 10).Concat(Rect(20, 0, 10, 10)));
+ var labels = new[]
+ {
+ new LabeledRegion("everything", new Box(0, 0, 30, 10)),
+ new LabeledRegion(" star ", new Box(0, 0, 10, 10)),
+ new LabeledRegion("too small", new Box(1, 1, 2, 2)),
+ };
+
+ Assert.Equal("star", bodies.NameOf(0, labels));
+ Assert.Null(bodies.NameOf(1, labels));
+ Assert.Null(bodies.NameOf(0, null));
+ }
+}
diff --git a/OpenNest.Tests/IO/SvgImportTests.cs b/OpenNest.Tests/IO/SvgImportTests.cs
index 0e22a135..e947a431 100644
--- a/OpenNest.Tests/IO/SvgImportTests.cs
+++ b/OpenNest.Tests/IO/SvgImportTests.cs
@@ -50,6 +50,25 @@ namespace OpenNest.Tests.IO
Assert.Equal(expected, width, 6);
}
+ [Fact]
+ public void ElementTitlesNameTheGeometryTheyDraw()
+ {
+ var result = Import(Svg(
+ "sheet"
+ + " star "
+ + "tag"
+ + "empty"
+ + ""));
+
+ Assert.Equal(new[] { "star", "tag" }, result.Labels.Select(l => l.Name));
+ var star = result.Labels[0].Bounds;
+ // In the entities' frame: SVG's y axis points down, so y=1 to 3 lands at -3 to -1.
+ Assert.Equal(1, star.Left, 6);
+ Assert.Equal(3, star.Right, 6);
+ Assert.Equal(-3, star.Bottom, 6);
+ Assert.Equal(-1, star.Top, 6);
+ }
+
[Fact]
public void ConvertsToMillimeterDrawings()
{
diff --git a/OpenNest.WinForms.Tests/Forms/CadConverterSeparateTests.cs b/OpenNest.WinForms.Tests/Forms/CadConverterSeparateTests.cs
new file mode 100644
index 00000000..759414c4
--- /dev/null
+++ b/OpenNest.WinForms.Tests/Forms/CadConverterSeparateTests.cs
@@ -0,0 +1,125 @@
+using System.IO;
+using System.Reflection;
+using System.Windows.Forms;
+using OpenNest.Controls;
+using OpenNest.Forms;
+using OpenNest.Geometry;
+using static OpenNest.WinForms.Tests.FormTesting;
+
+namespace OpenNest.WinForms.Tests.Forms;
+
+///
+/// A file that draws several parts separates into one drawing per part, named from the file's
+/// titles where it has them, each keeping its holes, IDs and settings.
+///
+public class CadConverterSeparateTests
+{
+ // Three parts in a row: a titled square with a hole, a titled disc with a hole, and an
+ // untitled frame with a loose part sitting in its window.
+ private const string ThreeParts =
+ "";
+
+ [Fact]
+ public void SeparateAll_GivesEachPartItsOwnDrawing() => ArchUnitsTests.RunSta(() =>
+ WithFile(form =>
+ {
+ var list = Field(form, "fileList");
+ var source = list.SelectedItem!;
+ source.Quantity = 3;
+ source.Customer = "Acme";
+ var ids = source.Entities.Select(e => e.Id).ToHashSet();
+
+ Assert.True(form.SeparateParts(null));
+
+ Assert.Equal(new[] { "bauble", "parts-3", "parts-4", "tag" }, list.Items.Select(i => i.Name));
+ var drawings = form.GetDrawings();
+ Assert.Equal(4, drawings.Count);
+ Assert.All(drawings, d =>
+ {
+ Assert.Equal(3, d.Quantity.Required);
+ Assert.Equal("Acme", d.Customer);
+ Assert.Equal(source.Path, d.Source.Path);
+ Assert.All(d.SourceEntities, e => Assert.Contains(e.Id, ids));
+ });
+ Assert.Equal(ids.Count, drawings.Sum(d => d.SourceEntities.Count));
+
+ var bauble = drawings.Single(d => d.Name == "bauble");
+ Assert.Equal(2, bauble.SourceEntities.Count);
+ // The frame keeps its window; the loose square inside it is a part of its own.
+ Assert.Equal(8, drawings.Single(d => d.Name == "parts-3").SourceEntities.Count);
+ Assert.Equal(4, drawings.Single(d => d.Name == "parts-4").SourceEntities.Count);
+ }));
+
+ [Fact]
+ public void SeparateOne_LeavesTheRestTogether_UnderTheFileName() => ArchUnitsTests.RunSta(() =>
+ WithFile(form =>
+ {
+ var list = Field(form, "fileList");
+ var excluded = list.SelectedItem!.Entities.OfType().Single(c => c.Radius < 5 && c.Center.X > 30);
+ list.SelectedItem.ExcludedEntityIds.Add(excluded.Id);
+
+ Assert.True(form.SeparateParts(new[] { 1 }));
+
+ Assert.Equal(new[] { "bauble", "parts" }, list.Items.Select(i => i.Name));
+ Assert.Equal("bauble", list.SelectedItem!.Name);
+ Assert.Equal(new[] { excluded.Id }, list.SelectedItem.ExcludedEntityIds);
+ Assert.Empty(list.Items.Single(i => i.Name == "parts").ExcludedEntityIds);
+ WaitFor(form.BodiesSearch);
+ Assert.Equal(1, form.CurrentBodies!.Count);
+ }));
+
+ [Fact]
+ public void OnePart_OffersNoSeparation() => ArchUnitsTests.RunSta(() =>
+ WithFile(form =>
+ {
+ Assert.Equal(1, form.CurrentBodies!.Count);
+ Assert.False(Field