fix(engine): enforce whole-job safety invariants

Task 5 of the whole-job engine API: add a geometry safety gate that
validates every candidate trial before the runner commits accounting.

- NestJobPlacementValidator: closed-contour validity, rotation-policy
  compliance, work-area containment per quadrant, hole-aware material
  overlap, and required part spacing. Overlap is interior-only, so
  zero-clearance edge/corner contact remains a valid placement.
- NestJobValidator: route candidate validation through the geometry
  gate; reject unusable/unclosed/degenerate contours up front.
- NestJobRunner: wrap candidate evaluation in a progress bridge that
  tags legacy engine detail with the current candidate context.
- LegacyPlateNesterAdapter: forward IProgress to the legacy engine so
  its progress surfaces under the active candidate.
- Tests: geometry (quadrants, rotations, touching, containment, holes,
  empty stock, real Default/Strip smoke), validation, and cancellation
  suites; repaired test fakes that emitted out-of-bounds or overlapping
  placements the gate now correctly rejects.

Engine.Tests: 70 passed, 0 failed, 0 skipped in Debug and Release.
Windows-only OpenNest.Tests not run on Linux.
This commit is contained in:
aj
2026-09-18 05:56:37 -04:00
parent 75c8adc76c
commit 2b0b962c8f
12 changed files with 760 additions and 29 deletions
@@ -16,7 +16,7 @@ public class FiniteStockJobTests
} }
internal static PlateCandidate One(PlatePlacementRequest request) => new(new[] internal static PlateCandidate One(PlatePlacementRequest request) => new(new[]
{ new NestJobPlacement(request.Parts[0].Id, 99, 1, 2, 0) }); { new NestJobPlacement(request.Parts[0].Id, 99, 0, 0, 0) });
[Theory] [Theory]
[InlineData(3, 3, 0, NestJobStatus.Complete, NestJobStopReason.Completed)] [InlineData(3, 3, 0, NestJobStatus.Complete, NestJobStopReason.Completed)]
@@ -108,7 +108,7 @@ public class FiniteStockJobTests
public void MixedStockCanBeEvaluated() public void MixedStockCanBeEvaluated()
{ {
var job = Job(); var job = Job();
var mixed = new NestJob(job.Parts, job.Plates.Concat(new[] { new NestPlateStock("other", new Size(10, 20), 2) })); var mixed = new NestJob(job.Parts, job.Plates.Concat(new[] { new NestPlateStock("other", new Size(20, 10), 2) }));
var result = new NestJobRunner(_ => new Nester(One)).Solve(mixed); var result = new NestJobRunner(_ => new Nester(One)).Solve(mixed);
Assert.Equal(NestJobStatus.Complete, result.Status); Assert.Equal(NestJobStatus.Complete, result.Status);
} }
@@ -58,7 +58,11 @@ public class JobAdapterTests
{ {
Assert.NotSame(items[0].Drawing, items[1].Drawing); Assert.NotSame(items[0].Drawing, items[1].Drawing);
foreach (var item in items) item.Drawing.Name = "identical"; foreach (var item in items) item.Drawing.Name = "identical";
return items.Select(i => new Part(i.Drawing)).ToList(); return new List<Part>
{
new Part(items[0].Drawing, new Vector(0, 0)),
new Part(items[1].Drawing, new Vector(10, 0))
};
})); }));
var result = new NestJobRunner(_ => adapter).Solve(job); var result = new NestJobRunner(_ => adapter).Solve(job);
Assert.Equal(new[] { "a", "b" }, result.Plates[0].Placements.Select(p => p.PartId)); Assert.Equal(new[] { "a", "b" }, result.Plates[0].Placements.Select(p => p.PartId));
@@ -0,0 +1,114 @@
using OpenNest.CNC;
using OpenNest.Geometry;
namespace OpenNest.Engine.Tests.Jobs;
public class NestJobCancellationTests
{
[Fact]
public void PreTrialCancellationSkipsCandidateWorkAndPreservesInput()
{
using var cancellation = new CancellationTokenSource();
cancellation.Cancel();
var nester = new CancellableNester(_ => new PlateCandidate(Array.Empty<NestJobPlacement>()));
var part = new NestJobPart("part", PartGeometrySnapshot.FromProgram(TestDrawingFactory.Rectangle(4, 3)), 1);
var sourceGeometry = part.Geometry.Motions.ToArray();
var stock = new NestPlateStock("stock", new Size(20, 30), 1);
var job = new NestJob(new[] { part }, new[] { stock });
Assert.Throws<OperationCanceledException>(() => new NestJobRunner(_ => nester).Solve(job, token: cancellation.Token));
Assert.Equal(0, nester.Calls);
Assert.Equal(sourceGeometry, job.Parts[0].Geometry.Motions);
Assert.Equal(1, job.Parts[0].Quantity);
Assert.Equal(1, job.Plates[0].Quantity);
}
[Fact]
public void CancellationDuringCandidateThrowsWithoutCommitOrInputMutation()
{
using var cancellation = new CancellationTokenSource();
var reports = new List<NestJobProgress>();
var part = new NestJobPart("part", PartGeometrySnapshot.FromProgram(TestDrawingFactory.Rectangle(4, 3)), 1);
var sourceGeometry = part.Geometry.Motions.ToArray();
var stock = new NestPlateStock("stock", new Size(20, 30), 1);
var job = new NestJob(new[] { part }, new[] { stock });
var nester = new CancellableNester((_, token) =>
{
cancellation.Cancel();
token.ThrowIfCancellationRequested();
return new PlateCandidate(Array.Empty<NestJobPlacement>());
});
Assert.Throws<OperationCanceledException>(() => new NestJobRunner(_ => nester)
.Solve(job, new InlineProgress(reports.Add), cancellation.Token));
Assert.Equal(1, nester.Calls);
Assert.DoesNotContain(reports, report => report.Stage == NestJobStage.PlateCommitted);
Assert.Equal(sourceGeometry, job.Parts[0].Geometry.Motions);
Assert.Equal(1, job.Parts[0].Quantity);
Assert.Equal(1, job.Plates[0].Quantity);
}
[Fact]
public void LegacyProgressIsWrappedWithCurrentCandidateContext()
{
var reports = new List<NestJobProgress>();
var part = new NestJobPart("part", PartGeometrySnapshot.FromProgram(TestDrawingFactory.Rectangle(4, 3)), 1);
var job = new NestJob(new[] { part }, new[] { new NestPlateStock("stock", new Size(20, 30), 1) });
var runner = new NestJobRunner(_ => new LegacyPlateNesterAdapter(plate => new ReportingEngine(plate)));
var result = runner.Solve(job, new InlineProgress(reports.Add));
Assert.Equal(NestJobStopReason.NoPlacementFound, result.StopReason);
var legacy = Assert.Single(reports.Where(report => report.LegacyProgress != null));
Assert.Equal(NestJobStage.EvaluatingCandidate, legacy.Stage);
Assert.Equal("stock", legacy.StockId);
Assert.Equal(0, legacy.PlateIndex);
Assert.Equal(0, legacy.CommittedPlates);
Assert.Equal(0, legacy.CommittedParts);
Assert.Equal("legacy detail", legacy.LegacyProgress!.Description);
}
private sealed class InlineProgress(Action<NestJobProgress> report) : IProgress<NestJobProgress>
{
public void Report(NestJobProgress value) => report(value);
}
private sealed class CancellableNester : IPlateNester
{
private readonly Func<PlatePlacementRequest, CancellationToken, PlateCandidate> place;
public CancellableNester(Func<PlatePlacementRequest, PlateCandidate> place)
{
this.place = (request, _) => place(request);
}
public CancellableNester(Func<PlatePlacementRequest, CancellationToken, PlateCandidate> place)
{
this.place = place;
}
public int Calls { get; private set; }
public PlateCandidate Place(PlatePlacementRequest request, IProgress<NestJobProgress>? progress = null,
CancellationToken token = default)
{
Calls++;
return place(request, token);
}
}
private sealed class ReportingEngine(Plate plate) : NestEngineBase(plate)
{
public override string Name => "reporting";
public override string Description => "reports progress";
public override List<Part> Nest(List<NestItem> items, IProgress<NestProgress>? progress,
CancellationToken token)
{
progress?.Report(new NestProgress { Description = "legacy detail" });
return new List<Part>();
}
}
}
@@ -0,0 +1,159 @@
using OpenNest.Geometry;
namespace OpenNest.Engine.Tests.Jobs;
public class NestJobGeometryTests
{
[Fact]
public void CandidateOutsideUsableWorkAreaFailsWithoutMutatingInput()
{
var part = new NestJobPart("part", PartGeometrySnapshot.FromProgram(TestDrawingFactory.Rectangle(4, 3)), 1);
var sourceGeometry = part.Geometry.Motions.ToArray();
var stock = new NestPlateStock("stock", new Size(20, 30), 1,
edgeSpacing: new Spacing(2, 1, 3, 4));
var job = new NestJob(new[] { part }, new[] { stock });
var runner = new NestJobRunner(_ => new CandidateNester(new[] { new NestJobPlacement("part", 0, 26, 1, 0) }));
Assert.Throws<InvalidOperationException>(() => runner.Solve(job));
Assert.Equal(sourceGeometry, job.Parts[0].Geometry.Motions);
Assert.Equal(1, job.Parts[0].Quantity);
Assert.Equal(1, job.Plates[0].Quantity);
}
[Theory]
[InlineData(1, 0, 0)]
[InlineData(2, -11, 0)]
[InlineData(3, -11, -7)]
[InlineData(4, 0, -7)]
public void UnequalRectanglesFitAtEachQuadrantsUsableOrigin(int quadrant, double x, double y)
{
var part = new NestJobPart("part", PartGeometrySnapshot.FromProgram(TestDrawingFactory.Rectangle(2, 3)), 1);
var stock = new NestPlateStock("stock", new Size(7, 11), 1, quadrant: quadrant);
var job = new NestJob(new[] { part }, new[] { stock });
var result = Solve(job, new NestJobPlacement("part", 0, x, y, 0));
Assert.Equal(NestJobStatus.Complete, result.Status);
Assert.Equal(new NestJobPlacement("part", 0, x, y, 0), Assert.Single(result.Plates[0].Placements));
}
[Fact]
public void FixedAndBoundedRotationPoliciesRejectDisallowedAngles()
{
var fixedPart = new NestJobPart("part", PartGeometrySnapshot.FromProgram(TestDrawingFactory.Rectangle(4, 2)), 1,
rotation: RotationPolicy.Fixed(System.Math.PI / 2));
var fixedJob = new NestJob(new[] { fixedPart }, new[] { new NestPlateStock("stock", new Size(10, 10), 1) });
Assert.Throws<InvalidOperationException>(() => Solve(fixedJob, new NestJobPlacement("part", 0, 0, 0, 0)));
var fixedResult = Solve(fixedJob, new NestJobPlacement("part", 0, 2, 0, System.Math.PI / 2));
Assert.Equal(NestJobStatus.Complete, fixedResult.Status);
var boundedPart = new NestJobPart("part", PartGeometrySnapshot.FromProgram(TestDrawingFactory.Rectangle(4, 2)), 1,
rotation: RotationPolicy.BoundedSweep(0, System.Math.PI / 2, System.Math.PI / 4));
var boundedJob = new NestJob(new[] { boundedPart }, new[] { new NestPlateStock("stock", new Size(10, 10), 1) });
Assert.Throws<InvalidOperationException>(() => Solve(boundedJob,
new NestJobPlacement("part", 0, 2, 0, System.Math.PI / 3)));
var boundedResult = Solve(boundedJob, new NestJobPlacement("part", 0, 2, 0, System.Math.PI / 4));
Assert.Equal(NestJobStatus.Complete, boundedResult.Status);
}
[Fact]
public void EdgeTouchingIsAllowedAtZeroSpacingAndRejectedAtPositiveSpacing()
{
var part = new NestJobPart("part", PartGeometrySnapshot.FromProgram(TestDrawingFactory.Rectangle(2, 2)), 2);
var touching = new[]
{
new NestJobPlacement("part", 0, 0, 0, 0),
new NestJobPlacement("part", 1, 2, 0, 0)
};
var zeroSpacing = new NestJob(new[] { part }, new[] { new NestPlateStock("stock", new Size(10, 10), 1) });
var positiveSpacing = new NestJob(new[] { part }, new[] { new NestPlateStock("stock", new Size(10, 10), 1, 0.1) });
Assert.Equal(NestJobStatus.Complete, Solve(zeroSpacing, touching).Status);
Assert.Throws<InvalidOperationException>(() => Solve(positiveSpacing, touching));
}
[Fact]
public void OverlapAndContainmentAreRejected()
{
var outer = new NestJobPart("outer", PartGeometrySnapshot.FromProgram(TestDrawingFactory.Rectangle(6, 6)), 1);
var inner = new NestJobPart("inner", PartGeometrySnapshot.FromProgram(TestDrawingFactory.Rectangle(2, 2)), 1);
var job = new NestJob(new[] { outer, inner }, new[] { new NestPlateStock("stock", new Size(20, 20), 1) });
Assert.Throws<InvalidOperationException>(() => Solve(job,
new NestJobPlacement("outer", 0, 0, 0, 0),
new NestJobPlacement("inner", 0, 2, 2, 0)));
}
[Fact]
public void EmptyStockStopsWithoutCallingCandidateNester()
{
var nester = new CountingNester();
var part = new NestJobPart("part", PartGeometrySnapshot.FromProgram(TestDrawingFactory.Rectangle(2, 2)), 1);
var job = new NestJob(new[] { part }, Array.Empty<NestPlateStock>());
var result = new NestJobRunner(_ => nester).Solve(job);
Assert.Equal(NestJobStopReason.StockExhausted, result.StopReason);
Assert.Equal(0, nester.Calls);
}
[Theory]
[InlineData("Default")]
[InlineData("Strip")]
public void RealEngineSmokeCasesPreserveInputAndProduceSafeAccounting(string strategy)
{
var drawing = new Drawing("generated rectangle", TestDrawingFactory.Rectangle(6, 4));
var part = DrawingJobMapper.FromDrawing("part", drawing, 3);
var sourceGeometry = part.Geometry.Motions.ToArray();
var stock = new NestPlateStock("stock", new Size(30, 50), 1, 1, new Spacing(1, 1, 1, 1));
var job = new NestJob(new[] { part }, new[] { stock }, new NestJobOptions(strategy));
var result = new NestJobRunner(PlateNesterFactory.Create).Solve(job);
var materialized = NestResultMaterializer.Materialize(job, result);
Assert.Equal(NestJobStatus.Complete, result.Status);
Assert.All(result.Fulfillment, fulfillment => Assert.Equal(fulfillment.Requested,
fulfillment.Placed + fulfillment.Unplaced));
Assert.Equal(sourceGeometry, job.Parts[0].Geometry.Motions);
Assert.Equal(3, job.Parts[0].Quantity);
Assert.Equal(1, job.Plates[0].Quantity);
Assert.All(materialized.Nest.Plates, plate =>
{
var workArea = plate.WorkArea();
Assert.All(plate.Parts, placed =>
{
Assert.True(placed.BoundingBox.Left >= workArea.Left - 1e-6);
Assert.True(placed.BoundingBox.Right <= workArea.Right + 1e-6);
Assert.True(placed.BoundingBox.Bottom >= workArea.Bottom - 1e-6);
Assert.True(placed.BoundingBox.Top <= workArea.Top + 1e-6);
});
for (var left = 0; left < plate.Parts.Count; left++)
for (var right = left + 1; right < plate.Parts.Count; right++)
Assert.False(plate.Parts[left].Intersects(plate.Parts[right], out _));
});
}
private static NestJobResult Solve(NestJob job, params NestJobPlacement[] placements) =>
new NestJobRunner(_ => new CandidateNester(placements)).Solve(job);
private sealed class CandidateNester(IEnumerable<NestJobPlacement> placements) : IPlateNester
{
public PlateCandidate Place(PlatePlacementRequest request, IProgress<NestJobProgress>? progress = null,
CancellationToken token = default) => new(placements);
}
private sealed class CountingNester : IPlateNester
{
public int Calls { get; private set; }
public PlateCandidate Place(PlatePlacementRequest request, IProgress<NestJobProgress>? progress = null,
CancellationToken token = default)
{
Calls++;
return new PlateCandidate(Array.Empty<NestJobPlacement>());
}
}
}
@@ -66,7 +66,7 @@ public class NestJobStockSelectionTests
var area = Solve(new[] { Part("p", 1) }, new[] { Stock("large", 20, 20, 1), Stock("small", 10, 10, 1) }, var area = Solve(new[] { Part("p", 1) }, new[] { Stock("large", 20, 20, 1), Stock("small", 10, 10, 1) },
request => Candidate(request, "p")); request => Candidate(request, "p"));
var envelope = Solve(new[] { Part("p", 2) }, new[] { Stock("a", 10, 10, 1), Stock("b", 10, 10, 1) }, var envelope = Solve(new[] { Part("p", 2) }, new[] { Stock("a", 10, 10, 1), Stock("b", 10, 10, 1) },
request => request.Stock.Id == "a" ? CandidatePair("p", 0, 10) : CandidatePair("p", 0, 1)); request => request.Stock.Id == "a" ? CandidatePair("p", 4, 5) : CandidatePair("p", 4, 0));
var inputOrder = Solve(new[] { Part("p", 1) }, new[] { Stock("first", 10, 10, 1), Stock("second", 10, 10, 1) }, var inputOrder = Solve(new[] { Part("p", 1) }, new[] { Stock("first", 10, 10, 1), Stock("second", 10, 10, 1) },
request => Candidate(request, "p")); request => Candidate(request, "p"));
@@ -93,7 +93,7 @@ public class NestJobStockSelectionTests
new NestJobRunner(_ => new Nester(place)).Solve(new NestJob(parts, stock, options)); new NestJobRunner(_ => new Nester(place)).Solve(new NestJob(parts, stock, options));
private static NestJobPart Part(string id, int quantity, int priority = 0) => private static NestJobPart Part(string id, int quantity, int priority = 0) =>
new(id, PartGeometrySnapshot.FromProgram(TestDrawingFactory.Rectangle()), quantity, priority); new(id, PartGeometrySnapshot.FromProgram(TestDrawingFactory.Rectangle(4, 5)), quantity, priority);
private static NestPlateStock Stock(string id, double width, double length, int? quantity) => private static NestPlateStock Stock(string id, double width, double length, int? quantity) =>
new(id, new Size(width, length), quantity); new(id, new Size(width, length), quantity);
@@ -103,10 +103,10 @@ public class NestJobStockSelectionTests
return new PlateCandidate(new[] { new NestJobPlacement(id, 0, firstX, 0, 0) }); return new PlateCandidate(new[] { new NestJobPlacement(id, 0, firstX, 0, 0) });
} }
private static PlateCandidate CandidatePair(string id, double first, double second) => new(new[] private static PlateCandidate CandidatePair(string id, double secondX, double secondY) => new(new[]
{ {
new NestJobPlacement(id, 0, first, first, 0), new NestJobPlacement(id, 0, 0, 0, 0),
new NestJobPlacement(id, 1, second, second, 0) new NestJobPlacement(id, 1, secondX, secondY, 0)
}); });
private static PlateCandidate Empty() => new(Array.Empty<NestJobPlacement>()); private static PlateCandidate Empty() => new(Array.Empty<NestJobPlacement>());
@@ -0,0 +1,120 @@
using OpenNest.CNC;
using OpenNest.Geometry;
namespace OpenNest.Engine.Tests.Jobs;
public class NestJobValidationTests
{
[Fact]
public void IncrementalContoursUseAccumulatedCoordinates()
{
var program = new Program(Mode.Incremental);
program.MoveTo(0, 0);
program.LineTo(4, 0);
program.LineTo(0, 3);
program.LineTo(-4, 0);
program.LineTo(0, -3);
var job = new NestJob(new[]
{
new NestJobPart("part", PartGeometrySnapshot.FromProgram(program), 1)
}, new[] { new NestPlateStock("stock", new Size(10, 10), 1) });
var result = Solve(job, new NestJobPlacement("part", 0, 0, 0, 0));
Assert.Equal(NestJobStatus.Complete, result.Status);
Assert.Equal(new PartFulfillment("part", 1, 1, 0), Assert.Single(result.Fulfillment));
}
[Fact]
public void CandidateInsideAnotherRequirementsHoleDoesNotOverlapMaterial()
{
var outer = new NestJobPart("outer", PartGeometrySnapshot.FromProgram(RectangleWithHole()), 1);
var inner = new NestJobPart("inner", PartGeometrySnapshot.FromProgram(TestDrawingFactory.Rectangle(2, 2)), 1);
var job = new NestJob(new[] { outer, inner }, new[] { new NestPlateStock("stock", new Size(20, 20), 1) });
var result = Solve(job,
new NestJobPlacement("outer", 0, 0, 0, 0),
new NestJobPlacement("inner", 0, 4, 4, 0));
Assert.Equal(NestJobStatus.Complete, result.Status);
Assert.Single(result.Plates);
Assert.Equal(2, result.Plates[0].Placements.Count);
}
[Fact]
public void UnknownOrOverproducingCandidateFailsBeforeCommitWithoutChangingInput()
{
var reports = new List<NestJobProgress>();
var part = new NestJobPart("part", PartGeometrySnapshot.FromProgram(TestDrawingFactory.Rectangle(2, 2)), 1);
var stock = new NestPlateStock("stock", new Size(20, 20), 1);
var job = new NestJob(new[] { part }, new[] { stock });
var runner = new NestJobRunner(_ => new CandidateNester(new[]
{
new NestJobPlacement("part", 0, 0, 0, 0),
new NestJobPlacement("unknown", 0, 4, 0, 0)
}));
Assert.Throws<InvalidOperationException>(() => runner.Solve(job, new InlineProgress(reports.Add)));
Assert.Equal(1, job.Parts[0].Quantity);
Assert.Equal(1, job.Plates[0].Quantity);
Assert.DoesNotContain(reports, report => report.Stage == NestJobStage.PlateCommitted);
}
[Fact]
public void CandidateThatOverproducesIsRejectedRatherThanClamped()
{
var part = new NestJobPart("part", PartGeometrySnapshot.FromProgram(TestDrawingFactory.Rectangle(2, 2)), 1);
var job = new NestJob(new[] { part }, new[] { new NestPlateStock("stock", new Size(20, 20), 1) });
Assert.Throws<InvalidOperationException>(() => Solve(job,
new NestJobPlacement("part", 0, 0, 0, 0),
new NestJobPlacement("part", 1, 4, 0, 0)));
Assert.Equal(1, job.Parts[0].Quantity);
Assert.Equal(1, job.Plates[0].Quantity);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void OpenOrZeroLengthContoursAreRejected(bool zeroLength)
{
var program = new Program();
program.MoveTo(0, 0);
program.LineTo(4, 0);
if (zeroLength) program.LineTo(4, 0);
program.LineTo(4, 3);
program.LineTo(0, 3);
if (zeroLength) program.LineTo(0, 0);
var job = new NestJob(new[] { new NestJobPart("part", PartGeometrySnapshot.FromProgram(program), 1) },
new[] { new NestPlateStock("stock", new Size(20, 20), 1) });
Assert.Throws<ArgumentException>(() => new NestJobRunner(_ => new CandidateNester(Array.Empty<NestJobPlacement>())).Solve(job));
}
private static NestJobResult Solve(NestJob job, params NestJobPlacement[] placements) =>
new NestJobRunner(_ => new CandidateNester(placements)).Solve(job);
private static Program RectangleWithHole()
{
var program = TestDrawingFactory.Rectangle(10, 10);
program.MoveTo(3, 3);
program.LineTo(3, 7);
program.LineTo(7, 7);
program.LineTo(7, 3);
program.LineTo(3, 3);
return program;
}
private sealed class CandidateNester(IEnumerable<NestJobPlacement> placements) : IPlateNester
{
public PlateCandidate Place(PlatePlacementRequest request, IProgress<NestJobProgress>? progress = null,
CancellationToken token = default) => new(placements);
}
private sealed class InlineProgress(Action<NestJobProgress> report) : IProgress<NestJobProgress>
{
public void Report(NestJobProgress value) => report(value);
}
}
@@ -46,7 +46,8 @@ public sealed class LegacyPlateNesterAdapter : IPlateNester
}); });
} }
var engine = engineFactory(plate) ?? throw new InvalidOperationException("Legacy engine factory returned null."); var engine = engineFactory(plate) ?? throw new InvalidOperationException("Legacy engine factory returned null.");
var parts = engine.Nest(items, null, token); var legacyProgress = progress == null ? null : new LegacyProgress(progress, request.Stock.Id);
var parts = engine.Nest(items, legacyProgress, token);
token.ThrowIfCancellationRequested(); token.ThrowIfCancellationRequested();
if (parts == null) throw new InvalidOperationException("Legacy engine returned null placements."); if (parts == null) throw new InvalidOperationException("Legacy engine returned null placements.");
var placements = new List<NestJobPlacement>(); var placements = new List<NestJobPlacement>();
@@ -58,4 +59,13 @@ public sealed class LegacyPlateNesterAdapter : IPlateNester
} }
return new PlateCandidate(placements); return new PlateCandidate(placements);
} }
private sealed class LegacyProgress(IProgress<NestJobProgress> progress, string stockId) : IProgress<NestProgress>
{
public void Report(NestProgress value)
{
ArgumentNullException.ThrowIfNull(value);
progress.Report(new NestJobProgress(NestJobStage.EvaluatingCandidate, stockId, -1, 0, 0, value));
}
}
} }
@@ -0,0 +1,307 @@
using System;
using System.Collections.Generic;
using OpenNest.Converters;
using OpenNest.Geometry;
using OpenNest.Math;
namespace OpenNest;
/// <summary>Validates a trial against immutable job geometry before the runner commits accounting.</summary>
internal static class NestJobPlacementValidator
{
private const double Epsilon = 0.0000001;
internal static void ValidateCandidate(PlateCandidate candidate, NestPlateStock stock,
IReadOnlyDictionary<string, int> remaining, IReadOnlyDictionary<string, NestJobPart> parts)
{
if (candidate == null) throw new InvalidOperationException("The plate nester returned a null candidate.");
var counts = new Dictionary<string, int>(StringComparer.Ordinal);
var placed = new List<ShapeTopology>();
foreach (var placement in candidate.Placements)
{
if (placement.PartId == null || !remaining.TryGetValue(placement.PartId, out var available) ||
!parts.TryGetValue(placement.PartId, out var part))
throw new InvalidOperationException("Candidate references an unknown requirement ID.");
if (!double.IsFinite(placement.X) || !double.IsFinite(placement.Y) || !double.IsFinite(placement.Rotation))
throw new InvalidOperationException("Candidate poses must be finite.");
counts.TryGetValue(placement.PartId, out var count);
if (count >= available) throw new InvalidOperationException("Candidate overproduces a requirement.");
if (!RotationIsAllowed(part.Rotation, placement.Rotation))
throw new InvalidOperationException("Candidate rotation is not allowed for the requirement.");
var shape = Transform(CreateShape(part.Geometry), placement);
if (!FitsWorkArea(shape, stock))
throw new InvalidOperationException("Candidate placement falls outside the usable stock area.");
foreach (var other in placed)
{
if (Overlaps(shape, other))
throw new InvalidOperationException("Candidate placements overlap.");
if (stock.PartSpacing > 0 && Distance(shape, other) < stock.PartSpacing - Epsilon)
throw new InvalidOperationException("Candidate placements violate required part spacing.");
}
placed.Add(shape);
counts[placement.PartId] = count + 1;
}
}
internal static void ValidateGeometry(PartGeometrySnapshot geometry)
{
_ = CreateShape(geometry);
}
private static bool RotationIsAllowed(RotationPolicy policy, double rotation)
{
if (policy.Kind == RotationPolicyKind.Automatic) return true;
if (policy.Kind == RotationPolicyKind.Fixed)
return AnglesEqual(rotation, policy.Start);
if (rotation < policy.Start - Epsilon || rotation > policy.End + Epsilon) return false;
var steps = (rotation - policy.Start) / policy.Step;
return System.Math.Abs(steps - System.Math.Round(steps)) <= Epsilon;
}
private static bool AnglesEqual(double left, double right)
{
var delta = (left - right) % (System.Math.PI * 2);
return System.Math.Abs(delta) <= Epsilon || System.Math.Abs(System.Math.Abs(delta) - System.Math.PI * 2) <= Epsilon;
}
private static ShapeTopology CreateShape(PartGeometrySnapshot geometry)
{
var entities = ConvertProgram.ToGeometry(DrawingJobMapper.ToProgram(geometry));
var cutEntities = new List<Entity>();
foreach (var entity in entities)
if (!ReferenceEquals(entity.Layer, SpecialLayers.Rapid))
cutEntities.Add(entity);
var contours = ShapeBuilder.GetShapes(cutEntities);
if (contours.Count == 0) throw new ArgumentException("Geometry must contain a closed contour.");
foreach (var contour in contours)
ValidateContour(contour);
var profile = new ShapeProfile(cutEntities);
profile.NormalizeWinding();
return new ShapeTopology(profile.Perimeter, profile.Cutouts);
}
private static void ValidateContour(Shape contour)
{
if (!contour.IsClosed())
throw new ArgumentException("Geometry must contain closed contours with usable edges.");
foreach (var entity in contour.Entities)
if (entity.Length <= Epsilon)
throw new ArgumentException("Geometry contains a zero-length edge.");
if (contour.Area() <= Epsilon)
throw new ArgumentException("Geometry must contain non-degenerate contours.");
}
private static ShapeTopology Transform(ShapeTopology source, NestJobPlacement placement)
{
var perimeter = TransformContour(source.Perimeter, placement);
var cutouts = new List<Shape>(source.Cutouts.Count);
foreach (var cutout in source.Cutouts)
cutouts.Add(TransformContour(cutout, placement));
return new ShapeTopology(perimeter, cutouts);
}
private static Shape TransformContour(Shape source, NestJobPlacement placement)
{
var contour = (Shape)source.Clone();
contour.Rotate(placement.Rotation);
contour.Offset(placement.X, placement.Y);
return contour;
}
private static bool FitsWorkArea(ShapeTopology shape, NestPlateStock stock)
{
var workArea = WorkArea(stock);
if (!FitsWorkArea(shape.Perimeter, workArea)) return false;
foreach (var cutout in shape.Cutouts)
if (!FitsWorkArea(cutout, workArea)) return false;
return true;
}
private static Box WorkArea(NestPlateStock stock)
{
var left = stock.Quadrant is 1 or 4 ? 0 : -stock.Size.Length;
var bottom = stock.Quadrant is 1 or 2 ? 0 : -stock.Size.Width;
return new Box(left + stock.EdgeSpacing.Left, bottom + stock.EdgeSpacing.Bottom,
stock.Size.Length - stock.EdgeSpacing.Left - stock.EdgeSpacing.Right,
stock.Size.Width - stock.EdgeSpacing.Bottom - stock.EdgeSpacing.Top);
}
private static bool FitsWorkArea(Shape contour, Box workArea)
{
var bounds = contour.BoundingBox;
return bounds.Left >= workArea.Left - Epsilon && bounds.Right <= workArea.Right + Epsilon &&
bounds.Bottom >= workArea.Bottom - Epsilon && bounds.Top <= workArea.Top + Epsilon;
}
private static bool Overlaps(ShapeTopology left, ShapeTopology right)
{
var leftPoly = ToPolygon(left.Perimeter);
var rightPoly = ToPolygon(right.Perimeter);
if (!leftPoly.BoundingBox.Intersects(rightPoly.BoundingBox))
return false;
// True material overlap requires shared interior area, not boundary touching.
// Edge/corner contact (zero clearance) is a valid placement when part spacing is zero.
return InteriorOverlap(leftPoly, left, rightPoly, right);
}
private static bool InteriorOverlap(Polygon leftPoly, ShapeTopology left, Polygon rightPoly, ShapeTopology right)
{
// The intersection of two polygons is either empty, a region of positive area (true overlap),
// or a zero-area line/point (boundary contact). Test the interior of the intersection region:
// a point strictly inside BOTH perimeters and outside both parts' holes proves shared material.
foreach (var point in InteriorWitnessPoints(leftPoly, rightPoly))
{
if (StrictlyInside(leftPoly, point) && !InAnyHole(left, point) &&
StrictlyInside(rightPoly, point) && !InAnyHole(right, point))
return true;
}
return false;
}
/// <summary>
/// Points that lie in the interior of the perimeter-perimeter intersection when one exists.
/// For each pair of crossing edges, the two interior-side vertices (one from each polygon)
/// have their midpoint inside both perimeters; that midpoint is a witness of positive-area
/// overlap. For containment, an interior vertex of the inner perimeter witnesses it.
/// </summary>
private static IEnumerable<Vector> InteriorWitnessPoints(Polygon left, Polygon right)
{
foreach (var l in left.ToLines())
foreach (var r in right.ToLines())
if (l.Intersects(r, out var pt) && pt.IsValid())
{
yield return Midpoint(l, pt);
yield return Midpoint(r, pt);
}
// Containment: an interior point of one polygon inside the other. Use a point pulled
// toward the centroid of each polygon from a vertex (guaranteed interior for simple shapes).
foreach (var poly in new[] { left, right })
{
foreach (var vertex in poly.Vertices)
{
var centroid = Centroid(poly);
yield return (vertex + centroid) * 0.5;
}
}
}
private static Vector Midpoint(Line line, Vector point)
{
var other = line.StartPoint.DistanceTo(point) <= line.EndPoint.DistanceTo(point)
? line.EndPoint
: line.StartPoint;
return (other + point) * 0.5;
}
private static Vector Centroid(Polygon polygon)
{
var n = polygon.IsClosed() ? polygon.Vertices.Count - 1 : polygon.Vertices.Count;
var sum = Vector.Zero;
for (var i = 0; i < n; i++)
sum += polygon.Vertices[i];
return sum / n;
}
/// <summary>
/// Winding-number point-in-polygon. Returns false for points on an edge or vertex.
/// </summary>
private static bool StrictlyInside(Polygon polygon, Vector point)
{
var n = polygon.IsClosed() ? polygon.Vertices.Count - 1 : polygon.Vertices.Count;
if (n < 3) return false;
var winding = 0;
for (var i = 0; i < n; i++)
{
var p1 = polygon.Vertices[i];
var p2 = polygon.Vertices[(i + 1) % n];
if (OnSegment(p1, p2, point)) return false;
if (p1.Y <= point.Y)
{
if (p2.Y > point.Y && IsLeft(p1, p2, point) > 0)
winding++;
}
else if (p2.Y <= point.Y && IsLeft(p1, p2, point) < 0)
{
winding--;
}
}
return winding != 0;
}
private static bool OnSegment(Vector a, Vector b, Vector p)
{
var cross = (b.X - a.X) * (p.Y - a.Y) - (b.Y - a.Y) * (p.X - a.X);
if (!cross.IsEqualTo(0.0)) return false;
return System.Math.Min(a.X, b.X) - Epsilon <= p.X && p.X <= System.Math.Max(a.X, b.X) + Epsilon &&
System.Math.Min(a.Y, b.Y) - Epsilon <= p.Y && p.Y <= System.Math.Max(a.Y, b.Y) + Epsilon;
}
private static double IsLeft(Vector p1, Vector p2, Vector p) =>
(p2.X - p1.X) * (p.Y - p1.Y) - (p2.Y - p1.Y) * (p.X - p1.X);
private static bool InAnyHole(ShapeTopology topology, Vector point)
{
foreach (var cutout in topology.Cutouts)
if (ToPolygon(cutout).ContainsPoint(point))
return true;
return false;
}
private static double Distance(ShapeTopology left, ShapeTopology right)
{
var result = double.PositiveInfinity;
foreach (var leftContour in AllContours(left))
foreach (var rightContour in AllContours(right))
result = System.Math.Min(result, BoundaryDistance(ToPolygon(leftContour), ToPolygon(rightContour)));
return result;
}
private static IEnumerable<Shape> AllContours(ShapeTopology shape)
{
yield return shape.Perimeter;
foreach (var cutout in shape.Cutouts)
yield return cutout;
}
private static List<Polygon> ToPolygons(List<Shape> contours)
{
var polygons = new List<Polygon>(contours.Count);
foreach (var contour in contours)
polygons.Add(ToPolygon(contour));
return polygons;
}
private static Polygon ToPolygon(Shape contour)
{
var polygon = contour.ToPolygon();
polygon.UpdateBounds();
return polygon;
}
private static double BoundaryDistance(Polygon left, Polygon right)
{
var result = double.PositiveInfinity;
foreach (var leftLine in left.ToLines())
{
foreach (var rightLine in right.ToLines())
{
if (leftLine.Intersects(rightLine)) return 0;
result = System.Math.Min(result, leftLine.ClosestPointTo(rightLine.StartPoint).DistanceTo(rightLine.StartPoint));
result = System.Math.Min(result, leftLine.ClosestPointTo(rightLine.EndPoint).DistanceTo(rightLine.EndPoint));
result = System.Math.Min(result, rightLine.ClosestPointTo(leftLine.StartPoint).DistanceTo(leftLine.StartPoint));
result = System.Math.Min(result, rightLine.ClosestPointTo(leftLine.EndPoint).DistanceTo(leftLine.EndPoint));
}
}
return result;
}
private sealed class ShapeTopology(Shape perimeter, List<Shape> cutouts)
{
internal Shape Perimeter { get; } = perimeter;
internal List<Shape> Cutouts { get; } = cutouts;
}
}
+10
View File
@@ -0,0 +1,10 @@
namespace OpenNest;
public enum NestJobStage { EvaluatingCandidate, PlateCommitted }
/// <summary>
/// Whole-job progress. Counts change only after a physical sheet commits; LegacyProgress is optional
/// non-authoritative detail from a plate nester while its candidate remains under evaluation.
/// </summary>
public sealed record NestJobProgress(NestJobStage Stage, string StockId, int PlateIndex,
int CommittedPlates, int CommittedParts, NestProgress LegacyProgress = null);
-5
View File
@@ -5,11 +5,6 @@ namespace OpenNest;
public enum NestJobStatus { Complete, Incomplete } public enum NestJobStatus { Complete, Incomplete }
public enum NestJobStopReason { Completed, StockExhausted, NoPlacementFound, PlateLimitReached } public enum NestJobStopReason { Completed, StockExhausted, NoPlacementFound, PlateLimitReached }
public enum NestJobStage { EvaluatingCandidate, PlateCommitted }
/// <summary>Committed counts only; candidate evaluation does not imply committed production.</summary>
public sealed record NestJobProgress(NestJobStage Stage, string StockId, int PlateIndex,
int CommittedPlates, int CommittedParts);
/// <summary> /// <summary>
/// Rotate about the snapshot origin, then translate by X/Y into the selected plate quadrant frame. /// Rotate about the snapshot origin, then translate by X/Y into the selected plate quadrant frame.
+16 -2
View File
@@ -29,6 +29,7 @@ public sealed class NestJobRunner : INestingEngine
var plates = new List<NestJobPlateResult>(); var plates = new List<NestJobPlateResult>();
var remaining = job.Parts.ToDictionary(part => part.Id, part => part.Quantity, StringComparer.Ordinal); var remaining = job.Parts.ToDictionary(part => part.Id, part => part.Quantity, StringComparer.Ordinal);
var placed = job.Parts.ToDictionary(part => part.Id, _ => 0, StringComparer.Ordinal); var placed = job.Parts.ToDictionary(part => part.Id, _ => 0, StringComparer.Ordinal);
var parts = job.Parts.ToDictionary(part => part.Id, StringComparer.Ordinal);
var used = job.Plates.ToDictionary(stock => stock.Id, _ => 0, StringComparer.Ordinal); var used = job.Plates.ToDictionary(stock => stock.Id, _ => 0, StringComparer.Ordinal);
var comparer = new NestJobCandidateComparer(job.Parts); var comparer = new NestJobCandidateComparer(job.Parts);
var nester = job.Parts.Count == 0 ? null : plateNesterFactory(job.Options.PlacementStrategy) ?? var nester = job.Parts.Count == 0 ? null : plateNesterFactory(job.Options.PlacementStrategy) ??
@@ -55,9 +56,11 @@ public sealed class NestJobRunner : INestingEngine
progress?.Report(new NestJobProgress(NestJobStage.EvaluatingCandidate, stock.Id, progress?.Report(new NestJobProgress(NestJobStage.EvaluatingCandidate, stock.Id,
plates.Count, plates.Count, placed.Values.Sum())); plates.Count, plates.Count, placed.Values.Sum()));
token.ThrowIfCancellationRequested(); token.ThrowIfCancellationRequested();
var candidate = nester.Place(request, token: token); var candidateProgress = progress == null ? null : new CandidateProgress(progress, stock.Id,
plates.Count, plates.Count, placed.Values.Sum());
var candidate = nester.Place(request, candidateProgress, token);
token.ThrowIfCancellationRequested(); token.ThrowIfCancellationRequested();
NestJobValidator.ValidateCandidate(candidate, remaining); NestJobValidator.ValidateCandidate(candidate, stock, remaining, parts);
var trial = new CandidateTrial(candidate, stock, index); var trial = new CandidateTrial(candidate, stock, index);
if (winner == null || comparer.Compare(trial.Candidate, trial.Stock, trial.StockIndex, if (winner == null || comparer.Compare(trial.Candidate, trial.Stock, trial.StockIndex,
winner.Candidate, winner.Stock, winner.StockIndex) > 0) winner.Candidate, winner.Stock, winner.StockIndex) > 0)
@@ -95,4 +98,15 @@ public sealed class NestJobRunner : INestingEngine
} }
private sealed record CandidateTrial(PlateCandidate Candidate, NestPlateStock Stock, int StockIndex); private sealed record CandidateTrial(PlateCandidate Candidate, NestPlateStock Stock, int StockIndex);
private sealed class CandidateProgress(IProgress<NestJobProgress> progress, string stockId, int plateIndex,
int committedPlates, int committedParts) : IProgress<NestJobProgress>
{
public void Report(NestJobProgress value)
{
ArgumentNullException.ThrowIfNull(value);
progress.Report(new NestJobProgress(NestJobStage.EvaluatingCandidate, stockId, plateIndex,
committedPlates, committedParts, value.LegacyProgress));
}
}
} }
+11 -13
View File
@@ -25,23 +25,21 @@ public static class NestJobValidator
!double.IsFinite(m.X) || !double.IsFinite(m.Y) || !double.IsFinite(m.X) || !double.IsFinite(m.Y) ||
!double.IsFinite(m.CenterX) || !double.IsFinite(m.CenterY))) !double.IsFinite(m.CenterX) || !double.IsFinite(m.CenterY)))
throw new ArgumentException($"Geometry must contain finite motions: {part.Id}.", nameof(job)); throw new ArgumentException($"Geometry must contain finite motions: {part.Id}.", nameof(job));
try
{
NestJobPlacementValidator.ValidateGeometry(part.Geometry);
}
catch (ArgumentException exception)
{
throw new ArgumentException($"Geometry must contain usable closed edges: {part.Id}.", nameof(job), exception);
}
} }
} }
internal static void ValidateCandidate(PlateCandidate candidate, IReadOnlyDictionary<string, int> remaining) internal static void ValidateCandidate(PlateCandidate candidate, NestPlateStock stock,
IReadOnlyDictionary<string, int> remaining, IReadOnlyDictionary<string, NestJobPart> parts)
{ {
if (candidate == null) throw new InvalidOperationException("The plate nester returned a null candidate."); NestJobPlacementValidator.ValidateCandidate(candidate, stock, remaining, parts);
var counts = new Dictionary<string, int>(StringComparer.Ordinal);
foreach (var placement in candidate.Placements)
{
if (placement.PartId == null || !remaining.TryGetValue(placement.PartId, out var available))
throw new InvalidOperationException("Candidate references an unknown requirement ID.");
if (!double.IsFinite(placement.X) || !double.IsFinite(placement.Y) || !double.IsFinite(placement.Rotation))
throw new InvalidOperationException("Candidate poses must be finite.");
counts.TryGetValue(placement.PartId, out var count);
if (count >= available) throw new InvalidOperationException("Candidate overproduces a requirement.");
counts[placement.PartId] = count + 1;
}
} }
private static bool Positive(double value) => double.IsFinite(value) && value > 0; private static bool Positive(double value) => double.IsFinite(value) && value > 0;