feat(engine): lower, clamp-aware bands in Irregular's banded fill

Bands were always the full work-area height and placed flush to the
bottom or top edge. On N26-2HH (20 + 20 formed legs, 60 x 120, bottom
clamp rail) the larger leg's full-height band had less slack than the
rail's depth, so three copies dropped to the gap fill and Auto Nest
ended at 104.71 against a hand layout at 104.0.

Each type now also offers up to three lower bands, each asked for just
short of the last band's height and searched over three lengths, which
leave a strip along the sheet for the remaining parts. A band that would
lose members to clamps also tries the top edge and just past the clamps
lining either edge (ClampObstacles.ClearOfEdges, moved out of
EdgeFirstFill). N26-2HH now ends at 103.87; the README sample, help
tutorial and N26-2GT layouts are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
ajandClaude Opus 5.5 committed 2026-11-19 21:11:42 -05:00
1 parent 6cf6a78306
commit 0a413dd242
5 files changed
+163 -66

No files matched your search

@@ -0,0 +1,39 @@
using OpenNest.Clamps;
using OpenNest.Engine.Jobs;
using OpenNest.Engine.Jobs.Adapters;
using OpenNest.Engine.NestingEngines.Irregular;
using OpenNest.Geometry;
using static OpenNest.Engine.Tests.NestingEngines.JobBuilder;
namespace OpenNest.Engine.Tests.NestingEngines;
/// <summary>
/// Banded fill on a sheet with a clamp rail along its bottom edge. The larger part's full-height
/// band fills the work area to within less than the rail's depth, so it cannot clear the clamps
/// and the copies on them went to the gap fill, ending the layout at 104.36. A band a row lower
/// seats whole clear of the rail and leaves a strip for the last copies; the layout ends at 103.95.
/// </summary>
public class IrregularBandedClampTests
{
private static ClampZone[] Rail() => Enumerable.Range(0, 6)
.Select(i => new ClampZone($"clamp-{i + 1}", new Box(19.25 + 20 * i, 0, 1.5, 0.625))).ToArray();
[Fact]
public void LowerBandClearsABottomClampRail()
{
var stock = Stock("sheet", 60, 120, spacing: 0.25, edge: new Spacing(0.25, 0.25, 0.25, 0.25),
clampZones: Rail());
var job = Job([
Part("large", Shapes.Rectangle(22.5, 7.2), 20, RotationPolicy.Automatic),
Part("small", Shapes.Rectangle(18, 6), 20, RotationPolicy.Automatic),
], [stock]);
var result = new IrregularNestingEngine().Solve(job);
LayoutAssert.Valid(job, result);
var plate = Assert.Single(NestResultMaterializer.Materialize(job, result).Nest.Plates);
Assert.Equal(40, plate.Parts.Count);
var right = plate.Parts.Max(p => p.BoundingBox.Right);
Assert.True(right < 104.2, $"Layout ends at {right:F3}");
}
}
@@ -14,8 +14,9 @@ namespace OpenNest.Engine.NestingEngines.Irregular;
///
/// <see cref="Fill"/> lays each like-part group out as a band: the group's Lattice pattern (the one
/// interactive Fill gives that part alone, so a round part stacks, a hexagon tiles and an L
/// interlocks with its pair) in the narrowest strip that holds all its copies. Bands stand side
/// by side, then the copies held back from them and the types too few to band fill the gaps.
/// interlocks with its pair) in the narrowest strip that holds all its copies, or a few rows lower
/// to leave room along the sheet. Bands stand side by side, then the copies held back from them
/// and the types too few to band fill the gaps.
///
/// <see cref="FillStrips"/> builds each strip as densely as it can from any parts: the strip holds
/// the largest remaining part, as its band or as a column of it, and every other part fills the
@@ -38,7 +39,19 @@ internal sealed class BandedFill(
/// <summary>Fewest copies a band may hold back to be narrower; a third of them when more.</summary>
private const int MaxHeldBack = 4;
private sealed record Band(int Type, int Copies, double Length, IReadOnlyList<Placed> Members);
/// <summary>A type's pattern. <c>Height</c> is the height of the box it was asked for, so a
/// band cut short at the sheet's end is asked for in the same box.</summary>
private sealed record Band(int Type, int Copies, double Length, double Height, IReadOnlyList<Placed> Members);
/// <summary>The work area's height with a side carrying clamps moved in past their keep-outs:
/// a band seated there clears the clamps whole.</summary>
private readonly (double Bottom, double Top) clear = ClearHeight(stock, clamps);
private static (double Bottom, double Top) ClearHeight(NestPlateStock stock, ClampObstacles? clamps)
{
var (area, onEdges) = ClampObstacles.ClearOfEdges(stock.WorkArea, clamps);
return onEdges ? (area.Bottom, area.Top) : (stock.WorkArea.Bottom, stock.WorkArea.Top);
}
/// <summary>The fill, or null when nothing bands on this sheet.</summary>
public SheetFill? Fill(IReadOnlyList<int> remaining, CancellationToken token)
@@ -172,7 +185,7 @@ internal sealed class BandedFill(
if (state.Rest[t] >= GroupedFill.MinGroup)
{
if (!bandCache.TryGetValue((t, state.Rest[t]), out var bands))
bandCache[(t, state.Rest[t])] = bands = Bands(t, state.Rest[t], region, token);
bandCache[(t, state.Rest[t])] = bands = Bands(t, state.Rest[t], region, region.Width, MaxSteps, Probes, token);
foreach (var band in bands)
{
if (band.Length > region.Right - start + 1e-9)
@@ -243,8 +256,9 @@ internal sealed class BandedFill(
private sealed record StripState(List<Placed> Placed, int[] Rest, double Area, double Front);
/// <summary>A band's members starting at <paramref name="front"/>, flush to the bottom, or to
/// the top when that keeps more of them off the clamps; members on a clamp are left out.</summary>
/// <summary>A band's members starting at <paramref name="front"/>, flush to the bottom, or,
/// when that leaves members on the clamps, flush to the top or just past the clamps along
/// either side, whichever keeps the most off them; members on a clamp are left out.</summary>
private List<Placed> Seat(Band band, double front, Box region)
{
var minX = band.Members.Min(p => p.Left);
@@ -253,11 +267,19 @@ internal sealed class BandedFill(
List<Placed> Shifted(double dy) => band.Members
.Select(m => new Placed(m.Orientation, m.X + front - minX, m.Y + dy)).Where(p => !OnClamp(p)).ToList();
var members = Shifted(region.Bottom - minY);
if (members.Count < band.Members.Count && region.Top - maxY > region.Bottom - minY + 1e-9)
var tried = new List<double> { region.Bottom - minY };
foreach (var dy in new[] { region.Top - maxY, clear.Bottom - minY, clear.Top - maxY })
{
var top = Shifted(region.Top - maxY);
if (top.Count > members.Count)
members = top;
if (members.Count == band.Members.Count)
break;
// Inside the work area, and a pose not tried yet.
if (dy < region.Bottom - minY - 1e-9 || dy > region.Top - maxY + 1e-9
|| tried.Any(d => System.Math.Abs(d - dy) < 1e-9))
continue;
tried.Add(dy);
var seated = Shifted(dy);
if (seated.Count > members.Count)
members = seated;
}
return members;
}
@@ -281,24 +303,12 @@ internal sealed class BandedFill(
if (band.Length > room + 1e-9)
{
// The sheet ends inside this band: as many copies as the room left holds.
var partial = Pattern(t, band.Copies, room, region.Width, token);
var partial = Pattern(t, band.Copies, room, band.Height, token);
if (partial == null)
continue;
band = partial;
}
var minX = band.Members.Min(p => p.Left);
var minY = band.Members.Min(p => p.Bottom);
var maxY = band.Members.Max(p => p.Top);
// Flush to the bottom, or to the top when that keeps more copies off the clamps.
List<Placed> Shifted(double dy) => band.Members
.Select(m => new Placed(m.Orientation, m.X + front - minX, m.Y + dy)).Where(p => !OnClamp(p)).ToList();
var members = Shifted(region.Bottom - minY);
if (members.Count < band.Members.Count && region.Top - maxY > region.Bottom - minY + 1e-9)
{
var top = Shifted(region.Top - maxY);
if (top.Count > members.Count)
members = top;
}
var members = Seat(band, front, region);
var maxX = front;
foreach (var placed in members)
{
@@ -325,7 +335,8 @@ internal sealed class BandedFill(
/// columns, so each next band is asked for just short of the last one's length, and a few
/// halvings toward the area bound catch patterns the steps skip.
/// </summary>
private List<Band> Bands(int t, int copies, Box region, CancellationToken token, Drawing? prefetch = null)
private List<Band> Bands(int t, int copies, Box region, double height, int steps, int probes,
CancellationToken token, Drawing? prefetch = null)
{
var type = types[t];
var fewest = copies - HeldBack(copies);
@@ -339,9 +350,9 @@ internal sealed class BandedFill(
}
}
var length = region.Length;
for (var step = 0; step < MaxSteps; step++)
for (var step = 0; step < steps; step++)
{
var band = Pattern(t, copies, length, region.Width, token, prefetch);
var band = Pattern(t, copies, length, height, token, prefetch);
if (band == null || band.Copies < fewest)
break;
Keep(band);
@@ -351,12 +362,12 @@ internal sealed class BandedFill(
if (full == null)
return new List<Band>();
var lo = System.Math.Max(type.Orientations.Min(o => System.Math.Min(o.Width, o.Height)),
copies * type.Area / region.Width);
copies * type.Area / height);
var hi = full.Length;
for (var probe = 0; probe < Probes && hi - lo > StepShort; probe++)
for (var probe = 0; probe < probes && hi - lo > StepShort; probe++)
{
var mid = (lo + hi) / 2;
var band = Pattern(t, copies, mid, region.Width, token, prefetch);
var band = Pattern(t, copies, mid, height, token, prefetch);
if (band != null)
Keep(band);
if (band != null && band.Copies >= copies)
@@ -373,15 +384,45 @@ internal sealed class BandedFill(
/// <see cref="Bands"/> for each type at once. Each type's search depends only on its own
/// patterns (fixed step counts, no shared budget), so the result is the same in any order.
/// </summary>
private List<Band>[] BandsInParallel(int[] typeIndexes, IReadOnlyList<int> remaining, Box region, CancellationToken token)
private List<Band>[] BandsInParallel(int[] typeIndexes, IReadOnlyList<int> remaining, Box region,
CancellationToken token)
{
var result = new List<Band>[typeIndexes.Length];
System.Threading.Tasks.Parallel.For(0, typeIndexes.Length,
new System.Threading.Tasks.ParallelOptions { CancellationToken = token },
i => result[i] = Bands(typeIndexes[i], remaining[typeIndexes[i]], region, token));
i => result[i] = BandOptions(typeIndexes[i], remaining[typeIndexes[i]], region, token));
return result;
}
/// <summary>
/// The type's bands of full work-area height (<see cref="Bands"/>), then up to
/// <see cref="LowerHeights"/> lower ones, each asked for just short of the last pattern's
/// height, so each is a row or so lower: a lower band can sit past a clamp rail whole, and
/// leaves a strip along the sheet that other parts fill. Lower bands search fewer lengths.
/// </summary>
private List<Band> BandOptions(int t, int copies, Box region, CancellationToken token, Drawing? prefetch = null)
{
var options = Bands(t, copies, region, region.Width, MaxSteps, Probes, token, prefetch);
var shortest = types[t].Orientations.Min(o => System.Math.Min(o.Width, o.Height));
var last = options.FirstOrDefault();
for (var i = 0; i < LowerHeights && last != null; i++)
{
var height = last.Members.Max(p => p.Top) - last.Members.Min(p => p.Bottom) - StepShort;
if (height < shortest)
break;
var lower = Bands(t, copies, region, height, LowerSteps, 0, token, prefetch);
options.AddRange(lower);
last = lower.FirstOrDefault();
}
return options;
}
/// <summary>Lower band heights searched per type.</summary>
private const int LowerHeights = 3;
/// <summary>Lengths a lower band's search steps through; it makes no probes.</summary>
private const int LowerSteps = 3;
/// <summary>
/// Builds the patterns of each (type, copies) band search ahead of need, the searches in
/// parallel, so the ordinary searches that follow find them cached. Each search fills its
@@ -399,7 +440,7 @@ internal sealed class BandedFill(
var drawing = BlockCatalog.PrefetchDrawing(types[searches[i].Type]);
try
{
Bands(searches[i].Type, searches[i].Copies, region, token, drawing);
Bands(searches[i].Type, searches[i].Copies, region, region.Width, MaxSteps, Probes, token, drawing);
}
finally
{
@@ -427,7 +468,7 @@ internal sealed class BandedFill(
// Bounds carry the arc flattening padding; a pattern they push past the box is no band.
if (members.Count == 0 || members.Max(p => p.Top) - members.Min(p => p.Bottom) > width + 1e-9)
return null;
return new Band(t, members.Count, members.Max(p => p.Right) - members.Min(p => p.Left), members);
return new Band(t, members.Count, members.Max(p => p.Right) - members.Min(p => p.Left), width, members);
}
/// <summary>
@@ -1,6 +1,7 @@
#nullable enable
using Clipper2Lib;
using OpenNest.Engine.Jobs;
using OpenNest.Geometry;
namespace OpenNest.Engine.NestingEngines.Irregular;
@@ -61,4 +62,37 @@ internal sealed class ClampObstacles
// No additional physical spacing. NoFitCache retains the established arc/grid safety
// margin and covered-hole certification for the moving orientation and rectangle.
public Nfp Get(int index, Orientation moving) => nfps.Get(rectangles[index], moving);
/// <summary>A keep-out this close to a work-area side lies on it.</summary>
private const double EdgeReach = 0.02;
/// <summary>
/// <paramref name="area"/> with each side that carries clamps moved in just past their
/// keep-outs, as a larger edge spacing would, and whether every clamp inside it lies on a side;
/// when one does not, the area unchanged.
/// </summary>
public static (Box Area, bool OnEdges) ClearOfEdges(Box area, ClampObstacles? clamps)
{
var allOnEdges = true;
double left = area.Left, right = area.Right, bottom = area.Bottom, top = area.Top;
for (var i = 0; clamps != null && i < clamps.Count; i++)
{
var box = Clipper.GetBounds(clamps.Outline(i));
if (box.right <= area.Left || box.left >= area.Right || box.bottom <= area.Bottom || box.top >= area.Top)
continue; // Outside the work area: nothing to clear.
if (box.left <= area.Left + EdgeReach)
left = System.Math.Max(left, box.right);
else if (box.right >= area.Right - EdgeReach)
right = System.Math.Min(right, box.left);
else if (box.top <= area.Bottom + EdgeReach) // Clipper RectD: top is the minimum Y.
bottom = System.Math.Max(bottom, box.bottom);
else if (box.bottom >= area.Top - EdgeReach)
top = System.Math.Min(top, box.top);
else
allOnEdges = false;
}
if (!allOnEdges || right <= left || top <= bottom)
return (area, false);
return (new Box(left, bottom, right - left, top - bottom), true);
}
}
@@ -70,35 +70,10 @@ internal sealed class EdgeFirstFill(
/// above the clamps keeps parts flush with one straight edge instead of stepping between
/// clamps. A clamp off every side stays an obstacle instead.
/// </summary>
private readonly Box work = ClearOfClamps(stock.WorkArea, clamps).Area;
private readonly Box work = ClampObstacles.ClearOfEdges(stock.WorkArea, clamps).Area;
/// <summary>Clamps not cleared by moving a side: obstacles inside the work area.</summary>
private readonly ClampObstacles? obstacles = ClearOfClamps(stock.WorkArea, clamps).OnEdges ? null : clamps;
private static (Box Area, bool OnEdges) ClearOfClamps(Box area, ClampObstacles? clamps)
{
var allOnEdges = true;
double left = area.Left, right = area.Right, bottom = area.Bottom, top = area.Top;
for (var i = 0; clamps != null && i < clamps.Count; i++)
{
var box = Clipper.GetBounds(clamps.Outline(i));
if (box.right <= area.Left || box.left >= area.Right || box.bottom <= area.Bottom || box.top >= area.Top)
continue; // Outside the work area: nothing to clear.
if (box.left <= area.Left + OnEdge)
left = System.Math.Max(left, box.right);
else if (box.right >= area.Right - OnEdge)
right = System.Math.Min(right, box.left);
else if (box.top <= area.Bottom + OnEdge) // Clipper RectD: top is the minimum Y.
bottom = System.Math.Max(bottom, box.bottom);
else if (box.bottom >= area.Top - OnEdge)
top = System.Math.Min(top, box.top);
else
allOnEdges = false;
}
if (!allOnEdges || right <= left || top <= bottom)
return (area, false);
return (new Box(left, bottom, right - left, top - bottom), true);
}
private readonly ClampObstacles? obstacles = ClampObstacles.ClearOfEdges(stock.WorkArea, clamps).OnEdges ? null : clamps;
public SheetFill? Fill(IReadOnlyList<int> demand, CancellationToken token)
{
+13 -5
View File
@@ -334,7 +334,10 @@ scatters the smallest parts into the gaps between groups.
then the copies held back from them and the types with one or two copies fill the gaps under
the usual rule. On the better order each type's narrower bands holding fewer copies (at most
four, or a third, fewer; at most two per type) are tried in turn, kept when they improve the
sheet.
sheet. So are each type's lower bands: up to three, each asked for just short of the last
band's height, so each is a row or so lower (its search steps through three lengths and makes
no halvings). A lower band leaves a strip along the sheet that the held-back copies and other
parts fill, and can sit past a clamp rail whole.
- Strips: each strip holds the largest remaining part, as its band (full or narrower) or as a
column one to three copies wide that the part fills first, and every other part fills the
strip's gaps, the largest piece at its leftmost, lowest point first, looking back one part
@@ -352,15 +355,20 @@ scatters the smallest parts into the gaps between groups.
are those of building each pattern in turn. Patterns are filled one Clipper grid unit (0.0001) wider than the part spacing and
certified at the spacing: Fill sets parts exactly the spacing apart, which the strict
certification can reject for curved parts, and a stack of rings would lose its densest pattern.
- A band member inside a clamp keep-out goes to the gap fill instead; a band shorter than the
sheet moves flush to the far edge when that keeps more of it off the clamps. Outlined sheets do
not band.
- A band sits flush to the bottom. When that leaves members in a clamp keep-out, it also tries
flush to the top and just past the clamps lining the bottom or top edge (the work area with that
side moved in past the keep-outs, as the sheet-reduction pass packs it), keeping whichever holds
the most; members still inside a keep-out go to the gap fill. Outlined sheets do not band.
Neither way wins every sheet. On the README sample parts (18 L brackets, 14 base plates, 18 clamp
jaws, 12 flanges, 24 gussets, 14 hex covers, 30 links on 60 x 120) bands end the layout at 102.9
(104.6 with the desktop's edge spacing and a bottom clamp rail) rather than 107.7 (108.6); with
about twice those quantities over two sheets, strips end the second sheet at 99.9 rather than 106.2,
and on the help tutorial's parts at 33.6 rather than 34.9. It
and on the help tutorial's parts at 33.6 rather than 34.9. On a production job of 20 formed legs of
each of two sizes on 60 x 120 with a bottom clamp rail, the larger leg's full-height band could
not clear the rail, so three copies went to the gaps and the layout ended at 104.7; its band a row
lower (two rows of nine and two copies turned across the top), flush to the top, clears the rail
and leaves a strip below it for the smaller leg's last two copies, ending the layout at 103.9. It
starts while the work spent stays under three work budgets and replaces the result only by
beating it, with its own tail re-plan.