perf(irregular): remember outline overlap verdicts across a solve's fills

Auto Nest's banded variant fills the same box with the same part once per
remaining quantity, and each fill's tilted-remnant step triangulated and
tested the same spacing outlines at the same places: 98 s of a 271 s
profile of N26-2J9.

OutlineOverlapMemo keeps the verdict of SpacingOutline.Overlaps by the
exact coordinates of both perimeters, so a remembered answer is the one
the test would give and no layout can change. The block catalog owns one
memo per solve and passes it to its private fills; interactive fills pass
none and test every pair as before. It holds coordinates and verdicts
only, in two bounded generations.

N26-2J9 Auto Nest: 244 s to 179 s, the same plans and result.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
ajandClaude Fable 5.2 committed 2026-11-22 14:53:05 -05:00
1 parent 295bda728e
commit 3fccf6670f
8 files changed
+336 -5

No files matched your search

@@ -0,0 +1,110 @@
using OpenNest.Engine.Fill;
using OpenNest.Geometry;
namespace OpenNest.Engine.Tests.Fill;
/// <summary>
/// The memo may only ever answer what <see cref="SpacingOutline.Overlaps"/> answers for the
/// same two perimeters: it saves the test, never changes its verdict.
/// </summary>
public class OutlineOverlapMemoTests
{
[Fact]
public void VerdictsMatchTheDirectTest_FirstAndRemembered()
{
var memo = new OutlineOverlapMemo(10_000, 10_000);
var outlines = Outlines().ToList();
// Twice: the first pass tests and remembers, the second answers from memory, with fresh
// outline objects of the same vertices as a later fill would bring.
for (var pass = 0; pass < 2; pass++)
{
var fresh = Outlines().ToList();
for (var i = 0; i < fresh.Count; i++)
for (var j = 0; j < fresh.Count; j++)
{
var expected = outlines[i].Overlaps(outlines[j]);
var actual = memo.Overlaps(fresh[i], memo.ShapeOf(fresh[i]), fresh[j], memo.ShapeOf(fresh[j]));
Assert.True(expected == actual, $"pass {pass}, outlines {i} and {j}");
}
}
}
[Fact]
public void OutlinesOfTheSameVerticesShareAnEntry_OthersDoNot()
{
var memo = new OutlineOverlapMemo(10_000, 10_000);
var shape = memo.ShapeOf(Bar(0, 0));
Assert.Same(shape, memo.ShapeOf(Bar(0, 0)));
Assert.NotSame(shape, memo.ShapeOf(Bar(0, 1e-12)));
// The same loop started at another vertex is another vertex order.
Assert.NotSame(shape, memo.ShapeOf(Rotated(Bar(0, 0))));
}
[Fact]
public void OutlinesWithCutoutsAreTestedDirectly()
{
var memo = new OutlineOverlapMemo(10_000, 10_000);
var ring = new SpacingOutline(Loop((0, 0), (10, 0), (10, 10), (0, 10)),
new List<Polygon> { Loop((2, 2), (8, 2), (8, 8), (2, 8)) });
var inside = new SpacingOutline(Loop((4, 4), (6, 4), (6, 6), (4, 6)), new List<Polygon>());
Assert.Null(memo.ShapeOf(ring));
Assert.False(memo.Overlaps(inside, memo.ShapeOf(inside), ring, memo.ShapeOf(ring)));
Assert.False(memo.Overlaps(ring, memo.ShapeOf(ring), inside, memo.ShapeOf(inside)));
}
[Fact]
public void FullGenerationsDropOldEntriesWithoutChangingVerdicts()
{
// Room for two bars and one verdict per generation: nearly every lookup turns one over.
var memo = new OutlineOverlapMemo(8, 1);
for (var pass = 0; pass < 3; pass++)
for (var i = 0; i < 12; i++)
for (var j = 0; j < 12; j++)
{
var a = Bar(i * 0.75, 0);
var b = Bar(j * 0.75, 0.5);
var expected = Bar(i * 0.75, 0).Overlaps(Bar(j * 0.75, 0.5));
Assert.Equal(expected, memo.Overlaps(a, memo.ShapeOf(a), b, memo.ShapeOf(b)));
}
}
// Convex and concave outlines that overlap, touch, nest and miss each other.
private static IEnumerable<SpacingOutline> Outlines()
{
yield return Bar(0, 0);
yield return Bar(0.5, 0.25);
yield return Bar(2, 0); // Shares an edge with the first.
yield return Bar(5, 5);
yield return Outline((0, 0), (6, 0), (6, 1), (1, 1), (1, 6), (0, 6)); // An L.
yield return Outline((1.5, 1.5), (4, 1.5), (4, 4), (1.5, 4)); // In the L's notch.
yield return Outline((0.5, 0.5), (3, 0.5), (3, 3), (0.5, 3)); // Over the L's corner.
yield return Outline((0.2, 0.2), (0.4, 0.2), (0.4, 0.4), (0.2, 0.4)); // Inside the first bar.
}
private static SpacingOutline Bar(double x, double y) =>
Outline((x, y), (x + 2, y), (x + 2, y + 1), (x, y + 1));
private static SpacingOutline Rotated(SpacingOutline outline)
{
var vertices = outline.Perimeter.Vertices.Take(outline.Perimeter.Vertices.Count - 1).ToList();
vertices.Add(vertices[0]);
vertices.RemoveAt(0);
return Outline(vertices.Select(v => (v.X, v.Y)).ToArray());
}
private static SpacingOutline Outline(params (double X, double Y)[] points) =>
new(Loop(points), new List<Polygon>());
private static Polygon Loop(params (double X, double Y)[] points)
{
var polygon = new Polygon();
foreach (var (x, y) in points)
polygon.Vertices.Add(new Vector(x, y));
polygon.Close();
polygon.UpdateBounds();
return polygon;
}
}
+161
View File
@@ -0,0 +1,161 @@
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using OpenNest.Geometry;
namespace OpenNest.Engine.Fill
{
/// <summary>
/// Remembers whether two spacing outlines overlap, by the exact coordinates of their
/// perimeters. Auto Nest fills one box with one part once per remaining quantity, and each
/// of those fills tests the same outlines at the same places; triangulating an outline to
/// test it costs far more than comparing its vertices.
///
/// The answer for a pair is the one <see cref="SpacingOutline.Overlaps"/> gave for outlines
/// of the same vertices, bit for bit and in the same order, so a remembered verdict is the
/// verdict the test would give: the memo changes how long a fill takes, never its result.
/// Outlines with cutouts are not remembered and are tested directly.
///
/// One memo serves the fills of one solve, from any thread, and goes with it. It is bounded
/// meanwhile: outlines and verdicts are kept in two generations, the older dropped when the
/// newer fills up, so what a run of fills keeps asking for stays and the rest goes.
/// </summary>
internal sealed class OutlineOverlapMemo
{
/// <summary>Perimeter vertices a generation of outlines holds: 16 bytes each.</summary>
private const int DefaultMaxVertices = 2_000_000;
/// <summary>Verdicts a generation holds.</summary>
private const int DefaultMaxVerdicts = 500_000;
private readonly object gate = new();
private readonly int maxVertices;
private readonly int maxVerdicts;
private Dictionary<Key, Shape> shapes = new();
private Dictionary<Key, Shape> olderShapes = new();
private int vertices;
private Dictionary<(Shape, Shape), bool> verdicts = new();
private Dictionary<(Shape, Shape), bool> olderVerdicts = new();
public OutlineOverlapMemo()
: this(DefaultMaxVertices, DefaultMaxVerdicts) { }
/// <param name="maxVertices">Perimeter vertices a generation of outlines may hold.</param>
/// <param name="maxVerdicts">Verdicts a generation may hold.</param>
internal OutlineOverlapMemo(int maxVertices, int maxVerdicts)
{
this.maxVertices = maxVertices;
this.maxVerdicts = maxVerdicts;
}
/// <summary>
/// The outline's entry: one per distinct perimeter, so two outlines of the same vertices
/// share it. Null for an outline with cutouts, which the memo does not hold.
/// </summary>
public Shape ShapeOf(SpacingOutline outline)
{
if (outline.Holes.Count != 0)
return null;
var key = new Key(outline.Perimeter);
lock (gate)
{
if (shapes.TryGetValue(key, out var shape))
return shape;
if (!olderShapes.Remove(key, out shape))
shape = new Shape();
if (vertices + key.VertexCount > maxVertices && shapes.Count > 0)
{
olderShapes = shapes;
shapes = new Dictionary<Key, Shape>();
vertices = 0;
}
shapes[key] = shape;
vertices += key.VertexCount;
return shape;
}
}
/// <summary>
/// <c>a.Overlaps(b)</c>, remembered when both outlines have an entry
/// (<paramref name="shapeA"/> and <paramref name="shapeB"/>, from <see cref="ShapeOf"/>).
/// </summary>
public bool Overlaps(SpacingOutline a, Shape shapeA, SpacingOutline b, Shape shapeB)
{
if (shapeA == null || shapeB == null)
return a.Overlaps(b);
var pair = (shapeA, shapeB);
lock (gate)
{
if (verdicts.TryGetValue(pair, out var known))
return known;
if (olderVerdicts.TryGetValue(pair, out known))
{
Keep(pair, known);
return known;
}
}
var overlaps = a.Overlaps(b);
lock (gate)
Keep(pair, overlaps);
return overlaps;
}
// Caller holds the gate.
private void Keep((Shape, Shape) pair, bool overlaps)
{
if (verdicts.Count >= maxVerdicts)
{
olderVerdicts = verdicts;
verdicts = new Dictionary<(Shape, Shape), bool>();
}
verdicts[pair] = overlaps;
}
/// <summary>One distinct perimeter; verdicts are kept by the two entries of a pair.</summary>
internal sealed class Shape { }
/// <summary>A perimeter's vertices, equal only to the same coordinates bit for bit in the
/// same order.</summary>
private readonly struct Key : IEquatable<Key>
{
private readonly double[] coordinates;
private readonly int hash;
public Key(Polygon perimeter)
{
var source = perimeter.Vertices;
coordinates = new double[source.Count * 2];
var code = new HashCode();
for (var i = 0; i < source.Count; i++)
{
coordinates[2 * i] = source[i].X;
coordinates[2 * i + 1] = source[i].Y;
code.Add(BitConverter.DoubleToInt64Bits(source[i].X));
code.Add(BitConverter.DoubleToInt64Bits(source[i].Y));
}
hash = code.ToHashCode();
}
public int VertexCount => coordinates.Length / 2;
public bool Equals(Key other) =>
hash == other.hash
&& MemoryMarshal.Cast<double, long>(coordinates)
.SequenceEqual(MemoryMarshal.Cast<double, long>(other.coordinates));
public override bool Equals(object obj) => obj is Key other && Equals(other);
public override int GetHashCode() => hash;
}
}
}
+28 -1
View File
@@ -30,6 +30,10 @@ namespace OpenNest.Engine.Fill
// Placed copies are tested against every layout variant; reference keys are per copy.
private readonly Dictionary<Part, SpacingOutline> inflatedOutlines = new(ReferenceEqualityComparer.Instance);
// Each outline's entry in the overlap memo, looked up once per outline.
private readonly Dictionary<SpacingOutline, OutlineOverlapMemo.Shape> shapes =
new(ReferenceEqualityComparer.Instance);
public TiltedRemnantFiller(Box workArea, double partSpacing, IFillComparer comparer)
{
this.workArea = workArea;
@@ -37,6 +41,12 @@ namespace OpenNest.Engine.Fill
this.comparer = comparer;
}
/// <summary>
/// Overlap verdicts shared with other fills of the same part, which test the same
/// outlines at the same places; null tests every pair. See <see cref="OutlineOverlapMemo"/>.
/// </summary>
internal OutlineOverlapMemo OverlapMemo { get; init; }
/// <summary>
/// Returns <paramref name="layout"/> (possibly moved) plus tilted parts when that beats
/// the layout, or null when no tilted placement helps.
@@ -325,6 +335,23 @@ namespace OpenNest.Engine.Fill
return outline;
}
/// <summary>Whether the outlines share material, from the memo when there is one.</summary>
private bool Overlap(SpacingOutline inflated, SpacingOutline raw) =>
OverlapMemo == null
? inflated.Overlaps(raw)
: OverlapMemo.Overlaps(inflated, ShapeOf(inflated), raw, ShapeOf(raw));
private OutlineOverlapMemo.Shape ShapeOf(SpacingOutline outline)
{
if (!shapes.TryGetValue(outline, out var shape))
{
shape = OverlapMemo.ShapeOf(outline);
shapes[outline] = shape;
}
return shape;
}
private static double Low(Box box, bool alongX) => alongX ? box.Left : box.Bottom;
private static double High(Box box, bool alongX) => alongX ? box.Right : box.Top;
@@ -367,7 +394,7 @@ namespace OpenNest.Engine.Fill
inflated ??= owner.InflatedOutline(part);
outlines[i] ??= owner.Outline(Parts[i], 0);
if (inflated == null || outlines[i] == null || inflated.Overlaps(outlines[i]))
if (inflated == null || outlines[i] == null || owner.Overlap(inflated, outlines[i]))
return false;
}
@@ -91,6 +91,12 @@ internal class PlateFiller
/// </summary>
internal bool WholePairGrids { get; init; } = true;
/// <summary>
/// Outline overlap verdicts this fill shares with the caller's other fills of the same part
/// (<see cref="OutlineOverlapMemo"/>); null, the default, keeps the fill to itself.
/// </summary>
internal OutlineOverlapMemo OverlapMemo { get; init; }
public virtual List<double> BuildAngles(
NestItem item,
ClassificationResult classification,
@@ -470,6 +476,7 @@ internal class PlateFiller
),
MaxQuantity = StopAtQuantity ? System.Math.Max(0, item.Quantity) : 0,
WholePairGrids = WholePairGrids,
OverlapMemo = OverlapMemo,
};
RunPipeline(context);
@@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Linq;
using System.Threading;
using OpenNest.Engine.BestFit;
using OpenNest.Engine.Fill;
using OpenNest.Engine.Jobs.Adapters;
using OpenNest.Engine.Jobs.Placement.Fillers;
using OpenNest.Geometry;
@@ -20,8 +21,11 @@ internal static class PrivatePlateFill
/// <param name="width">Y extent of the plate and work area.</param>
/// <param name="quantity">Copies wanted; zero fills the whole area.</param>
/// <param name="wholePairGrids">See <see cref="PlateFiller.WholePairGrids"/>.</param>
/// <param name="overlapMemo">See <see cref="PlateFiller.OverlapMemo"/>: a caller filling one
/// part again and again passes the same memo to each fill.</param>
internal static List<Part> Run(Drawing drawing, RotationPolicy rotation, double spacing,
double length, double width, int quantity, CancellationToken token, bool wholePairGrids = true)
double length, double width, int quantity, CancellationToken token, bool wholePairGrids = true,
OutlineOverlapMemo overlapMemo = null)
{
var plate = new Plate(new Size(width, length)) { PartSpacing = spacing };
// The drawing is private: stabilize this cache entry before Fill's candidate pruning.
@@ -35,7 +39,12 @@ internal static class PrivatePlateFill
fits.AddRange(sorted);
// A positive quantity lets supporting strategies avoid surplus rows. Zero still
// fills the whole area (the cutout lattice caller requires an uncapped lattice).
var filler = new PlateFiller(plate) { StopAtQuantity = true, WholePairGrids = wholePairGrids };
var filler = new PlateFiller(plate)
{
StopAtQuantity = true,
WholePairGrids = wholePairGrids,
OverlapMemo = overlapMemo,
};
return filler.Fill(new NestItem
{
Drawing = drawing,
@@ -5,6 +5,7 @@ using System.Linq;
using System.Threading;
using Clipper2Lib;
using OpenNest.Engine.BestFit;
using OpenNest.Engine.Fill;
using OpenNest.Engine.Jobs;
using OpenNest.Engine.Jobs.Adapters;
using OpenNest.Engine.Jobs.Placement;
@@ -77,6 +78,12 @@ internal sealed class BlockCatalog : IDisposable
/// </summary>
public bool Frozen { get; set; }
/// <summary>
/// Overlap verdicts every Fill proposal of this catalog shares: the same part is filled in
/// the same box for one quantity after another, testing the same outlines each time.
/// </summary>
private readonly OutlineOverlapMemo overlapMemo = new();
/// <summary>Guarded by its own lock, as are its entries' members and charge.</summary>
private readonly Dictionary<PatternKey, BandEntry> bands = new();
@@ -417,7 +424,7 @@ internal sealed class BlockCatalog : IDisposable
try
{
var members = PrivatePlateFill.Run(drawing, type.Part.Rotation, fillSpacing,
rectangle.Length, rectangle.Width, quantity, token);
rectangle.Length, rectangle.Width, quantity, token, overlapMemo: overlapMemo);
token.ThrowIfCancellationRequested();
var kept = members.Take(quantity).ToArray();
var poses = Certify(type, kept, spacing, token);
@@ -28,6 +28,13 @@ namespace OpenNest.Engine.Strategies
/// (<see cref="Fill.PairFiller.WholePairGrids"/>).
/// </summary>
public bool WholePairGrids { get; init; } = true;
/// <summary>
/// Outline overlap verdicts shared by a caller's fills of the same part; null keeps
/// each fill to itself (see <see cref="Fill.OutlineOverlapMemo"/>).
/// </summary>
internal Fill.OutlineOverlapMemo OverlapMemo { get; init; }
public PartType PartType { get; set; }
/// <summary>
@@ -33,7 +33,10 @@ public class TiltedRemnantStrategy : IFillStrategy
context.WorkArea,
context.Plate.PartSpacing,
context.Policy.Comparer
);
)
{
OverlapMemo = context.OverlapMemo,
};
var result = filler.Fill(item.Drawing, layout, context.Token);
if (result != null)