From d4ad7a62015f78a30a08f7277ee11f6b68c022c0 Mon Sep 17 00:00:00 2001 From: AJ Isaacs Date: Tue, 24 Nov 2026 14:37:04 -0500 Subject: [PATCH] perf(bestfit): slide a batch on boundaries prepared once, with the same distances Best-fit slide distances rebuilt their band indexes for every offset: over half of a slide's time and nearly all of its allocation (5.8 GB for the 225,684 slides of 51 drawings). CpuDistanceComputer now slides a batch through Core's SlideBatch, which packs the two boundaries and builds their vertices, contact topology and one band index per boundary and push axis once. The pair search prepares each pair once for its first slides and its settling slides (IPreparedDistanceComputer). For pushes along an axis a slide also passes over pairs that cannot change its answer: a vertex or curve outside the other boundary's whole extent across the push, which every band test rejects, and, while the nearest contact is searched for, a pair whose gap along the push already reaches the nearest distance found, which the search discards. Both keep margins for the kernels' own tolerances; a ray hits a line up to epsilon of its length past its ends. Every distance is bit for bit what the per-slide query returns: CpuDistanceComputerEquivalenceTests compares the batch with a frozen copy of the old computer on hand-built boundaries, grazing and touching starts and the pair search's own batches. The per-slide sources and SlideResolver are unchanged and remain what every other caller uses. Co-Authored-By: Claude Fable 5.2 --- OpenNest.Core/Geometry/SlideBand.cs | 6 +- OpenNest.Core/Geometry/SlideBatch.cs | 1284 +++++++++++++++++ OpenNest.Core/Geometry/SlideEvents.cs | 2 +- .../BestFit/CpuDistanceComputer.cs | 61 +- .../BestFit/IPreparedDistanceComputer.cs | 28 + .../BestFit/RotationSlideStrategy.cs | 28 +- .../CpuDistanceComputerEquivalenceTests.cs | 658 +++++++++ .../BestFit/LegacyCpuDistanceComputer.cs | 69 + docs/geometry/directional-slides.md | 3 + 9 files changed, 2098 insertions(+), 41 deletions(-) create mode 100644 OpenNest.Core/Geometry/SlideBatch.cs create mode 100644 OpenNest.Engine/BestFit/IPreparedDistanceComputer.cs create mode 100644 OpenNest.Tests/BestFit/CpuDistanceComputerEquivalenceTests.cs create mode 100644 OpenNest.Tests/BestFit/LegacyCpuDistanceComputer.cs diff --git a/OpenNest.Core/Geometry/SlideBand.cs b/OpenNest.Core/Geometry/SlideBand.cs index 5f373417..5d89f08c 100644 --- a/OpenNest.Core/Geometry/SlideBand.cs +++ b/OpenNest.Core/Geometry/SlideBand.cs @@ -167,7 +167,7 @@ namespace OpenNest.Geometry ); } - private static bool PointMayReachSegment(double v, double a, double b) + internal static bool PointMayReachSegment(double v, double a, double b) { var lo = System.Math.Min(a, b); var hi = System.Math.Max(a, b); @@ -177,7 +177,7 @@ namespace OpenNest.Geometry return true; } - private static bool PointMayReachCircle( + internal static bool PointMayReachCircle( Axis axis, double vx, double vy, @@ -206,7 +206,7 @@ namespace OpenNest.Geometry } /// False for NaN, infinities and magnitudes beyond the coordinate limit. - private static bool Bounded(double value) => System.Math.Abs(value) <= CoordinateLimit; + internal static bool Bounded(double value) => System.Math.Abs(value) <= CoordinateLimit; internal static double Perp(Axis axis, double x, double y) => axis == Axis.PerpendicularY ? y : x; diff --git a/OpenNest.Core/Geometry/SlideBatch.cs b/OpenNest.Core/Geometry/SlideBatch.cs new file mode 100644 index 00000000..e304102d --- /dev/null +++ b/OpenNest.Core/Geometry/SlideBatch.cs @@ -0,0 +1,1284 @@ +using System.Collections.Generic; +using System.Linq; +using System.Runtime.CompilerServices; +using OpenNest.Math; + +namespace OpenNest.Geometry +{ + /// + /// One moving boundary slid against one stationary boundary from many start offsets, as a + /// best-fit batch does. returns, bit for bit, what + /// returns for an + /// (or ) source at that offset: every event that can change + /// the answer is computed by the same arithmetic on the same operands, reaches the same + /// sinks in the same order and is classified by the same contact classifier. + /// + /// + /// Four things differ from running those sources once per offset. + /// + /// Everything that does not depend on the offset is prepared once: the boundaries + /// are read into packed arrays, the vertices and contact topology are built once, and the + /// band indexes are built once per push axis instead of once per slide (they were most of + /// a slide's time and nearly all of its allocation). A slide allocates nothing; its + /// scratch lists belong to the thread. + /// A band index only chooses which pairs get the exact test, + /// and that test still decides every pair. So a shared index need only return a superset + /// of the pairs each slide's own index would, in ascending order: see + /// for why it does. + /// A vertex or curve of one boundary that lies outside the other boundary's whole + /// extent across the push, by more than any band test reaches, is passed over without + /// those tests: each of them would reject it. Most of a boundary is, when the two sit + /// side by side. + /// While the nearest event is being searched for, a pair is skipped when no event + /// of it can be nearer than the nearest found so far: the sink would discard those + /// events unchanged. See . + /// + /// The last two apply to pushes along an exact axis, which is every push of the pair + /// search; other directions enumerate every pair. + /// Call for every offset and then before sliding; + /// until the next an instance is immutable and may be shared by + /// concurrent slides. Further batches of slides of the same boundaries may follow, each + /// covered and indexed before it starts and never while slides are running. The + /// entities must not change while it is in use. + /// + internal sealed class SlideBatch + { + private const double Eps = Tolerance.Epsilon; + + private const byte OtherKind = 0; + private const byte LineKind = 1; + private const byte ArcKind = 2; + private const byte CircleKind = 3; + + // A translated coordinate is at most its untranslated magnitude plus the offset's; + // this covers the last-place difference between that sum and how Measure adds a + // radius to a translated center. + private const double Headroom = 1 + 1e-12; + + // Extra reach, relative to the largest perpendicular magnitude, of an index over + // untranslated moving extents that is queried at (value - offset). Shifting the query + // instead of the extents moves each end by a few units in the last place of those + // magnitudes (about 1.5e-15 of them in all); this is some 600,000 times that. + private const double ShiftSlack = 1e-9; + + /// + /// Margin, relative to 1 + the largest coordinate magnitude B of a slide, of the gap + /// test that skips a pair. + /// + /// + /// For a push along an exact axis every event's distance is the travel t its kernel + /// computes from one primitive of the moving boundary to one of the stationary + /// boundary. Let the gap be the distance along the push from the front of the moving + /// primitive's extent to the near side of the stationary primitive's (a vertex is a + /// point, a line its two ends, a curve its center plus and minus its radius). Then + /// the computed t is at least gap − margin: + /// + /// A ray against a line () emits only for a + /// segment parameter in [−ε, 1 + ε], ε = , so its hit + /// is at most ε of the segment's length (under 2εB) past an end; t itself is + /// rounded by a few units in the last place of B. + /// A ray against a circle () + /// hits the circle, so it is inside the curve's extent; its discriminant is rounded + /// by about 2e-14·B², which moves a root by at most 2e-7·B. Curve tangency solves + /// the same equation for a radius no larger than the two radii together. + /// An arc's closest-approach point is on its circle, then a ray against a + /// line. + /// + /// That is under 2.1e-5·B in all; the margin is nearly twice it. An event at or + /// beyond the nearest distance found so far is discarded by + /// without changing it, so a pair whose gap less + /// the margin reaches that distance is skipped with the sink left exactly as it + /// would have been. The test is false, and nothing is skipped, when no event has + /// been found, when every event is wanted, when the direction is not an axis, or + /// when any operand is not a number. + /// + private const double PruneSlack = 4 * Eps; + + private readonly Boundary moving; + private readonly Boundary stationary; + private readonly bool banded; + private readonly OffsetRange rangeY = new OffsetRange(); + private readonly OffsetRange rangeX = new OffsetRange(); + private AxisData perpendicularY; + private AxisData perpendicularX; + + private SlideBatch(Boundary moving, Boundary stationary, bool banded) + { + this.moving = moving; + this.stationary = stationary; + this.banded = banded; + } + + /// + /// Slides of native Line/Arc/Circle boundaries, as + /// with arc-to-line events enumerates them. + /// + public static SlideBatch ForEntities(List moving, List stationary) + { + // EntitySlideEvents reads a stationary entity translated by zero, which turns a + // negative zero coordinate into a positive one; keep that. + return new SlideBatch( + Pack(moving, SpatialQuery.ExtractEntityVertices(moving), false), + Pack(stationary, SpatialQuery.ExtractEntityVertices(stationary), true), + true + ); + } + + /// + /// Slides of line boundaries, as enumerates them: every + /// vertex against every line, stationary lines read as stored. + /// + public static SlideBatch ForLines(List moving, List stationary) + { + return new SlideBatch( + Pack(new List(moving), Vertices(moving), false), + Pack(new List(stationary), Vertices(stationary), false), + false + ); + } + + private static Vector[] Vertices(List lines) => + lines.SelectMany(line => new[] { line.StartPoint, line.EndPoint }).Distinct().ToArray(); + + /// Notes a slide the batch will be asked for, so its indexes cover it. + public void Cover(double dx, double dy, double dirX, double dirY) + { + if (!banded) + return; + + var band = SlideBand.For(dirX, dirY); + if (band == SlideBand.Axis.None) + return; + + var range = band == SlideBand.Axis.PerpendicularY ? rangeY : rangeX; + range.Used = true; + range.Along = Larger(range.Along, System.Math.Abs(SlideBand.Para(band, dx, dy))); + range.Perpendicular = Larger( + range.Perpendicular, + System.Math.Abs(SlideBand.Perp(band, dx, dy)) + ); + } + + /// + /// Prepares each push axis for the covered slides. Call before sliding, and again + /// after covering more slides: an axis already sized for them is kept. + /// + public void Index() + { + if (!Holds(perpendicularY, rangeY)) + perpendicularY = BuildAxis(SlideBand.Axis.PerpendicularY, rangeY); + if (!Holds(perpendicularX, rangeX)) + perpendicularX = BuildAxis(SlideBand.Axis.PerpendicularX, rangeX); + } + + private static bool Holds(AxisData data, OffsetRange range) => + data != null && range.Along <= data.Along && range.Perpendicular <= data.Perpendicular; + + /// + /// Travel along the unit direction (dirX, dirY) from the moving boundary's start at + /// (dx, dy) to the first contact that blocks, or double.MaxValue. + /// + public double FirstBlocking(double dx, double dy, double dirX, double dirY) + { + var scratch = SlideScratch.Current; + + var first = new NearestSink(); + Enumerate(ref first, dx, dy, dirX, dirY, scratch); + var nearest = first.Nearest; + + if (!nearest.Found) + return double.MaxValue; + + var origin = new Vector(dx, dy); + if (Blocks(nearest.MovingPoint, nearest.StationaryPoint, origin, dirX, dirY)) + return nearest.Distance; + + var all = new EverySink { Events = scratch.Events }; + all.Events.Clear(); + Enumerate(ref all, dx, dy, dirX, dirY, scratch); + all.Events.Sort((a, b) => a.Distance.CompareTo(b.Distance)); + + foreach (var (distance, movingPoint, stationaryPoint) in all.Events) + { + if (Blocks(movingPoint, stationaryPoint, origin, dirX, dirY)) + return distance; + } + + return double.MaxValue; + } + + // SlideContactClassifier.Blocks for a classifier placed at (origin, zero). + private bool Blocks( + Vector movingPoint, + Vector stationaryPoint, + Vector origin, + double dirX, + double dirY + ) => + SlideContact.Blocks( + moving.Contact, + movingPoint - origin, + stationary.Contact, + stationaryPoint - Vector.Zero, + dirX, + dirY + ); + + /// + /// The events of , in its order, less those + /// that cannot change the sink (see ). Without bands (line + /// boundaries) the curve phases have nothing to visit and this is + /// . + /// + private void Enumerate( + ref TSink sink, + double dx, + double dy, + double dirX, + double dirY, + SlideScratch scratch + ) + where TSink : struct, ILimitedSink + { + var band = banded ? SlideBand.For(dirX, dirY) : SlideBand.Axis.None; + var axis = AxisFor(band, dx, dy); + var alongX = band == SlideBand.Axis.PerpendicularY; + + var slide = new Slide + { + Dx = dx, + Dy = dy, + DirX = dirX, + DirY = dirY, + Band = band, + Axis = axis, + AlongX = alongX, + Forward = SlideBand.Para(band, dirX, dirY) > 0, + Shift = SlideBand.Perp(band, dx, dy), + Travel = SlideBand.Para(band, dx, dy), + Margin = axis != null ? axis.Margin : double.NaN, + }; + slide.Prune = !double.IsNaN(slide.Margin); + slide.StationaryMin = alongX ? stationary.MinX : stationary.MinY; + slide.StationaryMax = alongX ? stationary.MaxX : stationary.MaxY; + slide.MovingMin = (alongX ? moving.MinX : moving.MinY) + slide.Travel; + slide.MovingMax = (alongX ? moving.MaxX : moving.MaxY) + slide.Travel; + + // Each boundary's extent across the push (the acceptance extents of its entities, + // see Pack), widened by the farthest any band test reaches beyond an entity's + // own (see BuildAxis): a vertex or curve of one boundary outside the other's is + // rejected by every band test of that boundary, so it is passed over without + // them. NaN without an axis, which passes over nothing. + var across = axis != null ? axis.Reach : double.NaN; + var movingLow = (alongX ? moving.MinY : moving.MinX) + slide.Shift; + var movingHigh = (alongX ? moving.MaxY : moving.MaxX) + slide.Shift; + slide.StationaryLow = (alongX ? stationary.MinY : stationary.MinX) - across; + slide.StationaryHigh = (alongX ? stationary.MaxY : stationary.MaxX) + across; + slide.MovingLow = movingLow - across; + slide.MovingHigh = movingHigh + across; + + // The boundaries are nowhere level across the push: no pair can emit. + if (movingLow > slide.StationaryHigh || movingHigh < slide.StationaryLow) + return; + + // Phase 1: moving vertices along the push against stationary entities. + var vertices = moving.Vertices; + var count = vertices.Length; + for (var v = 0; v < count; v++) + { + var level = SlideBand.Perp(band, vertices[v].X + dx, vertices[v].Y + dy); + if (level < slide.StationaryLow || level > slide.StationaryHigh) + continue; + + MovingVertex(ref sink, in slide, v); + if (sink.IsDone) + return; + } + + // Phase 2: stationary vertices against the push onto moving entities. + vertices = stationary.Vertices; + count = vertices.Length; + for (var v = 0; v < count; v++) + { + var level = SlideBand.Perp(band, vertices[v].X, vertices[v].Y); + if (level < slide.MovingLow || level > slide.MovingHigh) + continue; + + StationaryVertex(ref sink, in slide, v); + if (sink.IsDone) + return; + } + + // Phase 3: arc-to-line closest points, which vertex sampling can miss. + if (moving.Curves.Length > 0 && stationary.Lines.Length > 0) + { + ArcToLine( + ref sink, in slide, moving, dx, dy, stationary, 0, 0, dirX, dirY, true, + axis?.Stationary, 0, scratch, slide.StationaryMin, slide.StationaryMax, + slide.StationaryLow, slide.StationaryHigh + ); + if (sink.IsDone) + return; + } + + if (stationary.Curves.Length > 0 && moving.Lines.Length > 0) + { + ArcToLine( + ref sink, in slide, stationary, 0, 0, moving, dx, dy, -dirX, -dirY, false, + axis?.Moving, slide.Shift, scratch, slide.MovingMin, slide.MovingMax, + slide.MovingLow, slide.MovingHigh + ); + if (sink.IsDone) + return; + } + + // Phase 4: native curve tangency, including a convex corner inside a concave arc. + var movingItems = moving.Items; + var stationaryItems = stationary.Items; + var movingCurves = moving.Curves; + var stationaryCurves = stationary.Curves; + if (stationaryCurves.Length == 0) + return; + + var curveIndex = axis?.Stationary; + var candidates = scratch.Candidates; + for (var a = 0; a < movingCurves.Length; a++) + { + var i = movingCurves[a]; + var mcx = movingItems[i].X1; + var mcy = movingItems[i].Y1; + var mr = movingItems[i].X2; + var along = SlideBand.Para(band, mcx + dx, mcy + dy); + var radius = System.Math.Abs(mr); + + if (Skip(in slide, ref sink, slide.Forward ? slide.StationaryMin - (along + radius) : along - radius - slide.StationaryMax)) + continue; + + var c = SlideBand.Perp(band, mcx + dx, mcy + dy); + var reach = SlideBandIndex.CurveReach(mr); + if (c + reach < slide.StationaryLow || c - reach > slide.StationaryHigh) + continue; + + var indexed = false; + if (curveIndex != null) + { + indexed = curveIndex.TryRange(c - reach, c + reach, candidates); + } + + var visits = indexed ? candidates.Count : stationaryCurves.Length; + for (var n = 0; n < visits; n++) + { + var j = indexed ? candidates[n] : stationaryCurves[n]; + ref readonly var curve = ref stationaryItems[j]; + if (curve.Kind != ArcKind && curve.Kind != CircleKind) + continue; + + if (Skip(in slide, ref sink, slide.Forward ? Lo(in curve, alongX) - (along + radius) : along - radius - Hi(in curve, alongX))) + continue; + + if ( + band != SlideBand.Axis.None + && !SlideBand.CirclesMayTouch( + band, mcx + dx, mcy + dy, mr, curve.RawX, curve.RawY, curve.X2 + ) + ) + continue; + + SlideEvents.CurveTangency( + ref sink, + mcx + dx, + mcy + dy, + mr, + moving.Arcs[i], + curve.RawX, + curve.RawY, + curve.X2, + stationary.Arcs[j], + dirX, + dirY + ); + if (sink.IsDone) + return; + } + } + } + + /// + /// One moving vertex of phase 1: its ray along the push against the stationary + /// entities. + /// + private void MovingVertex(ref TSink sink, in Slide slide, int v) + where TSink : struct, ILimitedSink + { + var band = slide.Band; + var alongX = slide.AlongX; + var vx = moving.Vertices[v].X + slide.Dx; + var vy = moving.Vertices[v].Y + slide.Dy; + var along = SlideBand.Para(band, vx, vy); + + if (Skip(in slide, ref sink, slide.Forward ? slide.StationaryMin - along : along - slide.StationaryMax)) + return; + + // SlideBand.RayMayHit keeps every entity for a vertex that is not bounded. + var test = band != SlideBand.Axis.None && SlideBand.Bounded(vx) && SlideBand.Bounded(vy); + var items = stationary.Items; + var index = slide.Axis?.Stationary; + + if ( + index != null + && index.TryPoint(SlideBand.Perp(band, vx, vy), out var first, out var last) + ) + { + for (var k = first; k < last; k++) + { + ref readonly var item = ref items[index.Item(k)]; + if (Skip(in slide, ref sink, slide.Forward ? Lo(in item, alongX) - along : along - Hi(in item, alongX))) + continue; + if (test && !MayHit(band, vx, vy, in item, item.X1, item.Y1, item.X2, item.Y2)) + continue; + Ray(ref sink, vx, vy, in item, item.X1, item.Y1, item.X2, item.Y2, slide.DirX, slide.DirY, true); + if (sink.IsDone) + return; + } + return; + } + + for (var j = 0; j < items.Length; j++) + { + ref readonly var item = ref items[j]; + if (Skip(in slide, ref sink, slide.Forward ? Lo(in item, alongX) - along : along - Hi(in item, alongX))) + continue; + if (test && !MayHit(band, vx, vy, in item, item.X1, item.Y1, item.X2, item.Y2)) + continue; + Ray(ref sink, vx, vy, in item, item.X1, item.Y1, item.X2, item.Y2, slide.DirX, slide.DirY, true); + if (sink.IsDone) + return; + } + } + + /// + /// One stationary vertex of phase 2: its ray against the push onto the moving + /// entities. + /// + private void StationaryVertex(ref TSink sink, in Slide slide, int v) + where TSink : struct, ILimitedSink + { + var band = slide.Band; + var alongX = slide.AlongX; + var dx = slide.Dx; + var dy = slide.Dy; + var travel = slide.Travel; + var vx = stationary.Vertices[v].X; + var vy = stationary.Vertices[v].Y; + var along = SlideBand.Para(band, vx, vy); + + if (Skip(in slide, ref sink, slide.Forward ? along - slide.MovingMax : slide.MovingMin - along)) + return; + + var test = band != SlideBand.Axis.None && SlideBand.Bounded(vx) && SlideBand.Bounded(vy); + var items = moving.Items; + var index = slide.Axis?.Moving; + + // The moving index holds untranslated extents: ask it where the vertex is in + // the moving boundary's own frame. + if ( + index != null + && index.TryPoint(SlideBand.Perp(band, vx, vy) - slide.Shift, out var first, out var last) + ) + { + for (var k = first; k < last; k++) + { + ref readonly var item = ref items[index.Item(k)]; + if (Skip(in slide, ref sink, slide.Forward ? along - (Hi(in item, alongX) + travel) : Lo(in item, alongX) + travel - along)) + continue; + var ax = item.X1 + dx; + var ay = item.Y1 + dy; + var bx = item.X2 + dx; + var by = item.Y2 + dy; + if (test && !MayHit(band, vx, vy, in item, ax, ay, bx, by)) + continue; + Ray(ref sink, vx, vy, in item, ax, ay, bx, by, -slide.DirX, -slide.DirY, false); + if (sink.IsDone) + return; + } + return; + } + + for (var j = 0; j < items.Length; j++) + { + ref readonly var item = ref items[j]; + if (Skip(in slide, ref sink, slide.Forward ? along - (Hi(in item, alongX) + travel) : Lo(in item, alongX) + travel - along)) + continue; + var ax = item.X1 + dx; + var ay = item.Y1 + dy; + var bx = item.X2 + dx; + var by = item.Y2 + dy; + if (test && !MayHit(band, vx, vy, in item, ax, ay, bx, by)) + continue; + Ray(ref sink, vx, vy, in item, ax, ay, bx, by, -slide.DirX, -slide.DirY, false); + if (sink.IsDone) + return; + } + } + + /// + /// True when no event of a pair whose gap along the push is + /// can change the sink (see ): its distance would be at or + /// beyond what the sink already discards. False whenever an operand is not a + /// number. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static bool Skip(in Slide slide, ref TSink sink, double gap) + where TSink : struct, ILimitedSink + { + return slide.Prune && gap - slide.Margin >= sink.Limit; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static double Lo(in Item item, bool alongX) => alongX ? item.LoX : item.LoY; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static double Hi(in Item item, bool alongX) => alongX ? item.HiX : item.HiY; + + /// + /// after its vertex check, for an entity whose + /// translated coordinates are (ax, ay)-(bx, by). + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static bool MayHit( + SlideBand.Axis band, + double vx, + double vy, + in Item item, + double ax, + double ay, + double bx, + double by + ) + { + switch (item.Kind) + { + case LineKind: + if ( + !SlideBand.Bounded(ax) || !SlideBand.Bounded(ay) + || !SlideBand.Bounded(bx) || !SlideBand.Bounded(by) + ) + return true; + return SlideBand.PointMayReachSegment( + SlideBand.Perp(band, vx, vy), + SlideBand.Perp(band, ax, ay), + SlideBand.Perp(band, bx, by) + ); + case ArcKind: + case CircleKind: + return SlideBand.PointMayReachCircle(band, vx, vy, ax, ay, item.X2); + default: + return true; + } + } + + /// for an entity translated to (ax, ay)-(bx, by). + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void Ray( + ref TSink sink, + double vx, + double vy, + in Item item, + double ax, + double ay, + double bx, + double by, + double rayX, + double rayY, + bool vertexMoves + ) + where TSink : struct, ISlideEventSink + { + switch (item.Kind) + { + case LineKind: + SlideEvents.RayLine(ref sink, vx, vy, ax, ay, bx, by, rayX, rayY, vertexMoves); + break; + case ArcKind: + RayArc(ref sink, vx, vy, in item, ax, ay, rayX, rayY, vertexMoves); + break; + case CircleKind: + RayCircle(ref sink, vx, vy, ax, ay, item.X2, rayX, rayY, vertexMoves); + break; + } + } + + private static void RayArc( + ref TSink sink, + double vx, + double vy, + in Item arc, + double cx, + double cy, + double rayX, + double rayY, + bool vertexMoves + ) + where TSink : struct, ISlideEventSink + { + if (!SlideCurvePrimitives.SolveRayCircle(vx, vy, cx, cy, arc.X2, rayX, rayY, out var t1, out var t2)) + return; + + for (var k = 0; k < 2; k++) + { + var t = k == 0 ? t1 : t2; + if (t <= -Eps) + continue; + + var hitAngle = Normalize(PortableMath.Atan2(vy + t * rayY - cy, vx + t * rayX - cx)); + if (!Contains(in arc, hitAngle)) + continue; + + SlideEvents.Emit(ref sink, vx, vy, t, rayX, rayY, vertexMoves); + if (sink.IsDone) + return; + } + } + + private static void RayCircle( + ref TSink sink, + double vx, + double vy, + double cx, + double cy, + double r, + double rayX, + double rayY, + bool vertexMoves + ) + where TSink : struct, ISlideEventSink + { + if (!SlideCurvePrimitives.SolveRayCircle(vx, vy, cx, cy, r, rayX, rayY, out var t1, out var t2)) + return; + + for (var k = 0; k < 2; k++) + { + var t = k == 0 ? t1 : t2; + if (t < -Eps) + continue; + + SlideEvents.Emit(ref sink, vx, vy, t, rayX, rayY, vertexMoves); + if (sink.IsDone) + return; + } + } + + /// + /// for the curves of one boundary against the + /// lines of the other. The directions of a line's two closest-approach points and + /// their cosines and sines depend only on the line's direction, so they are looked up + /// (see ) instead of being recomputed for every arc. + /// + private static void ArcToLine( + ref TSink sink, + in Slide slide, + Boundary arcs, + double arcDx, + double arcDy, + Boundary lines, + double lineDx, + double lineDy, + double rayX, + double rayY, + bool arcMoves, + SlideBandIndex lineIndex, + double lineShift, + SlideScratch scratch, + double linesMin, + double linesMax, + double linesLow, + double linesHigh + ) + where TSink : struct, ILimitedSink + { + var band = slide.Band; + var arcItems = arcs.Items; + var lineItems = lines.Items; + var curves = arcs.Curves; + var allLines = lines.Lines; + var candidates = scratch.Candidates; + + // The gap test: the arc is ahead of the line along the push when it moves with + // the push or stands still against a push the other way. + var alongX = slide.AlongX; + var ahead = arcMoves == slide.Forward; + var lineSlide = SlideBand.Para(band, lineDx, lineDy); + + for (var a = 0; a < curves.Length; a++) + { + ref readonly var arc = ref arcItems[curves[a]]; + var r = arc.X2; + var isArc = arc.Kind == ArcKind; + var cx = arc.X1 + arcDx; + var cy = arc.Y1 + arcDy; + var radius = System.Math.Abs(r); + var along = SlideBand.Para(band, cx, cy); + + if (Skip(in slide, ref sink, ahead ? linesMin - (along + radius) : along - radius - linesMax)) + continue; + + var c = SlideBand.Perp(band, cx, cy); + if (c + radius < linesLow || c - radius > linesHigh) + continue; + + // With an index, visit only the entities whose extents the circle's meets, + // ascending; the lines among them are those CircleMayReachLine can accept. + var indexed = false; + if (lineIndex != null) + { + indexed = lineIndex.TryRange(c - radius - lineShift, c + radius - lineShift, candidates); + } + + var count = indexed ? candidates.Count : allLines.Length; + for (var n = 0; n < count; n++) + { + ref readonly var line = ref lineItems[indexed ? candidates[n] : allLines[n]]; + if (line.Kind != LineKind) + continue; + + if ( + Skip( + in slide, + ref sink, + ahead + ? Lo(in line, alongX) + lineSlide - (along + radius) + : along - radius - (Hi(in line, alongX) + lineSlide) + ) + ) + continue; + + var p1x = line.X1 + lineDx; + var p1y = line.Y1 + lineDy; + var p2x = line.X2 + lineDx; + var p2y = line.Y2 + lineDy; + + if ( + band != SlideBand.Axis.None + && !SlideBand.CircleMayReachLine(band, cx, cy, r, p1x, p1y, p2x, p2y) + ) + continue; + + var ex = p2x - p1x; + var ey = p2y - p1y; + + var det = ex * rayY - ey * rayX; + if (System.Math.Abs(det) < Eps) + continue; + + ref readonly var normal = ref scratch.Normal(ex, ey); + + for (var k = 0; k < 2; k++) + { + if (isArc && !Contains(in arc, k == 0 ? normal.Theta1 : normal.Theta2)) + continue; + + var qx = cx + r * (k == 0 ? normal.Cos1 : normal.Cos2); + var qy = cy + r * (k == 0 ? normal.Sin1 : normal.Sin2); + + SlideEvents.RayLine(ref sink, qx, qy, p1x, p1y, p2x, p2y, rayX, rayY, arcMoves); + if (sink.IsDone) + return; + } + } + } + } + + /// + /// . An angle within one turn of zero is its own + /// remainder, so the division is skipped for it. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static double Normalize(double angle) + { + if (angle >= 0) + { + if (angle < Angle.TwoPI) + return angle; + } + else if (angle > -Angle.TwoPI) + { + return Angle.TwoPI + angle; + } + + return Angle.NormalizeRad(angle); + } + + /// + /// for the arc's angles, with the parts that depend + /// only on the arc (the swap for a reversed arc, the sweep and the full-circle test) + /// taken from the packed item. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static bool Contains(in Item arc, double angle) + { + if (arc.Full) + return true; + + return arc.Sweep >= Normalize(angle - arc.From) - Eps + || arc.Sweep >= Normalize(arc.To - angle) - Eps; + } + + private static double Larger(double max, double value) => + value > max || double.IsNaN(value) ? value : max; + + /// + /// What was prepared for an axis, or null when the slide is not along one or starts + /// outside the offsets it was sized for (the band tests then scan everything and + /// nothing is skipped, as without it). + /// + private AxisData AxisFor(SlideBand.Axis band, double dx, double dy) + { + if (band == SlideBand.Axis.None) + return null; + + var axis = band == SlideBand.Axis.PerpendicularY ? perpendicularY : perpendicularX; + if (axis == null) + return null; + + return + System.Math.Abs(SlideBand.Para(band, dx, dy)) <= axis.Along + && System.Math.Abs(SlideBand.Perp(band, dx, dy)) <= axis.Perpendicular + ? axis + : null; + } + + /// + /// The gap-test margin and the band indexes shared by every covered slide along one + /// axis. + /// + /// + /// A slide's own indexes () hold each entity's + /// exact acceptance extent widened by a reach sized from that slide's coordinates. A + /// pair the band test accepts has its query value inside that extent, and a value + /// inside an extent is always found, whatever the bucket layout. The shared indexes + /// keep that property for every covered slide: + /// + /// Stationary extents do not depend on the offset. The shared reach is + /// of bounds no smaller than any covered slide's, + /// and Reach never decreases as its arguments grow, so each shared extent contains + /// the slide's own. + /// Moving extents move with the offset. They are indexed untranslated and + /// queried at the value minus the offset, which is the same containment test up to + /// rounding of the translation; widens the reach by far + /// more than that rounding. + /// + /// Queries return ascending entity indices without repeats, so the surviving pairs + /// keep their order. An index is left out exactly where the per-slide code leaves it + /// out or where no bound is usable; the band tests then scan every entity. + /// + private AxisData BuildAxis(SlideBand.Axis axis, OffsetRange range) + { + if (!range.Used) + return null; + + double along = 0, + perpendicular = 0; + SlideBandIndex.Measure( + axis, stationary.Entities, stationary.Vertices, 0, 0, ref along, ref perpendicular + ); + double movingAlong = 0, + movingPerpendicular = 0; + SlideBandIndex.Measure( + axis, moving.Entities, moving.Vertices, 0, 0, ref movingAlong, ref movingPerpendicular + ); + + along = Larger(along, (movingAlong + range.Along) * Headroom); + perpendicular = Larger(perpendicular, (movingPerpendicular + range.Perpendicular) * Headroom); + + // The perpendicular bound includes every radius, so the sum bounds every + // coordinate and radius of every covered slide. + var size = along + perpendicular; + var reach = SlideBandIndex.Reach(along, perpendicular); + var movingReach = reach + ShiftSlack * (1 + perpendicular + reach); + var data = new AxisData + { + Along = range.Along, + Perpendicular = range.Perpendicular, + Margin = size <= SlideBand.CoordinateLimit ? PruneSlack * (1 + size) : double.NaN, + Reach = double.IsFinite(movingReach) ? movingReach : double.NaN, + }; + + if ( + stationary.Items.Length < SlideBandIndex.MinimumEntities + && moving.Items.Length < SlideBandIndex.MinimumEntities + ) + return data; + + if (!double.IsFinite(reach)) + return data; + + // One index of every entity per boundary. The per-slide code keeps separate + // line and curve indexes for the curve phases; an entity's extent is the same in + // each, so the one index returns their entities among others, which those + // phases pass over by kind. + var all = SlideBandIndex.Kind.All; + data.Stationary = SlideBandIndex.Build(axis, stationary.Entities, 0, 0, reach, all); + data.Moving = SlideBandIndex.Build(axis, moving.Entities, 0, 0, movingReach, all); + return data; + } + + private static Boundary Pack(List entities, Vector[] vertices, bool translateByZero) + { + var count = entities.Count; + var items = new Item[count]; + var arcs = new Arc[count]; + var lineCount = 0; + var curveCount = 0; + + // Math.Min and Math.Max keep a NaN, which then fails every gap test. + var minX = double.PositiveInfinity; + var minY = double.PositiveInfinity; + var maxX = double.NegativeInfinity; + var maxY = double.NegativeInfinity; + + // Translating by zero is what the kernels do to a stationary entity; it is not a + // no-op for a negative zero. + double zero = 0; + + for (var i = 0; i < count; i++) + { + ref var item = ref items[i]; + switch (entities[i]) + { + case Line line: + item.Kind = LineKind; + item.X1 = translateByZero ? line.pt1.X + zero : line.pt1.X; + item.Y1 = translateByZero ? line.pt1.Y + zero : line.pt1.Y; + item.X2 = translateByZero ? line.pt2.X + zero : line.pt2.X; + item.Y2 = translateByZero ? line.pt2.Y + zero : line.pt2.Y; + item.LoX = System.Math.Min(item.X1, item.X2); + item.HiX = System.Math.Max(item.X1, item.X2); + item.LoY = System.Math.Min(item.Y1, item.Y2); + item.HiY = System.Math.Max(item.Y1, item.Y2); + lineCount++; + break; + + case Arc arc: + { + item.Kind = ArcKind; + var center = arc.Center; + item.RawX = center.X; + item.RawY = center.Y; + item.X1 = translateByZero ? center.X + zero : center.X; + item.Y1 = translateByZero ? center.Y + zero : center.Y; + item.X2 = arc.Radius; + CircleExtent(ref item); + + // Angle.IsBetweenRad(angle, StartAngle, EndAngle, IsReversed). + var a1 = arc.StartAngle; + var a2 = arc.EndAngle; + if (arc.IsReversed) + Generic.Swap(ref a1, ref a2); + item.From = a1; + item.To = a2; + item.Sweep = Angle.NormalizeRad(a2 - a1); + item.Full = a2.IsEqualTo(a1); + arcs[i] = arc; + curveCount++; + break; + } + + case Circle circle: + { + item.Kind = CircleKind; + var center = circle.Center; + item.RawX = center.X; + item.RawY = center.Y; + item.X1 = translateByZero ? center.X + zero : center.X; + item.Y1 = translateByZero ? center.Y + zero : center.Y; + item.X2 = circle.Radius; + CircleExtent(ref item); + curveCount++; + break; + } + + default: + // No kernel emits for it; a NaN extent is never skipped. + item.Kind = OtherKind; + item.LoX = item.HiX = item.LoY = item.HiY = double.NaN; + continue; + } + + // The band tests accept a ray up to SpanSlack of a line's span past its + // ends (SlideBand.PointMayReachSegment), a curve's within its circle. + var slackX = item.Kind == LineKind ? SlideBand.SpanSlack * (item.HiX - item.LoX) : 0; + var slackY = item.Kind == LineKind ? SlideBand.SpanSlack * (item.HiY - item.LoY) : 0; + minX = System.Math.Min(minX, item.LoX - slackX); + minY = System.Math.Min(minY, item.LoY - slackY); + maxX = System.Math.Max(maxX, item.HiX + slackX); + maxY = System.Math.Max(maxY, item.HiY + slackY); + } + + // Vertices are points of the entities, give or take the rounding of an arc's ends. + for (var i = 0; i < vertices.Length; i++) + { + minX = System.Math.Min(minX, vertices[i].X); + minY = System.Math.Min(minY, vertices[i].Y); + maxX = System.Math.Max(maxX, vertices[i].X); + maxY = System.Math.Max(maxY, vertices[i].Y); + } + + var lineIndices = new int[lineCount]; + var curveIndices = new int[curveCount]; + lineCount = curveCount = 0; + for (var i = 0; i < count; i++) + { + if (items[i].Kind == LineKind) + lineIndices[lineCount++] = i; + else if (items[i].Kind != OtherKind) + curveIndices[curveCount++] = i; + } + + return new Boundary + { + Entities = entities, + Items = items, + Arcs = arcs, + Lines = lineIndices, + Curves = curveIndices, + Vertices = vertices, + Contact = SlideContactGeometry.Prepare(entities), + MinX = minX, + MinY = minY, + MaxX = maxX, + MaxY = maxY, + }; + } + + private static void CircleExtent(ref Item item) + { + var radius = System.Math.Abs(item.X2); + item.LoX = item.X1 - radius; + item.HiX = item.X1 + radius; + item.LoY = item.Y1 - radius; + item.HiY = item.Y1 + radius; + } + + /// A sink that can say which events it would discard unchanged. + private interface ILimitedSink : ISlideEventSink + { + /// + /// An event at or beyond this distance leaves the sink as it is. NaN while every + /// event counts. + /// + double Limit { get; } + } + + /// The values of one slide the phases share. + private struct Slide + { + public double Dx; + public double Dy; + public double DirX; + public double DirY; + public SlideBand.Axis Band; + public AxisData Axis; + + /// The push is along X. + public bool AlongX; + + /// The push is toward the positive end of its axis. + public bool Forward; + + /// The offset's components across and along the push. + public double Shift; + public double Travel; + + /// The gap test is usable (see PruneSlack), with this margin. + public bool Prune; + public double Margin; + + /// Extents along the push, the moving one translated. + public double StationaryMin; + public double StationaryMax; + public double MovingMin; + public double MovingMax; + + /// + /// Extents across the push, the moving one translated, each widened by the + /// reach of the band tests. + /// + public double StationaryLow; + public double StationaryHigh; + public double MovingLow; + public double MovingHigh; + } + + /// , which discards anything not nearer. + private struct NearestSink : ILimitedSink + { + public NearestSlideEvent Nearest; + + public bool IsDone => Nearest.IsDone; + + public double Limit => Nearest.Found ? Nearest.Distance : double.NaN; + + public void Add(double distance, Vector movingPoint, Vector stationaryPoint) => + Nearest.Add(distance, movingPoint, stationaryPoint); + } + + /// : keeps every event. + private struct EverySink : ILimitedSink + { + public List<(double Distance, Vector MovingPoint, Vector StationaryPoint)> Events; + + public bool IsDone => false; + + public double Limit => double.NaN; + + public void Add(double distance, Vector movingPoint, Vector stationaryPoint) => + Events.Add((distance, movingPoint, stationaryPoint)); + } + + private struct Item + { + // The entity's extent: a line's ends, a curve's center plus and minus its radius. + public double LoX; + public double HiX; + public double LoY; + public double HiY; + + // A line's ends, or a curve's center (X1, Y1) and radius (X2), as the kernels + // read them. + public double X1; + public double Y1; + public double X2; + public double Y2; + + // A curve's center as stored: the tangency phase reads a stationary curve + // without translating it. + public double RawX; + public double RawY; + + // An arc's angles in the order Angle.IsBetweenRad tests them, the sweep between + // them and whether it reads them as a full circle. + public double From; + public double To; + public double Sweep; + public bool Full; + + public byte Kind; + } + + private sealed class Boundary + { + public List Entities; + public Item[] Items; + + /// Per entity, the arc or null. + public Arc[] Arcs; + + /// Indices of the lines, ascending. + public int[] Lines; + + /// Indices of the arcs and circles, ascending. + public int[] Curves; + + public Vector[] Vertices; + public SlideContactGeometry Contact; + + // The extent of every vertex and of every entity as the band tests accept it: a + // line with their slack past its ends, a curve as its whole circle. + public double MinX; + public double MinY; + public double MaxX; + public double MaxY; + } + + private sealed class OffsetRange + { + public bool Used; + public double Along; + public double Perpendicular; + } + + private sealed class AxisData + { + /// Largest |along| and |perpendicular| offset this was sized for. + public double Along; + public double Perpendicular; + + /// The gap-test margin, or NaN when the coordinates are not usable. + public double Margin; + + /// + /// How far across the push any band test reaches beyond an entity's extent, with + /// the slack of a shifted query; NaN when the coordinates are not usable. + /// + public double Reach; + + public SlideBandIndex Stationary; + public SlideBandIndex Moving; + } + } + + /// Per-thread working storage of slides. + internal sealed class SlideScratch + { + // A power of two. Larger than the line directions of two boundaries in a few frames. + private const int NormalSlots = 2048; + + [System.ThreadStatic] + private static SlideScratch current; + + private readonly LineNormal[] normals = new LineNormal[NormalSlots]; + + public static SlideScratch Current => current ??= new SlideScratch(); + + /// Scratch list for range queries. + public List Candidates { get; } = new List(); + + /// Every event of a slide whose nearest contact did not block. + public List<(double Distance, Vector MovingPoint, Vector StationaryPoint)> Events { get; } = + new List<(double Distance, Vector MovingPoint, Vector StationaryPoint)>(); + + /// + /// The two arc angles at which the directional distance to a line of direction + /// (ex, ey) is stationary, as computes them, with + /// their cosines and sines. A pure function of the exact bits of (ex, ey), so a value + /// remembered from any earlier slide is the value computing it again would give. + /// + public ref readonly LineNormal Normal(double ex, double ey) + { + var exBits = System.BitConverter.DoubleToInt64Bits(ex); + var eyBits = System.BitConverter.DoubleToInt64Bits(ey); + var hash = (ulong)exBits * 0x9E3779B97F4A7C15UL + (ulong)eyBits * 0xC2B2AE3D27D4EB4FUL; + ref var slot = ref normals[(int)(hash >> 40) & (NormalSlots - 1)]; + + if (!slot.Set || slot.ExBits != exBits || slot.EyBits != eyBits) + { + var theta1 = Angle.NormalizeRad(PortableMath.Atan2(-ex, ey)); + var theta2 = Angle.NormalizeRad(theta1 + System.Math.PI); + slot.ExBits = exBits; + slot.EyBits = eyBits; + slot.Theta1 = theta1; + slot.Theta2 = theta2; + slot.Cos1 = PortableMath.Cos(theta1); + slot.Sin1 = PortableMath.Sin(theta1); + slot.Cos2 = PortableMath.Cos(theta2); + slot.Sin2 = PortableMath.Sin(theta2); + slot.Set = true; + } + + return ref slot; + } + + internal struct LineNormal + { + public long ExBits; + public long EyBits; + public double Theta1; + public double Theta2; + public double Cos1; + public double Sin1; + public double Cos2; + public double Sin2; + public bool Set; + } + } +} diff --git a/OpenNest.Core/Geometry/SlideEvents.cs b/OpenNest.Core/Geometry/SlideEvents.cs index 1f1f6fc1..d5ac44f7 100644 --- a/OpenNest.Core/Geometry/SlideEvents.cs +++ b/OpenNest.Core/Geometry/SlideEvents.cs @@ -415,7 +415,7 @@ namespace OpenNest.Geometry } } - private static void Emit( + internal static void Emit( ref TSink sink, double vx, double vy, diff --git a/OpenNest.Engine/BestFit/CpuDistanceComputer.cs b/OpenNest.Engine/BestFit/CpuDistanceComputer.cs index be9fa49a..961436f5 100644 --- a/OpenNest.Engine/BestFit/CpuDistanceComputer.cs +++ b/OpenNest.Engine/BestFit/CpuDistanceComputer.cs @@ -1,10 +1,14 @@ using System.Collections.Generic; -using System.Linq; using OpenNest.Geometry; namespace OpenNest.Engine.BestFit { - public class CpuDistanceComputer : IDistanceComputer + /// + /// Slides one boundary against another from every offset of a batch. The boundaries are + /// prepared once (); each slide then returns what + /// returns for that offset, bit for bit. + /// + public class CpuDistanceComputer : IPreparedDistanceComputer { public double[] ComputeDistances( List stationaryLines, @@ -12,22 +16,7 @@ namespace OpenNest.Engine.BestFit SlideOffset[] offsets ) { - var results = new double[offsets.Length]; - var movingVertices = Vertices(movingTemplateLines); - var stationaryVertices = Vertices(stationaryLines); - var contacts = SlideContactClassifier.FromLines( - movingTemplateLines, Vector.Zero, stationaryLines, Vector.Zero).Prepare(); - - System.Threading.Tasks.Parallel.For(0, offsets.Length, i => - { - var offset = offsets[i]; - var source = new LineSlideEvents( - movingTemplateLines, movingVertices, offset.Dx, offset.Dy, - stationaryLines, stationaryVertices, offset.DirX, offset.DirY); - results[i] = SlideResolver.FirstBlocking(ref source, - contacts.At(new Vector(offset.Dx, offset.Dy), Vector.Zero), offset.DirX, offset.DirY); - }); - return results; + return Slide(SlideBatch.ForLines(movingTemplateLines, stationaryLines), offsets); } public double[] ComputeDistances( @@ -35,27 +24,43 @@ namespace OpenNest.Engine.BestFit List movingEntities, SlideOffset[] offsets ) + { + return Slide(SlideBatch.ForEntities(movingEntities, stationaryEntities), offsets); + } + + public IPreparedDistances Prepare(List stationaryEntities, List movingEntities) + { + return new Prepared(SlideBatch.ForEntities(movingEntities, stationaryEntities)); + } + + private static double[] Slide(SlideBatch batch, SlideOffset[] offsets) { var results = new double[offsets.Length]; - var movingVertices = SpatialQuery.ExtractEntityVertices(movingEntities); - var stationaryVertices = SpatialQuery.ExtractEntityVertices(stationaryEntities); - var contacts = new SlideContactClassifier(movingEntities, stationaryEntities).Prepare(); + + for (var i = 0; i < offsets.Length; i++) + batch.Cover(offsets[i].Dx, offsets[i].Dy, offsets[i].DirX, offsets[i].DirY); + batch.Index(); // All vertices participate: a leading-half filter can miss the next contact // after sliding past an initial touch on a concave boundary. System.Threading.Tasks.Parallel.For(0, offsets.Length, i => { var offset = offsets[i]; - var source = new EntitySlideEvents( - movingEntities, movingVertices, offset.Dx, offset.Dy, - stationaryEntities, stationaryVertices, offset.DirX, offset.DirY, arcToLine: true); - results[i] = SlideResolver.FirstBlocking(ref source, - contacts.At(new Vector(offset.Dx, offset.Dy), Vector.Zero), offset.DirX, offset.DirY); + results[i] = batch.FirstBlocking(offset.Dx, offset.Dy, offset.DirX, offset.DirY); }); return results; } - private static Vector[] Vertices(List lines) => - lines.SelectMany(line => new[] { line.StartPoint, line.EndPoint }).Distinct().ToArray(); + private sealed class Prepared : IPreparedDistances + { + private readonly SlideBatch batch; + + public Prepared(SlideBatch batch) + { + this.batch = batch; + } + + public double[] ComputeDistances(SlideOffset[] offsets) => Slide(batch, offsets); + } } } diff --git a/OpenNest.Engine/BestFit/IPreparedDistanceComputer.cs b/OpenNest.Engine/BestFit/IPreparedDistanceComputer.cs new file mode 100644 index 00000000..2f444cd5 --- /dev/null +++ b/OpenNest.Engine/BestFit/IPreparedDistanceComputer.cs @@ -0,0 +1,28 @@ +using System.Collections.Generic; +using OpenNest.Geometry; + +namespace OpenNest.Engine.BestFit +{ + /// + /// A distance computer that can prepare one pair of boundaries once for several batches + /// of slides, as the pair search does: the grid of first slides, then the settling slides + /// of the same two boundaries. + /// + public interface IPreparedDistanceComputer : IDistanceComputer + { + /// + /// Prepares the boundaries. The lists must not change while the result is in use. + /// + IPreparedDistances Prepare(List stationaryEntities, List movingEntities); + } + + /// One pair of boundaries prepared by an . + public interface IPreparedDistances + { + /// + /// What + /// returns for the prepared boundaries and these offsets. One batch at a time. + /// + double[] ComputeDistances(SlideOffset[] offsets); + } +} diff --git a/OpenNest.Engine/BestFit/RotationSlideStrategy.cs b/OpenNest.Engine/BestFit/RotationSlideStrategy.cs index ab5dfa27..8779f05f 100644 --- a/OpenNest.Engine/BestFit/RotationSlideStrategy.cs +++ b/OpenNest.Engine/BestFit/RotationSlideStrategy.cs @@ -59,12 +59,15 @@ namespace OpenNest.Engine.BestFit if (offsets.Length == 0) return candidates; - var distances = _distanceComputer.ComputeDistances( + // The first slides and the settling slides are of the same two boundaries: a + // computer that can prepare them does so once. + var prepared = (_distanceComputer as IPreparedDistanceComputer)?.Prepare( part1Entities, - part2Entities, - offsets + part2Entities ); + var distances = Distances(prepared, part1Entities, part2Entities, offsets); + // Where each slide came to rest, as an offset of the part 2 template. var rests = new List(); @@ -89,7 +92,7 @@ namespace OpenNest.Engine.BestFit foreach (var rest in rests) candidates.Add(CreateCandidate(drawing, part2Template, rest, spacing, testNumber++)); - foreach (var settled in Settle(part1Entities, part2Entities, rests)) + foreach (var settled in Settle(prepared, part1Entities, part2Entities, rests)) candidates.Add(CreateCandidate(drawing, part2Template, settled, spacing, testNumber++)); return candidates; @@ -103,6 +106,7 @@ namespace OpenNest.Engine.BestFit /// or repeat an earlier one are dropped. /// private List Settle( + IPreparedDistances prepared, List part1Entities, List part2Entities, List rests @@ -123,11 +127,7 @@ namespace OpenNest.Engine.BestFit sideways[i * 2 + 1] = new SlideOffset(rest.Dx, rest.Dy, rest.DirY, -rest.DirX); } - var distances = _distanceComputer.ComputeDistances( - part1Entities, - part2Entities, - sideways - ); + var distances = Distances(prepared, part1Entities, part2Entities, sideways); var seen = new HashSet<(long X, long Y)>(); @@ -150,6 +150,16 @@ namespace OpenNest.Engine.BestFit return settled; } + private double[] Distances( + IPreparedDistances prepared, + List part1Entities, + List part2Entities, + SlideOffset[] offsets + ) => + prepared != null + ? prepared.ComputeDistances(offsets) + : _distanceComputer.ComputeDistances(part1Entities, part2Entities, offsets); + private static (long X, long Y) PositionKey(double dx, double dy) => ( (long)System.Math.Round(dx / PositionResolution), diff --git a/OpenNest.Tests/BestFit/CpuDistanceComputerEquivalenceTests.cs b/OpenNest.Tests/BestFit/CpuDistanceComputerEquivalenceTests.cs new file mode 100644 index 00000000..43fafd45 --- /dev/null +++ b/OpenNest.Tests/BestFit/CpuDistanceComputerEquivalenceTests.cs @@ -0,0 +1,658 @@ +using OpenNest.CNC; +using OpenNest.Engine; +using OpenNest.Engine.BestFit; +using OpenNest.Geometry; +using OpenNest.Math; +using OpenNest.Shapes; + +namespace OpenNest.Tests.BestFit; + +/// +/// prepares its two boundaries once per batch +/// () and passes over pairs that cannot change a slide. These tests +/// compare every distance it returns, bit for bit, with the frozen pre-change +/// (commit 6067d0c8), which runs Core's per-slide +/// event sources once per offset. +/// +public class CpuDistanceComputerEquivalenceTests +{ + public static IEnumerable Pairs() + { + var names = Boundaries.Keys.ToList(); + for (var i = 0; i < names.Count; i++) + { + yield return new object[] { names[i], names[i], 0.0 }; + yield return new object[] { names[i], names[i], 180.0 }; + yield return new object[] { names[i], names[i], 33.5 }; + yield return new object[] { names[i], names[(i + 5) % names.Count], 90.0 }; + } + } + + public static IEnumerable LinePairs() => + Pairs().Where(pair => + Boundaries[(string)pair[0]]().All(e => e is Line) + && Boundaries[(string)pair[1]]().All(e => e is Line)); + + public static IEnumerable Drawings() => Parts.Keys.Select(name => new object[] { name }); + + private static readonly Dictionary>> Boundaries = new() + { + // Lines only. + ["rectangle"] = () => Loop((0, 0), (6, 0), (6, 3), (0, 3)), + ["notched"] = () => Loop((0, 0), (3, 0), (3, 1.5), (4.25, 1.5), (4.25, 0), (8, 0), (8, 5), (0, 5)), + ["channel"] = () => Loop((0, 0), (7, 0), (7, 4), (6, 4), (6, 1), (1, 1), (1, 4), (0, 4)), + ["triangle"] = () => Loop((0, 0), (5, 0.5), (1.5, 4)), + + // Enough lines for band indexes: teeth that interlock, and a curve as a polyline. + ["gear"] = () => Loop(Gear(16, 5, 3.9)), + ["polyline ellipse"] = () => Loop(Ellipse(64, 4, 1.5)), + + // Convex arcs, traversed both ways. + ["rounded rectangle"] = () => RoundedRectangle(6, 3.5, 0.75), + ["rounded rectangle clockwise"] = () => Reversed(RoundedRectangle(6, 3.5, 0.75)), + ["slot"] = Slot, + + // A concave arc, and arcs only. + ["filleted ell"] = FilletedEll, + ["lens"] = Lens, + + // Lines, convex bumps and concave scallops, enough of them for band indexes. + ["scalloped"] = () => Scalloped(30, 5), + + // Full circles and loops inside loops. + ["disc"] = () => new List { new Circle(new Vector(2.5, 2.5), 2.5) }, + ["full arc"] = () => new List { new Arc(1, 2, 2.25, 0, Angle.TwoPI) }, + ["ring"] = () => new List { new Circle(new Vector(3, 3), 3), new Circle(new Vector(3, 3), 1.75) }, + ["plate with holes"] = PlateWithHoles, + + // What offsetting by zero spacing leaves: a zero-radius arc at every corner, which + // the contact topology cannot resolve, so that every contact blocks. + ["zero radius corners"] = () => ZeroRadiusCorners(Loop((0, 0), (6, 0), (6, 3), (2, 3), (2, 5), (0, 5))), + ["zero radius gear"] = () => ZeroRadiusCorners(Loop(Gear(14, 4, 3.2))), + + // A boundary that is not a closed loop. + ["open chain"] = () => Chain((0, 0), (5, 0), (5, 3), (2, 4)), + }; + + private static readonly Dictionary> Parts = new() + { + ["rounded rectangle"] = () => new RoundedRectangleShape { Length = 6, Width = 3.5, Radius = 0.75 }.GetDrawing(), + ["tee"] = () => new TShape { Width = 10, Height = 8 }.GetDrawing(), + ["ell"] = () => new LShape { Width = 7, Height = 9, LegWidth = 2, LegHeight = 2.5 }.GetDrawing(), + ["disc"] = () => new CircleShape { Diameter = 5 }.GetDrawing(), + ["hexagon"] = () => new NgonShape { Sides = 6, Width = 4 }.GetDrawing(), + ["notched arcs"] = NotchedArcs, + ["gear"] = () => Outline("gear", Gear(16, 5, 3.9)), + }; + + [Theory] + [MemberData(nameof(Pairs))] + public void ComputeDistances_MatchesLegacyBitwise(string stationaryName, string movingName, double degrees) + { + var stationary = Boundaries[stationaryName](); + var moving = Turned(Boundaries[movingName](), degrees); + var label = $"{stationaryName} / {movingName} at {degrees}"; + + var legacy = new LegacyCpuDistanceComputer(); + var offsets = Offsets(stationary, moving); + var expected = legacy.ComputeDistances(stationary, moving, offsets); + AssertSameBits(expected, new CpuDistanceComputer().ComputeDistances(stationary, moving, offsets), offsets, label); + + // Slides that start in contact, as the pair search's settling slides do. + var sideways = Sideways(offsets, expected); + var expectedSideways = legacy.ComputeDistances(stationary, moving, sideways); + AssertSameBits(expectedSideways, new CpuDistanceComputer().ComputeDistances(stationary, moving, sideways), sideways, label + ", sideways"); + + // Offsets no slide can come from. They get a batch of their own: one of them in a + // batch leaves its axis without an index. + var degenerate = Degenerate(); + AssertSameBits( + legacy.ComputeDistances(stationary, moving, degenerate), + new CpuDistanceComputer().ComputeDistances(stationary, moving, degenerate), + degenerate, + label + ", degenerate"); + + // One prepared pair for several batches, in either order. + var prepared = new CpuDistanceComputer().Prepare(stationary, moving); + AssertSameBits(expected, prepared.ComputeDistances(offsets), offsets, label + ", prepared"); + AssertSameBits(expectedSideways, prepared.ComputeDistances(sideways), sideways, label + ", prepared sideways"); + + prepared = new CpuDistanceComputer().Prepare(stationary, moving); + AssertSameBits(expectedSideways, prepared.ComputeDistances(sideways), sideways, label + ", prepared sideways first"); + AssertSameBits(expected, prepared.ComputeDistances(offsets), offsets, label + ", prepared second"); + + // A prepared pair asked for slides one at a time: each batch is sized for its own + // offset, so later ones start outside what earlier ones prepared. + prepared = new CpuDistanceComputer().Prepare(stationary, moving); + for (var i = 0; i < offsets.Length; i += 37) + { + var one = new[] { offsets[i] }; + AssertSameBits(new[] { expected[i] }, prepared.ComputeDistances(one), one, label + $", single {i}"); + } + + // The comparison is only worth something when it sees slides that stop and slides + // that never touch. + Assert.Contains(expected, d => d < double.MaxValue); + Assert.Contains(expected, d => d >= double.MaxValue); + } + + [Theory] + [MemberData(nameof(LinePairs))] + public void ComputeDistances_Lines_MatchesLegacyBitwise(string stationaryName, string movingName, double degrees) + { + var stationaryEntities = Boundaries[stationaryName](); + var movingEntities = Turned(Boundaries[movingName](), degrees); + var stationary = stationaryEntities.Cast().ToList(); + var moving = movingEntities.Cast().ToList(); + var label = $"{stationaryName} / {movingName} at {degrees}, lines"; + + var legacy = new LegacyCpuDistanceComputer(); + var offsets = Offsets(stationaryEntities, movingEntities); + var expected = legacy.ComputeDistances(stationary, moving, offsets); + AssertSameBits(expected, new CpuDistanceComputer().ComputeDistances(stationary, moving, offsets), offsets, label); + + var sideways = Sideways(offsets, expected); + AssertSameBits( + legacy.ComputeDistances(stationary, moving, sideways), + new CpuDistanceComputer().ComputeDistances(stationary, moving, sideways), + sideways, + label + ", sideways"); + + var degenerate = Degenerate(); + AssertSameBits( + legacy.ComputeDistances(stationary, moving, degenerate), + new CpuDistanceComputer().ComputeDistances(stationary, moving, degenerate), + degenerate, + label + ", degenerate"); + } + + /// + /// The batches the pair search itself asks for: its grid of first slides and the + /// settling slides from where those came to rest, at no spacing (zero-radius offset + /// corners) and at a spacing (rounded ones). + /// + [Theory] + [MemberData(nameof(Drawings))] + public void RotationSlideStrategy_MatchesLegacyBitwise(string name) + { + var drawing = CanonicalFrame.AsCanonicalCopy(Parts[name]()); + var batches = 0; + + foreach (var spacing in new[] { 0.0, 0.25 }) + { + foreach (var degrees in new[] { 0.0, 90, 180, 37, 211.5 }) + { + var rotation = Angle.ToRadians(degrees); + var label = $"{name}, spacing {spacing}, {degrees} degrees"; + + var recorder = new Recorder(new LegacyCpuDistanceComputer()); + var expected = new RotationSlideStrategy(rotation, 1, string.Empty, recorder) + .GenerateCandidates(drawing, spacing, 0.25); + var actual = new RotationSlideStrategy(rotation, 1, string.Empty, new CpuDistanceComputer()) + .GenerateCandidates(drawing, spacing, 0.25); + + Assert.Equal(expected.Count, actual.Count); + for (var i = 0; i < expected.Count; i++) + { + Assert.True( + Bits(expected[i].Part2Offset.X) == Bits(actual[i].Part2Offset.X) + && Bits(expected[i].Part2Offset.Y) == Bits(actual[i].Part2Offset.Y) + && Bits(expected[i].Part2Rotation) == Bits(actual[i].Part2Rotation) + && expected[i].TestNumber == actual[i].TestNumber, + $"{label}: candidate {i}"); + } + + foreach (var (stationary, moving, offsets, distances) in recorder.Calls) + { + AssertSameBits(distances, new CpuDistanceComputer().ComputeDistances(stationary, moving, offsets), offsets, label); + batches++; + } + } + } + + Assert.True(batches >= 10, $"{name}: {batches} batches"); + } + + /// + /// A ray may hit a line up to of its length past its + /// end, which is nearer than the line's own extent. Here that grazing hit is the first + /// contact, by less than the hit lies past the end, and another vertex has already + /// found the contact just behind it: skipping the pair on its extent alone would + /// return the later contact. Turned through every quarter, for each push axis and sign. + /// + [Theory] + [InlineData(0)] + [InlineData(90)] + [InlineData(180)] + [InlineData(270)] + public void ComputeDistances_HitPastASegmentEnd_IsTheFirstContact(double degrees) + { + // The moving edge's top end meets the wall after 7.99997; its bottom end passes + // 5e-5 below the sloping line's start and meets its extension after 7.99995. + var stationary = Turned( + new List + { + new Line(new Vector(0, 0), new Vector(10, 10)), + new Line(new Vector(-3e-5, 20), new Vector(-3e-5, 30)), + }, + degrees); + var moving = Turned( + new List { new Line(new Vector(-8, 25), new Vector(-8, -5e-5)) }, + degrees); + + var radians = Angle.ToRadians(degrees); + var dirX = System.Math.Round(System.Math.Cos(radians)); + var dirY = System.Math.Round(System.Math.Sin(radians)); + var offsets = new[] { new SlideOffset(0, 0, dirX, dirY), new SlideOffset(-dirX, -dirY, dirX, dirY) }; + + var expected = new LegacyCpuDistanceComputer().ComputeDistances(stationary, moving, offsets); + Assert.Equal(7.99995, expected[0], 9); + Assert.Equal(8.99995, expected[1], 9); + + AssertSameBits(expected, new CpuDistanceComputer().ComputeDistances(stationary, moving, offsets), offsets, $"grazing at {degrees}"); + AssertSameBits(expected, new CpuDistanceComputer().Prepare(stationary, moving).ComputeDistances(offsets), offsets, $"grazing at {degrees}, prepared"); + } + + [Fact] + public void ComputeDistances_NoOffsets_IsEmpty() + { + var boundary = Boundaries["rounded rectangle"](); + Assert.Empty(new CpuDistanceComputer().ComputeDistances(boundary, boundary, Array.Empty())); + Assert.Empty(new CpuDistanceComputer().Prepare(boundary, boundary).ComputeDistances(Array.Empty())); + } + + [Fact] + public void ComputeDistances_NoEntities_NeverTouches() + { + var offsets = new[] { new SlideOffset(5, 0, -1, 0), new SlideOffset(0, 5, 0, -1), new SlideOffset(1, 1, 0.6, 0.8) }; + var empty = new List(); + var boundary = Boundaries["rounded rectangle"](); + var legacy = new LegacyCpuDistanceComputer(); + + foreach (var (stationary, moving) in new[] { (empty, boundary), (boundary, empty), (empty, empty) }) + { + AssertSameBits( + legacy.ComputeDistances(stationary, moving, offsets), + new CpuDistanceComputer().ComputeDistances(stationary, moving, offsets), + offsets, + "no entities"); + } + } + + [Fact] + public void Normalize_MatchesNormalizeRadBitwise() + { + var random = new Random(4711); + var angles = new List + { + 0, -0.0, double.Epsilon, -double.Epsilon, Angle.TwoPI, -Angle.TwoPI, System.Math.PI, -System.Math.PI, + System.Math.BitDecrement(Angle.TwoPI), System.Math.BitIncrement(Angle.TwoPI), + System.Math.BitDecrement(-Angle.TwoPI), System.Math.BitIncrement(-Angle.TwoPI), + 2 * Angle.TwoPI, -2 * Angle.TwoPI, 1e300, -1e300, + double.NaN, double.PositiveInfinity, double.NegativeInfinity, + }; + for (var i = 0; i < 2000; i++) + angles.Add((random.NextDouble() - 0.5) * 40); + + foreach (var angle in angles) + Assert.Equal(Bits(Angle.NormalizeRad(angle)), Bits(SlideBatch.Normalize(angle))); + } + + private static long Bits(double value) => BitConverter.DoubleToInt64Bits(value); + + private static void AssertSameBits(double[] expected, double[] actual, SlideOffset[] offsets, string label) + { + Assert.Equal(expected.Length, actual.Length); + for (var i = 0; i < expected.Length; i++) + { + if (Bits(expected[i]) == Bits(actual[i])) + continue; + + var offset = offsets[i]; + Assert.Fail( + $"{label}: slide {i} from ({offset.Dx:R}, {offset.Dy:R}) along ({offset.DirX:R}, {offset.DirY:R}): " + + $"expected {expected[i]:R}, was {actual[i]:R}"); + } + } + + /// + /// Starts well clear of the stationary boundary, with the bounding boxes touching and + /// overlapping, for each axis push; across the push, positions that miss, graze either + /// end by amounts around every tolerance in play, sit level with an edge, and sweep the + /// whole range. Then pushes that are not along an axis. + /// + private static SlideOffset[] Offsets(List stationary, List moving) + { + var s = Bounds(stationary); + var m = Bounds(moving); + var offsets = new List(); + var random = new Random(12345); + double[] nudges = + { + 0, 1e-9, -1e-9, 1e-7, -1e-7, 1e-6, -1e-6, 4e-6, -4e-6, 1e-5, -1e-5, + 3e-5, -3e-5, 1e-4, -1e-4, 1e-3, -1e-3, 0.02, -0.02, + }; + + foreach (var (dirX, dirY) in new[] { (-1.0, 0.0), (0.0, -1.0), (1.0, 0.0), (0.0, 1.0) }) + { + var horizontal = dirY == 0; + var sign = dirX + dirY; + var (sLow, sHigh, mLow, mHigh) = horizontal ? (s.MinY, s.MaxY, m.MinY, m.MaxY) : (s.MinX, s.MaxX, m.MinX, m.MaxX); + var (sNear, sFar, mNear, mFar) = horizontal ? (s.MinX, s.MaxX, m.MinX, m.MaxX) : (s.MinY, s.MaxY, m.MinY, m.MaxY); + var span = sHigh - sLow + (mHigh - mLow); + + // Where the moving box rests against the stationary box on the side it comes from. + var against = sign < 0 ? sFar - mNear : sNear - mFar; + var starts = new[] { against - sign * 5, against, against + sign * 0.4 * (mFar - mNear) }; + + var across = new List(); + foreach (var nudge in nudges) + { + across.Add(sHigh - mLow + nudge); + across.Add(sLow - mHigh + nudge); + across.Add(sHigh - mLow + nudge * span); + across.Add(sLow - mHigh + nudge * span); + across.Add(sLow - mLow + nudge); + across.Add(sHigh - mHigh + nudge); + } + for (var i = 0; i <= 24; i++) + across.Add(sLow - mHigh - 0.5 + (span + 1) * i / 24); + for (var i = 0; i < 24; i++) + across.Add(sLow - mHigh + span * random.NextDouble()); + + foreach (var start in starts) + { + foreach (var level in across) + offsets.Add(horizontal ? new SlideOffset(start, level, dirX, dirY) : new SlideOffset(level, start, dirX, dirY)); + } + } + + var diagonal = System.Math.Sqrt(0.5); + foreach (var (dirX, dirY) in new[] { (0.6, 0.8), (-0.8, 0.6), (diagonal, -diagonal), (-0.28, -0.96), (2.0, 0.0) }) + { + var centerX = (s.MinX + s.MaxX - m.MinX - m.MaxX) / 2; + var centerY = (s.MinY + s.MaxY - m.MinY - m.MaxY) / 2; + var reach = s.MaxX - s.MinX + s.MaxY - s.MinY + m.MaxX - m.MinX + m.MaxY - m.MinY; + for (var i = 0; i < 40; i++) + { + var back = reach * (0.2 + random.NextDouble()); + var side = reach * (random.NextDouble() - 0.5); + offsets.Add(new SlideOffset( + centerX - dirX * back - dirY * side, + centerY - dirY * back + dirX * side, + dirX, + dirY)); + } + } + + return offsets.ToArray(); + } + + /// Both sideways slides from where each slide came to rest, as the pair search settles. + private static SlideOffset[] Sideways(SlideOffset[] offsets, double[] distances) + { + var sideways = new List(); + for (var i = 0; i < offsets.Length; i += 2) + { + var distance = distances[i]; + if (distance >= double.MaxValue || distance < 0) + continue; + + var offset = offsets[i]; + var dx = offset.Dx + offset.DirX * distance; + var dy = offset.Dy + offset.DirY * distance; + sideways.Add(new SlideOffset(dx, dy, -offset.DirY, offset.DirX)); + sideways.Add(new SlideOffset(dx, dy, offset.DirY, -offset.DirX)); + } + return sideways.ToArray(); + } + + private static SlideOffset[] Degenerate() => + new[] + { + new SlideOffset(double.NaN, 0, -1, 0), + new SlideOffset(0, double.NaN, 0, 1), + new SlideOffset(double.PositiveInfinity, 0, -1, 0), + new SlideOffset(1, double.NegativeInfinity, 0, -1), + new SlideOffset(1e200, 1, -1, 0), + new SlideOffset(1e155, 0.5, 1, 0), + new SlideOffset(0.5, -1e160, 0, 1), + new SlideOffset(9, 1, -1, 0), + new SlideOffset(1, 9, 0, -1), + new SlideOffset(3, 3, 0, 0), + new SlideOffset(3, 3, double.NaN, 0), + new SlideOffset(9, 1, -1, double.NaN), + }; + + private static (double MinX, double MinY, double MaxX, double MaxY) Bounds(List entities) + { + double minX = double.MaxValue, minY = double.MaxValue, maxX = double.MinValue, maxY = double.MinValue; + foreach (var entity in entities) + { + var box = entity.BoundingBox; + minX = System.Math.Min(minX, box.Left); + minY = System.Math.Min(minY, box.Bottom); + maxX = System.Math.Max(maxX, box.Right); + maxY = System.Math.Max(maxY, box.Top); + } + return (minX, minY, maxX, maxY); + } + + private static List Turned(List entities, double degrees) + { + if (degrees == 0) + return entities; + + foreach (var entity in entities) + entity.Rotate(Angle.ToRadians(degrees)); + return entities; + } + + private static List Loop(params (double X, double Y)[] points) + { + var entities = Chain(points); + entities.Add(new Line(new Vector(points[^1].X, points[^1].Y), new Vector(points[0].X, points[0].Y))); + return entities; + } + + private static List Chain(params (double X, double Y)[] points) + { + var entities = new List(); + for (var i = 0; i + 1 < points.Length; i++) + { + entities.Add(new Line( + new Vector(points[i].X, points[i].Y), + new Vector(points[i + 1].X, points[i + 1].Y))); + } + return entities; + } + + /// A loop traversed the other way round. + private static List Reversed(List entities) + { + entities.Reverse(); + foreach (var entity in entities) + entity.Reverse(); + return entities; + } + + private static (double X, double Y)[] Gear(int teeth, double outer, double root) + { + var points = new List<(double, double)>(); + var step = Angle.TwoPI / teeth; + for (var i = 0; i < teeth; i++) + { + var a = i * step; + points.Add((outer * System.Math.Cos(a), outer * System.Math.Sin(a))); + points.Add((outer * System.Math.Cos(a + step * 0.3), outer * System.Math.Sin(a + step * 0.3))); + points.Add((root * System.Math.Cos(a + step * 0.45), root * System.Math.Sin(a + step * 0.45))); + points.Add((root * System.Math.Cos(a + step * 0.85), root * System.Math.Sin(a + step * 0.85))); + } + return points.ToArray(); + } + + private static (double X, double Y)[] Ellipse(int segments, double a, double b) + { + var points = new (double, double)[segments]; + for (var i = 0; i < segments; i++) + { + var t = i * Angle.TwoPI / segments; + points[i] = (a * System.Math.Cos(t), b * System.Math.Sin(t)); + } + return points; + } + + private static List RoundedRectangle(double length, double width, double r) => + new() + { + new Line(new Vector(r, 0), new Vector(length - r, 0)), + new Arc(length - r, r, r, 3 * Angle.HalfPI, 0), + new Line(new Vector(length, r), new Vector(length, width - r)), + new Arc(length - r, width - r, r, 0, Angle.HalfPI), + new Line(new Vector(length - r, width), new Vector(r, width)), + new Arc(r, width - r, r, Angle.HalfPI, System.Math.PI), + new Line(new Vector(0, width - r), new Vector(0, r)), + new Arc(r, r, r, System.Math.PI, 3 * Angle.HalfPI), + }; + + private static List Slot() => + new() + { + new Line(new Vector(1, 0), new Vector(6, 0)), + new Arc(6, 1, 1, 3 * Angle.HalfPI, Angle.HalfPI), + new Line(new Vector(6, 2), new Vector(1, 2)), + new Arc(1, 1, 1, Angle.HalfPI, 3 * Angle.HalfPI), + }; + + /// An ell whose inside corner is a concave fillet and whose toe is rounded. + private static List FilletedEll() => + new() + { + new Line(new Vector(0, 0), new Vector(6, 0)), + new Line(new Vector(6, 0), new Vector(6, 1.5)), + new Arc(5.5, 1.5, 0.5, 0, Angle.HalfPI), + new Line(new Vector(5.5, 2), new Vector(3, 2)), + new Arc(3, 3, 1, 3 * Angle.HalfPI, System.Math.PI, true), + new Line(new Vector(2, 3), new Vector(2, 6)), + new Line(new Vector(2, 6), new Vector(0, 6)), + new Line(new Vector(0, 6), new Vector(0, 0)), + }; + + /// The overlap of two radius-5 discs 6 apart: two arcs meeting at sharp tips. + private static List Lens() => + new() + { + new Arc(0, 0, 5, Angle.NormalizeRad(System.Math.Atan2(-4, 3)), System.Math.Atan2(4, 3)), + new Arc(6, 0, 5, System.Math.Atan2(4, -3), Angle.NormalizeRad(System.Math.Atan2(-4, -3))), + }; + + /// + /// Points round a circle joined in turn by a line, a bump outward and a scallop inward. + /// + private static List Scalloped(int sides, double radius) + { + var entities = new List(); + for (var i = 0; i < sides; i++) + { + var a = i * Angle.TwoPI / sides; + var b = (i + 1) * Angle.TwoPI / sides; + var from = new Vector(radius * System.Math.Cos(a), radius * System.Math.Sin(a)); + var to = new Vector(radius * System.Math.Cos(b), radius * System.Math.Sin(b)); + + if (i % 3 == 0) + { + entities.Add(new Line(from, to)); + continue; + } + + var center = new Vector((from.X + to.X) / 2, (from.Y + to.Y) / 2); + var r = from.DistanceTo(to) / 2; + var start = Angle.NormalizeRad(System.Math.Atan2(from.Y - center.Y, from.X - center.X)); + var end = Angle.NormalizeRad(System.Math.Atan2(to.Y - center.Y, to.X - center.X)); + entities.Add(new Arc(center.X, center.Y, r, start, end, i % 3 == 2)); + } + return entities; + } + + private static List PlateWithHoles() + { + var entities = Loop((0, 0), (9, 0), (9, 6), (0, 6)); + entities.Add(new Circle(new Vector(2.5, 3), 1.25)); + entities.AddRange(Loop((5, 2), (5, 4.5), (7.5, 4.5), (7.5, 2))); + return entities; + } + + /// The loop with a zero-radius arc turning each corner, as a zero offset leaves it. + private static List ZeroRadiusCorners(List loop) + { + var entities = new List(); + for (var i = 0; i < loop.Count; i++) + { + var line = (Line)loop[i]; + var next = (Line)loop[(i + 1) % loop.Count]; + entities.Add(line); + + var leaving = System.Math.Atan2(line.EndPoint.Y - line.StartPoint.Y, line.EndPoint.X - line.StartPoint.X); + var entering = System.Math.Atan2(next.EndPoint.Y - next.StartPoint.Y, next.EndPoint.X - next.StartPoint.X); + entities.Add(new Arc( + line.EndPoint.X, + line.EndPoint.Y, + 0, + Angle.NormalizeRad(leaving - Angle.HalfPI), + Angle.NormalizeRad(entering - Angle.HalfPI))); + } + return entities; + } + + /// A plate with a square notch, a round notch cut clockwise and two rounded corners. + private static Drawing NotchedArcs() + { + var program = new Program(); + program.MoveTo(0, 0); + program.LineTo(3, 0); + program.LineTo(3, 1.5); + program.LineTo(4.25, 1.5); + program.LineTo(4.25, 0); + program.LineTo(8, 0); + program.LineTo(8, 4); + program.ArcTo(7, 5, 7, 4, RotationType.CCW); + program.LineTo(5.5, 5); + program.ArcTo(3.5, 5, 4.5, 5, RotationType.CW); + program.LineTo(1, 5); + program.ArcTo(0, 4, 1, 4, RotationType.CCW); + program.LineTo(0, 0); + return new Drawing("notched arcs", program); + } + + private static Drawing Outline(string name, (double X, double Y)[] points) + { + var program = new Program(); + program.MoveTo(points[0].X, points[0].Y); + for (var i = 1; i < points.Length; i++) + program.LineTo(points[i].X, points[i].Y); + program.LineTo(points[0].X, points[0].Y); + return new Drawing(name, program); + } + + private sealed class Recorder : IDistanceComputer + { + private readonly IDistanceComputer inner; + + public Recorder(IDistanceComputer inner) + { + this.inner = inner; + } + + public List<(List Stationary, List Moving, SlideOffset[] Offsets, double[] Distances)> Calls { get; } = new(); + + public double[] ComputeDistances(List stationaryLines, List movingTemplateLines, SlideOffset[] offsets) => + inner.ComputeDistances(stationaryLines, movingTemplateLines, offsets); + + public double[] ComputeDistances(List stationaryEntities, List movingEntities, SlideOffset[] offsets) + { + var distances = inner.ComputeDistances(stationaryEntities, movingEntities, offsets); + Calls.Add((stationaryEntities, movingEntities, offsets, distances)); + return distances; + } + } +} diff --git a/OpenNest.Tests/BestFit/LegacyCpuDistanceComputer.cs b/OpenNest.Tests/BestFit/LegacyCpuDistanceComputer.cs new file mode 100644 index 00000000..d551c8ce --- /dev/null +++ b/OpenNest.Tests/BestFit/LegacyCpuDistanceComputer.cs @@ -0,0 +1,69 @@ +#nullable disable +// Frozen, test-only copy of OpenNest.Engine/BestFit/CpuDistanceComputer.cs at commit 6067d0c8 +// (before a batch prepared its boundaries once and skipped pairs that cannot change a slide). +// It runs Core's per-slide sources (EntitySlideEvents, LineSlideEvents) and SlideResolver, +// which that change left as they were. Only #nullable disable, the namespace, type name and +// visibility differ from the original. +// Do not edit: differential tests use it as the independent pre-change oracle. +using System.Collections.Generic; +using System.Linq; +using OpenNest.Engine.BestFit; +using OpenNest.Geometry; + +namespace OpenNest.Tests.BestFit +{ + internal class LegacyCpuDistanceComputer : IDistanceComputer + { + public double[] ComputeDistances( + List stationaryLines, + List movingTemplateLines, + SlideOffset[] offsets + ) + { + var results = new double[offsets.Length]; + var movingVertices = Vertices(movingTemplateLines); + var stationaryVertices = Vertices(stationaryLines); + var contacts = SlideContactClassifier.FromLines( + movingTemplateLines, Vector.Zero, stationaryLines, Vector.Zero).Prepare(); + + System.Threading.Tasks.Parallel.For(0, offsets.Length, i => + { + var offset = offsets[i]; + var source = new LineSlideEvents( + movingTemplateLines, movingVertices, offset.Dx, offset.Dy, + stationaryLines, stationaryVertices, offset.DirX, offset.DirY); + results[i] = SlideResolver.FirstBlocking(ref source, + contacts.At(new Vector(offset.Dx, offset.Dy), Vector.Zero), offset.DirX, offset.DirY); + }); + return results; + } + + public double[] ComputeDistances( + List stationaryEntities, + List movingEntities, + SlideOffset[] offsets + ) + { + var results = new double[offsets.Length]; + var movingVertices = SpatialQuery.ExtractEntityVertices(movingEntities); + var stationaryVertices = SpatialQuery.ExtractEntityVertices(stationaryEntities); + var contacts = new SlideContactClassifier(movingEntities, stationaryEntities).Prepare(); + + // All vertices participate: a leading-half filter can miss the next contact + // after sliding past an initial touch on a concave boundary. + System.Threading.Tasks.Parallel.For(0, offsets.Length, i => + { + var offset = offsets[i]; + var source = new EntitySlideEvents( + movingEntities, movingVertices, offset.Dx, offset.Dy, + stationaryEntities, stationaryVertices, offset.DirX, offset.DirY, arcToLine: true); + results[i] = SlideResolver.FirstBlocking(ref source, + contacts.At(new Vector(offset.Dx, offset.Dy), Vector.Zero), offset.DirX, offset.DirY); + }); + return results; + } + + private static Vector[] Vertices(List lines) => + lines.SelectMany(line => new[] { line.StartPoint, line.EndPoint }).Distinct().ToArray(); + } +} diff --git a/docs/geometry/directional-slides.md b/docs/geometry/directional-slides.md index 2bae3cb3..d5bfdedd 100644 --- a/docs/geometry/directional-slides.md +++ b/docs/geometry/directional-slides.md @@ -14,6 +14,7 @@ Open/incomplete chains and ambiguous contacts conservatively block. Loops are re - With **Calculated distance** checked in Tools > Set Offset Increment, PlateView's arrow keys use `SelectionManager.StepSelected` → `Compactor.Step`. The step is the selection's linear-fill copy distance (`FillLinear.CopyDistance`) at the plate's part spacing, so a shape that nests into its own copy steps less than its size. That copy distance is the same in both directions along an axis. The move is not a slide: like a fixed nudge it always moves the full step, ignoring the work-area edge, clamps and other parts, because interlocked rows (staggered triangles, say) cannot slide straight past their neighbors to the next row. It can land off the plate or on a part; the layout check reports that as it does for any nudge. - Linear fill inherits the shared native-entity query unchanged. Its pattern copy distance slides each part of the next copy against every part of the pattern whose bounding box is in the copy's path or beside it by less than the part spacing; a part beside the path by the spacing or more cannot come too close and is skipped. Skipping on bounding-box overlap alone let a copy pass a part 0.04 beside its path: columns of a gusset pair interlocked closer than the spacing (`PatternCopySpacingTests`). Extents fill passes complete boundary loops instead of direction-filtered fragments. - CPU best-fit batches prepare contact topology once and use all vertices plus curve/line interior and curve/curve tangency events. The old leading-half vertex filter cannot establish the next blocker after a skipped touch. +- A batch (`CpuDistanceComputer`, through Core's `SlideBatch`) returns for every offset exactly the distance the per-slide query returns, bit for bit; it only does less work. The two boundaries are packed, and their vertices, contact topology and band indexes built, once per batch instead of once per slide (the per-slide indexes were most of the time and nearly all of the allocation); the pair search prepares each pair once for its first slides and its settling slides (`IPreparedDistanceComputer`). For a push along an exact axis it also passes over pairs that cannot change the answer: a vertex or curve outside the other boundary's whole extent across the push, which every band test would reject, and, while the nearest contact is searched for, a pair whose gap along the push already reaches the nearest distance found, which the search would discard. Both keep margins for the tolerances and rounding of the kernels they stand in for: a ray hits a line up to `Tolerance.Epsilon` of its length past its ends, so neither test may use a line's bare extent. A zero part spacing leaves a zero-radius arc at every corner of the offset boundary, which the contact topology cannot resolve, so every contact of such a pair blocks; the batch keeps that. - The best-fit pair search (`RotationSlideStrategy`) starts each slide from an offset on its step grid, then slides every resting position sideways, both ways, and keeps the new resting positions as extra candidates. A pair that locks in a corner (two interlocking channels) therefore closes to the part spacing on both axes instead of stopping up to a step short. This relies on leaving an existing contact being legal. - GPU kernels retain nearest-hit reduction and return unsnapped contact witnesses. The shared CPU classifier accepts a blocking witness or replays the full query after a nonblocking witness, preserving tied/later blockers. Both batch APIs honor active buffer lengths and refresh mutated/reused segment arrays. The GPU distance adapter sends only exact cardinal directions to the axis-only slide interface; arbitrary directions and native curves use the shared CPU path. @@ -24,6 +25,8 @@ Open/incomplete chains and ambiguous contacts conservatively block. Loops are re ## Regression coverage `SlideContactTests` exercises cardinal line, translated line, reused edge-array, arbitrary-vector, native-entity, and both CPU batch paths. Cases include winding reversal, nonzero origins, rotated hooks, holes, separating circles, positive-distance grazing followed by a blocker, full-circle arc seams, concave/straight junctions, thin rings, and circle/line interior contact. +`CpuDistanceComputerEquivalenceTests` compares every distance of the batch, bit for bit, with a frozen copy of the per-slide computer (`LegacyCpuDistanceComputer`): lines, convex and concave arcs, circles, holes, zero-radius corners and an open chain, enough entities for band indexes and too few, starts that miss, graze either end by amounts around each tolerance, touch and overlap, pushes off the axes, offsets that are not numbers, one prepared pair used for several batches, and the pair search's own batches. `ComputeDistances_HitPastASegmentEnd_IsTheFirstContact` is the case a bare-extent skip gets wrong. + `CompactorTests` covers the reported sequence (push left with spacing, then right/up/down), genuine zero-distance blocking, zero/nonzero-spacing later hooks, and inside-hole pushes through both direct and plate entry points. Physical spacing is measured from raw outlines rather than the inflated contours used by the solver. `CompactorTabbedPartTests` covers a tabbed, lead-carrying part resting at the spacing in the notch of an eared neighbor whose bounds wrap it: pushes away (either part moving), along, into and from a distance, an overlapping start compared with an untabbed twin, and a block level with a wide tab. `TabClosureTests` covers the closure itself: line and arc restoration, a round outside cut as one arc, a swallowed corner, a contour regrouped by shape, and the cases left alone.