perf(fill): cut a cold Lattice fill from ~300 s to ~160 s with identical layouts

The first fill of a new drawing was blamed on the best-fit pair search, but on the
reported nest that search takes ~3.4 s. The time goes to FillLinear.FillGrid, run
thousands of times by the Pairs, Row/Column and Linear strategies: pattern copy-distance
slides and the grid overlap check. Every change keeps the output bit for bit (part
poses compared on the benchmark nest; best-fit results unchanged).

- ConvexDecomposition.Triangulate: unlink clipped vertices from a circular list instead
  of List.RemoveAt, and remember why a vertex failed the ear test (same neighbors, same
  blocking vertex still present) instead of retesting it after every ear. Compared
  bitwise against a frozen pre-change copy, including the blocker-clipped case.
- Collision: skip triangles whose box misses the other triangulation's union box (exact:
  min/max and monotone subtraction), reuse each triangle's open vertices, and let the
  overlap-only path stop at its first region when there are no holes. Check still
  returns every region.
- SpatialQuery.ExtractEntityVertices presizes its set; FillLinear extracts each entity
  list's vertices once per copy-distance search rather than once per pair.
- StripeFiller converges its stripe angles and tiles its grids in parallel. Dedup claims,
  cached remnant fills, ranking and progress stay in candidate order, and grids are tiled
  only for configurations a claim can still win (GridDedup.Contains), so results and
  reports do not depend on the thread count.
- LinearFillStrategy fills its angles in parallel through
  FillHelpers.BestOverAnglesInParallel; angle results, ranking and progress stay in order.

Benchmark (one drawing, 60x120, 0.25 spacing, cleared plate, interleaved runs):
FillItem Lattice 291/317 s -> 164/153 s, 132 parts both; PairFiller alone 48 s -> 38-42 s.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
ajandClaude Opus 5.5 committed 2026-11-07 19:34:31 -05:00
1 parent 331234d6f3
commit bcbcf1e611
10 files changed
+816 -109

No files matched your search

+18 -3
View File
@@ -148,6 +148,9 @@ namespace OpenNest.Engine.Fill
var movingBoxes = new Box[parts.Count];
var stationaryEntities = new List<Entity>[parts.Count];
var movingEntities = new List<Entity>[parts.Count];
// Each list slides against several others; extract its vertices once.
var stationaryVertices = new Vector[parts.Count][];
var movingVertices = new Vector[parts.Count][];
for (var i = 0; i < parts.Count; i++)
{
@@ -174,13 +177,25 @@ namespace OpenNest.Engine.Fill
if (!SpatialQuery.PerpendicularOverlap(movingBox, stationaryBox, dirVec))
continue;
stationaryEntities[i] ??= cache.AtLocation(parts[i].Program, parts[i].Location);
movingEntities[j] ??= cache.AtLocation(parts[j].Program, parts[j].Location + offset);
if (stationaryEntities[i] == null)
{
stationaryEntities[i] = cache.AtLocation(parts[i].Program, parts[i].Location);
stationaryVertices[i] = SpatialQuery.ExtractEntityVertices(stationaryEntities[i]);
}
if (movingEntities[j] == null)
{
movingEntities[j] = cache.AtLocation(parts[j].Program, parts[j].Location + offset);
movingVertices[j] = SpatialQuery.ExtractEntityVertices(movingEntities[j]);
}
var slideDistance = SpatialQuery.DirectionalDistance(
movingEntities[j],
movingVertices[j],
stationaryEntities[i],
pushDir
stationaryVertices[i],
dirVec,
new SlideContactClassifier(movingEntities[j], stationaryEntities[i])
);
if (slideDistance >= double.MaxValue || slideDistance < 0)
+7
View File
@@ -24,6 +24,13 @@ public class GridDedup
return _seen.TryAdd(key, 0);
}
/// <summary>
/// True if <see cref="TryAdd"/> already accepted this configuration. Claims are never
/// removed, so a configuration seen now stays rejected.
/// </summary>
public bool Contains(Box patternBox, Box workArea, NestDirection dir) =>
_seen.ContainsKey(new GridKey(patternBox, workArea, dir));
public int Count => _seen.Count;
/// <summary>
+149 -55
View File
@@ -1,7 +1,10 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
using OpenNest.Engine;
using OpenNest.Engine.BestFit;
using OpenNest.Engine.Strategies;
@@ -41,58 +44,36 @@ public class StripeFiller
return new List<Part>();
var workArea = _context.WorkArea;
var spacing = _context.Plate.PartSpacing;
var drawing = _context.Item.Drawing;
var strategyName = _primaryAxis == NestDirection.Horizontal ? "Row" : "Column";
var layouts = ComputeLayouts(bestFits, drawing);
List<Part> bestParts = null;
for (var i = 0; i < bestFits.Count; i++)
{
_context.Token.ThrowIfCancellationRequested();
var candidate = bestFits[i];
var pairParts = candidate.BuildParts(drawing);
foreach (var axis in new[] { NestDirection.Horizontal, NestDirection.Vertical })
for (var a = 0; a < Axes.Length; a++)
{
var perpAxis =
axis == NestDirection.Horizontal
? NestDirection.Vertical
: NestDirection.Horizontal;
var sheetSpan = GetDimension(workArea, axis);
var axis = Axes[a];
var dirLabel = axis == NestDirection.Horizontal ? "Row" : "Col";
var expandResult = ConvergeStripeAngle(
pairParts,
sheetSpan,
spacing,
axis,
_context.Token,
_context.MaxQuantity
);
var shrinkResult = ConvergeStripeAngleShrink(
pairParts,
sheetSpan,
spacing,
axis,
_context.Token,
_context.MaxQuantity
);
foreach (var (angle, waste, count) in new[] { expandResult, shrinkResult })
for (var v = 0; v < VariantsPerAxis; v++)
{
if (count <= 0)
var layout = layouts[LayoutIndex(i, a, v)];
if (layout.Count <= 0)
continue;
var result = BuildGrid(pairParts, angle, axis, perpAxis);
var result = ClaimGrid(layout, axis);
if (result == null || result.Count == 0)
continue;
Debug.WriteLine(
$"[StripeFiller] {strategyName} candidate {i} {dirLabel}: "
+ $"angle={Angle.ToDegrees(angle):F1}°, N={count}, waste={waste:F2}, "
+ $"angle={Angle.ToDegrees(layout.Angle):F1}°, N={layout.Count}, waste={layout.Waste:F2}, "
+ $"grid={result.Count} parts"
);
@@ -112,23 +93,149 @@ public class StripeFiller
return bestParts ?? new List<Part>();
}
private List<Part> BuildGrid(
List<Part> pairParts,
double angle,
NestDirection primaryAxis,
NestDirection perpAxis
)
private static readonly NestDirection[] Axes = { NestDirection.Horizontal, NestDirection.Vertical };
/// <summary>Expanding (<see cref="ConvergeStripeAngle"/>) then shrinking convergence.</summary>
private const int VariantsPerAxis = 2;
private static int LayoutIndex(int candidate, int axis, int variant) =>
(candidate * Axes.Length + axis) * VariantsPerAxis + variant;
/// <summary>
/// A converged stripe angle and, when it holds a pattern, the rotated pattern and the grid
/// it tiles before the order-dependent steps (<see cref="GridDedup"/> claim, cached remnant
/// fill).
/// </summary>
private sealed class StripeLayout
{
public double Angle;
public double Waste;
public int Count;
public Pattern Pattern;
public bool GridReady;
public List<Part> Grid;
}
/// <summary>
/// Converges every candidate's stripe angle per axis and variant, then tiles the grids that
/// <see cref="Fill"/> will claim, each step in parallel. Every layout is a pure function of
/// its candidate, axis and variant (fresh part clones, per-call <see cref="FillLinear"/>
/// state), so the results do not depend on the thread count. A grid is tiled only when its
/// configuration is not yet claimed and no earlier layout shares it: claims are only ever
/// added, so exactly those are the grids the sequential loop would have tiled.
/// <see cref="Fill"/> then claims, fills remnants and ranks in the original order.
/// </summary>
private StripeLayout[] ComputeLayouts(List<BestFitResult> bestFits, Drawing drawing)
{
var layouts = new StripeLayout[bestFits.Count * Axes.Length * VariantsPerAxis];
RunParallel(layouts.Length, index =>
{
var variant = index % VariantsPerAxis;
var axis = Axes[index / VariantsPerAxis % Axes.Length];
var candidate = bestFits[index / VariantsPerAxis / Axes.Length];
layouts[index] = Converge(candidate.BuildParts(drawing), axis, variant);
});
var batch = new GridDedup();
var toTile = new List<int>();
for (var index = 0; index < layouts.Length; index++)
{
var layout = layouts[index];
if (layout.Count <= 0)
continue;
var axis = Axes[index / VariantsPerAxis % Axes.Length];
var box = layout.Pattern.BoundingBox;
if (!_dedup.Contains(box, _context.WorkArea, axis) && batch.TryAdd(box, _context.WorkArea, axis))
toTile.Add(index);
}
RunParallel(toTile.Count, k =>
{
var index = toTile[k];
var layout = layouts[index];
layout.Grid = BuildGrid(layout.Pattern, Axes[index / VariantsPerAxis % Axes.Length]);
layout.GridReady = true;
});
return layouts;
}
private void RunParallel(int count, Action<int> body)
{
try
{
Parallel.For(0, count, new ParallelOptions { CancellationToken = _context.Token }, body);
}
catch (AggregateException ex)
{
// Surface the failure itself, cancellation included, as the sequential loop did.
ExceptionDispatchInfo.Capture(ex.InnerExceptions[0]).Throw();
throw;
}
}
private StripeLayout Converge(List<Part> pairParts, NestDirection axis, int variant)
{
var spacing = _context.Plate.PartSpacing;
var sheetSpan = GetDimension(_context.WorkArea, axis);
var (angle, waste, count) = variant == 0
? ConvergeStripeAngle(pairParts, sheetSpan, spacing, axis, _context.Token, _context.MaxQuantity)
: ConvergeStripeAngleShrink(pairParts, sheetSpan, spacing, axis, _context.Token, _context.MaxQuantity);
var layout = new StripeLayout { Angle = angle, Waste = waste, Count = count };
if (count > 0)
layout.Pattern = FillHelpers.BuildRotatedPattern(pairParts, angle);
return layout;
}
/// <summary>
/// The order-dependent half of a stripe grid: claims its configuration and adds the cached
/// remnant fill. Null when the configuration was already evaluated or no grid fits.
/// </summary>
private List<Part> ClaimGrid(StripeLayout layout, NestDirection primaryAxis)
{
if (!_dedup.TryAdd(layout.Pattern.BoundingBox, _context.WorkArea, primaryAxis))
return null;
// ComputeLayouts tiled every grid a claim can succeed for; tile here should it not have.
var gridParts = layout.GridReady ? layout.Grid : BuildGrid(layout.Pattern, primaryAxis);
if (gridParts == null)
return null;
var allParts = new List<Part>(gridParts);
// A capped fill that already holds the quantity needs no remnant parts.
if (_context.MaxQuantity > 0 && gridParts.Count >= _context.MaxQuantity)
return allParts;
var remnantParts = FillRemnant(gridParts, primaryAxis);
if (remnantParts != null)
{
Debug.WriteLine($"[StripeFiller] Remnant: {remnantParts.Count} parts");
allParts.AddRange(remnantParts);
}
return allParts;
}
/// <summary>
/// Tiles the rotated pattern into a stripe and the stripe into a grid. Pure: reads only the
/// pattern and the context's fixed inputs.
/// </summary>
private List<Part> BuildGrid(Pattern rotatedPattern, NestDirection primaryAxis)
{
var perpAxis =
primaryAxis == NestDirection.Horizontal ? NestDirection.Vertical : NestDirection.Horizontal;
var workArea = _context.WorkArea;
var spacing = _context.Plate.PartSpacing;
var rotatedPattern = FillHelpers.BuildRotatedPattern(pairParts, angle);
var perpDim = GetDimension(rotatedPattern.BoundingBox, perpAxis);
var stripeBox = MakeStripeBox(workArea, perpDim, primaryAxis);
if (!_dedup.TryAdd(rotatedPattern.BoundingBox, workArea, primaryAxis))
return null;
var stripeEngine = new FillLinear(stripeBox, spacing)
{
Label = "Stripe",
@@ -187,20 +294,7 @@ public class StripeFiller
return null;
}
var allParts = new List<Part>(gridParts);
// A capped fill that already holds the quantity needs no remnant parts.
if (_context.MaxQuantity > 0 && gridParts.Count >= _context.MaxQuantity)
return allParts;
var remnantParts = FillRemnant(gridParts, primaryAxis);
if (remnantParts != null)
{
Debug.WriteLine($"[StripeFiller] Remnant: {remnantParts.Count} parts");
allParts.AddRange(remnantParts);
}
return allParts;
return gridParts;
}
private List<BestFitResult> GetPairCandidates()
+49
View File
@@ -169,6 +169,55 @@ namespace OpenNest.Engine.Strategies
return best ?? new List<Part>();
}
/// <summary>
/// <see cref="BestOverAngles"/> for a pure per-angle fill: every angle is filled in
/// parallel, then <paramref name="recordResult"/>, the ranking and the progress reports run
/// once per angle in angle order, so the result does not depend on the thread count.
/// <paramref name="fillAtAngle"/> must not touch shared state; side effects of an angle's
/// result belong in <paramref name="recordResult"/>.
/// </summary>
public static List<Part> BestOverAnglesInParallel(
FillContext context,
IReadOnlyList<double> angles,
Func<double, List<Part>> fillAtAngle,
Action<double, List<Part>> recordResult,
string phaseLabel
)
{
var results = new List<Part>[angles.Count];
try
{
Parallel.For(
0,
angles.Count,
new ParallelOptions { CancellationToken = context.Token },
i => results[i] = fillAtAngle(angles[i])
);
}
catch (AggregateException ex)
{
// Surface the failure itself, cancellation included, as the sequential sweep did.
System.Runtime.ExceptionServices.ExceptionDispatchInfo
.Capture(ex.InnerExceptions[0])
.Throw();
throw;
}
var next = 0;
return BestOverAngles(
context,
angles,
angle =>
{
var result = results[next++];
recordResult(angle, result);
return result;
},
phaseLabel
);
}
/// <summary>
/// Checks if any pair of parts geometrically overlap. Uses bounding box
/// pre-filtering for performance, then falls back to shape intersection.
@@ -20,7 +20,8 @@ namespace OpenNest.Engine.Strategies
var comparer = context.Policy?.Comparer ?? new DefaultFillComparer();
var preferred = context.Policy?.PreferredDirection;
return FillHelpers.BestOverAngles(
// Each angle's fill is independent; its angle result is recorded in angle order.
return FillHelpers.BestOverAnglesInParallel(
context,
angles,
angle =>
@@ -29,13 +30,15 @@ namespace OpenNest.Engine.Strategies
{
Label = "Linear",
};
var result = FillHelpers.FillWithDirectionPreference(
return FillHelpers.FillWithDirectionPreference(
dir => engine.Fill(context.Item.Drawing, angle, dir),
preferred,
comparer,
workArea
);
},
(angle, result) =>
{
if (result != null && result.Count > 0)
{
context.AngleResults.Add(
@@ -47,8 +50,6 @@ namespace OpenNest.Engine.Strategies
}
);
}
return result;
},
"Linear"
);