diff --git a/OpenNest.Engine/Fill/PairFiller.cs b/OpenNest.Engine/Fill/PairFiller.cs index 716c283b..5f88576f 100644 --- a/OpenNest.Engine/Fill/PairFiller.cs +++ b/OpenNest.Engine/Fill/PairFiller.cs @@ -102,6 +102,15 @@ namespace OpenNest.Engine.Fill this.remnantFiller = new PairRemnantFiller(plate, this.comparer); } + /// + /// The fill pipeline's stripe convergences, for the stripe fills of the remnant strips. + /// + internal StripeConvergenceCache StripeConvergence + { + get => remnantFiller.StripeConvergence; + init => remnantFiller.StripeConvergence = value; + } + /// /// The Fill /// diff --git a/OpenNest.Engine/Fill/PairRemnantFiller.cs b/OpenNest.Engine/Fill/PairRemnantFiller.cs index fbcd9c06..a5be01e9 100644 --- a/OpenNest.Engine/Fill/PairRemnantFiller.cs +++ b/OpenNest.Engine/Fill/PairRemnantFiller.cs @@ -50,6 +50,13 @@ namespace OpenNest.Engine.Fill this.plate = plate; } + /// + /// The fill pipeline's stripe convergences, shared with the strips' stripe fills: a strip + /// along a full side of the work area converges the same spans as the Row strategy and + /// as every other such strip. Null converges each strip on its own. + /// + internal StripeConvergenceCache StripeConvergence { get; set; } + public int EstimateUpperBound( List gridParts, Box workArea, @@ -224,6 +231,8 @@ namespace OpenNest.Engine.Fill Policy = new FillPolicy(comparer), }; context.SharedState["BestFits"] = bestFits; + if (StripeConvergence != null) + context.SharedState[StripeConvergenceCache.SharedStateKey] = StripeConvergence; // The stripe filler lays rows along both axes itself; its axis only names it. var best = new StripeFiller(context, NestDirection.Horizontal).Fill(); diff --git a/OpenNest.Engine/Fill/StripeConvergenceCache.cs b/OpenNest.Engine/Fill/StripeConvergenceCache.cs new file mode 100644 index 00000000..ef9d1ba4 --- /dev/null +++ b/OpenNest.Engine/Fill/StripeConvergenceCache.cs @@ -0,0 +1,149 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using OpenNest.Engine.BestFit; +using OpenNest.Geometry; + +namespace OpenNest.Engine.Fill; + +/// +/// One estimate row of a stripe convergence: the turned pair's span along the row and across +/// it, and the parts and remaining span of the row tiled across the sheet (zero parts and NaN +/// when none fit, or when the span leaves no room to step). +/// +internal readonly record struct StripeRow(double PairSpan, double PerpDim, int Count, double Remaining); + +/// +/// The stripe angles converged in one fill pipeline, so each pair, +/// axis, variant and span converges once, and the turned bounds and estimate rows they were +/// converged from. The Row and Column strategies converge the same layouts (both lay rows along +/// both axes), every pair remnant strip along a full side of the work area repeats the same +/// span, and the expanding and shrinking variants revisit each other's angles. Each value is a +/// pure function of its key (the pair's parts rebuilt from the drawing, the angle, the span, +/// the spacing and the row cap), so a hit returns exactly what computing it again would. A +/// canceled convergence stores no result; the rows and bounds it stored are complete. +/// +internal sealed class StripeConvergenceCache +{ + internal const string SharedStateKey = "StripeConvergence"; + + private readonly ConcurrentDictionary results = + new(); + + private readonly ConcurrentDictionary> bounds = new(); + + private readonly ConcurrentDictionary>> rows = + new(); + + /// + /// The cached convergence for the key, or the one computes, + /// stored unless it throws. + /// + public (double Angle, double Waste, int Count) GetOrAdd( + BestFitResult candidate, + Drawing drawing, + NestDirection axis, + int variant, + double sheetSpan, + double spacing, + int maxParts, + Func<(double Angle, double Waste, int Count)> converge + ) + { + var key = new Key(candidate, drawing, axis, variant, sheetSpan, spacing, maxParts); + if (results.TryGetValue(key, out var cached)) + return cached; + + // Threads converging the same key at once compute identical results; the first stored wins. + var result = converge(); + results.TryAdd(key, result); + return result; + } + + /// The number of convergences stored. + internal int Count => results.Count; + + /// The pair's parts turned about their center: bounding boxes by angle. + public ConcurrentDictionary Bounds(BestFitResult candidate, Drawing drawing) => + bounds.GetOrAdd( + new Key(candidate, drawing, default, -1, 0, 0, 0), + _ => new ConcurrentDictionary() + ); + + /// The pair's estimate rows across one span, by angle. + public ConcurrentDictionary> Rows( + BestFitResult candidate, + Drawing drawing, + NestDirection axis, + double sheetSpan, + double spacing, + int maxParts + ) => + rows.GetOrAdd( + new Key(candidate, drawing, axis, -1, sheetSpan, spacing, maxParts), + _ => new ConcurrentDictionary>() + ); + + /// Gets or creates the pipeline's cache in a fill context's shared state. + public static StripeConvergenceCache GetOrCreate(Dictionary sharedState) + { + if (sharedState.TryGetValue(SharedStateKey, out var existing)) + return (StripeConvergenceCache)existing; + + var cache = new StripeConvergenceCache(); + sharedState[SharedStateKey] = cache; + return cache; + } + + private readonly struct Key : IEquatable + { + private readonly BestFitResult candidate; + private readonly Drawing drawing; + private readonly NestDirection axis; + private readonly int variant; + private readonly long sheetSpanBits; + private readonly long spacingBits; + private readonly int maxParts; + + public Key( + BestFitResult candidate, + Drawing drawing, + NestDirection axis, + int variant, + double sheetSpan, + double spacing, + int maxParts + ) + { + this.candidate = candidate; + this.drawing = drawing; + this.axis = axis; + this.variant = variant; + sheetSpanBits = BitConverter.DoubleToInt64Bits(sheetSpan); + spacingBits = BitConverter.DoubleToInt64Bits(spacing); + this.maxParts = maxParts; + } + + public bool Equals(Key other) => + ReferenceEquals(candidate, other.candidate) + && ReferenceEquals(drawing, other.drawing) + && axis == other.axis + && variant == other.variant + && sheetSpanBits == other.sheetSpanBits + && spacingBits == other.spacingBits + && maxParts == other.maxParts; + + public override bool Equals(object obj) => obj is Key other && Equals(other); + + public override int GetHashCode() => + HashCode.Combine( + System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(candidate), + System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(drawing), + axis, + variant, + sheetSpanBits, + spacingBits, + maxParts + ); + } +} diff --git a/OpenNest.Engine/Fill/StripeFiller.cs b/OpenNest.Engine/Fill/StripeFiller.cs index 3810976d..e5cfc9e4 100644 --- a/OpenNest.Engine/Fill/StripeFiller.cs +++ b/OpenNest.Engine/Fill/StripeFiller.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Linq; @@ -23,6 +24,7 @@ public class StripeFiller private readonly NestDirection _primaryAxis; private readonly IFillComparer _comparer; private readonly GridDedup _dedup; + private readonly StripeConvergenceCache _convergence; /// /// When true, only complete stripes are placed — no partial rows/columns. @@ -35,6 +37,7 @@ public class StripeFiller _primaryAxis = primaryAxis; _comparer = context.Policy?.Comparer ?? new DefaultFillComparer(); _dedup = GridDedup.GetOrCreate(context.SharedState); + _convergence = StripeConvergenceCache.GetOrCreate(context.SharedState); } public List Fill() @@ -124,6 +127,8 @@ public class StripeFiller /// configuration is not yet claimed and no earlier layout shares it: claims are only ever /// added, so exactly those are the grids the sequential loop would have tiled. /// then claims, fills remnants and ranks in the original order. + /// Convergence goes through the pipeline's : the Column + /// strategy and pair remnant strips repeat the Row strategy's. /// private StripeLayout[] ComputeLayouts(List bestFits, Drawing drawing) { @@ -134,7 +139,7 @@ public class StripeFiller var variant = index % VariantsPerAxis; var axis = Axes[index / VariantsPerAxis % Axes.Length]; var candidate = bestFits[index / VariantsPerAxis / Axes.Length]; - layouts[index] = Converge(candidate.BuildParts(drawing), axis, variant); + layouts[index] = Converge(candidate, drawing, axis, variant); }); var batch = new GridDedup(); @@ -176,15 +181,35 @@ public class StripeFiller } } - private StripeLayout Converge(List pairParts, NestDirection axis, int variant) + private StripeLayout Converge(BestFitResult candidate, Drawing drawing, NestDirection axis, int variant) { var spacing = _context.Plate.PartSpacing; var sheetSpan = GetDimension(_context.WorkArea, axis); + var maxParts = _context.MaxQuantity; - var bounds = new RotatedBounds(pairParts); - var (angle, waste, count) = variant == 0 - ? ConvergeStripeAngle(bounds, sheetSpan, spacing, axis, _context.Token, _context.MaxQuantity) - : ConvergeStripeAngleShrink(bounds, sheetSpan, spacing, axis, _context.Token, _context.MaxQuantity); + // Convergence only reads the parts (its rotations are clones), so the pattern below is + // built from parts as fresh as those a cache hit converged. + var pairParts = candidate.BuildParts(drawing); + var (angle, waste, count) = _convergence.GetOrAdd( + candidate, + drawing, + axis, + variant, + sheetSpan, + spacing, + maxParts, + () => + { + // Both variants, and every other fill of this pipeline, share the pair's rotated + // bounds and the estimate rows tiled at each angle for this span: the variants + // revisit each other's angles, and a trajectory often cycles between two angles. + var bounds = new RotatedBounds(pairParts, _convergence.Bounds(candidate, drawing)); + var rows = _convergence.Rows(candidate, drawing, axis, sheetSpan, spacing, maxParts); + return variant == 0 + ? ConvergeStripeAngle(bounds, rows, sheetSpan, spacing, axis, _context.Token, maxParts) + : ConvergeStripeAngleShrink(bounds, rows, sheetSpan, spacing, axis, _context.Token, maxParts); + } + ); var layout = new StripeLayout { Angle = angle, Waste = waste, Count = count }; if (count > 0) @@ -397,20 +422,32 @@ public class StripeFiller /// Bounding boxes of one pattern's parts rotated about their common center, by angle. A /// box is a pure function of the parts and the angle, and the angle searches sample the /// same angles over and over (every scans the same - /// grid), so each is built once. The parts must not change while it is in use. + /// grid), so each is built once. The parts must not change while it is in use. The boxes + /// may be shared, on any thread, with other instances whose parts are built alike from the + /// same pair. /// private sealed class RotatedBounds { - private readonly Dictionary boxes = new(); + private readonly ConcurrentDictionary boxes; - public RotatedBounds(List parts) => Parts = parts; + public RotatedBounds(List parts) + : this(parts, new ConcurrentDictionary()) { } + + public RotatedBounds(List parts, ConcurrentDictionary boxes) + { + Parts = parts; + this.boxes = boxes; + } public List Parts { get; } public Box At(double angle) { if (!boxes.TryGetValue(angle, out var box)) - boxes[angle] = box = FillHelpers.BuildRotatedPattern(Parts, angle).BoundingBox; + { + box = FillHelpers.BuildRotatedPattern(Parts, angle).BoundingBox; + boxes.TryAdd(angle, box); + } return box; } } @@ -499,10 +536,12 @@ public class StripeFiller NestDirection axis, CancellationToken token = default, int maxParts = 0 - ) => ConvergeStripeAngle(new RotatedBounds(patternParts), sheetSpan, spacing, axis, token, maxParts); + ) => ConvergeStripeAngle(new RotatedBounds(patternParts), new ConcurrentDictionary>(), + sheetSpan, spacing, axis, token, maxParts); private static (double Angle, double Waste, int Count) ConvergeStripeAngle( RotatedBounds patternParts, + ConcurrentDictionary> rows, double sheetSpan, double spacing, NestDirection axis, @@ -511,7 +550,7 @@ public class StripeFiller ) { var startAngle = OrientShortSideAlong(patternParts, axis); - return ConvergeFromAngle(patternParts, startAngle, sheetSpan, spacing, axis, token, maxParts); + return ConvergeFromAngle(patternParts, rows, startAngle, sheetSpan, spacing, axis, token, maxParts); } /// @@ -525,10 +564,12 @@ public class StripeFiller NestDirection axis, CancellationToken token = default, int maxParts = 0 - ) => ConvergeStripeAngleShrink(new RotatedBounds(patternParts), sheetSpan, spacing, axis, token, maxParts); + ) => ConvergeStripeAngleShrink(new RotatedBounds(patternParts), new ConcurrentDictionary>(), + sheetSpan, spacing, axis, token, maxParts); private static (double Angle, double Waste, int Count) ConvergeStripeAngleShrink( RotatedBounds patternParts, + ConcurrentDictionary> rows, double sheetSpan, double spacing, NestDirection axis, @@ -550,11 +591,14 @@ public class StripeFiller return (0, double.MaxValue, 0); var startAngle = FindAngleForTargetSpan(patternParts, targetSpan, axis); - return ConvergeFromAngle(patternParts, startAngle, sheetSpan, spacing, axis, token, maxParts); + return ConvergeFromAngle(patternParts, rows, startAngle, sheetSpan, spacing, axis, token, maxParts); } + /// The estimate rows already tiled at each angle for these parts, span, + /// spacing, axis and cap (), shared by every convergence of them. private static (double Angle, double Waste, int Count) ConvergeFromAngle( RotatedBounds patternParts, + ConcurrentDictionary> rows, double startAngle, double sheetSpan, double spacing, @@ -573,33 +617,27 @@ public class StripeFiller { token.ThrowIfCancellationRequested(); - var rotated = FillHelpers.BuildRotatedPattern(patternParts.Parts, currentAngle); - var pairSpan = GetDimension(rotated.BoundingBox, axis); - var perpDim = - axis == NestDirection.Horizontal - ? rotated.BoundingBox.Width - : rotated.BoundingBox.Length; + // Fills of this pipeline converge on several threads at once and often reach the same + // angle together: one tiles the row while the others wait for it. + var parts = patternParts.Parts; + var row = rows.GetOrAdd( + currentAngle, + angle => new Lazy(() => + EstimateRow(parts, angle, sheetSpan, spacing, axis, maxParts)) + ).Value; + + var pairSpan = row.PairSpan; + var perpDim = row.PerpDim; if (pairSpan + spacing <= 0) break; - var stripeBox = - axis == NestDirection.Horizontal - ? new Box(0, 0, sheetSpan, perpDim) - : new Box(0, 0, perpDim, sheetSpan); - var engine = new FillLinear(stripeBox, spacing) - { - Label = "Stripe-EstimateRow", - MaxParts = maxParts, - }; - var filled = engine.Fill(rotated, axis); - var n = filled?.Count ?? 0; + var n = row.Count; if (n <= 0) break; - var filledBox = ((IEnumerable)filled).GetBoundingBox(); - var remaining = sheetSpan - GetDimension(filledBox, axis); + var remaining = row.Remaining; Debug.WriteLine( $"[Converge] iter={iteration}: angle={Angle.ToDegrees(currentAngle):F2}°, " @@ -632,6 +670,49 @@ public class StripeFiller return (bestAngle, bestWaste, bestCount); } + /// + /// One stripe row of the parts turned to , tiled across the span: + /// a pure function of its arguments. The row is not tiled when the turned pattern's span + /// leaves no room to step. + /// + private static StripeRow EstimateRow( + List patternParts, + double angle, + double sheetSpan, + double spacing, + NestDirection axis, + int maxParts + ) + { + var rotated = FillHelpers.BuildRotatedPattern(patternParts, angle); + var pairSpan = GetDimension(rotated.BoundingBox, axis); + var perpDim = + axis == NestDirection.Horizontal + ? rotated.BoundingBox.Width + : rotated.BoundingBox.Length; + + if (pairSpan + spacing <= 0) + return new StripeRow(pairSpan, perpDim, 0, double.NaN); + + var stripeBox = + axis == NestDirection.Horizontal + ? new Box(0, 0, sheetSpan, perpDim) + : new Box(0, 0, perpDim, sheetSpan); + var engine = new FillLinear(stripeBox, spacing) + { + Label = "Stripe-EstimateRow", + MaxParts = maxParts, + }; + var filled = engine.Fill(rotated, axis); + var n = filled?.Count ?? 0; + + if (n <= 0) + return new StripeRow(pairSpan, perpDim, 0, double.NaN); + + var filledBox = ((IEnumerable)filled).GetBoundingBox(); + return new StripeRow(pairSpan, perpDim, n, sheetSpan - GetDimension(filledBox, axis)); + } + private static double BisectForTarget( RotatedBounds patternParts, double lo, diff --git a/OpenNest.Engine/Strategies/PairsFillStrategy.cs b/OpenNest.Engine/Strategies/PairsFillStrategy.cs index 472cebad..b3b8fbf5 100644 --- a/OpenNest.Engine/Strategies/PairsFillStrategy.cs +++ b/OpenNest.Engine/Strategies/PairsFillStrategy.cs @@ -28,7 +28,10 @@ namespace OpenNest.Engine.Strategies { var comparer = context.Policy?.Comparer; var dedup = GridDedup.GetOrCreate(context.SharedState); - var filler = new PairFiller(context.Plate, comparer, dedup); + var filler = new PairFiller(context.Plate, comparer, dedup) + { + StripeConvergence = StripeConvergenceCache.GetOrCreate(context.SharedState), + }; var result = filler.Fill( context.Item, context.WorkArea,