From ce594814c67ee825d4ba949ba952c52cc38e5648 Mon Sep 17 00:00:00 2001 From: AJ Isaacs Date: Wed, 25 Nov 2026 19:56:54 -0500 Subject: [PATCH] feat(autonest): choose new plates, current plates or both Auto Nest's Plates choice lets a run use only the nest's current plates (the free space beside parts already placed, then the empty plates it was given) or current plates first and then new sheets. New plates stays the default and unchanged. The review draws parts already on a plate in one gray, and the whole proposal is kept in one undo record. Co-Authored-By: Claude Opus 5.5 --- OpenNest.Core/PlateManager.cs | 32 +- OpenNest.Desktop/Forms/NestLayoutChoices.cs | 11 +- .../Jobs/CurrentPlatesNestTests.cs | 283 ++++++++++++++++ OpenNest.Engine/Jobs/CurrentPlatesNest.cs | 311 ++++++++++++++++++ OpenNest.Engine/Jobs/NestLayoutCheck.cs | 53 ++- OpenNest.Engine/Jobs/NestPipeline.cs | 8 + OpenNest.Engine/Jobs/NestPipelineCommit.cs | 51 ++- .../Jobs/Placement/PlateFillService.cs | 14 + .../Jobs/Placement/PlateLeftoverFill.cs | 226 +++++++++++++ .../Forms/AutoNestFormPlateSourceTests.cs | 70 ++++ .../Forms/NestReviewFormTests.cs | 2 +- OpenNest/Controls/SheetStripControl.cs | 34 +- OpenNest/Forms/AutoNestForm.Designer.cs | 28 ++ OpenNest/Forms/AutoNestForm.cs | 45 ++- OpenNest/Forms/Commands/AutoNestCommand.cs | 160 +++++++++ OpenNest/Forms/NestReviewForm.cs | 28 +- docs/automatic-nesting.md | 16 +- docs/irregular-stock.md | 4 +- docs/server-nesting.md | 3 +- 19 files changed, 1327 insertions(+), 52 deletions(-) create mode 100644 OpenNest.Engine.Tests/Jobs/CurrentPlatesNestTests.cs create mode 100644 OpenNest.Engine/Jobs/CurrentPlatesNest.cs create mode 100644 OpenNest.Engine/Jobs/Placement/PlateLeftoverFill.cs create mode 100644 OpenNest.WinForms.Tests/Forms/AutoNestFormPlateSourceTests.cs diff --git a/OpenNest.Core/PlateManager.cs b/OpenNest.Core/PlateManager.cs index 5df94bb3..cb4d3600 100644 --- a/OpenNest.Core/PlateManager.cs +++ b/OpenNest.Core/PlateManager.cs @@ -123,18 +123,19 @@ namespace OpenNest } /// - /// Applies a nest-defaults edit, moving only an untouched trailing empty sheet - /// that matched the old defaults to the new defaults. + /// True when is the nest's trailing empty sheet exactly as the nest + /// defaults make it: the untouched workspace sentinel rather than stock someone set up. + /// Exact configuration equality, not geometric tolerance: even a small edit makes it + /// configured stock. /// - public void ChangePlateDefaults(Action changeDefaults) + public bool IsUntouchedSentinel(Plate plate) { - ArgumentNullException.ThrowIfNull(changeDefaults); + ArgumentNullException.ThrowIfNull(plate); + if (Count == 0 || !ReferenceEquals(nest.Plates[^1], plate)) + return false; var defaults = nest.PlateDefaults; - var trailing = Count > 0 ? nest.Plates[^1] : null; - // Exact configuration equality, not geometric tolerance: even a small edit - // makes this configured stock rather than the untouched workspace sentinel. - var followsDefaults = trailing != null - && trailing.Parts.Count == 0 + var trailing = plate; + return trailing.Parts.Count == 0 && trailing.CutOffs.Count == 0 && trailing.Outline == null && trailing.Size.Width == defaults.Size.Width @@ -150,13 +151,24 @@ namespace OpenNest && (defaults.ClampRail == null ? trailing.ClampZones.Count == 0 : defaults.ClampRail.Matches(trailing)); + } + + /// + /// Applies a nest-defaults edit, moving only an untouched trailing empty sheet + /// that matched the old defaults to the new defaults. + /// + public void ChangePlateDefaults(Action changeDefaults) + { + ArgumentNullException.ThrowIfNull(changeDefaults); + var trailing = Count > 0 ? nest.Plates[^1] : null; + var followsDefaults = trailing != null && IsUntouchedSentinel(trailing); changeDefaults(); if (!followsDefaults) return; - defaults = nest.PlateDefaults; + var defaults = nest.PlateDefaults; trailing.Size = defaults.Size; trailing.Quadrant = defaults.Quadrant; trailing.EdgeSpacing = defaults.EdgeSpacing; diff --git a/OpenNest.Desktop/Forms/NestLayoutChoices.cs b/OpenNest.Desktop/Forms/NestLayoutChoices.cs index 85e0e6ea..5f1e2504 100644 --- a/OpenNest.Desktop/Forms/NestLayoutChoices.cs +++ b/OpenNest.Desktop/Forms/NestLayoutChoices.cs @@ -31,8 +31,9 @@ namespace OpenNest.Forms public static SheetRemnant? Of(ProposedPlate plate) { var stock = plate?.Stock; - if (stock == null || stock.Outline != null || plate.Parts.Count == 0) + if (stock == null || stock.Outline != null || plate.Parts.Count + plate.Occupants.Count == 0) return null; + var parts = plate.Parts.Concat(plate.Occupants).ToList(); var length = stock.Size.Length; var width = stock.Size.Width; // Sheet extents around the origin, as the plate view places them for this quadrant. @@ -40,10 +41,10 @@ namespace OpenNest.Forms 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 left = parts.Min(p => p.BoundingBox.Left); + var right = parts.Max(p => p.BoundingBox.Right); + var bottom = parts.Min(p => p.BoundingBox.Bottom); + var top = 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 diff --git a/OpenNest.Engine.Tests/Jobs/CurrentPlatesNestTests.cs b/OpenNest.Engine.Tests/Jobs/CurrentPlatesNestTests.cs new file mode 100644 index 00000000..7cdef8fc --- /dev/null +++ b/OpenNest.Engine.Tests/Jobs/CurrentPlatesNestTests.cs @@ -0,0 +1,283 @@ +using OpenNest.Engine.Jobs; +using OpenNest.Engine.Jobs.Placement; +using OpenNest.Geometry; + +namespace OpenNest.Engine.Tests.Jobs; + +public class CurrentPlatesNestTests +{ + /// Places one part per offered sheet it fits, at the work area's corner, until demand runs out. + private sealed class OnePerSheetEngine : INestingEngine + { + public NestJobResult Solve(NestJob job, IProgress? progress = null, + CancellationToken token = default) + { + var part = job.Parts[0]; + var plates = new List(); + var placed = 0; + foreach (var stock in job.Plates) + { + // The test part is 10 x 20, unrotated. + if (!stock.Fits(10, 20)) + continue; + var sheets = stock.Quantity ?? job.Options.MaxPlates ?? 100; + for (var i = 0; i < sheets && placed < part.Quantity + && plates.Count < (job.Options.MaxPlates ?? 100); i++, placed++) + { + var area = stock.WorkArea; + plates.Add(new NestJobPlateResult(plates.Count, stock, + new[] { new NestJobPlacement(part.Id, placed, area.X, area.Y, 0) })); + } + } + var done = placed == part.Quantity; + return new NestJobResult( + done ? NestJobStatus.Complete : NestJobStatus.Incomplete, + done ? NestJobStopReason.Completed : NestJobStopReason.StockExhausted, + plates, + new[] { new PartFulfillment(part.Id, part.Quantity, placed, part.Quantity - placed) }, + job.Plates.Select(s => new StockUsage(s.Id, plates.Count(p => p.Stock.Id == s.Id), s.Quantity)).ToList()); + } + } + + private static Task Solve(NestPipelineRequest request) => + Task.FromResult(NestPipeline.Run(new OnePerSheetEngine(), "stub", request)); + + private static Task Fill(Func, LeftoverFillResult> plan) => + Task.FromResult(plan(null!)); + + /// A nest without a plate manager yet: a live manager collapses a second empty + /// plate at the tail, so tests add their plates first. + private static (Nest Nest, Drawing Drawing) NewNest() + { + var drawing = new Drawing("part", TestDrawingFactory.Rectangle()); + var nest = new Nest(); + nest.Drawings.Add(drawing); + nest.PlateDefaults.Size = new Size(48, 96); + nest.PlateDefaults.PartSpacing = 0.25; + return (nest, drawing); + } + + private static Plate EmptyPlate(Nest nest, double width, double length) + { + var plate = nest.CreatePlate(); + plate.Size = new Size(width, length); + plate.PartSpacing = 0.25; + return plate; + } + + [Fact] + public void LayoutCheck_HoldsOccupantsFixedButReportsNewPartsAgainstThem() + { + var drawing = new Drawing("part", TestDrawingFactory.Rectangle()); + var plate = new Plate(new Size(48, 96)) { PartSpacing = 0.25 }; + // Two occupants that already overlap each other: not this proposal's problem. + var occupantA = new Part(drawing, new Vector(0, 0)); + var occupantB = new Part(drawing, new Vector(5, 0)); + var clear = new Part(drawing, new Vector(40, 0)); + var tooClose = new Part(drawing, new Vector(15.1, 0)); + var requirements = new Dictionary(ReferenceEqualityComparer.Instance) + { + [drawing] = ("part", 2), + }; + var fixedParts = new HashSet(new[] { occupantA, occupantB }, ReferenceEqualityComparer.Instance); + + Assert.Empty(NestLayoutCheck.Validate( + new List<(Plate, List)> { (plate, new List { occupantA, occupantB, clear }) }, + requirements, fixedParts)); + Assert.NotEmpty(NestLayoutCheck.Validate( + new List<(Plate, List)> { (plate, new List { occupantA, occupantB, tooClose }) }, + requirements, fixedParts)); + // Without fixed parts every pair is checked, as before. + Assert.NotEmpty(NestLayoutCheck.Validate( + new List<(Plate, List)> { (plate, new List { occupantA, occupantB, clear }) }, + requirements)); + } + + public static TheoryData Strategies() + { + var data = new TheoryData(); + foreach (var strategy in PlateFillService.BuiltInStrategies) + data.Add(strategy); + return data; + } + + [Theory] + [MemberData(nameof(Strategies))] + public void LeftoverFill_PlacesAroundExistingPartsWithoutChangingThePlate(string strategy) + { + var drawing = new Drawing("part", TestDrawingFactory.Rectangle()); + var plate = new Plate(new Size(48, 96)) { PartSpacing = 0.25 }; + var occupant = new Part(drawing, new Vector(0, 0)); + plate.Parts.Add(occupant); + + var result = PlateLeftoverFill.Run(new[] { plate }, + new[] { new NestItem { Drawing = drawing, Quantity = 5 } }, strategy, null, CancellationToken.None); + + var fill = Assert.Single(result.Plates); + Assert.Equal(5, fill.Parts.Count); + Assert.Empty(result.Violations); + Assert.Same(occupant, Assert.Single(plate.Parts)); + var requirements = new Dictionary(ReferenceEqualityComparer.Instance) + { + [drawing] = ("part", 5), + }; + Assert.Empty(NestLayoutCheck.Validate( + new List<(Plate, List)> { (plate, fill.Parts.Append(occupant).ToList()) }, requirements, + new HashSet(new[] { occupant }, ReferenceEqualityComparer.Instance))); + } + + [Fact] + public void LeftoverFill_ARepeatedPlateUsesEveryCopysParts() + { + var drawing = new Drawing("part", TestDrawingFactory.Rectangle()); + var plate = new Plate(new Size(48, 96)) { PartSpacing = 0.25, Quantity = 3 }; + plate.Parts.Add(new Part(drawing, new Vector(0, 0))); + + var result = PlateLeftoverFill.Run(new[] { plate }, + new[] { new NestItem { Drawing = drawing, Quantity = 7 } }, PlateFillService.DefaultStrategy, null, + CancellationToken.None); + + // Seven copies over three plates: two per plate, six in all. + Assert.Equal(2, Assert.Single(result.Plates).Parts.Count); + Assert.Equal(6, result.Placed()[drawing]); + } + + [Fact] + public void ApplyToStockPlates_UsesTheExactPlatesAndRefusesOneThatChanged() + { + var (nest, drawing) = NewNest(); + var first = EmptyPlate(nest, 30, 40); + var second = EmptyPlate(nest, 48, 96); + var map = new Dictionary { ["a"] = first, ["b"] = second }; + var result = NestPipeline.Run(new OnePerSheetEngine(), "stub", new NestPipelineRequest("stub", + new[] { new NestItem { Drawing = drawing, Quantity = 2 } }, + new[] + { + OpenNest.Engine.Jobs.Adapters.DrawingJobMapper.FromPlate("a", first, 1), + OpenNest.Engine.Jobs.Adapters.DrawingJobMapper.FromPlate("b", second, 1), + })); + Assert.True(result.IsValid, string.Join("; ", result.Violations)); + + second.Parts.Add(new Part(drawing)); + Assert.Throws(() => NestPipelineCommit.ApplyToStockPlates(result, map)); + Assert.Empty(first.Parts); + + second.Parts.Clear(); + var applied = NestPipelineCommit.ApplyToStockPlates(result, map); + Assert.Equal(new[] { first, second }, applied); + Assert.Equal(new Size(30, 40), first.Size); + Assert.Single(first.Parts); + Assert.Single(second.Parts); + } + + [Fact] + public async Task CurrentPlates_FillsLeftoverAndEmptyPlatesAndNeverCreatesAPlate() + { + var (nest, drawing) = NewNest(); + var occupied = EmptyPlate(nest, 48, 96); + occupied.Parts.Add(new Part(drawing, new Vector(0, 0))); + var configured = EmptyPlate(nest, 30, 40); + using var manager = new PlateManager(nest); + manager.EnsureSentinel(); + var plates = nest.Plates.Count; + + var proposal = await CurrentPlatesNest.RunAsync(nest, manager, NestPlateSource.Current, + new[] { new NestItem { Drawing = drawing, Quantity = 100 } }, "stub", + PlateFillService.DefaultStrategy, null, null, Fill, Solve); + + Assert.True(proposal.IsValid, string.Join("; ", proposal.Violations)); + Assert.NotEmpty(Assert.Single(proposal.Leftover.Plates).Parts); + Assert.Same(configured, Assert.Single(proposal.PlateByStockId.Values)); + Assert.Null(proposal.New); + Assert.NotEmpty(proposal.Unplaced); + Assert.Equal(occupied.Parts.Count, proposal.Sheets[0].Occupants.Count); + Assert.Equal(1, proposal.Sheets[0].ExistingPlateNumber); + + var applied = CurrentPlatesNest.Commit(proposal, nest, manager, false, CancellationToken.None, out var newPlates); + + Assert.Empty(newPlates); + Assert.Equal(new[] { occupied, configured }, applied); + Assert.Single(configured.Parts); + Assert.True(occupied.Parts.Count > 1); + // The only plate added is the empty trailing sheet the nest keeps ready after the + // configured plate (the old tail) received parts; nothing was nested on it. + Assert.Equal(plates + 1, nest.Plates.Count); + Assert.Empty(nest.Plates[^1].Parts); + } + + [Fact] + public async Task Both_NestsTheRemainderOnNewSheetsAfterCurrentPlates() + { + var (nest, drawing) = NewNest(); + var configured = EmptyPlate(nest, 30, 40); + using var manager = new PlateManager(nest); + manager.EnsureSentinel(); + IReadOnlyList? askedNew = null; + + var proposal = await CurrentPlatesNest.RunAsync(nest, manager, NestPlateSource.Both, + new[] { new NestItem { Drawing = drawing, Quantity = 3 } }, "stub", + PlateFillService.DefaultStrategy, null, + remaining => + { + askedNew = remaining; + return new NestPipelineRequest("stub", remaining.ToList(), + new[] { new NestPlateStock("new", new Size(48, 96), null, 0.25, new Spacing(), 1) }); + }, + Fill, Solve); + + Assert.True(proposal.IsValid, string.Join("; ", proposal.Violations)); + Assert.Equal(2, Assert.Single(askedNew!).Quantity); + Assert.Empty(proposal.Unplaced); + // The configured plate, then the two identical new sheets as one layout cut twice. + Assert.Equal(2, proposal.Sheets.Count); + Assert.Equal(2, proposal.Sheets[1].Quantity); + + CurrentPlatesNest.Commit(proposal, nest, manager, false, CancellationToken.None, out var newPlates); + + Assert.Single(configured.Parts); + var fresh = Assert.Single(newPlates); + Assert.NotSame(configured, fresh); + Assert.Equal(2, fresh.Quantity); + Assert.Equal(3, drawing.Quantity.Nested); + } + + [Fact] + public async Task Both_NeverLaysNewSheetsOnAnEmptyPlateTheUserSetUp() + { + var (nest, drawing) = NewNest(); + nest.Plates.Add(new Plate(new Size(48, 96)) { PartSpacing = 0.25 }); + nest.Plates[0].Parts.Add(new Part(drawing, new Vector(0, 0))); + // Too small for the part, so the current-plate stage leaves it empty. + var remnant = EmptyPlate(nest, 5, 5); + using var manager = new PlateManager(nest); + manager.EnsureSentinel(); + + var proposal = await CurrentPlatesNest.RunAsync(nest, manager, NestPlateSource.Both, + new[] { new NestItem { Drawing = drawing, Quantity = 40 } }, "stub", + PlateFillService.DefaultStrategy, null, + remaining => new NestPipelineRequest("stub", remaining.ToList(), + new[] { new NestPlateStock("new", new Size(48, 96), null, 0.25, new Spacing(), 1) }), + Fill, Solve); + Assert.True(proposal.IsValid, string.Join("; ", proposal.Violations)); + Assert.NotNull(proposal.New); + + CurrentPlatesNest.Commit(proposal, nest, manager, false, CancellationToken.None, out var newPlates); + + Assert.NotEmpty(newPlates); + Assert.DoesNotContain(remnant, newPlates); + Assert.Empty(remnant.Parts); + Assert.Equal(new Size(5, 5), remnant.Size); + } + + [Fact] + public void EmptyPlates_SkipsTheUntouchedTrailingSheet() + { + var (nest, _) = NewNest(); + using var manager = new PlateManager(nest); + manager.EnsureSentinel(); + Assert.Empty(CurrentPlatesNest.EmptyPlates(nest, manager)); + + nest.Plates[^1].Size = new Size(60, 120); + Assert.Same(nest.Plates[^1], Assert.Single(CurrentPlatesNest.EmptyPlates(nest, manager))); + } +} diff --git a/OpenNest.Engine/Jobs/CurrentPlatesNest.cs b/OpenNest.Engine/Jobs/CurrentPlatesNest.cs new file mode 100644 index 00000000..d5b7839d --- /dev/null +++ b/OpenNest.Engine/Jobs/CurrentPlatesNest.cs @@ -0,0 +1,311 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using OpenNest.Engine.Jobs.Adapters; +using OpenNest.Engine.Jobs.Placement; + +namespace OpenNest.Engine.Jobs; + +/// Which plates Auto Nest may use. +public enum NestPlateSource +{ + /// Fresh sheets from the template plate or the stock options (the original behavior). + New, + + /// Only plates already in the nest: the free space beside parts already placed, then + /// the empty plates. No plate is created. + Current, + + /// first, then new sheets for whatever remains. + Both, +} + +/// +/// One Auto Nest proposal over the nest's current plates, and new plates when allowed, shown and +/// kept as a whole. Nothing is committed until . +/// +public sealed class CurrentPlatesProposal +{ + internal CurrentPlatesProposal(LeftoverFillResult leftover, NestPipelineResult empty, + IReadOnlyDictionary plateByStockId, NestPipelineResult fresh, + IReadOnlyList unplaced, IReadOnlyDictionary plateNumbers) + { + Leftover = leftover; + Empty = empty; + PlateByStockId = plateByStockId; + New = fresh; + Unplaced = unplaced; + var sheets = new List(); + foreach (var fill in leftover.Plates) + { + sheets.Add(new ProposedPlate(sheets.Count, + DrawingJobMapper.FromPlate("existing", fill.Plate, 1), fill.Parts) + { + Occupants = fill.Occupants, + Quantity = System.Math.Max(1, fill.Plate.Quantity), + ExistingPlateNumber = plateNumbers.GetValueOrDefault(fill.Plate), + }); + } + if (empty != null) + foreach (var proposed in empty.Plates.Where(p => p.Parts.Count > 0)) + sheets.Add(proposed with + { + ExistingPlateNumber = plateNumbers.GetValueOrDefault(plateByStockId[proposed.Stock.Id]), + }); + if (fresh != null) + sheets.AddRange(fresh.Plates.Where(p => p.Parts.Count > 0)); + Sheets = sheets.AsReadOnly(); + Violations = leftover.Violations + .Concat(empty?.Violations ?? Array.Empty()) + .Concat(fresh?.Violations ?? Array.Empty()) + .ToList().AsReadOnly(); + CanKeep = (empty?.CanKeep ?? true) && (fresh?.CanKeep ?? true); + } + + /// Parts proposed beside the parts already on occupied plates. + public LeftoverFillResult Leftover { get; } + + /// The whole-job result on the nest's empty plates; null when that stage did not run. + public NestPipelineResult Empty { get; } + + /// The nest's empty plate each stock id of stands for. + public IReadOnlyDictionary PlateByStockId { get; } + + /// The whole-job result on new sheets; null when that stage did not run. + public NestPipelineResult New { get; } + + /// Every sheet the proposal places parts on: occupied plates, then empty plates, then + /// new sheets. + public IReadOnlyList Sheets { get; } + + /// Layout problems from every stage. + public IReadOnlyList Violations { get; } + + public bool IsValid => Violations.Count == 0; + + /// True when every whole-job stage can be kept. + public bool CanKeep { get; } + + /// Every requested copy the whole proposal leaves unplaced. + public IReadOnlyList Unplaced { get; } + + /// True when any stage places a part. + public bool PlacesAnything => Sheets.Any(s => s.Parts.Count > 0); +} + +/// +/// Auto Nest on the nest's current plates ( and +/// ), in stages that each ask only for what the earlier ones left: +/// the free space beside parts already placed (), then the nest's +/// empty plates as one whole-job solve with one sheet per plate, then, for Both, new sheets. +/// Whole-job placements only ever go onto empty plates. does +/// not come here. +/// +public static class CurrentPlatesNest +{ + /// + /// The nest's empty plates Auto Nest may use as current plates, in nest order: no parts, no + /// cut-offs, and not the untouched trailing sheet the nest keeps ready for new work. + /// + public static IReadOnlyList EmptyPlates(Nest nest, PlateManager manager) + { + ArgumentNullException.ThrowIfNull(nest); + return nest.Plates + .Where(p => p.Parts.Count == 0 && p.CutOffs.Count == 0 + && !(manager?.IsUntouchedSentinel(p) ?? false)) + .ToList(); + } + + /// + /// Runs the stages calls for. runs the + /// leftover fill (typically off the UI thread), each whole-job + /// request; gives the empty-plate stage's options for that + /// many sheets (no salvage: the sheets are already the nest's); builds the new-sheet request for the demand + /// left (Both only). The nest is not changed. + /// + public static async Task RunAsync( + Nest nest, + PlateManager manager, + NestPlateSource source, + IReadOnlyList items, + string engineName, + string fillStrategy, + Func currentOptions, + Func, NestPipelineRequest> newPlatesRequest, + Func, LeftoverFillResult>, Task> fill, + Func> solve, + CancellationToken token = default) + { + ArgumentNullException.ThrowIfNull(nest); + ArgumentNullException.ThrowIfNull(items); + ArgumentNullException.ThrowIfNull(fill); + ArgumentNullException.ThrowIfNull(solve); + if (source == NestPlateSource.New) + throw new ArgumentOutOfRangeException(nameof(source), "New plates use the ordinary Auto Nest request."); + if (source == NestPlateSource.Both) + ArgumentNullException.ThrowIfNull(newPlatesRequest); + + var plateNumbers = new Dictionary(ReferenceEqualityComparer.Instance); + for (var i = 0; i < nest.Plates.Count; i++) + plateNumbers[nest.Plates[i]] = i + 1; + + var remaining = Copy(items); + // Every plate, in nest order, so the fill names plates by their nest number; it skips + // plates without parts itself. + var plates = nest.Plates.ToList(); + var leftover = LeftoverFillResult.Empty; + if (plates.Any(PlateLeftoverFill.HasParts) && remaining.Count > 0) + { + var plan = remaining; + leftover = await fill(progress => PlateLeftoverFill.Run(plates, plan, fillStrategy, progress, token)); + token.ThrowIfCancellationRequested(); + remaining = Subtract(remaining, leftover.Placed()); + } + + NestPipelineResult empty = null; + var plateByStockId = new Dictionary(StringComparer.Ordinal); + var emptyPlates = EmptyPlates(nest, manager); + if (emptyPlates.Count > 0 && remaining.Count > 0) + { + var stock = new List(); + foreach (var plate in emptyPlates) + { + var id = $"current-{plateNumbers[plate]}"; + plateByStockId[id] = plate; + stock.Add(DrawingJobMapper.FromPlate(id, plate, 1)); + } + var options = currentOptions?.Invoke(stock.Count) + ?? new NestJobOptions(maxPlates: stock.Count, salvageRate: 0); + empty = await solve(new NestPipelineRequest(engineName, remaining, stock, options)); + token.ThrowIfCancellationRequested(); + if (empty.CanKeep) + remaining = Subtract(remaining, Placed(empty)); + } + + NestPipelineResult fresh = null; + if (source == NestPlateSource.Both && remaining.Count > 0) + { + var request = newPlatesRequest(remaining); + if (request != null) + { + fresh = await solve(request); + token.ThrowIfCancellationRequested(); + if (fresh.CanKeep) + remaining = Subtract(remaining, Placed(fresh)); + } + } + + // The last whole-job stage names what it left and why; with none, what the leftover fill + // left had no sheet to go on. + var unplaced = fresh?.Unplaced ?? empty?.Unplaced + ?? remaining.Select(i => new NestUnplacedPart(i.Drawing.Name, i.Drawing, i.Quantity, + NestUnplacedReason.StockExhausted)).ToList(); + return new CurrentPlatesProposal(leftover, empty, plateByStockId, fresh, unplaced, plateNumbers); + } + + /// + /// Commits as one batch: the leftover parts onto their occupied + /// plates, the empty-plate layouts onto those exact plates, then new sheets onto the untouched + /// trailing sheet and new plates, never onto an empty plate the user set up (it was offered as + /// a current plate). Every check runs before anything changes, and nothing after them can + /// fail; a plate that changed since the proposal refuses the whole commit. Returns every + /// plate that received parts, and in those of the new-sheet + /// stage, in its order. + /// + public static IReadOnlyList Commit(CurrentPlatesProposal proposal, Nest nest, PlateManager manager, + bool allowInvalid, CancellationToken token, out IReadOnlyList newPlates) + { + ArgumentNullException.ThrowIfNull(proposal); + ArgumentNullException.ThrowIfNull(nest); + ArgumentNullException.ThrowIfNull(manager); + token.ThrowIfCancellationRequested(); + if (!proposal.CanKeep || (!proposal.IsValid && !allowInvalid)) + throw new InvalidOperationException("The nesting result cannot be committed without a keepable layout and explicit consent to its violations."); + foreach (var fill in proposal.Leftover.Plates) + { + if (fill.Plate.Parts.Count != fill.Occupants.Count + || fill.Plate.Parts.Where((part, i) => !ReferenceEquals(part, fill.Occupants[i])).Any() + || !PlateLeftoverFill.CanFill(fill.Plate)) + throw new InvalidOperationException("A plate changed after the nesting proposal was made; run Auto Nest again."); + } + if (proposal.Empty != null) + NestPipelineCommit.EnsureStockPlates(proposal.Empty, proposal.PlateByStockId, allowInvalid, token); + if (proposal.New != null) + NestPipelineCommit.EnsureCanApply(proposal.New, allowInvalid, token); + token.ThrowIfCancellationRequested(); + + var applied = new List(); + newPlates = Array.Empty(); + manager.BeginBatch(); + try + { + foreach (var fill in proposal.Leftover.Plates) + { + fill.Plate.Parts.AddRange(fill.Parts); + applied.Add(fill.Plate); + } + // Checked above; no token here, so a late cancel cannot leave half a commit. + if (proposal.Empty != null) + applied.AddRange(NestPipelineCommit.ApplyToStockPlates(proposal.Empty, + proposal.PlateByStockId, allowInvalid, CancellationToken.None)); + if (proposal.New != null) + { + var sentinel = nest.Plates.Count > 0 && manager.IsUntouchedSentinel(nest.Plates[^1]) + ? nest.Plates[^1] : null; + newPlates = NestPipelineCommit.ApplyToPlates(proposal.New, () => + { + if (sentinel != null && sentinel.Parts.Count == 0) + return sentinel; + return nest.CreatePlate(); + }, allowInvalid, CancellationToken.None); + applied.AddRange(newPlates); + } + } + finally + { + manager.EndBatch(); + } + return applied.AsReadOnly(); + } + + private static List Copy(IEnumerable items) => items + .Where(i => i?.Drawing != null && i.Quantity > 0) + .Select(i => With(i, i.Quantity)) + .ToList(); + + private static NestItem With(NestItem item, int quantity) => new() + { + Drawing = item.Drawing, + Quantity = quantity, + Priority = item.Priority, + RotationStart = item.RotationStart, + RotationEnd = item.RotationEnd, + StepAngle = item.StepAngle, + }; + + private static List Subtract(List items, IReadOnlyDictionary placed) + { + var left = new List(); + var used = new Dictionary(placed, ReferenceEqualityComparer.Instance); + foreach (var item in items) + { + var take = System.Math.Min(item.Quantity, used.GetValueOrDefault(item.Drawing)); + used[item.Drawing] = used.GetValueOrDefault(item.Drawing) - take; + if (item.Quantity - take > 0) + left.Add(With(item, item.Quantity - take)); + } + return left; + } + + /// Physical copies of each drawing a whole-job result places. + private static IReadOnlyDictionary Placed(NestPipelineResult result) + { + var placed = new Dictionary(ReferenceEqualityComparer.Instance); + foreach (var plate in result.Plates) + foreach (var part in plate.Parts) + placed[part.BaseDrawing] = placed.GetValueOrDefault(part.BaseDrawing) + plate.Quantity; + return placed; + } +} diff --git a/OpenNest.Engine/Jobs/NestLayoutCheck.cs b/OpenNest.Engine/Jobs/NestLayoutCheck.cs index 0f7d40f6..02297279 100644 --- a/OpenNest.Engine/Jobs/NestLayoutCheck.cs +++ b/OpenNest.Engine/Jobs/NestLayoutCheck.cs @@ -251,9 +251,14 @@ public static class NestLayoutCheck /// identity must never be inferred from Name, which is only incidentally seeded from the /// originating NestJobPart id) to its original quantity limit and display name. /// + /// Parts already on the plate before this proposal (by reference): + /// they count as occupants other parts must clear, but nothing is reported about them alone + /// (their bounds, clamps, quantities, pairs with each other or groups only they form). Null, + /// the default, checks every part. internal static List Validate( List<(Plate Plate, List Parts)> plateRuns, - IReadOnlyDictionary requirements + IReadOnlyDictionary requirements, + IReadOnlySet fixedParts = null ) { var result = new List(); @@ -262,24 +267,33 @@ public static class NestLayoutCheck if (allParts.Count == 0) return result; - ValidateQuantities(allParts, requirements, result); + bool IsFixed(Part part) => fixedParts != null && fixedParts.Contains(part); + ValidateQuantities(fixedParts == null ? allParts : allParts.Where(p => !IsFixed(p)).ToList(), + requirements, result); foreach (var (plate, parts) in plateRuns) { if (parts.Count == 0) continue; - ValidateBounds(parts, plate, requirements, result); - ValidateAreaBudget(parts, plate, result); - ValidateSpacing(parts, plate.PartSpacing, requirements, result, plate.CommonLines); - ValidateCommonLines(plate, parts, requirements, result); + var proposed = fixedParts == null ? parts : parts.Where(p => !IsFixed(p)).ToList(); + if (proposed.Count == 0) + continue; + ValidateBounds(proposed, plate, requirements, result); + if (fixedParts == null || FixedArea(parts, fixedParts) <= AreaBudget(plate) + Tolerance.Epsilon) + ValidateAreaBudget(parts, plate, result); + ValidateSpacing(parts, plate.PartSpacing, requirements, result, plate.CommonLines, fixedParts); + ValidateCommonLines(plate, parts, requirements, result, fixedParts); if (plate.ClampZones.Count > 0) - ValidateClamps(parts, plate, requirements, result); + ValidateClamps(proposed, plate, requirements, result); } return result; } + private static double FixedArea(List parts, IReadOnlySet fixedParts) => + parts.Where(fixedParts.Contains).Sum(p => p.BaseDrawing.Area); + /// /// C1/C5: no part material may enter a clamp zone inflated by the plate's clamp /// clearance (the rail's own, else the bottom-edge spacing, D6), enforced with the @@ -597,10 +611,7 @@ public static class NestLayoutCheck List result ) { - var workArea = plate.WorkArea(); - var budget = plate.Outline == null - ? workArea.Width * workArea.Length - : DrawingJobMapper.FromPlate("plate", plate, null).UsableOutline().Sum(Clipper.Area); + var budget = AreaBudget(plate); var placedArea = parts.Sum(p => p.BaseDrawing.Area); if (placedArea > budget + Tolerance.Epsilon) @@ -612,6 +623,14 @@ public static class NestLayoutCheck } } + private static double AreaBudget(Plate plate) + { + var workArea = plate.WorkArea(); + return plate.Outline == null + ? workArea.Width * workArea.Length + : DrawingJobMapper.FromPlate("plate", plate, null).UsableOutline().Sum(Clipper.Area); + } + /// /// Every pair of parts must be at least apart. /// Each part's material is inflated by the spacing (perimeter offset @@ -628,7 +647,8 @@ public static class NestLayoutCheck double spacing, IReadOnlyDictionary requirements, List result, - IEnumerable commonLines = null + IEnumerable commonLines = null, + IReadOnlySet fixedParts = null ) { // Members of one explicit common-line group are held to the group's kerf instead. @@ -677,6 +697,10 @@ public static class NestLayoutCheck if (!BoxesTouch(reach, other)) continue; + // Two occupants were placed before this proposal; only pairs with a new part count. + if (fixedParts != null && fixedParts.Contains(parts[i]) && fixedParts.Contains(parts[j])) + continue; + // Inflating one side by the full spacing covers both cases: part j // inside part i's (shrunk) cutout, or part i's inflated outline // inside part j's raw cutout. @@ -719,10 +743,13 @@ public static class NestLayoutCheck /// so its spacing exemption would hide a real violation. /// private static void ValidateCommonLines(Plate plate, List parts, - IReadOnlyDictionary requirements, List result) + IReadOnlyDictionary requirements, List result, + IReadOnlySet fixedParts = null) { foreach (var group in plate.CommonLines) { + if (fixedParts != null && group.Members.All(fixedParts.Contains)) + continue; if (group.Members.Any(member => !parts.Contains(member))) { result.Add("A common-line group names a part that is not on its plate"); diff --git a/OpenNest.Engine/Jobs/NestPipeline.cs b/OpenNest.Engine/Jobs/NestPipeline.cs index bbd49d47..f55d31cc 100644 --- a/OpenNest.Engine/Jobs/NestPipeline.cs +++ b/OpenNest.Engine/Jobs/NestPipeline.cs @@ -30,6 +30,14 @@ public sealed record ProposedPlate(int PlateIndex, NestPlateStock Stock, IReadOn /// . Empty when the layout has none. public IReadOnlyList CommonLines { get; init; } = Array.Empty(); + /// Parts already on the nest's plate before this proposal, shown with it but never + /// committed again; empty for a new sheet. holds only the new parts. + public IReadOnlyList Occupants { get; init; } = Array.Empty(); + + /// The nest's plate number (1-based) when the layout goes onto a plate already in the + /// nest; null for a new sheet. + public int? ExistingPlateNumber { get; init; } + private int quantity = 1; public int Quantity { diff --git a/OpenNest.Engine/Jobs/NestPipelineCommit.cs b/OpenNest.Engine/Jobs/NestPipelineCommit.cs index 1fcf5d7f..9d873b50 100644 --- a/OpenNest.Engine/Jobs/NestPipelineCommit.cs +++ b/OpenNest.Engine/Jobs/NestPipelineCommit.cs @@ -25,7 +25,7 @@ public static class NestPipelineCommit manager.BeginBatch(); try { - return Attach(result, manager.GetOrCreateEmpty); + return Attach(result, _ => manager.GetOrCreateEmpty()); } finally { @@ -48,9 +48,52 @@ public static class NestPipelineCommit { ArgumentNullException.ThrowIfNull(nextPlate); EnsureCommittable(result, allowInvalid, token); - return Attach(result, nextPlate); + return Attach(result, _ => nextPlate()); } + /// + /// Commits a result solved on stock made from the nest's own empty plates: each proposed + /// plate goes onto the plate names for its stock id. Every + /// check runs before anything changes; a stock id with no plate, a plate that has gained parts + /// or cut-offs, or two layouts on one plate refuses the whole commit. + /// + public static IReadOnlyList ApplyToStockPlates( + NestPipelineResult result, + IReadOnlyDictionary plateByStockId, + bool allowInvalid = false, + CancellationToken token = default + ) + { + ArgumentNullException.ThrowIfNull(plateByStockId); + EnsureStockPlates(result, plateByStockId, allowInvalid, token); + return Attach(result, proposed => plateByStockId[proposed.Stock.Id]); + } + + /// The checks runs before it changes anything. + public static void EnsureStockPlates( + NestPipelineResult result, + IReadOnlyDictionary plateByStockId, + bool allowInvalid = false, + CancellationToken token = default + ) + { + ArgumentNullException.ThrowIfNull(plateByStockId); + EnsureCommittable(result, allowInvalid, token); + var used = new HashSet(ReferenceEqualityComparer.Instance); + foreach (var proposed in result.Plates.Where(p => p.Parts.Count > 0)) + { + if (!plateByStockId.TryGetValue(proposed.Stock.Id, out var plate) + || plate.Parts.Count > 0 || plate.CutOffs.Count > 0 || proposed.Quantity != 1 + || !used.Add(plate)) + throw new InvalidOperationException("A plate changed after the nesting proposal was made; run Auto Nest again."); + } + } + + /// The checks every commit runs before it changes anything; public so a caller + /// committing several results can check them all first. + public static void EnsureCanApply(NestPipelineResult result, bool allowInvalid = false, + CancellationToken token = default) => EnsureCommittable(result, allowInvalid, token); + /// /// Pairs the plates or returned /// for with the stock each was solved on: one per proposed plate @@ -82,14 +125,14 @@ public static class NestPipelineCommit token.ThrowIfCancellationRequested(); } - private static IReadOnlyList Attach(NestPipelineResult result, Func nextPlate) + private static IReadOnlyList Attach(NestPipelineResult result, Func plateFor) { var applied = new List(); foreach (var proposed in result.Plates) { if (proposed.Parts.Count == 0) continue; - var plate = nextPlate(); + var plate = plateFor(proposed); plate.Size = proposed.Stock.Size; plate.Outline = proposed.Stock.Outline; plate.PartSpacing = proposed.Stock.PartSpacing; diff --git a/OpenNest.Engine/Jobs/Placement/PlateFillService.cs b/OpenNest.Engine/Jobs/Placement/PlateFillService.cs index ec88c16e..122fd302 100644 --- a/OpenNest.Engine/Jobs/Placement/PlateFillService.cs +++ b/OpenNest.Engine/Jobs/Placement/PlateFillService.cs @@ -512,6 +512,20 @@ public static partial class PlateFillService return new RemnantFinder(area, obstacles).FindRemnants(); } + /// + /// The parts of that lie in , keep the plate's + /// part spacing from its parts, and each other, stay out of its + /// clamp keep-outs and fit : the same certification the clamp path + /// gives every fill. Neither list is changed. + /// + internal static List CertifyClear(Plate plate, Box area, List proposed, + List accepted, List demand) + { + var clear = new List(); + AddClear(clear, proposed, plate, area, demand, accepted); + return clear; + } + private static void AddClear(List accepted, List proposed, Plate plate, Box area, List demand = null, List previouslyPlaced = null, int groupSize = 1) diff --git a/OpenNest.Engine/Jobs/Placement/PlateLeftoverFill.cs b/OpenNest.Engine/Jobs/Placement/PlateLeftoverFill.cs new file mode 100644 index 00000000..dfbe2d45 --- /dev/null +++ b/OpenNest.Engine/Jobs/Placement/PlateLeftoverFill.cs @@ -0,0 +1,226 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using OpenNest.Engine.Fill; +using OpenNest.Geometry; + +namespace OpenNest.Engine.Jobs.Placement; + +/// New parts proposed for the leftover space of a plate that already holds parts. +/// The nest's plate; never changed by the fill. +/// The plate's parts when the fill ran, in order; the commit refuses a +/// plate whose parts changed since. +/// The proposed parts, clear of and the clamps. +public sealed record LeftoverPlateFill(Plate Plate, IReadOnlyList Occupants, IReadOnlyList Parts); + +/// What proposed. +/// One entry per plate that received parts, in the order given. +/// Layout problems the independent check found in the proposals. +/// Occupied plates the fill cannot use: an outlined sheet, or one with +/// cut-offs. +public sealed record LeftoverFillResult( + IReadOnlyList Plates, + IReadOnlyList Violations, + IReadOnlyList Skipped) +{ + public static LeftoverFillResult Empty { get; } = + new(Array.Empty(), Array.Empty(), Array.Empty()); + + /// Copies of each drawing the proposals use, counting every physical copy of a plate + /// (), by drawing reference. + public IReadOnlyDictionary Placed() + { + var placed = new Dictionary(ReferenceEqualityComparer.Instance); + foreach (var fill in Plates) + foreach (var part in fill.Parts) + placed[part.BaseDrawing] = placed.GetValueOrDefault(part.BaseDrawing) + + System.Math.Max(1, fill.Plate.Quantity); + return placed; + } +} + +/// +/// Auto Nest's "current plates" leftover stage: fills the free space on plates that already hold +/// parts with the fill strategies, around the parts already there, and checks each proposal with +/// the same layout rules as a whole-job result, the existing parts held fixed. Whole-job engines +/// never place on an occupied plate; only these certified fill proposals do. Nothing is +/// committed: the plates and the caller's items are left unchanged. +/// +public static class PlateLeftoverFill +{ + /// Fill rounds per item on one plate; a round that adds nothing ends it. + private const int MaxRounds = 8; + + /// True when holds parts and the fill can use its leftover + /// space: a rectangular sheet without cut-offs. + public static bool CanFill(Plate plate) => + plate != null && HasParts(plate) && PlateFillService.Refusal(plate) == null + && plate.CutOffs.Count == 0 && !plate.Parts.Any(p => p.BaseDrawing.IsCutOff); + + /// True when holds at least one part that is not a cut-off. + public static bool HasParts(Plate plate) => plate.Parts.Any(p => !p.BaseDrawing.IsCutOff); + + /// + /// Fills each occupied plate of (the nest's plates, in order: messages + /// name a plate by its position here) in turn with what remains of + /// : items by priority, then larger parts first, each into the largest + /// free rectangles left beside the parts already there. A plate repeated + /// times uses that many copies of each part it receives. + /// + public static LeftoverFillResult Run( + IReadOnlyList plates, + IReadOnlyList items, + string strategy, + IProgress progress, + CancellationToken token) + { + ArgumentNullException.ThrowIfNull(plates); + ArgumentNullException.ThrowIfNull(items); + var remaining = items.Where(i => i?.Drawing != null && i.Quantity > 0) + .Select(i => (Item: i, Left: i.Quantity)) + .ToList(); + var fills = new List(); + var violations = new List(); + var skipped = new List(); + + for (var index = 0; index < plates.Count; index++) + { + token.ThrowIfCancellationRequested(); + var plate = plates[index]; + if (plate == null || !HasParts(plate)) + continue; + if (!CanFill(plate)) + { + skipped.Add(plate); + continue; + } + if (remaining.All(r => r.Left <= 0)) + break; + + var copies = System.Math.Max(1, plate.Quantity); + var occupants = plate.Parts.ToList(); + var accepted = new List(); + var caps = new Dictionary(ReferenceEqualityComparer.Instance); + foreach (var (item, left) in remaining + .OrderByDescending(r => r.Item.Priority) + .ThenByDescending(r => r.Item.Drawing.Area)) + { + var cap = left / copies; + if (cap <= 0) + continue; + caps[item.Drawing] = caps.GetValueOrDefault(item.Drawing) + cap; + FillItem(plate, item, cap, strategy, accepted, token); + } + + if (accepted.Count == 0) + continue; + var check = Check(plate, occupants, accepted, caps); + violations.AddRange(check.Select(v => $"Plate {index + 1}: {v}")); + fills.Add(new LeftoverPlateFill(plate, occupants.AsReadOnly(), accepted.AsReadOnly())); + // Two items of one drawing share its parts: each takes what it can, in order. + var used = accepted + .GroupBy(p => p.BaseDrawing, ReferenceEqualityComparer.Instance) + .ToDictionary(g => g.Key, g => g.Count() * copies, ReferenceEqualityComparer.Instance); + for (var i = 0; i < remaining.Count; i++) + { + var drawing = remaining[i].Item.Drawing; + var take = System.Math.Min(remaining[i].Left, used.GetValueOrDefault(drawing)); + used[drawing] = used.GetValueOrDefault(drawing) - take; + remaining[i] = (remaining[i].Item, remaining[i].Left - take); + } + progress?.Report(new NestProgress + { + BestParts = occupants.Concat(accepted).ToList(), + ActiveWorkArea = plate.WorkArea(), + PlateNumber = index + 1, + IsOverallBest = true, + Description = $"Plate {index + 1}: {accepted.Count} parts added around existing parts", + }); + } + + return new LeftoverFillResult(fills.AsReadOnly(), violations.AsReadOnly(), skipped.AsReadOnly()); + } + + /// + /// Up to copies of into the free rectangles of + /// , largest first, recomputing them after every accepted fill (free + /// rectangles overlap). Every proposal is certified clear of the plate's parts, the parts + /// already accepted and the clamps, and must keep the item's rotation limits. + /// + private static void FillItem(Plate plate, NestItem item, int cap, string strategy, + List accepted, CancellationToken token) + { + var rotation = RotationPolicy.FromLegacy(item.StepAngle, item.RotationStart, item.RotationEnd, + item.Drawing.Constraints?.Allow180Equivalent ?? false); + var size = item.Drawing.Program.BoundingBox(); + var placed = 0; + for (var round = 0; round < MaxRounds && placed < cap; round++) + { + var before = placed; + foreach (var region in FreeRegions(plate, accepted)) + { + token.ThrowIfCancellationRequested(); + if (placed >= cap) + break; + if (!Fits(region, size)) + continue; + var demand = new NestItem + { + Drawing = item.Drawing, + Quantity = cap - placed, + Priority = item.Priority, + RotationStart = item.RotationStart, + RotationEnd = item.RotationEnd, + StepAngle = item.StepAngle, + }; + var proposed = PlateFillService.FillItem(strategy, plate, demand, region, null, token) + ?.Where(p => rotation.Allows(p.Rotation)) + .ToList(); + var clear = PlateFillService.CertifyClear(plate, region, proposed, accepted, + new List { demand }); + if (clear.Count == 0) + continue; + accepted.AddRange(clear); + placed += clear.Count; + // The free rectangles changed; start again from the largest. + break; + } + if (placed == before) + return; + } + } + + /// The plate's free rectangles beside its parts, the accepted parts and the clamps, + /// largest first. + private static List FreeRegions(Plate plate, List accepted) + { + var obstacles = InteractiveClamps.ClearanceRectangles(plate).ToList(); + obstacles.AddRange(plate.Parts.Where(part => !part.BaseDrawing.IsCutOff) + .Concat(accepted) + .Select(part => part.BoundingBox.Offset(plate.PartSpacing))); + return new RemnantFinder(plate.WorkArea(), obstacles).FindRemnants() + .OrderByDescending(box => box.Length * box.Width) + .ToList(); + } + + private static bool Fits(Box region, Box size) + { + const double slack = 1e-6; + return (region.Length + slack >= size.Length && region.Width + slack >= size.Width) + || (region.Length + slack >= size.Width && region.Width + slack >= size.Length); + } + + /// The whole-job layout rules on the plate's parts plus the proposal, the parts + /// already there held fixed. + private static List Check(Plate plate, List occupants, List proposed, + IReadOnlyDictionary caps) + { + var requirements = caps.ToDictionary( + c => c.Key, c => (c.Key.Name, c.Value), (IEqualityComparer)ReferenceEqualityComparer.Instance); + var fixedParts = new HashSet(occupants, ReferenceEqualityComparer.Instance); + return NestLayoutCheck.Validate( + new List<(Plate, List)> { (plate, occupants.Concat(proposed).ToList()) }, + requirements, fixedParts); + } +} diff --git a/OpenNest.WinForms.Tests/Forms/AutoNestFormPlateSourceTests.cs b/OpenNest.WinForms.Tests/Forms/AutoNestFormPlateSourceTests.cs new file mode 100644 index 00000000..b10987a9 --- /dev/null +++ b/OpenNest.WinForms.Tests/Forms/AutoNestFormPlateSourceTests.cs @@ -0,0 +1,70 @@ +using System.Windows.Forms; +using OpenNest.Engine.Jobs; +using OpenNest.Forms; +using OpenNest.Geometry; + +namespace OpenNest.WinForms.Tests.Forms; + +public class AutoNestFormPlateSourceTests +{ + [Fact] + public void OpensOnNewPlates() => RunSta(() => + { + using var form = new AutoNestForm(new Nest()); + + Assert.Equal(NestPlateSource.New, form.PlateSource); + }); + + [Theory] + [InlineData(NestPlateSource.Current)] + [InlineData(NestPlateSource.Both)] + public void CurrentPlatesAreNeverNestedOnTheServer(NestPlateSource source) => RunSta(() => + { + using var form = new AutoNestForm(new Nest()) { ServerNestingAvailable = true }; + var box = Assert.IsType(form.Controls.Find("nestOnServerBox", true).Single()); + box.Checked = true; + + form.PlateSource = source; + + Assert.False(box.Enabled); + Assert.False(form.NestOnServer); + form.PlateSource = NestPlateSource.New; + Assert.Equal(box.Checked, form.NestOnServer); + }); + + [Fact] + public void CurrentPlatesOnlyOffersNoStockOptions() => RunSta(() => + { + using var form = new AutoNestForm(new Nest()) { OptimizePlateSize = true }; + + form.PlateSource = NestPlateSource.Current; + Assert.False(form.OptimizePlateSize); + + form.PlateSource = NestPlateSource.Both; + Assert.True(form.OptimizePlateSize); + }); + + [Fact] + public void ReviewShowsPartsAlreadyPlacedWithoutCountingThem() => RunSta(() => + { + var drawing = new Drawing("bracket", NestReviewFormTests.Rectangle()); + var stock = new NestPlateStock("existing", new Size(48, 96), quantity: 1, partSpacing: 0.25); + var sheet = new ProposedPlate(0, stock, new[] { new Part(drawing, new Vector(20, 1)) }) + { + Occupants = new[] { new Part(drawing, new Vector(1, 1)), new Part(drawing, new Vector(1, 30)) }, + ExistingPlateNumber = 2, + }; + + using var form = new NestReviewForm("Review", new[] { sheet }, 0, + Array.Empty(), ColorScheme.Default); + + Assert.Equal(1, form.Strip.PartCount); + Assert.Equal(2, form.Strip.ExistingPartCount); + // Three 10 x 20 parts now fill the sheet's material. + Assert.Equal(600.0 / (48 * 96), form.Strip.Utilization, 6); + Assert.Contains("already on the plates (2)", form.Summary); + }); + + private static void RunSta(Action action) => + StaTestThread.Run(action, TimeSpan.FromSeconds(15), "The STA test did not complete."); +} diff --git a/OpenNest.WinForms.Tests/Forms/NestReviewFormTests.cs b/OpenNest.WinForms.Tests/Forms/NestReviewFormTests.cs index 65b4d260..42bbfa27 100644 --- a/OpenNest.WinForms.Tests/Forms/NestReviewFormTests.cs +++ b/OpenNest.WinForms.Tests/Forms/NestReviewFormTests.cs @@ -110,7 +110,7 @@ public class NestReviewFormTests CancellationToken token = default) => solve(job); } - private static CNC.Program Rectangle() + internal static CNC.Program Rectangle() { var program = new CNC.Program(); program.MoveTo(0, 0); diff --git a/OpenNest/Controls/SheetStripControl.cs b/OpenNest/Controls/SheetStripControl.cs index 620275bb..35db6354 100644 --- a/OpenNest/Controls/SheetStripControl.cs +++ b/OpenNest/Controls/SheetStripControl.cs @@ -74,6 +74,12 @@ namespace OpenNest.Controls public int PartCount => tiles.Sum(t => t.Quantity * t.PartCount); + /// Parts already on the sheets before this proposal, every physical copy counted. + public int ExistingPartCount => tiles.Sum(t => t.Quantity * t.OccupantCount); + + /// The one color parts already on a plate are drawn in, so the new parts stand out. + internal static readonly Color OccupantColor = Color.FromArgb(160, 160, 160); + public void SetSheets(IReadOnlyList sheets) { ClearTiles(); @@ -179,6 +185,8 @@ namespace OpenNest.Controls var baseline = (room - content) / 2 + (content - CaptionHeight); using var partPen = new Pen(Color.FromArgb(60, 60, 60), 0); using var clampBrush = new SolidBrush(Color.FromArgb(90, 230, 170, 40)); + using var occupantBrush = new SolidBrush(Color.FromArgb(170, OccupantColor)); + using var occupantPen = new Pen(Color.FromArgb(120, 120, 120), 0); // The plate view's obstacle colors. using var obstacleBrush = new HatchBrush(HatchStyle.WideUpwardDiagonal, Color.FromArgb(170, 120, 60, 60), Color.FromArgb(60, 200, 80, 80)); @@ -225,6 +233,11 @@ namespace OpenNest.Controls g.Transform = toDevice; foreach (var zone in tile.Clamps) g.FillRectangle(clampBrush, zone); + foreach (var path in tile.Occupants) + { + g.FillPath(occupantBrush, path); + g.DrawPath(occupantPen, path); + } foreach (var (path, brush) in tile.Parts) { g.FillPath(brush, path); @@ -292,6 +305,12 @@ namespace OpenNest.Controls foreach (var zone in stock.ClampZones) Clamps.Add(new RectangleF((float)zone.Bounds.X, (float)zone.Bounds.Y, (float)zone.Bounds.Length, (float)zone.Bounds.Width)); + foreach (var part in plate.Occupants) + { + PartArea += part.BaseDrawing.IsCutOff ? 0 : part.BaseDrawing.Area; + Occupants.Add(part.Program.GetFillPath(part.Location)); + } + OccupantCount = plate.Occupants.Count(p => !p.BaseDrawing.IsCutOff); foreach (var part in plate.Parts) { PartArea += part.BaseDrawing.Area; @@ -315,9 +334,13 @@ namespace OpenNest.Controls }; } - Title = Quantity == 1 ? $"Sheet {firstNumber}" : $"Sheets {firstNumber}–{firstNumber + Quantity - 1} (×{Quantity})"; + Title = plate.ExistingPlateNumber is int existing + ? (Quantity == 1 ? $"Plate {existing} (existing)" : $"Plate {existing} (existing, ×{Quantity})") + : Quantity == 1 ? $"Sheet {firstNumber}" : $"Sheets {firstNumber}–{firstNumber + Quantity - 1} (×{Quantity})"; var utilization = SheetArea > 0 ? PartArea / SheetArea : 0; - Detail = $"{stock.Size} · {PartCount} parts · {utilization:P0}"; + Detail = OccupantCount > 0 + ? $"{stock.Size} · {PartCount} new parts · {utilization:P0}" + : $"{stock.Size} · {PartCount} parts · {utilization:P0}"; } public Geometry.Box Sheet { get; } @@ -332,6 +355,9 @@ namespace OpenNest.Controls public GraphicsPath Obstacles { get; } public int Quantity { get; } public int PartCount { get; } + + /// Parts already on the plate, drawn in . + public int OccupantCount { get; } public double PartArea { get; } public string Title { get; } public string Detail { get; } @@ -343,6 +369,7 @@ namespace OpenNest.Controls public PointF[] RemnantSpan { get; } public List Clamps { get; } = new(); public List<(GraphicsPath Path, Brush Brush)> Parts { get; } = new(); + public List Occupants { get; } = new(); private static PointF[] ToPoints(IReadOnlyList points, double x, double y) => points.Select(p => new PointF((float)(p.X + x), (float)(p.Y + y))).ToArray(); @@ -357,6 +384,9 @@ namespace OpenNest.Controls brush.Dispose(); } Parts.Clear(); + foreach (var path in Occupants) + path.Dispose(); + Occupants.Clear(); } } } diff --git a/OpenNest/Forms/AutoNestForm.Designer.cs b/OpenNest/Forms/AutoNestForm.Designer.cs index c18656a6..17cc177e 100644 --- a/OpenNest/Forms/AutoNestForm.Designer.cs +++ b/OpenNest/Forms/AutoNestForm.Designer.cs @@ -29,6 +29,8 @@ namespace OpenNest.Forms this.nestOnServerBox = new System.Windows.Forms.CheckBox(); this.commonLineLabel = new System.Windows.Forms.Label(); this.commonLineComboBox = new System.Windows.Forms.ComboBox(); + this.plateSourceLabel = new System.Windows.Forms.Label(); + this.plateSourceComboBox = new System.Windows.Forms.ComboBox(); this.minRemnantLabel = new System.Windows.Forms.Label(); this.minRemnantBox = new System.Windows.Forms.TextBox(); this.plateOptimizerGroup = new System.Windows.Forms.GroupBox(); @@ -86,6 +88,8 @@ namespace OpenNest.Forms this.platesTab.Controls.Add(this.nestOnServerBox); this.platesTab.Controls.Add(this.commonLineLabel); this.platesTab.Controls.Add(this.commonLineComboBox); + this.platesTab.Controls.Add(this.plateSourceLabel); + this.platesTab.Controls.Add(this.plateSourceComboBox); this.platesTab.Location = new System.Drawing.Point(4, 25); this.platesTab.Name = "platesTab"; this.platesTab.Padding = new System.Windows.Forms.Padding(6); @@ -157,6 +161,28 @@ namespace OpenNest.Forms this.engineComboBox.TabIndex = 1; this.engineComboBox.SelectedIndexChanged += new System.EventHandler(this.engineComboBox_SelectedIndexChanged); // + // plateSourceLabel + // + this.plateSourceLabel.AutoSize = true; + this.plateSourceLabel.Location = new System.Drawing.Point(316, 15); + this.plateSourceLabel.Name = "plateSourceLabel"; + this.plateSourceLabel.Size = new System.Drawing.Size(48, 16); + this.plateSourceLabel.TabIndex = 7; + this.plateSourceLabel.Text = "Plates:"; + // + // plateSourceComboBox + // + this.plateSourceComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; + this.plateSourceComboBox.Items.AddRange(new object[] { + "New plates", + "Current plates only", + "Current, then new"}); + this.plateSourceComboBox.Location = new System.Drawing.Point(370, 12); + this.plateSourceComboBox.Name = "plateSourceComboBox"; + this.plateSourceComboBox.Size = new System.Drawing.Size(168, 24); + this.plateSourceComboBox.TabIndex = 8; + this.plateSourceComboBox.SelectedIndexChanged += new System.EventHandler(this.plateSourceComboBox_SelectedIndexChanged); + // // nestOnServerBox // this.nestOnServerBox.AutoSize = true; @@ -375,6 +401,8 @@ namespace OpenNest.Forms private System.Windows.Forms.ToolTip ledgerToolTip; private System.Windows.Forms.Label commonLineLabel; private System.Windows.Forms.ComboBox commonLineComboBox; + private System.Windows.Forms.Label plateSourceLabel; + private System.Windows.Forms.ComboBox plateSourceComboBox; private System.Windows.Forms.Label salvageRateLabel; private System.Windows.Forms.TextBox salvageRateBox; private System.Windows.Forms.Label salvageRatePercentLabel; diff --git a/OpenNest/Forms/AutoNestForm.cs b/OpenNest/Forms/AutoNestForm.cs index 401ebdef..35bc3e49 100644 --- a/OpenNest/Forms/AutoNestForm.cs +++ b/OpenNest/Forms/AutoNestForm.cs @@ -47,6 +47,13 @@ namespace OpenNest.Forms SetPlateOptimizerVisible(false); UpdateLedgerButton(); CommonLineUsage = nest?.CommonLineUsage ?? CommonLineUsage.Off; + // Always opens on New plates, so Current is never reused by accident. + PlateSource = NestPlateSource.New; + ledgerToolTip.SetToolTip(plateSourceComboBox, + "New plates: lay out fresh sheets (the stock options below, or sheets like the current plate).\n" + + "Current plates only: fill the free space beside parts already placed, then the nest's empty " + + "plates, and create no plate.\n" + + "Current, then new: current plates first, then new sheets for what remains."); ledgerToolTip.SetToolTip(commonLineComboBox, "Place parts one kerf apart so they share a cut. Only drawings with \"Allow common line\" " + "set in Drawing Properties take part. \"When it adds parts\" keeps a common-line layout only " @@ -73,6 +80,30 @@ namespace OpenNest.Forms }; } + /// Which plates the run may use; New unless the user picks another. + public NestPlateSource PlateSource + { + get => plateSourceComboBox.SelectedIndex switch + { + 1 => NestPlateSource.Current, + 2 => NestPlateSource.Both, + _ => NestPlateSource.New, + }; + set => plateSourceComboBox.SelectedIndex = value switch + { + NestPlateSource.Current => 1, + NestPlateSource.Both => 2, + _ => 0, + }; + } + + private void plateSourceComboBox_SelectedIndexChanged(object sender, EventArgs e) + { + // Current plates only never lays out new stock, so the stock options do not apply. + plateOptimizerGroup.Enabled = PlateSource != NestPlateSource.Current; + UpdateNestOnServerBox(); + } + public string EngineName { get { return engineComboBox.SelectedItem as string; } @@ -102,15 +133,19 @@ namespace OpenNest.Forms private void UpdateNestOnServerBox() { var builtIn = NestingEngineRegistry.IsBuiltIn(EngineName); - nestOnServerBox.Enabled = builtIn; - ledgerToolTip.SetToolTip(nestOnServerBox, builtIn - ? "Send this nest to the nest server's worker. This PC stays free while it runs; Keep and Discard work as usual." - : "Plug-in engines run only on this PC."); + var newPlates = PlateSource == NestPlateSource.New; + nestOnServerBox.Enabled = builtIn && newPlates; + ledgerToolTip.SetToolTip(nestOnServerBox, !builtIn + ? "Plug-in engines run only on this PC." + : !newPlates + ? "Server nesting lays out new plates only; current plates are nested on this PC." + : "Send this nest to the nest server's worker. This PC stays free while it runs; Keep and Discard work as usual."); } + /// True when the run offers the stock options; never with Current plates only. public bool OptimizePlateSize { - get { return optimizePlateSizeBox.Checked; } + get { return optimizePlateSizeBox.Checked && PlateSource != NestPlateSource.Current; } set { optimizePlateSizeBox.Checked = value; } } diff --git a/OpenNest/Forms/Commands/AutoNestCommand.cs b/OpenNest/Forms/Commands/AutoNestCommand.cs index 02442ffc..2d87c5f4 100644 --- a/OpenNest/Forms/Commands/AutoNestCommand.cs +++ b/OpenNest/Forms/Commands/AutoNestCommand.cs @@ -9,6 +9,7 @@ using OpenNest.Data.MaterialLedger; using OpenNest.Diagnostics; using OpenNest.Engine; using OpenNest.Engine.Jobs; +using OpenNest.Engine.Jobs.Placement; namespace OpenNest.Forms.Commands { @@ -35,6 +36,7 @@ namespace OpenNest.Forms.Commands private IReadOnlyList ledgerRows = Array.Empty(); private bool nestOnServer; private CommonLineUsage commonLineUsage; + private NestPlateSource plateSource; private AutoNestCommand(IWin32Window owner, EditNestForm target, List items, List plateOptions, string engineName, double salvageRate, double minRemnantSize) @@ -99,6 +101,7 @@ namespace OpenNest.Forms.Commands ledgerRows = form.OptimizePlateSize ? form.LedgerRows : Array.Empty(), nestOnServer = form.NestOnServer, commonLineUsage = form.CommonLineUsage, + plateSource = form.PlateSource, }; } @@ -108,6 +111,11 @@ namespace OpenNest.Forms.Commands /// public async Task RunAsync(CancellationTokenSource cts) { + if (plateSource != NestPlateSource.New) + { + await RunOnCurrentPlatesAsync(cts); + return; + } try { var request = new NestPipelineRequest(EngineName, items, @@ -325,6 +333,158 @@ namespace OpenNest.Forms.Commands return await solve; } + /// + /// Auto Nest on the nest's current plates (and new sheets for Both): the free space beside + /// placed parts, the empty plates, then new sheets, shown together in one review and kept in + /// one undo record. Always on this PC: the server lays out new plates only. + /// + private async Task RunOnCurrentPlatesAsync(CancellationTokenSource cts) + { + try + { + var kerf = CommonLineKerf(target); + var proposal = await CurrentPlatesNest.RunAsync(target.Nest, target.PlateManager, plateSource, + items, EngineName, EngineSelection.FillStrategy, + sheets => new NestJobOptions(maxPlates: sheets, salvageRate: 0, + minimumSalvageDimension: minRemnantSize) + { + CommonLineUsage = commonLineUsage, + CommonLineKerf = kerf, + }, + remaining => new NestPipelineRequest(EngineName, remaining.ToList(), + NestStockBuilder.FromTemplate(target.PlateView.Plate, plateOptions), + new NestJobOptions(maxPlates: 100, + salvageRate: plateOptions?.Count > 0 ? salvageRate : 0, + minimumSalvageDimension: minRemnantSize) + { + CommonLineUsage = commonLineUsage, + CommonLineKerf = kerf, + }), + plan => FillLeftoverAsync(plan, cts), + async request => (await SolveAndPickAsync(owner, target, request, cts)).Result, + cts.Token); + cts.Token.ThrowIfCancellationRequested(); + + if (!proposal.PlacesAnything) + { + var why = plateSource == NestPlateSource.Current + && CurrentPlatesNest.EmptyPlates(target.Nest, target.PlateManager).Count == 0 + && !target.Nest.Plates.Any(PlateLeftoverFill.CanFill) + ? "The nest has no current plate Auto Nest can use: no empty plate you have set up, " + + "and no rectangular plate with parts and without cut-offs." + : plateSource == NestPlateSource.Current + ? "Auto Nest placed nothing on the current plates." + : "Auto Nest placed nothing on the current plates or new sheets."; + if (proposal.Unplaced.Count > 0) + why += "\n\n" + $"Not placed ({proposal.Unplaced.Sum(u => u.Count)}):\n" + + string.Join("\n", proposal.Unplaced.Select(u => u.Describe())); + MessageBox.Show(owner, why, Caption, MessageBoxButtons.OK, MessageBoxIcon.Information); + return; + } + + await ReviewAndCommitAsync(proposal, cts.Token); + } + catch (OperationCanceledException) when (cts.IsCancellationRequested) + { + // Stop discards the entire proposal. + } + catch (Exception ex) + { + MessageBox.Show(owner, $"Nesting error: {ex.Message}", Caption, + MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + /// Runs the leftover fill off the UI thread behind a cancellable progress window. + private async Task FillLeftoverAsync( + Func, LeftoverFillResult> plan, CancellationTokenSource cts) + { + using var progressForm = new NestProgressForm(cts, showPlateRow: true) + { + AllowAccept = false, + HoldOpenUntilCompleted = true, + }; + var receiving = true; + var progress = new Progress(p => + { + if (receiving && !target.IsDisposed) + progressForm.UpdateProgress(p); + }); + async Task RunFillAsync() + { + try + { + return await Task.Run(() => plan(progress)); + } + finally + { + receiving = false; + progressForm.ShowCompleted(); + progressForm.Close(); + } + } + + var fill = RunFillAsync(); + if (!fill.IsCompleted) + progressForm.ShowDialog(owner); + return await fill; + } + + /// + /// The current-plates counterpart of the shared review: the validation review when a stage + /// broke layout rules, the Keep/Discard review of every sheet (parts already placed shown in + /// one color), then one commit in one undo record. + /// + private async Task ReviewAndCommitAsync(CurrentPlatesProposal proposal, CancellationToken token) + { + var allowInvalid = false; + if (!proposal.IsValid) + { + using var validation = new NestValidationForm(proposal.Violations, proposal.CanKeep); + if (validation.ShowDialog(owner) != DialogResult.OK) + return; + allowInvalid = true; + } + using (var review = new NestReviewForm($"Review Auto Nest — {EngineName}", proposal.Sheets, + proposal.IsValid ? 0 : proposal.Violations.Count, proposal.Unplaced, + target.PlateView.ColorScheme, null)) + { + if (review.ShowDialog(owner) != DialogResult.OK) + return; + } + if (target.IsDisposed) + return; + + IReadOnlyList applied; + using (var change = target.BeginChange(Caption)) + { + change.MarkChanged(); + applied = CurrentPlatesNest.Commit(proposal, target.Nest, target.PlateManager, allowInvalid, token, + out var newPlates); + if (proposal.New != null) + AssignLedgerStock(proposal.New, newPlates); + target.Nest.CommonLineUsage = commonLineUsage; + if (proposal.New != null && plateOptions?.Count > 0) + { + if (savedOptions?.Count > 0) + target.Nest.PlateOptions = savedOptions; + target.Nest.SalvageRate = salvageRate; + target.Nest.MinimumRemnantDimension = minRemnantSize; + } + if (applied.Count > 0) + target.PlateManager.LoadAt(target.Nest.Plates.IndexOf(applied[0])); + change.Complete(); + } + target.PlateView.Invalidate(); + target.UpdatePlateList(); + if (allowInvalid) + { + target.OverlapDisplay = OverlapDisplayMode.Both; + await target.CheckOverlapsAsync(); + } + ShowResultNotices(owner, target, applied); + } + // Only a committed proposal gets codes: every return above leaves them as they were. private void AssignLedgerStock(NestPipelineResult result, IReadOnlyList applied) { diff --git a/OpenNest/Forms/NestReviewForm.cs b/OpenNest/Forms/NestReviewForm.cs index 9748eaf9..17638d9f 100644 --- a/OpenNest/Forms/NestReviewForm.cs +++ b/OpenNest/Forms/NestReviewForm.cs @@ -15,8 +15,20 @@ namespace OpenNest.Forms internal sealed class NestReviewForm : Form { public NestReviewForm(NestPipelineResult result, ColorScheme colorScheme, string costSummary = null) + : this($"Review Auto Nest — {result.EngineName}", result.Plates, + result.IsValid ? 0 : result.Violations.Count, result.Unplaced, colorScheme, costSummary) { - Text = $"Review Auto Nest — {result.EngineName}"; + } + + /// + /// Any set of proposed sheets: is how many layout + /// violations the validation review accepted (zero for a valid proposal). Parts already on a + /// plate () show in one color and do not count as placed. + /// + public NestReviewForm(string title, IReadOnlyList sheets, int acceptedViolations, + IReadOnlyList unplaced, ColorScheme colorScheme, string costSummary = null) + { + Text = title; StartPosition = FormStartPosition.CenterParent; ShowInTaskbar = false; MinimizeBox = false; @@ -25,22 +37,24 @@ namespace OpenNest.Forms Font = new Font("Segoe UI", 9.75F); var strip = new SheetStripControl { Dock = DockStyle.Fill, ColorScheme = colorScheme, ShowRemnant = true }; - strip.SetSheets(result.Plates); + strip.SetSheets(sheets); Strip = strip; var lines = new List { $"{strip.SheetCount} sheet(s), {strip.PartCount} part(s) placed, {strip.Utilization:P1} utilization", }; - if (!result.IsValid) - lines.Add($"{result.Violations.Count} layout violation(s) accepted in the validation review; overlaps are marked after Keep."); + if (strip.ExistingPartCount > 0) + lines.Add($"Parts already on the plates ({strip.ExistingPartCount}) are shown in gray and stay where they are."); + if (acceptedViolations > 0) + lines.Add($"{acceptedViolations} layout violation(s) accepted in the validation review; overlaps are marked after Keep."); if (!string.IsNullOrEmpty(costSummary)) lines.Add(costSummary); // Never drop demand silently: name every unplaced part and why. - if (result.Unplaced.Count > 0) + if (unplaced.Count > 0) { - lines.Add($"Not placed ({result.Unplaced.Sum(u => u.Count)}):"); - lines.AddRange(result.Unplaced.Select(u => " " + u.Describe())); + lines.Add($"Not placed ({unplaced.Sum(u => u.Count)}):"); + lines.AddRange(unplaced.Select(u => " " + u.Describe())); } var summary = new TextBox { diff --git a/docs/automatic-nesting.md b/docs/automatic-nesting.md index 2ca1ddea..3f90c1e6 100644 --- a/docs/automatic-nesting.md +++ b/docs/automatic-nesting.md @@ -10,7 +10,7 @@ 5. Check returned placements with the independent `NestLayoutCheck` used by the benchmark (for bundles, again after expanding them to physical frames and inserts). 6. Consolidate exact ordered nonempty layouts only when the entire result is valid, then bind each layout to the caller's drawing references; the caller decides whether to commit it. -`NestStockBuilder.FromTemplate` snapshots sheet options and spacing settings for multiple-sheet jobs. `SinglePlate` offers exactly one physical sheet, regardless of the legacy plate repeat quantity. `NestPipelineCommit.ApplyToEmptyPlates` applies accepted desktop proposals to empty/new plates with the checked size, quadrant, spacing and total-copy quantity semantics. Quantity is set before parts are attached, so drawing counts multiply exactly once. It never fills occupied plates. +`NestStockBuilder.FromTemplate` snapshots sheet options and spacing settings for multiple-sheet jobs. `SinglePlate` offers exactly one physical sheet, regardless of the legacy plate repeat quantity. `NestPipelineCommit.ApplyToEmptyPlates` applies accepted desktop proposals to empty/new plates with the checked size, quadrant, spacing and total-copy quantity semantics. Quantity is set before parts are attached, so drawing counts multiply exactly once. It never fills occupied plates; `ApplyToStockPlates` commits a result solved on the nest's own empty plates onto exactly those plates. ## Repeated layouts and physical sheets @@ -22,9 +22,19 @@ Layout-entry count is not physical-sheet count: sum layout quantities for sheets ## Desktop Auto Nest -Every engine selected in **Nest > Auto Nest** uses the pipeline. Part-First and its sorting controls are removed. Use interactive Fill Area/remnant tools for leftover space on occupied sheets; these are not whole-job nesting. +Every engine selected in **Nest > Auto Nest** uses the pipeline. Part-First and its sorting controls are removed. Leftover space on occupied sheets is filled by the **Plates** choice below or the interactive Fill Area/remnant tools; neither is whole-job nesting. -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. +With **Plates: New plates** (the default; the dialog always opens on it), Auto Nest starts on empty/new sheets and does not change existing populated plates. + +**Plates** (`NestPlateSource`, run by `CurrentPlatesNest`) chooses which plates the run may use: + +- **New plates**: the original behavior above, unchanged. +- **Current plates only**: no plate is created. First `PlateLeftoverFill` fills the free space beside the parts already on each occupied plate with the fill strategy (Options' fill strategy, as Fill Area uses): items by priority, then larger first, into the largest free rectangles, each proposal certified clear of the parts there, other new parts and the clamps, then checked by `NestLayoutCheck` with the existing parts held fixed (only new parts, and their pairs with existing parts, are reported). It skips outlined plates and plates with cut-offs, and a plate repeated `Plate.Quantity` times uses that many copies of each part it receives. Then the remaining demand is one whole-job solve with the chosen engine on the nest's empty plates, one sheet per plate with that plate's size, outline and clamps, no salvage, committed onto exactly those plates. The untouched trailing sheet the nest keeps ready (still at the nest defaults) is not a current plate; one you resized or set up is. The stock options do not apply. +- **Current, then new**: current plates as above, then the ordinary new-sheet request (stock options, salvage, ledger) for what remains. + +Each stage asks only for what earlier stages placed less. New sheets go onto the untouched trailing sheet or newly created plates, never onto an empty plate you set up. As in New mode, an empty plate that receives a layout is cut once: its `Plate.Quantity` is reset to 1. The proposal is reviewed once (parts already on a plate show in one gray, and existing plates are titled "Plate N (existing)"), and kept in one undo record; a plate that changed in the meantime refuses the whole commit. Whole-job placements still never go onto an occupied plate. Leftover fill makes no common lines; the whole-job stages keep the dialog's choice. Nest on the server lays out new plates only, so it is disabled unless Plates is New 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. **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. diff --git a/docs/irregular-stock.md b/docs/irregular-stock.md index 473982f4..2758972c 100644 --- a/docs/irregular-stock.md +++ b/docs/irregular-stock.md @@ -61,7 +61,9 @@ snapshots go through the same writer and reader, so a restore rebuilds the outli rectangle to Default may well land on the rectangle: Default keeps the cheaper valid layout. - Auto Nest's stock-options grid offers rectangles only; an outlined sheet is nested through the target plate (no options), or through `NestPlateStock` directly: the console's `--outline`, - or API callers that set `NestPlateStock.Outline`. MCP has no outline input. + or API callers that set `NestPlateStock.Outline`. MCP has no outline input. With **Plates: + Current plates**, an empty outlined plate is offered as itself (only Irregular places on it); + an outlined plate that already holds parts is skipped, since leftover fill needs a rectangle. - The stored polygon is inside the true material by up to the chord tolerance (0.001) on imported arcs and exactly on straight edges. Outlines imported before straight edges were kept exactly sit 0.001 inside every edge (a 60 x 27 sheet reads 59.998 x 26.998); import the diff --git a/docs/server-nesting.md b/docs/server-nesting.md index 7a1cb9b0..2e792887 100644 --- a/docs/server-nesting.md +++ b/docs/server-nesting.md @@ -11,7 +11,8 @@ when none are waiting. ## Desktop The Auto Nest dialog's Plates tab shows **Nest on the server** in Database mode only. It is -enabled for built-in engines only: the server loads no plug-ins from `Engines/`. The dialog +enabled for built-in engines only: the server loads no plug-ins from `Engines/`; and only +when **Plates** is New plates, since the server lays out new sheets only. The dialog remembers the last choice (`AutoNestOnServer` in the user settings). With the box ticked, `ServerAutoNest`: