refactor: fold duplicated helpers into one shared copy each

Roslyn Bridge's duplicate scan found helpers copied verbatim between
projects, so a fix to one copy could silently miss the other. Each copy
now calls a single implementation with the same body:

- boundary nearest point: ClipperBridge.NearestBoundaryPoint (ErodedPierce,
  ScrapPierceSearch)
- nesting profile of a part: NestLayoutCheck.Profile (CommonLinePair)
- part label points: PartLabels in OpenNest.Desktop (WinForms LayoutPart)
- copied common-line groups: CommonLineGroup.AmongParts (ActionClone,
  PlaceTool)
- shared saved cutting parameters: CuttingParametersSerializer.SharedBy
  (MCP, Console)
- bounding box of boxes: generic BoundingBox.GetBoundingBox<T> (rectangle
  packing items)
- box proximity: Clearance.BoxesWithin (Expander)

Behavior is unchanged: every moved body is identical to the copies it
replaces, so the fill change in Expander and rectangle packing skips the
problem-nest corpus. Core, IO, Desktop and Engine suites and the label,
clone and common-line WinForms tests pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
ajandClaude Opus 5.5 committed 2026-11-21 17:50:53 -05:00
1 parent 4b3d7d57aa
commit e011fe8290
17 files changed
+96 -204

No files matched your search

