feat(common-line): place parts on common lines automatically at a chosen level

Slice 3 of common-line cutting. On costly plate (N26-295: 3/16 RA310S at about
$2,500 a sheet) pairing parts one kerf apart fits the part the spacing cannot:
the last plate's 38 parts fit on one 48x120 with Auto Nest only with pairs.

- Drawing Properties gains "Allow common line" (Drawing.AllowCommonLine, off by
  default because customer edge-quality needs vary). The nest's CommonLineUsage
  (Off / When it adds parts / Whenever available) is set in Auto Nest and seeded
  from Tools > Nest Defaults; both persist (nest.json, defaults.json).
- NestPipeline runs the ordinary solve, then, with a level on, trials where
  eligible parts are offered as kerf-gap pair compounds. Placed pairs expand into
  parts plus explicit NestJobCommonLine groups, are validated again, and
  CommonLineRanking keeps a trial only by the level: count first, then sheets;
  "when it adds parts" keeps the plain layout on a tie, "whenever" also takes a
  shorter cut or less material, never at the cost of a part. Engines, FillScore
  and their comparers are unchanged; Off asks the engine exactly what it did.
- NestLayoutCheck exempts members only through a sheet's explicit group list and
  only when the job allows common lines; materializing and committing create
  Plate.CommonLines.
- Server nesting writes common-line jobs as version 3 and replays the recorded
  trial answers, so the desktop binds the same groups.
- Fill Area honors the level through a PlateFillService overload.
- The benchmark gains --common-lines <level> --kerf <k>.

Benchmark (synthetic nests + N26-295, --parallel 1): with no flag and with
--common-lines off every engine matches the base commit; with a level on no
layout becomes invalid and three runs save a sheet at equal nested area.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
ajandClaude Opus 5.5 committed 2026-11-05 19:38:00 -05:00
1 parent f9b2713420
commit b026bd19d2
61 files changed
+2155 -118

No files matched your search

