4 Commits
Author SHA1 Message Date
ajandClaude Opus 4.6 b15375cca5 feat: capacity-based fill/pack split with best-fit pair placement
Change Nest() to decide fill vs pack based on total area coverage
instead of qty != 1. Items covering < 10% of the plate are packed,
so large parts get prime position and small low-qty parts fill gaps.

Qty=2 items are placed as interlocking best-fit pairs in remnant
spaces after the main pack phase, rather than as separate rectangles.

- Add ShouldFill() capacity-based heuristic
- Split pack phase: regular items pack first, then pairs
- Add PlaceBestFitPairs() for Phase 3 remnant pair placement

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-30 00:38:57 -04:00
ajandClaude Opus 4.6 e3b388464d feat: fast-path fill and dual-axis shrink for low quantities
For qty 1-2, skip the full 6-strategy pipeline: place a single part
or a best-fit pair directly. For larger low quantities, shrink the
work area in both dimensions (sqrt scaling with 2x margin) before
running strategies, with fallback to full area if insufficient.

- Add TryFillSmallQuantity fast path (qty=1 single, qty=2 best-fit pair)
- Add ShrinkWorkArea with proportional dual-axis reduction
- Extract RunFillPipeline helper from Fill()
- Make ShrinkFiller.EstimateStartBox internal with margin parameter
- Add MaxQuantity to FillContext for strategy-level access

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-30 00:38:44 -04:00
ajandClaude Opus 4.6 ab09f835d3 refactor: extract RunAutoNest_Click into focused helper methods
Break the 113-line click handler into single-responsibility methods:
RunAutoNestAsync, GetOrCreatePlate, NestSinglePlateAsync, and
CreatePreviewPlate (eliminates duplicated plate-cloning code).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-29 23:52:07 -04:00
ajandClaude Opus 4.6 f8b0fb573b fix: fill preview now matches accepted layout
Refresh PlateView preview with settled parts after Compactor.Settle
so the accepted layout matches what was shown, not the pre-settle
positions from the last progress report.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-29 23:39:43 -04:00
6 changed files with 352 additions and 89 deletions
+163 -14
View File
@@ -1,7 +1,9 @@
using OpenNest.Engine; using OpenNest.Engine;
using OpenNest.Engine.BestFit;
using OpenNest.Engine.Fill; using OpenNest.Engine.Fill;
using OpenNest.Engine.Strategies; using OpenNest.Engine.Strategies;
using OpenNest.Geometry; using OpenNest.Geometry;
using OpenNest.Math;
using OpenNest.RectanglePacking; using OpenNest.RectanglePacking;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@@ -45,24 +47,50 @@ namespace OpenNest
PhaseResults.Clear(); PhaseResults.Clear();
AngleResults.Clear(); AngleResults.Clear();
var context = new FillContext // Fast path: for very small quantities, skip the full strategy pipeline.
if (item.Quantity > 0 && item.Quantity <= 2)
{ {
Item = item, var fast = TryFillSmallQuantity(item, workArea);
WorkArea = workArea, if (fast != null && fast.Count >= item.Quantity)
Plate = Plate, {
PlateNumber = PlateNumber, Debug.WriteLine($"[Fill] Fast path: placed {fast.Count} parts for qty={item.Quantity}");
Token = token, WinnerPhase = NestPhase.Pairs;
Progress = progress, ReportProgress(progress, new ProgressReport
Policy = BuildPolicy(), {
}; Phase = WinnerPhase,
PlateNumber = PlateNumber,
Parts = fast,
WorkArea = workArea,
Description = $"Fast path: {fast.Count} parts",
IsOverallBest = true,
});
return fast;
}
}
RunPipeline(context); // For low quantities, shrink the work area in both dimensions to avoid
// running expensive strategies against the full plate.
var effectiveWorkArea = workArea;
if (item.Quantity > 0)
{
effectiveWorkArea = ShrinkWorkArea(item, workArea, Plate.PartSpacing);
// PhaseResults already synced during RunPipeline. if (effectiveWorkArea != workArea)
AngleResults.AddRange(context.AngleResults); Debug.WriteLine($"[Fill] Low-qty shrink: {item.Quantity} requested, " +
WinnerPhase = context.WinnerPhase; $"from {workArea.Width:F1}x{workArea.Length:F1} " +
$"to {effectiveWorkArea.Width:F1}x{effectiveWorkArea.Length:F1}");
}
var best = context.CurrentBest ?? new List<Part>(); var best = RunFillPipeline(item, effectiveWorkArea, progress, token);
// Fallback: if the reduced area didn't yield enough, retry with full area.
if (item.Quantity > 0 && best.Count < item.Quantity && effectiveWorkArea != workArea)
{
Debug.WriteLine($"[Fill] Low-qty fallback: got {best.Count}, need {item.Quantity}, retrying full area");
PhaseResults.Clear();
AngleResults.Clear();
best = RunFillPipeline(item, workArea, progress, token);
}
if (item.Quantity > 0 && best.Count > item.Quantity) if (item.Quantity > 0 && best.Count > item.Quantity)
best = ShrinkFiller.TrimToCount(best, item.Quantity, TrimAxis); best = ShrinkFiller.TrimToCount(best, item.Quantity, TrimAxis);
@@ -80,6 +108,127 @@ namespace OpenNest
return best; return best;
} }
/// <summary>
/// Fast path for qty 1-2: place a single part or a best-fit pair
/// without running the full strategy pipeline.
/// </summary>
private List<Part> TryFillSmallQuantity(NestItem item, Box workArea)
{
if (item.Quantity == 1)
return TryPlaceSingle(item.Drawing, workArea);
if (item.Quantity == 2)
return TryPlaceBestFitPair(item.Drawing, workArea);
return null;
}
private static List<Part> TryPlaceSingle(Drawing drawing, Box workArea)
{
var part = Part.CreateAtOrigin(drawing);
if (part.BoundingBox.Width > workArea.Width + Tolerance.Epsilon ||
part.BoundingBox.Length > workArea.Length + Tolerance.Epsilon)
return null;
part.Offset(workArea.Location - part.BoundingBox.Location);
return new List<Part> { part };
}
private List<Part> TryPlaceBestFitPair(Drawing drawing, Box workArea)
{
var bestFits = BestFitCache.GetOrCompute(
drawing, Plate.Size.Length, Plate.Size.Width, Plate.PartSpacing);
var best = bestFits.FirstOrDefault(r => r.Keep);
if (best == null)
return null;
var parts = best.BuildParts(drawing);
// BuildParts positions at origin — offset to work area.
var bbox = ((IEnumerable<IBoundable>)parts).GetBoundingBox();
var offset = workArea.Location - bbox.Location;
foreach (var p in parts)
{
p.Offset(offset);
p.UpdateBounds();
}
// Verify pair fits in work area.
bbox = ((IEnumerable<IBoundable>)parts).GetBoundingBox();
if (bbox.Width > workArea.Width + Tolerance.Epsilon ||
bbox.Length > workArea.Length + Tolerance.Epsilon)
return null;
return parts;
}
/// <summary>
/// Shrinks the work area in both dimensions proportionally when the
/// requested quantity is much less than the plate capacity.
/// </summary>
private static Box ShrinkWorkArea(NestItem item, Box workArea, double spacing)
{
var bbox = item.Drawing.Program.BoundingBox();
if (bbox.Width <= 0 || bbox.Length <= 0)
return workArea;
var bin = new Bin { Size = new Size(workArea.Width, workArea.Length) };
var packItem = new Item { Size = new Size(bbox.Width + spacing, bbox.Length + spacing) };
var packer = new FillBestFit(bin);
packer.Fill(packItem);
var fullCount = bin.Items.Count;
if (fullCount <= 0 || fullCount <= item.Quantity)
return workArea;
// Scale both dimensions by sqrt(ratio) so the area shrinks
// proportionally. 2x margin gives strategies room to optimize.
var ratio = (double)item.Quantity / fullCount;
var scale = System.Math.Sqrt(ratio) * 2.0;
var newWidth = workArea.Width * scale;
var newLength = workArea.Length * scale;
// Ensure at least one part fits.
var minWidth = bbox.Width + spacing * 2;
var minLength = bbox.Length + spacing * 2;
newWidth = System.Math.Max(newWidth, minWidth);
newLength = System.Math.Max(newLength, minLength);
// Clamp to original dimensions.
newWidth = System.Math.Min(newWidth, workArea.Width);
newLength = System.Math.Min(newLength, workArea.Length);
if (newWidth >= workArea.Width && newLength >= workArea.Length)
return workArea;
return new Box(workArea.X, workArea.Y, newWidth, newLength);
}
private List<Part> RunFillPipeline(NestItem item, Box workArea,
IProgress<NestProgress> progress, CancellationToken token)
{
var context = new FillContext
{
Item = item,
WorkArea = workArea,
Plate = Plate,
PlateNumber = PlateNumber,
Token = token,
Progress = progress,
Policy = BuildPolicy(),
MaxQuantity = item.Quantity,
};
RunPipeline(context);
AngleResults.AddRange(context.AngleResults);
WinnerPhase = context.WinnerPhase;
return context.CurrentBest ?? new List<Part>();
}
public override List<Part> Fill(List<Part> groupParts, Box workArea, public override List<Part> Fill(List<Part> groupParts, Box workArea,
IProgress<NestProgress> progress, CancellationToken token) IProgress<NestProgress> progress, CancellationToken token)
{ {
+3 -3
View File
@@ -94,8 +94,8 @@ namespace OpenNest.Engine.Fill
/// that fits roughly the target count. Scales the shrink axis proportionally /// that fits roughly the target count. Scales the shrink axis proportionally
/// from the full-area count down to the target, with margin. /// from the full-area count down to the target, with margin.
/// </summary> /// </summary>
private static Box EstimateStartBox(NestItem item, Box box, internal static Box EstimateStartBox(NestItem item, Box box,
double spacing, ShrinkAxis axis, int targetCount) double spacing, ShrinkAxis axis, int targetCount, double marginFactor = 1.3)
{ {
var bbox = item.Drawing.Program.BoundingBox(); var bbox = item.Drawing.Program.BoundingBox();
if (bbox.Width <= 0 || bbox.Length <= 0) if (bbox.Width <= 0 || bbox.Length <= 0)
@@ -115,7 +115,7 @@ namespace OpenNest.Engine.Fill
// Scale dimension proportionally: target/full * maxDim, with margin. // Scale dimension proportionally: target/full * maxDim, with margin.
var ratio = (double)targetCount / fullCount; var ratio = (double)targetCount / fullCount;
var estimate = maxDim * ratio * 1.3; var estimate = maxDim * ratio * marginFactor;
estimate = System.Math.Min(estimate, maxDim); estimate = System.Math.Min(estimate, maxDim);
if (estimate <= 0 || estimate >= maxDim) if (estimate <= 0 || estimate >= maxDim)
+104 -6
View File
@@ -1,4 +1,5 @@
using OpenNest.Engine; using OpenNest.Engine;
using OpenNest.Engine.BestFit;
using OpenNest.Engine.Fill; using OpenNest.Engine.Fill;
using OpenNest.Engine.Strategies; using OpenNest.Engine.Strategies;
using OpenNest.Geometry; using OpenNest.Geometry;
@@ -86,14 +87,16 @@ namespace OpenNest
var workArea = Plate.WorkArea(); var workArea = Plate.WorkArea();
var allParts = new List<Part>(); var allParts = new List<Part>();
var plateArea = workArea.Width * workArea.Length;
var fillItems = items var fillItems = items
.Where(i => i.Quantity != 1) .Where(i => ShouldFill(i, plateArea))
.OrderBy(i => i.Priority) .OrderBy(i => i.Priority)
.ThenByDescending(i => i.Drawing.Area) .ThenByDescending(i => i.Drawing.Area)
.ToList(); .ToList();
var packItems = items var packItems = items
.Where(i => i.Quantity == 1) .Where(i => !ShouldFill(i, plateArea))
.ToList(); .ToList();
// Phase 1: Fill multi-quantity drawings using RemnantFiller. // Phase 1: Fill multi-quantity drawings using RemnantFiller.
@@ -129,19 +132,22 @@ namespace OpenNest
} }
} }
// Phase 2: Pack single-quantity items into remaining space. // Phase 2: Pack low-quantity items into remaining space.
// Separate qty=2 items — they'll be placed as best-fit pairs after packing.
packItems = packItems.Where(i => i.Quantity > 0).ToList(); packItems = packItems.Where(i => i.Quantity > 0).ToList();
var pairItems = packItems.Where(i => i.Quantity == 2).ToList();
var regularPackItems = packItems.Where(i => i.Quantity != 2).ToList();
if (packItems.Count > 0 && workArea.Width > 0 && workArea.Length > 0 if (regularPackItems.Count > 0 && workArea.Width > 0 && workArea.Length > 0
&& !token.IsCancellationRequested) && !token.IsCancellationRequested)
{ {
var packParts = PackArea(workArea, packItems, progress, token); var packParts = PackArea(workArea, regularPackItems, progress, token);
if (packParts.Count > 0) if (packParts.Count > 0)
{ {
allParts.AddRange(packParts); allParts.AddRange(packParts);
foreach (var item in packItems) foreach (var item in regularPackItems)
{ {
var placed = packParts.Count(p => var placed = packParts.Count(p =>
p.BaseDrawing.Name == item.Drawing.Name); p.BaseDrawing.Name == item.Drawing.Name);
@@ -150,6 +156,13 @@ namespace OpenNest
} }
} }
// Phase 3: Place best-fit pairs for qty=2 items in remaining space.
if (pairItems.Count > 0 && !token.IsCancellationRequested)
{
var placed = PlaceBestFitPairs(pairItems, allParts, Plate.WorkArea());
allParts.AddRange(placed);
}
// Compact placed parts toward the origin to close gaps. // Compact placed parts toward the origin to close gaps.
Compactor.Settle(allParts, Plate.WorkArea(), Plate.PartSpacing); Compactor.Settle(allParts, Plate.WorkArea(), Plate.PartSpacing);
@@ -301,5 +314,90 @@ namespace OpenNest
return false; return false;
} }
/// <summary>
/// Places best-fit pairs for qty=2 items into remnant spaces around
/// already-placed parts. Returns all placed pair parts.
/// </summary>
private List<Part> PlaceBestFitPairs(List<NestItem> pairItems,
List<Part> existingParts, Box fullWorkArea)
{
var result = new List<Part>();
var obstacles = existingParts
.Select(p => p.BoundingBox.Offset(Plate.PartSpacing))
.ToList();
var finder = new RemnantFinder(fullWorkArea, obstacles);
foreach (var item in pairItems)
{
if (item.Quantity < 2) continue;
var bestFits = BestFitCache.GetOrCompute(
item.Drawing, Plate.Size.Length, Plate.Size.Width, Plate.PartSpacing);
var bestFit = bestFits.FirstOrDefault(r => r.Keep);
if (bestFit == null) continue;
var parts = bestFit.BuildParts(item.Drawing);
var pairBbox = ((IEnumerable<IBoundable>)parts).GetBoundingBox();
var pairW = pairBbox.Width;
var pairL = pairBbox.Length;
var minDim = System.Math.Min(pairW, pairL);
var remnants = finder.FindRemnants(minDim);
Box target = null;
foreach (var r in remnants)
{
if (pairW <= r.Width + Tolerance.Epsilon &&
pairL <= r.Length + Tolerance.Epsilon)
{
target = r;
break;
}
}
if (target == null) continue;
var offset = target.Location - pairBbox.Location;
foreach (var p in parts)
{
p.Offset(offset);
p.UpdateBounds();
}
result.AddRange(parts);
item.Quantity = 0;
var envelope = ((IEnumerable<IBoundable>)parts).GetBoundingBox();
finder.AddObstacle(envelope.Offset(Plate.PartSpacing));
Debug.WriteLine($"[Nest] Placed best-fit pair for {item.Drawing.Name} " +
$"at ({target.X:F1},{target.Y:F1}), size {pairW:F1}x{pairL:F1}");
}
return result;
}
/// <summary>
/// Determines whether a drawing should use grid-fill (true) or bin-pack (false).
/// Low-quantity items whose total area is a small fraction of the plate are
/// better off being packed alongside other parts rather than filling first.
/// </summary>
private bool ShouldFill(NestItem item, double plateArea)
{
if (item.Quantity <= 1)
return false;
var bbox = item.Drawing.Program.BoundingBox();
var partArea = (bbox.Width + Plate.PartSpacing) * (bbox.Length + Plate.PartSpacing);
if (partArea <= 0)
return false;
var totalArea = partArea * item.Quantity;
// If the total area of all copies is less than 10% of the plate,
// packing produces better results than grid-filling.
return totalArea >= plateArea * 0.1;
}
} }
} }
@@ -16,6 +16,7 @@ namespace OpenNest.Engine.Strategies
public CancellationToken Token { get; init; } public CancellationToken Token { get; init; }
public IProgress<NestProgress> Progress { get; init; } public IProgress<NestProgress> Progress { get; init; }
public FillPolicy Policy { get; init; } public FillPolicy Policy { get; init; }
public int MaxQuantity { get; init; }
public PartType PartType { get; set; } public PartType PartType { get; set; }
public List<Part> CurrentBest { get; set; } public List<Part> CurrentBest { get; set; }
+1
View File
@@ -1279,6 +1279,7 @@ namespace OpenNest.Controls
if (parts.Count > 0 && (!cts.IsCancellationRequested || progressForm.Accepted)) if (parts.Count > 0 && (!cts.IsCancellationRequested || progressForm.Accepted))
{ {
SetActiveParts(parts);
AcceptPreviewParts(parts); AcceptPreviewParts(parts);
if (Plate.CutOffs.Count > 0) if (Plate.CutOffs.Count > 0)
+80 -66
View File
@@ -901,19 +901,8 @@ namespace OpenNest.Forms
return; return;
nestingCts = new CancellationTokenSource(); nestingCts = new CancellationTokenSource();
var token = nestingCts.Token;
var progressForm = new NestProgressForm(nestingCts, showPlateRow: true); var progressForm = new NestProgressForm(nestingCts, showPlateRow: true);
progressForm.PreviewPlate = CreatePreviewPlate(activeForm.PlateView.Plate);
var previewPlate = new Plate(activeForm.PlateView.Plate.Size)
{
Quadrant = activeForm.PlateView.Plate.Quadrant,
PartSpacing = activeForm.PlateView.Plate.PartSpacing,
Thickness = activeForm.PlateView.Plate.Thickness,
Material = activeForm.PlateView.Plate.Material,
};
previewPlate.EdgeSpacing = activeForm.PlateView.Plate.EdgeSpacing;
progressForm.PreviewPlate = previewPlate;
var progress = new Progress<NestProgress>(p => var progress = new Progress<NestProgress>(p =>
{ {
@@ -931,60 +920,7 @@ namespace OpenNest.Forms
try try
{ {
var maxPlates = 100; await RunAutoNestAsync(items, progressForm, progress, nestingCts.Token);
for (var plateCount = 0; plateCount < maxPlates; plateCount++)
{
var remaining = items.Where(i => i.Quantity > 0).ToList();
if (remaining.Count == 0)
break;
if (token.IsCancellationRequested)
break;
var plate = activeForm.PlateView.Plate.Parts.Count > 0
? activeForm.Nest.CreatePlate()
: activeForm.PlateView.Plate;
if (plate != activeForm.PlateView.Plate)
{
activeForm.LoadLastPlate();
var newPreviewPlate = new Plate(plate.Size)
{
Quadrant = plate.Quadrant,
PartSpacing = plate.PartSpacing,
Thickness = plate.Thickness,
Material = plate.Material,
};
newPreviewPlate.EdgeSpacing = plate.EdgeSpacing;
progressForm.PreviewPlate = newPreviewPlate;
}
var anyPlaced = false;
var engine = NestEngineRegistry.Create(plate);
engine.PlateNumber = plateCount;
var nestParts = await Task.Run(() =>
engine.Nest(remaining, progress, token));
activeForm.PlateView.ClearPreviewParts();
if (nestParts.Count > 0 && (!token.IsCancellationRequested || progressForm.Accepted))
{
plate.Parts.AddRange(nestParts);
activeForm.PlateView.Invalidate();
anyPlaced = true;
}
if (!anyPlaced)
break;
}
activeForm.Nest.UpdateDrawingQuantities();
progressForm.ShowCompleted();
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -1002,6 +938,84 @@ namespace OpenNest.Forms
} }
} }
private async Task RunAutoNestAsync(
List<NestItem> items,
NestProgressForm progressForm,
IProgress<NestProgress> progress,
CancellationToken token)
{
const int maxPlates = 100;
for (var plateIndex = 0; plateIndex < maxPlates; plateIndex++)
{
var remaining = items.Where(i => i.Quantity > 0).ToList();
if (remaining.Count == 0 || token.IsCancellationRequested)
break;
var plate = GetOrCreatePlate(progressForm);
var placed = await NestSinglePlateAsync(
plate, plateIndex, remaining, progressForm, progress, token);
if (!placed)
break;
}
activeForm.Nest.UpdateDrawingQuantities();
progressForm.ShowCompleted();
}
private Plate GetOrCreatePlate(NestProgressForm progressForm)
{
var currentPlate = activeForm.PlateView.Plate;
if (currentPlate.Parts.Count == 0)
return currentPlate;
var plate = activeForm.Nest.CreatePlate();
activeForm.LoadLastPlate();
progressForm.PreviewPlate = CreatePreviewPlate(plate);
return plate;
}
private async Task<bool> NestSinglePlateAsync(
Plate plate,
int plateIndex,
List<NestItem> items,
NestProgressForm progressForm,
IProgress<NestProgress> progress,
CancellationToken token)
{
var engine = NestEngineRegistry.Create(plate);
engine.PlateNumber = plateIndex;
var nestParts = await Task.Run(() =>
engine.Nest(items, progress, token));
activeForm.PlateView.ClearPreviewParts();
if (nestParts.Count == 0 || (token.IsCancellationRequested && !progressForm.Accepted))
return false;
plate.Parts.AddRange(nestParts);
activeForm.PlateView.Invalidate();
return true;
}
private static Plate CreatePreviewPlate(Plate source)
{
var plate = new Plate(source.Size)
{
Quadrant = source.Quadrant,
PartSpacing = source.PartSpacing,
Thickness = source.Thickness,
Material = source.Material,
};
plate.EdgeSpacing = source.EdgeSpacing;
return plate;
}
private void SequenceAllPlates_Click(object sender, EventArgs e) private void SequenceAllPlates_Click(object sender, EventArgs e)
{ {
if (activeForm == null) if (activeForm == null)