diff --git a/AGENTS.md b/AGENTS.md index e63c6670..2292f15a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -69,6 +69,7 @@ Read the relevant contract before changing its behavior: - [Separating parts](docs/separate-parts.md): the CAD Converter splits a file drawing several parts into one drawing per part (`PartBodies`), keeping IDs and refusing a breakoff or tabbed cutout that spans parts - [Irregular stock](docs/irregular-stock.md): outlined sheets, what honors the outline and what refuses it - [Directional slides](docs/geometry/directional-slides.md) and [pair-spacing limits](docs/geometry/pair-spacing.md) +- [Dense outlines](docs/geometry/dense-outlines.md): spacing outlines thin runs of tiny entities (curves exported as polylines) to chords that only add clearance; validation keeps the true geometry - [Lead-in placement](docs/geometry/lead-in-placement.md) (including the planner's eroded pierce for cutouts too small for their lead-in and the stop at a feature's center line) and [pierce zones](docs/geometry/pierce-zone.md): opt-in `PierceDiameter` clearance, the hole pole fallback and the planner's perimeter scrap fallback - [Breakoffs](docs/breakoffs.md): tabbed scrap; `Break`-layer open cuts that are cut but are not material - [Tabbed cutouts](docs/tabbed-cutouts.md): holes cut in pieces around `Tab`-layer spans that are material but never cut; nesting reads material through `NestingMaterial.ForNesting`, so nothing nests in them diff --git a/OpenNest.Core/Geometry/DenseOutline.cs b/OpenNest.Core/Geometry/DenseOutline.cs new file mode 100644 index 00000000..672b5be2 --- /dev/null +++ b/OpenNest.Core/Geometry/DenseOutline.cs @@ -0,0 +1,203 @@ +using System.Collections.Generic; +using OpenNest.Math; + +namespace OpenNest.Geometry +{ + /// + /// Thins spacing outlines whose contour holds a dense run of tiny entities, such as a curve a + /// CAD export wrote as hundreds of 0.005-inch lines. Every slide and fill query costs in + /// proportion to the entities on both sides, so one such run can make Fill of a single part + /// take minutes. + /// + /// The thinned outline only ever adds clearance. It is the contour offset by the spacing plus + /// , with each dense run replaced by chords through points on that offset that + /// stay within of it (arcs sampled within + /// ). Every chord therefore lies outside the outline offset by the + /// spacing alone, so a layout spaced on the thinned outline holds the true spacing, at most + /// 2 * Pad wider at a dense run. Contours without a dense run keep their exact offset. + /// + public static class DenseOutline + { + /// Entities shorter than this count toward a dense run. + public const double ShortLength = 0.02; + + /// Fewest consecutive short entities that make a dense run. + public const int MinRun = 16; + + /// Largest distance a chord may stray from the sampled offset. + public const double ChordTolerance = 0.001; + + /// Largest distance an arc may bulge past the chords it is sampled into. + public const double SampleTolerance = 0.0005; + + /// Extra offset a thinned outline takes so its chords never cut inside the + /// outline at the true spacing. + public const double Pad = ChordTolerance + SampleTolerance; + + /// Whether the closed contour holds a dense run (a run may wrap past its first + /// entity). + public static bool HasDenseRun(IReadOnlyList contour) + { + if (contour.Count < MinRun) + return false; + var start = FirstLong(contour); + if (start < 0) + return true; + var run = 0; + for (var k = 1; k <= contour.Count; k++) + { + if (IsShort(contour[(start + k) % contour.Count])) + { + if (++run >= MinRun) + return true; + } + else + { + run = 0; + } + } + return false; + } + + /// + /// The closed contour with each dense run replaced by chords within + /// of it; other entities are kept as they are. Callers pass a + /// contour already offset by beyond the clearance it must keep. + /// + public static List Thin(IReadOnlyList contour) + { + var result = new List(contour.Count); + var start = FirstLong(contour); + if (start < 0) + { + // Every entity is short (a circle exported as lines): thin it as two halves so + // each run has distinct ends. + var half = contour.Count / 2; + AddChords(contour, 0, half, result); + AddChords(contour, half, contour.Count - half, result); + return result; + } + + // Walk once around the loop from a long entity, so no run is split at index 0. + var k = 0; + while (k < contour.Count) + { + var index = (start + k) % contour.Count; + var entity = contour[index]; + if (!IsShort(entity)) + { + result.Add(entity); + k++; + continue; + } + var length = 0; + while (k + length < contour.Count && IsShort(contour[(start + k + length) % contour.Count])) + length++; + if (length >= MinRun) + { + AddChords(contour, index, length, result); + } + else + { + for (var i = 0; i < length; i++) + result.Add(contour[(index + i) % contour.Count]); + } + k += length; + } + return result; + } + + private static bool IsShort(Entity entity) => + (entity is Line || entity is Arc) && entity.Length < ShortLength; + + private static int FirstLong(IReadOnlyList contour) + { + for (var i = 0; i < contour.Count; i++) + if (!IsShort(contour[i])) + return i; + return -1; + } + + /// Appends the run's chords: a Douglas-Peucker pass over its sampled points + /// that keeps both ends exact. + private static void AddChords(IReadOnlyList contour, int first, int count, List result) + { + var points = new List(); + for (var i = 0; i < count; i++) + Sample(contour[(first + i) % contour.Count], points); + points.Add(End(contour[(first + count - 1) % contour.Count])); + + var keep = new bool[points.Count]; + keep[0] = true; + keep[points.Count - 1] = true; + var spans = new Stack<(int From, int To)>(); + spans.Push((0, points.Count - 1)); + while (spans.Count > 0) + { + var (from, to) = spans.Pop(); + var farthest = -1; + var distance = ChordTolerance; + for (var i = from + 1; i < to; i++) + { + var d = DistanceToSegment(points[i], points[from], points[to]); + if (d > distance) + { + distance = d; + farthest = i; + } + } + if (farthest < 0) + continue; + keep[farthest] = true; + spans.Push((farthest, to)); + spans.Push((from, farthest)); + } + + var previous = points[0]; + for (var i = 1; i < points.Count; i++) + { + if (!keep[i]) + continue; + result.Add(new Line(previous, points[i])); + previous = points[i]; + } + } + + /// Adds the entity's points from its start up to, not including, its end. + private static void Sample(Entity entity, List points) + { + if (entity is Line line) + { + points.Add(line.StartPoint); + return; + } + var arc = (Arc)entity; + var sweep = arc.SweepAngle(); + var segments = 1; + if (arc.Radius > SampleTolerance) + { + // A chord over angle a sags r(1 - cos(a/2)) below its arc. + var step = 2 * PortableMath.Acos(1 - SampleTolerance / arc.Radius); + segments = System.Math.Max(1, (int)System.Math.Ceiling(sweep / step)); + } + var sampled = arc.ToPoints(segments); + for (var i = 0; i < sampled.Count - 1; i++) + points.Add(sampled[i]); + } + + private static Vector End(Entity entity) => + entity is Line line ? line.EndPoint : ((Arc)entity).EndPoint(); + + private static double DistanceToSegment(Vector p, Vector a, Vector b) + { + var dx = b.X - a.X; + var dy = b.Y - a.Y; + var lengthSquared = dx * dx + dy * dy; + if (lengthSquared <= 0) + return p.DistanceTo(a); + var t = ((p.X - a.X) * dx + (p.Y - a.Y) * dy) / lengthSquared; + t = System.Math.Max(0, System.Math.Min(1, t)); + return p.DistanceTo(new Vector(a.X + t * dx, a.Y + t * dy)); + } + } +} diff --git a/OpenNest.Core/Geometry/Shape.cs b/OpenNest.Core/Geometry/Shape.cs index dd2059ee..12080f9c 100644 --- a/OpenNest.Core/Geometry/Shape.cs +++ b/OpenNest.Core/Geometry/Shape.cs @@ -688,6 +688,17 @@ namespace OpenNest.Geometry offsetLine.StartPoint = intersection; lastOffsetLine.EndPoint = intersection; } + else if ( + (side == OffsetSide.Left && cross >= 0) || (side == OffsetSide.Right && cross <= 0) + ) + { + // Nearly parallel lines turning concave by less than the corner test resolves + // (short segments of a polyline curve): an arc between the offsets' ends would + // sweep the long way round the corner, a near circle per joint. A straight + // bridge stays inside the offset envelope, as at any concave corner. + if (lastOffsetLine.EndPoint.DistanceTo(offsetLine.StartPoint) > OpenNest.Math.Tolerance.Epsilon) + offsetShape.Entities.Add(new Line(lastOffsetLine.EndPoint, offsetLine.StartPoint)); + } else { var arc = new Arc( diff --git a/OpenNest.Core/PartGeometry.cs b/OpenNest.Core/PartGeometry.cs index fca663a2..7b42239a 100644 --- a/OpenNest.Core/PartGeometry.cs +++ b/OpenNest.Core/PartGeometry.cs @@ -69,6 +69,15 @@ namespace OpenNest var geoEntities = MaterialEntities(program); var profile = new ShapeProfile(geoEntities); + // A dense run of tiny entities is thinned to a few chords on a slightly wider offset; + // the chords stay outside the true one, so only clearance is added (DenseOutline). + if (DenseOutline.HasDenseRun(profile.Perimeter.Entities)) + { + var padded = profile.Perimeter.OffsetOutward(spacing + DenseOutline.Pad); + if (padded != null) + return DenseOutline.Thin(padded.Entities); + } + var offsetShape = profile.Perimeter.OffsetOutward(spacing); if (offsetShape == null) return new List(); diff --git a/OpenNest.Tests/Geometry/DenseOutlineTests.cs b/OpenNest.Tests/Geometry/DenseOutlineTests.cs new file mode 100644 index 00000000..8574ee0a --- /dev/null +++ b/OpenNest.Tests/Geometry/DenseOutlineTests.cs @@ -0,0 +1,124 @@ +using System.Collections.Generic; +using System.Linq; +using OpenNest.Geometry; +using OpenNest.Math; + +namespace OpenNest.Tests.Geometry; + +/// +/// A plate whose top edge is a curve exported as 200 tiny lines, as CAD exports often write +/// splines. The spacing outline must not grow a near-circle at every joint, and the thinned +/// outline must keep at least the spacing from the part everywhere. +/// +public class DenseOutlineTests +{ + private const double Spacing = 0.125; + + /// A 3 x 1 plate, counterclockwise, whose top edge sags by + /// (negative: bulges out) in 200 lines of 0.015. + private static Shape Plate(double bow) + { + var points = new List { new(0, 0), new(3, 0), new(3, 1) }; + for (var i = 1; i < 200; i++) + { + var x = 3 - 3.0 * i / 200; + points.Add(new Vector(x, 1 - bow * System.Math.Sin(System.Math.PI * x / 3))); + } + points.Add(new Vector(0, 1)); + var shape = new Shape(); + for (var i = 0; i < points.Count; i++) + shape.Entities.Add(new Line(points[i], points[(i + 1) % points.Count])); + return shape; + } + + [Theory] + [InlineData(0.02)] + [InlineData(0.0005)] + public void OffsetOfShallowConcaveJointsHasNoNearCircleArcs(double bow) + { + var offset = Plate(bow).OffsetOutward(Spacing); + + Assert.NotNull(offset); + // The plate's own corners turn a quarter; no joint arc may sweep round its corner. + Assert.All(offset.Entities.OfType(), arc => Assert.True(arc.SweepAngle() < 0.75 * System.Math.PI, + $"arc sweeps {arc.SweepAngle()}")); + } + + [Theory] + [InlineData(0.02)] + [InlineData(-0.02)] + [InlineData(0.0005)] + public void ThinnedOutlineKeepsTheSpacingWithFewEntities(double bow) + { + var plate = Plate(bow); + Assert.True(DenseOutline.HasDenseRun(plate.Entities), "no dense run"); + + var thinned = DenseOutline.Thin(plate.OffsetOutward(Spacing + DenseOutline.Pad).Entities); + + Assert.True(thinned.Count < 40, $"{thinned.Count} entities"); + var edges = plate.Entities.Cast().ToList(); + foreach (var point in Samples(thinned)) + { + var distance = edges.Min(e => Distance(point, e.StartPoint, e.EndPoint)); + Assert.True(distance >= Spacing - 1e-9, $"{point} is {distance} from the plate"); + Assert.True(distance <= Spacing + 2 * DenseOutline.Pad + 1e-6, $"{point} is {distance} from the plate"); + } + } + + [Fact] + public void ThinnedOutlineIsClosed() + { + var thinned = DenseOutline.Thin(Plate(0.02).OffsetOutward(Spacing + DenseOutline.Pad).Entities); + + for (var i = 0; i < thinned.Count; i++) + { + var end = End(thinned[i]); + var next = Start(thinned[(i + 1) % thinned.Count]); + Assert.True(end.DistanceTo(next) < 1e-6, $"gap after entity {i} of {thinned.Count}: {thinned[i]} then {thinned[(i + 1) % thinned.Count]}"); + } + } + + [Fact] + public void ContourWithoutADenseRunIsNotThinned() + { + var square = new Shape(); + square.Entities.Add(new Line(0, 0, 10, 0)); + square.Entities.Add(new Line(10, 0, 10, 10)); + square.Entities.Add(new Line(10, 10, 0, 10)); + square.Entities.Add(new Line(0, 10, 0, 0)); + + Assert.False(DenseOutline.HasDenseRun(square.Entities)); + } + + private static IEnumerable Samples(IEnumerable entities) + { + foreach (var entity in entities) + { + if (entity is Arc arc) + { + foreach (var p in arc.ToPoints(16)) + yield return p; + continue; + } + var line = (Line)entity; + for (var i = 0; i <= 16; i++) + { + var t = i / 16.0; + yield return new Vector(line.StartPoint.X + t * (line.EndPoint.X - line.StartPoint.X), + line.StartPoint.Y + t * (line.EndPoint.Y - line.StartPoint.Y)); + } + } + } + + private static Vector Start(Entity e) => e is Line l ? l.StartPoint : ((Arc)e).StartPoint(); + + private static Vector End(Entity e) => e is Line l ? l.EndPoint : ((Arc)e).EndPoint(); + + private static double Distance(Vector p, Vector a, Vector b) + { + var dx = b.X - a.X; + var dy = b.Y - a.Y; + var t = System.Math.Clamp(((p.X - a.X) * dx + (p.Y - a.Y) * dy) / (dx * dx + dy * dy), 0, 1); + return p.DistanceTo(new Vector(a.X + t * dx, a.Y + t * dy)); + } +} diff --git a/docs/geometry/dense-outlines.md b/docs/geometry/dense-outlines.md new file mode 100644 index 00000000..874df8b3 --- /dev/null +++ b/docs/geometry/dense-outlines.md @@ -0,0 +1,47 @@ +# Dense outlines in spacing geometry + +Fill, best-fit pairs and `Compactor` slide parts against each part's spacing outline: +`PartGeometry.GetOffsetPerimeterEntities`, the perimeter offset outward by the spacing (cutouts +are never part of it). Every slide costs in proportion to the entities on both sides, so a +perimeter carrying a curve that a CAD export wrote as hundreds of tiny lines makes every query +slow. + +## Reproduced case + +A braze-casing angle (`4980 A01 PT71`, 5.30 x 28.28, 3/16 steel) has a 0.98-inch curve of radius +22.9 written as 199 lines of about 0.005 inch. Its spacing outline held 414 entities, and Fill of +33 copies on a 72 x 144 sheet took 8.6 minutes; Auto Nest's Irregular engine, which proposes such +fills as Lattice blocks, never finished its first plate in 15 minutes. + +Two causes, both fixed: + +- **Near-circle joint arcs.** `Shape.JoinOffsetLines` tells a convex corner from a concave one by + an unnormalized cross product against `Tolerance.Epsilon`. Between 0.005-inch lines a shallow + concave turn falls under that threshold, the nearly parallel offsets do not intersect, and the + fallback arc swept the long way round the corner: a near circle of the spacing radius at every + joint. Those circles lie inside the true offset, so layouts stayed valid, but each one is a slide + query. A turn that is not convex now gets a straight bridge between the offsets' ends, as the + general join already does at concave corners; a convex turn keeps its short arc. +- **Dense runs are thinned** (`DenseOutline`). A perimeter holding a run of at least + `MinRun` (16) consecutive lines or arcs shorter than `ShortLength` (0.02 inch) is offset by the + spacing plus `Pad` (0.0015 inch) instead, and each such run is replaced by Douglas-Peucker chords + through points on that offset (arcs sampled within 0.0005, chords within 0.001). Every chord + stays within the pad of the padded offset, so it lies outside the offset at the true spacing: + layouts spaced on the thinned outline keep the spacing, at most twice the pad (0.003 inch) wider + beside a dense run. Perimeters without a dense run keep their exact offset. + +The angle's spacing outline is now 21 entities, and the same Fill takes 69 seconds with every +part passing the overlap check. What remains is mostly the exact overlap check, which still +triangulates the true perimeter and is deliberately not thinned. On the whole braze-casing job +(219 parts, five stock sizes) Irregular now completes its normal search in under 5 minutes +(24 sheets, 88.6%), and searching until a 15-minute limit reaches 22 sheets (89.9%), against +28 sheets (78.3%) before. + +## Boundaries + +- Thinning only ever adds clearance; it never loosens a tolerance. Validation (`NestLayoutCheck`, + `SpacingOutline`, `NativeContours`) and the overlap check still read the true geometry. +- Only the spacing outline is thinned. Drawings, programs, cut paths and posts are unchanged; to + remove the dense run itself, simplify the drawing in the CAD Converter. +- `DenseOutlineTests` covers the joint arcs, the spacing bound on both sides of a dense run, and + closure.