From ca9e08b93d3d9b2657761b337cafb10715c8c482 Mon Sep 17 00:00:00 2001 From: AJ Isaacs Date: Tue, 24 Nov 2026 23:06:56 -0500 Subject: [PATCH] feat(engine): add the Raster nesting engine Raster packs each part rotation as a bit mask of its material grown by half the part spacing plus 0.75 cell, so masks that never share a cell keep the spacing and every layout passes the layout check unrepaired. Coarse raster no-fit maps propose positions and a grid four times finer settles them; the job is decoded in 48 greedy variants through the shared stock loop. It is selectable by name, not a Default candidate. Benchmark, 7 real jobs, --parallel 1, 6" minimum salvage: all layouts valid; Irregular's sheet count on 5 jobs in 0.6-2.3 s against 11-78 s, at under 1 to 4% more salvage-credited cost; 3 sheets against 2 on 27K; 24 s on 2J9 (seven stock sizes). Packing tighter and opening the gaps with Fix Spacing saved under 0.1% of cost for up to 25 times the time, so it was left out. Co-Authored-By: Claude Opus 5.5 --- .../Jobs/NestingEngineRegistryTests.cs | 1 + .../RasterNestingEngineTests.cs | 60 ++++ OpenNest.Engine/Jobs/NestingEngineRegistry.cs | 7 + .../NestingEngines/Raster/RasterGrid.cs | 188 ++++++++++++ .../NestingEngines/Raster/RasterMask.cs | 284 ++++++++++++++++++ .../Raster/RasterNestingEngine.cs | 147 +++++++++ .../NestingEngines/Raster/RasterSheet.cs | 275 +++++++++++++++++ README.md | 2 +- docs/automatic-nesting.md | 2 +- docs/nesting-engines.md | 35 ++- scripts/ReleaseSmoke/Program.cs | 2 +- 11 files changed, 999 insertions(+), 4 deletions(-) create mode 100644 OpenNest.Engine.Tests/NestingEngines/RasterNestingEngineTests.cs create mode 100644 OpenNest.Engine/NestingEngines/Raster/RasterGrid.cs create mode 100644 OpenNest.Engine/NestingEngines/Raster/RasterMask.cs create mode 100644 OpenNest.Engine/NestingEngines/Raster/RasterNestingEngine.cs create mode 100644 OpenNest.Engine/NestingEngines/Raster/RasterSheet.cs diff --git a/OpenNest.Engine.Tests/Jobs/NestingEngineRegistryTests.cs b/OpenNest.Engine.Tests/Jobs/NestingEngineRegistryTests.cs index 4487be03..e9203413 100644 --- a/OpenNest.Engine.Tests/Jobs/NestingEngineRegistryTests.cs +++ b/OpenNest.Engine.Tests/Jobs/NestingEngineRegistryTests.cs @@ -22,6 +22,7 @@ public class NestingEngineRegistryTests Assert.Contains("Rectangles", names); Assert.Contains("Irregular", names); Assert.Contains("Circles", names); + Assert.Contains("Raster", names); Assert.Contains("Lattice", names); Assert.Contains("Strip", names); Assert.Contains("Vertical Remnant", names); diff --git a/OpenNest.Engine.Tests/NestingEngines/RasterNestingEngineTests.cs b/OpenNest.Engine.Tests/NestingEngines/RasterNestingEngineTests.cs new file mode 100644 index 00000000..1959be50 --- /dev/null +++ b/OpenNest.Engine.Tests/NestingEngines/RasterNestingEngineTests.cs @@ -0,0 +1,60 @@ +using OpenNest.Clamps; +using OpenNest.Engine.Jobs; +using OpenNest.Engine.NestingEngines.Raster; +using OpenNest.Geometry; +using Xunit; +using static OpenNest.Engine.Tests.NestingEngines.JobBuilder; +using static OpenNest.Engine.Tests.NestingEngines.Shapes; + +namespace OpenNest.Engine.Tests.NestingEngines; + +public class RasterNestingEngineTests +{ + [Theory] + [InlineData(0)] + [InlineData(0.02)] + [InlineData(0.25)] + [InlineData(1)] + public void MasksKeepTheSpacingWithoutRepair(double spacing) + { + // Arcs, notches and holes: every layout must pass the layout check as decoded. + var job = Job( + [ + Part("ring", Ring(6, 3), 6), + Part("ell", LShape(9, 7, 3), 8), + Part("tri", Triangle(7, 7), 8), + Part("disc", Disc(1), 10), + ], + [Stock("s", 24, 36, spacing)]); + var result = new RasterNestingEngine().Solve(job); + LayoutAssert.Valid(job, result); + Assert.Equal(NestJobStatus.Complete, result.Status); + } + + [Fact] + public void SmallPartsNestInHoles() + { + // A 1 x 1 square fits a 10-wide ring's 8-wide hole; the sheet only holds the ring. + var job = Job([Part("ring", Ring(10, 8), 1), Part("square", Rectangle(1, 1), 4)], + [Stock("s", 10.2, 10.2, 0.1, quantity: 1)]); + var result = new RasterNestingEngine().Solve(job); + LayoutAssert.Valid(job, result); + Assert.Equal(NestJobStatus.Complete, result.Status); + } + + [Fact] + public void ClampKeepOutsStayClear() + { + var job = Job([Part("ell", LShape(4, 3, 1), 20)], + [Stock("s", 20, 20, 0.2, clampZones: [new ClampZone("c", new Box(8, 0, 4, 2))])]); + var result = new RasterNestingEngine().Solve(job); + LayoutAssert.Valid(job, result); + Assert.Equal(NestJobStatus.Complete, result.Status); + } + + [Fact] + public void IsRegistered() => + Assert.IsType(NestingEngineRegistry.Create("Raster")); +} + +public sealed class RasterContractTests : EngineContractTests { } diff --git a/OpenNest.Engine/Jobs/NestingEngineRegistry.cs b/OpenNest.Engine/Jobs/NestingEngineRegistry.cs index 29539994..d53b1072 100644 --- a/OpenNest.Engine/Jobs/NestingEngineRegistry.cs +++ b/OpenNest.Engine/Jobs/NestingEngineRegistry.cs @@ -9,6 +9,7 @@ using OpenNest.Engine.NestingEngines.Circles; using OpenNest.Engine.NestingEngines.Default; using OpenNest.Engine.NestingEngines.FlatBar; using OpenNest.Engine.NestingEngines.Irregular; +using OpenNest.Engine.NestingEngines.Raster; using OpenNest.Engine.NestingEngines.Rectangles; namespace OpenNest.Engine.Jobs; @@ -67,6 +68,12 @@ public static class NestingEngineRegistry () => new CirclesNestingEngine() ); + Register( + "Raster", + "Packs irregular parts on a fine grid; a fast first plan", + () => new RasterNestingEngine() + ); + Register( "FlatBar", "One row of parts along a flat bar", diff --git a/OpenNest.Engine/NestingEngines/Raster/RasterGrid.cs b/OpenNest.Engine/NestingEngines/Raster/RasterGrid.cs new file mode 100644 index 00000000..73cd0ae5 --- /dev/null +++ b/OpenNest.Engine/NestingEngines/Raster/RasterGrid.cs @@ -0,0 +1,188 @@ +#nullable enable +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using OpenNest.Engine.Jobs; +using OpenNest.Geometry; +using OpenNest.Math; + +namespace OpenNest.Engine.NestingEngines.Raster; + +/// One requested part type with its readable material. +internal sealed record RasterType(int Index, NestJobPart Part, JobPartGeometry? Geometry, double MaterialArea) +{ + public string Id => Part.Id; + public int Priority => Part.Priority; +} + +/// +/// Two raster grids for one part spacing: a coarse grid whose no-fit maps propose positions over +/// the whole sheet, and a fine grid, times finer, that settles each proposal +/// in a small window by direct mask tests and is the only authority on what fits. Every requested +/// type gets one mask per candidate rotation on both grids. +/// +internal sealed class RasterGrid +{ + /// Coarse cells per fine cell along each axis. + public const int Ratio = 4; + + /// Fine cells per part spacing (or per without one). + private const double CellsPerSpacing = 8; + + /// Stand-in spacing for sizing cells when the job has none. + private const double ZeroSpacingBasis = 0.25; + + /// Most fine cells across the largest part, and across the largest sheet: caps the + /// work on large parts and the memory of a sheet's occupancy map. + private const double MaxCellsPerPart = 2400, MaxCellsPerSheet = 8000; + + /// Extra fine-mask dilation in cells; above 1/sqrt 2 so disjoint masks keep the spacing + /// (see ). + private const double FineBias = 0.75; + + /// Coarse-mask dilation in coarse cells, less than half the spacing: the coarse + /// grid only proposes, so it leans optimistic. + private const double CoarseBias = -0.25; + + /// Fine window reach around a coarse proposal, in coarse cells. + private const double Reach = 1.5; + + private readonly ConcurrentDictionary<(RasterMask, RasterMask), Lazy> noFits = new(); + + private RasterGrid(double spacing, double fineCell) + { + Spacing = spacing; + FineCell = fineCell; + FineDilate = System.Math.Max(0, spacing / 2 + FineBias * fineCell); + Cell = fineCell * Ratio; + Dilate = System.Math.Min(FineDilate, System.Math.Max(0, spacing / 2 + CoarseBias * Cell)); + Span = (int)System.Math.Ceiling(Reach * Ratio); + } + + public double Spacing { get; } + public double Cell { get; } + public double Dilate { get; } + public double FineCell { get; } + public double FineDilate { get; } + public int Span { get; } + + /// Coarse masks per type index, each with its twin. + public IReadOnlyList[] Masks { get; private set; } = Array.Empty>(); + + public NoFitMap NoFit(RasterMask a, RasterMask b) => + noFits.GetOrAdd((a, b), key => new Lazy(() => NoFitMap.Build(key.Item1, key.Item2))).Value; + + /// Builds the grid for every stock of one part spacing. + public static RasterGrid Create(double spacing, IReadOnlyList stocks, + IReadOnlyList types, bool[] usable, CancellationToken token) + { + var largest = types.Where(t => usable[t.Index] && t.Geometry != null) + .Select(t => System.Math.Max(t.Geometry!.Bounds.Length, t.Geometry.Bounds.Width)) + .DefaultIfEmpty(1).Max(); + var sheet = stocks.Max(s => System.Math.Max(s.WorkArea.Length, s.WorkArea.Width)); + var basis = spacing > 0 ? spacing : ZeroSpacingBasis; + var fine = System.Math.Max(basis / CellsPerSpacing, + System.Math.Max(largest / MaxCellsPerPart, sheet / MaxCellsPerSheet)); + var grid = new RasterGrid(spacing, fine); + + var poses = new List<(int Type, double Angle, int Kinds)>(); + foreach (var t in types) + if (usable[t.Index] && t.Geometry != null) + poses.AddRange(Angles(t).Select(a => (t.Index, a.Angle, a.Kinds))); + var built = new RasterMask?[poses.Count]; + Parallel.For(0, poses.Count, new ParallelOptions { CancellationToken = token }, i => + { + var (type, angle, kinds) = poses[i]; + var outline = Outline(types[type].Geometry!, angle); + if (outline == null) + return; + var coarse = RasterMask.Build(type, angle, outline, grid.Cell, grid.Dilate); + var fineMask = RasterMask.Build(type, angle, outline, grid.FineCell, grid.FineDilate); + if (coarse == null || fineMask == null) + return; + coarse.Kinds = fineMask.Kinds = kinds; + coarse.Fine = fineMask; + built[i] = coarse; + }); + var masks = built.Where(m => m != null).Select(m => m!).ToList(); + var maxWidth = masks.Count == 0 ? 1 : masks.Max(m => m.W); + Parallel.ForEach(masks, new ParallelOptions { CancellationToken = token }, m => m.PrepareForNoFit(maxWidth)); + grid.Masks = types.Select(t => (IReadOnlyList)masks.Where(m => m.Type == t.Index).ToList()).ToArray(); + return grid; + } + + /// The material outline the layout check measures (perimeter arcs circumscribed, + /// cutout arcs inscribed), rotated about the snapshot origin. + private static SpacingOutline? Outline(JobPartGeometry geometry, double angle) + { + var shapes = new[] { geometry.Perimeter }.Concat(geometry.Cutouts); + var entities = shapes.SelectMany(s => s.Entities).Select(e => e.Clone()).ToList(); + if (angle != 0) + foreach (var entity in entities) + entity.Rotate(angle); + return SpacingOutline.Build(new ShapeProfile(entities), Vector.Zero, 0); + } + + /// + /// Candidate rotations. A part free to turn gets the quarter turns, the eighth turns and the + /// turns that lay its longest convex-hull edges along the sheet's axes, each tagged with its + /// ; a limited part gets its legal angles (at most eight sweep + /// samples), usable by every variant. + /// + private static List<(double Angle, int Kinds)> Angles(RasterType type) + { + var policy = type.Part.Rotation; + var result = new List<(double Angle, int Kinds)>(); + if (policy.Kind != RotationPolicyKind.Automatic) + { + foreach (var angle in policy.EnumerateAngles(maxSamples: 8)) + result.Add((angle, RotationKinds.All)); + return result; + } + + for (var i = 0; i < 4; i++) + Add(System.Math.PI / 2 * i, RotationKinds.QuarterTurns); + for (var i = 0; i < 4; i++) + Add(System.Math.PI / 4 + System.Math.PI / 2 * i, RotationKinds.EighthTurns); + + var points = type.Geometry!.Perimeter.ToPolygonWithTolerance(0.01).Vertices; + var hull = ConvexHull.Compute(points).Vertices; + var edges = new List<(double Length, double Angle, int Order)>(); + for (var i = 0; i < hull.Count; i++) + { + var p = hull[i]; + var q = hull[(i + 1) % hull.Count]; + var length = p.DistanceTo(q); + if (length > 0) + edges.Add((length, PortableMath.Atan2(q.Y - p.Y, q.X - p.X), i)); + } + foreach (var edge in edges.OrderByDescending(e => e.Length).ThenBy(e => e.Order).Take(HullEdges)) + for (var i = 0; i < 4; i++) + Add(-edge.Angle + System.Math.PI / 2 * i, RotationKinds.HullAligned); + return result; + + void Add(double angle, int kinds) + { + var turn = 2 * System.Math.PI; + angle %= turn; + if (angle < 0) + angle += turn; + foreach (var existing in result) + { + var diff = System.Math.Abs(existing.Angle - angle); + if (System.Math.Min(diff, turn - diff) < SameAngle) + return; + } + result.Add((angle, kinds)); + } + } + + /// Longest hull edges laid along the sheet's axes per part. + private const int HullEdges = 2; + + /// Rotations closer than this (half a degree) count as one. + private const double SameAngle = System.Math.PI / 360; +} diff --git a/OpenNest.Engine/NestingEngines/Raster/RasterMask.cs b/OpenNest.Engine/NestingEngines/Raster/RasterMask.cs new file mode 100644 index 00000000..a9f9149e --- /dev/null +++ b/OpenNest.Engine/NestingEngines/Raster/RasterMask.cs @@ -0,0 +1,284 @@ +#nullable enable +using System; +using System.Collections.Generic; +using System.Linq; +using OpenNest.Geometry; +using BitOperations = System.Numerics.BitOperations; + +namespace OpenNest.Engine.NestingEngines.Raster; + +/// +/// One rotation of a part as a bit-packed raster: cells whose center lies in the part's material +/// or within dilate of its outline. Cutouts stay open, so other parts may nest in them. +/// Bit i of row j is cell (i, j); row j covers Y from + j * cell. +/// +internal sealed class RasterMask +{ + /// Requested type index. + public int Type; + + /// Rotation in radians about the snapshot origin. + public double Angle; + + /// Rotation kinds this pose belongs to (see ). + public int Kinds; + + /// Outline bounds in the rotated snapshot frame. + public double MinX, MinY, Length, Width; + + /// Lower-left corner of cell (0, 0) in the rotated snapshot frame. + public double OriginX, OriginY; + + public int W, H, Words; + public ulong[] Bits = Array.Empty(); + + /// Set runs per row, for building no-fit maps (coarse masks only). + public (int Start, int End)[][] Runs = Array.Empty<(int, int)[]>(); + + /// Table[k] bit x of a row: OR of the mask's bits x - 2^k + 1 .. x (coarse masks only). + public ulong[][] Table = Array.Empty(); + public int TableWords; + + /// The same pose on the fine grid (bits only), or this mask for a single grid. + public RasterMask Fine = null!; + + /// + /// Rasterizes (the part's spacing outline at zero inflation, + /// already rotated by ). Null when the outline is empty. + /// + /// + /// Two parts whose material comes closer than 2 * ( - cell / sqrt 2) + /// always share a cell: the cell holding the midpoint of their closest points has its center + /// within that distance of both. The engine sets dilate to half the part spacing plus + /// 0.75 cell, so disjoint masks keep the spacing. + /// + public static RasterMask? Build(int type, double angle, SpacingOutline outline, double cell, double dilate) + { + var polygons = new List { outline.Perimeter }; + polygons.AddRange(outline.Holes); + var points = outline.Perimeter.Vertices; + if (points.Count < 3) + return null; + double minX = points.Min(v => v.X), maxX = points.Max(v => v.X); + double minY = points.Min(v => v.Y), maxY = points.Max(v => v.Y); + var m = new RasterMask + { + Type = type, + Angle = angle, + MinX = minX, + MinY = minY, + Length = maxX - minX, + Width = maxY - minY, + OriginX = minX - dilate, + OriginY = minY - dilate, + }; + m.W = System.Math.Max(1, (int)System.Math.Ceiling((m.Length + 2 * dilate) / cell - 1e-9)); + m.H = System.Math.Max(1, (int)System.Math.Ceiling((m.Width + 2 * dilate) / cell - 1e-9)); + m.Words = (m.W + 63) / 64; + m.Bits = new ulong[m.H * m.Words]; + + // Interior: even-odd over every contour, so cutouts stay open. + var xs = new List(); + for (var j = 0; j < m.H; j++) + { + var y = m.OriginY + (j + 0.5) * cell; + xs.Clear(); + foreach (var polygon in polygons) + foreach (var (p, q) in Edges(polygon)) + { + if ((p.Y <= y) == (q.Y <= y)) + continue; + xs.Add(p.X + (y - p.Y) / (q.Y - p.Y) * (q.X - p.X)); + } + xs.Sort(); + for (var k = 0; k + 1 < xs.Count; k += 2) + { + var i0 = (int)System.Math.Ceiling((xs[k] - m.OriginX) / cell - 0.5); + var i1 = (int)System.Math.Floor((xs[k + 1] - m.OriginX) / cell - 0.5); + for (var i = i0; i <= i1; i++) + m.Set(i, j); + } + } + + // Band: every cell whose center lies within the dilation of an edge. + if (dilate > 0) + foreach (var polygon in polygons) + foreach (var (p, q) in Edges(polygon)) + { + var i0 = (int)System.Math.Floor((System.Math.Min(p.X, q.X) - dilate - m.OriginX) / cell); + var i1 = (int)System.Math.Ceiling((System.Math.Max(p.X, q.X) + dilate - m.OriginX) / cell); + var j0 = (int)System.Math.Floor((System.Math.Min(p.Y, q.Y) - dilate - m.OriginY) / cell); + var j1 = (int)System.Math.Ceiling((System.Math.Max(p.Y, q.Y) + dilate - m.OriginY) / cell); + double ex = q.X - p.X, ey = q.Y - p.Y, length2 = ex * ex + ey * ey; + for (var j = j0; j <= j1; j++) + for (var i = i0; i <= i1; i++) + { + double cx = m.OriginX + (i + 0.5) * cell - p.X, cy = m.OriginY + (j + 0.5) * cell - p.Y; + var t = length2 > 0 ? System.Math.Clamp((cx * ex + cy * ey) / length2, 0, 1) : 0; + double dx = cx - t * ex, dy = cy - t * ey; + if (dx * dx + dy * dy <= dilate * dilate) + m.Set(i, j); + } + } + return m; + } + + private static IEnumerable<(Vector P, Vector Q)> Edges(Polygon polygon) + { + var v = polygon.Vertices; + for (var k = 0; k < v.Count; k++) + { + var q = v[(k + 1) % v.Count]; + if (v[k] != q) + yield return (v[k], q); + } + } + + private void Set(int i, int j) + { + if (i >= 0 && i < W && j >= 0 && j < H) + Bits[j * Words + (i >> 6)] |= 1UL << (i & 63); + } + + /// Prepares the run lists and the shifted-OR table no-fit maps are built from; + /// is the widest coarse mask of the grid. + public void PrepareForNoFit(int maxWidth) + { + Runs = new (int, int)[H][]; + var runs = new List<(int, int)>(); + for (var j = 0; j < H; j++) + { + runs.Clear(); + var start = -1; + for (var i = 0; i <= W; i++) + { + var on = i < W && (Bits[j * Words + (i >> 6)] >> (i & 63) & 1) != 0; + if (on && start < 0) + start = i; + else if (!on && start >= 0) + { + runs.Add((start, i - 1)); + start = -1; + } + } + Runs[j] = runs.ToArray(); + } + + TableWords = (W + maxWidth + 63) / 64 + 1; + var levels = 1; + while ((1 << levels) <= maxWidth) + levels++; + Table = new ulong[levels][]; + Table[0] = new ulong[H * TableWords]; + for (var j = 0; j < H; j++) + Array.Copy(Bits, j * Words, Table[0], j * TableWords, Words); + for (var k = 1; k < levels; k++) + { + var previous = Table[k - 1]; + var current = Table[k] = (ulong[])previous.Clone(); + for (var j = 0; j < H; j++) + Bits64.OrShift(current, j * TableWords, TableWords, previous, j * TableWords, TableWords, 1 << (k - 1)); + } + } +} + +/// Rotation kinds a variant may use. +internal static class RotationKinds +{ + public const int QuarterTurns = 1; + public const int EighthTurns = 2; + public const int HullAligned = 4; + public const int All = QuarterTurns | EighthTurns | HullAligned; +} + +/// +/// Raster no-fit map of mask B around mask A: bit X of row Y is set when B, placed +/// (X - (B.W - 1), Y - (B.H - 1)) cells from A's cell (0, 0), shares a cell with A. +/// +internal sealed class NoFitMap +{ + public ulong[] Bits = Array.Empty(); + public int W, H, Words; + + public static NoFitMap Build(RasterMask a, RasterMask b) + { + int w = a.W + b.W - 1, h = a.H + b.H - 1, words = (w + 63) / 64; + var bits = new ulong[h * words]; + for (var y = 0; y < h; y++) + for (var j = System.Math.Max(0, b.H - 1 - y); j < b.H; j++) + { + var row = y - (b.H - 1) + j; + if (row >= a.H) + break; + foreach (var (start, end) in b.Runs[j]) + { + // Every shift t0..t1 of A's row: the OR of two overlapping power-of-two spans. + int t0 = b.W - 1 - end, t1 = b.W - 1 - start; + var k = BitOperations.Log2((uint)(t1 - t0 + 1)); + var table = a.Table[k]; + Bits64.OrShift(bits, y * words, words, table, row * a.TableWords, a.TableWords, t0); + var t = t1 - (1 << k) + 1; + if (t != t0) + Bits64.OrShift(bits, y * words, words, table, row * a.TableWords, a.TableWords, t); + } + } + return new NoFitMap { Bits = bits, W = w, H = h, Words = words }; + } +} + +internal static class Bits64 +{ + /// dest bit (x + shift) |= src bit x, for a signed shift. + public static void OrShift(ulong[] dest, int destAt, int destWords, ulong[] src, int srcAt, int srcWords, int shift) + { + if (shift >= 0) + { + int q = shift >> 6, r = shift & 63; + for (var w = q; w < destWords; w++) + { + var s = w - q; + ulong v = 0; + if (s < srcWords) + v = src[srcAt + s] << r; + if (r > 0 && s - 1 >= 0 && s - 1 < srcWords) + v |= src[srcAt + s - 1] >> (64 - r); + if (v != 0) + dest[destAt + w] |= v; + } + } + else + { + int q = -shift >> 6, r = -shift & 63; + for (var w = 0; w < destWords; w++) + { + var s = w + q; + if (s >= srcWords) + break; + var v = src[srcAt + s] >> r; + if (r > 0 && s + 1 < srcWords) + v |= src[srcAt + s + 1] << (64 - r); + if (v != 0) + dest[destAt + w] |= v; + } + } + } + + /// First clear bit at or after in a row of + /// bits, or -1. + public static int NextClear(ulong[] bits, int at, int words, int width, int from) + { + if (from >= width) + return -1; + for (var w = from >> 6; w < words; w++) + { + var free = ~bits[at + w]; + if (w == from >> 6) + free &= ulong.MaxValue << (from & 63); + if (free == 0) + continue; + var x = (w << 6) + BitOperations.TrailingZeroCount(free); + return x < width ? x : -1; + } + return -1; + } +} diff --git a/OpenNest.Engine/NestingEngines/Raster/RasterNestingEngine.cs b/OpenNest.Engine/NestingEngines/Raster/RasterNestingEngine.cs new file mode 100644 index 00000000..bfb87aad --- /dev/null +++ b/OpenNest.Engine/NestingEngines/Raster/RasterNestingEngine.cs @@ -0,0 +1,147 @@ +#nullable enable +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using OpenNest.Engine.Jobs; + +namespace OpenNest.Engine.NestingEngines.Raster; + +/// +/// Raster nesting engine for a fast first plan of irregular parts. Every part rotation is a +/// bit-packed mask of its material grown by half the part spacing (); +/// coarse raster no-fit maps propose positions over the whole sheet and a finer grid settles each +/// one (). Masks keep the spacing by construction, so every layout passes +/// the layout check without a repair step. +/// +/// The job is decoded greedily in 48 variants (largest area first, longest first and six seeded +/// shuffles of the area order; quarter turns, quarter turns plus hull-aligned turns, or eighth +/// turns as well; leftmost or behind-the-frontier positions), each sheet by sheet through +/// , plus one run that offers every variant's sheet in each round. The +/// best result by is reported as the one whole-job plan. Packing +/// tighter and opening the gaps with Fix Spacing was tried and gained under 0.1% for up to 25 +/// times the time. +/// Deterministic: seeded orders, no clocks; the only stop besides completion is the host token. +/// +public sealed class RasterNestingEngine : INestingEngine +{ + /// Seeded shuffles of the area order per rotation set and policy. + private const int Shuffles = 6; + + private const int Seed = 12345; + + public NestJobResult Solve( + NestJob job, + IProgress? progress = null, + CancellationToken token = default + ) + { + ArgumentNullException.ThrowIfNull(job); + token.ThrowIfCancellationRequested(); + + var types = job.Parts.Select((p, i) => + { + var geometry = JobPartGeometry.TryRead(p.Geometry); + return new RasterType(i, p, geometry, geometry?.MaterialArea ?? 0); + }).ToList(); + // Rasters fill rectangles only; an outlined sheet is left to Irregular. + var stocks = job.Plates.Where(s => s.Outline == null).ToList(); + var usable = types.Select(t => t.Geometry != null && t.Part.Quantity > 0).ToArray(); + var spacings = stocks.Select(s => s.PartSpacing).Distinct().Order().ToList(); + var grids = spacings.ToDictionary(s => s, + s => RasterGrid.Create(s, stocks.Where(x => x.PartSpacing == s).ToList(), types, usable, token)); + var remaining = types.Select(t => usable[t.Index] + && stocks.Any(s => grids[s.PartSpacing].Masks[t.Index].Any(m => Fits(s, m))) + ? t.Part.Quantity : 0).ToArray(); + var demand = types.Select(t => new SheetDemand(t.Index, t.Id, t.Priority, t.MaterialArea)).ToArray(); + var variants = Variants(types, remaining); + var results = new NestJobResult[variants.Count + 1]; + // Only the first run reports its stock trials, so the host hears from one thread; commits + // belong to the result finally chosen. + var forward = progress == null ? null : new CandidateProgress(progress); + try + { + Parallel.For(0, results.Length, new ParallelOptions { CancellationToken = token }, i => + { + results[i] = i < variants.Count + ? SheetByStock.Run(job, demand, remaining.ToArray(), + (stock, left) => new[] { Fill(stock, variants[i], left) }, i == 0 ? forward : null, token) + : SheetByStock.Run(job, demand, remaining.ToArray(), + (stock, left) => variants.Select(v => Fill(stock, v, left)), null, token); + }); + } + catch (AggregateException e) when (token.IsCancellationRequested + && e.Flatten().InnerExceptions.All(x => x is OperationCanceledException)) + { + throw new OperationCanceledException(token); + } + + // Rank unchecked (masks keep the spacing), then confirm with the layout check, best first. + var ranked = results.Select((r, i) => Score(r, i)).ToList(); + ranked.Sort((a, b) => a.IsBetterThan(b) ? -1 : b.IsBetterThan(a) ? 1 : 0); + var best = ranked[0]; + foreach (var candidate in ranked) + { + token.ThrowIfCancellationRequested(); + if (NestLayoutCheck.Violations(job, candidate.Result).Count == 0) + { + best = candidate; + break; + } + } + CandidateProgress.ReportPlan(best.Result, progress); + CandidateProgress.ReportCommits(best.Result, progress, token); + return best.Result; + + SheetLayout Fill(NestPlateStock stock, RasterVariant variant, IReadOnlyList left) => + RasterSheet.Fill(grids[stock.PartSpacing], types, stock, variant, left, token); + + CandidateScore Score(NestJobResult r, int at) + { + var unplaced = System.Math.Max(0, job.Parts.Sum(p => p.Quantity) - r.Plates.Sum(p => p.Placements.Count)); + return new CandidateScore(r, true, unplaced, NestJobCost.Evaluate(job, r), + NestJobCost.CompactnessOffcut(job, r), at, NestJobCost.UsesExplicitCosts(job)); + } + } + + private static bool Fits(NestPlateStock stock, RasterMask m) => + m.Length <= stock.WorkArea.Length + Rectangles.SheetPacker.OverhangAllowance + && m.Width <= stock.WorkArea.Width + Rectangles.SheetPacker.OverhangAllowance; + + /// Orderings x rotation sets x policies. Every order serves higher priority numbers + /// first; the plain area order with quarter turns, leftmost, comes first. + private static List Variants(IReadOnlyList types, int[] remaining) + { + var live = types.Where(t => remaining[t.Index] > 0).ToList(); + var longest = live.ToDictionary(t => t.Index, t => System.Math.Max(t.Geometry!.Bounds.Length, t.Geometry.Bounds.Width)); + var orders = new List> + { + Order(t => t.MaterialArea), + Order(t => longest[t.Index]), + }; + var random = new Random(Seed); + for (var i = 0; i < Shuffles; i++) + { + // Pure arithmetic weights: no transcendental calls, so orders match across platforms. + var weight = live.ToDictionary(t => t.Index, t => t.MaterialArea * (0.5 + random.NextDouble())); + orders.Add(Order(t => weight[t.Index])); + } + + var variants = new List(); + foreach (var kinds in new[] + { + RotationKinds.QuarterTurns, + RotationKinds.QuarterTurns | RotationKinds.HullAligned, + RotationKinds.All, + }) + foreach (var policy in new[] { RasterPolicy.Leftmost, RasterPolicy.Frontier }) + foreach (var order in orders) + variants.Add(new RasterVariant(order, kinds, policy)); + return variants; + + IReadOnlyList Order(Func size) => + live.OrderByDescending(t => t.Priority).ThenByDescending(size).ThenBy(t => t.Index) + .Select(t => t.Index).ToArray(); + } +} diff --git a/OpenNest.Engine/NestingEngines/Raster/RasterSheet.cs b/OpenNest.Engine/NestingEngines/Raster/RasterSheet.cs new file mode 100644 index 00000000..1c95b6f3 --- /dev/null +++ b/OpenNest.Engine/NestingEngines/Raster/RasterSheet.cs @@ -0,0 +1,275 @@ +#nullable enable +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using OpenNest.Engine.Jobs; +using OpenNest.Engine.NestingEngines.Rectangles; +using OpenNest.Geometry; + +namespace OpenNest.Engine.NestingEngines.Raster; + +/// How a variant picks the next position. +internal enum RasterPolicy +{ + /// The position whose part ends leftmost, then lowest. + Leftmost, + + /// Behind the frontier of the parts placed so far first, then leftmost, then lowest. + Frontier, +} + +/// One greedy decode: the order types are placed in, which rotations it may use and how +/// it picks positions. +internal sealed record RasterVariant(IReadOnlyList Order, int Kinds, RasterPolicy Policy); + +/// +/// Greedy raster placement on one sheet. Each type in the variant's order is placed copy by copy: +/// the coarse no-fit maps of every allowed rotation list the free coarse positions, the best by +/// the variant's policy is settled on the fine grid in a small window around it (leftmost, then +/// lowest free fine position), and a proposal the fine grid refuses is skipped for the next one. +/// A type that no longer fits gives way to the next. Deterministic, budgeted by +/// . +/// +internal static class RasterSheet +{ + /// Most coarse proposals tried per placed part. + private const int MaxProposals = 4000; + + /// Gap kept between a part's material box and a clamp keep-out, so rounding cannot + /// put a flush edge inside it (the layout check's spacing slack). + private const double ClampMargin = NestTolerances.SpacingSlack; + + public static SheetLayout Fill(RasterGrid grid, IReadOnlyList types, NestPlateStock stock, + RasterVariant variant, IReadOnlyList remaining, CancellationToken token) + { + var work = stock.WorkArea; + var clamps = stock.ClampZones + .Select(z => z.Bounds) + .Select(b => new Box(b.Left - stock.ClampClearance - ClampMargin, b.Bottom - stock.ClampClearance - ClampMargin, + b.Length + 2 * (stock.ClampClearance + ClampMargin), b.Width + 2 * (stock.ClampClearance + ClampMargin))) + .ToArray(); + var cell = grid.Cell; + var fine = grid.FineCell; + var allowance = SheetPacker.OverhangAllowance; + var occupancyWords = ((int)System.Math.Ceiling((work.Length + 2 * grid.FineDilate) / fine) + 2 + 63) / 64 + 1; + var occupancyRows = (int)System.Math.Ceiling((work.Width + 2 * grid.FineDilate) / fine) + 2; + var occupancy = new ulong[occupancyRows * occupancyWords]; + var maps = new Dictionary(); + var stamps = new List<(RasterMask Mask, int X, int Y)>(); + var placed = new List<(RasterMask Mask, int X, int Y)>(); + var left = remaining.ToArray(); + var frontier = 0.0; + + foreach (var type in variant.Order) + { + while (left[type] > 0) + { + token.ThrowIfCancellationRequested(); + var candidates = grid.Masks[type] + .Where(m => (m.Kinds & variant.Kinds) != 0) + .Select(m => (Mask: m, Map: MapOf(m))) + .Where(c => c.Map.Bits.Length > 0) + .ToList(); + var cursor = candidates + .Select(c => Enumerable.Range(0, c.Map.Rows) + .Select(y => Bits64.NextClear(c.Map.Bits, y * c.Map.Words, c.Map.Words, c.Map.Columns, 0)) + .ToArray()) + .ToList(); + RasterMask? chosen = null; + int fx = 0, fy = 0; + for (var attempt = 0; attempt < MaxProposals; attempt++) + { + int best = -1, cx = 0, cy = 0; + var bestKey = (double.MaxValue, 0.0, 0.0); + for (var i = 0; i < candidates.Count; i++) + { + var m = candidates[i].Mask; + var row = cursor[i]; + for (var y = 0; y < row.Length; y++) + { + var x = row[y]; + if (x < 0) + continue; + var right = x * cell + m.Length; + var key = variant.Policy == RasterPolicy.Leftmost + ? (right, y * cell, 0.0) + : (System.Math.Max(frontier, right), x * cell, y * cell); + if (key.CompareTo(bestKey) < 0) + { + bestKey = key; + best = i; + cx = x; + cy = y; + } + } + } + if (best < 0) + break; + if (Settle(candidates[best].Mask, cx, cy, out fx, out fy)) + { + chosen = candidates[best].Mask; + break; + } + var map = candidates[best].Map; + cursor[best][cy] = Bits64.NextClear(map.Bits, cy * map.Words, map.Words, map.Columns, cx + 1); + } + if (chosen == null) + break; + placed.Add((chosen, fx, fy)); + Stamp(chosen.Fine, fx, fy); + // The coarse maps see the part at its nearest coarse position. + stamps.Add((chosen, (int)System.Math.Round((double)fx / RasterGrid.Ratio), + (int)System.Math.Round((double)fy / RasterGrid.Ratio))); + frontier = System.Math.Max(frontier, fx * fine + chosen.Length); + left[type]--; + } + } + + var counts = new int[types.Count]; + Box? envelope = null; + var poses = new List<(string PartId, double X, double Y, double Rotation)>(placed.Count); + foreach (var (mask, x, y) in placed) + { + counts[mask.Type]++; + var f = mask.Fine; + double materialLeft = work.Left + x * fine, materialBottom = work.Bottom + y * fine; + poses.Add((types[mask.Type].Id, materialLeft - f.MinX, materialBottom - f.MinY, mask.Angle)); + var box = new Box(materialLeft, materialBottom, f.Length, f.Width); + envelope = envelope == null ? box : BoundingBox.Union(envelope, box); + } + // Summed per type in type order, so equal layouts get bit-identical areas. + var area = types.Sum(t => counts[t.Index] * t.MaterialArea); + return new SheetLayout(stock, poses, area, envelope); + + // The coarse map of free positions for one mask, brought up to date with every part + // placed since it was last used. + SheetMap MapOf(RasterMask m) + { + if (!maps.TryGetValue(m, out var map)) + { + map = new SheetMap( + (int)System.Math.Floor((work.Length - m.Length + allowance) / cell + 1e-9) + 1, + (int)System.Math.Floor((work.Width - m.Width + allowance) / cell + 1e-9) + 1); + if (map.Bits.Length > 0) + foreach (var c in clamps) + { + // Every position whose material box would reach the keep-out. + var i0 = System.Math.Max(0, (int)System.Math.Floor((c.Left - m.Length - work.Left) / cell) + 1); + var i1 = System.Math.Min(map.Columns - 1, (int)System.Math.Ceiling((c.Right - work.Left) / cell) - 1); + var j0 = System.Math.Max(0, (int)System.Math.Floor((c.Bottom - m.Width - work.Bottom) / cell) + 1); + var j1 = System.Math.Min(map.Rows - 1, (int)System.Math.Ceiling((c.Top - work.Bottom) / cell) - 1); + for (var j = j0; j <= j1; j++) + for (var i = i0; i <= i1; i++) + map.Bits[j * map.Words + (i >> 6)] |= 1UL << (i & 63); + } + maps[m] = map; + } + if (map.Bits.Length == 0) + return map; + for (; map.Applied < stamps.Count; map.Applied++) + { + var (a, px, py) = stamps[map.Applied]; + var noFit = grid.NoFit(a, m); + for (var y = 0; y < noFit.H; y++) + { + var row = py + y - (m.H - 1); + if (row < 0 || row >= map.Rows) + continue; + Bits64.OrShift(map.Bits, row * map.Words, map.Words, noFit.Bits, y * noFit.Words, noFit.Words, px - (m.W - 1)); + } + } + return map; + } + + // The first free fine position in the window around a coarse proposal, leftmost then + // lowest, or false when the fine grid refuses the whole window. + bool Settle(RasterMask m, int cx, int cy, out int x, out int y) + { + var f = m.Fine; + var maxX = (int)System.Math.Floor((work.Length - f.Length + allowance) / fine + 1e-9); + var maxY = (int)System.Math.Floor((work.Width - f.Width + allowance) / fine + 1e-9); + int x0 = System.Math.Max(0, cx * RasterGrid.Ratio - grid.Span), x1 = System.Math.Min(maxX, cx * RasterGrid.Ratio + grid.Span); + int y0 = System.Math.Max(0, cy * RasterGrid.Ratio - grid.Span), y1 = System.Math.Min(maxY, cy * RasterGrid.Ratio + grid.Span); + for (x = x0; x <= x1; x++) + for (y = y0; y <= y1; y++) + if (!Collides(f, x, y) && !HitsClamp(f, x, y)) + return true; + x = y = 0; + return false; + } + + bool HitsClamp(RasterMask f, int x, int y) + { + double l = work.Left + x * fine, b = work.Bottom + y * fine; + foreach (var c in clamps) + if (l < c.Right && l + f.Length > c.Left && b < c.Top && b + f.Width > c.Bottom) + return true; + return false; + } + + bool Collides(RasterMask f, int x, int y) + { + int q = x >> 6, r = x & 63; + for (var j = 0; j < f.H; j++) + { + var at = (y + j) * occupancyWords + q; + var row = j * f.Words; + for (var w = 0; w < f.Words; w++) + { + var bits = f.Bits[row + w]; + if (bits == 0) + continue; + var o = occupancy[at + w] >> r; + if (r > 0) + o |= occupancy[at + w + 1] << (64 - r); + if ((o & bits) != 0) + return true; + } + } + return false; + } + + void Stamp(RasterMask f, int x, int y) + { + int q = x >> 6, r = x & 63; + for (var j = 0; j < f.H; j++) + { + var at = (y + j) * occupancyWords + q; + var row = j * f.Words; + for (var w = 0; w < f.Words; w++) + { + var bits = f.Bits[row + w]; + if (bits == 0) + continue; + occupancy[at + w] |= bits << r; + if (r > 0) + occupancy[at + w + 1] |= bits >> (64 - r); + } + } + } + } + + /// Coarse positions of one mask on the sheet; a set bit collides. + private sealed class SheetMap + { + public SheetMap(int columns, int rows) + { + Columns = columns; + Rows = rows; + if (columns > 0 && rows > 0) + { + Words = (columns + 63) / 64; + Bits = new ulong[rows * Words]; + } + } + + public int Columns { get; } + public int Rows { get; } + public int Words { get; } + public ulong[] Bits { get; } = Array.Empty(); + + /// Placed parts already merged into . + public int Applied { get; set; } + } +} diff --git a/README.md b/README.md index dd49bc26..8b066547 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,7 @@ A Windows desktop application for CNC nesting — imports DXF, DWG and SVG drawi - Windows 10+ for the desktop app; the console, API, shared desktop library (`OpenNest.Desktop`) and most test projects build on Linux/macOS too. `OpenNest.Avalonia` is an early cross-platform desktop prototype, not yet a usable replacement. - [.NET 8 SDK](https://dotnet.microsoft.com/download/dotnet/8.0) to build from source. -Prebuilt Windows downloads are on [GitHub Releases](https://github.com/ajisaacs/OpenNest/releases), or [build from source](#build-test-run) to run the latest code. Release ZIPs are self-contained: extract the entire archive into a new folder and run `OpenNest.exe`; no separate .NET installation is needed. For automatic updates, install with `OpenNest-win-Setup.exe` or extract `OpenNest-win-Portable.zip` instead: those copies download new full releases in the background, from GitHub Releases or, in Database mode, the nest server's mirror of them first (a hand-set feed URL overrides both) and restart only when you agree ([auto-update](docs/auto-update.md)). The plain ZIP does not auto-update; to update it, close OpenNest and extract the new release into a new folder. All nesting engines (Default, Rectangles, Irregular, Circles, FlatBar and the fill strategies) are built in; see [nesting engines](docs/nesting-engines.md). +Prebuilt Windows downloads are on [GitHub Releases](https://github.com/ajisaacs/OpenNest/releases), or [build from source](#build-test-run) to run the latest code. Release ZIPs are self-contained: extract the entire archive into a new folder and run `OpenNest.exe`; no separate .NET installation is needed. For automatic updates, install with `OpenNest-win-Setup.exe` or extract `OpenNest-win-Portable.zip` instead: those copies download new full releases in the background, from GitHub Releases or, in Database mode, the nest server's mirror of them first (a hand-set feed URL overrides both) and restart only when you agree ([auto-update](docs/auto-update.md)). The plain ZIP does not auto-update; to update it, close OpenNest and extract the new release into a new folder. All nesting engines (Default, Rectangles, Irregular, Circles, Raster, FlatBar and the fill strategies) are built in; see [nesting engines](docs/nesting-engines.md). ## Build, Test, Run diff --git a/docs/automatic-nesting.md b/docs/automatic-nesting.md index 2deb9c69..2ca1ddea 100644 --- a/docs/automatic-nesting.md +++ b/docs/automatic-nesting.md @@ -28,7 +28,7 @@ Auto Nest starts on empty/new sheets and does not change existing populated plat 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 **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, sheet sizes and free-strip direction) other than the best's, so the cards are real alternatives, such as the same job on one 60 x 120 sheet instead of one 48 x 144, or packed toward the left edge and toward the bottom, not near copies. The alternatives are ordered by parts placed, then fewer sheets, less sheet area and the larger free strip. 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, sheet sizes and free-strip direction) other than the best's, so the cards are real alternatives, such as the same job on one 60 x 120 sheet instead of one 48 x 144, or packed toward the left edge and toward the bottom, not near copies. The alternatives are ordered by parts placed, then fewer sheets, less sheet area and the larger free strip. Default, Irregular, Rectangles, Circles and Raster 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. Make Nests runs offer the same cards: using one during the search stops it and goes on with that layout, so a good enough layout need not wait for the search to finish. A Make Nests search that finishes with more than one layout counts down 5 seconds in the status line, then uses the engine's result and goes on to the next nest; picking a card stops the countdown, so the window waits for **Use This Layout** or **Discard** (which, like Stop, stops the release). 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. diff --git a/docs/nesting-engines.md b/docs/nesting-engines.md index a66a80d1..6253953b 100644 --- a/docs/nesting-engines.md +++ b/docs/nesting-engines.md @@ -6,7 +6,7 @@ see [automatic nesting and validation](automatic-nesting.md). ## Built-in engines -Engines are named for the jobs they suit, not for how or by whom they were built. Engine code lives +Engines are named for the jobs they suit, not for how or by whom they were built; Raster is the exception, named for its method because the job it suits (a fast first plan) is a speed another engine may overtake. Engine code lives in `OpenNest.Engine/NestingEngines//`, its tests in `OpenNest.Engine.Tests/NestingEngines/`. | Engine | Best for | Method | @@ -15,6 +15,7 @@ in `OpenNest.Engine/NestingEngines//`, its tests in `OpenNest.Engine.Tests | Rectangles | Plain and near-rectangular plates | Each part packed as the box of its material at its minimum-area rotation, using a maximal-rectangles free list; the sheet that finishes the job is also squeezed into a shorter or narrower bin; stock chosen sheet by sheet by salvage-credited look-ahead cost, and the whole job also run large parts first with the small parts filling their sheets' gaps | | Circles | Round parts: blanks, washers, flanges, gears by their tip circle | Each part packed as its minimum enclosing circle at centers tangent to two of walls, placed discs and clamp keep-outs, with hexagonal and square lattice seeds; bids only when every part is round; stock chosen as Rectangles does, plus whole-job runs preferring each stock and a tail re-plan | | Irregular | Irregular profiles | No-fit-polygon frontier packing with gap filling and best-fit pairs, six whole-job strategy variants (each also keeping a stock that finished the job when the per-sheet estimate passed it over for a plan that ended up dearer) and a tail re-plan, then large-first variants that pack each sheet's large parts before any small one, then grouped variants that pack like parts together, then a banded variant that packs each sheet in full-height strips, each group as its Lattice band or each strip from the largest parts down, with the last sheet of every plan it makes its best packed again as such bands, then a sheet-reduction pass that packs edge parts first and turns a key part by its contacts, then a squeeze that packs the last sheet again, largest part first, in ever shorter strips; under a time limit it first reports a quick plan without Lattice blocks, and after its search keeps trying seeded variants until the limit | +| Raster | A fast first plan of irregular parts | Each part rotation rasterized as a bit mask of its material grown by half the part spacing; coarse raster no-fit maps propose positions over the sheet and a grid four times finer settles each one; the job decoded greedily in 48 variants (orders, rotation sets, leftmost or frontier positions) and once offering every variant's sheet each round, stock chosen as Rectangles does, best by Default's ranking kept; not one of Default's candidates | | FlatBar | Flat bar: parts about as wide as the bar | Each stock read as a bar and cut in one row: the CutList cut-list packer and a best-fill search on part lengths less their self-nesting gain, then a slide-left pass that nests shaped ends and refills freed length; stock chosen bar by bar by whole-plan cost | | Lattice, Strip, Vertical Remnant, Horizontal Remnant | Many copies of a few parts | The fixed placement strategies behind interactive fill; Lattice is the multi-phase lattice fill (linear, pairs, rectangle best-fit, remainder; the pairs phase fills the strip its grid leaves with rows of pairs when they hold more than single parts, and also tiles herringbone pairs: the part turned so a hull edge lies along a sheet axis, nested into its own row, with every other row reversed), and the remnant strategies run it ranked to keep the largest drop. In whole jobs, all four place a plate with any fixed or bounded part rotation by the rotation-aware ordered placer instead | @@ -116,6 +117,7 @@ progress sink. reports such a plan with its last sheet banded (see [last-sheet bands](#last-sheet-bands)) when that beats every plan reported, and then skips the search's next best plans until one beats it. - Rectangles makes one sheet-by-sheet run, so it reports the finished job as its one plan. +- Raster runs its variants in parallel and reports the best finished job as its one plan. - Circles reports when a stock-preference run or a tail re-plan beats its best result so far. - Default scores each candidate plan as it ranks results (valid, fewest unplaced, lowest cost, then candidate order) and reports it only when it beats every plan Default has reported, so a @@ -566,6 +568,37 @@ strips on 48 x 96 with a clamp rail) the search ended the layout at 75.2 with a behind the sectors; the squeeze stacks both plates along the bottom with everything else above and beside them, ends at 62.1, and leaves a 33.4 x 47.5 drop rather than 20.3 x 47.5. +## Raster + +Raster (`OpenNest.Engine/NestingEngines/Raster/`) nests on two raster grids per part spacing. The +fine cell is an eighth of the part spacing (of 0.25 with none), coarsened only so the largest part +spans at most 2400 cells and the largest sheet 8000; the coarse cell is four fine cells. A mask +marks every cell whose center lies in the part's material, read from the outline the layout check +measures (perimeter arcs circumscribed, cutout arcs inscribed), or within half the spacing plus +0.75 cell of its edges. Two parts closer than the spacing always share a cell (the cell holding +the midpoint of their closest points is within half the spacing plus 0.71 cell of both), so masks +that never share a cell keep the spacing and every layout passes the check without a repair pass. +Cutouts stay open, so small parts nest in holes; clamp keep-outs are tested as boxes. + +Each placement picks, over every allowed rotation, the best free coarse position (the coarse +masks are grown less than half the spacing, so they propose optimistically), and settles it at the +leftmost, then lowest, free fine position within a window 1.5 coarse cells around it; a proposal +the fine grid refuses is passed over for the next, at most 4000 per part. A part free to turn +tries quarter turns, eighth turns and the turns laying its two longest convex-hull edges along the +sheet's axes; a limited part tries its legal angles (eight sweep samples at most). + +On seven real jobs (one to 292 parts, `--parallel 1`, 6" minimum salvage) every Raster layout +was valid. It matched Irregular's sheet count on five, in 0.6 to 2.3 s where Irregular took 11 to +78 s, at under 1 to 4% more salvage-credited cost; it took a third sheet where Irregular used two on a +job of ten large plates, and 24 s on a job offering seven stock sizes. It suits a quick look at a +job, not a final layout, and is not one of Default's candidates. + +Packing tighter than the spacing (masks grown by half the spacing, then half and one cell under) +and opening the gaps with Fix Spacing was tried on the same jobs: it saved under 0.1% of total +cost and took up to 25 times as long, since the 0.75-cell margin is only about a ninth of the +spacing per side. The greedy placement rule, not the margin, is what leaves Raster behind +Irregular. + ## Flat bar FlatBar treats each stock's long work-area axis as the bar's length and lays parts in a single diff --git a/scripts/ReleaseSmoke/Program.cs b/scripts/ReleaseSmoke/Program.cs index 22a8e17d..edd3c934 100644 --- a/scripts/ReleaseSmoke/Program.cs +++ b/scripts/ReleaseSmoke/Program.cs @@ -22,7 +22,7 @@ try // Every built-in engine the desktop offers must instantiate from the packaged assembly. string[] expected = [ - "Default", "Rectangles", "Irregular", "Circles", "FlatBar", + "Default", "Rectangles", "Irregular", "Circles", "Raster", "FlatBar", "Lattice", "Strip", "Vertical Remnant", "Horizontal Remnant", ]; foreach (var name in expected)