feat(cad-converter): separate a file that draws several parts

A file such as a sheet of ornaments imported as one drawing, with every
part but the largest treated as a cutout. PartBodies (Core) now finds the
separate parts by contour nesting, and the CAD Converter offers a
Separate (N) button plus Separate This Part / Separate All Parts in the
entity menu. Each part keeps its entity IDs, so roles, exclusions,
breakoffs, tabbed cutouts and dimensions follow it; separation is refused
when a breakoff or tabbed cutout spans parts.

SVG import keeps element titles as labeled regions, which name the
separated parts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
ajandClaude Opus 5.5 committed 2026-11-20 20:53:08 -05:00
1 parent 1206f04114
commit c8ba250adc
16 files changed
+825 -7

No files matched your search

+1
View File
@@ -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
+229
View File
@@ -0,0 +1,229 @@
using System.Collections.Generic;
using System.Linq;
namespace OpenNest.Geometry
{
/// <summary>A name a source file gives to the geometry inside a region, such as an SVG group's title.</summary>
public sealed record LabeledRegion(string Name, Box Bounds);
/// <summary>
/// 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.
/// </summary>
public sealed class PartBodies
{
private readonly List<Body> bodies;
private readonly Dictionary<Entity, int> outlineOwners = new();
private PartBodies(List<Body> 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;
}
/// <summary>The number of parts found; fewer than two means there is nothing to separate.</summary>
public int Count => bodies.Count;
/// <summary>The bounds of part <paramref name="index"/>'s outer outline.</summary>
public Box Bounds(int index) => bodies[index].Outer.BoundingBox;
/// <summary>
/// Finds the parts outlined by <paramref name="outlines"/>: the cut entities, without marks or
/// display-only geometry. Parts are numbered in reading order, top row first, left to right.
/// </summary>
public static PartBodies Find(IEnumerable<Entity> 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));
}
/// <summary>The part an entity belongs to, or -1 when no part was found.</summary>
public int IndexOf(Entity entity)
{
if (outlineOwners.TryGetValue(entity, out var owner))
return owner;
return IndexOf(RepresentativePoint(entity));
}
/// <summary>The innermost part whose outer outline holds <paramref name="point"/>, else the nearest part.</summary>
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;
}
/// <summary>Splits <paramref name="entities"/> by part, keeping their order; one list per part.</summary>
public List<List<Entity>> Group(IEnumerable<Entity> entities)
{
var groups = bodies.Select(_ => new List<Entity>()).ToList();
if (groups.Count == 0)
return groups;
foreach (var entity in entities)
groups[IndexOf(entity)].Add(entity);
return groups;
}
/// <summary>
/// The name <paramref name="labels"/> give part <paramref name="index"/>: the smallest labeled
/// region that holds its whole outline and no other part's, or null when there is none.
/// </summary>
public string NameOf(int index, IEnumerable<LabeledRegion> 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<Body> ReadingOrder(List<Body> bodies)
{
var remaining = bodies.OrderByDescending(b => b.Outer.BoundingBox.Top).ToList();
var ordered = new List<Body>();
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<Shape> Contours { get; } = new();
}
}
}
+6
View File
@@ -31,6 +31,12 @@ namespace OpenNest.IO
/// </summary>
public List<Bend> Bends { get; set; } = new List<Bend>();
/// <summary>
/// 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.
/// </summary>
public List<LabeledRegion> Labels { get; set; } = new List<LabeledRegion>();
public List<Bending.BendRepairReport> BendRepairReports { get; set; } =
new List<Bending.BendRepairReport>();
+1
View File
@@ -96,6 +96,7 @@ namespace OpenNest.IO
Entities = dxf.Entities,
RawEntities = dxf.RawEntities,
Bends = bends,
Labels = dxf.Labels ?? new List<LabeledRegion>(),
BendRepairReports = repairReports,
Bounds = dxf.Entities.GetBoundingBox(),
SourcePath = path,
+4
View File
@@ -21,6 +21,10 @@ namespace OpenNest.IO
/// detected from <see cref="Document"/> instead.
/// </summary>
public List<Bend> Bends { get; set; }
/// <summary>Names the file gives to regions of its geometry, such as SVG titles; empty when none.</summary>
public List<LabeledRegion> Labels { get; set; } = new();
public List<string> Warnings { get; set; } = new();
}
}
+27
View File
@@ -58,6 +58,7 @@ namespace OpenNest.IO
private readonly List<Arc> arcs = new List<Arc>();
private readonly List<Circle> circles = new List<Circle>();
private readonly List<Bend> bends = new List<Bend>();
private readonly List<LabeledRegion> labels = new List<LabeledRegion>();
private readonly HashSet<XElement> activeUses = new HashSet<XElement>();
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<Entity>()
.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)
{
+115
View File
@@ -0,0 +1,115 @@
using OpenNest.Geometry;
namespace OpenNest.Tests.Geometry;
public class PartBodiesTests
{
private static List<Entity> 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));
}
}
+19
View File
@@ -50,6 +50,25 @@ namespace OpenNest.Tests.IO
Assert.Equal(expected, width, 6);
}
[Fact]
public void ElementTitlesNameTheGeometryTheyDraw()
{
var result = Import(Svg(
"<title>sheet</title>"
+ "<g transform='translate(1 1)'><title> star </title><path d='M0 0H2V2H0Z'/></g>"
+ "<path d='M5 5H7V7H5Z'><title>tag</title></path>"
+ "<g><title>empty</title></g>"
+ "<path d='M8 8H9V9H8Z'/>"));
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()
{
@@ -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;
/// <summary>
/// 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.
/// </summary>
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 =
"<svg xmlns='http://www.w3.org/2000/svg' width='100mm' height='30mm' viewBox='0 0 100 30'>"
+ "<title>sheet</title>"
+ "<g><title>tag</title><path d='M0 0H20V20H0Z M8 4A2 2 0 1 0 12 4A2 2 0 1 0 8 4Z'/></g>"
+ "<g><title>bauble</title><circle cx='40' cy='10' r='10'/><circle cx='40' cy='3' r='1'/></g>"
+ "<path d='M60 0H90V30H60Z M65 5H85V25H65Z'/>"
+ "<path d='M70 10H80V20H70Z'/>"
+ "</svg>";
[Fact]
public void SeparateAll_GivesEachPartItsOwnDrawing() => ArchUnitsTests.RunSta(() =>
WithFile(form =>
{
var list = Field<FileListControl>(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<FileListControl>(form, "fileList");
var excluded = list.SelectedItem!.Entities.OfType<Circle>().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<Button>(form, "btnSeparate").Visible);
Assert.False(form.SeparateParts(null));
}, "<svg xmlns='http://www.w3.org/2000/svg' width='20mm' height='20mm' viewBox='0 0 20 20'>"
+ "<path d='M0 0H20V20H0Z M8 4A2 2 0 1 0 12 4A2 2 0 1 0 8 4Z'/></svg>"));
private static void WithFile(Action<CadConverterForm> test, string svg = ThreeParts)
{
var directory = Directory.CreateTempSubdirectory("opennest-separate-").FullName;
try
{
var path = Path.Combine(directory, "parts.svg");
File.WriteAllText(path, svg);
using var form = new CadConverterForm { DrawingUnits = Units.Millimeters };
Show(form);
form.AddFile(path);
WaitFor(form.BodiesSearch);
if (svg == ThreeParts)
{
Assert.Equal(4, form.CurrentBodies!.Count);
var button = Field<Button>(form, "btnSeparate");
Assert.True(button.Visible);
Assert.Equal("Separate (4)", button.Text);
Assert.Equal(4, Field<EntityView>(form, "entityView1").SeparablePartCount);
}
test(form);
form.Close();
}
finally
{
Directory.Delete(directory, true);
}
}
private static void WaitFor(Task task)
{
var deadline = DateTime.UtcNow.AddSeconds(30);
while (!task.IsCompleted && DateTime.UtcNow < deadline)
Application.DoEvents();
Assert.True(task.IsCompleted, "The parts search did not finish.");
}
private static T Field<T>(object owner, string name) =>
(T)typeof(CadConverterForm).GetField(name, BindingFlags.Instance | BindingFlags.NonPublic)!.GetValue(owner)!;
}
+19
View File
@@ -18,6 +18,8 @@ namespace OpenNest.Controls
Include,
AddRadiusDimension,
AddDiameterDimension,
SeparatePart,
SeparateAllParts,
}
public sealed class EntityActionEventArgs : EventArgs
@@ -54,6 +56,12 @@ namespace OpenNest.Controls
public IReadOnlyCollection<Entity> SelectedEntities => selectedEntities;
/// <summary>
/// How many separate parts the shown drawing holds; at two or more the entity menu offers
/// to separate them.
/// </summary>
public int SeparablePartCount { get; set; }
public event EventHandler<EntityActionEventArgs> EntityActionRequested;
public void ClearSelection()
@@ -213,6 +221,17 @@ namespace OpenNest.Controls
menu.Items.Add(diameter);
}
if (SeparablePartCount >= 2)
{
menu.Items.Add(new ToolStripSeparator());
var part = new ToolStripMenuItem("Separate This Part");
part.Click += (s, e) => RaiseEntityAction(EntityAction.SeparatePart, selection);
menu.Items.Add(part);
var all = new ToolStripMenuItem($"Separate All {SeparablePartCount} Parts");
all.Click += (s, e) => RaiseEntityAction(EntityAction.SeparateAllParts, selection);
menu.Items.Add(all);
}
menu.Closed += (s, e) => BeginInvoke(new Action(menu.Dispose));
menu.Show(this, location);
}
+27 -7
View File
@@ -41,6 +41,9 @@ namespace OpenNest.Controls
public Box Bounds { get; set; }
public int EntityCount { get; set; }
public List<CadText> Texts { get; set; } = new();
/// <summary>Names the source file gives to regions of its geometry; they name the parts it separates into.</summary>
public List<LabeledRegion> Labels { get; set; } = new();
}
public class FileListControl : Control
@@ -93,17 +96,34 @@ namespace OpenNest.Controls
public FileListItem SelectedItem =>
selectedIndex >= 0 && selectedIndex < items.Count ? items[selectedIndex] : null;
public void AddItem(FileListItem item)
private static readonly Comparer<FileListItem> ByName = Comparer<FileListItem>.Create(
(a, b) => string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase));
private int InsertSorted(FileListItem item)
{
var index = items.BinarySearch(
item,
Comparer<FileListItem>.Create(
(a, b) => string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase)
)
);
var index = items.BinarySearch(item, ByName);
if (index < 0)
index = ~index;
items.Insert(index, item);
return index;
}
/// <summary>Replaces the item at <paramref name="index"/> with others, selecting the first of them.</summary>
public void ReplaceItem(int index, IReadOnlyList<FileListItem> replacements)
{
items.RemoveAt(index);
foreach (var item in replacements)
InsertSorted(item);
selectedIndex = replacements.Count > 0 ? items.IndexOf(replacements[0]) : System.Math.Min(index, items.Count - 1);
UpdateScrollBar();
EnsureVisible(selectedIndex);
Invalidate();
SelectedIndexChanged?.Invoke(this, selectedIndex);
}
public void AddItem(FileListItem item)
{
var index = InsertSorted(item);
if (items.Count == 1)
{
+18
View File
@@ -31,6 +31,7 @@ namespace OpenNest.Forms
lblEntityCount = new System.Windows.Forms.Label();
btnSplit = new System.Windows.Forms.Button();
btnSimplify = new System.Windows.Forms.Button();
btnSeparate = new System.Windows.Forms.Button();
btnExport = new System.Windows.Forms.Button();
btnHoleTable = new System.Windows.Forms.Button();
chkShowOriginal = new System.Windows.Forms.CheckBox();
@@ -169,6 +170,7 @@ namespace OpenNest.Forms
detailBar.Controls.Add(txtCustomer);
detailBar.Controls.Add(lblDimensions);
detailBar.Controls.Add(lblEntityCount);
detailBar.Controls.Add(btnSeparate);
detailBar.Controls.Add(btnSplit);
detailBar.Controls.Add(btnSimplify);
detailBar.Controls.Add(btnExport);
@@ -251,6 +253,21 @@ namespace OpenNest.Forms
lblEntityCount.Size = new System.Drawing.Size(0, 15);
lblEntityCount.TabIndex = 5;
//
// btnSeparate
//
btnSeparate.AutoSize = true;
btnSeparate.BackColor = System.Drawing.Color.FromArgb(60, 120, 60);
btnSeparate.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
btnSeparate.Font = new System.Drawing.Font("Segoe UI", 9F);
btnSeparate.ForeColor = System.Drawing.Color.White;
btnSeparate.Margin = new System.Windows.Forms.Padding(0, 0, 10, 0);
btnSeparate.Name = "btnSeparate";
btnSeparate.Size = new System.Drawing.Size(85, 27);
btnSeparate.TabIndex = 6;
btnSeparate.Text = "Separate...";
btnSeparate.UseVisualStyleBackColor = false;
btnSeparate.Visible = false;
//
// btnSplit
//
btnSplit.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
@@ -444,6 +461,7 @@ namespace OpenNest.Forms
private System.Windows.Forms.NumericUpDown numQuantity;
private System.Windows.Forms.TextBox txtCustomer;
private System.Windows.Forms.Button btnSplit;
private System.Windows.Forms.Button btnSeparate;
private System.Windows.Forms.Button btnSimplify;
private System.Windows.Forms.Button btnExport;
private System.Windows.Forms.Button btnHoleTable;
+195
View File
@@ -0,0 +1,195 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using OpenNest.Controls;
using OpenNest.Converters;
using OpenNest.Geometry;
namespace OpenNest.Forms
{
// Separating a file that draws several parts (a sheet of ornaments, say) into one drawing per part.
public partial class CadConverterForm
{
private PartBodies currentBodies;
private FileListItem bodiesItem;
private int bodiesVersion;
/// <summary>The parts found in the shown item, once the background search has finished; null before.</summary>
internal PartBodies CurrentBodies => bodiesItem == CurrentItem ? currentBodies : null;
/// <summary>Completes when the parts search started by the last item load or filter change has finished.</summary>
internal Task BodiesSearch { get; private set; } = Task.CompletedTask;
// The outlines that make parts: shown entities that cut, on material layers.
private static List<Entity> Outlines(FileListItem item) =>
item.Entities
.Where(e => e.Layer is { IsVisible: true } && e.IsVisible
&& SpecialLayers.IsMaterial(e.Layer)
&& EntityRoles.Of(e, item.EntityRoles) == EntityRole.Cut)
.ToList();
// Finds the item's parts off the UI thread, as the Simplify check does, and shows the
// Separate button when there are two or more.
private void RefreshSeparable(FileListItem item)
{
var version = ++bodiesVersion;
currentBodies = null;
bodiesItem = null;
ShowSeparable(0);
if (item == null)
{
BodiesSearch = Task.CompletedTask;
return;
}
var outlines = Outlines(item);
BodiesSearch = Task.Run(() => PartBodies.Find(outlines))
.ContinueWith(
t =>
{
if (version != bodiesVersion || item != CurrentItem || !t.IsCompletedSuccessfully)
return;
currentBodies = t.Result;
bodiesItem = item;
ShowSeparable(t.Result.Count);
},
CancellationToken.None,
TaskContinuationOptions.None,
TaskScheduler.FromCurrentSynchronizationContext());
}
private void ShowSeparable(int count)
{
var separable = count >= 2;
btnSeparate.Visible = separable;
btnSeparate.Text = separable ? $"Separate ({count})" : "Separate...";
entityView1.SeparablePartCount = separable ? count : 0;
}
private void OnSeparateClicked(object sender, EventArgs e) => SeparateParts(null);
/// <summary>
/// Replaces the shown item with one item per part. With <paramref name="chosen"/>, only those
/// parts leave; the rest stay together under the item's name. Returns false when nothing changed.
/// </summary>
internal bool SeparateParts(IReadOnlyCollection<int> chosen)
{
var item = CurrentItem;
var bodies = CurrentBodies;
if (item == null || bodies == null || bodies.Count < 2)
return false;
var spanning = SpanningFeature(item, bodies);
if (spanning != null)
{
ShowSeparateMessage($"A {spanning} joins more than one of these parts, so they cannot be separated. "
+ "Remove it first.");
return false;
}
if (programEditor.IsDirty && !ConfirmSeparate(
"Separating rebuilds each part's program, so your edits to this program will be lost. Separate anyway?"))
return false;
var leaving = (chosen ?? Enumerable.Range(0, bodies.Count)).Distinct().OrderBy(i => i).ToList();
var staying = Enumerable.Range(0, bodies.Count).Except(leaving).ToList();
var taken = new HashSet<string>(
fileList.Items.Where(i => i != item).Select(i => i.Name), StringComparer.OrdinalIgnoreCase);
var replacements = new List<FileListItem>();
foreach (var index in leaving)
{
var name = UniqueName(bodies.NameOf(index, item.Labels) ?? $"{item.Name}-{index + 1}", taken);
replacements.Add(Slice(item, bodies, new HashSet<int> { index }, name));
}
if (staying.Count > 0)
replacements.Add(Slice(item, bodies, staying.ToHashSet(), UniqueName(item.Name, taken)));
programEditor.Clear();
fileList.ReplaceItem(fileList.SelectedIndex, replacements);
return true;
}
internal virtual void ShowSeparateMessage(string message) =>
MessageBox.Show(this, message, "Separate Parts", MessageBoxButtons.OK, MessageBoxIcon.Information);
internal virtual bool ConfirmSeparate(string message) =>
MessageBox.Show(this, message, "Separate Parts", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning)
== DialogResult.OK;
private void SeparateSelectedParts(IReadOnlyList<Entity> selection)
{
var bodies = CurrentBodies;
if (bodies == null)
return;
var chosen = selection.Select(bodies.IndexOf).Where(i => i >= 0).ToHashSet();
if (chosen.Count > 0)
SeparateParts(chosen);
}
// A breakoff or tabbed cutout whose edges lie in more than one part cannot follow either.
private static string SpanningFeature(FileListItem item, PartBodies bodies)
{
var owners = new Dictionary<Guid, int>();
foreach (var entity in item.Entities)
owners.TryAdd(entity.Id, bodies.IndexOf(entity));
bool Spans(IEnumerable<Guid> ids) =>
ids.Where(owners.ContainsKey).Select(id => owners[id]).Distinct().Count() > 1;
if (item.Breakoffs.Any(b => Spans(b.EdgeIds)))
return "breakoff";
if (item.TabbedCutouts.Any(c => Spans(c.EdgeIds)))
return "tabbed cutout";
return null;
}
// The part of an item that lies in the given parts: its entities keep their IDs, so roles,
// exclusions, suppression, breakoffs, tabbed cutouts and dimensions follow them; bends and
// text go by position.
private static FileListItem Slice(FileListItem item, PartBodies bodies, HashSet<int> parts, string name)
{
bool Owns(Entity e) => parts.Contains(bodies.IndexOf(e));
bool OwnsPoint(Vector p) => parts.Contains(bodies.IndexOf(p));
var entities = item.Entities.Where(Owns).ToList();
var ids = entities.Select(e => e.Id).ToHashSet();
bool OwnsIds(IEnumerable<Guid> edgeIds) => edgeIds.Any(ids.Contains);
return new FileListItem
{
Name = name,
Customer = item.Customer,
Quantity = item.Quantity,
Path = item.Path,
Entities = entities,
OriginalEntities = item.OriginalEntities?.Where(Owns).ToList(),
RawEntities = item.RawEntities?.Where(Owns).ToList(),
Bends = item.Bends?
.Where(b => b.SourceEntity != null
? Owns(b.SourceEntity)
: OwnsPoint(new Vector((b.StartPoint.X + b.EndPoint.X) / 2, (b.StartPoint.Y + b.EndPoint.Y) / 2)))
.ToList() ?? new List<Bending.Bend>(),
Breakoffs = item.Breakoffs.Where(b => OwnsIds(b.EdgeIds)).ToList(),
TabbedCutouts = item.TabbedCutouts.Where(c => OwnsIds(c.EdgeIds)).ToList(),
Dimensions = item.Dimensions.Where(d => ids.Contains(d.EntityId)).ToList(),
SuppressedEntityIds = item.SuppressedEntityIds?.Where(ids.Contains).ToHashSet(),
ExcludedEntityIds = item.ExcludedEntityIds.Where(ids.Contains).ToHashSet(),
EntityRoles = item.EntityRoles.Where(r => ids.Contains(r.Key)).ToDictionary(r => r.Key, r => r.Value),
Bounds = entities.GetBoundingBox(),
EntityCount = entities.Count,
Texts = item.Texts?.Where(t => OwnsPoint(t.Position)).ToList() ?? new List<CadText>(),
Labels = item.Labels,
};
}
private static string UniqueName(string name, HashSet<string> taken)
{
var unique = name;
for (var n = 2; taken.Contains(unique); n++)
unique = $"{name} ({n})";
taken.Add(unique);
return unique;
}
}
}
+13
View File
@@ -74,6 +74,7 @@ namespace OpenNest.Forms
entityView1.TextConvertRequested += OnTextConvertRequested;
entityView1.EntityActionRequested += OnEntityActionRequested;
btnSplit.Click += OnSplitClicked;
btnSeparate.Click += OnSeparateClicked;
numQuantity.ValueChanged += OnQuantityChanged;
txtCustomer.TextChanged += OnCustomerChanged;
cboBendDetector.SelectedIndexChanged += OnBendDetectorChanged;
@@ -130,6 +131,7 @@ namespace OpenNest.Forms
Bounds = result.Bounds,
EntityCount = result.Entities.Count,
Texts = ExtractTexts(result.Document),
Labels = result.Labels,
};
if (InvokeRequired)
@@ -262,6 +264,7 @@ namespace OpenNest.Forms
entityView1.ZoomToFit();
CheckSimplifiable(item);
RefreshSeparable(item);
RefreshHoleTable();
}
@@ -324,6 +327,7 @@ namespace OpenNest.Forms
entityView1.DimensionLayouts = Array.Empty<DimensionLayout>();
entityView1.Invalidate();
RefreshHoleTable();
RefreshSeparable(null);
}
private void OnFilterChanged(object sender, EventArgs e)
@@ -339,6 +343,7 @@ namespace OpenNest.Forms
RefreshBreakoffs(item);
RefreshTabbedCutouts(item);
RefreshHoleTable();
RefreshSeparable(item);
staleProgram = true;
}
@@ -1561,6 +1566,14 @@ namespace OpenNest.Forms
switch (e.Action)
{
case EntityAction.SeparatePart:
SeparateSelectedParts(e.Entities);
return;
case EntityAction.SeparateAllParts:
SeparateParts(null);
return;
case EntityAction.AddRadiusDimension:
case EntityAction.AddDiameterDimension:
AddRadialDimensions(item, e.Entities,
+25
View File
@@ -0,0 +1,25 @@
# Separating parts
A file can draw several parts, such as a sheet of ornaments. Import still makes one item of it, whose program would cut every part as one drawing. The CAD Converter offers to separate it.
## Finding the parts
`PartBodies.Find` (Core) takes the item's outlines: shown entities that cut (`EntityRoles.Of` is `Cut`) on material layers. Closed contours are sorted by what holds what:
- A contour no other contour holds starts a part. The contours directly inside it are its holes, and a contour inside one of those holes starts another part (a part in a hole is never treated as a hole).
- One contour holds another when its bounds hold the other's, it is larger, and its polygon holds most of a sample of the other's vertices, so a vertex on a shared edge cannot decide alone.
- Open chains never start a part.
- Every other entity (open paths, marks, hidden entities, bend lines, text) goes to the innermost part whose outline holds a point on it, or to the nearest part when none does.
- Parts are numbered in reading order: rows from the top, each left to right.
The search runs off the UI thread whenever an item loads or its filters change. With two or more parts, the **Separate (N)** button shows in the detail bar, and the entity right-click menu adds **Separate This Part** and **Separate All N Parts**.
## What a separated item keeps
Each new item takes the entities of its part, with their IDs, so entity roles, exclusions, suppression, breakoffs, tabbed cutouts and dimensions follow them. Bends go with their source entity or, without one, their midpoint; text goes by its position. Quantity, customer and source path are copied, so every drawing records the same file. `BuildDrawing` then gives each its own source offset.
Names come from the file's labels (SVG element titles): the smallest label region that holds the part's outline and no other part's. Without one, the part is `<file>-<number>`. Names are made unique within the list.
**Separate This Part** moves only the chosen parts out; the rest stay together under the item's name.
Separation is refused when a breakoff or tabbed cutout has edges in more than one part. Edits made in the Program tab are lost, after a warning, since each part's program is rebuilt.
+1
View File
@@ -26,6 +26,7 @@ Import takes path centerlines: `path`, `rect` (with rounded corners), `circle`,
- Text, images, nested `svg`, `use` of a `symbol`, and shapes sized in percentages are skipped and listed in `CadImportResult.Warnings`.
- Layers come from `data-layer`, an Inkscape layer label, or the `id` of a top-level group (Illustrator). `ETCH`, `SCRIBE`, `RAPID` and `PLATE` are dropped, so an exported plate reads back as its parts.
- The file's DTD may parse, because older Illustrator files declare namespaces in one, but external fetches are off and entity expansion is capped.
- An element's `<title>` (not the root's) is kept in `CadImportResult.Labels` as a name for the region its geometry covers. Labels never change geometry; they name the parts when the CAD Converter [separates a file](separate-parts.md).
- Each `line` on a `BEND` layer is a bend, as a center line on a DXF's `BEND` layer is; nothing else there is read. Its `data-bend-direction` (`up` or `down`), `data-bend-angle` (degrees), `data-bend-radius` (scaled like the line) and `data-bend-note` fill in the bend when present. `CadImportOptions.DetectBends` false ignores them; the detector choice does not apply.
## What export writes