feat(auto-nest): offer the top layouts in the progress window with each sheet's free strip

The Auto Nest progress window lists up to three whole-job layouts as
cards, the engine's best first and then the best of each other family
(sheet count and free-strip direction). Every sheet shows the distance
from its parts to the right edge (vertical strips) or the top
(horizontal strips), dimensioned on the sheet. Any card can be used:
during the search it stops it, and a finished search with more than one
layout waits for the pick. The layout used is validated and bound like
the engine's own result.

Engines may report plans that lost to their best as
NestJobStage.PlanAlternative; Irregular, Default and the time-limited
solve do. Reporting never changes a layout.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
ajandClaude Fable 5.2 committed 2026-11-15 18:04:21 -05:00
1 parent bf734ea743
commit b96e0853b5
23 files changed
+1232 -62

No files matched your search

+1 -1
View File
@@ -52,7 +52,7 @@ namespace OpenNest.Benchmark
public void Report(NestJobProgress value)
{
if (value == null)
if (value == null || value.Stage == NestJobStage.PlanAlternative)
return;
if (value.Stage == NestJobStage.PlateCommitted)
@@ -0,0 +1,176 @@
using OpenNest.CNC;
using OpenNest.Engine.Jobs;
using OpenNest.Forms;
using OpenNest.Geometry;
namespace OpenNest.Desktop.Tests.Forms;
public class NestLayoutChoicesTests
{
private static readonly Drawing Bracket = new("bracket", Rectangle());
// 10 long (X) by 20 wide (Y).
private static Program Rectangle()
{
var program = new Program();
program.MoveTo(0, 0);
program.LineTo(10, 0);
program.LineTo(10, 20);
program.LineTo(0, 20);
program.LineTo(0, 0);
return program;
}
// 96 long (X) by 48 wide (Y).
private static NestPlateStock Stock(int quadrant = 1) =>
new("sheet", new Size(48, 96), quantity: null, partSpacing: 0.25, quadrant: quadrant);
private static ProposedPlate Sheet(NestPlateStock stock, params (double X, double Y)[] at)
{
var parts = at.Select(p =>
{
var part = new Part(Bracket) { Location = new Vector(p.X, p.Y) };
part.UpdateBounds();
return part;
}).ToList();
return new ProposedPlate(0, stock, parts);
}
private static NestLayoutChoice Layout(params ProposedPlate[] sheets) => new(sheets);
[Fact]
public void VerticalStrips_LeaveTheDistanceToTheRightEdge()
{
// Two columns to the full height: 76 free along the length, nothing above.
var remnant = SheetRemnant.Of(Sheet(Stock(), (0, 0), (0, 28), (10, 0), (10, 28)));
Assert.Equal(SheetEdge.Right, remnant!.Value.Edge);
Assert.Equal(76, remnant.Value.Distance, 6);
Assert.Equal("76 to right edge", remnant.Value.ToString());
}
[Fact]
public void HorizontalStrips_LeaveTheDistanceToTheTop()
{
// One row along the whole length: 28 free above it.
var remnant = SheetRemnant.Of(Sheet(Stock(), (0, 0), (40, 0), (86, 0)));
Assert.Equal(SheetEdge.Top, remnant!.Value.Edge);
Assert.Equal(28, remnant.Value.Distance, 6);
Assert.Equal("28 to top", remnant.Value.ToString());
}
[Fact]
public void TheFreeStripIsMeasuredAwayFromTheSheetOrigin()
{
// Quadrant 3: the sheet spans -96..0 by -48..0 and parts pack from its top-right corner.
var remnant = SheetRemnant.Of(Sheet(Stock(3), (-10, -20), (-10, -48), (-20, -48), (-20, -20)));
Assert.Equal(SheetEdge.Left, remnant!.Value.Edge);
Assert.Equal(76, remnant.Value.Distance, 6);
}
[Fact]
public void AnEmptySheet_HasNoFreeStrip() => Assert.Null(SheetRemnant.Of(Sheet(Stock())));
[Fact]
public void TheSummaryNamesTheLastSheetsFreeStrip()
{
var stock = Stock();
var layout = Layout(Sheet(stock, (0, 0), (86, 28)), Sheet(stock, (0, 0), (0, 28)));
Assert.Equal(2, layout.SheetCount);
Assert.Equal(4, layout.PartCount);
Assert.EndsWith("86 to right edge on sheet 2", layout.Summary);
Assert.StartsWith("2 sheets · 4 parts", layout.Summary);
}
[Fact]
public void ANewBestReplacesItsFamilyAndKeepsTheOtherDirection()
{
var stock = Stock();
var choices = new NestLayoutChoices();
var vertical = Layout(Sheet(stock, (0, 0), (0, 28), (10, 0)));
var horizontal = Layout(Sheet(stock, (0, 0), (40, 0), (86, 0)));
var tighter = Layout(Sheet(stock, (0, 0), (0, 28), (10.5, 0)));
Assert.True(choices.Add(vertical, best: true));
Assert.True(choices.Add(horizontal, best: false));
Assert.Equal(new[] { vertical, horizontal }, choices.Top);
// Same sheet count and direction as the old best: it takes its place.
Assert.True(choices.Add(tighter, best: true));
Assert.Equal(new[] { tighter, horizontal }, choices.Top);
Assert.Same(tighter, choices.Best);
}
[Fact]
public void AnAlternativeNeverDisplacesTheBestOfItsFamily_AndOnlyABetterOneDisplacesAnother()
{
var stock = Stock();
var choices = new NestLayoutChoices();
var best = Layout(Sheet(stock, (0, 0), (0, 28), (10, 0)));
var sameFamily = Layout(Sheet(stock, (0, 0), (0, 28), (10, 0), (10, 28)));
var row = Layout(Sheet(stock, (0, 0), (86, 0)));
var fullerRow = Layout(Sheet(stock, (0, 0), (40, 0), (86, 0)));
choices.Add(best, best: true);
Assert.False(choices.Add(sameFamily, best: false));
Assert.True(choices.Add(row, best: false));
Assert.False(choices.Add(Layout(Sheet(stock, (0, 0), (86, 0))), best: false));
Assert.True(choices.Add(fullerRow, best: false));
Assert.Equal(new[] { best, fullerRow }, choices.Top);
}
[Fact]
public void TheListIsCappedBestFirstThenByPartsPlaced()
{
var stock = Stock();
var choices = new NestLayoutChoices(capacity: 2);
var best = Layout(Sheet(stock, (0, 0), (0, 28)));
var twoSheets = Layout(Sheet(stock, (0, 0)), Sheet(stock, (0, 0)));
var row = Layout(Sheet(stock, (0, 0), (40, 0), (86, 0)));
choices.Add(best, best: true);
choices.Add(twoSheets, best: false);
choices.Add(row, best: false);
Assert.Equal(new[] { best, row }, choices.Top);
}
[Fact]
public void LayoutReports_CarryEveryPlanAndMarkTheBest()
{
var reports = new List<NestLayoutReport>();
var described = new List<OpenNest.Engine.NestProgress>();
var progress = JobEngineNest.CreateLayoutProgress("Irregular", new Inline<OpenNest.Engine.NestProgress>(described.Add),
new Inline<NestLayoutReport>(reports.Add));
var sheets = new[] { Sheet(Stock(), (0, 0)) };
NestPipelineResult Accept(CancellationToken _) => null!;
progress.Report(new NestJobProgress(NestJobStage.PlanImproved, "s", 0, 0, 0) { PlanSheets = sheets, AcceptPlan = Accept });
progress.Report(new NestJobProgress(NestJobStage.PlanAlternative, "s", 0, 0, 0) { PlanSheets = sheets, AcceptPlan = Accept });
Assert.Empty(described);
Assert.Equal(new[] { true, false }, reports.Select(r => r.Best));
Assert.All(reports, r => Assert.Same(sheets, r.Layout.Sheets));
Assert.All(reports, r => Assert.NotNull(r.Layout.Accept));
}
[Fact]
public void AnAlternativePlan_IsNeverDescribedAsAStage()
{
var described = new List<OpenNest.Engine.NestProgress>();
JobEngineNest.CreateProgress("Irregular", new Inline<OpenNest.Engine.NestProgress>(described.Add))
.Report(new NestJobProgress(NestJobStage.PlanAlternative, "s", 0, 0, 0) { PlanSheets = [] });
Assert.Empty(described);
}
private sealed class Inline<T>(Action<T> report) : IProgress<T>
{
public void Report(T value) => report(value);
}
}
+22 -4
View File
@@ -32,7 +32,23 @@ namespace OpenNest.Forms
string engineName,
IProgress<NestProgress> progress,
IProgress<IReadOnlyList<ProposedPlate>> plans
) => new ProgressAdapter(engineName, progress, plans);
) => new ProgressAdapter(engineName, progress, plans == null ? null : value =>
{
if (value.Stage == NestJobStage.PlanImproved)
plans.Report(value.PlanSheets);
});
/// <summary>
/// As <see cref="CreateProgress(string, IProgress{NestProgress})"/>, and also sends every
/// plan the engine reports to <paramref name="layouts"/> as a layout the user may choose:
/// its best so far and the alternatives beside it.
/// </summary>
public static IProgress<NestJobProgress> CreateLayoutProgress(
string engineName,
IProgress<NestProgress> progress,
IProgress<NestLayoutReport> layouts
) => new ProgressAdapter(engineName, progress, value => layouts.Report(new NestLayoutReport(
new NestLayoutChoice(value.PlanSheets, value.AcceptPlan), value.Stage == NestJobStage.PlanImproved)));
public static string Describe(string engineName, NestJobProgress value) => value.Stage switch
{
@@ -50,7 +66,7 @@ namespace OpenNest.Forms
private sealed class ProgressAdapter(
string engineName,
IProgress<NestProgress> progress,
IProgress<IReadOnlyList<ProposedPlate>> plans
Action<NestJobProgress> plans
) : IProgress<NestJobProgress>
{
public void Report(NestJobProgress value)
@@ -59,10 +75,12 @@ namespace OpenNest.Forms
return;
// A plan sink shows plans as sheets; the plate row keeps tracking the search.
if (value.Stage == NestJobStage.PlanImproved && plans != null)
// An alternative plan is never a stage of the search.
if (value.Stage == NestJobStage.PlanAlternative
|| (value.Stage == NestJobStage.PlanImproved && plans != null))
{
if (value.PlanSheets != null)
plans.Report(value.PlanSheets);
plans?.Invoke(value);
return;
}
+214
View File
@@ -0,0 +1,214 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using OpenNest.Engine.Jobs;
namespace OpenNest.Forms
{
/// <summary>The sheet edge a layout leaves its free strip against.</summary>
internal enum SheetEdge
{
Right,
Left,
Top,
Bottom,
}
/// <summary>
/// The free strip a sheet's parts leave: the distance from the parts to the sheet edge they
/// were packed away from. Parts packed in vertical strips advance along the sheet's length
/// and leave it against the right edge (left in quadrants 2 and 3); horizontal strips leave
/// it against the top (bottom in quadrants 3 and 4). Of the two, the strip with more area is
/// the one reported.
/// </summary>
internal readonly record struct SheetRemnant(SheetEdge Edge, double Distance, double Area)
{
/// <summary>True when the strip runs the sheet's full height (vertical strips).</summary>
public bool AlongLength => Edge is SheetEdge.Right or SheetEdge.Left;
/// <summary>Null for an empty sheet and for an outlined one, which has no such edge.</summary>
public static SheetRemnant? Of(ProposedPlate plate)
{
var stock = plate?.Stock;
if (stock == null || stock.Outline != null || plate.Parts.Count == 0)
return null;
var length = stock.Size.Length;
var width = stock.Size.Width;
// Sheet extents around the origin, as the plate view places them for this quadrant.
var fromRight = stock.Quadrant is 2 or 3;
var fromTop = stock.Quadrant is 3 or 4;
var x = fromRight ? -length : 0;
var y = fromTop ? -width : 0;
var left = plate.Parts.Min(p => p.BoundingBox.Left);
var right = plate.Parts.Max(p => p.BoundingBox.Right);
var bottom = plate.Parts.Min(p => p.BoundingBox.Bottom);
var top = plate.Parts.Max(p => p.BoundingBox.Top);
var alongLength = System.Math.Max(0, fromRight ? left - x : x + length - right);
var alongWidth = System.Math.Max(0, fromTop ? bottom - y : y + width - top);
return alongLength * width >= alongWidth * length
? new SheetRemnant(fromRight ? SheetEdge.Left : SheetEdge.Right, alongLength, alongLength * width)
: new SheetRemnant(fromTop ? SheetEdge.Bottom : SheetEdge.Top, alongWidth, alongWidth * length);
}
public override string ToString() => $"{Distance:0.##} to {EdgeName}";
private string EdgeName => Edge switch
{
SheetEdge.Right => "right edge",
SheetEdge.Left => "left edge",
SheetEdge.Top => "top",
_ => "bottom",
};
}
/// <summary>
/// One whole-job layout a user may choose: its sheets, what it places, the free strip its
/// last sheet leaves, and how to turn it into a proposal.
/// </summary>
internal sealed class NestLayoutChoice
{
/// <param name="accept">Validates and binds the layout; null for a layout that can only be shown.</param>
public NestLayoutChoice(IReadOnlyList<ProposedPlate> sheets,
Func<CancellationToken, NestPipelineResult> accept = null)
{
Sheets = sheets ?? Array.Empty<ProposedPlate>();
Accept = accept;
SheetCount = Sheets.Sum(s => s.Quantity);
PartCount = Sheets.Sum(s => s.Quantity * s.Parts.Count);
SheetArea = Sheets.Sum(s => s.Quantity * s.Stock.Area);
PartArea = Sheets.Sum(s => s.Quantity * s.Parts.Sum(p => p.BaseDrawing.Area));
// The last sheet holds the leftovers, so its free strip is the usable drop.
if (Sheets.Count > 0)
Remnant = SheetRemnant.Of(Sheets[^1]);
}
public IReadOnlyList<ProposedPlate> Sheets { get; }
public Func<CancellationToken, NestPipelineResult> Accept { get; }
public int SheetCount { get; }
public int PartCount { get; }
public double SheetArea { get; }
public double PartArea { get; }
public double Utilization => SheetArea > 0 ? PartArea / SheetArea : 0;
/// <summary>The free strip on the last sheet; null when it has none to measure.</summary>
public SheetRemnant? Remnant { get; }
/// <summary>"2 sheets · 130 parts · 29.9% used · 112.4 to right edge on sheet 2".</summary>
public string Summary
{
get
{
var text = $"{SheetCount} {(SheetCount == 1 ? "sheet" : "sheets")} · {PartCount} parts · {Utilization:P1} used";
if (Remnant is not { } remnant)
return text;
return SheetCount == 1 ? $"{text} · {remnant}" : $"{text} · {remnant} on sheet {SheetCount}";
}
}
/// <summary>
/// Layouts alike enough that only the better one is offered: the same number of sheets,
/// leaving the free strip the same way.
/// </summary>
internal (int Sheets, bool? AlongLength) Family => (SheetCount, Remnant?.AlongLength);
/// <summary>True when both place the same parts at the same poses on the same stock.</summary>
public bool SameLayoutAs(NestLayoutChoice other)
{
if (ReferenceEquals(this, other))
return true;
if (other == null || Sheets.Count != other.Sheets.Count)
return false;
for (var i = 0; i < Sheets.Count; i++)
{
var (a, b) = (Sheets[i], other.Sheets[i]);
if (a.Quantity != b.Quantity || a.Parts.Count != b.Parts.Count
|| !string.Equals(a.Stock.Id, b.Stock.Id, StringComparison.Ordinal))
return false;
for (var j = 0; j < a.Parts.Count; j++)
{
var (p, q) = (a.Parts[j], b.Parts[j]);
if (!string.Equals(p.BaseDrawing.Name, q.BaseDrawing.Name, StringComparison.Ordinal)
|| System.Math.Abs(p.Location.X - q.Location.X) > 1e-6
|| System.Math.Abs(p.Location.Y - q.Location.Y) > 1e-6
|| System.Math.Abs(p.Rotation - q.Rotation) > 1e-9)
return false;
}
}
return true;
}
/// <summary>More parts placed, then fewer sheets, less sheet area, the larger free strip.</summary>
internal bool IsBetterThan(NestLayoutChoice other)
{
if (PartCount != other.PartCount)
return PartCount > other.PartCount;
if (SheetCount != other.SheetCount)
return SheetCount < other.SheetCount;
if (System.Math.Abs(SheetArea - other.SheetArea) > 1e-6)
return SheetArea < other.SheetArea;
return (Remnant?.Area ?? 0) > (other.Remnant?.Area ?? 0);
}
}
/// <summary>
/// The layouts a run offers: the engine's best first, then the best layout of every other
/// family (sheet count and free-strip direction), so the list holds real alternatives rather
/// than near copies of the best. Not thread-safe: use it from one thread.
/// </summary>
internal sealed class NestLayoutChoices
{
private readonly List<NestLayoutChoice> kept = new();
private readonly int capacity;
public NestLayoutChoices(int capacity = 3)
{
this.capacity = capacity > 0 ? capacity : throw new ArgumentOutOfRangeException(nameof(capacity));
}
/// <summary>The engine's best layout so far; null before the first.</summary>
public NestLayoutChoice Best { get; private set; }
/// <summary>The layouts offered, best first.</summary>
public IReadOnlyList<NestLayoutChoice> Top { get; private set; } = Array.Empty<NestLayoutChoice>();
/// <summary>
/// Adds a layout. <paramref name="best"/> marks the engine's new best, which replaces
/// every layout of its family; any other layout is kept only when its family has none
/// yet or it beats the one kept. Returns whether <see cref="Top"/> changed.
/// </summary>
public bool Add(NestLayoutChoice choice, bool best)
{
ArgumentNullException.ThrowIfNull(choice);
if (choice.Sheets.Count == 0)
return false;
if (best)
{
kept.RemoveAll(c => c.Family == choice.Family);
kept.Add(choice);
Best = choice;
}
else
{
var rival = kept.Find(c => c.Family == choice.Family);
if (rival != null && (ReferenceEquals(rival, Best) || !choice.IsBetterThan(rival)))
return false;
kept.Remove(rival);
kept.Add(choice);
}
var top = new List<NestLayoutChoice>();
if (Best != null)
top.Add(Best);
var others = kept.Where(c => !ReferenceEquals(c, Best)).ToList();
others.Sort((a, b) => a.IsBetterThan(b) ? -1 : b.IsBetterThan(a) ? 1 : 0);
top.AddRange(others.Take(capacity - top.Count));
var changed = !top.SequenceEqual(Top);
Top = top;
return changed;
}
}
/// <summary>A layout from a running solve; <see cref="Best"/> marks the engine's best so far.</summary>
internal sealed record NestLayoutReport(NestLayoutChoice Layout, bool Best);
}
@@ -6,3 +6,4 @@ using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("OpenNest")]
[assembly: InternalsVisibleTo("OpenNest.Avalonia")]
[assembly: InternalsVisibleTo("OpenNest.Desktop.Tests")]
[assembly: InternalsVisibleTo("OpenNest.WinForms.Tests")]
@@ -80,6 +80,73 @@ public class NestPipelineTests
Assert.Equal(0, item.Drawing.Quantity.Nested);
}
[Fact]
public void AnAlternativePlanCanBeAcceptedAsAValidatedProposalBoundToCallerDrawings()
{
var item = Item("bracket", 2);
var engine = new AlternativeEngine(
job => OnePlate(job,
new NestJobPlacement(job.Parts[0].Id, 0, 1, 1, 0),
new NestJobPlacement(job.Parts[0].Id, 1, 20, 1, 0)),
job => OnePlate(job,
new NestJobPlacement(job.Parts[0].Id, 0, 1, 25, 0),
new NestJobPlacement(job.Parts[0].Id, 1, 20, 25, 0)));
var reports = new List<NestJobProgress>();
var result = NestPipeline.Run(engine, "Stub", Request("Stub", item), new InlineProgress(reports.Add));
var alternative = Assert.Single(reports, r => r.Stage == NestJobStage.PlanAlternative);
Assert.Equal(new[] { 25.0, 25.0 }, Assert.Single(alternative.PlanSheets).Parts.Select(p => p.Location.Y));
Assert.NotNull(Assert.Single(reports, r => r.Stage == NestJobStage.PlanImproved).AcceptPlan);
var accepted = alternative.AcceptPlan(CancellationToken.None);
Assert.True(accepted.IsValid, string.Join("; ", accepted.Violations));
Assert.True(accepted.CanKeep);
var parts = Assert.Single(accepted.Plates).Parts;
Assert.Equal(new[] { 25.0, 25.0 }, parts.Select(p => p.Location.Y));
Assert.All(parts, part => Assert.Same(item.Drawing, part.BaseDrawing));
Assert.Empty(accepted.Unplaced);
// The engine's own result is untouched by the accepted alternative.
Assert.Equal(new[] { 1.0, 1.0 }, Assert.Single(result.Plates).Parts.Select(p => p.Location.Y));
Assert.Equal(0, item.Drawing.Quantity.Nested);
}
[Fact]
public void AnAcceptedPlanThatBreaksLayoutRulesIsReportedInvalid()
{
var item = Item("bracket", 2);
var engine = new AlternativeEngine(
job => OnePlate(job,
new NestJobPlacement(job.Parts[0].Id, 0, 1, 1, 0),
new NestJobPlacement(job.Parts[0].Id, 1, 20, 1, 0)),
job => OnePlate(job,
new NestJobPlacement(job.Parts[0].Id, 0, 1, 1, 0),
new NestJobPlacement(job.Parts[0].Id, 1, 1, 1, 0)));
var reports = new List<NestJobProgress>();
NestPipeline.Run(engine, "Stub", Request("Stub", item), new InlineProgress(reports.Add));
var accepted = reports.Single(r => r.Stage == NestJobStage.PlanAlternative).AcceptPlan(CancellationToken.None);
Assert.False(accepted.IsValid);
}
private sealed class AlternativeEngine(Func<NestJob, NestJobResult> solve, Func<NestJob, NestJobResult> alternative)
: INestingEngine
{
public NestJobResult Solve(
NestJob job,
IProgress<NestJobProgress>? progress = null,
CancellationToken token = default
)
{
var result = solve(job);
progress?.Report(new NestJobProgress(NestJobStage.PlanImproved, string.Empty, -1, 0, 0, Plan: result));
progress?.Report(new NestJobProgress(NestJobStage.PlanAlternative, string.Empty, -1, 0, 0, Plan: alternative(job)));
return result;
}
}
private sealed class ReportingEngine(Func<NestJob, NestJobResult> solve) : INestingEngine
{
public NestJobResult Solve(
+20 -2
View File
@@ -1,4 +1,6 @@
using System;
using System.Collections.Generic;
using System.Threading;
namespace OpenNest.Engine.Jobs;
@@ -12,6 +14,13 @@ public enum NestJobStage
/// validated and possibly replaced by a later plan; never counts as committed.
/// </summary>
PlanImproved,
/// <summary>
/// Another complete whole-job plan the engine found that is not its best, in
/// <see cref="NestJobProgress.Plan"/>: a different layout a front end may offer beside the
/// best. Optional, unranked, not validated, and never the engine's result.
/// </summary>
PlanAlternative,
}
/// <summary>
@@ -30,8 +39,17 @@ public sealed record NestJobProgress(
{
/// <summary>
/// <see cref="Plan"/> as displayable sheets, filled in by <see cref="NestPipeline"/> for
/// <see cref="NestJobStage.PlanImproved"/> reports. Parts use detached drawings built from
/// the job geometry, so they never touch the caller's drawings or quantities.
/// <see cref="NestJobStage.PlanImproved"/> and <see cref="NestJobStage.PlanAlternative"/>
/// reports. Parts use detached drawings built from the job geometry, so they never touch
/// the caller's drawings or quantities.
/// </summary>
public IReadOnlyList<ProposedPlate> PlanSheets { get; init; }
/// <summary>
/// Turns <see cref="Plan"/> into a proposal exactly as the pipeline does an engine's result:
/// validated, then bound to the caller's drawings. Filled in with <see cref="PlanSheets"/>,
/// for a caller that stops the search to use this plan. Call it only once the solve that
/// reported the plan has ended.
/// </summary>
public Func<CancellationToken, NestPipelineResult> AcceptPlan { get; init; }
}
+38 -7
View File
@@ -114,7 +114,8 @@ public static class NestPipeline
{
public void Report(NestJobProgress value)
{
if (value != null && value.Stage is NestJobStage.EvaluatingCandidate or NestJobStage.PlanImproved)
if (value != null && value.Stage is NestJobStage.EvaluatingCandidate or NestJobStage.PlanImproved
or NestJobStage.PlanAlternative)
inner.Report(value with { CommittedPlates = 0, CommittedParts = 0 });
}
}
@@ -125,7 +126,8 @@ public static class NestPipeline
/// one per part, so a preview never touches the caller's drawings or their quantities.
/// </summary>
private sealed class PlanProgress(IProgress<NestJobProgress> inner, NestJob engineJob,
IReadOnlyDictionary<string, Drawing> callerDrawings, CancellationToken token)
IReadOnlyDictionary<string, Drawing> callerDrawings, CancellationToken token,
Func<NestJobResult, CancellationToken, NestPipelineResult> accept)
: IProgress<NestJobProgress>
{
private readonly Dictionary<string, NestJobPart> parts =
@@ -134,14 +136,20 @@ public static class NestPipeline
public void Report(NestJobProgress value)
{
if (value?.Stage == NestJobStage.PlanImproved && value.Plan != null && value.PlanSheets == null)
if (value?.Stage is NestJobStage.PlanImproved or NestJobStage.PlanAlternative
&& value.Plan != null && value.PlanSheets == null)
{
lock (drawings)
{
// A plan naming unknown parts has nothing to draw; validation reports it later.
if (value.Plan.Plates.Any(s => s.Placements.Any(p => p.PartId == null || !parts.ContainsKey(p.PartId))))
return;
value = value with { PlanSheets = PlanSheets(value.Plan, parts, callerDrawings, drawings, token) };
var plan = value.Plan;
value = value with
{
PlanSheets = PlanSheets(plan, parts, callerDrawings, drawings, token),
AcceptPlan = t => accept(plan, t),
};
}
}
inner.Report(value);
@@ -397,13 +405,17 @@ public static class NestPipeline
)
{
var engineJob = prepass?.EngineJob ?? job;
IReadOnlyDictionary<string, int> released = new Dictionary<string, int>();
if (prepass != null)
NestJobValidator.Validate(engineJob);
var clock = Stopwatch.StartNew();
// A reported plan is accepted against the job as it was asked: last-resort clamp
// removal belongs to the engine's own result.
var askedJob = job;
var engineProgress = progress == null ? null
: new PlanProgress(prepass == null ? progress : new PreviewProgress(progress), engineJob, drawingsByPartId, token);
: new PlanProgress(prepass == null ? progress : new PreviewProgress(progress), engineJob, drawingsByPartId, token,
(plan, accepting) => Finish(engineName, askedJob, prepass?.EngineJob ?? askedJob, prepass, plan,
drawingsByPartId, clock.Elapsed, accepting));
var raw =
engine.Solve(engineJob, engineProgress, token)
?? throw new InvalidOperationException($"Engine '{engineName}' returned no result.");
@@ -423,8 +435,27 @@ public static class NestPipeline
}
}
token.ThrowIfCancellationRequested();
return Finish(engineName, job, engineJob, prepass, raw, drawingsByPartId, solveTime, token);
}
clock.Restart();
/// <summary>
/// Validates <paramref name="raw"/> (an engine's result, or a plan it reported that the
/// caller chose instead) and binds it to the caller's drawings.
/// </summary>
private static NestPipelineResult Finish(
string engineName,
NestJob job,
NestJob engineJob,
IPipelinePrepass prepass,
NestJobResult raw,
IReadOnlyDictionary<string, Drawing> drawingsByPartId,
TimeSpan solveTime,
CancellationToken token
)
{
token.ThrowIfCancellationRequested();
IReadOnlyDictionary<string, int> released = new Dictionary<string, int>();
var clock = Stopwatch.StartNew();
var names = drawingsByPartId.ToDictionary(
kv => kv.Key,
kv => kv.Value.Name ?? kv.Key,
@@ -39,6 +39,11 @@ internal sealed class CandidateProgress(IProgress<NestJobProgress> inner) : IPro
public static void ReportPlan(NestJobResult plan, IProgress<NestJobProgress>? progress) =>
progress?.Report(new NestJobProgress(NestJobStage.PlanImproved, string.Empty, -1, 0, 0, Plan: plan));
/// <summary>Reports a whole-job plan that is not the best so far as
/// <see cref="NestJobStage.PlanAlternative"/>. Reporting never changes the search.</summary>
public static void ReportAlternative(NestJobResult plan, IProgress<NestJobProgress>? progress) =>
progress?.Report(new NestJobProgress(NestJobStage.PlanAlternative, string.Empty, -1, 0, 0, Plan: plan));
/// <summary>True when both results place the same parts at the same poses on the same stock,
/// sheet by sheet.</summary>
public static bool SameLayout(NestJobResult a, NestJobResult b) =>
@@ -151,7 +151,11 @@ public sealed class DeadlineNestingEngine : INestingEngine
return;
}
if (Best != null && Best.IsBetterThan(plan))
{
if (plan.Valid)
CandidateProgress.ReportAlternative(plan.Result, inner);
return;
}
Best = plan;
inner?.Report(value);
}
@@ -188,11 +188,16 @@ public sealed class DefaultNestingEngine : INestingEngine
Offer(plan);
}
/// <summary>Reports the plan when it beats every plan reported so far.</summary>
/// <summary>Reports the plan when it beats every plan reported so far; a valid plan that
/// does not is reported as an alternative.</summary>
public void Offer(CandidateScore plan)
{
if (shown != null && !plan.IsBetterThan(shown))
{
if (plan.Valid && !CandidateProgress.SameLayout(plan.Result, shown.Result))
CandidateProgress.ReportAlternative(plan.Result, inner);
return;
}
shown = plan;
CandidateProgress.ReportPlan(plan.Result, inner);
}
@@ -129,6 +129,8 @@ public sealed class IrregularNestingEngine : INestingEngine
best = plan;
ReportPlan(job, types, best, progress, token);
}
else
ReportAlternative(job, types, plan, progress, token);
if (best.Unplaced == 0 && best.Sheets.Count == 0)
break;
}
@@ -151,7 +153,10 @@ public sealed class IrregularNestingEngine : INestingEngine
break;
var plan = solver.Plan(demand, axis, 1.0, grouped: true);
if (!plan.IsBetterThan(improved))
{
ReportAlternative(job, types, plan, progress, token);
continue;
}
ReportPlan(job, types, plan, progress, token);
improved = solver.ImproveTail(plan, solver.Work.Value + WorkBudget * 2);
if (!ReferenceEquals(improved, plan))
@@ -173,6 +178,8 @@ public sealed class IrregularNestingEngine : INestingEngine
if (!ReferenceEquals(improved, plan))
ReportPlan(job, types, improved, progress, token);
}
else
ReportAlternative(job, types, plan, progress, token);
}
// Then try to drop a sheet: split the parts over one sheet fewer and pack each sheet edge
// first, the key part turned by its contacts. Replaces the result only by beating it.
@@ -249,6 +256,16 @@ public sealed class IrregularNestingEngine : INestingEngine
CandidateProgress.ReportPlan(BuildResult(job, types, plan, null, token), progress);
}
/// <summary>Reports a whole-job plan that lost to the best so far, as another layout a front
/// end may offer; reporting never changes the search.</summary>
private static void ReportAlternative(NestJob job, IReadOnlyList<PartType> types, Plan plan,
IProgress<NestJobProgress>? progress, CancellationToken token)
{
if (progress == null || plan.Sheets.Count == 0)
return;
CandidateProgress.ReportAlternative(BuildResult(job, types, plan, null, token), progress);
}
/// <summary>Exercises the production physical-tail lifecycle from a test-owned incumbent.
/// This does not alter normal Solve or expose a public packing API.</summary>
internal NestJobResult ImproveTailForTesting(NestJob job, IReadOnlyList<SheetFill> physicalPlan)
+2 -1
View File
@@ -18,7 +18,8 @@ public sealed class NestJobReporter : IProgress<NestJobProgress>
public void Report(NestJobProgress value)
{
if (value is null)
// Alternative plans stay on the worker: the job stores only its best plan.
if (value is null || value.Stage == NestJobStage.PlanAlternative)
return;
// Copied here, on the engine's thread, so later changes to its objects cannot leak in;
// serialized later, off that thread.
@@ -0,0 +1,154 @@
using System.Windows.Forms;
using OpenNest.CNC;
using OpenNest.Controls;
using OpenNest.Engine.Jobs;
using OpenNest.Forms;
using OpenNest.Geometry;
namespace OpenNest.WinForms.Tests.Forms;
// The picks read here have already completed on this STA thread; nothing blocks.
#pragma warning disable xUnit1031
/// <summary>
/// The Auto Nest progress window's top layouts: one card per layout with its sheets, and the
/// pick of the layout to use, during the run and once it has finished.
/// </summary>
public class NestProgressFormLayoutsTests
{
private static readonly Drawing Bracket = new("bracket", Rectangle());
private static readonly NestPlateStock Stock = new("sheet", new Size(48, 96), quantity: null, partSpacing: 0.25);
private static Program Rectangle()
{
var program = new Program();
program.MoveTo(0, 0);
program.LineTo(10, 0);
program.LineTo(10, 20);
program.LineTo(0, 20);
program.LineTo(0, 0);
return program;
}
private static NestLayoutChoice Layout(params (double X, double Y)[] at)
{
var parts = at.Select(p =>
{
var part = new Part(Bracket) { Location = new Vector(p.X, p.Y) };
part.UpdateBounds();
return part;
}).ToList();
return new NestLayoutChoice(new[] { new ProposedPlate(0, Stock, parts) }, _ => null!);
}
private static NestLayoutChoice Columns() => Layout((0, 0), (0, 28), (10, 0));
private static NestLayoutChoice Row() => Layout((0, 0), (40, 0), (86, 0));
private static void WithForm(Action<NestProgressForm, CancellationTokenSource, Func<bool>> test) => StaTestThread.Run(() =>
{
using var cts = new CancellationTokenSource();
var stopped = false;
using var form = new NestProgressForm(cts) { AllowAccept = false, HoldOpenUntilCompleted = true };
form.ShowPlanStrip(new ColorScheme(), () => stopped = true);
form.Show();
try
{
test(form, cts, () => stopped);
}
finally
{
form.ShowCompleted();
form.Close();
}
}, TimeSpan.FromSeconds(30), "The STA test did not complete.");
private static Button Button(Form form, string name) =>
Assert.IsType<Button>(form.Controls.Find(name, true).Single());
private static LayoutChoiceList List(Control parent) =>
Descendants(parent).OfType<LayoutChoiceList>().Single();
private static IEnumerable<Control> Descendants(Control parent) =>
parent.Controls.Cast<Control>().SelectMany(c => Descendants(c).Prepend(c));
[Fact]
public void EachLayoutGetsACardAndTheBestIsSelected() => WithForm((form, _, _) =>
{
var use = Button(form, "useLayoutButton");
Assert.False(use.Enabled);
var columns = Columns();
var row = Row();
form.AddLayout(columns, best: true);
form.AddLayout(row, best: false);
Assert.Equal(new[] { columns, row }, form.Layouts);
Assert.Equal(2, Descendants(form).OfType<SheetStripControl>().Count());
Assert.Same(columns, List(form).Selected);
Assert.True(use.Enabled);
Assert.Contains("76 to right edge", columns.Summary);
Assert.Contains("28 to top", row.Summary);
});
[Fact]
public void UsingALayoutDuringTheRunStopsTheSearchOnly() => WithForm((form, cts, stopped) =>
{
var row = Row();
form.AddLayout(Columns(), best: true);
form.AddLayout(row, best: false);
List(form).Pick(row);
Button(form, "useLayoutButton").PerformClick();
Assert.True(stopped());
Assert.False(cts.IsCancellationRequested);
Assert.Same(row, form.ChosenLayout);
// Already chosen: the finished search does not ask again.
Assert.True(form.ChooseLayoutAsync(Columns()).Result);
Assert.Same(row, form.ChosenLayout);
});
[Fact]
public void AFinishedSearchWaitsForThePickAmongItsLayouts() => WithForm((form, cts, stopped) =>
{
form.AddLayout(Columns(), best: true);
form.AddLayout(Row(), best: false);
var final = Columns();
var pick = form.ChooseLayoutAsync(final);
Assert.False(pick.IsCompleted);
Assert.Equal("Discard", Button(form, "stopButton").Text);
Assert.Same(final, List(form).Selected);
Button(form, "useLayoutButton").PerformClick();
Assert.True(pick.Result);
Assert.Same(final, form.ChosenLayout);
Assert.False(stopped());
Assert.False(cts.IsCancellationRequested);
});
[Fact]
public void DiscardAfterTheSearchChoosesNothing() => WithForm((form, cts, _) =>
{
form.AddLayout(Columns(), best: true);
form.AddLayout(Row(), best: false);
var pick = form.ChooseLayoutAsync(Columns());
Button(form, "stopButton").PerformClick();
Assert.False(pick.Result);
Assert.Null(form.ChosenLayout);
Assert.False(cts.IsCancellationRequested);
});
[Fact]
public void AFinishedSearchWithOneLayoutDoesNotAsk() => WithForm((form, _, _) =>
{
form.AddLayout(Columns(), best: true);
var final = Columns();
Assert.True(form.ChooseLayoutAsync(final).Result);
Assert.Same(final, form.ChosenLayout);
});
}
+229
View File
@@ -0,0 +1,229 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using OpenNest.Forms;
namespace OpenNest.Controls
{
/// <summary>
/// Whole-job layouts stacked as cards, the best first: each a summary line over its sheets,
/// with every sheet's free strip dimensioned. One card is selected: the best, until the user
/// clicks another. Read-only like the sheet strips it holds.
/// </summary>
internal sealed class LayoutChoiceList : Panel
{
private const int Gap = 8;
private static readonly Color Accent = Color.FromArgb(0, 120, 215);
private static readonly Color Border = Color.FromArgb(200, 200, 200);
private readonly List<Card> cards = new();
private IReadOnlyList<NestLayoutChoice> choices = Array.Empty<NestLayoutChoice>();
private NestLayoutChoice pinned;
private NestLayoutChoice selected;
private bool firstIsBest;
private bool allowSelection;
private string bestLabel = "Best so far";
private ColorScheme colorScheme = ColorScheme.Default;
public LayoutChoiceList()
{
SetStyle(ControlStyles.ResizeRedraw | ControlStyles.OptimizedDoubleBuffer, true);
Padding = new Padding(Gap);
}
public ColorScheme ColorScheme
{
get => colorScheme;
set
{
colorScheme = value ?? ColorScheme.Default;
foreach (var card in cards)
card.Strip.ColorScheme = colorScheme;
}
}
/// <summary>The text shown when there are no layouts.</summary>
public string EmptyText { get; set; } = "No layouts yet";
/// <summary>How the first card is titled while it is the engine's best.</summary>
public string BestLabel
{
get => bestLabel;
set
{
bestLabel = value;
Refill();
}
}
/// <summary>Whether clicking a card selects it; without it the list only shows.</summary>
public bool AllowSelection
{
get => allowSelection;
set
{
allowSelection = value;
Refill();
}
}
/// <summary>The selected layout: the one the user clicked while it is still offered,
/// otherwise the first. Null with no layouts.</summary>
public NestLayoutChoice Selected => selected;
public IReadOnlyList<NestLayoutChoice> Choices => choices;
public event EventHandler SelectionChanged;
/// <summary>A card was double-clicked: use its layout.</summary>
public event EventHandler ChoiceActivated;
/// <summary>Shows <paramref name="top"/>, best first. <paramref name="firstIsBest"/> titles
/// the first card as the engine's best.</summary>
public void SetChoices(IReadOnlyList<NestLayoutChoice> top, bool firstIsBest = true)
{
choices = top ?? Array.Empty<NestLayoutChoice>();
this.firstIsBest = firstIsBest;
if (pinned != null && !choices.Contains(pinned))
pinned = null;
Refill();
}
/// <summary>Selects <paramref name="choice"/> as a click on its card does.</summary>
public void Pick(NestLayoutChoice choice)
{
if (!allowSelection || !choices.Contains(choice))
return;
pinned = choice;
Refill();
}
private void Refill()
{
SuspendLayout();
while (cards.Count > choices.Count)
{
var last = cards[^1];
cards.RemoveAt(cards.Count - 1);
Controls.Remove(last);
last.Dispose();
}
while (cards.Count < choices.Count)
{
var card = new Card(this) { Font = Font };
card.Strip.ColorScheme = colorScheme;
cards.Add(card);
Controls.Add(card);
}
var now = pinned ?? choices.FirstOrDefault();
for (var i = 0; i < cards.Count; i++)
{
var title = i == 0 && firstIsBest ? bestLabel : $"Alternative {(firstIsBest ? i : i + 1)}";
cards[i].Fill(choices[i], title, allowSelection, ReferenceEquals(choices[i], now));
}
Arrange();
ResumeLayout();
Invalidate();
if (!ReferenceEquals(now, selected))
{
selected = now;
SelectionChanged?.Invoke(this, EventArgs.Empty);
}
}
protected override void OnResize(EventArgs e)
{
base.OnResize(e);
Arrange();
}
/// <summary>Cards share the height equally.</summary>
private void Arrange()
{
if (cards.Count == 0)
return;
var area = DisplayRectangle;
var height = System.Math.Max(40, (area.Height - Gap * (cards.Count - 1)) / cards.Count);
for (var i = 0; i < cards.Count; i++)
cards[i].Bounds = new Rectangle(area.Left, area.Top + i * (height + Gap), area.Width, height);
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
if (cards.Count == 0)
TextRenderer.DrawText(e.Graphics, EmptyText, Font, ClientRectangle, ForeColor,
TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter);
}
private void Clicked(Card card, bool activate)
{
if (!allowSelection)
return;
Pick(card.Choice);
if (activate)
ChoiceActivated?.Invoke(this, EventArgs.Empty);
}
/// <summary>One layout: a frame (accented when selected) around its title and sheets.</summary>
private sealed class Card : Panel
{
private readonly Label header;
private Font bold;
public Card(LayoutChoiceList owner)
{
Padding = new Padding(2);
BackColor = Border;
Strip = new SheetStripControl { Dock = DockStyle.Fill, ShowRemnant = true };
header = new Label
{
Dock = DockStyle.Top,
AutoSize = false,
AutoEllipsis = true,
Height = 28,
Padding = new Padding(8, 0, 8, 0),
TextAlign = ContentAlignment.MiddleLeft,
BackColor = Color.White,
};
Controls.Add(Strip);
Controls.Add(header);
foreach (var control in new Control[] { this, header, Strip })
{
control.Click += (s, e) => owner.Clicked(this, activate: false);
control.DoubleClick += (s, e) => owner.Clicked(this, activate: true);
}
}
public SheetStripControl Strip { get; }
protected override void Dispose(bool disposing)
{
if (disposing)
bold?.Dispose();
base.Dispose(disposing);
}
public NestLayoutChoice Choice { get; private set; }
public void Fill(NestLayoutChoice choice, string title, bool selectable, bool isSelected)
{
if (!ReferenceEquals(choice, Choice))
{
Choice = choice;
Strip.SetSheets(choice.Sheets);
}
var marked = selectable && isSelected;
var mark = !selectable ? "" : isSelected ? "● " : "○ ";
header.Text = $"{mark}{title} · {choice.Summary}";
header.Font = marked ? bold ??= new Font(Font, FontStyle.Bold) : Font;
header.ForeColor = marked ? Accent : Color.FromArgb(51, 51, 51);
BackColor = marked ? Accent : Border;
Cursor = header.Cursor = Strip.Cursor = selectable ? Cursors.Hand : Cursors.Default;
}
}
}
}
+59 -3
View File
@@ -5,6 +5,7 @@ using System.Drawing.Drawing2D;
using System.Linq;
using System.Windows.Forms;
using OpenNest.Engine.Jobs;
using OpenNest.Forms;
namespace OpenNest.Controls
{
@@ -20,6 +21,7 @@ namespace OpenNest.Controls
private readonly List<Tile> tiles = new();
private ColorScheme colorScheme = ColorScheme.Default;
private bool showRemnant;
public SheetStripControl()
{
@@ -43,6 +45,21 @@ namespace OpenNest.Controls
/// <summary>The text shown when there are no sheets.</summary>
public string EmptyText { get; set; } = "No sheets yet";
/// <summary>
/// Shows each sheet's free strip: a dimension across it and its distance in the caption
/// (to the right edge for vertical strips, to the top for horizontal ones).
/// </summary>
public bool ShowRemnant
{
get => showRemnant;
set
{
showRemnant = value;
UpdateScrollSize();
Invalidate();
}
}
public int SheetCount => tiles.Sum(t => t.Quantity);
/// <summary>Material area over sheet area for every physical sheet; 0 with no sheets.</summary>
@@ -90,7 +107,11 @@ namespace OpenNest.Controls
tiles.Clear();
}
private int CaptionHeight => Font.Height * 2 + 4;
private int CaptionHeight => Font.Height * (showRemnant ? 3 : 2) + 4;
private string Caption(Tile tile) => showRemnant && tile.Remnant is { } remnant
? $"{tile.Title}\n{tile.Detail}\n{remnant}"
: $"{tile.Title}\n{tile.Detail}";
/// <summary>
/// Pixels per world unit, shared by every sheet. All sheets fit the width when they can;
@@ -130,7 +151,7 @@ namespace OpenNest.Controls
}
private int TileWidth(Tile tile, float scale) =>
System.Math.Max((int)System.Math.Ceiling(tile.Sheet.Length * scale), TextRenderer.MeasureText(tile.Detail, Font).Width);
System.Math.Max((int)System.Math.Ceiling(tile.Sheet.Length * scale), TextRenderer.MeasureText(Caption(tile), Font).Width);
protected override void OnPaint(PaintEventArgs e)
{
@@ -158,6 +179,12 @@ namespace OpenNest.Controls
using var obstacleBrush = new HatchBrush(HatchStyle.WideUpwardDiagonal,
Color.FromArgb(170, 120, 60, 60), Color.FromArgb(60, 200, 80, 80));
using var obstaclePen = new Pen(Color.FromArgb(170, 120, 60, 60), 1.5f);
using var remnantCap = new AdjustableArrowCap(3, 4);
using var remnantPen = new Pen(Color.FromArgb(20, 100, 190), 1.5f)
{
CustomStartCap = remnantCap,
CustomEndCap = remnantCap,
};
foreach (var tile in tiles)
{
var width = TileWidth(tile, scale);
@@ -205,8 +232,16 @@ namespace OpenNest.Controls
g.DrawPath(colorScheme.Gdi().LayoutOutlinePen, outline);
else
g.DrawRectangle(colorScheme.Gdi().LayoutOutlinePen, sheetRect.X, sheetRect.Y, sheetRect.Width, sheetRect.Height);
if (showRemnant && tile.Remnant != null)
{
// Device space, so the arrows keep their pixel size.
var ends = (PointF[])tile.RemnantSpan.Clone();
toDevice.TransformPoints(ends);
if (System.Math.Abs(ends[1].X - ends[0].X) + System.Math.Abs(ends[1].Y - ends[0].Y) >= 14)
g.DrawLine(remnantPen, ends[0], ends[1]);
}
var caption = new Rectangle(x, (int)baseline + 4, width, CaptionHeight);
TextRenderer.DrawText(g, tile.Title + "\n" + tile.Detail, Font, caption, ForeColor,
TextRenderer.DrawText(g, Caption(tile), Font, caption, ForeColor,
TextFormatFlags.HorizontalCenter | TextFormatFlags.Top);
x += width + Gap;
}
@@ -261,6 +296,21 @@ namespace OpenNest.Controls
Parts.Add((part.Program.GetFillPath(part.Location), new SolidBrush(Color.FromArgb(200, color))));
}
Remnant = SheetRemnant.Of(plate);
if (Remnant is { } remnant)
{
// Across the free strip, through the sheet's middle.
var (midX, midY) = ((float)(x + length / 2), (float)(y + width / 2));
var distance = (float)remnant.Distance;
RemnantSpan = remnant.Edge switch
{
SheetEdge.Right => new[] { new PointF((float)(x + length) - distance, midY), new PointF((float)(x + length), midY) },
SheetEdge.Left => new[] { new PointF((float)x, midY), new PointF((float)x + distance, midY) },
SheetEdge.Top => new[] { new PointF(midX, (float)(y + width) - distance), new PointF(midX, (float)(y + width)) },
_ => new[] { new PointF(midX, (float)y), new PointF(midX, (float)y + distance) },
};
}
Title = Quantity == 1 ? $"Sheet {firstNumber}" : $"Sheets {firstNumber}–{firstNumber + Quantity - 1} (×{Quantity})";
var utilization = SheetArea > 0 ? PartArea / SheetArea : 0;
Detail = $"{stock.Size} · {PartCount} parts · {utilization:P0}";
@@ -281,6 +331,12 @@ namespace OpenNest.Controls
public double PartArea { get; }
public string Title { get; }
public string Detail { get; }
/// <summary>The sheet's free strip; null when it has none to measure.</summary>
public SheetRemnant? Remnant { get; }
/// <summary>The two world points the free strip's dimension runs between.</summary>
public PointF[] RemnantSpan { get; }
public List<RectangleF> Clamps { get; } = new();
public List<(GraphicsPath Path, Brush Brush)> Parts { get; } = new();
+32 -8
View File
@@ -128,7 +128,7 @@ namespace OpenNest.Forms.Commands
}
else
{
result = await SolveAsync(owner, target, request, cts);
result = await SolveAsync(owner, target, request, cts, chooseLayout: true);
}
cts.Token.ThrowIfCancellationRequested();
@@ -226,34 +226,58 @@ namespace OpenNest.Forms.Commands
/// <paramref name="cts"/>. Nothing is committed: the caller keeps or discards the result.
/// Make Nests uses it too, to nest each released nest in its tab as Auto Nest would.
/// </summary>
/// <param name="chooseLayout">Lets the user use any of the top layouts shown: one picked
/// during the run stops the search, and a finished run with more than one waits for the
/// pick. The layout used is validated and bound like the engine's own result. Off, the
/// engine's result is returned as soon as it is known.</param>
internal static async Task<NestPipelineResult> SolveAsync(IWin32Window owner, EditNestForm target,
NestPipelineRequest request, CancellationTokenSource cts)
NestPipelineRequest request, CancellationTokenSource cts, bool chooseLayout = false)
{
using var progressForm = new NestProgressForm(cts, showPlateRow: true)
{
AllowAccept = false,
HoldOpenUntilCompleted = true,
};
progressForm.ShowPlanStrip(target.PlateView.ColorScheme);
// Using a layout stops the search only; the caller's source still discards everything.
using var search = CancellationTokenSource.CreateLinkedTokenSource(cts.Token);
progressForm.ShowPlanStrip(target.PlateView.ColorScheme, chooseLayout ? search.Cancel : null);
var receivingProgress = true;
bool Receiving() => receivingProgress && !target.IsDisposed && !cts.IsCancellationRequested;
bool Receiving() => receivingProgress && !target.IsDisposed && !search.IsCancellationRequested;
var progress = new Progress<NestProgress>(p =>
{
if (Receiving())
progressForm.UpdateProgress(p);
});
var plans = new Progress<IReadOnlyList<ProposedPlate>>(sheets =>
var layouts = new Progress<NestLayoutReport>(report =>
{
if (Receiving())
progressForm.UpdatePlan(sheets);
progressForm.AddLayout(report.Layout, report.Best);
});
var jobProgress = JobEngineNest.CreateProgress(request.EngineName, progress, plans);
var jobProgress = JobEngineNest.CreateLayoutProgress(request.EngineName, progress, layouts);
async Task<NestPipelineResult> RunSolveAsync()
{
try
{
return await Task.Run(() => NestPipeline.Run(request, jobProgress, cts.Token));
NestPipelineResult result = null;
try
{
result = await Task.Run(() => NestPipeline.Run(request, jobProgress, search.Token));
}
catch (OperationCanceledException)
when (progressForm.ChosenLayout != null && !cts.IsCancellationRequested)
{
// The user stopped the search to use a layout it had already found.
}
receivingProgress = false;
if (result != null
&& !await progressForm.ChooseLayoutAsync(new NestLayoutChoice(result.Plates, _ => result)))
{
cts.Cancel();
throw new OperationCanceledException(cts.Token);
}
var chosen = progressForm.ChosenLayout;
return chosen == null ? result : await Task.Run(() => chosen.Accept(cts.Token));
}
finally
{
+1 -1
View File
@@ -57,7 +57,7 @@ namespace OpenNest.Forms.Commands
$"The nest server could not take this nest:\n\n{ex.Message}\n\nNest on this PC instead?",
Caption, MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (choice == DialogResult.Yes)
return (await AutoNestCommand.SolveAsync(owner, target, request, cts), null);
return (await AutoNestCommand.SolveAsync(owner, target, request, cts, chooseLayout: true), null);
cts.Cancel();
throw new OperationCanceledException(cts.Token);
}
+168 -29
View File
@@ -4,6 +4,7 @@ using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using OpenNest.Engine;
@@ -87,7 +88,7 @@ namespace OpenNest.Forms
SetValueWithFlash(plateValue, progress.PlateNumber.ToString());
// In plan mode the results rows describe the whole-job plan, not a part preview.
if (progress.IsOverallBest && planStrip == null)
if (progress.IsOverallBest && layoutList == null)
{
SetValueWithFlash(partsValue, progress.BestPartCount.ToString());
@@ -107,54 +108,179 @@ namespace OpenNest.Forms
: progress.Phase.DisplayName();
}
private Controls.SheetStripControl planStrip;
private Controls.LayoutChoiceList layoutList;
private NestLayoutChoices layouts;
private Button useLayoutButton;
private Action stopSearch;
private TaskCompletionSource<bool> choice;
/// <summary>
/// Adds the "best plan so far" sheet strip for whole-job runs, whose result is a set of
/// sheets rather than parts on the current plate. The results rows then describe that plan.
/// Switches the window to whole-job layouts: the run's top layouts as cards, the best
/// first, each with its sheets and the free strip its last sheet leaves, over a status
/// line. A whole-job result is a set of sheets rather than parts on the current plate.
/// With <paramref name="stopSearch"/> the user may pick a card and use that layout: during
/// the run it stops the search (<paramref name="stopSearch"/>), and afterwards
/// <see cref="ChooseLayoutAsync"/> waits for the pick. Without it the cards only show.
/// </summary>
public void ShowPlanStrip(ColorScheme colorScheme)
public void ShowPlanStrip(ColorScheme colorScheme, Action stopSearch = null)
{
if (planStrip != null)
if (layoutList != null)
return;
this.stopSearch = stopSearch;
layouts = new NestLayoutChoices();
var choosing = stopSearch != null;
SuspendLayout();
Controls.Remove(statsPanel);
var header = new Label
{
Dock = DockStyle.Top,
AutoSize = true,
Font = resultsHeader.Font,
ForeColor = resultsHeader.ForeColor,
Padding = new Padding(14, 8, 0, 4),
Text = "BEST PLAN SO FAR",
Padding = new Padding(10, 8, 0, 0),
Text = choosing ? "TOP LAYOUTS" : "BEST PLAN SO FAR",
};
planStrip = new Controls.SheetStripControl
layoutList = new Controls.LayoutChoiceList
{
Dock = DockStyle.Fill,
ColorScheme = colorScheme,
AllowSelection = choosing,
EmptyText = "Waiting for the first complete plan…",
};
var panel = new Panel { Dock = DockStyle.Right, Width = 520 };
panel.Controls.Add(planStrip);
panel.Controls.Add(header);
Controls.Add(panel);
nestedAreaLabel.Text = "Sheets:";
densityLabel.Text = "Utilization:";
// Read the size first: raising the minimum would otherwise widen the form twice.
var client = ClientSize;
MinimumSize = new System.Drawing.Size(MinimumSize.Width + panel.Width, MinimumSize.Height);
ClientSize = new System.Drawing.Size(client.Width + panel.Width, client.Height);
// Status and buttons share one line: the detail text gets the whole width.
var footer = new TableLayoutPanel
{
Dock = DockStyle.Bottom,
AutoSize = true,
BackColor = Color.White,
ColumnCount = 4,
RowCount = 1,
Padding = new Padding(10, 2, 0, 2),
};
footer.ColumnStyles.Add(new ColumnStyle());
footer.ColumnStyles.Add(new ColumnStyle());
footer.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100));
footer.ColumnStyles.Add(new ColumnStyle());
elapsedLabel.Anchor = elapsedValue.Anchor = AnchorStyles.Left;
elapsedValue.Margin = new Padding(0, 3, 12, 3);
descriptionValue.AutoSize = false;
descriptionValue.AutoEllipsis = true;
descriptionValue.Dock = DockStyle.Fill;
descriptionValue.TextAlign = ContentAlignment.MiddleLeft;
buttonPanel.Dock = DockStyle.None;
buttonPanel.Anchor = AnchorStyles.Right;
buttonPanel.WrapContents = false;
if (choosing)
{
useLayoutButton = new Button
{
Name = "useLayoutButton",
Enabled = false,
Font = stopButton.Font,
Margin = new Padding(0, 3, 6, 3),
Size = new System.Drawing.Size(132, 27),
Text = "Use This Layout",
UseVisualStyleBackColor = true,
};
useLayoutButton.Click += (s, e) => UseSelectedLayout();
buttonPanel.Controls.Add(useLayoutButton);
layoutList.SelectionChanged += (s, e) => UpdateUseLayout();
layoutList.ChoiceActivated += (s, e) => UseSelectedLayout();
}
footer.Controls.Add(elapsedLabel, 0, 0);
footer.Controls.Add(elapsedValue, 1, 0);
footer.Controls.Add(descriptionValue, 2, 0);
footer.Controls.Add(buttonPanel, 3, 0);
Controls.Add(layoutList);
Controls.Add(header);
Controls.Add(footer);
MinimumSize = new System.Drawing.Size(640, 420);
ClientSize = new System.Drawing.Size(920, 600);
ResumeLayout(true);
}
/// <summary>Shows a whole-job plan in the strip added by <see cref="ShowPlanStrip"/>.</summary>
public void UpdatePlan(IReadOnlyList<Engine.Jobs.ProposedPlate> sheets)
/// <summary>The layouts offered now, best first; empty outside plan mode.</summary>
internal IReadOnlyList<NestLayoutChoice> Layouts => layouts?.Top ?? Array.Empty<NestLayoutChoice>();
/// <summary>The layout the user chose to use; null when none was chosen.</summary>
internal NestLayoutChoice ChosenLayout { get; private set; }
/// <summary>
/// Adds a layout from the running solve to the cards added by <see cref="ShowPlanStrip"/>;
/// <paramref name="best"/> marks the engine's best so far.
/// </summary>
internal void AddLayout(NestLayoutChoice layout, bool best)
{
if (planStrip == null || IsDisposed || !IsHandleCreated)
if (layoutList == null || IsDisposed || !IsHandleCreated)
return;
planStrip.SetSheets(sheets);
SetValueWithFlash(partsValue, planStrip.PartCount.ToString());
var utilization = planStrip.Utilization;
SetValueWithFlash(densityValue, utilization.ToString("P1"), GetDensityColor(utilization));
densityBar.Value = utilization;
SetValueWithFlash(nestedAreaValue, planStrip.SheetCount.ToString());
if (layouts.Add(layout, best))
layoutList.SetChoices(layouts.Top, ReferenceEquals(layouts.Top[0], layouts.Best));
}
/// <summary>Shows a whole-job plan as the best layout so far.</summary>
public void UpdatePlan(IReadOnlyList<Engine.Jobs.ProposedPlate> sheets) =>
AddLayout(new NestLayoutChoice(sheets), best: true);
/// <summary>
/// The search is over and <paramref name="final"/> is its result: with other layouts to
/// pick from, waits until the user uses one (true, in <see cref="ChosenLayout"/>) or
/// discards them all (false). With nothing to pick from, or a layout already chosen
/// during the run, returns at once.
/// </summary>
internal Task<bool> ChooseLayoutAsync(NestLayoutChoice final)
{
if (ChosenLayout != null)
return Task.FromResult(true);
if (layoutList == null || useLayoutButton == null || IsDisposed || !Visible)
{
ChosenLayout = final;
return Task.FromResult(true);
}
AddLayout(final, best: true);
if (layouts.Top.Count < 2)
{
ChosenLayout = final;
return Task.FromResult(true);
}
choice = new TaskCompletionSource<bool>();
stopwatch.Stop();
elapsedTimer.Stop();
UpdateElapsed();
Text = "Nesting Finished";
layoutList.BestLabel = "Best";
descriptionValue.Text = "Search finished. Pick the layout to use.";
stopButton.Text = "Discard";
stopButton.Enabled = true;
UpdateUseLayout();
return choice.Task;
}
private void UpdateUseLayout()
{
if (useLayoutButton != null && ChosenLayout == null)
useLayoutButton.Enabled = layoutList.Selected?.Accept != null;
}
private void UseSelectedLayout()
{
if (useLayoutButton == null || ChosenLayout != null || layoutList.Selected?.Accept == null)
return;
ChosenLayout = layoutList.Selected;
layoutList.AllowSelection = false;
useLayoutButton.Enabled = false;
stopButton.Enabled = false;
if (choice != null)
{
choice.TrySetResult(true);
return;
}
// Still searching: stop, then the caller validates the chosen layout.
useLayoutButton.Text = "Stopping...";
stopSearch();
}
public void ShowCompleted()
@@ -201,6 +327,15 @@ namespace OpenNest.Forms
private void StopButton_Click(object sender, EventArgs e)
{
if (choice != null)
{
// The search is over: this is Discard.
stopButton.Enabled = false;
choice.TrySetResult(false);
return;
}
if (useLayoutButton != null)
useLayoutButton.Enabled = false;
cts.Cancel();
acceptButton.Enabled = false;
stopButton.Enabled = false;
@@ -211,7 +346,11 @@ namespace OpenNest.Forms
{
if (HoldOpenUntilCompleted && !completed)
{
cts.Cancel();
// Closing while picking a layout discards them all, as Discard does.
if (choice != null)
choice.TrySetResult(false);
else
cts.Cancel();
e.Cancel = true;
return;
}
+1 -1
View File
@@ -24,7 +24,7 @@ namespace OpenNest.Forms
MinimumSize = new Size(560, 360);
Font = new Font("Segoe UI", 9.75F);
var strip = new SheetStripControl { Dock = DockStyle.Fill, ColorScheme = colorScheme };
var strip = new SheetStripControl { Dock = DockStyle.Fill, ColorScheme = colorScheme, ShowRemnant = true };
strip.SetSheets(result.Plates);
Strip = strip;
+6 -3
View File
@@ -26,9 +26,11 @@ Every engine selected in **Nest > Auto Nest** uses the pipeline. Part-First and
Auto Nest starts on empty/new sheets and does not change existing populated plates. Stock Options offers sheet sizes and salvage settings; minimum salvage size is part of that section, not a Part-First option. When enabled, its grid keeps a blank last row for adding another size (`W x L`) and cost, including after loading saved options. Unused blank rows are not offered as stock. The maximum remains 100 physical sheets per run.
Progress is owned and modal so the input drawings cannot be edited while a worker uses them. Stop or closing progress cancels and discards the whole proposal. The dialog waits for the worker to finish; no engine has an Accept-early button on this path. A plug-in that ignores the cancellation token cannot commit its late result.
Progress is owned and modal so the input drawings cannot be edited while a worker uses them. Stop or closing progress cancels and discards the whole proposal. The dialog waits for the worker to finish. **Use This Layout** (below) is the only way to end the search early with something to keep, and what it keeps is validated like any result. A plug-in that ignores the cancellation token cannot commit its late result.
Auto Nest never draws its parts on the plate view before they are kept: its result is a set of sheets, possibly of several sizes, not parts on the current plate. Ghost (preview) parts on the plate view mean only "what this plate gets if you accept now", and stay with interactive Fill and the remnant tools. Instead the progress window shows **Best plan so far**: every sheet of the engine's best whole-job plan drawn side by side at one scale, identical sheets once with their count, each captioned with size, part count and utilization. An engine reports a plan with `NestJobStage.PlanImproved` and `NestJobProgress.Plan`; `NestPipeline` adds `PlanSheets`, parts on detached drawings built from the job geometry, so nothing touches the caller's drawings or quantities. The plan is unvalidated and may be replaced. Default, Irregular, Rectangles and Circles report plans (see [nesting engines](nesting-engines.md#best-plan-so-far)); FlatBar, the fixed-strategy engines and plug-ins that report none show the strip empty until the review.
Auto Nest never draws its parts on the plate view before they are kept: its result is a set of sheets, possibly of several sizes, not parts on the current plate. Ghost (preview) parts on the plate view mean only "what this plate gets if you accept now", and stay with interactive Fill and the remnant tools. Instead the progress window shows **Top layouts**: up to three whole-job layouts as cards, the engine's best so far first. A card draws every sheet of its layout side by side at one scale, identical sheets once with their count, each captioned with size, part count, utilization and its free strip, which is also dimensioned on the sheet: the distance from the parts to the right edge when they were packed in vertical strips, or to the top for horizontal strips (the left edge or the bottom in the quadrants whose origin is on the other side; whichever strip has more area is the one shown, and an outlined sheet shows none). The card's title line totals the layout and gives the last sheet's free strip, the usable drop. An engine reports a plan with `NestJobStage.PlanImproved` and `NestJobProgress.Plan`; `NestPipeline` adds `PlanSheets`, parts on detached drawings built from the job geometry, so nothing touches the caller's drawings or quantities. The plan is unvalidated and may be replaced. An engine may also report plans that lost to its best (`NestJobStage.PlanAlternative`); the window keeps the best layout of each family (sheet count and free-strip direction) other than the best's, so the cards are real alternatives, such as the same job packed toward the left edge and toward the bottom, not near copies. Default, Irregular, Rectangles and Circles report plans (see [nesting engines](nesting-engines.md#best-plan-so-far)); FlatBar, the fixed-strategy engines and plug-ins that report none show the strip empty until the review.
Any card can be used. Click a card to select it (the best stays selected until you do) and choose **Use This Layout**, or double-click the card: during the search this stops it; when the search finishes with more than one layout the window stays open, titled **Nesting Finished**, until a layout is used or **Discard** drops them all. A search that ends with a single layout goes straight to the review, as do Make Nests runs, which always take the engine's result. The layout used goes through the same validation and binding as the engine's result (`NestJobProgress.AcceptPlan`), so a layout that breaks a rule shows the validation report below; last-resort clamp removal applies only to the engine's own result.
After a valid result, or an invalid one kept in the validation report, a review window shows the final sheets in the same strip with totals, the supplied-cost summary and every unplaced drawing, count and reason. **Keep** (Enter) commits the whole proposal; **Discard** (Escape) applies nothing.
@@ -53,7 +55,8 @@ Unplaced demand is never dropped silently. `NestPipelineResult.Unplaced` lists e
An incomplete but valid proposal is keepable like any other; keeping it is still an explicit action. Desktop Auto Nest lists each unplaced drawing, count and reason in its review before committing (the drawing list keeps showing remaining quantities); Console `--autonest` writes `Unplaced:` lines to standard error; MCP `autonest_plate` adds `Unplaced:` lines and `autonest_job` names the reasons when it refuses an incomplete proposal; the API returns `NestResponse.Unplaced` by request part ID. This check does not replace pre-post CNC verification.
In Database mode, **Nest on the server** sends the job to the nest server's worker instead;
the progress window shows the worker's best plan so far, and the review and Keep are
the progress window shows the worker's best plan so far as its one layout (alternatives
stay on the worker, and there is nothing to pick), and the review and Keep are
unchanged. Results can be reopened later from **Nest > My Server Jobs**. See [server nesting](server-nesting.md).
The selected engine is saved in `%APPDATA%\OpenNest\engine-selection.json`.
+8
View File
@@ -96,6 +96,14 @@ progress sink.
Plug-ins may report plans the same way; FlatBar and the fixed-strategy engines do not.
An engine may also report a complete plan that lost to its best as `NestJobStage.PlanAlternative`:
another layout the desktop may offer beside the best (see [automatic nesting](automatic-nesting.md)).
Alternatives are optional, unranked and unvalidated, never the engine's result, and reporting
them never changes the search. Irregular reports the strategy, grouped and banded variants that
did not beat its best (not the seeded decodes of a search until cancelled); Default and a
time-limited solve report a valid plan or candidate result that did not beat the one shown. The
nest server's worker drops them.
### Time limits
`DeadlineNestingEngine` wraps any engine with a wall-clock limit. An engine that finishes in time
+1 -1
View File
@@ -21,7 +21,7 @@ With the box ticked, `ServerAutoNest`:
this PC instead; declining discards the run.
3. Follows the job (`NestJobWatch`) behind the same owned modal progress window a local run
uses: the queue position, then the worker's stage ("On the nest server: …"), and the
worker's **Best plan so far** in the same sheet strip a local run fills
worker's **Best plan so far** as the one layout card of the window a local run fills
(`RemoteNestPlanPreview`, below). Updates come from the job's event stream; when it drops,
the client polls once and reconnects with the last event id, and a server without the
stream is polled every two seconds throughout. Connection trouble only shows a waiting