+2 -10
View File
@@ -881,16 +881,8 @@ static class NestConsole
return true;
}
/// <summary>The plates' saved settings when every plate carries the same ones; otherwise null.</summary>
static CuttingParameters SavedCuttingParameters(IReadOnlyList<Plate> plates)
{
var first = plates[0].CuttingParameters;
if (first == null)
return null;
var json = CuttingParametersSerializer.Serialize(first);
return plates.All(p => p.CuttingParameters != null
&& CuttingParametersSerializer.Serialize(p.CuttingParameters) == json) ? first : null;
}
static CuttingParameters SavedCuttingParameters(IReadOnlyList<Plate> plates) =>
CuttingParametersSerializer.SharedBy(plates);
/// <summary>Reports synchronously, so phase lines print in order with the summary.</summary>
sealed class PlanningProgress(int plateCount) : IProgress<CuttingPlanProgress>
@@ -120,24 +120,7 @@ namespace OpenNest.CNC.CuttingStrategy
System.Math.Max(System.Math.Min(width, length) / 100, System.Math.Pow(10, -ClipperBridge.Precision));
// The closest point of the region's boundary; targets lie on the wall, outside it.
private static Vector Nearest(List<PathD> paths, Vector target)
{
var best = default(Vector);
var bestDistance = double.PositiveInfinity;
foreach (var path in paths)
for (var i = 0; i < path.Count; i++)
{
var a = new Vector(path[i].x, path[i].y);
var b = new Vector(path[(i + 1) % path.Count].x, path[(i + 1) % path.Count].y);
var point = new Line(a, b).ClosestPointTo(target);
var distance = point.DistanceTo(target);
if (distance < bestDistance)
{
bestDistance = distance;
best = point;
}
}
return best;
}
private static Vector Nearest(List<PathD> paths, Vector target) =>
ClipperBridge.NearestBoundaryPoint(paths, target);
}
}
@@ -45,6 +45,28 @@ namespace OpenNest.CommonLines
public bool Contains(Part part) => members.Any(member => ReferenceEquals(member, part));
/// <summary>
/// The plate's groups that join two or more of <paramref name="parts"/>, as indexes into
/// <paramref name="parts"/>, so copies of those parts can be joined the same way. Empty when
/// <paramref name="plate"/> is null.
/// </summary>
public static List<(int[] Members, double Kerf)> AmongParts(Plate plate, IReadOnlyList<Part> parts)
{
ArgumentNullException.ThrowIfNull(parts);
var groups = new List<(int[] Members, double Kerf)>();
if (plate == null)
return groups;
foreach (var group in plate.CommonLines)
{
var indexes = Enumerable.Range(0, parts.Count).Where(i => group.Contains(parts[i])).ToArray();
if (indexes.Length >= 2)
groups.Add((indexes, group.Kerf));
}
return groups;
}
/// <summary>Drops a member (a part removed from the plate); true when it was one.</summary>
internal bool Remove(Part part) => members.RemoveAll(member => ReferenceEquals(member, part)) > 0;
}
+6 -2
View File
@@ -1,11 +1,15 @@
using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq;
namespace OpenNest.Geometry
{
public static class BoundingBox
{
public static Box GetBoundingBox(this IList<Box> boxes)
public static Box GetBoundingBox(this IList<Box> boxes) => GetBoundingBox<Box>(boxes);
/// <summary>The box around every box in the list, or <see cref="Box.Empty"/> when it is empty.</summary>
public static Box GetBoundingBox<T>(this IList<T> boxes)
where T : Box
{
if (boxes.Count == 0)
return Box.Empty;
+2 -1
View File
@@ -359,7 +359,8 @@ namespace OpenNest.Geometry
);
}
private static bool BoxesWithin(Box a, Box b, double distance)
/// <summary>Whether the boxes are no more than <paramref name="distance"/> apart on both axes.</summary>
internal static bool BoxesWithin(Box a, Box b, double distance)
{
return !(
a.Right + distance < b.Left
+24
View File
@@ -23,6 +23,30 @@ namespace OpenNest.Geometry
private const double ValidationJoinFactor = 0.1;
/// <summary>
/// The closest point to <paramref name="target"/> on any edge of the closed
/// <paramref name="paths"/>; the first edge wins a tie, and an empty set gives the default vector.
/// </summary>
internal static Vector NearestBoundaryPoint(List<PathD> paths, Vector target)
{
var best = default(Vector);
var bestDistance = double.PositiveInfinity;
foreach (var path in paths)
for (var i = 0; i < path.Count; i++)
{
var a = new Vector(path[i].x, path[i].y);
var b = new Vector(path[(i + 1) % path.Count].x, path[(i + 1) % path.Count].y);
var point = new Line(a, b).ClosestPointTo(target);
var distance = point.DistanceTo(target);
if (distance < bestDistance)
{
bestDistance = distance;
best = point;
}
}
return best;
}
/// <summary>
/// Converts a polygon to a Clipper path, dropping the closing vertex and
/// orienting it positive (CCW) or negative (CW).
+3 -17
View File
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using OpenNest.CommonLines;
using OpenNest.Desktop.Rendering;
using OpenNest.Engine.Fill;
using OpenNest.Geometry;
@@ -58,23 +59,8 @@ public sealed class PlaceTool : PlateTool
// The common-line groups among the copied parts, by index into the copy, so each placement
// joins its copies the same way. Read now: Cut removes the sources, and their groups, next.
private static List<(int[] Members, double Kerf)> CopiedCommonLines(
Plate plate, List<Part> copied)
{
var groups = new List<(int[] Members, double Kerf)>();
if (plate == null)
return groups;
foreach (var group in plate.CommonLines)
{
var members = Enumerable.Range(0, copied.Count)
.Where(i => group.Contains(copied[i]))
.ToArray();
if (members.Length >= 2)
groups.Add((members, group.Kerf));
}
return groups;
}
Plate plate, List<Part> copied) =>
CommonLineGroup.AmongParts(plate, copied);
/// <summary>
/// Moves the previews' lower-left corner to the pointer. A move to the screen point last seen
@@ -140,25 +140,8 @@ internal sealed class ScrapPierceSearch
}
// The closest point of the clear region's boundary; targets lie on material, outside it.
private static Vector Nearest(List<PathD> paths, Vector target)
{
var best = default(Vector);
var bestDistance = double.PositiveInfinity;
foreach (var path in paths)
for (var i = 0; i < path.Count; i++)
{
var a = new Vector(path[i].x, path[i].y);
var b = new Vector(path[(i + 1) % path.Count].x, path[(i + 1) % path.Count].y);
var point = new Line(a, b).ClosestPointTo(target);
var distance = point.DistanceTo(target);
if (distance < bestDistance)
{
bestDistance = distance;
best = point;
}
}
return best;
}
private static Vector Nearest(List<PathD> paths, Vector target) =>
ClipperBridge.NearestBoundaryPoint(paths, target);
// Outlines flattened as conservatively as ClipperBridge.ToRegion: the perimeter never inside
// its curves, holes never outside theirs. A part's own holes are not scrap for its perimeter.
+1 -9
View File
@@ -1451,15 +1451,7 @@ namespace OpenNest.Engine.Fill
return clone;
}
private static bool BoxOverlap(Box a, Box b, double slack)
{
return !(
a.Right + slack < b.Left
|| b.Right + slack < a.Left
|| a.Top + slack < b.Bottom
|| b.Top + slack < a.Bottom
);
}
private static bool BoxOverlap(Box a, Box b, double slack) => Clearance.BoxesWithin(a, b, slack);
}
}
}
@@ -5,7 +5,6 @@ using System.Linq;
using Clipper2Lib;
using OpenNest.CNC;
using OpenNest.CommonLines;
using OpenNest.Converters;
using OpenNest.Engine.Jobs.Adapters;
using OpenNest.Geometry;
@@ -124,14 +123,7 @@ internal sealed class CommonLinePair
return new CommonLinePair(geometry, offset.X, offset.Y, spans.Sum(s => s.Length));
}
private static ShapeProfile? Profile(Part part)
{
var entities = ConvertProgram.ToGeometry(part.Program).ForNesting().ToList();
if (entities.Count == 0)
return null;
var profile = new ShapeProfile(entities);
return profile.Perimeter == null ? null : profile;
}
private static ShapeProfile? Profile(Part part) => NestLayoutCheck.Profile(part);
/// <summary>The union of both perimeters (arcs circumscribed) and the kerf between them, or
/// null when it is not one outline.</summary>
+1 -1
View File
@@ -783,7 +783,7 @@ public static class NestLayoutCheck
/// <summary>A part's clean nesting material, already rotated; null when it has no closed
/// perimeter.</summary>
private static ShapeProfile Profile(Part part)
internal static ShapeProfile Profile(Part part)
{
var entities = ConvertProgram
.ToGeometry(part.Program)
@@ -1,5 +1,6 @@
using System;
using System;
using OpenNest.Engine.Fill;
using OpenNest.Geometry;
using OpenNest.Math;
namespace OpenNest.Engine.RectanglePacking
-29
View File
@@ -1,4 +1,3 @@
using System.Collections.Generic;
using OpenNest.Geometry;
using OpenNest.Math;
@@ -27,32 +26,4 @@ namespace OpenNest.Engine.RectanglePacking
};
}
}
internal static class ItemListExtensions
{
public static Box GetBoundingBox(this IList<Item> items)
{
if (items.Count == 0)
return Box.Empty;
double minX = items[0].X;
double minY = items[0].Y;
double maxX = items[0].Right;
double maxY = items[0].Top;
foreach (var box in items)
{
if (box.Left < minX)
minX = box.Left;
if (box.Right > maxX)
maxX = box.Right;
if (box.Bottom < minY)
minY = box.Bottom;
if (box.Top > maxY)
maxY = box.Top;
}
return new Box(minX, minY, maxX - minX, maxY - minY);
}
}
}
@@ -1,4 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using OpenNest.CNC.CuttingStrategy;
using static OpenNest.IO.CuttingParametersDto;
@@ -23,6 +25,23 @@ public static class CuttingParametersSerializer
return JsonSerializer.Serialize(dto, JsonOptions);
}
/// <summary>
/// The plates' saved settings when every plate carries the same ones (compared as serialized
/// settings); otherwise null.
/// </summary>
/// <exception cref="ArgumentException">No plates.</exception>
public static CuttingParameters SharedBy(IReadOnlyList<Plate> plates)
{
ArgumentNullException.ThrowIfNull(plates);
if (plates.Count == 0)
throw new ArgumentException("At least one plate is needed.", nameof(plates));
var first = plates[0].CuttingParameters;
if (first == null)
return null;
var json = Serialize(first);
return plates.All(p => p.CuttingParameters != null && Serialize(p.CuttingParameters) == json) ? first : null;
}
/// <summary>Reads desktop settings with their historical defaults and angle fallback.</summary>
public static CuttingParameters Deserialize(string json)
{
+2 -10
View File
@@ -156,15 +156,7 @@ namespace OpenNest.Mcp.Tools
+ "Save with save_nest to keep it.";
}
/// <summary>The plates' saved settings when every plate carries the same ones; otherwise null.</summary>
private static CuttingParameters SavedCuttingParameters(IReadOnlyList<Plate> plates)
{
var first = plates[0].CuttingParameters;
if (first == null)
return null;
var json = CuttingParametersSerializer.Serialize(first);
return plates.All(p => p.CuttingParameters != null
&& CuttingParametersSerializer.Serialize(p.CuttingParameters) == json) ? first : null;
}
private static CuttingParameters SavedCuttingParameters(IReadOnlyList<Plate> plates) =>
CuttingParametersSerializer.SharedBy(plates);
}
}
+3 -15
View File
@@ -2,6 +2,7 @@ using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows.Forms;
using OpenNest.CommonLines;
using OpenNest.Controls;
using OpenNest.CutOffs;
using OpenNest.Engine.Fill;
@@ -47,21 +48,8 @@ namespace OpenNest.Actions
// The common-line groups among the copied parts, by index into the copy, so each paste
// joins its clones the same way. Read now: Cut removes the sources, and their groups, next.
private static List<(int[] Members, double Kerf)> CopiedCommonLines(Plate plate, List<Part> copied)
{
var groups = new List<(int[] Members, double Kerf)>();
if (plate == null)
return groups;
foreach (var group in plate.CommonLines)
{
var members = Enumerable.Range(0, copied.Count).Where(i => group.Contains(copied[i])).ToArray();
if (members.Length >= 2)
groups.Add((members, group.Kerf));
}
return groups;
}
private static List<(int[] Members, double Kerf)> CopiedCommonLines(Plate plate, List<Part> copied) =>
CommonLineGroup.AmongParts(plate, copied);
// Re-flag on every reselect: a deselect elsewhere would otherwise leave the
// previews drawn with the solid fill of placed parts.
+4 -62
View File
@@ -6,6 +6,7 @@ using System.Linq;
using System.Windows.Forms;
using OpenNest.Controls;
using OpenNest.Converters;
using OpenNest.Desktop.Rendering;
using OpenNest.Geometry;
namespace OpenNest
@@ -13,7 +14,6 @@ namespace OpenNest
public class LayoutPart : IPart
{
private static Color selectedColor = Color.FromArgb(90, 150, 200, 255);
private const int LabelSearchCells = 20000;
// GDI+ objects are not thread-safe, so views on different UI threads each draw
// with their own; sharing one fails with "Object is currently in use elsewhere".
@@ -318,37 +318,8 @@ namespace OpenNest
/// The drawing's label point in its program frame; uses no GDI+ objects. The Drawing
/// Library grid's check passes an unlimited <paramref name="maxCells"/> to time the search.
/// </summary>
internal static Vector ComputeLabelPoint(Drawing drawing, int maxCells = LabelSearchCells)
{
var entities = ConvertProgram.ToGeometry(drawing.Program);
var nonRapid = entities.Where(e => SpecialLayers.IsMaterial(e.Layer)).ToList();
var shapes = ShapeBuilder.GetShapes(nonRapid);
if (shapes.Count == 0)
{
var bbox = drawing.Program.BoundingBox();
return new Vector(
bbox.Location.X + bbox.Length / 2,
bbox.Location.Y + bbox.Width / 2
);
}
var profile = ShapeProfile.FromShapes(shapes);
var outer = profile.Perimeter.ToPolygonWithTolerance(0.1);
List<Polygon> holes = null;
if (profile.Cutouts.Count > 0)
{
holes = new List<Polygon>();
foreach (var cutout in profile.Cutouts)
holes.Add(cutout.ToPolygonWithTolerance(0.1));
}
// The label is cosmetic: a budget keeps any shape from stalling the paint.
return PolyLabel.Find(outer, holes, PolyLabel.ThicknessPrecision(outer, holes), maxCells);
}
internal static Vector ComputeLabelPoint(Drawing drawing, int maxCells = PartLabels.SearchCells) =>
PartLabels.LabelPoint(drawing, maxCells);
/// <summary>Rebuilds the part's paths from its program and maps them to the view.</summary>
public void Update(DrawControl plateView)
@@ -476,36 +447,7 @@ namespace OpenNest
// Every segment of a cut-off is a part of the one cut-off drawing with its own trimmed
// program. Labeled from the drawing, all of them would stack on one point and the view's
// culling would decide which number shows; label each at the middle of its own cut.
private Vector? CutOffSegmentLabelPoint()
{
var program = BasePart.Program;
if (!BasePart.BaseDrawing.IsCutOff || program?.Mode != CNC.Mode.Absolute)
return null;
double minX = double.MaxValue, minY = double.MaxValue;
double maxX = double.MinValue, maxY = double.MinValue;
Vector? position = null;
foreach (var code in program.Codes)
{
if (code is not CNC.Motion motion)
continue;
if (motion is not CNC.RapidMove && position is { } start)
{
foreach (var point in new[] { start, motion.EndPoint })
{
minX = System.Math.Min(minX, point.X);
minY = System.Math.Min(minY, point.Y);
maxX = System.Math.Max(maxX, point.X);
maxY = System.Math.Max(maxY, point.Y);
}
}
position = motion.EndPoint;
}
if (minX > maxX)
return null;
return new Vector((minX + maxX) / 2, (minY + maxY) / 2) + BasePart.Location;
}
private Vector? CutOffSegmentLabelPoint() => PartLabels.CutOffSegmentPoint(BasePart);
public void UpdateOffset(double spacing, double tolerance, Matrix matrix)
{