perf(cutting): remember each contour's pierce-zone resolution per preparation

With a pierce diameter set, every internal contour whose configured
pierce is inside the zone is resolved by flattening the cutout, finding
its pole and eroding it, and the search emits a part's whole chain again
on every expansion, so on parts with dozens of such holes almost all of
the planning time went there: three 1,600-motion parts took 41 minutes
and timed out in production. The resolution is a pure function of the
hole, the entry, the configured lead-in, the zone and the turn, so each
preparation now keeps it by contour ordinal and reuses it, unchanged,
across its emissions and copies. The same plate plans in 148 s.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
ajandClaude Fable 5.1 committed 2026-11-02 14:31:45 -05:00
1 parent c122e64edd
commit 96db154d9e
5 files changed
+128 -9

No files matched your search

@@ -39,6 +39,8 @@ public sealed class PreparedContours
// Closed cutouts with tab spans, in program order. Like break cuts they are not choices:
// every full or prefix emission cuts their pieces after the break cuts.
private readonly List<Shape> tabbedCutouts;
// Pierce-zone resolutions by contour, shared with every copy: the contours are the same by ordinal.
private readonly PierceZoneMemo pierceZones;
// By contour ordinal; all null without pins. A pinned contour has exactly one entry and
// its own owned settings (the pin's lead-in, lead-out and tab).
private readonly ContourChoice[] pinned;
@@ -61,8 +63,9 @@ public sealed class PreparedContours
}
private PreparedContours(Shape[] shapes, List<Entity> scribes, List<Shape> breakCuts, List<Shape> tabbedCutouts,
CuttingParameters parameters, Shape displayOutline)
CuttingParameters parameters, Shape displayOutline, PierceZoneMemo pierceZones = null)
{
this.pierceZones = pierceZones ?? new PierceZoneMemo();
this.displayOutline = displayOutline;
this.shapes = shapes;
this.scribes = scribes;
@@ -75,7 +78,7 @@ public sealed class PreparedContours
private PreparedContours(PreparedContours unpinned, IReadOnlyList<CutPinResolution> pins, CancellationToken token)
: this(unpinned.shapes, unpinned.scribes, unpinned.breakCuts, unpinned.tabbedCutouts, unpinned.parameters,
unpinned.displayOutline)
unpinned.displayOutline, unpinned.pierceZones)
{
contourParameters = new CuttingParameters[shapes.Length];
var rejected = new List<CutPinResolution>();
@@ -113,7 +116,7 @@ public sealed class PreparedContours
// a pinned perimeter keeps its pin's settings: the analysis is only kept for review.
private PreparedContours(PreparedContours source, PartSupport support, Vector location, Tab tab)
: this(source.shapes, source.scribes, source.breakCuts, source.tabbedCutouts, source.parameters,
source.displayOutline)
source.displayOutline, source.pierceZones)
{
for (var contour = 0; contour < Count; contour++)
{
@@ -171,6 +174,9 @@ public sealed class PreparedContours
/// <summary>The pierce zone every lead-in pierce of these contours keeps; 0 when off.</summary>
internal double PierceZoneRadius => parameters.GetPierceZoneRadius();
/// <summary>The pierce-zone resolutions these contours' emissions share; for tests.</summary>
internal PierceZoneMemo PierceZones => pierceZones;
/// <summary>
/// The cut perimeter, emitted after every hole; <see cref="Count"/> (no contour) when the outside
/// is a display perimeter, so every contour below it is a hole.
@@ -882,7 +888,7 @@ public sealed class PreparedContours
// reads only the chosen contour and the contour count, so only that contour is cloned.
var owned = new Shape[shapes.Length];
owned[choice.ContourOrdinal] = (Shape)shapes[choice.ContourOrdinal].Clone();
return new ContourCuttingStrategy { Parameters = parameters }.EmitCandidateIsolated(
return new ContourCuttingStrategy { Parameters = parameters, PierceZones = pierceZones }.EmitCandidateIsolated(
owned, scribes.Select(e => e.Clone()).ToList(), choice, contourParameters, PerimeterOrdinal);
}
@@ -895,7 +901,7 @@ public sealed class PreparedContours
// Only a complete emission carries a display perimeter's tail: prefixes are search probes.
private Program EmitOwned(IReadOnlyList<ContourChoice> choices, bool complete) =>
new ContourCuttingStrategy { Parameters = parameters }.EmitPrepared(
new ContourCuttingStrategy { Parameters = parameters, PierceZones = pierceZones }.EmitPrepared(
shapes.Select(s => (Shape)s.Clone()).ToArray(), scribes.Select(e => e.Clone()).ToList(), choices,
contourParameters, breakCuts.Select(s => (Shape)s.Clone()).ToList(),
tabbedCutouts.Select(s => (Shape)s.Clone()).ToList(), PerimeterOrdinal,
@@ -10,6 +10,12 @@ namespace OpenNest.CNC.CuttingStrategy
{
public CuttingParameters Parameters { get; set; }
/// <summary>
/// Remembers pierce-zone resolutions by contour ordinal across the emissions of one
/// preparation (see <see cref="PierceZoneMemo"/>); null resolves every emission afresh.
/// </summary>
internal PierceZoneMemo PierceZones { get; set; }
private record ContourEntry(Shape Shape, Vector Point, Entity Entity);
public CuttingResult Apply(Program partProgram, Vector approachPoint)
@@ -315,7 +321,8 @@ namespace OpenNest.CNC.CuttingStrategy
EmitContour(result, shape, choice.Point, shape.Entities[choice.EntityOrdinal],
choice.ContourOrdinal == perimeterOrdinal ? ContourType.External : null,
exactCirclePrograms: true, scrapPierce: choice.Pierce,
stopAtCenterLine: contourParameters?[choice.ContourOrdinal] == null);
stopAtCenterLine: contourParameters?[choice.ContourOrdinal] == null,
memoContour: choice.ContourOrdinal);
}
}
finally
@@ -442,7 +449,8 @@ namespace OpenNest.CNC.CuttingStrategy
ContourType? forceType = null,
bool exactCirclePrograms = false,
Vector? scrapPierce = null,
bool stopAtCenterLine = false
bool stopAtCenterLine = false,
int? memoContour = null
)
{
var contourType = forceType ?? DetectContourType(shape);
@@ -478,7 +486,7 @@ namespace OpenNest.CNC.CuttingStrategy
leadIn = StopAtCenterLine(shape, point, leadIn, normal, winding);
leadIn = ClampLeadInForCircle(leadIn, circle, point, normal,
Parameters.GetEffectivePierceClearance());
leadIn = ResolvePierceZone(shape, point, leadIn, normal, Parameters.GetPierceZoneRadius(), winding);
leadIn = PierceZone(memoContour, shape, point, leadIn, normal, winding);
}
// Build hole sub-program relative to (0,0)
@@ -531,7 +539,7 @@ namespace OpenNest.CNC.CuttingStrategy
{
if (stopAtCenterLine)
leadIn = StopAtCenterLine(shape, point, leadIn, leadInNormal, turn);
leadIn = ResolvePierceZone(shape, point, leadIn, leadInNormal, Parameters.GetPierceZoneRadius(), turn);
leadIn = PierceZone(memoContour, shape, point, leadIn, leadInNormal, turn);
}
}
program.Codes.AddRange(leadIn.Generate(point, leadInNormal, turn));
@@ -1079,6 +1087,15 @@ namespace OpenNest.CNC.CuttingStrategy
/// manual placement preview. <paramref name="turn"/> is the hole's
/// <see cref="LeadTurn"/>, which places a curved lead's pierce.
/// </summary>
// The memoized resolution for a contour the preparation emits by ordinal.
private LeadIn PierceZone(int? contour, Shape hole, Vector point, LeadIn leadIn, double normal, RotationType turn)
{
var radius = Parameters.GetPierceZoneRadius();
return PierceZones != null && contour is { } ordinal
? PierceZones.Resolve(ordinal, hole, point, leadIn, normal, radius, turn)
: ResolvePierceZone(hole, point, leadIn, normal, radius, turn);
}
public static LeadIn ResolvePierceZone(Shape hole, Vector point, LeadIn leadIn, double normal,
double pierceRadius, RotationType turn)
{
@@ -0,0 +1,65 @@
using System;
using System.Collections.Generic;
using OpenNest.Geometry;
namespace OpenNest.CNC.CuttingStrategy
{
/// <summary>
/// Remembers <see cref="ContourCuttingStrategy.ResolvePierceZone"/> for one preparation's
/// contours. The resolution reads only the cutout's own geometry, the entry, the configured
/// lead-in and the zone, so for a given contour it is a pure function of those, yet the
/// search emits every contour of a part's chain again on every expansion, and on a cutout
/// whose configured pierce is inside the zone each resolution flattens the cutout, finds its
/// pole and erodes it. One memo serves every emission of one <c>PreparedContours</c> and
/// its copies, which share the contours by ordinal. A lead-in a memo returns is shared and
/// must not be mutated.
/// </summary>
internal sealed class PierceZoneMemo
{
private readonly Dictionary<Key, LeadIn> resolved = new();
private readonly object gate = new();
/// <summary>How many resolutions the memo answered without computing; for tests.</summary>
internal int Hits { get; private set; }
internal LeadIn Resolve(int contour, Shape hole, Vector point, LeadIn leadIn, double normal,
double pierceRadius, RotationType turn)
{
if (KeyOf(leadIn) is not { } lead)
return ContourCuttingStrategy.ResolvePierceZone(hole, point, leadIn, normal, pierceRadius, turn);
var key = new Key(contour, point.X, point.Y, normal, pierceRadius, turn, lead);
lock (gate)
{
if (resolved.TryGetValue(key, out var known))
{
Hits++;
return known;
}
}
var result = ContourCuttingStrategy.ResolvePierceZone(hole, point, leadIn, normal, pierceRadius, turn);
lock (gate)
{
resolved[key] = result;
}
return result;
}
// The configured lead-in by value: an equal lead-in resolves the same way whichever
// instance carries it. A lead-in type this does not know is resolved every time.
private static LeadKey? KeyOf(LeadIn leadIn) => leadIn switch
{
NoLeadIn => new(0, 0, 0, 0, 0),
LineLeadIn line => new(1, line.Length, line.ApproachAngle, 0, 0),
ArcLeadIn arc => new(2, arc.Radius, arc.SweepAngle, 0, 0),
LineArcLeadIn lineArc => new(3, lineArc.LineLength, lineArc.ApproachAngle, lineArc.ArcRadius, 0),
CleanHoleLeadIn cleanHole => new(4, cleanHole.LineLength, cleanHole.ArcRadius, cleanHole.Kerf, 0),
LineLineLeadIn lineLine => new(5, lineLine.Length1, lineLine.ApproachAngle1, lineLine.Length2, lineLine.ApproachAngle2),
_ => null,
};
private readonly record struct LeadKey(int Kind, double A, double B, double C, double D);
private readonly record struct Key(int Contour, double X, double Y, double Normal, double PierceRadius,
RotationType Turn, LeadKey Lead);
}
}
@@ -232,6 +232,28 @@ public class PierceZoneTests
Assert.Matches(@"keeps 0\.11\d* of the 0\.5 needed", finding.Message);
}
[Fact]
public void Emission_RemembersAHoleFallbackAcrossEmissionsOfOnePreparation()
{
// A 0.5 pierce diameter in a 6 x 0.6 slot: the configured pierce is inside the zone, so
// the hole fallback flattens the slot, finds its pole and erodes it. The search emits the
// whole chain again on every expansion; the memo answers the repeats, and identically.
var program = Rectangle(0, 0, 10, 10);
program.Codes.AddRange(LeadPathValidationTests.Rectangle(2, 4.7, 8, 5.3).Codes);
var prepared = PreparedContours.Capture(program, Parameters(0.5));
var hole = Enumerable.Range(0, prepared.Count).First(c => c != prepared.PerimeterOrdinal);
var chain = new[] { prepared.ClosestEntry(hole, new Vector(3, 4.7)), prepared.ClosestEntry(prepared.PerimeterOrdinal, new Vector(0, 5)) };
var first = prepared.Emit(chain).ToString();
var hits = prepared.PierceZones.Hits;
var second = prepared.Emit(chain).ToString();
Assert.Equal(first, second);
Assert.True(prepared.PierceZones.Hits > hits, "The second emission did not reuse the first's pierce-zone resolution.");
var pierce = Assert.Single(Pierces(Read(prepared.Emit(chain))), p => p.X > 2 && p.X < 8);
Assert.InRange(pierce.Y, 4.95 - 1e-9, 5.05 + 1e-9); // The slot's center line keeps the 0.25 zone.
}
[Fact]
public void ScrapPierceEntry_LeadsStraightFromThePierceToTheNearestPoint()
{
+9
View File
@@ -40,6 +40,15 @@ emitter cuts, and for the manual lead-in preview:
The fallback reads only the hole's own geometry, so it does not know about a part nested
inside the hole. Such a part is still checked as other material.
Plan Cutting emits a part's whole chain again on every search expansion, and steps 3 and 4
flatten the hole, find its pole and erode it each time, so a part with dozens of holes too
narrow for their configured pierce spent most of its planning time there (three 1,600-motion
parts took 41 minutes). The resolution is a pure function of the hole, the entry, the configured
lead-in, the zone and the turn, so `PreparedContours` keeps a `PierceZoneMemo` of it by contour
ordinal, shared with its pinned and support-tabbed copies; the first emission of each entry
computes it and every later emission of the same entry reuses it unchanged. The manual preview
and `ContourCuttingStrategy.Apply` resolve every call afresh, as before.
## Perimeter fallback
A perimeter's fallback needs the parts around it, which the emitter never reads (it emits each