@@ -26,7 +26,8 @@ public static class DrawingJobMapper
constraints.EndAngle,
constraints.Allow180Equivalent
)
);
)
{ AllowCommonLine = drawing.AllowCommonLine };
}
public static NestJobPart FromItem(string partId, NestItem item)
@@ -44,7 +45,8 @@ public static class DrawingJobMapper
item.RotationEnd,
item.Drawing.Constraints?.Allow180Equivalent ?? false
)
);
)
{ AllowCommonLine = item.Drawing.AllowCommonLine };
}
/// <summary>Available stock is explicit; the legacy plate repeat count is not inventory.</summary>
@@ -98,7 +100,11 @@ public static class DrawingJobMapper
/// geometry in a later job, engine instance or Auto Nest run does not search again.</summary>
internal static Drawing CreateDrawing(NestJobPart part)
{
var drawing = new Drawing(part.Id, ToProgram(part.Geometry)) { Priority = part.Priority };
var drawing = new Drawing(part.Id, ToProgram(part.Geometry))
{
Priority = part.Priority,
AllowCommonLine = part.AllowCommonLine,
};
drawing.Quantity.Required = part.Quantity;
drawing.Constraints = new NestConstraints
{
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using OpenNest.Geometry;
namespace OpenNest.Engine.Jobs.Adapters;
@@ -37,4 +38,20 @@ public static class NestResultBinder
}
return parts;
}
/// <summary>The sheet's common-line groups over <paramref name="parts"/>, which
/// <see cref="Bind"/> returned for that sheet (same order).</summary>
public static IReadOnlyList<CommonLineGroup> BindCommonLines(NestJobPlateResult sheet, IReadOnlyList<Part> parts)
{
ArgumentNullException.ThrowIfNull(sheet);
ArgumentNullException.ThrowIfNull(parts);
var groups = new List<CommonLineGroup>(sheet.CommonLines.Count);
foreach (var group in sheet.CommonLines)
{
if (group.Placements.Count < 2 || group.Placements.Any(i => i < 0 || i >= parts.Count))
throw new ArgumentException("A common-line group names a placement the sheet does not have.", nameof(sheet));
groups.Add(new CommonLineGroup(group.Placements.Select(i => parts[i]), group.Kerf));
}
return groups;
}
}
@@ -52,8 +52,29 @@ public static class NestResultMaterializer
// Quantity=1 is set before the only attachment; Plate's event owns Nested accounting.
plate.Parts.Add(part);
}
AddCommonLines(plate, plate.Parts.ToList(), sheet.CommonLines);
nest.Plates.Add(plate);
}
return new MaterializedNestResult(nest, drawings);
}
/// <summary>
/// Adds a sheet's explicit common-line groups to <paramref name="plate"/>; members are the
/// sheet's placements by position in <paramref name="parts"/>. A group naming a position
/// outside the sheet, a part twice, a part of an earlier group, or fewer than two parts throws:
/// such a result is malformed.
/// </summary>
internal static void AddCommonLines(Plate plate, IReadOnlyList<Part> parts,
IReadOnlyList<NestJobCommonLine> groups)
{
if (groups.Count == 0)
return;
var taken = new HashSet<int>();
foreach (var group in groups)
{
if (group.Placements.Count < 2 || group.Placements.Any(i => i < 0 || i >= parts.Count || !taken.Add(i)))
throw new ArgumentException("A common-line group names a placement that is missing, repeated or in another group.");
plate.CommonLines.Add(new CommonLineGroup(group.Placements.Select(i => parts[i]), group.Kerf));
}
}
}
@@ -0,0 +1,186 @@
#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
using Clipper2Lib;
using OpenNest.CNC;
using OpenNest.Converters;
using OpenNest.Engine.Jobs.Adapters;
using OpenNest.Geometry;
namespace OpenNest.Engine.Jobs.CommonLines;
/// <summary>
/// Two copies of one part sharing their longest straight edge one kerf apart: the second copy
/// is the first turned half a turn, so that edge faces its own copy. Engines place the pair as one
/// compound part (<see cref="Geometry"/>), and the pipeline expands it back into the two copies
/// and their common-line group.
/// </summary>
internal sealed class CommonLinePair
{
/// <summary>Chord tolerance of the compound outline; arcs are circumscribed, so it only
/// controls vertex count, never makes the compound smaller than its copies.</summary>
private const double FlattenTolerance = 0.002;
/// <summary>How far the bridge over the kerf reaches into each copy's material, so the union
/// joins the copies into one outline.</summary>
private const double BridgeOverlap = 1e-4;
private CommonLinePair(PartGeometrySnapshot geometry, double secondX, double secondY, double sharedLength)
{
Geometry = geometry;
SecondX = secondX;
SecondY = secondY;
SharedLength = sharedLength;
}
/// <summary>The compound: both copies and the kerf between them as one solid outline, in the
/// first copy's snapshot frame. Holes are not offered (they read as solid).</summary>
public PartGeometrySnapshot Geometry { get; }
/// <summary>Where the second copy sits in the compound's frame; it is turned half a turn.</summary>
public double SecondX { get; }
public double SecondY { get; }
/// <summary>Length of the shared span (the cut saved once per pair when cut once).</summary>
public double SharedLength { get; }
/// <summary>The second copy's rotation relative to the compound.</summary>
public const double SecondRotation = System.Math.PI;
/// <summary>
/// The pair for <paramref name="geometry"/> at <paramref name="kerf"/>, or null when the part
/// has no straight edge of at least <see cref="CommonLineGeometry.MinSharedLength"/>, or when
/// the half-turned copy would come closer than the kerf anywhere else.
/// </summary>
public static CommonLinePair? Build(PartGeometrySnapshot geometry, double kerf)
{
ArgumentNullException.ThrowIfNull(geometry);
if (!double.IsFinite(kerf) || kerf <= 0)
return null;
Drawing drawing;
Part first;
IReadOnlyList<CommonLineGeometry.Edge> edges;
try
{
drawing = new Drawing("pair", DrawingJobMapper.ToProgram(geometry));
first = new Part(drawing);
edges = CommonLineGeometry.Edges(first, new CommonLineGeometry.ProfileCache());
}
catch (Exception exception) when (exception is ArgumentException or InvalidOperationException
or NotSupportedException or ArithmeticException)
{
return null;
}
// Longest edges first; equal lengths keep perimeter order, so the choice is deterministic.
foreach (var edge in edges.OrderByDescending(e => System.Math.Round(e.Length, 9)).Take(4))
{
var pair = TryEdge(drawing, first, edge, kerf);
if (pair != null)
return pair;
}
return null;
}
private static CommonLinePair? TryEdge(Drawing drawing, Part first, CommonLineGeometry.Edge edge, double kerf)
{
// Turning a copy half a turn maps this edge to itself reversed, outward normal opposed;
// moving it to the edge's mirror across the kerf centerline makes the two face each other
// over their whole length.
var middle = new Vector((edge.Start.X + edge.End.X) / 2, (edge.Start.Y + edge.End.Y) / 2);
var offset = new Vector(2 * middle.X + edge.Outward.X * kerf, 2 * middle.Y + edge.Outward.Y * kerf);
var second = new Part(drawing);
second.Rotate(SecondRotation);
second.Location = offset;
second.UpdateBounds();
var spans = CommonLineGeometry.Spans(first, second, kerf);
if (spans.Count == 0)
return null;
var firstProfile = Profile(first);
var secondProfile = Profile(second);
if (firstProfile == null || secondProfile == null)
return null;
// Away from the shared edge the copies must still clear one kerf (a concave part's
// half-turned copy can reach back into it).
if (NativeContours.Of(firstProfile, first.Location).TooClose(NativeContours.Of(secondProfile, second.Location), kerf))
return null;
var outline = Outline(firstProfile, first.Location, secondProfile, second.Location, edge, kerf);
if (outline == null)
return null;
var geometry = Snapshot(outline);
// Engines accept only usable closed edges; a compound they would refuse is no pair.
try
{
_ = JobPartGeometry.Read(geometry);
}
catch (ArgumentException)
{
return null;
}
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;
}
/// <summary>The union of both perimeters (arcs circumscribed) and the kerf between them, or
/// null when it is not one outline.</summary>
private static PathD? Outline(ShapeProfile first, Vector firstAt, ShapeProfile second, Vector secondAt,
CommonLineGeometry.Edge edge, double kerf)
{
var a = ClipperBridge.ToPath(ClipperBridge.Flatten(first.Perimeter, FlattenTolerance, circumscribe: true), firstAt);
var b = ClipperBridge.ToPath(ClipperBridge.Flatten(second.Perimeter, FlattenTolerance, circumscribe: true), secondAt);
var n = edge.Outward;
double inner = -BridgeOverlap, outer = kerf + BridgeOverlap;
var bridge = new PathD
{
new(edge.Start.X + n.X * inner, edge.Start.Y + n.Y * inner),
new(edge.End.X + n.X * inner, edge.End.Y + n.Y * inner),
new(edge.End.X + n.X * outer, edge.End.Y + n.Y * outer),
new(edge.Start.X + n.X * outer, edge.Start.Y + n.Y * outer),
};
// Clipper rounds PathsD to its precision; 8 decimals keeps the outline within 5e-9 of the copies.
// Every piece counter-clockwise, whatever the program's winding, so overlaps add up.
var pieces = new PathsD { a, b, bridge };
foreach (var piece in pieces)
if (!Clipper.IsPositive(piece))
piece.Reverse();
var union = Clipper.Union(pieces, new PathsD(), FillRule.NonZero, 8);
var outers = union.Where(path => Clipper.Area(path) > 0).ToList();
return outers.Count == 1 ? outers[0] : null;
}
private static PartGeometrySnapshot Snapshot(PathD outline)
{
// Clipper can return (nearly) repeated vertices; a zero-length edge is not usable geometry.
var points = new PathD(outline.Count);
foreach (var point in outline)
if (points.Count == 0 || !Same(points[^1], point))
points.Add(point);
while (points.Count > 1 && Same(points[^1], points[0]))
points.RemoveAt(points.Count - 1);
outline = points;
var program = new Program(Mode.Absolute);
program.Codes.Add(new RapidMove(outline[0].x, outline[0].y));
for (var i = 1; i <= outline.Count; i++)
{
var point = outline[i % outline.Count];
program.Codes.Add(new LinearMove(point.x, point.y) { Layer = LayerType.Cut });
}
return PartGeometrySnapshot.FromProgram(program);
}
// Engines refuse edges shorter than 1e-7; dropping a vertex this close moves the outline by
// far less than the spacing slack.
private static bool Same(PointD a, PointD b) =>
System.Math.Abs(a.x - b.x) <= 1e-6 && System.Math.Abs(a.y - b.y) <= 1e-6;
}
@@ -0,0 +1,165 @@
#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
namespace OpenNest.Engine.Jobs.CommonLines;
/// <summary>
/// The common-line trial <see cref="NestPipeline"/> runs beside the ordinary solve when the
/// job's <see cref="NestJobOptions.CommonLineUsage"/> is on: every part that allows common lines
/// is offered as kerf-gap pairs (<see cref="CommonLinePair"/>) plus its odd copy, so any engine
/// places them without knowing about common lines. Placed pairs expand into their two copies and
/// one explicit <see cref="NestJobCommonLine"/> group each; the expanded layout is validated again.
/// </summary>
internal sealed class CommonLinePipelinePrepass : IPipelinePrepass
{
/// <summary>Every pair proxy's part id starts with this; ordinary parts never do.</summary>
internal const string ProxyPrefix = "__common-line-pair-";
/// <summary>How many of a part's copies a trial offers as pairs.</summary>
internal enum Share
{
/// <summary>As many pairs as the quantity allows.</summary>
All,
/// <summary>About half the copies paired, the rest single: rows that fit an odd count.</summary>
Half,
}
private sealed record Proxy(string PartId, CommonLinePair Pair);
private readonly IReadOnlyDictionary<string, Proxy> proxies;
private readonly double kerf;
private CommonLinePipelinePrepass(NestJob engineJob, IReadOnlyDictionary<string, Proxy> proxies, double kerf)
{
EngineJob = engineJob;
this.proxies = proxies;
this.kerf = kerf;
}
public NestJob EngineJob { get; }
public string ReconciliationFailure => "Common-line engine output failed reconciliation";
/// <summary>True for a job holding pair proxies: a common-line trial's engine job.</summary>
internal static bool HasProxies(NestJob job) =>
job.Parts.Any(p => p.Id.StartsWith(ProxyPrefix, StringComparison.Ordinal));
/// <summary>
/// The trial job, or null when the job does not use common lines or no part can pair
/// (none allows it, has two copies, may turn half a turn and has a long enough straight edge).
/// </summary>
internal static CommonLinePipelinePrepass? Prepare(NestJob original, Share share, CancellationToken token)
{
ArgumentNullException.ThrowIfNull(original);
token.ThrowIfCancellationRequested();
if (!original.Options.UsesCommonLines || original.Plates.Count == 0)
return null;
var kerf = original.Options.CommonLineKerf;
// A pair a kerf apart only saves anything where the part spacing is wider than the kerf.
if (original.Plates.All(stock => !(kerf < stock.PartSpacing)))
return null;
var ids = original.Parts.Select(p => p.Id).ToHashSet(StringComparer.Ordinal);
var proxies = new Dictionary<string, Proxy>(StringComparer.Ordinal);
var parts = new List<NestJobPart>();
foreach (var part in original.Parts)
{
token.ThrowIfCancellationRequested();
var pairs = Pairs(part, share);
var pair = pairs > 0 && CanTurnHalf(part.Rotation) ? CommonLinePair.Build(part.Geometry, kerf) : null;
if (pair == null)
{
parts.Add(part);
continue;
}
var proxyId = ProxyPrefix + part.Id;
if (ids.Contains(proxyId))
throw new InvalidOperationException("Common-line proxy ID collides with a requirement.");
proxies.Add(proxyId, new Proxy(part.Id, pair));
// The pair first: it is the larger piece, and engines keep input order among equals.
parts.Add(new NestJobPart(proxyId, pair.Geometry, pairs, part.Priority, part.Rotation));
var singles = part.Quantity - 2 * pairs;
if (singles > 0)
parts.Add(new NestJobPart(part.Id, part.Geometry, singles, part.Priority, part.Rotation)
{
AllowCommonLine = part.AllowCommonLine,
});
}
if (proxies.Count == 0)
return null;
var engineJob = new NestJob(parts, original.Plates, original.Options);
try
{
NestJobValidator.Validate(engineJob);
}
catch (ArgumentException)
{
return null; // A trial the engine could not be asked is no trial; the ordinary solve stands.
}
return new CommonLinePipelinePrepass(engineJob, proxies, kerf);
}
private static int Pairs(NestJobPart part, Share share)
{
if (!part.AllowCommonLine || part.Quantity < 2)
return 0;
return share == Share.All ? part.Quantity / 2 : part.Quantity / 4;
}
// The second copy turns half a turn from the first, so the part must allow both angles.
private static bool CanTurnHalf(RotationPolicy rotation) =>
rotation.Kind == RotationPolicyKind.Automatic || rotation.Allow180Equivalent;
public IReadOnlyDictionary<string, int> ReleasedInserts(NestJobResult engineResult) =>
new Dictionary<string, int>(StringComparer.Ordinal);
public bool TryExpand(NestJob original, NestJobResult result, CancellationToken token,
out NestJobResult? expanded, out string failure)
{
expanded = null;
failure = "Invalid common-line engine accounting";
if (!PipelinePrepassAccounting.Matches(EngineJob, result, token))
return false;
var builder = new NestJobResultBuilder(original);
foreach (var sheet in result.Plates)
{
token.ThrowIfCancellationRequested();
if (sheet.CommonLines.Count > 0)
return false; // Engines place pairs as parts; they never return groups of their own here.
var poses = new List<(string PartId, double X, double Y, double Rotation)>();
var groups = new List<NestJobCommonLine>();
foreach (var pose in sheet.Placements)
{
if (!proxies.TryGetValue(pose.PartId, out var proxy))
{
poses.Add((pose.PartId, pose.X, pose.Y, pose.Rotation));
continue;
}
var sine = System.Math.Sin(pose.Rotation);
var cosine = System.Math.Cos(pose.Rotation);
var pair = proxy.Pair;
groups.Add(new NestJobCommonLine(kerf, new[] { poses.Count, poses.Count + 1 }));
poses.Add((proxy.PartId, pose.X, pose.Y, pose.Rotation));
poses.Add((proxy.PartId,
pose.X + pair.SecondX * cosine - pair.SecondY * sine,
pose.Y + pair.SecondX * sine + pair.SecondY * cosine,
pose.Rotation + CommonLinePair.SecondRotation));
}
var stock = original.Plates.Single(s => s.Id == sheet.StockId);
try
{
builder.AddSheet(stock, poses, groups);
}
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException)
{
return false;
}
}
token.ThrowIfCancellationRequested();
expanded = builder.Build(result.StopReason);
return true;
}
}
@@ -0,0 +1,91 @@
using System;
using System.Collections.Generic;
using System.Linq;
using OpenNest.Converters;
namespace OpenNest.Engine.Jobs.CommonLines;
/// <summary>
/// Decides whether a common-line layout replaces the best layout without common lines (or an
/// earlier common-line trial), by the job's <see cref="CommonLineUsage"/>. Both must be valid,
/// keepable proposals of the same job; an invalid incumbent always loses to a valid candidate.
/// The engines' own ranking (and <c>FillScore</c>) is untouched: this only chooses between the
/// layouts they returned.
/// </summary>
internal static class CommonLineRanking
{
/// <summary>Differences below this are rounding, never a reason to prefer either layout.</summary>
private const double Epsilon = 1e-6;
internal static bool Prefers(CommonLineUsage usage, NestPipelineResult candidate, NestPipelineResult incumbent)
{
ArgumentNullException.ThrowIfNull(candidate);
ArgumentNullException.ThrowIfNull(incumbent);
if (usage == CommonLineUsage.Off || !Keepable(candidate))
return false;
if (!Keepable(incumbent))
return true;
var placed = Placed(candidate).CompareTo(Placed(incumbent));
if (placed != 0)
return placed > 0;
var sheets = Sheets(candidate).CompareTo(Sheets(incumbent));
if (sheets != 0)
return sheets < 0;
// Equal parts and sheets: "when it adds parts" keeps the incumbent.
if (usage != CommonLineUsage.Whenever)
return false;
var material = Material(candidate, incumbent);
var cut = Compare(CutLength(candidate), CutLength(incumbent));
// Better on one measure and no worse on the other.
return (material > 0 && cut <= 0) || (cut < 0 && material >= 0);
}
private static bool Keepable(NestPipelineResult result) => result.CanKeep && result.IsValid;
private static int Placed(NestPipelineResult result) => result.Raw.Plates.Sum(p => p.Placements.Count);
private static int Sheets(NestPipelineResult result) => result.Raw.Plates.Count;
/// <summary>Positive when <paramref name="a"/> uses less material than <paramref name="b"/>:
/// a lower net cost (a larger salvage-credited remnant), then the larger compactness offcut
/// (a shorter used length).</summary>
internal static int Material(NestPipelineResult a, NestPipelineResult b)
{
var cost = Compare(NestJobCost.Evaluate(a.Job, a.Raw), NestJobCost.Evaluate(b.Job, b.Raw));
if (cost != 0)
return -cost;
return Compare(NestJobCost.CompactnessOffcut(a.Job, a.Raw), NestJobCost.CompactnessOffcut(b.Job, b.Raw));
}
/// <summary>
/// Total cut length: every part's cut contours, less each shared span once (a common line is
/// cut once). Repeated sheets count each copy.
/// </summary>
internal static double CutLength(NestPipelineResult result)
{
var lengths = new Dictionary<Drawing, double>(ReferenceEqualityComparer.Instance);
var total = 0.0;
foreach (var plate in result.Plates)
{
var length = plate.Parts.Sum(part => ContourLength(part.BaseDrawing, lengths));
foreach (var group in plate.CommonLines)
length -= CommonLineGeometry.Check(group).Spans.Sum(span => span.Length);
total += plate.Quantity * length;
}
return total;
}
private static double ContourLength(Drawing drawing, Dictionary<Drawing, double> lengths)
{
if (!lengths.TryGetValue(drawing, out var length))
{
length = ConvertProgram.ToGeometry(drawing.Program).ForNesting().Sum(entity => entity.Length);
lengths.Add(drawing, length);
}
return length;
}
private static int Compare(double a, double b) =>
System.Math.Abs(a - b) <= Epsilon * System.Math.Max(1, System.Math.Max(System.Math.Abs(a), System.Math.Abs(b)))
? 0 : a.CompareTo(b);
}
@@ -16,7 +16,7 @@ namespace OpenNest.Engine.Jobs.Cutouts;
/// Those go only through <see cref="CutoutCirclePacker"/>, which keeps every disc clear of the
/// others' whole enclosing circles; lattice and NFP placement could seat a part in a ring's
/// empty bore, or over a nested bundle's reserved inserts.</remarks>
internal sealed class CutoutPipelinePrepass
internal sealed class CutoutPipelinePrepass : IPipelinePrepass
{
// A job with thousands of repeats still offers the residual as ordinary demand;
// do not multiply expensive Clipper/Fill preparation by every physical instance.
@@ -44,7 +44,9 @@ internal sealed class CutoutPipelinePrepass
this.bundles = bundles;
}
internal NestJob EngineJob { get; }
public NestJob EngineJob { get; }
public string ReconciliationFailure => "Cutout engine output failed reconciliation";
internal static CutoutPipelinePrepass? Prepare(NestJob original, CancellationToken token)
{
@@ -242,7 +244,7 @@ internal sealed class CutoutPipelinePrepass
/// <summary>Reserved insert copies per original requirement whose frame proxy the engine
/// did not place; call only on engine output that <see cref="TryExpand"/> accepted.</summary>
internal IReadOnlyDictionary<string, int> ReleasedInserts(NestJobResult engineResult)
public IReadOnlyDictionary<string, int> ReleasedInserts(NestJobResult engineResult)
{
var placed = engineResult.Plates.SelectMany(p => p.Placements)
.Select(p => p.PartId).ToHashSet(StringComparer.Ordinal);
@@ -271,65 +273,13 @@ internal sealed class CutoutPipelinePrepass
/// <summary>Reject untrusted accounting before expansion. A failed trial is never bindable,
/// including with allowInvalid. Only actually placed proxies consume reserved inserts;
/// an unplaced proxy's inserts stay unplaced demand of their own requirements.</summary>
internal bool TryExpand(NestJob original, NestJobResult result, CancellationToken token,
public bool TryExpand(NestJob original, NestJobResult result, CancellationToken token,
out NestJobResult? expanded,
out string failure)
{
expanded = null;
failure = "Invalid cutout engine accounting";
var parts = EngineJob.Parts.ToDictionary(p => p.Id);
var counts = parts.ToDictionary(p => p.Key, _ => 0);
var indices = parts.ToDictionary(p => p.Key, _ => new HashSet<int>());
var stockById = EngineJob.Plates.ToDictionary(s => s.Id, StringComparer.Ordinal);
var used = stockById.ToDictionary(s => s.Key, _ => 0, StringComparer.Ordinal);
var expectedIndex = 0;
foreach (var sheet in result.Plates)
{
token.ThrowIfCancellationRequested();
if (sheet.PlateIndex != expectedIndex++ || sheet.Placements.Count == 0
|| !used.ContainsKey(sheet.StockId))
return false;
used[sheet.StockId]++;
foreach (var pose in sheet.Placements)
{
if (pose.PartId == null || !parts.ContainsKey(pose.PartId)
|| pose.InstanceIndex < 0 || !indices[pose.PartId].Add(pose.InstanceIndex)
|| ++counts[pose.PartId] > parts[pose.PartId].Quantity)
return false;
}
}
foreach (var row in indices)
{
token.ThrowIfCancellationRequested();
if (row.Value.Any(index => index >= counts[row.Key]))
return false;
}
if (result.Fulfillment.Count != parts.Count || result.StockUsage.Count != used.Count)
return false;
var seenParts = new HashSet<string>(StringComparer.Ordinal);
foreach (var row in result.Fulfillment)
{
token.ThrowIfCancellationRequested();
if (row.PartId == null || !parts.TryGetValue(row.PartId, out var part)
|| !seenParts.Add(row.PartId)
|| row.Requested != part.Quantity || row.Placed != counts[row.PartId]
|| row.Unplaced != part.Quantity - counts[row.PartId])
return false;
}
var seenStock = new HashSet<string>(StringComparer.Ordinal);
foreach (var row in result.StockUsage)
{
token.ThrowIfCancellationRequested();
if (row.StockId == null || !stockById.TryGetValue(row.StockId, out var stock)
|| !seenStock.Add(row.StockId)
|| row.Used != used[row.StockId]
|| row.Remaining != stock.Quantity - row.Used)
return false;
}
var complete = parts.Values.All(p => counts[p.Id] == p.Quantity);
if (result.Status != (complete ? NestJobStatus.Complete : NestJobStatus.Incomplete)
|| (complete && result.StopReason != NestJobStopReason.Completed)
|| (!complete && result.StopReason == NestJobStopReason.Completed))
if (!PipelinePrepassAccounting.Matches(EngineJob, result, token))
return false;
var builder = new NestJobResultBuilder(original);
+29 -1
View File
@@ -53,7 +53,35 @@ public sealed class NestJobOptions
/// <summary>A copy of these options with <see cref="SearchUntilCancelled"/> set.</summary>
public NestJobOptions WithSearchUntilCancelled(bool value) =>
new(PlacementStrategy, MaxPlates, SalvageRate, MinimumSalvageDimension, value, OffcutCut);
new(PlacementStrategy, MaxPlates, SalvageRate, MinimumSalvageDimension, value, OffcutCut)
{
CommonLineUsage = CommonLineUsage,
CommonLineKerf = CommonLineKerf,
};
/// <summary>
/// When the pipeline may place parts that allow it on common lines, one
/// <see cref="CommonLineKerf"/> apart (see docs/common-line-cutting.md). Off by default;
/// without a positive kerf it acts as off.
/// </summary>
public CommonLineUsage CommonLineUsage
{
get => commonLineUsage;
init => commonLineUsage = Enum.IsDefined(value) ? value : throw new ArgumentOutOfRangeException(nameof(CommonLineUsage));
}
private readonly CommonLineUsage commonLineUsage;
private readonly double commonLineKerf;
/// <summary>The cutting kerf for the job's material and thickness, in job units; zero when unknown.</summary>
public double CommonLineKerf
{
get => commonLineKerf;
init => commonLineKerf = double.IsFinite(value) && value >= 0 ? value : throw new ArgumentOutOfRangeException(nameof(CommonLineKerf));
}
/// <summary>True when common lines may be made: a level is on and the kerf is positive.</summary>
public bool UsesCommonLines => CommonLineUsage != CommonLineUsage.Off && CommonLineKerf > 0;
/// <summary>Fraction of eligible edge-offcut area credited by <see cref="NestJobCost.NetSheetCost"/> (0..1).</summary>
public double SalvageRate { get; }
+6
View File
@@ -42,4 +42,10 @@ public sealed class NestJobPart
/// </summary>
public int Priority { get; }
public RotationPolicy Rotation { get; }
/// <summary>
/// The part may share a common line with copies of itself when the job's
/// <see cref="NestJobOptions.CommonLineUsage"/> allows it (<c>Drawing.AllowCommonLine</c>).
/// </summary>
public bool AllowCommonLine { get; init; }
}
+45 -1
View File
@@ -36,25 +36,69 @@ public sealed record PartFulfillment(string PartId, int Requested, int Placed, i
/// <summary>Used counts physical sheets; Remaining is null only for unlimited stock.</summary>
public sealed record StockUsage(string StockId, int Used, int? Remaining);
/// <summary>
/// One common-line group on a result sheet: the zero-based positions of its members in the
/// sheet's <see cref="NestJobPlateResult.Placements"/> and the kerf they were placed at. The
/// validation exempts members from the part spacing only through this explicit list, never by
/// guessing from proximity (see docs/common-line-cutting.md).
/// </summary>
public sealed record NestJobCommonLine
{
public NestJobCommonLine(double kerf, IEnumerable<int> placements)
{
Kerf = kerf;
Placements = NestJob.Own(placements ?? throw new ArgumentNullException(nameof(placements)));
}
public double Kerf { get; }
public IReadOnlyList<int> Placements { get; }
public bool Equals(NestJobCommonLine other) =>
other is not null
&& BitConverter.DoubleToInt64Bits(Kerf) == BitConverter.DoubleToInt64Bits(other.Kerf)
&& System.Linq.Enumerable.SequenceEqual(Placements, other.Placements);
public override int GetHashCode()
{
var hash = new HashCode();
hash.Add(BitConverter.DoubleToInt64Bits(Kerf));
foreach (var index in Placements)
hash.Add(index);
return hash.ToHashCode();
}
}
/// <summary>One physical sheet, with owned ordered placements and immutable stock/settings snapshot.</summary>
public sealed class NestJobPlateResult
{
public NestJobPlateResult(
int plateIndex,
NestPlateStock stock,
IEnumerable<NestJobPlacement> placements
IEnumerable<NestJobPlacement> placements,
IEnumerable<NestJobCommonLine> commonLines = null
)
{
ArgumentNullException.ThrowIfNull(stock);
PlateIndex = plateIndex;
Stock = stock;
Placements = NestJob.Own(placements);
CommonLines = commonLines == null ? Array.Empty<NestJobCommonLine>() : NestJob.Own(commonLines);
}
public int PlateIndex { get; }
public string StockId => Stock.Id;
public NestPlateStock Stock { get; }
public IReadOnlyList<NestJobPlacement> Placements { get; }
/// <summary>Common-line groups among <see cref="Placements"/>; empty when there are none.</summary>
[System.Text.Json.Serialization.JsonIgnore]
public IReadOnlyList<NestJobCommonLine> CommonLines { get; }
/// <summary><see cref="CommonLines"/> when serialized: omitted when empty, so a sheet without
/// groups serializes exactly as before they existed.</summary>
[System.Text.Json.Serialization.JsonPropertyName("CommonLines")]
[System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull)]
public IReadOnlyList<NestJobCommonLine> SerializedCommonLines => CommonLines.Count == 0 ? null : CommonLines;
}
/// <summary>Detached result values in commit/input order; no mutable Drawing, Plate, or NestItem escapes.</summary>
+3 -2
View File
@@ -35,7 +35,8 @@ public sealed class NestJobResultBuilder
/// </summary>
public int AddSheet(
NestPlateStock stock,
IEnumerable<(string PartId, double X, double Y, double Rotation)> placements
IEnumerable<(string PartId, double X, double Y, double Rotation)> placements,
IEnumerable<NestJobCommonLine> commonLines = null
)
{
ArgumentNullException.ThrowIfNull(placements);
@@ -57,7 +58,7 @@ public sealed class NestJobResultBuilder
}
var plateIndex = sheets.Count;
sheets.Add(new NestJobPlateResult(plateIndex, stock, poses));
sheets.Add(new NestJobPlateResult(plateIndex, stock, poses, commonLines));
foreach (var count in counts)
placed[count.Key] = count.Value;
used[stock.Id]++;
+90 -2
View File
@@ -90,6 +90,11 @@ public static class NestLayoutCheck
if (!double.IsFinite(pose.Rotation))
violations.Add($"{description} has nonfinite Rotation ({pose.Rotation})");
}
var grouped = new HashSet<int>();
foreach (var group in sheet.CommonLines)
if (group.Placements.Count < 2 || !double.IsFinite(group.Kerf) || group.Kerf <= 0
|| group.Placements.Any(i => i < 0 || i >= sheet.Placements.Count || !grouped.Add(i)))
violations.Add($"Plate {sheet.PlateIndex} has a malformed common-line group");
}
}
@@ -232,7 +237,8 @@ public static class NestLayoutCheck
ValidateBounds(parts, plate, requirements, result);
ValidateAreaBudget(parts, plate, result);
ValidateSpacing(parts, plate.PartSpacing, requirements, result);
ValidateSpacing(parts, plate.PartSpacing, requirements, result, plate.CommonLines);
ValidateCommonLines(plate, parts, requirements, result);
if (plate.ClampZones.Count > 0)
ValidateClamps(parts, plate, requirements, result);
}
@@ -363,6 +369,9 @@ public static class NestLayoutCheck
}
}
foreach (var sheet in jobResult.Plates)
ValidateCommonLinesAgainstJob(job, sheet, partsById, displayNames, result);
foreach (var sheet in jobResult.Plates)
{
foreach (var placement in sheet.Placements)
@@ -384,6 +393,43 @@ public static class NestLayoutCheck
}
}
/// <summary>
/// A sheet's explicit common-line groups must be allowed by the job: a common-line level on,
/// the job's kerf, members that allow common lines, and positions on the sheet that no other
/// group takes. Geometry (that the members really share edges) is checked on the plate.
/// </summary>
private static void ValidateCommonLinesAgainstJob(NestJob job, NestJobPlateResult sheet,
IReadOnlyDictionary<string, NestJobPart> partsById, IReadOnlyDictionary<string, string> displayNames,
List<string> result)
{
if (sheet.CommonLines.Count == 0)
return;
if (!job.Options.UsesCommonLines)
{
result.Add($"Plate {sheet.PlateIndex} has common-line groups, which this job does not allow");
return;
}
var taken = new HashSet<int>();
foreach (var group in sheet.CommonLines)
{
if (BitConverter.DoubleToInt64Bits(group.Kerf) != BitConverter.DoubleToInt64Bits(job.Options.CommonLineKerf))
result.Add($"Plate {sheet.PlateIndex} has a common-line group at kerf {group.Kerf:F4}; the job's kerf is {job.Options.CommonLineKerf:F4}");
if (group.Placements.Count < 2)
result.Add($"Plate {sheet.PlateIndex} has a common-line group of fewer than two parts");
foreach (var index in group.Placements)
{
if (index < 0 || index >= sheet.Placements.Count || !taken.Add(index))
{
result.Add($"Plate {sheet.PlateIndex} has a common-line group naming placement {index}, which is missing or already in a group");
continue;
}
var id = sheet.Placements[index].PartId;
if (id != null && partsById.TryGetValue(id, out var part) && !part.AllowCommonLine)
result.Add($"'{displayNames.GetValueOrDefault(id, id)}' is in a common-line group on plate {sheet.PlateIndex} but does not allow common lines");
}
}
}
private static bool SameSettings(NestPlateStock expected, NestPlateStock actual) =>
ReferenceEquals(expected, actual)
|| (
@@ -547,9 +593,16 @@ public static class NestLayoutCheck
List<Part> parts,
double spacing,
IReadOnlyDictionary<Drawing, (string Name, int Quantity)> requirements,
List<string> result
List<string> result,
IEnumerable<CommonLineGroup> commonLines = null
)
{
// Members of one explicit common-line group are held to the group's kerf instead.
var groupOf = new Dictionary<Part, CommonLineGroup>(ReferenceEqualityComparer.Instance);
if (commonLines != null)
foreach (var group in commonLines)
foreach (var member in group.Members)
groupOf.TryAdd(member, group);
var profiles = new ShapeProfile[parts.Count];
var raw = new SpacingOutline[parts.Count];
var inflated = new SpacingOutline[parts.Count];
@@ -596,6 +649,18 @@ public static class NestLayoutCheck
if (!Overlaps(inflated[i], raw[j]))
continue;
if (groupOf.TryGetValue(parts[i], out var shared)
&& groupOf.TryGetValue(parts[j], out var partnerGroup) && ReferenceEquals(shared, partnerGroup))
{
native[i] ??= NativeContours.Of(profiles[i], parts[i].Location);
native[j] ??= NativeContours.Of(profiles[j], parts[j].Location);
if (native[i].TooClose(native[j], shared.Kerf))
result.Add(
$"'{DisplayName(parts[i], requirements)}' and '{DisplayName(parts[j], requirements)}' share a common line but are closer than its kerf ({shared.Kerf:F4})"
);
continue;
}
// The outline circumscribes arcs by more than the slack, so confirm a spacing
// candidate on the native contours. Zero spacing has no gap to confirm.
if (inflateBy > Tolerance.Epsilon)
@@ -613,6 +678,29 @@ public static class NestLayoutCheck
}
}
/// <summary>
/// Every explicit common-line group must be intact: each member shares a straight edge one
/// kerf apart with another member and the members form one connected group
/// (<see cref="CommonLineGeometry.Check"/>). A group that does not share is not a common line,
/// so its spacing exemption would hide a real violation.
/// </summary>
private static void ValidateCommonLines(Plate plate, List<Part> parts,
IReadOnlyDictionary<Drawing, (string Name, int Quantity)> requirements, List<string> result)
{
foreach (var group in plate.CommonLines)
{
if (group.Members.Any(member => !parts.Contains(member)))
{
result.Add("A common-line group names a part that is not on its plate");
continue;
}
if (!(group.Kerf < plate.PartSpacing))
result.Add($"A common-line group's kerf ({group.Kerf:F4}) is not smaller than the part spacing ({plate.PartSpacing:F3})");
foreach (var problem in CommonLineGeometry.Check(group).Problems)
result.Add($"'{DisplayName(problem.Part, requirements)}' {problem.Message}");
}
}
/// <summary>Analytic world-space material bounds; surface marks never bound material.</summary>
internal static Box MaterialBounds(Part part) => PlateRemnant.MaterialBounds(part);
+67 -6
View File
@@ -4,6 +4,7 @@ using System.Diagnostics;
using System.Linq;
using System.Threading;
using OpenNest.Engine.Jobs.Adapters;
using OpenNest.Engine.Jobs.CommonLines;
using OpenNest.Engine.Jobs.Cutouts;
namespace OpenNest.Engine.Jobs;
@@ -24,6 +25,10 @@ public sealed record NestPipelineRequest(
/// raw physical occurrence; Quantity is the total physical copies, including the first.</summary>
public sealed record ProposedPlate(int PlateIndex, NestPlateStock Stock, IReadOnlyList<Part> Parts)
{
/// <summary>Common-line groups among <see cref="Parts"/>; committing the plate adds them to
/// <see cref="Plate.CommonLines"/>. Empty when the layout has none.</summary>
public IReadOnlyList<CommonLineGroup> CommonLines { get; init; } = Array.Empty<CommonLineGroup>();
private int quantity = 1;
public int Quantity
{
@@ -176,7 +181,11 @@ public static class NestPipeline
part.UpdateBounds();
placed.Add(part);
}
sheets.Add(new ProposedPlate(group.Sheet.PlateIndex, group.Sheet.Stock, placed) { Quantity = group.Quantity });
sheets.Add(new ProposedPlate(group.Sheet.PlateIndex, group.Sheet.Stock, placed)
{
Quantity = group.Quantity,
CommonLines = NestResultBinder.BindCommonLines(group.Sheet, placed),
});
}
return sheets;
}
@@ -251,6 +260,55 @@ public static class NestPipeline
)
{
var (job, drawingsByPartId) = CreateJob(engine, request, token);
return Run(engine, engineName, job, drawingsByPartId, progress, token, cutouts);
}
/// <summary>
/// The pipeline for an already built job whose part ids map to <paramref name="drawingsByPartId"/>
/// (the benchmark builds its own jobs); identical to <see cref="Run(INestingEngine, string, NestPipelineRequest, IProgress{NestJobProgress}, CancellationToken)"/> otherwise.
/// </summary>
internal static NestPipelineResult Run(INestingEngine engine, string engineName, NestJob job,
IReadOnlyDictionary<string, Drawing> drawingsByPartId, IProgress<NestJobProgress> progress,
CancellationToken token, bool cutouts = true)
{
ArgumentNullException.ThrowIfNull(engine);
ArgumentNullException.ThrowIfNull(job);
NestJobValidator.Validate(job);
var ordinary = RunOrdinary(engine, engineName, job, drawingsByPartId, progress, token, cutouts);
return job.Options.UsesCommonLines
? WithCommonLines(engine, engineName, job, drawingsByPartId, ordinary, progress, token)
: ordinary;
}
/// <summary>
/// The common-line trials (see <see cref="CommonLinePipelinePrepass"/>), each solved after
/// the ordinary solve and kept only when <see cref="CommonLineRanking"/> prefers it at the
/// job's usage level; otherwise the ordinary result stands as it was.
/// </summary>
private static NestPipelineResult WithCommonLines(INestingEngine engine, string engineName, NestJob job,
IReadOnlyDictionary<string, Drawing> drawingsByPartId, NestPipelineResult ordinary,
IProgress<NestJobProgress> progress, CancellationToken token)
{
var best = ordinary;
var asked = new HashSet<string>(StringComparer.Ordinal);
foreach (var share in new[] { CommonLinePipelinePrepass.Share.All, CommonLinePipelinePrepass.Share.Half })
{
token.ThrowIfCancellationRequested();
var prepass = CommonLinePipelinePrepass.Prepare(job, share, token);
// Two shares that pair the same counts would ask the engine the same question.
if (prepass == null || !asked.Add(string.Join("|", Remote.NestSolveTranscript.Fingerprint(prepass.EngineJob))))
continue;
var trial = Evaluate(engine, engineName, job, prepass, drawingsByPartId, progress, token);
if (CommonLineRanking.Prefers(job.Options.CommonLineUsage, trial, best))
best = trial;
}
return ReferenceEquals(best, ordinary) ? ordinary : Committed(best, progress, token);
}
private static NestPipelineResult RunOrdinary(INestingEngine engine, string engineName, NestJob job,
IReadOnlyDictionary<string, Drawing> drawingsByPartId, IProgress<NestJobProgress> progress,
CancellationToken token, bool cutouts)
{
var prepass = cutouts ? CutoutPipelinePrepass.Prepare(job, token) : null;
if (prepass == null)
return Evaluate(engine, engineName, job, null, drawingsByPartId, progress, token);
@@ -331,7 +389,7 @@ public static class NestPipeline
INestingEngine engine,
string engineName,
NestJob job,
CutoutPipelinePrepass prepass,
IPipelinePrepass prepass,
IReadOnlyDictionary<string, Drawing> drawingsByPartId,
IProgress<NestJobProgress> progress,
CancellationToken token
@@ -378,7 +436,7 @@ public static class NestPipeline
{
// A compound may be physically invalid even when its envelope is legal.
// Refuse every unverified trial, including with explicit invalid-result consent.
var failure = "Cutout engine output failed reconciliation";
var failure = prepass.ReconciliationFailure;
if (violations.Count == 0 && prepass.TryExpand(job, raw, token, out var expanded, out failure))
{
released = prepass.ReleasedInserts(raw);
@@ -408,9 +466,12 @@ public static class NestPipeline
foreach (var group in RepeatedPlateGrouping.Create(raw.Plates, consolidate, token))
{
token.ThrowIfCancellationRequested();
plates.Add(new ProposedPlate(group.Sheet.PlateIndex, group.Sheet.Stock,
NestResultBinder.Bind(group.Sheet, drawingsByPartId))
{ Quantity = group.Quantity });
var bound = NestResultBinder.Bind(group.Sheet, drawingsByPartId);
plates.Add(new ProposedPlate(group.Sheet.PlateIndex, group.Sheet.Stock, bound)
{
Quantity = group.Quantity,
CommonLines = NestResultBinder.BindCommonLines(group.Sheet, bound),
});
}
// Binding clones the caller's current Program; a concurrent edit during binding
@@ -97,6 +97,8 @@ public static class NestPipelineCommit
plate.Quantity = proposed.Quantity;
SyncClampZones(plate, proposed.Stock);
plate.Parts.AddRange(proposed.Parts);
foreach (var group in proposed.CommonLines)
plate.CommonLines.Add(group);
applied.Add(plate);
}
return applied.AsReadOnly();
+7 -1
View File
@@ -190,7 +190,13 @@ public static class NestRenest
NestStockBuilder.FromTemplate(nest.PlateDefaults.CreateNew(), options),
new NestJobOptions(maxPlates: MaxPlates,
salvageRate: options.Count > 0 ? nest.SalvageRate : 0,
minimumSalvageDimension: options.Count > 0 ? minimumSalvageDimension : 0));
minimumSalvageDimension: options.Count > 0 ? minimumSalvageDimension : 0)
{
// The engine has no machine defaults: a plate's saved cutting kerf, if any.
CommonLineUsage = nest.CommonLineUsage,
CommonLineKerf = nest.Plates.Select(p => p.CuttingParameters?.Kerf ?? 0)
.FirstOrDefault(k => double.IsFinite(k) && k > 0),
});
}
/// <summary>
+94
View File
@@ -0,0 +1,94 @@
#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
namespace OpenNest.Engine.Jobs;
/// <summary>
/// A pipeline pre-pass that offers the engine a transformed job (compound proxies standing in
/// for several parts) and expands the engine's answer back to the original job's parts, which
/// are then validated again. Cutout bundles and common-line pairs are the two kinds.
/// </summary>
internal interface IPipelinePrepass
{
/// <summary>The job the engine solves.</summary>
NestJob EngineJob { get; }
/// <summary>The violation reported when the engine's answer cannot be expanded.</summary>
string ReconciliationFailure { get; }
/// <summary>Expands an answer to <see cref="EngineJob"/> into one for <paramref name="original"/>.</summary>
bool TryExpand(NestJob original, NestJobResult result, CancellationToken token,
out NestJobResult? expanded, out string failure);
/// <summary>Copies per original requirement that an unplaced proxy left unplaced as a frame's insert.</summary>
IReadOnlyDictionary<string, int> ReleasedInserts(NestJobResult engineResult);
}
/// <summary>The accounting every pre-pass checks before trusting an engine's answer.</summary>
internal static class PipelinePrepassAccounting
{
/// <summary>
/// True when <paramref name="result"/> is self-consistent for <paramref name="engineJob"/>:
/// consecutive sheet indices, known stock and parts, unique instance indices within quantity,
/// and fulfillment, stock usage and status rows that match the placements.
/// </summary>
internal static bool Matches(NestJob engineJob, NestJobResult result, CancellationToken token)
{
var parts = engineJob.Parts.ToDictionary(p => p.Id);
var counts = parts.ToDictionary(p => p.Key, _ => 0);
var indices = parts.ToDictionary(p => p.Key, _ => new HashSet<int>());
var stockById = engineJob.Plates.ToDictionary(s => s.Id, StringComparer.Ordinal);
var used = stockById.ToDictionary(s => s.Key, _ => 0, StringComparer.Ordinal);
var expectedIndex = 0;
foreach (var sheet in result.Plates)
{
token.ThrowIfCancellationRequested();
if (sheet.PlateIndex != expectedIndex++ || sheet.Placements.Count == 0
|| !used.ContainsKey(sheet.StockId))
return false;
used[sheet.StockId]++;
foreach (var pose in sheet.Placements)
{
if (pose.PartId == null || !parts.ContainsKey(pose.PartId)
|| pose.InstanceIndex < 0 || !indices[pose.PartId].Add(pose.InstanceIndex)
|| ++counts[pose.PartId] > parts[pose.PartId].Quantity)
return false;
}
}
foreach (var row in indices)
{
token.ThrowIfCancellationRequested();
if (row.Value.Any(index => index >= counts[row.Key]))
return false;
}
if (result.Fulfillment.Count != parts.Count || result.StockUsage.Count != used.Count)
return false;
var seenParts = new HashSet<string>(StringComparer.Ordinal);
foreach (var row in result.Fulfillment)
{
token.ThrowIfCancellationRequested();
if (row.PartId == null || !parts.TryGetValue(row.PartId, out var part)
|| !seenParts.Add(row.PartId)
|| row.Requested != part.Quantity || row.Placed != counts[row.PartId]
|| row.Unplaced != part.Quantity - counts[row.PartId])
return false;
}
var seenStock = new HashSet<string>(StringComparer.Ordinal);
foreach (var row in result.StockUsage)
{
token.ThrowIfCancellationRequested();
if (row.StockId == null || !stockById.TryGetValue(row.StockId, out var stock)
|| !seenStock.Add(row.StockId)
|| row.Used != used[row.StockId]
|| row.Remaining != stock.Quantity - row.Used)
return false;
}
var complete = parts.Values.All(p => counts[p.Id] == p.Quantity);
return result.Status == (complete ? NestJobStatus.Complete : NestJobStatus.Incomplete)
&& (!complete || result.StopReason == NestJobStopReason.Completed)
&& (complete || result.StopReason != NestJobStopReason.Completed);
}
}
@@ -0,0 +1,116 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using OpenNest.Engine.Jobs.Adapters;
using OpenNest.Engine.Jobs.CommonLines;
using OpenNest.Geometry;
namespace OpenNest.Engine.Jobs.Placement;
/// <summary>A proposed fill: new parts and the common-line groups among them (empty when none).</summary>
public sealed record PlateFillProposal(List<Part> Parts, IReadOnlyList<CommonLineGroup> CommonLines);
public static partial class PlateFillService
{
/// <summary>
/// <see cref="FillItem(string, Plate, NestItem, Box, IProgress{NestProgress}, CancellationToken)"/>
/// at a common-line usage level. With the level off, a drawing that does not allow common lines,
/// or no positive kerf, it is exactly that fill. Otherwise the area is also filled with kerf-gap
/// pairs of the drawing (<see cref="CommonLinePair"/>), each expanded into its two parts and a
/// group, and the pair fill replaces the plain one when it places more parts, or (at
/// <see cref="CommonLineUsage.Whenever"/>) the same number and the strategy's own ranking does
/// not prefer the plain fill. Ties at <see cref="CommonLineUsage.WhenItAddsParts"/> keep the
/// plain fill. The proposal is not committed: the caller adds the parts, then the groups.
/// </summary>
public static PlateFillProposal FillItem(
string strategy,
Plate plate,
NestItem item,
Box workArea,
CommonLineUsage usage,
double kerf,
IProgress<NestProgress> progress,
CancellationToken token
)
{
ArgumentNullException.ThrowIfNull(item);
var plain = FillItem(strategy, plate, item, workArea, progress, token);
var none = new PlateFillProposal(plain, Array.Empty<CommonLineGroup>());
if (usage == CommonLineUsage.Off || item.Drawing?.AllowCommonLine != true
|| !double.IsFinite(kerf) || kerf <= 0 || !(kerf < plate.PartSpacing)
|| item.Quantity is > 0 and < 2 || token.IsCancellationRequested)
return none;
var constraints = item.Drawing.Constraints;
// The second copy turns half a turn, so a fixed rotation must allow its 180° equivalent.
if (item.StepAngle > 0 && constraints?.Allow180Equivalent != true)
return none;
CommonLinePair pair;
try
{
pair = CommonLinePair.Build(PartGeometrySnapshot.FromProgram(item.Drawing.Program), kerf);
}
catch (NotSupportedException)
{
return none;
}
if (pair == null)
return none;
var proxy = new Drawing(item.Drawing.Name, DrawingJobMapper.ToProgram(pair.Geometry))
{
Priority = item.Drawing.Priority,
Constraints = constraints,
};
var proxyItem = new NestItem
{
Drawing = proxy,
Priority = item.Priority,
Quantity = item.Quantity > 0 ? item.Quantity / 2 : item.Quantity,
StepAngle = item.StepAngle,
RotationStart = item.RotationStart,
RotationEnd = item.RotationEnd,
};
// Previews show the plain fill; the pair fill is compared once both are done.
var pairs = FillItem(strategy, plate, proxyItem, workArea, null, token);
if (pairs.Count == 0 || token.IsCancellationRequested)
return none;
var parts = new List<Part>(2 * pairs.Count);
var groups = new List<CommonLineGroup>(pairs.Count);
foreach (var placed in pairs)
{
var rotation = placed.Rotation;
var first = Place(item.Drawing, rotation, placed.Location);
var sine = System.Math.Sin(rotation);
var cosine = System.Math.Cos(rotation);
var second = Place(item.Drawing, rotation + CommonLinePair.SecondRotation,
new Vector(placed.Location.X + pair.SecondX * cosine - pair.SecondY * sine,
placed.Location.Y + pair.SecondX * sine + pair.SecondY * cosine));
parts.Add(first);
parts.Add(second);
groups.Add(new CommonLineGroup(new[] { first, second }, kerf));
}
if (parts.Count < plain.Count)
return none;
if (parts.Count == plain.Count)
{
if (usage != CommonLineUsage.Whenever
|| RequireFiller(strategy, plate).IsBetterFill(plain, parts, workArea))
return none;
}
return new PlateFillProposal(parts, groups);
}
// The proxy's frame is the drawing's own: rotate about the program origin, then move.
private static Part Place(Drawing drawing, double rotation, Vector location)
{
var part = new Part(drawing);
part.Rotate(rotation);
part.Location = location;
part.UpdateBounds();
return part;
}
}
@@ -15,7 +15,7 @@ namespace OpenNest.Engine.Jobs.Placement;
/// (accepting a preview, adding parts to a plate) and cancel/discard behavior remain with the
/// caller, exactly as they were with the legacy single-plate engine surface.
/// </summary>
public static class PlateFillService
public static partial class PlateFillService
{
/// <summary>Strategy used when a caller selection names none.</summary>
public const string DefaultStrategy = "Lattice";
+25 -2
View File
@@ -24,6 +24,13 @@ public sealed class NestJobDocument
private const int LowerFirstPriorityVersion = 1;
/// <summary>
/// A version 2 job that also uses common lines (<see cref="OptionsJson.CommonLineUsage"/> on
/// with a positive kerf). Written only then, so a worker that cannot make common lines refuses
/// the job rather than solving it without them, which the desktop's replay would reject.
/// </summary>
public const int CommonLineVersion = 3;
private static readonly JsonSerializerOptions Options = new()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
@@ -70,8 +77,12 @@ public sealed class NestJobDocument
SalvageRate = o.SalvageRate,
MinimumSalvageDimension = o.MinimumSalvageDimension,
OffcutCut = o.OffcutCut,
CommonLineUsage = o.CommonLineUsage,
CommonLineKerf = o.CommonLineKerf,
} : null,
};
if (request.Options?.UsesCommonLines == true)
document.Version = CommonLineVersion;
foreach (var item in request.Items)
{
var index = item?.Drawing == null ? -1 : IndexOf(drawings, item.Drawing);
@@ -94,8 +105,8 @@ public sealed class NestJobDocument
public NestPipelineRequest ToRequest(IReadOnlyList<Drawing> drawings)
{
ArgumentNullException.ThrowIfNull(drawings);
if (Version != CurrentVersion && Version != LowerFirstPriorityVersion)
throw new FormatException($"Nest job version {Version} is not supported; this build reads {CurrentVersion}.");
if (Version != CurrentVersion && Version != LowerFirstPriorityVersion && Version != CommonLineVersion)
throw new FormatException($"Nest job version {Version} is not supported; this build reads {CommonLineVersion}.");
if (string.IsNullOrWhiteSpace(EngineName))
throw new FormatException("The nest job names no engine.");
if (DrawingNames == null || DrawingNames.Count != drawings.Count
@@ -124,6 +135,12 @@ public sealed class NestJobDocument
var options = JobOptions is { } o
? new NestJobOptions(o.PlacementStrategy ?? "Lattice", o.MaxPlates, o.SalvageRate, o.MinimumSalvageDimension,
searchUntilCancelled: false, o.OffcutCut)
{
CommonLineUsage = Enum.IsDefined(o.CommonLineUsage) ? o.CommonLineUsage
: throw new FormatException("The nest job's common-line usage is not one this build knows."),
CommonLineKerf = double.IsFinite(o.CommonLineKerf) && o.CommonLineKerf >= 0 ? o.CommonLineKerf
: throw new FormatException("The nest job's common-line kerf is not a finite, nonnegative number."),
}
: null;
return new NestPipelineRequest(EngineName, items,
(Stock ?? new()).Select(s => s?.ToStock() ?? throw new FormatException("A nest job stock entry is empty.")).ToList(),
@@ -169,5 +186,11 @@ public sealed class NestJobDocument
public double SalvageRate { get; set; }
public double MinimumSalvageDimension { get; set; }
public CutOffAxis? OffcutCut { get; set; }
/// <summary><see cref="NestJobOptions.CommonLineUsage"/>; absent (off) before version 3.</summary>
public CommonLineUsage CommonLineUsage { get; set; }
/// <summary><see cref="NestJobOptions.CommonLineKerf"/>; absent (zero) before version 3.</summary>
public double CommonLineKerf { get; set; }
}
}
@@ -76,6 +76,8 @@ public sealed class NestSolveTranscript
PlateIndex = p.PlateIndex,
Stock = NestStockJson.From(p.Stock),
Placements = p.Placements.ToList(),
CommonLines = p.CommonLines.Count == 0 ? null
: p.CommonLines.Select(g => new CommonLineJson { Kerf = g.Kerf, Placements = g.Placements.ToList() }).ToList(),
}).ToList(),
Fulfillment = result.Fulfillment.ToList(),
StockUsage = result.StockUsage.ToList(),
@@ -90,7 +92,9 @@ public sealed class NestSolveTranscript
{
var stock = plate.Stock?.ToStock() ?? throw new FormatException("A result sheet has no stock.");
var own = job.Plates.FirstOrDefault(s => RepeatedPlateGrouping.SameStock(s, stock));
plates.Add(new NestJobPlateResult(plate.PlateIndex, own ?? stock, plate.Placements ?? new()));
plates.Add(new NestJobPlateResult(plate.PlateIndex, own ?? stock, plate.Placements ?? new(),
plate.CommonLines?.Select(g => g == null ? throw new FormatException("A result common-line group is empty.")
: new NestJobCommonLine(g.Kerf, g.Placements ?? new()))));
}
return new NestJobResult(Status, StopReason, plates, Fulfillment ?? new(), StockUsage ?? new());
}
@@ -101,5 +105,16 @@ public sealed class NestSolveTranscript
public int PlateIndex { get; set; }
public NestStockJson Stock { get; set; }
public List<NestJobPlacement> Placements { get; set; } = new();
/// <summary>Common-line groups an engine returned itself (none of the built-in engines
/// do: the pipeline makes pairs around them). Omitted when empty.</summary>
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public List<CommonLineJson> CommonLines { get; set; }
}
public sealed class CommonLineJson
{
public double Kerf { get; set; }
public List<int> Placements { get; set; } = new();
}
}
@@ -31,7 +31,7 @@ public sealed class RecordingNestingEngine : INestingEngine
{
if (Progress != null)
{
var tap = CutoutPipelinePrepass.HasProxies(job) ? new NestPipeline.PreviewProgress(Progress) : Progress;
var tap = CutoutPipelinePrepass.HasProxies(job) || CommonLines.CommonLinePipelinePrepass.HasProxies(job) ? new NestPipeline.PreviewProgress(Progress) : Progress;
progress = progress == null ? tap : new BothProgress(progress, tap);
}
var result = inner.Solve(job, progress, token);
@@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Threading;
using OpenNest.Engine.Jobs.CommonLines;
using OpenNest.Engine.Jobs.Cutouts;
namespace OpenNest.Engine.Jobs.Remote;
@@ -131,6 +132,11 @@ public sealed class RemoteNestPlanPreview
foreach (var part in engineJob.Parts)
parts.TryAdd(part.Id, part);
}
// A common-line trial's pair proxies, from either share (same geometry per part).
foreach (var share in new[] { CommonLinePipelinePrepass.Share.All, CommonLinePipelinePrepass.Share.Half })
if (CommonLinePipelinePrepass.Prepare(job, share, token)?.EngineJob is { } pairJob)
foreach (var part in pairJob.Parts)
parts.TryAdd(part.Id, part);
}
if (!Known(plan))
return null;
@@ -80,7 +80,8 @@ internal static class RepeatedPlateGrouping
if (ReferenceEquals(a, b))
return true;
if (a == null || b == null || !SameStock(a.Stock, b.Stock)
|| a.Placements.Count != b.Placements.Count)
|| a.Placements.Count != b.Placements.Count
|| !System.Linq.Enumerable.SequenceEqual(a.CommonLines, b.CommonLines))
return false;
for (var i = 0; i < a.Placements.Count; i++)
{