From 8ed2b291012fae5985757c1b2ac34707db7c8dd1 Mon Sep 17 00:00:00 2001 From: James Jackson-South Date: Tue, 27 Oct 2026 17:00:29 +1000 Subject: [PATCH 01/24] Update shared infrastructure for V2 --- .editorconfig | 5 +++++ .gitattributes | 2 ++ AGENTS.md | 32 +++++++++++++++++--------------- SECURITY.md | 21 ++++++++++++++------- shared-infrastructure | 2 +- 5 files changed, 39 insertions(+), 23 deletions(-) diff --git a/.editorconfig b/.editorconfig index f579ff5..9592a0c 100644 --- a/.editorconfig +++ b/.editorconfig @@ -19,6 +19,7 @@ indent_size = 4 end_of_line = lf insert_final_newline = true trim_trailing_whitespace = true +max_line_length = 160 ########################################## # File Extension Settings @@ -134,6 +135,10 @@ csharp_style_prefer_null_check_over_type_check = true:warning # C# Style Rules # https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/language-rules#c-style-rules [*.{cs,csx,cake}] +# Report lines exceeding the shared editor limit during analysis and builds. +roslynator_max_line_length = 160 +dotnet_diagnostic.RCS0056.severity = warning + # 'var' preferences csharp_style_var_for_built_in_types = false:error csharp_style_var_when_type_is_apparent = false:error diff --git a/.gitattributes b/.gitattributes index e594c0e..29bb203 100644 --- a/.gitattributes +++ b/.gitattributes @@ -125,6 +125,8 @@ *.ktx filter=lfs diff=lfs merge=lfs -text *.ktx2 filter=lfs diff=lfs merge=lfs -text *.astc filter=lfs diff=lfs merge=lfs -text +*.uastc filter=lfs diff=lfs merge=lfs -text +*.raw filter=lfs diff=lfs merge=lfs -text *.pam filter=lfs diff=lfs merge=lfs -text *.pbm filter=lfs diff=lfs merge=lfs -text *.pgm filter=lfs diff=lfs merge=lfs -text diff --git a/AGENTS.md b/AGENTS.md index 814e3ce..38cc8ea 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -4,9 +4,12 @@ These instructions apply to the entire repository. More-specific `AGENTS.md` fil ## Working Practices -- Inspect the relevant implementation, tests, benchmarks, project files, and nearby code before proposing or making changes. Do not infer current behavior when the source is available. +- Inspect only the source and supporting files needed for the task before proposing or making changes. Do not infer current behavior when the source is available. - Make the smallest complete change that solves the requested problem. Avoid unrelated cleanup, speculative abstractions, and formatting churn. -- Match established architecture, naming, formatting, documentation, and test patterns. Treat `.editorconfig`, analyzers, and repository build settings as authoritative. +- Trace the existing execution path before changing it. Extend and optimize the existing implementation within the requested behavior and affected path. +- Before implementing an operation, find and inspect the existing APIs that provide it. Use or extend those APIs instead of writing equivalent logic elsewhere. This includes color conversion, pixel conversion, memory management, and vectorized operations. If an API lacks required behavior, improve its owning implementation rather than bypassing it with a separate implementation. +- Follow existing naming, formatting, documentation, and test patterns. Treat `.editorconfig`, analyzers, and repository build settings as authoritative. +- Use simple technical English in all communication, documentation, and comments. Use short sentences, active voice, and existing code terminology. - Preserve public API and observable behavior unless the task explicitly requires a change. Public API documentation must describe observable behavior, not implementation details. - Do not use reflection against built assemblies, ad hoc assembly loading, or temporary probe projects unless explicitly requested. - Build .NET projects in Release configuration unless explicitly instructed otherwise. @@ -15,27 +18,26 @@ These instructions apply to the entire repository. More-specific `AGENTS.md` fil - Treat throughput, latency, memory use, and binary size as design constraints, especially in pixel-processing, drawing, parsing, encoding, and other hot paths. - Avoid unnecessary allocations, copies, boxing, closures, interface dispatch, repeated enumeration, and extra passes over data. -- Reuse the repository's existing memory ownership, pooling, span, vectorization, and parallelization patterns. Do not introduce a new mechanism when an established one fits. -- Keep hot loops simple and bounds-check-friendly. Hoist invariant work, preserve locality, and use the narrowest suitable data types without sacrificing correctness. -- Do not trade correctness or maintainability for assumed speed. Support non-obvious optimizations with measurements or clear evidence, and add or update benchmarks when performance is the purpose of the change. +- Reuse existing memory ownership, pooling, span, vectorization, and parallelization mechanisms. +- Use a SIMD-first design for suitable data processing code. Build on existing vectorized operations, dispatch mechanisms, and scalar fallbacks. Keep hot loops simple, hoist invariant work, and preserve memory locality. +- Preserve correctness and maintainability during optimization. Distinguish source-based reasoning from measured results. Claim a speedup only with measurements. Use existing benchmarks first. Add or update cases only when they measure relevant behavior that existing benchmarks miss. - Consider all supported target frameworks and runtime capabilities. Do not regress fallback paths while optimizing newer runtimes. ## C# Conventions -- Follow the existing code around the change; local patterns take precedence over generic preferences. +- Follow local patterns when they comply with the explicit rules. - Do not use `record` or `record struct` types. - Prefer established invariants over redundant guards. Validate at real external boundaries and do not add defensive checks for internally controlled states. -- Do not extract single-use helpers merely to name a block. Extract only for genuine reuse, an established local pattern, or meaningful complexity reduction. +- Do not extract single-use helpers merely to name a block. Extract only for genuine reuse, an established local pattern, or independently complex logic. - Add vertical whitespace after multi-line statements and declarations and between distinct logical stages. Never add trailing whitespace. -- Document every method, constructor, and property, regardless of whether it is public, internal, protected, or private. Keep public API documentation limited to observable behavior; use private and internal documentation to capture the contract and intent needed to maintain the code. -- Add inline comments throughout complex code. Explain algorithms, formulas, invariants, ownership, compatibility behavior, and performance tradeoffs at the operations and decisions they govern. Explain why the code is shaped that way rather than narrating the syntax. -- Document SIMD code especially thoroughly. Explain the vector layout, lane meaning, widening or narrowing, masks, shuffles, constants, alignment or remainder handling, supported instruction paths, scalar equivalence, and the reason each non-obvious operation is correct. -- Write algorithm and SIMD comments for a maintainer who is unfamiliar with the implementation. The reader should not need to reconstruct intent from external documentation, issue history, or benchmark results. +- Document every added method, constructor, and property, regardless of visibility. Update documentation when a member's behavior or contract changes. Keep public API documentation limited to observable behavior. Use private and internal documentation to explain the contract and intent. +- Add inline comments that explain why complex code works. Explain algorithms, formulas, invariants, memory ownership, compatibility behavior, and performance decisions where they apply. +- For SIMD, explain lane layouts, operations, alignment, remainders, and scalar equivalence so an unfamiliar maintainer can follow the code. ## Verification -- Add or update focused tests when behavior changes, following the test framework and conventions already used by the project. -- Never hack, weaken, skip, conditionally bypass, or otherwise manipulate a test to make it pass. Fix the production defect or the genuine test defect while preserving the test's intended coverage and sensitivity. -- Do not update golden files, reference images, snapshots, baselines, or expected-output artifacts to resolve a test failure. Treat a mismatch as evidence to investigate and correct the implementation. -- Run the narrowest relevant formatting, test, and Release build commands, then expand verification in proportion to the risk and scope of the change. +- Add or update tests only when they prove a required behavior or expose a real defect. Derive expectations from established contracts, explicit requirements, or defect evidence. Use source to identify contracts and integration points, not to copy implementation results into expectations. Prefer extending existing tests. Avoid redundant cases and assertions that merely repeat the implementation. +- Never weaken, skip, or bypass a valid test to make it pass. Fix the production defect or the genuine test defect. Replace or remove a test only with evidence that its expectation is invalid or its coverage is redundant. +- Do not update golden files, reference images, snapshots, baselines, or expected-output artifacts merely to silence a failure. Investigate mismatches. Update expected results only for an established requirement change or an incorrect reference result proved by independent contract or defect evidence. +- Test the actual behavior through the existing execution path. Synthetic inputs must exercise an established requirement or reproduce a real defect. Do not invent requirements or substitute internal structure and helper calls for assertions about required behavior. Run the narrowest relevant formatting, test, and Release build commands. - Report what changed, the verification performed, and any remaining risks or unverified assumptions. diff --git a/SECURITY.md b/SECURITY.md index 8b2e1df..2e060f6 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -2,16 +2,23 @@ ## Supported Versions -Six Labors provides security fixes only for the latest major version of each library. +Six Labors provides security updates for the latest major version of each library. -Older major versions are end-of-life and do not receive security fixes. +Each major version remains eligible for security updates for 12 months after the first stable release of the next major version of that library. +After this period, that major version is end-of-life and does not receive security updates. -Users must upgrade to the latest major version to receive security fixes. +Users must install the latest available patch or minor release within a supported major version to receive security fixes. +Older releases within that major version are not maintained separately. -| Version | Supported | -| -------------------- | --------- | -| Latest major version | Yes | -| Older major versions | No | +| Version | Supported | +| ------- | --------- | +| Latest major version | Yes | +| Superseded major version within 12 months of the next major's first stable release | Yes | +| Superseded major version after that 12-month period | No | + +Security updates may require a license key under the existing license terms. This does not change the license terms. + +This policy covers security fixes only. It does not include feature backports or extend support for underlying .NET versions. Security fixes, if any, are provided at Six Labors' discretion. diff --git a/shared-infrastructure b/shared-infrastructure index a835a9d..4b38130 160000 --- a/shared-infrastructure +++ b/shared-infrastructure @@ -1 +1 @@ -Subproject commit a835a9d74e82b2d32b580a7902eb2699ebc47098 +Subproject commit 4b381305f82be24773db8aaea53ecc949943429e From 7438e1d47c8e564a0ad6e2d9b67a41d1071e1b5d Mon Sep 17 00:00:00 2001 From: James Jackson-South Date: Tue, 27 Oct 2026 17:10:47 +1000 Subject: [PATCH 02/24] Fix contour hierarchy, winding caches and small intersections --- src/PolygonClipper/Contour.cs | 66 ++++++++++++++----- src/PolygonClipper/Polygon.cs | 10 ++- src/PolygonClipper/PolygonClipper.cs | 11 ++++ src/PolygonClipper/PolygonUtilities.cs | 19 ++++-- src/PolygonClipper/SelfIntersectionRemover.cs | 20 +----- .../SelfIntersectionSweepLine.cs | 6 +- src/PolygonClipper/SweepEventComparer.cs | 5 ++ tests/PolygonClipper.Tests/ContourTests.cs | 29 ++++++++ tests/PolygonClipper.Tests/PolygonTests.cs | 36 ++++++++++ .../PolygonUtilitiesTests.cs | 13 ++++ .../SweepEventComparerTests.cs | 11 ++++ 11 files changed, 174 insertions(+), 52 deletions(-) diff --git a/src/PolygonClipper/Contour.cs b/src/PolygonClipper/Contour.cs index 5e73b41..0a0751f 100644 --- a/src/PolygonClipper/Contour.cs +++ b/src/PolygonClipper/Contour.cs @@ -140,22 +140,7 @@ public bool IsCounterClockwise() this.hasCachedOrientation = true; - double area = 0; - Vertex c; - Vertex c1; - - List points = this.vertices; - for (int i = 0; i < points.Count - 1; i++) - { - c = points[i]; - c1 = points[i + 1]; - area += Vertex.Cross(c, c1); - } - - c = points[^1]; - c1 = points[0]; - area += Vertex.Cross(c, c1); - return this.cachedCounterClockwise = area >= 0; + return this.cachedCounterClockwise = PolygonUtilities.Area(this.vertices) >= 0; } /// @@ -216,14 +201,22 @@ public void Translate(double x, double y) /// /// The vertex to add. [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Add(in Vertex vertex) => this.vertices.Add(vertex); + public void Add(in Vertex vertex) + { + this.vertices.Add(vertex); + this.hasCachedOrientation = false; + } /// /// Removes the vertex at the specified index from the contour. /// /// The index of the vertex to remove. [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void RemoveVertexAt(int index) => this.vertices.RemoveAt(index); + public void RemoveVertexAt(int index) + { + this.vertices.RemoveAt(index); + this.hasCachedOrientation = false; + } /// /// Clears all vertices and holes from the contour. @@ -232,6 +225,7 @@ public void Clear() { this.vertices.Clear(); this.holeIndices.Clear(); + this.hasCachedOrientation = false; } /// @@ -251,6 +245,42 @@ public void Clear() /// The index of the hole to add. public void AddHoleIndex(int index) => this.holeIndices.Add(index); + /// + /// Moves hierarchy indices into a polygon that already contains contours. + /// + /// The number of preceding contours in the destination. + internal void OffsetHierarchyIndices(int offset) + { + if (this.ParentIndex is int parent) + { + this.ParentIndex = parent + offset; + } + + // Update the owning list in place. Join shares contour instances, so clearing + // and then reading the source's holes would erase the same list. + for (int i = 0; i < this.holeIndices.Count; i++) + { + this.holeIndices[i] += offset; + } + } + + /// + /// Remaps hierarchy indices after contours have been reordered. + /// + /// The destination index for each original contour index. + internal void RemapHierarchyIndices(ReadOnlySpan indices) + { + if (this.ParentIndex is int parent) + { + this.ParentIndex = indices[parent]; + } + + for (int i = 0; i < this.holeIndices.Count; i++) + { + this.holeIndices[i] = indices[this.holeIndices[i]]; + } + } + /// /// Creates a deep copy of this contour. /// diff --git a/src/PolygonClipper/Polygon.cs b/src/PolygonClipper/Polygon.cs index a5d0bfa..80e5383 100644 --- a/src/PolygonClipper/Polygon.cs +++ b/src/PolygonClipper/Polygon.cs @@ -74,19 +74,17 @@ public Contour this[int index] /// Joins another polygon to this instance. /// /// The polygon to join. + /// + /// Contours are shared with the source. Their hierarchy indices are updated for this polygon. + /// public void Join(Polygon polygon) { int size = this.Count; for (int i = 0; i < polygon.contours.Count; ++i) { Contour contour = polygon.contours[i]; + contour.OffsetHierarchyIndices(size); this.Add(contour); - this.GetLastContour().ClearHoles(); - - for (int j = 0; j < contour.HoleCount; ++j) - { - this.GetLastContour().AddHoleIndex(contour.GetHoleIndex(j) + size); - } } } diff --git a/src/PolygonClipper/PolygonClipper.cs b/src/PolygonClipper/PolygonClipper.cs index 3252c81..cb1c6f9 100644 --- a/src/PolygonClipper/PolygonClipper.cs +++ b/src/PolygonClipper/PolygonClipper.cs @@ -1020,6 +1020,8 @@ private static Polygon ConnectEdges(SweepEventPoolList sortedEvents, SweepEventC } Polygon polygon = []; + using Buffer contourIndices = new(result.Count); + Span indices = contourIndices.GetSpan(); for (int i = 0; i < result.Count; i++) { @@ -1027,17 +1029,26 @@ private static Polygon ConnectEdges(SweepEventPoolList sortedEvents, SweepEventC if (contour.IsExternal) { // The exterior ring goes first + indices[i] = polygon.Count; polygon.Add(contour); // Followed by holes if any for (int j = 0; j < contour.HoleCount; j++) { int holeId = contour.GetHoleIndex(j); + indices[holeId] = polygon.Count; polygon.Add(result[holeId]); } } } + // Connectivity used the original contour order. Exported indices must + // instead address the exterior/hole order returned to the caller. + for (int i = 0; i < polygon.Count; i++) + { + polygon[i].RemapHierarchyIndices(indices); + } + return polygon; } diff --git a/src/PolygonClipper/PolygonUtilities.cs b/src/PolygonClipper/PolygonUtilities.cs index a5f64b9..3d1451d 100644 --- a/src/PolygonClipper/PolygonUtilities.cs +++ b/src/PolygonClipper/PolygonUtilities.cs @@ -92,10 +92,11 @@ private static int FindIntersectionImpl(in Segment seg0, in Segment seg1, out Ve Vertex e = a2 - a1; double kross = Vertex.Cross(va, vb); - double sqrKross = kross * kross; double sqrLenA = Vertex.Dot(va, va); - if (sqrKross > 0) + // Squaring a representable non-zero cross product can underflow to zero, + // incorrectly sending small crossing segments into the collinear branch. + if (kross != 0) { // Lines of the segments are not parallel double s = Vertex.Cross(e, vb) / kross; @@ -132,8 +133,7 @@ private static int FindIntersectionImpl(in Segment seg0, in Segment seg1, out Ve // Lines are parallel; check if they are collinear kross = Vertex.Cross(e, va); - sqrKross = kross * kross; - if (sqrKross > 0) + if (kross != 0) { // Lines of the segments are different return 0; @@ -271,11 +271,16 @@ public static double Area(List path) } double area = 0; - Vertex prev = path[count - 1]; + + // Translation does not change area. Subtract a local origin before the + // products so a small ring far from zero does not lose its area or sign + // when large absolute-coordinate products cancel. + Vertex origin = path[0]; + Vertex prev = path[count - 1] - origin; for (int i = 0; i < count; i++) { - Vertex current = path[i]; - area += (prev.Y + current.Y) * (prev.X - current.X); + Vertex current = path[i] - origin; + area += Vertex.Cross(prev, current); prev = current; } diff --git a/src/PolygonClipper/SelfIntersectionRemover.cs b/src/PolygonClipper/SelfIntersectionRemover.cs index 20de49e..a4274b7 100644 --- a/src/PolygonClipper/SelfIntersectionRemover.cs +++ b/src/PolygonClipper/SelfIntersectionRemover.cs @@ -241,25 +241,7 @@ private static Vertex GetContourTestPoint(List contour) } private static double GetSignedArea(List contour) - { - int count = contour.Count; - if (count == 0) - { - return 0D; - } - - double area = 0; - Vertex current = contour[0]; - for (int i = 1; i < count; i++) - { - Vertex next = contour[i]; - area += Vertex.Cross(current, next); - current = next; - } - - area += Vertex.Cross(current, contour[0]); - return area * 0.5D; - } + => PolygonUtilities.Area(contour); private static bool HasSelfIntersection(List contour) { diff --git a/src/PolygonClipper/SelfIntersectionSweepLine.cs b/src/PolygonClipper/SelfIntersectionSweepLine.cs index e1e1119..54448b6 100644 --- a/src/PolygonClipper/SelfIntersectionSweepLine.cs +++ b/src/PolygonClipper/SelfIntersectionSweepLine.cs @@ -293,12 +293,14 @@ private static void SetOutputOwner(OutputRecord outputRecord, OutputRecord newOw [MethodImpl(MethodImplOptions.AggressiveInlining)] public static double ComputeSignedArea(OutputPoint outputPoint) { - // https://en.wikipedia.org/wiki/Shoelace_formula + // Use a local origin, as for PolygonUtilities.Area, without materializing + // the linked ring. Absolute-coordinate products can lose a small area. + Vertex origin = outputPoint.Point; double signedArea = 0.0; OutputPoint outputPoint2 = outputPoint; do { - signedArea += Vertex.Cross(outputPoint2.Prev.Point, outputPoint2.Point); + signedArea += Vertex.Cross(outputPoint2.Prev.Point - origin, outputPoint2.Point - origin); outputPoint2 = outputPoint2.Next!; } while (outputPoint2 != outputPoint); diff --git a/src/PolygonClipper/SweepEventComparer.cs b/src/PolygonClipper/SweepEventComparer.cs index f450ab3..0ca37af 100644 --- a/src/PolygonClipper/SweepEventComparer.cs +++ b/src/PolygonClipper/SweepEventComparer.cs @@ -13,6 +13,11 @@ internal sealed class SweepEventComparer : IComparer, IComparer /// public int Compare(SweepEvent? x, SweepEvent? y) { + if (ReferenceEquals(x, y)) + { + return 0; + } + if (x == null) { return -1; diff --git a/tests/PolygonClipper.Tests/ContourTests.cs b/tests/PolygonClipper.Tests/ContourTests.cs index 10cd8c4..edcd1e7 100644 --- a/tests/PolygonClipper.Tests/ContourTests.cs +++ b/tests/PolygonClipper.Tests/ContourTests.cs @@ -5,6 +5,35 @@ namespace SixLabors.PolygonClipper.Tests; public class ContourTests { + [Theory] + [InlineData(true)] + [InlineData(false)] + public void Orientation_TranslatedUnitSquare_PreservesDirection(bool counterClockwise) + { + Contour contour = CreateSquare(1E12, 1E12, 1, counterClockwise); + + Assert.Equal(counterClockwise, contour.IsCounterClockwise()); + } + + [Fact] + public void Orientation_VertexEdits_InvalidateCachedDirection() + { + Contour contour = [new Vertex(0, 0), new Vertex(1, 0), new Vertex(0, 1)]; + Assert.True(contour.IsCounterClockwise()); + + contour.Add(new Vertex(10, -10)); + Assert.False(contour.IsCounterClockwise()); + + contour.RemoveVertexAt(3); + Assert.True(contour.IsCounterClockwise()); + + contour.Clear(); + contour.Add(new Vertex(0, 0)); + contour.Add(new Vertex(0, 1)); + contour.Add(new Vertex(1, 0)); + Assert.False(contour.IsCounterClockwise()); + } + private static Contour CreateSquare(double x, double y, double size, bool counterClockwise = true) { Contour contour = new(4); diff --git a/tests/PolygonClipper.Tests/PolygonTests.cs b/tests/PolygonClipper.Tests/PolygonTests.cs index ccda967..9ae96de 100644 --- a/tests/PolygonClipper.Tests/PolygonTests.cs +++ b/tests/PolygonClipper.Tests/PolygonTests.cs @@ -5,6 +5,42 @@ namespace SixLabors.PolygonClipper.Tests; public class PolygonTests { + [Fact] + public void Join_PreservesAndOffsetsSharedContourHierarchy() + { + Polygon target = [CreateSquare(-20, -20, 5)]; + Contour outer = CreateSquare(0, 0, 10); + Contour hole = CreateSquare(2, 2, 6); + outer.AddHoleIndex(1); + hole.ParentIndex = 0; + hole.Depth = 1; + Polygon source = [outer, hole]; + + target.Join(source); + + Assert.Same(outer, target[1]); + Assert.Same(hole, target[2]); + Assert.Equal(1, outer.HoleCount); + Assert.Equal(2, outer.GetHoleIndex(0)); + Assert.Equal(1, hole.ParentIndex); + Assert.Equal(1, hole.Depth); + } + + [Fact] + public void Intersection_ReorderedComponents_KeepValidHoleIndices() + { + Polygon subject = [CreateSquare(0, 0, 100), CreateSquare(40, 40, 20), CreateSquare(20, -20, 5)]; + Polygon clip = [CreateSquare(-30, -30, 160)]; + + Polygon result = PolygonClipper.Intersection(subject, clip); + + Assert.Equal(3, result.Count); + Contour outer = Assert.Single(result, contour => contour.HoleCount == 1); + int holeIndex = outer.GetHoleIndex(0); + Assert.Equal(new Vertex(40, 40), result[holeIndex].GetBoundingBox().Min); + Assert.Same(outer, result[result[holeIndex].ParentIndex!.Value]); + } + private static Contour CreateSquare(double x, double y, double size) { Contour contour = diff --git a/tests/PolygonClipper.Tests/PolygonUtilitiesTests.cs b/tests/PolygonClipper.Tests/PolygonUtilitiesTests.cs index b3a1960..d7fa7dc 100644 --- a/tests/PolygonClipper.Tests/PolygonUtilitiesTests.cs +++ b/tests/PolygonClipper.Tests/PolygonUtilitiesTests.cs @@ -5,6 +5,19 @@ namespace SixLabors.PolygonClipper.Tests; public class PolygonUtilitiesTests { + [Fact] + public void FindIntersection_TinyCrossingSegments_ReturnsUniqueCrossing() + { + const double size = 1E-90; + Segment first = new(new Vertex(0, 0), new Vertex(size, size)); + Segment second = new(new Vertex(0, size), new Vertex(size, 0)); + + int count = PolygonUtilities.FindIntersection(first, second, out Vertex intersection, out _); + + Assert.Equal(1, count); + Assert.Equal(new Vertex(size * 0.5D, size * 0.5D), intersection); + } + [Fact] public void AnalyticalSignedArea() { diff --git a/tests/PolygonClipper.Tests/SweepEventComparerTests.cs b/tests/PolygonClipper.Tests/SweepEventComparerTests.cs index ef736a2..ba816aa 100644 --- a/tests/PolygonClipper.Tests/SweepEventComparerTests.cs +++ b/tests/PolygonClipper.Tests/SweepEventComparerTests.cs @@ -5,6 +5,17 @@ namespace SixLabors.PolygonClipper.Tests; public class SweepEventComparerTests { + [Fact] + public void SameEvent_CompareEqual() + { + SweepEvent first = new(new Vertex(0, 0), true, new SweepEvent(new Vertex(4, 0), false)); + SweepEventComparer comparer = new(); + + Assert.Equal(0, comparer.Compare(first, first)); + SegmentComparer segments = new(); + Assert.Equal(0, segments.Compare(first, first)); + } + private readonly SweepEventComparer comparer = new(); [Fact] From 51fdb4fcd6a962841556b21cf1b484593dcba7e9 Mon Sep 17 00:00:00 2001 From: James Jackson-South Date: Tue, 27 Oct 2026 17:57:47 +1000 Subject: [PATCH 03/24] Fix tiny intersections in the vertex overload --- src/PolygonClipper/PolygonUtilities.cs | 8 ++++---- tests/PolygonClipper.Tests/PolygonUtilitiesTests.cs | 11 ++++++++--- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/src/PolygonClipper/PolygonUtilities.cs b/src/PolygonClipper/PolygonUtilities.cs index 3d1451d..8129069 100644 --- a/src/PolygonClipper/PolygonUtilities.cs +++ b/src/PolygonClipper/PolygonUtilities.cs @@ -745,10 +745,11 @@ private static int FindIntersectionImpl(in Vertex a1, in Vertex a2, in Vertex b1 Vertex vb = b2 - b1; Vertex e = b1 - a1; double kross = Vertex.Cross(va, vb); - double sqrKross = kross * kross; double sqrLenA = Vertex.Dot(va, va); - if (sqrKross > 0D) + // Match the segment overload: squaring can underflow even when the + // determinant itself is non-zero and the crossing is representable. + if (kross != 0D) { // Lines of the segments are not parallel. double s = Vertex.Cross(e, vb) / kross; @@ -785,8 +786,7 @@ private static int FindIntersectionImpl(in Vertex a1, in Vertex a2, in Vertex b1 // Lines are parallel; check if they are collinear. kross = Vertex.Cross(e, va); - sqrKross = kross * kross; - if (sqrKross > 0D) + if (kross != 0D) { // Parallel but not collinear. return 0; diff --git a/tests/PolygonClipper.Tests/PolygonUtilitiesTests.cs b/tests/PolygonClipper.Tests/PolygonUtilitiesTests.cs index d7fa7dc..60d5072 100644 --- a/tests/PolygonClipper.Tests/PolygonUtilitiesTests.cs +++ b/tests/PolygonClipper.Tests/PolygonUtilitiesTests.cs @@ -8,14 +8,19 @@ public class PolygonUtilitiesTests [Fact] public void FindIntersection_TinyCrossingSegments_ReturnsUniqueCrossing() { - const double size = 1E-90; + double size = Math.ScaleB(1D, -300); Segment first = new(new Vertex(0, 0), new Vertex(size, size)); - Segment second = new(new Vertex(0, size), new Vertex(size, 0)); + Segment second = new(new Vertex(0, size * 0.75D), new Vertex(size, size * 0.75D)); int count = PolygonUtilities.FindIntersection(first, second, out Vertex intersection, out _); Assert.Equal(1, count); - Assert.Equal(new Vertex(size * 0.5D, size * 0.5D), intersection); + Assert.Equal(new Vertex(size * 0.75D, size * 0.75D), intersection); + + count = PolygonUtilities.FindIntersection(first.Source, first.Target, second.Source, second.Target, out intersection, out _); + + Assert.Equal(1, count); + Assert.Equal(new Vertex(size * 0.75D, size * 0.75D), intersection); } [Fact] From 74b1affe559fe73189a831c3ada74ca0090be1f1 Mon Sep 17 00:00:00 2001 From: James Jackson-South Date: Tue, 27 Oct 2026 18:10:27 +1000 Subject: [PATCH 04/24] Add single-pass Martinez fill-rule clipping --- README.md | 24 +- src/PolygonClipper/FillRule.cs | 26 + .../PolygonClipper.FillRules.cs | 147 ++++ src/PolygonClipper/PolygonClipper.Winding.cs | 802 ++++++++++++++++++ src/PolygonClipper/PolygonClipper.cs | 14 +- .../PolygonUtilities.Intersections.cs | 110 +++ src/PolygonClipper/PolygonUtilities.cs | 2 +- .../StablePriorityQueue{T,TComparer}.cs | 3 + src/PolygonClipper/VertexPoolList.cs | 4 + tests/PolygonClipper.Benchmarks/Benches.cs | 10 + .../FillRuleClippingTests.cs | 448 ++++++++++ .../PolygonClipper.Tests/GenericTestCases.cs | 8 +- .../NormalizationTests.cs | 2 +- 13 files changed, 1594 insertions(+), 6 deletions(-) create mode 100644 src/PolygonClipper/FillRule.cs create mode 100644 src/PolygonClipper/PolygonClipper.FillRules.cs create mode 100644 src/PolygonClipper/PolygonClipper.Winding.cs create mode 100644 src/PolygonClipper/PolygonUtilities.Intersections.cs create mode 100644 tests/PolygonClipper.Tests/FillRuleClippingTests.cs diff --git a/README.md b/README.md index 2e59dfd..3b152d8 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,7 @@ Contour normalization is handled by a dedicated Vatti/Clipper2-inspired pipeline - Works with non-convex polygons, including holes and multiple disjoint regions - Handles edge cases like overlapping edges and vertical segments - Preserves topology: output polygons include hole/contour hierarchy -- Deterministic and robust sweep line algorithm with O((n + k) log n) complexity +- Deterministic sweep line processing - Includes `PolygonClipper.Normalize` (Clipper2-inspired) for positive-winding contour normalization - Includes `PolygonStroker` for configurable geometric stroking (joins, caps, miter limits) - Uses double precision geometry without coordinate quantization @@ -45,6 +45,28 @@ Polygon clean = PolygonClipper.Normalize(input); `Normalize` uses a fixed positive-winding normalization path. +### Explicit fill rules + +The V2 overloads accept `EvenOdd`, `NonZero`, `Positive`, and `Negative` fill rules. +They interpret the original directed contours in one Martínez clipping sweep. They do not run `Normalize` first. +Counterclockwise contours contribute positive winding and clockwise contours contribute negative winding. +Input parent and hole metadata do not override the selected rule. + +```csharp +// Interpret both operands using their signed winding counts. +Polygon result = PolygonClipper.Union(subject, clipping, FillRule.NonZero); + +// Select an independent rule for each operand. +Polygon intersection = PolygonClipper.Intersection(subject, clipping, FillRule.EvenOdd, FillRule.NonZero); + +// Resolve one raw operand under an explicit rule without a separate normalization pass. +Polygon clean = PolygonClipper.Union(input, FillRule.NonZero); +``` + +Explicit-rule results have counterclockwise exterior contours, clockwise holes, and no duplicated closing vertex. +Coordinates must be finite doubles. The existing overloads and `Normalize` retain their existing behaviour. +Polygon clipping is pure geometry and remains entirely separate from rasterization and rasterizer clipping. + ### Stroking Use `PolygonStroker` to generate filled stroke polygons from input contours: diff --git a/src/PolygonClipper/FillRule.cs b/src/PolygonClipper/FillRule.cs new file mode 100644 index 0000000..49889ba --- /dev/null +++ b/src/PolygonClipper/FillRule.cs @@ -0,0 +1,26 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +namespace SixLabors.PolygonClipper; + +/// +/// Specifies how directed contours define a filled area. +/// +/// +/// Counterclockwise contours contribute positive winding; clockwise contours contribute negative winding. +/// The directed vertices determine winding independently of contour parent and hole metadata. +/// +public enum FillRule +{ + /// The area is filled where the winding count is odd. + EvenOdd = 0, + + /// The area is filled where the winding count is non-zero. + NonZero = 1, + + /// The area is filled where the winding count is positive. + Positive = 2, + + /// The area is filled where the winding count is negative. + Negative = 3 +} diff --git a/src/PolygonClipper/PolygonClipper.FillRules.cs b/src/PolygonClipper/PolygonClipper.FillRules.cs new file mode 100644 index 0000000..ae88053 --- /dev/null +++ b/src/PolygonClipper/PolygonClipper.FillRules.cs @@ -0,0 +1,147 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +namespace SixLabors.PolygonClipper; + +/// Provides explicit fill-rule operations on polygon geometry. +public partial class PolygonClipper +{ + private static readonly Polygon EmptyFillOperand = []; + + private bool useFillRules; + private FillRule subjectFillRule; + private FillRule clipFillRule; + private WindingSweep? windingSweep; + + /// + /// Initializes a new instance of the class with independent operand fill rules. + /// + /// The left-hand operand. + /// The right-hand operand. + /// The Boolean operation. + /// The rule interpreting the subject's directed contours. + /// The rule interpreting the clipping operand's directed contours. + public PolygonClipper(Polygon subject, Polygon clip, BooleanOperation operation, FillRule subjectFillRule, FillRule clipFillRule) + { + ValidateFillArguments(subject, clip, operation, subjectFillRule, clipFillRule); + this.Configure(subject, clip, operation); + this.useFillRules = true; + this.subjectFillRule = subjectFillRule; + this.clipFillRule = clipFillRule; + } + + /// Intersects two filled areas using a common fill rule. + /// The left-hand operand. + /// The right-hand operand. + /// The rule interpreting both operands. + /// The filled area common to both operands. + public static Polygon Intersection(Polygon subject, Polygon clip, FillRule fillRule) + => Intersection(subject, clip, fillRule, fillRule); + + /// Intersects two filled areas using independent fill rules. + /// The left-hand operand. + /// The right-hand operand. + /// The subject's fill rule. + /// The clipping operand's fill rule. + /// The filled area common to both operands. + public static Polygon Intersection(Polygon subject, Polygon clip, FillRule subjectFillRule, FillRule clipFillRule) + => ExecuteFillOperation(subject, clip, BooleanOperation.Intersection, subjectFillRule, clipFillRule); + + /// Unites two filled areas using a common fill rule. + /// The left-hand operand. + /// The right-hand operand. + /// The rule interpreting both operands. + /// The filled area belonging to either operand. + public static Polygon Union(Polygon subject, Polygon clip, FillRule fillRule) + => Union(subject, clip, fillRule, fillRule); + + /// Unites two filled areas using independent fill rules. + /// The left-hand operand. + /// The right-hand operand. + /// The subject's fill rule. + /// The clipping operand's fill rule. + /// The filled area belonging to either operand. + public static Polygon Union(Polygon subject, Polygon clip, FillRule subjectFillRule, FillRule clipFillRule) + => ExecuteFillOperation(subject, clip, BooleanOperation.Union, subjectFillRule, clipFillRule); + + /// Resolves directed contours into their filled area. + /// The raw directed contours. + /// The rule interpreting the contours. + /// The resolved filled area, without changing the input contours. + /// Input hierarchy does not override contour direction or the selected fill rule. + public static Polygon Union(Polygon polygon, FillRule fillRule) + => ExecuteFillOperation(polygon, EmptyFillOperand, BooleanOperation.Union, fillRule, FillRule.EvenOdd); + + /// Subtracts one filled area from another using a common fill rule. + /// The area to retain. + /// The area to subtract. + /// The rule interpreting both operands. + /// The subject area outside the clipping operand. + public static Polygon Difference(Polygon subject, Polygon clip, FillRule fillRule) + => Difference(subject, clip, fillRule, fillRule); + + /// Subtracts one filled area from another using independent fill rules. + /// The area to retain. + /// The area to subtract. + /// The subject's fill rule. + /// The clipping operand's fill rule. + /// The subject area outside the clipping operand. + public static Polygon Difference(Polygon subject, Polygon clip, FillRule subjectFillRule, FillRule clipFillRule) + => ExecuteFillOperation(subject, clip, BooleanOperation.Difference, subjectFillRule, clipFillRule); + + /// Computes exclusive filled coverage using a common fill rule. + /// The left-hand operand. + /// The right-hand operand. + /// The rule interpreting both operands. + /// The filled area belonging to exactly one operand. + public static Polygon Xor(Polygon subject, Polygon clip, FillRule fillRule) + => Xor(subject, clip, fillRule, fillRule); + + /// Computes exclusive filled coverage using independent fill rules. + /// The left-hand operand. + /// The right-hand operand. + /// The subject's fill rule. + /// The clipping operand's fill rule. + /// The filled area belonging to exactly one operand. + public static Polygon Xor(Polygon subject, Polygon clip, FillRule subjectFillRule, FillRule clipFillRule) + => ExecuteFillOperation(subject, clip, BooleanOperation.Xor, subjectFillRule, clipFillRule); + + /// Executes an explicit fill-rule operation through the existing clipper pool. + /// The left-hand operand. + /// The right-hand operand. + /// The Boolean operation. + /// The subject's fill rule. + /// The clipping operand's fill rule. + /// The resolved filled area. + private static Polygon ExecuteFillOperation(Polygon subject, Polygon clip, BooleanOperation operation, FillRule subjectRule, FillRule clipRule) + { + ValidateFillArguments(subject, clip, operation, subjectRule, clipRule); + PolygonClipper clipper = Rent(subject, clip, operation); + try + { + clipper.useFillRules = true; + clipper.subjectFillRule = subjectRule; + clipper.clipFillRule = clipRule; + return clipper.Run(); + } + finally + { + Return(clipper); + } + } + + /// Validates new public operation arguments before taking geometry shortcuts. + /// The left-hand operand. + /// The right-hand operand. + /// The Boolean operation. + /// The subject's fill rule. + /// The clipping operand's fill rule. + private static void ValidateFillArguments(Polygon subject, Polygon clip, BooleanOperation operation, FillRule subjectRule, FillRule clipRule) + { + ArgumentNullException.ThrowIfNull(subject); + ArgumentNullException.ThrowIfNull(clip); + ArgumentOutOfRangeException.ThrowIfGreaterThan((uint)operation, (uint)BooleanOperation.Xor, nameof(operation)); + ArgumentOutOfRangeException.ThrowIfGreaterThan((uint)subjectRule, (uint)FillRule.Negative, nameof(subjectRule)); + ArgumentOutOfRangeException.ThrowIfGreaterThan((uint)clipRule, (uint)FillRule.Negative, nameof(clipRule)); + } +} diff --git a/src/PolygonClipper/PolygonClipper.Winding.cs b/src/PolygonClipper/PolygonClipper.Winding.cs new file mode 100644 index 0000000..f321b92 --- /dev/null +++ b/src/PolygonClipper/PolygonClipper.Winding.cs @@ -0,0 +1,802 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +namespace SixLabors.PolygonClipper; + +/// Provides native signed-winding execution for polygon clipping. +public partial class PolygonClipper +{ + /// Compares points in the formal sweep's lexicographic order. + /// The first point. + /// The second point. + /// Their sweep ordering. + private static int ComparePoints(Vertex first, Vertex second) + { + int x = first.X.CompareTo(second.X); + return x == 0 ? first.Y.CompareTo(second.Y) : x; + } + + /// Stores separate subject and clip contributions without cross-operand cancellation. + private readonly struct WindingCount + { + /// The subject winding. + public readonly int Subject; + + /// The clipping operand winding. + public readonly int Clip; + + /// Initializes a new instance of the struct. + /// The subject component. + /// The clipping component. + public WindingCount(int subject, int clip) + { + this.Subject = subject; + this.Clip = clip; + } + + /// Gets a value indicating whether both contributions cancel. + public bool IsZero => this.Subject == 0 && this.Clip == 0; + + /// Adds an interval's contribution. + /// The contribution to add. + /// The summed winding. + public WindingCount Add(WindingCount other) => new(this.Subject + other.Subject, this.Clip + other.Clip); + + /// Removes contributions terminating at an endpoint. + /// The terminating contributions. + /// The remaining winding. + public WindingCount Subtract(WindingCount other) => new(this.Subject - other.Subject, this.Clip - other.Clip); + } + + /// Stores a versioned endpoint in the existing priority queue. + private readonly struct WindingEvent + { + /// The queued geometric point. + public readonly Vertex Point; + + /// The associated interval. + public readonly WindingEdge Edge; + + /// The interval version when queued. + public readonly int Version; + + /// Whether this record starts a source interval. + public readonly bool IsStart; + + /// Initializes a new instance of the struct. + /// The endpoint. + /// The interval. + /// Whether the record starts the interval. + public WindingEvent(Vertex point, WindingEdge edge, bool isStart) + { + this.Point = point; + this.Edge = edge; + this.Version = edge.Version; + this.IsStart = isStart; + } + + /// Gets a value indicating whether the representative still owns this queued record. + public bool IsValid => this.Version == this.Edge.Version && (this.IsStart || this.Edge.Active); + } + + /// + /// Stores the additional state needed by explicit fill rules. Legacy parity calls + /// do not allocate this workspace or enlarge their individual sweep events. + /// + private sealed class WindingSweep + { + private readonly List eventStorage = []; + private readonly StablePriorityQueue events; + private readonly WindingEdgePool edges = new(); + private readonly List active = []; + private readonly List activeResult = []; + private readonly List outgoing = []; + private readonly List bundled = []; + + /// Initializes a new instance of the class. + public WindingSweep() => this.events = new(WindingEventComparer.Instance, this.eventStorage); + + /// Gets the storage retained by this native sweep. + public int RetainedCapacity => this.edges.Capacity + this.eventStorage.Capacity + this.active.Capacity + + this.activeResult.Capacity + this.outgoing.Capacity + this.bundled.Capacity; + + /// Releases per-operation references while retaining bounded scratch storage. + public void Reset() + { + this.eventStorage.Clear(); + this.active.Clear(); + this.activeResult.Clear(); + this.outgoing.Clear(); + this.bundled.Clear(); + for (int i = 0; i < this.edges.Count; i++) + { + this.edges[i].Ends = null; + this.edges[i].Boundary = null; + } + + this.edges.Clear(); + } + + /// Clips raw directed contours in one Martinez intersection sweep. + /// The subject contours. + /// The clipping contours. + /// The Boolean operation. + /// The subject's fill rule. + /// The clipping operand's fill rule. + /// The existing clipper's output-event storage. + /// The existing edge-connection event comparer. + /// The connected result boundaries. + public Polygon Run( + Polygon subject, + Polygon clip, + BooleanOperation operation, + FillRule subjectRule, + FillRule clipRule, + SweepEventPoolList resultEvents, + SweepEventComparer resultComparer) + { + this.Reset(); + if (operation == BooleanOperation.Intersection && (subject.Count == 0 || clip.Count == 0)) + { + return []; + } + + // Reuse the existing capacity APIs and reserve source-sized storage + // before ingestion. Repeated geometric growth otherwise copies the + // larger endpoint records and can exceed the shared retention bound. + int vertexCount = subject.VertexCount + clip.VertexCount; + this.eventStorage.EnsureCapacity(vertexCount); + this.edges.EnsureCapacity(vertexCount); + resultEvents.EnsureCapacity(vertexCount * 2); + + this.AddInput(subject, true); + this.AddInput(clip, false); + this.events.Heapify(); + + while (this.events.Count > 0) + { + WindingEvent next = this.events.Dequeue(); + if (!next.IsValid) + { + continue; + } + + Vertex point = next.Point; + this.outgoing.Clear(); + int firstEnd = int.MaxValue; + int lastEnd = -1; + if (next.IsStart) + { + this.outgoing.Add(next.Edge); + } + else + { + firstEnd = lastEnd = next.Edge.Position; + } + + // A vertex is a transaction, not a sequence of parity toggles. + // Collect every start/end at this exact lexicographic point. + while (this.events.Count > 0 && this.events.Peek().Point == point) + { + next = this.events.Dequeue(); + if (next.IsValid && next.IsStart) + { + this.outgoing.Add(next.Edge); + } + else if (next.IsValid) + { + firstEnd = Math.Min(firstEnd, next.Edge.Position); + lastEnd = Math.Max(lastEnd, next.Edge.Position); + } + } + + int first = lastEnd < 0 ? FindLower(this.active, point) : firstEnd; + while (first > 0 && ContainsPoint(this.active[first - 1], point)) + { + first--; + } + + int after = Math.Max(first, lastEnd + 1); + while (after < this.active.Count && ContainsPoint(this.active[after], point)) + { + after++; + } + + // The result index is a filtered view of the very same block. + // Derive removals from the owned interval identities, so rounded + // incidence tests cannot remove a boundary independently of its + // source interval and leave a stale birth context behind. + int firstResult = first == 0 ? 0 : this.active[first - 1].ResultRank; + int afterResult = firstResult; + for (int i = first; i < after; i++) + { + WindingEdge incoming = this.active[i]; + if (incoming.Boundary is not null) + { + afterResult++; + } + } + + // The surviving lower interval is outside the changed block. + // Closure conserves the sum of signed contributions, so its + // prefix and every surviving prefix above the block stay valid. + WindingCount winding = first == 0 ? default : this.active[first - 1].Above; + SweepEvent? previousBoundary = firstResult == 0 ? null : this.activeResult[firstResult - 1].Boundary; + if (firstResult > 0 && this.activeResult[firstResult - 1].Start.X == this.activeResult[firstResult - 1].End.X) + { + previousBoundary = previousBoundary!.PrevInResult; + } + + for (int i = first; i < after; i++) + { + WindingEdge incoming = this.active[i]; + incoming.Active = false; + incoming.Version++; + if (incoming.Boundary is SweepEvent boundary) + { + // A historical contribution is never rewritten when its + // continuation changes fill membership. Only its actual + // terminal endpoint becomes known at this event. + SweepEvent right = new(point, false, boundary, PolygonType.Subject) + { + ContourId = boundary.ContourId + }; + boundary.OtherEvent = right; + resultEvents.Add(boundary); + resultEvents.Add(right); + } + + this.ContinueAt(incoming, point); + } + + this.active.RemoveRange(first, after - first); + this.activeResult.RemoveRange(firstResult, afterResult - firstResult); + + // All active intervals through point were included above, not + // merely those named by queued events. Outgoing rays all start + // here, so non-collinear rays cannot meet again in their interiors. + this.outgoing.Sort(WindingRayComparer.Instance); + this.BundleOutgoing(); + + int resultIndex = firstResult; + for (int i = 0; i < this.bundled.Count; i++) + { + WindingEdge edge = this.bundled[i]; + bool below = Membership(winding, operation, subjectRule, clipRule); + winding = winding.Add(edge.Delta); + edge.Above = winding; + bool above = Membership(winding, operation, subjectRule, clipRule); + if (below != above) + { + // Endpoint pairing is completed when the interval ends. + // No geometry consumer reads this event until connection. + edge.Boundary = new SweepEvent(point, true, PolygonType.Subject) + { + ContourId = edge.Id, + PrevInResult = previousBoundary!, + ResultTransition = above ? ResultTransition.Contributing : ResultTransition.NonContributing + }; + if (edge.Start.X != edge.End.X) + { + previousBoundary = edge.Boundary; + } + + this.activeResult.Insert(resultIndex++, edge); + } + + edge.Active = true; + this.active.Insert(first + i, edge); + this.events.Enqueue(new WindingEvent(edge.End, edge, false)); + } + + // List insertion/removal already shifts this suffix. Keep the + // endpoint anchors and filtered-boundary ranks in the same order. + // Winding counts above the changed block do not need recomputing. + int resultRank = firstResult; + for (int i = first; i < this.active.Count; i++) + { + WindingEdge edge = this.active[i]; + edge.Position = i; + if (edge.Boundary is not null) + { + resultRank++; + } + + edge.ResultRank = resultRank; + } + + // Interior outgoing pairs share this already closed event point. + // Only the two new exterior adjacencies can expose a future crossing. + if (this.bundled.Count == 0) + { + this.CheckNeighbors(first - 1, first, point); + } + else + { + this.CheckNeighbors(first - 1, first, point); + this.CheckNeighbors(first + this.bundled.Count - 1, first + this.bundled.Count, point); + } + } + + // Native events are completed at their right endpoints. Restore the + // ordering expected by the existing connector in O(B log B), rather + // than making its nearly-sorted repair loop sort reversed history. + resultEvents.Sort(resultComparer); + Polygon result = ConnectEdges(resultEvents, resultComparer); + for (int i = 0; i < result.Count; i++) + { + Contour contour = result[i]; + if (contour.Count > 1 && contour[0] == contour[^1]) + { + contour.RemoveVertexAt(contour.Count - 1); + } + + if (contour.IsExternal) + { + contour.SetCounterClockwise(); + } + else + { + contour.SetClockwise(); + } + } + + return result; + } + + /// Adds directed input segments without normalizing or reorienting them. + /// The input contours. + /// Whether these contours belong to the subject. + private void AddInput(Polygon polygon, bool subject) + { + for (int i = 0; i < polygon.Count; i++) + { + Contour contour = polygon[i]; + int count = GetContourSegmentCount(contour); + for (int j = 0; j < count; j++) + { + Segment segment = contour.GetSegment(j); + Vertex start = segment.Source; + Vertex end = segment.Target; + if (!double.IsFinite(start.X) || !double.IsFinite(start.Y)) + { + throw new ArgumentException("Polygon coordinates must be finite.", nameof(polygon)); + } + + if (start == end) + { + continue; + } + + int direction = 1; + if (ComparePoints(start, end) > 0) + { + (start, end) = (end, start); + direction = -1; + } + + // Lexicographic direction is the formal x+epsilon*y sweep + // direction, including vertical source segments. Epsilon is + // never evaluated or applied to the stored double coordinates. + WindingCount delta = subject ? new(direction, 0) : new(0, direction); + WindingEdge edge = this.edges.Add(start, end, delta); + this.eventStorage.Add(new WindingEvent(start, edge, true)); + } + } + } + + /// Preserves a split interval's longer source tails and endpoint deltas. + /// The interval ending at this point. + /// The complete event point. + private void ContinueAt(WindingEdge incoming, Vertex point) + { + if (incoming.Ends is SortedDictionary ends) + { + WindingCount delta = incoming.Delta; + if (ends.Remove(point, out WindingCount ending)) + { + delta = delta.Subtract(ending); + } + + if (ends.Count == 0) + { + incoming.Ends = null; + return; + } + + incoming.Delta = delta; + incoming.SourceEnd = FirstEndpoint(ends); + } + else if (ComparePoints(point, incoming.SourceEnd) >= 0) + { + return; + } + + // Output history owns independent SweepEvent objects. Reuse only the + // live interval, whose version was advanced before closing its old + // piece. Stale queue records stay invalid without retaining a new + // interval object for every intersection in the operation. + incoming.Start = point; + incoming.End = incoming.SourceEnd; + incoming.Boundary = null; + this.outgoing.Add(incoming); + } + + /// Combines coincident outgoing intervals without losing longer continuations. + private void BundleOutgoing() + { + this.bundled.Clear(); + int i = 0; + while (i < this.outgoing.Count) + { + WindingEdge edge = this.outgoing[i++]; + while (i < this.outgoing.Count && WindingRayComparer.Instance.Compare(edge, this.outgoing[i]) == 0) + { + WindingEdge other = this.outgoing[i++]; + + // A bundle may outlive its representative's original segment. + // Its support must cover every retained endpoint-ledger tail. + if (ComparePoints(other.Support.Target, edge.Support.Target) > 0) + { + edge.Support = new Segment(edge.Support.Source, other.Support.Target); + } + + if (edge.Ends is null && other.Ends is null && edge.SourceEnd == other.SourceEnd) + { + // The common duplicate-edge case needs no endpoint ledger. + edge.Delta = edge.Delta.Add(other.Delta); + continue; + } + + SortedDictionary ends = edge.Ends ??= + new SortedDictionary(WindingPointComparer.Instance) + { + [edge.SourceEnd] = edge.Delta + }; + if (other.Ends is SortedDictionary otherEnds) + { + foreach (KeyValuePair endpoint in otherEnds) + { + AddEndpoint(ends, endpoint.Key, endpoint.Value); + } + + other.Ends = null; + } + else + { + AddEndpoint(ends, other.SourceEnd, other.Delta); + } + + edge.Delta = edge.Delta.Add(other.Delta); + } + + if (edge.Ends is SortedDictionary ledger) + { + if (ledger.Count == 0) + { + continue; + } + + edge.SourceEnd = edge.End = FirstEndpoint(ledger); + } + else if (edge.Delta.IsZero) + { + continue; + } + + // A zero current sum with non-zero later endpoint changes must + // retain its continuation, even though it emits no boundary now. + this.bundled.Add(edge); + } + } + + /// Accumulates one coincident contribution's terminal change. + /// The bundle's future endpoint changes. + /// The terminal point. + /// The contribution ending there. + private static void AddEndpoint(SortedDictionary ends, Vertex point, WindingCount delta) + { + if (ends.TryGetValue(point, out WindingCount existing)) + { + delta = delta.Add(existing); + } + + if (delta.IsZero) + { + ends.Remove(point); + } + else + { + ends[point] = delta; + } + } + + /// Gets the next terminal change of a non-empty bundle ledger. + /// The non-empty endpoint ledger. + /// The first endpoint. + private static Vertex FirstEndpoint(SortedDictionary ends) + { + using SortedDictionary.Enumerator enumerator = ends.GetEnumerator(); + enumerator.MoveNext(); + return enumerator.Current.Key; + } + + /// Schedules the next intersection of newly adjacent active intervals. + /// The lower neighbor's index. + /// The upper neighbor's index. + /// The event already processed. + private void CheckNeighbors(int lower, int upper, Vertex point) + { + if (lower < 0 || upper >= this.active.Count) + { + return; + } + + WindingEdge first = this.active[lower]; + WindingEdge second = this.active[upper]; + + // Keep the original support lines across splits. Reconstructing a + // line from a rounded intersection rotates it and can create a second, + // slightly different intersection at an existing source vertex. + if (first.LineId > second.LineId) + { + (first, second) = (second, first); + } + + int count = PolygonUtilities.FindIntersectionPrecise( + first.Support, second.Support, out Vertex intersection, out Vertex last); + if (count > 0) + { + // Match the established Martinez repair: a rounded crossing on + // this x coordinate but below the completed event cannot be + // visited backwards. Advance x by one representable double. + if (intersection.X == point.X && intersection.Y < point.Y) + { + intersection = new Vertex(intersection.X.NextAfter(double.PositiveInfinity), intersection.Y); + } + + if (ComparePoints(intersection, first.Start) < 0 || ComparePoints(intersection, second.Start) < 0 || + (ComparePoints(intersection, first.End) > 0 && (first.End != first.SourceEnd || intersection.X != first.End.X)) || + (ComparePoints(intersection, second.End) > 0 && (second.End != second.SourceEnd || intersection.X != second.End.X))) + { + return; + } + + this.ScheduleSplit(first, intersection, point); + this.ScheduleSplit(second, intersection, point); + if (count == 2) + { + this.ScheduleSplit(first, last, point); + this.ScheduleSplit(second, last, point); + } + } + } + + /// Shortens a live interval to its earliest discovered future node. + /// The live interval. + /// The discovered node. + /// The completed event point. + private void ScheduleSplit(WindingEdge edge, Vertex intersection, Vertex current) + { + if (ComparePoints(intersection, current) <= 0 || intersection == edge.End) + { + return; + } + + if (ComparePoints(intersection, edge.End) > 0) + { + if (edge.End != edge.SourceEnd || intersection.X != edge.End.X || edge.Start.X == edge.End.X) + { + return; + } + + // The second established Martinez rounding case reverses the + // tiny final piece: the source endpoint precedes the rounded + // crossing on the same x coordinate. Represent that piece as a + // new forward interval with the opposite signed contribution. + WindingEdge tail = this.edges.Add(edge.SourceEnd, intersection, default(WindingCount).Subtract(edge.Delta)); + this.events.Enqueue(new WindingEvent(tail.Start, tail, true)); + edge.SourceEnd = intersection; + } + + // SourceEnd/Ends retain the source's real terminal changes. End only + // limits this open interval; its continuation is made at the new node. + edge.End = intersection; + edge.Version++; + this.events.Enqueue(new WindingEvent(intersection, edge, false)); + } + + /// Finds the first live interval not strictly below an event point. + /// The already ordered status list. + /// The event point. + /// The lower insertion bound. + private static int FindLower(List status, Vertex point) + { + int left = 0; + int right = status.Count; + while (left < right) + { + int middle = left + ((right - left) >> 1); + WindingEdge edge = status[middle]; + if (!ContainsPoint(edge, point) && PolygonUtilities.SignedArea(edge.Start, edge.End, point) > 0) + { + left = middle + 1; + } + else + { + right = middle; + } + } + + return left; + } + + /// Tests incidence on both the noded interval and its preserved source support. + /// The active interval. + /// The event point. + /// Whether the interval participates in this event. + private static bool ContainsPoint(WindingEdge edge, Vertex point) + { + // The two equivalent determinant origins can round differently. + // Preserve endpoint incidence on either representation, and source + // vertices on the support even after a rounded split shortened End. + return ComparePoints(edge.Start, point) <= 0 && ComparePoints(point, edge.End) <= 0 && + (PolygonUtilities.SignedArea(edge.Start, edge.End, point) == 0 || + Vertex.Cross(edge.End - edge.Start, point - edge.Start) == 0 || + Vertex.Cross(edge.Support.Target - edge.Support.Source, point - edge.Support.Source) == 0); + } + + /// Evaluates Boolean membership from independent signed winding counts. + /// The region's winding counts. + /// The Boolean operation. + /// The subject's fill rule. + /// The clipping operand's fill rule. + /// Whether the region belongs to the result. + private static bool Membership(WindingCount count, BooleanOperation operation, FillRule subjectRule, FillRule clipRule) + { + bool subject = Filled(count.Subject, subjectRule); + bool clip = Filled(count.Clip, clipRule); + return operation switch + { + BooleanOperation.Intersection => subject && clip, + BooleanOperation.Union => subject || clip, + BooleanOperation.Difference => subject && !clip, + _ => subject ^ clip + }; + } + + /// Interprets a winding count using a validated fill rule. + /// The signed winding count. + /// The validated fill rule. + /// Whether the region is filled. + private static bool Filled(int count, FillRule rule) + => rule switch + { + FillRule.EvenOdd => (count & 1) != 0, + FillRule.NonZero => count != 0, + FillRule.Positive => count > 0, + _ => count < 0 + }; + } + + /// Stores one live native interval, separately from completed output history. + private sealed class WindingEdge + { + /// Gets or sets the stable identity within this operation. + public int Id { get; set; } + + /// Gets or sets the canonical start point. + public Vertex Start { get; set; } + + /// Gets or sets the next discovered endpoint or intersection. + public Vertex End { get; set; } + + /// Gets or sets the next actual source contribution endpoint. + public Vertex SourceEnd { get; set; } + + /// Gets or sets the original directed support, unaffected by rounded split points. + public Segment Support { get; set; } + + /// Gets or sets the original segment identity used to construct intersections consistently. + public int LineId { get; set; } + + /// Gets or sets the live status position, used to anchor constructed intersections. + public int Position { get; set; } + + /// Gets or sets the count of live result boundaries at or below this interval. + public int ResultRank { get; set; } + + /// Gets or sets the signed contribution of the live interval. + public WindingCount Delta { get; set; } + + /// Gets or sets the cached winding immediately above the live interval. + public WindingCount Above { get; set; } + + /// Gets or sets the longer-tail endpoint ledger for a coincident bundle. + public SortedDictionary? Ends { get; set; } + + /// Gets or sets the fixed contribution and birth context when this interval contributes. + public SweepEvent? Boundary { get; set; } + + /// Gets or sets the version used to discard superseded queued endpoints. + public int Version { get; set; } + + /// Gets or sets a value indicating whether this representative remains in the active status. + public bool Active { get; set; } + } + + /// Reuses native interval objects through the existing append-only pool mechanism. + private sealed class WindingEdgePool : PooledList + { + /// Acquires an interval for a new open piece. + /// The canonical start. + /// The source endpoint. + /// The signed contribution. + /// The initialized interval. + public WindingEdge Add(Vertex start, Vertex end, WindingCount delta) + { + this.TryGrow(); + WindingEdge edge = this.Items[this.Size] ??= new WindingEdge(); + edge.Id = this.Size++; + edge.LineId = edge.Id; + edge.Start = start; + edge.End = edge.SourceEnd = end; + edge.Support = new(start, end); + edge.Delta = delta; + edge.Above = default; + edge.Ends = null; + edge.Boundary = null; + edge.Version = 0; + edge.Active = false; + return edge; + } + } + + /// Orders native endpoint records deterministically without changing coordinates. + private sealed class WindingEventComparer : IComparer + { + /// The shared stateless comparer. + public static readonly WindingEventComparer Instance = new(); + + /// + public int Compare(WindingEvent x, WindingEvent y) + { + int order = ComparePoints(x.Point, y.Point); + if (order == 0) + { + order = x.Edge.Id.CompareTo(y.Edge.Id); + } + + if (order == 0) + { + order = x.Version.CompareTo(y.Version); + } + + return order == 0 ? x.IsStart.CompareTo(y.IsStart) : order; + } + } + + /// Orders rays immediately after their shared event point. + private sealed class WindingRayComparer : IComparer + { + /// The shared stateless comparer. + public static readonly WindingRayComparer Instance = new(); + + /// + public int Compare(WindingEdge? x, WindingEdge? y) + { + double cross = Vertex.Cross(x!.SourceEnd - x.Start, y!.SourceEnd - y.Start); + return cross > 0 ? -1 : cross < 0 ? 1 : 0; + } + } + + /// Orders contribution endpoints within a coincident bundle. + private sealed class WindingPointComparer : IComparer + { + /// The shared stateless comparer. + public static readonly WindingPointComparer Instance = new(); + + /// + public int Compare(Vertex x, Vertex y) => ComparePoints(x, y); + } +} diff --git a/src/PolygonClipper/PolygonClipper.cs b/src/PolygonClipper/PolygonClipper.cs index cb1c6f9..8e1d6eb 100644 --- a/src/PolygonClipper/PolygonClipper.cs +++ b/src/PolygonClipper/PolygonClipper.cs @@ -37,7 +37,7 @@ namespace SixLabors.PolygonClipper; /// Connecting edges: Constructs the resulting polygon by connecting valid segments. /// /// -public class PolygonClipper +public partial class PolygonClipper { // Keep a small per-thread hot set of clipper instances. Depth 4 covers common // burst usage without retaining many heavyweight buffers per thread. @@ -191,6 +191,7 @@ private static void Return(PolygonClipper clipper) clipper.unorderedEventQueue.Clear(); clipper.sortedEvents.Clear(); clipper.statusLine.Reset(0); + clipper.windingSweep?.Reset(); // Avoid keeping very large event buffers alive in thread-static pools. if (clipper.GetRetainedEventCapacityScore() > MaxRetainedEventCapacityScore) @@ -211,11 +212,13 @@ private void Configure(Polygon subject, Polygon clip, BooleanOperation operation this.subject = subject; this.clipping = clip; this.operation = operation; + this.useFillRules = false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private int GetRetainedEventCapacityScore() - => this.unorderedEventQueue.Capacity + this.sortedEvents.Capacity + this.statusLine.RetainedCapacity; + => this.unorderedEventQueue.Capacity + this.sortedEvents.Capacity + this.statusLine.RetainedCapacity + + (this.windingSweep?.RetainedCapacity ?? 0); /// /// Executes the configured boolean operation for the current subject and clipping polygons. @@ -229,6 +232,13 @@ public Polygon Run() Polygon clipping = this.clipping ?? throw new InvalidOperationException("Polygon clipper clipping polygon is not configured."); BooleanOperation operation = this.operation; + if (this.useFillRules) + { + this.sortedEvents.Clear(); + WindingSweep sweep = this.windingSweep ??= new WindingSweep(); + return sweep.Run(subject, clipping, operation, this.subjectFillRule, this.clipFillRule, this.sortedEvents, this.comparer); + } + // Check for trivial cases that can be resolved without sweeping if (TryTrivialOperationForEmptyPolygons(subject, clipping, operation, out Polygon? result)) { diff --git a/src/PolygonClipper/PolygonUtilities.Intersections.cs b/src/PolygonClipper/PolygonUtilities.Intersections.cs new file mode 100644 index 0000000..a9d4854 --- /dev/null +++ b/src/PolygonClipper/PolygonUtilities.Intersections.cs @@ -0,0 +1,110 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +namespace SixLabors.PolygonClipper; + +/// Provides compensated construction of geometric intersections. +internal static partial class PolygonUtilities +{ + /// Finds segment intersections with compensated construction of a crossing point. + /// The first source segment. + /// The second source segment. + /// The first intersection. + /// The final intersection of an overlap. + /// The number of intersections. + public static int FindIntersectionPrecise(in Segment first, in Segment second, out Vertex point, out Vertex last) + { + int count = FindIntersection(first, second, out point, out last); + if (count != 1 || point == first.Source || point == first.Target || point == second.Source || point == second.Target) + { + return count; + } + + // Intersection parameters are quotients of determinants. Retain the + // multiplication and addition roundoff until the final coordinate is + // rounded, rather than rounding the parameter and then each multiply/add. + // Independent pairs at a multiway junction then construct the same node. + CompensatedDouble ax = CompensatedDouble.Difference(first.Target.X, first.Source.X); + CompensatedDouble ay = CompensatedDouble.Difference(first.Target.Y, first.Source.Y); + CompensatedDouble bx = CompensatedDouble.Difference(second.Target.X, second.Source.X); + CompensatedDouble by = CompensatedDouble.Difference(second.Target.Y, second.Source.Y); + CompensatedDouble ex = CompensatedDouble.Difference(second.Source.X, first.Source.X); + CompensatedDouble ey = CompensatedDouble.Difference(second.Source.Y, first.Source.Y); + CompensatedDouble denominator = ax.Multiply(by).Subtract(ay.Multiply(bx)); + if (denominator.Value != 0) + { + CompensatedDouble numerator = ex.Multiply(by).Subtract(ey.Multiply(bx)); + CompensatedDouble parameter = numerator.Divide(denominator); + point = new Vertex(parameter.Multiply(ax).Add(new(first.Source.X)).Value, parameter.Multiply(ay).Add(new(first.Source.Y)).Value); + Box2 bounds = new( + Vertex.Max(Vertex.Min(first.Source, first.Target), Vertex.Min(second.Source, second.Target)), + Vertex.Min(Vertex.Max(first.Source, first.Target), Vertex.Max(second.Source, second.Target))); + point = ConstrainToBoundingBox(point, bounds); + } + + return count; + } + + /// Retains arithmetic roundoff as a second double during intersection construction. + private readonly struct CompensatedDouble + { + private readonly double high; + private readonly double low; + + /// Initializes a new instance of the struct. + /// The leading value. + /// The retained roundoff. + public CompensatedDouble(double high, double low = 0) + { + this.high = high; + this.low = low; + } + + /// Gets the value rounded to one double. + public double Value => this.high + this.low; + + /// Subtracts two coordinates without discarding the subtraction roundoff. + /// The first coordinate. + /// The coordinate to subtract. + /// The compensated difference. + public static CompensatedDouble Difference(double first, double second) => new CompensatedDouble(first).Subtract(new(second)); + + /// Adds two compensated values using the error-free two-sum identity. + /// The value to add. + /// The compensated sum. + public CompensatedDouble Add(CompensatedDouble other) + { + double sum = this.high + other.high; + double virtualOther = sum - this.high; + double error = (this.high - (sum - virtualOther)) + (other.high - virtualOther) + this.low + other.low; + double high = sum + error; + return new(high, error - (high - sum)); + } + + /// Subtracts a compensated value. + /// The value to subtract. + /// The compensated difference. + public CompensatedDouble Subtract(CompensatedDouble other) => this.Add(new(-other.high, -other.low)); + + /// Multiplies values while retaining the leading product's roundoff with FMA. + /// The multiplier. + /// The compensated product. + public CompensatedDouble Multiply(CompensatedDouble other) + { + double product = this.high * other.high; + double error = Math.FusedMultiplyAdd(this.high, other.high, -product) + (this.high * other.low) + (this.low * other.high); + double high = product + error; + return new(high, error - (high - product)); + } + + /// Corrects a leading quotient using its compensated residual. + /// The non-zero divisor. + /// The compensated quotient. + public CompensatedDouble Divide(CompensatedDouble other) + { + CompensatedDouble quotient = new(this.high / other.high); + CompensatedDouble remainder = this.Subtract(other.Multiply(quotient)); + return quotient.Add(new(remainder.Value / other.high)); + } + } +} diff --git a/src/PolygonClipper/PolygonUtilities.cs b/src/PolygonClipper/PolygonUtilities.cs index 8129069..028f153 100644 --- a/src/PolygonClipper/PolygonUtilities.cs +++ b/src/PolygonClipper/PolygonUtilities.cs @@ -10,7 +10,7 @@ namespace SixLabors.PolygonClipper; /// Provides utility methods for performing geometric calculations related to polygons, such as calculating signed areas /// and finding intersections of line segments. /// -internal static class PolygonUtilities +internal static partial class PolygonUtilities { /// /// Returns the signed area of a triangle. diff --git a/src/PolygonClipper/StablePriorityQueue{T,TComparer}.cs b/src/PolygonClipper/StablePriorityQueue{T,TComparer}.cs index 5b74b93..7312f3d 100644 --- a/src/PolygonClipper/StablePriorityQueue{T,TComparer}.cs +++ b/src/PolygonClipper/StablePriorityQueue{T,TComparer}.cs @@ -71,6 +71,9 @@ public int Count /// public TComparer Comparer { get; } + /// Restores queue ordering after filling the shared backing list with unordered items. + public void Heapify() => this.Heapify(this.heap); + /// /// Adds an item to the priority queue, maintaining the heap property. /// diff --git a/src/PolygonClipper/VertexPoolList.cs b/src/PolygonClipper/VertexPoolList.cs index 61ad829..b870c64 100644 --- a/src/PolygonClipper/VertexPoolList.cs +++ b/src/PolygonClipper/VertexPoolList.cs @@ -167,6 +167,10 @@ public HorizontalJoin Add(OutputPoint ltor, OutputPoint rtol) /// internal sealed class SweepEventPoolList : PooledList { + /// Orders completed native boundary events for edge connection. + /// The edge connector's event ordering. + public void Sort(SweepEventComparer comparer) => this.Items.AsSpan(0, this.Size).Sort(comparer); + /// /// Adds a sweep event to the active range. /// diff --git a/tests/PolygonClipper.Benchmarks/Benches.cs b/tests/PolygonClipper.Benchmarks/Benches.cs index 442e090..db0873f 100644 --- a/tests/PolygonClipper.Benchmarks/Benches.cs +++ b/tests/PolygonClipper.Benchmarks/Benches.cs @@ -39,6 +39,16 @@ public void Setup() [Benchmark] public Polygon PolygonClipper() => SixLabors.PolygonClipper.PolygonClipper.Union(this.subject, this.clipping); + /// Measures explicit parity clipping on the same raw geometry as the legacy API. + /// The clipped geometry. + [Benchmark] + public Polygon PolygonClipperEvenOdd() => SixLabors.PolygonClipper.PolygonClipper.Union(this.subject, this.clipping, FillRule.EvenOdd); + + /// Measures non-zero clipping without a separate normalization operation. + /// The clipped geometry. + [Benchmark] + public Polygon PolygonClipperNonZero() => SixLabors.PolygonClipper.PolygonClipper.Union(this.subject, this.clipping, FillRule.NonZero); + [Benchmark] public PolyTreeD Clipper2Union() { diff --git a/tests/PolygonClipper.Tests/FillRuleClippingTests.cs b/tests/PolygonClipper.Tests/FillRuleClippingTests.cs new file mode 100644 index 0000000..9d9948c --- /dev/null +++ b/tests/PolygonClipper.Tests/FillRuleClippingTests.cs @@ -0,0 +1,448 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +namespace SixLabors.PolygonClipper.Tests; + +/// Checks filled geometry through the public single-sweep APIs. +public class FillRuleClippingTests +{ + /// Checks dense self-crossings through the established star input generator. + /// The number of vertices in each star. + [Theory] + [InlineData(31)] + [InlineData(101)] + public void DenseStars_ExplicitRules_MatchSourceCoverage(int vertexCount) + { + Polygon subject = GenericTestCases.BuildStarPolygon(vertexCount, 100D, 0D, 0D); + Polygon clip = GenericTestCases.BuildStarPolygon(vertexCount, 100D, 35D, 22D); + for (int rule = 0; rule < 4; rule++) + { + for (int operation = 0; operation < 4; operation++) + { + Polygon result = Execute(subject, clip, (BooleanOperation)operation, (FillRule)rule, (FillRule)rule); + AssertCoverage(subject, clip, result, (BooleanOperation)operation, (FillRule)rule, (FillRule)rule); + } + } + } + + /// Checks both small and large double coordinate scales without integer conversion. + /// The coordinate scale. + [Theory] + [InlineData(1E-90)] + [InlineData(1E90)] + public void UnaryUnion_ScaledCrossing_PreservesFilledArea(double scale) + { + Polygon input = [[new Vertex(0, 0), new Vertex(10 * scale, 10 * scale), new Vertex(10 * scale, 0), new Vertex(0, 10 * scale)]]; + + Polygon result = PolygonClipper.Union(input, FillRule.NonZero); + + Assert.Equal(50D, Area(result) / (scale * scale), 10); + } + + /// Checks that empty-operand shortcuts cannot return unresolved duplicate contours. + /// The subject fill rule. + /// The expected filled area. + [Theory] + [InlineData(FillRule.EvenOdd, 0D)] + [InlineData(FillRule.NonZero, 16D)] + [InlineData(FillRule.Positive, 16D)] + [InlineData(FillRule.Negative, 0D)] + public void EmptyClippingOperand_PreservesSelectedFillRule(FillRule rule, double expected) + { + Polygon input = [Rectangle(0, 0, 4, 4), Rectangle(0, 0, 4, 4)]; + + Assert.Equal(expected, Area(PolygonClipper.Union(input, [], rule))); + Assert.Equal(expected, Area(PolygonClipper.Difference(input, [], rule))); + Assert.Equal(expected, Area(PolygonClipper.Xor(input, [], rule))); + Assert.Empty(PolygonClipper.Intersection(input, [], rule)); + } + + /// Checks raw geographic contours at the scales used by the benchmark suite. + /// The geographic benchmark fixture. + [Theory] + [InlineData("hole_hole.geojson")] + [InlineData("states_source.geojson")] + [InlineData("asia.geojson")] + public void GeographicFixtures_MixedRules_MatchSourceCoverage(string file) + { + (Polygon subject, Polygon clip) = TestPolygonUtilities.BuildPolygon(TestData.Benchmarks.GetFeatureCollection(file)); + for (int operation = 0; operation < 4; operation++) + { + for (int rule = 0; rule < 2; rule++) + { + Polygon result = Execute(subject, clip, (BooleanOperation)operation, (FillRule)rule, FillRule.NonZero); + AssertCoverage(subject, clip, result, (BooleanOperation)operation, (FillRule)rule, FillRule.NonZero); + } + } + } + + /// Checks the established intersection defect corpus under independent fill rules. + /// The existing GeoJSON defect fixture. + [Theory] + [MemberData(nameof(GenericTestCases.GetTestCases), MemberType = typeof(GenericTestCases))] + public void ExistingDefectFixtures_ExplicitRules_MatchSourceCoverage(string testCaseFile) + { + (Polygon subject, Polygon clip) = TestPolygonUtilities.BuildPolygon(TestData.Generic.GetFeatureCollection(testCaseFile)); + for (int operation = 0; operation < 4; operation++) + { + for (int subjectRule = 0; subjectRule < 4; subjectRule++) + { + for (int clipRule = 0; clipRule < 4; clipRule++) + { + Polygon result = Execute(subject, clip, (BooleanOperation)operation, (FillRule)subjectRule, (FillRule)clipRule); + AssertCoverage(subject, clip, result, (BooleanOperation)operation, (FillRule)subjectRule, (FillRule)clipRule); + } + } + } + } + + /// Checks arbitrary directed crossings against the independent source winding oracle. + [Fact] + public void SeededSelfCrossingContours_MixedRules_MatchSourceCoverage() + { + Random random = new(6492); + for (int sample = 0; sample < 1024; sample++) + { + Polygon subject = [RandomContour(random), RandomContour(random)]; + Polygon clip = [RandomContour(random)]; + for (int subjectRule = 0; subjectRule < 4; subjectRule++) + { + for (int clipRule = 0; clipRule < 4; clipRule++) + { + for (int operation = 0; operation < 4; operation++) + { + Polygon result = Execute(subject, clip, (BooleanOperation)operation, (FillRule)subjectRule, (FillRule)clipRule); + AssertCoverage(subject, clip, result, (BooleanOperation)operation, (FillRule)subjectRule, (FillRule)clipRule); + } + } + } + } + } + + /// Constructs a deterministic closed contour with unconstrained direction and crossings. + /// The seeded generator. + /// The raw directed contour. + private static Contour RandomContour(Random random) + { + int count = random.Next(3, 8); + Contour contour = new(count); + for (int i = 0; i < count; i++) + { + contour.Add(new Vertex(random.Next(-4, 5), random.Next(-4, 5))); + } + + return contour; + } + + /// Enumerates independent operand rules and all Boolean operations. + /// The geometric case and operation combinations. + public static TheoryData Combinations() + { + TheoryData data = []; + for (int geometry = 0; geometry < 7; geometry++) + { + for (int operation = 0; operation < 4; operation++) + { + for (int subject = 0; subject < 4; subject++) + { + for (int clip = 0; clip < 4; clip++) + { + data.Add(geometry, (BooleanOperation)operation, (FillRule)subject, (FillRule)clip); + } + } + } + } + + return data; + } + + /// Distinguishes raw signed winding from nesting-based hole preparation. + /// The input fill rule. + /// The analytically expected area. + [Theory] + [InlineData(FillRule.EvenOdd, 64D)] + [InlineData(FillRule.NonZero, 100D)] + [InlineData(FillRule.Positive, 100D)] + [InlineData(FillRule.Negative, 0D)] + public void UnaryUnion_SameDirectionNestedRings_UsesSelectedRule(FillRule rule, double area) + { + Polygon input = [Rectangle(0, 0, 10, 10), Rectangle(2, 2, 8, 8)]; + + Polygon result = PolygonClipper.Union(input, rule); + + Assert.Equal(area, Area(result), 10); + Assert.Equal(2, input.Count); + Assert.Equal(4, input[0].Count); + Assert.Null(input[1].ParentIndex); + } + + /// Retains both winding signs of a zero-net-area self-crossing contour. + /// The input fill rule. + /// The analytically expected area. + [Theory] + [InlineData(FillRule.EvenOdd, 50D)] + [InlineData(FillRule.NonZero, 50D)] + [InlineData(FillRule.Positive, 25D)] + [InlineData(FillRule.Negative, 25D)] + public void UnaryUnion_Bowtie_ResolvesBothWindingSigns(FillRule rule, double area) + { + Polygon input = [[new Vertex(0, 0), new Vertex(10, 10), new Vertex(10, 0), new Vertex(0, 10)]]; + + Polygon result = PolygonClipper.Union(input, rule); + + Assert.Equal(area, Area(result), 10); + } + + /// Checks binary output against direct winding of the original, unsplit contours. + /// The directed input configuration. + /// The Boolean operation. + /// The subject rule. + /// The clipping rule. + [Theory] + [MemberData(nameof(Combinations))] + public void BinaryOperations_MixedRules_MatchOriginalWinding( + int geometry, BooleanOperation operation, FillRule subjectRule, FillRule clipRule) + { + (Polygon subject, Polygon clip) = Inputs(geometry); + Polygon result = Execute(subject, clip, operation, subjectRule, clipRule); + + AssertCoverage(subject, clip, result, operation, subjectRule, clipRule); + } + + /// Checks sign reversal, manual reuse, and the preserved legacy overload path. + [Fact] + public void ManualClipperAndPooledLegacyCalls_DoNotLeakRules() + { + Polygon subject = [Rectangle(0, 0, 10, 10)]; + subject[0].Reverse(); + PolygonClipper manual = new(subject, [], BooleanOperation.Union, FillRule.Negative, FillRule.EvenOdd); + Assert.Equal(100D, Area(manual.Run())); + Assert.Equal(100D, Area(manual.Run())); + Assert.Equal(0D, Area(PolygonClipper.Union(subject, FillRule.Positive))); + Assert.Equal(100D, Area(PolygonClipper.Union(subject, FillRule.Negative))); + + Polygon legacy = PolygonClipper.Union(subject, []); + Assert.Equal(subject[0].Count, legacy[0].Count); + Assert.False(legacy[0].IsCounterClockwise()); + Assert.NotSame(subject[0], legacy[0]); + } + + /// Checks double-coordinate behavior without integer scaling. + [Fact] + public void UnaryUnion_TranslatedUnitRings_PreservesSmallArea() + { + const double origin = 1E12; + Polygon input = [Rectangle(origin, origin, origin + 1, origin + 1)]; + + Polygon result = PolygonClipper.Union(input, FillRule.NonZero); + + Assert.Equal(1D, Area(result)); + Assert.Equal(origin, result[0].GetBoundingBox().Min.X); + } + + /// Checks output against signed source coverage away from input boundaries. + /// The original subject contours. + /// The original clipping contours. + /// The clipped geometry. + /// The Boolean operation. + /// The subject rule. + /// The clipping rule. + private static void AssertCoverage(Polygon subject, Polygon clip, Polygon result, BooleanOperation operation, FillRule subjectRule, FillRule clipRule) + { + Box2 bounds = subject.GetBoundingBox().Add(clip.GetBoundingBox()); + for (int y = 0; y < 9; y++) + { + for (int x = 0; x < 9; x++) + { + Vertex point = new( + bounds.Min.X + ((bounds.Max.X - bounds.Min.X) * (x + 0.25D) / 9D), + bounds.Min.Y + ((bounds.Max.Y - bounds.Min.Y) * (y + 0.375D) / 9D)); + if (OnBoundary(subject, point) || OnBoundary(clip, point)) + { + continue; + } + + bool first = Filled(Winding(subject, point), subjectRule); + bool second = Filled(Winding(clip, point), clipRule); + bool expected = operation switch + { + BooleanOperation.Intersection => first && second, + BooleanOperation.Union => first || second, + BooleanOperation.Difference => first && !second, + _ => first ^ second + }; + bool actual = Winding(result, point) != 0; + if (expected != actual) + { + Assert.Fail($"{operation}, {subjectRule}/{clipRule}, point {point}: expected {expected}." + + $"\nSubject: {subject.ToDebugString()}\nClip: {clip.ToDebugString()}\nResult: {result.ToDebugString()}"); + } + } + } + + for (int i = 0; i < result.Count; i++) + { + Contour contour = result[i]; + Assert.NotEqual(contour[0], contour[^1]); + Assert.Equal(contour.IsExternal, contour.IsCounterClockwise()); + for (int j = 0; j < contour.HoleCount; j++) + { + Assert.Equal(i, result[contour.GetHoleIndex(j)].ParentIndex); + } + } + } + + /// Builds raw directed input cases with crossings, vertical runs, and duplicates. + /// The requested case. + /// The subject and clipping contours. + private static (Polygon Subject, Polygon Clip) Inputs(int geometry) + { + Polygon subject = geometry switch + { + 0 => [Rectangle(0, 0, 10, 10), Rectangle(2, 2, 8, 8)], + 1 => [Rectangle(0, 0, 10, 10), Rectangle(0, 2, 8, 8)], + 2 => [[new Vertex(0, 0), new Vertex(10, 10), new Vertex(10, 0), new Vertex(0, 10)]], + 3 => [Rectangle(0, 0, 10, 10), Rectangle(0, 0, 10, 10)], + 4 => [Rectangle(0, 0, 10, 10), Rectangle(2, 2, 8, 8), Rectangle(3, 3, 7, 7)], + 5 => [Rectangle(0, 0, 4, 4), Rectangle(4, 4, 8, 8)], + _ => [Rectangle(0, 0, 10, 10), Rectangle(0, 0, 10, 10)] + }; + if (geometry is 4 or 6) + { + subject[1].Reverse(); + } + + Polygon clip = [Rectangle(0, 3, 6, 7), Rectangle(2, 1, 9, 9)]; + clip[1].Reverse(); + return (subject, clip); + } + + /// Executes the selected public binary operation. + /// The subject. + /// The clipping contours. + /// The Boolean operation. + /// The subject rule. + /// The clipping rule. + /// The resulting geometry. + private static Polygon Execute(Polygon subject, Polygon clip, BooleanOperation operation, FillRule subjectRule, FillRule clipRule) + { + try + { + return operation switch + { + BooleanOperation.Intersection => PolygonClipper.Intersection(subject, clip, subjectRule, clipRule), + BooleanOperation.Union => PolygonClipper.Union(subject, clip, subjectRule, clipRule), + BooleanOperation.Difference => PolygonClipper.Difference(subject, clip, subjectRule, clipRule), + _ => PolygonClipper.Xor(subject, clip, subjectRule, clipRule) + }; + } + catch (Exception exception) + { + Assert.Fail($"{operation}, {subjectRule}/{clipRule}: {exception}\nSubject: {subject.ToDebugString()}\nClip: {clip.ToDebugString()}"); + throw; + } + } + + /// Constructs a positively directed rectangle. + /// The left coordinate. + /// The top coordinate. + /// The right coordinate. + /// The bottom coordinate. + /// The four directed vertices. + private static Contour Rectangle(double left, double top, double right, double bottom) + => [new Vertex(left, top), new Vertex(right, top), new Vertex(right, bottom), new Vertex(left, bottom)]; + + /// Evaluates the documented winding predicates independently of the clipper. + /// The winding count. + /// The selected rule. + /// The filled membership. + private static bool Filled(int winding, FillRule rule) + => rule switch + { + FillRule.EvenOdd => (winding % 2) != 0, + FillRule.NonZero => winding != 0, + FillRule.Positive => winding > 0, + _ => winding < 0 + }; + + /// Counts signed horizontal-ray crossings on the original contours. + /// The directed contours. + /// A point away from input boundaries. + /// The signed winding count. + private static int Winding(Polygon polygon, Vertex point) + { + int winding = 0; + foreach (Contour contour in polygon) + { + for (int i = 0; i < contour.Count; i++) + { + Vertex first = contour[i]; + Vertex second = contour[(i + 1) % contour.Count]; + double side = Vertex.Cross(second - first, point - first); + if (first.Y <= point.Y && second.Y > point.Y && side > 0) + { + winding++; + } + else if (first.Y > point.Y && second.Y <= point.Y && side < 0) + { + winding--; + } + } + } + + return winding; + } + + /// Excludes points whose membership is boundary-convention dependent. + /// The input contours. + /// The sampled point. + /// Whether the point lies on a source segment. + private static bool OnBoundary(Polygon polygon, Vertex point) + { + foreach (Contour contour in polygon) + { + for (int i = 0; i < contour.Count; i++) + { + Vertex first = contour[i]; + Vertex second = contour[(i + 1) % contour.Count]; + Vertex direction = second - first; + Vertex offset = point - first; + + // Grid interpolation and intersection construction can place a + // boundary sample a few rounding units on either side. Coverage + // is asserted only where that boundary convention is immaterial. + double scale = Math.Max( + Math.Max(Math.Abs(first.X), Math.Abs(first.Y)), + Math.Max(Math.Max(Math.Abs(second.X), Math.Abs(second.Y)), Math.Max(Math.Abs(point.X), Math.Abs(point.Y)))); + double tolerance = 16 * 2.2204460492503131E-16 * scale; + double crossTolerance = tolerance * (Math.Abs(direction.X) + Math.Abs(direction.Y)); + if (Math.Abs(Vertex.Cross(direction, offset)) <= crossTolerance && + point.X >= Math.Min(first.X, second.X) - tolerance && point.X <= Math.Max(first.X, second.X) + tolerance && + point.Y >= Math.Min(first.Y, second.Y) - tolerance && point.Y <= Math.Max(first.Y, second.Y) + tolerance) + { + return true; + } + } + } + + return false; + } + + /// Measures signed filled area using a local origin for each result ring. + /// The result geometry. + /// The total signed area. + private static double Area(Polygon polygon) + { + double twiceArea = 0; + foreach (Contour contour in polygon) + { + Vertex origin = contour[0]; + for (int i = 0; i < contour.Count; i++) + { + twiceArea += Vertex.Cross(contour[i] - origin, contour[(i + 1) % contour.Count] - origin); + } + } + + return twiceArea * 0.5D; + } +} diff --git a/tests/PolygonClipper.Tests/GenericTestCases.cs b/tests/PolygonClipper.Tests/GenericTestCases.cs index 6252599..d65ea59 100644 --- a/tests/PolygonClipper.Tests/GenericTestCases.cs +++ b/tests/PolygonClipper.Tests/GenericTestCases.cs @@ -110,7 +110,13 @@ public void StarBenchmark() Polygon result = PolygonClipper.Union(subject, clipping); } - private static Polygon BuildStarPolygon(int vertexCount, double radius, double centerX, double centerY) + /// Constructs the self-crossing star used by the clipping stress cases. + /// The odd vertex count. + /// The distance from the centre to each vertex. + /// The horizontal centre. + /// The vertical centre. + /// The directed star contour. + internal static Polygon BuildStarPolygon(int vertexCount, double radius, double centerX, double centerY) { if (vertexCount < 5 || (vertexCount & 1) == 0) { diff --git a/tests/PolygonClipper.Tests/NormalizationTests.cs b/tests/PolygonClipper.Tests/NormalizationTests.cs index 7b2ec8b..a1c0b8e 100644 --- a/tests/PolygonClipper.Tests/NormalizationTests.cs +++ b/tests/PolygonClipper.Tests/NormalizationTests.cs @@ -2508,7 +2508,7 @@ private static PathsD NormalizeWithClipperD(Polygon polygon, int precision = 6) clipper.AddSubject(subject); PathsD solution = []; - clipper.Execute(ClipType.Union, FillRule.Positive, solution); + clipper.Execute(ClipType.Union, Clipper2Lib.FillRule.Positive, solution); return solution; } From 62dc90a9b5b6c34964674f5af9ea6669a51cfcaf Mon Sep 17 00:00:00 2001 From: James Jackson-South Date: Thu, 29 Oct 2026 10:43:58 +1000 Subject: [PATCH 05/24] Fix cancelled determinants and collinear event ordering Recover nonzero determinants hidden by rounded products and retain intersection precision until coordinates are constructed. Order collinear events consistently. Exact rational checks support the four fixture corrections. Check the issue 1051 boundary edges instead of assuming identical walk grouping. --- src/PolygonClipper/ExtendedPrecisionDouble.cs | 133 +++++++++++++ src/PolygonClipper/PolygonUtilities.cs | 33 +++- src/PolygonClipper/SweepEventComparer.cs | 20 +- src/PolygonClipper/Vertex.cs | 21 +- .../ExtendedPrecisionDoubleTests.cs | 182 ++++++++++++++++++ .../NormalizationTests.cs | 31 ++- .../PolygonUtilitiesTests.cs | 35 ++++ .../SweepEventComparerTests.cs | 25 +++ tests/TestData/Generic/fatal4.geojson | 2 + tests/TestData/Generic/issue103.geojson | 3 +- tests/TestData/Generic/issue76.geojson | 14 +- tests/TestData/Generic/issue99.geojson | 3 +- 12 files changed, 479 insertions(+), 23 deletions(-) create mode 100644 src/PolygonClipper/ExtendedPrecisionDouble.cs create mode 100644 tests/PolygonClipper.Tests/ExtendedPrecisionDoubleTests.cs diff --git a/src/PolygonClipper/ExtendedPrecisionDouble.cs b/src/PolygonClipper/ExtendedPrecisionDouble.cs new file mode 100644 index 0000000..1186faa --- /dev/null +++ b/src/PolygonClipper/ExtendedPrecisionDouble.cs @@ -0,0 +1,133 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +using System.Runtime.CompilerServices; + +namespace SixLabors.PolygonClipper; + +/// +/// Stores a number as the sum of two doubles to retain arithmetic rounding error. +/// +/// +/// The high component holds the rounded leading value. The low component holds the remaining low-order bits. +/// Intersection calculations carry both components until produces a double coordinate. +/// This increases precision but does not extend the double exponent range. +/// Arithmetic requires finite inputs and finite intermediate results. +/// +internal readonly struct ExtendedPrecisionDouble +{ + /// + /// The rounded leading component of the value. + /// + private readonly double high; + + /// + /// The residual added to the leading component to retain low-order bits. + /// + private readonly double low; + + /// + /// Initializes a new instance of the struct from a double. + /// + /// The exact starting value, with no residual component. + public ExtendedPrecisionDouble(double value) + : this(value, 0) + { + } + + /// + /// Initializes a new instance of the struct from a normalized pair. + /// + /// The rounded leading component. + /// The residual that cannot be represented in the leading component. + private ExtendedPrecisionDouble(double high, double low) + { + this.high = high; + this.low = low; + } + + /// + /// Gets the sum of both components rounded to one double. + /// + public double Value => this.high + this.low; + + /// + /// Adds two values and retains their rounding error. + /// + /// The first value. + /// The second value. + /// The sum with its residual component. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ExtendedPrecisionDouble operator +(in ExtendedPrecisionDouble left, in ExtendedPrecisionDouble right) + { + // Two-sum recovers the parts of the leading operands lost when their + // sum is rounded. Include both existing residuals before renormalizing. + double sum = left.high + right.high; + double virtualRight = sum - left.high; + double error = (left.high - (sum - virtualRight)) + (right.high - virtualRight) + left.low + right.low; + + // Move the representable part of the accumulated error into high. + // Keep the rest in low for subsequent operations. + double high = sum + error; + return new(high, error - (high - sum)); + } + + /// + /// Subtracts the second value from the first and retains the rounding error. + /// + /// The value to subtract from. + /// The value to subtract. + /// The difference with its residual component. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ExtendedPrecisionDouble operator -(in ExtendedPrecisionDouble left, in ExtendedPrecisionDouble right) + { + // Negate both components so addition also carries the right residual. + ExtendedPrecisionDouble negativeRight = new(-right.high, -right.low); + return left + negativeRight; + } + + /// + /// Multiplies two values and retains the rounding error. + /// + /// The first factor. + /// The second factor. + /// The product with its residual component. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ExtendedPrecisionDouble operator *(in ExtendedPrecisionDouble left, in ExtendedPrecisionDouble right) + { + double product = left.high * right.high; + + // FMA recovers the leading product's rounding error. The cross terms + // carry each low component into the result; low * low is below the retained precision. + double error = Math.FusedMultiplyAdd(left.high, right.high, -product) + (left.high * right.low) + (left.low * right.high); + double high = product + error; + return new(high, error - (high - product)); + } + + /// + /// Divides two values and corrects the leading quotient with its remainder. + /// + /// The dividend. + /// The divisor, whose leading component must be non-zero. + /// The quotient with its residual component. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ExtendedPrecisionDouble operator /(in ExtendedPrecisionDouble left, in ExtendedPrecisionDouble right) + { + // The first quotient uses the leading components. Divide the remaining + // error by the leading divisor to recover the next quotient component. + ExtendedPrecisionDouble quotient = new(left.high / right.high); + ExtendedPrecisionDouble product = right * quotient; + ExtendedPrecisionDouble remainder = left - product; + ExtendedPrecisionDouble correction = new(remainder.Value / right.high); + return quotient + correction; + } + + /// + /// Subtracts double coordinates without discarding their subtraction error. + /// + /// The coordinate to subtract from. + /// The coordinate to subtract. + /// The difference with its residual component. + public static ExtendedPrecisionDouble Difference(double first, double second) + => new ExtendedPrecisionDouble(first) - new ExtendedPrecisionDouble(second); +} diff --git a/src/PolygonClipper/PolygonUtilities.cs b/src/PolygonClipper/PolygonUtilities.cs index 028f153..cdd84e2 100644 --- a/src/PolygonClipper/PolygonUtilities.cs +++ b/src/PolygonClipper/PolygonUtilities.cs @@ -115,19 +115,34 @@ private static int FindIntersectionImpl(in Segment seg0, in Segment seg1, out Ve if (s is 0 or 1) { // On an endpoint of line segment a - pi0 = MidPoint(a1, s, va); + pi0 = s == 0 ? a1 : seg0.Target; return 1; } if (t is 0 or 1) { // On an endpoint of line segment b - pi0 = MidPoint(a2, t, vb); + pi0 = t == 0 ? a2 : seg1.Target; return 1; } - // Intersection of lines is a point on each segment - pi0 = a1 + (s * va); + // Retain subtraction, determinant, and division roundoff until the + // final coordinate is rounded. Independent segment pairs meeting at + // one junction must construct the same point for event closure. + ExtendedPrecisionDouble ax = ExtendedPrecisionDouble.Difference(seg0.Target.X, a1.X); + ExtendedPrecisionDouble ay = ExtendedPrecisionDouble.Difference(seg0.Target.Y, a1.Y); + ExtendedPrecisionDouble bx = ExtendedPrecisionDouble.Difference(seg1.Target.X, a2.X); + ExtendedPrecisionDouble by = ExtendedPrecisionDouble.Difference(seg1.Target.Y, a2.Y); + ExtendedPrecisionDouble ex = ExtendedPrecisionDouble.Difference(a2.X, a1.X); + ExtendedPrecisionDouble ey = ExtendedPrecisionDouble.Difference(a2.Y, a1.Y); + ExtendedPrecisionDouble denominator = (ax * by) - (ay * bx); + ExtendedPrecisionDouble numerator = (ex * by) - (ey * bx); + ExtendedPrecisionDouble parameter = numerator / denominator; + ExtendedPrecisionDouble intersectionX = parameter * ax; + ExtendedPrecisionDouble intersectionY = parameter * ay; + intersectionX += new ExtendedPrecisionDouble(a1.X); + intersectionY += new ExtendedPrecisionDouble(a1.Y); + pi0 = new Vertex(intersectionX.Value, intersectionY.Value); return 1; } @@ -149,18 +164,20 @@ private static int FindIntersectionImpl(in Segment seg0, in Segment seg1, out Ve { if (smin == 1) { - pi0 = MidPoint(a1, smin, va); + pi0 = seg0.Target; return 1; } if (smax == 0) { - pi0 = MidPoint(a1, smax, va); + pi0 = a1; return 1; } - pi0 = MidPoint(a1, Math.Max(smin, 0), va); - pi1 = MidPoint(a1, Math.Min(smax, 1), va); + // Overlap endpoints are existing source vertices. Reconstructing + // them through a parameter can move a shared vertex by one ULP. + pi0 = smin <= 0 ? a1 : sa <= sb ? a2 : seg1.Target; + pi1 = smax >= 1 ? seg0.Target : sa >= sb ? a2 : seg1.Target; return 2; } diff --git a/src/PolygonClipper/SweepEventComparer.cs b/src/PolygonClipper/SweepEventComparer.cs index 0ca37af..bd1bb8a 100644 --- a/src/PolygonClipper/SweepEventComparer.cs +++ b/src/PolygonClipper/SweepEventComparer.cs @@ -59,7 +59,25 @@ public int Compare(SweepEvent? x, SweepEvent? y) } // Compare by polygon type: subject polygons have higher priority - return x.PolygonType != PolygonType.Subject && y.PolygonType == PolygonType.Subject ? 1 : -1; + int order = ((int)x.PolygonType).CompareTo((int)y.PolygonType); + if (order == 0) + { + // Collinear rays can have different lengths. Order their other + // endpoints consistently rather than declaring each event smaller. + order = x.OtherEvent.Point.X.CompareTo(y.OtherEvent.Point.X); + if (order == 0) + { + order = x.OtherEvent.Point.Y.CompareTo(y.OtherEvent.Point.Y); + } + + // At either endpoint, the shorter collinear segment comes first. + if (!x.Left) + { + order = -order; + } + } + + return order; } /// diff --git a/src/PolygonClipper/Vertex.cs b/src/PolygonClipper/Vertex.cs index 4bb4255..9c4ccd3 100644 --- a/src/PolygonClipper/Vertex.cs +++ b/src/PolygonClipper/Vertex.cs @@ -161,7 +161,26 @@ public static double Dot(in Vertex a, in Vertex b) /// The cross product. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static double Cross(in Vertex a, in Vertex b) - => (a.X * b.Y) - (a.Y * b.X); + { + double first = a.X * b.Y; + double second = a.Y * b.X; + double cross = first - second; + + // Unequal rounded products preserve their order. Equal products can hide + // a non-zero determinant, so recover their residuals only in that case. + // A zero product cannot hide cancellation between two rounded products. + if (cross != 0 || first == 0 || second == 0) + { + return cross; + } + + // FMA retains each product's rounding error. Subtract the rounded second + // product inside the first FMA, then restore the part lost from that + // second product. Distinct near-parallel vectors must not become collinear. + double secondError = Math.FusedMultiplyAdd(-a.Y, b.X, second); + double determinant = Math.FusedMultiplyAdd(a.X, b.Y, -second); + return determinant + secondError; + } /// Computes the Euclidean distance between the two given vertices. /// The first vertex. diff --git a/tests/PolygonClipper.Tests/ExtendedPrecisionDoubleTests.cs b/tests/PolygonClipper.Tests/ExtendedPrecisionDoubleTests.cs new file mode 100644 index 0000000..c262ef1 --- /dev/null +++ b/tests/PolygonClipper.Tests/ExtendedPrecisionDoubleTests.cs @@ -0,0 +1,182 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +namespace SixLabors.PolygonClipper.Tests; + +/// +/// Tests arithmetic and retained low-order bits using exact binary identities. +/// +public class ExtendedPrecisionDoubleTests +{ + /// + /// Checks addition for exactly representable operands and results. + /// + /// The first value. + /// The second value. + /// The exact sum. + [Theory] + [InlineData(6D, 3D, 9D)] + [InlineData(-6D, 3D, -3D)] + [InlineData(6D, -3D, 3D)] + [InlineData(0D, 3D, 3D)] + public void Addition_ReturnsExactSum(double left, double right, double expected) + { + ExtendedPrecisionDouble result = new ExtendedPrecisionDouble(left) + new ExtendedPrecisionDouble(right); + + Assert.Equal(expected, result.Value); + } + + /// + /// Checks subtraction for exactly representable operands and results. + /// + /// The value to subtract from. + /// The value to subtract. + /// The exact difference. + [Theory] + [InlineData(6D, 3D, 3D)] + [InlineData(-6D, 3D, -9D)] + [InlineData(6D, -3D, 9D)] + [InlineData(0D, 3D, -3D)] + public void Subtraction_ReturnsExactDifference(double left, double right, double expected) + { + ExtendedPrecisionDouble result = new ExtendedPrecisionDouble(left) - new ExtendedPrecisionDouble(right); + + Assert.Equal(expected, result.Value); + } + + /// + /// Checks multiplication for exactly representable operands and results. + /// + /// The first factor. + /// The second factor. + /// The exact product. + [Theory] + [InlineData(6D, 3D, 18D)] + [InlineData(-6D, 3D, -18D)] + [InlineData(6D, -3D, -18D)] + [InlineData(0D, 3D, 0D)] + public void Multiplication_ReturnsExactProduct(double left, double right, double expected) + { + ExtendedPrecisionDouble result = new ExtendedPrecisionDouble(left) * new ExtendedPrecisionDouble(right); + + Assert.Equal(expected, result.Value); + } + + /// + /// Checks division for exactly representable operands and quotients. + /// + /// The dividend. + /// The divisor. + /// The exact quotient. + [Theory] + [InlineData(6D, 3D, 2D)] + [InlineData(-6D, 3D, -2D)] + [InlineData(6D, -3D, -2D)] + [InlineData(0D, 3D, 0D)] + public void Division_ReturnsExactQuotient(double left, double right, double expected) + { + ExtendedPrecisionDouble result = new ExtendedPrecisionDouble(left) / new ExtendedPrecisionDouble(right); + + Assert.Equal(expected, result.Value); + } + + /// + /// Checks that addition retains a term smaller than the leading value's spacing. + /// + [Fact] + public void Addition_RetainsLowOrderTermAfterCancellation() + { + ExtendedPrecisionDouble large = new(Math.ScaleB(1D, 53)); + ExtendedPrecisionDouble one = new(1D); + ExtendedPrecisionDouble sum = large + one; + + // A double rounds 2^53 + 1 to 2^53, but the retained term must survive cancellation. + Assert.Equal(Math.ScaleB(1D, 53), sum.Value); + Assert.Equal(1D, (sum - large).Value); + } + + /// + /// Checks subtraction when the leading components cancel and both residuals remain. + /// + [Fact] + public void Subtraction_RetainsBothLowComponents() + { + ExtendedPrecisionDouble large = new(Math.ScaleB(1D, 54)); + ExtendedPrecisionDouble one = new(1D); + ExtendedPrecisionDouble first = large + one; + ExtendedPrecisionDouble second = large - one; + + // (2^54 + 1) - (2^54 - 1) is exactly 2, though each operand rounds to 2^54. + Assert.Equal(2D, (first - second).Value); + } + + /// + /// Checks that coordinate subtraction retains bits lost by a double subtraction. + /// + [Fact] + public void Difference_RetainsSubtractionError() + { + double large = Math.ScaleB(1D, 54); + ExtendedPrecisionDouble difference = ExtendedPrecisionDouble.Difference(large, 1D); + + Assert.Equal(-1D, (difference - new ExtendedPrecisionDouble(large)).Value); + } + + /// + /// Checks multiplication against an exact difference-of-squares identity. + /// + [Fact] + public void Multiplication_RetainsProductRoundingError() + { + double increment = Math.ScaleB(1D, -27); + ExtendedPrecisionDouble left = new(1D + increment); + ExtendedPrecisionDouble right = new(1D - increment); + ExtendedPrecisionDouble difference = (left * right) - new ExtendedPrecisionDouble(1D); + + // (1 + 2^-27)(1 - 2^-27) - 1 is exactly -2^-54. + Assert.Equal(-Math.ScaleB(1D, -54), difference.Value); + } + + /// + /// Checks that multiplication carries both operands' low components into the product. + /// + [Fact] + public void Multiplication_RetainsBothLowComponents() + { + ExtendedPrecisionDouble value = new ExtendedPrecisionDouble(1D) + new ExtendedPrecisionDouble(Math.ScaleB(1D, -54)); + ExtendedPrecisionDouble difference = (value * value) - new ExtendedPrecisionDouble(1D); + + // (1 + 2^-54)^2 - 1 rounds to 2^-53; its 2^-108 term is below that double's rounding threshold. + Assert.Equal(Math.ScaleB(1D, -53), difference.Value); + } + + /// + /// Checks quotient correction against the exact rounding error of one third. + /// + [Fact] + public void Division_RetainsQuotientRoundingError() + { + ExtendedPrecisionDouble quotient = new ExtendedPrecisionDouble(1D) / new ExtendedPrecisionDouble(3D); + ExtendedPrecisionDouble difference = quotient - new ExtendedPrecisionDouble(1D / 3D); + ExtendedPrecisionDouble scaled = difference * new ExtendedPrecisionDouble(Math.ScaleB(1D, 54)); + + // The nearest double is 1/(3 * 2^54) below 1/3. Scaling that residual by 2^54 gives 1/3. + Assert.Equal(1D / 3D, scaled.Value); + } + + /// + /// Checks division when the dividend and divisor both contain retained low components. + /// + [Fact] + public void Division_RetainsBothLowComponents() + { + ExtendedPrecisionDouble large = new(Math.ScaleB(1D, 54)); + ExtendedPrecisionDouble one = new(1D); + ExtendedPrecisionDouble quotient = (large + one) / (large - one); + ExtendedPrecisionDouble difference = quotient - one; + ExtendedPrecisionDouble scaled = difference * new ExtendedPrecisionDouble(Math.ScaleB(1D, 53)); + + // ((2^54 + 1)/(2^54 - 1) - 1) * 2^53 rounds to 1. + Assert.Equal(1D, scaled.Value); + } +} diff --git a/tests/PolygonClipper.Tests/NormalizationTests.cs b/tests/PolygonClipper.Tests/NormalizationTests.cs index a1c0b8e..8771251 100644 --- a/tests/PolygonClipper.Tests/NormalizationTests.cs +++ b/tests/PolygonClipper.Tests/NormalizationTests.cs @@ -2317,7 +2317,36 @@ public void Issue1051_Union_Add2_MatchesMartinezUnion() new Vertex(-2, 1) ]]); - AssertContourVertexSignature(expected, actual); + // The square has area four. The added line is traversed once in each + // direction. It can remain attached to the square or form its own walk. + // Both representations must retain these seven directed boundary edges. + Segment[] boundary = + [ + new(new Vertex(0, 0), new Vertex(2, 0)), + new(new Vertex(2, 0), new Vertex(2, 2)), + new(new Vertex(2, 2), new Vertex(0, 2)), + new(new Vertex(0, 2), new Vertex(0, 1)), + new(new Vertex(0, 1), new Vertex(0, 0)), + new(new Vertex(0, 1), new Vertex(-2, 1)), + new(new Vertex(-2, 1), new Vertex(0, 1)) + ]; + foreach (Polygon polygon in new[] { actual, expected }) + { + List edges = []; + foreach (Contour contour in polygon) + { + for (int i = 0; i < GetImplicitVertexCount(contour); i++) + { + edges.Add(contour.GetSegment(i)); + } + } + + Assert.Equal(boundary.Length, edges.Count); + foreach (Segment edge in boundary) + { + Assert.Contains(edge, edges); + } + } } private static Contour CreateIssue1051Main() diff --git a/tests/PolygonClipper.Tests/PolygonUtilitiesTests.cs b/tests/PolygonClipper.Tests/PolygonUtilitiesTests.cs index 60d5072..7f5694d 100644 --- a/tests/PolygonClipper.Tests/PolygonUtilitiesTests.cs +++ b/tests/PolygonClipper.Tests/PolygonUtilitiesTests.cs @@ -5,6 +5,41 @@ namespace SixLabors.PolygonClipper.Tests; public class PolygonUtilitiesTests { + /// + /// Checks a determinant whose rounded products are equal but whose exact difference is one. + /// + [Fact] + public void Cross_NearlyParallelIntegerVectors_PreservesUnitDeterminant() + { + const double n = 134217728D; + Vertex first = new(n, n + 1); + Vertex second = new(n - 1, n); + + // n*n - (n+1)*(n-1) is exactly one. Reversing the operands changes its sign. + Assert.Equal(1D, Vertex.Cross(first, second)); + Assert.Equal(-1D, Vertex.Cross(second, first)); + Assert.Equal(0D, Vertex.Cross(first, first)); + } + + /// + /// Checks two nearly parallel segments that both pass through the origin. + /// + [Fact] + public void FindIntersection_CancelledProducts_ReturnsOrigin() + { + const double n = 134217728D; + Segment first = new(new Vertex(-n, -n - 1), new Vertex(n, n + 1)); + Segment second = new(new Vertex(1 - n, -n), new Vertex(n - 1, n)); + + int count = PolygonUtilities.FindIntersection(first, second, out Vertex intersection, out _); + + Assert.Equal(1, count); + Assert.Equal(new Vertex(0, 0), intersection); + count = PolygonUtilities.FindIntersection(first.Source, first.Target, second.Source, second.Target, out intersection, out _); + Assert.Equal(1, count); + Assert.Equal(new Vertex(0, 0), intersection); + } + [Fact] public void FindIntersection_TinyCrossingSegments_ReturnsUniqueCrossing() { diff --git a/tests/PolygonClipper.Tests/SweepEventComparerTests.cs b/tests/PolygonClipper.Tests/SweepEventComparerTests.cs index ba816aa..885d31b 100644 --- a/tests/PolygonClipper.Tests/SweepEventComparerTests.cs +++ b/tests/PolygonClipper.Tests/SweepEventComparerTests.cs @@ -5,6 +5,31 @@ namespace SixLabors.PolygonClipper.Tests; public class SweepEventComparerTests { + /// + /// Checks consistent order for collinear segments and equality for identical geometry. + /// + /// Whether both events start their segments. + /// Whether both events belong to the subject. + [Theory] + [InlineData(true, true)] + [InlineData(false, true)] + [InlineData(true, false)] + [InlineData(false, false)] + public void DistinctCollinearEvents_CompareConsistently(bool left, bool subject) + { + PolygonType polygonType = subject ? PolygonType.Subject : PolygonType.Clipping; + double direction = left ? 1 : -1; + SweepEvent first = new(new Vertex(0, 0), left, new SweepEvent(new Vertex(2 * direction, 2 * direction), !left), polygonType); + SweepEvent second = new(new Vertex(0, 0), left, new SweepEvent(new Vertex(4 * direction, 4 * direction), !left), polygonType); + SweepEvent identical = new(first.Point, left, first.OtherEvent, polygonType); + SweepEventComparer events = new(); + + Assert.Equal(-1, Math.Sign(events.Compare(first, second))); + Assert.Equal(1, Math.Sign(events.Compare(second, first))); + Assert.Equal(0, events.Compare(first, identical)); + Assert.Equal(0, events.Compare(identical, first)); + } + [Fact] public void SameEvent_CompareEqual() { diff --git a/tests/TestData/Generic/fatal4.geojson b/tests/TestData/Generic/fatal4.geojson index 18aae54..9e41df2 100644 --- a/tests/TestData/Generic/fatal4.geojson +++ b/tests/TestData/Generic/fatal4.geojson @@ -50,6 +50,7 @@ [-0.753125, 20.2234375], [-0.565625, 11.0828125], [3.846028904999335, 7.51285572161238], + [3.8460289049993355, 7.51285572161238], [6.559375, 5.3171875], [3.60625, 4.2390625], [4.121875, 1.0515625], @@ -79,6 +80,7 @@ [ [ [3.846028904999335, 7.51285572161238], + [3.8460289049993355, 7.51285572161238], [13.846028904999335, 7.51285572161238], [13.846028904999335, 11.512855721612379], [3.846028904999335, 11.512855721612379], diff --git a/tests/TestData/Generic/issue103.geojson b/tests/TestData/Generic/issue103.geojson index 8aa049a..109b69c 100644 --- a/tests/TestData/Generic/issue103.geojson +++ b/tests/TestData/Generic/issue103.geojson @@ -138,11 +138,10 @@ [257.9987920828058, 305.09120506683007], [248.5849016468879, 306.58250278991926], [244.5557189962528, 185.9229643180382], - [222.9869248986131, 178.3491004724274], [120.9957537807505, 142.53498680412483], [18.94383187314372, 116.08488152321168], [18.90341962399799, 111.35909458586124], - [37.232408208905824, 116.42585099314746], + [37.23240820890581, 116.42585099314746], [18.89787710655719, 110.71095554199546], [18.870187035423584, 107.47289333997468] ] diff --git a/tests/TestData/Generic/issue76.geojson b/tests/TestData/Generic/issue76.geojson index e937ad8..3472eb3 100644 --- a/tests/TestData/Generic/issue76.geojson +++ b/tests/TestData/Generic/issue76.geojson @@ -36,10 +36,9 @@ [ [ [-19.3046867422006, -107.63400219275148], - [-19.304686742200598, -126.63400219275148], - [10.695313257799395, -126.63400219275148], - [10.695313257799397, -126.63400219275148], - [10.695313257799395, -107.63400219275148], + [-19.3046867422006, -126.63400219275148], + [10.695313257799398, -126.63400219275148], + [10.695313257799398, -107.63400219275148], [-19.3046867422006, -107.63400219275148] ] ] @@ -96,12 +95,11 @@ ], [ [ - [-19.304686742200598, -126.63400219275148], + [-19.3046867422006, -126.63400219275148], [-19.304686742200587, -357.48241878255635], [10.695313257799413, -357.48241878255635], - [10.695313257799397, -126.63400219275148], - [10.695313257799395, -126.63400219275148], - [-19.304686742200598, -126.63400219275148] + [10.695313257799398, -126.63400219275148], + [-19.3046867422006, -126.63400219275148] ] ] ], diff --git a/tests/TestData/Generic/issue99.geojson b/tests/TestData/Generic/issue99.geojson index 630b772..0c625ec 100644 --- a/tests/TestData/Generic/issue99.geojson +++ b/tests/TestData/Generic/issue99.geojson @@ -38,9 +38,8 @@ [ [ [-98, -530], - [1.2500125250252, -530], + [1.2500125250251999, -530], [1.2500125250250003, 530], - [1.250012525025, 530], [-98, 530], [-98, -530] ] From 9b79427e08809abfc8c30c582aefb21eec84ce45 Mon Sep 17 00:00:00 2001 From: James Jackson-South Date: Thu, 29 Oct 2026 11:02:25 +1000 Subject: [PATCH 06/24] Complete the V2 Martinez fill-rule implementation Use one Martinez path for explicit fill rules and unary cleanup. Stage complete point events before publishing boundary history. Preserve distinct rounded crossings and use reliable orientation predicates. Reuse endpoint queues and restore safe sweep bounds. Keep explicit contour closure and test geometry against independent expectations. --- README.md | 109 +- src/PolygonClipper/ActiveEdge.cs | 194 -- src/PolygonClipper/ActiveEdgeList.cs | 348 --- src/PolygonClipper/Contour.cs | 55 +- ...FloatExtensions.cs => DoubleExtensions.cs} | 4 +- src/PolygonClipper/FillRule.cs | 22 +- src/PolygonClipper/IntersectNode.cs | 41 - src/PolygonClipper/JoinWith.cs | 25 - src/PolygonClipper/LocalMinima.cs | 39 - src/PolygonClipper/OutputRecord.cs | 161 - src/PolygonClipper/Polygon.cs | 5 +- .../PolygonClipper.FillRules.cs | 147 - src/PolygonClipper/PolygonClipper.Winding.cs | 802 ----- src/PolygonClipper/PolygonClipper.cs | 1693 ++++++----- src/PolygonClipper/PolygonStroker.cs | 200 +- .../PolygonUtilities.Intersections.cs | 110 - src/PolygonClipper/PolygonUtilities.cs | 270 +- src/PolygonClipper/ScanlineSchedule.cs | 157 - src/PolygonClipper/SegmentComparer.cs | 12 + src/PolygonClipper/SelfIntersectionRemover.cs | 1332 --------- .../SelfIntersectionSweepLine.cs | 2611 ----------------- .../StablePriorityQueue{T,TComparer}.cs | 4 +- src/PolygonClipper/StatusLine.cs | 40 + src/PolygonClipper/StrokeOptions.cs | 4 +- src/PolygonClipper/SweepEvent.cs | 190 +- src/PolygonClipper/SweepEventComparer.cs | 48 +- ...ertexPoolList.cs => SweepEventPoolList.cs} | 176 +- src/PolygonClipper/SweepVertex.cs | 53 - src/PolygonClipper/Vertex.cs | 12 +- src/PolygonClipper/VertexFlags.cs | 31 - tests/PolygonClipper.Benchmarks/Benches.cs | 11 +- .../NormalizationBenches.cs | 2 +- .../StarBooleanBenches.cs | 8 +- tests/PolygonClipper.Tests/ContourTests.cs | 58 + ...sionsTests.cs => DoubleExtensionsTests.cs} | 2 +- .../FillRuleClippingTests.cs | 450 ++- .../PolygonClipper.Tests/GenericTestCases.cs | 66 +- .../HorizontalJoinPoolListTests.cs | 104 - .../HorizontalJoinTests.cs | 48 - .../IntersectNodeComparerTests.cs | 60 - .../PolygonClipper.Tests/LocalMinimaTests.cs | 80 - .../NormalizationTests.cs | 208 +- .../PolygonClipperContourClosureTests.cs | 53 +- .../PolygonStrokerTests.cs | 312 +- tests/PolygonClipper.Tests/PolygonTests.cs | 2 +- .../PolygonUtilitiesTests.cs | 31 + .../TestPolygonUtilities.cs | 22 + .../TestPolygonUtilitiesTests.cs | 6 +- .../daef_polygonwithholes_holed.geojson | 7 - tests/TestData/Generic/fatal3.geojson | 5 +- tests/TestData/Generic/fatal4.geojson | 1 + tests/TestData/Generic/issue76.geojson | 5 +- tests/TestData/Generic/rust_issue12.geojson | 2 - .../Generic/vertical_ulp_slopes1.geojson | 3 - .../Generic/vertical_ulp_slopes2.geojson | 3 - 55 files changed, 2592 insertions(+), 7852 deletions(-) delete mode 100644 src/PolygonClipper/ActiveEdge.cs delete mode 100644 src/PolygonClipper/ActiveEdgeList.cs rename src/PolygonClipper/{FloatExtensions.cs => DoubleExtensions.cs} (95%) delete mode 100644 src/PolygonClipper/IntersectNode.cs delete mode 100644 src/PolygonClipper/JoinWith.cs delete mode 100644 src/PolygonClipper/LocalMinima.cs delete mode 100644 src/PolygonClipper/OutputRecord.cs delete mode 100644 src/PolygonClipper/PolygonClipper.FillRules.cs delete mode 100644 src/PolygonClipper/PolygonClipper.Winding.cs delete mode 100644 src/PolygonClipper/PolygonUtilities.Intersections.cs delete mode 100644 src/PolygonClipper/ScanlineSchedule.cs delete mode 100644 src/PolygonClipper/SelfIntersectionRemover.cs delete mode 100644 src/PolygonClipper/SelfIntersectionSweepLine.cs rename src/PolygonClipper/{VertexPoolList.cs => SweepEventPoolList.cs} (55%) delete mode 100644 src/PolygonClipper/SweepVertex.cs delete mode 100644 src/PolygonClipper/VertexFlags.cs rename tests/PolygonClipper.Tests/{FloatExtensionsTests.cs => DoubleExtensionsTests.cs} (97%) delete mode 100644 tests/PolygonClipper.Tests/HorizontalJoinPoolListTests.cs delete mode 100644 tests/PolygonClipper.Tests/HorizontalJoinTests.cs delete mode 100644 tests/PolygonClipper.Tests/IntersectNodeComparerTests.cs delete mode 100644 tests/PolygonClipper.Tests/LocalMinimaTests.cs diff --git a/README.md b/README.md index 3b152d8..fa99495 100644 --- a/README.md +++ b/README.md @@ -13,69 +13,79 @@ SixLabors.PolygonClipper -SixLabors.PolygonClipper provides high-performance polygon clipping and stroking in C#. -Boolean operations (union, intersection, difference, xor) are implemented with a Martínez-Rueda sweep-line pipeline for complex polygons with holes and multiple contours. -Contour normalization is handled by a dedicated Vatti/Clipper2-inspired pipeline (`PolygonClipper.Normalize`) that resolves self-intersections/overlaps into positive-winding output. -`PolygonStroker` can optionally run that normalization pass on emitted stroke geometry. +SixLabors.PolygonClipper performs polygon clipping and stroking in C#. +It uses the Martinez-Rueda algorithm with double coordinates. It supports holes, +self-intersections, overlapping edges, and multiple contours. -## Features +## Clipping -- Works with non-convex polygons, including holes and multiple disjoint regions -- Handles edge cases like overlapping edges and vertical segments -- Preserves topology: output polygons include hole/contour hierarchy -- Deterministic sweep line processing -- Includes `PolygonClipper.Normalize` (Clipper2-inspired) for positive-winding contour normalization -- Includes `PolygonStroker` for configurable geometric stroking (joins, caps, miter limits) -- Uses double precision geometry without coordinate quantization +The Boolean operations are `Intersection`, `Union`, `Difference`, and `Xor`. +Each accepts `EvenOdd`, `NonZero`, `Positive`, or `Negative` filling. -## Usage +```csharp +using SixLabors.PolygonClipper; + +Polygon subject = +[ + [new Vertex(0, 0), new Vertex(10, 0), new Vertex(10, 10), new Vertex(0, 10)] +]; +Polygon clip = +[ + [new Vertex(5, 5), new Vertex(15, 5), new Vertex(15, 15), new Vertex(5, 15)] +]; + +// Intersect both polygons using NonZero filling. +Polygon result = PolygonClipper.Intersection(subject, clip, FillRule.NonZero); +``` -The API centers around `Polygon` and `Contour` types. Construct input polygons using contours, then apply Boolean operations via `PolygonClipper`: +The subject and clip can use different fill rules: ```csharp -Polygon result = PolygonClipper.Union(subject, clipping); +// Use EvenOdd for the subject and NonZero for the clip. +Polygon result = PolygonClipper.Intersection(subject, clip, FillRule.EvenOdd, FillRule.NonZero); ``` -Boolean operations can process self-intersecting inputs directly. -Use normalization when you want canonical positive-winding contours (for example, before export or rendering pipelines that rely on winding semantics): +To resolve self-intersections and overlaps in one polygon, use unary union: ```csharp -Polygon clean = PolygonClipper.Normalize(input); +// Keep every region whose winding count is non-zero. +Polygon result = PolygonClipper.Union(subject, FillRule.NonZero); ``` -`Normalize` uses a fixed positive-winding normalization path. - -### Explicit fill rules +These operations apply the fill rules during the clipping sweep. They do not require +an input normalization pass. Coordinates must be finite doubles. -The V2 overloads accept `EvenOdd`, `NonZero`, `Positive`, and `Negative` fill rules. -They interpret the original directed contours in one Martínez clipping sweep. They do not run `Normalize` first. -Counterclockwise contours contribute positive winding and clockwise contours contribute negative winding. -Input parent and hole metadata do not override the selected rule. +Fill rules interpret the input contours. Every result uses positive orientation: +counterclockwise exterior contours and islands, with clockwise holes, in Cartesian coordinates. +Use `NonZero`, `EvenOdd`, or `Positive` filling to consume the resolved area. +`Negative` selects negatively wound input; it does not request negatively oriented output. -```csharp -// Interpret both operands using their signed winding counts. -Polygon result = PolygonClipper.Union(subject, clipping, FillRule.NonZero); +## Normalization -// Select an independent rule for each operand. -Polygon intersection = PolygonClipper.Intersection(subject, clipping, FillRule.EvenOdd, FillRule.NonZero); +`Normalize(polygon, fillRule)` is unary union. It resolves self-intersections and overlaps, +removes zero-area retraces, and returns the full contour hierarchy. +It reads the original contour directions without changing the input or applying a preparation pass. +Small features are not discarded using fixed distance or area thresholds. -// Resolve one raw operand under an explicit rule without a separate normalization pass. -Polygon clean = PolygonClipper.Union(input, FillRule.NonZero); +```csharp +// Clean the NonZero-filled area and retain parent and hole information. +Polygon result = PolygonClipper.Normalize(subject, FillRule.NonZero); ``` -Explicit-rule results have counterclockwise exterior contours, clockwise holes, and no duplicated closing vertex. -Coordinates must be finite doubles. The existing overloads and `Normalize` retain their existing behaviour. -Polygon clipping is pure geometry and remains entirely separate from rasterization and rasterizer clipping. - -### Stroking +Clipping accepts raw contours and their fill rules directly. It does not require `Normalize` first. +The positive output orientation follows [Clipper2's output convention](https://www.angusj.com/clipper2/Docs/Overview.htm). -Use `PolygonStroker` to generate filled stroke polygons from input contours: +## Stroking -```csharp -Polygon stroked = PolygonStroker.Stroke(input, width: 12); -``` +`PolygonStroker` creates stroke polygons with configurable joins, caps, and width. +Each source contour has an `IsClosed` property, which defaults to `true`. +Set it to `false` for an open source path. Endpoint coordinates and stroke width do not select closure. +One polygon can contain both open and closed stroke inputs. -Configure join/cap behavior through `StrokeOptions`: +Boolean operations use the filled area of each contour and implicitly close open inputs. +Both Boolean and stroke output contain closed contours without a repeated closing vertex. +When `NormalizeOutput` is enabled, stroke cleanup uses unary union with `NonZero` filling. +This preserves the raw outlines' filled area for either sign of stroke width. ```csharp StrokeOptions options = new() @@ -86,9 +96,17 @@ StrokeOptions options = new() ArcDetailScale = 1 }; -Polygon stroked = PolygonStroker.Stroke(input, width: 12, options); +// Build a stroke with width 12 and the specified joins and caps. +Polygon result = PolygonStroker.Stroke(subject, width: 12, options); ``` +## Complexity + +Martinez has a published complexity of `O((n + k) log n)` for `n` input edges and `k` intersections. + +This implementation stores active edges in a list, so inserting or removing an edge can take linear time. +It does not guarantee that bound. + ## Algorithm References This project draws on the following algorithm and implementation references: @@ -96,13 +114,10 @@ This project draws on the following algorithm and implementation references: > F. Martínez et al., "A simple algorithm for Boolean operations on polygons", *Advances in Engineering Software*, 64 (2013), pp. 11-19. > https://doi.org/10.1016/j.advengsoft.2013.04.004 -> B. R. Vatti, "A generic solution to polygon clipping", *Communications of the ACM*, 35(7), 1992, pp. 56-63. -> https://dl.acm.org/doi/pdf/10.1145/129902.129906 - > 21re, *rust-geo-booleanop* (Rust Martínez-Rueda implementation reference). > https://github.com/21re/rust-geo-booleanop -> Angus Johnson, *Clipper2* polygon clipping library (reference implementation for the normalization pipeline). +> Angus Johnson, *Clipper2* polygon clipping library. > https://github.com/AngusJohnson/Clipper2 ## License diff --git a/src/PolygonClipper/ActiveEdge.cs b/src/PolygonClipper/ActiveEdge.cs deleted file mode 100644 index 80debd0..0000000 --- a/src/PolygonClipper/ActiveEdge.cs +++ /dev/null @@ -1,194 +0,0 @@ -// Copyright (c) Six Labors. -// Licensed under the Six Labors Split License. - -using System.Runtime.CompilerServices; - -namespace SixLabors.PolygonClipper; - -/// -/// Represents an edge that is currently active in the sweep-line. -/// -/// -/// The sweep assumes a Y-axis-positive-down coordinate system. "Bottom" and "Top" -/// refer to the lower and upper scanline endpoints (larger and smaller Y respectively). -/// -internal sealed class ActiveEdge -{ -#pragma warning disable SA1401 // Hot sweep state uses fields to avoid accessor overhead. - /// - /// The lower endpoint of the edge in scanline order. - /// - public Vertex Bottom; - - /// - /// The upper endpoint of the edge in scanline order. - /// - public Vertex Top; - - /// - /// The X coordinate where the edge intersects the current scanline. - /// - public double CurrentX; - - /// - /// The delta-X per delta-Y for the edge (its scanline slope). - /// - public double Dx; - - /// - /// The winding delta contributed by this edge (+1 or -1). - /// - public int WindDelta; - - /// - /// The accumulated winding count for this edge. - /// - public int WindCount; - - /// - /// The output record this edge is contributing to, if any. - /// - public OutputRecord? OutputRecord; - - /// - /// The previous edge in the Active Edge List (AEL). - /// - public ActiveEdge? PrevInAel; - - /// - /// The next edge in the Active Edge List (AEL). - /// - public ActiveEdge? NextInAel; - - /// - /// The previous edge in the Sorted Edge List (SEL). - /// - public ActiveEdge? PrevInSel; - - /// - /// The next edge in the Sorted Edge List (SEL). - /// - public ActiveEdge? NextInSel; - - /// - /// The temporary link used when sorting intersections. - /// - public ActiveEdge? Jump; - - /// - /// The current top vertex for this edge's bound. - /// - public SweepVertex? VertexTop; - - /// - /// The local minima that spawned this edge. - /// - public LocalMinima LocalMin; - - /// - /// Indicates whether this edge is the left bound of its pair. - /// - public bool IsLeftBound; - - /// - /// The pending join state for this edge. - /// - public JoinWith JoinWith; -#pragma warning restore SA1401 - - /// - /// Gets a value indicating whether this edge currently contributes to output. - /// - public bool IsHot => this.OutputRecord != null; - - /// - /// Gets a value indicating whether the edge is horizontal within tolerance. - /// - public bool IsHorizontal => this.Top.Y == this.Bottom.Y; - - /// - /// Gets a value indicating whether a horizontal edge is heading right. - /// - public bool IsHeadingRightHorizontal => double.IsNegativeInfinity(this.Dx); - - /// - /// Gets a value indicating whether a horizontal edge is heading left. - /// - public bool IsHeadingLeftHorizontal => double.IsPositiveInfinity(this.Dx); - - /// - /// Gets a value indicating whether the current top vertex is a local maxima. - /// - public bool IsMaxima => this.VertexTop != null && this.VertexTop.IsMaxima; - - /// - /// Gets a value indicating whether this edge is the front edge of its output record. - /// - public bool IsFront => this.OutputRecord != null && this == this.OutputRecord.FrontEdge; - - /// - /// Gets the next input vertex along the bound in the winding direction. - /// - public SweepVertex NextVertex => this.WindDelta > 0 ? this.VertexTop!.Next! : this.VertexTop!.Prev!; - - /// - /// Gets the vertex two steps behind the current top, used for turn tests. - /// - public SweepVertex PrevPrevVertex => this.WindDelta > 0 ? this.VertexTop!.Prev!.Prev! : this.VertexTop!.Next!.Next!; - - /// - /// Finds the previous hot edge in the AEL, if any. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public ActiveEdge? GetPrevHotEdge() - { - ActiveEdge? prev = this.PrevInAel; - while (prev != null && !prev.IsHot) - { - prev = prev.PrevInAel; - } - - return prev; - } - - /// - /// Calculates the X coordinate where this edge intersects the scanline at . - /// - // This method sits on the hottest path in large self-intersection workloads. - // AggressiveOptimization consistently improves codegen here versus tiered defaults. - [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] - public static double TopX(ActiveEdge edge, double currentY) - { - if (currentY == edge.Top.Y || edge.Top.X == edge.Bottom.X) - { - return edge.Top.X; - } - - if (currentY == edge.Bottom.Y) - { - return edge.Bottom.X; - } - - return edge.Bottom.X + (edge.Dx * (currentY - edge.Bottom.Y)); - } - - /// - /// Recomputes from the current endpoints. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void UpdateDx() => this.Dx = GetDx(this.Bottom, this.Top); - - /// - /// Computes delta-X per delta-Y, returning infinities for horizontal edges. - /// - private static double GetDx(Vertex pt1, Vertex pt2) - { - double dy = pt2.Y - pt1.Y; - if (dy != 0) - { - return (pt2.X - pt1.X) / dy; - } - - return pt2.X > pt1.X ? double.NegativeInfinity : double.PositiveInfinity; - } -} diff --git a/src/PolygonClipper/ActiveEdgeList.cs b/src/PolygonClipper/ActiveEdgeList.cs deleted file mode 100644 index 164aacf..0000000 --- a/src/PolygonClipper/ActiveEdgeList.cs +++ /dev/null @@ -1,348 +0,0 @@ -// Copyright (c) Six Labors. -// Licensed under the Six Labors Split License. - -using System.Runtime.CompilerServices; - -namespace SixLabors.PolygonClipper; - -/// -/// Maintains the active edge list (AEL) plus a horizontal edge stack for the sweep. -/// -/// -/// The AEL is ordered left-to-right at the current scanline. As edges are inserted -/// and removed, this list preserves adjacency for intersection processing. -/// The horizontal stack is a lightweight LIFO queue used to process horizontal -/// bounds separately from the main sweep order. -/// -internal sealed class ActiveEdgeList -{ - private readonly Stack pool; - private ActiveEdge? horizontalHead; - - /// - /// Initializes a new instance of the class. - /// - public ActiveEdgeList() => this.pool = new Stack(); - - /// - /// Gets the head of the active edge list. - /// - public ActiveEdge? Head { get; private set; } - - /// - /// Gets the number of retained pooled edge objects. - /// - public int RetainedPoolCount => this.pool.Count; - - /// - /// Clears all active edges and returns them to the pool. - /// - public void ClearActiveEdges() - { - while (this.Head != null) - { - this.Remove(this.Head); - } - - this.horizontalHead = null; - } - - /// - /// Resets sweep pointers without clearing the pool. - /// - public void Reset() - { - this.Head = null; - this.horizontalHead = null; - } - - /// - /// Acquires a reusable active edge, allocating if the pool is empty. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public ActiveEdge Acquire() - => this.pool.Count == 0 ? new ActiveEdge() : this.pool.Pop(); - - /// - /// Inserts an edge into the active list, maintaining left-to-right order. - /// - /// The edge to insert. - public void InsertLeft(ActiveEdge edge) - { - if (this.Head == null) - { - edge.PrevInAel = null; - edge.NextInAel = null; - this.Head = edge; - return; - } - - if (!IsValidActiveEdgeOrder(this.Head, edge)) - { - edge.PrevInAel = null; - edge.NextInAel = this.Head; - this.Head.PrevInAel = edge; - this.Head = edge; - return; - } - - ActiveEdge edge2 = this.Head; - while (edge2.NextInAel != null && IsValidActiveEdgeOrder(edge2.NextInAel, edge)) - { - edge2 = edge2.NextInAel; - } - - // Keep joined edges adjacent in the active list. - if (edge2.JoinWith == JoinWith.Right) - { - edge2 = edge2.NextInAel!; - } - - edge.NextInAel = edge2.NextInAel; - if (edge2.NextInAel != null) - { - edge2.NextInAel.PrevInAel = edge; - } - - edge.PrevInAel = edge2; - edge2.NextInAel = edge; - } - - /// - /// Inserts a right bound edge immediately after another edge in the active list. - /// - /// The anchor edge. - /// The edge to insert. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void InsertRight(ActiveEdge edge, ActiveEdge edge2) - { - edge2.NextInAel = edge.NextInAel; - if (edge.NextInAel != null) - { - edge.NextInAel.PrevInAel = edge2; - } - - edge2.PrevInAel = edge; - edge.NextInAel = edge2; - } - - /// - /// Removes an edge from the active list and returns it to the pool. - /// - /// The edge to remove. - public void Remove(ActiveEdge edge) - { - ActiveEdge? prev = edge.PrevInAel; - ActiveEdge? next = edge.NextInAel; - - if (prev == null && next == null && edge != this.Head) - { - return; - } - - if (prev != null) - { - prev.NextInAel = next; - } - else - { - this.Head = next; - } - - if (next != null) - { - next.PrevInAel = prev; - } - - this.Recycle(edge); - } - - /// - /// Swaps the positions of two adjacent edges in the active list. - /// - /// The left edge. - /// The right edge. - public void SwapPositions(ActiveEdge left, ActiveEdge right) - { - // Precondition: left must be immediately to the left of right. - ActiveEdge? next = right.NextInAel; - if (next != null) - { - next.PrevInAel = left; - } - - ActiveEdge? prev = left.PrevInAel; - if (prev != null) - { - prev.NextInAel = right; - } - - right.PrevInAel = prev; - right.NextInAel = left; - left.PrevInAel = right; - left.NextInAel = next; - if (right.PrevInAel == null) - { - this.Head = right; - } - } - - /// - /// Clears the horizontal edge stack. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void ClearHorizontalQueue() => this.horizontalHead = null; - - /// - /// Pushes a horizontal edge onto the processing stack. - /// - /// The horizontal edge to push. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void PushHorizontal(ActiveEdge edge) - { - edge.NextInSel = this.horizontalHead; - this.horizontalHead = edge; - } - - /// - /// Pops the next horizontal edge to process. - /// - /// The next horizontal edge, or . - /// when a horizontal edge was available. - public bool TryPopHorizontal(out ActiveEdge? edge) - { - while (true) - { - edge = this.horizontalHead; - if (edge == null) - { - return false; - } - - ActiveEdge? next = edge.NextInSel; - this.horizontalHead = ReferenceEquals(next, edge) ? null : next; - if (edge.VertexTop != null) - { - return true; - } - } - } - - /// - /// Copies the active list into a sorted list and updates current X values. - /// - /// The scanline top Y coordinate. - /// The head of the sorted list. - [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] - public ActiveEdge? CopyToSorted(double topY) - { - ActiveEdge? edge = this.Head; - ActiveEdge? sortedHead = edge; - while (edge != null) - { - edge.PrevInSel = edge.PrevInAel; - edge.NextInSel = edge.NextInAel; - edge.Jump = edge.NextInSel; - - // Joined edges can be split later during intersection processing. - edge.CurrentX = ActiveEdge.TopX(edge, topY); - - // Defer any Y updates; intersection tests use original bounds. - edge = edge.NextInAel; - } - - return sortedHead; - } - - /// - /// Determines whether the newcomer should be inserted after the resident in the active list. - /// - /// The current resident edge. - /// The incoming edge to compare. - /// if the newcomer bedoubles after the resident. - public static bool IsValidActiveEdgeOrder(ActiveEdge resident, ActiveEdge newcomer) - { - if (newcomer.CurrentX != resident.CurrentX) - { - return newcomer.CurrentX > resident.CurrentX; - } - - // Compare turning direction: resident.Top -> newcomer.Bottom -> newcomer.Top. - int d = PolygonUtilities.CrossSign(resident.Top, newcomer.Bottom, newcomer.Top); - if (d != 0) - { - return d < 0; - } - - // For collinear bounds, use the next turn to order them. - if (!resident.IsMaxima && (resident.Top.Y > newcomer.Top.Y)) - { - return PolygonUtilities.CrossSign( - newcomer.Bottom, - resident.Top, - resident.NextVertex.Point) <= 0; - } - - if (!newcomer.IsMaxima && (newcomer.Top.Y > resident.Top.Y)) - { - return PolygonUtilities.CrossSign( - newcomer.Bottom, - newcomer.Top, - newcomer.NextVertex.Point) >= 0; - } - - double y = newcomer.Bottom.Y; - bool newcomerIsLeft = newcomer.IsLeftBound; - - if (resident.Bottom.Y != y || resident.LocalMin.Vertex.Point.Y != y) - { - return newcomer.IsLeftBound; - } - - // Only newly inserted edges reach this branch. - if (resident.IsLeftBound != newcomerIsLeft) - { - return newcomerIsLeft; - } - - if (PolygonUtilities.IsCollinear( - resident.PrevPrevVertex.Point, - resident.Bottom, - resident.Top)) - { - return true; - } - - // Use the alternate bound turn to break the tie. - return (PolygonUtilities.CrossSign( - resident.PrevPrevVertex.Point, - newcomer.Bottom, - newcomer.PrevPrevVertex.Point) > 0) == newcomerIsLeft; - } - - /// - /// Resets and returns an active edge to the reuse pool. - /// - /// The edge to recycle. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void Recycle(ActiveEdge edge) - { - // Clear references so pooled edges do not retain objects. - edge.Bottom = default; - edge.Top = default; - edge.Dx = 0.0; - edge.CurrentX = 0; - edge.WindCount = 0; - edge.OutputRecord = null; - edge.PrevInAel = null; - edge.NextInAel = null; - edge.PrevInSel = null; - edge.NextInSel = null; - edge.Jump = null; - edge.VertexTop = null; - edge.LocalMin = default; - edge.IsLeftBound = false; - edge.JoinWith = JoinWith.None; - this.pool.Push(edge); - } -} diff --git a/src/PolygonClipper/Contour.cs b/src/PolygonClipper/Contour.cs index 0a0751f..436226d 100644 --- a/src/PolygonClipper/Contour.cs +++ b/src/PolygonClipper/Contour.cs @@ -4,16 +4,16 @@ using System.Collections; using System.Diagnostics; using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; namespace SixLabors.PolygonClipper; /// -/// Represents a single polygon ring (outer contour or hole). +/// Represents an open or closed sequence of vertices. /// /// -/// A contour is treated as implicitly closed: an edge is always considered between the last -/// vertex and the first vertex. A duplicated terminal closing vertex is optional on input -/// but not required. +/// Stroking respects . Filled-area operations implicitly close the +/// contour regardless of that value. A repeated closing vertex is optional on input. /// [DebuggerDisplay("Count = {Count}")] #pragma warning disable CA1710 // Identifiers should have correct suffix @@ -57,22 +57,32 @@ public int Count } /// - /// Gets the number of holes. + /// Gets or sets a value indicating whether the source contour is closed. + /// + /// + /// The default is true. Stroking respects this value. + /// Filled-area operations implicitly close the contour regardless of this value. + /// + public bool IsClosed { get; set; } = true; + + /// + /// Gets the number of directly nested child contours. /// public int HoleCount => this.holeIndices.Count; /// - /// Gets a value indicating whether the contour is external (not a hole). + /// Gets a value indicating whether the contour has no parent contour. /// + /// In a full containment hierarchy, even depths identify exterior contours and islands. public bool IsExternal => this.ParentIndex == null; /// - /// Gets or sets the index of the parent contour in the polygon if this contour is a hole. + /// Gets or sets the index of the contour that directly contains this contour. /// public int? ParentIndex { get; set; } /// - /// Gets or sets the depth of the contour. + /// Gets or sets the number of ancestors of this contour. /// public int Depth { get; set; } @@ -88,14 +98,14 @@ public Vertex this[int index] } /// - /// Gets the hole index at the specified position in the contour. + /// Gets the child contour index at the specified position. /// - /// The index of the hole. - /// The hole index. + /// The position in the child contour list. + /// The child's index in the owning polygon. public int GetHoleIndex(int index) => this.holeIndices[index]; /// - /// Gets the segment at the specified index of the contour. + /// Gets the filled-area boundary segment at the specified index. /// /// The index of the segment. /// The . The final segment wraps from last vertex to first vertex. @@ -104,6 +114,13 @@ internal Segment GetSegment(int index) ? new Segment(this.vertices[^1], this.vertices[0]) : new Segment(this.vertices[index], this.vertices[index + 1]); + /// + /// Gets a read-only span of the vertices in this contour. + /// + /// The vertex span. + /// Do not add or remove vertices while using the span. + internal ReadOnlySpan AsVertexSpan() => CollectionsMarshal.AsSpan(this.vertices); + /// /// Gets the bounding box of the contour. /// @@ -126,7 +143,7 @@ public Box2 GetBoundingBox() } /// - /// Gets a value indicating whether the contour is counterclockwise oriented + /// Determines whether the implicitly closed contour has counterclockwise orientation. /// /// /// if the contour is counterclockwise oriented; otherwise . @@ -144,7 +161,7 @@ public bool IsCounterClockwise() } /// - /// Gets a value indicating whether the contour is clockwise oriented + /// Determines whether the implicitly closed contour has clockwise orientation. /// /// /// if the contour is clockwise oriented; otherwise . @@ -219,8 +236,9 @@ public void RemoveVertexAt(int index) } /// - /// Clears all vertices and holes from the contour. + /// Clears all vertices and child contour indices. /// + /// The closure state is unchanged. public void Clear() { this.vertices.Clear(); @@ -229,7 +247,7 @@ public void Clear() } /// - /// Clears all holes from the contour. + /// Clears all child contour indices. /// public void ClearHoles() => this.holeIndices.Clear(); @@ -240,9 +258,9 @@ public void Clear() public Vertex GetLastVertex() => this.vertices[^1]; /// - /// Adds a hole index to the contour. + /// Adds an index to the child contour list. /// - /// The index of the hole to add. + /// The child's index in the owning polygon. public void AddHoleIndex(int index) => this.holeIndices.Add(index); /// @@ -289,6 +307,7 @@ public Contour DeepClone() { Contour clone = new(this.vertices.Count) { + IsClosed = this.IsClosed, ParentIndex = this.ParentIndex, Depth = this.Depth, hasCachedOrientation = this.hasCachedOrientation, diff --git a/src/PolygonClipper/FloatExtensions.cs b/src/PolygonClipper/DoubleExtensions.cs similarity index 95% rename from src/PolygonClipper/FloatExtensions.cs rename to src/PolygonClipper/DoubleExtensions.cs index 3f8affd..1e45dac 100644 --- a/src/PolygonClipper/FloatExtensions.cs +++ b/src/PolygonClipper/DoubleExtensions.cs @@ -6,9 +6,9 @@ namespace SixLabors.PolygonClipper; /// -/// Provides extension methods for floating-point numbers. +/// Provides extension methods for double values. /// -internal static class FloatExtensions +internal static class DoubleExtensions { /// /// Returns the next representable double value in the direction of y. diff --git a/src/PolygonClipper/FillRule.cs b/src/PolygonClipper/FillRule.cs index 49889ba..0605566 100644 --- a/src/PolygonClipper/FillRule.cs +++ b/src/PolygonClipper/FillRule.cs @@ -4,23 +4,27 @@ namespace SixLabors.PolygonClipper; /// -/// Specifies how directed contours define a filled area. +/// Specifies the polygon fill rule. /// -/// -/// Counterclockwise contours contribute positive winding; clockwise contours contribute negative winding. -/// The directed vertices determine winding independently of contour parent and hole metadata. -/// public enum FillRule { - /// The area is filled where the winding count is odd. + /// + /// The area is filled where the winding count is odd. + /// EvenOdd = 0, - /// The area is filled where the winding count is non-zero. + /// + /// The area is filled where the winding count is non-zero. + /// NonZero = 1, - /// The area is filled where the winding count is positive. + /// + /// The area is filled where the winding count is positive. + /// Positive = 2, - /// The area is filled where the winding count is negative. + /// + /// The area is filled where the winding count is negative. + /// Negative = 3 } diff --git a/src/PolygonClipper/IntersectNode.cs b/src/PolygonClipper/IntersectNode.cs deleted file mode 100644 index f2a7985..0000000 --- a/src/PolygonClipper/IntersectNode.cs +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright (c) Six Labors. -// Licensed under the Six Labors Split License. - -namespace SixLabors.PolygonClipper; - -/// -/// Represents a pending intersection between two active edges. -/// -/// -/// Intersections are sorted and processed from higher scanlines to lower ones so -/// that edge order in the AEL remains consistent as the sweep descends. -/// -internal readonly struct IntersectNode -{ -#pragma warning disable SA1401 // Hot path intersection sorting benefits from field access. - /// - /// Gets the intersection point between and . - /// - public readonly Vertex Point; - - /// - /// Gets the first active edge participating in the intersection. - /// - public readonly ActiveEdge Edge1; - - /// - /// Gets the second active edge participating in the intersection. - /// - public readonly ActiveEdge Edge2; -#pragma warning restore SA1401 - - /// - /// Initializes a new instance of the struct. - /// - internal IntersectNode(Vertex point, ActiveEdge edge1, ActiveEdge edge2) - { - this.Point = point; - this.Edge1 = edge1; - this.Edge2 = edge2; - } -} diff --git a/src/PolygonClipper/JoinWith.cs b/src/PolygonClipper/JoinWith.cs deleted file mode 100644 index 36a530d..0000000 --- a/src/PolygonClipper/JoinWith.cs +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) Six Labors. -// Licensed under the Six Labors Split License. - -namespace SixLabors.PolygonClipper; - -/// -/// Indicates whether an active edge should be joined with a neighbor after a split. -/// -internal enum JoinWith -{ - /// - /// No pending join. - /// - None, - - /// - /// Join with the left neighbor in the AEL. - /// - Left, - - /// - /// Join with the right neighbor in the AEL. - /// - Right -} diff --git a/src/PolygonClipper/LocalMinima.cs b/src/PolygonClipper/LocalMinima.cs deleted file mode 100644 index 3ba6c93..0000000 --- a/src/PolygonClipper/LocalMinima.cs +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) Six Labors. -// Licensed under the Six Labors Split License. - -namespace SixLabors.PolygonClipper; - -/// -/// Describes the lowest vertex of an edge bound for the sweep line. -/// -internal readonly struct LocalMinima : IEquatable -{ - /// - /// Initializes a new instance of the struct. - /// - internal LocalMinima(SweepVertex vertex) => this.Vertex = vertex; - - /// - /// Gets the vertex associated with this local minima. - /// - internal SweepVertex Vertex { get; } - - public static bool operator ==(LocalMinima lm1, LocalMinima lm2) => lm1.Equals(lm2); - - public static bool operator !=(LocalMinima lm1, LocalMinima lm2) => !(lm1 == lm2); - - public override bool Equals(object? obj) => obj is LocalMinima minima && this.Equals(minima); - - public override int GetHashCode() => this.Vertex.GetHashCode(); - - public bool Equals(LocalMinima other) => ReferenceEquals(this.Vertex, other.Vertex); -} - -/// -/// Orders local minima so higher Y-values are processed first during the sweep. -/// -internal sealed class LocalMinimaComparer : IComparer -{ - public int Compare(LocalMinima locMin1, LocalMinima locMin2) - => locMin2.Vertex.Point.Y.CompareTo(locMin1.Vertex.Point.Y); -} diff --git a/src/PolygonClipper/OutputRecord.cs b/src/PolygonClipper/OutputRecord.cs deleted file mode 100644 index 213f271..0000000 --- a/src/PolygonClipper/OutputRecord.cs +++ /dev/null @@ -1,161 +0,0 @@ -// Copyright (c) Six Labors. -// Licensed under the Six Labors Split License. - -namespace SixLabors.PolygonClipper; - -/// -/// Captures a clipped contour, its topology, and its ownership hierarchy. -/// -internal sealed class OutputRecord -{ - /// - /// Gets or sets the stable index assigned when the record is pooled. - /// - public int Index { get; set; } - - /// - /// Gets or sets the number of output points in the contour. - /// - public int OutputPointCount { get; set; } - - /// - /// Gets or sets the containing output record, if any. - /// - public OutputRecord? Owner { get; set; } - - /// - /// Gets or sets the front edge that defines the output orientation. - /// - public ActiveEdge? FrontEdge { get; set; } - - /// - /// Gets or sets the back edge that defines the output orientation. - /// - public ActiveEdge? BackEdge { get; set; } - - /// - /// Gets or sets the circular linked list of output points. - /// - public OutputPoint? Points { get; set; } - - /// - /// Gets or sets the cached bounds for ownership tests. - /// - public Box2 Bounds { get; set; } - - /// - /// Gets or sets the temporary contour used during bounds checks. - /// - public List Path { get; set; } = []; - - /// - /// Gets or sets split indices used to resolve complex self-intersections. - /// - public List? Splits { get; set; } - - /// - /// Gets or sets the cached split ownership used to avoid recursion. - /// - public OutputRecord? RecursiveSplit { get; set; } -} - -/// -/// Represents a vertex in the output contour linked list. -/// -internal sealed class OutputPoint -{ -#pragma warning disable SA1401 // Hot output ring traversal uses fields to avoid accessor overhead. - /// - /// The vertex coordinate. - /// - public Vertex Point; - - /// - /// The next point in the linked list. - /// - public OutputPoint? Next; - - /// - /// The previous point in the linked list. - /// - public OutputPoint Prev; - - /// - /// The owning output record. - /// - public OutputRecord OutputRecord; - - /// - /// The horizontal segment reference used for joins. - /// - public HorizontalSegment? HorizontalSegment; -#pragma warning restore SA1401 - - /// - /// Initializes a new instance of the class. - /// - public OutputPoint(Vertex point, OutputRecord outputRecord) - { - this.Point = point; - this.OutputRecord = outputRecord; - this.Next = this; - this.Prev = this; - this.HorizontalSegment = null; - } -} - -/// -/// Captures a pending horizontal segment to be joined. -/// -internal sealed class HorizontalSegment -{ - /// - /// Initializes a new instance of the class. - /// - public HorizontalSegment(OutputPoint op) - { - this.LeftPoint = op; - this.RightPoint = null; - this.LeftToRight = true; - } - - /// - /// Gets or sets the left-most point of the segment. - /// - public OutputPoint? LeftPoint { get; set; } - - /// - /// Gets or sets the right-most point of the segment. - /// - public OutputPoint? RightPoint { get; set; } - - /// - /// Gets or sets a value indicating whether the segment runs left-to-right. - /// - public bool LeftToRight { get; set; } -} - -/// -/// Stores a pair of horizontal edges to be joined. -/// -internal sealed class HorizontalJoin -{ - /// - /// Initializes a new instance of the class. - /// - public HorizontalJoin(OutputPoint leftToRight, OutputPoint rightToLeft) - { - this.LeftToRight = leftToRight; - this.RightToLeft = rightToLeft; - } - - /// - /// Gets or sets the left-to-right point of the join. - /// - public OutputPoint? LeftToRight { get; set; } - - /// - /// Gets or sets the right-to-left point of the join. - /// - public OutputPoint? RightToLeft { get; set; } -} diff --git a/src/PolygonClipper/Polygon.cs b/src/PolygonClipper/Polygon.cs index 80e5383..8887d56 100644 --- a/src/PolygonClipper/Polygon.cs +++ b/src/PolygonClipper/Polygon.cs @@ -8,8 +8,11 @@ namespace SixLabors.PolygonClipper; /// -/// Represents a complex polygon. +/// Represents a collection of contours. /// +/// +/// Filled-area operations implicitly close every contour. Stroking respects each contour's closure state. +/// #pragma warning disable CA1710 // Identifiers should have correct suffix public sealed class Polygon : IReadOnlyCollection #pragma warning restore CA1710 // Identifiers should have correct suffix diff --git a/src/PolygonClipper/PolygonClipper.FillRules.cs b/src/PolygonClipper/PolygonClipper.FillRules.cs deleted file mode 100644 index ae88053..0000000 --- a/src/PolygonClipper/PolygonClipper.FillRules.cs +++ /dev/null @@ -1,147 +0,0 @@ -// Copyright (c) Six Labors. -// Licensed under the Six Labors Split License. - -namespace SixLabors.PolygonClipper; - -/// Provides explicit fill-rule operations on polygon geometry. -public partial class PolygonClipper -{ - private static readonly Polygon EmptyFillOperand = []; - - private bool useFillRules; - private FillRule subjectFillRule; - private FillRule clipFillRule; - private WindingSweep? windingSweep; - - /// - /// Initializes a new instance of the class with independent operand fill rules. - /// - /// The left-hand operand. - /// The right-hand operand. - /// The Boolean operation. - /// The rule interpreting the subject's directed contours. - /// The rule interpreting the clipping operand's directed contours. - public PolygonClipper(Polygon subject, Polygon clip, BooleanOperation operation, FillRule subjectFillRule, FillRule clipFillRule) - { - ValidateFillArguments(subject, clip, operation, subjectFillRule, clipFillRule); - this.Configure(subject, clip, operation); - this.useFillRules = true; - this.subjectFillRule = subjectFillRule; - this.clipFillRule = clipFillRule; - } - - /// Intersects two filled areas using a common fill rule. - /// The left-hand operand. - /// The right-hand operand. - /// The rule interpreting both operands. - /// The filled area common to both operands. - public static Polygon Intersection(Polygon subject, Polygon clip, FillRule fillRule) - => Intersection(subject, clip, fillRule, fillRule); - - /// Intersects two filled areas using independent fill rules. - /// The left-hand operand. - /// The right-hand operand. - /// The subject's fill rule. - /// The clipping operand's fill rule. - /// The filled area common to both operands. - public static Polygon Intersection(Polygon subject, Polygon clip, FillRule subjectFillRule, FillRule clipFillRule) - => ExecuteFillOperation(subject, clip, BooleanOperation.Intersection, subjectFillRule, clipFillRule); - - /// Unites two filled areas using a common fill rule. - /// The left-hand operand. - /// The right-hand operand. - /// The rule interpreting both operands. - /// The filled area belonging to either operand. - public static Polygon Union(Polygon subject, Polygon clip, FillRule fillRule) - => Union(subject, clip, fillRule, fillRule); - - /// Unites two filled areas using independent fill rules. - /// The left-hand operand. - /// The right-hand operand. - /// The subject's fill rule. - /// The clipping operand's fill rule. - /// The filled area belonging to either operand. - public static Polygon Union(Polygon subject, Polygon clip, FillRule subjectFillRule, FillRule clipFillRule) - => ExecuteFillOperation(subject, clip, BooleanOperation.Union, subjectFillRule, clipFillRule); - - /// Resolves directed contours into their filled area. - /// The raw directed contours. - /// The rule interpreting the contours. - /// The resolved filled area, without changing the input contours. - /// Input hierarchy does not override contour direction or the selected fill rule. - public static Polygon Union(Polygon polygon, FillRule fillRule) - => ExecuteFillOperation(polygon, EmptyFillOperand, BooleanOperation.Union, fillRule, FillRule.EvenOdd); - - /// Subtracts one filled area from another using a common fill rule. - /// The area to retain. - /// The area to subtract. - /// The rule interpreting both operands. - /// The subject area outside the clipping operand. - public static Polygon Difference(Polygon subject, Polygon clip, FillRule fillRule) - => Difference(subject, clip, fillRule, fillRule); - - /// Subtracts one filled area from another using independent fill rules. - /// The area to retain. - /// The area to subtract. - /// The subject's fill rule. - /// The clipping operand's fill rule. - /// The subject area outside the clipping operand. - public static Polygon Difference(Polygon subject, Polygon clip, FillRule subjectFillRule, FillRule clipFillRule) - => ExecuteFillOperation(subject, clip, BooleanOperation.Difference, subjectFillRule, clipFillRule); - - /// Computes exclusive filled coverage using a common fill rule. - /// The left-hand operand. - /// The right-hand operand. - /// The rule interpreting both operands. - /// The filled area belonging to exactly one operand. - public static Polygon Xor(Polygon subject, Polygon clip, FillRule fillRule) - => Xor(subject, clip, fillRule, fillRule); - - /// Computes exclusive filled coverage using independent fill rules. - /// The left-hand operand. - /// The right-hand operand. - /// The subject's fill rule. - /// The clipping operand's fill rule. - /// The filled area belonging to exactly one operand. - public static Polygon Xor(Polygon subject, Polygon clip, FillRule subjectFillRule, FillRule clipFillRule) - => ExecuteFillOperation(subject, clip, BooleanOperation.Xor, subjectFillRule, clipFillRule); - - /// Executes an explicit fill-rule operation through the existing clipper pool. - /// The left-hand operand. - /// The right-hand operand. - /// The Boolean operation. - /// The subject's fill rule. - /// The clipping operand's fill rule. - /// The resolved filled area. - private static Polygon ExecuteFillOperation(Polygon subject, Polygon clip, BooleanOperation operation, FillRule subjectRule, FillRule clipRule) - { - ValidateFillArguments(subject, clip, operation, subjectRule, clipRule); - PolygonClipper clipper = Rent(subject, clip, operation); - try - { - clipper.useFillRules = true; - clipper.subjectFillRule = subjectRule; - clipper.clipFillRule = clipRule; - return clipper.Run(); - } - finally - { - Return(clipper); - } - } - - /// Validates new public operation arguments before taking geometry shortcuts. - /// The left-hand operand. - /// The right-hand operand. - /// The Boolean operation. - /// The subject's fill rule. - /// The clipping operand's fill rule. - private static void ValidateFillArguments(Polygon subject, Polygon clip, BooleanOperation operation, FillRule subjectRule, FillRule clipRule) - { - ArgumentNullException.ThrowIfNull(subject); - ArgumentNullException.ThrowIfNull(clip); - ArgumentOutOfRangeException.ThrowIfGreaterThan((uint)operation, (uint)BooleanOperation.Xor, nameof(operation)); - ArgumentOutOfRangeException.ThrowIfGreaterThan((uint)subjectRule, (uint)FillRule.Negative, nameof(subjectRule)); - ArgumentOutOfRangeException.ThrowIfGreaterThan((uint)clipRule, (uint)FillRule.Negative, nameof(clipRule)); - } -} diff --git a/src/PolygonClipper/PolygonClipper.Winding.cs b/src/PolygonClipper/PolygonClipper.Winding.cs deleted file mode 100644 index f321b92..0000000 --- a/src/PolygonClipper/PolygonClipper.Winding.cs +++ /dev/null @@ -1,802 +0,0 @@ -// Copyright (c) Six Labors. -// Licensed under the Six Labors Split License. - -namespace SixLabors.PolygonClipper; - -/// Provides native signed-winding execution for polygon clipping. -public partial class PolygonClipper -{ - /// Compares points in the formal sweep's lexicographic order. - /// The first point. - /// The second point. - /// Their sweep ordering. - private static int ComparePoints(Vertex first, Vertex second) - { - int x = first.X.CompareTo(second.X); - return x == 0 ? first.Y.CompareTo(second.Y) : x; - } - - /// Stores separate subject and clip contributions without cross-operand cancellation. - private readonly struct WindingCount - { - /// The subject winding. - public readonly int Subject; - - /// The clipping operand winding. - public readonly int Clip; - - /// Initializes a new instance of the struct. - /// The subject component. - /// The clipping component. - public WindingCount(int subject, int clip) - { - this.Subject = subject; - this.Clip = clip; - } - - /// Gets a value indicating whether both contributions cancel. - public bool IsZero => this.Subject == 0 && this.Clip == 0; - - /// Adds an interval's contribution. - /// The contribution to add. - /// The summed winding. - public WindingCount Add(WindingCount other) => new(this.Subject + other.Subject, this.Clip + other.Clip); - - /// Removes contributions terminating at an endpoint. - /// The terminating contributions. - /// The remaining winding. - public WindingCount Subtract(WindingCount other) => new(this.Subject - other.Subject, this.Clip - other.Clip); - } - - /// Stores a versioned endpoint in the existing priority queue. - private readonly struct WindingEvent - { - /// The queued geometric point. - public readonly Vertex Point; - - /// The associated interval. - public readonly WindingEdge Edge; - - /// The interval version when queued. - public readonly int Version; - - /// Whether this record starts a source interval. - public readonly bool IsStart; - - /// Initializes a new instance of the struct. - /// The endpoint. - /// The interval. - /// Whether the record starts the interval. - public WindingEvent(Vertex point, WindingEdge edge, bool isStart) - { - this.Point = point; - this.Edge = edge; - this.Version = edge.Version; - this.IsStart = isStart; - } - - /// Gets a value indicating whether the representative still owns this queued record. - public bool IsValid => this.Version == this.Edge.Version && (this.IsStart || this.Edge.Active); - } - - /// - /// Stores the additional state needed by explicit fill rules. Legacy parity calls - /// do not allocate this workspace or enlarge their individual sweep events. - /// - private sealed class WindingSweep - { - private readonly List eventStorage = []; - private readonly StablePriorityQueue events; - private readonly WindingEdgePool edges = new(); - private readonly List active = []; - private readonly List activeResult = []; - private readonly List outgoing = []; - private readonly List bundled = []; - - /// Initializes a new instance of the class. - public WindingSweep() => this.events = new(WindingEventComparer.Instance, this.eventStorage); - - /// Gets the storage retained by this native sweep. - public int RetainedCapacity => this.edges.Capacity + this.eventStorage.Capacity + this.active.Capacity + - this.activeResult.Capacity + this.outgoing.Capacity + this.bundled.Capacity; - - /// Releases per-operation references while retaining bounded scratch storage. - public void Reset() - { - this.eventStorage.Clear(); - this.active.Clear(); - this.activeResult.Clear(); - this.outgoing.Clear(); - this.bundled.Clear(); - for (int i = 0; i < this.edges.Count; i++) - { - this.edges[i].Ends = null; - this.edges[i].Boundary = null; - } - - this.edges.Clear(); - } - - /// Clips raw directed contours in one Martinez intersection sweep. - /// The subject contours. - /// The clipping contours. - /// The Boolean operation. - /// The subject's fill rule. - /// The clipping operand's fill rule. - /// The existing clipper's output-event storage. - /// The existing edge-connection event comparer. - /// The connected result boundaries. - public Polygon Run( - Polygon subject, - Polygon clip, - BooleanOperation operation, - FillRule subjectRule, - FillRule clipRule, - SweepEventPoolList resultEvents, - SweepEventComparer resultComparer) - { - this.Reset(); - if (operation == BooleanOperation.Intersection && (subject.Count == 0 || clip.Count == 0)) - { - return []; - } - - // Reuse the existing capacity APIs and reserve source-sized storage - // before ingestion. Repeated geometric growth otherwise copies the - // larger endpoint records and can exceed the shared retention bound. - int vertexCount = subject.VertexCount + clip.VertexCount; - this.eventStorage.EnsureCapacity(vertexCount); - this.edges.EnsureCapacity(vertexCount); - resultEvents.EnsureCapacity(vertexCount * 2); - - this.AddInput(subject, true); - this.AddInput(clip, false); - this.events.Heapify(); - - while (this.events.Count > 0) - { - WindingEvent next = this.events.Dequeue(); - if (!next.IsValid) - { - continue; - } - - Vertex point = next.Point; - this.outgoing.Clear(); - int firstEnd = int.MaxValue; - int lastEnd = -1; - if (next.IsStart) - { - this.outgoing.Add(next.Edge); - } - else - { - firstEnd = lastEnd = next.Edge.Position; - } - - // A vertex is a transaction, not a sequence of parity toggles. - // Collect every start/end at this exact lexicographic point. - while (this.events.Count > 0 && this.events.Peek().Point == point) - { - next = this.events.Dequeue(); - if (next.IsValid && next.IsStart) - { - this.outgoing.Add(next.Edge); - } - else if (next.IsValid) - { - firstEnd = Math.Min(firstEnd, next.Edge.Position); - lastEnd = Math.Max(lastEnd, next.Edge.Position); - } - } - - int first = lastEnd < 0 ? FindLower(this.active, point) : firstEnd; - while (first > 0 && ContainsPoint(this.active[first - 1], point)) - { - first--; - } - - int after = Math.Max(first, lastEnd + 1); - while (after < this.active.Count && ContainsPoint(this.active[after], point)) - { - after++; - } - - // The result index is a filtered view of the very same block. - // Derive removals from the owned interval identities, so rounded - // incidence tests cannot remove a boundary independently of its - // source interval and leave a stale birth context behind. - int firstResult = first == 0 ? 0 : this.active[first - 1].ResultRank; - int afterResult = firstResult; - for (int i = first; i < after; i++) - { - WindingEdge incoming = this.active[i]; - if (incoming.Boundary is not null) - { - afterResult++; - } - } - - // The surviving lower interval is outside the changed block. - // Closure conserves the sum of signed contributions, so its - // prefix and every surviving prefix above the block stay valid. - WindingCount winding = first == 0 ? default : this.active[first - 1].Above; - SweepEvent? previousBoundary = firstResult == 0 ? null : this.activeResult[firstResult - 1].Boundary; - if (firstResult > 0 && this.activeResult[firstResult - 1].Start.X == this.activeResult[firstResult - 1].End.X) - { - previousBoundary = previousBoundary!.PrevInResult; - } - - for (int i = first; i < after; i++) - { - WindingEdge incoming = this.active[i]; - incoming.Active = false; - incoming.Version++; - if (incoming.Boundary is SweepEvent boundary) - { - // A historical contribution is never rewritten when its - // continuation changes fill membership. Only its actual - // terminal endpoint becomes known at this event. - SweepEvent right = new(point, false, boundary, PolygonType.Subject) - { - ContourId = boundary.ContourId - }; - boundary.OtherEvent = right; - resultEvents.Add(boundary); - resultEvents.Add(right); - } - - this.ContinueAt(incoming, point); - } - - this.active.RemoveRange(first, after - first); - this.activeResult.RemoveRange(firstResult, afterResult - firstResult); - - // All active intervals through point were included above, not - // merely those named by queued events. Outgoing rays all start - // here, so non-collinear rays cannot meet again in their interiors. - this.outgoing.Sort(WindingRayComparer.Instance); - this.BundleOutgoing(); - - int resultIndex = firstResult; - for (int i = 0; i < this.bundled.Count; i++) - { - WindingEdge edge = this.bundled[i]; - bool below = Membership(winding, operation, subjectRule, clipRule); - winding = winding.Add(edge.Delta); - edge.Above = winding; - bool above = Membership(winding, operation, subjectRule, clipRule); - if (below != above) - { - // Endpoint pairing is completed when the interval ends. - // No geometry consumer reads this event until connection. - edge.Boundary = new SweepEvent(point, true, PolygonType.Subject) - { - ContourId = edge.Id, - PrevInResult = previousBoundary!, - ResultTransition = above ? ResultTransition.Contributing : ResultTransition.NonContributing - }; - if (edge.Start.X != edge.End.X) - { - previousBoundary = edge.Boundary; - } - - this.activeResult.Insert(resultIndex++, edge); - } - - edge.Active = true; - this.active.Insert(first + i, edge); - this.events.Enqueue(new WindingEvent(edge.End, edge, false)); - } - - // List insertion/removal already shifts this suffix. Keep the - // endpoint anchors and filtered-boundary ranks in the same order. - // Winding counts above the changed block do not need recomputing. - int resultRank = firstResult; - for (int i = first; i < this.active.Count; i++) - { - WindingEdge edge = this.active[i]; - edge.Position = i; - if (edge.Boundary is not null) - { - resultRank++; - } - - edge.ResultRank = resultRank; - } - - // Interior outgoing pairs share this already closed event point. - // Only the two new exterior adjacencies can expose a future crossing. - if (this.bundled.Count == 0) - { - this.CheckNeighbors(first - 1, first, point); - } - else - { - this.CheckNeighbors(first - 1, first, point); - this.CheckNeighbors(first + this.bundled.Count - 1, first + this.bundled.Count, point); - } - } - - // Native events are completed at their right endpoints. Restore the - // ordering expected by the existing connector in O(B log B), rather - // than making its nearly-sorted repair loop sort reversed history. - resultEvents.Sort(resultComparer); - Polygon result = ConnectEdges(resultEvents, resultComparer); - for (int i = 0; i < result.Count; i++) - { - Contour contour = result[i]; - if (contour.Count > 1 && contour[0] == contour[^1]) - { - contour.RemoveVertexAt(contour.Count - 1); - } - - if (contour.IsExternal) - { - contour.SetCounterClockwise(); - } - else - { - contour.SetClockwise(); - } - } - - return result; - } - - /// Adds directed input segments without normalizing or reorienting them. - /// The input contours. - /// Whether these contours belong to the subject. - private void AddInput(Polygon polygon, bool subject) - { - for (int i = 0; i < polygon.Count; i++) - { - Contour contour = polygon[i]; - int count = GetContourSegmentCount(contour); - for (int j = 0; j < count; j++) - { - Segment segment = contour.GetSegment(j); - Vertex start = segment.Source; - Vertex end = segment.Target; - if (!double.IsFinite(start.X) || !double.IsFinite(start.Y)) - { - throw new ArgumentException("Polygon coordinates must be finite.", nameof(polygon)); - } - - if (start == end) - { - continue; - } - - int direction = 1; - if (ComparePoints(start, end) > 0) - { - (start, end) = (end, start); - direction = -1; - } - - // Lexicographic direction is the formal x+epsilon*y sweep - // direction, including vertical source segments. Epsilon is - // never evaluated or applied to the stored double coordinates. - WindingCount delta = subject ? new(direction, 0) : new(0, direction); - WindingEdge edge = this.edges.Add(start, end, delta); - this.eventStorage.Add(new WindingEvent(start, edge, true)); - } - } - } - - /// Preserves a split interval's longer source tails and endpoint deltas. - /// The interval ending at this point. - /// The complete event point. - private void ContinueAt(WindingEdge incoming, Vertex point) - { - if (incoming.Ends is SortedDictionary ends) - { - WindingCount delta = incoming.Delta; - if (ends.Remove(point, out WindingCount ending)) - { - delta = delta.Subtract(ending); - } - - if (ends.Count == 0) - { - incoming.Ends = null; - return; - } - - incoming.Delta = delta; - incoming.SourceEnd = FirstEndpoint(ends); - } - else if (ComparePoints(point, incoming.SourceEnd) >= 0) - { - return; - } - - // Output history owns independent SweepEvent objects. Reuse only the - // live interval, whose version was advanced before closing its old - // piece. Stale queue records stay invalid without retaining a new - // interval object for every intersection in the operation. - incoming.Start = point; - incoming.End = incoming.SourceEnd; - incoming.Boundary = null; - this.outgoing.Add(incoming); - } - - /// Combines coincident outgoing intervals without losing longer continuations. - private void BundleOutgoing() - { - this.bundled.Clear(); - int i = 0; - while (i < this.outgoing.Count) - { - WindingEdge edge = this.outgoing[i++]; - while (i < this.outgoing.Count && WindingRayComparer.Instance.Compare(edge, this.outgoing[i]) == 0) - { - WindingEdge other = this.outgoing[i++]; - - // A bundle may outlive its representative's original segment. - // Its support must cover every retained endpoint-ledger tail. - if (ComparePoints(other.Support.Target, edge.Support.Target) > 0) - { - edge.Support = new Segment(edge.Support.Source, other.Support.Target); - } - - if (edge.Ends is null && other.Ends is null && edge.SourceEnd == other.SourceEnd) - { - // The common duplicate-edge case needs no endpoint ledger. - edge.Delta = edge.Delta.Add(other.Delta); - continue; - } - - SortedDictionary ends = edge.Ends ??= - new SortedDictionary(WindingPointComparer.Instance) - { - [edge.SourceEnd] = edge.Delta - }; - if (other.Ends is SortedDictionary otherEnds) - { - foreach (KeyValuePair endpoint in otherEnds) - { - AddEndpoint(ends, endpoint.Key, endpoint.Value); - } - - other.Ends = null; - } - else - { - AddEndpoint(ends, other.SourceEnd, other.Delta); - } - - edge.Delta = edge.Delta.Add(other.Delta); - } - - if (edge.Ends is SortedDictionary ledger) - { - if (ledger.Count == 0) - { - continue; - } - - edge.SourceEnd = edge.End = FirstEndpoint(ledger); - } - else if (edge.Delta.IsZero) - { - continue; - } - - // A zero current sum with non-zero later endpoint changes must - // retain its continuation, even though it emits no boundary now. - this.bundled.Add(edge); - } - } - - /// Accumulates one coincident contribution's terminal change. - /// The bundle's future endpoint changes. - /// The terminal point. - /// The contribution ending there. - private static void AddEndpoint(SortedDictionary ends, Vertex point, WindingCount delta) - { - if (ends.TryGetValue(point, out WindingCount existing)) - { - delta = delta.Add(existing); - } - - if (delta.IsZero) - { - ends.Remove(point); - } - else - { - ends[point] = delta; - } - } - - /// Gets the next terminal change of a non-empty bundle ledger. - /// The non-empty endpoint ledger. - /// The first endpoint. - private static Vertex FirstEndpoint(SortedDictionary ends) - { - using SortedDictionary.Enumerator enumerator = ends.GetEnumerator(); - enumerator.MoveNext(); - return enumerator.Current.Key; - } - - /// Schedules the next intersection of newly adjacent active intervals. - /// The lower neighbor's index. - /// The upper neighbor's index. - /// The event already processed. - private void CheckNeighbors(int lower, int upper, Vertex point) - { - if (lower < 0 || upper >= this.active.Count) - { - return; - } - - WindingEdge first = this.active[lower]; - WindingEdge second = this.active[upper]; - - // Keep the original support lines across splits. Reconstructing a - // line from a rounded intersection rotates it and can create a second, - // slightly different intersection at an existing source vertex. - if (first.LineId > second.LineId) - { - (first, second) = (second, first); - } - - int count = PolygonUtilities.FindIntersectionPrecise( - first.Support, second.Support, out Vertex intersection, out Vertex last); - if (count > 0) - { - // Match the established Martinez repair: a rounded crossing on - // this x coordinate but below the completed event cannot be - // visited backwards. Advance x by one representable double. - if (intersection.X == point.X && intersection.Y < point.Y) - { - intersection = new Vertex(intersection.X.NextAfter(double.PositiveInfinity), intersection.Y); - } - - if (ComparePoints(intersection, first.Start) < 0 || ComparePoints(intersection, second.Start) < 0 || - (ComparePoints(intersection, first.End) > 0 && (first.End != first.SourceEnd || intersection.X != first.End.X)) || - (ComparePoints(intersection, second.End) > 0 && (second.End != second.SourceEnd || intersection.X != second.End.X))) - { - return; - } - - this.ScheduleSplit(first, intersection, point); - this.ScheduleSplit(second, intersection, point); - if (count == 2) - { - this.ScheduleSplit(first, last, point); - this.ScheduleSplit(second, last, point); - } - } - } - - /// Shortens a live interval to its earliest discovered future node. - /// The live interval. - /// The discovered node. - /// The completed event point. - private void ScheduleSplit(WindingEdge edge, Vertex intersection, Vertex current) - { - if (ComparePoints(intersection, current) <= 0 || intersection == edge.End) - { - return; - } - - if (ComparePoints(intersection, edge.End) > 0) - { - if (edge.End != edge.SourceEnd || intersection.X != edge.End.X || edge.Start.X == edge.End.X) - { - return; - } - - // The second established Martinez rounding case reverses the - // tiny final piece: the source endpoint precedes the rounded - // crossing on the same x coordinate. Represent that piece as a - // new forward interval with the opposite signed contribution. - WindingEdge tail = this.edges.Add(edge.SourceEnd, intersection, default(WindingCount).Subtract(edge.Delta)); - this.events.Enqueue(new WindingEvent(tail.Start, tail, true)); - edge.SourceEnd = intersection; - } - - // SourceEnd/Ends retain the source's real terminal changes. End only - // limits this open interval; its continuation is made at the new node. - edge.End = intersection; - edge.Version++; - this.events.Enqueue(new WindingEvent(intersection, edge, false)); - } - - /// Finds the first live interval not strictly below an event point. - /// The already ordered status list. - /// The event point. - /// The lower insertion bound. - private static int FindLower(List status, Vertex point) - { - int left = 0; - int right = status.Count; - while (left < right) - { - int middle = left + ((right - left) >> 1); - WindingEdge edge = status[middle]; - if (!ContainsPoint(edge, point) && PolygonUtilities.SignedArea(edge.Start, edge.End, point) > 0) - { - left = middle + 1; - } - else - { - right = middle; - } - } - - return left; - } - - /// Tests incidence on both the noded interval and its preserved source support. - /// The active interval. - /// The event point. - /// Whether the interval participates in this event. - private static bool ContainsPoint(WindingEdge edge, Vertex point) - { - // The two equivalent determinant origins can round differently. - // Preserve endpoint incidence on either representation, and source - // vertices on the support even after a rounded split shortened End. - return ComparePoints(edge.Start, point) <= 0 && ComparePoints(point, edge.End) <= 0 && - (PolygonUtilities.SignedArea(edge.Start, edge.End, point) == 0 || - Vertex.Cross(edge.End - edge.Start, point - edge.Start) == 0 || - Vertex.Cross(edge.Support.Target - edge.Support.Source, point - edge.Support.Source) == 0); - } - - /// Evaluates Boolean membership from independent signed winding counts. - /// The region's winding counts. - /// The Boolean operation. - /// The subject's fill rule. - /// The clipping operand's fill rule. - /// Whether the region belongs to the result. - private static bool Membership(WindingCount count, BooleanOperation operation, FillRule subjectRule, FillRule clipRule) - { - bool subject = Filled(count.Subject, subjectRule); - bool clip = Filled(count.Clip, clipRule); - return operation switch - { - BooleanOperation.Intersection => subject && clip, - BooleanOperation.Union => subject || clip, - BooleanOperation.Difference => subject && !clip, - _ => subject ^ clip - }; - } - - /// Interprets a winding count using a validated fill rule. - /// The signed winding count. - /// The validated fill rule. - /// Whether the region is filled. - private static bool Filled(int count, FillRule rule) - => rule switch - { - FillRule.EvenOdd => (count & 1) != 0, - FillRule.NonZero => count != 0, - FillRule.Positive => count > 0, - _ => count < 0 - }; - } - - /// Stores one live native interval, separately from completed output history. - private sealed class WindingEdge - { - /// Gets or sets the stable identity within this operation. - public int Id { get; set; } - - /// Gets or sets the canonical start point. - public Vertex Start { get; set; } - - /// Gets or sets the next discovered endpoint or intersection. - public Vertex End { get; set; } - - /// Gets or sets the next actual source contribution endpoint. - public Vertex SourceEnd { get; set; } - - /// Gets or sets the original directed support, unaffected by rounded split points. - public Segment Support { get; set; } - - /// Gets or sets the original segment identity used to construct intersections consistently. - public int LineId { get; set; } - - /// Gets or sets the live status position, used to anchor constructed intersections. - public int Position { get; set; } - - /// Gets or sets the count of live result boundaries at or below this interval. - public int ResultRank { get; set; } - - /// Gets or sets the signed contribution of the live interval. - public WindingCount Delta { get; set; } - - /// Gets or sets the cached winding immediately above the live interval. - public WindingCount Above { get; set; } - - /// Gets or sets the longer-tail endpoint ledger for a coincident bundle. - public SortedDictionary? Ends { get; set; } - - /// Gets or sets the fixed contribution and birth context when this interval contributes. - public SweepEvent? Boundary { get; set; } - - /// Gets or sets the version used to discard superseded queued endpoints. - public int Version { get; set; } - - /// Gets or sets a value indicating whether this representative remains in the active status. - public bool Active { get; set; } - } - - /// Reuses native interval objects through the existing append-only pool mechanism. - private sealed class WindingEdgePool : PooledList - { - /// Acquires an interval for a new open piece. - /// The canonical start. - /// The source endpoint. - /// The signed contribution. - /// The initialized interval. - public WindingEdge Add(Vertex start, Vertex end, WindingCount delta) - { - this.TryGrow(); - WindingEdge edge = this.Items[this.Size] ??= new WindingEdge(); - edge.Id = this.Size++; - edge.LineId = edge.Id; - edge.Start = start; - edge.End = edge.SourceEnd = end; - edge.Support = new(start, end); - edge.Delta = delta; - edge.Above = default; - edge.Ends = null; - edge.Boundary = null; - edge.Version = 0; - edge.Active = false; - return edge; - } - } - - /// Orders native endpoint records deterministically without changing coordinates. - private sealed class WindingEventComparer : IComparer - { - /// The shared stateless comparer. - public static readonly WindingEventComparer Instance = new(); - - /// - public int Compare(WindingEvent x, WindingEvent y) - { - int order = ComparePoints(x.Point, y.Point); - if (order == 0) - { - order = x.Edge.Id.CompareTo(y.Edge.Id); - } - - if (order == 0) - { - order = x.Version.CompareTo(y.Version); - } - - return order == 0 ? x.IsStart.CompareTo(y.IsStart) : order; - } - } - - /// Orders rays immediately after their shared event point. - private sealed class WindingRayComparer : IComparer - { - /// The shared stateless comparer. - public static readonly WindingRayComparer Instance = new(); - - /// - public int Compare(WindingEdge? x, WindingEdge? y) - { - double cross = Vertex.Cross(x!.SourceEnd - x.Start, y!.SourceEnd - y.Start); - return cross > 0 ? -1 : cross < 0 ? 1 : 0; - } - } - - /// Orders contribution endpoints within a coincident bundle. - private sealed class WindingPointComparer : IComparer - { - /// The shared stateless comparer. - public static readonly WindingPointComparer Instance = new(); - - /// - public int Compare(Vertex x, Vertex y) => ComparePoints(x, y); - } -} diff --git a/src/PolygonClipper/PolygonClipper.cs b/src/PolygonClipper/PolygonClipper.cs index 8e1d6eb..b065be1 100644 --- a/src/PolygonClipper/PolygonClipper.cs +++ b/src/PolygonClipper/PolygonClipper.cs @@ -1,43 +1,36 @@ // Copyright (c) Six Labors. // Licensed under the Six Labors Split License. -using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; namespace SixLabors.PolygonClipper; /// -/// Performs boolean operations on polygons. +/// Performs Boolean operations on the filled areas of directed contours. /// /// /// -/// This implementation follows the algorithm described in -/// "A Simple Algorithm for Boolean Operations on Polygons" by Francisco Martínez, -/// Carlos Ogayar, Juan R. Jiménez, and Antonio J. Rueda. -/// It supports intersection, union, difference, and symmetric difference (XOR). +/// Intersection, union, difference, and exclusive-or interpret the original contour directions using the selected fill rules. +/// Input vertices and hierarchy are not modified. Results own their contour data. /// /// -/// It uses a sweep-line with an event queue to process segment intersections and robustly -/// handles special cases, including overlapping edges and trivial non-overlapping inputs. +/// Instance members are not thread-safe for concurrent use. /// /// -/// The static boolean methods are the recommended entry points. They route work through -/// an internal thread-local pool of reusable clipper instances and automatically reset -/// temporary state between calls. +/// Fill rules interpret the input contours. Output uses positive orientation regardless of the input rules: +/// counterclockwise exteriors and islands, and clockwise holes in Cartesian coordinates. +/// Use NonZero, EvenOdd, or Positive filling to reuse that resolved area. +/// Contours use implicit closure without a repeated closing vertex. /// /// -/// Instance members are not thread-safe for concurrent use. +/// Unary union and Normalize return full containment hierarchies. Binary operations group each exterior contour with its holes. +/// +/// +/// Coordinates must be finite. Only coordinates used by an operation are validated. +/// Intersection with an empty operand returns before inspecting the other operand's coordinates. /// -/// The high-level workflow has three stages: -/// -/// Preprocessing: Handles trivial operations and prepares segments for processing. -/// Sweeping: Processes events using a priority queue, handling segment insertions and removals. -/// Connecting edges: Constructs the resulting polygon by connecting valid segments. -/// /// -public partial class PolygonClipper +public class PolygonClipper { // Keep a small per-thread hot set of clipper instances. Depth 4 covers common // burst usage without retaining many heavyweight buffers per thread. @@ -47,86 +40,485 @@ public partial class PolygonClipper // 131_072 (~128K) keeps normal workloads warm while dropping pathological runs. private const int MaxRetainedEventCapacityScore = 131_072; + private static readonly Polygon EmptyFillOperand = []; + [ThreadStatic] private static Stack? clipperPool; - private readonly SweepEventComparer comparer = new(); - private readonly List unorderedEventQueue = []; + private readonly SweepEventComparer comparer = SweepEventComparer.Instance; private readonly SweepEventPoolList sortedEvents = []; private readonly StatusLine statusLine = new(); + private readonly List eventStorage = []; + private readonly StablePriorityQueue events; + private readonly SweepEventPoolList segments = []; + private readonly StatusLine activeResult = new(); + private readonly List outgoing = []; + private readonly List bundled = []; + private readonly List pendingBoundaries = []; + private readonly Stack> endpointQueues = new(); + private int retainedEndpointCapacity; + private Polygon? subject; private Polygon? clipping; private BooleanOperation operation; + private ContourOutput contourOutput; + private FillRule subjectFillRule; + private FillRule clipFillRule; /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class with independent operand fill rules. /// - /// The polygon used as the left-hand operand. - /// The polygon used as the right-hand operand. - /// The boolean operation to execute. - /// - /// This constructor is intended for advanced/manual execution flows. - /// For typical usage, prefer the static methods to take advantage of - /// internal pooling and automatic lifecycle management. - /// - public PolygonClipper(Polygon subject, Polygon clip, BooleanOperation operation) - => this.Configure(subject, clip, operation); + /// The left-hand operand. + /// The right-hand operand. + /// The Boolean operation. + /// The rule interpreting the subject's directed contours. + /// The rule interpreting the clipping operand's directed contours. + public PolygonClipper(Polygon subject, Polygon clip, BooleanOperation operation, FillRule subjectFillRule, FillRule clipFillRule) + : this() + { + ValidateFillArguments(subject, clip, operation, subjectFillRule, clipFillRule); + this.Configure(subject, clip, operation, subjectFillRule, clipFillRule); + } + /// + /// Initializes a new instance of the class for pooled execution. + /// private PolygonClipper() + => this.events = new(this.comparer, this.eventStorage); + + /// + /// Specifies the form of returned contours. + /// + private enum ContourOutput { + /// + /// Groups exterior contours with their holes. + /// + Grouped, + + /// + /// Preserves every immediate owner in a nesting chain. + /// + Nested } /// - /// Computes the intersection of two polygons. + /// Intersects two filled areas using a common fill rule. + /// + /// The left-hand operand. + /// The right-hand operand. + /// The rule interpreting both operands. + /// The filled area common to both operands. + public static Polygon Intersection(Polygon subject, Polygon clip, FillRule fillRule) + => Intersection(subject, clip, fillRule, fillRule); + + /// + /// Intersects two filled areas using independent fill rules. + /// + /// The left-hand operand. + /// The right-hand operand. + /// The subject's fill rule. + /// The clipping operand's fill rule. + /// The filled area common to both operands. + public static Polygon Intersection(Polygon subject, Polygon clip, FillRule subjectFillRule, FillRule clipFillRule) + => ExecuteFillOperation(subject, clip, BooleanOperation.Intersection, subjectFillRule, clipFillRule, ContourOutput.Grouped); + + /// + /// Unites two filled areas using a common fill rule. + /// + /// The left-hand operand. + /// The right-hand operand. + /// The rule interpreting both operands. + /// The filled area belonging to either operand. + public static Polygon Union(Polygon subject, Polygon clip, FillRule fillRule) + => Union(subject, clip, fillRule, fillRule); + + /// + /// Unites two filled areas using independent fill rules. + /// + /// The left-hand operand. + /// The right-hand operand. + /// The subject's fill rule. + /// The clipping operand's fill rule. + /// The filled area belonging to either operand. + public static Polygon Union(Polygon subject, Polygon clip, FillRule subjectFillRule, FillRule clipFillRule) + => ExecuteFillOperation(subject, clip, BooleanOperation.Union, subjectFillRule, clipFillRule, ContourOutput.Grouped); + + /// + /// Resolves directed contours into their filled area. + /// + /// The raw directed contours. + /// The rule interpreting the contours. + /// The resolved filled area with the full containment hierarchy, without changing the input contours. + /// Input hierarchy does not override contour direction or the selected fill rule. + public static Polygon Union(Polygon polygon, FillRule fillRule) + => ExecuteFillOperation(polygon, EmptyFillOperand, BooleanOperation.Union, fillRule, FillRule.EvenOdd, ContourOutput.Nested); + + /// + /// Subtracts one filled area from another using a common fill rule. + /// + /// The area to retain. + /// The area to subtract. + /// The rule interpreting both operands. + /// The subject area outside the clipping operand. + public static Polygon Difference(Polygon subject, Polygon clip, FillRule fillRule) + => Difference(subject, clip, fillRule, fillRule); + + /// + /// Subtracts one filled area from another using independent fill rules. + /// + /// The area to retain. + /// The area to subtract. + /// The subject's fill rule. + /// The clipping operand's fill rule. + /// The subject area outside the clipping operand. + public static Polygon Difference(Polygon subject, Polygon clip, FillRule subjectFillRule, FillRule clipFillRule) + => ExecuteFillOperation(subject, clip, BooleanOperation.Difference, subjectFillRule, clipFillRule, ContourOutput.Grouped); + + /// + /// Computes exclusive filled coverage using a common fill rule. + /// + /// The left-hand operand. + /// The right-hand operand. + /// The rule interpreting both operands. + /// The filled area belonging to exactly one operand. + public static Polygon Xor(Polygon subject, Polygon clip, FillRule fillRule) + => Xor(subject, clip, fillRule, fillRule); + + /// + /// Computes exclusive filled coverage using independent fill rules. + /// + /// The left-hand operand. + /// The right-hand operand. + /// The subject's fill rule. + /// The clipping operand's fill rule. + /// The filled area belonging to exactly one operand. + public static Polygon Xor(Polygon subject, Polygon clip, FillRule subjectFillRule, FillRule clipFillRule) + => ExecuteFillOperation(subject, clip, BooleanOperation.Xor, subjectFillRule, clipFillRule, ContourOutput.Grouped); + + /// + /// Resolves self-intersections and overlaps using the specified fill rule. /// - /// The polygon used as the left-hand operand. - /// The polygon used as the right-hand operand. - /// A polygon containing regions common to both inputs. - /// Preferred entry point. Uses internal thread-local reusable instances. - public static Polygon Intersection(Polygon subject, Polygon clip) + /// The source contours. Their vertices and directions are not modified. + /// The rule that determines the source polygon's filled area. + /// + /// The same cleanup as unary union, with closed contours and their full containment hierarchy. + /// Exterior contours and islands are counterclockwise. Holes are clockwise. + /// The first vertex is not repeated at the end of a contour. + /// + /// + /// The fill rule interprets the input. Output orientation is positive even when the input rule is Negative. + /// Use NonZero, EvenOdd, or Positive filling when reusing the cleaned polygon. + /// + public static Polygon Normalize(Polygon polygon, FillRule fillRule) + => Union(polygon, fillRule); + + /// + /// Executes the configured Boolean operation using the operand fill rules. + /// + /// The connected filled boundaries. + /// Instance execution is not thread-safe for concurrent use. + public Polygon Run() { - PolygonClipper clipper = Rent(subject, clip, BooleanOperation.Intersection); - try + Polygon subject = this.subject!; + Polygon clip = this.clipping!; + BooleanOperation operation = this.operation; + FillRule subjectRule = this.subjectFillRule; + FillRule clipRule = this.clipFillRule; + SweepEventPoolList resultEvents = this.sortedEvents; + SweepEventComparer resultComparer = this.comparer; + resultEvents.Clear(); + + this.ResetSweep(); + if (operation == BooleanOperation.Intersection && (subject.Count == 0 || clip.Count == 0)) { - return clipper.Run(); + return []; } - finally + + // Reuse the existing capacity APIs and reserve source-sized storage + // before ingestion. Repeated geometric growth otherwise copies the + // larger endpoint records and can exceed the shared retention bound. + int vertexCount = subject.VertexCount + clip.VertexCount; + this.eventStorage.EnsureCapacity(vertexCount); + this.segments.EnsureCapacity(vertexCount); + resultEvents.EnsureCapacity(vertexCount * 2); + + Box2 subjectBounds = this.ProcessSegments(subject, true); + Box2 clipBounds = this.ProcessSegments(clip, false); + if (operation == BooleanOperation.Intersection && !subjectBounds.Intersects(clipBounds)) { - Return(clipper); + return []; } - } - /// - /// Computes the union of two polygons. - /// - /// The polygon used as the left-hand operand. - /// The polygon used as the right-hand operand. - /// A polygon containing regions from either input. - /// Preferred entry point. Uses internal thread-local reusable instances. - public static Polygon Union(Polygon subject, Polygon clip) - { - PolygonClipper clipper = Rent(subject, clip, BooleanOperation.Union); - try + double stopX = operation switch { - return clipper.Run(); + BooleanOperation.Intersection => Math.Min(subjectBounds.Max.X, clipBounds.Max.X), + BooleanOperation.Difference => subjectBounds.Max.X, + _ => double.PositiveInfinity + }; + + this.events.Heapify(); + + while (this.events.Count > 0) + { + // Bounds exclude any further filled result. Finish active boundaries + // first because an ordering repair can move their endpoint by one ULP. + if (this.events.Peek().Point.X > stopX && this.activeResult.Count == 0) + { + break; + } + + QueueEntry next = this.events.Dequeue(); + if (!next.IsValid) + { + continue; + } + + Vertex point = next.Point; + bool sourcePoint = next.IsStart || point == next.Edge.SourceEnd; + this.outgoing.Clear(); + this.pendingBoundaries.Clear(); + int firstEnd = int.MaxValue; + int lastEnd = -1; + if (next.IsStart) + { + this.outgoing.Add(next.Edge); + } + else + { + firstEnd = lastEnd = next.Edge.PosSL; + } + + // A vertex is a transaction, not a sequence of parity toggles. + // Collect every start/end at this exact lexicographic point. + while (this.events.Count > 0 && this.events.Peek().Point == point) + { + next = this.events.Dequeue(); + if (next.IsValid && (next.IsStart || point == next.Edge.SourceEnd)) + { + sourcePoint = true; + } + + if (next.IsValid && next.IsStart) + { + this.outgoing.Add(next.Edge); + } + else if (next.IsValid) + { + firstEnd = Math.Min(firstEnd, next.Edge.PosSL); + lastEnd = Math.Max(lastEnd, next.Edge.PosSL); + } + } + + int first = lastEnd < 0 ? this.statusLine.FindLower(point) : firstEnd; + while (first > 0 && this.statusLine[first - 1].ContainsPoint(point)) + { + first--; + } + + int after = Math.Max(first, lastEnd + 1); + while (after < this.statusLine.Count && this.statusLine[after].ContainsPoint(point)) + { + after++; + } + + // The result index is a filtered view of the very same block. + // Derive removals from the owned interval identities, so rounded + // incidence tests cannot remove a boundary independently of its + // source interval and leave a stale birth context behind. + int firstResult = first == 0 ? 0 : this.statusLine[first - 1].ResultRank; + int afterResult = firstResult; + for (int i = first; i < after; i++) + { + SweepEvent incoming = this.statusLine[i]; + if (incoming.Boundary is not null) + { + afterResult++; + } + } + + // The surviving lower interval is outside the changed block. + // Closure conserves the sum of signed contributions, so its + // prefix and every surviving prefix above the block stay valid. + for (int i = first; i < after; i++) + { + this.StageIncoming(this.statusLine[i], point); + } + + this.statusLine.RemoveRange(first, after - first); + this.activeResult.RemoveRange(firstResult, afterResult - firstResult); + + while (true) + { + this.outgoing.Sort(SegmentComparer.CompareRays); + this.BundleOutgoing(); + for (int i = 0; i < this.bundled.Count; i++) + { + SweepEvent edge = this.bundled[i]; + edge.Active = true; + this.statusLine.Insert(first + i, edge); + } + + // Rounded intersections can equal this point even when the + // incidence predicate missed a neighboring interval. Absorb it + // before committing winding or immutable boundary history. + bool lowerIncident = this.PossibleIntersection(first - 1, first, point, sourcePoint); + bool upperIncident = this.bundled.Count == 0 + ? lowerIncident + : !lowerIncident && this.PossibleIntersection(first + this.bundled.Count - 1, first + this.bundled.Count, point, sourcePoint); + if (!lowerIncident && !upperIncident) + { + break; + } + + this.statusLine.RemoveRange(first, this.bundled.Count); + this.outgoing.Clear(); + this.outgoing.AddRange(this.bundled); + foreach (SweepEvent edge in this.outgoing) + { + // Rebundling can replace a representative. Invalidate any + // future endpoint queued while checking the staged block. + edge.Active = false; + edge.Version++; + } + + if (lowerIncident) + { + SweepEvent incoming = this.statusLine[--first]; + if (incoming.Boundary is not null) + { + this.activeResult.RemoveAt(--firstResult); + } + + this.statusLine.RemoveAt(first); + this.StageIncoming(incoming, point); + } + + if (upperIncident) + { + SweepEvent incoming = this.statusLine[first]; + if (incoming.Boundary is not null) + { + this.activeResult.RemoveAt(firstResult); + } + + this.statusLine.RemoveAt(first); + this.StageIncoming(incoming, point); + } + } + + foreach (SweepEvent boundary in this.pendingBoundaries) + { + // The point is closed. Complete each historical piece without + // changing its original transition or predecessor. + SweepEvent right = resultEvents.Add(point, false, boundary, ResultTransition.Neutral, null!, boundary.ContourId); + boundary.OtherEvent = right; + } + + WindingCount winding = first == 0 ? default : this.statusLine[first - 1].Above; + SweepEvent? previousBoundary = firstResult == 0 ? null : this.activeResult[firstResult - 1].Boundary; + if (firstResult > 0 && this.activeResult[firstResult - 1].Point.X == this.activeResult[firstResult - 1].End.X) + { + previousBoundary = previousBoundary!.PrevInResult; + } + + int resultIndex = firstResult; + for (int i = 0; i < this.bundled.Count; i++) + { + SweepEvent edge = this.bundled[i]; + bool below = InResult(winding, operation, subjectRule, clipRule); + winding = winding.Add(edge.Delta); + edge.Above = winding; + bool above = InResult(winding, operation, subjectRule, clipRule); + if (below != above) + { + // Endpoint pairing is completed when the interval ends. + // No geometry consumer reads this event until connection. + edge.Boundary = resultEvents.Add( + point, + true, + null!, + above ? ResultTransition.Contributing : ResultTransition.NonContributing, + previousBoundary!, + edge.ContourId); + + if (edge.Point.X != edge.End.X) + { + previousBoundary = edge.Boundary; + } + + this.activeResult.Insert(resultIndex++, edge); + } + + this.events.Enqueue(new QueueEntry(edge.End, edge, false)); + } + + // List insertion/removal already shifts this suffix. Keep the + // endpoint anchors and filtered-boundary ranks in the same order. + // Winding counts above the changed block do not need recomputing. + int resultRank = firstResult; + for (int i = first; i < this.statusLine.Count; i++) + { + SweepEvent edge = this.statusLine[i]; + edge.PosSL = i; + if (edge.Boundary is not null) + { + resultRank++; + } + + edge.ResultRank = resultRank; + } } - finally + + // Boundary events are completed at their right endpoints. Restore the + // ordering expected by the existing connector in O(B log B), rather + // than making its nearly-sorted repair loop sort reversed history. + resultEvents.Sort(resultComparer); + Polygon result = this.ConnectEdges(resultEvents); + for (int i = 0; i < result.Count; i++) { - Return(clipper); + Contour contour = result[i]; + if (contour.Count > 1 && contour[0] == contour[^1]) + { + contour.RemoveVertexAt(contour.Count - 1); + } + + if ((contour.Depth & 1) == 0) + { + contour.SetCounterClockwise(); + } + else + { + contour.SetClockwise(); + } } + + return result; } /// - /// Computes the difference of two polygons ( minus ). + /// Executes an explicit fill-rule operation through the existing clipper pool. /// - /// The polygon used as the left-hand operand. - /// The polygon used as the right-hand operand. - /// A polygon containing regions from not covered by . - /// Preferred entry point. Uses internal thread-local reusable instances. - public static Polygon Difference(Polygon subject, Polygon clip) + /// The left-hand operand. + /// The right-hand operand. + /// The Boolean operation. + /// The subject's fill rule. + /// The clipping operand's fill rule. + /// The requested contour hierarchy. + /// The resolved filled area. + private static Polygon ExecuteFillOperation( + Polygon subject, + Polygon clip, + BooleanOperation operation, + FillRule subjectRule, + FillRule clipRule, + ContourOutput output) { - PolygonClipper clipper = Rent(subject, clip, BooleanOperation.Difference); + ValidateFillArguments(subject, clip, operation, subjectRule, clipRule); + PolygonClipper clipper = Rent(subject, clip, operation, subjectRule, clipRule); + clipper.contourOutput = output; + try { return clipper.Run(); @@ -138,60 +530,60 @@ public static Polygon Difference(Polygon subject, Polygon clip) } /// - /// Computes the symmetric difference (XOR) of two polygons. + /// Validates public operation arguments before taking geometry shortcuts. /// - /// The polygon used as the left-hand operand. - /// The polygon used as the right-hand operand. - /// A polygon containing regions that belong to exactly one input. - /// Preferred entry point. Uses internal thread-local reusable instances. - public static Polygon Xor(Polygon subject, Polygon clip) + /// The left-hand operand. + /// The right-hand operand. + /// The Boolean operation. + /// The subject's fill rule. + /// The clipping operand's fill rule. + private static void ValidateFillArguments(Polygon subject, Polygon clip, BooleanOperation operation, FillRule subjectRule, FillRule clipRule) { - PolygonClipper clipper = Rent(subject, clip, BooleanOperation.Xor); - try - { - return clipper.Run(); - } - finally - { - Return(clipper); - } + ArgumentNullException.ThrowIfNull(subject); + ArgumentNullException.ThrowIfNull(clip); + ArgumentOutOfRangeException.ThrowIfGreaterThan((uint)operation, (uint)BooleanOperation.Xor, nameof(operation)); + ArgumentOutOfRangeException.ThrowIfGreaterThan((uint)subjectRule, (uint)FillRule.Negative, nameof(subjectRule)); + ArgumentOutOfRangeException.ThrowIfGreaterThan((uint)clipRule, (uint)FillRule.Negative, nameof(clipRule)); } /// - /// Normalizes a polygon by resolving self-intersections and overlaps. + /// Acquires an instance configured for this operation and both operand rules. /// - /// The polygon to process. - /// - /// A new normalized polygon. Output contours are implicitly closed - /// (no duplicated terminal closing vertex is appended). - /// - /// Preferred entry point. Uses internal thread-local reusable builders. - public static Polygon Normalize(Polygon polygon) - => SelfIntersectionRemover.Process(polygon); - + /// The subject contours. + /// The clipping contours. + /// The Boolean operation. + /// The subject fill rule. + /// The clipping fill rule. + /// The clipper configured for this operation. [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static PolygonClipper Rent(Polygon subject, Polygon clip, BooleanOperation operation) + private static PolygonClipper Rent(Polygon subject, Polygon clip, BooleanOperation operation, FillRule subjectRule, FillRule clipRule) { Stack? pool = clipperPool; if (pool != null && pool.Count > 0) { PolygonClipper clipper = pool.Pop(); - clipper.Configure(subject, clip, operation); + clipper.Configure(subject, clip, operation, subjectRule, clipRule); return clipper; } - return new PolygonClipper(subject, clip, operation); + // The public entry point already validated these arguments. Configure the + // private instance directly so a cold pool does not validate them twice. + PolygonClipper created = new(); + created.Configure(subject, clip, operation, subjectRule, clipRule); + return created; } + /// + /// Releases operation references and retains only bounded reusable state. + /// + /// The completed clipping instance. [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void Return(PolygonClipper clipper) { clipper.subject = null; clipper.clipping = null; - clipper.unorderedEventQueue.Clear(); clipper.sortedEvents.Clear(); - clipper.statusLine.Reset(0); - clipper.windingSweep?.Reset(); + clipper.ResetSweep(); // Avoid keeping very large event buffers alive in thread-static pools. if (clipper.GetRetainedEventCapacityScore() > MaxRetainedEventCapacityScore) @@ -206,771 +598,472 @@ private static void Return(PolygonClipper clipper) } } + /// + /// Configures the inputs and fill rules before any event is created. + /// + /// The subject contours. + /// The clipping contours. + /// The Boolean operation. + /// The subject fill rule. + /// The clipping fill rule. [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void Configure(Polygon subject, Polygon clip, BooleanOperation operation) + private void Configure(Polygon subject, Polygon clip, BooleanOperation operation, FillRule subjectRule, FillRule clipRule) { this.subject = subject; this.clipping = clip; this.operation = operation; - this.useFillRules = false; + this.contourOutput = ContourOutput.Grouped; + this.subjectFillRule = subjectRule; + this.clipFillRule = clipRule; } + /// + /// Gets the combined retained event and status capacities. + /// + /// The total capacity retained by the clipping buffers. [MethodImpl(MethodImplOptions.AggressiveInlining)] private int GetRetainedEventCapacityScore() - => this.unorderedEventQueue.Capacity + this.sortedEvents.Capacity + this.statusLine.RetainedCapacity + - (this.windingSweep?.RetainedCapacity ?? 0); + => this.sortedEvents.Capacity + this.eventStorage.Capacity + this.segments.Capacity + this.statusLine.RetainedCapacity + + this.activeResult.RetainedCapacity + this.outgoing.Capacity + this.bundled.Capacity + + this.pendingBoundaries.Capacity + this.retainedEndpointCapacity; /// - /// Executes the configured boolean operation for the current subject and clipping polygons. + /// Counts the edges of an implicitly closed filled boundary. /// - /// The operation result. - /// Instance execution is not thread-safe for concurrent use. - public Polygon Run() + /// The contour to inspect. + /// The number of segments to iterate. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static int GetContourSegmentCount(Contour contour) { - // Compute bounding boxes for optimization steps 1 and 2 - Polygon subject = this.subject ?? throw new InvalidOperationException("Polygon clipper subject is not configured."); - Polygon clipping = this.clipping ?? throw new InvalidOperationException("Polygon clipper clipping polygon is not configured."); - BooleanOperation operation = this.operation; - - if (this.useFillRules) - { - this.sortedEvents.Clear(); - WindingSweep sweep = this.windingSweep ??= new WindingSweep(); - return sweep.Run(subject, clipping, operation, this.subjectFillRule, this.clipFillRule, this.sortedEvents, this.comparer); - } - - // Check for trivial cases that can be resolved without sweeping - if (TryTrivialOperationForEmptyPolygons(subject, clipping, operation, out Polygon? result)) - { - return result; - } - - // Process all segments in the subject polygon - Vertex min = new(double.PositiveInfinity); - Vertex max = new(double.NegativeInfinity); - - // Estimate the total number of sweep events. - // Each segment contributes two events (left/right endpoints), - // and subdivision during intersection may increase the count, - // so we conservatively double the total vertex count. - int subjectVertexCount = subject.VertexCount; - int clippingVertexCount = clipping.VertexCount; - int eventCount = (subjectVertexCount + clippingVertexCount) * 2; - - SweepEventComparer comparer = this.comparer; - List unorderedEventQueue = this.unorderedEventQueue; - unorderedEventQueue.Clear(); - if (eventCount > unorderedEventQueue.Capacity) - { - unorderedEventQueue.EnsureCapacity(eventCount); - } - - int contourId = 0; - - for (int i = 0; i < subject.Count; i++) + int count = contour.Count; + if (count < 3) { - Contour contour = subject[i]; - contourId++; - int segmentCount = GetContourSegmentCount(contour); - for (int j = 0; j < segmentCount; j++) - { - ProcessSegment( - contourId, - contour.GetSegment(j), - PolygonType.Subject, - unorderedEventQueue, - comparer, - ref min, - ref max); - } + return 0; } - Box2 subjectBB = new(min, max); + return contour[0] == contour[^1] ? count - 1 : count; + } - // Process all segments in the clipping polygon - min = new Vertex(double.PositiveInfinity); - max = new Vertex(double.NegativeInfinity); - for (int i = 0; i < clipping.Count; i++) + /// + /// Releases per-operation references while retaining bounded scratch storage. + /// + private void ResetSweep() + { + this.eventStorage.Clear(); + this.statusLine.Reset(0); + this.activeResult.Reset(0); + this.outgoing.Clear(); + this.bundled.Clear(); + this.pendingBoundaries.Clear(); + for (int i = 0; i < this.segments.Count; i++) { - Contour contour = clipping[i]; - - int segmentCount = GetContourSegmentCount(contour); - for (int j = 0; j < segmentCount; j++) + if (this.segments[i].Ends is PriorityQueue ends) { - ProcessSegment( - contourId, - contour.GetSegment(j), - PolygonType.Clipping, - unorderedEventQueue, - comparer, - ref min, - ref max); + this.ReturnEndpoints(ends); } - } - Box2 clippingBB = new(min, max); - if (TryTrivialOperationForNonOverlappingBoundingBoxes(subject, clipping, subjectBB, clippingBB, operation, out result)) - { - return result; + this.segments[i].Ends = null; + this.segments[i].Boundary = null; } - // Sweep line algorithm: process events in the priority queue - StablePriorityQueue eventQueue = new(comparer, unorderedEventQueue); - SweepEventPoolList sortedEvents = this.sortedEvents; - sortedEvents.Clear(); - if (eventCount > sortedEvents.Capacity) - { - sortedEvents.EnsureCapacity(eventCount); - } + this.segments.Clear(); + } - // Heuristic capacity for the sweep line status structure. - // At any given point during the sweep, only a subset of segments - // are active, so we preallocate half the subject's vertex count - // to reduce resizing without overcommitting memory. - StatusLine statusLine = this.statusLine; - statusLine.Reset(subjectVertexCount >> 1); - double subjectMaxX = subjectBB.Max.X; - double minMaxX = Vertex.Min(subjectBB.Max, clippingBB.Max).X; - - SweepEvent? prevEvent; - SweepEvent? nextEvent; - Span workspace = new SweepEvent[4]; - while (eventQueue.Count > 0) + /// + /// Adds directed input segments without normalizing or reorienting them. + /// + /// The input contours. + /// Whether these contours belong to the subject. + /// The bounds collected during the existing input traversal. + private Box2 ProcessSegments(Polygon polygon, bool subject) + { + Box2 bounds = Box2.Invalid; + for (int i = 0; i < polygon.Count; i++) { - SweepEvent sweepEvent = eventQueue.Dequeue(); - sortedEvents.Add(sweepEvent); - - // Optimization: skip further processing if intersection is impossible - if ((operation == BooleanOperation.Intersection && sweepEvent.Point.X > minMaxX) || - (operation == BooleanOperation.Difference && sweepEvent.Point.X > subjectMaxX)) + Contour contour = polygon[i]; + int count = GetContourSegmentCount(contour); + if (count == 0) { - return ConnectEdges(sortedEvents, comparer); + // These external contours have no closed segments to process. + continue; } - if (sweepEvent.Left) + for (int j = 0; j < count; j++) { - // Insert the event into the status line and get neighbors - int it = statusLine.Add(sweepEvent); - prevEvent = statusLine.Prev(it); - nextEvent = statusLine.Next(it); - - // Compute fields for the current event - ComputeFields(sweepEvent, prevEvent, operation); - - // Check intersection with the next neighbor - if (nextEvent != null) + Segment segment = contour.GetSegment(j); + Vertex start = segment.Source; + Vertex end = segment.Target; + if (!double.IsFinite(start.X) || !double.IsFinite(start.Y)) { - // Check intersection with the next neighbor - if (PossibleIntersection(sweepEvent, nextEvent, eventQueue, workspace) == 2) - { - ComputeFields(sweepEvent, prevEvent, operation); - ComputeFields(nextEvent, sweepEvent, operation); - } + throw new ArgumentException("Polygon coordinates must be finite.", nameof(polygon)); } - // Check intersection with the previous neighbor - if (prevEvent != null) + bounds = bounds.Add(new Box2(start)); + if (start == end) { - // Check intersection with the previous neighbor - if (PossibleIntersection(prevEvent, sweepEvent, eventQueue, workspace) == 2) - { - int prevIndex = statusLine.IndexOf(prevEvent); - SweepEvent? prevPrevEvent = statusLine.Prev(prevIndex); - ComputeFields(prevEvent, prevPrevEvent, operation); - ComputeFields(sweepEvent, prevEvent, operation); - } + continue; } - } - else - { - // Remove the event from the status line - sweepEvent = sweepEvent.OtherEvent; - int it = statusLine.IndexOf(sweepEvent); - prevEvent = statusLine.Prev(it); - nextEvent = statusLine.Next(it); - - // Check intersection between neighbors - if (prevEvent != null && nextEvent != null) + + int direction = 1; + if (SweepEventComparer.Instance.Compare(start, end) > 0) { - _ = PossibleIntersection(prevEvent, nextEvent, eventQueue, workspace); + (start, end) = (end, start); + direction = -1; } - statusLine.RemoveAt(it); + // Lexicographic direction is the formal x+epsilon*y sweep + // direction, including vertical source segments. Epsilon is + // never evaluated or applied to the stored double coordinates. + WindingCount delta = subject ? new(direction, 0) : new(0, direction); + SweepEvent edge = this.segments.Add(start, end, delta); + this.eventStorage.Add(new QueueEntry(start, edge, true)); } } - // Connect edges after processing all events - return ConnectEdges(sortedEvents, comparer); + return bounds; } /// - /// Gets the number of edges to process for a contour, treating non-closed rings as implicitly closed. + /// Removes an incoming interval while retaining its history until the point is closed. /// - /// The contour to inspect. - /// The number of segments to iterate. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static int GetContourSegmentCount(Contour contour) + /// The incident active interval. + /// The staged event point. + private void StageIncoming(SweepEvent incoming, Vertex point) { - int count = contour.Count; - if (count < 3) + incoming.Active = false; + incoming.Version++; + if (incoming.Boundary is SweepEvent boundary) { - return 0; + this.pendingBoundaries.Add(boundary); } - return contour[0] == contour[^1] ? count - 1 : count; + this.ContinueAt(incoming, point); } /// - /// Checks if the boolean operation is trivial due to one polygon having zero contours - /// and sets the result accordingly. + /// Preserves a split interval's longer source tails and endpoint deltas. /// - /// The subject polygon. - /// The clipping polygon. - /// The boolean operation being performed. - /// The resulting polygon if the operation is trivial. - /// - /// if the operation results in a trivial case due to zero contours; - /// otherwise, . - /// - private static bool TryTrivialOperationForEmptyPolygons( - Polygon subject, - Polygon clipping, - BooleanOperation operation, - [NotNullWhen(true)] out Polygon? result) + /// The interval ending at this point. + /// The complete event point. + private void ContinueAt(SweepEvent incoming, Vertex point) { - result = null; - - if (subject.Count * clipping.Count == 0) + if (incoming.Ends is PriorityQueue ends) { - if (operation == BooleanOperation.Intersection) + WindingCount delta = incoming.Delta; + while (ends.TryPeek(out WindingCount ending, out Vertex endpoint) && endpoint == point) { - result = []; - return true; + delta = delta.Subtract(ending); + ends.Dequeue(); } - if (operation == BooleanOperation.Difference) + if (ends.Count == 0) { - result = subject.DeepClone(); - return true; + incoming.Ends = null; + this.ReturnEndpoints(ends); + return; } - if (operation is BooleanOperation.Union or BooleanOperation.Xor) - { - result = subject.Count == 0 ? clipping.DeepClone() : subject.DeepClone(); - return true; - } + incoming.Delta = delta; + incoming.SourceEnd = FirstEndpoint(ends); + } + else if (SweepEventComparer.Instance.Compare(point, incoming.SourceEnd) >= 0) + { + return; } - return false; + // Output history owns independent SweepEvent objects. Reuse only the + // live interval, whose version was advanced before closing its old + // piece. Stale queue records stay invalid without retaining a new + // interval object for every intersection in the operation. + incoming.Point = point; + incoming.End = incoming.SourceEnd; + incoming.Boundary = null; + this.outgoing.Add(incoming); } /// - /// Checks if the boolean operation is trivial due to non-overlapping bounding boxes - /// and sets the result accordingly. + /// Combines coincident outgoing intervals without losing longer continuations. /// - /// The subject polygon. - /// The clipping polygon. - /// The bounding box of the subject polygon. - /// The bounding box of the clipping polygon. - /// The boolean operation being performed. - /// The resulting polygon if the operation is trivial. - /// - /// if the operation results in a trivial case due to non-overlapping - /// bounding boxes; otherwise, . - /// - private static bool TryTrivialOperationForNonOverlappingBoundingBoxes( - Polygon subject, - Polygon clipping, - Box2 subjectBB, - Box2 clippingBB, - BooleanOperation operation, - [NotNullWhen(true)] out Polygon? result) + private void BundleOutgoing() { - result = null; - - if (subjectBB.Min.X > clippingBB.Max.X || clippingBB.Min.X > subjectBB.Max.X || - subjectBB.Min.Y > clippingBB.Max.Y || clippingBB.Min.Y > subjectBB.Max.Y) + this.bundled.Clear(); + int i = 0; + while (i < this.outgoing.Count) { - if (operation == BooleanOperation.Intersection) + SweepEvent edge = this.outgoing[i++]; + while (i < this.outgoing.Count && SegmentComparer.CompareRays(edge, this.outgoing[i]) == 0) { - result = []; - return true; + SweepEvent other = this.outgoing[i++]; + if (SweepEventComparer.Instance.Compare(other.End, edge.End) < 0) + { + // A staged neighbor check may already have found an earlier + // crossing. Keep that node when rebuilding a coincident bundle. + edge.End = other.End; + } + + // A bundle may outlive its representative's original segment. + // Its support must cover every retained endpoint-ledger tail. + if (SweepEventComparer.Instance.Compare(other.Support.Target, edge.Support.Target) > 0) + { + edge.Support = new Segment(edge.Support.Source, other.Support.Target); + } + + if (edge.Ends is null && other.Ends is null && edge.SourceEnd == other.SourceEnd) + { + // The common duplicate-edge case needs no endpoint ledger. + edge.Delta = edge.Delta.Add(other.Delta); + continue; + } + + if (edge.Ends is null) + { + edge.Ends = this.RentEndpoints(); + if (!edge.Delta.IsZero) + { + edge.Ends.Enqueue(edge.Delta, edge.SourceEnd); + } + } + + PriorityQueue ends = edge.Ends; + if (other.Ends is PriorityQueue otherEnds) + { + foreach ((WindingCount delta, Vertex endpoint) in otherEnds.UnorderedItems) + { + ends.Enqueue(delta, endpoint); + } + + other.Ends = null; + this.ReturnEndpoints(otherEnds); + } + else if (!other.Delta.IsZero) + { + ends.Enqueue(other.Delta, other.SourceEnd); + } + + edge.Delta = edge.Delta.Add(other.Delta); } - // The bounding boxes do not overlap - if (operation == BooleanOperation.Difference) + if (edge.Ends is PriorityQueue ledger) { - result = subject.DeepClone(); - return true; - } + if (ledger.Count == 0) + { + edge.Ends = null; + this.ReturnEndpoints(ledger); + continue; + } - if (operation is BooleanOperation.Union or BooleanOperation.Xor) + edge.SourceEnd = FirstEndpoint(ledger); + if (SweepEventComparer.Instance.Compare(edge.SourceEnd, edge.End) < 0) + { + edge.End = edge.SourceEnd; + } + } + else if (edge.Delta.IsZero) { - result = new Polygon(subject.Count + clipping.Count); - result.Join(subject.DeepClone()); - result.Join(clipping.DeepClone()); - return true; + continue; } - } - return false; + // A zero current sum with non-zero later endpoint changes must + // retain its continuation, even though it emits no boundary now. + this.bundled.Add(edge); + } } /// - /// Processes a segment by generating sweep events for its endpoints and adding them to the event queue. + /// Gets the earliest endpoint of a non-empty contribution queue. /// - /// The identifier of the contour to which the segment belongs. - /// The segment to process. - /// The polygon type to which the segment belongs. - /// The unordered event queue to add the generated events to. - /// The comparer used to determine the order of sweep events in the queue. - /// The minimum vertex of the bounding box. - /// The maximum vertex of the bounding box. - private static void ProcessSegment( - int contourId, - Segment s, - PolygonType pt, - List eventQueue, - SweepEventComparer comparer, - ref Vertex min, - ref Vertex max) + /// The non-empty endpoint queue. + /// The earliest endpoint. + private static Vertex FirstEndpoint(PriorityQueue ends) { - if (s.Source == s.Target) - { - // Skip degenerate zero-length segments. - return; - } - - // Create sweep events for the endpoints of the segment - SweepEvent e1 = new(s.Source, true, pt); - SweepEvent e2 = new(s.Target, true, e1, pt); - e1.OtherEvent = e2; - e1.ContourId = e2.ContourId = contourId; - - // Determine which endpoint is the left endpoint - if (comparer.Compare(e1, e2) < 0) - { - e2.Left = false; - } - else - { - e1.Left = false; - } - - min = Vertex.Min(min, s.Min); - max = Vertex.Max(max, s.Max); - - // Add the events to the event queue - eventQueue.Add(e1); - eventQueue.Add(e2); + ends.TryPeek(out _, out Vertex endpoint); + return endpoint; } /// - /// Computes fields for a given sweep event. + /// Rents endpoint storage without allocating tree nodes for each contribution. /// - /// The sweep event to compute fields for. - /// The the previous event in the status line. - /// The boolean operation being performed. - private static void ComputeFields(SweepEvent le, SweepEvent? prev, BooleanOperation operation) + /// An empty reusable priority queue. + private PriorityQueue RentEndpoints() { - // Compute inOut and otherInOut fields - if (prev == null) - { - le.InOut = false; - le.OtherInOut = true; - } - else if (le.PolygonType == prev.PolygonType) + if (this.endpointQueues.TryPop(out PriorityQueue? ends)) { - // Previous line segment in sl belongs to the same polygon that "se" belongs to. - le.InOut = !prev.InOut; - le.OtherInOut = prev.OtherInOut; - } - else - { - // Previous line segment in sl belongs to a different polygon that "se" belongs to. - le.InOut = !prev.OtherInOut; - le.OtherInOut = prev.IsVertical() ? !prev.InOut : prev.InOut; + this.retainedEndpointCapacity -= ends.EnsureCapacity(0); + return ends; } - // Compute PrevInResult field - if (prev != null) - { - le.PrevInResult = (!InResult(prev, operation) || prev.IsVertical()) - ? prev.PrevInResult - : prev; - } - - // Check if the line segment belongs to the Boolean operation - bool inResult = InResult(le, operation); - if (inResult) - { - le.ResultTransition = DetermineResultTransition(le, operation); - } - else - { - le.ResultTransition = ResultTransition.Neutral; - } + return new(SweepEventComparer.Instance); } /// - /// Determines the result transition state for a given sweep event based on the specified boolean operation. + /// Returns endpoint storage after its interval releases ownership. /// - /// The sweep event to evaluate. - /// The boolean operation being performed (e.g., Intersection, Union, XOR, Difference). - /// - /// A value that represents the transition state of the event: - /// - /// if the event contributes to the result. - /// if the event does not contribute to the result. - /// if the event does not affect the transition but is part of the result. - /// - /// - /// Thrown if the boolean operation is invalid or unsupported. - private static ResultTransition DetermineResultTransition(SweepEvent sweepEvent, BooleanOperation operation) + /// The queue no longer referenced by a live interval. + private void ReturnEndpoints(PriorityQueue ends) { - bool thisIn = !sweepEvent.InOut; - bool thatIn = !sweepEvent.OtherInOut; - bool isIn; - - // Determine the "in" state based on the operation - switch (operation) - { - case BooleanOperation.Intersection: - isIn = thisIn && thatIn; - break; - case BooleanOperation.Union: - isIn = thisIn || thatIn; - break; - case BooleanOperation.Xor: - isIn = thisIn ^ thatIn; - break; - case BooleanOperation.Difference: - if (sweepEvent.PolygonType == PolygonType.Subject) - { - isIn = thisIn && !thatIn; - } - else - { - isIn = thatIn && !thisIn; - } - - break; - default: - throw new InvalidOperationException("Invalid boolean operation."); - } - - return isIn ? ResultTransition.Contributing : ResultTransition.NonContributing; + // Retain the array for the next bundle. Include it in the clipper's + // capacity limit so a large overlap cannot pin unbounded scratch storage. + ends.Clear(); + this.retainedEndpointCapacity += ends.EnsureCapacity(0); + this.endpointQueues.Push(ends); } /// - /// Determines if the given sweep event belongs to the result of the boolean operation. + /// Schedules the next intersection of newly adjacent active intervals. /// - /// The sweep event to check. - /// The boolean operation being performed. - /// if the event belongs to the result; otherwise, . - private static bool InResult(SweepEvent sweepEvent, BooleanOperation operation) - => sweepEvent.EdgeType switch - { - EdgeType.Normal => operation switch - { - BooleanOperation.Intersection => !sweepEvent.OtherInOut, - BooleanOperation.Union => sweepEvent.OtherInOut, - BooleanOperation.Difference => - (sweepEvent.OtherInOut && sweepEvent.PolygonType == PolygonType.Subject) || - (!sweepEvent.OtherInOut && sweepEvent.PolygonType == PolygonType.Clipping), - BooleanOperation.Xor => true, - _ => false, - }, - EdgeType.NonContributing => false, - EdgeType.SameTransition => operation is BooleanOperation.Intersection or BooleanOperation.Union, - EdgeType.DifferentTransition => operation == BooleanOperation.Difference, - _ => false, - }; - - /// - /// Determines the possible intersection of two sweep line segments. - /// - /// The first sweep event representing a line segment. - /// The second sweep event representing a line segment. - /// The event queue to add new events to. - /// - /// A scratch space for temporary storage of sweep events. - /// Must be at least 4 elements long to hold the events for the two segments and their associated other events. - /// - /// - /// An integer indicating the result of the intersection: - /// - /// 0 if no intersection or trivial intersection at endpoints. - /// 1 if the segments intersect at a single point. - /// 2 if the segments overlap and share a left endpoint. - /// 3 if the segments partially overlap or one includes the other. - /// - /// - /// - /// Thrown when the line segments overlap but belong to the same polygon. - /// - private static int PossibleIntersection( - SweepEvent le1, - SweepEvent le2, - StablePriorityQueue eventQueue, - Span workspace) + /// The lower neighbor's index. + /// The upper neighbor's index. + /// The event already processed. + /// Whether this event contains an original source endpoint. + /// Whether the new adjacency also meets at the staged point. + private bool PossibleIntersection(int lower, int upper, Vertex point, bool sourcePoint) { - if (le1.OtherEvent == null || le2.OtherEvent == null) + if (lower < 0 || upper >= this.statusLine.Count) { - // No intersection possible. - return 0; + return false; } - // Point intersections - int nIntersections = PolygonUtilities.FindIntersection( - le1.GetSegment(), - le2.GetSegment(), - out Vertex ip1, - out Vertex _); // Currently unused but could be used to detect collinear overlapping segments - - if (nIntersections == 0) - { - // No intersection - return 0; - } - - // Ignore intersection if it occurs at the exact left or right endpoint of both segments - if (nIntersections == 1 && - (le1.Point == le2.Point || le1.OtherEvent.Point == le2.OtherEvent.Point)) - { - // Line segments intersect at an endpoint of both line segments - return 0; - } + SweepEvent first = this.statusLine[lower]; + SweepEvent second = this.statusLine[upper]; - // If segments overlap and belong to the same polygon, ignore them - if (nIntersections == 2 && le1.PolygonType == le2.PolygonType) + // Keep the original support lines across splits. Reconstructing a + // line from a rounded intersection rotates it and can create a second, + // slightly different intersection at an existing source vertex. + if (first.ContourId > second.ContourId) { - return 0; + (first, second) = (second, first); } - // Handle a single intersection point - SweepEventComparer comparer = eventQueue.Comparer; - if (nIntersections == 1) + int count = PolygonUtilities.FindIntersection( + first.Support, second.Support, out Vertex intersection, out Vertex last); + if (count > 0) { - // If the intersection point is not an endpoint of le1 segment. - if (le1.Point != ip1 && le1.OtherEvent.Point != ip1) + if (intersection == point || (count == 2 && last == point)) { - DivideSegment(le1, ip1, eventQueue, comparer); - } + if (!sourcePoint || + (PolygonUtilities.SignedArea(first.Support.Source, first.Support.Target, point) == 0 && + PolygonUtilities.SignedArea(second.Support.Source, second.Support.Target, point) == 0)) + { + return true; + } - // If the intersection point is not an endpoint of le2 segment. - if (le2.Point != ip1 && le2.OtherEvent.Point != ip1) - { - DivideSegment(le2, ip1, eventQueue, comparer); + // A real interior crossing can round to a nearby source vertex. + // Do not merge those distinct events. Preserve a vertical support's + // x coordinate; otherwise use the existing one-ULP x-order repair. + intersection = first.Point.X == first.SourceEnd.X || second.Point.X == second.SourceEnd.X + ? new Vertex(point.X, point.Y.NextAfter(double.PositiveInfinity)) + : new Vertex(point.X.NextAfter(double.PositiveInfinity), point.Y); } - return 1; - } - - // The line segments associated with le1 and le2 overlap. - bool leftCoincide = le1.Point == le2.Point; - bool rightCoincide = le1.OtherEvent.Point == le2.OtherEvent.Point; - - // Populate the events. - // The working buffer has a length of 4, which is sufficient to hold the events - // for the two segments and their associated other events. - // Events are assigned in a specific order to avoid overwriting shared references. - ref SweepEvent wRef = ref MemoryMarshal.GetReference(workspace); - if (!leftCoincide) - { - if (comparer.Compare(le1, le2) > 0) - { - Unsafe.Add(ref wRef, 0u) = le2; - Unsafe.Add(ref wRef, 1u) = le1; - } - else + // Match the established Martinez repair: a rounded crossing on + // this x coordinate but below the completed event cannot be + // visited backwards. Advance x by one representable double. + if (intersection.X == point.X && intersection.Y < point.Y) { - Unsafe.Add(ref wRef, 0u) = le1; - Unsafe.Add(ref wRef, 1u) = le2; + intersection = new Vertex(intersection.X.NextAfter(double.PositiveInfinity), intersection.Y); } - // Positions 0 and 1 contain the left events of the segments. - // Positions 2 and 3 will contain the right events of the segments. - if (!rightCoincide) + if (SweepEventComparer.Instance.Compare(intersection, first.Point) < 0 || SweepEventComparer.Instance.Compare(intersection, second.Point) < 0 || + (SweepEventComparer.Instance.Compare(intersection, first.End) > 0 && (first.End != first.SourceEnd || intersection.X != first.End.X)) || + (SweepEventComparer.Instance.Compare(intersection, second.End) > 0 && (second.End != second.SourceEnd || intersection.X != second.End.X))) { - Unsafe.Add(ref wRef, 2u) = le1.OtherEvent; - Unsafe.Add(ref wRef, 3u) = le2.OtherEvent; + return false; } - else - { - Unsafe.Add(ref wRef, 2u) = le2.OtherEvent; - Unsafe.Add(ref wRef, 3u) = le1.OtherEvent; - } - } - else if (leftCoincide && !rightCoincide) - { - // Only the right endpoints differ, so we use positions 0 and 1 for their sorted order. - if (comparer.Compare(le1.OtherEvent, le2.OtherEvent) > 0) - { - Unsafe.Add(ref wRef, 0u) = le2.OtherEvent; - Unsafe.Add(ref wRef, 1u) = le1.OtherEvent; - } - else - { - Unsafe.Add(ref wRef, 0u) = le1.OtherEvent; - Unsafe.Add(ref wRef, 1u) = le2.OtherEvent; - } - } - if (leftCoincide) - { - le2.EdgeType = EdgeType.NonContributing; - le1.EdgeType = (le2.InOut == le1.InOut) - ? EdgeType.SameTransition - : EdgeType.DifferentTransition; - - if (leftCoincide && !rightCoincide) + this.DivideSegment(first, intersection, point); + this.DivideSegment(second, intersection, point); + if (count == 2) { - DivideSegment(Unsafe.Add(ref wRef, 1u).OtherEvent, Unsafe.Add(ref wRef, 0u).Point, eventQueue, comparer); + this.DivideSegment(first, last, point); + this.DivideSegment(second, last, point); } - - return 2; } - if (rightCoincide) - { - // Since leftCoincide is false, the first two workspace slots contain distinct left events. - DivideSegment(Unsafe.Add(ref wRef, 0u), Unsafe.Add(ref wRef, 1u).Point, eventQueue, comparer); - return 3; - } - - // Handle general overlapping case - // At this point: workspace[0,1] = sorted left events, workspace[2,3] = sorted right events. - if (Unsafe.Add(ref wRef, 0u) != Unsafe.Add(ref wRef, 3u).OtherEvent) - { - DivideSegment(Unsafe.Add(ref wRef, 0u), Unsafe.Add(ref wRef, 1u).Point, eventQueue, comparer); - DivideSegment(Unsafe.Add(ref wRef, 1u), Unsafe.Add(ref wRef, 2u).Point, eventQueue, comparer); - return 3; - } - - // One segment fully contains the other - DivideSegment(Unsafe.Add(ref wRef, 0u), Unsafe.Add(ref wRef, 1u).Point, eventQueue, comparer); - DivideSegment(Unsafe.Add(ref wRef, 3u).OtherEvent, Unsafe.Add(ref wRef, 2u).Point, eventQueue, comparer); - return 3; + return false; } /// - /// Divides the given segment at the specified point, creating two new segments. + /// Shortens a live interval to its earliest discovered future node. /// - /// The left event representing the segment to divide. - /// The point at which to divide the segment. - /// The event queue to add the new events to. - /// The comparer used to sort the events. - private static void DivideSegment( - SweepEvent le, - Vertex p, - StablePriorityQueue eventQueue, - SweepEventComparer comparer) + /// The live interval. + /// The discovered node. + /// The completed event point. + private void DivideSegment(SweepEvent edge, Vertex intersection, Vertex current) { - if (le.OtherEvent == null) + if (SweepEventComparer.Instance.Compare(intersection, current) <= 0 || intersection == edge.End) { return; } - SweepEvent re = le.OtherEvent; - - // The idea is to divide the segment based on the given `inter` coordinate as follows: - // - // (se_l)--------(r)(l)--------(re) - // - // Under normal circumstances the resulting events satisfy the conditions: - // - // se_l is before r, and l is before re. - // - // Since the intersection point computation is bounded to the interval [se_l.x, re.x] - // it is impossible for r/l to fall outside the interval. This leaves the corner cases: - // - // 1. r.x == se_l.x and r.y < se_l.y: This corresponds to the case where the first - // sub-segment becomes a perfectly vertical line. The problem is that vertical - // segments always have to be processed from bottom to top consistency. The - // theoretically correct event order would be r first (bottom), se_l later (top). - // However, se_l is the event just being processed, so there is no (easy) way of - // processing r before se_l. The easiest solution to the problem is to avoid it, - // by incrementing inter.x by one ULP. - // 2. l.x == re.x and l.y > re.y: This corresponds to the case where the second - // sub-segment becomes a perfectly vertical line, and because of the bottom-to-top - // convention for vertical segment, the order of l and re must be swapped. - // In this case swapping is not a problem, because both events are in the future. - // - // See also: https://github.com/21re/rust-geo-booleanop/pull/11 - - // Prevent from corner case 1 - if (p.X == le.Point.X && p.Y < le.Point.Y) + if (SweepEventComparer.Instance.Compare(intersection, edge.End) > 0) { - // The files are different in the two reference repositories but both fail. - p = new Vertex(p.X.NextAfter(double.PositiveInfinity), p.Y); - } - - // Create the right event for the left segment (new right endpoint) - SweepEvent r = new(p, false, le, le.PolygonType); - - // Create the left event for the right segment (new left endpoint) - SweepEvent l = new(p, true, re, le.PolygonType); - - // Assign the same contour ID to maintain connectivity - r.ContourId = l.ContourId = le.ContourId; + if (edge.End != edge.SourceEnd || intersection.X != edge.End.X || edge.Point.X == edge.End.X) + { + return; + } - // Corner case 2 can be accounted for by swapping l / se_r - if (comparer.Compare(l, re) > 0) - { - Debug.WriteLine("Rounding error detected: Adjusting left/right flags for event ordering."); - re.Left = true; - l.Left = false; + // The second established Martinez rounding case reverses the + // tiny final piece: the source endpoint precedes the rounded + // crossing on the same x coordinate. Represent that piece as a + // new forward interval with the opposite signed contribution. + SweepEvent tail = this.segments.Add(edge.SourceEnd, intersection, default(WindingCount).Subtract(edge.Delta)); + this.events.Enqueue(new QueueEntry(tail.Point, tail, true)); + edge.SourceEnd = intersection; } - // Update references to maintain correct linkage - re.OtherEvent = l; - le.OtherEvent = r; - - // Add the new events to the event queue - eventQueue.Enqueue(l); - eventQueue.Enqueue(r); + // SourceEnd/Ends retain the source's real terminal changes. End only + // limits this open interval; its continuation is made at the new node. + edge.End = intersection; + edge.Version++; + this.events.Enqueue(new QueueEntry(intersection, edge, false)); } /// - /// Connects edges in the result polygon by processing the sweep events - /// and constructing contours for the final result. + /// Evaluates Boolean membership from independent signed winding counts. /// - /// The sorted list of sweep events. - /// The comparer used to sort the events. - /// The resulting . - private static Polygon ConnectEdges(SweepEventPoolList sortedEvents, SweepEventComparer comparer) + /// The region's winding counts. + /// The Boolean operation. + /// The subject's fill rule. + /// The clipping operand's fill rule. + /// Whether the region belongs to the result. + private static bool InResult(WindingCount count, BooleanOperation operation, FillRule subjectRule, FillRule clipRule) { - // Copy the events in the result polygon to resultEvents list - List resultEvents = new(sortedEvents.Count); - for (int i = 0; i < sortedEvents.Count; i++) + bool subject = Filled(count.Subject, subjectRule); + bool clip = Filled(count.Clip, clipRule); + return operation switch { - SweepEvent se = sortedEvents[i]; - if (se.Left && se.InResult) - { - resultEvents.Add(se); - } - else if (!se.Left && se.OtherEvent.InResult) - { - resultEvents.Add(se); - } - } + BooleanOperation.Intersection => subject && clip, + BooleanOperation.Union => subject || clip, + BooleanOperation.Difference => subject && !clip, + _ => subject ^ clip + }; + } - // Due to overlapping edges, the resultEvents list may not be completely sorted - bool sorted = false; - while (!sorted) + /// + /// Interprets a winding count using a validated fill rule. + /// + /// The signed winding count. + /// The validated fill rule. + /// Whether the region is filled. + private static bool Filled(int count, FillRule rule) + => rule switch { - sorted = true; - for (int i = 0; i < resultEvents.Count - 1; i++) - { - if (comparer.Compare(resultEvents[i], resultEvents[i + 1]) > 0) - { - (resultEvents[i], resultEvents[i + 1]) = (resultEvents[i + 1], resultEvents[i]); - sorted = false; - } - } - } + FillRule.EvenOdd => (count & 1) != 0, + FillRule.NonZero => count != 0, + FillRule.Positive => count > 0, + _ => count < 0 + }; + /// + /// Connects edges in the result polygon by processing the sweep events + /// and constructing contours for the final result. + /// + /// The sorted, paired filled-boundary events. + /// The connected polygon. + private Polygon ConnectEdges(SweepEventPoolList resultEvents) + { + // Run already sorts completed boundary events. Work directly on their + // pooled storage; no filtering copy or second ordering pass is needed. // Assign positions to events // The first loop ensures that every event gets its initial position based on its index in the list. // This must be completed for all events before adjustments are made for right events to avoid inconsistent state. @@ -1003,7 +1096,7 @@ private static Polygon ConnectEdges(SweepEventPoolList sortedEvents, SweepEventC } int contourId = result.Count; - Contour contour = InitializeContourFromContext(resultEvents[i], result, contourId); + Contour contour = this.InitializeContourFromContext(resultEvents[i], result, contourId); int pos = i; Vertex initial = resultEvents[i].Point; @@ -1017,7 +1110,9 @@ private static Polygon ConnectEdges(SweepEventPoolList sortedEvents, SweepEventC MarkProcessed(resultEvents[pos], processed, pos, contourId); - contour.Add(resultEvents[pos].Point); + Vertex point = resultEvents[pos].Point; + contour.Add(point); + pos = NextPos(pos, processed, iterationMap, out bool found); if (!found) { @@ -1029,6 +1124,11 @@ private static Polygon ConnectEdges(SweepEventPoolList sortedEvents, SweepEventC result.Add(contour); } + if (this.contourOutput == ContourOutput.Nested) + { + return result; + } + Polygon polygon = []; using Buffer contourIndices = new(result.Count); Span indices = contourIndices.GetSpan(); @@ -1062,7 +1162,12 @@ private static Polygon ConnectEdges(SweepEventPoolList sortedEvents, SweepEventC return polygon; } - private static ReadOnlySpan PrecomputeIterationOrder(List data) + /// + /// Builds the incident boundary order used to trace connected contours. + /// + /// The fully sorted, paired output events. + /// The next incident event index for each boundary endpoint. + private static ReadOnlySpan PrecomputeIterationOrder(SweepEventPoolList data) { Span map = new int[data.Count]; @@ -1145,6 +1250,13 @@ private static ReadOnlySpan PrecomputeIterationOrder(List data) return map; } + /// + /// Marks a connected endpoint and records its owning output contour. + /// + /// The connected endpoint. + /// The traversal state. + /// The endpoint position. + /// The output contour index. [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void MarkProcessed(SweepEvent sweepEvent, Span processed, int pos, int contourId) { @@ -1160,9 +1272,31 @@ private static void MarkProcessed(SweepEvent sweepEvent, Span processed, i /// The collection of contours processed so far. /// The ID for the new contour. /// The initialized . - private static Contour InitializeContourFromContext(SweepEvent sweepEvent, Polygon polygon, int contourId) + private Contour InitializeContourFromContext(SweepEvent sweepEvent, Polygon polygon, int contourId) { Contour contour = []; + if (this.contourOutput == ContourOutput.Nested) + { + if (sweepEvent.PrevInResult is SweepEvent lower) + { + int lowerId = lower.OutputContourId; + Contour lowerContour = polygon[lowerId]; + bool filledAbove = lower.ResultTransition > 0; + bool lowerExterior = (lowerContour.Depth & 1) == 0; + + // At a contour's leftmost point, the surviving lower boundary + // locates its containing region. Crossing into the lower contour + // makes it the owner; crossing out returns to that contour's owner. + contour.ParentIndex = filledAbove == lowerExterior ? lowerId : lowerContour.ParentIndex; + if (contour.ParentIndex is int parent) + { + contour.Depth = polygon[parent].Depth + 1; + polygon[parent].AddHoleIndex(contourId); + } + } + + return contour; + } // Check if there is a "previous in result" event if (sweepEvent.PrevInResult != null) @@ -1196,9 +1330,9 @@ private static Contour InitializeContourFromContext(SweepEvent sweepEvent, Polyg } else { - // We are outside: This contour is an exterior contour of the same depth. + // Exterior/hole grouping starts each exterior at depth zero. contour.ParentIndex = null; - contour.Depth = polygon[lowerContourId].Depth; + contour.Depth = 0; } } else @@ -1212,18 +1346,16 @@ private static Contour InitializeContourFromContext(SweepEvent sweepEvent, Polyg } /// - /// Finds the next unprocessed position in the result events, either forward or backward, - /// starting from the given position. + /// Finds the next unprocessed boundary event incident to the current point. /// /// The current position in the result events. - /// A list indicating whether each event at the corresponding index has been processed. - /// A precomputed map that indicates the next position to check for unprocessed events. - /// A boolean indicating whether an unprocessed event was found. - /// The index of the next unprocessed position. + /// Whether each boundary event has already been traced. + /// The cyclic order of incident boundary events. + /// Whether an unprocessed incident event was found. + /// The next event index, or when all incident events are processed. /// - /// This method searches forward from the current position until it finds an unprocessed event with - /// a different point or reaches the end of the list. If no such event is found, it searches backward - /// until it finds an unprocessed event. + /// The incident order selects the boundary continuation around the filled region. + /// Returning to the starting event without finding an unprocessed event ends the search. /// private static int NextPos( int pos, @@ -1250,4 +1382,95 @@ private static int NextPos( } } } + + /// + /// Stores separate subject and clip contributions without cross-operand cancellation. + /// + internal readonly struct WindingCount + { + /// + /// The subject winding. + /// + public readonly int Subject; + + /// + /// The clipping operand winding. + /// + public readonly int Clip; + + /// + /// Initializes a new instance of the struct. + /// + /// The subject component. + /// The clipping component. + public WindingCount(int subject, int clip) + { + this.Subject = subject; + this.Clip = clip; + } + + /// + /// Gets a value indicating whether both contributions cancel. + /// + public bool IsZero => this.Subject == 0 && this.Clip == 0; + + /// + /// Adds an interval's contribution. + /// + /// The contribution to add. + /// The summed winding. + public WindingCount Add(WindingCount other) => new(this.Subject + other.Subject, this.Clip + other.Clip); + + /// + /// Removes contributions terminating at an endpoint. + /// + /// The terminating contributions. + /// The remaining winding. + public WindingCount Subtract(WindingCount other) => new(this.Subject - other.Subject, this.Clip - other.Clip); + } + + /// + /// Stores a versioned endpoint in the existing priority queue. + /// + internal readonly struct QueueEntry + { + /// + /// The queued geometric point. + /// + public readonly Vertex Point; + + /// + /// The associated interval. + /// + public readonly SweepEvent Edge; + + /// + /// The interval version when queued. + /// + public readonly int Version; + + /// + /// Whether this record starts a source interval. + /// + public readonly bool IsStart; + + /// + /// Initializes a new instance of the struct. + /// + /// The endpoint. + /// The interval. + /// Whether the record starts the interval. + public QueueEntry(Vertex point, SweepEvent edge, bool isStart) + { + this.Point = point; + this.Edge = edge; + this.Version = edge.Version; + this.IsStart = isStart; + } + + /// + /// Gets a value indicating whether the representative still owns this queued record. + /// + public bool IsValid => this.Version == this.Edge.Version && (this.IsStart || this.Edge.Active); + } } diff --git a/src/PolygonClipper/PolygonStroker.cs b/src/PolygonClipper/PolygonStroker.cs index 8b57061..eb58ca0 100644 --- a/src/PolygonClipper/PolygonStroker.cs +++ b/src/PolygonClipper/PolygonStroker.cs @@ -8,23 +8,17 @@ namespace SixLabors.PolygonClipper; #pragma warning disable SA1201 // Elements should appear in the correct order /// -/// Generates polygonal stroke geometry for contours with configurable joins and caps. +/// Generates closed stroke contours with configurable width, joins, and caps. /// /// -/// This type performs two phases: -/// -/// Expand each source contour into one or two stroke-side outlines with joins/caps. -/// -/// Optionally resolve generated overlaps/self-intersections using -/// with positive fill semantics. -/// -/// -/// The emitted contours are implicitly closed (first vertex is not duplicated at the end). +/// Each source contour's selects a closure join or endpoint caps. +/// Returned contours are closed and do not repeat the first vertex at the end. /// -/// The static method is the recommended -/// entry point. It routes calls through an internal thread-local pool of reusable stroker -/// instances and automatically resets temporary state between calls. +/// Two remaining source vertices produce a capped segment, even for closed source input. +/// Two coincident input vertices produce a round footprint for round caps and a square footprint for other caps. +/// Other inputs with fewer than two remaining vertices produce no stroke. /// +/// controls whether overlaps and self-intersections are resolved before return. /// Instance members are not thread-safe for concurrent use. /// public sealed class PolygonStroker @@ -73,9 +67,7 @@ public sealed class PolygonStroker /// The stroke options. /// Thrown when is null. /// - /// This constructor is intended for advanced/manual usage. - /// For typical call patterns, prefer the static - /// method to use internal pooling automatically. + /// Set before calling to select the stroke width. /// public PolygonStroker(StrokeOptions options) { @@ -92,37 +84,59 @@ public PolygonStroker(StrokeOptions options) /// private enum Status { - /// Initial setup and input normalization. + /// + /// Initial setup and input normalization. + /// Initial, - /// Ready to emit the first command for the contour. + /// + /// Ready to emit the first command for the contour. + /// Ready, - /// Emit start-cap vertices for open contours. + /// + /// Emit start-cap vertices for open contours. + /// Cap1, - /// Emit end-cap vertices for open contours. + /// + /// Emit end-cap vertices for open contours. + /// Cap2, - /// Emit joins for the first stroke side. + /// + /// Emit joins for the first stroke side. + /// Outline1, - /// Switch from first side to second side for closed paths. + /// + /// Switch from first side to second side for closed paths. + /// CloseFirst, - /// Emit joins for the second stroke side. + /// + /// Emit joins for the second stroke side. + /// Outline2, - /// Flush buffered vertices from the current join/cap computation. + /// + /// Flush buffered vertices from the current join/cap computation. + /// OutVertices, - /// Emit end-poly marker for first stroke side. + /// + /// Emit end-poly marker for first stroke side. + /// EndPoly1, - /// Emit end-poly marker for second stroke side. + /// + /// Emit end-poly marker for second stroke side. + /// EndPoly2, - /// Stop emitting commands. + /// + /// Stop emitting commands. + /// Stop } @@ -166,23 +180,29 @@ public override int GetHashCode() } /// - /// Strokes with using optional - /// . + /// Strokes the source contours with the specified width and default options. /// - /// Input polygon to stroke. - /// Stroke width. - /// - /// Stroke options controlling joins, caps and approximation behavior. - /// When null, default are used. - /// - /// The stroked polygon contours. - /// Thrown when is null. - /// Preferred entry point. Uses internal thread-local reusable instances. - public static Polygon Stroke(Polygon polygon, double width, StrokeOptions? options = null) + /// The source contours, each with its own closure state. + /// The stroke width. + /// Closed stroke contours without a repeated closing vertex. + /// The polygon is null. + public static Polygon Stroke(Polygon polygon, double width) + => Stroke(polygon, width, DefaultStrokeOptions); + + /// + /// Strokes the source contours with the specified width and options. + /// + /// The source contours, each with its own closure state. + /// The stroke width. + /// The join, cap, approximation, and output cleanup options. + /// Closed stroke contours without a repeated closing vertex. + /// The polygon or options are null. + public static Polygon Stroke(Polygon polygon, double width, StrokeOptions options) { - StrokeOptions effectiveOptions = options ?? DefaultStrokeOptions; - StrokeOptionsKey key = new(effectiveOptions); - PolygonStroker stroker = Rent(key, effectiveOptions); + ArgumentNullException.ThrowIfNull(options); + + StrokeOptionsKey key = new(options); + PolygonStroker stroker = Rent(key, options); try { stroker.Width = width; @@ -197,8 +217,8 @@ public static Polygon Stroke(Polygon polygon, double width, StrokeOptions? optio /// /// Strokes using this instance's configured options and width. /// - /// Input polygon to stroke. - /// The stroked polygon contours. + /// The source contours, each with its own closure state. + /// Closed stroke contours without a repeated closing vertex. /// Thrown when is null. /// Instance execution is not thread-safe for concurrent use. public Polygon Stroke(Polygon polygon) @@ -214,10 +234,7 @@ public Polygon Stroke(Polygon polygon) { Contour contour = polygon[i]; - // Close explicit or near-seam contours to avoid tiny stitch gaps, - // but keep clearly open polylines open so caps are emitted. - bool isClosed = IsContourClosedForEmission(contour, this.widthAbs * 2D); - Polygon stroked = this.ProcessPathToPolygon(contour, isClosed); + Polygon stroked = this.ProcessPathToPolygon(contour, contour.IsClosed); if (stroked.Count > 0) { allContours.Join(stroked); @@ -234,22 +251,9 @@ public Polygon Stroke(Polygon polygon) return allContours; } - // Stroker emission already follows positive-fill assumptions, so skip - // extra input-orientation normalization and only resolve overlaps. - return SelfIntersectionRemover.Process(allContours, normalizeInputForPositiveFill: false); - } - - /// - /// Strokes after setting the current stroke width. - /// - /// Input polygon to stroke. - /// Stroke width. - /// The stroked polygon contours. - /// Instance execution is not thread-safe for concurrent use. - public Polygon Stroke(Polygon polygon, double width) - { - this.Width = width; - return this.Stroke(polygon); + // Raw outlines describe a NonZero-filled band. A negative width reverses + // their winding, so Positive filling would incorrectly erase that band. + return PolygonClipper.Union(allContours, FillRule.NonZero); } /// @@ -311,7 +315,7 @@ public double Width /// Converts a single contour into stroked polygon contours. /// /// The source contour. - /// Whether the contour should be emitted as closed. + /// Whether the source contour includes a final-to-first segment and closure join. /// The generated stroked contour set for this input contour. private Polygon ProcessPathToPolygon(Contour contour, bool isClosed) { @@ -323,19 +327,13 @@ private Polygon ProcessPathToPolygon(Contour contour, bool isClosed) return []; } - bool hasExplicitClosure = pointCount > 1 && contour[0] == contour[^1]; - if (isClosed && hasExplicitClosure) + if (isClosed && pointCount > 2 && contour[0] == contour[^1]) { - // Keep one implicit closure path in the stroker state machine. - // Duplicate terminal vertices are re-added at final contour emission. + // Keep two coincident input vertices for the established point-cap case. + // Longer closed paths need only one copy of their starting vertex. pointCount--; } - if (pointCount < 2) - { - return []; - } - if (pointCount == 2) { Vertex p0 = contour[0]; @@ -419,31 +417,6 @@ private void ResetForReuse() this.status = Status.Initial; } - /// - /// Returns whether a contour should be treated as closed when emitting stroke geometry. - /// - /// The contour to inspect. - /// Current stroke width. - /// if the contour should be treated as closed; otherwise . - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static bool IsContourClosedForEmission(Contour contour, double strokeWidth) - { - int count = contour.Count; - if (count < 3) - { - return false; - } - - if (contour[0] == contour[^1]) - { - return true; - } - - Vertex delta = contour[0] - contour[^1]; - double closeThreshold = Math.Max(strokeWidth, 1E-3D); - return delta.LengthSquared() <= closeThreshold * closeThreshold; - } - /// /// Marks the current path as closed before finishing the outline. /// @@ -486,7 +459,7 @@ private void FinishPath(Polygon result) // Start a new contour. Commit any previous contour that is already complete. if (currentContour is { Count: >= 3 }) { - result.Add(currentContour); + AddStrokeContour(result, currentContour); } currentContour = new Contour(16); @@ -511,7 +484,7 @@ private void FinishPath(Polygon result) { if (currentContour is { Count: >= 3 }) { - result.Add(currentContour); + AddStrokeContour(result, currentContour); } currentContour = null; @@ -521,7 +494,27 @@ private void FinishPath(Polygon result) if (currentContour is { Count: >= 3 }) { - result.Add(currentContour); + AddStrokeContour(result, currentContour); + } + } + + /// + /// Adds a generated contour after removing a repeated closing vertex. + /// + /// The destination polygon. + /// A generated contour with at least three stored vertices. + private static void AddStrokeContour(Polygon result, Contour contour) + { + // Closure belongs to the contour, not to a duplicate endpoint. Apply this + // before emission so raw and cleaned output use the same representation. + if (contour[0] == contour[^1]) + { + contour.RemoveVertexAt(contour.Count - 1); + } + + if (contour.Count >= 3) + { + result.Add(contour); } } @@ -599,7 +592,8 @@ private PathCommand Accumulate(ref Vertex point) if (src.Length < 3) { - // Very short contours cannot be treated as closed reliably. + // Preserve capped-segment handling when duplicate removal leaves + // only two vertices. This does not change the source closure flag. this.closed = 0; } diff --git a/src/PolygonClipper/PolygonUtilities.Intersections.cs b/src/PolygonClipper/PolygonUtilities.Intersections.cs deleted file mode 100644 index a9d4854..0000000 --- a/src/PolygonClipper/PolygonUtilities.Intersections.cs +++ /dev/null @@ -1,110 +0,0 @@ -// Copyright (c) Six Labors. -// Licensed under the Six Labors Split License. - -namespace SixLabors.PolygonClipper; - -/// Provides compensated construction of geometric intersections. -internal static partial class PolygonUtilities -{ - /// Finds segment intersections with compensated construction of a crossing point. - /// The first source segment. - /// The second source segment. - /// The first intersection. - /// The final intersection of an overlap. - /// The number of intersections. - public static int FindIntersectionPrecise(in Segment first, in Segment second, out Vertex point, out Vertex last) - { - int count = FindIntersection(first, second, out point, out last); - if (count != 1 || point == first.Source || point == first.Target || point == second.Source || point == second.Target) - { - return count; - } - - // Intersection parameters are quotients of determinants. Retain the - // multiplication and addition roundoff until the final coordinate is - // rounded, rather than rounding the parameter and then each multiply/add. - // Independent pairs at a multiway junction then construct the same node. - CompensatedDouble ax = CompensatedDouble.Difference(first.Target.X, first.Source.X); - CompensatedDouble ay = CompensatedDouble.Difference(first.Target.Y, first.Source.Y); - CompensatedDouble bx = CompensatedDouble.Difference(second.Target.X, second.Source.X); - CompensatedDouble by = CompensatedDouble.Difference(second.Target.Y, second.Source.Y); - CompensatedDouble ex = CompensatedDouble.Difference(second.Source.X, first.Source.X); - CompensatedDouble ey = CompensatedDouble.Difference(second.Source.Y, first.Source.Y); - CompensatedDouble denominator = ax.Multiply(by).Subtract(ay.Multiply(bx)); - if (denominator.Value != 0) - { - CompensatedDouble numerator = ex.Multiply(by).Subtract(ey.Multiply(bx)); - CompensatedDouble parameter = numerator.Divide(denominator); - point = new Vertex(parameter.Multiply(ax).Add(new(first.Source.X)).Value, parameter.Multiply(ay).Add(new(first.Source.Y)).Value); - Box2 bounds = new( - Vertex.Max(Vertex.Min(first.Source, first.Target), Vertex.Min(second.Source, second.Target)), - Vertex.Min(Vertex.Max(first.Source, first.Target), Vertex.Max(second.Source, second.Target))); - point = ConstrainToBoundingBox(point, bounds); - } - - return count; - } - - /// Retains arithmetic roundoff as a second double during intersection construction. - private readonly struct CompensatedDouble - { - private readonly double high; - private readonly double low; - - /// Initializes a new instance of the struct. - /// The leading value. - /// The retained roundoff. - public CompensatedDouble(double high, double low = 0) - { - this.high = high; - this.low = low; - } - - /// Gets the value rounded to one double. - public double Value => this.high + this.low; - - /// Subtracts two coordinates without discarding the subtraction roundoff. - /// The first coordinate. - /// The coordinate to subtract. - /// The compensated difference. - public static CompensatedDouble Difference(double first, double second) => new CompensatedDouble(first).Subtract(new(second)); - - /// Adds two compensated values using the error-free two-sum identity. - /// The value to add. - /// The compensated sum. - public CompensatedDouble Add(CompensatedDouble other) - { - double sum = this.high + other.high; - double virtualOther = sum - this.high; - double error = (this.high - (sum - virtualOther)) + (other.high - virtualOther) + this.low + other.low; - double high = sum + error; - return new(high, error - (high - sum)); - } - - /// Subtracts a compensated value. - /// The value to subtract. - /// The compensated difference. - public CompensatedDouble Subtract(CompensatedDouble other) => this.Add(new(-other.high, -other.low)); - - /// Multiplies values while retaining the leading product's roundoff with FMA. - /// The multiplier. - /// The compensated product. - public CompensatedDouble Multiply(CompensatedDouble other) - { - double product = this.high * other.high; - double error = Math.FusedMultiplyAdd(this.high, other.high, -product) + (this.high * other.low) + (this.low * other.high); - double high = product + error; - return new(high, error - (high - product)); - } - - /// Corrects a leading quotient using its compensated residual. - /// The non-zero divisor. - /// The compensated quotient. - public CompensatedDouble Divide(CompensatedDouble other) - { - CompensatedDouble quotient = new(this.high / other.high); - CompensatedDouble remainder = this.Subtract(other.Multiply(quotient)); - return quotient.Add(new(remainder.Value / other.high)); - } - } -} diff --git a/src/PolygonClipper/PolygonUtilities.cs b/src/PolygonClipper/PolygonUtilities.cs index cdd84e2..4be5baa 100644 --- a/src/PolygonClipper/PolygonUtilities.cs +++ b/src/PolygonClipper/PolygonUtilities.cs @@ -3,6 +3,7 @@ using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; namespace SixLabors.PolygonClipper; @@ -10,7 +11,7 @@ namespace SixLabors.PolygonClipper; /// Provides utility methods for performing geometric calculations related to polygons, such as calculating signed areas /// and finding intersections of line segments. /// -internal static partial class PolygonUtilities +internal static class PolygonUtilities { /// /// Returns the signed area of a triangle. @@ -21,7 +22,29 @@ internal static partial class PolygonUtilities /// The area. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static double SignedArea(in Vertex p0, in Vertex p1, in Vertex p2) - => Vertex.Cross(p0 - p2, p1 - p2); + { + Vertex a = p0 - p2; + Vertex b = p1 - p2; + double first = a.X * b.Y; + double second = a.Y * b.X; + double area = first - second; + + // The orientation filter includes rounding in coordinate differences + // and products. Recover those differences only when cancellation can + // obscure the sign. The bound selects precision; it does not merge points. + const double errorFactor = 3.3306690738754716E-16D; + if (first == 0 || second == 0 || !double.IsFinite(area) || + Math.Abs(area) > errorFactor * (Math.Abs(first) + Math.Abs(second))) + { + return area; + } + + ExtendedPrecisionDouble ax = ExtendedPrecisionDouble.Difference(p0.X, p2.X); + ExtendedPrecisionDouble ay = ExtendedPrecisionDouble.Difference(p0.Y, p2.Y); + ExtendedPrecisionDouble bx = ExtendedPrecisionDouble.Difference(p1.X, p2.X); + ExtendedPrecisionDouble by = ExtendedPrecisionDouble.Difference(p1.Y, p2.Y); + return ((ax * by) - (ay * bx)).Value; + } /// /// Finds the intersection of two line segments, constraining results to their intersection bounding box. @@ -99,44 +122,44 @@ private static int FindIntersectionImpl(in Segment seg0, in Segment seg1, out Ve if (kross != 0) { // Lines of the segments are not parallel - double s = Vertex.Cross(e, vb) / kross; - if (s is < 0 or > 1) - { - return 0; - } - - double t = Vertex.Cross(e, va) / kross; - if (t is < 0 or > 1) + // Retain subtraction, determinant, and division roundoff until the + // final coordinate is rounded. Independent segment pairs meeting at + // one junction must construct the same point for event closure. + ExtendedPrecisionDouble ax = ExtendedPrecisionDouble.Difference(seg0.Target.X, a1.X); + ExtendedPrecisionDouble ay = ExtendedPrecisionDouble.Difference(seg0.Target.Y, a1.Y); + ExtendedPrecisionDouble bx = ExtendedPrecisionDouble.Difference(seg1.Target.X, a2.X); + ExtendedPrecisionDouble by = ExtendedPrecisionDouble.Difference(seg1.Target.Y, a2.Y); + ExtendedPrecisionDouble ex = ExtendedPrecisionDouble.Difference(a2.X, a1.X); + ExtendedPrecisionDouble ey = ExtendedPrecisionDouble.Difference(a2.Y, a1.Y); + ExtendedPrecisionDouble denominator = (ax * by) - (ay * bx); + ExtendedPrecisionDouble numerator = (ex * by) - (ey * bx); + ExtendedPrecisionDouble otherNumerator = (ex * ay) - (ey * ax); + double start = numerator.Value; + double end = (numerator - denominator).Value; + double otherStart = otherNumerator.Value; + double otherEnd = (otherNumerator - denominator).Value; + bool positive = denominator.Value > 0; + if (positive ? start < 0 || end > 0 || otherStart < 0 || otherEnd > 0 + : start > 0 || end < 0 || otherStart > 0 || otherEnd < 0) { return 0; } - // If s or t is exactly 0 or 1, the intersection is on an endpoint - if (s is 0 or 1) + // A rounded quotient can equal one for an interior crossing. + // Preserve a source endpoint only when the retained numerator + // actually equals zero or the denominator. + if (start == 0 || end == 0) { - // On an endpoint of line segment a - pi0 = s == 0 ? a1 : seg0.Target; + pi0 = start == 0 ? a1 : seg0.Target; return 1; } - if (t is 0 or 1) + if (otherStart == 0 || otherEnd == 0) { - // On an endpoint of line segment b - pi0 = t == 0 ? a2 : seg1.Target; + pi0 = otherStart == 0 ? a2 : seg1.Target; return 1; } - // Retain subtraction, determinant, and division roundoff until the - // final coordinate is rounded. Independent segment pairs meeting at - // one junction must construct the same point for event closure. - ExtendedPrecisionDouble ax = ExtendedPrecisionDouble.Difference(seg0.Target.X, a1.X); - ExtendedPrecisionDouble ay = ExtendedPrecisionDouble.Difference(seg0.Target.Y, a1.Y); - ExtendedPrecisionDouble bx = ExtendedPrecisionDouble.Difference(seg1.Target.X, a2.X); - ExtendedPrecisionDouble by = ExtendedPrecisionDouble.Difference(seg1.Target.Y, a2.Y); - ExtendedPrecisionDouble ex = ExtendedPrecisionDouble.Difference(a2.X, a1.X); - ExtendedPrecisionDouble ey = ExtendedPrecisionDouble.Difference(a2.Y, a1.Y); - ExtendedPrecisionDouble denominator = (ax * by) - (ay * bx); - ExtendedPrecisionDouble numerator = (ex * by) - (ey * bx); ExtendedPrecisionDouble parameter = numerator / denominator; ExtendedPrecisionDouble intersectionX = parameter * ax; ExtendedPrecisionDouble intersectionY = parameter * ay; @@ -279,9 +302,16 @@ public static bool IsCollinear(in Vertex a, in Vertex shared, in Vertex b) /// /// Computes the signed area of a contour. /// - public static double Area(List path) + public static double Area(List path) => Area(CollectionsMarshal.AsSpan(path)); + + /// + /// Computes the signed area of a contour. + /// + /// The contour vertices. + /// The signed area. + public static double Area(ReadOnlySpan path) { - int count = path.Count; + int count = path.Length; if (count < 3) { return 0D; @@ -523,8 +553,17 @@ public static Box2 GetBounds(List path) /// Determines whether a point is inside a contour. /// public static PointInPolygonResult PointInPolygon(in Vertex point, List polygon) + => PointInPolygon(point, CollectionsMarshal.AsSpan(polygon)); + + /// + /// Determines whether a point is inside a contour. + /// + /// The point to test. + /// The contour vertices. + /// The point's position relative to the contour. + public static PointInPolygonResult PointInPolygon(in Vertex point, ReadOnlySpan polygon) { - int len = polygon.Count; + int len = polygon.Length; int start = 0; if (len < 3) { @@ -709,172 +748,5 @@ private static bool PathContainsPath(List inner, List outer) /// - Returns 2 if the segments overlap. /// public static int FindIntersection(in Vertex a1, in Vertex a2, in Vertex b1, in Vertex b2, out Vertex pi0, out Vertex pi1) - { - pi0 = default; - pi1 = default; - - if (!TryGetIntersectionBoundingBox(a1, a2, b1, b2, out Box2 bbox)) - { - return 0; - } - - int interResult = FindIntersectionImpl(a1, a2, b1, b2, out pi0, out pi1); - - if (interResult == 1) - { - pi0 = ConstrainToBoundingBox(pi0, bbox); - } - else if (interResult == 2) - { - pi0 = ConstrainToBoundingBox(pi0, bbox); - pi1 = ConstrainToBoundingBox(pi1, bbox); - } - - return interResult; - } - - /// - /// Finds the intersection of two line segments. - /// - /// The first point of the first segment. - /// The second point of the first segment. - /// The first point of the second segment. - /// The second point of the second segment. - /// - /// The first intersection point (if any). If the segments intersect at a single point, this will contain the intersection point. - /// If the segments overlap, this will contain the start of the overlapping segment. - /// - /// - /// The second intersection point (if any). If the segments overlap, this will contain the end of the overlapping segment. - /// - /// - /// An indicating the number of intersection points: - /// - Returns 0 if there is no intersection. - /// - Returns 1 if the segments intersect at a single point. - /// - Returns 2 if the segments overlap. - /// - private static int FindIntersectionImpl(in Vertex a1, in Vertex a2, in Vertex b1, in Vertex b2, out Vertex pi0, out Vertex pi1) - { - pi0 = default; - pi1 = default; - - Vertex va = a2 - a1; - Vertex vb = b2 - b1; - Vertex e = b1 - a1; - double kross = Vertex.Cross(va, vb); - double sqrLenA = Vertex.Dot(va, va); - - // Match the segment overload: squaring can underflow even when the - // determinant itself is non-zero and the crossing is representable. - if (kross != 0D) - { - // Lines of the segments are not parallel. - double s = Vertex.Cross(e, vb) / kross; - if (s is < 0D or > 1D) - { - return 0; - } - - double t = Vertex.Cross(e, va) / kross; - if (t is < 0D or > 1D) - { - return 0; - } - - // If s or t is exactly 0 or 1, the intersection is on an endpoint. - if (s is 0D or 1D) - { - // On an endpoint of segment a. - pi0 = MidPoint(a1, s, va); - return 1; - } - - if (t is 0D or 1D) - { - // On an endpoint of segment b. - pi0 = MidPoint(a2, t, vb); - return 1; - } - - // Intersection of lines is a point on each segment. - pi0 = MidPoint(a1, s, va); - return 1; - } - - // Lines are parallel; check if they are collinear. - kross = Vertex.Cross(e, va); - if (kross != 0D) - { - // Parallel but not collinear. - return 0; - } - - if (sqrLenA == 0D) - { - return 0; - } - - // Segments are collinear, check 1D overlap in segment-a parameter space. - double sa = Vertex.Dot(va, e) / sqrLenA; - double sb = sa + (Vertex.Dot(va, vb) / sqrLenA); - double smin = Math.Min(sa, sb); - double smax = Math.Max(sa, sb); - - if (smin <= 1D && smax >= 0D) - { - if (smin == 1D) - { - pi0 = MidPoint(a1, smin, va); - return 1; - } - - if (smax == 0D) - { - pi0 = MidPoint(a1, smax, va); - return 1; - } - - pi0 = MidPoint(a1, Math.Max(smin, 0D), va); - pi1 = MidPoint(a1, Math.Min(smax, 1D), va); - return pi0 == pi1 ? 1 : 2; - } - - return 0; - } - - /// - /// Computes the bounding box of the intersection area of two line segments. - /// - /// The first point of the first segment. - /// The second point of the first segment. - /// The first point of the second segment. - /// The second point of the second segment. - /// The intersection bounding box if one exists, otherwise null. - /// - /// if the segments intersect; otherwise, . - /// - private static bool TryGetIntersectionBoundingBox( - in Vertex a1, - in Vertex a2, - in Vertex b1, - in Vertex b2, - out Box2 result) - { - Vertex minA = Vertex.Min(a1, a2); - Vertex maxA = Vertex.Max(a1, a2); - Vertex minB = Vertex.Min(b1, b2); - Vertex maxB = Vertex.Max(b1, b2); - - Vertex interMin = Vertex.Max(minA, minB); - Vertex interMax = Vertex.Min(maxA, maxB); - - if (interMin.X <= interMax.X && interMin.Y <= interMax.Y) - { - result = new Box2(interMin, interMax); - return true; - } - - result = default; - return false; - } + => FindIntersection(new Segment(a1, a2), new Segment(b1, b2), out pi0, out pi1); } diff --git a/src/PolygonClipper/ScanlineSchedule.cs b/src/PolygonClipper/ScanlineSchedule.cs deleted file mode 100644 index 608bd52..0000000 --- a/src/PolygonClipper/ScanlineSchedule.cs +++ /dev/null @@ -1,157 +0,0 @@ -// Copyright (c) Six Labors. -// Licensed under the Six Labors Split License. - -using System.Runtime.CompilerServices; - -namespace SixLabors.PolygonClipper; - -/// -/// Manages scanline ordering and local minima scheduling for the sweep line. -/// -/// -/// This type keeps local minima in sorted order and seeds scanlines from their Y coordinates. -/// It also provides ordered scanline pop/insert operations used during the sweep. -/// -internal sealed class ScanlineSchedule -{ - private static readonly LocalMinimaComparer LocalMinimaComparerInstance = new(); - - private ArrayBuilder localMinima; - private readonly List scanlines; - private int localMinimaIndex; - private bool isLocalMinimaSorted; - - /// - /// Initializes a new instance of the class. - /// - public ScanlineSchedule() - { - this.localMinima = new ArrayBuilder(16); - this.scanlines = []; - } - - /// - /// Gets the number of registered local minima. - /// - public int LocalMinimaCount => this.localMinima.Length; - - /// - /// Gets a retained-capacity score used to decide pooling reuse. - /// - public int RetainedCapacityScore => this.localMinima.Capacity + this.scanlines.Capacity; - - /// - /// Adds a local minima to the schedule. - /// - /// The minima to append. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void AddLocalMinima(in LocalMinima localMinima) - { - this.localMinima.Add(localMinima); - this.isLocalMinimaSorted = false; - } - - /// - /// Marks the local minima list as unsorted. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void MarkDirty() => this.isLocalMinimaSorted = false; - - /// - /// Clears all minima and scanline state. - /// - public void Clear() - { - this.localMinima.Clear(); - this.scanlines.Clear(); - this.localMinimaIndex = 0; - this.isLocalMinimaSorted = false; - } - - /// - /// Clears scanlines while keeping local minima intact. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void ClearScanlines() => this.scanlines.Clear(); - - /// - /// Sorts minima (if needed) and seeds the scanline list. - /// - public void Reset() - { - if (!this.isLocalMinimaSorted) - { - this.localMinima.Sort(LocalMinimaComparerInstance); - this.isLocalMinimaSorted = true; - } - - this.scanlines.Clear(); - int localMinimaCount = this.localMinima.Length; - this.scanlines.EnsureCapacity(localMinimaCount); - for (int i = localMinimaCount - 1; i >= 0; i--) - { - this.scanlines.Add(this.localMinima[i].Vertex.Point.Y); - } - - this.localMinimaIndex = 0; - } - - /// - /// Determines whether the next local minima is on the given scanline. - /// - /// The scanline Y coordinate. - /// if a minima exists at this Y. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public bool HasLocalMinimaAtY(double y) - => this.localMinimaIndex < this.localMinima.Length && - this.localMinima[this.localMinimaIndex].Vertex.Point.Y == y; - - /// - /// Pops the next local minima from the schedule. - /// - /// The next local minima. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public LocalMinima PopLocalMinima() => this.localMinima[this.localMinimaIndex++]; - - /// - /// Inserts a scanline value into the ordered list. - /// - /// The scanline Y coordinate. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void InsertScanline(double y) - { - int index = this.scanlines.BinarySearch(y); - if (index >= 0) - { - return; - } - - index = ~index; - this.scanlines.Insert(index, y); - } - - /// - /// Pops the next scanline from the schedule. - /// - /// The popped scanline value. - /// when a scanline was available. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public bool TryPopScanline(out double y) - { - int count = this.scanlines.Count - 1; - if (count < 0) - { - y = 0; - return false; - } - - y = this.scanlines[count]; - this.scanlines.RemoveAt(count--); - while (count >= 0 && y == this.scanlines[count]) - { - this.scanlines.RemoveAt(count--); - } - - return true; - } -} diff --git a/src/PolygonClipper/SegmentComparer.cs b/src/PolygonClipper/SegmentComparer.cs index 699a4e6..f223524 100644 --- a/src/PolygonClipper/SegmentComparer.cs +++ b/src/PolygonClipper/SegmentComparer.cs @@ -11,6 +11,18 @@ namespace SixLabors.PolygonClipper; /// internal sealed class SegmentComparer : IComparer, IComparer { + /// + /// Compares outgoing rays sharing the same complete event point. + /// + /// The first outgoing interval. + /// The second outgoing interval. + /// The right-limit order, or zero for coincident rays. + public static int CompareRays(SweepEvent first, SweepEvent second) + { + double cross = PolygonUtilities.SignedArea(first.Point, first.SourceEnd, second.SourceEnd); + return cross > 0 ? -1 : cross < 0 ? 1 : 0; + } + /// public int Compare(SweepEvent? x, SweepEvent? y) { diff --git a/src/PolygonClipper/SelfIntersectionRemover.cs b/src/PolygonClipper/SelfIntersectionRemover.cs deleted file mode 100644 index a4274b7..0000000 --- a/src/PolygonClipper/SelfIntersectionRemover.cs +++ /dev/null @@ -1,1332 +0,0 @@ -// Copyright (c) Six Labors. -// Licensed under the Six Labors Split License. - -using System.Runtime.CompilerServices; - -namespace SixLabors.PolygonClipper; - -/// -/// Provides functionality to remove self-intersections from polygons using a sweep line algorithm. -/// -/// -/// -/// This class implements a sweep line algorithm that resolves self-intersections -/// and normalizes contours for positive winding output. -/// -/// -/// The algorithm works in three phases: -/// -/// -/// -/// Intersection Detection: Uses a sweep line to find all points where segments -/// intersect each other (both self-intersections and cross-contour intersections). -/// -/// -/// Segment Splitting: Divides segments at intersection points, creating new -/// vertices where crossings occur. -/// -/// -/// Boundary Extraction: Keeps only edges that -/// form the boundary between filled and unfilled regions. -/// -/// -/// -internal static class SelfIntersectionRemover -{ - // Mirror PolygonClipper pooling policy: keep a tiny hot set per thread. - private const int MaxOutputBuilderPoolDepth = 4; - - // Retain builders only while their pooled internal capacity stays in a - // bounded range. Oversized builders are dropped after heavy/pathological inputs. - private const int MaxRetainedOutputBuilderCapacityScore = 131_072; - - [ThreadStatic] - private static Stack? outputBuilderPool; - - /// - /// Processes a polygon to remove self-intersections. - /// - /// The polygon to process. - /// - /// A new with self-intersections resolved and contours - /// normalized for positive winding fill semantics. - /// - public static Polygon Process(Polygon polygon) - => Process(polygon, normalizeInputForPositiveFill: true); - - /// - /// Processes a polygon to remove self-intersections. - /// - /// The polygon to process. - /// - /// Whether input contours should be normalized before sweep execution. - /// - /// The self-intersection-removed polygon. - internal static Polygon Process(Polygon polygon, bool normalizeInputForPositiveFill) - { - if (polygon.Count == 0) - { - return []; - } - - List> subject = BuildSubjectPaths(polygon, normalizeInputForPositiveFill); - if (normalizeInputForPositiveFill) - { - GetLowestPathInfo(subject, out int lowestPathIdx, out bool isNegativeArea); - if (lowestPathIdx >= 0 && isNegativeArea) - { - ReverseContours(subject); - } - } - - OutputBuilder builder = RentOutputBuilder(); - try - { - return UnionWithClipper(subject, polygon.Count, builder); - } - finally - { - ReturnOutputBuilder(builder); - } - } - - /// - /// Executes a union using the internal clipper. - /// - /// The quantized subject contours to union. - /// The initial contour capacity for the output polygon. - /// The reusable output builder instance. - /// A polygon containing the unioned contours. - private static Polygon UnionWithClipper( - List> subject, - int resultCapacity, - OutputBuilder builder) - { - builder.ResetForReuse(); - builder.PreserveCollinear = true; - builder.AddSubject(subject); - return builder.Execute(resultCapacity); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static void ReverseContours(List> subject) - { - for (int i = 0; i < subject.Count; i++) - { - subject[i].Reverse(); - } - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static OutputBuilder RentOutputBuilder() - { - Stack? pool = outputBuilderPool; - if (pool != null && pool.Count > 0) - { - return pool.Pop(); - } - - return new OutputBuilder(); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static void ReturnOutputBuilder(OutputBuilder builder) - { - builder.ResetForReuse(); - - // Drop oversized builders to prevent long-lived thread-local memory spikes. - if (builder.RetainedCapacityScore > MaxRetainedOutputBuilderCapacityScore) - { - return; - } - - Stack pool = outputBuilderPool ??= new Stack(MaxOutputBuilderPoolDepth); - if (pool.Count < MaxOutputBuilderPoolDepth) - { - pool.Push(builder); - } - } - - /// - /// Determines the lowest point across all paths and whether its contour area is negative. - /// - /// The paths to examine. - /// The index of the path containing the lowest point. - /// True when the lowest path has negative area. - private static void GetLowestPathInfo(List> paths, out int lowestPathIdx, out bool isNegativeArea) - { - lowestPathIdx = -1; - isNegativeArea = false; - - if (paths.Count == 0) - { - return; - } - - Vertex lowestPoint = default; - bool hasPoint = false; - for (int i = 0; i < paths.Count; i++) - { - List path = paths[i]; - if (path.Count == 0) - { - continue; - } - - Vertex candidate = GetLowestPoint(path); - if (!hasPoint || candidate.Y > lowestPoint.Y || (candidate.Y == lowestPoint.Y && candidate.X < lowestPoint.X)) - { - lowestPoint = candidate; - lowestPathIdx = i; - hasPoint = true; - } - } - - if (lowestPathIdx >= 0) - { - isNegativeArea = GetSignedArea(paths[lowestPathIdx]) < 0D; - } - } - - private static Vertex GetLowestPoint(List path) - { - int count = path.Count; - int lastIndex = count - 1; - if (count > 1 && path[0] == path[^1]) - { - lastIndex = count - 2; - } - - Vertex lowest = path[0]; - for (int i = 1; i <= lastIndex; i++) - { - Vertex candidate = path[i]; - if (candidate.Y > lowest.Y || (candidate.Y == lowest.Y && candidate.X < lowest.X)) - { - lowest = candidate; - } - } - - return lowest; - } - - private static int GetDepth(int index, ReadOnlySpan parentIndices) - { - int depth = 0; - int current = parentIndices[index]; - while (current >= 0) - { - depth++; - current = parentIndices[current]; - } - - return depth; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static Vertex GetContourTestPoint(List contour) - { - if (contour.Count == 0) - { - return default; - } - - Vertex first = contour[0]; - if (contour.Count > 1 && first == contour[^1]) - { - return contour[1]; - } - - return first; - } - - private static double GetSignedArea(List contour) - => PolygonUtilities.Area(contour); - - private static bool HasSelfIntersection(List contour) - { - int vertexCount = contour.Count - 1; - if (vertexCount < 4) - { - return false; - } - - for (int i = 0; i < vertexCount; i++) - { - Vertex segA1 = contour[i]; - Vertex segA2 = contour[i + 1]; - if (segA1 == segA2) - { - continue; - } - - for (int j = i + 1; j < vertexCount; j++) - { - if (j == i || j == i + 1 || (i == 0 && j == vertexCount - 1)) - { - continue; - } - - Vertex segB1 = contour[j]; - Vertex segB2 = contour[j + 1]; - if (segB1 == segB2) - { - continue; - } - - if (PolygonUtilities.SegmentsIntersect(segA1, segA2, segB1, segB2, true) || - (PolygonUtilities.IsCollinear(segA1, segA2, segB1) && - PolygonUtilities.IsCollinear(segA1, segA2, segB2) && - SegmentsOverlap(segA1, segA2, segB1, segB2))) - { - return true; - } - } - } - - return false; - } - - private static bool ContoursIntersect( - List left, - List right, - in Box2 leftBounds, - in Box2 rightBounds) - { - if (!leftBounds.Intersects(rightBounds)) - { - return false; - } - - int leftCount = left.Count - 1; - int rightCount = right.Count - 1; - for (int i = 0; i < leftCount; i++) - { - Vertex leftSeg1 = left[i]; - Vertex leftSeg2 = left[i + 1]; - if (leftSeg1 == leftSeg2) - { - continue; - } - - for (int j = 0; j < rightCount; j++) - { - Vertex rightSeg1 = right[j]; - Vertex rightSeg2 = right[j + 1]; - if (rightSeg1 == rightSeg2) - { - continue; - } - - if (PolygonUtilities.SegmentsIntersect(leftSeg1, leftSeg2, rightSeg1, rightSeg2, true) || - (PolygonUtilities.IsCollinear(leftSeg1, leftSeg2, rightSeg1) && - PolygonUtilities.IsCollinear(leftSeg1, leftSeg2, rightSeg2) && - SegmentsOverlap(leftSeg1, leftSeg2, rightSeg1, rightSeg2))) - { - return true; - } - } - } - - return false; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static bool SegmentsOverlap(in Vertex a1, in Vertex a2, in Vertex b1, in Vertex b2) - { - Vertex aMin = Vertex.Min(a1, a2); - Vertex aMax = Vertex.Max(a1, a2); - Vertex bMin = Vertex.Min(b1, b2); - Vertex bMax = Vertex.Max(b1, b2); - - return aMax.X >= bMin.X && - bMax.X >= aMin.X && - aMax.Y >= bMin.Y && - bMax.Y >= aMin.Y; - } - - /// - /// Builds subject paths from a polygon. - /// - /// The polygon to convert. - /// Whether input contour orientation should be normalized. - /// A list of fixed-precision vertex paths ready for clipping. - private static List> BuildSubjectPaths(Polygon polygon, bool normalizeForPositiveFill) - { - List> subject = new(polygon.Count); - List? sourceIndices = normalizeForPositiveFill ? new List(polygon.Count) : null; - for (int i = 0; i < polygon.Count; i++) - { - Contour contour = polygon[i]; - if (contour.Count == 0) - { - continue; - } - - bool isClosed = contour.Count > 1 && contour[0] == contour[^1]; - int capacity = contour.Count + (isClosed ? 0 : 1); - List path = new(capacity); - - CopyContourVertices(contour, isClosed, path); - subject.Add(path); - sourceIndices?.Add(i); - } - - if (normalizeForPositiveFill) - { - ApplyPositiveFillOrientation(polygon, subject, sourceIndices!); - } - - return subject; - } - - private static void CopyContourVertices(Contour source, bool isClosed, List destination) - { - for (int i = 0; i < source.Count; i++) - { - destination.Add(source[i]); - } - - if (!isClosed && destination.Count > 1 && destination[^1] != destination[0]) - { - destination.Add(destination[0]); - } - } - - private static void ApplyPositiveFillOrientation( - Polygon source, - List> subject, - List sourceIndices) - { - bool[]? reverseFlags = BuildPositiveFillReversalFlags(source, subject, sourceIndices); - if (reverseFlags == null) - { - return; - } - - for (int i = 0; i < reverseFlags.Length; i++) - { - if (reverseFlags[i]) - { - subject[i].Reverse(); - } - } - } - - private static bool[]? BuildPositiveFillReversalFlags( - Polygon source, - List> subject, - List sourceIndices) - { - int count = subject.Count; - if (count == 0) - { - return null; - } - - if (count == 1) - { - return GetSignedArea(subject[0]) < 0D ? [true] : null; - } - - using Buffer parentIndicesBuffer = new(count); - Span parentIndices = parentIndicesBuffer.GetSpan(); - parentIndices.Fill(-1); - - using Buffer signedAreasBuffer = new(count); - Span signedAreas = signedAreasBuffer.GetSpan(); - - bool hasHierarchy = false; - bool hasSignedAreas = false; - for (int i = 0; i < count; i++) - { - Contour contour = source[sourceIndices[i]]; - if (contour.ParentIndex == null && contour.HoleCount <= 0) - { - continue; - } - - hasHierarchy = true; - break; - } - - if (hasHierarchy) - { - int sourceCount = source.Count; - using Buffer sourceToSubjectBuffer = new(sourceCount); - Span sourceToSubject = sourceToSubjectBuffer.GetSpan(); - sourceToSubject.Fill(-1); - - for (int i = 0; i < sourceIndices.Count; i++) - { - sourceToSubject[sourceIndices[i]] = i; - } - - for (int i = 0; i < count; i++) - { - int sourceIndex = sourceIndices[i]; - int parentIndex = source[sourceIndex].ParentIndex ?? -1; - parentIndices[i] = parentIndex >= 0 && parentIndex < sourceCount - ? sourceToSubject[parentIndex] - : -1; - } - } - else - { - using Buffer boundsBuffer = new(count); - Span bounds = boundsBuffer.GetSpan(); - using Buffer absAreasBuffer = new(count); - Span absAreas = absAreasBuffer.GetSpan(); - - for (int i = 0; i < count; i++) - { - List contour = subject[i]; - bounds[i] = PolygonUtilities.GetBounds(contour); - double signedArea = GetSignedArea(contour); - signedAreas[i] = signedArea; - absAreas[i] = Math.Abs(signedArea); - - if (HasSelfIntersection(contour)) - { - // Avoid reorienting inputs that are already self-intersecting. - return null; - } - } - - for (int i = 0; i < count; i++) - { - for (int j = i + 1; j < count; j++) - { - if (ContoursIntersect(subject[i], subject[j], bounds[i], bounds[j])) - { - // Overlapping contours can change semantics when reoriented. - return null; - } - } - } - - hasSignedAreas = true; - - for (int i = 0; i < count; i++) - { - List contour = subject[i]; - if (contour.Count == 0) - { - continue; - } - - Vertex testPoint = GetContourTestPoint(contour); - double smallestArea = double.PositiveInfinity; - int parentIndex = -1; - for (int j = 0; j < count; j++) - { - if (i == j || !bounds[j].Contains(testPoint)) - { - continue; - } - - if (PolygonUtilities.PointInPolygon(testPoint, subject[j]) != PointInPolygonResult.Inside) - { - continue; - } - - if (absAreas[j] < smallestArea) - { - smallestArea = absAreas[j]; - parentIndex = j; - } - } - - parentIndices[i] = parentIndex; - } - } - - bool[] reverseFlags = new bool[count]; - bool needsReversal = false; - for (int i = 0; i < count; i++) - { - List contour = subject[i]; - if (contour.Count == 0) - { - continue; - } - - int depth = GetDepth(i, parentIndices); - bool shouldBeCounterClockwise = (depth & 1) == 0; - double signedArea = hasSignedAreas ? signedAreas[i] : GetSignedArea(contour); - bool isCounterClockwise = signedArea >= 0D; - if (isCounterClockwise != shouldBeCounterClockwise) - { - reverseFlags[i] = true; - needsReversal = true; - } - } - - return needsReversal ? reverseFlags : null; - } - - private sealed class OutputBuilder - { - // Clipper integer-space tolerances converted to double-space equivalents - // of ClipperD(6). - private const double NearPointDelta = 2E-6D; - private const double MinimumSplitArea = 2E-12D; - private const double SignificantTriangleArea = 1E-12D; - - private readonly SelfIntersectionSweepLine sweepLine; - private bool buildHierarchy; - - /// - /// Initializes a new instance of the class. - /// - public OutputBuilder() => this.sweepLine = new SelfIntersectionSweepLine(); - - /// - /// Gets or sets a value indicating whether collinear output points are preserved. - /// - public bool PreserveCollinear - { - get => this.sweepLine.PreserveCollinear; - set => this.sweepLine.PreserveCollinear = value; - } - - /// - /// Gets or sets a value indicating whether the output orientation is reversed. - /// - public bool ReverseSolution { get; set; } - - /// - /// Gets a retained-capacity score used by caller-side pooling policy. - /// - public int RetainedCapacityScore => this.sweepLine.RetainedCapacityScore; - - /// - /// Clears all cached input and output data. - /// - public void Clear() => this.sweepLine.Clear(); - - /// - /// Resets mutable state so this instance can be safely reused. - /// - public void ResetForReuse() - { - this.buildHierarchy = false; - this.ReverseSolution = false; - this.PreserveCollinear = true; - this.Clear(); - } - - /// - /// Adds subject contours to the sweep-line clipper. - /// - /// The subject contours to add. - public void AddSubject(List> paths) => this.sweepLine.AddSubject(paths); - - /// - /// Determines whether two points are within a tight tolerance. - /// - /// The first point. - /// The second point. - /// if the points are nearly coincident. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static bool ArePointsVeryClose(in Vertex firstPoint, in Vertex secondPoint) - { - Vertex delta = Vertex.Abs(firstPoint - secondPoint); - return delta.X < NearPointDelta && delta.Y < NearPointDelta; - } - - /// - /// Tests whether an output ring collapses to a very small triangle. - /// - /// A point on the ring. - /// if the triangle is degenerate. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static bool IsVerySmallTriangle(OutputPoint outputPoint) => outputPoint.Next!.Next == outputPoint.Prev && - (ArePointsVeryClose(outputPoint.Prev.Point, outputPoint.Next.Point) || - ArePointsVeryClose(outputPoint.Point, outputPoint.Next.Point) || - ArePointsVeryClose(outputPoint.Point, outputPoint.Prev.Point)); - - /// - /// Validates that an output ring is a non-degenerate closed loop. - /// - /// A point on the ring. - /// if the ring is valid. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static bool IsValidClosedPath(OutputPoint? outputPoint) => outputPoint != null && outputPoint.Next != outputPoint && - (outputPoint.Next != outputPoint.Prev || !IsVerySmallTriangle(outputPoint)); - - /// - /// Removes an output point from the ring and returns the next point. - /// - /// The output point to remove. - /// The next output point in the ring, or . - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static OutputPoint? RecycleOutputPoint(OutputPoint outputPoint) - { - OutputPoint? result = outputPoint.Next == outputPoint ? null : outputPoint.Next; - outputPoint.Prev.Next = outputPoint.Next; - outputPoint.Next!.Prev = outputPoint.Prev; - - return result; - } - - /// - /// Creates a new output record with the next stable index. - /// - /// The created output record. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private OutputRecord CreateOutputRecord() - { - int idx = this.sweepLine.OutputRecords.Count; - OutputRecord result = this.sweepLine.OutputRecords.Add(); - result.Index = idx; - return result; - } - - /// - /// Duplicates an output point and inserts it before or after the original. - /// - /// The point to duplicate. - /// Whether to insert after the original. - /// The newly inserted output point. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private OutputPoint DuplicateOutputPoint(OutputPoint outputPoint, bool insertAfter) - { - OutputPoint result = this.sweepLine.OutputPoints.Add(outputPoint.Point, outputPoint.OutputRecord); - if (insertAfter) - { - result.Next = outputPoint.Next; - result.Next!.Prev = result; - result.Prev = outputPoint; - outputPoint.Next = result; - } - else - { - result.Prev = outputPoint.Prev; - result.Prev.Next = result; - result.Next = outputPoint; - outputPoint.Prev = result; - } - - return result; - } - - /// - /// Removes collinear points and resolves self-intersections in an output record. - /// - /// The output record to clean. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void CleanCollinearEdges(OutputRecord? outputRecord) - { - outputRecord = SelfIntersectionSweepLine.ResolveOutputRecord(outputRecord); - - if (outputRecord == null) - { - return; - } - - if (!IsValidClosedPath(outputRecord.Points)) - { - outputRecord.Points = null; - return; - } - - OutputPoint startOp = outputRecord.Points!; - OutputPoint? outputPoint2 = startOp; - while (true) - { - // Preserve immediate A-B-A return spikes. The flat-ring fix injects - // these intentionally (touch -> tip -> touch), so we keep apex B even - // when collinear to avoid collapsing expected boundary detail. - bool isReturnSpikeApex = outputPoint2!.Prev.Point == outputPoint2.Next!.Point && - outputPoint2.Point != outputPoint2.Prev.Point; - if (PolygonUtilities.IsCollinear(outputPoint2!.Prev.Point, outputPoint2.Point, outputPoint2.Next!.Point) && - (outputPoint2.Point == outputPoint2.Prev.Point || - outputPoint2.Point == outputPoint2.Next.Point || - (!this.PreserveCollinear && !isReturnSpikeApex) || - (PolygonUtilities.Dot(outputPoint2.Prev.Point, outputPoint2.Point, outputPoint2.Next.Point) < 0 && - !isReturnSpikeApex))) - { - if (outputPoint2 == outputRecord.Points) - { - outputRecord.Points = outputPoint2.Prev; - } - - outputPoint2 = RecycleOutputPoint(outputPoint2); - if (!IsValidClosedPath(outputPoint2)) - { - outputRecord.Points = null; - return; - } - - startOp = outputPoint2!; - continue; - } - - outputPoint2 = outputPoint2.Next; - if (outputPoint2 == startOp) - { - break; - } - } - - this.FixSelfIntersections(outputRecord); - } - - /// - /// Splits an output record at a self-intersection. - /// - /// The record being split. - /// The output point where the split occurs. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void SplitOutputRecord(OutputRecord outputRecord, OutputPoint splitOp) - { - // The segments (splitOp.Prev, splitOp) and (splitOp.Next, splitOp.Next.Next) intersect. - OutputPoint prevOp = splitOp.Prev; - OutputPoint nextNextOp = splitOp.Next!.Next!; - outputRecord.Points = prevOp; - - PolygonUtilities.TryGetLineIntersection( - prevOp.Point, splitOp.Point, splitOp.Next.Point, nextNextOp.Point, out Vertex intersectionPoint); - - double area1 = SelfIntersectionSweepLine.ComputeSignedArea(prevOp); - double absArea1 = Math.Abs(area1); - - if (absArea1 < MinimumSplitArea) - { - outputRecord.Points = null; - return; - } - - double area2 = AreaTriangle(intersectionPoint, splitOp.Point, splitOp.Next.Point); - double absArea2 = Math.Abs(area2); - - // Remove the crossing segment and insert the intersection point. - if (intersectionPoint == prevOp.Point || intersectionPoint == nextNextOp.Point) - { - nextNextOp.Prev = prevOp; - prevOp.Next = nextNextOp; - } - else - { - OutputPoint newOp2 = this.sweepLine.OutputPoints.Add(intersectionPoint, outputRecord); - newOp2.Prev = prevOp; - newOp2.Next = nextNextOp; - nextNextOp.Prev = newOp2; - prevOp.Next = newOp2; - } - - // Note: area1 is the path's signed area *before* splitting, whereas area2 is - // the signed area of the triangle containing splitOp & splitOp.Next. - // So the only way for these areas to have the same sign is if - // the split triangle is larger than the path containing prevOp or - // if there's more than one self-intersection. - if (!(absArea2 > SignificantTriangleArea) || - (!(absArea2 > absArea1) && - ((area2 > 0) != (area1 > 0)))) - { - return; - } - - OutputRecord newOutputRecord = this.CreateOutputRecord(); - newOutputRecord.Owner = outputRecord.Owner; - splitOp.OutputRecord = newOutputRecord; - splitOp.Next.OutputRecord = newOutputRecord; - - OutputPoint newOp = this.sweepLine.OutputPoints.Add(intersectionPoint, newOutputRecord); - newOp.Prev = splitOp.Next; - newOp.Next = splitOp; - newOutputRecord.Points = newOp; - splitOp.Prev = newOp; - splitOp.Next.Next = newOp; - - if (!this.buildHierarchy) - { - return; - } - - if (SelfIntersectionSweepLine.IsPathInsidePath(prevOp, newOp)) - { - newOutputRecord.Splits ??= []; - newOutputRecord.Splits.Add(outputRecord.Index); - } - else - { - outputRecord.Splits ??= []; - outputRecord.Splits.Add(newOutputRecord.Index); - } - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static double AreaTriangle(in Vertex pt1, in Vertex pt2, in Vertex pt3) - => ((pt3.Y + pt1.Y) * (pt3.X - pt1.X)) + - ((pt1.Y + pt2.Y) * (pt1.X - pt2.X)) + - ((pt2.Y + pt3.Y) * (pt2.X - pt3.X)); - - /// - /// Resolves self-intersections within an output record. - /// - /// The output record to inspect. - private void FixSelfIntersections(OutputRecord outputRecord) - { - OutputPoint outputPoint2 = outputRecord.Points!; - if (outputPoint2.Prev == outputPoint2.Next!.Next) - { - // Triangles cannot self-intersect. - return; - } - - while (true) - { - if (PolygonUtilities.SegmentsIntersect( - outputPoint2!.Prev.Point, - outputPoint2.Point, - outputPoint2.Next!.Point, - outputPoint2.Next.Next!.Point)) - { - if (PolygonUtilities.SegmentsIntersect( - outputPoint2.Prev.Point, - outputPoint2.Point, - outputPoint2.Next.Next!.Point, - outputPoint2.Next.Next.Next!.Point)) - { - // Adjacent intersections (micro self-intersection). - outputPoint2 = this.DuplicateOutputPoint(outputPoint2, false); - outputPoint2.Point = outputPoint2.Next!.Next!.Next!.Point; - outputPoint2 = outputPoint2.Next; - } - else - { - if (outputPoint2 == outputRecord.Points || outputPoint2.Next == outputRecord.Points) - { - outputRecord.Points = outputRecord.Points.Prev; - } - - this.SplitOutputRecord(outputRecord, outputPoint2); - if (outputRecord.Points == null) - { - return; - } - - outputPoint2 = outputRecord.Points; - - // Triangles cannot self-intersect. - if (outputPoint2.Prev == outputPoint2.Next!.Next) - { - break; - } - - continue; - } - } - - outputPoint2 = outputPoint2.Next!; - if (outputPoint2 == outputRecord.Points) - { - break; - } - } - } - - /// - /// Builds a lightweight path from an output ring. - /// - /// A point on the output ring. - /// Whether to reverse point order. - /// The destination contour. - /// if a valid path was built. - private static bool BuildPath(OutputPoint? outputPoint, bool reverse, List path) - { - if (outputPoint == null || outputPoint.Next == outputPoint || outputPoint.Next == outputPoint.Prev) - { - return false; - } - - path.Clear(); - - Vertex lastPoint; - OutputPoint currentPoint; - if (reverse) - { - lastPoint = outputPoint.Point; - currentPoint = outputPoint.Prev; - } - else - { - outputPoint = outputPoint.Next!; - lastPoint = outputPoint.Point; - currentPoint = outputPoint.Next!; - } - - path.Add(lastPoint); - - while (currentPoint != outputPoint) - { - if (currentPoint.Point != lastPoint) - { - lastPoint = currentPoint.Point; - path.Add(lastPoint); - } - - currentPoint = reverse ? currentPoint.Prev : currentPoint.Next!; - } - - return path.Count != 3 || !IsVerySmallTriangle(currentPoint); - } - - /// - /// Builds a contour from an output ring. - /// - /// A point on the output ring. - /// Whether to reverse point order. - /// The destination contour. - /// if a valid contour was built. - private static bool BuildContour(OutputPoint? outputPoint, bool reverse, Contour contour) - { - if (outputPoint == null || outputPoint.Next == outputPoint || outputPoint.Next == outputPoint.Prev) - { - return false; - } - - contour.Clear(); - - Vertex lastPoint; - OutputPoint currentPoint; - if (reverse) - { - lastPoint = outputPoint.Point; - currentPoint = outputPoint.Prev; - } - else - { - outputPoint = outputPoint.Next!; - lastPoint = outputPoint.Point; - currentPoint = outputPoint.Next!; - } - - contour.Add(lastPoint); - - while (currentPoint != outputPoint) - { - Vertex current = currentPoint.Point; - if (current != lastPoint) - { - lastPoint = current; - contour.Add(lastPoint); - } - - currentPoint = reverse ? currentPoint.Prev : currentPoint.Next!; - } - - if (contour.Count == 3 && IsVerySmallTriangle(currentPoint)) - { - contour.Clear(); - return false; - } - - if (contour.Count < 3) - { - contour.Clear(); - return false; - } - - return true; - } - - /// - /// Ensures an output record has bounds populated and valid geometry. - /// - /// The output record to check. - /// if bounds are available. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private bool CheckOutputBounds(OutputRecord outputRecord) - { - if (outputRecord.Points == null) - { - return false; - } - - if (!outputRecord.Bounds.IsEmpty()) - { - return true; - } - - this.CleanCollinearEdges(outputRecord); - if (outputRecord.Points == null) - { - return false; - } - - if (outputRecord.OutputPointCount > 0) - { - outputRecord.Path.EnsureCapacity(outputRecord.OutputPointCount); - } - - if (!BuildPath(outputRecord.Points, this.ReverseSolution, outputRecord.Path)) - { - return false; - } - - outputRecord.Bounds = PolygonUtilities.GetBounds(outputRecord.Path); - return true; - } - - /// - /// Determines ownership for split output records. - /// - /// The output record whose owner is being resolved. - /// The split indices to evaluate. - /// if ownership could be resolved. - private bool CheckSplitOwner(OutputRecord outputRecord, List? splits) - { - // Use indexing because splits can be modified during iteration (Issue #1029). - for (int i = 0; i < splits!.Count; i++) - { - OutputRecord? splitRecord = this.sweepLine.OutputRecords[splits[i]]; - if (splitRecord.Points == null && splitRecord.Splits != null && - this.CheckSplitOwner(outputRecord, splitRecord.Splits)) - { - // Issue #942. - return true; - } - - splitRecord = SelfIntersectionSweepLine.ResolveOutputRecord(splitRecord); - if (splitRecord == null || splitRecord == outputRecord || splitRecord.RecursiveSplit == outputRecord) - { - continue; - } - - // Issue #599. - splitRecord.RecursiveSplit = outputRecord; - - if (splitRecord.Splits != null && this.CheckSplitOwner(outputRecord, splitRecord.Splits)) - { - return true; - } - - if (!this.CheckOutputBounds(splitRecord) || - !splitRecord.Bounds.Contains(outputRecord.Bounds) || - !SelfIntersectionSweepLine.IsPathInsidePath(outputRecord.Points!, splitRecord.Points!)) - { - continue; - } - - // splitRecord is owned by outputRecord (Issue #957). - if (!SelfIntersectionSweepLine.IsOwnerValid(outputRecord, splitRecord)) - { - splitRecord.Owner = outputRecord.Owner; - } - - // Found in splitRecord. - outputRecord.Owner = splitRecord; - return true; - } - - return false; - } - - /// - /// Resolves the owning output record for hierarchy construction. - /// - /// The output record to resolve. - private void ResolveOutputOwner(OutputRecord outputRecord) - { - if (outputRecord.Bounds.IsEmpty()) - { - return; - } - - while (outputRecord.Owner != null) - { - if (outputRecord.Owner.Splits != null && - this.CheckSplitOwner(outputRecord, outputRecord.Owner.Splits)) - { - break; - } - - if (outputRecord.Owner.Points != null && this.CheckOutputBounds(outputRecord.Owner) && - SelfIntersectionSweepLine.IsPathInsidePath(outputRecord.Points!, outputRecord.Owner.Points!)) - { - break; - } - - outputRecord.Owner = outputRecord.Owner.Owner; - } - } - - /// - /// Builds and returns a hierarchical polygon from output records. - /// - /// The initial contour capacity for the output polygon. - /// The built polygon. - private Polygon BuildPolygon(int resultCapacity) - { - int validClosedCount = 0; - int i = 0; - - // First pass: validate bounds and resolve owners. - // Complexity is O(N) over current output records, but N can grow during - // the pass because CheckOutputBounds may split/fix paths and append records. - while (i < this.sweepLine.OutputRecords.Count) - { - OutputRecord outputRecord = this.sweepLine.OutputRecords[i++]; - if (outputRecord.Points == null) - { - continue; - } - - if (this.CheckOutputBounds(outputRecord)) - { - this.ResolveOutputOwner(outputRecord); - validClosedCount++; - } - } - - if (validClosedCount == 0) - { - return new Polygon(resultCapacity); - } - - int outputRecordCount = this.sweepLine.OutputRecords.Count; - Polygon polygon = new(Math.Max(resultCapacity, validClosedCount)); - using Buffer contourIndexBuffer = new(outputRecordCount); - Span contourIndexByOutputRecord = contourIndexBuffer.GetSpan(); - contourIndexByOutputRecord.Fill(-1); - - // Second pass: build contours and map OutputRecord.Index -> contour index. - // This avoids a dictionary allocation and keeps lookups O(1). - for (int index = 0; index < outputRecordCount; index++) - { - OutputRecord outputRecord = this.sweepLine.OutputRecords[index]; - if (outputRecord.Points == null || outputRecord.Bounds.IsEmpty()) - { - continue; - } - - int estimatedCapacity = outputRecord.OutputPointCount > 0 - ? outputRecord.OutputPointCount - : 0; - Contour contour = estimatedCapacity > 0 ? new Contour(estimatedCapacity) : []; - if (!BuildContour(outputRecord.Points, this.ReverseSolution, contour)) - { - continue; - } - - int contourIndex = polygon.Count; - polygon.Add(contour); - int outputRecordIndex = outputRecord.Index; - if ((uint)outputRecordIndex < (uint)contourIndexByOutputRecord.Length) - { - contourIndexByOutputRecord[outputRecordIndex] = contourIndex; - } - } - - if (polygon.Count == 0) - { - return polygon; - } - - for (int index = 0; index < polygon.Count; index++) - { - Contour contour = polygon[index]; - contour.ParentIndex = null; - contour.Depth = 0; - contour.ClearHoles(); - } - - // Third pass: map owner links to parent contour indices. - for (int index = 0; index < outputRecordCount; index++) - { - OutputRecord outputRecord = this.sweepLine.OutputRecords[index]; - int outputRecordIndex = outputRecord.Index; - if ((uint)outputRecordIndex >= (uint)contourIndexByOutputRecord.Length) - { - continue; - } - - int contourIndex = contourIndexByOutputRecord[outputRecordIndex]; - if (contourIndex < 0) - { - continue; - } - - OutputRecord? owner = outputRecord.Owner; - while (owner != null) - { - int ownerIndex = owner.Index; - if ((uint)ownerIndex < (uint)contourIndexByOutputRecord.Length) - { - int parentIndex = contourIndexByOutputRecord[ownerIndex]; - if (parentIndex >= 0) - { - polygon[contourIndex].ParentIndex = parentIndex; - break; - } - } - - owner = owner.Owner; - } - } - - // Fourth pass: depth is owner-chain length within the emitted contour set. - for (int index = 0; index < outputRecordCount; index++) - { - OutputRecord outputRecord = this.sweepLine.OutputRecords[index]; - int outputRecordIndex = outputRecord.Index; - if ((uint)outputRecordIndex >= (uint)contourIndexByOutputRecord.Length) - { - continue; - } - - int contourIndex = contourIndexByOutputRecord[outputRecordIndex]; - if (contourIndex < 0) - { - continue; - } - - // Depth is the number of owning contours in the chain. - int depth = 0; - OutputRecord? owner = outputRecord.Owner; - while (owner != null) - { - int ownerIndex = owner.Index; - if ((uint)ownerIndex < (uint)contourIndexByOutputRecord.Length && - contourIndexByOutputRecord[ownerIndex] >= 0) - { - depth++; - } - - owner = owner.Owner; - } - - polygon[contourIndex].Depth = depth; - } - - for (int index = 0; index < polygon.Count; index++) - { - Contour contour = polygon[index]; - if (contour.ParentIndex != null) - { - // Map parent links to hole indices for quick traversal. - polygon[contour.ParentIndex.Value].AddHoleIndex(index); - } - } - - return polygon; - } - - /// - /// Executes the union and returns a hierarchical polygon. - /// - /// The initial contour capacity for the output polygon. - /// The resulting polygon. - public Polygon Execute(int resultCapacity) - { - this.buildHierarchy = true; - bool succeeded = this.sweepLine.Execute(true); - Polygon result = succeeded ? this.BuildPolygon(resultCapacity) : []; - this.sweepLine.ClearSolutionData(); - return result; - } - } -} diff --git a/src/PolygonClipper/SelfIntersectionSweepLine.cs b/src/PolygonClipper/SelfIntersectionSweepLine.cs deleted file mode 100644 index 54448b6..0000000 --- a/src/PolygonClipper/SelfIntersectionSweepLine.cs +++ /dev/null @@ -1,2611 +0,0 @@ -// Copyright (c) Six Labors. -// Licensed under the Six Labors Split License. - -using System.Runtime.CompilerServices; - -namespace SixLabors.PolygonClipper; - -/// -/// Sweep-line union clipper specialized for self-intersection removal. -/// -/// -/// This clipper consumes subject-only paths and applies positive winding fill -/// semantics to compute the union. It reuses pooled data structures to keep allocations low. -/// -internal sealed class SelfIntersectionSweepLine -{ - // Clipper's integer constants are calibrated for scaled coordinates. - // This port operates directly in double-space, so thresholds must be - // converted to the equivalent ClipperD(6) magnitudes. - private const double JoinExtremaDelta = 2E-6D; - private const double JoinPerpendicularDistanceSquaredTolerance = 2.5E-13D; - private const int HorizontalLoopFailSafeLimit = 100_000; - - private readonly ActiveEdgeList activeEdges; - private readonly ScanlineSchedule scanlineSchedule; - private readonly List intersectionList; - private readonly VertexPoolList vertexList; - private readonly List horizontalSegments; - private readonly HorizontalJoinPoolList horizontalJoins; - private double currentScanlineBottomY; - private bool buildHierarchy; - private bool succeeded; - - /// - /// Initializes a new instance of the class. - /// - public SelfIntersectionSweepLine() - { - this.activeEdges = new ActiveEdgeList(); - this.scanlineSchedule = new ScanlineSchedule(); - this.intersectionList = []; - this.vertexList = []; - this.OutputRecords = []; - this.horizontalSegments = []; - this.horizontalJoins = []; - this.OutputPoints = []; - this.PreserveCollinear = true; - } - - /// - /// Gets or sets a value indicating whether collinear output points are preserved. - /// - public bool PreserveCollinear { get; set; } - - /// - /// Gets the pooled output records produced by the sweep. - /// - public OutputRecordPoolList OutputRecords { get; } - - /// - /// Gets the pooled output points produced by the sweep. - /// - public OutputPointPoolList OutputPoints { get; } - - /// - /// Gets a retained-capacity score used by caller-side pooling policy. - /// - public int RetainedCapacityScore => - this.scanlineSchedule.RetainedCapacityScore + - this.intersectionList.Capacity + - this.vertexList.Capacity + - this.horizontalSegments.Capacity + - this.horizontalJoins.Capacity + - this.OutputRecords.Capacity + - this.OutputPoints.Capacity + - this.activeEdges.RetainedPoolCount; - - /// - /// Swaps two active edge references. - /// - /// The first active edge. - /// The second active edge. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static void SwapActiveEdges(ref ActiveEdge edge1, ref ActiveEdge edge2) => (edge2, edge1) = (edge1, edge2); - - /// - /// Locates the active edge that shares the same maxima vertex. - /// - /// The active edge being matched. - /// The paired maxima edge, or if none exists in the active list. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static ActiveEdge? FindMaximaPair(ActiveEdge edge) - { - ActiveEdge? edge2 = edge.NextInAel; - while (edge2 != null) - { - if (edge2.VertexTop == edge.VertexTop) - { - // Matched the companion maxima edge. - return edge2; - } - - edge2 = edge2.NextInAel; - } - - return null; - } - - /// - /// Returns the maxima vertex on the current Y scanline for the edge. - /// - /// The active edge to inspect. - /// The maxima vertex at the current Y, or if not a maxima. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static SweepVertex? GetMaximaVertexAtCurrentY(ActiveEdge edge) - { - SweepVertex? result = edge.VertexTop; - if (result == null) - { - return null; - } - - SweepVertex start = result; - - // Horizontal plateaus at the top can have multiple same-Y vertices. - // Follow the plateau in winding direction to find the effective scanline - // endpoint candidate in O(k), where k is plateau length. - if (edge.WindDelta > 0) - { - while (result.Next!.Point.Y == result.Point.Y) - { - SweepVertex next = result.Next; - if (next == start) - { - break; - } - - result = next; - } - } - else - { - while (result.Prev!.Point.Y == result.Point.Y) - { - SweepVertex prev = result.Prev; - if (prev == start) - { - break; - } - - result = prev; - } - } - - // If the traversed endpoint is not flagged maxima but the start vertex is - // a maxima on the same scanline, prefer the explicit maxima marker. - if (!result.IsMaxima && start.IsMaxima && start.Point.Y == result.Point.Y) - { - result = start; - } - - if (!result.IsMaxima) - { - // No maxima at the current scanline. - result = null; - } - - return result; - } - - /// - /// Assigns the output record edges that define the front and back sides. - /// - /// The output record to update. - /// The edge used for the front side. - /// The edge used for the back side. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static void SetOutputSides(OutputRecord outputRecord, ActiveEdge startEdge, ActiveEdge endEdge) - { - outputRecord.FrontEdge = startEdge; - outputRecord.BackEdge = endEdge; - } - - /// - /// Swaps output record ownership between two active edges. - /// - /// The first active edge. - /// The second active edge. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static void SwapOutputRecords(ActiveEdge edge1, ActiveEdge edge2) - { - // At least one edge already owns an output record. - OutputRecord? outputRecord1 = edge1.OutputRecord; - OutputRecord? outputRecord2 = edge2.OutputRecord; - if (outputRecord1 == outputRecord2) - { - ActiveEdge? edge = outputRecord1!.FrontEdge; - outputRecord1.FrontEdge = outputRecord1.BackEdge; - outputRecord1.BackEdge = edge; - return; - } - - if (outputRecord1 != null) - { - if (edge1 == outputRecord1.FrontEdge) - { - outputRecord1.FrontEdge = edge2; - } - else - { - outputRecord1.BackEdge = edge2; - } - } - - if (outputRecord2 != null) - { - if (edge2 == outputRecord2.FrontEdge) - { - outputRecord2.FrontEdge = edge1; - } - else - { - outputRecord2.BackEdge = edge1; - } - } - - edge1.OutputRecord = outputRecord2; - edge2.OutputRecord = outputRecord1; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static bool IsTwoVertexFlatRingEdge(ActiveEdge edge) => - - // Degenerate "ring" used by issue-style tests: two opposing horizontal - // edges around a single local minimum (A-B-A). This is an O(1) shape check. - edge.IsHorizontal && edge.LocalMin.Vertex.Prev == edge.LocalMin.Vertex.Next; - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static Vertex GetFlatRingTip(ActiveEdge flatEdge, in Vertex touchPoint) - { - // If touch is at an endpoint, the tip is the opposite endpoint. - if (touchPoint == flatEdge.Bottom) - { - return flatEdge.Top; - } - - if (touchPoint == flatEdge.Top) - { - return flatEdge.Bottom; - } - - // Otherwise choose the endpoint farther from the touch in X. - // This gives a stable spike apex for touch->tip->touch emission. - double bottomDx = Math.Abs(touchPoint.X - flatEdge.Bottom.X); - double topDx = Math.Abs(touchPoint.X - flatEdge.Top.X); - return bottomDx > topDx ? flatEdge.Bottom : flatEdge.Top; - } - - /// - /// Assigns an output record's owner while preventing cyclic ownership. - /// - /// The output record to update. - /// The candidate owner. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static void SetOutputOwner(OutputRecord outputRecord, OutputRecord newOwner) - { - // Precondition: newOwner is never null. - while (newOwner.Owner != null && newOwner.Owner.Points == null) - { - newOwner.Owner = newOwner.Owner.Owner; - } - - // Avoid cycles: ensure outputRecord is not already an ancestor of newOwner. - OutputRecord? tmp = newOwner; - while (tmp != null && tmp != outputRecord) - { - tmp = tmp.Owner; - } - - if (tmp != null) - { - newOwner.Owner = outputRecord.Owner; - } - - outputRecord.Owner = newOwner; - } - - /// - /// Computes the signed area of a closed output ring. - /// - /// A point on the output ring. - /// The signed area of the ring. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static double ComputeSignedArea(OutputPoint outputPoint) - { - // Use a local origin, as for PolygonUtilities.Area, without materializing - // the linked ring. Absolute-coordinate products can lose a small area. - Vertex origin = outputPoint.Point; - double signedArea = 0.0; - OutputPoint outputPoint2 = outputPoint; - do - { - signedArea += Vertex.Cross(outputPoint2.Prev.Point - origin, outputPoint2.Point - origin); - outputPoint2 = outputPoint2.Next!; - } - while (outputPoint2 != outputPoint); - return signedArea * 0.5; - } - - /// - /// Resolves a non-null output record that still owns geometry. - /// - /// The candidate output record. - /// The resolved output record, or if none remains. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static OutputRecord? ResolveOutputRecord(OutputRecord? outputRecord) - { - while (outputRecord != null && outputRecord.Points == null) - { - outputRecord = outputRecord.Owner; - } - - return outputRecord; - } - - /// - /// Validates that an output record is not owned by a descendant. - /// - /// The output record to validate. - /// The owner candidate. - /// when the ownership chain is valid. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool IsOwnerValid(OutputRecord? outputRecord, OutputRecord? testOwner) - { - while (testOwner != null && testOwner != outputRecord) - { - testOwner = testOwner.Owner; - } - - return testOwner == null; - } - - /// - /// Clears output record links from a hot edge. - /// - /// The active edge to detach. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static void DetachOutputRecord(ActiveEdge edge) - { - OutputRecord? outputRecord = edge.OutputRecord; - if (outputRecord == null) - { - return; - } - - outputRecord.FrontEdge!.OutputRecord = null; - outputRecord.BackEdge!.OutputRecord = null; - outputRecord.FrontEdge = null; - outputRecord.BackEdge = null; - } - - /// - /// Determines whether an edge is the front edge of its output record. - /// - /// The active edge to query. - /// when the edge is the front edge. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static bool IsOutputRecordAscending(ActiveEdge hotEdge) => hotEdge == hotEdge.OutputRecord!.FrontEdge; - - /// - /// Checks whether the two edges in an intersection node are adjacent in the active list. - /// - /// The intersection node to inspect. - /// if the edges are adjacent in the active list. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static bool AreEdgesAdjacentInActiveList(in IntersectNode intersectionNode) - => (intersectionNode.Edge1.NextInAel == intersectionNode.Edge2) || (intersectionNode.Edge1.PrevInAel == intersectionNode.Edge2); - - /// - /// Clears solution-only data while preserving the input vertices and minima list. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void ClearSolutionData() - { - this.activeEdges.ClearActiveEdges(); - this.scanlineSchedule.ClearScanlines(); - this.ClearIntersectionNodes(); - this.OutputRecords.Clear(); - this.horizontalSegments.Clear(); - this.horizontalJoins.Clear(); - this.OutputPoints.Clear(); - } - - /// - /// Clears all clipper state, including cached input data. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Clear() - { - this.ClearSolutionData(); - this.scanlineSchedule.Clear(); - this.vertexList.Clear(); - } - - /// - /// Resets scanline state and sorts local minima before an execution pass. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void ResetState() - { - this.scanlineSchedule.Reset(); - this.currentScanlineBottomY = 0; - this.activeEdges.Reset(); - this.succeeded = true; - } - - /// - /// Adds subject contours for the union operation. - /// - /// The subject contours to add. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void AddSubject(List> paths) - { - this.scanlineSchedule.MarkDirty(); - this.AddPathsToVertexList(paths); - } - - /// - /// Registers a local minima vertex once for the sweep. - /// - /// The vertex that marks a local minima. - /// The schedule collecting minima. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static void RegisterLocalMinima(SweepVertex vertex, ScanlineSchedule scanlineSchedule) - { - // Guard against registering the same vertex twice. - if ((vertex.Flags & VertexFlags.LocalMin) != VertexFlags.None) - { - return; - } - - vertex.Flags |= VertexFlags.LocalMin; - scanlineSchedule.AddLocalMinima(new LocalMinima(vertex)); - } - - /// - /// Builds circular vertex lists and captures local minima/maxima for the sweep. - /// - /// The subject contours to process. - private void AddPathsToVertexList(List> paths) - { - int totalVertCnt = 0; - foreach (List path in paths) - { - totalVertCnt += path.Count; - } - - // Pre-size the pool to avoid growth during vertex creation. - this.vertexList.EnsureCapacity(this.vertexList.Count + totalVertCnt); - - foreach (List path in paths) - { - SweepVertex? v0 = null; - SweepVertex? prevVertex = null; - SweepVertex? currVertex; - foreach (Vertex point in path) - { - if (v0 == null) - { - v0 = this.vertexList.Add(point, VertexFlags.None, null); - prevVertex = v0; - continue; - } - - if (prevVertex!.Point != point) - { - currVertex = this.vertexList.Add(point, VertexFlags.None, prevVertex); - prevVertex.Next = currVertex; - prevVertex = currVertex; - } - } - - if (v0 == null || prevVertex?.Prev == null) - { - continue; - } - - if (prevVertex.Point == v0.Point) - { - prevVertex = prevVertex.Prev; - } - - prevVertex.Next = v0; - v0.Prev = prevVertex; - if (prevVertex.Next == prevVertex) - { - continue; - } - - // Non-degenerate closed ring. - prevVertex = v0.Prev; - while (prevVertex != v0 && prevVertex!.Point.Y == v0.Point.Y) - { - prevVertex = prevVertex.Prev; - } - - if (prevVertex == v0) - { - // Flat closed rings still contribute when they touch other contours. - if (!RegisterFlatRingExtrema(v0, this.scanlineSchedule)) - { - continue; - } - - continue; - } - - bool goingUp = prevVertex.Point.Y > v0.Point.Y; - - bool goingUp0 = goingUp; - prevVertex = v0; - currVertex = v0.Next; - while (currVertex != v0) - { - if (currVertex!.Point.Y > prevVertex.Point.Y && goingUp) - { - prevVertex.Flags |= VertexFlags.LocalMax; - goingUp = false; - } - else if (currVertex.Point.Y < prevVertex.Point.Y && !goingUp) - { - goingUp = true; - RegisterLocalMinima(prevVertex, this.scanlineSchedule); - } - - prevVertex = currVertex; - currVertex = currVertex.Next; - } - - if (goingUp != goingUp0) - { - if (goingUp0) - { - RegisterLocalMinima(prevVertex, this.scanlineSchedule); - } - else - { - prevVertex.Flags |= VertexFlags.LocalMax; - } - } - } - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static bool RegisterFlatRingExtrema(SweepVertex start, ScanlineSchedule scanlineSchedule) - { - // For a fully flat closed ring, derive synthetic extrema by scanning once - // for left/right-most vertices: O(m) in ring vertex count. - SweepVertex leftMost = start; - SweepVertex rightMost = start; - SweepVertex current = start.Next!; - while (current != start) - { - if (current.Point.X < leftMost.Point.X) - { - leftMost = current; - } - - if (current.Point.X > rightMost.Point.X) - { - rightMost = current; - } - - current = current.Next!; - } - - if (leftMost == rightMost) - { - return false; - } - - rightMost.Flags |= VertexFlags.LocalMax; - RegisterLocalMinima(leftMost, scanlineSchedule); - return true; - } - - /// - /// Determines whether a closed edge contributes to the union result. - /// - /// The edge to test. - /// if the edge contributes. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static bool IsContributingClosedEdge(ActiveEdge edge) => edge.WindCount == 1; - - /// - /// Updates the winding count for a closed path edge. - /// - /// The active edge to update. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static void SetWindingCountForClosedEdge(ActiveEdge edge) - { - // Winding counts apply to regions, not edges. The edge wind count tracks the - // higher of the two adjacent region counts. Adjacent regions differ by one. - ActiveEdge? edge2 = edge.PrevInAel; - - if (edge2 == null) - { - edge.WindCount = edge.WindDelta; - } - else - { - // If edge2's wind count follows its wind delta, - // the filled region is to the right of edge2 (so edge is inside). Neither value is 0. - if (edge2.WindCount * edge2.WindDelta < 0) - { - // Opposite signs: edge lies outside edge2's region. - if (Math.Abs(edge2.WindCount) > 1) - { - // Outside this polygon but still inside another. - if (edge2.WindDelta * edge.WindDelta < 0) - { - // Reversing direction; keep the same winding count. - edge.WindCount = edge2.WindCount; - } - else - { - // Otherwise step the winding count toward zero. - edge.WindCount = edge2.WindCount + edge.WindDelta; - } - } - else - { - // Outside all polygons; reset to the edge's own winding. - edge.WindCount = edge.WindDelta; - } - } - else - { - // Same sign: edge lies inside edge2's region. - if (edge2.WindDelta * edge.WindDelta < 0) - { - // Reversing direction; keep the same winding count. - edge.WindCount = edge2.WindCount; - } - else - { - // Otherwise step the winding count away from zero. - edge.WindCount = edge2.WindCount + edge.WindDelta; - } - } - } - } - - /// - /// Inserts any local minima that occur at the current scanline into the active list. - /// - /// The current scanline Y coordinate. - private void InsertLocalMinimaIntoActiveList(double botY) - { - // Insert all minima on the current scanline. - // Horizontal minima use the previous vertex as the descending bound. - while (this.scanlineSchedule.HasLocalMinimaAtY(botY)) - { - LocalMinima localMinima = this.scanlineSchedule.PopLocalMinima(); - ActiveEdge leftBound = this.activeEdges.Acquire(); - leftBound.Bottom = localMinima.Vertex.Point; - leftBound.CurrentX = localMinima.Vertex.Point.X; - leftBound.WindDelta = -1; - leftBound.VertexTop = localMinima.Vertex.Prev; - leftBound.Top = localMinima.Vertex.Prev!.Point; - leftBound.OutputRecord = null; - leftBound.LocalMin = localMinima; - leftBound.UpdateDx(); - - ActiveEdge rightBound = this.activeEdges.Acquire(); - rightBound.Bottom = localMinima.Vertex.Point; - rightBound.CurrentX = localMinima.Vertex.Point.X; - rightBound.WindDelta = 1; - - // Ascending bound. - rightBound.VertexTop = localMinima.Vertex.Next; - rightBound.Top = localMinima.Vertex.Next!.Point; - rightBound.OutputRecord = null; - rightBound.LocalMin = localMinima; - rightBound.UpdateDx(); - - // leftBound starts descending and rightBound ascending. - // Swap them if their geometric ordering is inverted. - if (leftBound.IsHorizontal) - { - if (leftBound.IsHeadingRightHorizontal) - { - SwapActiveEdges(ref leftBound, ref rightBound); - } - } - else if (rightBound.IsHorizontal) - { - if (rightBound.IsHeadingLeftHorizontal) - { - SwapActiveEdges(ref leftBound, ref rightBound); - } - } - else if (leftBound.Dx < rightBound.Dx) - { - SwapActiveEdges(ref leftBound, ref rightBound); - } - - bool contributing; - leftBound.IsLeftBound = true; - this.activeEdges.InsertLeft(leftBound); - - SetWindingCountForClosedEdge(leftBound); - contributing = IsContributingClosedEdge(leftBound); - if (leftBound.IsHorizontal && - rightBound.IsHorizontal && - leftBound.LocalMin.Vertex.Prev == leftBound.LocalMin.Vertex.Next) - { - contributing = false; - } - - rightBound.WindCount = leftBound.WindCount; - ActiveEdgeList.InsertRight(leftBound, rightBound); - - if (contributing) - { - _ = this.AddLocalMinimumOutput(leftBound, rightBound, leftBound.Bottom, true); - if (!leftBound.IsHorizontal) - { - this.CheckJoinLeft(leftBound, leftBound.Bottom); - } - } - - while (rightBound.NextInAel != null && - ActiveEdgeList.IsValidActiveEdgeOrder(rightBound.NextInAel, rightBound)) - { - this.IntersectActiveEdges(rightBound, rightBound.NextInAel, rightBound.Bottom); - this.activeEdges.SwapPositions(rightBound, rightBound.NextInAel); - } - - if (rightBound.IsHorizontal) - { - this.activeEdges.PushHorizontal(rightBound); - } - else - { - this.CheckJoinRight(rightBound, rightBound.Bottom); - this.scanlineSchedule.InsertScanline(rightBound.Top.Y); - } - - if (leftBound.IsHorizontal) - { - this.activeEdges.PushHorizontal(leftBound); - } - else - { - this.scanlineSchedule.InsertScanline(leftBound.Top.Y); - } - } - } - - /// - /// Creates a new output record at a local minimum. - /// - /// The first bound edge. - /// The second bound edge. - /// The local minimum point. - /// Whether this output is created for a split. - /// The created output point. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private OutputPoint AddLocalMinimumOutput(ActiveEdge edge1, ActiveEdge edge2, Vertex point, bool isNew = false) - { - OutputRecord outputRecord = this.CreateOutputRecord(); - edge1.OutputRecord = outputRecord; - edge2.OutputRecord = outputRecord; - - ActiveEdge? prevHotEdge = edge1.GetPrevHotEdge(); - - // WindDelta reflects input winding, not output orientation. - // Output orientation is driven by which edge is assigned as the front (ascending) edge. - if (prevHotEdge != null) - { - if (this.buildHierarchy) - { - SetOutputOwner(outputRecord, prevHotEdge.OutputRecord!); - } - - outputRecord.Owner = prevHotEdge.OutputRecord; - if (IsOutputRecordAscending(prevHotEdge) == isNew) - { - SetOutputSides(outputRecord, edge2, edge1); - } - else - { - SetOutputSides(outputRecord, edge1, edge2); - } - } - else - { - outputRecord.Owner = null; - if (isNew) - { - SetOutputSides(outputRecord, edge1, edge2); - } - else - { - SetOutputSides(outputRecord, edge2, edge1); - } - } - - OutputPoint outputPoint = this.OutputPoints.Add(point, outputRecord); - outputRecord.Points = outputPoint; - return outputPoint; - } - - /// - /// Joins two output records when a local maximum is encountered. - /// - /// The first active edge. - /// The second active edge. - /// The local maximum point. - /// The last output point, or when no output remains. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private OutputPoint? AddLocalMaximumOutput(ActiveEdge edge1, ActiveEdge edge2, Vertex point) - { - if (IsJoined(edge1)) - { - this.SplitEdge(edge1, point); - } - - if (IsJoined(edge2)) - { - this.SplitEdge(edge2, point); - } - - if (edge1.IsFront == edge2.IsFront) - { - bool hasTwoVertexFlatEdge = - (edge1.IsHorizontal && edge1.NextVertex == edge1.LocalMin.Vertex) || - (edge2.IsHorizontal && edge2.NextVertex == edge2.LocalMin.Vertex); - if (hasTwoVertexFlatEdge) - { - OutputPoint outputPoint = this.AddOutputPoint(edge1, point); - _ = this.AddOutputPoint(edge2, point); - SwapOutputRecords(edge1, edge2); - return outputPoint; - } - - if (edge1.IsHorizontal && edge2.IsHorizontal) - { - return this.AddOutputPoint(edge1, point); - } - - this.succeeded = false; - return null; - } - - OutputPoint result = this.AddOutputPoint(edge1, point); - if (edge1.OutputRecord == edge2.OutputRecord) - { - OutputRecord outputRecord = edge1.OutputRecord!; - outputRecord.Points = result; - - if (this.buildHierarchy) - { - ActiveEdge? e = edge1.GetPrevHotEdge(); - if (e == null) - { - outputRecord.Owner = null; - } - else - { - SetOutputOwner(outputRecord, e.OutputRecord!); - } - - // Owner assignment here is provisional and will be resolved later. - } - - DetachOutputRecord(edge1); - } - - // Join in index order to preserve output orientation. - else if (edge1.OutputRecord!.Index < edge2.OutputRecord!.Index) - { - JoinOutputRecords(edge1, edge2); - } - else - { - JoinOutputRecords(edge2, edge1); - } - - return result; - } - - /// - /// Merges the output paths from two active edges into a single record. - /// - /// The primary edge to keep. - /// The secondary edge to merge. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static void JoinOutputRecords(ActiveEdge edge1, ActiveEdge edge2) - { - // Append edge2's path onto edge1's path, then discard edge2's path pointers. - // The joining ends rarely share coordinates, so pointer swaps are safe. - OutputPoint p1Start = edge1.OutputRecord!.Points!; - OutputPoint p2Start = edge2.OutputRecord!.Points!; - OutputPoint p1End = p1Start.Next!; - OutputPoint p2End = p2Start.Next!; - if (edge1.IsFront) - { - p2End.Prev = p1Start; - p1Start.Next = p2End; - p2Start.Next = p1End; - p1End.Prev = p2Start; - edge1.OutputRecord!.Points = p2Start; - - edge1.OutputRecord!.FrontEdge = edge2.OutputRecord!.FrontEdge; - if (edge1.OutputRecord!.FrontEdge != null) - { - edge1.OutputRecord!.FrontEdge!.OutputRecord = edge1.OutputRecord; - } - } - else - { - p1End.Prev = p2Start; - p2Start.Next = p1End; - p1Start.Next = p2End; - p2End.Prev = p1Start; - - edge1.OutputRecord!.BackEdge = edge2.OutputRecord!.BackEdge; - if (edge1.OutputRecord!.BackEdge != null) - { - edge1.OutputRecord!.BackEdge!.OutputRecord = edge1.OutputRecord; - } - } - - // After joining, edge2's output record contains no vertices. - edge2.OutputRecord!.FrontEdge = null; - edge2.OutputRecord!.BackEdge = null; - edge2.OutputRecord!.Points = null; - edge1.OutputRecord!.OutputPointCount += edge2.OutputRecord!.OutputPointCount; - SetOutputOwner(edge2.OutputRecord, edge1.OutputRecord); - - // and edge1 and edge2 are maxima and are about to be dropped from the Actives list. - edge1.OutputRecord = null; - edge2.OutputRecord = null; - } - - /// - /// Adds an output point to the front or back of the current output record. - /// - /// The active edge that owns the output. - /// The point to add. - /// The output point that was added or reused. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private OutputPoint AddOutputPoint(ActiveEdge edge, Vertex point) - { - // outputRecord.Points is a circular list; Points is the front point and - // Points.Next is the back point for this output record. - OutputRecord outputRecord = edge.OutputRecord!; - bool toFront = edge.IsFront; - OutputPoint opFront = outputRecord.Points!; - OutputPoint opBack = opFront.Next!; - - switch (toFront) - { - case true when point == opFront.Point: - return opFront; - case false when point == opBack.Point: - return opBack; - } - - OutputPoint newOp = this.OutputPoints.Add(point, outputRecord); - opBack.Prev = newOp; - newOp.Prev = opFront; - newOp.Next = opBack; - opFront.Next = newOp; - if (toFront) - { - outputRecord.Points = newOp; - } - - return newOp; - } - - /// - /// Creates a new output record and assigns the next index. - /// - /// The created output record. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private OutputRecord CreateOutputRecord() - { - int idx = this.OutputRecords.Count; - OutputRecord result = this.OutputRecords.Add(); - result.Index = idx; - return result; - } - - /// - /// Advances the active edge to the next vertex in the scanbeam. - /// - /// The active edge to update. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void UpdateEdgeInActiveList(ActiveEdge edge) - { - edge.Bottom = edge.Top; - edge.VertexTop = edge.NextVertex; - edge.Top = edge.VertexTop.Point; - edge.CurrentX = edge.Bottom.X; - edge.UpdateDx(); - - if (IsJoined(edge)) - { - // Split joined edges before advancing to avoid missing intersections. - this.SplitEdge(edge, edge.Bottom); - } - - if (edge.IsHorizontal) - { - TrimHorizontal(edge, this.PreserveCollinear); - - return; - } - - this.scanlineSchedule.InsertScanline(edge.Top.Y); - - this.CheckJoinLeft(edge, edge.Bottom); - - // Issue #500: check join on the right bound at the bottom point. - this.CheckJoinRight(edge, edge.Bottom, true); - } - - /// - /// Handles an intersection between two active edges at a given point. - /// - /// The first intersecting edge. - /// The second intersecting edge. - /// The intersection point. - private void IntersectActiveEdges(ActiveEdge edge1, ActiveEdge edge2, Vertex point) - { - if (IsJoined(edge1)) - { - this.SplitEdge(edge1, point); - } - - if (IsJoined(edge2)) - { - this.SplitEdge(edge2, point); - } - - // Update winding counts for both edges. - if (edge1.WindCount + edge2.WindDelta == 0) - { - edge1.WindCount = -edge1.WindCount; - } - else - { - edge1.WindCount += edge2.WindDelta; - } - - if (edge2.WindCount - edge1.WindDelta == 0) - { - edge2.WindCount = -edge2.WindCount; - } - else - { - edge2.WindCount -= edge1.WindDelta; - } - - int oldE1WindCount = edge1.WindCount; - int oldE2WindCount = edge2.WindCount; - - bool e1WindCountIs0or1 = oldE1WindCount is 0 or 1; - bool e2WindCountIs0or1 = oldE2WindCount is 0 or 1; - bool edge1IsTwoVertexFlatRing = IsTwoVertexFlatRingEdge(edge1); - bool edge2IsTwoVertexFlatRing = IsTwoVertexFlatRingEdge(edge2); - - if ((!edge1.IsHot && !e1WindCountIs0or1 && !edge1IsTwoVertexFlatRing) || - (!edge2.IsHot && !e2WindCountIs0or1 && !edge2IsTwoVertexFlatRing)) - { - return; - } - - if (edge1IsTwoVertexFlatRing || edge2IsTwoVertexFlatRing) - { - if (edge1.IsHot ^ edge2.IsHot) - { - ActiveEdge hotEdge = edge1.IsHot ? edge1 : edge2; - ActiveEdge flatEdge = edge1IsTwoVertexFlatRing ? edge1 : edge2; - if (!flatEdge.IsHot) - { - // Keep the fix in-sweep: inject touch->tip->touch directly into the - // hot output chain in O(1), avoiding any post-process contour scans. - Vertex tip = GetFlatRingTip(flatEdge, point); - _ = this.AddOutputPoint(hotEdge, point); - _ = this.AddOutputPoint(hotEdge, tip); - _ = this.AddOutputPoint(hotEdge, point); - return; - } - } - } - - // Emit output based on hot edges and winding state. - - // If both edges are hot, treat as maxima or crossing. - if (edge1.IsHot && edge2.IsHot) - { - if ((oldE1WindCount != 0 && oldE1WindCount != 1) || (oldE2WindCount != 0 && oldE2WindCount != 1)) - { - _ = this.AddLocalMaximumOutput(edge1, edge2, point); - } - else if (edge1.IsFront || (edge1.OutputRecord == edge2.OutputRecord)) - { - // this 'else if' condition isn't strictly needed but - // it's sensible to split polygons that only touch at - // a common vertex (not at common edges). - _ = this.AddLocalMaximumOutput(edge1, edge2, point); - } - else - { - // Treat as a crossing; emit and swap output records. - _ = this.AddOutputPoint(edge1, point); - SwapOutputRecords(edge1, edge2); - } - } - - // If only one edge is hot, emit and swap. - else if (edge1.IsHot) - { - _ = this.AddOutputPoint(edge1, point); - SwapOutputRecords(edge1, edge2); - } - else if (edge2.IsHot) - { - _ = this.AddOutputPoint(edge2, point); - SwapOutputRecords(edge1, edge2); - } - - // If both edges are cold, only minima with winding=1 start output. - else - { - if (oldE1WindCount == 1 && oldE2WindCount == 1) - { - _ = this.AddLocalMinimumOutput(edge1, edge2, point); - } - } - } - - /// - /// Executes the sweep-line union. - /// - private void ExecuteInternal() - { - this.ResetState(); - if (!this.scanlineSchedule.TryPopScanline(out double y)) - { - return; - } - - // Process each scanbeam: insert local minima, handle horizontals, resolve intersections, - // then advance to the next scanline. - while (this.succeeded) - { - this.InsertLocalMinimaIntoActiveList(y); - ActiveEdge? edge; - while (this.activeEdges.TryPopHorizontal(out edge)) - { - this.ProcessHorizontal(edge!); - } - - if (this.horizontalSegments.Count > 0) - { - this.ConvertHorizontalSegmentsToJoins(); - this.horizontalSegments.Clear(); - } - - // Advance to the next scanbeam. - this.currentScanlineBottomY = y; - if (!this.scanlineSchedule.TryPopScanline(out y)) - { - // y is now the new top of the scanbeam. - break; - } - - this.ProcessIntersections(y); - this.ProcessScanbeamTop(y); - while (this.activeEdges.TryPopHorizontal(out edge)) - { - this.ProcessHorizontal(edge!); - } - } - - if (this.succeeded) - { - this.ProcessHorizontalJoins(); - } - } - - /// - /// Executes the sweep-line union, leaving output records populated for conversion. - /// - /// Whether hierarchy-sensitive output ownership is required. - /// if the sweep completed successfully. - public bool Execute(bool buildHierarchy) - { - this.buildHierarchy = buildHierarchy; - try - { - this.ExecuteInternal(); - } - catch - { - this.succeeded = false; - } - - return this.succeeded; - } - - /// - /// Builds and processes edge intersections for the current scanbeam. - /// - /// The scanbeam top Y coordinate. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void ProcessIntersections(double topY) - { - if (!this.BuildIntersectionList(topY)) - { - return; - } - - this.ProcessIntersectionList(); - this.ClearIntersectionNodes(); - } - - /// - /// Clears the list of pending intersection nodes. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void ClearIntersectionNodes() => this.intersectionList.Clear(); - - /// - /// Adds a new intersection node between two edges at the current scanbeam. - /// - /// The first edge. - /// The second edge. - /// The scanbeam top Y coordinate. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void AddIntersectionNode(ActiveEdge edge1, ActiveEdge edge2, double topY) - { - if (!PolygonUtilities.TryGetLineIntersection( - edge1.Bottom, edge1.Top, edge2.Bottom, edge2.Top, out Vertex intersectionPoint)) - { - intersectionPoint = new Vertex(edge1.CurrentX, topY); - } - - // Prevent vertical segment ordering violations: if the intersection creates a perfectly - // vertical split where the new split point has the same X but lower Y than the bottom, - // nudge X to the next representable value. Vertical segments must be processed bottom-to-top, - // but the current bottom event is already being processed, so we cannot reorder. Moving X by - // one ULP ensures the split point sorts after the bottom event. - // See: https://github.com/21re/rust-geo-booleanop/pull/11 - if (intersectionPoint.X == edge1.Bottom.X && intersectionPoint.Y < edge1.Bottom.Y) - { - intersectionPoint = new Vertex(intersectionPoint.X.NextAfter(double.PositiveInfinity), intersectionPoint.Y); - } - else if (intersectionPoint.X == edge2.Bottom.X && intersectionPoint.Y < edge2.Bottom.Y) - { - intersectionPoint = new Vertex(intersectionPoint.X.NextAfter(double.PositiveInfinity), intersectionPoint.Y); - } - - // Clamp intersections that drift outside the scanbeam due to numeric error. - if (intersectionPoint.Y > this.currentScanlineBottomY || intersectionPoint.Y < topY) - { - double absDx1 = Math.Abs(edge1.Dx); - double absDx2 = Math.Abs(edge2.Dx); - - // dx is dX/dY, so large magnitudes mean the edge is nearly horizontal (dY is tiny). - // Using TopX with a clamped Y can amplify floating-point error in that case, so we - // fall back to closest-point clamping when |dx| > 100 (about 0.57 degrees from horizontal). - // This threshold keeps near-horizontal intersections stable without scaling the input. - switch (absDx1 > 100) - { - case true when absDx2 > 100: - { - intersectionPoint = absDx1 > absDx2 - ? PolygonUtilities.ClosestPointOnSegment(intersectionPoint, edge1.Bottom, edge1.Top) - : PolygonUtilities.ClosestPointOnSegment(intersectionPoint, edge2.Bottom, edge2.Top); - - break; - } - - case true: - intersectionPoint = PolygonUtilities.ClosestPointOnSegment(intersectionPoint, edge1.Bottom, edge1.Top); - break; - default: - { - if (absDx2 > 100) - { - intersectionPoint = PolygonUtilities.ClosestPointOnSegment(intersectionPoint, edge2.Bottom, edge2.Top); - } - else - { - double targetY = intersectionPoint.Y < topY ? topY : this.currentScanlineBottomY; - double targetX = absDx1 < absDx2 ? ActiveEdge.TopX(edge1, targetY) : ActiveEdge.TopX(edge2, targetY); - intersectionPoint = new Vertex(targetX, targetY); - } - - break; - } - } - } - - IntersectNode node = new(intersectionPoint, edge1, edge2); - this.intersectionList.Add(node); - } - - /// - /// Extracts an edge from the sorted edge list. - /// - /// The edge to extract. - /// The next edge after the extracted one. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static ActiveEdge? ExtractFromSortedEdges(ActiveEdge edge) - { - ActiveEdge? res = edge.NextInSel; - if (res != null) - { - res.PrevInSel = edge.PrevInSel; - } - - edge.PrevInSel!.NextInSel = res; - return res; - } - - /// - /// Inserts an edge before another edge in the sorted edge list. - /// - /// The edge to insert. - /// The reference edge. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static void InsertBeforeInSortedEdges(ActiveEdge edge1, ActiveEdge edge2) - { - edge1.PrevInSel = edge2.PrevInSel; - if (edge1.PrevInSel != null) - { - edge1.PrevInSel.NextInSel = edge1; - } - - edge1.NextInSel = edge2; - edge2.PrevInSel = edge1; - } - - /// - /// Builds the list of intersections required to sort edges at the top of the scanbeam. - /// - /// The scanbeam top Y coordinate. - /// if any intersections were found. - private bool BuildIntersectionList(double topY) - { - if (this.activeEdges.Head?.NextInAel == null) - { - return false; - } - - // Compute edge positions at the top of the scanbeam to derive required intersections. - ActiveEdge? sortedHead = this.activeEdges.CopyToSorted(topY); - - // Find intersections via a stable merge sort so only adjacent edges intersect. - // Nodes are stored for ProcessIntersectionList. See https://stackoverflow.com/a/46319131/359538. - ActiveEdge? left = sortedHead; - - while (left!.Jump != null) - { - ActiveEdge? prevBase = null; - while (left?.Jump != null) - { - ActiveEdge? currBase = left; - ActiveEdge? right = left.Jump; - ActiveEdge? lEnd = right; - ActiveEdge? rEnd = right.Jump; - left.Jump = rEnd; - while (left != lEnd && right != rEnd) - { - if (right!.CurrentX < left!.CurrentX) - { - ActiveEdge? tmp = right.PrevInSel!; - while (true) - { - this.AddIntersectionNode(tmp, right, topY); - if (tmp == left) - { - break; - } - - tmp = tmp.PrevInSel!; - } - - tmp = right; - right = ExtractFromSortedEdges(tmp); - lEnd = right; - InsertBeforeInSortedEdges(tmp, left); - if (left != currBase) - { - continue; - } - - currBase = tmp; - currBase.Jump = rEnd; - if (prevBase == null) - { - sortedHead = currBase; - } - else - { - prevBase.Jump = currBase; - } - } - else - { - left = left.NextInSel; - } - } - - prevBase = currBase; - left = rEnd; - } - - left = sortedHead; - } - - return this.intersectionList.Count > 0; - } - - /// - /// Processes the intersection list in bottom-up order, swapping edges and generating output. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void ProcessIntersectionList() - { - // Intersections must be processed bottom-up, and only between adjacent edges. - - // Sort so intersections proceed from bottom to top. - this.intersectionList.Sort(default(IntersectNodeComparer)); - - // Reorder as needed to ensure intersecting edges are adjacent. - for (int i = 0; i < this.intersectionList.Count; ++i) - { - if (!AreEdgesAdjacentInActiveList(this.intersectionList[i])) - { - int j = i + 1; - while (!AreEdgesAdjacentInActiveList(this.intersectionList[j])) - { - j++; - } - - // Swap into adjacency. - (this.intersectionList[j], this.intersectionList[i]) = - (this.intersectionList[i], this.intersectionList[j]); - } - - IntersectNode node = this.intersectionList[i]; - this.IntersectActiveEdges(node.Edge1, node.Edge2, node.Point); - this.activeEdges.SwapPositions(node.Edge1, node.Edge2); - - node.Edge1.CurrentX = node.Point.X; - node.Edge2.CurrentX = node.Point.X; - this.CheckJoinLeft(node.Edge2, node.Point, true); - this.CheckJoinRight(node.Edge1, node.Point, true); - } - } - - /// - /// Resolves left-to-right direction and bounds for a horizontal edge. - /// - /// The horizontal edge. - /// The maxima vertex for the horizontal span. - /// The left bound X value. - /// The right bound X value. - /// when the edge is left-to-right. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static bool ResetHorizontalDirection( - ActiveEdge horizontalEdge, - SweepVertex? vertexMax, - out double leftX, - out double rightX) - { - if (horizontalEdge.Bottom.X == horizontalEdge.Top.X) - { - // Degenerate horizontal edge (zero length). - leftX = horizontalEdge.CurrentX; - rightX = horizontalEdge.CurrentX; - ActiveEdge? edge = horizontalEdge.NextInAel; - while (edge != null && edge.VertexTop != vertexMax) - { - edge = edge.NextInAel; - } - - return edge != null; - } - - if (horizontalEdge.CurrentX < horizontalEdge.Top.X) - { - leftX = horizontalEdge.CurrentX; - rightX = horizontalEdge.Top.X; - return true; - } - - // Right to left. - leftX = horizontalEdge.Top.X; - rightX = horizontalEdge.CurrentX; - return false; - } - - /// - /// Trims collinear points from a horizontal edge. - /// - /// The horizontal edge. - /// Whether collinear points are preserved. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static void TrimHorizontal(ActiveEdge horizontalEdge, bool preserveCollinear) - { - bool wasTrimmed = false; - Vertex point = horizontalEdge.NextVertex.Point; - - while (point.Y == horizontalEdge.Top.Y) - { - // Always trim 180-degree spikes in closed paths; otherwise stop when preserving collinear. - if (preserveCollinear && - (point.X < horizontalEdge.Top.X) != (horizontalEdge.Bottom.X < horizontalEdge.Top.X)) - { - break; - } - - horizontalEdge.VertexTop = horizontalEdge.NextVertex; - horizontalEdge.Top = point; - wasTrimmed = true; - if (horizontalEdge.IsMaxima) - { - break; - } - - point = horizontalEdge.NextVertex.Point; - } - - if (wasTrimmed) - { - // Recompute slope after trimming. - horizontalEdge.UpdateDx(); - } - } - - /// - /// Adds a horizontal segment for later join processing. - /// - /// The output point that anchors the segment. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void AddHorizontalSegment(OutputPoint outputPoint) - => this.horizontalSegments.Add(new HorizontalSegment(outputPoint)); - - /// - /// Returns the last output point for a hot edge. - /// - /// The hot edge to inspect. - /// The last output point. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static OutputPoint GetLastOutputPoint(ActiveEdge hotEdge) - { - OutputRecord outputRecord = hotEdge.OutputRecord!; - return (hotEdge == outputRecord.FrontEdge) ? - outputRecord.Points! : outputRecord.Points!.Next!; - } - - /// - /// Processes a horizontal edge and resolves any intersections adouble the scanline. - /// - /// The horizontal edge to process. - private void ProcessHorizontal(ActiveEdge horizontalEdge) - /******************************************************************************* - * Notes: Horizontal edges (HEs) at scanline intersections (i.e. at the top or * - * bottom of a scanbeam) are processed as if layered. The order in which HEs * - * are processed doesn't matter. HEs intersect with the bottom vertices of * - * other HEs[#] and with non-horizontal edges [*]. Once these intersections * - * are completed, intermediate HEs are 'promoted' to the next edge in their * - * bounds, and they in turn may be intersected[%] by other HEs. * - * * - * eg: 3 horizontals at a scanline: / | / / * - * | / | (HE3)o ========%========== o * - * o ======= o(HE2) / | / / * - * o ============#=========*======*========#=========o (HE1) * - * / | / | / * - *******************************************************************************/ - { - double y = horizontalEdge.Bottom.Y; - - SweepVertex? vertexMax = GetMaximaVertexAtCurrentY(horizontalEdge); - - bool isLeftToRight = - ResetHorizontalDirection(horizontalEdge, vertexMax, out double leftX, out double rightX); - - ActiveEdge? immediatePair = horizontalEdge.NextInAel; - if (immediatePair == null || - immediatePair.LocalMin.Vertex != horizontalEdge.LocalMin.Vertex || - !immediatePair.IsHorizontal) - { - immediatePair = horizontalEdge.PrevInAel; - } - - if (!horizontalEdge.IsHot && - IsTwoVertexFlatRingEdge(horizontalEdge) && - immediatePair != null && - immediatePair.LocalMin.Vertex == horizontalEdge.LocalMin.Vertex && - immediatePair.IsHorizontal) - { - // Fast path for degenerate flat rings. Complexity is O(K) where K is the - // number of active edges crossing this horizontal span at the scanline. - // No extra contour collections are built. - ActiveEdge? scan = isLeftToRight ? horizontalEdge.NextInAel : horizontalEdge.PrevInAel; - if (scan == immediatePair) - { - scan = isLeftToRight ? immediatePair.NextInAel : immediatePair.PrevInAel; - } - - while (scan != null) - { - if ((isLeftToRight && scan.CurrentX > rightX) || - (!isLeftToRight && scan.CurrentX < leftX)) - { - break; - } - - if (!scan.IsHorizontal) - { - Vertex point = new(scan.CurrentX, y); - if (isLeftToRight) - { - this.IntersectActiveEdges(horizontalEdge, scan, point); - } - else - { - this.IntersectActiveEdges(scan, horizontalEdge, point); - } - } - - scan = isLeftToRight ? scan.NextInAel : scan.PrevInAel; - } - - this.activeEdges.Remove(immediatePair); - this.activeEdges.Remove(horizontalEdge); - return; - } - - if (horizontalEdge.IsHot) - { - OutputPoint outputPoint = this.AddOutputPoint(horizontalEdge, new Vertex(horizontalEdge.CurrentX, y)); - this.AddHorizontalSegment(outputPoint); - } - - int horizontalLoopGuard = 0; - while (true) - { - if (++horizontalLoopGuard > HorizontalLoopFailSafeLimit) - { - // Fail-safe for corrupted links: bail out instead of throwing/hanging. - return; - } - - // Traverse consecutive horizontal edges on this scanline. - ActiveEdge? edge = isLeftToRight ? horizontalEdge.NextInAel : horizontalEdge.PrevInAel; - - int edgeLoopGuard = 0; - while (edge != null) - { - if (++edgeLoopGuard > HorizontalLoopFailSafeLimit) - { - // Fail-safe for corrupted links: bail out instead of throwing/hanging. - return; - } - - if (edge.VertexTop == vertexMax) - { - // Handle the maxima pair before processing other intersections. - if (horizontalEdge.IsHot && IsJoined(edge)) - { - this.SplitEdge(edge, edge.Top); - } - - if (horizontalEdge.IsHot) - { - while (horizontalEdge.VertexTop != vertexMax) - { - _ = this.AddOutputPoint(horizontalEdge, horizontalEdge.Top); - this.UpdateEdgeInActiveList(horizontalEdge); - } - - if (isLeftToRight) - { - _ = this.AddLocalMaximumOutput(horizontalEdge, edge, horizontalEdge.Top); - } - else - { - _ = this.AddLocalMaximumOutput(edge, horizontalEdge, horizontalEdge.Top); - } - } - - this.activeEdges.Remove(edge); - this.activeEdges.Remove(horizontalEdge); - return; - } - - // If this horizontal is a maxima, keep going until its pair is reached; - // otherwise check for break conditions. - Vertex point; - if (vertexMax != horizontalEdge.VertexTop) - { - // Stop once the edge moves beyond the horizontal span. - if ((isLeftToRight && edge.CurrentX > rightX) || - (!isLeftToRight && edge.CurrentX < leftX)) - { - break; - } - - if (edge.CurrentX == horizontalEdge.Top.X && !edge.IsHorizontal) - { - point = horizontalEdge.NextVertex.Point; - - // At the horizontal end, stop only when the outslope overtakes the edge - // (greater when heading right, smaller when heading left). - if ((isLeftToRight && (ActiveEdge.TopX(edge, point.Y) >= point.X)) || - (!isLeftToRight && (ActiveEdge.TopX(edge, point.Y) <= point.X))) - { - break; - } - } - } - - point = new Vertex(edge.CurrentX, y); - - if (isLeftToRight) - { - this.IntersectActiveEdges(horizontalEdge, edge, point); - this.activeEdges.SwapPositions(horizontalEdge, edge); - this.CheckJoinLeft(edge, point); - horizontalEdge.CurrentX = edge.CurrentX; - edge = horizontalEdge.NextInAel; - } - else - { - this.IntersectActiveEdges(edge, horizontalEdge, point); - this.activeEdges.SwapPositions(edge, horizontalEdge); - this.CheckJoinRight(edge, point); - horizontalEdge.CurrentX = edge.CurrentX; - edge = horizontalEdge.PrevInAel; - } - - if (horizontalEdge.IsHot) - { - this.AddHorizontalSegment(GetLastOutputPoint(horizontalEdge)); - } - } - - // Stop once no more consecutive horizontals remain. - if (horizontalEdge.NextVertex.Point.Y != horizontalEdge.Top.Y) - { - break; - } - - // Advance to the next horizontal segment in the bound. - if (horizontalEdge.IsHot) - { - _ = this.AddOutputPoint(horizontalEdge, horizontalEdge.Top); - } - - this.UpdateEdgeInActiveList(horizontalEdge); - - isLeftToRight = ResetHorizontalDirection( - horizontalEdge, - vertexMax, - out leftX, - out rightX); - } - - // Finished this horizontal chain. - if (horizontalEdge.IsHot) - { - OutputPoint outputPoint = this.AddOutputPoint(horizontalEdge, horizontalEdge.Top); - this.AddHorizontalSegment(outputPoint); - } - - // Advance past the final intermediate horizontal. - this.UpdateEdgeInActiveList(horizontalEdge); - } - - /// - /// Processes edges that reach the top of the scanbeam, updating or removing them. - /// - /// The scanbeam top Y coordinate. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void ProcessScanbeamTop(double y) - { - this.activeEdges.ClearHorizontalQueue(); - ActiveEdge? edge = this.activeEdges.Head; - while (edge != null) - { - // Edge is never horizontal at this point. - if (edge.Top.Y == y) - { - edge.CurrentX = edge.Top.X; - if (edge.IsMaxima) - { - // Maxima reached; finalize this bound. - edge = this.ProcessMaxima(edge); - continue; - } - - // Intermediate vertex on the bound. - if (edge.IsHot) - { - _ = this.AddOutputPoint(edge, edge.Top); - } - - this.UpdateEdgeInActiveList(edge); - - // Queue horizontals for dedicated processing. - if (edge.IsHorizontal) - { - this.activeEdges.PushHorizontal(edge); - } - } - - // Edge continues through the scanbeam. - else - { - edge.CurrentX = ActiveEdge.TopX(edge, y); - } - - edge = edge.NextInAel; - } - } - - /// - /// Handles a maxima event for the active edge. - /// - /// The active edge at the maxima. - /// The next edge to continue scanning from. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private ActiveEdge? ProcessMaxima(ActiveEdge edge) - { - ActiveEdge? prevEdge = edge.PrevInAel; - ActiveEdge? nextEdge = edge.NextInAel; - - ActiveEdge? maxPair = FindMaximaPair(edge); - if (maxPair == null) - { - // Horizontal maxima pair is handled in horizontal processing. - return nextEdge; - } - - if (IsJoined(edge)) - { - this.SplitEdge(edge, edge.Top); - } - - if (IsJoined(maxPair)) - { - this.SplitEdge(maxPair, maxPair.Top); - } - - // Only non-horizontal maxima reach here. - // Process edges between the maxima pair. - while (nextEdge != maxPair) - { - this.IntersectActiveEdges(edge, nextEdge!, edge.Top); - this.activeEdges.SwapPositions(edge, nextEdge!); - nextEdge = edge.NextInAel; - } - - // At this point edge.NextInAel == maxPair. - if (edge.IsHot) - { - _ = this.AddLocalMaximumOutput(edge, maxPair, edge.Top); - } - - this.activeEdges.Remove(edge); - this.activeEdges.Remove(maxPair); - return prevEdge != null ? prevEdge.NextInAel : this.activeEdges.Head; - } - - /// - /// Tests whether an edge is currently joined to a neighbor. - /// - /// The edge to inspect. - /// if the edge is joined. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static bool IsJoined(ActiveEdge edge) => edge.JoinWith != JoinWith.None; - - /// - /// Splits a joined edge at the specified point. - /// - /// The edge to split. - /// The split point. - private void SplitEdge(ActiveEdge edge, Vertex point) - { - if (edge.JoinWith == JoinWith.Right) - { - edge.JoinWith = JoinWith.None; - edge.NextInAel!.JoinWith = JoinWith.None; - _ = this.AddLocalMinimumOutput(edge, edge.NextInAel, point, true); - } - else - { - edge.JoinWith = JoinWith.None; - edge.PrevInAel!.JoinWith = JoinWith.None; - _ = this.AddLocalMinimumOutput(edge.PrevInAel, edge, point, true); - } - } - - /// - /// Attempts to join the current edge with its left neighbor. - /// - /// The active edge being evaluated. - /// The candidate join point. - /// Whether to check the current X for proximity. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void CheckJoinLeft( - ActiveEdge edge, - Vertex point, - bool checkCurrX = false) - { - ActiveEdge? prev = edge.PrevInAel; - if (prev == null || - !edge.IsHot || !prev.IsHot || - edge.IsHorizontal || prev.IsHorizontal) - { - return; - } - - // Reject joins that are too close to extrema (Issue #490). - if ((point.Y < edge.Top.Y + JoinExtremaDelta || point.Y < prev.Top.Y + JoinExtremaDelta) && - ((edge.Bottom.Y > point.Y) || (prev.Bottom.Y > point.Y))) - { - // Issue #490. - return; - } - - if (checkCurrX) - { - if (PolygonUtilities.PerpendicularDistanceSquared(point, prev.Bottom, prev.Top) > - JoinPerpendicularDistanceSquaredTolerance) - { - return; - } - } - else if (edge.CurrentX != prev.CurrentX) - { - return; - } - - if (!PolygonUtilities.IsCollinear(edge.Top, point, prev.Top)) - { - return; - } - - if (edge.OutputRecord!.Index == prev.OutputRecord!.Index) - { - _ = this.AddLocalMaximumOutput(prev, edge, point); - } - else if (edge.OutputRecord!.Index < prev.OutputRecord!.Index) - { - JoinOutputRecords(edge, prev); - } - else - { - JoinOutputRecords(prev, edge); - } - - prev.JoinWith = JoinWith.Right; - edge.JoinWith = JoinWith.Left; - } - - /// - /// Attempts to join the current edge with its right neighbor. - /// - /// The active edge being evaluated. - /// The candidate join point. - /// Whether to check the current X for proximity. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void CheckJoinRight( - ActiveEdge edge, - Vertex point, - bool checkCurrX = false) - { - ActiveEdge? next = edge.NextInAel; - if (next == null || - !edge.IsHot || !next.IsHot || - edge.IsHorizontal || next.IsHorizontal) - { - return; - } - - // Reject joins that are too close to extrema (Issue #490). - if ((point.Y < edge.Top.Y + JoinExtremaDelta || point.Y < next.Top.Y + JoinExtremaDelta) && - ((edge.Bottom.Y > point.Y) || (next.Bottom.Y > point.Y))) - { - // Issue #490. - return; - } - - if (checkCurrX) - { - if (PolygonUtilities.PerpendicularDistanceSquared(point, next.Bottom, next.Top) > - JoinPerpendicularDistanceSquaredTolerance) - { - return; - } - } - else if (edge.CurrentX != next.CurrentX) - { - return; - } - - if (!PolygonUtilities.IsCollinear(edge.Top, point, next.Top)) - { - return; - } - - if (edge.OutputRecord!.Index == next.OutputRecord!.Index) - { - _ = this.AddLocalMaximumOutput(edge, next, point); - } - else if (edge.OutputRecord!.Index < next.OutputRecord!.Index) - { - JoinOutputRecords(edge, next); - } - else - { - JoinOutputRecords(next, edge); - } - - edge.JoinWith = JoinWith.Right; - next.JoinWith = JoinWith.Left; - } - - /// - /// Ensures all output points in a record reference the correct owner. - /// - /// The output record to normalize. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static void FixOutputRecordPoints(OutputRecord outputRecord) - { - OutputPoint outputPoint = outputRecord.Points!; - do - { - outputPoint.OutputRecord = outputRecord; - outputPoint = outputPoint.Next!; - } - while (outputPoint != outputRecord.Points); - } - - /// - /// Determines the left/right ordering of a horizontal segment. - /// - /// The segment to update. - /// The previous output point. - /// The next output point. - /// if the segment has non-zero length. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static bool SetHorizontalSegmentHeadingForward(HorizontalSegment horizontalSegment, OutputPoint prevPoint, OutputPoint nextPoint) - { - if (prevPoint.Point.X == nextPoint.Point.X) - { - return false; - } - - if (prevPoint.Point.X < nextPoint.Point.X) - { - horizontalSegment.LeftPoint = prevPoint; - horizontalSegment.RightPoint = nextPoint; - horizontalSegment.LeftToRight = true; - } - else - { - horizontalSegment.LeftPoint = nextPoint; - horizontalSegment.RightPoint = prevPoint; - horizontalSegment.LeftToRight = false; - } - - return true; - } - - /// - /// Normalizes a horizontal segment and sets its left/right pointers. - /// - /// The segment to update. - /// if the segment remains valid after normalization. - private static bool UpdateHorizontalSegment(HorizontalSegment horizontalSegment) - { - OutputPoint outputPoint = horizontalSegment.LeftPoint!; - OutputRecord outputRecord = ResolveOutputRecord(outputPoint.OutputRecord)!; - bool outputRecordHasEdges = outputRecord.FrontEdge != null; - double currentY = outputPoint.Point.Y; - OutputPoint prevPoint = outputPoint, nextPoint = outputPoint; - if (outputRecordHasEdges) - { - OutputPoint opA = outputRecord.Points!, opZ = opA.Next!; - while (prevPoint != opZ && prevPoint.Prev.Point.Y == currentY) - { - prevPoint = prevPoint.Prev; - } - - while (nextPoint != opA && nextPoint.Next!.Point.Y == currentY) - { - nextPoint = nextPoint.Next; - } - } - else - { - while (prevPoint.Prev != nextPoint && prevPoint.Prev.Point.Y == currentY) - { - prevPoint = prevPoint.Prev; - } - - while (nextPoint.Next != prevPoint && nextPoint.Next!.Point.Y == currentY) - { - nextPoint = nextPoint.Next; - } - } - - bool result = - SetHorizontalSegmentHeadingForward(horizontalSegment, prevPoint, nextPoint) && - horizontalSegment.LeftPoint!.HorizontalSegment == null; - - if (result) - { - horizontalSegment.LeftPoint!.HorizontalSegment = horizontalSegment; - } - else - { - // Mark invalid so sorting pushes it to the end. - horizontalSegment.RightPoint = null; - } - - return result; - } - - /// - /// Duplicates an output point and inserts it before or after the original. - /// - /// The point to duplicate. - /// Whether to insert after the original. - /// The newly inserted output point. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private OutputPoint DuplicateOutputPoint(OutputPoint outputPoint, bool insertAfter) - { - OutputPoint result = this.OutputPoints.Add(outputPoint.Point, outputPoint.OutputRecord); - if (insertAfter) - { - result.Next = outputPoint.Next; - result.Next!.Prev = result; - result.Prev = outputPoint; - outputPoint.Next = result; - } - else - { - result.Prev = outputPoint.Prev; - result.Prev.Next = result; - result.Next = outputPoint; - outputPoint.Prev = result; - } - - return result; - } - - /// - /// Sorts horizontal segments by their X extents. - /// - /// The first segment. - /// The second segment. - /// A comparison result for sorting. - private static int CompareHorizontalSegments(HorizontalSegment? segment1, HorizontalSegment? segment2) - { - if (segment1 == null || segment2 == null) - { - return 0; - } - - if (segment1.RightPoint == null) - { - return segment2.RightPoint == null ? 0 : 1; - } - - if (segment2.RightPoint == null) - { - return -1; - } - - return segment1.LeftPoint!.Point.X.CompareTo(segment2.LeftPoint!.Point.X); - } - - /// - /// Converts horizontal segments into join candidates for post-processing. - /// - private void ConvertHorizontalSegmentsToJoins() - { - int k = 0; - foreach (HorizontalSegment horizontalSegment in this.horizontalSegments) - { - if (UpdateHorizontalSegment(horizontalSegment)) - { - k++; - } - } - - if (k < 2) - { - return; - } - - this.horizontalSegments.Sort(CompareHorizontalSegments); - - for (int i = 0; i < k - 1; i++) - { - HorizontalSegment segment1 = this.horizontalSegments[i]; - - // Find overlapping segments to generate join candidates. - for (int j = i + 1; j < k; j++) - { - HorizontalSegment segment2 = this.horizontalSegments[j]; - if ((segment2.LeftPoint!.Point.X >= segment1.RightPoint!.Point.X) || - (segment2.LeftToRight == segment1.LeftToRight) || - (segment2.RightPoint!.Point.X <= segment1.LeftPoint!.Point.X)) - { - continue; - } - - double currentY = segment1.LeftPoint.Point.Y; - if (segment1.LeftToRight) - { - while (segment1.LeftPoint.Next!.Point.Y == currentY && - segment1.LeftPoint.Next.Point.X <= segment2.LeftPoint.Point.X) - { - segment1.LeftPoint = segment1.LeftPoint.Next; - } - - while (segment2.LeftPoint.Prev.Point.Y == currentY && - segment2.LeftPoint.Prev.Point.X <= segment1.LeftPoint.Point.X) - { - segment2.LeftPoint = segment2.LeftPoint.Prev; - } - - _ = this.horizontalJoins.Add( - this.DuplicateOutputPoint(segment1.LeftPoint, true), - this.DuplicateOutputPoint(segment2.LeftPoint, false)); - } - else - { - while (segment1.LeftPoint.Prev.Point.Y == currentY && - segment1.LeftPoint.Prev.Point.X <= segment2.LeftPoint.Point.X) - { - segment1.LeftPoint = segment1.LeftPoint.Prev; - } - - while (segment2.LeftPoint.Next!.Point.Y == currentY && - segment2.LeftPoint.Next.Point.X <= segment1.LeftPoint.Point.X) - { - segment2.LeftPoint = segment2.LeftPoint.Next; - } - - _ = this.horizontalJoins.Add( - this.DuplicateOutputPoint(segment2.LeftPoint, true), - this.DuplicateOutputPoint(segment1.LeftPoint, false)); - } - } - } - } - - /// - /// Builds a cleaned contour by removing redundant collinear points. - /// - /// A point on the output ring. - /// A contour with redundant points removed. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static List BuildCleanContour(OutputPoint outputPoint) - { - List result = []; - OutputPoint outputPoint2 = outputPoint; - while (outputPoint2.Next != outputPoint && - ((outputPoint2.Point.X == outputPoint2.Next!.Point.X && - outputPoint2.Point.X == outputPoint2.Prev.Point.X) || - (outputPoint2.Point.Y == outputPoint2.Next.Point.Y && - outputPoint2.Point.Y == outputPoint2.Prev.Point.Y))) - { - outputPoint2 = outputPoint2.Next; - } - - result.Add(outputPoint2.Point); - OutputPoint prevOp = outputPoint2; - outputPoint2 = outputPoint2.Next; - while (outputPoint2 != outputPoint) - { - if ((outputPoint2.Point.X != outputPoint2.Next!.Point.X || outputPoint2.Point.X != prevOp.Point.X) && - (outputPoint2.Point.Y != outputPoint2.Next.Point.Y || outputPoint2.Point.Y != prevOp.Point.Y)) - { - result.Add(outputPoint2.Point); - prevOp = outputPoint2; - } - - outputPoint2 = outputPoint2.Next; - } - - return result; - } - - /// - /// Classifies a point against an output polygon. - /// - /// The point to test. - /// A point on the polygon ring. - /// The point-in-polygon classification. - private static PointInPolygonResult PointInOutputPolygon(Vertex point, OutputPoint outputPoint) - { - if (outputPoint == outputPoint.Next || outputPoint.Prev == outputPoint.Next) - { - return PointInPolygonResult.Outside; - } - - OutputPoint outputPoint2 = outputPoint; - do - { - if (outputPoint.Point.Y != point.Y) - { - break; - } - - outputPoint = outputPoint.Next!; - } - while (outputPoint != outputPoint2); - - // Degenerate ring. - if (outputPoint.Point.Y == point.Y) - { - return PointInPolygonResult.Outside; - } - - // Point is strictly above or below the starting Y. - bool isAbove = outputPoint.Point.Y < point.Y, startingAbove = isAbove; - int val = 0; - - outputPoint2 = outputPoint.Next!; - while (outputPoint2 != outputPoint) - { - if (isAbove) - { - while (outputPoint2 != outputPoint && outputPoint2.Point.Y < point.Y) - { - outputPoint2 = outputPoint2.Next!; - } - } - else - { - while (outputPoint2 != outputPoint && outputPoint2.Point.Y > point.Y) - { - outputPoint2 = outputPoint2.Next!; - } - } - - if (outputPoint2 == outputPoint) - { - break; - } - - // The scanline must touch or cross point.Y an even number of times. - // Handle horizontal touches explicitly. - if (outputPoint2.Point.Y == point.Y) - { - if (outputPoint2.Point.X == point.X || (outputPoint2.Point.Y == outputPoint2.Prev.Point.Y && - (point.X < outputPoint2.Prev.Point.X) != (point.X < outputPoint2.Point.X))) - { - return PointInPolygonResult.On; - } - - outputPoint2 = outputPoint2.Next!; - if (outputPoint2 == outputPoint) - { - break; - } - - continue; - } - - if (outputPoint2.Point.X <= point.X || outputPoint2.Prev.Point.X <= point.X) - { - if (outputPoint2.Prev.Point.X < point.X && outputPoint2.Point.X < point.X) - { - // Toggle parity. - val = 1 - val; - } - else - { - int d = PolygonUtilities.CrossSign(outputPoint2.Prev.Point, outputPoint2.Point, point); - if (d == 0) - { - return PointInPolygonResult.On; - } - - if ((d < 0) == isAbove) - { - val = 1 - val; - } - } - } - - isAbove = !isAbove; - outputPoint2 = outputPoint2.Next!; - } - - if (isAbove == startingAbove) - { - return val == 0 ? PointInPolygonResult.Outside : PointInPolygonResult.Inside; - } - - { - int d = PolygonUtilities.CrossSign(outputPoint2.Prev.Point, outputPoint2.Point, point); - if (d == 0) - { - return PointInPolygonResult.On; - } - - if ((d < 0) == isAbove) - { - val = 1 - val; - } - } - - return val == 0 ? PointInPolygonResult.Outside : PointInPolygonResult.Inside; - } - - /// - /// Determines whether one output ring lies inside another. - /// - /// A point on the candidate inner ring. - /// A point on the candidate outer ring. - /// if the first ring is inside the second. - public static bool IsPathInsidePath(OutputPoint outputPoint1, OutputPoint outputPoint2) - { - // Allow for rounding error; don't decide based solely on the first vertex. - PointInPolygonResult pip = PointInPolygonResult.On; - OutputPoint outputPoint = outputPoint1; - do - { - switch (PointInOutputPolygon(outputPoint.Point, outputPoint2)) - { - case PointInPolygonResult.Outside: - if (pip == PointInPolygonResult.Outside) - { - return false; - } - - pip = PointInPolygonResult.Outside; - break; - case PointInPolygonResult.Inside: - if (pip == PointInPolygonResult.Inside) - { - return true; - } - - pip = PointInPolygonResult.Inside; - break; - default: - break; - } - - outputPoint = outputPoint.Next!; - } - while (outputPoint != outputPoint1); - - // Result is unclear, so try again using cleaned paths (Issue #973). - return PolygonUtilities.Path2ContainsPath1(BuildCleanContour(outputPoint1), BuildCleanContour(outputPoint2)); - } - - /// - /// Moves split ownership from one output record to another. - /// - /// The output record to move from. - /// The output record to move to. - private static void MoveOutputSplits(OutputRecord sourceRecord, OutputRecord targetRecord) - { - if (sourceRecord.Splits == null) - { - return; - } - - targetRecord.Splits ??= []; - foreach (int i in sourceRecord.Splits) - { - if (i != targetRecord.Index) - { - targetRecord.Splits.Add(i); - } - } - - sourceRecord.Splits = null; - } - - /// - /// Processes horizontal joins captured during the sweep. - /// - private void ProcessHorizontalJoins() - { - foreach (HorizontalJoin join in this.horizontalJoins) - { - OutputRecord outputRecord1 = ResolveOutputRecord(join.LeftToRight!.OutputRecord)!; - OutputRecord outputRecord2 = ResolveOutputRecord(join.RightToLeft!.OutputRecord)!; - - OutputPoint op1b = join.LeftToRight.Next!; - OutputPoint op2b = join.RightToLeft.Prev; - join.LeftToRight.Next = join.RightToLeft; - join.RightToLeft.Prev = join.LeftToRight; - op1b.Prev = op2b; - op2b.Next = op1b; - - // This join may split a single output record. - if (outputRecord1 == outputRecord2) - { - outputRecord2 = this.CreateOutputRecord(); - outputRecord2.Points = op1b; - FixOutputRecordPoints(outputRecord2); - - // If outputRecord1.Points moved to outputRecord2, update outputRecord1.Points. - if (outputRecord1.Points!.OutputRecord == outputRecord2) - { - outputRecord1.Points = join.LeftToRight; - outputRecord1.Points.OutputRecord = outputRecord1; - } - - // Issue references: #498, #520, #584, #576, #618 - if (this.buildHierarchy) - { - if (IsPathInsidePath(outputRecord1.Points, outputRecord2.Points)) - { - // swap outputRecord1's and outputRecord2's points - (outputRecord2.Points, outputRecord1.Points) = (outputRecord1.Points, outputRecord2.Points); - FixOutputRecordPoints(outputRecord1); - FixOutputRecordPoints(outputRecord2); - - // outputRecord2 is now inside outputRecord1 - outputRecord2.Owner = outputRecord1; - } - else if (IsPathInsidePath(outputRecord2.Points, outputRecord1.Points)) - { - outputRecord2.Owner = outputRecord1; - } - else - { - outputRecord2.Owner = outputRecord1.Owner; - } - - outputRecord1.Splits ??= []; - outputRecord1.Splits.Add(outputRecord2.Index); - } - else - { - outputRecord2.Owner = outputRecord1; - } - } - else - { - outputRecord2.Points = null; - if (this.buildHierarchy) - { - SetOutputOwner(outputRecord2, outputRecord1); - - // Issue #618. - MoveOutputSplits(outputRecord2, outputRecord1); - } - else - { - outputRecord2.Owner = outputRecord1; - } - } - } - } - - /// - /// Sorts intersection nodes from top to bottom, then left to right. - /// - internal struct IntersectNodeComparer : IComparer - { - /// - /// Compares two intersection nodes for sorting. - /// - /// The first node. - /// The second node. - /// A comparison result for sorting. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public readonly int Compare(IntersectNode a, IntersectNode b) - { - double deltaY = a.Point.Y - b.Point.Y; - if (deltaY != 0) - { - return deltaY > 0 ? -1 : 1; - } - - double deltaX = a.Point.X - b.Point.X; - if (deltaX == 0) - { - return 0; - } - - return deltaX < 0 ? -1 : 1; - } - } -} diff --git a/src/PolygonClipper/StablePriorityQueue{T,TComparer}.cs b/src/PolygonClipper/StablePriorityQueue{T,TComparer}.cs index 7312f3d..22cf6e5 100644 --- a/src/PolygonClipper/StablePriorityQueue{T,TComparer}.cs +++ b/src/PolygonClipper/StablePriorityQueue{T,TComparer}.cs @@ -71,7 +71,9 @@ public int Count /// public TComparer Comparer { get; } - /// Restores queue ordering after filling the shared backing list with unordered items. + /// + /// Restores queue ordering after filling the shared backing list with unordered items. + /// public void Heapify() => this.Heapify(this.heap); /// diff --git a/src/PolygonClipper/StatusLine.cs b/src/PolygonClipper/StatusLine.cs index dd750d5..faceefc 100644 --- a/src/PolygonClipper/StatusLine.cs +++ b/src/PolygonClipper/StatusLine.cs @@ -112,6 +112,46 @@ public int Add(SweepEvent e) return index; } + /// + /// Inserts an interval at its established complete-point block position. + /// + /// The established position. + /// The outgoing interval. + public void Insert(int index, SweepEvent segment) => this.sortedEvents.Insert(index, segment); + + /// + /// Removes a contiguous incoming block before its outgoing replacement is inserted. + /// + /// The first incoming position. + /// The number of incoming intervals. + public void RemoveRange(int index, int count) => this.sortedEvents.RemoveRange(index, count); + + /// + /// Finds the first interval not strictly below the complete event point. + /// + /// The event point. + /// The beginning of the incident block or the insertion position. + public int FindLower(Vertex point) + { + int left = 0; + int right = this.sortedEvents.Count; + while (left < right) + { + int middle = left + ((right - left) >> 1); + SweepEvent segment = this.sortedEvents[middle]; + if (!segment.ContainsPoint(point) && segment.IsBelow(point)) + { + left = middle + 1; + } + else + { + right = middle; + } + } + + return left; + } + /// /// Removes a sweep event from the status line. /// diff --git a/src/PolygonClipper/StrokeOptions.cs b/src/PolygonClipper/StrokeOptions.cs index 5034af8..c0d15e6 100644 --- a/src/PolygonClipper/StrokeOptions.cs +++ b/src/PolygonClipper/StrokeOptions.cs @@ -13,8 +13,8 @@ public sealed class StrokeOptions : IEquatable /// resolving self-intersections and overlaps before returning. /// /// - /// Defaults to for maximum throughput. - /// When disabled, callers should rasterize with a non-zero winding fill rule. + /// Defaults to . + /// Raw outlines describe their filled area using the NonZero fill rule. /// public bool NormalizeOutput { get; set; } diff --git a/src/PolygonClipper/SweepEvent.cs b/src/PolygonClipper/SweepEvent.cs index 300f09e..8b9b175 100644 --- a/src/PolygonClipper/SweepEvent.cs +++ b/src/PolygonClipper/SweepEvent.cs @@ -12,6 +12,11 @@ namespace SixLabors.PolygonClipper; /// internal sealed class SweepEvent { + // Live-only state is allocated and pooled with source intervals. Output + // history needs only endpoint, transition, and predecessor data, so it must + // not pay for source support, bundle ledgers, and active-status bookkeeping. + private IntervalState interval; + /// /// Initializes a new instance of the class. /// @@ -64,9 +69,9 @@ public SweepEvent(Vertex point, bool left, int contourId) } /// - /// Gets the point associated with the event. + /// Gets or sets the point associated with the event. /// - public Vertex Point { get; } + public Vertex Point { get; set; } /// /// Gets or sets a value indicating whether the point is the @@ -84,6 +89,60 @@ public SweepEvent(Vertex point, bool left, int contourId) /// public PolygonType PolygonType { get; } + /// + /// Gets or sets the current terminal point of this live interval. + /// + public Vertex End + { + get => this.OtherEvent.Point; + set => this.OtherEvent.Point = value; + } + + /// + /// Gets or sets the next source contribution endpoint. + /// + public Vertex SourceEnd { get => this.interval.SourceEnd; set => this.interval.SourceEnd = value; } + + /// + /// Gets or sets the original supporting segment, preserved across rounded splits. + /// + public Segment Support { get => this.interval.Support; set => this.interval.Support = value; } + + /// + /// Gets or sets the signed subject and clip contributions of this interval. + /// + public PolygonClipper.WindingCount Delta { get => this.interval.Delta; set => this.interval.Delta = value; } + + /// + /// Gets or sets the winding immediately above this live interval. + /// + public PolygonClipper.WindingCount Above { get => this.interval.Above; set => this.interval.Above = value; } + + /// + /// Gets or sets the endpoint changes retained for a coincident bundle. + /// + public PriorityQueue Ends { get => this.interval.Ends; set => this.interval.Ends = value; } + + /// + /// Gets or sets the immutable output record for the current contributing piece. + /// + public SweepEvent Boundary { get => this.interval.Boundary; set => this.interval.Boundary = value; } + + /// + /// Gets or sets the number of result intervals at or below this status entry. + /// + public int ResultRank { get => this.interval.ResultRank; set => this.interval.ResultRank = value; } + + /// + /// Gets or sets the generation identifying this piece in queued endpoint records. + /// + public int Version { get => this.interval.Version; set => this.interval.Version = value; } + + /// + /// Gets or sets a value indicating whether this interval is active. + /// + public bool Active { get => this.interval.Active; set => this.interval.Active = value; } + /// /// Gets or sets the type of the edge. /// @@ -184,17 +243,7 @@ public bool IsBelow(in Vertex p) /// if this event comes before the other; otherwise . /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public bool IsBefore(SweepEvent other) - { - // Compare by x-coordinate first - if (this.Point.X != other.Point.X) - { - return this.Point.X < other.Point.X; - } - - // If x-coordinates are equal, compare by y-coordinate - return this.Point.Y < other.Point.Y; - } + public bool IsBefore(SweepEvent other) => SweepEventComparer.Instance.Compare(this.Point, other.Point) < 0; /// /// Returns the segment associated with the sweep event. @@ -202,4 +251,119 @@ public bool IsBefore(SweepEvent other) /// The . [MethodImpl(MethodImplOptions.AggressiveInlining)] public Segment GetSegment() => new(this.Point, this.OtherEvent.Point); + + /// + /// Tests incidence on the noded interval and its original supporting segment. + /// + /// The queued event point. + /// Whether this interval participates in the point event. + public bool ContainsPoint(Vertex point) + { + // Rounded split endpoints belong to their interval. For other points, + // use the original support so a rounded split cannot rotate the line + // into a nearby source vertex. Neighbor discovery closes rounded junctions. + return SweepEventComparer.Instance.Compare(this.Point, point) <= 0 && SweepEventComparer.Instance.Compare(point, this.End) <= 0 && + (point == this.Point || point == this.End || + PolygonUtilities.SignedArea(this.Support.Source, this.Support.Target, point) == 0); + } + + /// + /// Initializes a reusable directed source interval before it enters the event queue. + /// + /// The canonical starting point. + /// The source endpoint. + /// The stable interval identity. + /// The signed operand contributions. + public void InitializeInterval(Vertex start, Vertex end, int id, PolygonClipper.WindingCount delta) + { + this.interval ??= new IntervalState(); + this.Point = start; + this.End = end; + this.ContourId = id; + this.SourceEnd = end; + this.Support = new Segment(start, end); + this.Delta = delta; + this.Above = default; + this.Ends = null; + this.Boundary = null; + this.Version = this.ResultRank = this.PosSL = 0; + this.Active = false; + } + + /// + /// Initializes an output-history record without allocating live interval state. + /// + /// The boundary endpoint. + /// Whether this is the canonical starting endpoint. + /// The paired endpoint, completed when its position is known. + /// The filled-side transition of this boundary. + /// The immutable boundary predecessor. + /// The source interval identity. + public void InitializeBoundary( + Vertex point, + bool left, + SweepEvent other, + ResultTransition transition, + SweepEvent previous, + int id) + { + this.Point = point; + this.Left = left; + this.OtherEvent = other; + this.ResultTransition = transition; + this.PrevInResult = previous; + this.ContourId = id; + this.OutputContourId = this.Pos = 0; + } + + /// + /// Stores the live interval state that is unnecessary in completed boundary history. + /// + private sealed class IntervalState + { + /// + /// Gets or sets the next source contribution endpoint. + /// + public Vertex SourceEnd { get; set; } + + /// + /// Gets or sets the original supporting segment, preserved across rounded splits. + /// + public Segment Support { get; set; } + + /// + /// Gets or sets the signed subject and clip contributions of this interval. + /// + public PolygonClipper.WindingCount Delta { get; set; } + + /// + /// Gets or sets the winding immediately above this live interval. + /// + public PolygonClipper.WindingCount Above { get; set; } + + /// + /// Gets or sets the endpoint changes retained for a coincident bundle. + /// + public PriorityQueue Ends { get; set; } + + /// + /// Gets or sets the immutable output record for the current contributing piece. + /// + public SweepEvent Boundary { get; set; } + + /// + /// Gets or sets the number of result intervals at or below this status entry. + /// + public int ResultRank { get; set; } + + /// + /// Gets or sets the generation identifying this piece in queued endpoint records. + /// + public int Version { get; set; } + + /// + /// Gets or sets a value indicating whether this interval is active. + /// + public bool Active { get; set; } + } } diff --git a/src/PolygonClipper/SweepEventComparer.cs b/src/PolygonClipper/SweepEventComparer.cs index bd1bb8a..f6ef4f0 100644 --- a/src/PolygonClipper/SweepEventComparer.cs +++ b/src/PolygonClipper/SweepEventComparer.cs @@ -8,8 +8,20 @@ namespace SixLabors.PolygonClipper; /// /// Compares two instances for sorting in the event queue. /// -internal sealed class SweepEventComparer : IComparer, IComparer +internal sealed class SweepEventComparer : IComparer, IComparer, IComparer, IComparer { + /// + /// The shared comparer for point, queue, and boundary event order. + /// + public static readonly SweepEventComparer Instance = new(); + + /// + public int Compare(Vertex x, Vertex y) + { + int order = x.X.CompareTo(y.X); + return order == 0 ? x.Y.CompareTo(y.Y) : order; + } + /// public int Compare(SweepEvent? x, SweepEvent? y) { @@ -28,21 +40,10 @@ public int Compare(SweepEvent? x, SweepEvent? y) return 1; } - // Compare by x-coordinate - if (x.Point.X > y.Point.X) - { - return 1; - } - - if (x.Point.X < y.Point.X) - { - return -1; - } - - // Compare by y-coordinate when x-coordinates are the same - if (x.Point.Y != y.Point.Y) + int pointOrder = this.Compare(x.Point, y.Point); + if (pointOrder != 0) { - return x.Point.Y > y.Point.Y ? 1 : -1; + return pointOrder; } // Compare left vs. right endpoint @@ -80,6 +81,23 @@ public int Compare(SweepEvent? x, SweepEvent? y) return order; } + /// + public int Compare(PolygonClipper.QueueEntry x, PolygonClipper.QueueEntry y) + { + int order = this.Compare(x.Point, y.Point); + if (order == 0) + { + order = x.Edge.ContourId.CompareTo(y.Edge.ContourId); + } + + if (order == 0) + { + order = x.Version.CompareTo(y.Version); + } + + return order == 0 ? x.IsStart.CompareTo(y.IsStart) : order; + } + /// public int Compare(object? x, object? y) { diff --git a/src/PolygonClipper/VertexPoolList.cs b/src/PolygonClipper/SweepEventPoolList.cs similarity index 55% rename from src/PolygonClipper/VertexPoolList.cs rename to src/PolygonClipper/SweepEventPoolList.cs index b870c64..f31dae4 100644 --- a/src/PolygonClipper/VertexPoolList.cs +++ b/src/PolygonClipper/SweepEventPoolList.cs @@ -8,166 +8,60 @@ namespace SixLabors.PolygonClipper; /// -/// Pool-backed list of clip vertices reused across clipping operations. -/// -internal sealed class VertexPoolList : PooledList -{ - /// - /// Adds or reuses a clip vertex initialized with the given data. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public SweepVertex Add(Vertex point, VertexFlags flags, SweepVertex? prev) - { - this.TryGrow(); - SweepVertex poolVertex = this.Items[this.Size]; - if (poolVertex == null) - { - poolVertex = new SweepVertex(point, flags, prev); - this.Items[this.Size] = poolVertex; - } - else - { - // Reset pooled state so linked lists are rebuilt safely. - poolVertex.Point = point; - poolVertex.Flags = flags; - poolVertex.Prev = prev; - poolVertex.Next = null; - } - - this.Size++; - return poolVertex; - } -} - -/// -/// Pool-backed list of output points allocated during clipping. +/// Pool-backed list of sweep events reused between clipping runs. /// -internal sealed class OutputPointPoolList : PooledList +internal sealed class SweepEventPoolList : PooledList { /// - /// Adds or reuses an output point and increments the owning record count. + /// Acquires a directed source interval and its paired endpoint from reusable storage. /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public OutputPoint Add(Vertex pt, OutputRecord outputRecord) + /// The canonical starting point. + /// The source terminal point. + /// The signed operand contributions. + /// The initialized live interval. + public SweepEvent Add(Vertex start, Vertex end, PolygonClipper.WindingCount delta) { this.TryGrow(); - OutputPoint pooledPoint = this.Items[this.Size]; - if (pooledPoint == null) + SweepEvent segment = this.Items[this.Size]; + if (segment == null) { - pooledPoint = new OutputPoint(pt, outputRecord); - this.Items[this.Size] = pooledPoint; - } - else - { - pooledPoint.Point = pt; - pooledPoint.OutputRecord = outputRecord; - pooledPoint.Next = pooledPoint; - pooledPoint.Prev = pooledPoint; - pooledPoint.HorizontalSegment = null; + segment = new SweepEvent(start, true); + segment.OtherEvent = new SweepEvent(end, false, segment); + this.Items[this.Size] = segment; } - this.Size++; - outputRecord.OutputPointCount++; - return pooledPoint; + segment.InitializeInterval(start, end, this.Size++, delta); + return segment; } -} - -/// -/// Pool-backed list of output records that preserves per-record state between runs. -/// -internal sealed class OutputRecordPoolList : PooledList -{ - private static readonly List Tombstone = []; /// - /// Adds or reuses an output record with cleared state. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public OutputRecord Add() + /// Acquires an output boundary record from the existing append-only pool. + /// + /// The boundary endpoint. + /// Whether this endpoint starts the canonical interval. + /// The paired endpoint. + /// The filled-side transition. + /// The fixed predecessor at interval creation. + /// The source interval identity. + /// The initialized history record. + public SweepEvent Add( + Vertex point, + bool left, + SweepEvent other, + ResultTransition transition, + SweepEvent previous, + int id) { this.TryGrow(); - OutputRecord outputRecord = this.Items[this.Size]; - if (outputRecord == null) - { - outputRecord = new OutputRecord(); - this.Items[this.Size] = outputRecord; - } - else - { - outputRecord.Index = 0; - outputRecord.OutputPointCount = 0; - outputRecord.Owner = null; - outputRecord.FrontEdge = null; - outputRecord.BackEdge = null; - outputRecord.Points = null; - outputRecord.Bounds = default; - outputRecord.Path = outputRecord.Path == Tombstone ? [] : outputRecord.Path; - outputRecord.Path.Clear(); - outputRecord.Splits?.Clear(); - outputRecord.RecursiveSplit = null; - } - + SweepEvent boundary = this.Items[this.Size] ??= new SweepEvent(point, left); + boundary.InitializeBoundary(point, left, other, transition, previous, id); this.Size++; - return outputRecord; - } - - public override void Clear() - { - base.Clear(); - for (int i = 0; i < this.Items.Length; i++) - { - OutputRecord outputRecord = this.Items[i]; - if (outputRecord == null || outputRecord.Path == Tombstone) - { - break; - } - - // Mark paths so pooled records are not accidentally reused without reset. - outputRecord.Path = Tombstone; - outputRecord.Owner = null; - outputRecord.FrontEdge = null; - outputRecord.BackEdge = null; - outputRecord.Points = null; - outputRecord.RecursiveSplit = null; - } + return boundary; } -} -/// -/// Pool-backed list of horizontal joins used during sweep processing. -/// -internal sealed class HorizontalJoinPoolList : PooledList -{ /// - /// Adds or reuses a horizontal join entry. + /// Orders completed boundary events for edge connection. /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public HorizontalJoin Add(OutputPoint ltor, OutputPoint rtol) - { - this.TryGrow(); - HorizontalJoin hJoin = this.Items[this.Size]; - if (hJoin == null) - { - hJoin = new HorizontalJoin(ltor, rtol); - this.Items[this.Size] = hJoin; - } - else - { - hJoin.LeftToRight = ltor; - hJoin.RightToLeft = rtol; - } - - this.Size++; - return hJoin; - } -} - -/// -/// Pool-backed list of sweep events reused between clipping runs. -/// -internal sealed class SweepEventPoolList : PooledList -{ - /// Orders completed native boundary events for edge connection. /// The edge connector's event ordering. public void Sort(SweepEventComparer comparer) => this.Items.AsSpan(0, this.Size).Sort(comparer); diff --git a/src/PolygonClipper/SweepVertex.cs b/src/PolygonClipper/SweepVertex.cs deleted file mode 100644 index a7f4f89..0000000 --- a/src/PolygonClipper/SweepVertex.cs +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright (c) Six Labors. -// Licensed under the Six Labors Split License. - -namespace SixLabors.PolygonClipper; - -/// -/// Represents a vertex in the input contour linked list used by the sweep. -/// -/// -/// Vertices are linked in a circular doubly linked list (see and -/// ) so the sweep can traverse ascending/descending bounds and -/// detect local minima/maxima efficiently. -/// -internal sealed class SweepVertex -{ -#pragma warning disable SA1401 // Hot sweep vertex state uses fields to avoid accessor overhead. - /// - /// The vertex position. - /// - public Vertex Point; - - /// - /// The next vertex in the contour. - /// - public SweepVertex? Next; - - /// - /// The previous vertex in the contour. - /// - public SweepVertex? Prev; - - /// - /// Flags describing sweep-related classification. - /// - public VertexFlags Flags; -#pragma warning restore SA1401 - - /// - /// Initializes a new instance of the class. - /// - public SweepVertex(Vertex point, VertexFlags flags, SweepVertex? prev) - { - this.Point = point; - this.Flags = flags; - this.Next = null; - this.Prev = prev; - } - - /// - /// Gets a value indicating whether this vertex is marked as a local maxima. - /// - public bool IsMaxima => (this.Flags & VertexFlags.LocalMax) != 0; -} diff --git a/src/PolygonClipper/Vertex.cs b/src/PolygonClipper/Vertex.cs index 9c4ccd3..f0bdc3b 100644 --- a/src/PolygonClipper/Vertex.cs +++ b/src/PolygonClipper/Vertex.cs @@ -182,14 +182,18 @@ public static double Cross(in Vertex a, in Vertex b) return determinant + secondError; } - /// Computes the Euclidean distance between the two given vertices. + /// + /// Computes the Euclidean distance between the two given vertices. + /// /// The first vertex. /// The second vertex. /// The distance. public static double Distance(in Vertex a, in Vertex b) => double.Sqrt(DistanceSquared(a, b)); - /// Returns the Euclidean distance squared between two specified vertices. + /// + /// Returns the Euclidean distance squared between two specified vertices. + /// /// The first vertex. /// The second vertex. /// The distance squared. @@ -204,7 +208,9 @@ public static double DistanceSquared(in Vertex a, in Vertex b) public double Length() => double.Sqrt(this.LengthSquared()); - /// Returns the length of the vertex squared. + /// + /// Returns the length of the vertex squared. + /// /// The vertex's length squared. /// This operation offers better performance than a call to the method. /// diff --git a/src/PolygonClipper/VertexFlags.cs b/src/PolygonClipper/VertexFlags.cs deleted file mode 100644 index d656f22..0000000 --- a/src/PolygonClipper/VertexFlags.cs +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) Six Labors. -// Licensed under the Six Labors Split License. - -namespace SixLabors.PolygonClipper; - -/// -/// Classifies sweep vertices by local-extrema role during bound construction. -/// -/// -/// The self-intersection sweep decomposes each contour into monotonic bounds that -/// start at local minima and terminate at local maxima. These flags annotate -/// each with that role. -/// -[Flags] -internal enum VertexFlags -{ - /// - /// No extrema role is assigned. - /// - None = 0, - - /// - /// Marks a local maximum vertex (bound endpoint). - /// - LocalMax = 1 << 0, - - /// - /// Marks a local minimum vertex (bound start). - /// - LocalMin = 1 << 1 -} diff --git a/tests/PolygonClipper.Benchmarks/Benches.cs b/tests/PolygonClipper.Benchmarks/Benches.cs index db0873f..f7e2f65 100644 --- a/tests/PolygonClipper.Benchmarks/Benches.cs +++ b/tests/PolygonClipper.Benchmarks/Benches.cs @@ -36,15 +36,16 @@ public void Setup() this.clipperClipping = BuildClipperPaths(clipping); } - [Benchmark] - public Polygon PolygonClipper() => SixLabors.PolygonClipper.PolygonClipper.Union(this.subject, this.clipping); - - /// Measures explicit parity clipping on the same raw geometry as the legacy API. + /// + /// Measures even-odd union on the raw input contours. + /// /// The clipped geometry. [Benchmark] public Polygon PolygonClipperEvenOdd() => SixLabors.PolygonClipper.PolygonClipper.Union(this.subject, this.clipping, FillRule.EvenOdd); - /// Measures non-zero clipping without a separate normalization operation. + /// + /// Measures non-zero clipping without a separate normalization operation. + /// /// The clipped geometry. [Benchmark] public Polygon PolygonClipperNonZero() => SixLabors.PolygonClipper.PolygonClipper.Union(this.subject, this.clipping, FillRule.NonZero); diff --git a/tests/PolygonClipper.Benchmarks/NormalizationBenches.cs b/tests/PolygonClipper.Benchmarks/NormalizationBenches.cs index cb36d09..238e661 100644 --- a/tests/PolygonClipper.Benchmarks/NormalizationBenches.cs +++ b/tests/PolygonClipper.Benchmarks/NormalizationBenches.cs @@ -34,7 +34,7 @@ public void Setup() [Benchmark] public Polygon Normalize() - => PolygonClipper.Normalize(this.polygon); + => PolygonClipper.Normalize(this.polygon, FillRule.Positive); [Benchmark(Baseline = true)] public PolyTreeD Clipper2Union() diff --git a/tests/PolygonClipper.Benchmarks/StarBooleanBenches.cs b/tests/PolygonClipper.Benchmarks/StarBooleanBenches.cs index e0a78a2..971ef06 100644 --- a/tests/PolygonClipper.Benchmarks/StarBooleanBenches.cs +++ b/tests/PolygonClipper.Benchmarks/StarBooleanBenches.cs @@ -33,7 +33,7 @@ public void Setup() [Benchmark] public Polygon PolygonClipperUnion() - => PolygonClipper.Union(this.subject, this.clipping); + => PolygonClipper.Union(this.subject, this.clipping, FillRule.EvenOdd); //[Benchmark] //public PolyTreeD Clipper2Union() @@ -48,7 +48,7 @@ public Polygon PolygonClipperUnion() [Benchmark] public Polygon PolygonClipperIntersection() - => PolygonClipper.Intersection(this.subject, this.clipping); + => PolygonClipper.Intersection(this.subject, this.clipping, FillRule.EvenOdd); //[Benchmark] //public PolyTreeD Clipper2Intersection() @@ -63,7 +63,7 @@ public Polygon PolygonClipperIntersection() [Benchmark] public Polygon PolygonClipperDifference() - => PolygonClipper.Difference(this.subject, this.clipping); + => PolygonClipper.Difference(this.subject, this.clipping, FillRule.EvenOdd); //[Benchmark] //public PolyTreeD Clipper2Difference() @@ -78,7 +78,7 @@ public Polygon PolygonClipperDifference() [Benchmark] public Polygon PolygonClipperXor() - => PolygonClipper.Xor(this.subject, this.clipping); + => PolygonClipper.Xor(this.subject, this.clipping, FillRule.EvenOdd); //[Benchmark] //public PolyTreeD Clipper2Xor() diff --git a/tests/PolygonClipper.Tests/ContourTests.cs b/tests/PolygonClipper.Tests/ContourTests.cs index edcd1e7..971c67f 100644 --- a/tests/PolygonClipper.Tests/ContourTests.cs +++ b/tests/PolygonClipper.Tests/ContourTests.cs @@ -65,6 +65,7 @@ public void DefaultConstructor_CreatesEmptyContour() Assert.True(contour.IsExternal); Assert.Null(contour.ParentIndex); Assert.Equal(0, contour.Depth); + Assert.True(contour.IsClosed); } [Fact] @@ -73,6 +74,63 @@ public void CapacityConstructor_StartsEmpty() Contour contour = new(64); Assert.Equal(0, contour.Count); + Assert.True(contour.IsClosed); + } + + /// + /// Checks that vertex and hierarchy edits do not change source closure. + /// + /// The source closure state. + [Theory] + [InlineData(false)] + [InlineData(true)] + public void Closure_VertexEditsAndCopy_PreserveState(bool isClosed) + { + Contour contour = CreateSquare(0, 0, 10); + contour.IsClosed = isClosed; + + contour.Reverse(); + Assert.Equal(isClosed, contour.IsClosed); + contour.Translate(2, 3); + Assert.Equal(isClosed, contour.IsClosed); + contour.Add(new Vertex(4, 5)); + Assert.Equal(isClosed, contour.IsClosed); + contour.RemoveVertexAt(contour.Count - 1); + Assert.Equal(isClosed, contour.IsClosed); + + Polygon polygon = [contour]; + Contour joined = CreateSquare(20, 0, 10); + joined.IsClosed = isClosed; + polygon.Join([joined]); + Assert.Equal(isClosed, polygon[0].IsClosed); + Assert.Equal(isClosed, polygon[1].IsClosed); + + Polygon clone = polygon.DeepClone(); + Assert.Equal(isClosed, clone[0].IsClosed); + Assert.Equal(isClosed, clone[1].IsClosed); + clone[0].IsClosed = !isClosed; + Assert.Equal(isClosed, contour.IsClosed); + + contour.Clear(); + Assert.Empty(contour); + Assert.Equal(isClosed, contour.IsClosed); + } + + /// + /// Checks that orientation and filled-boundary segments do not depend on source closure. + /// + [Fact] + public void Closure_OrientationAndFilledBoundary_AreUnchanged() + { + Contour contour = CreateSquare(0, 0, 10); + Assert.True(contour.IsCounterClockwise()); + + contour.IsClosed = false; + + Assert.True(contour.IsCounterClockwise()); + Segment closing = contour.GetSegment(contour.Count - 1); + Assert.Equal(new Vertex(0, 10), closing.Source); + Assert.Equal(new Vertex(0, 0), closing.Target); } [Fact] diff --git a/tests/PolygonClipper.Tests/FloatExtensionsTests.cs b/tests/PolygonClipper.Tests/DoubleExtensionsTests.cs similarity index 97% rename from tests/PolygonClipper.Tests/FloatExtensionsTests.cs rename to tests/PolygonClipper.Tests/DoubleExtensionsTests.cs index 7102c44..cdcf2e4 100644 --- a/tests/PolygonClipper.Tests/FloatExtensionsTests.cs +++ b/tests/PolygonClipper.Tests/DoubleExtensionsTests.cs @@ -3,7 +3,7 @@ namespace SixLabors.PolygonClipper.Tests; -public class FloatExtensionsTests +public class DoubleExtensionsTests { public static TheoryData NextAfterTestData => new() { diff --git a/tests/PolygonClipper.Tests/FillRuleClippingTests.cs b/tests/PolygonClipper.Tests/FillRuleClippingTests.cs index 9d9948c..737bc93 100644 --- a/tests/PolygonClipper.Tests/FillRuleClippingTests.cs +++ b/tests/PolygonClipper.Tests/FillRuleClippingTests.cs @@ -3,10 +3,366 @@ namespace SixLabors.PolygonClipper.Tests; -/// Checks filled geometry through the public single-sweep APIs. +/// +/// Checks filled geometry through the public single-sweep APIs. +/// public class FillRuleClippingTests { - /// Checks dense self-crossings through the established star input generator. + /// + /// Checks the result bounds when the clipping operand extends beyond the subject. + /// + [Fact] + public void BoundedOperations_LongClip_PreserveCompleteResult() + { + Polygon subject = [Rectangle(0, 0, 10, 10)]; + Polygon clip = [Rectangle(5, -1, 1000, 11)]; + + Polygon intersection = PolygonClipper.Intersection(subject, clip, FillRule.NonZero); + Polygon difference = PolygonClipper.Difference(subject, clip, FillRule.NonZero); + + Assert.Equal(50D, Area(intersection)); + Assert.Equal(50D, Area(difference)); + Assert.Equal(new Vertex(5, 0), intersection.GetBoundingBox().Min); + Assert.Equal(new Vertex(10, 10), intersection.GetBoundingBox().Max); + Assert.Equal(new Vertex(0, 0), difference.GetBoundingBox().Min); + Assert.Equal(new Vertex(5, 10), difference.GetBoundingBox().Max); + } + + /// + /// Checks reuse of a full nesting hierarchy in a second clipping operation. + /// + [Fact] + public void NestedCleanup_ReusedInIntersection_PreservesAreaAndInputHierarchy() + { + Polygon source = [Rectangle(0, 0, 10, 10), Rectangle(2, 2, 8, 8), Rectangle(3, 3, 7, 7), Rectangle(4, 4, 6, 6)]; + Polygon cleaned = PolygonClipper.Normalize(source, FillRule.EvenOdd); + Polygon original = cleaned.DeepClone(); + + Polygon result = PolygonClipper.Intersection(cleaned, [Rectangle(5, -1, 11, 11)], FillRule.NonZero); + + // The mask bisects the symmetric area: (100 - 36 + 16 - 4) / 2 = 38. + Assert.Equal(38D, Area(result)); + Assert.Equal(2, result.Count); + foreach (Contour contour in result) + { + Assert.Null(contour.ParentIndex); + Assert.Equal(0, contour.Depth); + Assert.Equal(0, contour.HoleCount); + } + + for (int i = 0; i < cleaned.Count; i++) + { + Assert.Equal(original[i], cleaned[i]); + Assert.Equal(original[i].ParentIndex, cleaned[i].ParentIndex); + Assert.Equal(original[i].Depth, cleaned[i].Depth); + Assert.Equal(original[i].HoleCount, cleaned[i].HoleCount); + } + } + + /// + /// Checks rule validation before the empty-intersection shortcut. + /// + /// An undefined fill-rule value. + [Theory] + [InlineData(-1)] + [InlineData(4)] + public void InvalidRules_EmptyOperands_Throw(int value) + { + FillRule invalid = (FillRule)value; + Assert.Throws(() => PolygonClipper.Intersection([], [], invalid)); + Assert.Throws(() => PolygonClipper.Intersection([], [], FillRule.NonZero, invalid)); + Assert.Throws(() => PolygonClipper.Union([], invalid)); + Assert.Throws(() => new PolygonClipper([], [], BooleanOperation.Union, invalid, FillRule.NonZero)); + Assert.Throws(() => new PolygonClipper([], [], (BooleanOperation)value, FillRule.NonZero, FillRule.NonZero)); + } + + /// + /// Checks coordinate validation and pooled reuse after an operation fails during ingestion. + /// + /// The non-finite source coordinate. + [Theory] + [InlineData(double.NaN)] + [InlineData(double.PositiveInfinity)] + [InlineData(double.NegativeInfinity)] + public void NonFiniteCoordinates_UsedInputsThrow_AndPoolRemainsUsable(double coordinate) + { + Polygon invalid = [Rectangle(0, 0, 2, 2), [new Vertex(coordinate, 0), new Vertex(1, 0), new Vertex(0, 1)]]; + + // Empty intersection does not inspect unused geometry. Unary union does. + Assert.Empty(PolygonClipper.Intersection(invalid, [], FillRule.NonZero)); + Assert.Throws(() => PolygonClipper.Union(invalid, FillRule.NonZero)); + Assert.Equal(4D, Area(PolygonClipper.Union([Rectangle(0, 0, 2, 2)], FillRule.NonZero))); + } + + /// + /// Checks that rounded equal products do not cancel distinct source edges. + /// + /// The source fill rule. + [Theory] + [InlineData(FillRule.EvenOdd)] + [InlineData(FillRule.NonZero)] + [InlineData(FillRule.Positive)] + public void UnaryUnion_NearlyParallelIntegerEdges_PreservesTriangle(FillRule rule) + { + const double n = 134217728D; + Contour triangle = [new Vertex(0, 0), new Vertex(n, n + 1), new Vertex(n - 1, n)]; + + Polygon result = PolygonClipper.Union([triangle], rule); + + // The determinant is n*n - (n+1)*(n-1) = 1, so the area is exactly one half. + Contour boundary = Assert.Single(result); + Assert.Equal(3, boundary.Count); + Assert.Equal(0.5D, Area(result)); + foreach (Vertex vertex in triangle) + { + Assert.Contains(vertex, boundary); + } + } + + /// + /// Checks that input fill rules select the area while cleanup returns positive-oriented boundaries. + /// + /// The input fill rule. + /// The analytically expected filled area. + [Theory] + [InlineData(FillRule.EvenOdd, 64D)] + [InlineData(FillRule.NonZero, 64D)] + [InlineData(FillRule.Positive, 0D)] + [InlineData(FillRule.Negative, 64D)] + public void Cleanup_ClockwiseDonut_SelectsInputRuleAndCanonicalOutput(FillRule rule, double expectedArea) + { + Contour exterior = Rectangle(0, 0, 10, 10); + exterior.Reverse(); + Polygon input = [exterior, Rectangle(2, 2, 8, 8)]; + Polygon original = input.DeepClone(); + + Polygon cleaned = PolygonClipper.Normalize(input, rule); + Polygon union = PolygonClipper.Union(input, rule); + + // The clockwise exterior contributes -1. Its counterclockwise inner + // contour cancels that count in the 6-by-6 hole: 100 - 36 = 64. + Assert.Equal(expectedArea, Area(cleaned)); + Assert.Equal(expectedArea, Area(union)); + Assert.Equal(union.Count, cleaned.Count); + for (int i = 0; i < input.Count; i++) + { + Assert.Equal(original[i], input[i]); + Assert.Equal(original[i].ParentIndex, input[i].ParentIndex); + } + + if (expectedArea == 0) + { + Assert.Empty(cleaned); + Assert.Empty(union); + } + else + { + Assert.Equal(2, cleaned.Count); + Assert.True(Area([cleaned[0]]) > 0); + Assert.True(Area([cleaned[1]]) < 0); + Assert.Equal(0, cleaned[1].ParentIndex); + Assert.Equal(1, cleaned[0].GetHoleIndex(0)); + + for (int i = 0; i < cleaned.Count; i++) + { + Assert.True(cleaned[i].IsClosed); + Assert.NotEqual(cleaned[i][0], cleaned[i][^1]); + Assert.Equal(union[i], cleaned[i]); + } + + // Resolved output describes an area with positive orientation. + // NonZero, EvenOdd, and Positive therefore preserve that area on reuse. + Assert.Equal(expectedArea, Area(PolygonClipper.Normalize(cleaned, FillRule.NonZero))); + Assert.Equal(expectedArea, Area(PolygonClipper.Normalize(cleaned, FillRule.EvenOdd))); + Assert.Equal(expectedArea, Area(PolygonClipper.Normalize(cleaned, FillRule.Positive))); + Assert.Empty(PolygonClipper.Normalize(cleaned, FillRule.Negative)); + } + } + + /// + /// Checks cleanup against the bowtie's analytically defined winding regions. + /// + [Fact] + public void Cleanup_Bowtie_SelectedRuleDeterminesFilledLobes() + { + Contour bowtie = [new Vertex(0, 0), new Vertex(100, 100), new Vertex(100, 0), new Vertex(0, 100)]; + + Polygon positive = PolygonClipper.Normalize([bowtie], FillRule.Positive); + Polygon negative = PolygonClipper.Normalize([bowtie], FillRule.Negative); + Polygon evenOdd = PolygonClipper.Normalize([bowtie], FillRule.EvenOdd); + Polygon nonZero = PolygonClipper.Normalize([bowtie], FillRule.NonZero); + bowtie.Reverse(); + Polygon reversed = PolygonClipper.Normalize([bowtie], FillRule.Positive); + Polygon reversedNonZero = PolygonClipper.Normalize([bowtie], FillRule.NonZero); + + // The two triangular lobes each have base 100 and perpendicular height 50. + Assert.Equal(2500D, Area(positive)); + Assert.Equal(2500D, Area(negative)); + Assert.Equal(2500D, Area(reversed)); + Assert.Equal(5000D, Area(evenOdd)); + Assert.Equal(5000D, Area(nonZero)); + Assert.Equal(5000D, Area(reversedNonZero)); + Assert.Equal(new Vertex(0, 0), positive.GetBoundingBox().Min); + Assert.Equal(new Vertex(50, 100), positive.GetBoundingBox().Max); + Assert.Equal(new Vertex(50, 0), negative.GetBoundingBox().Min); + Assert.Equal(new Vertex(100, 100), negative.GetBoundingBox().Max); + Assert.Equal(new Vertex(50, 0), reversed.GetBoundingBox().Min); + Assert.Equal(new Vertex(100, 100), reversed.GetBoundingBox().Max); + + foreach (Polygon filled in new[] { nonZero, evenOdd, reversedNonZero }) + { + // The crossing is a shared vertex, not a bridge between the filled lobes. + Assert.Equal(2, filled.Count); + Assert.Contains(filled, triangle => triangle.Contains(new Vertex(0, 0)) && + triangle.Contains(new Vertex(50, 50)) && triangle.Contains(new Vertex(0, 100))); + Assert.Contains(filled, triangle => triangle.Contains(new Vertex(50, 50)) && + triangle.Contains(new Vertex(100, 0)) && triangle.Contains(new Vertex(100, 100))); + foreach (Contour triangle in filled) + { + Assert.Equal(3, triangle.Count); + Assert.True(triangle.IsClosed); + Assert.Null(triangle.ParentIndex); + Assert.Equal(0, triangle.HoleCount); + Assert.Equal(2500D, Area([triangle])); + } + } + } + + /// + /// Checks that retraced lines have no filled area in cleanup or binary clipping. + /// + /// The input fill rule. + [Theory] + [InlineData(FillRule.EvenOdd)] + [InlineData(FillRule.NonZero)] + [InlineData(FillRule.Positive)] + [InlineData(FillRule.Negative)] + public void Cleanup_RetracedLine_ProducesNoPolygon(FillRule rule) + { + Polygon line = [[new Vertex(0, 0), new Vertex(1, 0), new Vertex(0, 0)]]; + Polygon distant = [Rectangle(10, 10, 20, 20)]; + + Assert.Empty(PolygonClipper.Normalize(line, rule)); + Assert.Empty(PolygonClipper.Union(line, rule)); + Assert.Empty(PolygonClipper.Intersection(line, distant, rule, FillRule.NonZero)); + Assert.Empty(PolygonClipper.Difference(line, distant, rule, FillRule.NonZero)); + Assert.Equal(100D, Area(PolygonClipper.Union(line, distant, rule, FillRule.NonZero))); + Assert.Equal(100D, Area(PolygonClipper.Xor(line, distant, rule, FillRule.NonZero))); + } + + /// + /// Checks that cleanup retains real small features without fixed distance or area cutoffs. + /// + /// The triangle's side length. + [Theory] + [InlineData(1E-7)] + [InlineData(1E-90)] + [InlineData(1E90)] + public void Cleanup_ScaledTriangle_PreservesFilledArea(double scale) + { + Polygon triangle = [[new Vertex(0, 0), new Vertex(scale, 0), new Vertex(0, scale)]]; + + Polygon cleaned = PolygonClipper.Normalize(triangle, FillRule.NonZero); + + Assert.Equal(3, Assert.Single(cleaned).Count); + Assert.Equal(0.5D, Area(cleaned) / (scale * scale), 10); + } + + /// + /// Checks full nesting metadata independently of the input contour directions. + /// + [Fact] + public void Cleanup_FourNestedRings_PreservesContainmentAndArea() + { + Polygon input = [Rectangle(0, 0, 10, 10), Rectangle(2, 2, 8, 8), Rectangle(3, 3, 7, 7), Rectangle(4, 4, 6, 6)]; + + Polygon cleaned = PolygonClipper.Normalize(input, FillRule.EvenOdd); + Polygon union = PolygonClipper.Union(input, FillRule.EvenOdd); + + Assert.Equal(76D, Area(cleaned)); + Assert.Equal(4, cleaned.Count); + for (int i = 0; i < cleaned.Count; i++) + { + Assert.Equal(i, cleaned[i].Depth); + Assert.Equal(i == 0 ? (int?)null : i - 1, cleaned[i].ParentIndex); + Assert.Equal((i & 1) == 0, Area([cleaned[i]]) > 0); + Assert.Equal(union[i], cleaned[i]); + Assert.Equal(i == 3 ? 0 : 1, cleaned[i].HoleCount); + if (i < 3) + { + Assert.Equal(i + 1, cleaned[i].GetHoleIndex(0)); + } + } + } + + /// + /// Checks direct fill-aware clipping of overlapping glyph-like contours without preparation. + /// + [Fact] + public void DirectClipping_OverlappingContours_NeedsNoCleanupPass() + { + Polygon subject = [Rectangle(0, 0, 10, 10), Rectangle(5, 0, 15, 10)]; + Polygon clip = [Rectangle(2, -1, 13, 11)]; + + Polygon nonZero = PolygonClipper.Intersection(subject, clip, FillRule.NonZero, FillRule.EvenOdd); + Polygon evenOdd = PolygonClipper.Intersection(subject, clip, FillRule.EvenOdd); + + // NonZero keeps the whole 11-by-10 clipped band. EvenOdd removes the + // doubly covered 5-by-10 middle band and leaves two 3-by-10 pieces. + Assert.Equal(110D, Area(nonZero)); + Assert.Equal(60D, Area(evenOdd)); + AssertCoverage(subject, clip, nonZero, BooleanOperation.Intersection, FillRule.NonZero, FillRule.EvenOdd); + AssertCoverage(subject, clip, evenOdd, BooleanOperation.Intersection, FillRule.EvenOdd, FillRule.EvenOdd); + } + + /// + /// Checks direct NonZero clipping of both bowtie lobes without prior normalization. + /// + [Fact] + public void DirectClipping_SelfIntersection_PreservesBothNonZeroLobes() + { + Polygon subject = [[new Vertex(0, 0), new Vertex(100, 100), new Vertex(100, 0), new Vertex(0, 100)]]; + Polygon clip = [Rectangle(25, -10, 75, 110)]; + + Polygon result = PolygonClipper.Intersection(subject, clip, FillRule.NonZero, FillRule.EvenOdd); + + // Each clipped lobe is a triangle with base 50 and height 25. + // NonZero retains both signs, giving total area 2 * 50 * 25 / 2 = 1250. + Assert.Equal(1250D, Area(result)); + Assert.Equal(new Vertex(25, 25), result.GetBoundingBox().Min); + Assert.Equal(new Vertex(75, 75), result.GetBoundingBox().Max); + AssertCoverage(subject, clip, result, BooleanOperation.Intersection, FillRule.NonZero, FillRule.EvenOdd); + } + + /// + /// Checks that input ownership metadata cannot override the selected fill rule. + /// + /// The input fill rule. + /// The analytically expected filled area. + [Theory] + [InlineData(FillRule.EvenOdd, 64D)] + [InlineData(FillRule.NonZero, 100D)] + [InlineData(FillRule.Positive, 100D)] + [InlineData(FillRule.Negative, 0D)] + public void Cleanup_InputHierarchy_DoesNotOverrideWinding(FillRule rule, double expectedArea) + { + Polygon input = [Rectangle(0, 0, 10, 10), Rectangle(2, 2, 8, 8)]; + input[0].AddHoleIndex(1); + input[1].ParentIndex = 0; + input[1].Depth = 1; + + Polygon cleaned = PolygonClipper.Normalize(input, rule); + + Assert.Equal(expectedArea, Area(cleaned)); + Assert.Equal(0, input[1].ParentIndex); + Assert.Equal(1, input[0].GetHoleIndex(0)); + Assert.Equal(4, input[0].Count); + Assert.Equal(4, input[1].Count); + } + + /// + /// Checks dense self-crossings through the established star input generator. + /// /// The number of vertices in each star. [Theory] [InlineData(31)] @@ -25,7 +381,9 @@ public void DenseStars_ExplicitRules_MatchSourceCoverage(int vertexCount) } } - /// Checks both small and large double coordinate scales without integer conversion. + /// + /// Checks both small and large double coordinate scales without integer conversion. + /// /// The coordinate scale. [Theory] [InlineData(1E-90)] @@ -39,7 +397,9 @@ public void UnaryUnion_ScaledCrossing_PreservesFilledArea(double scale) Assert.Equal(50D, Area(result) / (scale * scale), 10); } - /// Checks that empty-operand shortcuts cannot return unresolved duplicate contours. + /// + /// Checks that empty-operand shortcuts cannot return unresolved duplicate contours. + /// /// The subject fill rule. /// The expected filled area. [Theory] @@ -57,7 +417,9 @@ public void EmptyClippingOperand_PreservesSelectedFillRule(FillRule rule, double Assert.Empty(PolygonClipper.Intersection(input, [], rule)); } - /// Checks raw geographic contours at the scales used by the benchmark suite. + /// + /// Checks raw geographic contours at the scales used by the benchmark suite. + /// /// The geographic benchmark fixture. [Theory] [InlineData("hole_hole.geojson")] @@ -76,7 +438,9 @@ public void GeographicFixtures_MixedRules_MatchSourceCoverage(string file) } } - /// Checks the established intersection defect corpus under independent fill rules. + /// + /// Checks the established intersection defect corpus under independent fill rules. + /// /// The existing GeoJSON defect fixture. [Theory] [MemberData(nameof(GenericTestCases.GetTestCases), MemberType = typeof(GenericTestCases))] @@ -96,7 +460,9 @@ public void ExistingDefectFixtures_ExplicitRules_MatchSourceCoverage(string test } } - /// Checks arbitrary directed crossings against the independent source winding oracle. + /// + /// Checks arbitrary directed crossings against the independent source winding oracle. + /// [Fact] public void SeededSelfCrossingContours_MixedRules_MatchSourceCoverage() { @@ -119,7 +485,9 @@ public void SeededSelfCrossingContours_MixedRules_MatchSourceCoverage() } } - /// Constructs a deterministic closed contour with unconstrained direction and crossings. + /// + /// Constructs a deterministic closed contour with unconstrained direction and crossings. + /// /// The seeded generator. /// The raw directed contour. private static Contour RandomContour(Random random) @@ -134,7 +502,9 @@ private static Contour RandomContour(Random random) return contour; } - /// Enumerates independent operand rules and all Boolean operations. + /// + /// Enumerates independent operand rules and all Boolean operations. + /// /// The geometric case and operation combinations. public static TheoryData Combinations() { @@ -156,7 +526,9 @@ public static TheoryData Combinations return data; } - /// Distinguishes raw signed winding from nesting-based hole preparation. + /// + /// Distinguishes raw signed winding from nesting-based hole preparation. + /// /// The input fill rule. /// The analytically expected area. [Theory] @@ -176,7 +548,9 @@ public void UnaryUnion_SameDirectionNestedRings_UsesSelectedRule(FillRule rule, Assert.Null(input[1].ParentIndex); } - /// Retains both winding signs of a zero-net-area self-crossing contour. + /// + /// Retains both winding signs of a zero-net-area self-crossing contour. + /// /// The input fill rule. /// The analytically expected area. [Theory] @@ -193,7 +567,9 @@ public void UnaryUnion_Bowtie_ResolvesBothWindingSigns(FillRule rule, double are Assert.Equal(area, Area(result), 10); } - /// Checks binary output against direct winding of the original, unsplit contours. + /// + /// Checks binary output against direct winding of the original, unsplit contours. + /// /// The directed input configuration. /// The Boolean operation. /// The subject rule. @@ -209,9 +585,11 @@ public void BinaryOperations_MixedRules_MatchOriginalWinding( AssertCoverage(subject, clip, result, operation, subjectRule, clipRule); } - /// Checks sign reversal, manual reuse, and the preserved legacy overload path. + /// + /// Checks sign reversal and rule changes between manual and pooled calls. + /// [Fact] - public void ManualClipperAndPooledLegacyCalls_DoNotLeakRules() + public void ManualClipperAndPooledCalls_DoNotLeakRules() { Polygon subject = [Rectangle(0, 0, 10, 10)]; subject[0].Reverse(); @@ -221,13 +599,15 @@ public void ManualClipperAndPooledLegacyCalls_DoNotLeakRules() Assert.Equal(0D, Area(PolygonClipper.Union(subject, FillRule.Positive))); Assert.Equal(100D, Area(PolygonClipper.Union(subject, FillRule.Negative))); - Polygon legacy = PolygonClipper.Union(subject, []); - Assert.Equal(subject[0].Count, legacy[0].Count); - Assert.False(legacy[0].IsCounterClockwise()); - Assert.NotSame(subject[0], legacy[0]); + Polygon evenOdd = PolygonClipper.Union(subject, [], FillRule.EvenOdd); + Assert.Equal(subject[0].Count, evenOdd[0].Count); + Assert.True(evenOdd[0].IsCounterClockwise()); + Assert.NotSame(subject[0], evenOdd[0]); } - /// Checks double-coordinate behavior without integer scaling. + /// + /// Checks double-coordinate behavior without integer scaling. + /// [Fact] public void UnaryUnion_TranslatedUnitRings_PreservesSmallArea() { @@ -240,7 +620,9 @@ public void UnaryUnion_TranslatedUnitRings_PreservesSmallArea() Assert.Equal(origin, result[0].GetBoundingBox().Min.X); } - /// Checks output against signed source coverage away from input boundaries. + /// + /// Checks output against signed source coverage away from input boundaries. + /// /// The original subject contours. /// The original clipping contours. /// The clipped geometry. @@ -292,7 +674,9 @@ private static void AssertCoverage(Polygon subject, Polygon clip, Polygon result } } - /// Builds raw directed input cases with crossings, vertical runs, and duplicates. + /// + /// Builds raw directed input cases with crossings, vertical runs, and duplicates. + /// /// The requested case. /// The subject and clipping contours. private static (Polygon Subject, Polygon Clip) Inputs(int geometry) @@ -317,7 +701,9 @@ private static (Polygon Subject, Polygon Clip) Inputs(int geometry) return (subject, clip); } - /// Executes the selected public binary operation. + /// + /// Executes the selected public binary operation. + /// /// The subject. /// The clipping contours. /// The Boolean operation. @@ -343,7 +729,9 @@ private static Polygon Execute(Polygon subject, Polygon clip, BooleanOperation o } } - /// Constructs a positively directed rectangle. + /// + /// Constructs a positively directed rectangle. + /// /// The left coordinate. /// The top coordinate. /// The right coordinate. @@ -352,7 +740,9 @@ private static Polygon Execute(Polygon subject, Polygon clip, BooleanOperation o private static Contour Rectangle(double left, double top, double right, double bottom) => [new Vertex(left, top), new Vertex(right, top), new Vertex(right, bottom), new Vertex(left, bottom)]; - /// Evaluates the documented winding predicates independently of the clipper. + /// + /// Evaluates the documented winding predicates independently of the clipper. + /// /// The winding count. /// The selected rule. /// The filled membership. @@ -365,7 +755,9 @@ private static bool Filled(int winding, FillRule rule) _ => winding < 0 }; - /// Counts signed horizontal-ray crossings on the original contours. + /// + /// Counts signed horizontal-ray crossings on the original contours. + /// /// The directed contours. /// A point away from input boundaries. /// The signed winding count. @@ -393,7 +785,9 @@ private static int Winding(Polygon polygon, Vertex point) return winding; } - /// Excludes points whose membership is boundary-convention dependent. + /// + /// Excludes points whose membership is boundary-convention dependent. + /// /// The input contours. /// The sampled point. /// Whether the point lies on a source segment. @@ -428,7 +822,9 @@ private static bool OnBoundary(Polygon polygon, Vertex point) return false; } - /// Measures signed filled area using a local origin for each result ring. + /// + /// Measures signed filled area using a local origin for each result ring. + /// /// The result geometry. /// The total signed area. private static double Area(Polygon polygon) diff --git a/tests/PolygonClipper.Tests/GenericTestCases.cs b/tests/PolygonClipper.Tests/GenericTestCases.cs index d65ea59..fb2f66d 100644 --- a/tests/PolygonClipper.Tests/GenericTestCases.cs +++ b/tests/PolygonClipper.Tests/GenericTestCases.cs @@ -1,10 +1,8 @@ // Copyright (c) Six Labors. // Licensed under the Six Labors Split License. -using GeoJson; using GeoJson.Feature; using GeoJson.Geometry; -using GeoPolygon = GeoJson.Geometry.Polygon; namespace SixLabors.PolygonClipper.Tests; @@ -32,7 +30,7 @@ public void GenericTestCase(string testCaseFile) (Polygon subject, Polygon clipping) = TestPolygonUtilities.BuildPolygon(data); #pragma warning disable RCS1124 // Inline local variable - List expectedResults = ExtractExpectedResults([.. data.Features.Skip(2)], data.Type); + List expectedResults = ExtractExpectedResults([.. data.Features.Skip(2)]); #pragma warning restore RCS1124 // Inline local variable foreach (ExpectedResult result in expectedResults) @@ -43,13 +41,33 @@ public void GenericTestCase(string testCaseFile) Assert.Equal(expected.Count, actual.Count); for (int i = 0; i < expected.Count; i++) { - // We don't test for holes here as the reference tests do not do so. this.testOutputHelper.WriteLine($"Current Contour {i}"); - Assert.Equal(expected[i].Count, actual[i].Count); - for (int j = 0; j < expected[i].Count; j++) + Contour reference = expected[i]; + Assert.Equal(reference[0], reference[^1]); + + // GeoJSON stores a closing vertex. V2 returns each ring without it. + int count = reference.Count - 1; + Assert.Equal(count, actual[i].Count); + Assert.NotEqual(actual[i][0], actual[i][^1]); + Assert.Equal(reference.IsExternal, actual[i].IsExternal); + + // Derive reference direction from its coordinates and GeoJSON ring + // role, without using the production orientation calculation. + double area = 0; + Vertex origin = reference[0]; + for (int j = 1; j < count - 1; j++) + { + Vertex first = reference[j]; + Vertex second = reference[j + 1]; + area += ((first.X - origin.X) * (second.Y - origin.Y)) - + ((first.Y - origin.Y) * (second.X - origin.X)); + } + + bool reverse = (area >= 0) != reference.IsExternal; + for (int j = 0; j < count; j++) { - Vertex expectedVertex = expected[i][j]; + Vertex expectedVertex = reference[reverse ? count - 1 - j : j]; Vertex actualVertex = actual[i][j]; Assert.Equal(expectedVertex.X, actualVertex.X, 3); Assert.Equal(expectedVertex.Y, actualVertex.Y, 3); @@ -58,33 +76,29 @@ public void GenericTestCase(string testCaseFile) } } - private static List ExtractExpectedResults(List features, GeoJSONObjectType type) + /// + /// Reads the reference operations and their GeoJSON geometry. + /// + /// The reference operations and their GeoJSON output. + /// The operations and their expected contours. + private static List ExtractExpectedResults(List features) => features.ConvertAll(feature => { string mode = feature.Properties["operation"]?.ToString(); Func operation = mode switch { - "union" => (a, b) => PolygonClipper.Union(a, b), - "intersection" => (a, b) => PolygonClipper.Intersection(a, b), - "xor" => (a, b) => PolygonClipper.Xor(a, b), - "diff" => (a, b) => PolygonClipper.Difference(a, b), - "diff_ba" => (a, b) => PolygonClipper.Difference(b, a), + "union" => (a, b) => PolygonClipper.Union(a, b, FillRule.EvenOdd), + "intersection" => (a, b) => PolygonClipper.Intersection(a, b, FillRule.EvenOdd), + "xor" => (a, b) => PolygonClipper.Xor(a, b, FillRule.EvenOdd), + "diff" => (a, b) => PolygonClipper.Difference(a, b, FillRule.EvenOdd), + "diff_ba" => (a, b) => PolygonClipper.Difference(b, a, FillRule.EvenOdd), _ => throw new InvalidOperationException($"Invalid mode: {mode}") }; - if (type == GeoJSONObjectType.Polygon) - { - return new ExpectedResult - { - Operation = operation, - Coordinates = TestPolygonUtilities.ConvertToPolygon(feature.Geometry as GeoPolygon) - }; - } - return new ExpectedResult { Operation = operation, - Coordinates = TestPolygonUtilities.ConvertToPolygon(feature.Geometry as MultiPolygon) + Coordinates = TestPolygonUtilities.ConvertToPolygon(feature.Geometry) }; }); @@ -107,10 +121,12 @@ public void StarBenchmark() { Polygon subject = BuildStarPolygon(1001, 100D, 0D, 0D); Polygon clipping = BuildStarPolygon(1001, 100D, 35D, 22D); - Polygon result = PolygonClipper.Union(subject, clipping); + Polygon result = PolygonClipper.Union(subject, clipping, FillRule.EvenOdd); } - /// Constructs the self-crossing star used by the clipping stress cases. + /// + /// Constructs the self-crossing star used by the clipping stress cases. + /// /// The odd vertex count. /// The distance from the centre to each vertex. /// The horizontal centre. diff --git a/tests/PolygonClipper.Tests/HorizontalJoinPoolListTests.cs b/tests/PolygonClipper.Tests/HorizontalJoinPoolListTests.cs deleted file mode 100644 index ec05f40..0000000 --- a/tests/PolygonClipper.Tests/HorizontalJoinPoolListTests.cs +++ /dev/null @@ -1,104 +0,0 @@ -// Copyright (c) Six Labors. -// Licensed under the Six Labors Split License. - -namespace SixLabors.PolygonClipper.Tests; - -public class HorizontalJoinPoolListTests -{ - private static OutputPoint CreatePoint(double x, double y) - => new(new Vertex(x, y), new OutputRecord()); - - [Fact] - public void Add_GrowsCountAndReturnsEntry() - { - HorizontalJoinPoolList pool = new(); - OutputPoint l = CreatePoint(0, 0); - OutputPoint r = CreatePoint(10, 0); - - HorizontalJoin join = pool.Add(l, r); - - Assert.Equal(1, pool.Count); - Assert.Same(join, pool[0]); - Assert.Same(l, join.LeftToRight); - Assert.Same(r, join.RightToLeft); - } - - [Fact] - public void Add_PastCapacity_GrowsBackingArray() - { - HorizontalJoinPoolList pool = new(); - - for (int i = 0; i < 9; i++) - { - pool.Add(CreatePoint(i, 0), CreatePoint(i + 1, 0)); - } - - Assert.Equal(9, pool.Count); - Assert.True(pool.Capacity >= 9); - for (int i = 0; i < 9; i++) - { - Assert.Equal(new Vertex(i, 0), pool[i].LeftToRight!.Point); - Assert.Equal(new Vertex(i + 1, 0), pool[i].RightToLeft!.Point); - } - } - - [Fact] - public void Clear_ResetsCountWithoutShrinkingCapacity() - { - HorizontalJoinPoolList pool = new(); - pool.Add(CreatePoint(0, 0), CreatePoint(1, 0)); - pool.Add(CreatePoint(2, 0), CreatePoint(3, 0)); - int capacityBefore = pool.Capacity; - - pool.Clear(); - - Assert.Equal(0, pool.Count); - Assert.Equal(capacityBefore, pool.Capacity); - } - - [Fact] - public void Add_AfterClear_ReusesExistingInstance() - { - HorizontalJoinPoolList pool = new(); - HorizontalJoin first = pool.Add(CreatePoint(0, 0), CreatePoint(1, 0)); - - pool.Clear(); - - OutputPoint newL = CreatePoint(5, 5); - OutputPoint newR = CreatePoint(6, 5); - HorizontalJoin reused = pool.Add(newL, newR); - - Assert.Same(first, reused); - Assert.Same(newL, reused.LeftToRight); - Assert.Same(newR, reused.RightToLeft); - Assert.Equal(1, pool.Count); - } - - [Fact] - public void EnsureCapacity_GrowsBackingArrayWithoutChangingCount() - { - HorizontalJoinPoolList pool = new(); - - pool.EnsureCapacity(32); - - Assert.True(pool.Capacity >= 32); - Assert.Equal(0, pool.Count); - } - - [Fact] - public void Enumeration_YieldsItemsInInsertionOrder() - { - HorizontalJoinPoolList pool = new(); - HorizontalJoin a = pool.Add(CreatePoint(0, 0), CreatePoint(1, 0)); - HorizontalJoin b = pool.Add(CreatePoint(2, 0), CreatePoint(3, 0)); - HorizontalJoin c = pool.Add(CreatePoint(4, 0), CreatePoint(5, 0)); - - List seen = []; - foreach (HorizontalJoin entry in pool) - { - seen.Add(entry); - } - - Assert.Equal([a, b, c], seen); - } -} diff --git a/tests/PolygonClipper.Tests/HorizontalJoinTests.cs b/tests/PolygonClipper.Tests/HorizontalJoinTests.cs deleted file mode 100644 index bd3b0b9..0000000 --- a/tests/PolygonClipper.Tests/HorizontalJoinTests.cs +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) Six Labors. -// Licensed under the Six Labors Split License. - -namespace SixLabors.PolygonClipper.Tests; - -public class HorizontalJoinTests -{ - private static OutputPoint CreatePoint(double x, double y) - => new(new Vertex(x, y), new OutputRecord()); - - [Fact] - public void Constructor_AssignsBothEndpoints() - { - OutputPoint left = CreatePoint(0, 0); - OutputPoint right = CreatePoint(10, 0); - - HorizontalJoin join = new(left, right); - - Assert.Same(left, join.LeftToRight); - Assert.Same(right, join.RightToLeft); - } - - [Fact] - public void Endpoints_AreReassignable() - { - HorizontalJoin join = new(CreatePoint(0, 0), CreatePoint(10, 0)); - - OutputPoint newLeft = CreatePoint(1, 1); - OutputPoint newRight = CreatePoint(9, 1); - join.LeftToRight = newLeft; - join.RightToLeft = newRight; - - Assert.Same(newLeft, join.LeftToRight); - Assert.Same(newRight, join.RightToLeft); - } - - [Fact] - public void Endpoints_AcceptNull() - { - HorizontalJoin join = new(CreatePoint(0, 0), CreatePoint(10, 0)); - - join.LeftToRight = null; - join.RightToLeft = null; - - Assert.Null(join.LeftToRight); - Assert.Null(join.RightToLeft); - } -} diff --git a/tests/PolygonClipper.Tests/IntersectNodeComparerTests.cs b/tests/PolygonClipper.Tests/IntersectNodeComparerTests.cs deleted file mode 100644 index 6a5bf48..0000000 --- a/tests/PolygonClipper.Tests/IntersectNodeComparerTests.cs +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) Six Labors. -// Licensed under the Six Labors Split License. - -using IntersectNodeComparer = SixLabors.PolygonClipper.SelfIntersectionSweepLine.IntersectNodeComparer; - -namespace SixLabors.PolygonClipper.Tests; - -public class IntersectNodeComparerTests -{ - private static IntersectNode Node(double x, double y) - { - ActiveEdge dummy = new(); - return new IntersectNode(new Vertex(x, y), dummy, dummy); - } - - [Fact] - public void HigherY_SortsBeforeLowerY() - { - IntersectNodeComparer comparer = default; - - // Higher Y must come first, so the higher-Y argument is "less" than the lower-Y one. - Assert.True(comparer.Compare(Node(0, 10), Node(0, 1)) < 0); - Assert.True(comparer.Compare(Node(0, 1), Node(0, 10)) > 0); - } - - [Fact] - public void EqualY_OrdersByAscendingX() - { - IntersectNodeComparer comparer = default; - - Assert.True(comparer.Compare(Node(1, 5), Node(7, 5)) < 0); - Assert.True(comparer.Compare(Node(7, 5), Node(1, 5)) > 0); - } - - [Fact] - public void EqualPoints_AreEqual() - { - IntersectNodeComparer comparer = default; - - Assert.Equal(0, comparer.Compare(Node(3, 4), Node(3, 4))); - } - - [Fact] - public void Sort_ProducesTopToBottomLeftToRight() - { - IntersectNode a = Node(5, 1); - IntersectNode b = Node(2, 10); - IntersectNode c = Node(7, 10); - IntersectNode d = Node(0, 5); - - List list = [a, b, c, d]; - list.Sort(default(IntersectNodeComparer)); - - // Y descending, then X ascending within the same Y. - Assert.Equal(new Vertex(2, 10), list[0].Point); - Assert.Equal(new Vertex(7, 10), list[1].Point); - Assert.Equal(new Vertex(0, 5), list[2].Point); - Assert.Equal(new Vertex(5, 1), list[3].Point); - } -} diff --git a/tests/PolygonClipper.Tests/LocalMinimaTests.cs b/tests/PolygonClipper.Tests/LocalMinimaTests.cs deleted file mode 100644 index 6498c69..0000000 --- a/tests/PolygonClipper.Tests/LocalMinimaTests.cs +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright (c) Six Labors. -// Licensed under the Six Labors Split License. - -namespace SixLabors.PolygonClipper.Tests; - -public class LocalMinimaTests -{ - private static SweepVertex Vert(double x, double y) - => new(new Vertex(x, y), VertexFlags.None, prev: null); - - [Fact] - public void Constructor_StoresVertex() - { - SweepVertex v = Vert(1, 2); - - LocalMinima lm = new(v); - - Assert.Same(v, lm.Vertex); - } - - [Fact] - public void Equality_UsesReferenceIdentityOfVertex() - { - SweepVertex shared = Vert(1, 2); - SweepVertex twin = Vert(1, 2); - - LocalMinima a = new(shared); - LocalMinima b = new(shared); - LocalMinima c = new(twin); - - Assert.True(a == b); - Assert.False(a != b); - Assert.True(a.Equals(b)); - Assert.True(a.Equals((object)b)); - Assert.False(a == c); - Assert.True(a != c); - Assert.False(a.Equals(c)); - Assert.False(a.Equals("not a local minima")); - } - - [Fact] - public void GetHashCode_MatchesUnderlyingVertexHash() - { - SweepVertex v = Vert(7, 9); - LocalMinima lm = new(v); - - Assert.Equal(v.GetHashCode(), lm.GetHashCode()); - } - - [Fact] - public void Comparer_OrdersHigherYFirst() - { - // The sweep wants higher Y processed first, so the comparer - // returns a negative value when the second's Y is larger. - LocalMinima high = new(Vert(0, 10)); - LocalMinima mid = new(Vert(0, 5)); - LocalMinima low = new(Vert(0, 1)); - - LocalMinimaComparer comparer = new(); - - Assert.True(comparer.Compare(high, low) < 0); - Assert.True(comparer.Compare(low, high) > 0); - Assert.Equal(0, comparer.Compare(mid, mid)); - } - - [Fact] - public void Comparer_SortsCollectionDescendingByY() - { - LocalMinima a = new(Vert(0, 1)); - LocalMinima b = new(Vert(0, 10)); - LocalMinima c = new(Vert(0, 5)); - - List list = [a, b, c]; - list.Sort(new LocalMinimaComparer()); - - Assert.Equal(10, list[0].Vertex.Point.Y); - Assert.Equal(5, list[1].Vertex.Point.Y); - Assert.Equal(1, list[2].Vertex.Point.Y); - } -} diff --git a/tests/PolygonClipper.Tests/NormalizationTests.cs b/tests/PolygonClipper.Tests/NormalizationTests.cs index 8771251..84e57d9 100644 --- a/tests/PolygonClipper.Tests/NormalizationTests.cs +++ b/tests/PolygonClipper.Tests/NormalizationTests.cs @@ -26,7 +26,7 @@ public void SimpleRectangle_NoSelfIntersections_PreservesStructure() Polygon input = [outer]; // Act - Polygon result = PolygonClipper.Normalize(input); + Polygon result = PolygonClipper.Normalize(input, FillRule.Positive); // Assert Assert.Equal(1, result.Count); @@ -65,7 +65,7 @@ public void RectangleWithHole_NoSelfIntersections_PreservesStructure() Polygon input = [outer, inner]; // Act - Polygon result = PolygonClipper.Normalize(input); + Polygon result = PolygonClipper.Normalize(input, FillRule.EvenOdd); // Assert Assert.Equal(2, result.Count); @@ -95,7 +95,7 @@ public void ConcentricOctagons_NoSelfIntersections_PreservesStructure() Polygon input = [outer, inner]; // Act - Polygon result = PolygonClipper.Normalize(input); + Polygon result = PolygonClipper.Normalize(input, FillRule.EvenOdd); // Assert: Must have exactly 2 contours Assert.Equal(2, result.Count); @@ -116,7 +116,7 @@ public void ConcentricCircles_ManyVertices_PreservesStructure() Polygon input = [outer, inner]; // Act - Polygon result = PolygonClipper.Normalize(input); + Polygon result = PolygonClipper.Normalize(input, FillRule.EvenOdd); // Assert: Must have exactly 2 contours Assert.Equal(2, result.Count); @@ -145,7 +145,7 @@ public void ConcentricCircles_StrokedTextScale_PreservesStructure() Polygon input = [outer, inner]; // Act - Polygon result = PolygonClipper.Normalize(input); + Polygon result = PolygonClipper.Normalize(input, FillRule.EvenOdd); // Assert: Must have exactly 2 contours Assert.Equal(2, result.Count); @@ -770,7 +770,7 @@ public void Stroked_Text_O_Shape() // Assert: The input has 2 compound contours (each containing two loops connected by bridge segments). // When processed with positive fill rule, this produces 4 contours. // Only the contour and vertex counts are validated; vertex ordering may differ from Clipper2. - AssertMatchesClipperByCount(input); + AssertMatchesClipperByCount(input, FillRule.NonZero); } [Fact] @@ -1533,7 +1533,7 @@ public void Stroked_Text_9_Shape() // Assert: The "9" shape is more complex than the "O" shape. The input contours contain // self-intersections that, when resolved with positive fill rule, produce 4 contours. // Validate count parity with Clipper2 and exact geometry parity between both remover paths. - AssertMatchesClipperByCount(input); + AssertMatchesClipperByCount(input, FillRule.NonZero); } [Fact] @@ -1932,7 +1932,7 @@ public void Stroked_Dashed_Complex_Polygon() outer42, outer43, outer44, outer45, outer46]; // Act + Assert - AssertMatchesClipperByCount(input); + AssertMatchesClipperByCount(input, FillRule.NonZero); } /// @@ -1951,7 +1951,7 @@ public void ConcentricCircles_LargeVertexCount_PreservesStructure() Polygon input = [outer, inner]; // Act - Polygon result = PolygonClipper.Normalize(input); + Polygon result = PolygonClipper.Normalize(input, FillRule.EvenOdd); // Assert: Must have exactly 2 contours Assert.Equal(2, result.Count); @@ -1978,7 +1978,7 @@ public void MultipleNestedContours_PreservesHierarchy() Polygon input = [ring1, ring2, ring3, ring4]; // Act - Polygon result = PolygonClipper.Normalize(input); + Polygon result = PolygonClipper.Normalize(input, FillRule.EvenOdd); // Assert: Must have exactly 4 contours Assert.Equal(4, result.Count); @@ -2004,7 +2004,7 @@ public void TwoSeparatePolygons_RemainSeparate() Polygon input = [circle1, circle2]; // Act - Polygon result = PolygonClipper.Normalize(input); + Polygon result = PolygonClipper.Normalize(input, FillRule.Positive); // Assert: Must have exactly 2 separate external contours Assert.Equal(2, result.Count); @@ -2038,7 +2038,7 @@ public void ExternalWithMultipleHoles_PreservesStructure() Polygon input = [outer, hole1, hole2]; // Act - Polygon result = PolygonClipper.Normalize(input); + Polygon result = PolygonClipper.Normalize(input, FillRule.EvenOdd); // Assert: 1 external + 2 holes Assert.Equal(3, result.Count); @@ -2077,12 +2077,12 @@ public void TwoTouchingRectangles_MergeIntoSingleContour() Polygon input = [rectA, rectB]; // Act - Polygon result = PolygonClipper.Normalize(input); + Polygon result = PolygonClipper.Normalize(input, FillRule.Positive); // Assert: Should merge into a single rectangle (0,0)-(20,0)-(20,10)-(0,10) Assert.Equal(1, result.Count); - AssertMatchesClipperByCount(input); + AssertMatchesClipperByCount(input, FillRule.Positive); } /// @@ -2117,16 +2117,16 @@ public void RectangleAndParallelogramTouchingAtHorizontalEdge_MergeCorrectly() Polygon input = [rect, para]; // Act + Assert - AssertMatchesClipperByCount(input); + AssertMatchesClipperByCount(input, FillRule.Positive); } /// - /// Tests that a self-intersecting bowtie stays as one filled region under positive fill. + /// Checks the positive region of a bowtie when Positive filling is explicitly selected. /// [Fact] - public void FigureEight_WithSelfIntersection_RemainsSingleContour() + public void Bowtie_PositiveFill_SelectsOnlyPositiveLobe() { - // Arrange: Bowtie/hourglass that crosses itself at (5,0) so the winding stays >0 everywhere. + // The lobes have opposite winding. Positive filling retains one lobe. Contour figure8 = [ new Vertex(0, 5), // Top-left @@ -2139,11 +2139,14 @@ public void FigureEight_WithSelfIntersection_RemainsSingleContour() Polygon input = [figure8]; // Act - Polygon result = PolygonClipper.Normalize(input); + Polygon result = PolygonClipper.Normalize(input, FillRule.Positive); - // Assert: Positive fill treats the bowtie as a single filled region (same as Clipper). + // Positive selects the right-hand triangle; the other lobe has negative winding. Assert.Equal(1, result.Count); - AssertMatchesClipperByCount(input); + Assert.Equal(new Vertex(5, -5), result.GetBoundingBox().Min); + Assert.Equal(new Vertex(10, 5), result.GetBoundingBox().Max); + Assert.Equal(25D, Clipper.Area(ProjectContour(result[0]))); + AssertMatchesClipperByCount(input, FillRule.Positive); } /// @@ -2192,14 +2195,14 @@ public void MultipleIntersectionsOnSingleSegment_SplitsAll() Polygon input = [baseRect, post1, post2, post3]; // Act + Assert - AssertMatchesClipperByCount(input); + AssertMatchesClipperByCount(input, FillRule.Positive); } /// - /// Tests partially overlapping collinear edges to validate overlap handling. + /// Checks the exact union rectangle independently of retained collinear vertex counts. /// [Fact] - public void PartialOverlap_CollinearEdges_MatchesClipper() + public void PartialOverlap_CollinearEdges_PreservesUnionRectangle() { // Arrange: Two rectangles with a partial overlap on the shared horizontal edges. Contour rectA = @@ -2222,8 +2225,29 @@ public void PartialOverlap_CollinearEdges_MatchesClipper() Polygon input = [rectA, rectB]; - // Act + Assert - AssertMatchesClipperByCount(input); + Polygon result = PolygonClipper.Normalize(input, FillRule.Positive); + Contour boundary = Assert.Single(result); + PathD reference = Assert.Single(NormalizeWithClipperD(input, FillRule.Positive, 6)); + + // [0,12] and [6,18] overlap over [6,12]. Their union is exactly + // [0,18] by [0,4], with area 72 and perimeter 44. Collinear nodes do not + // change that rectangle, so Clipper2's node count is not an expectation. + Assert.Equal(new Vertex(0, 0), boundary.GetBoundingBox().Min); + Assert.Equal(new Vertex(18, 4), boundary.GetBoundingBox().Max); + Assert.Equal(72D, Clipper.Area(ProjectContour(boundary))); + Assert.Equal(72D, Clipper.Area(reference)); + double perimeter = 0; + for (int i = 0; i < boundary.Count; i++) + { + Vertex first = boundary[i]; + Vertex second = boundary[(i + 1) % boundary.Count]; + bool horizontal = first.Y == second.Y && (first.Y == 0 || first.Y == 4); + bool vertical = first.X == second.X && (first.X == 0 || first.X == 18); + Assert.True(horizontal || vertical); + perimeter += Math.Abs(first.X - second.X) + Math.Abs(first.Y - second.Y); + } + + Assert.Equal(44D, perimeter); } /// @@ -2252,7 +2276,7 @@ public void DisjointPolygonsWithOverlappingBounds_RemainSeparate() Polygon input = [triA, triB]; // Act + Assert - AssertMatchesClipperByCount(input); + AssertMatchesClipperByCount(input, FillRule.Positive); } /// @@ -2272,7 +2296,7 @@ public void Issue1051_Union_Add1_MatchesMartinezUnion() new Vertex(-2, 0) ]; - Polygon actual = PolygonClipper.Normalize([mainActual, add1]); + Polygon actual = PolygonClipper.Normalize([mainActual, add1], FillRule.Positive); Polygon expected = PolygonClipper.Union( [CreateIssue1051Main()], @@ -2282,9 +2306,13 @@ public void Issue1051_Union_Add1_MatchesMartinezUnion() new Vertex(0, 1), new Vertex(-2, 1), new Vertex(-2, 0) - ]]); + ]], + FillRule.EvenOdd); AssertContourVertexSignature(expected, actual); + Assert.Equal(new Vertex(-2, 0), actual.GetBoundingBox().Min); + Assert.Equal(new Vertex(2, 2), actual.GetBoundingBox().Max); + Assert.Equal(6D, Clipper.Area(ProjectContour(Assert.Single(actual)))); } /// @@ -2305,7 +2333,7 @@ public void Issue1051_Union_Add2_MatchesMartinezUnion() new Vertex(-2, 1) ]; - Polygon actual = PolygonClipper.Normalize([mainActual, add2]); + Polygon actual = PolygonClipper.Normalize([mainActual, add2], FillRule.Positive); Polygon expected = PolygonClipper.Union( [CreateIssue1051Main()], @@ -2315,38 +2343,17 @@ public void Issue1051_Union_Add2_MatchesMartinezUnion() new Vertex(0, 1), new Vertex(-2, 1), new Vertex(-2, 1) - ]]); - - // The square has area four. The added line is traversed once in each - // direction. It can remain attached to the square or form its own walk. - // Both representations must retain these seven directed boundary edges. - Segment[] boundary = - [ - new(new Vertex(0, 0), new Vertex(2, 0)), - new(new Vertex(2, 0), new Vertex(2, 2)), - new(new Vertex(2, 2), new Vertex(0, 2)), - new(new Vertex(0, 2), new Vertex(0, 1)), - new(new Vertex(0, 1), new Vertex(0, 0)), - new(new Vertex(0, 1), new Vertex(-2, 1)), - new(new Vertex(-2, 1), new Vertex(0, 1)) - ]; - foreach (Polygon polygon in new[] { actual, expected }) - { - List edges = []; - foreach (Contour contour in polygon) - { - for (int i = 0; i < GetImplicitVertexCount(contour); i++) - { - edges.Add(contour.GetSegment(i)); - } - } + ]], + FillRule.EvenOdd); - Assert.Equal(boundary.Length, edges.Count); - foreach (Segment edge in boundary) - { - Assert.Contains(edge, edges); - } - } + AssertContourVertexSignature(expected, actual); + + // The degenerate rectangle contributes a segment in each direction. + // It has no filled area and cannot extend the original 2-by-2 square. + Contour boundary = Assert.Single(actual); + Assert.Equal(new Vertex(0, 0), boundary.GetBoundingBox().Min); + Assert.Equal(new Vertex(2, 2), boundary.GetBoundingBox().Max); + Assert.Equal(4D, Clipper.Area(ProjectContour(boundary))); } private static Contour CreateIssue1051Main() @@ -2429,10 +2436,15 @@ private static int GetImplicitVertexCount(PathD path) return first.x == last.x && first.y == last.y ? count - 1 : count; } - private static void AssertMatchesClipperByCount(Polygon input) + /// + /// Compares cleanup with Clipper2 using the same raw contours and fill rule. + /// + /// The source contours. + /// The source fill rule. + private static void AssertMatchesClipperByCount(Polygon input, FillRule fillRule) { - Polygon result = PolygonClipper.Normalize(input); - PathsD clipperResult = NormalizeWithClipperD(input); + Polygon result = PolygonClipper.Normalize(input, fillRule); + PathsD clipperResult = NormalizeWithClipperD(input, fillRule, 6); List expected = SortPathsByLowestPoint(clipperResult); List actual = SortContoursByLowestPoint(result); @@ -2507,7 +2519,14 @@ private static PointD GetLowestPoint(Contour contour) return new PointD(lowest.X, lowest.Y); } - private static PathsD NormalizeWithClipperD(Polygon polygon, int precision = 6) + /// + /// Resolves the source contours with Clipper2 at the requested decimal precision. + /// + /// The unmodified source contours. + /// The source fill rule. + /// The number of decimal places retained by Clipper2. + /// The resolved Clipper2 contours. + private static PathsD NormalizeWithClipperD(Polygon polygon, FillRule fillRule, int precision) { PathsD subject = new(polygon.Count); for (int i = 0; i < polygon.Count; i++) @@ -2523,12 +2542,6 @@ private static PathsD NormalizeWithClipperD(Polygon polygon, int precision = 6) subject.Add(path); } - GetLowestPathInfo(subject, out int lowestPathIdx, out bool isNegArea); - if (lowestPathIdx >= 0 && isNegArea) - { - ReversePaths(subject); - } - ClipperD clipper = new(precision) { PreserveCollinear = true, @@ -2537,53 +2550,16 @@ private static PathsD NormalizeWithClipperD(Polygon polygon, int precision = 6) clipper.AddSubject(subject); PathsD solution = []; - clipper.Execute(ClipType.Union, Clipper2Lib.FillRule.Positive, solution); - return solution; - } - - private static void ReversePaths(PathsD paths) - { - for (int i = 0; i < paths.Count; i++) - { - paths[i].Reverse(); - } - } - - private static void GetLowestPathInfo(PathsD paths, out int lowestPathIdx, out bool isNegArea) - { - lowestPathIdx = -1; - isNegArea = false; - - if (paths.Count == 0) - { - return; - } - - PointD lowestPoint = default; - bool hasPoint = false; - - for (int i = 0; i < paths.Count; i++) + Clipper2Lib.FillRule clipperRule = fillRule switch { - PathD path = paths[i]; - if (path.Count == 0) - { - continue; - } - - PointD candidate = GetLowestPoint(path); - if (!hasPoint || candidate.y > lowestPoint.y || - (candidate.y == lowestPoint.y && candidate.x < lowestPoint.x)) - { - lowestPoint = candidate; - lowestPathIdx = i; - hasPoint = true; - } - } + FillRule.EvenOdd => Clipper2Lib.FillRule.EvenOdd, + FillRule.NonZero => Clipper2Lib.FillRule.NonZero, + FillRule.Positive => Clipper2Lib.FillRule.Positive, + _ => Clipper2Lib.FillRule.Negative + }; - if (lowestPathIdx >= 0) - { - isNegArea = Clipper.Area(paths[lowestPathIdx]) < 0; - } + clipper.Execute(ClipType.Union, clipperRule, solution); + return solution; } private static PointD GetLowestPoint(PathD path) diff --git a/tests/PolygonClipper.Tests/PolygonClipperContourClosureTests.cs b/tests/PolygonClipper.Tests/PolygonClipperContourClosureTests.cs index db9d985..e06b959 100644 --- a/tests/PolygonClipper.Tests/PolygonClipperContourClosureTests.cs +++ b/tests/PolygonClipper.Tests/PolygonClipperContourClosureTests.cs @@ -5,6 +5,37 @@ namespace SixLabors.PolygonClipper.Tests; public class PolygonClipperContourClosureTests { + /// + /// Checks source closure independently of duplicate endpoint representation for all fill rules. + /// + /// The fill rule for both operands. + [Theory] + [InlineData(FillRule.EvenOdd)] + [InlineData(FillRule.NonZero)] + [InlineData(FillRule.Positive)] + [InlineData(FillRule.Negative)] + public void FilledOperations_SourceClosureFlags_DoNotChangeOutput(FillRule rule) + { + Polygon subject = [CreateRectangleContour(0, 0, 10, 10, false)]; + Polygon clip = [CreateRectangleContour(5, 5, 15, 15, false)]; + Polygon openSubject = subject.DeepClone(); + Polygon openClip = clip.DeepClone(); + openSubject[0].IsClosed = false; + openClip[0].IsClosed = false; + + AssertEquivalent(PolygonClipper.Intersection(subject, clip, rule), PolygonClipper.Intersection(openSubject, openClip, rule)); + AssertEquivalent(PolygonClipper.Union(subject, clip, rule), PolygonClipper.Union(openSubject, openClip, rule)); + AssertEquivalent(PolygonClipper.Difference(subject, clip, rule), PolygonClipper.Difference(openSubject, openClip, rule)); + AssertEquivalent(PolygonClipper.Xor(subject, clip, rule), PolygonClipper.Xor(openSubject, openClip, rule)); + AssertEquivalent(PolygonClipper.Union(subject, rule), PolygonClipper.Union(openSubject, rule)); + AssertEquivalent(PolygonClipper.Normalize(subject, rule), PolygonClipper.Normalize(openSubject, rule)); + + Assert.False(openSubject[0].IsClosed); + Assert.False(openClip[0].IsClosed); + Assert.Equal(subject[0], openSubject[0]); + Assert.Equal(clip[0], openClip[0]); + } + [Fact] public void BooleanOperations_OpenAndClosedContours_ProduceSameOutput() { @@ -14,17 +45,17 @@ public void BooleanOperations_OpenAndClosedContours_ProduceSameOutput() Polygon closedClip = [CreateRectangleContour(5, 5, 15, 15, true)]; AssertEquivalent( - PolygonClipper.Intersection(openSubject, openClip), - PolygonClipper.Intersection(closedSubject, closedClip)); + PolygonClipper.Intersection(openSubject, openClip, FillRule.EvenOdd), + PolygonClipper.Intersection(closedSubject, closedClip, FillRule.EvenOdd)); AssertEquivalent( - PolygonClipper.Union(openSubject, openClip), - PolygonClipper.Union(closedSubject, closedClip)); + PolygonClipper.Union(openSubject, openClip, FillRule.EvenOdd), + PolygonClipper.Union(closedSubject, closedClip, FillRule.EvenOdd)); AssertEquivalent( - PolygonClipper.Difference(openSubject, openClip), - PolygonClipper.Difference(closedSubject, closedClip)); + PolygonClipper.Difference(openSubject, openClip, FillRule.EvenOdd), + PolygonClipper.Difference(closedSubject, closedClip, FillRule.EvenOdd)); AssertEquivalent( - PolygonClipper.Xor(openSubject, openClip), - PolygonClipper.Xor(closedSubject, closedClip)); + PolygonClipper.Xor(openSubject, openClip, FillRule.EvenOdd), + PolygonClipper.Xor(closedSubject, closedClip, FillRule.EvenOdd)); } private static Contour CreateRectangleContour( @@ -65,6 +96,12 @@ private static void AssertEquivalent(Polygon left, Polygon right) Assert.Equal(leftContour[j], rightContour[j]); } } + + foreach (Contour contour in left.Concat(right)) + { + Assert.True(contour.IsClosed); + Assert.NotEqual(contour[0], contour[^1]); + } } private static List> BuildNormalizedContours(Polygon polygon) diff --git a/tests/PolygonClipper.Tests/PolygonStrokerTests.cs b/tests/PolygonClipper.Tests/PolygonStrokerTests.cs index c4d8ce3..8dedf69 100644 --- a/tests/PolygonClipper.Tests/PolygonStrokerTests.cs +++ b/tests/PolygonClipper.Tests/PolygonStrokerTests.cs @@ -86,6 +86,8 @@ public void Stroke_OpenPolylineWithThreeVertices_IsNotForcedClosed() new Vertex(0, 0) ]]; + open[0].IsClosed = false; + Polygon openResult = PolygonStroker.Stroke(open, width, options); Polygon closedResult = PolygonStroker.Stroke(closed, width, options); @@ -99,6 +101,300 @@ public void Stroke_OpenPolylineWithThreeVertices_IsNotForcedClosed() $"Open and closed path strokes should differ. openArea={openArea:R}, closedArea={closedArea:R}."); } + /// + /// Checks that source closure selects the closing segment without changing output closure. + /// + /// Whether to resolve the generated outlines. + [Theory] + [InlineData(false)] + [InlineData(true)] + public void Stroke_ThreePointSource_ClosureSelectsFinalSegment(bool normalizeOutput) + { + Contour source = [new Vertex(0, 0), new Vertex(10, 0), new Vertex(10, 10)]; + source.IsClosed = false; + Vertex[] originalVertices = [.. source]; + StrokeOptions options = new() { LineJoin = LineJoin.Miter, NormalizeOutput = normalizeOutput }; + + Polygon open = PolygonStroker.Stroke([source], 2, options); + source.IsClosed = true; + Polygon closed = PolygonStroker.Stroke([source], 2, options); + + // The diagonal belongs only to the closed source's final-to-first segment. + Assert.Equal(Containment.Outside, ClassifyPoint(open, new Vertex(5, 5), 1E-10)); + Assert.Equal(Containment.Inside, ClassifyPoint(closed, new Vertex(5, 5), 1E-10)); + AssertPolygonIsValid(open); + AssertPolygonIsValid(closed); + Assert.Equal(3, source.Count); + Assert.Equal(originalVertices, source); + } + + /// + /// Checks that nearby or coincident open endpoints retain caps at different widths. + /// + /// The final source vertex's distance from the start. + /// The stroke width. + [Theory] + [InlineData(0D, 1D)] + [InlineData(0D, 4D)] + [InlineData(0.25D, 1D)] + [InlineData(0.25D, 4D)] + public void Stroke_OpenEndpoints_DoNotSelectClosure(double endY, double width) + { + Contour source = + [ + new Vertex(0, 0), + new Vertex(10, 0), + new Vertex(10, 10), + new Vertex(0, 10), + new Vertex(0, endY) + ]; + source.IsClosed = false; + StrokeOptions options = new() { LineJoin = LineJoin.Miter, LineCap = LineCap.Butt, NormalizeOutput = true }; + + Polygon open = PolygonStroker.Stroke([source], width, options); + Assert.False(source.IsClosed); + Assert.Equal(5, source.Count); + source.IsClosed = true; + Polygon closed = PolygonStroker.Stroke([source], width, options); + + // A miter joins the closed bottom-left corner. The two butt caps leave + // this point outside the open stroke, even when the endpoints coincide. + Vertex corner = new(-width / 4, -width / 4); + Assert.Equal(Containment.Outside, ClassifyPoint(open, corner, 1E-10)); + Assert.Equal(Containment.Inside, ClassifyPoint(closed, corner, 1E-10)); + AssertPolygonIsValid(open); + AssertPolygonIsValid(closed); + } + + /// + /// Checks that repeated closing vertices do not change a closed contour's stroke. + /// + /// Whether to resolve the generated outlines. + [Theory] + [InlineData(false)] + [InlineData(true)] + public void Stroke_ClosedDuplicateEndpoint_DoesNotChangeGeometry(bool normalizeOutput) + { + Contour source = [new Vertex(0, 0), new Vertex(10, 0), new Vertex(10, 10), new Vertex(0, 10)]; + StrokeOptions options = new() { LineJoin = LineJoin.Miter, NormalizeOutput = normalizeOutput }; + Polygon implicitClosure = PolygonStroker.Stroke([source], 2, options); + source.Add(source[0]); + + Polygon explicitClosure = PolygonStroker.Stroke([source], 2, options); + + AssertSameStroke(implicitClosure, explicitClosure); + AssertPolygonIsValid(implicitClosure); + AssertPolygonIsValid(explicitClosure); + Assert.Equal(5, source.Count); + } + + /// + /// Checks combined cleanup where an open segment crosses a closed square's stroke. + /// + [Fact] + public void Stroke_MixedClosure_ResolvesCombinedArea() + { + Contour square = [new Vertex(0, 0), new Vertex(10, 0), new Vertex(10, 10), new Vertex(0, 10)]; + Contour segment = [new Vertex(5, -5), new Vertex(5, 15)]; + segment.IsClosed = false; + StrokeOptions options = new() { LineJoin = LineJoin.Miter, NormalizeOutput = true }; + + Polygon result = PolygonStroker.Stroke([square, segment], 2, options); + + // The square band has area 12*12 - 8*8 = 80. The segment adds 20*2 = 40, + // with two 2*2 overlaps. Their union therefore has area 112. + double area = 0; + foreach (Contour contour in result) + { + area += ComputeSignedArea(contour); + } + + Assert.Equal(112D, area, 10); + Assert.Equal(Containment.Inside, ClassifyPoint(result, new Vertex(5, 5), 1E-10)); + Assert.Equal(Containment.Outside, ClassifyPoint(result, new Vertex(2, 5), 1E-10)); + Assert.True(square.IsClosed); + Assert.False(segment.IsClosed); + AssertPolygonIsValid(result); + } + + /// + /// Checks direct reuse of Boolean output as a closed stroke source and filled-area operand. + /// + [Fact] + public void Stroke_BooleanOutput_RequiresNoClosureConversion() + { + Contour square = [new Vertex(0, 0), new Vertex(10, 0), new Vertex(10, 10), new Vertex(0, 10)]; + Polygon filled = PolygonClipper.Union([square], FillRule.NonZero); + + Polygon stroke = PolygonStroker.Stroke(filled, 2, new StrokeOptions { LineJoin = LineJoin.Miter }); + Polygon resolved = PolygonClipper.Union(stroke, FillRule.Positive); + + AssertPolygonIsValid(filled); + AssertPolygonIsValid(stroke); + AssertPolygonIsValid(resolved); + Assert.Equal(Containment.Inside, ClassifyPoint(resolved, new Vertex(-0.5, 5), 1E-10)); + Assert.Equal(Containment.Outside, ClassifyPoint(resolved, new Vertex(5, 5), 1E-10)); + } + + /// + /// Checks that default options and manually configured instances produce identical geometry. + /// + [Fact] + public void Stroke_DefaultExplicitAndInstanceOptions_Agree() + { + Polygon source = [[new Vertex(0, 0), new Vertex(10, 0), new Vertex(10, 10)]]; + StrokeOptions options = new(); + PolygonStroker stroker = new(options) { Width = 2 }; + + Polygon defaults = PolygonStroker.Stroke(source, 2); + Polygon explicitOptions = PolygonStroker.Stroke(source, 2, options); + Polygon instance = stroker.Stroke(source); + + AssertSameStroke(defaults, explicitOptions); + AssertSameStroke(defaults, instance); + } + + /// + /// Checks that optional cleanup preserves the NonZero area of raw stroke outlines. + /// + /// The signed stroke width. + /// Whether the source includes its final-to-first segment. + /// The analytically expected stroke area. + [Theory] + [InlineData(2D, true, 80D)] + [InlineData(-2D, true, 80D)] + [InlineData(2D, false, 60D)] + [InlineData(-2D, false, 60D)] + public void Stroke_OutputCleanup_PreservesNonZeroArea(double width, bool isClosed, double expectedArea) + { + Contour source = [new Vertex(0, 0), new Vertex(10, 0), new Vertex(10, 10), new Vertex(0, 10)]; + source.IsClosed = isClosed; + StrokeOptions options = new() { LineJoin = LineJoin.Miter }; + Polygon raw = PolygonStroker.Stroke([source], width, options); + options.NormalizeOutput = true; + + Polygon cleaned = PolygonStroker.Stroke([source], width, options); + + double area = 0; + foreach (Contour contour in cleaned) + { + area += ComputeSignedArea(contour); + } + + // Closed: 12*12 - 8*8 = 80. Open: three 10-unit segments at width 2 give 60. + // Reversing the width changes outline direction, not the intended filled area. + Assert.Equal(expectedArea, area, 10); + for (int y = -2; y <= 12; y++) + { + for (int x = -2; x <= 12; x++) + { + Vertex point = new(x + 0.25D, y + 0.375D); + Assert.Equal(ClassifyPointNonZero(raw, point, 1E-10), ClassifyPoint(cleaned, point, 1E-10)); + } + } + } + + /// + /// Checks the public boundary for an explicitly null options argument. + /// + [Fact] + public void Stroke_NullOptions_ThrowsArgumentNullException() + { + Assert.Throws("options", () => PolygonStroker.Stroke([], 2, null!)); + } + + /// + /// Checks the existing two-vertex point-cap result for both source closure states. + /// + /// The source closure state. + /// The point-cap shape. + [Theory] + [InlineData(false, LineCap.Butt)] + [InlineData(true, LineCap.Butt)] + [InlineData(false, LineCap.Square)] + [InlineData(true, LineCap.Square)] + [InlineData(false, LineCap.Round)] + [InlineData(true, LineCap.Round)] + public void Stroke_TwoEqualVertices_PreservesPointCap(bool isClosed, LineCap cap) + { + Contour source = [new Vertex(5, 5), new Vertex(5, 5)]; + source.IsClosed = isClosed; + + Polygon result = PolygonStroker.Stroke([source], 4, new StrokeOptions { LineCap = cap }); + + Contour footprint = Assert.Single(result); + Assert.Equal(isClosed, source.IsClosed); + Assert.Equal(2, source.Count); + AssertPolygonIsValid(result); + if (cap == LineCap.Round) + { + foreach (Vertex vertex in footprint) + { + Assert.Equal(4D, Vertex.DistanceSquared(new Vertex(5, 5), vertex), 10); + } + } + else + { + Assert.Equal(4, footprint.Count); + Assert.Equal(16D, Math.Abs(ComputeSignedArea(footprint))); + Assert.Equal(new Vertex(3, 3), footprint.GetBoundingBox().Min); + Assert.Equal(new Vertex(7, 7), footprint.GetBoundingBox().Max); + } + } + + /// + /// Checks the existing capped-segment fallback for two distinct vertices. + /// + /// The source closure state. + [Theory] + [InlineData(false)] + [InlineData(true)] + public void Stroke_TwoDistinctVertices_PreservesSegmentCaps(bool isClosed) + { + Contour source = [new Vertex(0, 0), new Vertex(10, 0)]; + source.IsClosed = isClosed; + + Polygon result = PolygonStroker.Stroke([source], 2, new StrokeOptions { LineCap = LineCap.Square }); + + Assert.Single(result); + Assert.Equal(new Vertex(-1, -1), result.GetBoundingBox().Min); + Assert.Equal(new Vertex(11, 1), result.GetBoundingBox().Max); + Assert.Equal(isClosed, source.IsClosed); + AssertPolygonIsValid(result); + } + + /// + /// Checks that empty and single-vertex source contours produce no stroke. + /// + /// The source closure state. + [Theory] + [InlineData(false)] + [InlineData(true)] + public void Stroke_FewerThanTwoVertices_ReturnsEmpty(bool isClosed) + { + Contour source = new() { IsClosed = isClosed }; + Assert.Empty(PolygonStroker.Stroke([source], 2)); + + source.Add(new Vertex(5, 5)); + Assert.Empty(PolygonStroker.Stroke([source], 2)); + Assert.Equal(isClosed, source.IsClosed); + } + + /// + /// Compares all stored vertices and closure states of two stroke results. + /// + /// The expected stroke contours. + /// The actual stroke contours. + private static void AssertSameStroke(Polygon expected, Polygon actual) + { + Assert.Equal(expected.Count, actual.Count); + for (int i = 0; i < expected.Count; i++) + { + Assert.Equal(expected[i].IsClosed, actual[i].IsClosed); + Assert.Equal(expected[i], actual[i]); + } + } + [Fact] public void ProcessPolygonAndClip_FoldBackOpenPath_ProducesValidStroke() { @@ -480,6 +776,8 @@ private static void AssertPolygonIsValid(Polygon polygon) { Contour contour = polygon[contourIndex]; Assert.True(contour.Count >= 3, $"Contour {contourIndex} must have at least 3 vertices."); + Assert.True(contour.IsClosed); + Assert.NotEqual(contour[0], contour[^1]); int edgeCount = contour.Count; if (edgeCount > 1 && contour[0] == contour[^1]) @@ -569,8 +867,9 @@ private static void AssertStrokeCoversInputCenterline(Polygon input, Polygon str continue; } - bool isClosed = contour.Count > 1 && contour[0] == contour[^1]; - int vertexCount = isClosed ? contour.Count - 1 : contour.Count; + bool isClosed = contour.IsClosed; + bool repeatedEndpoint = contour[0] == contour[^1]; + int vertexCount = isClosed && repeatedEndpoint ? contour.Count - 1 : contour.Count; int segmentCount = isClosed ? vertexCount : vertexCount - 1; for (int segmentIndex = 0; segmentIndex < segmentCount; segmentIndex++) @@ -887,12 +1186,10 @@ private static void AssertImplicitSeamsAreClosed(Polygon input, Polygon output, { Box2 bounds = output.GetBoundingBox(); double epsilon = Math.Max(bounds.Max.X - bounds.Min.X, bounds.Max.Y - bounds.Min.Y) * 1E-12D; - double closeThreshold = Math.Max(strokeWidth * 2D, 1E-3D); - for (int contourIndex = 0; contourIndex < input.Count; contourIndex++) { Contour contour = input[contourIndex]; - if (contour.Count < 3 || contour[0] == contour[^1]) + if (!contour.IsClosed || contour.Count < 3 || contour[0] == contour[^1]) { continue; } @@ -901,11 +1198,6 @@ private static void AssertImplicitSeamsAreClosed(Polygon input, Polygon output, Vertex last = contour[^1]; double dx = first.X - last.X; double dy = first.Y - last.Y; - if ((dx * dx) + (dy * dy) > closeThreshold * closeThreshold) - { - continue; - } - double seamLength = Math.Sqrt((dx * dx) + (dy * dy)); if (seamLength <= 1E-12D) { diff --git a/tests/PolygonClipper.Tests/PolygonTests.cs b/tests/PolygonClipper.Tests/PolygonTests.cs index 9ae96de..67b8e41 100644 --- a/tests/PolygonClipper.Tests/PolygonTests.cs +++ b/tests/PolygonClipper.Tests/PolygonTests.cs @@ -32,7 +32,7 @@ public void Intersection_ReorderedComponents_KeepValidHoleIndices() Polygon subject = [CreateSquare(0, 0, 100), CreateSquare(40, 40, 20), CreateSquare(20, -20, 5)]; Polygon clip = [CreateSquare(-30, -30, 160)]; - Polygon result = PolygonClipper.Intersection(subject, clip); + Polygon result = PolygonClipper.Intersection(subject, clip, FillRule.EvenOdd); Assert.Equal(3, result.Count); Contour outer = Assert.Single(result, contour => contour.HoleCount == 1); diff --git a/tests/PolygonClipper.Tests/PolygonUtilitiesTests.cs b/tests/PolygonClipper.Tests/PolygonUtilitiesTests.cs index 7f5694d..932cdef 100644 --- a/tests/PolygonClipper.Tests/PolygonUtilitiesTests.cs +++ b/tests/PolygonClipper.Tests/PolygonUtilitiesTests.cs @@ -5,6 +5,37 @@ namespace SixLabors.PolygonClipper.Tests; public class PolygonUtilitiesTests { + /// + /// Checks source incidence when rounded coordinate differences obscure the orientation. + /// + [Fact] + public void SignedArea_NearbySourceCorner_RetainsPositiveSign() + { + Vertex first = new(6.559375, 5.3171875); + Vertex second = new(-0.565625, 11.0828125); + Vertex corner = new(3.846028904999335, 7.51285572161238); + + // Exact binary-rational arithmetic gives a positive determinant of about 3.0769E-15. + Assert.True(PolygonUtilities.SignedArea(first, second, corner) > 0); + Assert.True(PolygonUtilities.SignedArea(second, first, corner) < 0); + } + + /// + /// Checks an interior crossing whose ordinary quotient rounds to an endpoint. + /// + [Fact] + public void FindIntersection_RoundedEndpointParameter_RetainsInteriorCrossing() + { + Segment first = new(new Vertex(3.846028904999335, 7.51285572161238), new Vertex(13.846028904999335, 7.51285572161238)); + Segment second = new(new Vertex(6.559375, 5.3171875), new Vertex(-0.565625, 11.0828125)); + + int count = PolygonUtilities.FindIntersection(first, second, out Vertex intersection, out _); + + // The exact intersection rounds one X step above the source corner. + Assert.Equal(1, count); + Assert.Equal(new Vertex(3.8460289049993355, 7.51285572161238), intersection); + } + /// /// Checks a determinant whose rounded products are equal but whose exact difference is one. /// diff --git a/tests/PolygonClipper.Tests/TestPolygonUtilities.cs b/tests/PolygonClipper.Tests/TestPolygonUtilities.cs index 3a394e6..eef1d33 100644 --- a/tests/PolygonClipper.Tests/TestPolygonUtilities.cs +++ b/tests/PolygonClipper.Tests/TestPolygonUtilities.cs @@ -20,6 +20,11 @@ public static (Polygon Subject, Polygon Clipping) BuildPolygon(FeatureCollection return (subject, clipping); } + /// + /// Converts GeoJSON coordinates and preserves exterior and hole indices. + /// + /// The Polygon or MultiPolygon geometry. + /// The contours with their GeoJSON hierarchy. public static Polygon ConvertToPolygon(IGeometryObject geometry) { if (geometry is GeoPolygon geoJsonPolygon) @@ -34,6 +39,14 @@ public static Polygon ConvertToPolygon(IGeometryObject geometry) contour.Add(new Vertex(xy.Longitude, xy.Latitude)); } + if (polygon.Count > 0) + { + // Later rings in this GeoJSON Polygon belong to its first ring. + contour.ParentIndex = 0; + contour.Depth = 1; + polygon[0].AddHoleIndex(polygon.Count); + } + polygon.Add(contour); if (!ring.IsClosed()) @@ -50,6 +63,7 @@ public static Polygon ConvertToPolygon(IGeometryObject geometry) Polygon polygon = []; foreach (GeoPolygon geoPolygon in geoJsonMultiPolygon.Coordinates) { + int exteriorIndex = polygon.Count; foreach (LineString ring in geoPolygon.Coordinates) { Contour contour = []; @@ -58,6 +72,14 @@ public static Polygon ConvertToPolygon(IGeometryObject geometry) contour.Add(new Vertex(xy.Longitude, xy.Latitude)); } + if (polygon.Count > exteriorIndex) + { + // Each component has its own exterior; keep global contour indices. + contour.ParentIndex = exteriorIndex; + contour.Depth = 1; + polygon[exteriorIndex].AddHoleIndex(polygon.Count); + } + polygon.Add(contour); if (!ring.IsClosed()) diff --git a/tests/PolygonClipper.Tests/TestPolygonUtilitiesTests.cs b/tests/PolygonClipper.Tests/TestPolygonUtilitiesTests.cs index 7e6f7d0..709232c 100644 --- a/tests/PolygonClipper.Tests/TestPolygonUtilitiesTests.cs +++ b/tests/PolygonClipper.Tests/TestPolygonUtilitiesTests.cs @@ -35,11 +35,11 @@ public void ConvertToPolygon_ValidGeometry_ReturnsPolygon() [Fact] public void PolygonClipper_Union_Profile_Test() { - Polygon solution = PolygonClipper.Union(Polygons.Subject, Polygons.Clipping); + Polygon solution = PolygonClipper.Union(Polygons.Subject, Polygons.Clipping, FillRule.EvenOdd); Assert.NotNull(solution); Assert.Equal(2, solution.Count); - Assert.Equal(122, solution[0].Count); - Assert.Equal(9, solution[1].Count); + Assert.Equal(121, solution[0].Count); + Assert.Equal(8, solution[1].Count); } } diff --git a/tests/TestData/Generic/daef_polygonwithholes_holed.geojson b/tests/TestData/Generic/daef_polygonwithholes_holed.geojson index b7c77a3..3e29ba5 100644 --- a/tests/TestData/Generic/daef_polygonwithholes_holed.geojson +++ b/tests/TestData/Generic/daef_polygonwithholes_holed.geojson @@ -53,13 +53,6 @@ { "geometry": { "coordinates": [ - [ - [ - [0, 0], - [0, 300], - [0, 0] - ] - ], [ [ [50, 50], diff --git a/tests/TestData/Generic/fatal3.geojson b/tests/TestData/Generic/fatal3.geojson index 5f4410c..7464b95 100644 --- a/tests/TestData/Generic/fatal3.geojson +++ b/tests/TestData/Generic/fatal3.geojson @@ -47,6 +47,7 @@ "coordinates": [ [ [ + [180.60987101280907, 22.943242898435667], [180.60987101280907, 22.943242898435663], [198.56943964860557, 22.943242898435663], [253.09375, 40.984375], @@ -54,7 +55,7 @@ [280.6098710128091, 60.657800699899646], [280.6098710128091, 62.94324289843566], [180.60987101280907, 62.94324289843566], - [180.60987101280907, 22.943242898435663] + [180.60987101280907, 22.943242898435667] ] ] ], @@ -79,6 +80,8 @@ [73.5625, 36.765625], [111.53125, 6.765625], [141.0625, 36.765625], + [180.60987101280907, 22.943242898435667], + [180.60987101280907, 22.943242898435663], [180.60987101280907, 22.943242898435663], [189.34375, 19.890625], [198.56943964860557, 22.943242898435663], diff --git a/tests/TestData/Generic/fatal4.geojson b/tests/TestData/Generic/fatal4.geojson index 9e41df2..ae7061b 100644 --- a/tests/TestData/Generic/fatal4.geojson +++ b/tests/TestData/Generic/fatal4.geojson @@ -50,6 +50,7 @@ [-0.753125, 20.2234375], [-0.565625, 11.0828125], [3.846028904999335, 7.51285572161238], + [3.846028904999335, 7.51285572161238], [3.8460289049993355, 7.51285572161238], [6.559375, 5.3171875], [3.60625, 4.2390625], diff --git a/tests/TestData/Generic/issue76.geojson b/tests/TestData/Generic/issue76.geojson index 3472eb3..31e51e4 100644 --- a/tests/TestData/Generic/issue76.geojson +++ b/tests/TestData/Generic/issue76.geojson @@ -58,13 +58,12 @@ [ [-96.66033269728321, -126.63400219275148], [-19.3046867422006, -126.63400219275148], - [-19.304686742200598, -126.63400219275148], [-19.304686742200587, -357.48241878255635], [10.695313257799413, -357.48241878255635], - [10.695313257799397, -126.63400219275148], + [10.695313257799398, -126.63400219275148], [13.370917302716792, -126.63400219275148], [13.370917302716792, -107.63400219275148], - [10.695313257799395, -107.63400219275148], + [10.695313257799398, -107.63400219275148], [10.695313257799384, 126.92383121744365], [-19.304686742200616, 126.92383121744365], [-19.3046867422006, -107.63400219275148], diff --git a/tests/TestData/Generic/rust_issue12.geojson b/tests/TestData/Generic/rust_issue12.geojson index 91efff2..2712f4f 100644 --- a/tests/TestData/Generic/rust_issue12.geojson +++ b/tests/TestData/Generic/rust_issue12.geojson @@ -199,8 +199,6 @@ [464, 48], [416, 48], [400, 32], - [416, 32], - [400, 32], [336, 32], [320, 48], [304, 48], diff --git a/tests/TestData/Generic/vertical_ulp_slopes1.geojson b/tests/TestData/Generic/vertical_ulp_slopes1.geojson index 13bb6d6..d76b114 100644 --- a/tests/TestData/Generic/vertical_ulp_slopes1.geojson +++ b/tests/TestData/Generic/vertical_ulp_slopes1.geojson @@ -284,16 +284,13 @@ [-0.41176470588235287, 2], [-0.5294117647058825, 2], [-0.5294117647058824, 1], - [-0.5294117647058825, 1], [-0.6470588235294118, 1], [-0.6470588235294118, 2], [-0.7647058823529412, 2], [-0.7647058823529411, 1], - [-0.7647058823529412, 1], [-0.8823529411764706, 1], [-0.8823529411764707, 2], [-1.0000000000000002, 2], - [-1, 1], [-1.0000000000000002, 1], [-2, 1], [-2, 0.8823529411764706], diff --git a/tests/TestData/Generic/vertical_ulp_slopes2.geojson b/tests/TestData/Generic/vertical_ulp_slopes2.geojson index 74673a9..309be8d 100644 --- a/tests/TestData/Generic/vertical_ulp_slopes2.geojson +++ b/tests/TestData/Generic/vertical_ulp_slopes2.geojson @@ -301,16 +301,13 @@ [-0.41176470588235287, 2.048453533107718], [-0.5294117647058825, 1.9067309100411467], [-0.5294117647058824, 1], - [-0.5294117647058825, 1], [-0.6470588235294118, 1], [-0.6470588235294118, 1.881859453615137], [-0.7647058823529412, 1.9321339284015497], [-0.7647058823529411, 1], - [-0.7647058823529412, 1], [-0.8823529411764706, 1], [-0.8823529411764707, 2.0198649911514837], [-1.0000000000000002, 1.8103704927311566], - [-1, 1], [-1.0000000000000002, 1], [-2.0705834729861206, 1], [-1.8067386218571149, 0.8823529411764706], From fcd1407407ffc63b3b0f1ebe7cde12eebac86859 Mon Sep 17 00:00:00 2001 From: James Jackson-South Date: Thu, 29 Oct 2026 11:34:22 +1000 Subject: [PATCH 07/24] Classify segment overlaps from source coordinates Use retained coordinate differences for the parallel decision. Select collinear overlap endpoints directly from source coordinates, without rounded projection parameters. Cover reversed operands, reversed directions and short overlaps near long-segment endpoints. --- src/PolygonClipper/PolygonUtilities.cs | 81 +++++++++---------- .../PolygonUtilitiesTests.cs | 46 +++++++++++ 2 files changed, 86 insertions(+), 41 deletions(-) diff --git a/src/PolygonClipper/PolygonUtilities.cs b/src/PolygonClipper/PolygonUtilities.cs index 4be5baa..a0d39cf 100644 --- a/src/PolygonClipper/PolygonUtilities.cs +++ b/src/PolygonClipper/PolygonUtilities.cs @@ -112,26 +112,31 @@ private static int FindIntersectionImpl(in Segment seg0, in Segment seg1, out Ve Vertex va = seg0.Target - a1; Vertex vb = seg1.Target - a2; - Vertex e = a2 - a1; + ExtendedPrecisionDouble ax = default; + ExtendedPrecisionDouble ay = default; + ExtendedPrecisionDouble bx = default; + ExtendedPrecisionDouble by = default; + ExtendedPrecisionDouble denominator = default; - double kross = Vertex.Cross(va, vb); - double sqrLenA = Vertex.Dot(va, va); + // Shared vertical or horizontal directions are exactly parallel. Other + // directions need the retained coordinate differences: rounding them + // first can make collinear source segments appear to cross. + if ((va.X != 0 || vb.X != 0) && (va.Y != 0 || vb.Y != 0)) + { + ax = ExtendedPrecisionDouble.Difference(seg0.Target.X, a1.X); + ay = ExtendedPrecisionDouble.Difference(seg0.Target.Y, a1.Y); + bx = ExtendedPrecisionDouble.Difference(seg1.Target.X, a2.X); + by = ExtendedPrecisionDouble.Difference(seg1.Target.Y, a2.Y); + denominator = (ax * by) - (ay * bx); + } - // Squaring a representable non-zero cross product can underflow to zero, - // incorrectly sending small crossing segments into the collinear branch. - if (kross != 0) + if (denominator.Value != 0) { - // Lines of the segments are not parallel // Retain subtraction, determinant, and division roundoff until the // final coordinate is rounded. Independent segment pairs meeting at // one junction must construct the same point for event closure. - ExtendedPrecisionDouble ax = ExtendedPrecisionDouble.Difference(seg0.Target.X, a1.X); - ExtendedPrecisionDouble ay = ExtendedPrecisionDouble.Difference(seg0.Target.Y, a1.Y); - ExtendedPrecisionDouble bx = ExtendedPrecisionDouble.Difference(seg1.Target.X, a2.X); - ExtendedPrecisionDouble by = ExtendedPrecisionDouble.Difference(seg1.Target.Y, a2.Y); ExtendedPrecisionDouble ex = ExtendedPrecisionDouble.Difference(a2.X, a1.X); ExtendedPrecisionDouble ey = ExtendedPrecisionDouble.Difference(a2.Y, a1.Y); - ExtendedPrecisionDouble denominator = (ax * by) - (ay * bx); ExtendedPrecisionDouble numerator = (ex * by) - (ey * bx); ExtendedPrecisionDouble otherNumerator = (ex * ay) - (ey * ax); double start = numerator.Value; @@ -169,42 +174,36 @@ private static int FindIntersectionImpl(in Segment seg0, in Segment seg1, out Ve return 1; } - // Lines are parallel; check if they are collinear - kross = Vertex.Cross(e, va); - if (kross != 0) + // Use the original coordinates for the collinearity decision too. + if (SignedArea(a1, seg0.Target, a2) != 0) { - // Lines of the segments are different return 0; } - // Segments are collinear, check for overlap - double sa = Vertex.Dot(va, e) / sqrLenA; - double sb = sa + (Vertex.Dot(va, vb) / sqrLenA); - double smin = Math.Min(sa, sb); - double smax = Math.Max(sa, sb); - - if (smin <= 1 && smax >= 0) + // The bounding-box check already established overlap. Compare source + // coordinates along a non-constant axis, without normalized parameters. + // A short overlap near a long segment's end must not round to one point. + bool useX = va.X != 0; + double firstSource = useX ? a1.X : a1.Y; + double firstTarget = useX ? seg0.Target.X : seg0.Target.Y; + double secondSource = useX ? a2.X : a2.Y; + double secondTarget = useX ? seg1.Target.X : seg1.Target.Y; + bool firstForward = firstSource <= firstTarget; + bool secondForward = secondSource <= secondTarget; + Vertex firstMin = firstForward ? a1 : seg0.Target; + Vertex firstMax = firstForward ? seg0.Target : a1; + Vertex secondMin = secondForward ? a2 : seg1.Target; + Vertex secondMax = secondForward ? seg1.Target : a2; + Vertex minimum = Math.Min(firstSource, firstTarget) >= Math.Min(secondSource, secondTarget) ? firstMin : secondMin; + Vertex maximum = Math.Max(firstSource, firstTarget) <= Math.Max(secondSource, secondTarget) ? firstMax : secondMax; + pi0 = firstForward ? minimum : maximum; + if (minimum == maximum) { - if (smin == 1) - { - pi0 = seg0.Target; - return 1; - } - - if (smax == 0) - { - pi0 = a1; - return 1; - } - - // Overlap endpoints are existing source vertices. Reconstructing - // them through a parameter can move a shared vertex by one ULP. - pi0 = smin <= 0 ? a1 : sa <= sb ? a2 : seg1.Target; - pi1 = smax >= 1 ? seg0.Target : sa >= sb ? a2 : seg1.Target; - return 2; + return 1; } - return 0; + pi1 = firstForward ? maximum : minimum; + return 2; } /// diff --git a/tests/PolygonClipper.Tests/PolygonUtilitiesTests.cs b/tests/PolygonClipper.Tests/PolygonUtilitiesTests.cs index 932cdef..76e109f 100644 --- a/tests/PolygonClipper.Tests/PolygonUtilitiesTests.cs +++ b/tests/PolygonClipper.Tests/PolygonUtilitiesTests.cs @@ -5,6 +5,52 @@ namespace SixLabors.PolygonClipper.Tests; public class PolygonUtilitiesTests { + /// + /// Checks overlap when rounded directions suggest a crossing or an endpoint contact. + /// + /// Whether a short overlap lies near a long segment's endpoint. + /// Whether to reverse the first segment. + /// Whether to reverse the second segment. + [Theory] + [InlineData(false, false, false)] + [InlineData(false, true, false)] + [InlineData(false, false, true)] + [InlineData(false, true, true)] + [InlineData(true, false, false)] + [InlineData(true, true, false)] + [InlineData(true, false, true)] + [InlineData(true, true, true)] + public void FindIntersection_CollinearRoundedDirections_ReturnsBothOverlapEndpoints( + bool largeCoordinates, bool reverseFirst, bool reverseSecond) + { + const double u = 1.0000000000000002; + Segment overlap = largeCoordinates + ? new(new Vertex(9999999999999998D, 9999999999999998D), new Vertex(1E16, 1E16)) + : new(new Vertex(-u, -1), new Vertex(2 * u, 2)); + Segment enclosing = largeCoordinates + ? new(new Vertex(-3E16, -3E16), new Vertex(1E16, 1E16)) + : new(new Vertex(-2 * u, -2), new Vertex(2 * u, 2)); + Segment first = reverseFirst ? overlap.Reverse() : overlap; + Segment second = reverseSecond ? enclosing.Reverse() : enclosing; + + // Both cases have a non-empty interval in common. Direction and operand + // order cannot turn that interval into a single-point intersection. + foreach ((Segment a, Segment b) in new[] { (first, second), (second, first) }) + { + int count = PolygonUtilities.FindIntersection(a, b, out Vertex start, out Vertex end); + + Assert.Equal(2, count); + Assert.NotEqual(start, end); + Assert.True(start == overlap.Source || start == overlap.Target); + Assert.True(end == overlap.Source || end == overlap.Target); + + int vertexCount = PolygonUtilities.FindIntersection(a.Source, a.Target, b.Source, b.Target, out Vertex vertexStart, out Vertex vertexEnd); + Assert.Equal(2, vertexCount); + Assert.Equal(start, vertexStart); + Assert.Equal(end, vertexEnd); + } + } + /// /// Checks source incidence when rounded coordinate differences obscure the orientation. /// From 631b39f540a077e07621033ec54a15fa48ef2146 Mon Sep 17 00:00:00 2001 From: James Jackson-South Date: Thu, 29 Oct 2026 11:34:22 +1000 Subject: [PATCH 08/24] Retain cached events when pooled storage grows Copy retained slots beyond the active count. Cover growth immediately after Clear and after partial reuse, checking event identity and refreshed coordinates. --- src/PolygonClipper/SweepEventPoolList.cs | 8 +-- .../SweepEventPoolListTests.cs | 49 +++++++++++++++++++ 2 files changed, 53 insertions(+), 4 deletions(-) create mode 100644 tests/PolygonClipper.Tests/SweepEventPoolListTests.cs diff --git a/src/PolygonClipper/SweepEventPoolList.cs b/src/PolygonClipper/SweepEventPoolList.cs index f31dae4..a873fbe 100644 --- a/src/PolygonClipper/SweepEventPoolList.cs +++ b/src/PolygonClipper/SweepEventPoolList.cs @@ -128,10 +128,10 @@ private set int target = (int)BitOperations.RoundUpToPowerOf2((uint)value); T[] newItems = new T[target]; - if (this.Size > 0) - { - Array.Copy(this.Items, newItems, this.Size); - } + + // Clear resets the active count but retains reusable objects. Copy + // those inactive slots too, including growth before the next run. + Array.Copy(this.Items, newItems, this.Items.Length); this.Items = newItems; } diff --git a/tests/PolygonClipper.Tests/SweepEventPoolListTests.cs b/tests/PolygonClipper.Tests/SweepEventPoolListTests.cs new file mode 100644 index 0000000..7103891 --- /dev/null +++ b/tests/PolygonClipper.Tests/SweepEventPoolListTests.cs @@ -0,0 +1,49 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +namespace SixLabors.PolygonClipper.Tests; + +/// +/// Checks event reuse when retained storage grows between clipping runs. +/// +public class SweepEventPoolListTests +{ + /// + /// Checks that growth preserves cached events outside the active range. + /// + /// The number of events reused before growth. + [Theory] + [InlineData(0)] + [InlineData(1)] + public void GrowthAfterClear_PreservesCachedEvents(int activeCount) + { + SweepEventPoolList pool = []; + SweepEvent[] original = new SweepEvent[4]; + for (int i = 0; i < original.Length; i++) + { + original[i] = pool.Add(new Vertex(i, 0), new Vertex(i + 1, 0), new PolygonClipper.WindingCount(1, 0)); + } + + int capacity = pool.Capacity; + pool.Clear(); + for (int i = 0; i < activeCount; i++) + { + Assert.Same(original[i], pool.Add(new Vertex(i, 1), new Vertex(i + 1, 1), new PolygonClipper.WindingCount(0, 1))); + } + + pool.EnsureCapacity(capacity + 1); + + Assert.Equal(activeCount, pool.Count); + Assert.True(pool.Capacity > capacity); + for (int i = activeCount; i < original.Length; i++) + { + SweepEvent reused = pool.Add(new Vertex(i, 1), new Vertex(i + 1, 1), new PolygonClipper.WindingCount(0, 1)); + Assert.Same(original[i], reused); + Assert.Equal(new Vertex(i, 1), reused.Point); + Assert.Equal(new Vertex(i + 1, 1), reused.End); + } + + pool.Add(new Vertex(4, 1), new Vertex(5, 1), new PolygonClipper.WindingCount(0, 1)); + Assert.Equal(5, pool.Count); + } +} From d2b8522d263033362a964ae84823c2ac907db200 Mon Sep 17 00:00:00 2001 From: James Jackson-South Date: Thu, 29 Oct 2026 22:02:38 +1000 Subject: [PATCH 09/24] Reduce Martinez sweep overhead and output allocations Replace incident status blocks in place and remove full-suffix result rank updates. Bound stale queue entries and store source pool indices without managed references. Reuse connector and sweep scratch storage, reduce event size, and remove redundant fill checks and contour traversal work. Validation: 808 tests passed on both .NET 10 and .NET 11, with two existing skips each. Exact geometry snapshots match across 20 comparison cases. --- src/PolygonClipper/Contour.cs | 2 +- src/PolygonClipper/EdgeType.cs | 33 ---- src/PolygonClipper/PolygonClipper.cs | 236 +++++++++++++---------- src/PolygonClipper/StatusLine.cs | 40 +++- src/PolygonClipper/SweepEvent.cs | 92 ++++----- src/PolygonClipper/SweepEventComparer.cs | 2 +- src/PolygonClipper/SweepEventPoolList.cs | 38 ++++ 7 files changed, 253 insertions(+), 190 deletions(-) delete mode 100644 src/PolygonClipper/EdgeType.cs diff --git a/src/PolygonClipper/Contour.cs b/src/PolygonClipper/Contour.cs index 436226d..27f9af6 100644 --- a/src/PolygonClipper/Contour.cs +++ b/src/PolygonClipper/Contour.cs @@ -26,7 +26,7 @@ public sealed class Contour : IReadOnlyCollection /// /// Set of vertices conforming the external contour /// - private readonly List vertices = []; + private readonly List vertices; /// /// Holes of the contour. They are stored as the indexes of diff --git a/src/PolygonClipper/EdgeType.cs b/src/PolygonClipper/EdgeType.cs deleted file mode 100644 index 8ef74de..0000000 --- a/src/PolygonClipper/EdgeType.cs +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) Six Labors. -// Licensed under the Six Labors Split License. - -namespace SixLabors.PolygonClipper; - -/// -/// Specifies the type of an edge in a boolean operation on polygons. -/// -internal enum EdgeType -{ - /// - /// A normal edge that contributes to the resulting polygon. - /// - Normal = 0, - - /// - /// An edge that does not contribute to the resulting polygon. - /// This typically occurs when the edge lies entirely inside another polygon. - /// - NonContributing = 1, - - /// - /// An edge that represents a transition within the same polygon, - /// meaning it does not cross into another polygon. - /// - SameTransition = 2, - - /// - /// An edge that represents a transition between different polygons, - /// meaning it crosses from one polygon to another. - /// - DifferentTransition = 3 -} diff --git a/src/PolygonClipper/PolygonClipper.cs b/src/PolygonClipper/PolygonClipper.cs index b065be1..4ae2fca 100644 --- a/src/PolygonClipper/PolygonClipper.cs +++ b/src/PolygonClipper/PolygonClipper.cs @@ -2,6 +2,7 @@ // Licensed under the Six Labors Split License. using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; namespace SixLabors.PolygonClipper; @@ -52,12 +53,12 @@ public class PolygonClipper private readonly List eventStorage = []; private readonly StablePriorityQueue events; private readonly SweepEventPoolList segments = []; - private readonly StatusLine activeResult = new(); - private readonly List outgoing = []; - private readonly List bundled = []; - private readonly List pendingBoundaries = []; + private readonly SweepEventPoolList outgoing = []; + private readonly SweepEventPoolList bundled = []; + private readonly SweepEventPoolList pendingBoundaries = []; private readonly Stack> endpointQueues = new(); private int retainedEndpointCapacity; + private int activeBoundaryCount; private Polygon? subject; private Polygon? clipping; @@ -264,30 +265,31 @@ public Polygon Run() { // Bounds exclude any further filled result. Finish active boundaries // first because an ordering repair can move their endpoint by one ULP. - if (this.events.Peek().Point.X > stopX && this.activeResult.Count == 0) + if (this.events.Peek().Point.X > stopX && this.activeBoundaryCount == 0) { break; } QueueEntry next = this.events.Dequeue(); - if (!next.IsValid) + SweepEvent queuedEdge = this.segments[next.EdgeIndex]; + if (!next.IsValid(queuedEdge)) { continue; } Vertex point = next.Point; - bool sourcePoint = next.IsStart || point == next.Edge.SourceEnd; + bool sourcePoint = next.IsStart || point == queuedEdge.SourceEnd; this.outgoing.Clear(); this.pendingBoundaries.Clear(); int firstEnd = int.MaxValue; int lastEnd = -1; if (next.IsStart) { - this.outgoing.Add(next.Edge); + this.outgoing.Add(queuedEdge); } else { - firstEnd = lastEnd = next.Edge.PosSL; + firstEnd = lastEnd = queuedEdge.Pos; } // A vertex is a transaction, not a sequence of parity toggles. @@ -295,19 +297,21 @@ public Polygon Run() while (this.events.Count > 0 && this.events.Peek().Point == point) { next = this.events.Dequeue(); - if (next.IsValid && (next.IsStart || point == next.Edge.SourceEnd)) + queuedEdge = this.segments[next.EdgeIndex]; + bool valid = next.IsValid(queuedEdge); + if (valid && (next.IsStart || point == queuedEdge.SourceEnd)) { sourcePoint = true; } - if (next.IsValid && next.IsStart) + if (valid && next.IsStart) { - this.outgoing.Add(next.Edge); + this.outgoing.Add(queuedEdge); } - else if (next.IsValid) + else if (valid) { - firstEnd = Math.Min(firstEnd, next.Edge.PosSL); - lastEnd = Math.Max(lastEnd, next.Edge.PosSL); + firstEnd = Math.Min(firstEnd, queuedEdge.Pos); + lastEnd = Math.Max(lastEnd, queuedEdge.Pos); } } @@ -323,21 +327,6 @@ public Polygon Run() after++; } - // The result index is a filtered view of the very same block. - // Derive removals from the owned interval identities, so rounded - // incidence tests cannot remove a boundary independently of its - // source interval and leave a stale birth context behind. - int firstResult = first == 0 ? 0 : this.statusLine[first - 1].ResultRank; - int afterResult = firstResult; - for (int i = first; i < after; i++) - { - SweepEvent incoming = this.statusLine[i]; - if (incoming.Boundary is not null) - { - afterResult++; - } - } - // The surviving lower interval is outside the changed block. // Closure conserves the sum of signed contributions, so its // prefix and every surviving prefix above the block stay valid. @@ -346,18 +335,19 @@ public Polygon Run() this.StageIncoming(this.statusLine[i], point); } - this.statusLine.RemoveRange(first, after - first); - this.activeResult.RemoveRange(firstResult, afterResult - firstResult); + int statusCount = this.statusLine.Count; + int blockCount = after - first; while (true) { this.outgoing.Sort(SegmentComparer.CompareRays); this.BundleOutgoing(); + this.statusLine.ReplaceRange(first, blockCount, this.bundled.GetEventsSpan()); + blockCount = this.bundled.Count; for (int i = 0; i < this.bundled.Count; i++) { SweepEvent edge = this.bundled[i]; edge.Active = true; - this.statusLine.Insert(first + i, edge); } // Rounded intersections can equal this point even when the @@ -372,7 +362,6 @@ public Polygon Run() break; } - this.statusLine.RemoveRange(first, this.bundled.Count); this.outgoing.Clear(); this.outgoing.AddRange(this.bundled); foreach (SweepEvent edge in this.outgoing) @@ -381,29 +370,20 @@ public Polygon Run() // future endpoint queued while checking the staged block. edge.Active = false; edge.Version++; + edge.EndQueued = false; } if (lowerIncident) { SweepEvent incoming = this.statusLine[--first]; - if (incoming.Boundary is not null) - { - this.activeResult.RemoveAt(--firstResult); - } - - this.statusLine.RemoveAt(first); + blockCount++; this.StageIncoming(incoming, point); } if (upperIncident) { - SweepEvent incoming = this.statusLine[first]; - if (incoming.Boundary is not null) - { - this.activeResult.RemoveAt(firstResult); - } - - this.statusLine.RemoveAt(first); + SweepEvent incoming = this.statusLine[first + blockCount]; + blockCount++; this.StageIncoming(incoming, point); } } @@ -417,22 +397,35 @@ public Polygon Run() } WindingCount winding = first == 0 ? default : this.statusLine[first - 1].Above; - SweepEvent? previousBoundary = firstResult == 0 ? null : this.activeResult[firstResult - 1].Boundary; - if (firstResult > 0 && this.activeResult[firstResult - 1].Point.X == this.activeResult[firstResult - 1].End.X) - { - previousBoundary = previousBoundary!.PrevInResult; - } - - int resultIndex = firstResult; + bool below = InResult(winding, operation, subjectRule, clipRule); + SweepEvent? previousBoundary = null; + bool hasBoundaryContext = false; for (int i = 0; i < this.bundled.Count; i++) { SweepEvent edge = this.bundled[i]; - bool below = InResult(winding, operation, subjectRule, clipRule); winding = winding.Add(edge.Delta); edge.Above = winding; bool above = InResult(winding, operation, subjectRule, clipRule); if (below != above) { + // Interior crossings emit nothing and need no output + // predecessor. For a boundary, the first contributing + // interval below this complete block owns that context. + if (!hasBoundaryContext) + { + for (int j = first - 1; j >= 0; j--) + { + SweepEvent lower = this.statusLine[j]; + if (lower.Boundary is not null) + { + previousBoundary = lower.Point.X == lower.End.X ? lower.Boundary.PrevInResult : lower.Boundary; + break; + } + } + + hasBoundaryContext = true; + } + // Endpoint pairing is completed when the interval ends. // No geometry consumer reads this event until connection. edge.Boundary = resultEvents.Add( @@ -442,32 +435,58 @@ public Polygon Run() above ? ResultTransition.Contributing : ResultTransition.NonContributing, previousBoundary!, edge.ContourId); + this.activeBoundaryCount++; if (edge.Point.X != edge.End.X) { previousBoundary = edge.Boundary; } + } + + // The next interval starts in this interval's upper region. + // Carry its membership instead of evaluating the same winding twice. + below = above; - this.activeResult.Insert(resultIndex++, edge); + // Neighbor intersection discovery can already have queued this + // version's shortened endpoint. Keep one record per version. + if (!edge.EndQueued) + { + this.events.Enqueue(new QueueEntry(edge.End, edge, false)); + edge.EndQueued = true; } - this.events.Enqueue(new QueueEntry(edge.End, edge, false)); + edge.Pos = first + i; } - // List insertion/removal already shifts this suffix. Keep the - // endpoint anchors and filtered-boundary ranks in the same order. - // Winding counts above the changed block do not need recomputing. - int resultRank = firstResult; - for (int i = first; i < this.statusLine.Count; i++) + // Crossings keep full-status positions unchanged. Only births, + // deaths, and changing bundles move the unchanged suffix. + if (this.statusLine.Count != statusCount) { - SweepEvent edge = this.statusLine[i]; - edge.PosSL = i; - if (edge.Boundary is not null) + for (int i = first + this.bundled.Count; i < this.statusLine.Count; i++) { - resultRank++; + SweepEvent edge = this.statusLine[i]; + edge.Pos = i; } + } - edge.ResultRank = resultRank; + // Each source interval owns at most one valid queued start or end. + // Above twice the interval count, at least half the heap is obsolete. + // Rebuild only then, so each scan is paid for by discarded versions + // and old endpoints cannot grow the queue with every intersection. + if (this.eventStorage.Count > this.segments.Count * 2) + { + Span queued = CollectionsMarshal.AsSpan(this.eventStorage); + int count = 0; + for (int i = 0; i < queued.Length; i++) + { + if (queued[i].IsValid(this.segments[queued[i].EdgeIndex])) + { + queued[count++] = queued[i]; + } + } + + this.eventStorage.RemoveRange(count, this.eventStorage.Count - count); + this.events.Heapify(); } } @@ -624,7 +643,7 @@ private void Configure(Polygon subject, Polygon clip, BooleanOperation operation [MethodImpl(MethodImplOptions.AggressiveInlining)] private int GetRetainedEventCapacityScore() => this.sortedEvents.Capacity + this.eventStorage.Capacity + this.segments.Capacity + this.statusLine.RetainedCapacity + - this.activeResult.RetainedCapacity + this.outgoing.Capacity + this.bundled.Capacity + + this.outgoing.Capacity + this.bundled.Capacity + this.pendingBoundaries.Capacity + this.retainedEndpointCapacity; /// @@ -651,10 +670,10 @@ private void ResetSweep() { this.eventStorage.Clear(); this.statusLine.Reset(0); - this.activeResult.Reset(0); this.outgoing.Clear(); this.bundled.Clear(); this.pendingBoundaries.Clear(); + this.activeBoundaryCount = 0; for (int i = 0; i < this.segments.Count; i++) { if (this.segments[i].Ends is PriorityQueue ends) @@ -732,9 +751,11 @@ private void StageIncoming(SweepEvent incoming, Vertex point) { incoming.Active = false; incoming.Version++; + incoming.EndQueued = false; if (incoming.Boundary is SweepEvent boundary) { this.pendingBoundaries.Add(boundary); + this.activeBoundaryCount--; } this.ContinueAt(incoming, point); @@ -1016,6 +1037,7 @@ private void DivideSegment(SweepEvent edge, Vertex intersection, Vertex current) edge.End = intersection; edge.Version++; this.events.Enqueue(new QueueEntry(intersection, edge, false)); + edge.EndQueued = true; } /// @@ -1028,14 +1050,12 @@ private void DivideSegment(SweepEvent edge, Vertex intersection, Vertex current) /// Whether the region belongs to the result. private static bool InResult(WindingCount count, BooleanOperation operation, FillRule subjectRule, FillRule clipRule) { - bool subject = Filled(count.Subject, subjectRule); - bool clip = Filled(count.Clip, clipRule); return operation switch { - BooleanOperation.Intersection => subject && clip, - BooleanOperation.Union => subject || clip, - BooleanOperation.Difference => subject && !clip, - _ => subject ^ clip + BooleanOperation.Intersection => Filled(count.Subject, subjectRule) && Filled(count.Clip, clipRule), + BooleanOperation.Union => Filled(count.Subject, subjectRule) || Filled(count.Clip, clipRule), + BooleanOperation.Difference => Filled(count.Subject, subjectRule) && !Filled(count.Clip, clipRule), + _ => Filled(count.Subject, subjectRule) ^ Filled(count.Clip, clipRule) }; } @@ -1084,10 +1104,17 @@ private Polygon ConnectEdges(SweepEventPoolList resultEvents) } } - ReadOnlySpan iterationMap = PrecomputeIterationOrder(resultEvents); + using Buffer iterationBuffer = new(resultEvents.Count); + Span iterationMap = iterationBuffer.GetSpan(); + PrecomputeIterationOrder(resultEvents, iterationMap); Polygon result = []; - Span processed = new bool[resultEvents.Count]; + using Buffer processedBuffer = new(resultEvents.Count); + Span processed = processedBuffer.GetSpan(); + + // Every iteration-map slot is assigned, but processed flags must + // start clear because pooled storage can contain flags from a prior run. + processed.Clear(); for (int i = 0; i < resultEvents.Count; i++) { if (processed[i]) @@ -1113,13 +1140,20 @@ private Polygon ConnectEdges(SweepEventPoolList resultEvents) Vertex point = resultEvents[pos].Point; contour.Add(point); + // Closing the contour needs no further edge. Searching here + // would revisit processed rays at a shared starting vertex. + if (point == initial) + { + break; + } + pos = NextPos(pos, processed, iterationMap, out bool found); if (!found) { break; } } - while (resultEvents[pos].Point != initial); + while (true); result.Add(contour); } @@ -1129,7 +1163,7 @@ private Polygon ConnectEdges(SweepEventPoolList resultEvents) return result; } - Polygon polygon = []; + Polygon polygon = new(result.Count); using Buffer contourIndices = new(result.Count); Span indices = contourIndices.GetSpan(); @@ -1166,11 +1200,9 @@ private Polygon ConnectEdges(SweepEventPoolList resultEvents) /// Builds the incident boundary order used to trace connected contours. /// /// The fully sorted, paired output events. - /// The next incident event index for each boundary endpoint. - private static ReadOnlySpan PrecomputeIterationOrder(SweepEventPoolList data) + /// Receives the next incident event index for every boundary endpoint. + private static void PrecomputeIterationOrder(SweepEventPoolList data, Span map) { - Span map = new int[data.Count]; - int i = 0; while (i < data.Count) { @@ -1246,8 +1278,6 @@ private static ReadOnlySpan PrecomputeIterationOrder(SweepEventPoolList dat } } } - - return map; } /// @@ -1274,7 +1304,9 @@ private static void MarkProcessed(SweepEvent sweepEvent, Span processed, i /// The initialized . private Contour InitializeContourFromContext(SweepEvent sweepEvent, Polygon polygon, int contourId) { - Contour contour = []; + // A triangle needs three vertices and its closing vertex during tracing. + // Reserve those slots instead of growing the list on the first Add. + Contour contour = new(4); if (this.contourOutput == ContourOutput.Nested) { if (sweepEvent.PrevInResult is SweepEvent lower) @@ -1440,20 +1472,15 @@ internal readonly struct QueueEntry public readonly Vertex Point; /// - /// The associated interval. + /// The source pool index, complemented for a start record. /// - public readonly SweepEvent Edge; + private readonly int sourceIndex; /// /// The interval version when queued. /// public readonly int Version; - /// - /// Whether this record starts a source interval. - /// - public readonly bool IsStart; - /// /// Initializes a new instance of the struct. /// @@ -1463,14 +1490,29 @@ internal readonly struct QueueEntry public QueueEntry(Vertex point, SweepEvent edge, bool isStart) { this.Point = point; - this.Edge = edge; + + // Pool indices remain stable until the operation ends. Encoding + // start/end in their sign keeps every version bit and removes the + // managed reference, so heap movement needs no GC write barriers. + this.sourceIndex = isStart ? ~edge.ContourId : edge.ContourId; this.Version = edge.Version; - this.IsStart = isStart; } /// - /// Gets a value indicating whether the representative still owns this queued record. + /// Gets a value indicating whether this record starts a source interval. + /// + public bool IsStart => this.sourceIndex < 0; + + /// + /// Gets the stable index in the source interval pool. + /// + public int EdgeIndex => this.sourceIndex < 0 ? ~this.sourceIndex : this.sourceIndex; + + /// + /// Checks whether the source interval still owns this queued record. /// - public bool IsValid => this.Version == this.Edge.Version && (this.IsStart || this.Edge.Active); + /// The interval at . + /// Whether the interval version and activity match. + public bool IsValid(SweepEvent edge) => this.Version == edge.Version && (this.IsStart || edge.Active); } } diff --git a/src/PolygonClipper/StatusLine.cs b/src/PolygonClipper/StatusLine.cs index faceefc..3ddd0f4 100644 --- a/src/PolygonClipper/StatusLine.cs +++ b/src/PolygonClipper/StatusLine.cs @@ -3,6 +3,7 @@ using System.Diagnostics; using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; namespace SixLabors.PolygonClipper; @@ -108,7 +109,7 @@ public int Add(SweepEvent e) } this.sortedEvents.Insert(index, e); - e.PosSL = index; + e.Pos = index; return index; } @@ -126,6 +127,33 @@ public int Add(SweepEvent e) /// The number of incoming intervals. public void RemoveRange(int index, int count) => this.sortedEvents.RemoveRange(index, count); + /// + /// Replaces an incident block without shifting the unchanged suffix when its size stays the same. + /// + /// The first incident interval. + /// The number of intervals to replace. + /// The outgoing intervals in status order. + public void ReplaceRange(int index, int count, ReadOnlySpan replacement) + { + int common = Math.Min(count, replacement.Length); + Span events = CollectionsMarshal.AsSpan(this.sortedEvents); + for (int i = 0; i < common; i++) + { + events[index + i] = replacement[i]; + } + + // Crossings normally replace two intervals with two intervals. Only + // source endpoints and changing bundles require a suffix move. + if (replacement.Length > count) + { + this.sortedEvents.InsertRange(index + count, replacement[count..]); + } + else if (replacement.Length < count) + { + this.sortedEvents.RemoveRange(index + replacement.Length, count - replacement.Length); + } + } + /// /// Finds the first interval not strictly below the complete event point. /// @@ -172,7 +200,7 @@ public int IndexOf(SweepEvent e) { List events = this.sortedEvents; int count = events.Count; - int hint = e.PosSL; + int hint = e.Pos; if ((uint)hint < (uint)count && ReferenceEquals(events[hint], e)) { @@ -184,7 +212,7 @@ public int IndexOf(SweepEvent e) { if (ReferenceEquals(events[index], e)) { - e.PosSL = index; + e.Pos = index; return index; } @@ -193,7 +221,7 @@ public int IndexOf(SweepEvent e) { if (ReferenceEquals(events[i], e)) { - e.PosSL = i; + e.Pos = i; return i; } } @@ -202,7 +230,7 @@ public int IndexOf(SweepEvent e) { if (ReferenceEquals(events[i], e)) { - e.PosSL = i; + e.Pos = i; return i; } } @@ -213,7 +241,7 @@ public int IndexOf(SweepEvent e) { if (ReferenceEquals(events[i], e)) { - e.PosSL = i; + e.Pos = i; return i; } } diff --git a/src/PolygonClipper/SweepEvent.cs b/src/PolygonClipper/SweepEvent.cs index 8b9b175..49cd856 100644 --- a/src/PolygonClipper/SweepEvent.cs +++ b/src/PolygonClipper/SweepEvent.cs @@ -12,6 +12,17 @@ namespace SixLabors.PolygonClipper; /// internal sealed class SweepEvent { + private const byte LeftFlag = 1; + private const byte ClipFlag = 2; + + // Direction and operand share one byte. Separate stored properties leave + // padding in every output endpoint, even though each needs only two bits. + private byte flags; + + // Result transitions are -1, 0, or 1. Keep their signed values without + // storing a four-byte enum in every completed output endpoint. + private sbyte resultTransition; + // Live-only state is allocated and pooled with source intervals. Output // history needs only endpoint, transition, and predecessor data, so it must // not pay for source support, bundle ledgers, and active-status bookkeeping. @@ -24,19 +35,16 @@ internal sealed class SweepEvent /// Whether the point is the left endpoint of the segment. /// The event associated with the other endpoint of the segment. /// The polygon type to which the segment belongs. - /// The type of the edge. Default is . public SweepEvent( Vertex point, bool left, SweepEvent otherEvent, - PolygonType polygonType = PolygonType.Subject, - EdgeType edgeType = EdgeType.Normal) + PolygonType polygonType = PolygonType.Subject) { + this.flags = polygonType == PolygonType.Clipping ? ClipFlag : (byte)0; this.Point = point; this.Left = left; this.OtherEvent = otherEvent; - this.PolygonType = polygonType; - this.EdgeType = edgeType; } /// @@ -47,10 +55,9 @@ public SweepEvent( /// The polygon type to which the segment belongs. public SweepEvent(Vertex point, bool left, PolygonType polygonType = PolygonType.Subject) { + this.flags = polygonType == PolygonType.Clipping ? ClipFlag : (byte)0; this.Point = point; this.Left = left; - this.PolygonType = polygonType; - this.EdgeType = EdgeType.Normal; } /// @@ -64,8 +71,6 @@ public SweepEvent(Vertex point, bool left, int contourId) this.Point = point; this.Left = left; this.ContourId = contourId; - this.PolygonType = PolygonType.Subject; - this.EdgeType = EdgeType.Normal; } /// @@ -77,7 +82,11 @@ public SweepEvent(Vertex point, bool left, int contourId) /// Gets or sets a value indicating whether the point is the /// left (source) endpoint of the segment (p, other->p). /// - public bool Left { get; set; } + public bool Left + { + get => (this.flags & LeftFlag) != 0; + set => this.flags = value ? (byte)(this.flags | LeftFlag) : (byte)(this.flags & ~LeftFlag); + } /// /// Gets or sets the ID of the contour to which the event belongs. @@ -87,7 +96,7 @@ public SweepEvent(Vertex point, bool left, int contourId) /// /// Gets index of the polygon to which the associated segment belongs to; /// - public PolygonType PolygonType { get; } + public PolygonType PolygonType => (this.flags & ClipFlag) == 0 ? PolygonType.Subject : PolygonType.Clipping; /// /// Gets or sets the current terminal point of this live interval. @@ -128,50 +137,26 @@ public Vertex End /// public SweepEvent Boundary { get => this.interval.Boundary; set => this.interval.Boundary = value; } - /// - /// Gets or sets the number of result intervals at or below this status entry. - /// - public int ResultRank { get => this.interval.ResultRank; set => this.interval.ResultRank = value; } - /// /// Gets or sets the generation identifying this piece in queued endpoint records. /// public int Version { get => this.interval.Version; set => this.interval.Version = value; } /// - /// Gets or sets a value indicating whether this interval is active. + /// Gets or sets a value indicating whether the current interval version already has a queued endpoint. /// - public bool Active { get => this.interval.Active; set => this.interval.Active = value; } + public bool EndQueued { get => this.interval.EndQueued; set => this.interval.EndQueued = value; } /// - /// Gets or sets the type of the edge. + /// Gets or sets a value indicating whether this interval is active. /// - public EdgeType EdgeType { get; set; } + public bool Active { get => this.interval.Active; set => this.interval.Active = value; } /// /// Gets or sets the event associated to the other endpoint of the segment. /// public SweepEvent OtherEvent { get; set; } - /// - /// Gets or sets a value indicating whether the segment (p, other->p) represent an - /// inside-outside transition in the polygon for a vertical ray from (p.x, -infinite) - /// that crosses the segment. - /// - public bool InOut { get; set; } - - /// - /// Gets or sets a value indicating whether the inOut transition for the segment from - /// the other polygon preceding this segment in the sweep line. - /// - public bool OtherInOut { get; set; } - - /// - /// Gets or sets the sorted sweep events. Only used in "left" events. - /// Position of the event (segment) in SL (status line). - /// - public int PosSL { get; set; } - /// /// Gets or sets the previous segment in the sweep line belonging to the result of the /// boolean operation. @@ -181,7 +166,11 @@ public Vertex End /// /// Gets or sets the transition state of the event in the result. /// - public ResultTransition ResultTransition { get; set; } + public ResultTransition ResultTransition + { + get => (ResultTransition)this.resultTransition; + set => this.resultTransition = (sbyte)value; + } /// /// Gets a value indicating whether the event contributes to the result. @@ -189,15 +178,13 @@ public Vertex End public bool InResult => this.ResultTransition != ResultTransition.Neutral; /// - /// Gets or sets the position of the event in the sorted events. + /// Gets or sets the active-status index for a source interval or the result-list index for an output endpoint. /// + /// + /// Source intervals and output endpoints are separate instances. + /// public int Pos { get; set; } - /// - /// Gets or sets a value indicating whether the event is a result in-out transition. - /// - public bool ResultInOut { get; set; } - /// /// Gets or sets the output contour ID associated with this contour. /// @@ -286,8 +273,9 @@ public void InitializeInterval(Vertex start, Vertex end, int id, PolygonClipper. this.Above = default; this.Ends = null; this.Boundary = null; - this.Version = this.ResultRank = this.PosSL = 0; + this.Version = this.Pos = 0; this.Active = false; + this.EndQueued = false; } /// @@ -351,11 +339,6 @@ private sealed class IntervalState /// public SweepEvent Boundary { get; set; } - /// - /// Gets or sets the number of result intervals at or below this status entry. - /// - public int ResultRank { get; set; } - /// /// Gets or sets the generation identifying this piece in queued endpoint records. /// @@ -365,5 +348,10 @@ private sealed class IntervalState /// Gets or sets a value indicating whether this interval is active. /// public bool Active { get; set; } + + /// + /// Gets or sets a value indicating whether this version's endpoint is already in the queue. + /// + public bool EndQueued { get; set; } } } diff --git a/src/PolygonClipper/SweepEventComparer.cs b/src/PolygonClipper/SweepEventComparer.cs index f6ef4f0..88b9ff0 100644 --- a/src/PolygonClipper/SweepEventComparer.cs +++ b/src/PolygonClipper/SweepEventComparer.cs @@ -87,7 +87,7 @@ public int Compare(PolygonClipper.QueueEntry x, PolygonClipper.QueueEntry y) int order = this.Compare(x.Point, y.Point); if (order == 0) { - order = x.Edge.ContourId.CompareTo(y.Edge.ContourId); + order = x.EdgeIndex.CompareTo(y.EdgeIndex); } if (order == 0) diff --git a/src/PolygonClipper/SweepEventPoolList.cs b/src/PolygonClipper/SweepEventPoolList.cs index a873fbe..a8d6ce1 100644 --- a/src/PolygonClipper/SweepEventPoolList.cs +++ b/src/PolygonClipper/SweepEventPoolList.cs @@ -65,6 +65,44 @@ public SweepEvent Add( /// The edge connector's event ordering. public void Sort(SweepEventComparer comparer) => this.Items.AsSpan(0, this.Size).Sort(comparer); + /// + /// Gets the active event references. + /// + /// A read-only span that is valid until this pool changes. + public ReadOnlySpan GetEventsSpan() => this.Items.AsSpan(0, this.Size); + + /// + /// Orders outgoing intervals with the sweep's ray comparison. + /// + /// The ordering of outgoing rays. + public void Sort(Comparison comparison) + { + // Ordinary crossings have two outgoing rays. They need one comparison, + // without entering the general sort used for larger shared vertices. + if (this.Size == 2) + { + if (comparison(this.Items[0], this.Items[1]) > 0) + { + (this.Items[0], this.Items[1]) = (this.Items[1], this.Items[0]); + } + } + else if (this.Size > 2) + { + this.Items.AsSpan(0, this.Size).Sort(comparison); + } + } + + /// + /// Appends references owned by another sweep pool without copying its inactive slots. + /// + /// The active references to append. + public void AddRange(SweepEventPoolList source) + { + this.EnsureCapacity(this.Size + source.Size); + source.Items.AsSpan(0, source.Size).CopyTo(this.Items.AsSpan(this.Size)); + this.Size += source.Size; + } + /// /// Adds a sweep event to the active range. /// From f9d56fce2e3e6b0a4b178cbeac548f3e77de72f7 Mon Sep 17 00:00:00 2001 From: James Jackson-South Date: Thu, 29 Oct 2026 23:56:18 +1000 Subject: [PATCH 10/24] Reduce NonZero fill-rule sweep overhead Reuse ray ordering when bundling outgoing intervals and inline the existing fill-rule membership helpers. Validation: 808 tests passed on both .NET 10 and .NET 11, with two existing skips each. All 20 exact output snapshots match. NonZero star union benchmarks take 4.3-4.8% less time. --- src/PolygonClipper/PolygonClipper.cs | 31 +++++++++++++++++++----- src/PolygonClipper/SweepEventPoolList.cs | 25 ++----------------- 2 files changed, 27 insertions(+), 29 deletions(-) diff --git a/src/PolygonClipper/PolygonClipper.cs b/src/PolygonClipper/PolygonClipper.cs index 4ae2fca..6b29be6 100644 --- a/src/PolygonClipper/PolygonClipper.cs +++ b/src/PolygonClipper/PolygonClipper.cs @@ -340,7 +340,6 @@ public Polygon Run() while (true) { - this.outgoing.Sort(SegmentComparer.CompareRays); this.BundleOutgoing(); this.statusLine.ReplaceRange(first, blockCount, this.bundled.GetEventsSpan()); blockCount = this.bundled.Count; @@ -803,18 +802,36 @@ private void ContinueAt(SweepEvent incoming, Vertex point) } /// - /// Combines coincident outgoing intervals without losing longer continuations. + /// Orders outgoing rays and combines coincident intervals without losing longer continuations. /// private void BundleOutgoing() { + Span outgoing = this.outgoing.GetEventsSpan(); + int pairOrder = 0; + + // Most crossings have two outgoing rays. Their order also tells us + // whether they coincide, so reuse that comparison when bundling. + if (outgoing.Length == 2) + { + pairOrder = SegmentComparer.CompareRays(outgoing[0], outgoing[1]); + if (pairOrder > 0) + { + (outgoing[0], outgoing[1]) = (outgoing[1], outgoing[0]); + } + } + else if (outgoing.Length > 2) + { + outgoing.Sort(SegmentComparer.CompareRays); + } + this.bundled.Clear(); int i = 0; - while (i < this.outgoing.Count) + while (i < outgoing.Length) { - SweepEvent edge = this.outgoing[i++]; - while (i < this.outgoing.Count && SegmentComparer.CompareRays(edge, this.outgoing[i]) == 0) + SweepEvent edge = outgoing[i++]; + while (i < outgoing.Length && (outgoing.Length == 2 ? pairOrder == 0 : SegmentComparer.CompareRays(edge, outgoing[i]) == 0)) { - SweepEvent other = this.outgoing[i++]; + SweepEvent other = outgoing[i++]; if (SweepEventComparer.Instance.Compare(other.End, edge.End) < 0) { // A staged neighbor check may already have found an earlier @@ -1048,6 +1065,7 @@ private void DivideSegment(SweepEvent edge, Vertex intersection, Vertex current) /// The subject's fill rule. /// The clipping operand's fill rule. /// Whether the region belongs to the result. + [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool InResult(WindingCount count, BooleanOperation operation, FillRule subjectRule, FillRule clipRule) { return operation switch @@ -1065,6 +1083,7 @@ private static bool InResult(WindingCount count, BooleanOperation operation, Fil /// The signed winding count. /// The validated fill rule. /// Whether the region is filled. + [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool Filled(int count, FillRule rule) => rule switch { diff --git a/src/PolygonClipper/SweepEventPoolList.cs b/src/PolygonClipper/SweepEventPoolList.cs index a8d6ce1..8150eb6 100644 --- a/src/PolygonClipper/SweepEventPoolList.cs +++ b/src/PolygonClipper/SweepEventPoolList.cs @@ -68,29 +68,8 @@ public SweepEvent Add( /// /// Gets the active event references. /// - /// A read-only span that is valid until this pool changes. - public ReadOnlySpan GetEventsSpan() => this.Items.AsSpan(0, this.Size); - - /// - /// Orders outgoing intervals with the sweep's ray comparison. - /// - /// The ordering of outgoing rays. - public void Sort(Comparison comparison) - { - // Ordinary crossings have two outgoing rays. They need one comparison, - // without entering the general sort used for larger shared vertices. - if (this.Size == 2) - { - if (comparison(this.Items[0], this.Items[1]) > 0) - { - (this.Items[0], this.Items[1]) = (this.Items[1], this.Items[0]); - } - } - else if (this.Size > 2) - { - this.Items.AsSpan(0, this.Size).Sort(comparison); - } - } + /// A span that is valid until this pool changes. + public Span GetEventsSpan() => this.Items.AsSpan(0, this.Size); /// /// Appends references owned by another sweep pool without copying its inactive slots. From 0a65a5bbf89bf62c0caf3983769e93cfda569802 Mon Sep 17 00:00:00 2001 From: James Jackson-South Date: Fri, 30 Oct 2026 00:12:55 +1000 Subject: [PATCH 11/24] Use Normalize as the single-polygon cleanup API Remove the public unary Union overload and route Normalize directly through the existing Martinez execution. Update stroke cleanup, test callers, and README examples. Keep independent geometry assertions and remove duplicate checks of the deleted alias. Release validation: 808 tests passed on both .NET 10 and .NET 11, with two existing skips each. Whitespace checks passed. --- README.md | 13 ++---- src/PolygonClipper/PolygonClipper.cs | 17 ++------ src/PolygonClipper/PolygonStroker.cs | 2 +- .../FillRuleClippingTests.cs | 40 ++++++++----------- .../PolygonClipperContourClosureTests.cs | 1 - .../PolygonStrokerTests.cs | 4 +- 6 files changed, 26 insertions(+), 51 deletions(-) diff --git a/README.md b/README.md index fa99495..e1a2054 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,7 @@ self-intersections, overlapping edges, and multiple contours. ## Clipping The Boolean operations are `Intersection`, `Union`, `Difference`, and `Xor`. +Each combines a subject polygon with a clip polygon. Each accepts `EvenOdd`, `NonZero`, `Positive`, or `Negative` filling. ```csharp @@ -45,13 +46,6 @@ The subject and clip can use different fill rules: Polygon result = PolygonClipper.Intersection(subject, clip, FillRule.EvenOdd, FillRule.NonZero); ``` -To resolve self-intersections and overlaps in one polygon, use unary union: - -```csharp -// Keep every region whose winding count is non-zero. -Polygon result = PolygonClipper.Union(subject, FillRule.NonZero); -``` - These operations apply the fill rules during the clipping sweep. They do not require an input normalization pass. Coordinates must be finite doubles. @@ -62,10 +56,9 @@ Use `NonZero`, `EvenOdd`, or `Positive` filling to consume the resolved area. ## Normalization -`Normalize(polygon, fillRule)` is unary union. It resolves self-intersections and overlaps, +`Normalize(polygon, fillRule)` cleans one polygon. It resolves self-intersections and overlaps, removes zero-area retraces, and returns the full contour hierarchy. It reads the original contour directions without changing the input or applying a preparation pass. -Small features are not discarded using fixed distance or area thresholds. ```csharp // Clean the NonZero-filled area and retain parent and hole information. @@ -84,7 +77,7 @@ One polygon can contain both open and closed stroke inputs. Boolean operations use the filled area of each contour and implicitly close open inputs. Both Boolean and stroke output contain closed contours without a repeated closing vertex. -When `NormalizeOutput` is enabled, stroke cleanup uses unary union with `NonZero` filling. +When `NormalizeOutput` is enabled, stroke cleanup calls `Normalize` with `NonZero` filling. This preserves the raw outlines' filled area for either sign of stroke width. ```csharp diff --git a/src/PolygonClipper/PolygonClipper.cs b/src/PolygonClipper/PolygonClipper.cs index 6b29be6..cda015c 100644 --- a/src/PolygonClipper/PolygonClipper.cs +++ b/src/PolygonClipper/PolygonClipper.cs @@ -24,7 +24,7 @@ namespace SixLabors.PolygonClipper; /// Contours use implicit closure without a repeated closing vertex. /// /// -/// Unary union and Normalize return full containment hierarchies. Binary operations group each exterior contour with its holes. +/// Normalize returns the full containment hierarchy. Binary operations group each exterior contour with its holes. /// /// /// Coordinates must be finite. Only coordinates used by an operation are validated. @@ -146,16 +146,6 @@ public static Polygon Union(Polygon subject, Polygon clip, FillRule fillRule) public static Polygon Union(Polygon subject, Polygon clip, FillRule subjectFillRule, FillRule clipFillRule) => ExecuteFillOperation(subject, clip, BooleanOperation.Union, subjectFillRule, clipFillRule, ContourOutput.Grouped); - /// - /// Resolves directed contours into their filled area. - /// - /// The raw directed contours. - /// The rule interpreting the contours. - /// The resolved filled area with the full containment hierarchy, without changing the input contours. - /// Input hierarchy does not override contour direction or the selected fill rule. - public static Polygon Union(Polygon polygon, FillRule fillRule) - => ExecuteFillOperation(polygon, EmptyFillOperand, BooleanOperation.Union, fillRule, FillRule.EvenOdd, ContourOutput.Nested); - /// /// Subtracts one filled area from another using a common fill rule. /// @@ -204,16 +194,17 @@ public static Polygon Xor(Polygon subject, Polygon clip, FillRule subjectFillRul /// The source contours. Their vertices and directions are not modified. /// The rule that determines the source polygon's filled area. /// - /// The same cleanup as unary union, with closed contours and their full containment hierarchy. + /// Closed contours with their full containment hierarchy. /// Exterior contours and islands are counterclockwise. Holes are clockwise. /// The first vertex is not repeated at the end of a contour. /// /// /// The fill rule interprets the input. Output orientation is positive even when the input rule is Negative. + /// Input hierarchy does not override contour direction or the selected fill rule. /// Use NonZero, EvenOdd, or Positive filling when reusing the cleaned polygon. /// public static Polygon Normalize(Polygon polygon, FillRule fillRule) - => Union(polygon, fillRule); + => ExecuteFillOperation(polygon, EmptyFillOperand, BooleanOperation.Union, fillRule, FillRule.EvenOdd, ContourOutput.Nested); /// /// Executes the configured Boolean operation using the operand fill rules. diff --git a/src/PolygonClipper/PolygonStroker.cs b/src/PolygonClipper/PolygonStroker.cs index eb58ca0..73fe02b 100644 --- a/src/PolygonClipper/PolygonStroker.cs +++ b/src/PolygonClipper/PolygonStroker.cs @@ -253,7 +253,7 @@ public Polygon Stroke(Polygon polygon) // Raw outlines describe a NonZero-filled band. A negative width reverses // their winding, so Positive filling would incorrectly erase that band. - return PolygonClipper.Union(allContours, FillRule.NonZero); + return PolygonClipper.Normalize(allContours, FillRule.NonZero); } /// diff --git a/tests/PolygonClipper.Tests/FillRuleClippingTests.cs b/tests/PolygonClipper.Tests/FillRuleClippingTests.cs index 737bc93..c164f2c 100644 --- a/tests/PolygonClipper.Tests/FillRuleClippingTests.cs +++ b/tests/PolygonClipper.Tests/FillRuleClippingTests.cs @@ -71,7 +71,7 @@ public void InvalidRules_EmptyOperands_Throw(int value) FillRule invalid = (FillRule)value; Assert.Throws(() => PolygonClipper.Intersection([], [], invalid)); Assert.Throws(() => PolygonClipper.Intersection([], [], FillRule.NonZero, invalid)); - Assert.Throws(() => PolygonClipper.Union([], invalid)); + Assert.Throws(() => PolygonClipper.Normalize([], invalid)); Assert.Throws(() => new PolygonClipper([], [], BooleanOperation.Union, invalid, FillRule.NonZero)); Assert.Throws(() => new PolygonClipper([], [], (BooleanOperation)value, FillRule.NonZero, FillRule.NonZero)); } @@ -88,10 +88,10 @@ public void NonFiniteCoordinates_UsedInputsThrow_AndPoolRemainsUsable(double coo { Polygon invalid = [Rectangle(0, 0, 2, 2), [new Vertex(coordinate, 0), new Vertex(1, 0), new Vertex(0, 1)]]; - // Empty intersection does not inspect unused geometry. Unary union does. + // Empty intersection does not inspect unused geometry. Normalize does. Assert.Empty(PolygonClipper.Intersection(invalid, [], FillRule.NonZero)); - Assert.Throws(() => PolygonClipper.Union(invalid, FillRule.NonZero)); - Assert.Equal(4D, Area(PolygonClipper.Union([Rectangle(0, 0, 2, 2)], FillRule.NonZero))); + Assert.Throws(() => PolygonClipper.Normalize(invalid, FillRule.NonZero)); + Assert.Equal(4D, Area(PolygonClipper.Normalize([Rectangle(0, 0, 2, 2)], FillRule.NonZero))); } /// @@ -102,12 +102,12 @@ public void NonFiniteCoordinates_UsedInputsThrow_AndPoolRemainsUsable(double coo [InlineData(FillRule.EvenOdd)] [InlineData(FillRule.NonZero)] [InlineData(FillRule.Positive)] - public void UnaryUnion_NearlyParallelIntegerEdges_PreservesTriangle(FillRule rule) + public void Normalize_NearlyParallelIntegerEdges_PreservesTriangle(FillRule rule) { const double n = 134217728D; Contour triangle = [new Vertex(0, 0), new Vertex(n, n + 1), new Vertex(n - 1, n)]; - Polygon result = PolygonClipper.Union([triangle], rule); + Polygon result = PolygonClipper.Normalize([triangle], rule); // The determinant is n*n - (n+1)*(n-1) = 1, so the area is exactly one half. Contour boundary = Assert.Single(result); @@ -137,13 +137,10 @@ public void Cleanup_ClockwiseDonut_SelectsInputRuleAndCanonicalOutput(FillRule r Polygon original = input.DeepClone(); Polygon cleaned = PolygonClipper.Normalize(input, rule); - Polygon union = PolygonClipper.Union(input, rule); // The clockwise exterior contributes -1. Its counterclockwise inner // contour cancels that count in the 6-by-6 hole: 100 - 36 = 64. Assert.Equal(expectedArea, Area(cleaned)); - Assert.Equal(expectedArea, Area(union)); - Assert.Equal(union.Count, cleaned.Count); for (int i = 0; i < input.Count; i++) { Assert.Equal(original[i], input[i]); @@ -153,7 +150,6 @@ public void Cleanup_ClockwiseDonut_SelectsInputRuleAndCanonicalOutput(FillRule r if (expectedArea == 0) { Assert.Empty(cleaned); - Assert.Empty(union); } else { @@ -167,7 +163,6 @@ public void Cleanup_ClockwiseDonut_SelectsInputRuleAndCanonicalOutput(FillRule r { Assert.True(cleaned[i].IsClosed); Assert.NotEqual(cleaned[i][0], cleaned[i][^1]); - Assert.Equal(union[i], cleaned[i]); } // Resolved output describes an area with positive orientation. @@ -243,7 +238,6 @@ public void Cleanup_RetracedLine_ProducesNoPolygon(FillRule rule) Polygon distant = [Rectangle(10, 10, 20, 20)]; Assert.Empty(PolygonClipper.Normalize(line, rule)); - Assert.Empty(PolygonClipper.Union(line, rule)); Assert.Empty(PolygonClipper.Intersection(line, distant, rule, FillRule.NonZero)); Assert.Empty(PolygonClipper.Difference(line, distant, rule, FillRule.NonZero)); Assert.Equal(100D, Area(PolygonClipper.Union(line, distant, rule, FillRule.NonZero))); @@ -277,7 +271,6 @@ public void Cleanup_FourNestedRings_PreservesContainmentAndArea() Polygon input = [Rectangle(0, 0, 10, 10), Rectangle(2, 2, 8, 8), Rectangle(3, 3, 7, 7), Rectangle(4, 4, 6, 6)]; Polygon cleaned = PolygonClipper.Normalize(input, FillRule.EvenOdd); - Polygon union = PolygonClipper.Union(input, FillRule.EvenOdd); Assert.Equal(76D, Area(cleaned)); Assert.Equal(4, cleaned.Count); @@ -286,7 +279,6 @@ public void Cleanup_FourNestedRings_PreservesContainmentAndArea() Assert.Equal(i, cleaned[i].Depth); Assert.Equal(i == 0 ? (int?)null : i - 1, cleaned[i].ParentIndex); Assert.Equal((i & 1) == 0, Area([cleaned[i]]) > 0); - Assert.Equal(union[i], cleaned[i]); Assert.Equal(i == 3 ? 0 : 1, cleaned[i].HoleCount); if (i < 3) { @@ -388,11 +380,11 @@ public void DenseStars_ExplicitRules_MatchSourceCoverage(int vertexCount) [Theory] [InlineData(1E-90)] [InlineData(1E90)] - public void UnaryUnion_ScaledCrossing_PreservesFilledArea(double scale) + public void Normalize_ScaledCrossing_PreservesFilledArea(double scale) { Polygon input = [[new Vertex(0, 0), new Vertex(10 * scale, 10 * scale), new Vertex(10 * scale, 0), new Vertex(0, 10 * scale)]]; - Polygon result = PolygonClipper.Union(input, FillRule.NonZero); + Polygon result = PolygonClipper.Normalize(input, FillRule.NonZero); Assert.Equal(50D, Area(result) / (scale * scale), 10); } @@ -536,11 +528,11 @@ public static TheoryData Combinations [InlineData(FillRule.NonZero, 100D)] [InlineData(FillRule.Positive, 100D)] [InlineData(FillRule.Negative, 0D)] - public void UnaryUnion_SameDirectionNestedRings_UsesSelectedRule(FillRule rule, double area) + public void Normalize_SameDirectionNestedRings_UsesSelectedRule(FillRule rule, double area) { Polygon input = [Rectangle(0, 0, 10, 10), Rectangle(2, 2, 8, 8)]; - Polygon result = PolygonClipper.Union(input, rule); + Polygon result = PolygonClipper.Normalize(input, rule); Assert.Equal(area, Area(result), 10); Assert.Equal(2, input.Count); @@ -558,11 +550,11 @@ public void UnaryUnion_SameDirectionNestedRings_UsesSelectedRule(FillRule rule, [InlineData(FillRule.NonZero, 50D)] [InlineData(FillRule.Positive, 25D)] [InlineData(FillRule.Negative, 25D)] - public void UnaryUnion_Bowtie_ResolvesBothWindingSigns(FillRule rule, double area) + public void Normalize_Bowtie_ResolvesBothWindingSigns(FillRule rule, double area) { Polygon input = [[new Vertex(0, 0), new Vertex(10, 10), new Vertex(10, 0), new Vertex(0, 10)]]; - Polygon result = PolygonClipper.Union(input, rule); + Polygon result = PolygonClipper.Normalize(input, rule); Assert.Equal(area, Area(result), 10); } @@ -596,8 +588,8 @@ public void ManualClipperAndPooledCalls_DoNotLeakRules() PolygonClipper manual = new(subject, [], BooleanOperation.Union, FillRule.Negative, FillRule.EvenOdd); Assert.Equal(100D, Area(manual.Run())); Assert.Equal(100D, Area(manual.Run())); - Assert.Equal(0D, Area(PolygonClipper.Union(subject, FillRule.Positive))); - Assert.Equal(100D, Area(PolygonClipper.Union(subject, FillRule.Negative))); + Assert.Equal(0D, Area(PolygonClipper.Normalize(subject, FillRule.Positive))); + Assert.Equal(100D, Area(PolygonClipper.Normalize(subject, FillRule.Negative))); Polygon evenOdd = PolygonClipper.Union(subject, [], FillRule.EvenOdd); Assert.Equal(subject[0].Count, evenOdd[0].Count); @@ -609,12 +601,12 @@ public void ManualClipperAndPooledCalls_DoNotLeakRules() /// Checks double-coordinate behavior without integer scaling. /// [Fact] - public void UnaryUnion_TranslatedUnitRings_PreservesSmallArea() + public void Normalize_TranslatedUnitRings_PreservesSmallArea() { const double origin = 1E12; Polygon input = [Rectangle(origin, origin, origin + 1, origin + 1)]; - Polygon result = PolygonClipper.Union(input, FillRule.NonZero); + Polygon result = PolygonClipper.Normalize(input, FillRule.NonZero); Assert.Equal(1D, Area(result)); Assert.Equal(origin, result[0].GetBoundingBox().Min.X); diff --git a/tests/PolygonClipper.Tests/PolygonClipperContourClosureTests.cs b/tests/PolygonClipper.Tests/PolygonClipperContourClosureTests.cs index e06b959..8ff14d5 100644 --- a/tests/PolygonClipper.Tests/PolygonClipperContourClosureTests.cs +++ b/tests/PolygonClipper.Tests/PolygonClipperContourClosureTests.cs @@ -27,7 +27,6 @@ public void FilledOperations_SourceClosureFlags_DoNotChangeOutput(FillRule rule) AssertEquivalent(PolygonClipper.Union(subject, clip, rule), PolygonClipper.Union(openSubject, openClip, rule)); AssertEquivalent(PolygonClipper.Difference(subject, clip, rule), PolygonClipper.Difference(openSubject, openClip, rule)); AssertEquivalent(PolygonClipper.Xor(subject, clip, rule), PolygonClipper.Xor(openSubject, openClip, rule)); - AssertEquivalent(PolygonClipper.Union(subject, rule), PolygonClipper.Union(openSubject, rule)); AssertEquivalent(PolygonClipper.Normalize(subject, rule), PolygonClipper.Normalize(openSubject, rule)); Assert.False(openSubject[0].IsClosed); diff --git a/tests/PolygonClipper.Tests/PolygonStrokerTests.cs b/tests/PolygonClipper.Tests/PolygonStrokerTests.cs index 8dedf69..3443d2a 100644 --- a/tests/PolygonClipper.Tests/PolygonStrokerTests.cs +++ b/tests/PolygonClipper.Tests/PolygonStrokerTests.cs @@ -224,10 +224,10 @@ public void Stroke_MixedClosure_ResolvesCombinedArea() public void Stroke_BooleanOutput_RequiresNoClosureConversion() { Contour square = [new Vertex(0, 0), new Vertex(10, 0), new Vertex(10, 10), new Vertex(0, 10)]; - Polygon filled = PolygonClipper.Union([square], FillRule.NonZero); + Polygon filled = PolygonClipper.Normalize([square], FillRule.NonZero); Polygon stroke = PolygonStroker.Stroke(filled, 2, new StrokeOptions { LineJoin = LineJoin.Miter }); - Polygon resolved = PolygonClipper.Union(stroke, FillRule.Positive); + Polygon resolved = PolygonClipper.Normalize(stroke, FillRule.Positive); AssertPolygonIsValid(filled); AssertPolygonIsValid(stroke); From ceb4a9fa4ff7e466eeb6393f86549aa819b45078 Mon Sep 17 00:00:00 2001 From: James Jackson-South Date: Fri, 30 Oct 2026 01:53:33 +1000 Subject: [PATCH 12/24] Fix point intersection symmetry and resolve axis crossings exactly Use the non-degenerate support for point incidence tests. Return perpendicular axis intersections from their exact overlapping bounds without determinant division. Add analytic point/diagonal and scaled axis-crossing regressions. The point/diagonal test reproduced the prior asymmetric result before the correction. --- src/PolygonClipper/PolygonUtilities.cs | 15 +++++- .../PolygonUtilitiesTests.cs | 50 +++++++++++++++++++ 2 files changed, 63 insertions(+), 2 deletions(-) diff --git a/src/PolygonClipper/PolygonUtilities.cs b/src/PolygonClipper/PolygonUtilities.cs index a0d39cf..7cd002f 100644 --- a/src/PolygonClipper/PolygonUtilities.cs +++ b/src/PolygonClipper/PolygonUtilities.cs @@ -69,6 +69,16 @@ public static int FindIntersection(in Segment seg0, in Segment seg1, out Vertex return 0; } + // A vertical segment and a horizontal segment intersect at existing + // source coordinates. The overlapping bounds identify that point + // exactly, so determinant construction and division add no information. + if ((seg0.IsVertical() && seg1.Source.Y == seg1.Target.Y) || + (seg1.IsVertical() && seg0.Source.Y == seg0.Target.Y)) + { + pi0 = bbox.Value.Min; + return 1; + } + int interResult = FindIntersectionImpl(seg0, seg1, out pi0, out pi1); if (interResult == 1) @@ -174,8 +184,9 @@ private static int FindIntersectionImpl(in Segment seg0, in Segment seg1, out Ve return 1; } - // Use the original coordinates for the collinearity decision too. - if (SignedArea(a1, seg0.Target, a2) != 0) + // Use the original coordinates for collinearity. A point has no + // supporting direction, so test it against the other segment instead. + if ((seg0.IsDegenerate() ? SignedArea(a2, seg1.Target, a1) : SignedArea(a1, seg0.Target, a2)) != 0) { return 0; } diff --git a/tests/PolygonClipper.Tests/PolygonUtilitiesTests.cs b/tests/PolygonClipper.Tests/PolygonUtilitiesTests.cs index 76e109f..d68a793 100644 --- a/tests/PolygonClipper.Tests/PolygonUtilitiesTests.cs +++ b/tests/PolygonClipper.Tests/PolygonUtilitiesTests.cs @@ -5,6 +5,56 @@ namespace SixLabors.PolygonClipper.Tests; public class PolygonUtilitiesTests { + /// + /// Checks a point against a diagonal segment in both operand orders. + /// + /// The point's x coordinate. + /// The point's y coordinate. + /// Whether the point lies on the segment. + [Theory] + [InlineData(1D, 1D, 1)] + [InlineData(1D, 1.5D, 0)] + [InlineData(3D, 3D, 0)] + public void FindIntersection_PointAndDiagonal_IsSymmetric(double x, double y, int expected) + { + Vertex point = new(x, y); + Segment singleton = new(point, point); + Segment diagonal = new(new(0, 0), new(2, 2)); + foreach ((Segment first, Segment second) in new[] { (singleton, diagonal), (diagonal, singleton) }) + { + Assert.Equal(expected, PolygonUtilities.FindIntersection(first, second, out Vertex intersection, out _)); + if (expected == 1) + { + Assert.Equal(point, intersection); + } + } + } + + /// + /// Checks axis-aligned crossings whose coordinates are supplied by the two source segments. + /// + /// The coordinate scale. + [Theory] + [InlineData(1D)] + [InlineData(1E-90)] + [InlineData(1E90)] + public void FindIntersection_PerpendicularAxes_ReturnsExactSourceCoordinates(double scale) + { + Segment horizontal = new(new(0, scale * 0.75D), new(scale, scale * 0.75D)); + Segment vertical = new(new(scale * 0.25D, 0), new(scale * 0.25D, scale)); + foreach (Segment first in new[] { horizontal, horizontal.Reverse() }) + { + foreach (Segment second in new[] { vertical, vertical.Reverse() }) + { + foreach ((Segment a, Segment b) in new[] { (first, second), (second, first) }) + { + Assert.Equal(1, PolygonUtilities.FindIntersection(a, b, out Vertex point, out _)); + Assert.Equal(new Vertex(scale * 0.25D, scale * 0.75D), point); + } + } + } + } + /// /// Checks overlap when rounded directions suggest a crossing or an endpoint contact. /// From 4f814c365b38684b116e76976444b386d24613d1 Mon Sep 17 00:00:00 2001 From: James Jackson-South Date: Fri, 30 Oct 2026 11:14:35 +1000 Subject: [PATCH 13/24] Support open contour clipping in the Martinez sweep --- README.md | 37 +- src/PolygonClipper/Contour.cs | 9 +- src/PolygonClipper/EndpointContribution.cs | 31 + src/PolygonClipper/Polygon.cs | 9 +- src/PolygonClipper/PolygonClipper.cs | 635 ++++++++++++++---- src/PolygonClipper/PolygonUtilities.cs | 24 +- src/PolygonClipper/QueueEntry.cs | 59 ++ src/PolygonClipper/SweepEvent.cs | 47 +- src/PolygonClipper/SweepEventComparer.cs | 4 +- src/PolygonClipper/SweepEventPoolList.cs | 2 +- src/PolygonClipper/WindingCount.cs | 50 ++ .../OpenClippingBenches.cs | 163 +++++ .../OpenPathClippingTests.cs | 455 +++++++++++++ .../PolygonClipperContourClosureTests.cs | 30 +- .../SweepEventPoolListTests.cs | 8 +- 15 files changed, 1406 insertions(+), 157 deletions(-) create mode 100644 src/PolygonClipper/EndpointContribution.cs create mode 100644 src/PolygonClipper/QueueEntry.cs create mode 100644 src/PolygonClipper/WindingCount.cs create mode 100644 tests/PolygonClipper.Benchmarks/OpenClippingBenches.cs create mode 100644 tests/PolygonClipper.Tests/OpenPathClippingTests.cs diff --git a/README.md b/README.md index e1a2054..7507efb 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,7 @@ self-intersections, overlapping edges, and multiple contours. ## Clipping The Boolean operations are `Intersection`, `Union`, `Difference`, and `Xor`. -Each combines a subject polygon with a clip polygon. +Each combines a subject polygon with a clip polygon. Both operands can contain open and closed contours. Each accepts `EvenOdd`, `NonZero`, `Positive`, or `Negative` filling. ```csharp @@ -49,15 +49,15 @@ Polygon result = PolygonClipper.Intersection(subject, clip, FillRule.EvenOdd, Fi These operations apply the fill rules during the clipping sweep. They do not require an input normalization pass. Coordinates must be finite doubles. -Fill rules interpret the input contours. Every result uses positive orientation: +Fill rules interpret closed input contours. Closed results use positive orientation: counterclockwise exterior contours and islands, with clockwise holes, in Cartesian coordinates. Use `NonZero`, `EvenOdd`, or `Positive` filling to consume the resolved area. `Negative` selects negatively wound input; it does not request negatively oriented output. ## Normalization -`Normalize(polygon, fillRule)` cleans one polygon. It resolves self-intersections and overlaps, -removes zero-area retraces, and returns the full contour hierarchy. +`Normalize(polygon, fillRule)` cleans one polygon. It resolves self-intersections and overlaps in filled boundaries +and retains their full contour hierarchy. It also resolves overlapping open paths without filling them. It reads the original contour directions without changing the input or applying a preparation pass. ```csharp @@ -68,6 +68,32 @@ Polygon result = PolygonClipper.Normalize(subject, FillRule.NonZero); Clipping accepts raw contours and their fill rules directly. It does not require `Normalize` first. The positive output orientation follows [Clipper2's output convention](https://www.angusj.com/clipper2/Docs/Overview.htm). +## Open paths + +`Contour.IsClosed` controls the closing edge for both clipping and stroking. +Closed contours enclose filled areas. Open contours contain consecutive line segments with no filled interior. +Fill rules do not change open path membership. + +All clipping operations return `Polygon`. Each result contour identifies its geometry: + +- A closed contour is a filled boundary. Its first vertex is not repeated at the end. +- An open contour with two or more vertices is a line piece. +- An open contour with one vertex is an isolated point. + +Clipping splits linework at intersections and retains the cut endpoints in each resulting piece. +Ordinary source bends stay connected. An explicit line cycle remains open and retains its repeated terminal vertex. +Open contours have no parent or holes. Covered linework and points are omitted when a retained area already represents them. + +```csharp +Contour horizontal = [new Vertex(-2, 0), new Vertex(2, 0)]; +horizontal.IsClosed = false; +Contour vertical = [new Vertex(0, -2), new Vertex(0, 2)]; +vertical.IsClosed = false; + +// Return one open contour containing the crossing point (0, 0). +Polygon result = PolygonClipper.Intersection([horizontal], [vertical], FillRule.NonZero); +``` + ## Stroking `PolygonStroker` creates stroke polygons with configurable joins, caps, and width. @@ -75,8 +101,7 @@ Each source contour has an `IsClosed` property, which defaults to `true`. Set it to `false` for an open source path. Endpoint coordinates and stroke width do not select closure. One polygon can contain both open and closed stroke inputs. -Boolean operations use the filled area of each contour and implicitly close open inputs. -Both Boolean and stroke output contain closed contours without a repeated closing vertex. +Stroke output contains closed contours without a repeated closing vertex. When `NormalizeOutput` is enabled, stroke cleanup calls `Normalize` with `NonZero` filling. This preserves the raw outlines' filled area for either sign of stroke width. diff --git a/src/PolygonClipper/Contour.cs b/src/PolygonClipper/Contour.cs index 27f9af6..344086d 100644 --- a/src/PolygonClipper/Contour.cs +++ b/src/PolygonClipper/Contour.cs @@ -12,8 +12,8 @@ namespace SixLabors.PolygonClipper; /// Represents an open or closed sequence of vertices. /// /// -/// Stroking respects . Filled-area operations implicitly close the -/// contour regardless of that value. A repeated closing vertex is optional on input. +/// controls the closing edge for clipping and stroking. +/// An open contour with one vertex represents a point. A repeated closing vertex is optional for closed input. /// [DebuggerDisplay("Count = {Count}")] #pragma warning disable CA1710 // Identifiers should have correct suffix @@ -60,8 +60,9 @@ public int Count /// Gets or sets a value indicating whether the source contour is closed. /// /// - /// The default is true. Stroking respects this value. - /// Filled-area operations implicitly close the contour regardless of this value. + /// The default is . + /// When true, clipping and stroking connect the last vertex to the first vertex. + /// When false, no closing segment is added. Clipping treats the contour as lines or a point, with no filled area. /// public bool IsClosed { get; set; } = true; diff --git a/src/PolygonClipper/EndpointContribution.cs b/src/PolygonClipper/EndpointContribution.cs new file mode 100644 index 0000000..dac8b8a --- /dev/null +++ b/src/PolygonClipper/EndpointContribution.cs @@ -0,0 +1,31 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +namespace SixLabors.PolygonClipper; + +/// +/// Stores independent signed area winding and unsigned line membership. +/// +internal readonly struct EndpointContribution +{ + /// + /// The signed area contribution ending at this source endpoint. + /// + public readonly WindingCount Area; + + /// + /// The unsigned line contribution ending at this source endpoint. + /// + public readonly WindingCount Lines; + + /// + /// Initializes a new instance of the struct. + /// + /// The signed area contribution. + /// The unsigned line contribution. + public EndpointContribution(WindingCount area, WindingCount lines) + { + this.Area = area; + this.Lines = lines; + } +} diff --git a/src/PolygonClipper/Polygon.cs b/src/PolygonClipper/Polygon.cs index 8887d56..f7cf60e 100644 --- a/src/PolygonClipper/Polygon.cs +++ b/src/PolygonClipper/Polygon.cs @@ -11,7 +11,8 @@ namespace SixLabors.PolygonClipper; /// Represents a collection of contours. /// /// -/// Filled-area operations implicitly close every contour. Stroking respects each contour's closure state. +/// Each contour's closure state distinguishes filled boundaries from open paths. +/// Clipping can also return isolated points as open contours with one vertex. /// #pragma warning disable CA1710 // Identifiers should have correct suffix public sealed class Polygon : IReadOnlyCollection @@ -91,6 +92,12 @@ public void Join(Polygon polygon) } } + /// + /// Reserves space for a known result contour count without adding contours. + /// + /// The total number of contours to accommodate. + internal void EnsureCapacity(int capacity) => this.contours.EnsureCapacity(capacity); + /// /// Gets the bounding box. /// diff --git a/src/PolygonClipper/PolygonClipper.cs b/src/PolygonClipper/PolygonClipper.cs index cda015c..0929ce1 100644 --- a/src/PolygonClipper/PolygonClipper.cs +++ b/src/PolygonClipper/PolygonClipper.cs @@ -7,24 +7,27 @@ namespace SixLabors.PolygonClipper; /// -/// Performs Boolean operations on the filled areas of directed contours. +/// Performs Boolean clipping on closed filled boundaries and open paths. /// /// /// -/// Intersection, union, difference, and exclusive-or interpret the original contour directions using the selected fill rules. +/// Fill rules interpret the original directions of closed contours. Open contours have no filled interior. /// Input vertices and hierarchy are not modified. Results own their contour data. /// /// /// Instance members are not thread-safe for concurrent use. /// /// -/// Fill rules interpret the input contours. Output uses positive orientation regardless of the input rules: +/// Closed output uses positive orientation regardless of the input rules: /// counterclockwise exteriors and islands, and clockwise holes in Cartesian coordinates. /// Use NonZero, EvenOdd, or Positive filling to reuse that resolved area. -/// Contours use implicit closure without a repeated closing vertex. +/// Closed output uses implicit closure without a repeated closing vertex. +/// Open output has no closing edge. A one-vertex open contour represents an isolated point intersection. +/// Line pieces retain their cut endpoints. An explicit line cycle retains its repeated terminal vertex and remains open. /// /// /// Normalize returns the full containment hierarchy. Binary operations group each exterior contour with its holes. +/// Open output has no parent or holes. Closed-only clipping returns filled-area boundaries. /// /// /// Coordinates must be finite. Only coordinates used by an operation are validated. @@ -56,10 +59,24 @@ public class PolygonClipper private readonly SweepEventPoolList outgoing = []; private readonly SweepEventPoolList bundled = []; private readonly SweepEventPoolList pendingBoundaries = []; - private readonly Stack> endpointQueues = new(); + private readonly Stack> endpointQueues = new(); private int retainedEndpointCapacity; private int activeBoundaryCount; + // Output buffers are initialized only for open input. Live membership and + // endpoint changes stay on the source intervals held by the status line. + private List openPoints = null!; + private List openNodes = null!; + private List openEdges = null!; + private int openPointLines; + private int openPointAreas; + private bool openPointAreaBoundary; + private bool openPointAreaResult; + private bool openPointLineResult; + private int openPointNode; + private int openLineEndpoints; + private bool hasOpenContours; + private Polygon? subject; private Polygon? clipping; private BooleanOperation operation; @@ -105,98 +122,109 @@ private enum ContourOutput } /// - /// Intersects two filled areas using a common fill rule. + /// Supplies a compile-time switch for open output in the shared sweep. + /// + private interface IOpenPathMode + { + /// + /// Gets a value indicating whether the sweep collects open output. + /// + static abstract bool Enabled { get; } + } + + /// + /// Intersects two operands using a common fill rule for their closed contours. /// /// The left-hand operand. /// The right-hand operand. /// The rule interpreting both operands. - /// The filled area common to both operands. + /// The shared filled areas, open line pieces, and isolated open-path intersection points. public static Polygon Intersection(Polygon subject, Polygon clip, FillRule fillRule) => Intersection(subject, clip, fillRule, fillRule); /// - /// Intersects two filled areas using independent fill rules. + /// Intersects two operands using independent fill rules for their closed contours. /// /// The left-hand operand. /// The right-hand operand. /// The subject's fill rule. /// The clipping operand's fill rule. - /// The filled area common to both operands. + /// The shared filled areas, open line pieces, and isolated open-path intersection points. public static Polygon Intersection(Polygon subject, Polygon clip, FillRule subjectFillRule, FillRule clipFillRule) => ExecuteFillOperation(subject, clip, BooleanOperation.Intersection, subjectFillRule, clipFillRule, ContourOutput.Grouped); /// - /// Unites two filled areas using a common fill rule. + /// Unites two operands using a common fill rule for their closed contours. /// /// The left-hand operand. /// The right-hand operand. /// The rule interpreting both operands. - /// The filled area belonging to either operand. + /// The filled areas and open path pieces belonging to either operand. public static Polygon Union(Polygon subject, Polygon clip, FillRule fillRule) => Union(subject, clip, fillRule, fillRule); /// - /// Unites two filled areas using independent fill rules. + /// Unites two operands using independent fill rules for their closed contours. /// /// The left-hand operand. /// The right-hand operand. /// The subject's fill rule. /// The clipping operand's fill rule. - /// The filled area belonging to either operand. + /// The filled areas and open path pieces belonging to either operand. public static Polygon Union(Polygon subject, Polygon clip, FillRule subjectFillRule, FillRule clipFillRule) => ExecuteFillOperation(subject, clip, BooleanOperation.Union, subjectFillRule, clipFillRule, ContourOutput.Grouped); /// - /// Subtracts one filled area from another using a common fill rule. + /// Subtracts one operand from another using a common fill rule for their closed contours. /// /// The area to retain. /// The area to subtract. /// The rule interpreting both operands. - /// The subject area outside the clipping operand. + /// The subject's retained filled areas and open path pieces, including their cut endpoints. public static Polygon Difference(Polygon subject, Polygon clip, FillRule fillRule) => Difference(subject, clip, fillRule, fillRule); /// - /// Subtracts one filled area from another using independent fill rules. + /// Subtracts one operand from another using independent fill rules for their closed contours. /// /// The area to retain. /// The area to subtract. /// The subject's fill rule. /// The clipping operand's fill rule. - /// The subject area outside the clipping operand. + /// The subject's retained filled areas and open path pieces, including their cut endpoints. public static Polygon Difference(Polygon subject, Polygon clip, FillRule subjectFillRule, FillRule clipFillRule) => ExecuteFillOperation(subject, clip, BooleanOperation.Difference, subjectFillRule, clipFillRule, ContourOutput.Grouped); /// - /// Computes exclusive filled coverage using a common fill rule. + /// Computes exclusive geometry using a common fill rule for closed contours. /// /// The left-hand operand. /// The right-hand operand. /// The rule interpreting both operands. - /// The filled area belonging to exactly one operand. + /// The selected filled areas and open path pieces, including their cut endpoints. public static Polygon Xor(Polygon subject, Polygon clip, FillRule fillRule) => Xor(subject, clip, fillRule, fillRule); /// - /// Computes exclusive filled coverage using independent fill rules. + /// Computes exclusive geometry using independent fill rules for closed contours. /// /// The left-hand operand. /// The right-hand operand. /// The subject's fill rule. /// The clipping operand's fill rule. - /// The filled area belonging to exactly one operand. + /// The selected filled areas and open path pieces, including their cut endpoints. public static Polygon Xor(Polygon subject, Polygon clip, FillRule subjectFillRule, FillRule clipFillRule) => ExecuteFillOperation(subject, clip, BooleanOperation.Xor, subjectFillRule, clipFillRule, ContourOutput.Grouped); /// - /// Resolves self-intersections and overlaps using the specified fill rule. + /// Resolves self-intersections and overlaps using the specified fill rule for closed contours. /// /// The source contours. Their vertices and directions are not modified. /// The rule that determines the source polygon's filled area. /// - /// Closed contours with their full containment hierarchy. + /// Filled boundaries with their full containment hierarchy, plus uncovered open path pieces and isolated points. /// Exterior contours and islands are counterclockwise. Holes are clockwise. - /// The first vertex is not repeated at the end of a contour. + /// Closed contours do not repeat their first vertex at the end. /// /// /// The fill rule interprets the input. Output orientation is positive even when the input rule is Negative. @@ -207,19 +235,16 @@ public static Polygon Normalize(Polygon polygon, FillRule fillRule) => ExecuteFillOperation(polygon, EmptyFillOperand, BooleanOperation.Union, fillRule, FillRule.EvenOdd, ContourOutput.Nested); /// - /// Executes the configured Boolean operation using the operand fill rules. + /// Executes the configured Boolean operation using the operand fill rules for closed contours. /// - /// The connected filled boundaries. + /// The clipped filled boundaries, open paths, and isolated points. /// Instance execution is not thread-safe for concurrent use. public Polygon Run() { Polygon subject = this.subject!; Polygon clip = this.clipping!; BooleanOperation operation = this.operation; - FillRule subjectRule = this.subjectFillRule; - FillRule clipRule = this.clipFillRule; SweepEventPoolList resultEvents = this.sortedEvents; - SweepEventComparer resultComparer = this.comparer; resultEvents.Clear(); this.ResetSweep(); @@ -238,6 +263,31 @@ public Polygon Run() Box2 subjectBounds = this.ProcessSegments(subject, true); Box2 clipBounds = this.ProcessSegments(clip, false); + + // The value-type mode makes open output a compile-time choice for the JIT. + // Both modes use the same Martinez sweep. Closed-only machine code does + // not carry point/line output checks or their extra live local variables. + return this.hasOpenContours + ? this.RunSweep(subjectBounds, clipBounds) + : this.RunSweep(subjectBounds, clipBounds); + } + + /// + /// Runs the shared clipping sweep with open output enabled only for inputs that contain open contours. + /// + /// The compile-time switch for open output. + /// The subject bounds collected during ingestion. + /// The clipping bounds collected during ingestion. + /// The clipped geometry. + private Polygon RunSweep(Box2 subjectBounds, Box2 clipBounds) + where TOpenPaths : struct, IOpenPathMode + { + BooleanOperation operation = this.operation; + FillRule subjectRule = this.subjectFillRule; + FillRule clipRule = this.clipFillRule; + SweepEventPoolList resultEvents = this.sortedEvents; + SweepEventComparer resultComparer = this.comparer; + bool open = TOpenPaths.Enabled; if (operation == BooleanOperation.Intersection && !subjectBounds.Intersects(clipBounds)) { return []; @@ -269,6 +319,13 @@ public Polygon Run() } Vertex point = next.Point; + if (open) + { + this.openPointLines = this.openPointAreas = 0; + this.openPointAreaBoundary = this.openPointAreaResult = this.openPointLineResult = false; + this.openPointNode = -1; + } + bool sourcePoint = next.IsStart || point == queuedEdge.SourceEnd; this.outgoing.Clear(); this.pendingBoundaries.Clear(); @@ -276,7 +333,14 @@ public Polygon Run() int lastEnd = -1; if (next.IsStart) { - this.outgoing.Add(queuedEdge); + if (open && queuedEdge.Point == queuedEdge.SourceEnd) + { + this.ObserveOpenSource(queuedEdge); + } + else + { + this.outgoing.Add(queuedEdge); + } } else { @@ -297,7 +361,14 @@ public Polygon Run() if (valid && next.IsStart) { - this.outgoing.Add(queuedEdge); + if (open && queuedEdge.Point == queuedEdge.SourceEnd) + { + this.ObserveOpenSource(queuedEdge); + } + else + { + this.outgoing.Add(queuedEdge); + } } else if (valid) { @@ -307,6 +378,16 @@ public Polygon Run() } int first = lastEnd < 0 ? this.statusLine.FindLower(point) : firstEnd; + if (open) + { + foreach (SweepEvent source in this.outgoing) + { + this.ObserveOpenSource(source); + } + + this.ObserveOpenRegion(first == 0 ? default : this.statusLine[first - 1].Above); + } + while (first > 0 && this.statusLine[first - 1].ContainsPoint(point)) { first--; @@ -323,7 +404,7 @@ public Polygon Run() // prefix and every surviving prefix above the block stay valid. for (int i = first; i < after; i++) { - this.StageIncoming(this.statusLine[i], point); + this.StageIncoming(this.statusLine[i], point, open); } int statusCount = this.statusLine.Count; @@ -367,14 +448,14 @@ public Polygon Run() { SweepEvent incoming = this.statusLine[--first]; blockCount++; - this.StageIncoming(incoming, point); + this.StageIncoming(incoming, point, open); } if (upperIncident) { SweepEvent incoming = this.statusLine[first + blockCount]; blockCount++; - this.StageIncoming(incoming, point); + this.StageIncoming(incoming, point, open); } } @@ -396,6 +477,11 @@ public Polygon Run() winding = winding.Add(edge.Delta); edge.Above = winding; bool above = InResult(winding, operation, subjectRule, clipRule); + if (open) + { + this.SelectOpenOutgoing(edge, winding.Subtract(edge.Delta), below, above); + } + if (below != above) { // Interior crossings emit nothing and need no output @@ -459,6 +545,11 @@ public Polygon Run() } } + if (open && this.openPointLines != 0) + { + this.CompleteOpenPoint(point); + } + // Each source interval owns at most one valid queued start or end. // Above twice the interval count, at least half the heap is obsolete. // Rebuild only then, so each scan is paid for by discarded versions @@ -503,6 +594,11 @@ public Polygon Run() } } + if (open) + { + this.AppendOpenOutput(result); + } + return result; } @@ -634,10 +730,11 @@ private void Configure(Polygon subject, Polygon clip, BooleanOperation operation private int GetRetainedEventCapacityScore() => this.sortedEvents.Capacity + this.eventStorage.Capacity + this.segments.Capacity + this.statusLine.RetainedCapacity + this.outgoing.Capacity + this.bundled.Capacity + - this.pendingBoundaries.Capacity + this.retainedEndpointCapacity; + this.pendingBoundaries.Capacity + this.retainedEndpointCapacity + + (this.openPoints?.Capacity ?? 0) + (this.openNodes?.Capacity ?? 0) + (this.openEdges?.Capacity ?? 0); /// - /// Counts the edges of an implicitly closed filled boundary. + /// Counts the edges selected by a contour's explicit closure state. /// /// The contour to inspect. /// The number of segments to iterate. @@ -645,6 +742,11 @@ private int GetRetainedEventCapacityScore() private static int GetContourSegmentCount(Contour contour) { int count = contour.Count; + if (!contour.IsClosed) + { + return Math.Max(0, count - 1); + } + if (count < 3) { return 0; @@ -658,6 +760,15 @@ private static int GetContourSegmentCount(Contour contour) /// private void ResetSweep() { + if (this.hasOpenContours) + { + this.openPoints.Clear(); + this.openNodes.Clear(); + this.openEdges.Clear(); + this.openLineEndpoints = 0; + } + + this.hasOpenContours = false; this.eventStorage.Clear(); this.statusLine.Reset(0); this.outgoing.Clear(); @@ -666,7 +777,7 @@ private void ResetSweep() this.activeBoundaryCount = 0; for (int i = 0; i < this.segments.Count; i++) { - if (this.segments[i].Ends is PriorityQueue ends) + if (this.segments[i].Ends is PriorityQueue ends) { this.ReturnEndpoints(ends); } @@ -690,6 +801,35 @@ private Box2 ProcessSegments(Polygon polygon, bool subject) for (int i = 0; i < polygon.Count; i++) { Contour contour = polygon[i]; + bool open = !contour.IsClosed; + if (open && contour.Count > 0) + { + this.openPoints ??= []; + this.openNodes ??= []; + this.openEdges ??= []; + this.hasOpenContours = true; + + // Closed ingestion visits every vertex as a segment start. + // Open ingestion also validates the terminal vertex, which is + // never a start and must not bypass the public finite-coordinate contract. + Vertex terminal = contour[contour.Count - 1]; + if (!double.IsFinite(terminal.X) || !double.IsFinite(terminal.Y)) + { + throw new ArgumentException("Polygon coordinates must be finite.", nameof(polygon)); + } + + if (contour.Count == 1) + { + bounds = bounds.Add(new Box2(terminal)); + SweepEvent source = this.segments.Add(terminal, terminal, default); + source.Lines = subject ? new(1, 0) : new(0, 1); + this.eventStorage.Add(new QueueEntry(terminal, source, true)); + continue; + } + + bounds = bounds.Add(new Box2(terminal)); + } + int count = GetContourSegmentCount(contour); if (count == 0) { @@ -710,6 +850,13 @@ private Box2 ProcessSegments(Polygon polygon, bool subject) bounds = bounds.Add(new Box2(start)); if (start == end) { + if (open) + { + SweepEvent source = this.segments.Add(start, end, default); + source.Lines = subject ? new(1, 0) : new(0, 1); + this.eventStorage.Add(new QueueEntry(start, source, true)); + } + continue; } @@ -723,8 +870,15 @@ private Box2 ProcessSegments(Polygon polygon, bool subject) // Lexicographic direction is the formal x+epsilon*y sweep // direction, including vertical source segments. Epsilon is // never evaluated or applied to the stored double coordinates. - WindingCount delta = subject ? new(direction, 0) : new(0, direction); + // Open edges participate in intersection events without changing + // area winding. Their unsigned operand counts are tracked separately. + WindingCount delta = open ? default : subject ? new(direction, 0) : new(0, direction); SweepEvent edge = this.segments.Add(start, end, delta); + if (open) + { + edge.Lines = subject ? new(1, 0) : new(0, 1); + } + this.eventStorage.Add(new QueueEntry(start, edge, true)); } } @@ -737,8 +891,17 @@ private Box2 ProcessSegments(Polygon polygon, bool subject) /// /// The incident active interval. /// The staged event point. - private void StageIncoming(SweepEvent incoming, Vertex point) + /// Whether open output is collected in this sweep. + // Open-path bookkeeping pushes this method above the JIT's normal inline budget. + // Keep interval retirement in the sweep loop, as it was for closed-only clipping. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void StageIncoming(SweepEvent incoming, Vertex point, bool open) { + if (open) + { + this.StageOpenIncoming(incoming, point); + } + incoming.Active = false; incoming.Version++; incoming.EndQueued = false; @@ -758,12 +921,14 @@ private void StageIncoming(SweepEvent incoming, Vertex point) /// The complete event point. private void ContinueAt(SweepEvent incoming, Vertex point) { - if (incoming.Ends is PriorityQueue ends) + if (incoming.Ends is PriorityQueue ends) { WindingCount delta = incoming.Delta; - while (ends.TryPeek(out WindingCount ending, out Vertex endpoint) && endpoint == point) + WindingCount lines = incoming.Lines; + while (ends.TryPeek(out EndpointContribution ending, out Vertex endpoint) && endpoint == point) { - delta = delta.Subtract(ending); + delta = delta.Subtract(ending.Area); + lines = lines.Subtract(ending.Lines); ends.Dequeue(); } @@ -775,6 +940,7 @@ private void ContinueAt(SweepEvent incoming, Vertex point) } incoming.Delta = delta; + incoming.Lines = lines; incoming.SourceEnd = FirstEndpoint(ends); } else if (SweepEventComparer.Instance.Compare(point, incoming.SourceEnd) >= 0) @@ -841,22 +1007,23 @@ private void BundleOutgoing() { // The common duplicate-edge case needs no endpoint ledger. edge.Delta = edge.Delta.Add(other.Delta); + edge.Lines = edge.Lines.Add(other.Lines); continue; } if (edge.Ends is null) { edge.Ends = this.RentEndpoints(); - if (!edge.Delta.IsZero) + if (!edge.Delta.IsZero || !edge.Lines.IsZero) { - edge.Ends.Enqueue(edge.Delta, edge.SourceEnd); + edge.Ends.Enqueue(new EndpointContribution(edge.Delta, edge.Lines), edge.SourceEnd); } } - PriorityQueue ends = edge.Ends; - if (other.Ends is PriorityQueue otherEnds) + PriorityQueue ends = edge.Ends; + if (other.Ends is PriorityQueue otherEnds) { - foreach ((WindingCount delta, Vertex endpoint) in otherEnds.UnorderedItems) + foreach ((EndpointContribution delta, Vertex endpoint) in otherEnds.UnorderedItems) { ends.Enqueue(delta, endpoint); } @@ -864,15 +1031,16 @@ private void BundleOutgoing() other.Ends = null; this.ReturnEndpoints(otherEnds); } - else if (!other.Delta.IsZero) + else if (!other.Delta.IsZero || !other.Lines.IsZero) { - ends.Enqueue(other.Delta, other.SourceEnd); + ends.Enqueue(new EndpointContribution(other.Delta, other.Lines), other.SourceEnd); } edge.Delta = edge.Delta.Add(other.Delta); + edge.Lines = edge.Lines.Add(other.Lines); } - if (edge.Ends is PriorityQueue ledger) + if (edge.Ends is PriorityQueue ledger) { if (ledger.Count == 0) { @@ -887,7 +1055,7 @@ private void BundleOutgoing() edge.End = edge.SourceEnd; } } - else if (edge.Delta.IsZero) + else if (edge.Delta.IsZero && edge.Lines.IsZero) { continue; } @@ -903,7 +1071,7 @@ private void BundleOutgoing() /// /// The non-empty endpoint queue. /// The earliest endpoint. - private static Vertex FirstEndpoint(PriorityQueue ends) + private static Vertex FirstEndpoint(PriorityQueue ends) { ends.TryPeek(out _, out Vertex endpoint); return endpoint; @@ -913,9 +1081,9 @@ private static Vertex FirstEndpoint(PriorityQueue ends) /// Rents endpoint storage without allocating tree nodes for each contribution. /// /// An empty reusable priority queue. - private PriorityQueue RentEndpoints() + private PriorityQueue RentEndpoints() { - if (this.endpointQueues.TryPop(out PriorityQueue? ends)) + if (this.endpointQueues.TryPop(out PriorityQueue? ends)) { this.retainedEndpointCapacity -= ends.EnsureCapacity(0); return ends; @@ -928,7 +1096,7 @@ private PriorityQueue RentEndpoints() /// Returns endpoint storage after its interval releases ownership. /// /// The queue no longer referenced by a live interval. - private void ReturnEndpoints(PriorityQueue ends) + private void ReturnEndpoints(PriorityQueue ends) { // Retain the array for the next bundle. Include it in the clipper's // capacity limit so a large overlap cannot pin unbounded scratch storage. @@ -1036,6 +1204,10 @@ private void DivideSegment(SweepEvent edge, Vertex intersection, Vertex current) // crossing on the same x coordinate. Represent that piece as a // new forward interval with the opposite signed contribution. SweepEvent tail = this.segments.Add(edge.SourceEnd, intersection, default(WindingCount).Subtract(edge.Delta)); + + // Line membership is unsigned even when this tiny area contribution reverses. + tail.Lines = edge.Lines; + this.events.Enqueue(new QueueEntry(tail.Point, tail, true)); edge.SourceEnd = intersection; } @@ -1057,7 +1229,7 @@ private void DivideSegment(SweepEvent edge, Vertex intersection, Vertex current) /// The clipping operand's fill rule. /// Whether the region belongs to the result. [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static bool InResult(WindingCount count, BooleanOperation operation, FillRule subjectRule, FillRule clipRule) + internal static bool InResult(WindingCount count, BooleanOperation operation, FillRule subjectRule, FillRule clipRule) { return operation switch { @@ -1075,7 +1247,7 @@ private static bool InResult(WindingCount count, BooleanOperation operation, Fil /// The validated fill rule. /// Whether the region is filled. [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static bool Filled(int count, FillRule rule) + internal static bool Filled(int count, FillRule rule) => rule switch { FillRule.EvenOdd => (count & 1) != 0, @@ -1426,103 +1598,338 @@ private static int NextPos( } /// - /// Stores separate subject and clip contributions without cross-operand cancellation. + /// Retains an isolated point or marks the line junctions at a completed event. /// - internal readonly struct WindingCount + /// The completed event point. + private void CompleteOpenPoint(Vertex point) { - /// - /// The subject winding. - /// - public readonly int Subject; + if (this.openPointNode >= 0) + { + ref OpenNode node = ref CollectionsMarshal.AsSpan(this.openNodes)[this.openPointNode]; + node.Split = this.openPointLines == 3 || this.openPointAreaBoundary; + if (node.Degree != 2 || node.Split) + { + this.openLineEndpoints += node.Degree; + } + } - /// - /// The clipping operand winding. - /// - public readonly int Clip; + int membership = this.openPointLines | this.openPointAreas; + if (!this.openPointAreaResult && !this.openPointLineResult && SelectOpenMembership((membership & 1) != 0, (membership & 2) != 0, this.operation)) + { + this.openPoints.Add(point); + } + } - /// - /// Initializes a new instance of the struct. - /// - /// The subject component. - /// The clipping component. - public WindingCount(int subject, int clip) + /// + /// Completes an open output piece before its live interval is continued or reused. + /// + /// The incoming interval. + /// The completed endpoint. + private void StageOpenIncoming(SweepEvent incoming, Vertex point) + { + // Keep open output construction outside the closed-only sweep's hot loop. + // The same sweep supplies its completed points, intervals, and area membership. + this.ObserveOpenSource(incoming); + this.ObserveOpenRegion(incoming.Above); + this.ObserveOpenRegion(incoming.Above.Subtract(incoming.Delta)); + if (incoming.LineIncluded && incoming.Point != point) { - this.Subject = subject; - this.Clip = clip; + int end = this.GetOpenPointNode(point); + ref OpenNode first = ref CollectionsMarshal.AsSpan(this.openNodes)[incoming.LineStartNode]; + ref OpenNode last = ref CollectionsMarshal.AsSpan(this.openNodes)[end]; + int index = this.openEdges.Count; + this.openEdges.Add(new OpenEdge(incoming.LineStartNode, end, first.First, last.First)); + first.First = last.First = index; + last.Degree++; + this.openPointLineResult = true; } - /// - /// Gets a value indicating whether both contributions cancel. - /// - public bool IsZero => this.Subject == 0 && this.Clip == 0; + incoming.LineIncluded = false; + } + + /// + /// Selects an outgoing line piece and reserves its output incidence at this event. + /// + /// The outgoing interval. + /// The area winding below the interval. + /// Whether the result contains the area below the interval. + /// Whether the result contains the area above the interval. + private void SelectOpenOutgoing(SweepEvent edge, WindingCount areaWindingBelow, bool areaBelow, bool areaAbove) + { + this.ObserveOpenSource(edge); + this.ObserveOpenRegion(areaWindingBelow); + this.ObserveOpenRegion(edge.Above); + if (edge.Lines.IsZero) + { + edge.LineIncluded = false; + } + else + { + // A boundary belongs to a filled operand when either adjacent sector + // is filled. A retained area already represents any line on its boundary. + bool lineSubject = edge.Lines.Subject > 0 || Filled(areaWindingBelow.Subject, this.subjectFillRule) || + Filled(edge.Above.Subject, this.subjectFillRule); + bool lineClip = edge.Lines.Clip > 0 || Filled(areaWindingBelow.Clip, this.clipFillRule) || + Filled(edge.Above.Clip, this.clipFillRule); + edge.LineIncluded = !areaBelow && !areaAbove && SelectOpenMembership(lineSubject, lineClip, this.operation); + if (edge.LineIncluded) + { + edge.LineStartNode = this.GetOpenPointNode(edge.Point); + + // The completed point already knows each selected outgoing ray. + // Count its incidence now; its adjacency link is completed when + // the interval ends. No coordinate dictionary or second pass is needed. + CollectionsMarshal.AsSpan(this.openNodes)[edge.LineStartNode].Degree++; + } + } + + this.openPointLineResult |= edge.LineIncluded; + } + + /// + /// Includes a source endpoint or a one-vertex input in the current point event. + /// + /// The incident source interval. + private void ObserveOpenSource(SweepEvent edge) + { + WindingCount lines = edge.Lines; + this.openPointLines |= (lines.Subject > 0 ? 1 : 0) | (lines.Clip > 0 ? 2 : 0); + this.openPointAreaBoundary |= !edge.Delta.IsZero; + } + + /// + /// Records filled sectors without treating line contributions as winding. + /// + /// The winding in an incident sector. + private void ObserveOpenRegion(WindingCount winding) + { + this.openPointAreas |= (Filled(winding.Subject, this.subjectFillRule) ? 1 : 0) | + (Filled(winding.Clip, this.clipFillRule) ? 2 : 0); + this.openPointAreaResult |= InResult(winding, this.operation, this.subjectFillRule, this.clipFillRule); + } + + /// + /// Applies the Boolean operation to line or point membership without signed area winding. + /// + /// Whether the subject contains this location. + /// Whether the clipping operand contains this location. + /// The Boolean operation. + /// Whether this location belongs to the result. + private static bool SelectOpenMembership(bool subject, bool clip, BooleanOperation operation) + => InResult(new(subject ? 1 : 0, clip ? 1 : 0), operation, FillRule.NonZero, FillRule.NonZero); + + /// + /// Appends open contours and isolated points after the closed contours have their final hierarchy indices. + /// + /// The result that owns the generated contours. + private void AppendOpenOutput(Polygon result) + { + // Every non-cycle line has two endpoint incidences. Complete-point + // processing counted them, so reserve their contours without another + // graph scan. Endpoint-free cycles can grow the result normally. + result.EnsureCapacity(result.Count + (this.openLineEndpoints / 2) + this.openPoints.Count); + + // Join ordinary degree-two source vertices. Every intersection node + // and branch remains an endpoint, so separate pieces retain their cut vertex. + for (int i = 0; i < this.openNodes.Count; i++) + { + OpenNode node = this.openNodes[i]; + if (node.Degree == 2 && !node.Split) + { + continue; + } + + int edge = node.First; + while (edge >= 0) + { + if (!this.openEdges[edge].Visited) + { + result.Add(this.TraceOpenPath(i, edge)); + } + + edge = this.NextOpenEdge(edge, i); + } + } + + // A line can form a cycle without an implicit closing edge. Trace the + // remaining cycles and retain their explicit terminal source vertex. + for (int i = 0; i < this.openEdges.Count; i++) + { + if (!this.openEdges[i].Visited) + { + result.Add(this.TraceOpenPath(this.openEdges[i].Start, i)); + } + } + + foreach (Vertex point in this.openPoints) + { + Contour contour = new(1) { IsClosed = false }; + contour.Add(point); + result.Add(contour); + } + } + /// + /// Gets the current complete point's output node without a coordinate lookup. + /// + /// The shared endpoint. + /// The stable output node index. + private int GetOpenPointNode(Vertex point) + { + if (this.openPointNode < 0) + { + // The sweep completes every incidence at this exact point before + // advancing. All selected rays therefore share this one node index. + this.openPointNode = this.openNodes.Count; + this.openNodes.Add(new OpenNode(point)); + } + + return this.openPointNode; + } + + /// + /// Gets the next edge in one node's incident list. + /// + /// The current incident edge. + /// The node owning this adjacency list. + /// The next incident edge index, or -1 at the end. + private int NextOpenEdge(int edge, int node) + { + OpenEdge current = this.openEdges[edge]; + return current.Start == node ? current.NextStart : current.NextEnd; + } + + /// + /// Traces a maximal unbranched line between cut endpoints. + /// + /// The first node. + /// The first unvisited incident edge. + /// An open contour that owns its vertices. + private Contour TraceOpenPath(int start, int index) + { + Contour contour = new(2) { IsClosed = false }; + contour.Add(this.openNodes[start].Point); + int node = start; + while (true) + { + ref OpenEdge edge = ref CollectionsMarshal.AsSpan(this.openEdges)[index]; + edge.Visited = true; + node = edge.Start == node ? edge.End : edge.Start; + OpenNode next = this.openNodes[node]; + contour.Add(next.Point); + if (node == start || next.Degree != 2 || next.Split) + { + return contour; + } + + index = next.First == index ? this.NextOpenEdge(index, node) : next.First; + } + } + + /// + /// Removes open output work when the JIT compiles the closed-only sweep. + /// + private readonly struct WithoutOpenPaths : IOpenPathMode + { /// - /// Adds an interval's contribution. + /// Gets a value indicating whether the sweep collects open output. /// - /// The contribution to add. - /// The summed winding. - public WindingCount Add(WindingCount other) => new(this.Subject + other.Subject, this.Clip + other.Clip); + public static bool Enabled => false; + } + /// + /// Includes open output work when the JIT compiles the shared sweep. + /// + private readonly struct WithOpenPaths : IOpenPathMode + { /// - /// Removes contributions terminating at an endpoint. + /// Gets a value indicating whether the sweep collects open output. /// - /// The terminating contributions. - /// The remaining winding. - public WindingCount Subtract(WindingCount other) => new(this.Subject - other.Subject, this.Clip - other.Clip); + public static bool Enabled => true; } /// - /// Stores a versioned endpoint in the existing priority queue. + /// Stores the incident output edges of one exact vertex. /// - internal readonly struct QueueEntry + private struct OpenNode { /// - /// The queued geometric point. + /// The node coordinate. /// - public readonly Vertex Point; + public Vertex Point; /// - /// The source pool index, complemented for a start record. + /// The first incident edge index, or -1 for a new node. /// - private readonly int sourceIndex; + public int First; /// - /// The interval version when queued. + /// The number of incident output edges. /// - public readonly int Version; + public int Degree; /// - /// Initializes a new instance of the struct. + /// Whether this event must remain a cut endpoint. /// - /// The endpoint. - /// The interval. - /// Whether the record starts the interval. - public QueueEntry(Vertex point, SweepEvent edge, bool isStart) + public bool Split; + + /// + /// Initializes a new instance of the struct. + /// + /// The exact output vertex. + public OpenNode(Vertex point) { this.Point = point; - - // Pool indices remain stable until the operation ends. Encoding - // start/end in their sign keeps every version bit and removes the - // managed reference, so heap movement needs no GC write barriers. - this.sourceIndex = isStart ? ~edge.ContourId : edge.ContourId; - this.Version = edge.Version; + this.First = -1; + this.Degree = 0; + this.Split = false; } + } + + /// + /// Stores one undirected line piece and its two adjacency links. + /// + private struct OpenEdge + { + /// + /// The first endpoint's node index. + /// + public int Start; + + /// + /// The second endpoint's node index. + /// + public int End; + + /// + /// The next edge incident to Start. + /// + public int NextStart; /// - /// Gets a value indicating whether this record starts a source interval. + /// The next edge incident to End. /// - public bool IsStart => this.sourceIndex < 0; + public int NextEnd; /// - /// Gets the stable index in the source interval pool. + /// Whether output traversal has consumed this edge. /// - public int EdgeIndex => this.sourceIndex < 0 ? ~this.sourceIndex : this.sourceIndex; + public bool Visited; /// - /// Checks whether the source interval still owns this queued record. + /// Initializes a new instance of the struct. /// - /// The interval at . - /// Whether the interval version and activity match. - public bool IsValid(SweepEvent edge) => this.Version == edge.Version && (this.IsStart || edge.Active); + /// The first endpoint index. + /// The second endpoint index. + /// The previous adjacency head at Start. + /// The previous adjacency head at End. + public OpenEdge(int start, int end, int nextStart, int nextEnd) + { + this.Start = start; + this.End = end; + this.NextStart = nextStart; + this.NextEnd = nextEnd; + this.Visited = false; + } } } diff --git a/src/PolygonClipper/PolygonUtilities.cs b/src/PolygonClipper/PolygonUtilities.cs index 7cd002f..8c4cc32 100644 --- a/src/PolygonClipper/PolygonUtilities.cs +++ b/src/PolygonClipper/PolygonUtilities.cs @@ -1,7 +1,6 @@ // Copyright (c) Six Labors. // Licensed under the Six Labors Split License. -using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -64,7 +63,7 @@ public static int FindIntersection(in Segment seg0, in Segment seg1, out Vertex pi0 = default; pi1 = default; - if (!TryGetIntersectionBoundingBox(seg0.Source, seg0.Target, seg1.Source, seg1.Target, out Box2? bbox)) + if (!TryGetIntersectionBoundingBox(seg0.Source, seg0.Target, seg1.Source, seg1.Target, out Box2 bbox)) { return 0; } @@ -72,10 +71,13 @@ public static int FindIntersection(in Segment seg0, in Segment seg1, out Vertex // A vertical segment and a horizontal segment intersect at existing // source coordinates. The overlapping bounds identify that point // exactly, so determinant construction and division add no information. - if ((seg0.IsVertical() && seg1.Source.Y == seg1.Target.Y) || - (seg1.IsVertical() && seg0.Source.Y == seg0.Target.Y)) + // Their overlap has zero width. Most diagonal crossings can skip the + // axis checks using bounds that the intersection already requires. + if (bbox.Min.X == bbox.Max.X && + ((seg0.IsVertical() && seg1.Source.Y == seg1.Target.Y) || + (seg1.IsVertical() && seg0.Source.Y == seg0.Target.Y))) { - pi0 = bbox.Value.Min; + pi0 = bbox.Min; return 1; } @@ -83,12 +85,12 @@ public static int FindIntersection(in Segment seg0, in Segment seg1, out Vertex if (interResult == 1) { - pi0 = ConstrainToBoundingBox(pi0, bbox.Value); + pi0 = ConstrainToBoundingBox(pi0, bbox); } else if (interResult == 2) { - pi0 = ConstrainToBoundingBox(pi0, bbox.Value); - pi1 = ConstrainToBoundingBox(pi1, bbox.Value); + pi0 = ConstrainToBoundingBox(pi0, bbox); + pi1 = ConstrainToBoundingBox(pi1, bbox); } return interResult; @@ -224,7 +226,7 @@ private static int FindIntersectionImpl(in Segment seg0, in Segment seg1, out Ve /// The second point of the first segment. /// The first point of the second segment. /// The second point of the second segment. - /// The intersection bounding box if one exists, otherwise null. + /// The intersection bounds when the method returns true. /// /// if the segments intersect; otherwise, . /// @@ -233,7 +235,7 @@ private static bool TryGetIntersectionBoundingBox( in Vertex a2, in Vertex b1, in Vertex b2, - [NotNullWhen(true)] out Box2? result) + out Box2 result) { Vertex minA = Vertex.Min(a1, a2); Vertex maxA = Vertex.Max(a1, a2); @@ -249,7 +251,7 @@ private static bool TryGetIntersectionBoundingBox( return true; } - result = null; + result = default; return false; } diff --git a/src/PolygonClipper/QueueEntry.cs b/src/PolygonClipper/QueueEntry.cs new file mode 100644 index 0000000..07bf77a --- /dev/null +++ b/src/PolygonClipper/QueueEntry.cs @@ -0,0 +1,59 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +namespace SixLabors.PolygonClipper; + +/// +/// Stores a versioned endpoint in the existing priority queue. +/// +internal readonly struct QueueEntry +{ + /// + /// The queued geometric point. + /// + public readonly Vertex Point; + + /// + /// The source pool index, complemented for a start record. + /// + private readonly int sourceIndex; + + /// + /// The interval version when queued. + /// + public readonly int Version; + + /// + /// Initializes a new instance of the struct. + /// + /// The endpoint. + /// The interval. + /// Whether the record starts the interval. + public QueueEntry(Vertex point, SweepEvent edge, bool isStart) + { + this.Point = point; + + // Pool indices remain stable until the operation ends. Encoding + // start/end in their sign keeps every version bit and removes the + // managed reference, so heap movement needs no GC write barriers. + this.sourceIndex = isStart ? ~edge.ContourId : edge.ContourId; + this.Version = edge.Version; + } + + /// + /// Gets a value indicating whether this record starts a source interval. + /// + public bool IsStart => this.sourceIndex < 0; + + /// + /// Gets the stable index in the source interval pool. + /// + public int EdgeIndex => this.sourceIndex < 0 ? ~this.sourceIndex : this.sourceIndex; + + /// + /// Checks whether the source interval still owns this queued record. + /// + /// The interval at . + /// Whether the interval version and activity match. + public bool IsValid(SweepEvent edge) => this.Version == edge.Version && (this.IsStart || edge.Active); +} diff --git a/src/PolygonClipper/SweepEvent.cs b/src/PolygonClipper/SweepEvent.cs index 49cd856..8e6fcc8 100644 --- a/src/PolygonClipper/SweepEvent.cs +++ b/src/PolygonClipper/SweepEvent.cs @@ -120,17 +120,32 @@ public Vertex End /// /// Gets or sets the signed subject and clip contributions of this interval. /// - public PolygonClipper.WindingCount Delta { get => this.interval.Delta; set => this.interval.Delta = value; } + public WindingCount Delta { get => this.interval.Delta; set => this.interval.Delta = value; } + + /// + /// Gets or sets the unsigned open-path contributions from each operand. + /// + public WindingCount Lines { get => this.interval.Lines; set => this.interval.Lines = value; } + + /// + /// Gets or sets a value indicating whether this interval contributes an open output piece. + /// + public bool LineIncluded { get => this.interval.LineIncluded; set => this.interval.LineIncluded = value; } + + /// + /// Gets or sets the output node where the selected open piece starts. + /// + public int LineStartNode { get => this.interval.LineStartNode; set => this.interval.LineStartNode = value; } /// /// Gets or sets the winding immediately above this live interval. /// - public PolygonClipper.WindingCount Above { get => this.interval.Above; set => this.interval.Above = value; } + public WindingCount Above { get => this.interval.Above; set => this.interval.Above = value; } /// /// Gets or sets the endpoint changes retained for a coincident bundle. /// - public PriorityQueue Ends { get => this.interval.Ends; set => this.interval.Ends = value; } + public PriorityQueue Ends { get => this.interval.Ends; set => this.interval.Ends = value; } /// /// Gets or sets the immutable output record for the current contributing piece. @@ -261,7 +276,7 @@ public bool ContainsPoint(Vertex point) /// The source endpoint. /// The stable interval identity. /// The signed operand contributions. - public void InitializeInterval(Vertex start, Vertex end, int id, PolygonClipper.WindingCount delta) + public void InitializeInterval(Vertex start, Vertex end, int id, WindingCount delta) { this.interval ??= new IntervalState(); this.Point = start; @@ -270,6 +285,9 @@ public void InitializeInterval(Vertex start, Vertex end, int id, PolygonClipper. this.SourceEnd = end; this.Support = new Segment(start, end); this.Delta = delta; + this.Lines = default; + this.LineIncluded = false; + this.LineStartNode = 0; this.Above = default; this.Ends = null; this.Boundary = null; @@ -322,17 +340,32 @@ private sealed class IntervalState /// /// Gets or sets the signed subject and clip contributions of this interval. /// - public PolygonClipper.WindingCount Delta { get; set; } + public WindingCount Delta { get; set; } + + /// + /// Gets or sets the unsigned open-path contributions from each operand. + /// + public WindingCount Lines { get; set; } + + /// + /// Gets or sets a value indicating whether this interval contributes an open output piece. + /// + public bool LineIncluded { get; set; } + + /// + /// Gets or sets the output node where the selected open piece starts. + /// + public int LineStartNode { get; set; } /// /// Gets or sets the winding immediately above this live interval. /// - public PolygonClipper.WindingCount Above { get; set; } + public WindingCount Above { get; set; } /// /// Gets or sets the endpoint changes retained for a coincident bundle. /// - public PriorityQueue Ends { get; set; } + public PriorityQueue Ends { get; set; } /// /// Gets or sets the immutable output record for the current contributing piece. diff --git a/src/PolygonClipper/SweepEventComparer.cs b/src/PolygonClipper/SweepEventComparer.cs index 88b9ff0..b649f15 100644 --- a/src/PolygonClipper/SweepEventComparer.cs +++ b/src/PolygonClipper/SweepEventComparer.cs @@ -8,7 +8,7 @@ namespace SixLabors.PolygonClipper; /// /// Compares two instances for sorting in the event queue. /// -internal sealed class SweepEventComparer : IComparer, IComparer, IComparer, IComparer +internal sealed class SweepEventComparer : IComparer, IComparer, IComparer, IComparer { /// /// The shared comparer for point, queue, and boundary event order. @@ -82,7 +82,7 @@ public int Compare(SweepEvent? x, SweepEvent? y) } /// - public int Compare(PolygonClipper.QueueEntry x, PolygonClipper.QueueEntry y) + public int Compare(QueueEntry x, QueueEntry y) { int order = this.Compare(x.Point, y.Point); if (order == 0) diff --git a/src/PolygonClipper/SweepEventPoolList.cs b/src/PolygonClipper/SweepEventPoolList.cs index 8150eb6..73dd09e 100644 --- a/src/PolygonClipper/SweepEventPoolList.cs +++ b/src/PolygonClipper/SweepEventPoolList.cs @@ -19,7 +19,7 @@ internal sealed class SweepEventPoolList : PooledList /// The source terminal point. /// The signed operand contributions. /// The initialized live interval. - public SweepEvent Add(Vertex start, Vertex end, PolygonClipper.WindingCount delta) + public SweepEvent Add(Vertex start, Vertex end, WindingCount delta) { this.TryGrow(); SweepEvent segment = this.Items[this.Size]; diff --git a/src/PolygonClipper/WindingCount.cs b/src/PolygonClipper/WindingCount.cs new file mode 100644 index 0000000..080b6ed --- /dev/null +++ b/src/PolygonClipper/WindingCount.cs @@ -0,0 +1,50 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +namespace SixLabors.PolygonClipper; + +/// +/// Stores separate subject and clip contributions without cross-operand cancellation. +/// +internal readonly struct WindingCount +{ + /// + /// The subject winding. + /// + public readonly int Subject; + + /// + /// The clipping operand winding. + /// + public readonly int Clip; + + /// + /// Initializes a new instance of the struct. + /// + /// The subject component. + /// The clipping component. + public WindingCount(int subject, int clip) + { + this.Subject = subject; + this.Clip = clip; + } + + /// + /// Gets a value indicating whether both contributions cancel. + /// + public bool IsZero => this.Subject == 0 && this.Clip == 0; + + /// + /// Adds an interval's contribution. + /// + /// The contribution to add. + /// The summed winding. + public WindingCount Add(WindingCount other) => new(this.Subject + other.Subject, this.Clip + other.Clip); + + /// + /// Removes contributions terminating at an endpoint. + /// + /// The terminating contributions. + /// The remaining winding. + public WindingCount Subtract(WindingCount other) => new(this.Subject - other.Subject, this.Clip - other.Clip); +} diff --git a/tests/PolygonClipper.Benchmarks/OpenClippingBenches.cs b/tests/PolygonClipper.Benchmarks/OpenClippingBenches.cs new file mode 100644 index 0000000..4dace0c --- /dev/null +++ b/tests/PolygonClipper.Benchmarks/OpenClippingBenches.cs @@ -0,0 +1,163 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +using BenchmarkDotNet.Attributes; +using Clipper2Lib; + +namespace SixLabors.PolygonClipper.Benchmarks; + +/// +/// Compares open line clipping against the same closed rectangle and hole. +/// +[MemoryDiagnoser] +[OperationsPerSecond] +public class OpenClippingBenches +{ + private Polygon subject = null!; + private Polygon clip = null!; + private PathsD openSubject = null!; + private PathsD closedClip = null!; + + /// + /// Gets or sets the number of independent source paths. + /// + [Params(10, 1000)] + public int PathCount { get; set; } + + /// + /// Gets or sets the number of vertices in each source path. + /// + [Params(2, 13)] + public int VerticesPerPath { get; set; } + + /// + /// Gets or sets whether both operands exchange their x and y coordinates. + /// + [Params(false, true)] + public bool Transpose { get; set; } + + /// + /// Builds equal input geometry and checks exact output edges before measurement. + /// + [GlobalSetup] + public void Setup() + { + this.subject = new(this.PathCount); + this.openSubject = new(this.PathCount); + for (int i = 0; i < this.PathCount; i++) + { + Contour contour = new(this.VerticesPerPath) { IsClosed = false }; + PathD path = new(this.VerticesPerPath); + for (int j = 0; j < this.VerticesPerPath; j++) + { + double x = -100D + (1200D * j / (this.VerticesPerPath - 1)); + double y = (i * 100D) + 25D + (this.VerticesPerPath == 2 ? 0D : (j & 1) * 25D); + if (this.Transpose) + { + (x, y) = (y, x); + } + + contour.Add(new Vertex(x, y)); + path.Add(new PointD(x, y)); + } + + this.subject.Add(contour); + this.openSubject.Add(path); + } + + double height = this.PathCount * 100D; + Contour exterior = [new(0, 0), new(1000, 0), new(1000, height), new(0, height)]; + Contour hole = [new(300, height * 0.25D), new(300, height * 0.75D), new(700, height * 0.75D), new(700, height * 0.25D)]; + this.clip = new(2); + this.closedClip = new(2); + foreach (Contour contour in new[] { exterior, hole }) + { + PathD path = new(contour.Count); + Contour transformed = new(contour.Count); + foreach (Vertex vertex in contour) + { + Vertex point = this.Transpose ? new(vertex.Y, vertex.X) : vertex; + path.Add(new PointD(point.X, point.Y)); + transformed.Add(point); + } + + this.closedClip.Add(path); + this.clip.Add(transformed); + } + + Polygon result = (Polygon)this.PolygonClipperIntersection(); + PathsD expected = (PathsD)this.Clipper2Intersection(); + List<(double X1, double Y1, double X2, double Y2)> actualEdges = []; + foreach (Contour contour in result) + { + if (contour.IsClosed) + { + throw new InvalidOperationException("Open-subject intersection returned an area contour."); + } + + for (int i = 1; i < contour.Count; i++) + { + AddEdge(actualEdges, contour[i - 1].X, contour[i - 1].Y, contour[i].X, contour[i].Y); + } + } + + List<(double X1, double Y1, double X2, double Y2)> expectedEdges = []; + foreach (PathD path in expected) + { + for (int i = 1; i < path.Count; i++) + { + AddEdge(expectedEdges, path[i - 1].x, path[i - 1].y, path[i].x, path[i].y); + } + } + + actualEdges.Sort(); + expectedEdges.Sort(); + if (!actualEdges.SequenceEqual(expectedEdges)) + { + throw new InvalidOperationException("The benchmark inputs did not produce equivalent open output edges."); + } + } + + /// + /// Clips the original open paths with the closed mask using Martinez. + /// + /// The open result contours. + [Benchmark] + public object PolygonClipperIntersection() => PolygonClipper.Intersection(this.subject, this.clip, FillRule.NonZero); + + /// + /// Clips the same original paths with the same closed mask using Clipper2. + /// + /// The open result paths. + [Benchmark(Baseline = true)] + public object Clipper2Intersection() + { + ClipperD engine = new(6); + engine.AddOpenSubject(this.openSubject); + engine.AddClip(this.closedClip); + PathsD closed = []; + PathsD open = []; + engine.Execute(ClipType.Intersection, Clipper2Lib.FillRule.NonZero, closed, open); + return open; + } + + /// + /// Adds a direction-independent edge without rounding coordinates or changing subdivisions. + /// + /// The collected output edges. + /// The first endpoint's x coordinate. + /// The first endpoint's y coordinate. + /// The second endpoint's x coordinate. + /// The second endpoint's y coordinate. + private static void AddEdge(List<(double X1, double Y1, double X2, double Y2)> edges, double x1, double y1, double x2, double y2) + { + if (x1 < x2 || (x1 == x2 && y1 <= y2)) + { + edges.Add((x1, y1, x2, y2)); + } + else + { + edges.Add((x2, y2, x1, y1)); + } + } +} diff --git a/tests/PolygonClipper.Tests/OpenPathClippingTests.cs b/tests/PolygonClipper.Tests/OpenPathClippingTests.cs new file mode 100644 index 0000000..b28d070 --- /dev/null +++ b/tests/PolygonClipper.Tests/OpenPathClippingTests.cs @@ -0,0 +1,455 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +namespace SixLabors.PolygonClipper.Tests; + +/// +/// Checks open clipping against exact segment and rectangle constructions. +/// +public class OpenPathClippingTests +{ + /// + /// Checks a crossing point and the line pieces selected by each Boolean operation. + /// + /// The requested operation. + [Theory] + [InlineData(BooleanOperation.Intersection)] + [InlineData(BooleanOperation.Union)] + [InlineData(BooleanOperation.Difference)] + [InlineData(BooleanOperation.Xor)] + public void CrossingLines_ReturnPointOrCutContours(BooleanOperation operation) + { + Vertex left = new(-2, 0); + Vertex right = new(2, 0); + Vertex bottom = new(0, -2); + Vertex top = new(0, 2); + Vertex point = new(0, 0); + Polygon subject = [Open(left, right)]; + Polygon clip = [Open(bottom, top)]; + + Polygon result = Execute(subject, clip, operation); + if (operation == BooleanOperation.Intersection) + { + Contour intersection = Assert.Single(result); + Assert.False(intersection.IsClosed); + Assert.Equal(point, Assert.Single(intersection)); + } + else if (operation == BooleanOperation.Difference) + { + AssertLines(result, (left, point), (point, right)); + } + else + { + AssertLines(result, (left, point), (point, right), (bottom, point), (point, top)); + } + + Assert.Equal([left, right], subject[0]); + Assert.Equal([bottom, top], clip[0]); + Assert.False(subject[0].IsClosed); + Assert.False(clip[0].IsClosed); + } + + /// + /// Checks overlapping line membership without using signed area or input direction. + /// + /// The requested operation. + /// Whether the second input runs in reverse. + [Theory] + [InlineData(BooleanOperation.Intersection, false)] + [InlineData(BooleanOperation.Intersection, true)] + [InlineData(BooleanOperation.Union, false)] + [InlineData(BooleanOperation.Union, true)] + [InlineData(BooleanOperation.Difference, false)] + [InlineData(BooleanOperation.Difference, true)] + [InlineData(BooleanOperation.Xor, false)] + [InlineData(BooleanOperation.Xor, true)] + public void CollinearOverlap_UsesLineMembership(BooleanOperation operation, bool reverse) + { + Vertex a = new(0, 0); + Vertex b = new(5, 0); + Vertex c = new(10, 0); + Vertex d = new(15, 0); + Contour second = reverse ? Open(d, b) : Open(b, d); + + Polygon result = Execute([Open(a, c)], [second], operation); + switch (operation) + { + case BooleanOperation.Intersection: + AssertLines(result, (b, c)); + break; + case BooleanOperation.Difference: + AssertLines(result, (a, b)); + break; + case BooleanOperation.Xor: + AssertLines(result, (a, b), (c, d)); + break; + default: + AssertLines(result, (a, b), (b, c), (c, d)); + break; + } + } + + /// + /// Checks that open membership does not depend on an area fill rule. + /// + /// The selected area fill rule. + [Theory] + [InlineData(FillRule.EvenOdd)] + [InlineData(FillRule.NonZero)] + [InlineData(FillRule.Positive)] + [InlineData(FillRule.Negative)] + public void OpenInputs_DoNotAcquireAreaWinding(FillRule rule) + { + Polygon result = PolygonClipper.Intersection( + [Open(new(-1, 0), new(1, 0))], [Open(new(0, -1), new(0, 1))], rule); + + Assert.Equal(new Vertex(0, 0), Assert.Single(Assert.Single(result))); + } + + /// + /// Checks rectangle entry, exit, and hole boundaries against analytic line intervals. + /// + /// The area fill rule. + [Theory] + [InlineData(FillRule.EvenOdd)] + [InlineData(FillRule.NonZero)] + public void LineAgainstDonut_RetainsOnlyFilledIntervals(FillRule rule) + { + Contour hole = Rectangle(3, 3, 7, 7); + hole.Reverse(); + Polygon result = PolygonClipper.Intersection( + [Open(new(-1, 5), new(11, 5))], [Rectangle(0, 0, 10, 10), hole], FillRule.NonZero, rule); + + AssertLines(result, (new(0, 5), new(3, 5)), (new(7, 5), new(10, 5))); + } + + /// + /// Checks coincident line and area boundaries with different terminal endpoints. + /// + /// Whether the line runs backwards. + /// Whether the area is the subject. + [Theory] + [InlineData(false, false)] + [InlineData(true, false)] + [InlineData(false, true)] + [InlineData(true, true)] + public void LineOnAreaBoundary_RetainsTheSharedSpan(bool reverse, bool swap) + { + Contour line = reverse ? Open(new(15, 0), new(-5, 0)) : Open(new(-5, 0), new(15, 0)); + Polygon first = [line]; + Polygon second = [Rectangle(0, 0, 10, 10)]; + + Polygon result = PolygonClipper.Intersection(swap ? second : first, swap ? first : second, FillRule.NonZero); + + AssertLines(result, (new(0, 0), new(10, 0))); + } + + /// + /// Checks that a line touching a filled corner produces one point without a manufactured edge. + /// + [Fact] + public void TangentLine_ReturnsOneCornerPoint() + { + Polygon result = PolygonClipper.Intersection( + [Open(new(-2, 2), new(2, -2))], [Rectangle(0, 0, 10, 10)], FillRule.NonZero); + + Contour point = Assert.Single(result); + Assert.False(point.IsClosed); + Assert.Equal(new Vertex(0, 0), Assert.Single(point)); + } + + /// + /// Checks that a point result can participate in subsequent clipping and splitting. + /// + [Fact] + public void PointResults_CanBeReusedAsOperands() + { + Polygon horizontal = [Open(new(-2, 0), new(2, 0))]; + Polygon point = PolygonClipper.Intersection(horizontal, [Open(new(0, -2), new(0, 2))], FillRule.NonZero); + + Assert.Equal(new Vertex(0, 0), Assert.Single(Assert.Single(PolygonClipper.Intersection(point, horizontal, FillRule.NonZero)))); + AssertLines( + PolygonClipper.Difference(horizontal, point, FillRule.NonZero), + (new(-2, 0), new(0, 0)), + (new(0, 0), new(2, 0))); + Assert.Empty(PolygonClipper.Intersection(point, [Open(new(3, 0), new(4, 0))], FillRule.NonZero)); + } + + /// + /// Checks that line output joins ordinary source vertices while remaining open. + /// + [Fact] + public void PolylineInsideArea_PreservesItsBend() + { + Polygon result = PolygonClipper.Intersection( + [Open(new(2, 2), new(4, 6), new(8, 2))], [Rectangle(0, 0, 10, 10)], FillRule.NonZero); + + Contour line = Assert.Single(result); + Assert.False(line.IsClosed); + Assert.Equal(3, line.Count); + Assert.Contains(new Vertex(2, 2), line); + Assert.Contains(new Vertex(4, 6), line); + Assert.Contains(new Vertex(8, 2), line); + } + + /// + /// Checks that retained areas suppress covered linework without discarding its outside pieces. + /// + [Fact] + public void MixedUnion_PreservesAreaAndOutsideLines() + { + Polygon result = PolygonClipper.Union( + [Rectangle(0, 0, 10, 10), Open(new(-5, 5), new(15, 5))], [], FillRule.NonZero); + + Contour area = Assert.Single(result, contour => contour.IsClosed); + Assert.Equal(100D, PolygonUtilities.Area(area.AsVertexSpan())); + Assert.Equal(3, result.Count); + Polygon open = []; + foreach (Contour contour in result.Where(contour => !contour.IsClosed)) + { + Assert.Null(contour.ParentIndex); + Assert.Equal(0, contour.HoleCount); + open.Add(contour); + } + + AssertLines(open, (new(-5, 5), new(0, 5)), (new(10, 5), new(15, 5))); + } + + /// + /// Checks that an explicit line cycle remains line geometry rather than acquiring a filled interior. + /// + [Fact] + public void OpenCycle_DoesNotBecomeAFilledBoundary() + { + Contour source = Open(new(0, 0), new(2, 0), new(2, 2), new(0, 2), new(0, 0)); + Contour line = Assert.Single(PolygonClipper.Normalize([source], FillRule.NonZero)); + + Assert.False(line.IsClosed); + Assert.Equal(5, line.Count); + Assert.Equal(line[0], line[^1]); + } + + /// + /// Checks tiny and large crossings without a tolerance or integer coordinate conversion. + /// + /// The segment length. + [Theory] + [InlineData(1E-90)] + [InlineData(1E90)] + public void ScaledLines_PreserveCrossingPoint(double scale) + { + Polygon result = PolygonClipper.Intersection( + [Open(new(0, 0), new(scale, scale))], [Open(new(0, scale), new(scale, 0))], FillRule.NonZero); + + Assert.Equal(new Vertex(scale * 0.5D, scale * 0.5D), Assert.Single(Assert.Single(result))); + } + + /// + /// Checks the terminal vertex that is not visited as an open segment's start. + /// + /// The invalid terminal coordinate. + [Theory] + [InlineData(double.NaN)] + [InlineData(double.PositiveInfinity)] + [InlineData(double.NegativeInfinity)] + public void NonFiniteTerminalVertex_IsRejected(double coordinate) + { + Assert.Throws(() => PolygonClipper.Normalize([Open(new(0, 0), new(coordinate, 1))], FillRule.NonZero)); + AssertLines(PolygonClipper.Normalize([Open(new(0, 0), new(1, 0))], FillRule.NonZero), (new(0, 0), new(1, 0))); + } + + /// + /// Checks every crossing in a line network and all pieces between those crossings. + /// + /// The requested operation. + [Theory] + [InlineData(BooleanOperation.Intersection)] + [InlineData(BooleanOperation.Union)] + [InlineData(BooleanOperation.Difference)] + [InlineData(BooleanOperation.Xor)] + public void GridLines_AllCrossingsAreRetained(BooleanOperation operation) + { + const int size = 10; + Polygon horizontal = []; + Polygon vertical = []; + for (int i = 0; i < size; i++) + { + horizontal.Add(Open(new(-1, i), new(size, i))); + vertical.Add(Open(new(i, -1), new(i, size))); + } + + Polygon result = Execute(horizontal, vertical, operation); + if (operation == BooleanOperation.Intersection) + { + Assert.Equal(size * size, result.Count); + for (int y = 0; y < size; y++) + { + for (int x = 0; x < size; x++) + { + Vertex expected = new(x, y); + Assert.Contains(result, contour => !contour.IsClosed && contour.Count == 1 && contour[0] == expected); + } + } + } + else + { + int expected = size * (size + 1) * (operation == BooleanOperation.Difference ? 1 : 2); + Assert.Equal(expected, result.Count); + foreach (Contour contour in result) + { + Assert.False(contour.IsClosed); + Assert.Equal(2, contour.Count); + Vertex difference = contour[1] - contour[0]; + Assert.Equal(1D, Math.Abs(difference.X) + Math.Abs(difference.Y)); + } + } + } + + /// + /// Checks cancelled area winding on a line boundary without cancelling the open source. + /// + [Fact] + public void OpposingAreaContours_DoNotCancelCoincidentLinework() + { + Contour first = Rectangle(0, 0, 10, 10); + Contour second = first.DeepClone(); + second.Reverse(); + + Polygon result = PolygonClipper.Normalize([first, second, Open(new(-5, 0), new(15, 0))], FillRule.NonZero); + + Assert.All(result, contour => Assert.False(contour.IsClosed)); + AssertLines(result, (new(-5, 0), new(0, 0)), (new(0, 0), new(10, 0)), (new(10, 0), new(15, 0))); + } + + /// + /// Checks that an open clipping call does not leak line state into later closed operations. + /// + [Fact] + public void PooledReuse_SeparatesOpenAndClosedState() + { + for (int i = 0; i < 3; i++) + { + Polygon crossing = PolygonClipper.Intersection( + [Open(new(-2, 0), new(2, 0))], [Open(new(0, -2), new(0, 2))], FillRule.Negative); + Assert.Equal(new Vertex(0, 0), Assert.Single(Assert.Single(crossing))); + + Polygon area = PolygonClipper.Intersection([Rectangle(0, 0, 10, 10)], [Rectangle(5, 5, 15, 15)], FillRule.NonZero); + Contour contour = Assert.Single(area); + Assert.True(contour.IsClosed); + Assert.Equal(25D, PolygonUtilities.Area(contour.AsVertexSpan())); + } + } + + /// + /// Checks constructed integer crossings with known coordinates and four exact ray endpoints. + /// + /// The requested operation. + [Theory] + [InlineData(BooleanOperation.Intersection)] + [InlineData(BooleanOperation.Union)] + [InlineData(BooleanOperation.Difference)] + [InlineData(BooleanOperation.Xor)] + public void ConstructedCrossings_MatchKnownIntegerGeometry(BooleanOperation operation) + { + for (int i = 1; i <= 50; i++) + { + Vertex point = new(((i * 73) % 101) - 50, ((i * 31) % 103) - 51); + Vertex first = new((i % 7) + 1, (i % 5) + 1); + Vertex second = new(-((i % 11) + 1), (i % 3) + 1); + Vertex a = point - first; + Vertex b = point + first; + Vertex c = point - second; + Vertex d = point + second; + + Polygon result = Execute([Open(a, b)], [Open(c, d)], operation); + if (operation == BooleanOperation.Intersection) + { + Assert.Equal(point, Assert.Single(Assert.Single(result))); + } + else if (operation == BooleanOperation.Difference) + { + AssertLines(result, (a, point), (point, b)); + } + else + { + AssertLines(result, (a, point), (point, b), (c, point), (point, d)); + } + } + } + + /// + /// Checks a self-crossing open path without filling either of its enclosed lobes. + /// + [Fact] + public void SelfCrossingPolyline_RetainsNodedLinework() + { + Polygon result = PolygonClipper.Normalize( + [Open(new(-2, -2), new(2, 2), new(-2, 2), new(2, -2))], FillRule.NonZero); + + Assert.Equal(3, result.Count); + Assert.All(result, contour => Assert.False(contour.IsClosed)); + Contour cycle = Assert.Single(result, contour => contour.Count == 4); + Assert.Equal(new Vertex(0, 0), cycle[0]); + Assert.Equal(cycle[0], cycle[^1]); + Assert.Contains(new Vertex(2, 2), cycle); + Assert.Contains(new Vertex(-2, 2), cycle); + } + + /// + /// Builds an explicitly open input without adding a closing vertex. + /// + /// The source vertex sequence. + /// The open contour. + private static Contour Open(params Vertex[] vertices) + { + Contour contour = new(vertices.Length) { IsClosed = false }; + foreach (Vertex vertex in vertices) + { + contour.Add(vertex); + } + + return contour; + } + + /// + /// Builds a counterclockwise closed rectangle with implicit closure. + /// + /// The left coordinate. + /// The bottom coordinate. + /// The right coordinate. + /// The top coordinate. + /// The closed rectangle. + private static Contour Rectangle(double left, double bottom, double right, double top) + => [new(left, bottom), new(right, bottom), new(right, top), new(left, top)]; + + /// + /// Executes the requested existing public operation. + /// + /// The subject contours. + /// The clip contours. + /// The requested operation. + /// The clipped contours. + private static Polygon Execute(Polygon subject, Polygon clip, BooleanOperation operation) + => operation switch + { + BooleanOperation.Intersection => PolygonClipper.Intersection(subject, clip, FillRule.NonZero), + BooleanOperation.Union => PolygonClipper.Union(subject, clip, FillRule.NonZero), + BooleanOperation.Difference => PolygonClipper.Difference(subject, clip, FillRule.NonZero), + _ => PolygonClipper.Xor(subject, clip, FillRule.NonZero) + }; + + /// + /// Checks exact undirected line pieces without depending on contour ordering or traversal direction. + /// + /// The returned contours. + /// The analytically expected line pieces. + private static void AssertLines(Polygon result, params (Vertex First, Vertex Last)[] expected) + { + Assert.Equal(expected.Length, result.Count); + foreach ((Vertex first, Vertex last) in expected) + { + Assert.Contains(result, contour => !contour.IsClosed && contour.Count == 2 && + ((contour[0] == first && contour[1] == last) || (contour[0] == last && contour[1] == first))); + } + } +} diff --git a/tests/PolygonClipper.Tests/PolygonClipperContourClosureTests.cs b/tests/PolygonClipper.Tests/PolygonClipperContourClosureTests.cs index 8ff14d5..2faa628 100644 --- a/tests/PolygonClipper.Tests/PolygonClipperContourClosureTests.cs +++ b/tests/PolygonClipper.Tests/PolygonClipperContourClosureTests.cs @@ -6,7 +6,7 @@ namespace SixLabors.PolygonClipper.Tests; public class PolygonClipperContourClosureTests { /// - /// Checks source closure independently of duplicate endpoint representation for all fill rules. + /// Checks that explicit closure selects filled boundaries or open lines. /// /// The fill rule for both operands. [Theory] @@ -14,7 +14,7 @@ public class PolygonClipperContourClosureTests [InlineData(FillRule.NonZero)] [InlineData(FillRule.Positive)] [InlineData(FillRule.Negative)] - public void FilledOperations_SourceClosureFlags_DoNotChangeOutput(FillRule rule) + public void FilledOperations_SourceClosureFlags_SelectPathGeometry(FillRule rule) { Polygon subject = [CreateRectangleContour(0, 0, 10, 10, false)]; Polygon clip = [CreateRectangleContour(5, 5, 15, 15, false)]; @@ -23,11 +23,27 @@ public void FilledOperations_SourceClosureFlags_DoNotChangeOutput(FillRule rule) openSubject[0].IsClosed = false; openClip[0].IsClosed = false; - AssertEquivalent(PolygonClipper.Intersection(subject, clip, rule), PolygonClipper.Intersection(openSubject, openClip, rule)); - AssertEquivalent(PolygonClipper.Union(subject, clip, rule), PolygonClipper.Union(openSubject, openClip, rule)); - AssertEquivalent(PolygonClipper.Difference(subject, clip, rule), PolygonClipper.Difference(openSubject, openClip, rule)); - AssertEquivalent(PolygonClipper.Xor(subject, clip, rule), PolygonClipper.Xor(openSubject, openClip, rule)); - AssertEquivalent(PolygonClipper.Normalize(subject, rule), PolygonClipper.Normalize(openSubject, rule)); + Polygon closed = PolygonClipper.Intersection(subject, clip, rule); + if (rule == FillRule.Negative) + { + Assert.Empty(closed); + } + else + { + Contour boundary = Assert.Single(closed); + Assert.True(boundary.IsClosed); + Assert.Equal(4, boundary.Count); + Assert.Contains(new Vertex(5, 5), boundary); + Assert.Contains(new Vertex(10, 5), boundary); + Assert.Contains(new Vertex(10, 10), boundary); + Assert.Contains(new Vertex(5, 10), boundary); + } + + // The two open three-sided paths share only (10, 5). Their omitted + // closing sides must not manufacture the filled rectangle above. + Contour point = Assert.Single(PolygonClipper.Intersection(openSubject, openClip, rule)); + Assert.False(point.IsClosed); + Assert.Equal(new Vertex(10, 5), Assert.Single(point)); Assert.False(openSubject[0].IsClosed); Assert.False(openClip[0].IsClosed); diff --git a/tests/PolygonClipper.Tests/SweepEventPoolListTests.cs b/tests/PolygonClipper.Tests/SweepEventPoolListTests.cs index 7103891..ced756e 100644 --- a/tests/PolygonClipper.Tests/SweepEventPoolListTests.cs +++ b/tests/PolygonClipper.Tests/SweepEventPoolListTests.cs @@ -21,14 +21,14 @@ public void GrowthAfterClear_PreservesCachedEvents(int activeCount) SweepEvent[] original = new SweepEvent[4]; for (int i = 0; i < original.Length; i++) { - original[i] = pool.Add(new Vertex(i, 0), new Vertex(i + 1, 0), new PolygonClipper.WindingCount(1, 0)); + original[i] = pool.Add(new Vertex(i, 0), new Vertex(i + 1, 0), new WindingCount(1, 0)); } int capacity = pool.Capacity; pool.Clear(); for (int i = 0; i < activeCount; i++) { - Assert.Same(original[i], pool.Add(new Vertex(i, 1), new Vertex(i + 1, 1), new PolygonClipper.WindingCount(0, 1))); + Assert.Same(original[i], pool.Add(new Vertex(i, 1), new Vertex(i + 1, 1), new WindingCount(0, 1))); } pool.EnsureCapacity(capacity + 1); @@ -37,13 +37,13 @@ public void GrowthAfterClear_PreservesCachedEvents(int activeCount) Assert.True(pool.Capacity > capacity); for (int i = activeCount; i < original.Length; i++) { - SweepEvent reused = pool.Add(new Vertex(i, 1), new Vertex(i + 1, 1), new PolygonClipper.WindingCount(0, 1)); + SweepEvent reused = pool.Add(new Vertex(i, 1), new Vertex(i + 1, 1), new WindingCount(0, 1)); Assert.Same(original[i], reused); Assert.Equal(new Vertex(i, 1), reused.Point); Assert.Equal(new Vertex(i + 1, 1), reused.End); } - pool.Add(new Vertex(4, 1), new Vertex(5, 1), new PolygonClipper.WindingCount(0, 1)); + pool.Add(new Vertex(4, 1), new Vertex(5, 1), new WindingCount(0, 1)); Assert.Equal(5, pool.Count); } } From 545b6c0a76e7089cee30e489327fc49bae9787c7 Mon Sep 17 00:00:00 2001 From: James Jackson-South Date: Fri, 30 Oct 2026 13:55:26 +1000 Subject: [PATCH 14/24] Record clipping benchmarks and verify dense-star boundaries --- src/PolygonClipper/PolygonUtilities.cs | 14 +- tests/PolygonClipper.Benchmarks/Benches.cs | 38 +++++ .../NormalizationBenches.cs | 23 +++ .../OpenClippingBenches.cs | 31 ++++ .../StarBooleanBenches.cs | 62 +++++++ .../FillRuleClippingTests.cs | 1 + .../NormalizationTests.cs | 26 +++ .../TestPolygonUtilities.cs | 153 ++++++++++++++++++ .../TestPolygonUtilitiesTests.cs | 32 ++++ 9 files changed, 375 insertions(+), 5 deletions(-) diff --git a/src/PolygonClipper/PolygonUtilities.cs b/src/PolygonClipper/PolygonUtilities.cs index 8c4cc32..cfd75d8 100644 --- a/src/PolygonClipper/PolygonUtilities.cs +++ b/src/PolygonClipper/PolygonUtilities.cs @@ -28,12 +28,16 @@ public static double SignedArea(in Vertex p0, in Vertex p1, in Vertex p2) double second = a.Y * b.X; double area = first - second; - // The orientation filter includes rounding in coordinate differences - // and products. Recover those differences only when cancellation can - // obscure the sign. The bound selects precision; it does not merge points. - const double errorFactor = 3.3306690738754716E-16D; + // The two products can almost cancel. Rounding can then change the sign. + // For double arithmetic, u = 2^-53. The error factor is (3 + 16u)u. + // If the absolute area exceeds the bound below, its sign is reliable. + // Otherwise, the calculation needs higher precision to determine the sign. + // Source: https://www.cs.cmu.edu/afs/cs/project/quake/public/code/predicates.c + // exactinit defines this factor as ccwerrboundA. orient2d uses it. + const double unitRoundoff = 1D / 9_007_199_254_740_992D; + const double orientationErrorFactor = (3D + (16D * unitRoundoff)) * unitRoundoff; if (first == 0 || second == 0 || !double.IsFinite(area) || - Math.Abs(area) > errorFactor * (Math.Abs(first) + Math.Abs(second))) + Math.Abs(area) > orientationErrorFactor * (Math.Abs(first) + Math.Abs(second))) { return area; } diff --git a/tests/PolygonClipper.Benchmarks/Benches.cs b/tests/PolygonClipper.Benchmarks/Benches.cs index f7e2f65..1580d9e 100644 --- a/tests/PolygonClipper.Benchmarks/Benches.cs +++ b/tests/PolygonClipper.Benchmarks/Benches.cs @@ -8,6 +8,44 @@ namespace SixLabors.PolygonClipper.Benchmarks; +/* + * Comparison results: 30 October 2026. + * Windows 11. AMD Ryzen AI Max+ 395. .NET 10.0.14. BenchmarkDotNet 0.15.8. + * V2 build: 4f814c3 with the orientation-bound formula. release/1.x: cb06839. Clipper2: 4be4655. + * Mean: milliseconds per operation. Op/s: operations per second. B/op: allocated bytes per operation. + * Input preparation occurs before measurement. ClipperD uses precision 6. + * Each case uses 12 measured iterations, a 250 ms iteration target, and one launch. All samples remain included. + * Rust: rust-geo-booleanop 0.3.2 at b9bbdbb. rustc 1.98.0. Release build. geo-types 0.7.20. + * Rust timings include the native call and output destruction. Rust supports EvenOdd only. + * The .NET counters measure managed bytes. A separate Rust build counts requested native bytes. + * All comparisons below use union on the same source coordinates. + * Warmup: 10 iterations. release/1.x NonZero includes its required input preparation. + * The release/1.x NonZero hole_hole output fails the geometry check and has no comparison timing. + * + * Input | Fill rule | Engine | Mean (ms) | Op/s | B/op + * --------------+-----------+-------------+-----------+------------+--------- + * hole_hole | EvenOdd | V2 | 0.005698 | 175501.974 | 2560 + * hole_hole | EvenOdd | release/1.x | 0.013171 | 75925.110 | 9440 + * hole_hole | EvenOdd | Clipper2 | 0.002463 | 406026.381 | 9992 + * hole_hole | EvenOdd | Rust | 0.013409 | 74578.548 | 13948 + * hole_hole | NonZero | V2 | 0.005199 | 192359.257 | 1392 + * hole_hole | NonZero | Clipper2 | 0.001927 | 519056.802 | 7512 + * states_source | EvenOdd | V2 | 0.753519 | 1327.106 | 36936 + * states_source | EvenOdd | release/1.x | 1.205269 | 829.691 | 454496 + * states_source | EvenOdd | Clipper2 | 0.296078 | 3377.492 | 348984 + * states_source | EvenOdd | Rust | 1.193274 | 838.031 | 806340 + * states_source | NonZero | V2 | 0.786269 | 1271.830 | 36936 + * states_source | NonZero | release/1.x | 1.968205 | 508.077 | 584856 + * states_source | NonZero | Clipper2 | 0.295386 | 3385.403 | 348984 + * asia | EvenOdd | V2 | 12.277375 | 81.451 | 1189296 + * asia | EvenOdd | release/1.x | 18.382942 | 54.398 | 7527048 + * asia | EvenOdd | Clipper2 | 13.100940 | 76.330 | 6612934 + * asia | EvenOdd | Rust | 18.389607 | 54.379 | 11034172 + * asia | NonZero | V2 | 12.439713 | 80.388 | 1189296 + * asia | NonZero | release/1.x | 30.984123 | 32.275 | 9062752 + * asia | NonZero | Clipper2 | 13.507377 | 74.034 | 6613557 + */ + /// /// Benchmarks the performance of PolygonClipper for polygon union operations using a fixed input dataset. /// diff --git a/tests/PolygonClipper.Benchmarks/NormalizationBenches.cs b/tests/PolygonClipper.Benchmarks/NormalizationBenches.cs index 238e661..8278f88 100644 --- a/tests/PolygonClipper.Benchmarks/NormalizationBenches.cs +++ b/tests/PolygonClipper.Benchmarks/NormalizationBenches.cs @@ -6,6 +6,29 @@ namespace SixLabors.PolygonClipper.Benchmarks; +/* + * Comparison results: 30 October 2026. + * Windows 11. AMD Ryzen AI Max+ 395. .NET 10.0.14. BenchmarkDotNet 0.15.8. + * V2 build: 4f814c3 with the orientation-bound formula. release/1.x: cb06839. Clipper2: 4be4655. + * Mean: milliseconds per operation. Op/s: operations per second. B/op: allocated bytes per operation. + * Input preparation occurs before measurement. ClipperD uses precision 6. + * Each case uses 12 measured iterations, a 250 ms iteration target, and one launch. All samples remain included. + * All comparisons below use Positive cleanup on one star. Warmup: 10 iterations. + * release/1.x uses its Clipper2-derived cleanup. V2 uses its shared Martinez sweep. + * + * Vertices | Engine | Mean (ms) | Op/s | B/op + * ---------+-------------+------------+----------+--------- + * 101 | V2 | 1.751403 | 570.971 | 8648 + * 101 | release/1.x | 0.516666 | 1935.486 | 13760 + * 101 | Clipper2 | 0.449719 | 2223.613 | 210728 + * 301 | V2 | 17.035385 | 58.701 | 33272 + * 301 | release/1.x | 5.714182 | 175.003 | 40032 + * 301 | Clipper2 | 5.731402 | 174.477 | 2352348 + * 1001 | V2 | 205.407133 | 4.868 | 66064 + * 1001 | release/1.x | 84.452671 | 11.841 | 17449540 + * 1001 | Clipper2 | 76.949340 | 12.996 | 17525094 + */ + /// /// Benchmarks normalization performance for star polygons. /// diff --git a/tests/PolygonClipper.Benchmarks/OpenClippingBenches.cs b/tests/PolygonClipper.Benchmarks/OpenClippingBenches.cs index 4dace0c..d7b8345 100644 --- a/tests/PolygonClipper.Benchmarks/OpenClippingBenches.cs +++ b/tests/PolygonClipper.Benchmarks/OpenClippingBenches.cs @@ -6,6 +6,37 @@ namespace SixLabors.PolygonClipper.Benchmarks; +/* + * Comparison results: 30 October 2026. + * Windows 11. AMD Ryzen AI Max+ 395. .NET 10.0.14. BenchmarkDotNet 0.15.8. + * V2 build: 4f814c3 with the orientation-bound formula. release/1.x: cb06839. Clipper2: 4be4655. + * Mean: milliseconds per operation. Op/s: operations per second. B/op: allocated bytes per operation. + * Input preparation occurs before measurement. ClipperD uses precision 6. + * Each case uses 12 measured iterations, a 250 ms iteration target, and one launch. All samples remain included. + * The setup checks exact output edges for every open-path case. + * The .NET counters measure managed bytes. release/1.x and Rust have no matching open-path API. + * Warmup: 10 iterations. The 1,000-path, 13-vertex transposed case uses a repeat with 30 iterations for both engines. + * + * Paths | Vertices/path | Transpose | Engine | Mean (ms) | Op/s | B/op + * ------+---------------+-----------+----------+-----------+------------+-------- + * 10 | 2 | False | Clipper2 | 0.002487 | 402069.493 | 13680 + * 10 | 2 | False | V2 | 0.009797 | 102068.642 | 2872 + * 10 | 2 | True | Clipper2 | 0.002442 | 409562.862 | 15272 + * 10 | 2 | True | V2 | 0.009971 | 100295.413 | 2872 + * 10 | 13 | False | Clipper2 | 0.009040 | 110623.884 | 43592 + * 10 | 13 | False | V2 | 0.028162 | 35508.975 | 7072 + * 10 | 13 | True | Clipper2 | 0.005468 | 182885.680 | 32808 + * 10 | 13 | True | V2 | 0.035768 | 27958.106 | 7072 + * 1000 | 2 | False | Clipper2 | 0.199499 | 5012.556 | 1098600 + * 1000 | 2 | False | V2 | 1.083615 | 922.837 | 264232 + * 1000 | 2 | True | Clipper2 | 0.576339 | 1735.091 | 1274864 + * 1000 | 2 | True | V2 | 1.235454 | 809.419 | 264232 + * 1000 | 13 | False | Clipper2 | 3.402228 | 293.925 | 3899782 + * 1000 | 13 | False | V2 | 4.668755 | 214.190 | 612232 + * 1000 | 13 | True | Clipper2 | 2.569250 | 389.219 | 3002254 + * 1000 | 13 | True | V2 | 5.211886 | 191.869 | 612232 + */ + /// /// Compares open line clipping against the same closed rectangle and hole. /// diff --git a/tests/PolygonClipper.Benchmarks/StarBooleanBenches.cs b/tests/PolygonClipper.Benchmarks/StarBooleanBenches.cs index 971ef06..34c6067 100644 --- a/tests/PolygonClipper.Benchmarks/StarBooleanBenches.cs +++ b/tests/PolygonClipper.Benchmarks/StarBooleanBenches.cs @@ -6,6 +6,68 @@ namespace SixLabors.PolygonClipper.Benchmarks; +/* + * Comparison results: 30 October 2026. + * Windows 11. AMD Ryzen AI Max+ 395. .NET 10.0.14. BenchmarkDotNet 0.15.8. + * V2 build: 4f814c3 with the orientation-bound formula. release/1.x: cb06839. Clipper2: 4be4655. + * Mean: milliseconds per operation. Op/s: operations per second. B/op: allocated bytes per operation. + * Input preparation occurs before measurement. ClipperD uses precision 6. + * Each case uses 12 measured iterations, a 250 ms iteration target, and one launch. All samples remain included. + * Rust: rust-geo-booleanop 0.3.2 at b9bbdbb. rustc 1.98.0. Release build. geo-types 0.7.20. + * Rust timings include the native call and output destruction. Rust supports EvenOdd only. + * The .NET counters measure managed bytes. A separate Rust build counts requested native bytes. + * The comparison harness measures the fill rules and engines shown below on the same pair of stars. + * Warmup: 10 iterations, except the four variable 101-vertex cases, which use a repeat with 30 iterations. + * Those repeats cover Union with EvenOdd and NonZero, and Intersection and Difference with EvenOdd. + * Every supported engine uses the same longer warmup in each repeated case. + * release/1.x NonZero includes its required input preparation. + * Both dense-star EvenOdd unions pass the boundary checks despite different contour grouping. + * + * Vertices | Fill rule | Operation | Engine | Mean (ms) | Op/s | B/op + * ---------+-----------+--------------+-------------+-------------+---------+---------- + * 101 | EvenOdd | Union | V2 | 9.531152 | 104.919 | 1221184 + * 101 | EvenOdd | Union | release/1.x | 33.957776 | 29.448 | 10058513 + * 101 | EvenOdd | Union | Clipper2 | 37.183475 | 26.894 | 5454480 + * 101 | EvenOdd | Union | Rust | 28.678877 | 34.869 | 12025868 + * 101 | EvenOdd | Intersection | V2 | 10.124404 | 98.771 | 1979952 + * 101 | EvenOdd | Intersection | release/1.x | 35.579118 | 28.106 | 11013441 + * 101 | EvenOdd | Intersection | Clipper2 | 6.114008 | 163.559 | 5081410 + * 101 | EvenOdd | Intersection | Rust | 29.568188 | 33.820 | 14123564 + * 101 | EvenOdd | Difference | V2 | 9.295369 | 107.580 | 1539000 + * 101 | EvenOdd | Difference | release/1.x | 34.142293 | 29.289 | 10492458 + * 101 | EvenOdd | Difference | Clipper2 | 6.015985 | 166.224 | 4180303 + * 101 | EvenOdd | Difference | Rust | 30.183794 | 33.130 | 13713340 + * 101 | EvenOdd | Xor | V2 | 23.045433 | 43.393 | 10778162 + * 101 | EvenOdd | Xor | release/1.x | 33.714825 | 29.661 | 12728260 + * 101 | EvenOdd | Xor | Clipper2 | 10.867327 | 92.019 | 8527564 + * 101 | EvenOdd | Xor | Rust | 35.518577 | 28.154 | 18811516 + * 101 | NonZero | Union | V2 | 7.799769 | 128.209 | 213480 + * 101 | NonZero | Union | release/1.x | 4.803016 | 208.202 | 1125464 + * 101 | NonZero | Union | Clipper2 | 3.329548 | 300.341 | 874861 + * 301 | EvenOdd | Union | V2 | 113.486163 | 8.812 | 34139832 + * 301 | EvenOdd | Union | release/1.x | 445.814992 | 2.243 | 88329168 + * 301 | EvenOdd | Union | Clipper2 | 1942.372475 | 0.515 | 40570064 + * 301 | EvenOdd | Union | Rust | 419.326683 | 2.385 | 104351676 + * 301 | EvenOdd | Intersection | V2 | 143.969358 | 6.946 | 55822008 + * 301 | EvenOdd | Intersection | release/1.x | 495.890125 | 2.017 | 96940976 + * 301 | EvenOdd | Intersection | Clipper2 | 123.051400 | 8.127 | 44447544 + * 301 | EvenOdd | Intersection | Rust | 468.113050 | 2.136 | 121501628 + * 301 | EvenOdd | Difference | V2 | 137.709375 | 7.262 | 45124380 + * 301 | EvenOdd | Difference | release/1.x | 459.630592 | 2.176 | 92145616 + * 301 | EvenOdd | Difference | Clipper2 | 103.656529 | 9.647 | 36238448 + * 301 | EvenOdd | Difference | Rust | 440.715792 | 2.269 | 117719484 + * 301 | EvenOdd | Xor | V2 | 265.359167 | 3.768 | 94318776 + * 301 | EvenOdd | Xor | release/1.x | 560.481942 | 1.784 | 111897144 + * 301 | EvenOdd | Xor | Clipper2 | 266.766542 | 3.749 | 73402336 + * 301 | EvenOdd | Xor | Rust | 555.358192 | 1.801 | 159997324 + * 301 | NonZero | Union | V2 | 72.203506 | 13.850 | 1879008 + * 301 | NonZero | Union | release/1.x | 50.096682 | 19.961 | 11411998 + * 301 | NonZero | Union | Clipper2 | 72.272604 | 13.837 | 6609810 + * 1001 | NonZero | Union | V2 | 923.958408 | 1.082 | 63130176 + * 1001 | NonZero | Union | release/1.x | 852.718975 | 1.173 | 151387784 + * 1001 | NonZero | Union | Clipper2 | 2850.236992 | 0.351 | 61347952 + */ + /// /// Benchmarks PolygonClipper boolean operations using two overlapping star polygons. /// diff --git a/tests/PolygonClipper.Tests/FillRuleClippingTests.cs b/tests/PolygonClipper.Tests/FillRuleClippingTests.cs index c164f2c..74694d9 100644 --- a/tests/PolygonClipper.Tests/FillRuleClippingTests.cs +++ b/tests/PolygonClipper.Tests/FillRuleClippingTests.cs @@ -359,6 +359,7 @@ public void Cleanup_InputHierarchy_DoesNotOverrideWinding(FillRule rule, double [Theory] [InlineData(31)] [InlineData(101)] + [InlineData(301)] public void DenseStars_ExplicitRules_MatchSourceCoverage(int vertexCount) { Polygon subject = GenericTestCases.BuildStarPolygon(vertexCount, 100D, 0D, 0D); diff --git a/tests/PolygonClipper.Tests/NormalizationTests.cs b/tests/PolygonClipper.Tests/NormalizationTests.cs index 84e57d9..9916709 100644 --- a/tests/PolygonClipper.Tests/NormalizationTests.cs +++ b/tests/PolygonClipper.Tests/NormalizationTests.cs @@ -7,6 +7,32 @@ namespace SixLabors.PolygonClipper.Tests; public class NormalizationTests { + /// + /// Checks every boundary connection in the two dense-star union cases. + /// + /// The number of vertices in each source star. + [Theory] + [InlineData(101)] + [InlineData(301)] + public void DenseStarUnion_PreservesBoundaryConnections(int vertexCount) + { + Polygon subject = GenericTestCases.BuildStarPolygon(vertexCount, 100D, 0D, 0D); + Polygon clip = GenericTestCases.BuildStarPolygon(vertexCount, 100D, 35D, 22D); + + // Use the same six-decimal input scale as the comparison benchmark. + ClipperD reference = new(6) { PreserveCollinear = false }; + reference.AddSubject(new PathsD(subject.Select(ProjectContour))); + reference.AddClip(new PathsD(clip.Select(ProjectContour))); + PathsD expected = []; + Assert.True(reference.Execute(ClipType.Union, Clipper2Lib.FillRule.EvenOdd, expected)); + + Polygon actual = PolygonClipper.Union(subject, clip, FillRule.EvenOdd); + + // Contours can join differently at a shared vertex. Check every + // junction and segment instead of requiring the same contour count. + Assert.True(TestPolygonUtilities.HaveEquivalentBoundaryGraphs(actual.Select(ProjectContour), expected)); + } + /// /// Tests that a simple rectangle (single contour, no holes) is preserved. /// diff --git a/tests/PolygonClipper.Tests/TestPolygonUtilities.cs b/tests/PolygonClipper.Tests/TestPolygonUtilities.cs index eef1d33..88fda4c 100644 --- a/tests/PolygonClipper.Tests/TestPolygonUtilities.cs +++ b/tests/PolygonClipper.Tests/TestPolygonUtilities.cs @@ -1,6 +1,7 @@ // Copyright (c) Six Labors. // Licensed under the Six Labors Split License. +using Clipper2Lib; using GeoJson.Feature; using GeoJson.Geometry; using GeoPolygon = GeoJson.Geometry.Polygon; @@ -9,6 +10,64 @@ namespace SixLabors.PolygonClipper.Tests; internal static class TestPolygonUtilities { + /// + /// Checks boundary connections without requiring the same contour grouping. + /// + /// The actual boundary paths. + /// The reference boundary paths. + /// Whether each junction and segment has one matching reference item. + /// + /// Matches junctions by distance, then checks every undirected segment. + /// Use a separate area or point check when coordinate rounding can change the filled area. + /// + public static bool HaveEquivalentBoundaryGraphs(IEnumerable actual, IEnumerable expected) + { + (List actualNodes, Dictionary<(int Start, int End), int> actualEdges) = BuildBoundaryGraph(actual); + (List expectedNodes, Dictionary<(int Start, int End), int> expectedEdges) = BuildBoundaryGraph(expected); + if (actualNodes.Count != expectedNodes.Count || actualEdges.Count != expectedEdges.Count) + { + return false; + } + + List<(Vertex Point, int Index)> ordered = new(expectedNodes.Count); + for (int i = 0; i < expectedNodes.Count; i++) + { + ordered.Add((expectedNodes[i], i)); + } + + IComparer<(Vertex Point, int Index)> comparer = Comparer<(Vertex Point, int Index)>.Create( + static (first, second) => first.Point.X.CompareTo(second.Point.X)); + ordered.Sort(comparer); + + int[] mapping = new int[actualNodes.Count]; + HashSet assigned = []; + for (int i = 0; i < actualNodes.Count; i++) + { + int index = FindNearestBoundaryNode(actualNodes[i], ordered, comparer); + if (!assigned.Add(index)) + { + // Two junctions cannot use one reference junction. That would + // hide a lost connection or a change caused by coordinate rounding. + return false; + } + + mapping[i] = index; + } + + foreach (((int start, int end), int count) in actualEdges) + { + int first = mapping[start]; + int second = mapping[end]; + (int, int) edge = first < second ? (first, second) : (second, first); + if (!expectedEdges.TryGetValue(edge, out int expectedCount) || count != expectedCount) + { + return false; + } + } + + return true; + } + public static (Polygon Subject, Polygon Clipping) BuildPolygon(FeatureCollection data) { IGeometryObject subjectGeometry = data.Features[0].Geometry; @@ -94,4 +153,98 @@ public static Polygon ConvertToPolygon(IGeometryObject geometry) throw new InvalidOperationException("Unsupported geometry type."); } + + /// + /// Collects boundary junctions and counts segments between them. + /// + /// The closed boundary paths. + /// The junction positions and segment counts. + private static (List Nodes, Dictionary<(int Start, int End), int> Edges) BuildBoundaryGraph(IEnumerable paths) + { + List nodes = []; + Dictionary indices = []; + Dictionary<(int Start, int End), int> edges = []; + foreach (PathD path in paths) + { + for (int i = 0; i < path.Count; i++) + { + PointD point = path[i]; + PointD next = path[(i + 1) % path.Count]; + Vertex first = new(point.x, point.y); + Vertex second = new(next.x, next.y); + if (first == second) + { + // A repeated closing vertex adds no segment. + continue; + } + + int start = GetBoundaryNodeIndex(first, indices, nodes); + int end = GetBoundaryNodeIndex(second, indices, nodes); + (int, int) edge = start < end ? (start, end) : (end, start); + edges[edge] = edges.GetValueOrDefault(edge) + 1; + } + } + + return (nodes, edges); + } + + /// + /// Gets the shared index for a boundary junction. + /// + /// The junction position. + /// The positions already indexed. + /// The indexed junctions. + /// The junction index. + private static int GetBoundaryNodeIndex(Vertex point, Dictionary indices, List nodes) + { + if (!indices.TryGetValue(point, out int index)) + { + index = nodes.Count; + indices.Add(point, index); + nodes.Add(point); + } + + return index; + } + + /// + /// Finds the closest reference junction without a fixed distance threshold. + /// + /// The actual junction. + /// The reference junctions sorted by X. + /// The X-coordinate comparer used for sorting. + /// The closest junction's original index. + private static int FindNearestBoundaryNode( + Vertex point, + List<(Vertex Point, int Index)> ordered, + IComparer<(Vertex Point, int Index)> comparer) + { + int position = ordered.BinarySearch((point, 0), comparer); + int right = position < 0 ? ~position : position; + int left = right - 1; + double bestDistance = double.PositiveInfinity; + int bestIndex = -1; + while (left >= 0 || right < ordered.Count) + { + double leftX = left >= 0 ? ordered[left].Point.X - point.X : double.PositiveInfinity; + double rightX = right < ordered.Count ? ordered[right].Point.X - point.X : double.PositiveInfinity; + double leftDistance = leftX * leftX; + double rightDistance = rightX * rightX; + if (Math.Min(leftDistance, rightDistance) > bestDistance) + { + // A greater X distance alone rules out all later candidates. + break; + } + + (Vertex candidate, int index) = leftDistance <= rightDistance ? ordered[left--] : ordered[right++]; + double distance = Vertex.DistanceSquared(point, candidate); + if (distance < bestDistance) + { + bestDistance = distance; + bestIndex = index; + } + } + + return bestIndex; + } } diff --git a/tests/PolygonClipper.Tests/TestPolygonUtilitiesTests.cs b/tests/PolygonClipper.Tests/TestPolygonUtilitiesTests.cs index 709232c..428d6bb 100644 --- a/tests/PolygonClipper.Tests/TestPolygonUtilitiesTests.cs +++ b/tests/PolygonClipper.Tests/TestPolygonUtilitiesTests.cs @@ -1,6 +1,7 @@ // Copyright (c) Six Labors. // Licensed under the Six Labors Split License. +using Clipper2Lib; using GeoJson.Feature; namespace SixLabors.PolygonClipper.Tests; @@ -14,6 +15,37 @@ public class TestPolygonUtilitiesTests /// private static readonly (Polygon Subject, Polygon Clipping) Polygons = TestPolygonUtilities.BuildPolygon(Data); + /// + /// Checks that contour grouping does not hide a change in boundary connections. + /// + /// Whether to change the connections between the same junctions. + [Theory] + [InlineData(false)] + [InlineData(true)] + public void BoundaryGraphs_CheckConnectionsAtSharedVertex(bool changeConnection) + { + // Both triangles meet at (2, 2). One contour can follow both boundaries. + PathsD separate = + [ + [new PointD(0, 0), new PointD(2, 0), new PointD(2, 2)], + [new PointD(2, 2), new PointD(4, 2), new PointD(4, 4)] + ]; + + PathD joined = + [ + new PointD(0, 0), new PointD(2, 0), new PointD(2, 2), + new PointD(4, 2), new PointD(4, 4), new PointD(2, 2) + ]; + + if (changeConnection) + { + // Keep the junctions and segment count, but connect different pairs. + (joined[1], joined[3]) = (joined[3], joined[1]); + } + + Assert.Equal(!changeConnection, TestPolygonUtilities.HaveEquivalentBoundaryGraphs([joined], separate)); + } + [Fact] public void ConvertToPolygon_ValidGeometry_ReturnsPolygon() { From eb5cb19adb5ec7aabd38e58a84be94686ee569ea Mon Sep 17 00:00:00 2001 From: James Jackson-South Date: Fri, 30 Oct 2026 16:38:58 +1000 Subject: [PATCH 15/24] Add SVG test output and curved open-path coverage --- .gitignore | 3 + .../FillRuleClippingTests.cs | 119 +++++- .../PolygonClipper.Tests/GenericTestCases.cs | 18 + .../OpenPathClippingTests.cs | 400 +++++++++++++++++- tests/PolygonClipper.Tests/SvgTestOutput.cs | 252 +++++++++++ .../SvgTestOutputTests.cs | 267 ++++++++++++ tests/PolygonClipper.Tests/TestEnvironment.cs | 7 + 7 files changed, 1047 insertions(+), 19 deletions(-) create mode 100644 tests/PolygonClipper.Tests/SvgTestOutput.cs create mode 100644 tests/PolygonClipper.Tests/SvgTestOutputTests.cs diff --git a/.gitignore b/.gitignore index c4a30dc..0d36bf7 100644 --- a/.gitignore +++ b/.gitignore @@ -61,6 +61,9 @@ project.lock.json project.fragment.lock.json artifacts/ +# Test image output +**/Images/ActualOutput + # StyleCop StyleCopReport.xml diff --git a/tests/PolygonClipper.Tests/FillRuleClippingTests.cs b/tests/PolygonClipper.Tests/FillRuleClippingTests.cs index 74694d9..d18c5a2 100644 --- a/tests/PolygonClipper.Tests/FillRuleClippingTests.cs +++ b/tests/PolygonClipper.Tests/FillRuleClippingTests.cs @@ -303,8 +303,26 @@ public void DirectClipping_OverlappingContours_NeedsNoCleanupPass() // doubly covered 5-by-10 middle band and leaves two 3-by-10 pieces. Assert.Equal(110D, Area(nonZero)); Assert.Equal(60D, Area(evenOdd)); - AssertCoverage(subject, clip, nonZero, BooleanOperation.Intersection, FillRule.NonZero, FillRule.EvenOdd); - AssertCoverage(subject, clip, evenOdd, BooleanOperation.Intersection, FillRule.EvenOdd, FillRule.EvenOdd); + AssertCoverage( + nameof(this.DirectClipping_OverlappingContours_NeedsNoCleanupPass), + string.Empty, + string.Empty, + subject, + clip, + nonZero, + BooleanOperation.Intersection, + FillRule.NonZero, + FillRule.EvenOdd); + AssertCoverage( + nameof(this.DirectClipping_OverlappingContours_NeedsNoCleanupPass), + string.Empty, + string.Empty, + subject, + clip, + evenOdd, + BooleanOperation.Intersection, + FillRule.EvenOdd, + FillRule.EvenOdd); } /// @@ -323,7 +341,16 @@ public void DirectClipping_SelfIntersection_PreservesBothNonZeroLobes() Assert.Equal(1250D, Area(result)); Assert.Equal(new Vertex(25, 25), result.GetBoundingBox().Min); Assert.Equal(new Vertex(75, 75), result.GetBoundingBox().Max); - AssertCoverage(subject, clip, result, BooleanOperation.Intersection, FillRule.NonZero, FillRule.EvenOdd); + AssertCoverage( + nameof(this.DirectClipping_SelfIntersection_PreservesBothNonZeroLobes), + string.Empty, + string.Empty, + subject, + clip, + result, + BooleanOperation.Intersection, + FillRule.NonZero, + FillRule.EvenOdd); } /// @@ -369,7 +396,16 @@ public void DenseStars_ExplicitRules_MatchSourceCoverage(int vertexCount) for (int operation = 0; operation < 4; operation++) { Polygon result = Execute(subject, clip, (BooleanOperation)operation, (FillRule)rule, (FillRule)rule); - AssertCoverage(subject, clip, result, (BooleanOperation)operation, (FillRule)rule, (FillRule)rule); + AssertCoverage( + nameof(this.DenseStars_ExplicitRules_MatchSourceCoverage), + string.Empty, + $"VertexCount-{vertexCount}", + subject, + clip, + result, + (BooleanOperation)operation, + (FillRule)rule, + (FillRule)rule); } } } @@ -426,7 +462,16 @@ public void GeographicFixtures_MixedRules_MatchSourceCoverage(string file) for (int rule = 0; rule < 2; rule++) { Polygon result = Execute(subject, clip, (BooleanOperation)operation, (FillRule)rule, FillRule.NonZero); - AssertCoverage(subject, clip, result, (BooleanOperation)operation, (FillRule)rule, FillRule.NonZero); + AssertCoverage( + nameof(this.GeographicFixtures_MixedRules_MatchSourceCoverage), + Path.GetFileNameWithoutExtension(file), + string.Empty, + subject, + clip, + result, + (BooleanOperation)operation, + (FillRule)rule, + FillRule.NonZero); } } } @@ -447,7 +492,16 @@ public void ExistingDefectFixtures_ExplicitRules_MatchSourceCoverage(string test for (int clipRule = 0; clipRule < 4; clipRule++) { Polygon result = Execute(subject, clip, (BooleanOperation)operation, (FillRule)subjectRule, (FillRule)clipRule); - AssertCoverage(subject, clip, result, (BooleanOperation)operation, (FillRule)subjectRule, (FillRule)clipRule); + AssertCoverage( + nameof(this.ExistingDefectFixtures_ExplicitRules_MatchSourceCoverage), + Path.GetFileNameWithoutExtension(testCaseFile), + string.Empty, + subject, + clip, + result, + (BooleanOperation)operation, + (FillRule)subjectRule, + (FillRule)clipRule); } } } @@ -471,7 +525,16 @@ public void SeededSelfCrossingContours_MixedRules_MatchSourceCoverage() for (int operation = 0; operation < 4; operation++) { Polygon result = Execute(subject, clip, (BooleanOperation)operation, (FillRule)subjectRule, (FillRule)clipRule); - AssertCoverage(subject, clip, result, (BooleanOperation)operation, (FillRule)subjectRule, (FillRule)clipRule); + AssertCoverage( + nameof(this.SeededSelfCrossingContours_MixedRules_MatchSourceCoverage), + string.Empty, + string.Empty, + subject, + clip, + result, + (BooleanOperation)operation, + (FillRule)subjectRule, + (FillRule)clipRule); } } } @@ -575,7 +638,16 @@ public void BinaryOperations_MixedRules_MatchOriginalWinding( (Polygon subject, Polygon clip) = Inputs(geometry); Polygon result = Execute(subject, clip, operation, subjectRule, clipRule); - AssertCoverage(subject, clip, result, operation, subjectRule, clipRule); + AssertCoverage( + nameof(this.BinaryOperations_MixedRules_MatchOriginalWinding), + string.Empty, + $"Geometry-{geometry}", + subject, + clip, + result, + operation, + subjectRule, + clipRule); } /// @@ -616,14 +688,39 @@ public void Normalize_TranslatedUnitRings_PreservesSmallArea() /// /// Checks output against signed source coverage away from input boundaries. /// + /// The test method name. + /// The input file name without an extension, or an empty string. + /// The invariant input parameter details, or an empty string. /// The original subject contours. /// The original clipping contours. /// The clipped geometry. /// The Boolean operation. /// The subject rule. /// The clipping rule. - private static void AssertCoverage(Polygon subject, Polygon clip, Polygon result, BooleanOperation operation, FillRule subjectRule, FillRule clipRule) - { + private static void AssertCoverage( + string testName, + string sourceName, + string inputDetails, + Polygon subject, + Polygon clip, + Polygon result, + BooleanOperation operation, + FillRule subjectRule, + FillRule clipRule) + { + // Generated samples replace this test's current result. A failure leaves the failing geometry available. + string group = sourceName.Length == 0 + ? nameof(FillRuleClippingTests) + : Path.Combine(nameof(FillRuleClippingTests), sourceName); + + string details = $"Operation-{operation}_SubjectRule-{subjectRule}_ClipRule-{clipRule}"; + if (inputDetails.Length > 0) + { + details = $"{inputDetails}_{details}"; + } + + string svgPath = SvgTestOutput.SaveSvg(group, testName, details, subject, clip, result); + Box2 bounds = subject.GetBoundingBox().Add(clip.GetBoundingBox()); for (int y = 0; y < 9; y++) { @@ -649,7 +746,7 @@ private static void AssertCoverage(Polygon subject, Polygon clip, Polygon result bool actual = Winding(result, point) != 0; if (expected != actual) { - Assert.Fail($"{operation}, {subjectRule}/{clipRule}, point {point}: expected {expected}." + + Assert.Fail($"{operation}, {subjectRule}/{clipRule}, point {point}: expected {expected}.\nSVG: {svgPath}" + $"\nSubject: {subject.ToDebugString()}\nClip: {clip.ToDebugString()}\nResult: {result.ToDebugString()}"); } } diff --git a/tests/PolygonClipper.Tests/GenericTestCases.cs b/tests/PolygonClipper.Tests/GenericTestCases.cs index fb2f66d..335f2af 100644 --- a/tests/PolygonClipper.Tests/GenericTestCases.cs +++ b/tests/PolygonClipper.Tests/GenericTestCases.cs @@ -38,6 +38,18 @@ public void GenericTestCase(string testCaseFile) Polygon expected = result.Coordinates; Polygon actual = result.Operation(subject, clipping); + string group = Path.Combine(nameof(GenericTestCases), Path.GetFileNameWithoutExtension(testCaseFile)); + string path = SvgTestOutput.SaveSvg( + group, + nameof(this.GenericTestCase), + $"Operation-{result.Name}", + subject, + clipping, + actual, + expected); + + this.testOutputHelper.WriteLine(path); + Assert.Equal(expected.Count, actual.Count); for (int i = 0; i < expected.Count; i++) { @@ -97,6 +109,7 @@ private static List ExtractExpectedResults(List feature return new ExpectedResult { + Name = mode, Operation = operation, Coordinates = TestPolygonUtilities.ConvertToPolygon(feature.Geometry) }; @@ -104,6 +117,11 @@ private static List ExtractExpectedResults(List feature private sealed class ExpectedResult { + /// + /// Gets or sets the operation name stored in the GeoJSON fixture. + /// + public string Name { get; set; } + public Func Operation { get; set; } public Polygon Coordinates { get; set; } diff --git a/tests/PolygonClipper.Tests/OpenPathClippingTests.cs b/tests/PolygonClipper.Tests/OpenPathClippingTests.cs index b28d070..ca1db94 100644 --- a/tests/PolygonClipper.Tests/OpenPathClippingTests.cs +++ b/tests/PolygonClipper.Tests/OpenPathClippingTests.cs @@ -4,7 +4,7 @@ namespace SixLabors.PolygonClipper.Tests; /// -/// Checks open clipping against exact segment and rectangle constructions. +/// Checks open clipping against exact points, line pieces and area boundaries. /// public class OpenPathClippingTests { @@ -27,7 +27,7 @@ public void CrossingLines_ReturnPointOrCutContours(BooleanOperation operation) Polygon subject = [Open(left, right)]; Polygon clip = [Open(bottom, top)]; - Polygon result = Execute(subject, clip, operation); + Polygon result = Execute(subject, clip, operation, nameof(this.CrossingLines_ReturnPointOrCutContours), $"Operation-{operation}", null); if (operation == BooleanOperation.Intersection) { Contour intersection = Assert.Single(result); @@ -71,7 +71,8 @@ public void CollinearOverlap_UsesLineMembership(BooleanOperation operation, bool Vertex d = new(15, 0); Contour second = reverse ? Open(d, b) : Open(b, d); - Polygon result = Execute([Open(a, c)], [second], operation); + string details = $"Operation-{operation}_Reverse-{reverse}"; + Polygon result = Execute([Open(a, c)], [second], operation, nameof(this.CollinearOverlap_UsesLineMembership), details, null); switch (operation) { case BooleanOperation.Intersection: @@ -278,7 +279,7 @@ public void GridLines_AllCrossingsAreRetained(BooleanOperation operation) vertical.Add(Open(new(i, -1), new(i, size))); } - Polygon result = Execute(horizontal, vertical, operation); + Polygon result = Execute(horizontal, vertical, operation, nameof(this.GridLines_AllCrossingsAreRetained), $"Operation-{operation}", null); if (operation == BooleanOperation.Intersection) { Assert.Equal(size * size, result.Count); @@ -361,7 +362,14 @@ public void ConstructedCrossings_MatchKnownIntegerGeometry(BooleanOperation oper Vertex c = point - second; Vertex d = point + second; - Polygon result = Execute([Open(a, b)], [Open(c, d)], operation); + // Keep the current generated sample. A failure leaves its geometry in this same file. + Polygon result = Execute( + [Open(a, b)], + [Open(c, d)], + operation, + nameof(this.ConstructedCrossings_MatchKnownIntegerGeometry), + $"Operation-{operation}", + null); if (operation == BooleanOperation.Intersection) { Assert.Equal(point, Assert.Single(Assert.Single(result))); @@ -395,6 +403,312 @@ public void SelfCrossingPolyline_RetainsNodedLinework() Assert.Contains(new Vertex(-2, 2), cycle); } + /// + /// Checks four crossings between sampled waves and the bends between their cut endpoints. + /// + /// The requested operation. + /// Whether both input paths run backwards. + [Theory] + [InlineData(BooleanOperation.Intersection, false)] + [InlineData(BooleanOperation.Intersection, true)] + [InlineData(BooleanOperation.Union, false)] + [InlineData(BooleanOperation.Union, true)] + [InlineData(BooleanOperation.Difference, false)] + [InlineData(BooleanOperation.Difference, true)] + [InlineData(BooleanOperation.Xor, false)] + [InlineData(BooleanOperation.Xor, true)] + public void SampledWaves_PreserveAllCrossingsAndBends(BooleanOperation operation, bool reverse) + { + Polygon subject = + [Open([ + new(-12, 4), new(-10, 5), new(-8, 4), new(-6, -4), new(-4, -5), new(-2, -4), + new(0, 4), new(2, 5), new(4, 4), new(6, -4), new(8, -5), new(10, -4), new(12, 4) + ])]; + Polygon clip = + [Open([ + new(-12, -4), new(-10, -5), new(-8, -4), new(-6, 4), new(-4, 5), new(-2, 4), + new(0, -4), new(2, -5), new(4, -4), new(6, 4), new(8, 5), new(10, 4), new(12, -4) + ])]; + + // The paths are reflections in y = 0. Their crossing segments meet at their midpoints. + // The other segments occupy separate X intervals or remain on opposite sides of y = 0. + Polygon expected = operation == BooleanOperation.Intersection + ? [Open(new Vertex(-7, 0)), Open(new Vertex(-1, 0)), Open(new Vertex(5, 0)), Open(new Vertex(11, 0))] + : + [ + Open(new(-12, 4), new(-10, 5), new(-8, 4), new(-7, 0)), + Open(new(-7, 0), new(-6, -4), new(-4, -5), new(-2, -4), new(-1, 0)), + Open(new(-1, 0), new(0, 4), new(2, 5), new(4, 4), new(5, 0)), + Open(new(5, 0), new(6, -4), new(8, -5), new(10, -4), new(11, 0)), + Open(new(11, 0), new(12, 4)) + ]; + + if (operation is BooleanOperation.Union or BooleanOperation.Xor) + { + // Reflect the known subject pieces to obtain the clip pieces. + int subjectCount = expected.Count; + for (int i = 0; i < subjectCount; i++) + { + Contour reflected = new() { IsClosed = false }; + foreach (Vertex vertex in expected[i]) + { + reflected.Add(new(vertex.X, -vertex.Y)); + } + + expected.Add(reflected); + } + } + + if (reverse) + { + subject[0].Reverse(); + clip[0].Reverse(); + } + + string details = $"Operation-{operation}_Reverse-{reverse}"; + Polygon actual = Execute(subject, clip, operation, nameof(this.SampledWaves_PreserveAllCrossingsAndBends), details, expected); + AssertOpenPaths(actual, expected); + } + + /// + /// Checks densely sampled curves whose four crossings are known polynomial roots. + /// + /// The requested operation. + /// Whether both input paths run backwards. + [Theory] + [InlineData(BooleanOperation.Intersection, false)] + [InlineData(BooleanOperation.Intersection, true)] + [InlineData(BooleanOperation.Union, false)] + [InlineData(BooleanOperation.Union, true)] + [InlineData(BooleanOperation.Difference, false)] + [InlineData(BooleanOperation.Difference, true)] + [InlineData(BooleanOperation.Xor, false)] + [InlineData(BooleanOperation.Xor, true)] + public void SampledQuartic_PreservesFourVertexCrossings(BooleanOperation operation, bool reverse) + { + Contour first = new() { IsClosed = false }; + Contour second = new() { IsClosed = false }; + for (int sample = -16; sample <= 16; sample++) + { + Vertex point = SampleQuartic(sample); + first.Add(point); + second.Add(new(point.X, -point.Y)); + } + + Polygon subject = [first]; + Polygon clip = [second]; + Polygon expected; + if (operation == BooleanOperation.Intersection) + { + expected = [Open(new Vertex(-3, 0)), Open(new Vertex(-1, 0)), Open(new Vertex(1, 0)), Open(new Vertex(3, 0))]; + } + else + { + expected = []; + + // For y = (x^2 - 9)(x^2 - 1) / 16 and its reflection, the only crossings + // are x = -3, -1, 1 and 3. These fixed intervals define the expected pieces. + int[] endpoints = [-16, -12, -4, 4, 12, 16]; + for (int i = 0; i < endpoints.Length - 1; i++) + { + Contour piece = new() { IsClosed = false }; + for (int sample = endpoints[i]; sample <= endpoints[i + 1]; sample++) + { + Vertex point = SampleQuartic(sample); + piece.Add(point); + } + + expected.Add(piece); + if (operation is BooleanOperation.Union or BooleanOperation.Xor) + { + Contour reflection = new() { IsClosed = false }; + foreach (Vertex point in piece) + { + reflection.Add(new(point.X, -point.Y)); + } + + expected.Add(reflection); + } + } + } + + if (reverse) + { + first.Reverse(); + second.Reverse(); + } + + string details = $"Operation-{operation}_Reverse-{reverse}"; + Polygon actual = Execute(subject, clip, operation, nameof(this.SampledQuartic_PreservesFourVertexCrossings), details, expected); + AssertOpenPaths(actual, expected); + } + + /// + /// Checks repeated area and hole crossings, retained bends and isolated corner contacts. + /// + /// The requested operation. + /// Whether the source path runs backwards. + [Theory] + [InlineData(BooleanOperation.Intersection, false)] + [InlineData(BooleanOperation.Intersection, true)] + [InlineData(BooleanOperation.Union, false)] + [InlineData(BooleanOperation.Union, true)] + [InlineData(BooleanOperation.Difference, false)] + [InlineData(BooleanOperation.Difference, true)] + [InlineData(BooleanOperation.Xor, false)] + [InlineData(BooleanOperation.Xor, true)] + public void CurvedPath_ClipsAgainstTwoHolesAndCornerContacts(BooleanOperation operation, bool reverse) + { + Polygon subject = + [Open([ + new(-2, 2), new(1, 2), new(2, 3), new(4, 3), new(6, 2), new(8, 2), new(10, 3), + new(13, 3), new(14, 4), new(13, 6), new(10, 6), new(8, 7), new(6, 7), new(4, 6), + new(2, 6), new(-2, 8), new(0, 10), new(4, 11), new(8, 11), new(12, 10), new(14, 8) + ])]; + Contour firstHole = Rectangle(3, 1, 5, 9); + Contour secondHole = Rectangle(7, 1, 9, 9); + firstHole.Reverse(); + secondHole.Reverse(); + Polygon clip = [Rectangle(0, 0, 12, 10), firstHole, secondHole]; + clip[0].AddHoleIndex(1); + clip[0].AddHoleIndex(2); + firstHole.ParentIndex = secondHole.ParentIndex = 0; + firstHole.Depth = secondHole.Depth = 1; + + // Vertical boundaries cut these segments at integer or half-integer coordinates. + // The upper arc touches (0, 10) and (12, 10), but remains outside between those points. + Polygon expected = operation == BooleanOperation.Intersection + ? + [ + Open(new(0, 2), new(1, 2), new(2, 3), new(3, 3)), + Open(new(5, 2.5), new(6, 2), new(7, 2)), + Open(new(9, 2.5), new(10, 3), new(12, 3)), + Open(new(12, 6), new(10, 6), new(9, 6.5)), + Open(new(7, 7), new(6, 7), new(5, 6.5)), + Open(new(3, 6), new(2, 6), new(0, 7)), + Open(new Vertex(0, 10)), + Open(new Vertex(12, 10)) + ] + : + [ + Open(new(-2, 2), new(0, 2)), + Open(new(3, 3), new(4, 3), new(5, 2.5)), + Open(new(7, 2), new(8, 2), new(9, 2.5)), + Open(new(12, 3), new(13, 3), new(14, 4), new(13, 6), new(12, 6)), + Open(new(9, 6.5), new(8, 7), new(7, 7)), + Open(new(5, 6.5), new(4, 6), new(3, 6)), + Open(new(0, 7), new(-2, 8), new(0, 10)), + Open(new(0, 10), new(4, 11), new(8, 11), new(12, 10)), + Open(new(12, 10), new(14, 8)) + ]; + + Polygon expectedLines = expected; + bool retainsArea = operation is BooleanOperation.Union or BooleanOperation.Xor; + if (retainsArea) + { + expected = clip.DeepClone(); + foreach (Contour line in expectedLines) + { + expected.Add(line); + } + } + + if (reverse) + { + subject[0].Reverse(); + } + + string details = $"Operation-{operation}_Reverse-{reverse}"; + Polygon actual = Execute(subject, clip, operation, nameof(this.CurvedPath_ClipsAgainstTwoHolesAndCornerContacts), details, expected); + Polygon actualLines = []; + List actualArea = []; + foreach (Contour contour in actual) + { + if (contour.IsClosed) + { + actualArea.Add(contour); + } + else + { + actualLines.Add(contour); + } + } + + AssertOpenPaths(actualLines, expectedLines); + Assert.Equal(retainsArea ? 3 : 0, actualArea.Count); + if (retainsArea) + { + // Line clipping must retain the rectangle and its two holes. + foreach (Contour reference in clip) + { + Assert.Contains(actualArea, contour => contour.GetBoundingBox() == reference.GetBoundingBox() && + PolygonUtilities.Area(contour.AsVertexSpan()) == PolygonUtilities.Area(reference.AsVertexSpan())); + } + } + } + + /// + /// Checks a shared curved span and a separate crossing in the same pair of paths. + /// + /// The requested operation. + /// Whether both paths run backwards. + [Theory] + [InlineData(BooleanOperation.Intersection, false)] + [InlineData(BooleanOperation.Intersection, true)] + [InlineData(BooleanOperation.Union, false)] + [InlineData(BooleanOperation.Union, true)] + [InlineData(BooleanOperation.Difference, false)] + [InlineData(BooleanOperation.Difference, true)] + [InlineData(BooleanOperation.Xor, false)] + [InlineData(BooleanOperation.Xor, true)] + public void SharedCurvedSpan_RetainsOverlapAndSeparateCrossing(BooleanOperation operation, bool reverse) + { + Polygon subject = + [Open(new(-6, 0), new(-4, 3), new(-2, 4), new(0, 3), new(2, 0), new(4, -3), new(6, -4), new(8, -3), new(10, 0))]; + Polygon clip = + [Open(new(-6, -2), new(-4, 3), new(-2, 4), new(0, 3), new(2, 0), new(4, 2), new(6, 0), new(8, -3), new(10, -1))]; + + Polygon expected = operation == BooleanOperation.Intersection + ? + [ + Open(new(-4, 3), new(-2, 4)), + Open(new(-2, 4), new(0, 3)), + Open(new(0, 3), new(2, 0)), + Open(new Vertex(8, -3)) + ] + : + [ + Open(new(-6, 0), new(-4, 3)), + Open(new(2, 0), new(4, -3), new(6, -4), new(8, -3)), + Open(new(8, -3), new(10, 0)) + ]; + + if (operation is BooleanOperation.Union or BooleanOperation.Xor) + { + expected.Add(Open(new(-6, -2), new(-4, 3))); + expected.Add(Open(new(2, 0), new(4, 2), new(6, 0), new(8, -3))); + expected.Add(Open(new(8, -3), new(10, -1))); + } + + if (operation == BooleanOperation.Union) + { + // Both operands meet at each shared vertex, so those vertices remain cut endpoints. + expected.Add(Open(new(-4, 3), new(-2, 4))); + expected.Add(Open(new(-2, 4), new(0, 3))); + expected.Add(Open(new(0, 3), new(2, 0))); + } + + if (reverse) + { + subject[0].Reverse(); + clip[0].Reverse(); + } + + string details = $"Operation-{operation}_Reverse-{reverse}"; + Polygon actual = Execute(subject, clip, operation, nameof(this.SharedCurvedSpan_RetainsOverlapAndSeparateCrossing), details, expected); + AssertOpenPaths(actual, expected); + } + /// /// Builds an explicitly open input without adding a closing vertex. /// @@ -411,6 +725,21 @@ private static Contour Open(params Vertex[] vertices) return contour; } + /// + /// Samples y = (x^2 - 9)(x^2 - 1) / 16 at quarter-unit X positions. + /// + /// Four times the X coordinate. + /// The exact double coordinates of this polynomial sample. + private static Vertex SampleQuartic(int sample) + { + double x = sample / 4D; + double squared = x * x; + + // Quarter-unit inputs and the vertical scale of 1/16 use powers of two. + // Every source coordinate is exact, including the four zero crossings. + return new(x, (squared - 9) * (squared - 1) / 16D); + } + /// /// Builds a counterclockwise closed rectangle with implicit closure. /// @@ -423,14 +752,19 @@ private static Contour Rectangle(double left, double bottom, double right, doubl => [new(left, bottom), new(right, bottom), new(right, top), new(left, top)]; /// - /// Executes the requested existing public operation. + /// Executes the public operation and saves the actual and available expected geometry. /// /// The subject contours. /// The clip contours. /// The requested operation. + /// The test method name. + /// The invariant parameter details for the file name. + /// The known expected geometry, or null when unavailable. /// The clipped contours. - private static Polygon Execute(Polygon subject, Polygon clip, BooleanOperation operation) - => operation switch + private static Polygon Execute( + Polygon subject, Polygon clip, BooleanOperation operation, string testName, string details, Polygon expected) + { + Polygon result = operation switch { BooleanOperation.Intersection => PolygonClipper.Intersection(subject, clip, FillRule.NonZero), BooleanOperation.Union => PolygonClipper.Union(subject, clip, FillRule.NonZero), @@ -438,6 +772,56 @@ private static Polygon Execute(Polygon subject, Polygon clip, BooleanOperation o _ => PolygonClipper.Xor(subject, clip, FillRule.NonZero) }; + if (expected is null) + { + SvgTestOutput.SaveSvg(nameof(OpenPathClippingTests), testName, details, subject, clip, result); + } + else + { + SvgTestOutput.SaveSvg(nameof(OpenPathClippingTests), testName, details, subject, clip, result, expected); + } + + return result; + } + + /// + /// Checks every open contour's vertices in either direction, including points and bends. + /// + /// The clipped open geometry. + /// The independently constructed open geometry. + private static void AssertOpenPaths(Polygon actual, Polygon expected) + { + Assert.Equal(expected.Count, actual.Count); + Assert.All(actual, contour => + { + Assert.False(contour.IsClosed); + Assert.Null(contour.ParentIndex); + Assert.Equal(0, contour.Depth); + Assert.Equal(0, contour.HoleCount); + }); + + foreach (Contour reference in expected) + { + Assert.Contains(actual, contour => + { + if (contour.Count != reference.Count) + { + return false; + } + + bool forward = true; + bool backward = true; + for (int i = 0; i < reference.Count; i++) + { + forward &= contour[i] == reference[i]; + backward &= contour[i] == reference[reference.Count - 1 - i]; + } + + return forward || backward; + }); + } + } + /// /// Checks exact undirected line pieces without depending on contour ordering or traversal direction. /// diff --git a/tests/PolygonClipper.Tests/SvgTestOutput.cs b/tests/PolygonClipper.Tests/SvgTestOutput.cs new file mode 100644 index 0000000..8767ed3 --- /dev/null +++ b/tests/PolygonClipper.Tests/SvgTestOutput.cs @@ -0,0 +1,252 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +using System.Globalization; +using System.Text; +using System.Xml.Linq; + +namespace SixLabors.PolygonClipper.Tests; + +/// +/// Saves polygon test geometry as SVG panels with a shared scale. +/// +internal static class SvgTestOutput +{ + private const int PanelSize = 400; + private const int TitleHeight = 40; + private const int Padding = 20; + private const double LineWidth = 1.5; + private static readonly XNamespace Svg = "http://www.w3.org/2000/svg"; + + /// + /// Saves the inputs and actual output on every call. + /// + /// The test class and any input subfolder. + /// The test method name. + /// The invariant parameter details, separated by underscores, or an empty string. + /// The subject geometry. + /// The clip geometry. + /// The actual output. + /// The full path to the SVG file. + public static string SaveSvg(string testGroup, string testName, string details, Polygon subject, Polygon clip, Polygon actual) + => SaveSvgCore(GetTestOutputFileName(testGroup, testName, details), subject, clip, actual, null); + + /// + /// Saves the inputs, actual output and available expected geometry on every call. + /// + /// The test class and any input subfolder. + /// The test method name. + /// The invariant parameter details, separated by underscores, or an empty string. + /// The subject geometry. + /// The clip geometry. + /// The actual output. + /// The expected geometry, including an expected empty result. + /// The full path to the SVG file. + public static string SaveSvg(string testGroup, string testName, string details, Polygon subject, Polygon clip, Polygon actual, Polygon expected) + => SaveSvgCore(GetTestOutputFileName(testGroup, testName, details), subject, clip, actual, expected); + + /// + /// Builds an output path using the ImageSharp test group, method and parameter naming convention. + /// + /// The test class and any input subfolder. + /// The test method name. + /// The invariant parameter details, separated by underscores, or an empty string. + /// The full output path. + public static string GetTestOutputFileName(string testGroup, string testName, string details) + { + string fileName = details.Length == 0 ? testName : $"{testName}_{details}"; + return Path.Combine(TestEnvironment.ActualOutputDirectoryFullPath, testGroup, fileName + ".svg"); + } + + /// + /// Fits all available geometry to one shared view and writes the panels. + /// + /// The full output path. + /// The subject geometry. + /// The clip geometry. + /// The actual output. + /// The expected geometry, or null when the test has none. + /// The full path to the SVG file. + private static string SaveSvgCore(string outputPath, Polygon subject, Polygon clip, Polygon actual, Polygon expected) + { + Polygon[] geometry = expected is null ? [subject, clip, actual] : [subject, clip, actual, expected]; + Box2? bounds = null; + foreach (Polygon polygon in geometry) + { + foreach (Contour contour in polygon) + { + // Empty contours have no bounds. Their default box would add an unrelated origin. + if (contour.Count > 0) + { + Box2 contourBounds = contour.GetBoundingBox(); + bounds = bounds is null ? contourBounds : bounds.Value.Add(contourBounds); + } + } + } + + Box2 box = bounds ?? default; + double scale = Math.Max(Math.Max(Math.Abs(box.Min.X), Math.Abs(box.Max.X)), Math.Max(Math.Abs(box.Min.Y), Math.Abs(box.Max.Y))); + if (scale == 0) + { + scale = 1; + } + + // SVG viewers can lose very small or large coordinates. Scale before subtraction + // to fit those inputs without overflow. Each contour also retains its source coordinates. + Vertex min = box.Min / scale; + Vertex max = box.Max / scale; + double extent = Math.Max(max.X - min.X, max.Y - min.Y); + if (extent == 0) + { + // An empty scene or one point still needs a visible viewport. + extent = 1; + } + + Vertex origin = new((min.X + max.X - extent) / 2, (min.Y + max.Y + extent) / 2); + int panelCount = expected is null ? 2 : 3; + XElement root = new( + Svg + "svg", + new XAttribute("viewBox", $"0 0 {PanelSize * panelCount} {PanelSize + TitleHeight}"), + new XElement(Svg + "title", Path.GetFileNameWithoutExtension(outputPath)), + new XElement(Svg + "desc", "All panels use outlines. Point markers match the line width. Paths retain source coordinates and hierarchy.")); + + XElement inputs = AddPanel(root, 0, "inputs", "Inputs: subject blue, clip orange"); + AddGeometry(inputs, subject, "#2563eb", origin, scale, extent); + AddGeometry(inputs, clip, "#ea580c", origin, scale, extent); + AddGeometry(AddPanel(root, 1, "actual", "Actual"), actual, "#15803d", origin, scale, extent); + if (expected is not null) + { + AddGeometry(AddPanel(root, 2, "expected", "Expected"), expected, "#7e22ce", origin, scale, extent); + } + + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + new XDocument(root).Save(outputPath); + return outputPath; + } + + /// + /// Adds a labeled panel with the same viewport dimensions as the other panels. + /// + /// The SVG document root. + /// The panel position. + /// The panel identifier. + /// The visible panel label. + /// The group that receives the panel geometry. + private static XElement AddPanel(XElement root, int index, string id, string label) + { + int x = index * PanelSize; + XElement group = new(Svg + "g"); + root.Add(new XElement( + Svg + "g", + new XAttribute("id", id), + new XElement( + Svg + "rect", + new XAttribute("x", x), + new XAttribute("width", PanelSize), + new XAttribute("height", PanelSize + TitleHeight), + new XAttribute("fill", "white"), + new XAttribute("stroke", "#cbd5e1")), + new XElement( + Svg + "text", + new XAttribute("x", x + Padding), + new XAttribute("y", 25), + new XAttribute("font-family", "sans-serif"), + new XAttribute("font-size", 14), + label), + new XElement( + Svg + "svg", + new XAttribute("x", x), + new XAttribute("y", TitleHeight), + new XAttribute("width", PanelSize), + new XAttribute("height", PanelSize), + new XAttribute("viewBox", $"0 0 {PanelSize} {PanelSize}"), + group))); + + return group; + } + + /// + /// Draws contour outlines and square point markers that match the line width. + /// + /// The panel geometry group. + /// The source polygon. + /// The geometry color. + /// The shared upper-left origin after coordinate scaling. + /// The shared coordinate scale. + /// The shared square extent after coordinate scaling. + private static void AddGeometry(XElement group, Polygon polygon, string color, Vertex origin, double scale, double extent) + { + for (int i = 0; i < polygon.Count; i++) + { + Contour contour = polygon[i]; + if (contour.Count == 0) + { + continue; + } + + StringBuilder path = new(); + StringBuilder source = new(); + foreach (Vertex vertex in contour) + { + Vertex point = Project(vertex, origin, scale, extent); + string command = path.Length == 0 ? "M " : " L "; + path.Append(command).Append(point.X.ToString("R", CultureInfo.InvariantCulture)) + .Append(' ').Append(point.Y.ToString("R", CultureInfo.InvariantCulture)); + + source.Append(command).Append(vertex.X.ToString("R", CultureInfo.InvariantCulture)) + .Append(' ').Append(vertex.Y.ToString("R", CultureInfo.InvariantCulture)); + } + + if (contour.IsClosed) + { + path.Append(" Z"); + source.Append(" Z"); + } + + XElement outline = new( + Svg + "path", + new XAttribute("class", "contour"), + new XAttribute("d", path.ToString()), + new XAttribute("fill", "none"), + new XAttribute("stroke", color), + new XAttribute("stroke-width", LineWidth), + new XAttribute("data-contour", i), + new XAttribute("data-closed", contour.IsClosed), + new XAttribute("data-depth", contour.Depth), + new XAttribute("data-parent", contour.ParentIndex?.ToString(CultureInfo.InvariantCulture) ?? "none"), + new XAttribute("data-holes", string.Join(" ", Enumerable.Range(0, contour.HoleCount).Select(contour.GetHoleIndex))), + new XAttribute("data-source-d", source.ToString()), + new XElement(Svg + "title", $"Contour {i}. {(contour.IsClosed ? "Closed" : "Open")}. Depth {contour.Depth}.")); + + group.Add(outline); + if (contour.Count == 1) + { + // Center the square on the point and match the contour line thickness. + Vertex point = Project(contour[0], origin, scale, extent); + group.Add(new XElement( + Svg + "rect", + new XAttribute("class", "point"), + new XAttribute("x", point.X - (LineWidth / 2)), + new XAttribute("y", point.Y - (LineWidth / 2)), + new XAttribute("width", LineWidth), + new XAttribute("height", LineWidth), + new XAttribute("fill", color), + new XElement(Svg + "title", FormattableString.Invariant($"Point ({contour[0].X:R}, {contour[0].Y:R}). Marker only.")))); + } + } + } + + /// + /// Maps a source vertex to the shared display scale with the Y axis upwards. + /// + /// The source vertex. + /// The shared upper-left origin after coordinate scaling. + /// The shared coordinate scale. + /// The shared square extent after coordinate scaling. + /// The display position in SVG units. + private static Vertex Project(Vertex point, Vertex origin, double scale, double extent) + { + Vertex offset = ((point / scale) - origin) / extent; + return new(Padding + (offset.X * (PanelSize - (2 * Padding))), Padding - (offset.Y * (PanelSize - (2 * Padding)))); + } +} diff --git a/tests/PolygonClipper.Tests/SvgTestOutputTests.cs b/tests/PolygonClipper.Tests/SvgTestOutputTests.cs new file mode 100644 index 0000000..1f22a10 --- /dev/null +++ b/tests/PolygonClipper.Tests/SvgTestOutputTests.cs @@ -0,0 +1,267 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +using System.Globalization; +using System.Xml.Linq; + +namespace SixLabors.PolygonClipper.Tests; + +/// +/// Checks SVG output through real clipping results. +/// +public class SvgTestOutputTests +{ + private static readonly XNamespace Svg = "http://www.w3.org/2000/svg"; + + /// + /// Checks explicit closure even when an open contour repeats its first vertex. + /// + /// Whether the input includes its closing edge. + [Theory] + [InlineData(false)] + [InlineData(true)] + public void SaveSvg_PreservesExplicitClosure(bool closed) + { + Contour contour = new() { IsClosed = closed }; + contour.Add(new(0, 0)); + contour.Add(new(6, 0)); + contour.Add(new(0, 6)); + contour.Add(new(0, 0)); + Polygon subject = [contour]; + Polygon clip = []; + Polygon actual = PolygonClipper.Union(subject, clip, FillRule.NonZero); + string before = subject.ToDebugString(); + + string path = SvgTestOutput.SaveSvg( + nameof(SvgTestOutputTests), nameof(this.SaveSvg_PreservesExplicitClosure), $"Closed-{closed}", subject, clip, actual); + string outputDirectory = Path.Combine(TestEnvironment.SolutionDirectoryFullPath, "tests", "Images", "ActualOutput"); + Assert.StartsWith(outputDirectory + Path.DirectorySeparatorChar, path); + Assert.Equal( + Path.Combine(outputDirectory, nameof(SvgTestOutputTests), $"SaveSvg_PreservesExplicitClosure_Closed-{closed}.svg"), + path); + + XElement root = XDocument.Load(path).Root!; + XElement input = Assert.Single(root.Elements().Single(element => (string)element.Attribute("id") == "inputs") + .Descendants(Svg + "path")); + + Assert.Equal(closed, ((string)input.Attribute("d")!).EndsWith(" Z", StringComparison.Ordinal)); + Assert.Equal(closed, (bool)input.Attribute("data-closed")!); + Assert.Equal("none", (string)input.Attribute("fill")!); + Assert.Equal(before, subject.ToDebugString()); + Assert.Equal(closed, contour.IsClosed); + Assert.DoesNotContain(root.Elements(), element => (string)element.Attribute("id") == "expected"); + } + + /// + /// Checks compound holes, nested islands and a shared scale across a large coordinate range. + /// + /// The source coordinate scale. + [Theory] + [InlineData(1E-90)] + [InlineData(1D)] + [InlineData(1E90)] + public void SaveSvg_PreservesHolesAndIslands(double scale) + { + Polygon subject = + [ + [new(0, 0), new(10 * scale, 0), new(10 * scale, 10 * scale), new(0, 10 * scale)], + [new(2 * scale, 2 * scale), new(8 * scale, 2 * scale), new(8 * scale, 8 * scale), new(2 * scale, 8 * scale)], + [new(4 * scale, 4 * scale), new(6 * scale, 4 * scale), new(6 * scale, 6 * scale), new(4 * scale, 6 * scale)] + ]; + Polygon actual = PolygonClipper.Normalize(subject, FillRule.EvenOdd); + Assert.Equal(3, actual.Count); + string before = actual.ToDebugString(); + + // The expected rings share a direction. Outlines must preserve their closure without adding a filled area. + string details = FormattableString.Invariant($"Scale-{scale:R}"); + string path = SvgTestOutput.SaveSvg( + nameof(SvgTestOutputTests), nameof(this.SaveSvg_PreservesHolesAndIslands), details, subject, [], actual, subject); + + XElement root = XDocument.Load(path).Root!; + XElement actualPanel = root.Elements().Single(element => (string)element.Attribute("id") == "actual"); + XElement expectedPanel = root.Elements().Single(element => (string)element.Attribute("id") == "expected"); + foreach (XElement panel in new[] { actualPanel, expectedPanel }) + { + XElement[] contours = panel.Descendants(Svg + "path").ToArray(); + Assert.Equal(3, contours.Length); + Assert.All(contours, contour => + { + Assert.Equal("contour", (string)contour.Attribute("class")!); + Assert.Equal("none", (string)contour.Attribute("fill")!); + string data = (string)contour.Attribute("d")!; + Assert.Equal(1, data.Count(value => value == 'M')); + Assert.Equal(1, data.Count(value => value == 'Z')); + Assert.DoesNotContain("NaN", data); + Assert.DoesNotContain("Infinity", data); + }); + } + + Assert.All(root.Descendants(Svg + "path"), contour => Assert.Equal("none", (string)contour.Attribute("fill")!)); + + XElement[] outlines = actualPanel.Descendants(Svg + "path").Where(element => (string)element.Attribute("class") == "contour").ToArray(); + for (int i = 0; i < actual.Count; i++) + { + Assert.Equal(actual[i].Depth, (int)outlines[i].Attribute("data-depth")!); + Assert.Equal(actual[i].ParentIndex?.ToString(CultureInfo.InvariantCulture) ?? "none", (string)outlines[i].Attribute("data-parent")!); + string holes = string.Join(" ", Enumerable.Range(0, actual[i].HoleCount).Select(actual[i].GetHoleIndex)); + Assert.Equal(holes, (string)outlines[i].Attribute("data-holes")!); + } + + // Both panels map the same exterior vertex to (20, 380), regardless of source scale. + string expectedExterior = (string)expectedPanel.Descendants(Svg + "path") + .Single(element => (string)element.Attribute("class") == "contour" && (int)element.Attribute("data-contour")! == 0).Attribute("d")!; + Assert.StartsWith("M 20 380", expectedExterior); + Assert.All(root.Descendants(Svg + "svg"), element => Assert.Equal("0 0 400 400", (string)element.Attribute("viewBox")!)); + Assert.Equal(before, actual.ToDebugString()); + } + + /// + /// Checks point results and culture-independent source coordinates. + /// + [Fact] + public void SaveSvg_PreservesPointResults() + { + Polygon subject = [Open(new(-2, 0.5), new(2, 0.5))]; + Polygon clip = [Open(new(0.25, -2), new(0.25, 2))]; + Polygon actual = PolygonClipper.Intersection(subject, clip, FillRule.NonZero); + Assert.Equal(new Vertex(0.25, 0.5), Assert.Single(Assert.Single(actual))); + CultureInfo previous = CultureInfo.CurrentCulture; + try + { + CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("fr-FR"); + + string path = SvgTestOutput.SaveSvg( + nameof(SvgTestOutputTests), nameof(this.SaveSvg_PreservesPointResults), string.Empty, subject, clip, actual); + + XElement root = XDocument.Load(path).Root!; + XElement panel = root.Elements().Single(element => (string)element.Attribute("id") == "actual"); + XElement point = Assert.Single(panel.Descendants(Svg + "rect"), element => (string)element.Attribute("class") == "point"); + XElement outline = Assert.Single(panel.Descendants(Svg + "path"), element => (string)element.Attribute("class") == "contour"); + double lineWidth = (double)outline.Attribute("stroke-width")!; + + Assert.Equal(lineWidth, (double)point.Attribute("width")!); + Assert.Equal(lineWidth, (double)point.Attribute("height")!); + Assert.Equal(222.5, (double)point.Attribute("x")! + (lineWidth / 2), 10); + Assert.Equal(155D, (double)point.Attribute("y")! + (lineWidth / 2), 10); + Assert.Equal((string)outline.Attribute("stroke")!, (string)point.Attribute("fill")!); + Assert.Equal("Point (0.25, 0.5). Marker only.", point.Element(Svg + "title")!.Value); + Assert.Empty(root.Elements(Svg + "text")); + Assert.Equal("0 0 800 440", (string)root.Attribute("viewBox")!); + Assert.Empty(root.Descendants(Svg + "circle")); + Assert.Equal("M 0.25 0.5", (string)outline.Attribute("data-source-d")!); + Assert.False((bool)outline.Attribute("data-closed")!); + Assert.Equal("none", (string)outline.Attribute("fill")!); + } + finally + { + CultureInfo.CurrentCulture = previous; + } + } + + /// + /// Checks open output intervals against available analytic expected geometry. + /// + [Fact] + public void SaveSvg_PreservesOpenOutputAndExpectedGeometry() + { + Polygon subject = [Open(new(-1, 5), new(11, 5))]; + Polygon clip = + [ + [new(0, 0), new(10, 0), new(10, 10), new(0, 10)], + [new(3, 3), new(7, 3), new(7, 7), new(3, 7)] + ]; + Polygon actual = PolygonClipper.Intersection(subject, clip, FillRule.EvenOdd); + Polygon expected = + [ + Open(new(0, 5), new(3, 5)), + Open(new(7, 5), new(10, 5)) + ]; + + string path = SvgTestOutput.SaveSvg( + nameof(SvgTestOutputTests), nameof(this.SaveSvg_PreservesOpenOutputAndExpectedGeometry), string.Empty, subject, clip, actual, expected); + + XElement root = XDocument.Load(path).Root!; + foreach (string id in new[] { "actual", "expected" }) + { + XElement panel = root.Elements().Single(element => (string)element.Attribute("id") == id); + XElement[] lines = panel.Descendants(Svg + "path").ToArray(); + Assert.Equal(2, lines.Length); + Assert.All(lines, line => + { + Assert.Equal("none", (string)line.Attribute("fill")!); + Assert.False((bool)line.Attribute("data-closed")!); + Assert.DoesNotContain("Z", (string)line.Attribute("d")!); + }); + } + } + + /// + /// Checks empty output and the distinction between missing and empty expected geometry. + /// + /// Whether the test supplies an empty expected result. + [Theory] + [InlineData(false)] + [InlineData(true)] + public void SaveSvg_WritesEmptyResults(bool hasExpected) + { + Polygon empty = []; + Polygon actual = PolygonClipper.Union(empty, empty, FillRule.EvenOdd); + string details = $"HasExpected-{hasExpected}"; + string path = hasExpected + ? SvgTestOutput.SaveSvg(nameof(SvgTestOutputTests), nameof(this.SaveSvg_WritesEmptyResults), details, empty, empty, actual, empty) + : SvgTestOutput.SaveSvg(nameof(SvgTestOutputTests), nameof(this.SaveSvg_WritesEmptyResults), details, empty, empty, actual); + XElement root = XDocument.Load(path).Root!; + + Assert.Equal(hasExpected ? "0 0 1200 440" : "0 0 800 440", (string)root.Attribute("viewBox")!); + Assert.Equal(hasExpected, root.Elements().Any(element => (string)element.Attribute("id") == "expected")); + Assert.Empty(root.Descendants(Svg + "path")); + Assert.Empty(root.Descendants(Svg + "circle")); + } + + /// + /// Checks that another call replaces the previous output at the same path. + /// + [Fact] + public void SaveSvg_ReplacesPreviousOutput() + { + Polygon subject = [Open(new(-2, 0), new(2, 0))]; + Polygon clip = [Open(new(0, -2), new(0, 2))]; + Polygon point = PolygonClipper.Intersection(subject, clip, FillRule.NonZero); + + string firstPath = SvgTestOutput.SaveSvg( + nameof(SvgTestOutputTests), nameof(this.SaveSvg_ReplacesPreviousOutput), string.Empty, subject, clip, point, point); + + Polygon empty = PolygonClipper.Intersection(subject, [], FillRule.NonZero); + + string secondPath = SvgTestOutput.SaveSvg( + nameof(SvgTestOutputTests), nameof(this.SaveSvg_ReplacesPreviousOutput), string.Empty, subject, [], empty); + + XElement root = XDocument.Load(secondPath).Root!; + XElement actual = root.Elements().Single(element => (string)element.Attribute("id") == "actual"); + + Assert.Equal(firstPath, secondPath); + Assert.Equal("SaveSvg_ReplacesPreviousOutput.svg", Path.GetFileName(secondPath)); + Assert.Empty(actual.Descendants(Svg + "path")); + Assert.Empty(actual.Descendants(Svg + "circle")); + Assert.DoesNotContain(root.Descendants(), element => (string)element.Attribute("class") == "point"); + Assert.DoesNotContain(root.Descendants(), element => (string)element.Attribute("class") == "point-legend"); + Assert.DoesNotContain(root.Elements(), element => (string)element.Attribute("id") == "expected"); + Assert.Single(Directory.EnumerateFiles(Path.GetDirectoryName(secondPath)!, nameof(this.SaveSvg_ReplacesPreviousOutput) + ".svg")); + } + + /// + /// Builds an explicitly open contour for the source or expected line geometry. + /// + /// The source vertices in order. + /// The open contour. + private static Contour Open(params Vertex[] vertices) + { + Contour contour = new() { IsClosed = false }; + foreach (Vertex vertex in vertices) + { + contour.Add(vertex); + } + + return contour; + } +} diff --git a/tests/PolygonClipper.Tests/TestEnvironment.cs b/tests/PolygonClipper.Tests/TestEnvironment.cs index a869cb9..3b1f791 100644 --- a/tests/PolygonClipper.Tests/TestEnvironment.cs +++ b/tests/PolygonClipper.Tests/TestEnvironment.cs @@ -14,6 +14,8 @@ internal static class TestEnvironment private const string GeoJsonTestDataRelativePath = @"tests\TestData\"; + private const string ActualOutputDirectoryRelativePath = @"tests\Images\ActualOutput"; + private static readonly Lazy SolutionDirectoryFullPathLazy = new(GetSolutionDirectoryFullPathImpl); public static string SolutionDirectoryFullPath => SolutionDirectoryFullPathLazy.Value; @@ -23,6 +25,11 @@ internal static class TestEnvironment /// public static string GeoJsonTestDataFullPath => GetFullPath(GeoJsonTestDataRelativePath); + /// + /// Gets the full path to the images written by tests. + /// + public static string ActualOutputDirectoryFullPath => GetFullPath(ActualOutputDirectoryRelativePath); + public static bool IsLinux => RuntimeInformation.IsOSPlatform(OSPlatform.Linux); public static bool IsMacOS => RuntimeInformation.IsOSPlatform(OSPlatform.OSX); From 20b46de7c7b10a302e56ac7ac0c2f13bc1158003 Mon Sep 17 00:00:00 2001 From: James Jackson-South Date: Fri, 30 Oct 2026 17:56:06 +1000 Subject: [PATCH 16/24] Preserve exact axis-aligned stroke intersections --- src/PolygonClipper/PolygonStroker.cs | 15 +++++++++++++++ .../PolygonClipper.Tests/PolygonStrokerTests.cs | 16 ++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/src/PolygonClipper/PolygonStroker.cs b/src/PolygonClipper/PolygonStroker.cs index 73fe02b..94a5a29 100644 --- a/src/PolygonClipper/PolygonStroker.cs +++ b/src/PolygonClipper/PolygonStroker.cs @@ -1225,6 +1225,7 @@ private static bool TryCalcIntersection(in Vertex a, in Vertex b, in Vertex c, i { Vertex ab = b - a; Vertex cd = d - c; + double denominator = Vertex.Cross(ab, cd); if (Math.Abs(denominator) < IntersectionEpsilon) { @@ -1233,6 +1234,20 @@ private static bool TryCalcIntersection(in Vertex a, in Vertex b, in Vertex c, i return false; } + // The parallel check also rejects offset lines whose endpoints round to one point. + // A nonparallel axis-aligned crossing uses existing coordinates without division error. + if (ab.X == 0 && cd.Y == 0) + { + intersection = new(a.X, c.Y); + return true; + } + + if (ab.Y == 0 && cd.X == 0) + { + intersection = new(c.X, a.Y); + return true; + } + double t = Vertex.Cross(c - a, cd) / denominator; intersection = a + (ab * t); return true; diff --git a/tests/PolygonClipper.Tests/PolygonStrokerTests.cs b/tests/PolygonClipper.Tests/PolygonStrokerTests.cs index 3443d2a..83b5a09 100644 --- a/tests/PolygonClipper.Tests/PolygonStrokerTests.cs +++ b/tests/PolygonClipper.Tests/PolygonStrokerTests.cs @@ -5,6 +5,22 @@ namespace SixLabors.PolygonClipper.Tests; public class PolygonStrokerTests { + /// + /// Checks that axis-aligned miter intersections retain a representable thin inner contour. + /// + [Fact] + public void Stroke_AxisAlignedMiter_PreservesThinInnerContour() + { + double left = -1D / 9_007_199_254_740_992D; + Contour source = [new(left, 0), new(2, 0), new(2, 4), new(left, 4), new(left, 0)]; + Polygon actual = PolygonStroker.Stroke([source], 2, new() { LineJoin = LineJoin.Miter }); + + Assert.Equal(2, actual.Count); + Contour inner = Assert.Single(actual, contour => contour.GetBoundingBox().Max.X - contour.GetBoundingBox().Min.X < 1); + Assert.Equal(new Vertex(1 + left, 1), inner.GetBoundingBox().Min); + Assert.Equal(new Vertex(1, 3), inner.GetBoundingBox().Max); + } + [Fact] public void ProcessPath_ClosedSquare_ReturnsGeometry() { From 48a4e26d98eca72c808907eb1f1e3eef4acde6cd Mon Sep 17 00:00:00 2001 From: James Jackson-South Date: Fri, 30 Oct 2026 21:26:37 +1000 Subject: [PATCH 17/24] Validate stroke widths and return empty geometry for zero width --- src/PolygonClipper/PolygonStroker.cs | 53 +++++++---- .../PolygonStrokerWidthTests.cs | 91 +++++++++++++++++++ 2 files changed, 125 insertions(+), 19 deletions(-) create mode 100644 tests/PolygonClipper.Tests/PolygonStrokerWidthTests.cs diff --git a/src/PolygonClipper/PolygonStroker.cs b/src/PolygonClipper/PolygonStroker.cs index 94a5a29..79fb7c0 100644 --- a/src/PolygonClipper/PolygonStroker.cs +++ b/src/PolygonClipper/PolygonStroker.cs @@ -183,9 +183,10 @@ public override int GetHashCode() /// Strokes the source contours with the specified width and default options. /// /// The source contours, each with its own closure state. - /// The stroke width. - /// Closed stroke contours without a repeated closing vertex. + /// The finite signed stroke width. Zero produces no geometry. + /// Closed stroke contours without a repeated closing vertex. Zero width returns no contours. /// The polygon is null. + /// The width is not finite. public static Polygon Stroke(Polygon polygon, double width) => Stroke(polygon, width, DefaultStrokeOptions); @@ -193,19 +194,21 @@ public static Polygon Stroke(Polygon polygon, double width) /// Strokes the source contours with the specified width and options. /// /// The source contours, each with its own closure state. - /// The stroke width. + /// The finite signed stroke width. Zero produces no geometry. /// The join, cap, approximation, and output cleanup options. - /// Closed stroke contours without a repeated closing vertex. + /// Closed stroke contours without a repeated closing vertex. Zero width returns no contours. /// The polygon or options are null. + /// The width is not finite. public static Polygon Stroke(Polygon polygon, double width, StrokeOptions options) { ArgumentNullException.ThrowIfNull(options); + Guard.MustBeBetweenOrEqualTo(width, double.MinValue, double.MaxValue, nameof(width)); StrokeOptionsKey key = new(options); PolygonStroker stroker = Rent(key, options); try { - stroker.Width = width; + stroker.SetHalfWidth(width * 0.5D); return stroker.Stroke(polygon); } finally @@ -218,13 +221,13 @@ public static Polygon Stroke(Polygon polygon, double width, StrokeOptions option /// Strokes using this instance's configured options and width. /// /// The source contours, each with its own closure state. - /// Closed stroke contours without a repeated closing vertex. + /// Closed stroke contours without a repeated closing vertex. Zero width returns no contours. /// Thrown when is null. /// Instance execution is not thread-safe for concurrent use. public Polygon Stroke(Polygon polygon) { ArgumentNullException.ThrowIfNull(polygon); - if (polygon.Count == 0) + if (polygon.Count == 0 || this.strokeWidth == 0) { return []; } @@ -289,26 +292,38 @@ public Polygon Stroke(Polygon polygon) /// /// Positive values produce conventional outward stroking. Negative values are supported /// and flip the side orientation while preserving magnitude. + /// Zero width produces no geometry. /// + /// The width is not finite. public double Width { get => this.strokeWidth * 2D; set { - this.strokeWidth = value * 0.5D; - if (this.strokeWidth < 0D) - { - this.widthAbs = -this.strokeWidth; - this.widthSign = -1; - } - else - { - this.widthAbs = this.strokeWidth; - this.widthSign = 1; - } + Guard.MustBeBetweenOrEqualTo(value, double.MinValue, double.MaxValue, nameof(value)); + this.SetHalfWidth(value * 0.5D); + } + } - this.widthEps = this.strokeWidth / 1024D; + /// + /// Sets the signed distance from the source path to each stroke side. + /// + /// The signed side distance from a finite public width. + private void SetHalfWidth(double halfWidth) + { + this.strokeWidth = halfWidth; + if (this.strokeWidth < 0D) + { + this.widthAbs = -this.strokeWidth; + this.widthSign = -1; } + else + { + this.widthAbs = this.strokeWidth; + this.widthSign = 1; + } + + this.widthEps = this.strokeWidth / 1024D; } /// diff --git a/tests/PolygonClipper.Tests/PolygonStrokerWidthTests.cs b/tests/PolygonClipper.Tests/PolygonStrokerWidthTests.cs new file mode 100644 index 0000000..bf648e4 --- /dev/null +++ b/tests/PolygonClipper.Tests/PolygonStrokerWidthTests.cs @@ -0,0 +1,91 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +namespace SixLabors.PolygonClipper.Tests; + +/// +/// Checks finite stroke widths and the empty result for zero width. +/// +public class PolygonStrokerWidthTests +{ + /// + /// Checks non-finite widths at the static entry points, including empty input. + /// + /// The non-finite stroke width. + [Theory] + [InlineData(double.NaN)] + [InlineData(double.PositiveInfinity)] + [InlineData(double.NegativeInfinity)] + public void Stroke_NonFiniteWidth_IsRejected(double width) + { + Polygon polygon = [[new(0, 0), new(10, 0), new(10, 10), new(0, 10), new(0, 0)]]; + StrokeOptions options = new() { LineJoin = LineJoin.Round, LineCap = LineCap.Round, NormalizeOutput = true }; + + Assert.Throws("width", () => PolygonStroker.Stroke(polygon, width)); + Assert.Throws("width", () => PolygonStroker.Stroke(polygon, width, options)); + Assert.Throws("width", () => PolygonStroker.Stroke([], width)); + Assert.Throws("width", () => PolygonStroker.Stroke([], width, options)); + } + + /// + /// Checks that a rejected width assignment preserves the previous width and geometry. + /// + /// The non-finite stroke width. + [Theory] + [InlineData(double.NaN)] + [InlineData(double.PositiveInfinity)] + [InlineData(double.NegativeInfinity)] + public void Width_NonFiniteValue_PreservesPreviousState(double width) + { + Polygon polygon = [[new(0, 0), new(10, 0), new(10, 10), new(0, 10), new(0, 0)]]; + PolygonStroker stroker = new(new StrokeOptions()) { Width = 2 }; + string before = stroker.Stroke(polygon).ToDebugString(); + + Assert.Throws("value", () => stroker.Width = width); + Assert.Equal(2D, stroker.Width); + Assert.Equal(before, stroker.Stroke(polygon).ToDebugString()); + } + + /// + /// Checks zero width before outline generation, point caps and optional cleanup. + /// + /// The join style. + /// The cap style. + /// Whether to resolve the generated outlines. + [Theory] + [InlineData(LineJoin.Miter, LineCap.Butt, false)] + [InlineData(LineJoin.Round, LineCap.Round, false)] + [InlineData(LineJoin.Miter, LineCap.Butt, true)] + [InlineData(LineJoin.Round, LineCap.Round, true)] + public void Stroke_ZeroWidth_ReturnsEmpty(LineJoin join, LineCap cap, bool normalizeOutput) + { + Polygon[] inputs = + [ + [], + [[new(0, 0), new(10, 0), new(10, 10), new(0, 10), new(0, 0)]], + [[new(0, 0), new(10, 0)]], + [[new(5, 5), new(5, 5)]] + ]; + StrokeOptions options = new() { LineJoin = join, LineCap = cap, NormalizeOutput = normalizeOutput }; + PolygonStroker stroker = new(options) { Width = 0 }; + + foreach (Polygon input in inputs) + { + Assert.Empty(PolygonStroker.Stroke(input, 0D, options)); + Assert.Empty(PolygonStroker.Stroke(input, -0D, options)); + Assert.Empty(stroker.Stroke(input)); + } + } + + /// + /// Checks that zero width does not bypass the null-polygon contract. + /// + [Fact] + public void Stroke_ZeroWidth_StillRejectsNullPolygon() + { + PolygonStroker stroker = new(new StrokeOptions()) { Width = 0 }; + + Assert.Throws("polygon", () => PolygonStroker.Stroke(null, 0)); + Assert.Throws("polygon", () => stroker.Stroke(null)); + } +} From 878291cd971c421ad5dd4dca3d8ca8fe57bc78e1 Mon Sep 17 00:00:00 2001 From: James Jackson-South Date: Fri, 30 Oct 2026 21:28:16 +1000 Subject: [PATCH 18/24] Match ImageSharp generated image output ignores --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 0d36bf7..3c82cbe 100644 --- a/.gitignore +++ b/.gitignore @@ -63,6 +63,7 @@ artifacts/ # Test image output **/Images/ActualOutput +**/Images/ReferenceOutput # StyleCop StyleCopReport.xml From ebbb87932562e70a179a2fda063478ee91026e69 Mon Sep 17 00:00:00 2001 From: James Jackson-South Date: Fri, 30 Oct 2026 21:47:36 +1000 Subject: [PATCH 19/24] Add polygon offsets and publish console benchmark results --- README.md | 21 +- src/Directory.Build.props | 1 + src/PolygonClipper/OffsetOptions.cs | 42 ++ src/PolygonClipper/PolygonClipper.cs | 54 +- src/PolygonClipper/PolygonOffsetter.cs | 125 ++++ src/PolygonClipper/PolygonStroker.cs | 194 ++++-- src/PolygonClipper/SweepEventPoolList.cs | 36 +- tests/PolygonClipper.Benchmarks/Benches.cs | 57 +- .../NormalizationBenches.cs | 41 +- .../OffsetBenches.cs | 150 ++++ .../OpenClippingBenches.cs | 64 +- .../StarBooleanBenches.cs | 84 +-- .../StrokeBenches.cs | 22 + .../ApproximateDoubleComparer.cs | 40 ++ .../ApproximateDoubleComparerTests.cs | 64 ++ .../OffsetOptionsTests.cs | 74 ++ .../PolygonOffsetTests.cs | 644 ++++++++++++++++++ .../PolygonStrokerTests.cs | 218 +++++- tests/PolygonClipper.Tests/SvgTestOutput.cs | 54 +- .../SvgTestOutputTests.cs | 47 ++ 20 files changed, 1810 insertions(+), 222 deletions(-) create mode 100644 src/PolygonClipper/OffsetOptions.cs create mode 100644 src/PolygonClipper/PolygonOffsetter.cs create mode 100644 tests/PolygonClipper.Benchmarks/OffsetBenches.cs create mode 100644 tests/PolygonClipper.Tests/ApproximateDoubleComparer.cs create mode 100644 tests/PolygonClipper.Tests/ApproximateDoubleComparerTests.cs create mode 100644 tests/PolygonClipper.Tests/OffsetOptionsTests.cs create mode 100644 tests/PolygonClipper.Tests/PolygonOffsetTests.cs diff --git a/README.md b/README.md index 7507efb..c2dde63 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ SixLabors.PolygonClipper -SixLabors.PolygonClipper performs polygon clipping and stroking in C#. +SixLabors.PolygonClipper performs polygon clipping, stroking and offsets in C#. It uses the Martinez-Rueda algorithm with double coordinates. It supports holes, self-intersections, overlapping edges, and multiple contours. @@ -118,6 +118,25 @@ StrokeOptions options = new() Polygon result = PolygonStroker.Stroke(subject, width: 12, options); ``` +## Offsets + +`PolygonOffsetter.Offset(polygon, delta, fillRule, options)` expands or contracts a filled polygon. +Positive distance expands exterior boundaries and shrinks holes. Negative distance contracts exterior boundaries and expands holes. +Collapsed holes and components disappear. Zero distance returns an independent, resolved copy of the source filled area. + +All source contours must be closed. The fill rule interprets the original source contours before their boundaries are offset. +`OffsetOptions` selects the join style, miter limit and arc detail. Offset results always contain resolved boundaries. + +```csharp +OffsetOptions offsetOptions = new() { LineJoin = LineJoin.Round }; + +// Expand the NonZero-filled area by two coordinate units with the selected joins. +Polygon expanded = PolygonOffsetter.Offset(subject, 2, FillRule.NonZero, offsetOptions); + +// Contract the same source area by two coordinate units. +Polygon contracted = PolygonOffsetter.Offset(subject, -2, FillRule.NonZero, offsetOptions); +``` + ## Complexity Martinez has a published complexity of `O((n + k) log n)` for `n` input edges and `k` intersections. diff --git a/src/Directory.Build.props b/src/Directory.Build.props index a3a4af5..4651c6c 100644 --- a/src/Directory.Build.props +++ b/src/Directory.Build.props @@ -27,6 +27,7 @@ + diff --git a/src/PolygonClipper/OffsetOptions.cs b/src/PolygonClipper/OffsetOptions.cs new file mode 100644 index 0000000..dc4ab34 --- /dev/null +++ b/src/PolygonClipper/OffsetOptions.cs @@ -0,0 +1,42 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +namespace SixLabors.PolygonClipper; + +/// +/// Provides join and arc settings for polygon inflation and deflation. +/// +public sealed class OffsetOptions : IEquatable +{ + /// + /// Gets or sets the miter limit used to clamp outer miter joins. + /// + /// The default is 4. + public double MiterLimit { get; set; } = 4D; + + /// + /// Gets or sets the detail scale for round joins. Higher values produce more vertices. + /// + /// The default is 1. + public double ArcDetailScale { get; set; } = 1D; + + /// + /// Gets or sets the join style for offset corners. + /// + /// The default is . + public LineJoin LineJoin { get; set; } = LineJoin.Bevel; + + /// + public override bool Equals(object? obj) => this.Equals(obj as OffsetOptions); + + /// + public bool Equals(OffsetOptions? other) + => other is not null && + this.MiterLimit == other.MiterLimit && + this.ArcDetailScale == other.ArcDetailScale && + this.LineJoin == other.LineJoin; + + /// + public override int GetHashCode() + => HashCode.Combine(this.MiterLimit, this.ArcDetailScale, this.LineJoin); +} diff --git a/src/PolygonClipper/PolygonClipper.cs b/src/PolygonClipper/PolygonClipper.cs index 0929ce1..f34eedc 100644 --- a/src/PolygonClipper/PolygonClipper.cs +++ b/src/PolygonClipper/PolygonClipper.cs @@ -571,9 +571,10 @@ private Polygon RunSweep(Box2 subjectBounds, Box2 clipBounds) } } - // Boundary events are completed at their right endpoints. Restore the - // ordering expected by the existing connector in O(B log B), rather - // than making its nearly-sorted repair loop sort reversed history. + // The queue visits points in order. DivideSegment only queues future + // crossings; a repaired tail starts at its old end, at or after this point. + // Boundary points never change, so only rays at each point need sorting. + // Wait until all pairs close because ray order uses the opposite endpoint. resultEvents.Sort(resultComparer); Polygon result = this.ConnectEdges(resultEvents); for (int i = 0; i < result.Count; i++) @@ -644,11 +645,11 @@ private static Polygon ExecuteFillOperation( /// The clipping operand's fill rule. private static void ValidateFillArguments(Polygon subject, Polygon clip, BooleanOperation operation, FillRule subjectRule, FillRule clipRule) { - ArgumentNullException.ThrowIfNull(subject); - ArgumentNullException.ThrowIfNull(clip); - ArgumentOutOfRangeException.ThrowIfGreaterThan((uint)operation, (uint)BooleanOperation.Xor, nameof(operation)); - ArgumentOutOfRangeException.ThrowIfGreaterThan((uint)subjectRule, (uint)FillRule.Negative, nameof(subjectRule)); - ArgumentOutOfRangeException.ThrowIfGreaterThan((uint)clipRule, (uint)FillRule.Negative, nameof(clipRule)); + Guard.NotNull(subject, nameof(subject)); + Guard.NotNull(clip, nameof(clip)); + Guard.MustBeLessThanOrEqualTo((uint)operation, (uint)BooleanOperation.Xor, nameof(operation)); + Guard.MustBeLessThanOrEqualTo((uint)subjectRule, (uint)FillRule.Negative, nameof(subjectRule)); + Guard.MustBeLessThanOrEqualTo((uint)clipRule, (uint)FillRule.Negative, nameof(clipRule)); } /// @@ -813,10 +814,7 @@ private Box2 ProcessSegments(Polygon polygon, bool subject) // Open ingestion also validates the terminal vertex, which is // never a start and must not bypass the public finite-coordinate contract. Vertex terminal = contour[contour.Count - 1]; - if (!double.IsFinite(terminal.X) || !double.IsFinite(terminal.Y)) - { - throw new ArgumentException("Polygon coordinates must be finite.", nameof(polygon)); - } + Guard.IsTrue(double.IsFinite(terminal.X) && double.IsFinite(terminal.Y), nameof(polygon), "Polygon coordinates must be finite."); if (contour.Count == 1) { @@ -842,10 +840,7 @@ private Box2 ProcessSegments(Polygon polygon, bool subject) Segment segment = contour.GetSegment(j); Vertex start = segment.Source; Vertex end = segment.Target; - if (!double.IsFinite(start.X) || !double.IsFinite(start.Y)) - { - throw new ArgumentException("Polygon coordinates must be finite.", nameof(polygon)); - } + Guard.IsTrue(double.IsFinite(start.X) && double.IsFinite(start.Y), nameof(polygon), "Polygon coordinates must be finite."); bounds = bounds.Add(new Box2(start)); if (start == end) @@ -1297,6 +1292,13 @@ private Polygon ConnectEdges(SweepEventPoolList resultEvents) // Every iteration-map slot is assigned, but processed flags must // start clear because pooled storage can contain flags from a prior run. processed.Clear(); + + // Each traced edge consumes two events. One shared scratch span can + // therefore hold any contour, including its repeated closing vertex. + // Trace into pooled memory first, then allocate the exact vertex count. + // This replaces repeated list growth, clearing and copying for large contours. + using Buffer vertexBuffer = new((resultEvents.Count / 2) + 1); + Span vertices = vertexBuffer.GetSpan(); for (int i = 0; i < resultEvents.Count; i++) { if (processed[i]) @@ -1305,11 +1307,10 @@ private Polygon ConnectEdges(SweepEventPoolList resultEvents) } int contourId = result.Count; - Contour contour = this.InitializeContourFromContext(resultEvents[i], result, contourId); - int pos = i; Vertex initial = resultEvents[i].Point; - contour.Add(initial); + vertices[0] = initial; + int vertexCount = 1; // Main loop to process the contour do @@ -1320,7 +1321,7 @@ private Polygon ConnectEdges(SweepEventPoolList resultEvents) MarkProcessed(resultEvents[pos], processed, pos, contourId); Vertex point = resultEvents[pos].Point; - contour.Add(point); + vertices[vertexCount++] = point; // Closing the contour needs no further edge. Searching here // would revisit processed rays at a shared starting vertex. @@ -1337,6 +1338,12 @@ private Polygon ConnectEdges(SweepEventPoolList resultEvents) } while (true); + Contour contour = this.InitializeContourFromContext(resultEvents[i], result, contourId, vertexCount); + for (int j = 0; j < vertexCount; j++) + { + contour.Add(vertices[j]); + } + result.Add(contour); } @@ -1483,12 +1490,11 @@ private static void MarkProcessed(SweepEvent sweepEvent, Span processed, i /// The current sweep event. /// The collection of contours processed so far. /// The ID for the new contour. + /// The number of traced vertices, including the closing vertex. /// The initialized . - private Contour InitializeContourFromContext(SweepEvent sweepEvent, Polygon polygon, int contourId) + private Contour InitializeContourFromContext(SweepEvent sweepEvent, Polygon polygon, int contourId, int vertexCount) { - // A triangle needs three vertices and its closing vertex during tracing. - // Reserve those slots instead of growing the list on the first Add. - Contour contour = new(4); + Contour contour = new(vertexCount); if (this.contourOutput == ContourOutput.Nested) { if (sweepEvent.PrevInResult is SweepEvent lower) diff --git a/src/PolygonClipper/PolygonOffsetter.cs b/src/PolygonClipper/PolygonOffsetter.cs new file mode 100644 index 0000000..b5fe15e --- /dev/null +++ b/src/PolygonClipper/PolygonOffsetter.cs @@ -0,0 +1,125 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +namespace SixLabors.PolygonClipper; + +/// +/// Expands or contracts the filled area of closed polygons. +/// +public static class PolygonOffsetter +{ + /// + /// Expands or contracts the filled area of closed contours by the specified distance. + /// + /// Closed source contours. Their vertices and directions are not modified. + /// A finite distance. Positive expands the area; negative contracts it. + /// The rule that determines the source filled area. + /// The join style, miter limit and arc detail. + /// + /// Closed boundaries with their full containment hierarchy. Exterior contours and islands are counterclockwise. + /// Holes are clockwise. Collapsed areas disappear. Zero distance returns a detached, resolved copy. + /// + /// The polygon or options are null. + /// The polygon contains an open contour. + /// The distance is not finite or the fill rule is invalid. + public static Polygon Offset(Polygon polygon, double delta, FillRule fillRule, OffsetOptions options) + { + Guard.NotNull(polygon, nameof(polygon)); + Guard.NotNull(options, nameof(options)); + Guard.MustBeBetweenOrEqualTo(delta, double.MinValue, double.MaxValue, nameof(delta)); + + foreach (Contour contour in polygon) + { + Guard.IsTrue(contour.IsClosed, nameof(polygon), "Offset requires closed contours. Use Stroke for open paths."); + } + + // Resolve the requested filled area before outlining it. Raw overlaps and self-crossings + // are not independent boundaries and must not introduce internal offset seams. + Polygon area = PolygonClipper.Normalize(polygon, fillRule); + if (delta == 0 || area.Count == 0) + { + return area; + } + + if (area[0].HoleCount == area.Count - 1) + { + // One exterior with its direct holes needs no component merge. + return OffsetComponent(area, delta, options); + } + + Polygon combined = new(area.Count); + foreach (Contour exterior in area) + { + if ((exterior.Depth & 1) != 0) + { + continue; + } + + Polygon component = new(exterior.HoleCount + 1) { exterior }; + for (int i = 0; i < exterior.HoleCount; i++) + { + component.Add(area[exterior.GetHoleIndex(i)]); + } + + Polygon offset = OffsetComponent(component, delta, options); + foreach (Contour boundary in offset) + { + combined.Add(boundary); + } + } + + // A collapsed component can have negative winding outside its source boundary. + // Resolve that winding before it can cancel a retained area in another component. + // The final union merges expansions and restores hierarchy between separate components. + return PolygonClipper.Normalize(combined, FillRule.NonZero); + } + + /// + /// Offsets one resolved exterior and its direct holes without changing their coordinates. + /// + /// One nonempty filled component with its exterior first. + /// The validated nonzero signed distance. + /// The join and arc settings. + /// The resolved offset component, which can split or disappear. + private static Polygon OffsetComponent(Polygon component, double delta, OffsetOptions options) + { + if (delta < 0) + { + Contour exterior = component[0]; + Box2 bounds = exterior.GetBoundingBox(); + ExtendedPrecisionDouble distance = new(-delta); + ExtendedPrecisionDouble halfWidth = ExtendedPrecisionDouble.Difference(bounds.Max.X * 0.5D, bounds.Min.X * 0.5D); + ExtendedPrecisionDouble halfHeight = ExtendedPrecisionDouble.Difference(bounds.Max.Y * 0.5D, bounds.Min.Y * 0.5D); + + // Retain the subtraction residual so a rounded box width cannot erase a surviving thin area. + if ((distance - halfWidth).Value >= 0 || (distance - halfHeight).Value >= 0) + { + // A convex erosion must remain at least this distance from every supporting edge. + // It cannot have area once that distance reaches half a bounding-box dimension. + // Test convexity only for that case. This avoids constructing a dense collapsed walk. + bool convex = true; + for (int i = 0; i < exterior.Count; i++) + { + if (PolygonUtilities.SignedArea(exterior[i], exterior[(i + 1) % exterior.Count], exterior[(i + 2) % exterior.Count]) < 0) + { + convex = false; + break; + } + } + + if (convex) + { + return []; + } + } + } + + Polygon boundaries = PolygonStroker.OffsetBoundaries(component, delta, options); + + // Source winding is 0 or 1. Band coverage is nonnegative, including overlapping strips. + // The displaced walk has source winding plus band coverage for expansion, or minus it + // for contraction. Positive filling selects the union or the uncovered source area. + // The source walk cancels in both expressions, so it need not enter the final sweep. + return PolygonClipper.Normalize(boundaries, FillRule.Positive); + } +} diff --git a/src/PolygonClipper/PolygonStroker.cs b/src/PolygonClipper/PolygonStroker.cs index 79fb7c0..9333fd6 100644 --- a/src/PolygonClipper/PolygonStroker.cs +++ b/src/PolygonClipper/PolygonStroker.cs @@ -1,6 +1,7 @@ // Copyright (c) Six Labors. // Licensed under the Six Labors Split License. +using System.Numerics; using System.Runtime.CompilerServices; namespace SixLabors.PolygonClipper; @@ -61,6 +62,9 @@ public sealed class PolygonStroker private double widthEps = 0.5D / 1024D; private int widthSign = 1; + // Offsets emit one side and retain overlaps at inner corners until Martinez resolves them. + private bool offsetBoundary; + /// /// Initializes a new instance of the class with the specified stroke options. /// @@ -70,13 +74,21 @@ public sealed class PolygonStroker /// Set before calling to select the stroke width. /// public PolygonStroker(StrokeOptions options) + : this(new StrokeOptionsKey(options)) { - ArgumentNullException.ThrowIfNull(options); - this.NormalizeOutput = options.NormalizeOutput; - this.LineJoin = options.LineJoin; - this.LineCap = options.LineCap; - this.MiterLimit = options.MiterLimit; - this.ArcDetailScale = options.ArcDetailScale; + } + + /// + /// Initializes a new instance of the class from captured pool settings. + /// + /// The captured stroke or offset settings. + private PolygonStroker(in StrokeOptionsKey key) + { + this.NormalizeOutput = key.NormalizeOutput; + this.LineJoin = key.LineJoin; + this.LineCap = key.LineCap; + this.MiterLimit = key.MiterLimit; + this.ArcDetailScale = key.ArcDetailScale; } /// @@ -142,8 +154,14 @@ private enum Status private readonly struct StrokeOptionsKey : IEquatable { + /// + /// Initializes a new instance of the struct from stroke settings. + /// + /// The settings supplied to a public stroke entry point. + /// The options are null. public StrokeOptionsKey(StrokeOptions options) { + Guard.NotNull(options, nameof(options)); this.NormalizeOutput = options.NormalizeOutput; this.LineJoin = options.LineJoin; this.LineCap = options.LineCap; @@ -151,6 +169,21 @@ public StrokeOptionsKey(StrokeOptions options) this.ArcDetailScale = options.ArcDetailScale; } + /// + /// Initializes a new instance of the struct from offset settings. + /// + /// The join and arc settings supplied by the offset entry point. + public StrokeOptionsKey(OffsetOptions options) + { + // Offsets use one closed side and resolve it in Martinez. Fixed stroke-only + // values let them share the existing pool without constructing stroke options. + this.NormalizeOutput = false; + this.LineCap = LineCap.Butt; + this.LineJoin = options.LineJoin; + this.MiterLimit = options.MiterLimit; + this.ArcDetailScale = options.ArcDetailScale; + } + public bool NormalizeOutput { get; } public LineJoin LineJoin { get; } @@ -184,7 +217,7 @@ public override int GetHashCode() /// /// The source contours, each with its own closure state. /// The finite signed stroke width. Zero produces no geometry. - /// Closed stroke contours without a repeated closing vertex. Zero width returns no contours. + /// Closed stroke contours without a repeated closing vertex. /// The polygon is null. /// The width is not finite. public static Polygon Stroke(Polygon polygon, double width) @@ -196,16 +229,15 @@ public static Polygon Stroke(Polygon polygon, double width) /// The source contours, each with its own closure state. /// The finite signed stroke width. Zero produces no geometry. /// The join, cap, approximation, and output cleanup options. - /// Closed stroke contours without a repeated closing vertex. Zero width returns no contours. + /// Closed stroke contours without a repeated closing vertex. /// The polygon or options are null. /// The width is not finite. public static Polygon Stroke(Polygon polygon, double width, StrokeOptions options) { - ArgumentNullException.ThrowIfNull(options); + StrokeOptionsKey key = new(options); Guard.MustBeBetweenOrEqualTo(width, double.MinValue, double.MaxValue, nameof(width)); - StrokeOptionsKey key = new(options); - PolygonStroker stroker = Rent(key, options); + PolygonStroker stroker = Rent(key); try { stroker.SetHalfWidth(width * 0.5D); @@ -226,7 +258,7 @@ public static Polygon Stroke(Polygon polygon, double width, StrokeOptions option /// Instance execution is not thread-safe for concurrent use. public Polygon Stroke(Polygon polygon) { - ArgumentNullException.ThrowIfNull(polygon); + Guard.NotNull(polygon, nameof(polygon)); if (polygon.Count == 0 || this.strokeWidth == 0) { return []; @@ -237,11 +269,7 @@ public Polygon Stroke(Polygon polygon) { Contour contour = polygon[i]; - Polygon stroked = this.ProcessPathToPolygon(contour, contour.IsClosed); - if (stroked.Count > 0) - { - allContours.Join(stroked); - } + this.AppendPath(contour, contour.IsClosed, allContours); } if (allContours.Count == 0) @@ -306,40 +334,61 @@ public double Width } /// - /// Sets the signed distance from the source path to each stroke side. + /// Displaces resolved closed boundaries for Positive-fill resolution. /// - /// The signed side distance from a finite public width. - private void SetHalfWidth(double halfWidth) + /// Resolved closed boundaries with positive output orientation. + /// The nonzero finite distance. Positive selects the right side of each boundary. + /// The offset join and arc settings. + /// The displaced contour walks, including overlaps that preserve collapse behavior. + internal static Polygon OffsetBoundaries(Polygon polygon, double delta, OffsetOptions options) { - this.strokeWidth = halfWidth; - if (this.strokeWidth < 0D) + StrokeOptionsKey key = new(options); + PolygonStroker stroker = Rent(key); + try { - this.widthAbs = -this.strokeWidth; - this.widthSign = -1; + stroker.SetHalfWidth(delta); + stroker.offsetBoundary = true; + Polygon boundaries = new(polygon.Count); + foreach (Contour boundary in polygon) + { + stroker.AppendPath(boundary, true, boundaries); + } + + return boundaries; } - else + finally { - this.widthAbs = this.strokeWidth; - this.widthSign = 1; + stroker.offsetBoundary = false; + Return(key, stroker); } + } - this.widthEps = this.strokeWidth / 1024D; + /// + /// Sets the signed distance from the source path to each stroke side. + /// + /// The signed side distance. + private void SetHalfWidth(double halfWidth) + { + this.strokeWidth = halfWidth; + this.widthAbs = Math.Abs(halfWidth); + this.widthSign = halfWidth < 0 ? -1 : 1; + this.widthEps = halfWidth / 1024D; } /// - /// Converts a single contour into stroked polygon contours. + /// Appends the generated closed contours directly to the destination polygon. /// /// The source contour. /// Whether the source contour includes a final-to-first segment and closure join. - /// The generated stroked contour set for this input contour. - private Polygon ProcessPathToPolygon(Contour contour, bool isClosed) + /// The destination for raw contours, which have no hierarchy to remap. + private void AppendPath(Contour contour, bool isClosed, Polygon result) { - ArgumentNullException.ThrowIfNull(contour); + Guard.NotNull(contour, nameof(contour)); int pointCount = contour.Count; if (pointCount < 2) { - return []; + return; } if (isClosed && pointCount > 2 && contour[0] == contour[^1]) @@ -356,7 +405,8 @@ private Polygon ProcessPathToPolygon(Contour contour, bool isClosed) if (Vertex.DistanceSquared(p0, p1) <= VertexDistanceEpsilon * VertexDistanceEpsilon) { // Degenerate segment behaves like a stroked point. - return [this.GeneratePointCap(p0.X, p0.Y)]; + result.Add(this.GeneratePointCap(p0.X, p0.Y)); + return; } } @@ -372,13 +422,16 @@ private Polygon ProcessPathToPolygon(Contour contour, bool isClosed) this.ClosePath(); } - Polygon result = new(isClosed ? 2 : 1); this.FinishPath(result); - return result; } + /// + /// Rents a stroker with the captured settings, or creates one when the pool is empty. + /// + /// The captured settings used for construction and pool lookup. + /// A stroker configured with the captured settings. [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static PolygonStroker Rent(in StrokeOptionsKey key, StrokeOptions options) + private static PolygonStroker Rent(in StrokeOptionsKey key) { Dictionary>? pools = strokersByOptions; if (pools != null && @@ -388,7 +441,7 @@ private static PolygonStroker Rent(in StrokeOptionsKey key, StrokeOptions option return pool.Pop(); } - return new PolygonStroker(options); + return new PolygonStroker(key); } [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -477,7 +530,12 @@ private void FinishPath(Polygon result) AddStrokeContour(result, currentContour); } - currentContour = new Contour(16); + // Each closed side visits the source once. An open outline visits + // both sides in one contour. Closure adds no repeated vertex here. + // Match the list's doubling sizes so extra join vertices do not + // overshoot the capacity that ordinary list growth would reach. + int capacity = Math.Max(16, this.closed != 0 ? this.srcVertices.Length : this.srcVertices.Length * 2); + currentContour = new Contour((int)BitOperations.RoundUpToPowerOf2((uint)capacity)); hasLastPoint = false; } @@ -485,14 +543,23 @@ private void FinishPath(Polygon result) { currentContour ??= new Contour(16); - // Drop immediate duplicate vertices to avoid zero-length segments - // entering the intersection-removal pass. - if (!hasLastPoint || current != lastPoint) + // Accumulate returns vertices only from a completed join or cap + // buffer. Drain that buffer here instead of repeating command + // dispatch for each vertex. The next call resumes the same state. + for (int i = this.outVertex - 1; i < this.outVertices.Length; i++) { - currentContour.Add(current); - lastPoint = current; - hasLastPoint = true; + Vertex vertex = this.outVertices[i]; + + // Keep the same duplicate removal across joins and caps. + if (!hasLastPoint || vertex != lastPoint) + { + currentContour.Add(vertex); + lastPoint = vertex; + hasLastPoint = true; + } } + + this.outVertex = this.outVertices.Length; } if (command.EndPoly()) @@ -691,6 +758,14 @@ private PathCommand Accumulate(ref Vertex point) break; case Status.CloseFirst: + if (this.offsetBoundary) + { + // Offset needs only the selected side. Positive filling resolves its displaced walk. + this.status = Status.Stop; + cmd = PathCommand.Stop; + break; + } + // Start second side as a new contour command stream. cmd = PathCommand.MoveTo; this.status = Status.Outline2; @@ -1112,6 +1187,35 @@ private void CalcJoin(ref StrokeVertexDistance v0, ref StrokeVertexDistance v1, double cp = Vertex.Cross(segNext, segForward); if (Math.Abs(cp) > double.Epsilon && (cp > 0D) == (strokeWidth > 0D)) { + if (this.offsetBoundary) + { + Vertex offset1 = new(dx1, -dy1); + Vertex offset2 = new(dx2, -dy2); + if (TryCalcIntersection(v0Vertex + offset1, v1Vertex + offset1, v1Vertex + offset2, v2Vertex + offset2, out Vertex intersection)) + { + Vertex fromCorner = intersection - v1Vertex; + double incoming = Math.Max(-Vertex.Dot(fromCorner, segForward), -Vertex.Dot(offset2, segForward)) / len1; + double outgoing = Math.Max(Vertex.Dot(fromCorner, segNext), Vertex.Dot(offset1, segNext)) / len2; + if (incoming >= 0 && incoming <= len1 * 0.5D && outgoing >= 0 && outgoing <= len2 * 0.5D) + { + // The miter and both offset endpoints must fit within each incident half-edge. + // Neighboring corners use opposite halves, so these trims cannot remove + // the same strip coverage twice. This avoids extra overlap events on wide features. + this.AddPoint(intersection.X, intersection.Y); + return; + } + } + + // Connect both edge strips through their common source vertex. Their overlap must + // remain filled when the side distance exceeds a local feature's size. Joining the + // support lines here can fold the displaced contour into a false hole or island. + // Positive filling resolves the displaced walk without a separate band cleanup. + this.AddPoint(v1.X + dx1, v1.Y - dy1); + this.AddPoint(v1.X, v1.Y); + this.AddPoint(v1.X + dx2, v1.Y - dy2); + return; + } + double limit = Math.Min(len1, len2) / widthAbs; if (limit < InnerMiterLimit) { diff --git a/src/PolygonClipper/SweepEventPoolList.cs b/src/PolygonClipper/SweepEventPoolList.cs index 73dd09e..a9c6a42 100644 --- a/src/PolygonClipper/SweepEventPoolList.cs +++ b/src/PolygonClipper/SweepEventPoolList.cs @@ -60,10 +60,42 @@ public SweepEvent Add( } /// - /// Orders completed boundary events for edge connection. + /// Orders completed boundary events at each sweep point for edge connection. /// /// The edge connector's event ordering. - public void Sort(SweepEventComparer comparer) => this.Items.AsSpan(0, this.Size).Sort(comparer); + /// The input points must already be in sweep order. + public void Sort(SweepEventComparer comparer) + { + Span events = this.GetEventsSpan(); + int first = 0; + while (first < events.Length) + { + int after = first + 1; + Vertex point = events[first].Point; + while (after < events.Length && events[after].Point == point) + { + after++; + } + + // RunSweep appends immutable boundary points in queue order. + // Only rays at the same point need ordering after their pairs close. + // Most vertices have two rays. Compare that pair without a general sort. + int count = after - first; + if (count == 2) + { + if (comparer.Compare(events[first], events[first + 1]) > 0) + { + (events[first], events[first + 1]) = (events[first + 1], events[first]); + } + } + else if (count > 2) + { + events.Slice(first, count).Sort(comparer); + } + + first = after; + } + } /// /// Gets the active event references. diff --git a/tests/PolygonClipper.Benchmarks/Benches.cs b/tests/PolygonClipper.Benchmarks/Benches.cs index 1580d9e..4a37425 100644 --- a/tests/PolygonClipper.Benchmarks/Benches.cs +++ b/tests/PolygonClipper.Benchmarks/Benches.cs @@ -9,42 +9,27 @@ namespace SixLabors.PolygonClipper.Benchmarks; /* - * Comparison results: 30 October 2026. - * Windows 11. AMD Ryzen AI Max+ 395. .NET 10.0.14. BenchmarkDotNet 0.15.8. - * V2 build: 4f814c3 with the orientation-bound formula. release/1.x: cb06839. Clipper2: 4be4655. - * Mean: milliseconds per operation. Op/s: operations per second. B/op: allocated bytes per operation. - * Input preparation occurs before measurement. ClipperD uses precision 6. - * Each case uses 12 measured iterations, a 250 ms iteration target, and one launch. All samples remain included. - * Rust: rust-geo-booleanop 0.3.2 at b9bbdbb. rustc 1.98.0. Release build. geo-types 0.7.20. - * Rust timings include the native call and output destruction. Rust supports EvenOdd only. - * The .NET counters measure managed bytes. A separate Rust build counts requested native bytes. - * All comparisons below use union on the same source coordinates. - * Warmup: 10 iterations. release/1.x NonZero includes its required input preparation. - * The release/1.x NonZero hole_hole output fails the geometry check and has no comparison timing. - * - * Input | Fill rule | Engine | Mean (ms) | Op/s | B/op - * --------------+-----------+-------------+-----------+------------+--------- - * hole_hole | EvenOdd | V2 | 0.005698 | 175501.974 | 2560 - * hole_hole | EvenOdd | release/1.x | 0.013171 | 75925.110 | 9440 - * hole_hole | EvenOdd | Clipper2 | 0.002463 | 406026.381 | 9992 - * hole_hole | EvenOdd | Rust | 0.013409 | 74578.548 | 13948 - * hole_hole | NonZero | V2 | 0.005199 | 192359.257 | 1392 - * hole_hole | NonZero | Clipper2 | 0.001927 | 519056.802 | 7512 - * states_source | EvenOdd | V2 | 0.753519 | 1327.106 | 36936 - * states_source | EvenOdd | release/1.x | 1.205269 | 829.691 | 454496 - * states_source | EvenOdd | Clipper2 | 0.296078 | 3377.492 | 348984 - * states_source | EvenOdd | Rust | 1.193274 | 838.031 | 806340 - * states_source | NonZero | V2 | 0.786269 | 1271.830 | 36936 - * states_source | NonZero | release/1.x | 1.968205 | 508.077 | 584856 - * states_source | NonZero | Clipper2 | 0.295386 | 3385.403 | 348984 - * asia | EvenOdd | V2 | 12.277375 | 81.451 | 1189296 - * asia | EvenOdd | release/1.x | 18.382942 | 54.398 | 7527048 - * asia | EvenOdd | Clipper2 | 13.100940 | 76.330 | 6612934 - * asia | EvenOdd | Rust | 18.389607 | 54.379 | 11034172 - * asia | NonZero | V2 | 12.439713 | 80.388 | 1189296 - * asia | NonZero | release/1.x | 30.984123 | 32.275 | 9062752 - * asia | NonZero | Clipper2 | 13.507377 | 74.034 | 6613557 - */ +BenchmarkDotNet v0.15.8, Windows 11 (10.0.26300.9818) +AMD RYZEN AI MAX+ 395 w/ Radeon 8060S 3.00GHz, 1 CPU, 32 logical and 16 physical cores +.NET SDK 11.0.100-preview.7.26381.103 + [Host] : .NET 10.0.14 (10.0.14, 10.0.1426.52326), X64 RyuJIT x86-64-v4 + ShortRun : .NET 10.0.14 (10.0.14, 10.0.1426.52326), X64 RyuJIT x86-64-v4 + +Job=ShortRun IterationCount=3 LaunchCount=1 +WarmupCount=3 + +| Method | File | Mean | Error | StdDev | Op/s | Gen0 | Gen1 | Gen2 | Allocated | +|---------------------- |--------------------- |--------------:|--------------:|------------:|-----------:|---------:|---------:|---------:|----------:| +| PolygonClipperEvenOdd | asia.geojson | 11,200.902 us | 2,124.6733 us | 116.4605 us | 89.28 | 15.6250 | - | - | 463688 B | +| PolygonClipperNonZero | asia.geojson | 11,388.093 us | 7,892.3194 us | 432.6047 us | 87.81 | 15.6250 | - | - | 463688 B | +| Clipper2Union | asia.geojson | 14,425.834 us | 7,891.2400 us | 432.5455 us | 69.32 | 468.7500 | 437.5000 | 125.0000 | 6613210 B | +| PolygonClipperEvenOdd | hole_hole.geojson | 5.639 us | 0.6195 us | 0.0340 us | 177,347.74 | 0.0916 | - | - | 1632 B | +| PolygonClipperNonZero | hole_hole.geojson | 5.105 us | 4.3337 us | 0.2375 us | 195,880.72 | 0.0458 | - | - | 872 B | +| Clipper2Union | hole_hole.geojson | 2.775 us | 1.8953 us | 0.1039 us | 360,372.84 | 0.5951 | 0.0114 | - | 9992 B | +| PolygonClipperEvenOdd | state(...)ojson [21] | 738.178 us | 115.4451 us | 6.3279 us | 1,354.69 | - | - | - | 16136 B | +| PolygonClipperNonZero | state(...)ojson [21] | 777.143 us | 449.2819 us | 24.6267 us | 1,286.76 | - | - | - | 16136 B | +| Clipper2Union | state(...)ojson [21] | 331.071 us | 326.0528 us | 17.8721 us | 3,020.50 | 20.5078 | 9.7656 | - | 348984 B | +*/ /// /// Benchmarks the performance of PolygonClipper for polygon union operations using a fixed input dataset. diff --git a/tests/PolygonClipper.Benchmarks/NormalizationBenches.cs b/tests/PolygonClipper.Benchmarks/NormalizationBenches.cs index 8278f88..d50c37d 100644 --- a/tests/PolygonClipper.Benchmarks/NormalizationBenches.cs +++ b/tests/PolygonClipper.Benchmarks/NormalizationBenches.cs @@ -7,27 +7,26 @@ namespace SixLabors.PolygonClipper.Benchmarks; /* - * Comparison results: 30 October 2026. - * Windows 11. AMD Ryzen AI Max+ 395. .NET 10.0.14. BenchmarkDotNet 0.15.8. - * V2 build: 4f814c3 with the orientation-bound formula. release/1.x: cb06839. Clipper2: 4be4655. - * Mean: milliseconds per operation. Op/s: operations per second. B/op: allocated bytes per operation. - * Input preparation occurs before measurement. ClipperD uses precision 6. - * Each case uses 12 measured iterations, a 250 ms iteration target, and one launch. All samples remain included. - * All comparisons below use Positive cleanup on one star. Warmup: 10 iterations. - * release/1.x uses its Clipper2-derived cleanup. V2 uses its shared Martinez sweep. - * - * Vertices | Engine | Mean (ms) | Op/s | B/op - * ---------+-------------+------------+----------+--------- - * 101 | V2 | 1.751403 | 570.971 | 8648 - * 101 | release/1.x | 0.516666 | 1935.486 | 13760 - * 101 | Clipper2 | 0.449719 | 2223.613 | 210728 - * 301 | V2 | 17.035385 | 58.701 | 33272 - * 301 | release/1.x | 5.714182 | 175.003 | 40032 - * 301 | Clipper2 | 5.731402 | 174.477 | 2352348 - * 1001 | V2 | 205.407133 | 4.868 | 66064 - * 1001 | release/1.x | 84.452671 | 11.841 | 17449540 - * 1001 | Clipper2 | 76.949340 | 12.996 | 17525094 - */ +BenchmarkDotNet v0.15.8, Windows 11 (10.0.26300.9818) +AMD RYZEN AI MAX+ 395 w/ Radeon 8060S 3.00GHz, 1 CPU, 32 logical and 16 physical cores +.NET SDK 11.0.100-preview.7.26381.103 + [Host] : .NET 10.0.14 (10.0.14, 10.0.1426.52326), X64 RyuJIT x86-64-v4 + ShortRun : .NET 10.0.14 (10.0.14, 10.0.1426.52326), X64 RyuJIT x86-64-v4 + +Job=ShortRun IterationCount=3 LaunchCount=1 +WarmupCount=3 + +| Method | VertexCount | Mean | Error | StdDev | Op/s | Ratio | RatioSD | Gen0 | Gen1 | Gen2 | Allocated | Alloc Ratio | +|-------------- |------------ |-------------:|------------:|------------:|----------:|------:|--------:|----------:|----------:|----------:|------------:|------------:| +| Normalize | 101 | 1,828.4 us | 229.6 us | 12.58 us | 546.932 | 3.64 | 0.08 | - | - | - | 3.52 KB | 0.02 | +| Clipper2Union | 101 | 502.5 us | 223.6 us | 12.26 us | 1,989.877 | 1.00 | 0.03 | 12.2070 | 3.9063 | - | 205.76 KB | 1.00 | +| | | | | | | | | | | | | | +| Normalize | 301 | 19,279.5 us | 6,815.6 us | 373.58 us | 51.869 | 3.20 | 0.06 | - | - | - | 10.57 KB | 0.005 | +| Clipper2Union | 301 | 6,027.2 us | 676.2 us | 37.06 us | 165.916 | 1.00 | 0.01 | 492.1875 | 492.1875 | 492.1875 | 2297.18 KB | 1.000 | +| | | | | | | | | | | | | | +| Normalize | 1001 | 203,995.7 us | 30,961.7 us | 1,697.11 us | 4.902 | 2.54 | 0.07 | - | - | - | 48.99 KB | 0.003 | +| Clipper2Union | 1001 | 80,238.6 us | 44,367.1 us | 2,431.91 us | 12.463 | 1.00 | 0.04 | 1857.1429 | 1857.1429 | 1857.1429 | 17115.08 KB | 1.000 | +*/ /// /// Benchmarks normalization performance for star polygons. diff --git a/tests/PolygonClipper.Benchmarks/OffsetBenches.cs b/tests/PolygonClipper.Benchmarks/OffsetBenches.cs new file mode 100644 index 0000000..264cd5c --- /dev/null +++ b/tests/PolygonClipper.Benchmarks/OffsetBenches.cs @@ -0,0 +1,150 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +using BenchmarkDotNet.Attributes; +using Clipper2Lib; +using SixLabors.PolygonClipper.Tests; + +namespace SixLabors.PolygonClipper.Benchmarks; + +/* +BenchmarkDotNet v0.15.8, Windows 11 (10.0.26300.9818) +AMD RYZEN AI MAX+ 395 w/ Radeon 8060S 3.00GHz, 1 CPU, 32 logical and 16 physical cores +.NET SDK 11.0.100-preview.7.26381.103 + [Host] : .NET 10.0.14 (10.0.14, 10.0.1426.52326), X64 RyuJIT x86-64-v4 + ShortRun : .NET 10.0.14 (10.0.14, 10.0.1426.52326), X64 RyuJIT x86-64-v4 + +Job=ShortRun IterationCount=3 LaunchCount=1 +WarmupCount=3 + +| Method | VertexCount | Delta | Mean | Error | StdDev | Op/s | Ratio | RatioSD | Gen0 | Gen1 | Gen2 | Allocated | Alloc Ratio | +|--------------- |------------ |------ |---------------:|----------------:|--------------:|------------:|------:|--------:|----------:|----------:|----------:|-----------:|------------:| +| Offset | 16 | -1200 | 3.187 us | 1.1629 us | 0.0637 us | 313,729.508 | 0.09 | 0.00 | 0.0420 | - | - | 712 B | 0.03 | +| Clipper2Offset | 16 | -1200 | 33.982 us | 16.4081 us | 0.8994 us | 29,426.923 | 1.00 | 0.03 | 1.3733 | 0.0305 | - | 23376 B | 1.00 | +| | | | | | | | | | | | | | | +| Offset | 16 | -1 | 6.414 us | 0.8044 us | 0.0441 us | 155,897.311 | 1.64 | 0.02 | 0.1068 | - | - | 1792 B | 0.15 | +| Clipper2Offset | 16 | -1 | 3.919 us | 0.9182 us | 0.0503 us | 255,160.744 | 1.00 | 0.02 | 0.7248 | 0.0114 | - | 12176 B | 1.00 | +| | | | | | | | | | | | | | | +| Offset | 16 | 1 | 6.444 us | 0.8902 us | 0.0488 us | 155,181.218 | 4.69 | 0.07 | 0.1068 | - | - | 1792 B | 0.29 | +| Clipper2Offset | 16 | 1 | 1.373 us | 0.4167 us | 0.0228 us | 728,208.963 | 1.00 | 0.02 | 0.3738 | 0.0038 | - | 6264 B | 1.00 | +| | | | | | | | | | | | | | | +| Offset | 256 | -1200 | 47.463 us | 10.8460 us | 0.5945 us | 21,068.890 | 0.003 | 0.00 | 0.2441 | - | - | 4553 B | 0.002 | +| Clipper2Offset | 256 | -1200 | 17,393.549 us | 2,751.6011 us | 150.8245 us | 57.493 | 1.000 | 0.01 | 468.7500 | 468.7500 | 468.7500 | 2313643 B | 1.000 | +| | | | | | | | | | | | | | | +| Offset | 256 | -1 | 112.811 us | 61.9141 us | 3.3937 us | 8,864.413 | 1.57 | 0.13 | 0.7324 | - | - | 13313 B | 0.09 | +| Clipper2Offset | 256 | -1 | 72.041 us | 123.9203 us | 6.7925 us | 13,880.950 | 1.01 | 0.11 | 8.9111 | 1.9531 | - | 150536 B | 1.00 | +| | | | | | | | | | | | | | | +| Offset | 256 | 1 | 122.703 us | 117.8423 us | 6.4593 us | 8,149.775 | 7.00 | 1.07 | 0.7324 | - | - | 13313 B | 0.20 | +| Clipper2Offset | 256 | 1 | 17.908 us | 60.4415 us | 3.3130 us | 55,841.318 | 1.02 | 0.22 | 4.0588 | 0.4272 | - | 67896 B | 1.00 | +| | | | | | | | | | | | | | | +| Offset | 1024 | -1200 | 213.038 us | 96.3788 us | 5.2828 us | 4,694.003 | 0.001 | 0.00 | 0.9766 | - | - | 16851 B | 0.000 | +| Clipper2Offset | 1024 | -1200 | 307,856.250 us | 111,568.5614 us | 6,115.4493 us | 3.248 | 1.000 | 0.02 | 1000.0000 | 1000.0000 | 1000.0000 | 34406036 B | 1.000 | +| | | | | | | | | | | | | | | +| Offset | 1024 | -1 | 544.064 us | 71.5710 us | 3.9230 us | 1,838.020 | 1.91 | 0.06 | 2.9297 | - | - | 50218 B | 0.08 | +| Clipper2Offset | 1024 | -1 | 284.680 us | 167.3285 us | 9.1718 us | 3,512.721 | 1.00 | 0.04 | 35.1563 | 20.5078 | - | 593456 B | 1.00 | +| | | | | | | | | | | | | | | +| Offset | 1024 | 1 | 570.951 us | 484.5199 us | 26.5582 us | 1,751.463 | 9.28 | 0.50 | 2.9297 | - | - | 50218 B | 0.19 | +| Clipper2Offset | 1024 | 1 | 61.601 us | 47.6335 us | 2.6110 us | 16,233.583 | 1.00 | 0.05 | 15.8081 | 5.8594 | - | 264600 B | 1.00 | +*/ + +/// +/// Compares complete polygon offsets on equivalent closed geometry. +/// +[MemoryDiagnoser] +[OperationsPerSecond] +public class OffsetBenches +{ + private const int ClipperPrecision = 8; + private Polygon polygon; + private PathsD paths; + private OffsetOptions options; + + /// + /// Gets or sets the number of source vertices. + /// + [Params(16, 256, 1024)] + public int VertexCount { get; set; } + + /// + /// Gets or sets the signed offset distance. + /// + [Params(-1200D, -1D, 1D)] + public double Delta { get; set; } + + /// + /// Builds the source and checks topology and coordinates before measurement. + /// + [GlobalSetup] + public void Setup() + { + Contour contour = new(this.VertexCount); + PathD path = new(this.VertexCount); + for (int i = 0; i < this.VertexCount; i++) + { + double angle = i * Math.PI * 2 / this.VertexCount; + Vertex vertex = new(1000 * Math.Cos(angle), 1000 * Math.Sin(angle)); + contour.Add(vertex); + path.Add(new(vertex.X, vertex.Y)); + } + + this.polygon = [contour]; + this.paths = [path]; + this.options = new() { LineJoin = LineJoin.Miter }; + + Polygon actual = this.Offset(); + PathsD expected = this.Clipper2Offset(); + + // The edge-to-center distance of a regular polygon is radius * cos(pi / vertexCount). + int contourCount = this.Delta <= -1000 * Math.Cos(Math.PI / this.VertexCount) ? 0 : 1; + if (actual.Count != contourCount || expected.Count != contourCount) + { + throw new InvalidOperationException("The offset boundary count differs from the regular polygon's collapse distance."); + } + + if (contourCount == 0) + { + return; + } + + PathsD actualPaths = [new PathD(actual[0].Select(vertex => new PointD(vertex.X, vertex.Y)))]; + if (!TestPolygonUtilities.HaveEquivalentBoundaryGraphs(actualPaths, expected)) + { + throw new InvalidOperationException("The offset boundary connections differ."); + } + + // Clipper2 rounds input and output coordinates. Check agreement within one millionth + // of a source unit as well as topology, rather than comparing timings for different work. + foreach (Vertex vertex in actual[0]) + { + double nearest = double.PositiveInfinity; + PathD boundary = expected[0]; + for (int i = 0; i < boundary.Count; i++) + { + PointD first = boundary[i]; + PointD second = boundary[(i + 1) % boundary.Count]; + Vertex closest = PolygonUtilities.ClosestPointOnSegment(vertex, new(first.x, first.y), new(second.x, second.y)); + nearest = Math.Min(nearest, Vertex.DistanceSquared(vertex, closest)); + } + + if (nearest > 1E-12D) + { + throw new InvalidOperationException($"Offset vertex {vertex} differs from Clipper2 by {Math.Sqrt(nearest):R}, exceeding 1E-6."); + } + } + } + + /// + /// Offsets the source through its fill rule, boundary construction and Martinez resolution. + /// + /// The resolved offset polygon. + [Benchmark] + public Polygon Offset() => PolygonOffsetter.Offset(this.polygon, this.Delta, FillRule.NonZero, this.options); + + /// + /// Offsets the same valid source with Clipper2 miter joins. + /// + /// The offset paths. + [Benchmark(Baseline = true)] + public PathsD Clipper2Offset() + => Clipper.InflatePaths(this.paths, this.Delta, JoinType.Miter, EndType.Polygon, 4, ClipperPrecision); +} diff --git a/tests/PolygonClipper.Benchmarks/OpenClippingBenches.cs b/tests/PolygonClipper.Benchmarks/OpenClippingBenches.cs index d7b8345..53a444e 100644 --- a/tests/PolygonClipper.Benchmarks/OpenClippingBenches.cs +++ b/tests/PolygonClipper.Benchmarks/OpenClippingBenches.cs @@ -7,35 +7,41 @@ namespace SixLabors.PolygonClipper.Benchmarks; /* - * Comparison results: 30 October 2026. - * Windows 11. AMD Ryzen AI Max+ 395. .NET 10.0.14. BenchmarkDotNet 0.15.8. - * V2 build: 4f814c3 with the orientation-bound formula. release/1.x: cb06839. Clipper2: 4be4655. - * Mean: milliseconds per operation. Op/s: operations per second. B/op: allocated bytes per operation. - * Input preparation occurs before measurement. ClipperD uses precision 6. - * Each case uses 12 measured iterations, a 250 ms iteration target, and one launch. All samples remain included. - * The setup checks exact output edges for every open-path case. - * The .NET counters measure managed bytes. release/1.x and Rust have no matching open-path API. - * Warmup: 10 iterations. The 1,000-path, 13-vertex transposed case uses a repeat with 30 iterations for both engines. - * - * Paths | Vertices/path | Transpose | Engine | Mean (ms) | Op/s | B/op - * ------+---------------+-----------+----------+-----------+------------+-------- - * 10 | 2 | False | Clipper2 | 0.002487 | 402069.493 | 13680 - * 10 | 2 | False | V2 | 0.009797 | 102068.642 | 2872 - * 10 | 2 | True | Clipper2 | 0.002442 | 409562.862 | 15272 - * 10 | 2 | True | V2 | 0.009971 | 100295.413 | 2872 - * 10 | 13 | False | Clipper2 | 0.009040 | 110623.884 | 43592 - * 10 | 13 | False | V2 | 0.028162 | 35508.975 | 7072 - * 10 | 13 | True | Clipper2 | 0.005468 | 182885.680 | 32808 - * 10 | 13 | True | V2 | 0.035768 | 27958.106 | 7072 - * 1000 | 2 | False | Clipper2 | 0.199499 | 5012.556 | 1098600 - * 1000 | 2 | False | V2 | 1.083615 | 922.837 | 264232 - * 1000 | 2 | True | Clipper2 | 0.576339 | 1735.091 | 1274864 - * 1000 | 2 | True | V2 | 1.235454 | 809.419 | 264232 - * 1000 | 13 | False | Clipper2 | 3.402228 | 293.925 | 3899782 - * 1000 | 13 | False | V2 | 4.668755 | 214.190 | 612232 - * 1000 | 13 | True | Clipper2 | 2.569250 | 389.219 | 3002254 - * 1000 | 13 | True | V2 | 5.211886 | 191.869 | 612232 - */ +BenchmarkDotNet v0.15.8, Windows 11 (10.0.26300.9818) +AMD RYZEN AI MAX+ 395 w/ Radeon 8060S 3.00GHz, 1 CPU, 32 logical and 16 physical cores +.NET SDK 11.0.100-preview.7.26381.103 + [Host] : .NET 10.0.14 (10.0.14, 10.0.1426.52326), X64 RyuJIT x86-64-v4 + ShortRun : .NET 10.0.14 (10.0.14, 10.0.1426.52326), X64 RyuJIT x86-64-v4 + +Job=ShortRun IterationCount=3 LaunchCount=1 +WarmupCount=3 + +| Method | PathCount | VerticesPerPath | Transpose | Mean | Error | StdDev | Op/s | Ratio | RatioSD | Gen0 | Gen1 | Gen2 | Allocated | Alloc Ratio | +|--------------------------- |---------- |---------------- |---------- |-------------:|--------------:|------------:|----------:|------:|--------:|---------:|---------:|---------:|-----------:|------------:| +| PolygonClipperIntersection | 10 | 2 | False | 10.041 us | 6.363 us | 0.3488 us | 99,591.4 | 3.84 | 0.17 | 0.1678 | - | - | 2.84 KB | 0.21 | +| Clipper2Intersection | 10 | 2 | False | 2.617 us | 1.762 us | 0.0966 us | 382,076.6 | 1.00 | 0.05 | 0.8163 | 0.0267 | - | 13.36 KB | 1.00 | +| | | | | | | | | | | | | | | | +| PolygonClipperIntersection | 10 | 2 | True | 11.112 us | 31.236 us | 1.7122 us | 89,995.8 | 4.11 | 0.57 | 0.1678 | - | - | 2.84 KB | 0.19 | +| Clipper2Intersection | 10 | 2 | True | 2.706 us | 2.357 us | 0.1292 us | 369,564.4 | 1.00 | 0.06 | 0.9117 | 0.0343 | - | 14.91 KB | 1.00 | +| | | | | | | | | | | | | | | | +| PolygonClipperIntersection | 10 | 13 | False | 29.653 us | 14.059 us | 0.7706 us | 33,723.5 | 2.98 | 0.08 | 0.3967 | - | - | 6.94 KB | 0.16 | +| Clipper2Intersection | 10 | 13 | False | 9.945 us | 2.376 us | 0.1302 us | 100,556.0 | 1.00 | 0.02 | 2.5940 | 0.2747 | - | 42.57 KB | 1.00 | +| | | | | | | | | | | | | | | | +| PolygonClipperIntersection | 10 | 13 | True | 35.715 us | 12.425 us | 0.6811 us | 27,999.5 | 5.94 | 0.17 | 0.3662 | - | - | 6.94 KB | 0.22 | +| Clipper2Intersection | 10 | 13 | True | 6.019 us | 2.905 us | 0.1592 us | 166,136.7 | 1.00 | 0.03 | 1.9608 | 0.1678 | - | 32.04 KB | 1.00 | +| | | | | | | | | | | | | | | | +| PolygonClipperIntersection | 1000 | 2 | False | 1,202.917 us | 1,173.842 us | 64.3422 us | 831.3 | 5.81 | 0.27 | 15.6250 | 5.8594 | - | 258.07 KB | 0.24 | +| Clipper2Intersection | 1000 | 2 | False | 207.058 us | 27.796 us | 1.5236 us | 4,829.6 | 1.00 | 0.01 | 65.4297 | 50.2930 | - | 1072.85 KB | 1.00 | +| | | | | | | | | | | | | | | | +| PolygonClipperIntersection | 1000 | 2 | True | 1,340.080 us | 949.095 us | 52.0231 us | 746.2 | 2.13 | 0.12 | 15.6250 | 5.8594 | - | 258.07 KB | 0.21 | +| Clipper2Intersection | 1000 | 2 | True | 629.687 us | 598.724 us | 32.8181 us | 1,588.1 | 1.00 | 0.06 | 76.1719 | 65.4297 | - | 1244.98 KB | 1.00 | +| | | | | | | | | | | | | | | | +| PolygonClipperIntersection | 1000 | 13 | False | 5,080.375 us | 1,062.886 us | 58.2604 us | 196.8 | 1.41 | 0.03 | 31.2500 | 7.8125 | - | 597.91 KB | 0.16 | +| Clipper2Intersection | 1000 | 13 | False | 3,600.080 us | 1,497.421 us | 82.0787 us | 277.8 | 1.00 | 0.03 | 316.4063 | 312.5000 | 109.3750 | 3808.37 KB | 1.00 | +| | | | | | | | | | | | | | | | +| PolygonClipperIntersection | 1000 | 13 | True | 5,290.140 us | 385.407 us | 21.1255 us | 189.0 | 1.62 | 0.26 | 31.2500 | 7.8125 | - | 597.91 KB | 0.20 | +| Clipper2Intersection | 1000 | 13 | True | 3,353.168 us | 12,912.942 us | 707.8019 us | 298.2 | 1.03 | 0.25 | 234.3750 | 230.4688 | 74.2188 | 2931.89 KB | 1.00 | +*/ /// /// Compares open line clipping against the same closed rectangle and hole. diff --git a/tests/PolygonClipper.Benchmarks/StarBooleanBenches.cs b/tests/PolygonClipper.Benchmarks/StarBooleanBenches.cs index 34c6067..1633905 100644 --- a/tests/PolygonClipper.Benchmarks/StarBooleanBenches.cs +++ b/tests/PolygonClipper.Benchmarks/StarBooleanBenches.cs @@ -7,66 +7,30 @@ namespace SixLabors.PolygonClipper.Benchmarks; /* - * Comparison results: 30 October 2026. - * Windows 11. AMD Ryzen AI Max+ 395. .NET 10.0.14. BenchmarkDotNet 0.15.8. - * V2 build: 4f814c3 with the orientation-bound formula. release/1.x: cb06839. Clipper2: 4be4655. - * Mean: milliseconds per operation. Op/s: operations per second. B/op: allocated bytes per operation. - * Input preparation occurs before measurement. ClipperD uses precision 6. - * Each case uses 12 measured iterations, a 250 ms iteration target, and one launch. All samples remain included. - * Rust: rust-geo-booleanop 0.3.2 at b9bbdbb. rustc 1.98.0. Release build. geo-types 0.7.20. - * Rust timings include the native call and output destruction. Rust supports EvenOdd only. - * The .NET counters measure managed bytes. A separate Rust build counts requested native bytes. - * The comparison harness measures the fill rules and engines shown below on the same pair of stars. - * Warmup: 10 iterations, except the four variable 101-vertex cases, which use a repeat with 30 iterations. - * Those repeats cover Union with EvenOdd and NonZero, and Intersection and Difference with EvenOdd. - * Every supported engine uses the same longer warmup in each repeated case. - * release/1.x NonZero includes its required input preparation. - * Both dense-star EvenOdd unions pass the boundary checks despite different contour grouping. - * - * Vertices | Fill rule | Operation | Engine | Mean (ms) | Op/s | B/op - * ---------+-----------+--------------+-------------+-------------+---------+---------- - * 101 | EvenOdd | Union | V2 | 9.531152 | 104.919 | 1221184 - * 101 | EvenOdd | Union | release/1.x | 33.957776 | 29.448 | 10058513 - * 101 | EvenOdd | Union | Clipper2 | 37.183475 | 26.894 | 5454480 - * 101 | EvenOdd | Union | Rust | 28.678877 | 34.869 | 12025868 - * 101 | EvenOdd | Intersection | V2 | 10.124404 | 98.771 | 1979952 - * 101 | EvenOdd | Intersection | release/1.x | 35.579118 | 28.106 | 11013441 - * 101 | EvenOdd | Intersection | Clipper2 | 6.114008 | 163.559 | 5081410 - * 101 | EvenOdd | Intersection | Rust | 29.568188 | 33.820 | 14123564 - * 101 | EvenOdd | Difference | V2 | 9.295369 | 107.580 | 1539000 - * 101 | EvenOdd | Difference | release/1.x | 34.142293 | 29.289 | 10492458 - * 101 | EvenOdd | Difference | Clipper2 | 6.015985 | 166.224 | 4180303 - * 101 | EvenOdd | Difference | Rust | 30.183794 | 33.130 | 13713340 - * 101 | EvenOdd | Xor | V2 | 23.045433 | 43.393 | 10778162 - * 101 | EvenOdd | Xor | release/1.x | 33.714825 | 29.661 | 12728260 - * 101 | EvenOdd | Xor | Clipper2 | 10.867327 | 92.019 | 8527564 - * 101 | EvenOdd | Xor | Rust | 35.518577 | 28.154 | 18811516 - * 101 | NonZero | Union | V2 | 7.799769 | 128.209 | 213480 - * 101 | NonZero | Union | release/1.x | 4.803016 | 208.202 | 1125464 - * 101 | NonZero | Union | Clipper2 | 3.329548 | 300.341 | 874861 - * 301 | EvenOdd | Union | V2 | 113.486163 | 8.812 | 34139832 - * 301 | EvenOdd | Union | release/1.x | 445.814992 | 2.243 | 88329168 - * 301 | EvenOdd | Union | Clipper2 | 1942.372475 | 0.515 | 40570064 - * 301 | EvenOdd | Union | Rust | 419.326683 | 2.385 | 104351676 - * 301 | EvenOdd | Intersection | V2 | 143.969358 | 6.946 | 55822008 - * 301 | EvenOdd | Intersection | release/1.x | 495.890125 | 2.017 | 96940976 - * 301 | EvenOdd | Intersection | Clipper2 | 123.051400 | 8.127 | 44447544 - * 301 | EvenOdd | Intersection | Rust | 468.113050 | 2.136 | 121501628 - * 301 | EvenOdd | Difference | V2 | 137.709375 | 7.262 | 45124380 - * 301 | EvenOdd | Difference | release/1.x | 459.630592 | 2.176 | 92145616 - * 301 | EvenOdd | Difference | Clipper2 | 103.656529 | 9.647 | 36238448 - * 301 | EvenOdd | Difference | Rust | 440.715792 | 2.269 | 117719484 - * 301 | EvenOdd | Xor | V2 | 265.359167 | 3.768 | 94318776 - * 301 | EvenOdd | Xor | release/1.x | 560.481942 | 1.784 | 111897144 - * 301 | EvenOdd | Xor | Clipper2 | 266.766542 | 3.749 | 73402336 - * 301 | EvenOdd | Xor | Rust | 555.358192 | 1.801 | 159997324 - * 301 | NonZero | Union | V2 | 72.203506 | 13.850 | 1879008 - * 301 | NonZero | Union | release/1.x | 50.096682 | 19.961 | 11411998 - * 301 | NonZero | Union | Clipper2 | 72.272604 | 13.837 | 6609810 - * 1001 | NonZero | Union | V2 | 923.958408 | 1.082 | 63130176 - * 1001 | NonZero | Union | release/1.x | 852.718975 | 1.173 | 151387784 - * 1001 | NonZero | Union | Clipper2 | 2850.236992 | 0.351 | 61347952 - */ +BenchmarkDotNet v0.15.8, Windows 11 (10.0.26300.9818) +AMD RYZEN AI MAX+ 395 w/ Radeon 8060S 3.00GHz, 1 CPU, 32 logical and 16 physical cores +.NET SDK 11.0.100-preview.7.26381.103 + [Host] : .NET 10.0.14 (10.0.14, 10.0.1426.52326), X64 RyuJIT x86-64-v4 + ShortRun : .NET 10.0.14 (10.0.14, 10.0.1426.52326), X64 RyuJIT x86-64-v4 + +Job=ShortRun IterationCount=3 LaunchCount=1 +WarmupCount=3 + +| Method | VertexCount | Mean | Error | StdDev | Op/s | Gen0 | Gen1 | Gen2 | Allocated | +|--------------------------- |------------ |-------------:|-------------:|------------:|---------:|-----------:|-----------:|----------:|--------------:| +| PolygonClipperUnion | 101 | 10.241 ms | 14.189 ms | 0.7778 ms | 97.6464 | 46.8750 | 15.6250 | - | 984.86 KB | +| PolygonClipperIntersection | 101 | 9.785 ms | 3.148 ms | 0.1726 ms | 102.2006 | 93.7500 | 46.8750 | - | 1769.23 KB | +| PolygonClipperDifference | 101 | 8.865 ms | 1.617 ms | 0.0886 ms | 112.8081 | 78.1250 | 15.6250 | - | 1330.24 KB | +| PolygonClipperXor | 101 | 19.532 ms | 7.799 ms | 0.4275 ms | 51.1991 | 1312.5000 | 1312.5000 | 843.7500 | 11968.01 KB | +| PolygonClipperUnion | 301 | 122.200 ms | 128.921 ms | 7.0666 ms | 8.1833 | 2600.0000 | 2600.0000 | 1200.0000 | 33225.89 KB | +| PolygonClipperIntersection | 301 | 170.792 ms | 109.231 ms | 5.9873 ms | 5.8551 | 3333.3333 | 3333.3333 | 1333.3333 | 57243.84 KB | +| PolygonClipperDifference | 301 | 156.373 ms | 170.076 ms | 9.3224 ms | 6.3950 | 3250.0000 | 3250.0000 | 1500.0000 | 48985.99 KB | +| PolygonClipperXor | 301 | 277.201 ms | 61.909 ms | 3.3934 ms | 3.6075 | 6000.0000 | 5500.0000 | 2000.0000 | 106509.15 KB | +| PolygonClipperUnion | 1001 | 1,853.955 ms | 1,062.212 ms | 58.2234 ms | 0.5394 | 21000.0000 | 20000.0000 | 5000.0000 | 421820.51 KB | +| PolygonClipperIntersection | 1001 | 2,498.312 ms | 270.235 ms | 14.8125 ms | 0.4003 | 34000.0000 | 32000.0000 | 6000.0000 | 738265.43 KB | +| PolygonClipperDifference | 1001 | 2,083.018 ms | 226.483 ms | 12.4143 ms | 0.4801 | 28000.0000 | 26000.0000 | 5000.0000 | 539974.69 KB | +| PolygonClipperXor | 1001 | 3,337.877 ms | 3,338.490 ms | 182.9939 ms | 0.2996 | 54000.0000 | 48000.0000 | 6000.0000 | 1080092.26 KB | +*/ /// /// Benchmarks PolygonClipper boolean operations using two overlapping star polygons. diff --git a/tests/PolygonClipper.Benchmarks/StrokeBenches.cs b/tests/PolygonClipper.Benchmarks/StrokeBenches.cs index 9ecbadf..d85a628 100644 --- a/tests/PolygonClipper.Benchmarks/StrokeBenches.cs +++ b/tests/PolygonClipper.Benchmarks/StrokeBenches.cs @@ -6,6 +6,28 @@ namespace SixLabors.PolygonClipper.Benchmarks; +/* +BenchmarkDotNet v0.15.8, Windows 11 (10.0.26300.9818) +AMD RYZEN AI MAX+ 395 w/ Radeon 8060S 3.00GHz, 1 CPU, 32 logical and 16 physical cores +.NET SDK 11.0.100-preview.7.26381.103 + [Host] : .NET 10.0.14 (10.0.14, 10.0.1426.52326), X64 RyuJIT x86-64-v4 + ShortRun : .NET 10.0.14 (10.0.14, 10.0.1426.52326), X64 RyuJIT x86-64-v4 + +Job=ShortRun IterationCount=3 LaunchCount=1 +WarmupCount=3 + +| Method | VertexCount | Mean | Error | StdDev | Op/s | Ratio | RatioSD | Gen0 | Gen1 | Gen2 | Allocated | Alloc Ratio | +|------------------------------------ |------------ |----------------:|--------------:|--------------:|------------:|------:|--------:|----------:|----------:|----------:|------------:|------------:| +| PolygonStrokerProcessPolygonAndClip | 101 | 86.35 us | 10.28 us | 0.564 us | 11,581.2627 | 0.01 | 0.00 | 8.7891 | - | - | 144.85 KB | 0.08 | +| Clipper2InflatePaths | 101 | 6,711.66 us | 6,421.82 us | 352.002 us | 148.9944 | 1.00 | 0.06 | 117.1875 | 117.1875 | 117.1875 | 1804.44 KB | 1.00 | +| | | | | | | | | | | | | | +| PolygonStrokerProcessPolygonAndClip | 301 | 263.81 us | 58.59 us | 3.211 us | 3,790.6037 | 0.004 | 0.00 | 27.3438 | 13.1836 | - | 448.83 KB | 0.07 | +| Clipper2InflatePaths | 301 | 66,415.27 us | 48,388.21 us | 2,652.321 us | 15.0568 | 1.001 | 0.05 | 625.0000 | 500.0000 | 500.0000 | 6144.33 KB | 1.00 | +| | | | | | | | | | | | | | +| PolygonStrokerProcessPolygonAndClip | 1001 | 1,199.12 us | 178.09 us | 9.762 us | 833.9431 | 0.000 | 0.00 | 498.0469 | 498.0469 | 498.0469 | 1921.08 KB | 0.06 | +| Clipper2InflatePaths | 1001 | 2,556,662.97 us | 375,556.20 us | 20,585.503 us | 0.3911 | 1.000 | 0.01 | 3000.0000 | 2000.0000 | 2000.0000 | 32250.45 KB | 1.00 | +*/ + /// /// Benchmarks stroke generation and clipping against Clipper2 path inflation. /// diff --git a/tests/PolygonClipper.Tests/ApproximateDoubleComparer.cs b/tests/PolygonClipper.Tests/ApproximateDoubleComparer.cs new file mode 100644 index 0000000..44011b2 --- /dev/null +++ b/tests/PolygonClipper.Tests/ApproximateDoubleComparer.cs @@ -0,0 +1,40 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +namespace SixLabors.PolygonClipper.Tests; + +/// +/// Compares double values and vertices within a specified error for test assertions. +/// +internal readonly struct ApproximateDoubleComparer : IEqualityComparer, IEqualityComparer +{ + private readonly double epsilon; + + /// + /// Initializes a new instance of the struct. + /// + /// The maximum absolute difference between coordinate values. + public ApproximateDoubleComparer(double epsilon) => this.epsilon = epsilon; + + /// + public bool Equals(double x, double y) + { + // Match the ImageSharp comparer for equal infinities and matching NaNs. + if (x == y || (double.IsNaN(x) && double.IsNaN(y))) + { + return true; + } + + double difference = x - y; + return difference >= -this.epsilon && difference <= this.epsilon; + } + + /// + public int GetHashCode(double obj) => obj.GetHashCode(); + + /// + public bool Equals(Vertex x, Vertex y) => this.Equals(x.X, y.X) && this.Equals(x.Y, y.Y); + + /// + public int GetHashCode(Vertex obj) => obj.GetHashCode(); +} diff --git a/tests/PolygonClipper.Tests/ApproximateDoubleComparerTests.cs b/tests/PolygonClipper.Tests/ApproximateDoubleComparerTests.cs new file mode 100644 index 0000000..73e162a --- /dev/null +++ b/tests/PolygonClipper.Tests/ApproximateDoubleComparerTests.cs @@ -0,0 +1,64 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +namespace SixLabors.PolygonClipper.Tests; + +/// +/// Checks the approximate comparer through xUnit equality assertions. +/// +public class ApproximateDoubleComparerTests +{ + /// + /// Checks finite differences, equal infinities and matching NaNs. + /// + /// The first value. + /// The second value. + /// Whether the values compare equal within one eighth. + [Theory] + [InlineData(0D, 0D, true)] + [InlineData(1D, 1.125D, true)] + [InlineData(-1D, -1.125D, true)] + [InlineData(1D, 1.25D, false)] + [InlineData(double.NaN, double.NaN, true)] + [InlineData(double.PositiveInfinity, double.PositiveInfinity, true)] + [InlineData(double.NegativeInfinity, double.NegativeInfinity, true)] + [InlineData(double.PositiveInfinity, double.NegativeInfinity, false)] + [InlineData(double.PositiveInfinity, double.MaxValue, false)] + public void Equals_Doubles_UsesSpecifiedError(double first, double second, bool equal) + { + ApproximateDoubleComparer comparer = new(0.125D); + if (equal) + { + Assert.Equal(first, second, comparer); + } + else + { + Assert.NotEqual(first, second, comparer); + } + } + + /// + /// Checks that both vertex coordinates must compare equal. + /// + /// The second vertex's X coordinate. + /// The second vertex's Y coordinate. + /// Whether both coordinates are within one eighth of zero. + [Theory] + [InlineData(0.125D, -0.125D, true)] + [InlineData(0.25D, 0D, false)] + [InlineData(0D, 0.25D, false)] + public void Equals_Vertices_ChecksBothCoordinates(double x, double y, bool equal) + { + ApproximateDoubleComparer comparer = new(0.125D); + Vertex first = new(0, 0); + Vertex second = new(x, y); + if (equal) + { + Assert.Equal(first, second, comparer); + } + else + { + Assert.NotEqual(first, second, comparer); + } + } +} diff --git a/tests/PolygonClipper.Tests/OffsetOptionsTests.cs b/tests/PolygonClipper.Tests/OffsetOptionsTests.cs new file mode 100644 index 0000000..648e88e --- /dev/null +++ b/tests/PolygonClipper.Tests/OffsetOptionsTests.cs @@ -0,0 +1,74 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +namespace SixLabors.PolygonClipper.Tests; + +/// +/// Checks the defaults and value comparison of offset settings. +/// +public class OffsetOptionsTests +{ + /// + /// Checks that offset settings retain the established join and arc defaults. + /// + [Fact] + public void Defaults_AreAsDocumented() + { + OffsetOptions options = new(); + + Assert.Equal(4D, options.MiterLimit); + Assert.Equal(1D, options.ArcDetailScale); + Assert.Equal(LineJoin.Bevel, options.LineJoin); + } + + /// + /// Checks that each setting retains its assigned value. + /// + [Fact] + public void Properties_RoundTrip() + { + OffsetOptions options = new() { MiterLimit = 2.5, ArcDetailScale = 0.5, LineJoin = LineJoin.Round }; + + Assert.Equal(2.5, options.MiterLimit); + Assert.Equal(0.5, options.ArcDetailScale); + Assert.Equal(LineJoin.Round, options.LineJoin); + } + + /// + /// Checks that value comparison includes every offset setting. + /// + /// The comparison miter limit. + /// The comparison arc detail scale. + /// The comparison join style. + /// Whether all settings match the defaults. + [Theory] + [InlineData(4D, 1D, LineJoin.Bevel, true)] + [InlineData(2D, 1D, LineJoin.Bevel, false)] + [InlineData(4D, 2D, LineJoin.Bevel, false)] + [InlineData(4D, 1D, LineJoin.Round, false)] + public void Equality_UsesAllSettings(double miterLimit, double arcDetailScale, LineJoin lineJoin, bool equal) + { + OffsetOptions first = new(); + OffsetOptions second = new() { MiterLimit = miterLimit, ArcDetailScale = arcDetailScale, LineJoin = lineJoin }; + + Assert.Equal(equal, first.Equals(second)); + Assert.Equal(equal, first.Equals((object)second)); + if (equal) + { + Assert.Equal(first.GetHashCode(), second.GetHashCode()); + } + } + + /// + /// Checks value comparison against null and an unrelated object. + /// + [Fact] + public void Equality_RejectsNullAndOtherTypes() + { + OffsetOptions options = new(); + + Assert.False(options.Equals(null)); + Assert.False(options.Equals((object)null)); + Assert.False(options.Equals("not options")); + } +} diff --git a/tests/PolygonClipper.Tests/PolygonOffsetTests.cs b/tests/PolygonClipper.Tests/PolygonOffsetTests.cs new file mode 100644 index 0000000..c0f8add --- /dev/null +++ b/tests/PolygonClipper.Tests/PolygonOffsetTests.cs @@ -0,0 +1,644 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +namespace SixLabors.PolygonClipper.Tests; + +/// +/// Checks polygon offsets against known geometry and collapse distances. +/// +public class PolygonOffsetTests +{ + /// + /// Checks that erosion past the center removes a square instead of leaving a false island. + /// + [Fact] + public void Offset_DeflationBeyondSquareCenter_ReturnsEmpty() + { + Polygon subject = [[new(0, 0), new(10, 0), new(10, 10), new(0, 10)]]; + OffsetOptions options = new() { LineJoin = LineJoin.Miter }; + Polygon actual = PolygonOffsetter.Offset(subject, -6, FillRule.NonZero, options); + SvgTestOutput.SaveSvg( + nameof(PolygonOffsetTests), nameof(this.Offset_DeflationBeyondSquareCenter_ReturnsEmpty), string.Empty, subject, [], actual, []); + + Assert.Empty(actual); + } + + /// + /// Checks exact rectangle boundaries before, at and beyond collapse. + /// + /// The signed boundary distance. + [Theory] + [InlineData(-12D)] + [InlineData(-5D)] + [InlineData(-4D)] + [InlineData(-1D)] + [InlineData(0D)] + [InlineData(1D)] + [InlineData(6D)] + public void Offset_Rectangle_MatchesKnownBounds(double delta) + { + Polygon subject = [Rectangle(0, 0, 10, 10)]; + Polygon expected = delta <= -5 ? [] : [Rectangle(-delta, -delta, 10 + delta, 10 + delta)]; + Polygon actual = PolygonOffsetter.Offset(subject, delta, FillRule.NonZero, new() { LineJoin = LineJoin.Miter }); + + AssertGeometry(nameof(this.Offset_Rectangle_MatchesKnownBounds), $"Delta-{delta}", subject, actual, expected); + } + + /// + /// Checks shrinking holes and the disappearance of an eroded ring. + /// + /// The signed boundary distance. + [Theory] + [InlineData(-4D)] + [InlineData(-3D)] + [InlineData(-2D)] + [InlineData(-1D)] + [InlineData(1D)] + [InlineData(4D)] + [InlineData(6D)] + public void Offset_Donut_HandlesBothBoundaryCollapses(double delta) + { + Contour hole = Rectangle(6, 6, 14, 14); + hole.Reverse(); + Polygon subject = [Rectangle(0, 0, 20, 20), hole]; + Polygon expected = []; + if (delta > -3) + { + expected.Add(Rectangle(-delta, -delta, 20 + delta, 20 + delta)); + if (delta < 4) + { + Contour expectedHole = Rectangle(6 + delta, 6 + delta, 14 - delta, 14 - delta); + expectedHole.Reverse(); + expected.Add(expectedHole); + } + } + + Polygon actual = PolygonOffsetter.Offset(subject, delta, FillRule.NonZero, new() { LineJoin = LineJoin.Miter }); + AssertGeometry(nameof(this.Offset_Donut_HandlesBothBoundaryCollapses), $"Delta-{delta}", subject, actual, expected); + if (expected.Count == 2) + { + Assert.Null(actual[0].ParentIndex); + Assert.Equal(1, actual[0].HoleCount); + Assert.Equal(0, actual[1].ParentIndex); + Assert.Equal(1, actual[1].Depth); + } + } + + /// + /// Checks inner corners and complete collapse of two narrow arms. + /// + /// The signed boundary distance. + [Theory] + [InlineData(-3D)] + [InlineData(-2D)] + [InlineData(-1D)] + [InlineData(1D)] + public void Offset_ConcaveBoundary_MatchesKnownCorners(double delta) + { + Polygon subject = [[new(0, 0), new(10, 0), new(10, 4), new(4, 4), new(4, 10), new(0, 10)]]; + Polygon expected = delta <= -2 + ? [] + : [[new(-delta, -delta), new(10 + delta, -delta), new(10 + delta, 4 + delta), + new(4 + delta, 4 + delta), new(4 + delta, 10 + delta), new(-delta, 10 + delta)]]; + Polygon actual = PolygonOffsetter.Offset(subject, delta, FillRule.NonZero, new() { LineJoin = LineJoin.Miter }); + + AssertGeometry(nameof(this.Offset_ConcaveBoundary_MatchesKnownCorners), $"Delta-{delta}", subject, actual, expected); + } + + /// + /// Checks that eroding a neck splits the area into two surviving components. + /// + [Fact] + public void Offset_NarrowNeck_SplitsComponents() + { + Polygon subject = + [[new(0, 0), new(6, 0), new(6, 2), new(10, 2), new(10, 0), new(16, 0), + new(16, 6), new(10, 6), new(10, 4), new(6, 4), new(6, 6), new(0, 6)]]; + Polygon expected = [Rectangle(1, 1, 5, 5), Rectangle(11, 1, 15, 5)]; + Polygon actual = PolygonOffsetter.Offset(subject, -1, FillRule.NonZero, new() { LineJoin = LineJoin.Miter }); + + AssertGeometry(nameof(this.Offset_NarrowNeck_SplitsComponents), string.Empty, subject, actual, expected); + } + + /// + /// Checks the union of separately expanded components when their boundaries meet. + /// + [Fact] + public void Offset_ExpandingComponents_Merge() + { + Polygon subject = [Rectangle(0, 0, 4, 4), Rectangle(6, 0, 10, 4)]; + Polygon expected = [Rectangle(-1, -1, 11, 5)]; + Polygon actual = PolygonOffsetter.Offset(subject, 1, FillRule.NonZero, new() { LineJoin = LineJoin.Miter }); + + AssertGeometry(nameof(this.Offset_ExpandingComponents_Merge), string.Empty, subject, actual, expected); + } + + /// + /// Checks the full containment hierarchy for an island inside a hole. + /// + [Fact] + public void Offset_NestedIsland_PreservesHierarchy() + { + Contour hole = Rectangle(4, 4, 26, 26); + hole.Reverse(); + Polygon subject = [Rectangle(0, 0, 30, 30), hole, Rectangle(10, 10, 20, 20)]; + Contour expectedHole = Rectangle(5, 5, 25, 25); + expectedHole.Reverse(); + Polygon expected = [Rectangle(-1, -1, 31, 31), expectedHole, Rectangle(9, 9, 21, 21)]; + Polygon actual = PolygonOffsetter.Offset(subject, 1, FillRule.NonZero, new() { LineJoin = LineJoin.Miter }); + + AssertGeometry(nameof(this.Offset_NestedIsland_PreservesHierarchy), string.Empty, subject, actual, expected); + Assert.Null(actual[0].ParentIndex); + Assert.Equal(0, actual[1].ParentIndex); + Assert.Equal(1, actual[2].ParentIndex); + Assert.Equal(2, actual[2].Depth); + } + + /// + /// Checks that raw overlap and direction are interpreted before offsetting the filled boundary. + /// + /// The source fill rule. + /// Whether both source contours run clockwise. + [Theory] + [InlineData(FillRule.EvenOdd, false)] + [InlineData(FillRule.EvenOdd, true)] + [InlineData(FillRule.NonZero, false)] + [InlineData(FillRule.NonZero, true)] + [InlineData(FillRule.Positive, false)] + [InlineData(FillRule.Positive, true)] + [InlineData(FillRule.Negative, false)] + [InlineData(FillRule.Negative, true)] + public void Offset_OverlappingContours_UsesSourceFillRule(FillRule rule, bool reverse) + { + Polygon subject = [Rectangle(0, 0, 10, 10), Rectangle(5, 0, 15, 10)]; + if (reverse) + { + foreach (Contour contour in subject) + { + contour.Reverse(); + } + } + + Polygon expected = rule == FillRule.EvenOdd + ? [Rectangle(-0.5, -0.5, 5.5, 10.5), Rectangle(9.5, -0.5, 15.5, 10.5)] + : rule == FillRule.NonZero || (rule == FillRule.Positive && !reverse) || (rule == FillRule.Negative && reverse) + ? [Rectangle(-0.5, -0.5, 15.5, 10.5)] + : []; + Polygon actual = PolygonOffsetter.Offset(subject, 0.5, rule, new() { LineJoin = LineJoin.Miter }); + + AssertGeometry(nameof(this.Offset_OverlappingContours_UsesSourceFillRule), $"Rule-{rule}_Reverse-{reverse}", subject, actual, expected); + } + + /// + /// Checks the eight known vertices of a beveled rectangle offset. + /// + /// The bevel join or miter fallback to check. + [Theory] + [InlineData(LineJoin.Bevel)] + [InlineData(LineJoin.MiterRevert)] + public void Offset_Bevel_ClipsOuterCorners(LineJoin join) + { + Polygon subject = [Rectangle(0, 0, 10, 10)]; + Polygon expected = [[new(-2, 0), new(0, -2), new(10, -2), new(12, 0), new(12, 10), new(10, 12), new(0, 12), new(-2, 10)]]; + Polygon actual = PolygonOffsetter.Offset(subject, 2, FillRule.NonZero, new() { LineJoin = join, MiterLimit = 1 }); + + AssertGeometry(nameof(this.Offset_Bevel_ClipsOuterCorners), $"Join-{join}", subject, actual, expected); + } + + /// + /// Checks the radius and area of tessellated round corners without assuming a vertex count. + /// + /// The round join or miter fallback to check. + [Theory] + [InlineData(LineJoin.Round)] + [InlineData(LineJoin.MiterRound)] + public void Offset_RoundCorners_StayAtRequestedDistance(LineJoin join) + { + Polygon subject = [Rectangle(0, 0, 10, 10)]; + Polygon actual = PolygonOffsetter.Offset(subject, 2, FillRule.NonZero, new() { LineJoin = join, MiterLimit = 1, ArcDetailScale = 32 }); + SvgTestOutput.SaveSvg(nameof(PolygonOffsetTests), nameof(this.Offset_RoundCorners_StayAtRequestedDistance), $"Join-{join}", subject, [], actual); + Contour outline = Assert.Single(actual); + foreach (Vertex vertex in outline) + { + double dx = vertex.X - Math.Clamp(vertex.X, 0, 10); + double dy = vertex.Y - Math.Clamp(vertex.Y, 0, 10); + Assert.Equal(4D, (dx * dx) + (dy * dy), 10); + } + + // The exact area is the square, four edge strips and four quarter circles. + // Straight chords approximate the arcs from inside, so their area is slightly smaller. + double exactArea = 180 + (4 * Math.PI); + Assert.InRange(PolygonUtilities.Area(outline.AsVertexSpan()), exactArea - 0.1, exactArea); + } + + /// + /// Checks that round deflation expands a hole while contracting the exterior boundary. + /// + [Fact] + public void Offset_RoundDeflation_ExpandsHoleCorners() + { + Contour hole = Rectangle(6, 6, 14, 14); + hole.Reverse(); + Polygon subject = [Rectangle(0, 0, 20, 20), hole]; + Polygon actual = PolygonOffsetter.Offset(subject, -2, FillRule.NonZero, new() { LineJoin = LineJoin.Round, ArcDetailScale = 32 }); + SvgTestOutput.SaveSvg(nameof(PolygonOffsetTests), nameof(this.Offset_RoundDeflation_ExpandsHoleCorners), string.Empty, subject, [], actual); + + Assert.Equal(2, actual.Count); + ApproximateDoubleComparer comparer = new(1E-10D); + Assert.Equal(new Vertex(2, 2), actual[0].GetBoundingBox().Min, comparer); + Assert.Equal(new Vertex(18, 18), actual[0].GetBoundingBox().Max, comparer); + Assert.Equal(0, actual[1].ParentIndex); + foreach (Vertex vertex in actual[1]) + { + double dx = vertex.X - Math.Clamp(vertex.X, 6, 14); + double dy = vertex.Y - Math.Clamp(vertex.Y, 6, 14); + Assert.Equal(4D, (dx * dx) + (dy * dy), comparer); + } + + // The exterior area is 16 squared. The hole adds four width-two strips and a radius-two circle. + // Chords slightly reduce the hole area, so the retained area slightly exceeds the exact value. + double exactArea = 256 - (128 + (4 * Math.PI)); + double area = actual.Sum(contour => PolygonUtilities.Area(contour.AsVertexSpan())); + Assert.InRange(area, exactArea, exactArea + 0.1); + } + + /// + /// Checks that zero distance returns independent resolved contours without changing the source. + /// + [Fact] + public void Offset_Zero_ReturnsDetachedResolvedArea() + { + Polygon subject = [Rectangle(0, 0, 10, 10), Rectangle(5, 0, 15, 10)]; + string before = subject.ToDebugString(); + Polygon actual = PolygonOffsetter.Offset(subject, 0, FillRule.NonZero, new()); + Polygon expected = [Rectangle(0, 0, 15, 10)]; + + AssertGeometry(nameof(this.Offset_Zero_ReturnsDetachedResolvedArea), string.Empty, subject, actual, expected); + actual[0].Reverse(); + Assert.Equal(before, subject.ToDebugString()); + } + + /// + /// Checks that pooled offset execution cannot change later ordinary strokes or mutate the options. + /// + [Fact] + public void Offset_PooledReuse_PreservesStrokeBehavior() + { + Polygon subject = [Rectangle(0, 0, 10, 10)]; + StrokeOptions options = new() { LineJoin = LineJoin.Miter, NormalizeOutput = true, LineCap = LineCap.Round }; + StrokeOptions rawOptions = new() { LineJoin = LineJoin.Miter }; + OffsetOptions offsetOptions = new() { LineJoin = LineJoin.Miter }; + string before = subject.ToDebugString(); + Polygon stroke = PolygonStroker.Stroke(subject, 2, options); + Polygon rawStroke = PolygonStroker.Stroke(subject, 2, rawOptions); + for (int i = 0; i < 4; i++) + { + Polygon actual = PolygonOffsetter.Offset(subject, (i & 1) == 0 ? -6 : 1, FillRule.NonZero, offsetOptions); + Polygon expected = (i & 1) == 0 ? [] : [Rectangle(-1, -1, 11, 11)]; + AssertGeometry(nameof(this.Offset_PooledReuse_PreservesStrokeBehavior), $"Iteration-{i}", subject, actual, expected); + Assert.Equal(stroke.ToDebugString(), PolygonStroker.Stroke(subject, 2, options).ToDebugString()); + Assert.Equal(rawStroke.ToDebugString(), PolygonStroker.Stroke(subject, 2, rawOptions).ToDebugString()); + } + + Assert.Equal(before, subject.ToDebugString()); + Assert.True(options.NormalizeOutput); + Assert.Equal(LineCap.Round, options.LineCap); + Assert.Equal(LineJoin.Miter, offsetOptions.LineJoin); + Assert.Equal(4D, offsetOptions.MiterLimit); + Assert.Equal(1D, offsetOptions.ArcDetailScale); + } + + /// + /// Checks public distance and closure validation before offset generation. + /// + [Fact] + public void Offset_InvalidArguments_AreRejected() + { + Polygon subject = [Rectangle(0, 0, 10, 10)]; + OffsetOptions options = new(); + Assert.Throws(() => PolygonOffsetter.Offset(null, 1, FillRule.NonZero, options)); + Assert.Throws(() => PolygonOffsetter.Offset(subject, 1, FillRule.NonZero, null)); + Assert.Throws(() => PolygonOffsetter.Offset(subject, double.NaN, FillRule.NonZero, options)); + Assert.Throws(() => PolygonOffsetter.Offset(subject, double.PositiveInfinity, FillRule.NonZero, options)); + Assert.Throws(() => PolygonOffsetter.Offset(subject, double.NegativeInfinity, FillRule.NonZero, options)); + Assert.Throws(() => PolygonOffsetter.Offset(subject, 0, (FillRule)99, options)); + subject[0].IsClosed = false; + Assert.Throws(() => PolygonOffsetter.Offset(subject, 1, FillRule.NonZero, options)); + Assert.False(subject[0].IsClosed); + } + + /// + /// Checks both lobes of an unprepared bowtie against the six independently derived miter vertices. + /// + [Fact] + public void Offset_SelfCrossingBoundary_ResolvesBothLobes() + { + Polygon subject = [[new(0, 0), new(10, 10), new(0, 10), new(10, 0)]]; + double diagonal = Math.Sqrt(2); + + // Each diagonal moves by one perpendicular unit. Its coordinate sum or difference + // therefore changes by sqrt(2). Intersect those lines with y = -1, 5 and 11. + Polygon expected = + [[new(-1 - diagonal, -1), new(11 + diagonal, -1), new(5 + diagonal, 5), + new(11 + diagonal, 11), new(-1 - diagonal, 11), new(5 - diagonal, 5)]]; + Polygon actual = PolygonOffsetter.Offset(subject, 1, FillRule.NonZero, new() { LineJoin = LineJoin.Miter }); + + AssertGeometry(nameof(this.Offset_SelfCrossingBoundary_ResolvesBothLobes), string.Empty, subject, actual, expected); + } + + /// + /// Checks that offset distance scales with the coordinates without an integer conversion. + /// + /// The coordinate and distance scale. + /// The signed distance before scaling. + [Theory] + [InlineData(1E-8, 1D)] + [InlineData(1E-8, -6D)] + [InlineData(1E8, 1D)] + [InlineData(1E8, -6D)] + [InlineData(1E90, 1D)] + [InlineData(1E90, -6D)] + public void Offset_ScaledRectangle_PreservesDistance(double scale, double delta) + { + Polygon subject = [Rectangle(0, 0, 10 * scale, 10 * scale)]; + Polygon expected = delta < -5 ? [] : [Rectangle(-scale, -scale, 11 * scale, 11 * scale)]; + Polygon actual = PolygonOffsetter.Offset(subject, delta * scale, FillRule.NonZero, new() { LineJoin = LineJoin.Miter }); + + AssertGeometry( + nameof(this.Offset_ScaledRectangle_PreservesDistance), + FormattableString.Invariant($"Scale-{scale:R}_Delta-{delta}"), + subject, + actual, + expected); + } + + /// + /// Checks dense regular polygons against the offset of their common edge distance from the center. + /// + /// The number of regular polygon vertices. + /// The source vertex distance from the center. + /// The signed boundary distance. + /// Radius 10 provides visible offsets. Radius 1000 retains the small-offset accuracy cases. + [Theory] + [InlineData(16, 10D, -3D)] + [InlineData(16, 10D, -1D)] + [InlineData(16, 10D, 1D)] + [InlineData(16, 10D, 3D)] + [InlineData(16, 1000D, -1D)] + [InlineData(16, 1000D, 1D)] + [InlineData(256, 10D, -3D)] + [InlineData(256, 10D, -1D)] + [InlineData(256, 10D, 1D)] + [InlineData(256, 10D, 3D)] + [InlineData(256, 1000D, -1D)] + [InlineData(256, 1000D, 1D)] + [InlineData(1024, 10D, -3D)] + [InlineData(1024, 10D, -1D)] + [InlineData(1024, 10D, 1D)] + [InlineData(1024, 10D, 3D)] + [InlineData(1024, 1000D, -1D)] + [InlineData(1024, 1000D, 1D)] + public void Offset_RegularPolygon_MatchesKnownRadius(int vertexCount, double radius, double delta) + { + Contour source = new(vertexCount); + Contour reference = new(vertexCount); + + // A regular polygon's edge distance from its center is radius * cos(pi / vertexCount). + // Moving every edge by delta therefore changes the vertex radius by delta / cos(pi / vertexCount). + double expectedRadius = radius + (delta / Math.Cos(Math.PI / vertexCount)); + for (int i = 0; i < vertexCount; i++) + { + double angle = i * Math.PI * 2 / vertexCount; + Vertex direction = new(Math.Cos(angle), Math.Sin(angle)); + source.Add(direction * radius); + reference.Add(direction * expectedRadius); + } + + Polygon subject = [source]; + Polygon actual = PolygonOffsetter.Offset(subject, delta, FillRule.NonZero, new() { LineJoin = LineJoin.Miter }); + AssertGeometry( + nameof(this.Offset_RegularPolygon_MatchesKnownRadius), + FormattableString.Invariant($"VertexCount-{vertexCount}_Radius-{radius}_Delta-{delta}"), + subject, + actual, + [reference]); + } + + /// + /// Checks short obtuse corners where the side strips overlap past the neighboring edge midpoints. + /// + /// The inward boundary distance. + [Theory] + [InlineData(1D)] + [InlineData(1.4D)] + public void Offset_ShortHexagon_HandlesOverlappingCornerStrips(double distance) + { + Contour source = new(6); + Contour reference = new(6); + double expectedRadius = 1.5 - (distance / Math.Cos(Math.PI / 6)); + for (int i = 0; i < 6; i++) + { + double angle = i * Math.PI / 3; + Vertex direction = new(Math.Cos(angle), Math.Sin(angle)); + source.Add(direction * 1.5); + reference.Add(direction * expectedRadius); + } + + Polygon subject = [source]; + Polygon expected = expectedRadius > 0 ? [reference] : []; + Polygon actual = PolygonOffsetter.Offset(subject, -distance, FillRule.NonZero, new() { LineJoin = LineJoin.Miter }); + + AssertGeometry(nameof(this.Offset_ShortHexagon_HandlesOverlappingCornerStrips), $"Distance-{distance}", subject, actual, expected); + } + + /// + /// Checks irregular orthogonal areas against independently expanded source or complement cells. + /// + /// The fixed cell selection seed. + /// The signed distance. + [Theory] + [InlineData(0, 0.5D)] + [InlineData(0, -0.5D)] + [InlineData(0, 3D)] + [InlineData(0, -3D)] + [InlineData(17, 0.5D)] + [InlineData(17, -0.5D)] + [InlineData(17, 3D)] + [InlineData(17, -3D)] + [InlineData(42, 0.5D)] + [InlineData(42, -0.5D)] + [InlineData(42, 3D)] + [InlineData(42, -3D)] + public void Offset_RectangleUnions_MatchCellConstruction(int seed, double delta) + { + Random random = new(seed); + bool[,] occupied = new bool[5, 5]; + Polygon subject = []; + for (int y = 0; y < 5; y++) + { + for (int x = 0; x < 5; x++) + { + occupied[x, y] = random.Next(3) != 0; + if (occupied[x, y]) + { + subject.Add(Rectangle(x * 2, y * 2, (x + 1) * 2, (y + 1) * 2)); + } + } + } + + // Axis-aligned miter dilation distributes over a union of rectangles. Erosion is + // the complement of the dilated complement. The extra two cell rows on each side + // cover the largest tested distance of three units without truncating that construction. + Polygon expandedCells = []; + double distance = Math.Abs(delta); + for (int y = -2; y < 7; y++) + { + for (int x = -2; x < 7; x++) + { + bool filled = x >= 0 && x < 5 && y >= 0 && y < 5 && occupied[x, y]; + if (filled == (delta > 0)) + { + expandedCells.Add(Rectangle((x * 2) - distance, (y * 2) - distance, ((x + 1) * 2) + distance, ((y + 1) * 2) + distance)); + } + } + } + + Polygon expected = delta > 0 + ? PolygonClipper.Normalize(expandedCells, FillRule.NonZero) + : PolygonClipper.Difference(subject, expandedCells, FillRule.NonZero); + Polygon actual = PolygonOffsetter.Offset(subject, delta, FillRule.NonZero, new() { LineJoin = LineJoin.Miter }); + + AssertGeometry(nameof(this.Offset_RectangleUnions_MatchCellConstruction), $"Seed-{seed}_Delta-{delta}", subject, actual, expected); + } + + /// + /// Checks that a collapsed component cannot cut the retained bevel of another component. + /// + [Fact] + public void Offset_CollapsedComponent_DoesNotCutNeighbor() + { + Polygon subject = + [ + [new(-10, -10), new(10, -10), new(10, 0), new(0, 0), new(0, 10), new(-10, 10)], + [new(0.01, 0.01), new(0.03, 0.01), new(0.01, 0.03)] + ]; + Polygon expected = [[new(-9, -9), new(9, -9), new(9, -1), new(0, -1), new(-1, 0), new(-1, 9), new(-9, 9)]]; + Polygon actual = PolygonOffsetter.Offset(subject, -1, FillRule.NonZero, new() { LineJoin = LineJoin.Bevel }); + + AssertGeometry(nameof(this.Offset_CollapsedComponent_DoesNotCutNeighbor), string.Empty, subject, actual, expected); + } + + /// + /// Checks complete collapse of a densely sampled convex boundary. + /// + [Fact] + public void Offset_DenseConvexCollapse_ReturnsEmpty() + { + Contour contour = new(128); + for (int i = 0; i < 128; i++) + { + double angle = i * Math.PI * 2 / 128; + contour.Add(new(10 * Math.Cos(angle), 10 * Math.Sin(angle))); + } + + Polygon subject = [contour]; + Polygon actual = PolygonOffsetter.Offset(subject, -12, FillRule.NonZero, new() { LineJoin = LineJoin.Miter }); + AssertGeometry(nameof(this.Offset_DenseConvexCollapse_ReturnsEmpty), string.Empty, subject, actual, []); + } + + /// + /// Checks that bounding-box subtraction rounding cannot classify a surviving area as collapsed. + /// + [Fact] + public void Offset_BoundsRounding_DoesNotDropThinArea() + { + double left = -1D / 9_007_199_254_740_992D; + Polygon subject = [Rectangle(left, 0, 2, 4)]; + Polygon expected = [Rectangle(1 + left, 1, 1, 3)]; + Polygon actual = PolygonOffsetter.Offset(subject, -1, FillRule.NonZero, new() { LineJoin = LineJoin.Miter }); + + AssertGeometry(nameof(this.Offset_BoundsRounding_DoesNotDropThinArea), string.Empty, subject, actual, expected); + Assert.True(actual[0].GetBoundingBox().Max.X > actual[0].GetBoundingBox().Min.X); + } + + /// + /// Saves the comparison and checks both boundaries, contour count and output closure. + /// + /// The test method name. + /// The parameter details for the SVG file name. + /// The source polygon. + /// The offset output. + /// Independently constructed expected boundaries. + private static void AssertGeometry(string testName, string details, Polygon subject, Polygon actual, Polygon expected) + { + SvgTestOutput.SaveSvg(nameof(PolygonOffsetTests), testName, details, subject, [], actual, expected); + Assert.Equal(expected.Count, actual.Count); + if (expected.Count > 0) + { + Box2 bounds = expected.GetBoundingBox(); + double magnitude = Math.Max(Math.Max(Math.Abs(bounds.Min.X), Math.Abs(bounds.Min.Y)), Math.Max(Math.Abs(bounds.Max.X), Math.Abs(bounds.Max.Y))); + + // Unit roundoff is 2^-53. Allow 64 rounding units for offset normals and line intersections. + // This allowance scales with the coordinates; it does not hide a fixed-size geometric defect. + double tolerance = magnitude * (64D / 9_007_199_254_740_992D); + ApproximateDoubleComparer comparer = new(tolerance); + AssertBoundaryOn(actual, expected, comparer); + AssertBoundaryOn(expected, actual, comparer); + } + + Assert.All(actual, contour => + { + Assert.True(contour.IsClosed); + Assert.NotEqual(contour[0], contour[^1]); + Assert.Equal((contour.Depth & 1) == 0, contour.IsCounterClockwise()); + }); + } + + /// + /// Checks each edge endpoint and midpoint against the other polygon's boundary segments. + /// + /// The boundary to inspect. + /// The comparison boundary. + /// The coordinate comparer for the xUnit assertions. + private static void AssertBoundaryOn(Polygon first, Polygon second, ApproximateDoubleComparer comparer) + { + foreach (Contour contour in first) + { + for (int i = 0; i < contour.Count; i++) + { + for (int sample = 0; sample < 2; sample++) + { + Vertex point = sample == 0 ? contour[i] : (contour[i] + contour[(i + 1) % contour.Count]) * 0.5D; + double nearest = double.PositiveInfinity; + Vertex nearestPoint = default; + foreach (Contour reference in second) + { + for (int j = 0; j < reference.Count; j++) + { + Vertex closest = PolygonUtilities.ClosestPointOnSegment(point, reference[j], reference[(j + 1) % reference.Count]); + double distance = Vertex.DistanceSquared(point, closest); + if (distance < nearest) + { + nearest = distance; + nearestPoint = closest; + } + } + } + + Assert.Equal(point, nearestPoint, comparer); + } + } + } + } + + /// + /// Constructs a counterclockwise rectangle with implicit closure. + /// + /// The minimum X coordinate. + /// The minimum Y coordinate. + /// The maximum X coordinate. + /// The maximum Y coordinate. + /// The rectangle boundary. + private static Contour Rectangle(double left, double bottom, double right, double top) + => [new(left, bottom), new(right, bottom), new(right, top), new(left, top)]; +} diff --git a/tests/PolygonClipper.Tests/PolygonStrokerTests.cs b/tests/PolygonClipper.Tests/PolygonStrokerTests.cs index 83b5a09..1a5346f 100644 --- a/tests/PolygonClipper.Tests/PolygonStrokerTests.cs +++ b/tests/PolygonClipper.Tests/PolygonStrokerTests.cs @@ -14,6 +14,13 @@ public void Stroke_AxisAlignedMiter_PreservesThinInnerContour() double left = -1D / 9_007_199_254_740_992D; Contour source = [new(left, 0), new(2, 0), new(2, 4), new(left, 4), new(left, 0)]; Polygon actual = PolygonStroker.Stroke([source], 2, new() { LineJoin = LineJoin.Miter }); + SvgTestOutput.SaveSvg( + nameof(PolygonStrokerTests), + nameof(this.Stroke_AxisAlignedMiter_PreservesThinInnerContour), + string.Empty, + [source], + [], + actual); Assert.Equal(2, actual.Count); Contour inner = Assert.Single(actual, contour => contour.GetBoundingBox().Max.X - contour.GetBoundingBox().Min.X < 1); @@ -36,6 +43,13 @@ public void ProcessPath_ClosedSquare_ReturnsGeometry() ]; Polygon result = PolygonStroker.Stroke([square], width); + SvgTestOutput.SaveSvg( + nameof(PolygonStrokerTests), + nameof(this.ProcessPath_ClosedSquare_ReturnsGeometry), + string.Empty, + [square], + [], + result); Assert.True(result.Count > 0); Assert.True(result[0].Count >= 4); @@ -52,7 +66,16 @@ public void ProcessPath_DegenerateTwoPointPath_ReturnsPointCap() new(5, 5) ]; - Polygon result = PolygonStroker.Stroke([new Contour(points.Length) { points[0], points[1] }], width); + Polygon input = [new Contour(points.Length) { points[0], points[1] }]; + Polygon result = PolygonStroker.Stroke(input, width); + SvgTestOutput.SaveSvg( + nameof(PolygonStrokerTests), + nameof(this.ProcessPath_DegenerateTwoPointPath_ReturnsPointCap), + string.Empty, + input, + [], + result); + Assert.True(result.Count > 0); Contour contour = result[0]; @@ -72,6 +95,13 @@ public void ProcessPolygonAndClip_SimplePolygon_ReturnsNonEmptyResult() ]]; Polygon result = PolygonStroker.Stroke(input, width: 2D); + SvgTestOutput.SaveSvg( + nameof(PolygonStrokerTests), + nameof(this.ProcessPolygonAndClip_SimplePolygon_ReturnsNonEmptyResult), + string.Empty, + input, + [], + result); Assert.True(result.Count > 0); } @@ -106,6 +136,21 @@ public void Stroke_OpenPolylineWithThreeVertices_IsNotForcedClosed() Polygon openResult = PolygonStroker.Stroke(open, width, options); Polygon closedResult = PolygonStroker.Stroke(closed, width, options); + SvgTestOutput.SaveSvg( + nameof(PolygonStrokerTests), + nameof(this.Stroke_OpenPolylineWithThreeVertices_IsNotForcedClosed), + "IsClosed-False", + open, + [], + openResult); + + SvgTestOutput.SaveSvg( + nameof(PolygonStrokerTests), + nameof(this.Stroke_OpenPolylineWithThreeVertices_IsNotForcedClosed), + "IsClosed-True", + closed, + [], + closedResult); AssertPolygonIsValid(openResult); AssertPolygonIsValid(closedResult); @@ -132,8 +177,23 @@ public void Stroke_ThreePointSource_ClosureSelectsFinalSegment(bool normalizeOut StrokeOptions options = new() { LineJoin = LineJoin.Miter, NormalizeOutput = normalizeOutput }; Polygon open = PolygonStroker.Stroke([source], 2, options); + SvgTestOutput.SaveSvg( + nameof(PolygonStrokerTests), + nameof(this.Stroke_ThreePointSource_ClosureSelectsFinalSegment), + $"NormalizeOutput-{normalizeOutput}_IsClosed-False", + [source], + [], + open); + source.IsClosed = true; Polygon closed = PolygonStroker.Stroke([source], 2, options); + SvgTestOutput.SaveSvg( + nameof(PolygonStrokerTests), + nameof(this.Stroke_ThreePointSource_ClosureSelectsFinalSegment), + $"NormalizeOutput-{normalizeOutput}_IsClosed-True", + [source], + [], + closed); // The diagonal belongs only to the closed source's final-to-first segment. Assert.Equal(Containment.Outside, ClassifyPoint(open, new Vertex(5, 5), 1E-10)); @@ -168,10 +228,25 @@ public void Stroke_OpenEndpoints_DoNotSelectClosure(double endY, double width) StrokeOptions options = new() { LineJoin = LineJoin.Miter, LineCap = LineCap.Butt, NormalizeOutput = true }; Polygon open = PolygonStroker.Stroke([source], width, options); + SvgTestOutput.SaveSvg( + nameof(PolygonStrokerTests), + nameof(this.Stroke_OpenEndpoints_DoNotSelectClosure), + FormattableString.Invariant($"EndY-{endY}_Width-{width}_IsClosed-False"), + [source], + [], + open); + Assert.False(source.IsClosed); Assert.Equal(5, source.Count); source.IsClosed = true; Polygon closed = PolygonStroker.Stroke([source], width, options); + SvgTestOutput.SaveSvg( + nameof(PolygonStrokerTests), + nameof(this.Stroke_OpenEndpoints_DoNotSelectClosure), + FormattableString.Invariant($"EndY-{endY}_Width-{width}_IsClosed-True"), + [source], + [], + closed); // A miter joins the closed bottom-left corner. The two butt caps leave // this point outside the open stroke, even when the endpoints coincide. @@ -194,9 +269,25 @@ public void Stroke_ClosedDuplicateEndpoint_DoesNotChangeGeometry(bool normalizeO Contour source = [new Vertex(0, 0), new Vertex(10, 0), new Vertex(10, 10), new Vertex(0, 10)]; StrokeOptions options = new() { LineJoin = LineJoin.Miter, NormalizeOutput = normalizeOutput }; Polygon implicitClosure = PolygonStroker.Stroke([source], 2, options); + SvgTestOutput.SaveSvg( + nameof(PolygonStrokerTests), + nameof(this.Stroke_ClosedDuplicateEndpoint_DoesNotChangeGeometry), + $"NormalizeOutput-{normalizeOutput}_RepeatedEndpoint-False", + [source], + [], + implicitClosure); + source.Add(source[0]); Polygon explicitClosure = PolygonStroker.Stroke([source], 2, options); + SvgTestOutput.SaveSvg( + nameof(PolygonStrokerTests), + nameof(this.Stroke_ClosedDuplicateEndpoint_DoesNotChangeGeometry), + $"NormalizeOutput-{normalizeOutput}_RepeatedEndpoint-True", + [source], + [], + explicitClosure, + implicitClosure); AssertSameStroke(implicitClosure, explicitClosure); AssertPolygonIsValid(implicitClosure); @@ -216,6 +307,13 @@ public void Stroke_MixedClosure_ResolvesCombinedArea() StrokeOptions options = new() { LineJoin = LineJoin.Miter, NormalizeOutput = true }; Polygon result = PolygonStroker.Stroke([square, segment], 2, options); + SvgTestOutput.SaveSvg( + nameof(PolygonStrokerTests), + nameof(this.Stroke_MixedClosure_ResolvesCombinedArea), + string.Empty, + [square, segment], + [], + result); // The square band has area 12*12 - 8*8 = 80. The segment adds 20*2 = 40, // with two 2*2 overlaps. Their union therefore has area 112. @@ -244,6 +342,21 @@ public void Stroke_BooleanOutput_RequiresNoClosureConversion() Polygon stroke = PolygonStroker.Stroke(filled, 2, new StrokeOptions { LineJoin = LineJoin.Miter }); Polygon resolved = PolygonClipper.Normalize(stroke, FillRule.Positive); + SvgTestOutput.SaveSvg( + nameof(PolygonStrokerTests), + nameof(this.Stroke_BooleanOutput_RequiresNoClosureConversion), + "Output-Raw", + filled, + [], + stroke); + + SvgTestOutput.SaveSvg( + nameof(PolygonStrokerTests), + nameof(this.Stroke_BooleanOutput_RequiresNoClosureConversion), + "Output-Resolved", + filled, + [], + resolved); AssertPolygonIsValid(filled); AssertPolygonIsValid(stroke); @@ -265,6 +378,31 @@ public void Stroke_DefaultExplicitAndInstanceOptions_Agree() Polygon defaults = PolygonStroker.Stroke(source, 2); Polygon explicitOptions = PolygonStroker.Stroke(source, 2, options); Polygon instance = stroker.Stroke(source); + SvgTestOutput.SaveSvg( + nameof(PolygonStrokerTests), + nameof(this.Stroke_DefaultExplicitAndInstanceOptions_Agree), + "Options-Default", + source, + [], + defaults); + + SvgTestOutput.SaveSvg( + nameof(PolygonStrokerTests), + nameof(this.Stroke_DefaultExplicitAndInstanceOptions_Agree), + "Options-Explicit", + source, + [], + explicitOptions, + defaults); + + SvgTestOutput.SaveSvg( + nameof(PolygonStrokerTests), + nameof(this.Stroke_DefaultExplicitAndInstanceOptions_Agree), + "Options-Instance", + source, + [], + instance, + defaults); AssertSameStroke(defaults, explicitOptions); AssertSameStroke(defaults, instance); @@ -287,9 +425,24 @@ public void Stroke_OutputCleanup_PreservesNonZeroArea(double width, bool isClose source.IsClosed = isClosed; StrokeOptions options = new() { LineJoin = LineJoin.Miter }; Polygon raw = PolygonStroker.Stroke([source], width, options); + SvgTestOutput.SaveSvg( + nameof(PolygonStrokerTests), + nameof(this.Stroke_OutputCleanup_PreservesNonZeroArea), + FormattableString.Invariant($"Width-{width}_IsClosed-{isClosed}_NormalizeOutput-False"), + [source], + [], + raw); + options.NormalizeOutput = true; Polygon cleaned = PolygonStroker.Stroke([source], width, options); + SvgTestOutput.SaveSvg( + nameof(PolygonStrokerTests), + nameof(this.Stroke_OutputCleanup_PreservesNonZeroArea), + FormattableString.Invariant($"Width-{width}_IsClosed-{isClosed}_NormalizeOutput-True"), + [source], + [], + cleaned); double area = 0; foreach (Contour contour in cleaned) @@ -317,6 +470,7 @@ public void Stroke_OutputCleanup_PreservesNonZeroArea(double width, bool isClose public void Stroke_NullOptions_ThrowsArgumentNullException() { Assert.Throws("options", () => PolygonStroker.Stroke([], 2, null!)); + Assert.Throws("options", () => new PolygonStroker(null!)); } /// @@ -337,6 +491,13 @@ public void Stroke_TwoEqualVertices_PreservesPointCap(bool isClosed, LineCap cap source.IsClosed = isClosed; Polygon result = PolygonStroker.Stroke([source], 4, new StrokeOptions { LineCap = cap }); + SvgTestOutput.SaveSvg( + nameof(PolygonStrokerTests), + nameof(this.Stroke_TwoEqualVertices_PreservesPointCap), + $"IsClosed-{isClosed}_Cap-{cap}", + [source], + [], + result); Contour footprint = Assert.Single(result); Assert.Equal(isClosed, source.IsClosed); @@ -371,6 +532,13 @@ public void Stroke_TwoDistinctVertices_PreservesSegmentCaps(bool isClosed) source.IsClosed = isClosed; Polygon result = PolygonStroker.Stroke([source], 2, new StrokeOptions { LineCap = LineCap.Square }); + SvgTestOutput.SaveSvg( + nameof(PolygonStrokerTests), + nameof(this.Stroke_TwoDistinctVertices_PreservesSegmentCaps), + $"IsClosed-{isClosed}", + [source], + [], + result); Assert.Single(result); Assert.Equal(new Vertex(-1, -1), result.GetBoundingBox().Min); @@ -389,10 +557,30 @@ public void Stroke_TwoDistinctVertices_PreservesSegmentCaps(bool isClosed) public void Stroke_FewerThanTwoVertices_ReturnsEmpty(bool isClosed) { Contour source = new() { IsClosed = isClosed }; - Assert.Empty(PolygonStroker.Stroke([source], 2)); + Polygon empty = PolygonStroker.Stroke([source], 2); + SvgTestOutput.SaveSvg( + nameof(PolygonStrokerTests), + nameof(this.Stroke_FewerThanTwoVertices_ReturnsEmpty), + $"IsClosed-{isClosed}_VertexCount-0", + [source], + [], + empty, + []); + + Assert.Empty(empty); source.Add(new Vertex(5, 5)); - Assert.Empty(PolygonStroker.Stroke([source], 2)); + Polygon single = PolygonStroker.Stroke([source], 2); + SvgTestOutput.SaveSvg( + nameof(PolygonStrokerTests), + nameof(this.Stroke_FewerThanTwoVertices_ReturnsEmpty), + $"IsClosed-{isClosed}_VertexCount-1", + [source], + [], + single, + []); + + Assert.Empty(single); Assert.Equal(isClosed, source.IsClosed); } @@ -426,6 +614,14 @@ public void ProcessPolygonAndClip_FoldBackOpenPath_ProducesValidStroke() Polygon input = [inputContour]; Polygon actual = PolygonStroker.Stroke(input, width, options); + SvgTestOutput.SaveSvg( + nameof(PolygonStrokerTests), + nameof(this.ProcessPolygonAndClip_FoldBackOpenPath_ProducesValidStroke), + string.Empty, + input, + [], + actual); + AssertPolygonIsValid(actual); AssertStrokeCoversInputCenterline(input, actual, samplesPerSegment: 3); } @@ -445,6 +641,14 @@ public void ProcessPolygonAndClip_FigureNinePath_ProducesValidStroke() Polygon input = [inputContour]; Polygon actual = PolygonStroker.Stroke(input, width, options); + SvgTestOutput.SaveSvg( + nameof(PolygonStrokerTests), + nameof(this.ProcessPolygonAndClip_FigureNinePath_ProducesValidStroke), + string.Empty, + input, + [], + actual); + AssertPolygonIsValid(actual); AssertStrokeCoversInputCenterline(input, actual, samplesPerSegment: 3); } @@ -778,6 +982,14 @@ public void ProcessPolygonAndClip_CompoundCircleGlyphPath_ProducesValidStroke() Polygon actual = PolygonStroker.Stroke(input, width); + SvgTestOutput.SaveSvg( + nameof(PolygonStrokerTests), + nameof(this.ProcessPolygonAndClip_CompoundCircleGlyphPath_ProducesValidStroke), + string.Empty, + input, + [], + actual); + AssertPolygonIsValid(actual); AssertStrokeCoversInputCenterline(input, actual, samplesPerSegment: 4); AssertImplicitSeamsAreClosed(input, actual, width); diff --git a/tests/PolygonClipper.Tests/SvgTestOutput.cs b/tests/PolygonClipper.Tests/SvgTestOutput.cs index 8767ed3..0de293c 100644 --- a/tests/PolygonClipper.Tests/SvgTestOutput.cs +++ b/tests/PolygonClipper.Tests/SvgTestOutput.cs @@ -119,6 +119,51 @@ private static string SaveSvgCore(string outputPath, Polygon subject, Polygon cl AddGeometry(AddPanel(root, 2, "expected", "Expected"), expected, "#7e22ce", origin, scale, extent); } + // Auto-fit preserves relative size within a file but changes pixels per unit between files. + // Show a source-unit scale below the input geometry so that difference stays visible. + const double requestedBarWidth = 60; + int drawingWidth = PanelSize - (2 * Padding); + double barUnits = Math.Max(double.Epsilon, scale * (extent * (requestedBarWidth / drawingWidth))); + + // A subnormal source distance can round to zero. Use at least one representable unit, + // then project that actual distance so the bar and its label still describe the same scale. + double barWidth = ((barUnits / scale) / extent) * drawingWidth; + double barEnd = Padding + barWidth; + int barY = PanelSize + TitleHeight - (Padding / 2); + root.Add(new XElement( + Svg + "g", + new XAttribute("id", "scale"), + new XAttribute("stroke", "#475569"), + new XElement( + Svg + "line", + new XAttribute("x1", Padding), + new XAttribute("x2", barEnd), + new XAttribute("y1", barY), + new XAttribute("y2", barY), + new XAttribute("data-units", barUnits)), + new XElement( + Svg + "line", + new XAttribute("x1", Padding), + new XAttribute("x2", Padding), + new XAttribute("y1", barY - 3), + new XAttribute("y2", barY + 3)), + new XElement( + Svg + "line", + new XAttribute("x1", barEnd), + new XAttribute("x2", barEnd), + new XAttribute("y1", barY - 3), + new XAttribute("y2", barY + 3)), + new XElement( + Svg + "text", + new XAttribute("x", barEnd + 10), + new XAttribute("y", barY), + new XAttribute("font-family", "sans-serif"), + new XAttribute("font-size", 11), + new XAttribute("dominant-baseline", "middle"), + new XAttribute("stroke", "none"), + new XAttribute("fill", "#475569"), + FormattableString.Invariant($"{barUnits:G6} units")))); + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); new XDocument(root).Save(outputPath); return outputPath; @@ -186,8 +231,15 @@ private static void AddGeometry(XElement group, Polygon polygon, string color, V StringBuilder path = new(); StringBuilder source = new(); + Vertex first = contour[0]; + bool singlePoint = true; + foreach (Vertex vertex in contour) { + // Repeated coincident vertices still describe one point. A zero-length + // SVG path has no visible outline, so it needs the same point marker. + singlePoint = singlePoint && vertex == first; + Vertex point = Project(vertex, origin, scale, extent); string command = path.Length == 0 ? "M " : " L "; path.Append(command).Append(point.X.ToString("R", CultureInfo.InvariantCulture)) @@ -219,7 +271,7 @@ private static void AddGeometry(XElement group, Polygon polygon, string color, V new XElement(Svg + "title", $"Contour {i}. {(contour.IsClosed ? "Closed" : "Open")}. Depth {contour.Depth}.")); group.Add(outline); - if (contour.Count == 1) + if (singlePoint) { // Center the square on the point and match the contour line thickness. Vertex point = Project(contour[0], origin, scale, extent); diff --git a/tests/PolygonClipper.Tests/SvgTestOutputTests.cs b/tests/PolygonClipper.Tests/SvgTestOutputTests.cs index 1f22a10..7643266 100644 --- a/tests/PolygonClipper.Tests/SvgTestOutputTests.cs +++ b/tests/PolygonClipper.Tests/SvgTestOutputTests.cs @@ -112,6 +112,14 @@ public void SaveSvg_PreservesHolesAndIslands(double scale) .Single(element => (string)element.Attribute("class") == "contour" && (int)element.Attribute("data-contour")! == 0).Attribute("d")!; Assert.StartsWith("M 20 380", expectedExterior); Assert.All(root.Descendants(Svg + "svg"), element => Assert.Equal("0 0 400 400", (string)element.Attribute("viewBox")!)); + + // A ten-unit exterior occupies 360 pixels. A 60-pixel scale bar must therefore + // represent 5/3 source units at every tested coordinate scale. + XElement scaleBar = root.Elements().Single(element => (string)element.Attribute("id") == "scale"); + XElement bar = scaleBar.Elements(Svg + "line").Single(element => element.Attribute("data-units") is not null); + Assert.Equal(60D, (double)bar.Attribute("x2")! - (double)bar.Attribute("x1")!, 10); + Assert.Equal(5D / 3, (double)bar.Attribute("data-units")! / scale, 12); + Assert.EndsWith(" units", scaleBar.Element(Svg + "text")!.Value); Assert.Equal(before, actual.ToDebugString()); } @@ -158,6 +166,45 @@ public void SaveSvg_PreservesPointResults() } } + /// + /// Checks that coincident source vertices have a visible point marker. + /// + /// The source closure state. + [Theory] + [InlineData(false)] + [InlineData(true)] + public void SaveSvg_CoincidentStrokeVertices_HavePointMarker(bool isClosed) + { + Contour contour = [new(5, 5), new(5, 5)]; + contour.IsClosed = isClosed; + Polygon subject = [contour]; + Polygon actual = PolygonStroker.Stroke(subject, 4, new() { LineCap = LineCap.Round }); + string before = subject.ToDebugString(); + string path = SvgTestOutput.SaveSvg( + nameof(SvgTestOutputTests), + nameof(this.SaveSvg_CoincidentStrokeVertices_HavePointMarker), + $"IsClosed-{isClosed}", + subject, + [], + actual); + + XElement root = XDocument.Load(path).Root!; + XElement input = root.Elements().Single(element => (string)element.Attribute("id") == "inputs"); + XElement outline = Assert.Single(input.Descendants(Svg + "path")); + XElement marker = Assert.Single(input.Descendants(Svg + "rect"), element => (string)element.Attribute("class") == "point"); + double lineWidth = (double)outline.Attribute("stroke-width")!; + string[] projected = ((string)outline.Attribute("d")!).Split(' '); + + Assert.Equal(lineWidth, (double)marker.Attribute("width")!); + Assert.Equal(lineWidth, (double)marker.Attribute("height")!); + Assert.Equal(double.Parse(projected[1], CultureInfo.InvariantCulture), (double)marker.Attribute("x")! + (lineWidth / 2), 10); + Assert.Equal(double.Parse(projected[2], CultureInfo.InvariantCulture), (double)marker.Attribute("y")! + (lineWidth / 2), 10); + Assert.Equal((string)outline.Attribute("stroke")!, (string)marker.Attribute("fill")!); + Assert.Equal(isClosed ? "M 5 5 L 5 5 Z" : "M 5 5 L 5 5", (string)outline.Attribute("data-source-d")!); + Assert.Equal(isClosed, (bool)outline.Attribute("data-closed")!); + Assert.Equal(before, subject.ToDebugString()); + } + /// /// Checks open output intervals against available analytic expected geometry. /// From 6faa3c887866448fa11871b7ee49f92c2a19b17d Mon Sep 17 00:00:00 2001 From: James Jackson-South Date: Mon, 2 Nov 2026 11:27:03 +1000 Subject: [PATCH 20/24] Optimize sweep queue comparisons and scratch buffer allocations --- src/PolygonClipper/Buffer{T}.cs | 28 ++- src/PolygonClipper/ByteMemoryManager{T}.cs | 49 ---- src/PolygonClipper/PolygonClipper.cs | 4 +- src/PolygonClipper/QueueEntryComparer.cs | 21 ++ tests/PolygonClipper.Benchmarks/Benches.cs | 84 ++++--- .../BenchmarkGeometry.cs | 34 +++ .../NormalizationBenches.cs | 128 +++------- .../OffsetBenches.cs | 140 ++++++----- .../OpenClippingBenches.cs | 106 +++------ .../StarBooleanBenches.cs | 223 +++++++++++------- .../StrokeBenches.cs | 89 ++++--- tests/PolygonClipper.Tests/BufferTests.cs | 83 +++++++ .../QueueEntryComparerTests.cs | 80 +++++++ 13 files changed, 600 insertions(+), 469 deletions(-) delete mode 100644 src/PolygonClipper/ByteMemoryManager{T}.cs create mode 100644 src/PolygonClipper/QueueEntryComparer.cs create mode 100644 tests/PolygonClipper.Benchmarks/BenchmarkGeometry.cs create mode 100644 tests/PolygonClipper.Tests/BufferTests.cs create mode 100644 tests/PolygonClipper.Tests/QueueEntryComparerTests.cs diff --git a/src/PolygonClipper/Buffer{T}.cs b/src/PolygonClipper/Buffer{T}.cs index b289093..2f7011c 100644 --- a/src/PolygonClipper/Buffer{T}.cs +++ b/src/PolygonClipper/Buffer{T}.cs @@ -3,38 +3,43 @@ using System.Buffers; using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; namespace SixLabors.PolygonClipper; /// -/// An disposable buffer that is backed by an array pool. +/// A disposable buffer that is backed by an array pool. /// /// The type of buffer element. internal ref struct Buffer where T : unmanaged { - private int length; private readonly byte[] buffer; private readonly Span span; private bool isDisposed; + /// + /// Initializes a new instance of the struct. + /// + /// The number of elements to rent. Their contents are not initialized. public Buffer(int length) { Guard.MustBeGreaterThanOrEqualTo(length, 0, nameof(length)); int itemSizeBytes = Unsafe.SizeOf(); int bufferSizeInBytes = length * itemSizeBytes; this.buffer = ArrayPool.Shared.Rent(bufferSizeInBytes); - this.length = length; - using ByteMemoryManager manager = new(this.buffer); - this.Memory = manager.Memory[..this.length]; - this.span = this.Memory.Span; + // The buffer owns the rented bytes until Dispose. A direct span cast + // keeps this lifetime without allocating a memory manager for each rental. + this.span = MemoryMarshal.Cast(this.buffer.AsSpan())[..length]; this.isDisposed = false; } - public Memory Memory { get; } - + /// + /// Gets the requested elements from the rented array. + /// + /// The elements. Use them only until the buffer is disposed. public readonly Span GetSpan() { if (this.buffer is null) @@ -45,6 +50,9 @@ public readonly Span GetSpan() return this.span; } + /// + /// Returns the rented array to the pool. Further calls have no effect. + /// public void Dispose() { if (this.isDisposed) @@ -53,10 +61,12 @@ public void Dispose() } ArrayPool.Shared.Return(this.buffer); - this.length = 0; this.isDisposed = true; } + /// + /// Reports access to a buffer without a rented array. + /// [MethodImpl(MethodImplOptions.NoInlining)] private static void ThrowObjectDisposedException() => throw new ObjectDisposedException("Buffer"); } diff --git a/src/PolygonClipper/ByteMemoryManager{T}.cs b/src/PolygonClipper/ByteMemoryManager{T}.cs deleted file mode 100644 index 27a2981..0000000 --- a/src/PolygonClipper/ByteMemoryManager{T}.cs +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (c) Six Labors. -// Licensed under the Six Labors Split License. - -using System.Buffers; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -namespace SixLabors.PolygonClipper; - -/// -/// A custom that can wrap of instances -/// and cast them to be for any arbitrary unmanaged value type. -/// -/// The value type to use when casting the wrapped instance. -internal sealed class ByteMemoryManager : MemoryManager - where T : unmanaged -{ - /// - /// The wrapped of instance. - /// - private readonly Memory memory; - - /// - /// Initializes a new instance of the class. - /// - /// The of instance to wrap. - public ByteMemoryManager(Memory memory) => this.memory = memory; - - /// - protected override void Dispose(bool disposing) - { - } - - /// - public override Span GetSpan() => MemoryMarshal.Cast(this.memory.Span); - - /// - public override MemoryHandle Pin(int elementIndex = 0) - - // We need to adjust the offset into the wrapped byte segment, - // as the input index refers to the target-cast memory of T. - // We just have to shift this index by the byte size of T. - => this.memory[(elementIndex * Unsafe.SizeOf())..].Pin(); - - /// - public override void Unpin() - { - } -} diff --git a/src/PolygonClipper/PolygonClipper.cs b/src/PolygonClipper/PolygonClipper.cs index f34eedc..1d3d623 100644 --- a/src/PolygonClipper/PolygonClipper.cs +++ b/src/PolygonClipper/PolygonClipper.cs @@ -54,7 +54,7 @@ public class PolygonClipper private readonly StatusLine statusLine = new(); private readonly List eventStorage = []; - private readonly StablePriorityQueue events; + private readonly StablePriorityQueue events; private readonly SweepEventPoolList segments = []; private readonly SweepEventPoolList outgoing = []; private readonly SweepEventPoolList bundled = []; @@ -103,7 +103,7 @@ public PolygonClipper(Polygon subject, Polygon clip, BooleanOperation operation, /// Initializes a new instance of the class for pooled execution. /// private PolygonClipper() - => this.events = new(this.comparer, this.eventStorage); + => this.events = new(default(QueueEntryComparer), this.eventStorage); /// /// Specifies the form of returned contours. diff --git a/src/PolygonClipper/QueueEntryComparer.cs b/src/PolygonClipper/QueueEntryComparer.cs new file mode 100644 index 0000000..387b4ba --- /dev/null +++ b/src/PolygonClipper/QueueEntryComparer.cs @@ -0,0 +1,21 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +using System.Runtime.CompilerServices; + +namespace SixLabors.PolygonClipper; + +/// +/// Compares queued endpoints with the shared sweep event order. +/// +internal readonly struct QueueEntryComparer : IComparer +{ + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int Compare(QueueEntry x, QueueEntry y) + { + // A value-type comparer lets the JIT inline heap comparisons. + // Keep the ordering in SweepEventComparer so all callers use the same rules. + return SweepEventComparer.Instance.Compare(x, y); + } +} diff --git a/tests/PolygonClipper.Benchmarks/Benches.cs b/tests/PolygonClipper.Benchmarks/Benches.cs index 4a37425..9bf03e6 100644 --- a/tests/PolygonClipper.Benchmarks/Benches.cs +++ b/tests/PolygonClipper.Benchmarks/Benches.cs @@ -18,17 +18,25 @@ .NET SDK 11.0.100-preview.7.26381.103 Job=ShortRun IterationCount=3 LaunchCount=1 WarmupCount=3 -| Method | File | Mean | Error | StdDev | Op/s | Gen0 | Gen1 | Gen2 | Allocated | -|---------------------- |--------------------- |--------------:|--------------:|------------:|-----------:|---------:|---------:|---------:|----------:| -| PolygonClipperEvenOdd | asia.geojson | 11,200.902 us | 2,124.6733 us | 116.4605 us | 89.28 | 15.6250 | - | - | 463688 B | -| PolygonClipperNonZero | asia.geojson | 11,388.093 us | 7,892.3194 us | 432.6047 us | 87.81 | 15.6250 | - | - | 463688 B | -| Clipper2Union | asia.geojson | 14,425.834 us | 7,891.2400 us | 432.5455 us | 69.32 | 468.7500 | 437.5000 | 125.0000 | 6613210 B | -| PolygonClipperEvenOdd | hole_hole.geojson | 5.639 us | 0.6195 us | 0.0340 us | 177,347.74 | 0.0916 | - | - | 1632 B | -| PolygonClipperNonZero | hole_hole.geojson | 5.105 us | 4.3337 us | 0.2375 us | 195,880.72 | 0.0458 | - | - | 872 B | -| Clipper2Union | hole_hole.geojson | 2.775 us | 1.8953 us | 0.1039 us | 360,372.84 | 0.5951 | 0.0114 | - | 9992 B | -| PolygonClipperEvenOdd | state(...)ojson [21] | 738.178 us | 115.4451 us | 6.3279 us | 1,354.69 | - | - | - | 16136 B | -| PolygonClipperNonZero | state(...)ojson [21] | 777.143 us | 449.2819 us | 24.6267 us | 1,286.76 | - | - | - | 16136 B | -| Clipper2Union | state(...)ojson [21] | 331.071 us | 326.0528 us | 17.8721 us | 3,020.50 | 20.5078 | 9.7656 | - | 348984 B | +| Method | File | FillRule | Mean | Error | StdDev | Op/s | Ratio | RatioSD | Gen0 | Gen1 | Gen2 | Allocated | Alloc Ratio | +|-------------- |--------------------- |--------- |--------------:|---------------:|------------:|-----------:|------:|--------:|---------:|---------:|--------:|----------:|------------:| +| Union | asia.geojson | EvenOdd | 10,873.490 us | 2,805.9234 us | 153.8021 us | 91.97 | 0.69 | 0.03 | 15.6250 | - | - | 463688 B | 0.07 | +| Clipper2Union | asia.geojson | EvenOdd | 15,826.802 us | 13,961.0760 us | 765.2537 us | 63.18 | 1.00 | 0.06 | 437.5000 | 406.2500 | 93.7500 | 6613050 B | 1.00 | +| | | | | | | | | | | | | | | +| Union | asia.geojson | NonZero | 11,579.924 us | 8,157.2822 us | 447.1282 us | 86.36 | 0.78 | 0.04 | 15.6250 | - | - | 463688 B | 0.07 | +| Clipper2Union | asia.geojson | NonZero | 14,908.794 us | 11,245.5674 us | 616.4075 us | 67.07 | 1.00 | 0.05 | 437.5000 | 406.2500 | 93.7500 | 6613050 B | 1.00 | +| | | | | | | | | | | | | | | +| Union | hole_hole.geojson | EvenOdd | 5.475 us | 0.3199 us | 0.0175 us | 182,655.67 | 2.18 | 0.02 | 0.0916 | - | - | 1632 B | 0.16 | +| Clipper2Union | hole_hole.geojson | EvenOdd | 2.508 us | 0.4731 us | 0.0259 us | 398,689.33 | 1.00 | 0.01 | 0.5951 | 0.0114 | - | 9992 B | 1.00 | +| | | | | | | | | | | | | | | +| Union | hole_hole.geojson | NonZero | 4.839 us | 0.5636 us | 0.0309 us | 206,639.50 | 2.44 | 0.03 | 0.0458 | - | - | 872 B | 0.12 | +| Clipper2Union | hole_hole.geojson | NonZero | 1.980 us | 0.4235 us | 0.0232 us | 505,151.22 | 1.00 | 0.01 | 0.4463 | 0.0076 | - | 7512 B | 1.00 | +| | | | | | | | | | | | | | | +| Union | state(...)ojson [21] | EvenOdd | 733.801 us | 252.2293 us | 13.8255 us | 1,362.77 | 2.32 | 0.04 | - | - | - | 16136 B | 0.05 | +| Clipper2Union | state(...)ojson [21] | EvenOdd | 315.624 us | 36.5730 us | 2.0047 us | 3,168.33 | 1.00 | 0.01 | 20.5078 | 6.8359 | - | 348984 B | 1.00 | +| | | | | | | | | | | | | | | +| Union | state(...)ojson [21] | NonZero | 737.601 us | 70.9301 us | 3.8879 us | 1,355.75 | 2.36 | 0.07 | - | - | - | 16136 B | 0.05 | +| Clipper2Union | state(...)ojson [21] | NonZero | 312.442 us | 182.0525 us | 9.9789 us | 3,200.59 | 1.00 | 0.04 | 20.5078 | 6.8359 | - | 348984 B | 1.00 | */ /// @@ -44,9 +52,21 @@ public class Benches private PathsD clipperClipping = null!; private const int ClipperPrecision = 6; + /// + /// Gets or sets the input geometry file. + /// [Params("hole_hole.geojson", "states_source.geojson", "asia.geojson")] public string File { get; set; } + /// + /// Gets or sets the fill rule used by both engines. + /// + [Params(FillRule.EvenOdd, FillRule.NonZero)] + public FillRule FillRule { get; set; } + + /// + /// Loads the input polygons for both engines. + /// [GlobalSetup] public void Setup() { @@ -55,26 +75,23 @@ public void Setup() this.subject = subject; this.clipping = clipping; - this.clipperSubject = BuildClipperPaths(subject); - this.clipperClipping = BuildClipperPaths(clipping); + this.clipperSubject = BenchmarkGeometry.ToPaths(subject); + this.clipperClipping = BenchmarkGeometry.ToPaths(clipping); } /// - /// Measures even-odd union on the raw input contours. + /// Unions the source polygons with the selected fill rule. /// - /// The clipped geometry. + /// The resolved polygon. [Benchmark] - public Polygon PolygonClipperEvenOdd() => SixLabors.PolygonClipper.PolygonClipper.Union(this.subject, this.clipping, FillRule.EvenOdd); + public Polygon Union() => PolygonClipper.Union(this.subject, this.clipping, this.FillRule); /// - /// Measures non-zero clipping without a separate normalization operation. + /// Unions the same polygons and fill rule with Clipper2. /// - /// The clipped geometry. - [Benchmark] - public Polygon PolygonClipperNonZero() => SixLabors.PolygonClipper.PolygonClipper.Union(this.subject, this.clipping, FillRule.NonZero); - - [Benchmark] - public PolyTreeD Clipper2Union() + /// The resolved contour tree. + [Benchmark(Baseline = true)] + public object Clipper2Union() { ClipperD clipper = new(ClipperPrecision) { @@ -85,26 +102,7 @@ public PolyTreeD Clipper2Union() clipper.AddSubject(this.clipperSubject); clipper.AddClip(this.clipperClipping); PolyTreeD solution = []; - clipper.Execute(ClipType.Union, Clipper2Lib.FillRule.EvenOdd, solution); + clipper.Execute(ClipType.Union, (Clipper2Lib.FillRule)this.FillRule, solution); return solution; } - - private static PathsD BuildClipperPaths(Polygon polygon) - { - PathsD paths = new(polygon.Count); - for (int i = 0; i < polygon.Count; i++) - { - Contour contour = polygon[i]; - PathD path = new(contour.Count); - for (int j = 0; j < contour.Count; j++) - { - Vertex vertex = contour[j]; - path.Add(new PointD(vertex.X, vertex.Y)); - } - - paths.Add(path); - } - - return paths; - } } diff --git a/tests/PolygonClipper.Benchmarks/BenchmarkGeometry.cs b/tests/PolygonClipper.Benchmarks/BenchmarkGeometry.cs new file mode 100644 index 0000000..6c479ed --- /dev/null +++ b/tests/PolygonClipper.Benchmarks/BenchmarkGeometry.cs @@ -0,0 +1,34 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +using Clipper2Lib; + +namespace SixLabors.PolygonClipper.Benchmarks; + +/// +/// Converts closed benchmark geometry to Clipper2 paths. +/// +internal static class BenchmarkGeometry +{ + /// + /// Copies contour vertices without changing their direction or closure. + /// + /// The closed source or result contours. + /// The matching Clipper2 paths. + public static PathsD ToPaths(Polygon polygon) + { + PathsD paths = new(polygon.Count); + foreach (Contour contour in polygon) + { + PathD path = new(contour.Count); + foreach (Vertex vertex in contour) + { + path.Add(new PointD(vertex.X, vertex.Y)); + } + + paths.Add(path); + } + + return paths; + } +} diff --git a/tests/PolygonClipper.Benchmarks/NormalizationBenches.cs b/tests/PolygonClipper.Benchmarks/NormalizationBenches.cs index d50c37d..d9e5654 100644 --- a/tests/PolygonClipper.Benchmarks/NormalizationBenches.cs +++ b/tests/PolygonClipper.Benchmarks/NormalizationBenches.cs @@ -16,16 +16,16 @@ .NET SDK 11.0.100-preview.7.26381.103 Job=ShortRun IterationCount=3 LaunchCount=1 WarmupCount=3 -| Method | VertexCount | Mean | Error | StdDev | Op/s | Ratio | RatioSD | Gen0 | Gen1 | Gen2 | Allocated | Alloc Ratio | -|-------------- |------------ |-------------:|------------:|------------:|----------:|------:|--------:|----------:|----------:|----------:|------------:|------------:| -| Normalize | 101 | 1,828.4 us | 229.6 us | 12.58 us | 546.932 | 3.64 | 0.08 | - | - | - | 3.52 KB | 0.02 | -| Clipper2Union | 101 | 502.5 us | 223.6 us | 12.26 us | 1,989.877 | 1.00 | 0.03 | 12.2070 | 3.9063 | - | 205.76 KB | 1.00 | -| | | | | | | | | | | | | | -| Normalize | 301 | 19,279.5 us | 6,815.6 us | 373.58 us | 51.869 | 3.20 | 0.06 | - | - | - | 10.57 KB | 0.005 | -| Clipper2Union | 301 | 6,027.2 us | 676.2 us | 37.06 us | 165.916 | 1.00 | 0.01 | 492.1875 | 492.1875 | 492.1875 | 2297.18 KB | 1.000 | -| | | | | | | | | | | | | | -| Normalize | 1001 | 203,995.7 us | 30,961.7 us | 1,697.11 us | 4.902 | 2.54 | 0.07 | - | - | - | 48.99 KB | 0.003 | -| Clipper2Union | 1001 | 80,238.6 us | 44,367.1 us | 2,431.91 us | 12.463 | 1.00 | 0.04 | 1857.1429 | 1857.1429 | 1857.1429 | 17115.08 KB | 1.000 | +| Method | VertexCount | Mean | Error | StdDev | Op/s | Ratio | RatioSD | Gen0 | Gen1 | Gen2 | Allocated | Alloc Ratio | +|------------------ |------------ |-------------:|------------:|------------:|----------:|------:|--------:|----------:|----------:|----------:|-----------:|------------:| +| Normalize | 101 | 1,695.4 us | 251.4 us | 13.78 us | 589.827 | 3.68 | 0.10 | - | - | - | 3.41 KB | 0.02 | +| Clipper2Normalize | 101 | 460.9 us | 253.8 us | 13.91 us | 2,169.784 | 1.00 | 0.04 | 12.2070 | 3.9063 | - | 205.76 KB | 1.00 | +| | | | | | | | | | | | | | +| Normalize | 301 | 16,385.1 us | 5,075.3 us | 278.19 us | 61.031 | 2.80 | 0.04 | - | - | - | 9.66 KB | 0.004 | +| Clipper2Normalize | 301 | 5,860.5 us | 765.2 us | 41.94 us | 170.633 | 1.00 | 0.01 | 492.1875 | 492.1875 | 492.1875 | 2297.18 KB | 1.000 | +| | | | | | | | | | | | | | +| Normalize | 1001 | 197,339.6 us | 76,838.2 us | 4,211.76 us | 5.067 | 2.51 | 0.09 | - | - | - | 31.54 KB | 0.002 | +| Clipper2Normalize | 1001 | 78,746.5 us | 55,733.0 us | 3,054.92 us | 12.699 | 1.00 | 0.05 | 1857.1429 | 1857.1429 | 1857.1429 | 17115.1 KB | 1.000 | */ /// @@ -39,27 +39,36 @@ public class NormalizationBenches private PathsD clipperSubject; private const int ClipperPrecision = 6; + /// + /// Gets or sets the number of distinct vertices in each star. + /// [Params(101, 301, 1001)] public int VertexCount { get; set; } + /// + /// Builds the input geometry for both engines. + /// [GlobalSetup] public void Setup() { this.polygon = BuildStarPolygon(this.VertexCount, 100d); - this.clipperSubject = BuildClipperSubject(this.polygon); - GetLowestPathInfo(this.clipperSubject, out int lowestPathIdx, out bool isNegArea); - if (lowestPathIdx >= 0 && isNegArea) - { - ReversePaths(this.clipperSubject); - } + this.clipperSubject = BenchmarkGeometry.ToPaths(this.polygon); } + /// + /// Resolves the positive-filled star with Martinez. + /// + /// The resolved polygon. [Benchmark] public Polygon Normalize() => PolygonClipper.Normalize(this.polygon, FillRule.Positive); + /// + /// Resolves the same positive-filled star with Clipper2. + /// + /// The resolved contour tree. [Benchmark(Baseline = true)] - public PolyTreeD Clipper2Union() + public object Clipper2Normalize() { ClipperD clipper = new(ClipperPrecision) { @@ -73,6 +82,12 @@ public PolyTreeD Clipper2Union() return solution; } + /// + /// Builds a star whose nonadjacent edges cross. + /// + /// The odd number of distinct vertices. + /// The distance from the center to each vertex. + /// The closed star contour. private static Polygon BuildStarPolygon(int vertexCount, double radius) { if (vertexCount < 5 || (vertexCount & 1) == 0) @@ -95,83 +110,4 @@ private static Polygon BuildStarPolygon(int vertexCount, double radius) Polygon polygon = [contour]; return polygon; } - - private static PathsD BuildClipperSubject(Polygon polygon) - { - PathsD subject = new(polygon.Count); - for (int i = 0; i < polygon.Count; i++) - { - Contour contour = polygon[i]; - PathD path = new(contour.Count); - for (int j = 0; j < contour.Count; j++) - { - Vertex vertex = contour[j]; - path.Add(new PointD(vertex.X, vertex.Y)); - } - - subject.Add(path); - } - - return subject; - } - - private static void ReversePaths(PathsD paths) - { - for (int i = 0; i < paths.Count; i++) - { - paths[i].Reverse(); - } - } - - private static void GetLowestPathInfo(PathsD paths, out int lowestPathIdx, out bool isNegArea) - { - lowestPathIdx = -1; - isNegArea = false; - - if (paths.Count == 0) - { - return; - } - - PointD lowestPoint = default; - bool hasPoint = false; - - for (int i = 0; i < paths.Count; i++) - { - PathD path = paths[i]; - if (path.Count == 0) - { - continue; - } - - PointD candidate = GetLowestPoint(path); - if (!hasPoint || candidate.y > lowestPoint.y || - (candidate.y == lowestPoint.y && candidate.x < lowestPoint.x)) - { - lowestPoint = candidate; - lowestPathIdx = i; - hasPoint = true; - } - } - - if (lowestPathIdx >= 0) - { - isNegArea = Clipper.Area(paths[lowestPathIdx]) < 0; - } - } - - private static PointD GetLowestPoint(PathD path) - { - PointD lowest = path[0]; - for (int i = 1; i < path.Count; i++) - { - PointD candidate = path[i]; - if (candidate.y > lowest.y || (candidate.y == lowest.y && candidate.x < lowest.x)) - { - lowest = candidate; - } - } - - return lowest; - } } diff --git a/tests/PolygonClipper.Benchmarks/OffsetBenches.cs b/tests/PolygonClipper.Benchmarks/OffsetBenches.cs index 264cd5c..1d6c157 100644 --- a/tests/PolygonClipper.Benchmarks/OffsetBenches.cs +++ b/tests/PolygonClipper.Benchmarks/OffsetBenches.cs @@ -3,7 +3,6 @@ using BenchmarkDotNet.Attributes; using Clipper2Lib; -using SixLabors.PolygonClipper.Tests; namespace SixLabors.PolygonClipper.Benchmarks; @@ -17,34 +16,70 @@ .NET SDK 11.0.100-preview.7.26381.103 Job=ShortRun IterationCount=3 LaunchCount=1 WarmupCount=3 -| Method | VertexCount | Delta | Mean | Error | StdDev | Op/s | Ratio | RatioSD | Gen0 | Gen1 | Gen2 | Allocated | Alloc Ratio | -|--------------- |------------ |------ |---------------:|----------------:|--------------:|------------:|------:|--------:|----------:|----------:|----------:|-----------:|------------:| -| Offset | 16 | -1200 | 3.187 us | 1.1629 us | 0.0637 us | 313,729.508 | 0.09 | 0.00 | 0.0420 | - | - | 712 B | 0.03 | -| Clipper2Offset | 16 | -1200 | 33.982 us | 16.4081 us | 0.8994 us | 29,426.923 | 1.00 | 0.03 | 1.3733 | 0.0305 | - | 23376 B | 1.00 | -| | | | | | | | | | | | | | | -| Offset | 16 | -1 | 6.414 us | 0.8044 us | 0.0441 us | 155,897.311 | 1.64 | 0.02 | 0.1068 | - | - | 1792 B | 0.15 | -| Clipper2Offset | 16 | -1 | 3.919 us | 0.9182 us | 0.0503 us | 255,160.744 | 1.00 | 0.02 | 0.7248 | 0.0114 | - | 12176 B | 1.00 | -| | | | | | | | | | | | | | | -| Offset | 16 | 1 | 6.444 us | 0.8902 us | 0.0488 us | 155,181.218 | 4.69 | 0.07 | 0.1068 | - | - | 1792 B | 0.29 | -| Clipper2Offset | 16 | 1 | 1.373 us | 0.4167 us | 0.0228 us | 728,208.963 | 1.00 | 0.02 | 0.3738 | 0.0038 | - | 6264 B | 1.00 | -| | | | | | | | | | | | | | | -| Offset | 256 | -1200 | 47.463 us | 10.8460 us | 0.5945 us | 21,068.890 | 0.003 | 0.00 | 0.2441 | - | - | 4553 B | 0.002 | -| Clipper2Offset | 256 | -1200 | 17,393.549 us | 2,751.6011 us | 150.8245 us | 57.493 | 1.000 | 0.01 | 468.7500 | 468.7500 | 468.7500 | 2313643 B | 1.000 | -| | | | | | | | | | | | | | | -| Offset | 256 | -1 | 112.811 us | 61.9141 us | 3.3937 us | 8,864.413 | 1.57 | 0.13 | 0.7324 | - | - | 13313 B | 0.09 | -| Clipper2Offset | 256 | -1 | 72.041 us | 123.9203 us | 6.7925 us | 13,880.950 | 1.01 | 0.11 | 8.9111 | 1.9531 | - | 150536 B | 1.00 | -| | | | | | | | | | | | | | | -| Offset | 256 | 1 | 122.703 us | 117.8423 us | 6.4593 us | 8,149.775 | 7.00 | 1.07 | 0.7324 | - | - | 13313 B | 0.20 | -| Clipper2Offset | 256 | 1 | 17.908 us | 60.4415 us | 3.3130 us | 55,841.318 | 1.02 | 0.22 | 4.0588 | 0.4272 | - | 67896 B | 1.00 | -| | | | | | | | | | | | | | | -| Offset | 1024 | -1200 | 213.038 us | 96.3788 us | 5.2828 us | 4,694.003 | 0.001 | 0.00 | 0.9766 | - | - | 16851 B | 0.000 | -| Clipper2Offset | 1024 | -1200 | 307,856.250 us | 111,568.5614 us | 6,115.4493 us | 3.248 | 1.000 | 0.02 | 1000.0000 | 1000.0000 | 1000.0000 | 34406036 B | 1.000 | -| | | | | | | | | | | | | | | -| Offset | 1024 | -1 | 544.064 us | 71.5710 us | 3.9230 us | 1,838.020 | 1.91 | 0.06 | 2.9297 | - | - | 50218 B | 0.08 | -| Clipper2Offset | 1024 | -1 | 284.680 us | 167.3285 us | 9.1718 us | 3,512.721 | 1.00 | 0.04 | 35.1563 | 20.5078 | - | 593456 B | 1.00 | -| | | | | | | | | | | | | | | -| Offset | 1024 | 1 | 570.951 us | 484.5199 us | 26.5582 us | 1,751.463 | 9.28 | 0.50 | 2.9297 | - | - | 50218 B | 0.19 | -| Clipper2Offset | 1024 | 1 | 61.601 us | 47.6335 us | 2.6110 us | 16,233.583 | 1.00 | 0.05 | 15.8081 | 5.8594 | - | 264600 B | 1.00 | +| Method | VertexCount | Delta | Mean | Error | StdDev | Op/s | Ratio | RatioSD | Gen0 | Gen1 | Gen2 | Allocated | Alloc Ratio | +|--------------- |------------ |------ |---------------:|----------------:|---------------:|------------:|------:|--------:|----------:|----------:|----------:|-----------:|------------:| +| Offset | 16 | -1200 | 2.468 us | 0.3326 us | 0.0182 us | 405,178.385 | 0.08 | 0.00 | 0.0343 | - | - | 616 B | 0.03 | +| Clipper2Offset | 16 | -1200 | 29.521 us | 4.0812 us | 0.2237 us | 33,874.633 | 1.00 | 0.01 | 1.3733 | 0.0305 | - | 23376 B | 1.00 | +| | | | | | | | | | | | | | | +| Offset | 16 | -900 | 57.562 us | 31.7352 us | 1.7395 us | 17,372.449 | 4.41 | 0.40 | 0.1831 | - | - | 3184 B | 0.15 | +| Clipper2Offset | 16 | -900 | 13.131 us | 24.1340 us | 1.3229 us | 76,157.684 | 1.01 | 0.12 | 1.2207 | 0.0305 | - | 20664 B | 1.00 | +| | | | | | | | | | | | | | | +| Offset | 16 | -100 | 6.204 us | 4.0512 us | 0.2221 us | 161,177.093 | 1.58 | 0.09 | 0.0916 | - | - | 1600 B | 0.13 | +| Clipper2Offset | 16 | -100 | 3.924 us | 4.0858 us | 0.2240 us | 254,843.936 | 1.00 | 0.07 | 0.7248 | 0.0114 | - | 12176 B | 1.00 | +| | | | | | | | | | | | | | | +| Offset | 16 | -1 | 6.655 us | 1.1062 us | 0.0606 us | 150,259.247 | 1.73 | 0.15 | 0.0916 | - | - | 1600 B | 0.13 | +| Clipper2Offset | 16 | -1 | 3.878 us | 7.2758 us | 0.3988 us | 257,884.953 | 1.01 | 0.13 | 0.7248 | 0.0114 | - | 12176 B | 1.00 | +| | | | | | | | | | | | | | | +| Offset | 16 | 1 | 6.678 us | 2.2652 us | 0.1242 us | 149,753.146 | 4.68 | 0.59 | 0.0916 | - | - | 1600 B | 0.26 | +| Clipper2Offset | 16 | 1 | 1.450 us | 4.1261 us | 0.2262 us | 689,619.764 | 1.02 | 0.19 | 0.3738 | 0.0038 | - | 6264 B | 1.00 | +| | | | | | | | | | | | | | | +| Offset | 16 | 100 | 6.501 us | 4.1664 us | 0.2284 us | 153,826.681 | 5.02 | 0.32 | 0.0916 | - | - | 1600 B | 0.26 | +| Clipper2Offset | 16 | 100 | 1.299 us | 1.5966 us | 0.0875 us | 769,606.026 | 1.00 | 0.08 | 0.3738 | 0.0038 | - | 6264 B | 1.00 | +| | | | | | | | | | | | | | | +| Offset | 16 | 1200 | 6.076 us | 2.4293 us | 0.1332 us | 164,583.210 | 4.76 | 0.10 | 0.0916 | - | - | 1600 B | 0.26 | +| Clipper2Offset | 16 | 1200 | 1.276 us | 0.2702 us | 0.0148 us | 783,515.559 | 1.00 | 0.01 | 0.3738 | 0.0038 | - | 6264 B | 1.00 | +| | | | | | | | | | | | | | | +| Offset | 256 | -1200 | 44.279 us | 3.5438 us | 0.1942 us | 22,584.136 | 0.003 | 0.00 | 0.2441 | - | - | 4457 B | 0.002 | +| Clipper2Offset | 256 | -1200 | 15,788.872 us | 2,011.9164 us | 110.2799 us | 63.336 | 1.000 | 0.01 | 468.7500 | 468.7500 | 468.7500 | 2313486 B | 1.000 | +| | | | | | | | | | | | | | | +| Offset | 256 | -900 | 2,314.089 us | 923.7301 us | 50.6328 us | 432.135 | 3.34 | 0.07 | - | - | - | 37786 B | 0.18 | +| Clipper2Offset | 256 | -900 | 692.685 us | 97.9071 us | 5.3666 us | 1,443.657 | 1.00 | 0.01 | 12.6953 | 3.9063 | - | 214040 B | 1.00 | +| | | | | | | | | | | | | | | +| Offset | 256 | -100 | 99.391 us | 5.6818 us | 0.3114 us | 10,061.287 | 0.80 | 0.01 | 0.7324 | - | - | 13120 B | 0.08 | +| Clipper2Offset | 256 | -100 | 123.854 us | 26.3756 us | 1.4457 us | 8,074.024 | 1.00 | 0.01 | 9.6436 | 1.9531 | - | 162640 B | 1.00 | +| | | | | | | | | | | | | | | +| Offset | 256 | -1 | 100.865 us | 5.5870 us | 0.3062 us | 9,914.212 | 1.71 | 0.01 | 0.7324 | - | - | 13120 B | 0.09 | +| Clipper2Offset | 256 | -1 | 59.068 us | 6.9002 us | 0.3782 us | 16,929.521 | 1.00 | 0.01 | 8.9722 | 1.9531 | - | 150536 B | 1.00 | +| | | | | | | | | | | | | | | +| Offset | 256 | 1 | 103.380 us | 4.4748 us | 0.2453 us | 9,673.071 | 7.19 | 0.12 | 0.7324 | - | - | 13120 B | 0.19 | +| Clipper2Offset | 256 | 1 | 14.380 us | 5.0707 us | 0.2779 us | 69,540.046 | 1.00 | 0.02 | 4.0588 | 0.4272 | - | 67896 B | 1.00 | +| | | | | | | | | | | | | | | +| Offset | 256 | 100 | 100.712 us | 11.0057 us | 0.6033 us | 9,929.330 | 6.95 | 0.12 | 0.7324 | - | - | 13120 B | 0.19 | +| Clipper2Offset | 256 | 100 | 14.492 us | 4.9685 us | 0.2723 us | 69,003.320 | 1.00 | 0.02 | 4.0588 | 0.4272 | - | 67896 B | 1.00 | +| | | | | | | | | | | | | | | +| Offset | 256 | 1200 | 102.491 us | 16.3031 us | 0.8936 us | 9,757.000 | 7.05 | 0.07 | 0.7324 | - | - | 13120 B | 0.19 | +| Clipper2Offset | 256 | 1200 | 14.531 us | 2.2596 us | 0.1239 us | 68,817.537 | 1.00 | 0.01 | 4.0588 | 0.4272 | - | 67896 B | 1.00 | +| | | | | | | | | | | | | | | +| Offset | 1024 | -1200 | 195.474 us | 171.1595 us | 9.3818 us | 5,115.769 | 0.001 | 0.00 | 0.9766 | - | - | 16744 B | 0.000 | +| Clipper2Offset | 1024 | -1200 | 323,053.700 us | 309,818.4386 us | 16,982.1941 us | 3.095 | 1.002 | 0.06 | 2000.0000 | 2000.0000 | 2000.0000 | 34406024 B | 1.000 | +| | | | | | | | | | | | | | | +| Offset | 1024 | -900 | 11,477.235 us | 8,978.6788 us | 492.1517 us | 87.129 | 0.94 | 0.05 | - | - | - | 148336 B | 0.19 | +| Clipper2Offset | 1024 | -900 | 12,293.630 us | 11,688.8019 us | 640.7027 us | 81.343 | 1.00 | 0.06 | 46.8750 | 15.6250 | - | 790344 B | 1.00 | +| | | | | | | | | | | | | | | +| Offset | 1024 | -100 | 503.410 us | 373.1325 us | 20.4527 us | 1,986.452 | 0.36 | 0.02 | 2.9297 | - | - | 50005 B | 0.08 | +| Clipper2Offset | 1024 | -100 | 1,388.242 us | 1,137.2492 us | 62.3365 us | 720.335 | 1.00 | 0.06 | 37.1094 | 11.7188 | - | 643472 B | 1.00 | +| | | | | | | | | | | | | | | +| Offset | 1024 | -1 | 524.284 us | 516.7832 us | 28.3266 us | 1,907.365 | 1.88 | 0.16 | 2.9297 | - | - | 50026 B | 0.08 | +| Clipper2Offset | 1024 | -1 | 279.539 us | 420.7071 us | 23.0604 us | 3,577.313 | 1.00 | 0.10 | 35.1563 | 20.5078 | - | 593456 B | 1.00 | +| | | | | | | | | | | | | | | +| Offset | 1024 | 1 | 542.421 us | 224.6571 us | 12.3142 us | 1,843.586 | 8.87 | 0.46 | 2.9297 | - | - | 50026 B | 0.19 | +| Clipper2Offset | 1024 | 1 | 61.299 us | 61.8332 us | 3.3893 us | 16,313.446 | 1.00 | 0.07 | 15.7471 | 5.7373 | - | 264600 B | 1.00 | +| | | | | | | | | | | | | | | +| Offset | 1024 | 100 | 543.999 us | 637.9292 us | 34.9671 us | 1,838.237 | 7.22 | 1.46 | 2.9297 | - | - | 50026 B | 0.19 | +| Clipper2Offset | 1024 | 100 | 78.080 us | 330.4798 us | 18.1147 us | 12,807.297 | 1.04 | 0.29 | 15.8081 | 5.8594 | - | 264600 B | 1.00 | +| | | | | | | | | | | | | | | +| Offset | 1024 | 1200 | 691.062 us | 587.1478 us | 32.1836 us | 1,447.049 | 9.34 | 1.47 | 2.9297 | - | - | 50026 B | 0.19 | +| Clipper2Offset | 1024 | 1200 | 75.458 us | 228.7613 us | 12.5392 us | 13,252.362 | 1.02 | 0.21 | 15.7471 | 5.7373 | - | 264600 B | 1.00 | */ /// @@ -68,11 +103,11 @@ public class OffsetBenches /// /// Gets or sets the signed offset distance. /// - [Params(-1200D, -1D, 1D)] + [Params(-1200D, -900D, -100D, -1D, 1D, 100D, 1200D)] public double Delta { get; set; } /// - /// Builds the source and checks topology and coordinates before measurement. + /// Builds the regular polygon for both engines. /// [GlobalSetup] public void Setup() @@ -90,47 +125,6 @@ public void Setup() this.polygon = [contour]; this.paths = [path]; this.options = new() { LineJoin = LineJoin.Miter }; - - Polygon actual = this.Offset(); - PathsD expected = this.Clipper2Offset(); - - // The edge-to-center distance of a regular polygon is radius * cos(pi / vertexCount). - int contourCount = this.Delta <= -1000 * Math.Cos(Math.PI / this.VertexCount) ? 0 : 1; - if (actual.Count != contourCount || expected.Count != contourCount) - { - throw new InvalidOperationException("The offset boundary count differs from the regular polygon's collapse distance."); - } - - if (contourCount == 0) - { - return; - } - - PathsD actualPaths = [new PathD(actual[0].Select(vertex => new PointD(vertex.X, vertex.Y)))]; - if (!TestPolygonUtilities.HaveEquivalentBoundaryGraphs(actualPaths, expected)) - { - throw new InvalidOperationException("The offset boundary connections differ."); - } - - // Clipper2 rounds input and output coordinates. Check agreement within one millionth - // of a source unit as well as topology, rather than comparing timings for different work. - foreach (Vertex vertex in actual[0]) - { - double nearest = double.PositiveInfinity; - PathD boundary = expected[0]; - for (int i = 0; i < boundary.Count; i++) - { - PointD first = boundary[i]; - PointD second = boundary[(i + 1) % boundary.Count]; - Vertex closest = PolygonUtilities.ClosestPointOnSegment(vertex, new(first.x, first.y), new(second.x, second.y)); - nearest = Math.Min(nearest, Vertex.DistanceSquared(vertex, closest)); - } - - if (nearest > 1E-12D) - { - throw new InvalidOperationException($"Offset vertex {vertex} differs from Clipper2 by {Math.Sqrt(nearest):R}, exceeding 1E-6."); - } - } } /// @@ -145,6 +139,6 @@ public void Setup() /// /// The offset paths. [Benchmark(Baseline = true)] - public PathsD Clipper2Offset() + public object Clipper2Offset() => Clipper.InflatePaths(this.paths, this.Delta, JoinType.Miter, EndType.Polygon, 4, ClipperPrecision); } diff --git a/tests/PolygonClipper.Benchmarks/OpenClippingBenches.cs b/tests/PolygonClipper.Benchmarks/OpenClippingBenches.cs index 53a444e..279edb0 100644 --- a/tests/PolygonClipper.Benchmarks/OpenClippingBenches.cs +++ b/tests/PolygonClipper.Benchmarks/OpenClippingBenches.cs @@ -16,31 +16,31 @@ .NET SDK 11.0.100-preview.7.26381.103 Job=ShortRun IterationCount=3 LaunchCount=1 WarmupCount=3 -| Method | PathCount | VerticesPerPath | Transpose | Mean | Error | StdDev | Op/s | Ratio | RatioSD | Gen0 | Gen1 | Gen2 | Allocated | Alloc Ratio | -|--------------------------- |---------- |---------------- |---------- |-------------:|--------------:|------------:|----------:|------:|--------:|---------:|---------:|---------:|-----------:|------------:| -| PolygonClipperIntersection | 10 | 2 | False | 10.041 us | 6.363 us | 0.3488 us | 99,591.4 | 3.84 | 0.17 | 0.1678 | - | - | 2.84 KB | 0.21 | -| Clipper2Intersection | 10 | 2 | False | 2.617 us | 1.762 us | 0.0966 us | 382,076.6 | 1.00 | 0.05 | 0.8163 | 0.0267 | - | 13.36 KB | 1.00 | -| | | | | | | | | | | | | | | | -| PolygonClipperIntersection | 10 | 2 | True | 11.112 us | 31.236 us | 1.7122 us | 89,995.8 | 4.11 | 0.57 | 0.1678 | - | - | 2.84 KB | 0.19 | -| Clipper2Intersection | 10 | 2 | True | 2.706 us | 2.357 us | 0.1292 us | 369,564.4 | 1.00 | 0.06 | 0.9117 | 0.0343 | - | 14.91 KB | 1.00 | -| | | | | | | | | | | | | | | | -| PolygonClipperIntersection | 10 | 13 | False | 29.653 us | 14.059 us | 0.7706 us | 33,723.5 | 2.98 | 0.08 | 0.3967 | - | - | 6.94 KB | 0.16 | -| Clipper2Intersection | 10 | 13 | False | 9.945 us | 2.376 us | 0.1302 us | 100,556.0 | 1.00 | 0.02 | 2.5940 | 0.2747 | - | 42.57 KB | 1.00 | -| | | | | | | | | | | | | | | | -| PolygonClipperIntersection | 10 | 13 | True | 35.715 us | 12.425 us | 0.6811 us | 27,999.5 | 5.94 | 0.17 | 0.3662 | - | - | 6.94 KB | 0.22 | -| Clipper2Intersection | 10 | 13 | True | 6.019 us | 2.905 us | 0.1592 us | 166,136.7 | 1.00 | 0.03 | 1.9608 | 0.1678 | - | 32.04 KB | 1.00 | -| | | | | | | | | | | | | | | | -| PolygonClipperIntersection | 1000 | 2 | False | 1,202.917 us | 1,173.842 us | 64.3422 us | 831.3 | 5.81 | 0.27 | 15.6250 | 5.8594 | - | 258.07 KB | 0.24 | -| Clipper2Intersection | 1000 | 2 | False | 207.058 us | 27.796 us | 1.5236 us | 4,829.6 | 1.00 | 0.01 | 65.4297 | 50.2930 | - | 1072.85 KB | 1.00 | -| | | | | | | | | | | | | | | | -| PolygonClipperIntersection | 1000 | 2 | True | 1,340.080 us | 949.095 us | 52.0231 us | 746.2 | 2.13 | 0.12 | 15.6250 | 5.8594 | - | 258.07 KB | 0.21 | -| Clipper2Intersection | 1000 | 2 | True | 629.687 us | 598.724 us | 32.8181 us | 1,588.1 | 1.00 | 0.06 | 76.1719 | 65.4297 | - | 1244.98 KB | 1.00 | -| | | | | | | | | | | | | | | | -| PolygonClipperIntersection | 1000 | 13 | False | 5,080.375 us | 1,062.886 us | 58.2604 us | 196.8 | 1.41 | 0.03 | 31.2500 | 7.8125 | - | 597.91 KB | 0.16 | -| Clipper2Intersection | 1000 | 13 | False | 3,600.080 us | 1,497.421 us | 82.0787 us | 277.8 | 1.00 | 0.03 | 316.4063 | 312.5000 | 109.3750 | 3808.37 KB | 1.00 | -| | | | | | | | | | | | | | | | -| PolygonClipperIntersection | 1000 | 13 | True | 5,290.140 us | 385.407 us | 21.1255 us | 189.0 | 1.62 | 0.26 | 31.2500 | 7.8125 | - | 597.91 KB | 0.20 | -| Clipper2Intersection | 1000 | 13 | True | 3,353.168 us | 12,912.942 us | 707.8019 us | 298.2 | 1.03 | 0.25 | 234.3750 | 230.4688 | 74.2188 | 2931.89 KB | 1.00 | +| Method | PathCount | VerticesPerPath | Transpose | Mean | Error | StdDev | Op/s | Ratio | RatioSD | Gen0 | Gen1 | Gen2 | Allocated | Alloc Ratio | +|--------------------- |---------- |---------------- |---------- |-------------:|-------------:|------------:|----------:|------:|--------:|---------:|---------:|---------:|-----------:|------------:| +| Intersection | 10 | 2 | False | 10.904 us | 9.838 us | 0.5393 us | 91,709.9 | 3.87 | 0.21 | 0.1678 | - | - | 2.84 KB | 0.21 | +| Clipper2Intersection | 10 | 2 | False | 2.823 us | 1.937 us | 0.1062 us | 354,259.3 | 1.00 | 0.05 | 0.8163 | 0.0267 | - | 13.36 KB | 1.00 | +| | | | | | | | | | | | | | | | +| Intersection | 10 | 2 | True | 10.301 us | 2.189 us | 0.1200 us | 97,079.2 | 4.13 | 0.09 | 0.1678 | - | - | 2.84 KB | 0.19 | +| Clipper2Intersection | 10 | 2 | True | 2.495 us | 1.087 us | 0.0596 us | 400,776.5 | 1.00 | 0.03 | 0.9117 | 0.0343 | - | 14.91 KB | 1.00 | +| | | | | | | | | | | | | | | | +| Intersection | 10 | 13 | False | 28.831 us | 1.610 us | 0.0883 us | 34,684.6 | 2.87 | 0.02 | 0.3967 | - | - | 6.94 KB | 0.16 | +| Clipper2Intersection | 10 | 13 | False | 10.062 us | 1.545 us | 0.0847 us | 99,387.5 | 1.00 | 0.01 | 2.5940 | 0.2747 | - | 42.57 KB | 1.00 | +| | | | | | | | | | | | | | | | +| Intersection | 10 | 13 | True | 41.346 us | 18.318 us | 1.0041 us | 24,186.3 | 7.46 | 0.18 | 0.3662 | - | - | 6.94 KB | 0.22 | +| Clipper2Intersection | 10 | 13 | True | 5.542 us | 1.384 us | 0.0758 us | 180,453.8 | 1.00 | 0.02 | 1.9608 | 0.1678 | - | 32.04 KB | 1.00 | +| | | | | | | | | | | | | | | | +| Intersection | 1000 | 2 | False | 1,136.246 us | 158.943 us | 8.7122 us | 880.1 | 5.68 | 0.13 | 15.6250 | 5.8594 | - | 258.07 KB | 0.24 | +| Clipper2Intersection | 1000 | 2 | False | 200.069 us | 93.368 us | 5.1178 us | 4,998.3 | 1.00 | 0.03 | 65.4297 | 50.2930 | - | 1072.85 KB | 1.00 | +| | | | | | | | | | | | | | | | +| Intersection | 1000 | 2 | True | 1,264.030 us | 91.072 us | 4.9920 us | 791.1 | 1.80 | 0.17 | 15.6250 | 5.8594 | - | 258.07 KB | 0.21 | +| Clipper2Intersection | 1000 | 2 | True | 708.218 us | 1,343.360 us | 73.6341 us | 1,412.0 | 1.01 | 0.13 | 76.1719 | 65.4297 | - | 1244.98 KB | 1.00 | +| | | | | | | | | | | | | | | | +| Intersection | 1000 | 13 | False | 4,938.736 us | 178.069 us | 9.7606 us | 202.5 | 1.23 | 0.10 | 31.2500 | 7.8125 | - | 597.91 KB | 0.16 | +| Clipper2Intersection | 1000 | 13 | False | 4,027.525 us | 6,991.955 us | 383.2526 us | 248.3 | 1.01 | 0.11 | 316.4063 | 312.5000 | 109.3750 | 3808.37 KB | 1.00 | +| | | | | | | | | | | | | | | | +| Intersection | 1000 | 13 | True | 5,410.344 us | 3,778.677 us | 207.1221 us | 184.8 | 1.85 | 0.18 | 31.2500 | 7.8125 | - | 597.91 KB | 0.20 | +| Clipper2Intersection | 1000 | 13 | True | 2,948.340 us | 5,395.866 us | 295.7656 us | 339.2 | 1.01 | 0.13 | 234.3750 | 230.4688 | 74.2188 | 2931.89 KB | 1.00 | */ /// @@ -74,7 +74,7 @@ public class OpenClippingBenches public bool Transpose { get; set; } /// - /// Builds equal input geometry and checks exact output edges before measurement. + /// Builds the open paths and closed mask for both engines. /// [GlobalSetup] public void Setup() @@ -121,38 +121,6 @@ public void Setup() this.closedClip.Add(path); this.clip.Add(transformed); } - - Polygon result = (Polygon)this.PolygonClipperIntersection(); - PathsD expected = (PathsD)this.Clipper2Intersection(); - List<(double X1, double Y1, double X2, double Y2)> actualEdges = []; - foreach (Contour contour in result) - { - if (contour.IsClosed) - { - throw new InvalidOperationException("Open-subject intersection returned an area contour."); - } - - for (int i = 1; i < contour.Count; i++) - { - AddEdge(actualEdges, contour[i - 1].X, contour[i - 1].Y, contour[i].X, contour[i].Y); - } - } - - List<(double X1, double Y1, double X2, double Y2)> expectedEdges = []; - foreach (PathD path in expected) - { - for (int i = 1; i < path.Count; i++) - { - AddEdge(expectedEdges, path[i - 1].x, path[i - 1].y, path[i].x, path[i].y); - } - } - - actualEdges.Sort(); - expectedEdges.Sort(); - if (!actualEdges.SequenceEqual(expectedEdges)) - { - throw new InvalidOperationException("The benchmark inputs did not produce equivalent open output edges."); - } } /// @@ -160,7 +128,7 @@ public void Setup() /// /// The open result contours. [Benchmark] - public object PolygonClipperIntersection() => PolygonClipper.Intersection(this.subject, this.clip, FillRule.NonZero); + public object Intersection() => PolygonClipper.Intersection(this.subject, this.clip, FillRule.NonZero); /// /// Clips the same original paths with the same closed mask using Clipper2. @@ -177,24 +145,4 @@ public object Clipper2Intersection() engine.Execute(ClipType.Intersection, Clipper2Lib.FillRule.NonZero, closed, open); return open; } - - /// - /// Adds a direction-independent edge without rounding coordinates or changing subdivisions. - /// - /// The collected output edges. - /// The first endpoint's x coordinate. - /// The first endpoint's y coordinate. - /// The second endpoint's x coordinate. - /// The second endpoint's y coordinate. - private static void AddEdge(List<(double X1, double Y1, double X2, double Y2)> edges, double x1, double y1, double x2, double y2) - { - if (x1 < x2 || (x1 == x2 && y1 <= y2)) - { - edges.Add((x1, y1, x2, y2)); - } - else - { - edges.Add((x2, y2, x1, y1)); - } - } } diff --git a/tests/PolygonClipper.Benchmarks/StarBooleanBenches.cs b/tests/PolygonClipper.Benchmarks/StarBooleanBenches.cs index 1633905..94a7ffd 100644 --- a/tests/PolygonClipper.Benchmarks/StarBooleanBenches.cs +++ b/tests/PolygonClipper.Benchmarks/StarBooleanBenches.cs @@ -2,6 +2,7 @@ // Licensed under the Six Labors Split License. using BenchmarkDotNet.Attributes; +using BenchmarkDotNet.Configs; using Clipper2Lib; namespace SixLabors.PolygonClipper.Benchmarks; @@ -16,20 +17,43 @@ .NET SDK 11.0.100-preview.7.26381.103 Job=ShortRun IterationCount=3 LaunchCount=1 WarmupCount=3 -| Method | VertexCount | Mean | Error | StdDev | Op/s | Gen0 | Gen1 | Gen2 | Allocated | -|--------------------------- |------------ |-------------:|-------------:|------------:|---------:|-----------:|-----------:|----------:|--------------:| -| PolygonClipperUnion | 101 | 10.241 ms | 14.189 ms | 0.7778 ms | 97.6464 | 46.8750 | 15.6250 | - | 984.86 KB | -| PolygonClipperIntersection | 101 | 9.785 ms | 3.148 ms | 0.1726 ms | 102.2006 | 93.7500 | 46.8750 | - | 1769.23 KB | -| PolygonClipperDifference | 101 | 8.865 ms | 1.617 ms | 0.0886 ms | 112.8081 | 78.1250 | 15.6250 | - | 1330.24 KB | -| PolygonClipperXor | 101 | 19.532 ms | 7.799 ms | 0.4275 ms | 51.1991 | 1312.5000 | 1312.5000 | 843.7500 | 11968.01 KB | -| PolygonClipperUnion | 301 | 122.200 ms | 128.921 ms | 7.0666 ms | 8.1833 | 2600.0000 | 2600.0000 | 1200.0000 | 33225.89 KB | -| PolygonClipperIntersection | 301 | 170.792 ms | 109.231 ms | 5.9873 ms | 5.8551 | 3333.3333 | 3333.3333 | 1333.3333 | 57243.84 KB | -| PolygonClipperDifference | 301 | 156.373 ms | 170.076 ms | 9.3224 ms | 6.3950 | 3250.0000 | 3250.0000 | 1500.0000 | 48985.99 KB | -| PolygonClipperXor | 301 | 277.201 ms | 61.909 ms | 3.3934 ms | 3.6075 | 6000.0000 | 5500.0000 | 2000.0000 | 106509.15 KB | -| PolygonClipperUnion | 1001 | 1,853.955 ms | 1,062.212 ms | 58.2234 ms | 0.5394 | 21000.0000 | 20000.0000 | 5000.0000 | 421820.51 KB | -| PolygonClipperIntersection | 1001 | 2,498.312 ms | 270.235 ms | 14.8125 ms | 0.4003 | 34000.0000 | 32000.0000 | 6000.0000 | 738265.43 KB | -| PolygonClipperDifference | 1001 | 2,083.018 ms | 226.483 ms | 12.4143 ms | 0.4801 | 28000.0000 | 26000.0000 | 5000.0000 | 539974.69 KB | -| PolygonClipperXor | 1001 | 3,337.877 ms | 3,338.490 ms | 182.9939 ms | 0.2996 | 54000.0000 | 48000.0000 | 6000.0000 | 1080092.26 KB | +| Method | Categories | VertexCount | Mean | Error | StdDev | Op/s | Ratio | RatioSD | Gen0 | Gen1 | Gen2 | Allocated | Alloc Ratio | +|--------------------- |------------- |------------ |---------------:|---------------:|--------------:|---------:|------:|--------:|-----------:|-----------:|----------:|-------------:|------------:| +| Difference | Difference | 101 | 8.593 ms | 1.0394 ms | 0.0570 ms | 116.3708 | 1.35 | 0.08 | 78.1250 | 31.2500 | - | 1316.74 KB | 0.32 | +| Clipper2Difference | Difference | 101 | 6.392 ms | 8.5489 ms | 0.4686 ms | 156.4422 | 1.00 | 0.09 | 328.1250 | 320.3125 | 164.0625 | 4082.33 KB | 1.00 | +| | | | | | | | | | | | | | | +| Difference | Difference | 301 | 130.095 ms | 99.1253 ms | 5.4334 ms | 7.6867 | 1.00 | 0.04 | 3000.0000 | 2800.0000 | 1000.0000 | 42073.83 KB | 1.19 | +| Clipper2Difference | Difference | 301 | 130.746 ms | 53.8317 ms | 2.9507 ms | 7.6484 | 1.00 | 0.03 | 3000.0000 | 3000.0000 | 1600.0000 | 35390.13 KB | 1.00 | +| | | | | | | | | | | | | | | +| Difference | Difference | 1001 | 2,125.882 ms | 673.9883 ms | 36.9436 ms | 0.4704 | 0.57 | 0.02 | 28000.0000 | 25000.0000 | 4000.0000 | 484677.92 KB | 1.21 | +| Clipper2Difference | Difference | 1001 | 3,726.175 ms | 1,879.7932 ms | 103.0378 ms | 0.2684 | 1.00 | 0.03 | 25000.0000 | 24000.0000 | 5000.0000 | 399665.54 KB | 1.00 | +| | | | | | | | | | | | | | | +| Intersection | Intersection | 101 | 9.145 ms | 0.9038 ms | 0.0495 ms | 109.3527 | 1.53 | 0.04 | 93.7500 | 46.8750 | - | 1755.73 KB | 0.35 | +| Clipper2Intersection | Intersection | 101 | 5.968 ms | 3.5492 ms | 0.1945 ms | 167.5699 | 1.00 | 0.04 | 328.1250 | 320.3125 | 164.0625 | 4962.32 KB | 1.00 | +| | | | | | | | | | | | | | | +| Intersection | Intersection | 301 | 157.319 ms | 79.0129 ms | 4.3310 ms | 6.3565 | 1.09 | 0.04 | 3250.0000 | 3000.0000 | 1000.0000 | 52551.37 KB | 1.21 | +| Clipper2Intersection | Intersection | 301 | 144.021 ms | 66.3565 ms | 3.6372 ms | 6.9434 | 1.00 | 0.03 | 3500.0000 | 3500.0000 | 1500.0000 | 43405.64 KB | 1.00 | +| | | | | | | | | | | | | | | +| Intersection | Intersection | 1001 | 2,282.190 ms | 388.6867 ms | 21.3052 ms | 0.4382 | 0.52 | 0.01 | 33000.0000 | 30000.0000 | 4000.0000 | 627672.06 KB | 1.25 | +| Clipper2Intersection | Intersection | 1001 | 4,390.261 ms | 894.3474 ms | 49.0222 ms | 0.2278 | 1.00 | 0.01 | 29000.0000 | 28000.0000 | 6000.0000 | 501898.72 KB | 1.00 | +| | | | | | | | | | | | | | | +| Union | Union | 101 | 8.655 ms | 2.8097 ms | 0.1540 ms | 115.5335 | 0.21 | 0.00 | 46.8750 | 15.6250 | - | 978.11 KB | 0.18 | +| Clipper2Union | Union | 101 | 40.964 ms | 4.0998 ms | 0.2247 ms | 24.4115 | 1.00 | 0.01 | 384.6154 | 230.7692 | 76.9231 | 5326.67 KB | 1.00 | +| | | | | | | | | | | | | | | +| Union | Union | 301 | 128.309 ms | 63.5969 ms | 3.4860 ms | 7.7937 | 0.06 | 0.00 | 2250.0000 | 2000.0000 | 750.0000 | 31126.62 KB | 0.79 | +| Clipper2Union | Union | 301 | 2,173.310 ms | 1,079.3527 ms | 59.1630 ms | 0.4601 | 1.00 | 0.03 | 4000.0000 | 4000.0000 | 3000.0000 | 39617.97 KB | 1.00 | +| | | | | | | | | | | | | | | +| Union | Union | 1001 | 1,734.050 ms | 566.3988 ms | 31.0462 ms | 0.5767 | 0.007 | 0.00 | 20000.0000 | 18000.0000 | 3000.0000 | 366522.3 KB | 0.97 | +| Clipper2Union | Union | 1001 | 234,883.294 ms | 49,429.5458 ms | 2,709.4002 ms | 0.0043 | 1.000 | 0.01 | 23000.0000 | 21000.0000 | 6000.0000 | 378275.68 KB | 1.00 | +| | | | | | | | | | | | | | | +| Xor | Xor | 101 | 18.371 ms | 15.0344 ms | 0.8241 ms | 54.4343 | 1.41 | 0.09 | 1000.0000 | 968.7500 | 500.0000 | 10669.71 KB | 1.28 | +| Clipper2Xor | Xor | 101 | 13.032 ms | 13.6608 ms | 0.7488 ms | 76.7356 | 1.00 | 0.07 | 609.3750 | 609.3750 | 375.0000 | 8327.78 KB | 1.00 | +| | | | | | | | | | | | | | | +| Xor | Xor | 301 | 235.357 ms | 110.2588 ms | 6.0437 ms | 4.2489 | 0.84 | 0.02 | 5000.0000 | 4000.0000 | 1000.0000 | 92684.45 KB | 1.29 | +| Clipper2Xor | Xor | 301 | 279.997 ms | 39.8076 ms | 2.1820 ms | 3.5715 | 1.00 | 0.01 | 5000.0000 | 5000.0000 | 2000.0000 | 71681.65 KB | 1.00 | +| | | | | | | | | | | | | | | +| Xor | Xor | 1001 | 3,251.201 ms | 1,311.9581 ms | 71.9129 ms | 0.3076 | 0.32 | 0.01 | 54000.0000 | 47000.0000 | 5000.0000 | 969498.71 KB | 1.30 | +| Clipper2Xor | Xor | 1001 | 10,123.423 ms | 1,516.1091 ms | 83.1031 ms | 0.0988 | 1.00 | 0.01 | 45000.0000 | 44000.0000 | 7000.0000 | 744382.44 KB | 1.00 | */ /// @@ -37,6 +61,8 @@ .NET SDK 11.0.100-preview.7.26381.103 /// [MemoryDiagnoser] [OperationsPerSecond] +[GroupBenchmarksBy(BenchmarkLogicalGroupRule.ByCategory)] +[CategoriesColumn] public class StarBooleanBenches { private const int ClipperPrecision = 6; @@ -45,78 +71,128 @@ public class StarBooleanBenches private PathsD clipperSubject; private PathsD clipperClipping; + /// + /// Gets or sets the number of distinct vertices in each star. + /// [Params(101, 301, 1001)] public int VertexCount { get; set; } + /// + /// Builds the same star inputs for both engines. + /// [GlobalSetup] public void Setup() { this.subject = BuildStarPolygon(this.VertexCount, 100D, 0D, 0D); this.clipping = BuildStarPolygon(this.VertexCount, 100D, 35D, 22D); - this.clipperSubject = BuildClipperPaths(this.subject); - this.clipperClipping = BuildClipperPaths(this.clipping); + this.clipperSubject = BenchmarkGeometry.ToPaths(this.subject); + this.clipperClipping = BenchmarkGeometry.ToPaths(this.clipping); } + /// + /// Unions the source stars with even-odd filling. + /// + /// The resolved polygon. [Benchmark] - public Polygon PolygonClipperUnion() + [BenchmarkCategory("Union")] + public Polygon Union() => PolygonClipper.Union(this.subject, this.clipping, FillRule.EvenOdd); - //[Benchmark] - //public PolyTreeD Clipper2Union() - //{ - // ClipperD clipper = CreateClipper(); - // clipper.AddSubject(this.clipperSubject); - // clipper.AddClip(this.clipperClipping); - // PolyTreeD solution = []; - // clipper.Execute(ClipType.Union, Clipper2Lib.FillRule.EvenOdd, solution); - // return solution; - //} + /// + /// Performs the same union operation and fill rule with Clipper2. + /// + /// The resolved contour tree. + [Benchmark(Baseline = true)] + [BenchmarkCategory("Union")] + public object Clipper2Union() + { + ClipperD clipper = CreateClipper(); + clipper.AddSubject(this.clipperSubject); + clipper.AddClip(this.clipperClipping); + PolyTreeD solution = []; + clipper.Execute(ClipType.Union, Clipper2Lib.FillRule.EvenOdd, solution); + return solution; + } + /// + /// Intersects the source stars with even-odd filling. + /// + /// The resolved polygon. [Benchmark] - public Polygon PolygonClipperIntersection() + [BenchmarkCategory("Intersection")] + public Polygon Intersection() => PolygonClipper.Intersection(this.subject, this.clipping, FillRule.EvenOdd); - //[Benchmark] - //public PolyTreeD Clipper2Intersection() - //{ - // ClipperD clipper = CreateClipper(); - // clipper.AddSubject(this.clipperSubject); - // clipper.AddClip(this.clipperClipping); - // PolyTreeD solution = []; - // clipper.Execute(ClipType.Intersection, Clipper2Lib.FillRule.EvenOdd, solution); - // return solution; - //} + /// + /// Performs the same intersection operation and fill rule with Clipper2. + /// + /// The resolved contour tree. + [Benchmark(Baseline = true)] + [BenchmarkCategory("Intersection")] + public object Clipper2Intersection() + { + ClipperD clipper = CreateClipper(); + clipper.AddSubject(this.clipperSubject); + clipper.AddClip(this.clipperClipping); + PolyTreeD solution = []; + clipper.Execute(ClipType.Intersection, Clipper2Lib.FillRule.EvenOdd, solution); + return solution; + } + /// + /// Subtracts the clipping star from the subject star with even-odd filling. + /// + /// The resolved polygon. [Benchmark] - public Polygon PolygonClipperDifference() + [BenchmarkCategory("Difference")] + public Polygon Difference() => PolygonClipper.Difference(this.subject, this.clipping, FillRule.EvenOdd); - //[Benchmark] - //public PolyTreeD Clipper2Difference() - //{ - // ClipperD clipper = CreateClipper(); - // clipper.AddSubject(this.clipperSubject); - // clipper.AddClip(this.clipperClipping); - // PolyTreeD solution = []; - // clipper.Execute(ClipType.Difference, Clipper2Lib.FillRule.EvenOdd, solution); - // return solution; - //} + /// + /// Performs the same difference operation and fill rule with Clipper2. + /// + /// The resolved contour tree. + [Benchmark(Baseline = true)] + [BenchmarkCategory("Difference")] + public object Clipper2Difference() + { + ClipperD clipper = CreateClipper(); + clipper.AddSubject(this.clipperSubject); + clipper.AddClip(this.clipperClipping); + PolyTreeD solution = []; + clipper.Execute(ClipType.Difference, Clipper2Lib.FillRule.EvenOdd, solution); + return solution; + } + /// + /// Finds the symmetric difference of the source stars with even-odd filling. + /// + /// The resolved polygon. [Benchmark] - public Polygon PolygonClipperXor() + [BenchmarkCategory("Xor")] + public Polygon Xor() => PolygonClipper.Xor(this.subject, this.clipping, FillRule.EvenOdd); - //[Benchmark] - //public PolyTreeD Clipper2Xor() - //{ - // ClipperD clipper = CreateClipper(); - // clipper.AddSubject(this.clipperSubject); - // clipper.AddClip(this.clipperClipping); - // PolyTreeD solution = []; - // clipper.Execute(ClipType.Xor, Clipper2Lib.FillRule.EvenOdd, solution); - // return solution; - //} + /// + /// Performs the same xor operation and fill rule with Clipper2. + /// + /// The resolved contour tree. + [Benchmark(Baseline = true)] + [BenchmarkCategory("Xor")] + public object Clipper2Xor() + { + ClipperD clipper = CreateClipper(); + clipper.AddSubject(this.clipperSubject); + clipper.AddClip(this.clipperClipping); + PolyTreeD solution = []; + clipper.Execute(ClipType.Xor, Clipper2Lib.FillRule.EvenOdd, solution); + return solution; + } + /// + /// Creates a Clipper2 engine with matching output direction and collinear handling. + /// + /// The clipping engine. private static ClipperD CreateClipper() => new(ClipperPrecision) { @@ -124,6 +200,14 @@ private static ClipperD CreateClipper() ReverseSolution = false }; + /// + /// Builds a translated star whose nonadjacent edges cross. + /// + /// The odd number of distinct vertices. + /// The distance from the center to each vertex. + /// The center X coordinate. + /// The center Y coordinate. + /// The closed star contour. private static Polygon BuildStarPolygon(int vertexCount, double radius, double centerX, double centerY) { if (vertexCount < 5 || (vertexCount & 1) == 0) @@ -146,23 +230,4 @@ private static Polygon BuildStarPolygon(int vertexCount, double radius, double c Polygon polygon = [contour]; return polygon; } - - private static PathsD BuildClipperPaths(Polygon polygon) - { - PathsD paths = new(polygon.Count); - for (int i = 0; i < polygon.Count; i++) - { - Contour contour = polygon[i]; - PathD path = new(contour.Count); - for (int j = 0; j < contour.Count; j++) - { - Vertex vertex = contour[j]; - path.Add(new PointD(vertex.X, vertex.Y)); - } - - paths.Add(path); - } - - return paths; - } } diff --git a/tests/PolygonClipper.Benchmarks/StrokeBenches.cs b/tests/PolygonClipper.Benchmarks/StrokeBenches.cs index d85a628..e42842e 100644 --- a/tests/PolygonClipper.Benchmarks/StrokeBenches.cs +++ b/tests/PolygonClipper.Benchmarks/StrokeBenches.cs @@ -16,20 +16,20 @@ .NET SDK 11.0.100-preview.7.26381.103 Job=ShortRun IterationCount=3 LaunchCount=1 WarmupCount=3 -| Method | VertexCount | Mean | Error | StdDev | Op/s | Ratio | RatioSD | Gen0 | Gen1 | Gen2 | Allocated | Alloc Ratio | -|------------------------------------ |------------ |----------------:|--------------:|--------------:|------------:|------:|--------:|----------:|----------:|----------:|------------:|------------:| -| PolygonStrokerProcessPolygonAndClip | 101 | 86.35 us | 10.28 us | 0.564 us | 11,581.2627 | 0.01 | 0.00 | 8.7891 | - | - | 144.85 KB | 0.08 | -| Clipper2InflatePaths | 101 | 6,711.66 us | 6,421.82 us | 352.002 us | 148.9944 | 1.00 | 0.06 | 117.1875 | 117.1875 | 117.1875 | 1804.44 KB | 1.00 | -| | | | | | | | | | | | | | -| PolygonStrokerProcessPolygonAndClip | 301 | 263.81 us | 58.59 us | 3.211 us | 3,790.6037 | 0.004 | 0.00 | 27.3438 | 13.1836 | - | 448.83 KB | 0.07 | -| Clipper2InflatePaths | 301 | 66,415.27 us | 48,388.21 us | 2,652.321 us | 15.0568 | 1.001 | 0.05 | 625.0000 | 500.0000 | 500.0000 | 6144.33 KB | 1.00 | -| | | | | | | | | | | | | | -| PolygonStrokerProcessPolygonAndClip | 1001 | 1,199.12 us | 178.09 us | 9.762 us | 833.9431 | 0.000 | 0.00 | 498.0469 | 498.0469 | 498.0469 | 1921.08 KB | 0.06 | -| Clipper2InflatePaths | 1001 | 2,556,662.97 us | 375,556.20 us | 20,585.503 us | 0.3911 | 1.000 | 0.01 | 3000.0000 | 2000.0000 | 2000.0000 | 32250.45 KB | 1.00 | +| Method | ToothCount | Mean | Error | StdDev | Op/s | Ratio | RatioSD | Gen0 | Gen1 | Gen2 | Allocated | Alloc Ratio | +|--------------- |----------- |-----------:|------------:|----------:|--------:|------:|--------:|----------:|----------:|----------:|------------:|------------:| +| Stroke | 101 | 3.908 ms | 0.1493 ms | 0.0082 ms | 255.888 | 1.41 | 0.05 | 7.8125 | - | - | 166.28 KB | 0.18 | +| Clipper2Stroke | 101 | 2.780 ms | 1.9662 ms | 0.1078 ms | 359.756 | 1.00 | 0.05 | 54.6875 | 31.2500 | - | 943.66 KB | 1.00 | +| | | | | | | | | | | | | | +| Stroke | 301 | 32.695 ms | 33.5114 ms | 1.8369 ms | 30.586 | 1.16 | 0.06 | - | - | - | 487.37 KB | 0.18 | +| Clipper2Stroke | 301 | 28.300 ms | 5.9455 ms | 0.3259 ms | 35.335 | 1.00 | 0.01 | 187.5000 | 125.0000 | 31.2500 | 2700.68 KB | 1.00 | +| | | | | | | | | | | | | | +| Stroke | 1001 | 354.823 ms | 29.7121 ms | 1.6286 ms | 2.818 | 0.38 | 0.00 | 1000.0000 | 1000.0000 | 1000.0000 | 20570.89 KB | 1.36 | +| Clipper2Stroke | 1001 | 934.864 ms | 134.0522 ms | 7.3479 ms | 1.070 | 1.00 | 0.01 | 1000.0000 | 1000.0000 | 1000.0000 | 15092.64 KB | 1.00 | */ /// -/// Benchmarks stroke generation and clipping against Clipper2 path inflation. +/// Compares resolved strokes of closed gear contours. /// [MemoryDiagnoser] [OperationsPerSecond] @@ -41,35 +41,55 @@ public class StrokeBenches private PathsD clipperPaths; private StrokeOptions strokeOptions; + /// + /// Gets or sets the number of teeth per gear. Each contour has twice this many vertices. + /// [Params(101, 301, 1001)] - public int VertexCount { get; set; } + public int ToothCount { get; set; } + /// + /// Builds the input geometry for both engines. + /// [GlobalSetup] public void Setup() { - this.polygon = BuildCompoundGearPolygon(this.VertexCount); - this.clipperPaths = BuildClipperPaths(this.polygon); + this.polygon = BuildCompoundGearPolygon(this.ToothCount); + this.clipperPaths = BenchmarkGeometry.ToPaths(this.polygon); this.strokeOptions = new StrokeOptions() { LineJoin = LineJoin.Round, - LineCap = LineCap.Round, + NormalizeOutput = true, }; } + /// + /// Strokes both closed gears and resolves overlaps. + /// + /// The resolved stroke polygon. [Benchmark] - public Polygon PolygonStrokerProcessPolygonAndClip() + public Polygon Stroke() => PolygonStroker.Stroke(this.polygon, StrokeWidth, this.strokeOptions); + /// + /// Strokes the same closed gears with Clipper2 and the same arc error. + /// + /// The resolved stroke paths. [Benchmark(Baseline = true)] - public PathsD Clipper2InflatePaths() + public object Clipper2Stroke() => Clipper.InflatePaths( this.clipperPaths, StrokeWidth * 0.5D, JoinType.Round, - EndType.Round, + EndType.Joined, 4D, - ClipperPrecision); - + ClipperPrecision, + arcTolerance: 0.125D); + + /// + /// Builds two closed gear contours with opposite directions. + /// + /// The number of teeth in each gear. + /// The two source contours. private static Polygon BuildCompoundGearPolygon(int toothCount) { if (toothCount < 3) @@ -82,6 +102,16 @@ private static Polygon BuildCompoundGearPolygon(int toothCount) return [outer, inner]; } + /// + /// Builds a gear by alternating the tip and root radii. + /// + /// The number of teeth. + /// The radius of each tooth tip. + /// The radius of each tooth root. + /// The center X coordinate. + /// The center Y coordinate. + /// Whether vertices run clockwise. + /// The closed gear contour. private static Contour BuildGearContour( int toothCount, double outerRadius, @@ -113,23 +143,4 @@ private static Contour BuildGearContour( return contour; } - - private static PathsD BuildClipperPaths(Polygon polygon) - { - PathsD paths = new(polygon.Count); - for (int i = 0; i < polygon.Count; i++) - { - Contour contour = polygon[i]; - PathD path = new(contour.Count); - for (int j = 0; j < contour.Count; j++) - { - Vertex vertex = contour[j]; - path.Add(new PointD(vertex.X, vertex.Y)); - } - - paths.Add(path); - } - - return paths; - } } diff --git a/tests/PolygonClipper.Tests/BufferTests.cs b/tests/PolygonClipper.Tests/BufferTests.cs new file mode 100644 index 0000000..17f2a5c --- /dev/null +++ b/tests/PolygonClipper.Tests/BufferTests.cs @@ -0,0 +1,83 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +namespace SixLabors.PolygonClipper.Tests; + +/// +/// Checks typed scratch storage and pooled buffer allocations. +/// +public class BufferTests +{ + /// + /// Checks the requested span length and writable vertex storage. + /// + /// The requested number of vertices. + [Theory] + [InlineData(0)] + [InlineData(1)] + [InlineData(17)] + public void GetSpan_ReturnsRequestedElements(int length) + { + using Buffer buffer = new(length); + Span span = buffer.GetSpan(); + Assert.Equal(length, span.Length); + for (int i = 0; i < span.Length; i++) + { + span[i] = new Vertex(i, -i); + } + + for (int i = 0; i < span.Length; i++) + { + Assert.Equal(new Vertex(i, -i), buffer.GetSpan()[i]); + } + } + + /// + /// Checks that buffer construction and return allocate no objects after pool warmup. + /// + [Fact] + public void RentAndReturn_WarmedPool_DoesNotAllocate() + { + // Warm both element types and the thread-local pool before measuring. + for (int i = 0; i < 256; i++) + { + using Buffer integers = new(17); + using Buffer vertices = new(17); + integers.GetSpan()[0] = i; + vertices.GetSpan()[0] = new Vertex(i); + } + + int sum = 0; + long before = GC.GetAllocatedBytesForCurrentThread(); + for (int i = 0; i < 1000; i++) + { + using Buffer integers = new(17); + using Buffer vertices = new(17); + integers.GetSpan()[0] = i; + vertices.GetSpan()[0] = new Vertex(i); + sum += integers.GetSpan()[0] + (int)vertices.GetSpan()[0].X; + } + + long allocated = GC.GetAllocatedBytesForCurrentThread() - before; + Assert.Equal(999000, sum); + Assert.Equal(0, allocated); + } + + /// + /// Checks that disposing twice does not return the same array twice. + /// + [Fact] + public void Dispose_CalledTwice_ReturnsArrayOnce() + { + Buffer buffer = new(17); + buffer.Dispose(); + buffer.Dispose(); + + using Buffer first = new(17); + using Buffer second = new(17); + first.GetSpan()[0] = 1; + second.GetSpan()[0] = 2; + Assert.Equal(1, first.GetSpan()[0]); + Assert.Equal(2, second.GetSpan()[0]); + } +} diff --git a/tests/PolygonClipper.Tests/QueueEntryComparerTests.cs b/tests/PolygonClipper.Tests/QueueEntryComparerTests.cs new file mode 100644 index 0000000..21d35ef --- /dev/null +++ b/tests/PolygonClipper.Tests/QueueEntryComparerTests.cs @@ -0,0 +1,80 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +namespace SixLabors.PolygonClipper.Tests; + +/// +/// Checks endpoint ordering through the value-type heap comparer. +/// +public class QueueEntryComparerTests +{ + /// + /// Checks point, interval, version and endpoint order with both heap entry paths. + /// + /// Whether to build the heap from its shared backing list. + [Theory] + [InlineData(false)] + [InlineData(true)] + public void Queue_OrdersAllEndpointKeys(bool heapify) + { + QueueEntry[] expected = + [ + CreateEntry(new Vertex(-1, 5), 4, 3, true), + CreateEntry(new Vertex(0, -1), 4, 3, true), + CreateEntry(new Vertex(0, 0), 0, 3, true), + CreateEntry(new Vertex(0, 0), 1, 0, true), + CreateEntry(new Vertex(0, 0), 1, 1, false), + CreateEntry(new Vertex(0, 0), 1, 1, true), + CreateEntry(new Vertex(1, -5), 0, 0, false) + ]; + + List storage = []; + StablePriorityQueue queue = new(default(QueueEntryComparer), storage); + int[] insertionOrder = [6, 3, 0, 4, 2, 1, 5]; + foreach (int index in insertionOrder) + { + if (heapify) + { + storage.Add(expected[index]); + } + else + { + queue.Enqueue(expected[index]); + } + } + + if (heapify) + { + queue.Heapify(); + } + + foreach (QueueEntry entry in expected) + { + QueueEntry actual = queue.Dequeue(); + Assert.Equal(entry.Point, actual.Point); + Assert.Equal(entry.EdgeIndex, actual.EdgeIndex); + Assert.Equal(entry.Version, actual.Version); + Assert.Equal(entry.IsStart, actual.IsStart); + } + + Assert.Equal(0, queue.Count); + Assert.Equal(0, queue.Comparer.Compare(expected[0], expected[0])); + } + + /// + /// Creates a queued endpoint from an initialized interval. + /// + /// The queued point. + /// The source interval index. + /// The interval version. + /// Whether this endpoint starts the interval. + /// The queued endpoint. + private static QueueEntry CreateEntry(Vertex point, int index, int version, bool isStart) + { + Vertex end = new(point.X + 1, point.Y); + SweepEvent edge = new(point, true, new SweepEvent(end, false)); + edge.InitializeInterval(point, end, index, default); + edge.Version = version; + return new QueueEntry(point, edge, isStart); + } +} From 0fd1130c976a3d343963410b7d63efce5b451771 Mon Sep 17 00:00:00 2001 From: James Jackson-South Date: Mon, 2 Nov 2026 15:33:21 +1000 Subject: [PATCH 21/24] Optimize offsets and output assembly and expose struct enumerators --- src/PolygonClipper/Contour.cs | 22 ++- src/PolygonClipper/Polygon.cs | 8 +- src/PolygonClipper/PolygonClipper.cs | 29 ++-- src/PolygonClipper/PolygonOffsetter.cs | 73 +++++++++- src/PolygonClipper/PolygonStroker.cs | 21 ++- tests/PolygonClipper.Benchmarks/Benches.cs | 40 +++--- .../NormalizationBenches.cs | 22 +-- .../OffsetBenches.cs | 130 +++++++++--------- .../OpenClippingBenches.cs | 54 ++++---- .../StarBooleanBenches.cs | 56 ++++---- .../StrokeBenches.cs | 14 +- .../PolygonClipper.Tests/EnumerationTests.cs | 124 +++++++++++++++++ .../PolygonOffsetTests.cs | 60 ++++++++ .../PolygonStrokerTests.cs | 44 ++++++ tests/PolygonClipper.Tests/PolygonTests.cs | 62 +++++++++ 15 files changed, 579 insertions(+), 180 deletions(-) create mode 100644 tests/PolygonClipper.Tests/EnumerationTests.cs diff --git a/src/PolygonClipper/Contour.cs b/src/PolygonClipper/Contour.cs index 344086d..86a0668 100644 --- a/src/PolygonClipper/Contour.cs +++ b/src/PolygonClipper/Contour.cs @@ -178,6 +178,20 @@ public void Reverse() this.cachedCounterClockwise = !this.cachedCounterClockwise; } + /// + /// Moves the selected vertex to the start without changing the cyclic order. + /// + /// The existing vertex that will become the first vertex. + internal void RotateVertices(int startIndex) + { + // Three reversals rotate the existing storage without allocating a copy. + // Rotation preserves the closed edges and any cached orientation. + Span points = CollectionsMarshal.AsSpan(this.vertices); + points[..startIndex].Reverse(); + points[startIndex..].Reverse(); + points.Reverse(); + } + /// /// Sets the contour to clockwise orientation. /// @@ -321,8 +335,14 @@ public Contour DeepClone() return clone; } + /// + /// Returns an enumerator that visits the stored vertices in order. + /// + /// The vertex enumerator. + public List.Enumerator GetEnumerator() => this.vertices.GetEnumerator(); + /// - public IEnumerator GetEnumerator() + IEnumerator IEnumerable.GetEnumerator() => ((IEnumerable)this.vertices).GetEnumerator(); /// diff --git a/src/PolygonClipper/Polygon.cs b/src/PolygonClipper/Polygon.cs index f7cf60e..93a438c 100644 --- a/src/PolygonClipper/Polygon.cs +++ b/src/PolygonClipper/Polygon.cs @@ -164,8 +164,14 @@ public Polygon DeepClone() return clone; } + /// + /// Returns an enumerator that visits the stored contours in order. + /// + /// The contour enumerator. + public List.Enumerator GetEnumerator() => this.contours.GetEnumerator(); + /// - public IEnumerator GetEnumerator() + IEnumerator IEnumerable.GetEnumerator() => ((IEnumerable)this.contours).GetEnumerator(); /// diff --git a/src/PolygonClipper/PolygonClipper.cs b/src/PolygonClipper/PolygonClipper.cs index 1d3d623..eb85764 100644 --- a/src/PolygonClipper/PolygonClipper.cs +++ b/src/PolygonClipper/PolygonClipper.cs @@ -580,11 +580,6 @@ private Polygon RunSweep(Box2 subjectBounds, Box2 clipBounds) for (int i = 0; i < result.Count; i++) { Contour contour = result[i]; - if (contour.Count > 1 && contour[0] == contour[^1]) - { - contour.RemoveVertexAt(contour.Count - 1); - } - if ((contour.Depth & 1) == 0) { contour.SetCounterClockwise(); @@ -1299,6 +1294,8 @@ private Polygon ConnectEdges(SweepEventPoolList resultEvents) // This replaces repeated list growth, clearing and copying for large contours. using Buffer vertexBuffer = new((resultEvents.Count / 2) + 1); Span vertices = vertexBuffer.GetSpan(); + int lastExterior = -1; + bool requiresGrouping = false; for (int i = 0; i < resultEvents.Count; i++) { if (processed[i]) @@ -1338,8 +1335,22 @@ private Polygon ConnectEdges(SweepEventPoolList resultEvents) } while (true); - Contour contour = this.InitializeContourFromContext(resultEvents[i], result, contourId, vertexCount); - for (int j = 0; j < vertexCount; j++) + // The trace includes its repeated closing vertex. Do not allocate a + // slot for that vertex in every result contour and remove it later. + int count = vertices[vertexCount - 1] == initial ? vertexCount - 1 : vertexCount; + Contour contour = this.InitializeContourFromContext(resultEvents[i], result, contourId, count); + if (contour.ParentIndex is int parent) + { + // Hole indices are appended in discovery order. The result is + // already grouped if each hole follows the latest exterior. + requiresGrouping |= parent != lastExterior; + } + else + { + lastExterior = contourId; + } + + for (int j = 0; j < count; j++) { contour.Add(vertices[j]); } @@ -1347,7 +1358,7 @@ private Polygon ConnectEdges(SweepEventPoolList resultEvents) result.Add(contour); } - if (this.contourOutput == ContourOutput.Nested) + if (this.contourOutput == ContourOutput.Nested || !requiresGrouping) { return result; } @@ -1490,7 +1501,7 @@ private static void MarkProcessed(SweepEvent sweepEvent, Span processed, i /// The current sweep event. /// The collection of contours processed so far. /// The ID for the new contour. - /// The number of traced vertices, including the closing vertex. + /// The number of stored vertices, without a repeated closing vertex. /// The initialized . private Contour InitializeContourFromContext(SweepEvent sweepEvent, Polygon polygon, int contourId, int vertexCount) { diff --git a/src/PolygonClipper/PolygonOffsetter.cs b/src/PolygonClipper/PolygonOffsetter.cs index b5fe15e..a88d521 100644 --- a/src/PolygonClipper/PolygonOffsetter.cs +++ b/src/PolygonClipper/PolygonOffsetter.cs @@ -28,9 +28,9 @@ public static Polygon Offset(Polygon polygon, double delta, FillRule fillRule, O Guard.NotNull(options, nameof(options)); Guard.MustBeBetweenOrEqualTo(delta, double.MinValue, double.MaxValue, nameof(delta)); - foreach (Contour contour in polygon) + for (int i = 0; i < polygon.Count; i++) { - Guard.IsTrue(contour.IsClosed, nameof(polygon), "Offset requires closed contours. Use Stroke for open paths."); + Guard.IsTrue(polygon[i].IsClosed, nameof(polygon), "Offset requires closed contours. Use Stroke for open paths."); } // Resolve the requested filled area before outlining it. Raw overlaps and self-crossings @@ -48,8 +48,9 @@ public static Polygon Offset(Polygon polygon, double delta, FillRule fillRule, O } Polygon combined = new(area.Count); - foreach (Contour exterior in area) + for (int contourIndex = 0; contourIndex < area.Count; contourIndex++) { + Contour exterior = area[contourIndex]; if ((exterior.Depth & 1) != 0) { continue; @@ -62,9 +63,9 @@ public static Polygon Offset(Polygon polygon, double delta, FillRule fillRule, O } Polygon offset = OffsetComponent(component, delta, options); - foreach (Contour boundary in offset) + for (int i = 0; i < offset.Count; i++) { - combined.Add(boundary); + combined.Add(offset[i]); } } @@ -116,10 +117,72 @@ private static Polygon OffsetComponent(Polygon component, double delta, OffsetOp Polygon boundaries = PolygonStroker.OffsetBoundaries(component, delta, options); + if (boundaries.Count == 1 && TryGetConvexStart(boundaries[0], out int start)) + { + // A strictly convex counterclockwise walk already bounds exactly the + // Positive-filled result. Match Martinez's leftmost starting vertex + // and orientation without sending this resolved boundary through another sweep. + Contour boundary = boundaries[0]; + if (start != 0) + { + boundary.RotateVertices(start); + } + + boundary.SetCounterClockwise(); + return boundaries; + } + // Source winding is 0 or 1. Band coverage is nonnegative, including overlapping strips. // The displaced walk has source winding plus band coverage for expansion, or minus it // for contraction. Positive filling selects the union or the uncovered source area. // The source walk cancels in both expressions, so it need not enter the final sweep. return PolygonClipper.Normalize(boundaries, FillRule.Positive); } + + /// + /// Checks for a simple, strictly convex counterclockwise walk and finds its first sweep vertex. + /// + /// A closed displaced walk with at least three vertices. + /// The index of the lexicographically smallest vertex. + /// Whether every turn is positive and the edge directions make exactly one full turn. + private static bool TryGetConvexStart(Contour contour, out int start) + { + ReadOnlySpan points = contour.AsVertexSpan(); + Vertex previous = points[^1]; + Vertex current = points[0]; + bool previousUpper = current.Y > previous.Y || (current.Y == previous.Y && current.X > previous.X); + int turns = 0; + start = 0; + for (int i = 0; i < points.Length; i++) + { + Vertex next = points[i + 1 == points.Length ? 0 : i + 1]; + double turn = PolygonUtilities.SignedArea(previous, current, next); + if (!double.IsFinite(current.X) || !double.IsFinite(current.Y) || + !double.IsFinite(turn) || turn <= 0) + { + return false; + } + + // Positive turns restrict each direction change to less than half a turn. + // Crossing from the lower half-plane to the upper half-plane counts a full + // direction wrap. One wrap proves convexity; stars and repeated walks wrap more often. + // Endpoint comparisons classify the half-plane without overflowing edge subtraction. + bool upper = next.Y > current.Y || (next.Y == current.Y && next.X > current.X); + if (!previousUpper && upper && ++turns > 1) + { + return false; + } + + if (SweepEventComparer.Instance.Compare(current, points[start]) < 0) + { + start = i; + } + + previousUpper = upper; + previous = current; + current = next; + } + + return turns == 1; + } } diff --git a/src/PolygonClipper/PolygonStroker.cs b/src/PolygonClipper/PolygonStroker.cs index 9333fd6..86eed4d 100644 --- a/src/PolygonClipper/PolygonStroker.cs +++ b/src/PolygonClipper/PolygonStroker.cs @@ -62,6 +62,10 @@ public sealed class PolygonStroker private double widthEps = 0.5D / 1024D; private int widthSign = 1; + // Width and arc detail stay fixed while a path is outlined. Reuse the same + // angular step without changing the per-arc angle or vertex calculations. + private double arcStep; + // Offsets emit one side and retain overlaps at inner corners until Martinez resolves them. private bool offsetBoundary; @@ -89,6 +93,7 @@ private PolygonStroker(in StrokeOptionsKey key) this.LineCap = key.LineCap; this.MiterLimit = key.MiterLimit; this.ArcDetailScale = key.ArcDetailScale; + this.SetHalfWidth(this.strokeWidth); } /// @@ -349,9 +354,9 @@ internal static Polygon OffsetBoundaries(Polygon polygon, double delta, OffsetOp stroker.SetHalfWidth(delta); stroker.offsetBoundary = true; Polygon boundaries = new(polygon.Count); - foreach (Contour boundary in polygon) + for (int i = 0; i < polygon.Count; i++) { - stroker.AppendPath(boundary, true, boundaries); + stroker.AppendPath(polygon[i], true, boundaries); } return boundaries; @@ -373,6 +378,10 @@ private void SetHalfWidth(double halfWidth) this.widthAbs = Math.Abs(halfWidth); this.widthSign = halfWidth < 0 ? -1 : 1; this.widthEps = halfWidth / 1024D; + if (this.LineJoin is LineJoin.Round or LineJoin.MiterRound || this.LineCap == LineCap.Round) + { + this.arcStep = Math.Acos(this.widthAbs / (this.widthAbs + (0.125D / this.ArcDetailScale))) * 2D; + } } /// @@ -908,8 +917,8 @@ private void CalcArc(double x, double y, double dx1, double dy1, double dx2, dou double a1 = Math.Atan2(dy1 * this.widthSign, dx1 * this.widthSign); double a2 = Math.Atan2(dy2 * this.widthSign, dx2 * this.widthSign); - // Derive angular step from arc detail scale and stroke radius. - double da = Math.Acos(this.widthAbs / (this.widthAbs + (0.125D / this.ArcDetailScale))) * 2D; + // Reuse the angular step for this width and arc detail. + double da = this.arcStep; this.AddPoint(x + dx1, y + dy1); if (this.widthSign > 0) @@ -1102,7 +1111,7 @@ private void CalcCap(ref StrokeVertexDistance v0, ref StrokeVertexDistance v1, d else { // Round cap emitted as half-circle arc around endpoint. - double da = Math.Acos(this.widthAbs / (this.widthAbs + (0.125D / this.ArcDetailScale))) * 2D; + double da = this.arcStep; int n = (int)(Pi / da); da = Pi / (n + 1); @@ -1292,7 +1301,7 @@ private Contour GeneratePointCap(double x, double y) if (this.LineCap == LineCap.Round) { // Emit a full circle when a contour collapses to a point. - double da = Math.Acos(this.widthAbs / (this.widthAbs + (0.125D / this.ArcDetailScale))) * 2D; + double da = this.arcStep; int n = Math.Max(4, (int)(PiMul2 / da)); double angleStep = PiMul2 / n; diff --git a/tests/PolygonClipper.Benchmarks/Benches.cs b/tests/PolygonClipper.Benchmarks/Benches.cs index 9bf03e6..49781e0 100644 --- a/tests/PolygonClipper.Benchmarks/Benches.cs +++ b/tests/PolygonClipper.Benchmarks/Benches.cs @@ -18,25 +18,25 @@ .NET SDK 11.0.100-preview.7.26381.103 Job=ShortRun IterationCount=3 LaunchCount=1 WarmupCount=3 -| Method | File | FillRule | Mean | Error | StdDev | Op/s | Ratio | RatioSD | Gen0 | Gen1 | Gen2 | Allocated | Alloc Ratio | -|-------------- |--------------------- |--------- |--------------:|---------------:|------------:|-----------:|------:|--------:|---------:|---------:|--------:|----------:|------------:| -| Union | asia.geojson | EvenOdd | 10,873.490 us | 2,805.9234 us | 153.8021 us | 91.97 | 0.69 | 0.03 | 15.6250 | - | - | 463688 B | 0.07 | -| Clipper2Union | asia.geojson | EvenOdd | 15,826.802 us | 13,961.0760 us | 765.2537 us | 63.18 | 1.00 | 0.06 | 437.5000 | 406.2500 | 93.7500 | 6613050 B | 1.00 | -| | | | | | | | | | | | | | | -| Union | asia.geojson | NonZero | 11,579.924 us | 8,157.2822 us | 447.1282 us | 86.36 | 0.78 | 0.04 | 15.6250 | - | - | 463688 B | 0.07 | -| Clipper2Union | asia.geojson | NonZero | 14,908.794 us | 11,245.5674 us | 616.4075 us | 67.07 | 1.00 | 0.05 | 437.5000 | 406.2500 | 93.7500 | 6613050 B | 1.00 | -| | | | | | | | | | | | | | | -| Union | hole_hole.geojson | EvenOdd | 5.475 us | 0.3199 us | 0.0175 us | 182,655.67 | 2.18 | 0.02 | 0.0916 | - | - | 1632 B | 0.16 | -| Clipper2Union | hole_hole.geojson | EvenOdd | 2.508 us | 0.4731 us | 0.0259 us | 398,689.33 | 1.00 | 0.01 | 0.5951 | 0.0114 | - | 9992 B | 1.00 | -| | | | | | | | | | | | | | | -| Union | hole_hole.geojson | NonZero | 4.839 us | 0.5636 us | 0.0309 us | 206,639.50 | 2.44 | 0.03 | 0.0458 | - | - | 872 B | 0.12 | -| Clipper2Union | hole_hole.geojson | NonZero | 1.980 us | 0.4235 us | 0.0232 us | 505,151.22 | 1.00 | 0.01 | 0.4463 | 0.0076 | - | 7512 B | 1.00 | -| | | | | | | | | | | | | | | -| Union | state(...)ojson [21] | EvenOdd | 733.801 us | 252.2293 us | 13.8255 us | 1,362.77 | 2.32 | 0.04 | - | - | - | 16136 B | 0.05 | -| Clipper2Union | state(...)ojson [21] | EvenOdd | 315.624 us | 36.5730 us | 2.0047 us | 3,168.33 | 1.00 | 0.01 | 20.5078 | 6.8359 | - | 348984 B | 1.00 | -| | | | | | | | | | | | | | | -| Union | state(...)ojson [21] | NonZero | 737.601 us | 70.9301 us | 3.8879 us | 1,355.75 | 2.36 | 0.07 | - | - | - | 16136 B | 0.05 | -| Clipper2Union | state(...)ojson [21] | NonZero | 312.442 us | 182.0525 us | 9.9789 us | 3,200.59 | 1.00 | 0.04 | 20.5078 | 6.8359 | - | 348984 B | 1.00 | +| Method | File | FillRule | Mean | Error | StdDev | Op/s | Ratio | RatioSD | Gen0 | Gen1 | Gen2 | Allocated | Alloc Ratio | +|-------------- |--------------------- |--------- |--------------:|---------------:|--------------:|-----------:|------:|--------:|---------:|---------:|---------:|----------:|------------:| +| Union | asia.geojson | EvenOdd | 10,308.052 us | 2,417.9597 us | 132.5365 us | 97.01 | 0.70 | 0.03 | 15.6250 | - | - | 455752 B | 0.07 | +| Clipper2Union | asia.geojson | EvenOdd | 14,730.047 us | 13,378.4588 us | 733.3185 us | 67.89 | 1.00 | 0.06 | 484.3750 | 468.7500 | 140.6250 | 6613312 B | 1.00 | +| | | | | | | | | | | | | | | +| Union | asia.geojson | NonZero | 10,082.858 us | 2,377.1639 us | 130.3004 us | 99.18 | 0.67 | 0.14 | 15.6250 | - | - | 455752 B | 0.07 | +| Clipper2Union | asia.geojson | NonZero | 15,738.498 us | 64,525.5472 us | 3,536.8630 us | 63.54 | 1.04 | 0.30 | 375.0000 | 343.7500 | 187.5000 | 6613021 B | 1.00 | +| | | | | | | | | | | | | | | +| Union | hole_hole.geojson | EvenOdd | 5.080 us | 2.2882 us | 0.1254 us | 196,852.80 | 1.98 | 0.07 | 0.0763 | - | - | 1304 B | 0.13 | +| Clipper2Union | hole_hole.geojson | EvenOdd | 2.562 us | 1.3565 us | 0.0744 us | 390,384.23 | 1.00 | 0.04 | 0.5951 | 0.0114 | - | 9992 B | 1.00 | +| | | | | | | | | | | | | | | +| Union | hole_hole.geojson | NonZero | 4.533 us | 2.4151 us | 0.1324 us | 220,607.24 | 2.16 | 0.07 | 0.0305 | - | - | 616 B | 0.08 | +| Clipper2Union | hole_hole.geojson | NonZero | 2.095 us | 0.8690 us | 0.0476 us | 477,409.56 | 1.00 | 0.03 | 0.4463 | 0.0076 | - | 7512 B | 1.00 | +| | | | | | | | | | | | | | | +| Union | state(...)ojson [21] | EvenOdd | 703.498 us | 382.3907 us | 20.9601 us | 1,421.47 | 2.31 | 0.10 | - | - | - | 15826 B | 0.05 | +| Clipper2Union | state(...)ojson [21] | EvenOdd | 304.315 us | 215.0055 us | 11.7852 us | 3,286.06 | 1.00 | 0.05 | 20.5078 | 9.7656 | - | 348984 B | 1.00 | +| | | | | | | | | | | | | | | +| Union | state(...)ojson [21] | NonZero | 678.031 us | 291.4692 us | 15.9764 us | 1,474.86 | 2.25 | 0.09 | - | - | - | 15826 B | 0.05 | +| Clipper2Union | state(...)ojson [21] | NonZero | 301.061 us | 228.4132 us | 12.5201 us | 3,321.59 | 1.00 | 0.05 | 20.5078 | 9.7656 | - | 348984 B | 1.00 | */ /// @@ -91,7 +91,7 @@ public void Setup() /// /// The resolved contour tree. [Benchmark(Baseline = true)] - public object Clipper2Union() + public PolyTreeD Clipper2Union() { ClipperD clipper = new(ClipperPrecision) { diff --git a/tests/PolygonClipper.Benchmarks/NormalizationBenches.cs b/tests/PolygonClipper.Benchmarks/NormalizationBenches.cs index d9e5654..34724d0 100644 --- a/tests/PolygonClipper.Benchmarks/NormalizationBenches.cs +++ b/tests/PolygonClipper.Benchmarks/NormalizationBenches.cs @@ -16,16 +16,16 @@ .NET SDK 11.0.100-preview.7.26381.103 Job=ShortRun IterationCount=3 LaunchCount=1 WarmupCount=3 -| Method | VertexCount | Mean | Error | StdDev | Op/s | Ratio | RatioSD | Gen0 | Gen1 | Gen2 | Allocated | Alloc Ratio | -|------------------ |------------ |-------------:|------------:|------------:|----------:|------:|--------:|----------:|----------:|----------:|-----------:|------------:| -| Normalize | 101 | 1,695.4 us | 251.4 us | 13.78 us | 589.827 | 3.68 | 0.10 | - | - | - | 3.41 KB | 0.02 | -| Clipper2Normalize | 101 | 460.9 us | 253.8 us | 13.91 us | 2,169.784 | 1.00 | 0.04 | 12.2070 | 3.9063 | - | 205.76 KB | 1.00 | -| | | | | | | | | | | | | | -| Normalize | 301 | 16,385.1 us | 5,075.3 us | 278.19 us | 61.031 | 2.80 | 0.04 | - | - | - | 9.66 KB | 0.004 | -| Clipper2Normalize | 301 | 5,860.5 us | 765.2 us | 41.94 us | 170.633 | 1.00 | 0.01 | 492.1875 | 492.1875 | 492.1875 | 2297.18 KB | 1.000 | -| | | | | | | | | | | | | | -| Normalize | 1001 | 197,339.6 us | 76,838.2 us | 4,211.76 us | 5.067 | 2.51 | 0.09 | - | - | - | 31.54 KB | 0.002 | -| Clipper2Normalize | 1001 | 78,746.5 us | 55,733.0 us | 3,054.92 us | 12.699 | 1.00 | 0.05 | 1857.1429 | 1857.1429 | 1857.1429 | 17115.1 KB | 1.000 | +| Method | VertexCount | Mean | Error | StdDev | Op/s | Ratio | RatioSD | Gen0 | Gen1 | Gen2 | Allocated | Alloc Ratio | +|------------------ |------------ |-------------:|--------------:|------------:|----------:|------:|--------:|----------:|----------:|----------:|------------:|------------:| +| Normalize | 101 | 1,702.8 us | 124.77 us | 6.84 us | 587.273 | 3.73 | 0.02 | - | - | - | 3.41 KB | 0.02 | +| Clipper2Normalize | 101 | 456.9 us | 53.14 us | 2.91 us | 2,188.465 | 1.00 | 0.01 | 12.2070 | 3.9063 | - | 205.76 KB | 1.00 | +| | | | | | | | | | | | | | +| Normalize | 301 | 15,951.5 us | 452.26 us | 24.79 us | 62.690 | 2.72 | 0.02 | - | - | - | 10.46 KB | 0.005 | +| Clipper2Normalize | 301 | 5,870.9 us | 710.59 us | 38.95 us | 170.333 | 1.00 | 0.01 | 492.1875 | 492.1875 | 492.1875 | 2297.18 KB | 1.000 | +| | | | | | | | | | | | | | +| Normalize | 1001 | 199,441.3 us | 112,517.17 us | 6,167.45 us | 5.014 | 2.31 | 0.10 | - | - | - | 48.88 KB | 0.003 | +| Clipper2Normalize | 1001 | 86,335.0 us | 57,758.23 us | 3,165.92 us | 11.583 | 1.00 | 0.05 | 1833.3333 | 1833.3333 | 1833.3333 | 17114.61 KB | 1.000 | */ /// @@ -68,7 +68,7 @@ public Polygon Normalize() /// /// The resolved contour tree. [Benchmark(Baseline = true)] - public object Clipper2Normalize() + public PolyTreeD Clipper2Normalize() { ClipperD clipper = new(ClipperPrecision) { diff --git a/tests/PolygonClipper.Benchmarks/OffsetBenches.cs b/tests/PolygonClipper.Benchmarks/OffsetBenches.cs index 1d6c157..909c8ef 100644 --- a/tests/PolygonClipper.Benchmarks/OffsetBenches.cs +++ b/tests/PolygonClipper.Benchmarks/OffsetBenches.cs @@ -16,70 +16,70 @@ .NET SDK 11.0.100-preview.7.26381.103 Job=ShortRun IterationCount=3 LaunchCount=1 WarmupCount=3 -| Method | VertexCount | Delta | Mean | Error | StdDev | Op/s | Ratio | RatioSD | Gen0 | Gen1 | Gen2 | Allocated | Alloc Ratio | -|--------------- |------------ |------ |---------------:|----------------:|---------------:|------------:|------:|--------:|----------:|----------:|----------:|-----------:|------------:| -| Offset | 16 | -1200 | 2.468 us | 0.3326 us | 0.0182 us | 405,178.385 | 0.08 | 0.00 | 0.0343 | - | - | 616 B | 0.03 | -| Clipper2Offset | 16 | -1200 | 29.521 us | 4.0812 us | 0.2237 us | 33,874.633 | 1.00 | 0.01 | 1.3733 | 0.0305 | - | 23376 B | 1.00 | -| | | | | | | | | | | | | | | -| Offset | 16 | -900 | 57.562 us | 31.7352 us | 1.7395 us | 17,372.449 | 4.41 | 0.40 | 0.1831 | - | - | 3184 B | 0.15 | -| Clipper2Offset | 16 | -900 | 13.131 us | 24.1340 us | 1.3229 us | 76,157.684 | 1.01 | 0.12 | 1.2207 | 0.0305 | - | 20664 B | 1.00 | -| | | | | | | | | | | | | | | -| Offset | 16 | -100 | 6.204 us | 4.0512 us | 0.2221 us | 161,177.093 | 1.58 | 0.09 | 0.0916 | - | - | 1600 B | 0.13 | -| Clipper2Offset | 16 | -100 | 3.924 us | 4.0858 us | 0.2240 us | 254,843.936 | 1.00 | 0.07 | 0.7248 | 0.0114 | - | 12176 B | 1.00 | -| | | | | | | | | | | | | | | -| Offset | 16 | -1 | 6.655 us | 1.1062 us | 0.0606 us | 150,259.247 | 1.73 | 0.15 | 0.0916 | - | - | 1600 B | 0.13 | -| Clipper2Offset | 16 | -1 | 3.878 us | 7.2758 us | 0.3988 us | 257,884.953 | 1.01 | 0.13 | 0.7248 | 0.0114 | - | 12176 B | 1.00 | -| | | | | | | | | | | | | | | -| Offset | 16 | 1 | 6.678 us | 2.2652 us | 0.1242 us | 149,753.146 | 4.68 | 0.59 | 0.0916 | - | - | 1600 B | 0.26 | -| Clipper2Offset | 16 | 1 | 1.450 us | 4.1261 us | 0.2262 us | 689,619.764 | 1.02 | 0.19 | 0.3738 | 0.0038 | - | 6264 B | 1.00 | -| | | | | | | | | | | | | | | -| Offset | 16 | 100 | 6.501 us | 4.1664 us | 0.2284 us | 153,826.681 | 5.02 | 0.32 | 0.0916 | - | - | 1600 B | 0.26 | -| Clipper2Offset | 16 | 100 | 1.299 us | 1.5966 us | 0.0875 us | 769,606.026 | 1.00 | 0.08 | 0.3738 | 0.0038 | - | 6264 B | 1.00 | -| | | | | | | | | | | | | | | -| Offset | 16 | 1200 | 6.076 us | 2.4293 us | 0.1332 us | 164,583.210 | 4.76 | 0.10 | 0.0916 | - | - | 1600 B | 0.26 | -| Clipper2Offset | 16 | 1200 | 1.276 us | 0.2702 us | 0.0148 us | 783,515.559 | 1.00 | 0.01 | 0.3738 | 0.0038 | - | 6264 B | 1.00 | -| | | | | | | | | | | | | | | -| Offset | 256 | -1200 | 44.279 us | 3.5438 us | 0.1942 us | 22,584.136 | 0.003 | 0.00 | 0.2441 | - | - | 4457 B | 0.002 | -| Clipper2Offset | 256 | -1200 | 15,788.872 us | 2,011.9164 us | 110.2799 us | 63.336 | 1.000 | 0.01 | 468.7500 | 468.7500 | 468.7500 | 2313486 B | 1.000 | -| | | | | | | | | | | | | | | -| Offset | 256 | -900 | 2,314.089 us | 923.7301 us | 50.6328 us | 432.135 | 3.34 | 0.07 | - | - | - | 37786 B | 0.18 | -| Clipper2Offset | 256 | -900 | 692.685 us | 97.9071 us | 5.3666 us | 1,443.657 | 1.00 | 0.01 | 12.6953 | 3.9063 | - | 214040 B | 1.00 | -| | | | | | | | | | | | | | | -| Offset | 256 | -100 | 99.391 us | 5.6818 us | 0.3114 us | 10,061.287 | 0.80 | 0.01 | 0.7324 | - | - | 13120 B | 0.08 | -| Clipper2Offset | 256 | -100 | 123.854 us | 26.3756 us | 1.4457 us | 8,074.024 | 1.00 | 0.01 | 9.6436 | 1.9531 | - | 162640 B | 1.00 | -| | | | | | | | | | | | | | | -| Offset | 256 | -1 | 100.865 us | 5.5870 us | 0.3062 us | 9,914.212 | 1.71 | 0.01 | 0.7324 | - | - | 13120 B | 0.09 | -| Clipper2Offset | 256 | -1 | 59.068 us | 6.9002 us | 0.3782 us | 16,929.521 | 1.00 | 0.01 | 8.9722 | 1.9531 | - | 150536 B | 1.00 | -| | | | | | | | | | | | | | | -| Offset | 256 | 1 | 103.380 us | 4.4748 us | 0.2453 us | 9,673.071 | 7.19 | 0.12 | 0.7324 | - | - | 13120 B | 0.19 | -| Clipper2Offset | 256 | 1 | 14.380 us | 5.0707 us | 0.2779 us | 69,540.046 | 1.00 | 0.02 | 4.0588 | 0.4272 | - | 67896 B | 1.00 | -| | | | | | | | | | | | | | | -| Offset | 256 | 100 | 100.712 us | 11.0057 us | 0.6033 us | 9,929.330 | 6.95 | 0.12 | 0.7324 | - | - | 13120 B | 0.19 | -| Clipper2Offset | 256 | 100 | 14.492 us | 4.9685 us | 0.2723 us | 69,003.320 | 1.00 | 0.02 | 4.0588 | 0.4272 | - | 67896 B | 1.00 | -| | | | | | | | | | | | | | | -| Offset | 256 | 1200 | 102.491 us | 16.3031 us | 0.8936 us | 9,757.000 | 7.05 | 0.07 | 0.7324 | - | - | 13120 B | 0.19 | -| Clipper2Offset | 256 | 1200 | 14.531 us | 2.2596 us | 0.1239 us | 68,817.537 | 1.00 | 0.01 | 4.0588 | 0.4272 | - | 67896 B | 1.00 | -| | | | | | | | | | | | | | | -| Offset | 1024 | -1200 | 195.474 us | 171.1595 us | 9.3818 us | 5,115.769 | 0.001 | 0.00 | 0.9766 | - | - | 16744 B | 0.000 | -| Clipper2Offset | 1024 | -1200 | 323,053.700 us | 309,818.4386 us | 16,982.1941 us | 3.095 | 1.002 | 0.06 | 2000.0000 | 2000.0000 | 2000.0000 | 34406024 B | 1.000 | -| | | | | | | | | | | | | | | -| Offset | 1024 | -900 | 11,477.235 us | 8,978.6788 us | 492.1517 us | 87.129 | 0.94 | 0.05 | - | - | - | 148336 B | 0.19 | -| Clipper2Offset | 1024 | -900 | 12,293.630 us | 11,688.8019 us | 640.7027 us | 81.343 | 1.00 | 0.06 | 46.8750 | 15.6250 | - | 790344 B | 1.00 | -| | | | | | | | | | | | | | | -| Offset | 1024 | -100 | 503.410 us | 373.1325 us | 20.4527 us | 1,986.452 | 0.36 | 0.02 | 2.9297 | - | - | 50005 B | 0.08 | -| Clipper2Offset | 1024 | -100 | 1,388.242 us | 1,137.2492 us | 62.3365 us | 720.335 | 1.00 | 0.06 | 37.1094 | 11.7188 | - | 643472 B | 1.00 | -| | | | | | | | | | | | | | | -| Offset | 1024 | -1 | 524.284 us | 516.7832 us | 28.3266 us | 1,907.365 | 1.88 | 0.16 | 2.9297 | - | - | 50026 B | 0.08 | -| Clipper2Offset | 1024 | -1 | 279.539 us | 420.7071 us | 23.0604 us | 3,577.313 | 1.00 | 0.10 | 35.1563 | 20.5078 | - | 593456 B | 1.00 | -| | | | | | | | | | | | | | | -| Offset | 1024 | 1 | 542.421 us | 224.6571 us | 12.3142 us | 1,843.586 | 8.87 | 0.46 | 2.9297 | - | - | 50026 B | 0.19 | -| Clipper2Offset | 1024 | 1 | 61.299 us | 61.8332 us | 3.3893 us | 16,313.446 | 1.00 | 0.07 | 15.7471 | 5.7373 | - | 264600 B | 1.00 | -| | | | | | | | | | | | | | | -| Offset | 1024 | 100 | 543.999 us | 637.9292 us | 34.9671 us | 1,838.237 | 7.22 | 1.46 | 2.9297 | - | - | 50026 B | 0.19 | -| Clipper2Offset | 1024 | 100 | 78.080 us | 330.4798 us | 18.1147 us | 12,807.297 | 1.04 | 0.29 | 15.8081 | 5.8594 | - | 264600 B | 1.00 | -| | | | | | | | | | | | | | | -| Offset | 1024 | 1200 | 691.062 us | 587.1478 us | 32.1836 us | 1,447.049 | 9.34 | 1.47 | 2.9297 | - | - | 50026 B | 0.19 | -| Clipper2Offset | 1024 | 1200 | 75.458 us | 228.7613 us | 12.5392 us | 13,252.362 | 1.02 | 0.21 | 15.7471 | 5.7373 | - | 264600 B | 1.00 | +| Method | VertexCount | Delta | Mean | Error | StdDev | Op/s | Ratio | RatioSD | Gen0 | Gen1 | Gen2 | Allocated | Alloc Ratio | +|--------------- |------------ |------ |---------------:|----------------:|--------------:|------------:|------:|--------:|----------:|----------:|----------:|-----------:|------------:| +| Offset | 16 | -1200 | 2.403 us | 0.7705 us | 0.0422 us | 416,069.248 | 0.07 | 0.00 | 0.0305 | - | - | 560 B | 0.02 | +| Clipper2Offset | 16 | -1200 | 36.459 us | 55.4619 us | 3.0401 us | 27,427.985 | 1.00 | 0.10 | 1.3428 | - | - | 23376 B | 1.00 | +| | | | | | | | | | | | | | | +| Offset | 16 | -900 | 56.001 us | 49.8951 us | 2.7349 us | 17,856.887 | 4.20 | 0.80 | 0.1831 | - | - | 3072 B | 0.15 | +| Clipper2Offset | 16 | -900 | 13.825 us | 61.8652 us | 3.3910 us | 72,334.519 | 1.04 | 0.30 | 1.2207 | 0.0305 | - | 20664 B | 1.00 | +| | | | | | | | | | | | | | | +| Offset | 16 | -100 | 3.765 us | 0.5495 us | 0.0301 us | 265,629.040 | 0.98 | 0.03 | 0.0572 | - | - | 984 B | 0.08 | +| Clipper2Offset | 16 | -100 | 3.846 us | 1.9876 us | 0.1089 us | 260,010.493 | 1.00 | 0.03 | 0.7248 | 0.0076 | - | 12176 B | 1.00 | +| | | | | | | | | | | | | | | +| Offset | 16 | -1 | 4.728 us | 5.7869 us | 0.3172 us | 211,520.252 | 1.04 | 0.09 | 0.0572 | - | - | 984 B | 0.08 | +| Clipper2Offset | 16 | -1 | 4.546 us | 6.4522 us | 0.3537 us | 219,990.806 | 1.00 | 0.10 | 0.7248 | 0.0114 | - | 12176 B | 1.00 | +| | | | | | | | | | | | | | | +| Offset | 16 | 1 | 4.026 us | 0.5961 us | 0.0327 us | 248,368.898 | 2.62 | 0.32 | 0.0534 | - | - | 984 B | 0.16 | +| Clipper2Offset | 16 | 1 | 1.558 us | 4.2528 us | 0.2331 us | 641,854.604 | 1.01 | 0.18 | 0.3738 | 0.0038 | - | 6264 B | 1.00 | +| | | | | | | | | | | | | | | +| Offset | 16 | 100 | 4.123 us | 0.4013 us | 0.0220 us | 242,522.207 | 2.87 | 0.02 | 0.0534 | - | - | 984 B | 0.16 | +| Clipper2Offset | 16 | 100 | 1.438 us | 0.1523 us | 0.0083 us | 695,541.890 | 1.00 | 0.01 | 0.3738 | 0.0038 | - | 6264 B | 1.00 | +| | | | | | | | | | | | | | | +| Offset | 16 | 1200 | 4.145 us | 4.5489 us | 0.2493 us | 241,229.810 | 3.02 | 0.19 | 0.0534 | - | - | 984 B | 0.16 | +| Clipper2Offset | 16 | 1200 | 1.372 us | 0.9723 us | 0.0533 us | 728,650.422 | 1.00 | 0.05 | 0.3738 | 0.0038 | - | 6264 B | 1.00 | +| | | | | | | | | | | | | | | +| Offset | 256 | -1200 | 43.989 us | 13.4638 us | 0.7380 us | 22,733.036 | 0.003 | 0.00 | 0.2441 | - | - | 4400 B | 0.002 | +| Clipper2Offset | 256 | -1200 | 16,134.432 us | 2,791.2480 us | 152.9977 us | 61.979 | 1.000 | 0.01 | 468.7500 | 468.7500 | 468.7500 | 2313486 B | 1.000 | +| | | | | | | | | | | | | | | +| Offset | 256 | -900 | 2,361.832 us | 262.1388 us | 14.3687 us | 423.400 | 3.23 | 0.02 | - | - | - | 37632 B | 0.18 | +| Clipper2Offset | 256 | -900 | 732.110 us | 24.1240 us | 1.3223 us | 1,365.916 | 1.00 | 0.00 | 12.6953 | 3.9063 | - | 214040 B | 1.00 | +| | | | | | | | | | | | | | | +| Offset | 256 | -100 | 63.996 us | 19.3250 us | 1.0593 us | 15,625.878 | 0.49 | 0.01 | 0.4883 | - | - | 8664 B | 0.05 | +| Clipper2Offset | 256 | -100 | 130.294 us | 6.0478 us | 0.3315 us | 7,674.949 | 1.00 | 0.00 | 9.5215 | 1.9531 | - | 162640 B | 1.00 | +| | | | | | | | | | | | | | | +| Offset | 256 | -1 | 62.656 us | 3.7711 us | 0.2067 us | 15,960.129 | 0.97 | 0.03 | 0.4883 | - | - | 8664 B | 0.06 | +| Clipper2Offset | 256 | -1 | 64.429 us | 41.1809 us | 2.2573 us | 15,521.011 | 1.00 | 0.04 | 8.9722 | 1.9531 | - | 150536 B | 1.00 | +| | | | | | | | | | | | | | | +| Offset | 256 | 1 | 66.962 us | 9.0239 us | 0.4946 us | 14,933.742 | 4.35 | 0.11 | 0.4883 | - | - | 8664 B | 0.13 | +| Clipper2Offset | 256 | 1 | 15.408 us | 7.8896 us | 0.4325 us | 64,900.325 | 1.00 | 0.03 | 4.0588 | 0.4272 | - | 67896 B | 1.00 | +| | | | | | | | | | | | | | | +| Offset | 256 | 100 | 65.022 us | 4.8034 us | 0.2633 us | 15,379.462 | 3.97 | 0.17 | 0.4883 | - | - | 8664 B | 0.13 | +| Clipper2Offset | 256 | 100 | 16.406 us | 14.6723 us | 0.8042 us | 60,951.676 | 1.00 | 0.06 | 4.0588 | 0.4272 | - | 67896 B | 1.00 | +| | | | | | | | | | | | | | | +| Offset | 256 | 1200 | 73.638 us | 84.0497 us | 4.6070 us | 13,579.929 | 4.24 | 0.56 | 0.4883 | - | - | 8664 B | 0.13 | +| Clipper2Offset | 256 | 1200 | 17.596 us | 47.1671 us | 2.5854 us | 56,831.787 | 1.01 | 0.18 | 4.0588 | 0.4272 | - | 67896 B | 1.00 | +| | | | | | | | | | | | | | | +| Offset | 1024 | -1200 | 209.607 us | 406.6169 us | 22.2880 us | 4,770.836 | 0.001 | 0.00 | 0.9766 | - | - | 16688 B | 0.000 | +| Clipper2Offset | 1024 | -1200 | 328,268.167 us | 142,160.3136 us | 7,792.2865 us | 3.046 | 1.000 | 0.03 | 2000.0000 | 2000.0000 | 2000.0000 | 34406024 B | 1.000 | +| | | | | | | | | | | | | | | +| Offset | 1024 | -900 | 10,390.567 us | 697.6087 us | 38.2383 us | 96.241 | 0.93 | 0.01 | - | - | - | 148224 B | 0.19 | +| Clipper2Offset | 1024 | -900 | 11,164.283 us | 1,175.7563 us | 64.4472 us | 89.571 | 1.00 | 0.01 | 46.8750 | 15.6250 | - | 790344 B | 1.00 | +| | | | | | | | | | | | | | | +| Offset | 1024 | -100 | 276.123 us | 36.4375 us | 1.9973 us | 3,621.579 | 0.20 | 0.00 | 1.9531 | - | - | 33240 B | 0.05 | +| Clipper2Offset | 1024 | -100 | 1,401.647 us | 77.3652 us | 4.2406 us | 713.446 | 1.00 | 0.00 | 37.1094 | 11.7188 | - | 643472 B | 1.00 | +| | | | | | | | | | | | | | | +| Offset | 1024 | -1 | 268.599 us | 27.7142 us | 1.5191 us | 3,723.028 | 0.96 | 0.01 | 1.9531 | - | - | 33240 B | 0.06 | +| Clipper2Offset | 1024 | -1 | 281.066 us | 74.0769 us | 4.0604 us | 3,557.883 | 1.00 | 0.02 | 35.1563 | 20.5078 | - | 593456 B | 1.00 | +| | | | | | | | | | | | | | | +| Offset | 1024 | 1 | 276.471 us | 18.1653 us | 0.9957 us | 3,617.020 | 4.38 | 0.29 | 1.9531 | - | - | 33240 B | 0.13 | +| Clipper2Offset | 1024 | 1 | 63.401 us | 93.7135 us | 5.1368 us | 15,772.592 | 1.00 | 0.10 | 15.8081 | 5.8594 | - | 264600 B | 1.00 | +| | | | | | | | | | | | | | | +| Offset | 1024 | 100 | 284.974 us | 75.0911 us | 4.1160 us | 3,509.086 | 4.90 | 0.06 | 1.9531 | - | - | 33240 B | 0.13 | +| Clipper2Offset | 1024 | 100 | 58.213 us | 5.3678 us | 0.2942 us | 17,178.212 | 1.00 | 0.01 | 15.8081 | 5.8594 | - | 264600 B | 1.00 | +| | | | | | | | | | | | | | | +| Offset | 1024 | 1200 | 284.830 us | 32.9884 us | 1.8082 us | 3,510.863 | 4.79 | 0.05 | 1.9531 | - | - | 33240 B | 0.13 | +| Clipper2Offset | 1024 | 1200 | 59.499 us | 11.5245 us | 0.6317 us | 16,806.922 | 1.00 | 0.01 | 15.8081 | 5.8594 | - | 264600 B | 1.00 | */ /// @@ -139,6 +139,6 @@ public void Setup() /// /// The offset paths. [Benchmark(Baseline = true)] - public object Clipper2Offset() + public PathsD Clipper2Offset() => Clipper.InflatePaths(this.paths, this.Delta, JoinType.Miter, EndType.Polygon, 4, ClipperPrecision); } diff --git a/tests/PolygonClipper.Benchmarks/OpenClippingBenches.cs b/tests/PolygonClipper.Benchmarks/OpenClippingBenches.cs index 279edb0..7434386 100644 --- a/tests/PolygonClipper.Benchmarks/OpenClippingBenches.cs +++ b/tests/PolygonClipper.Benchmarks/OpenClippingBenches.cs @@ -16,31 +16,31 @@ .NET SDK 11.0.100-preview.7.26381.103 Job=ShortRun IterationCount=3 LaunchCount=1 WarmupCount=3 -| Method | PathCount | VerticesPerPath | Transpose | Mean | Error | StdDev | Op/s | Ratio | RatioSD | Gen0 | Gen1 | Gen2 | Allocated | Alloc Ratio | -|--------------------- |---------- |---------------- |---------- |-------------:|-------------:|------------:|----------:|------:|--------:|---------:|---------:|---------:|-----------:|------------:| -| Intersection | 10 | 2 | False | 10.904 us | 9.838 us | 0.5393 us | 91,709.9 | 3.87 | 0.21 | 0.1678 | - | - | 2.84 KB | 0.21 | -| Clipper2Intersection | 10 | 2 | False | 2.823 us | 1.937 us | 0.1062 us | 354,259.3 | 1.00 | 0.05 | 0.8163 | 0.0267 | - | 13.36 KB | 1.00 | -| | | | | | | | | | | | | | | | -| Intersection | 10 | 2 | True | 10.301 us | 2.189 us | 0.1200 us | 97,079.2 | 4.13 | 0.09 | 0.1678 | - | - | 2.84 KB | 0.19 | -| Clipper2Intersection | 10 | 2 | True | 2.495 us | 1.087 us | 0.0596 us | 400,776.5 | 1.00 | 0.03 | 0.9117 | 0.0343 | - | 14.91 KB | 1.00 | -| | | | | | | | | | | | | | | | -| Intersection | 10 | 13 | False | 28.831 us | 1.610 us | 0.0883 us | 34,684.6 | 2.87 | 0.02 | 0.3967 | - | - | 6.94 KB | 0.16 | -| Clipper2Intersection | 10 | 13 | False | 10.062 us | 1.545 us | 0.0847 us | 99,387.5 | 1.00 | 0.01 | 2.5940 | 0.2747 | - | 42.57 KB | 1.00 | -| | | | | | | | | | | | | | | | -| Intersection | 10 | 13 | True | 41.346 us | 18.318 us | 1.0041 us | 24,186.3 | 7.46 | 0.18 | 0.3662 | - | - | 6.94 KB | 0.22 | -| Clipper2Intersection | 10 | 13 | True | 5.542 us | 1.384 us | 0.0758 us | 180,453.8 | 1.00 | 0.02 | 1.9608 | 0.1678 | - | 32.04 KB | 1.00 | -| | | | | | | | | | | | | | | | -| Intersection | 1000 | 2 | False | 1,136.246 us | 158.943 us | 8.7122 us | 880.1 | 5.68 | 0.13 | 15.6250 | 5.8594 | - | 258.07 KB | 0.24 | -| Clipper2Intersection | 1000 | 2 | False | 200.069 us | 93.368 us | 5.1178 us | 4,998.3 | 1.00 | 0.03 | 65.4297 | 50.2930 | - | 1072.85 KB | 1.00 | -| | | | | | | | | | | | | | | | -| Intersection | 1000 | 2 | True | 1,264.030 us | 91.072 us | 4.9920 us | 791.1 | 1.80 | 0.17 | 15.6250 | 5.8594 | - | 258.07 KB | 0.21 | -| Clipper2Intersection | 1000 | 2 | True | 708.218 us | 1,343.360 us | 73.6341 us | 1,412.0 | 1.01 | 0.13 | 76.1719 | 65.4297 | - | 1244.98 KB | 1.00 | -| | | | | | | | | | | | | | | | -| Intersection | 1000 | 13 | False | 4,938.736 us | 178.069 us | 9.7606 us | 202.5 | 1.23 | 0.10 | 31.2500 | 7.8125 | - | 597.91 KB | 0.16 | -| Clipper2Intersection | 1000 | 13 | False | 4,027.525 us | 6,991.955 us | 383.2526 us | 248.3 | 1.01 | 0.11 | 316.4063 | 312.5000 | 109.3750 | 3808.37 KB | 1.00 | -| | | | | | | | | | | | | | | | -| Intersection | 1000 | 13 | True | 5,410.344 us | 3,778.677 us | 207.1221 us | 184.8 | 1.85 | 0.18 | 31.2500 | 7.8125 | - | 597.91 KB | 0.20 | -| Clipper2Intersection | 1000 | 13 | True | 2,948.340 us | 5,395.866 us | 295.7656 us | 339.2 | 1.01 | 0.13 | 234.3750 | 230.4688 | 74.2188 | 2931.89 KB | 1.00 | +| Method | PathCount | VerticesPerPath | Transpose | Mean | Error | StdDev | Op/s | Ratio | RatioSD | Gen0 | Gen1 | Gen2 | Allocated | Alloc Ratio | +|--------------------- |---------- |---------------- |---------- |-------------:|--------------:|------------:|----------:|------:|--------:|---------:|---------:|---------:|-----------:|------------:| +| Intersection | 10 | 2 | False | 9.883 us | 3.8132 us | 0.2090 us | 101,188.0 | 3.92 | 0.09 | 0.1526 | - | - | 2.66 KB | 0.20 | +| Clipper2Intersection | 10 | 2 | False | 2.519 us | 0.6361 us | 0.0349 us | 396,913.1 | 1.00 | 0.02 | 0.8163 | 0.0267 | - | 13.36 KB | 1.00 | +| | | | | | | | | | | | | | | | +| Intersection | 10 | 2 | True | 10.748 us | 2.3662 us | 0.1297 us | 93,036.3 | 4.25 | 0.16 | 0.1526 | - | - | 2.66 KB | 0.18 | +| Clipper2Intersection | 10 | 2 | True | 2.531 us | 1.8811 us | 0.1031 us | 395,167.2 | 1.00 | 0.05 | 0.9117 | 0.0343 | - | 14.91 KB | 1.00 | +| | | | | | | | | | | | | | | | +| Intersection | 10 | 13 | False | 26.421 us | 5.0646 us | 0.2776 us | 37,849.3 | 2.77 | 0.05 | 0.3967 | - | - | 6.76 KB | 0.16 | +| Clipper2Intersection | 10 | 13 | False | 9.543 us | 3.2125 us | 0.1761 us | 104,784.4 | 1.00 | 0.02 | 2.5940 | 0.2747 | - | 42.57 KB | 1.00 | +| | | | | | | | | | | | | | | | +| Intersection | 10 | 13 | True | 33.000 us | 2.9610 us | 0.1623 us | 30,303.4 | 5.75 | 0.19 | 0.3662 | - | - | 6.76 KB | 0.21 | +| Clipper2Intersection | 10 | 13 | True | 5.748 us | 3.9759 us | 0.2179 us | 173,965.4 | 1.00 | 0.05 | 1.9608 | 0.1678 | - | 32.04 KB | 1.00 | +| | | | | | | | | | | | | | | | +| Intersection | 1000 | 2 | False | 1,078.401 us | 254.6082 us | 13.9559 us | 927.3 | 5.15 | 0.08 | 15.6250 | 5.8594 | - | 257.89 KB | 0.24 | +| Clipper2Intersection | 1000 | 2 | False | 209.518 us | 46.4339 us | 2.5452 us | 4,772.9 | 1.00 | 0.01 | 65.4297 | 50.2930 | - | 1072.85 KB | 1.00 | +| | | | | | | | | | | | | | | | +| Intersection | 1000 | 2 | True | 1,251.839 us | 465.4236 us | 25.5114 us | 798.8 | 1.98 | 0.06 | 15.6250 | 5.8594 | - | 257.89 KB | 0.21 | +| Clipper2Intersection | 1000 | 2 | True | 631.272 us | 285.8368 us | 15.6677 us | 1,584.1 | 1.00 | 0.03 | 76.1719 | 65.4297 | - | 1244.98 KB | 1.00 | +| | | | | | | | | | | | | | | | +| Intersection | 1000 | 13 | False | 4,641.406 us | 1,638.6524 us | 89.8201 us | 215.5 | 2.65 | 0.06 | 31.2500 | 7.8125 | - | 597.73 KB | 0.16 | +| Clipper2Intersection | 1000 | 13 | False | 1,751.292 us | 608.8764 us | 33.3746 us | 571.0 | 1.00 | 0.02 | 248.0469 | 246.0938 | 123.0469 | 3808.3 KB | 1.00 | +| | | | | | | | | | | | | | | | +| Intersection | 1000 | 13 | True | 5,604.583 us | 6,479.1650 us | 355.1449 us | 178.4 | 3.65 | 0.26 | 31.2500 | 7.8125 | - | 597.73 KB | 0.20 | +| Clipper2Intersection | 1000 | 13 | True | 1,539.851 us | 1,446.5691 us | 79.2913 us | 649.4 | 1.00 | 0.06 | 166.0156 | 164.0625 | 82.0313 | 2931.87 KB | 1.00 | */ /// @@ -128,14 +128,14 @@ public void Setup() /// /// The open result contours. [Benchmark] - public object Intersection() => PolygonClipper.Intersection(this.subject, this.clip, FillRule.NonZero); + public Polygon Intersection() => PolygonClipper.Intersection(this.subject, this.clip, FillRule.NonZero); /// /// Clips the same original paths with the same closed mask using Clipper2. /// /// The open result paths. [Benchmark(Baseline = true)] - public object Clipper2Intersection() + public PathsD Clipper2Intersection() { ClipperD engine = new(6); engine.AddOpenSubject(this.openSubject); diff --git a/tests/PolygonClipper.Benchmarks/StarBooleanBenches.cs b/tests/PolygonClipper.Benchmarks/StarBooleanBenches.cs index 94a7ffd..5ba9c0e 100644 --- a/tests/PolygonClipper.Benchmarks/StarBooleanBenches.cs +++ b/tests/PolygonClipper.Benchmarks/StarBooleanBenches.cs @@ -19,41 +19,41 @@ .NET SDK 11.0.100-preview.7.26381.103 | Method | Categories | VertexCount | Mean | Error | StdDev | Op/s | Ratio | RatioSD | Gen0 | Gen1 | Gen2 | Allocated | Alloc Ratio | |--------------------- |------------- |------------ |---------------:|---------------:|--------------:|---------:|------:|--------:|-----------:|-----------:|----------:|-------------:|------------:| -| Difference | Difference | 101 | 8.593 ms | 1.0394 ms | 0.0570 ms | 116.3708 | 1.35 | 0.08 | 78.1250 | 31.2500 | - | 1316.74 KB | 0.32 | -| Clipper2Difference | Difference | 101 | 6.392 ms | 8.5489 ms | 0.4686 ms | 156.4422 | 1.00 | 0.09 | 328.1250 | 320.3125 | 164.0625 | 4082.33 KB | 1.00 | +| Difference | Difference | 101 | 8.592 ms | 2.6134 ms | 0.1433 ms | 116.3822 | 1.39 | 0.04 | 62.5000 | 15.6250 | - | 1217.61 KB | 0.30 | +| Clipper2Difference | Difference | 101 | 6.195 ms | 2.7946 ms | 0.1532 ms | 161.4186 | 1.00 | 0.03 | 328.1250 | 320.3125 | 164.0625 | 4082.33 KB | 1.00 | | | | | | | | | | | | | | | | -| Difference | Difference | 301 | 130.095 ms | 99.1253 ms | 5.4334 ms | 7.6867 | 1.00 | 0.04 | 3000.0000 | 2800.0000 | 1000.0000 | 42073.83 KB | 1.19 | -| Clipper2Difference | Difference | 301 | 130.746 ms | 53.8317 ms | 2.9507 ms | 7.6484 | 1.00 | 0.03 | 3000.0000 | 3000.0000 | 1600.0000 | 35390.13 KB | 1.00 | +| Difference | Difference | 301 | 138.097 ms | 55.6052 ms | 3.0479 ms | 7.2413 | 1.15 | 0.06 | 2500.0000 | 2250.0000 | 750.0000 | 41170.04 KB | 1.16 | +| Clipper2Difference | Difference | 301 | 120.159 ms | 126.1519 ms | 6.9148 ms | 8.3223 | 1.00 | 0.07 | 3000.0000 | 3000.0000 | 1600.0000 | 35389.65 KB | 1.00 | | | | | | | | | | | | | | | | -| Difference | Difference | 1001 | 2,125.882 ms | 673.9883 ms | 36.9436 ms | 0.4704 | 0.57 | 0.02 | 28000.0000 | 25000.0000 | 4000.0000 | 484677.92 KB | 1.21 | -| Clipper2Difference | Difference | 1001 | 3,726.175 ms | 1,879.7932 ms | 103.0378 ms | 0.2684 | 1.00 | 0.03 | 25000.0000 | 24000.0000 | 5000.0000 | 399665.54 KB | 1.00 | +| Difference | Difference | 1001 | 2,090.871 ms | 352.1612 ms | 19.3031 ms | 0.4783 | 0.56 | 0.01 | 28000.0000 | 25000.0000 | 4000.0000 | 473410.95 KB | 1.18 | +| Clipper2Difference | Difference | 1001 | 3,732.178 ms | 1,137.1280 ms | 62.3298 ms | 0.2679 | 1.00 | 0.02 | 25000.0000 | 24000.0000 | 5000.0000 | 399665.55 KB | 1.00 | | | | | | | | | | | | | | | | -| Intersection | Intersection | 101 | 9.145 ms | 0.9038 ms | 0.0495 ms | 109.3527 | 1.53 | 0.04 | 93.7500 | 46.8750 | - | 1755.73 KB | 0.35 | -| Clipper2Intersection | Intersection | 101 | 5.968 ms | 3.5492 ms | 0.1945 ms | 167.5699 | 1.00 | 0.04 | 328.1250 | 320.3125 | 164.0625 | 4962.32 KB | 1.00 | +| Intersection | Intersection | 101 | 8.622 ms | 1.5939 ms | 0.0874 ms | 115.9833 | 1.38 | 0.03 | 93.7500 | - | - | 1626.57 KB | 0.33 | +| Clipper2Intersection | Intersection | 101 | 6.233 ms | 2.6067 ms | 0.1429 ms | 160.4281 | 1.00 | 0.03 | 328.1250 | 320.3125 | 164.0625 | 4962.32 KB | 1.00 | | | | | | | | | | | | | | | | -| Intersection | Intersection | 301 | 157.319 ms | 79.0129 ms | 4.3310 ms | 6.3565 | 1.09 | 0.04 | 3250.0000 | 3000.0000 | 1000.0000 | 52551.37 KB | 1.21 | -| Clipper2Intersection | Intersection | 301 | 144.021 ms | 66.3565 ms | 3.6372 ms | 6.9434 | 1.00 | 0.03 | 3500.0000 | 3500.0000 | 1500.0000 | 43405.64 KB | 1.00 | +| Intersection | Intersection | 301 | 173.414 ms | 68.4030 ms | 3.7494 ms | 5.7665 | 1.07 | 0.02 | 3500.0000 | 3250.0000 | 1000.0000 | 51374.25 KB | 1.18 | +| Clipper2Intersection | Intersection | 301 | 162.692 ms | 30.7326 ms | 1.6846 ms | 6.1466 | 1.00 | 0.01 | 3500.0000 | 3500.0000 | 1500.0000 | 43405.66 KB | 1.00 | | | | | | | | | | | | | | | | -| Intersection | Intersection | 1001 | 2,282.190 ms | 388.6867 ms | 21.3052 ms | 0.4382 | 0.52 | 0.01 | 33000.0000 | 30000.0000 | 4000.0000 | 627672.06 KB | 1.25 | -| Clipper2Intersection | Intersection | 1001 | 4,390.261 ms | 894.3474 ms | 49.0222 ms | 0.2278 | 1.00 | 0.01 | 29000.0000 | 28000.0000 | 6000.0000 | 501898.72 KB | 1.00 | +| Intersection | Intersection | 1001 | 2,371.434 ms | 588.3850 ms | 32.2514 ms | 0.4217 | 0.46 | 0.03 | 32000.0000 | 29000.0000 | 4000.0000 | 614610.15 KB | 1.22 | +| Clipper2Intersection | Intersection | 1001 | 5,125.881 ms | 7,195.6056 ms | 394.4154 ms | 0.1951 | 1.00 | 0.09 | 29000.0000 | 28000.0000 | 6000.0000 | 501897.55 KB | 1.00 | | | | | | | | | | | | | | | | -| Union | Union | 101 | 8.655 ms | 2.8097 ms | 0.1540 ms | 115.5335 | 0.21 | 0.00 | 46.8750 | 15.6250 | - | 978.11 KB | 0.18 | -| Clipper2Union | Union | 101 | 40.964 ms | 4.0998 ms | 0.2247 ms | 24.4115 | 1.00 | 0.01 | 384.6154 | 230.7692 | 76.9231 | 5326.67 KB | 1.00 | +| Union | Union | 101 | 8.066 ms | 0.2893 ms | 0.0159 ms | 123.9813 | 0.20 | 0.00 | 46.8750 | 15.6250 | - | 930.56 KB | 0.17 | +| Clipper2Union | Union | 101 | 40.169 ms | 15.9411 ms | 0.8738 ms | 24.8950 | 1.00 | 0.03 | 384.6154 | 230.7692 | 76.9231 | 5327.27 KB | 1.00 | | | | | | | | | | | | | | | | -| Union | Union | 301 | 128.309 ms | 63.5969 ms | 3.4860 ms | 7.7937 | 0.06 | 0.00 | 2250.0000 | 2000.0000 | 750.0000 | 31126.62 KB | 0.79 | -| Clipper2Union | Union | 301 | 2,173.310 ms | 1,079.3527 ms | 59.1630 ms | 0.4601 | 1.00 | 0.03 | 4000.0000 | 4000.0000 | 3000.0000 | 39617.97 KB | 1.00 | +| Union | Union | 301 | 127.845 ms | 93.5855 ms | 5.1297 ms | 7.8220 | 0.06 | 0.00 | 2000.0000 | 1800.0000 | 600.0000 | 30663.72 KB | 0.77 | +| Clipper2Union | Union | 301 | 2,227.592 ms | 1,380.0858 ms | 75.6472 ms | 0.4489 | 1.00 | 0.04 | 4000.0000 | 4000.0000 | 3000.0000 | 39612.54 KB | 1.00 | | | | | | | | | | | | | | | | -| Union | Union | 1001 | 1,734.050 ms | 566.3988 ms | 31.0462 ms | 0.5767 | 0.007 | 0.00 | 20000.0000 | 18000.0000 | 3000.0000 | 366522.3 KB | 0.97 | -| Clipper2Union | Union | 1001 | 234,883.294 ms | 49,429.5458 ms | 2,709.4002 ms | 0.0043 | 1.000 | 0.01 | 23000.0000 | 21000.0000 | 6000.0000 | 378275.68 KB | 1.00 | +| Union | Union | 1001 | 1,663.617 ms | 317.9582 ms | 17.4284 ms | 0.6011 | 0.007 | 0.00 | 20000.0000 | 18000.0000 | 3000.0000 | 361171.7 KB | 0.95 | +| Clipper2Union | Union | 1001 | 240,792.163 ms | 71,896.3248 ms | 3,940.8802 ms | 0.0042 | 1.000 | 0.02 | 23000.0000 | 21000.0000 | 6000.0000 | 378279.99 KB | 1.00 | | | | | | | | | | | | | | | | -| Xor | Xor | 101 | 18.371 ms | 15.0344 ms | 0.8241 ms | 54.4343 | 1.41 | 0.09 | 1000.0000 | 968.7500 | 500.0000 | 10669.71 KB | 1.28 | -| Clipper2Xor | Xor | 101 | 13.032 ms | 13.6608 ms | 0.7488 ms | 76.7356 | 1.00 | 0.07 | 609.3750 | 609.3750 | 375.0000 | 8327.78 KB | 1.00 | +| Xor | Xor | 101 | 16.579 ms | 15.8643 ms | 0.8696 ms | 60.3162 | 1.33 | 0.07 | 968.7500 | 937.5000 | 468.7500 | 10455.01 KB | 1.26 | +| Clipper2Xor | Xor | 101 | 12.510 ms | 7.3404 ms | 0.4024 ms | 79.9386 | 1.00 | 0.04 | 609.3750 | 609.3750 | 375.0000 | 8327.71 KB | 1.00 | | | | | | | | | | | | | | | | -| Xor | Xor | 301 | 235.357 ms | 110.2588 ms | 6.0437 ms | 4.2489 | 0.84 | 0.02 | 5000.0000 | 4000.0000 | 1000.0000 | 92684.45 KB | 1.29 | -| Clipper2Xor | Xor | 301 | 279.997 ms | 39.8076 ms | 2.1820 ms | 3.5715 | 1.00 | 0.01 | 5000.0000 | 5000.0000 | 2000.0000 | 71681.65 KB | 1.00 | +| Xor | Xor | 301 | 234.583 ms | 73.9136 ms | 4.0515 ms | 4.2629 | 0.80 | 0.02 | 5000.0000 | 4000.0000 | 1000.0000 | 90769.98 KB | 1.27 | +| Clipper2Xor | Xor | 301 | 293.448 ms | 77.4884 ms | 4.2474 ms | 3.4078 | 1.00 | 0.02 | 5000.0000 | 5000.0000 | 2000.0000 | 71681.67 KB | 1.00 | | | | | | | | | | | | | | | | -| Xor | Xor | 1001 | 3,251.201 ms | 1,311.9581 ms | 71.9129 ms | 0.3076 | 0.32 | 0.01 | 54000.0000 | 47000.0000 | 5000.0000 | 969498.71 KB | 1.30 | -| Clipper2Xor | Xor | 1001 | 10,123.423 ms | 1,516.1091 ms | 83.1031 ms | 0.0988 | 1.00 | 0.01 | 45000.0000 | 44000.0000 | 7000.0000 | 744382.44 KB | 1.00 | +| Xor | Xor | 1001 | 3,112.260 ms | 227.6820 ms | 12.4800 ms | 0.3213 | 0.26 | 0.02 | 54000.0000 | 47000.0000 | 5000.0000 | 948257.05 KB | 1.27 | +| Clipper2Xor | Xor | 1001 | 11,932.729 ms | 17,927.6550 ms | 982.6753 ms | 0.0838 | 1.00 | 0.10 | 45000.0000 | 44000.0000 | 7000.0000 | 744375.98 KB | 1.00 | */ /// @@ -104,7 +104,7 @@ public Polygon Union() /// The resolved contour tree. [Benchmark(Baseline = true)] [BenchmarkCategory("Union")] - public object Clipper2Union() + public PolyTreeD Clipper2Union() { ClipperD clipper = CreateClipper(); clipper.AddSubject(this.clipperSubject); @@ -129,7 +129,7 @@ public Polygon Intersection() /// The resolved contour tree. [Benchmark(Baseline = true)] [BenchmarkCategory("Intersection")] - public object Clipper2Intersection() + public PolyTreeD Clipper2Intersection() { ClipperD clipper = CreateClipper(); clipper.AddSubject(this.clipperSubject); @@ -154,7 +154,7 @@ public Polygon Difference() /// The resolved contour tree. [Benchmark(Baseline = true)] [BenchmarkCategory("Difference")] - public object Clipper2Difference() + public PolyTreeD Clipper2Difference() { ClipperD clipper = CreateClipper(); clipper.AddSubject(this.clipperSubject); @@ -179,7 +179,7 @@ public Polygon Xor() /// The resolved contour tree. [Benchmark(Baseline = true)] [BenchmarkCategory("Xor")] - public object Clipper2Xor() + public PolyTreeD Clipper2Xor() { ClipperD clipper = CreateClipper(); clipper.AddSubject(this.clipperSubject); diff --git a/tests/PolygonClipper.Benchmarks/StrokeBenches.cs b/tests/PolygonClipper.Benchmarks/StrokeBenches.cs index e42842e..124023e 100644 --- a/tests/PolygonClipper.Benchmarks/StrokeBenches.cs +++ b/tests/PolygonClipper.Benchmarks/StrokeBenches.cs @@ -18,14 +18,14 @@ .NET SDK 11.0.100-preview.7.26381.103 | Method | ToothCount | Mean | Error | StdDev | Op/s | Ratio | RatioSD | Gen0 | Gen1 | Gen2 | Allocated | Alloc Ratio | |--------------- |----------- |-----------:|------------:|----------:|--------:|------:|--------:|----------:|----------:|----------:|------------:|------------:| -| Stroke | 101 | 3.908 ms | 0.1493 ms | 0.0082 ms | 255.888 | 1.41 | 0.05 | 7.8125 | - | - | 166.28 KB | 0.18 | -| Clipper2Stroke | 101 | 2.780 ms | 1.9662 ms | 0.1078 ms | 359.756 | 1.00 | 0.05 | 54.6875 | 31.2500 | - | 943.66 KB | 1.00 | +| Stroke | 101 | 3.734 ms | 1.1859 ms | 0.0650 ms | 267.845 | 1.33 | 0.03 | 7.8125 | - | - | 166.13 KB | 0.18 | +| Clipper2Stroke | 101 | 2.815 ms | 1.0010 ms | 0.0549 ms | 355.293 | 1.00 | 0.02 | 54.6875 | 31.2500 | - | 943.66 KB | 1.00 | | | | | | | | | | | | | | | -| Stroke | 301 | 32.695 ms | 33.5114 ms | 1.8369 ms | 30.586 | 1.16 | 0.06 | - | - | - | 487.37 KB | 0.18 | -| Clipper2Stroke | 301 | 28.300 ms | 5.9455 ms | 0.3259 ms | 35.335 | 1.00 | 0.01 | 187.5000 | 125.0000 | 31.2500 | 2700.68 KB | 1.00 | +| Stroke | 301 | 30.147 ms | 5.3515 ms | 0.2933 ms | 33.171 | 1.05 | 0.01 | - | - | - | 487.21 KB | 0.18 | +| Clipper2Stroke | 301 | 28.612 ms | 0.9271 ms | 0.0508 ms | 34.950 | 1.00 | 0.00 | 187.5000 | 125.0000 | 31.2500 | 2700.68 KB | 1.00 | | | | | | | | | | | | | | | -| Stroke | 1001 | 354.823 ms | 29.7121 ms | 1.6286 ms | 2.818 | 0.38 | 0.00 | 1000.0000 | 1000.0000 | 1000.0000 | 20570.89 KB | 1.36 | -| Clipper2Stroke | 1001 | 934.864 ms | 134.0522 ms | 7.3479 ms | 1.070 | 1.00 | 0.01 | 1000.0000 | 1000.0000 | 1000.0000 | 15092.64 KB | 1.00 | +| Stroke | 1001 | 331.330 ms | 22.6436 ms | 1.2412 ms | 3.018 | 0.35 | 0.00 | 1000.0000 | 500.0000 | 500.0000 | 20570.41 KB | 1.36 | +| Clipper2Stroke | 1001 | 954.168 ms | 162.1455 ms | 8.8877 ms | 1.048 | 1.00 | 0.01 | 1000.0000 | 1000.0000 | 1000.0000 | 15092.64 KB | 1.00 | */ /// @@ -75,7 +75,7 @@ public Polygon Stroke() /// /// The resolved stroke paths. [Benchmark(Baseline = true)] - public object Clipper2Stroke() + public PathsD Clipper2Stroke() => Clipper.InflatePaths( this.clipperPaths, StrokeWidth * 0.5D, diff --git a/tests/PolygonClipper.Tests/EnumerationTests.cs b/tests/PolygonClipper.Tests/EnumerationTests.cs new file mode 100644 index 0000000..035b564 --- /dev/null +++ b/tests/PolygonClipper.Tests/EnumerationTests.cs @@ -0,0 +1,124 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +using System.Collections; +using System.Runtime.CompilerServices; + +namespace SixLabors.PolygonClipper.Tests; + +/// +/// Checks concrete and interface enumeration of polygons and contour vertices. +/// +public class EnumerationTests +{ + /// + /// Checks that nested concrete foreach loops allocate no enumerator objects. + /// + [Fact] + public void ConcreteForeach_DoesNotAllocate() + { + Polygon polygon = [[new(1, 0), new(2, 0)], [new(3, 0), new(4, 0)]]; + double sum = 0; + for (int i = 0; i < 256; i++) + { + sum += Enumerate(polygon); + } + + Assert.Equal(2560D, sum); + sum = 0; + long before = GC.GetAllocatedBytesForCurrentThread(); + for (int i = 0; i < 1000; i++) + { + sum += Enumerate(polygon); + } + + long allocated = GC.GetAllocatedBytesForCurrentThread() - before; + Assert.Equal(10000D, sum); + Assert.Equal(0, allocated); + } + + /// + /// Checks stored order through generic and non-generic interfaces, including empty collections. + /// + /// Whether the collections have no stored items. + [Theory] + [InlineData(false)] + [InlineData(true)] + public void InterfaceEnumeration_PreservesStoredOrder(bool empty) + { + Contour contour = empty ? [] : [new(3, 4), new(1, 2)]; + Polygon polygon = empty ? [] : [contour, new Contour()]; + IEnumerable genericPolygon = polygon; + IEnumerable genericContour = contour; + int count = 0; + foreach (Contour item in genericPolygon) + { + Assert.Same(polygon[count++], item); + } + + Assert.Equal(polygon.Count, count); + count = 0; + foreach (object item in (IEnumerable)polygon) + { + Assert.Same(polygon[count++], item); + } + + Assert.Equal(polygon.Count, count); + count = 0; + foreach (Vertex vertex in genericContour) + { + Assert.Equal(contour[count++], vertex); + } + + Assert.Equal(contour.Count, count); + count = 0; + foreach (object item in (IEnumerable)contour) + { + Assert.Equal(contour[count++], Assert.IsType(item)); + } + + Assert.Equal(contour.Count, count); + } + + /// + /// Checks that changing the underlying collection invalidates a concrete enumerator. + /// + [Fact] + public void ConcreteEnumeration_CollectionChange_InvalidatesEnumerator() + { + Contour contour = [new(1, 2), new(3, 4)]; + Polygon polygon = [contour]; + List.Enumerator contours = polygon.GetEnumerator(); + List.Enumerator vertices = contour.GetEnumerator(); + Assert.True(contours.MoveNext()); + Assert.True(vertices.MoveNext()); + + polygon.Add(new Contour()); + contour.Add(new Vertex(5, 6)); + Assert.Throws(() => contours.MoveNext()); + Assert.Throws(() => vertices.MoveNext()); + } + + /// + /// Enumerates both concrete collections through their public foreach pattern. + /// + /// The stored contours and vertices. + /// The sum of the vertex X coordinates. + /// + /// The warmup and measured loops must call the same compiled method. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + private static double Enumerate(Polygon polygon) + { + double sum = 0; + foreach (Contour contour in polygon) + { + foreach (Vertex vertex in contour) + { + sum += vertex.X; + } + } + + return sum; + } +} diff --git a/tests/PolygonClipper.Tests/PolygonOffsetTests.cs b/tests/PolygonClipper.Tests/PolygonOffsetTests.cs index c0f8add..2243822 100644 --- a/tests/PolygonClipper.Tests/PolygonOffsetTests.cs +++ b/tests/PolygonClipper.Tests/PolygonOffsetTests.cs @@ -561,6 +561,66 @@ public void Offset_BoundsRounding_DoesNotDropThinArea() Assert.True(actual[0].GetBoundingBox().Max.X > actual[0].GetBoundingBox().Min.X); } + /// + /// Compares the convex shortcut with the complete Martinez sweep, including vertex bits and order. + /// + /// The boundary join style. + /// The signed offset distance. + /// The stride through the source vertices. Two makes a self-intersecting star. + [Theory] + [InlineData(LineJoin.Miter, 1D, 1)] + [InlineData(LineJoin.Miter, -1D, 1)] + [InlineData(LineJoin.Round, 3D, 1)] + [InlineData(LineJoin.Bevel, 3D, 1)] + [InlineData(LineJoin.Miter, -9D, 1)] + [InlineData(LineJoin.Miter, 1D, 2)] + [InlineData(LineJoin.Round, -1D, 2)] + public void Offset_DisplacedWalk_MatchesMartinezExactly(LineJoin join, double delta, int step) + { + Contour source = new(17); + for (int i = 0; i < 17; i++) + { + double angle = (((i * step) % 17) + 0.25D) * (Math.PI * 2D / 17); + source.Add(new Vertex(23D + (Math.Cos(angle) * 10D), -7D + (Math.Sin(angle) * 10D))); + } + + Polygon subject = [source]; + OffsetOptions options = new() { LineJoin = join }; + Polygon area = PolygonClipper.Normalize(subject, FillRule.NonZero); + Assert.Single(area); + Polygon walks = PolygonStroker.OffsetBoundaries(area, delta, options); + Polygon expected = PolygonClipper.Normalize(walks, FillRule.Positive); + Polygon actual = PolygonOffsetter.Offset(subject, delta, FillRule.NonZero, options); + SvgTestOutput.SaveSvg( + nameof(PolygonOffsetTests), + nameof(this.Offset_DisplacedWalk_MatchesMartinezExactly), + $"Join-{join}_Delta-{delta}_Step-{step}", + subject, + [], + actual, + expected); + + Assert.Equal(expected.Count, actual.Count); + for (int i = 0; i < expected.Count; i++) + { + Assert.Equal(expected[i].IsClosed, actual[i].IsClosed); + Assert.Equal(expected[i].ParentIndex, actual[i].ParentIndex); + Assert.Equal(expected[i].Depth, actual[i].Depth); + Assert.Equal(expected[i].HoleCount, actual[i].HoleCount); + for (int j = 0; j < expected[i].HoleCount; j++) + { + Assert.Equal(expected[i].GetHoleIndex(j), actual[i].GetHoleIndex(j)); + } + + Assert.Equal(expected[i].Count, actual[i].Count); + for (int j = 0; j < expected[i].Count; j++) + { + Assert.Equal(BitConverter.DoubleToInt64Bits(expected[i][j].X), BitConverter.DoubleToInt64Bits(actual[i][j].X)); + Assert.Equal(BitConverter.DoubleToInt64Bits(expected[i][j].Y), BitConverter.DoubleToInt64Bits(actual[i][j].Y)); + } + } + } + /// /// Saves the comparison and checks both boundaries, contour count and output closure. /// diff --git a/tests/PolygonClipper.Tests/PolygonStrokerTests.cs b/tests/PolygonClipper.Tests/PolygonStrokerTests.cs index 1a5346f..400b68a 100644 --- a/tests/PolygonClipper.Tests/PolygonStrokerTests.cs +++ b/tests/PolygonClipper.Tests/PolygonStrokerTests.cs @@ -5,6 +5,50 @@ namespace SixLabors.PolygonClipper.Tests; public class PolygonStrokerTests { + /// + /// Checks exact output across contours and width changes when the same stroker is reused. + /// + /// Whether each source contour has a closing edge. + [Theory] + [InlineData(false)] + [InlineData(true)] + public void Stroke_ReusedInstance_MatchesFreshInstances(bool closed) + { + Polygon subject = + [ + new Contour { new(0, 0), new(10, 5), new(20, -5), new(30, 0) }, + new Contour { new(100, 10), new(110, -10), new(120, 0), new(140, 20) } + ]; + subject[0].IsClosed = subject[1].IsClosed = closed; + StrokeOptions options = new() { LineJoin = LineJoin.Round, LineCap = LineCap.Round, NormalizeOutput = false }; + PolygonStroker reused = new(options); + foreach (double width in new[] { 2D, -2D, 6D, 0D, 2D }) + { + reused.Width = width; + Polygon actual = reused.Stroke(subject); + Polygon expected = new PolygonStroker(options) { Width = width }.Stroke(subject); + SvgTestOutput.SaveSvg( + nameof(PolygonStrokerTests), + nameof(this.Stroke_ReusedInstance_MatchesFreshInstances), + $"IsClosed-{closed}_Width-{width}", + subject, + [], + actual, + expected); + + Assert.Equal(expected.Count, actual.Count); + for (int i = 0; i < expected.Count; i++) + { + Assert.Equal(expected[i].Count, actual[i].Count); + for (int j = 0; j < expected[i].Count; j++) + { + Assert.Equal(BitConverter.DoubleToInt64Bits(expected[i][j].X), BitConverter.DoubleToInt64Bits(actual[i][j].X)); + Assert.Equal(BitConverter.DoubleToInt64Bits(expected[i][j].Y), BitConverter.DoubleToInt64Bits(actual[i][j].Y)); + } + } + } + } + /// /// Checks that axis-aligned miter intersections retain a representable thin inner contour. /// diff --git a/tests/PolygonClipper.Tests/PolygonTests.cs b/tests/PolygonClipper.Tests/PolygonTests.cs index 67b8e41..5ba3733 100644 --- a/tests/PolygonClipper.Tests/PolygonTests.cs +++ b/tests/PolygonClipper.Tests/PolygonTests.cs @@ -41,6 +41,68 @@ public void Intersection_ReorderedComponents_KeepValidHoleIndices() Assert.Same(outer, result[result[holeIndex].ParentIndex!.Value]); } + /// + /// Checks that a later hole is grouped with its owner across another exterior. + /// + [Fact] + public void Union_InterleavedExteriorAndHole_PreservesGroupedHierarchy() + { + Contour exterior = CreateSquare(0, 0, 100); + Contour hole = CreateSquare(80, 80, 10); + Contour separate = CreateSquare(20, 200, 10); + Polygon subject = [exterior, hole, separate]; + Polygon result = PolygonClipper.Union(subject, [], FillRule.EvenOdd); + SvgTestOutput.SaveSvg( + nameof(PolygonTests), + nameof(this.Union_InterleavedExteriorAndHole_PreservesGroupedHierarchy), + string.Empty, + subject, + [], + result); + + Assert.Equal(3, result.Count); + Assert.Equal(new Vertex(0, 0), result[0].GetBoundingBox().Min); + Assert.Equal(new Vertex(80, 80), result[1].GetBoundingBox().Min); + Assert.Equal(new Vertex(20, 200), result[2].GetBoundingBox().Min); + Assert.Equal(1, result[0].HoleCount); + Assert.Equal(1, result[0].GetHoleIndex(0)); + Assert.Equal(0, result[1].ParentIndex); + Assert.Equal(1, result[1].Depth); + Assert.Null(result[2].ParentIndex); + } + + /// + /// Checks the vertex sequence of independent triangles in an already grouped result. + /// + [Fact] + public void Union_DisjointTriangles_PreservesVertexSequence() + { + Polygon subject = + [ + [new(0, 0), new(4, 0), new(2, 3)], + [new(10, 0), new(14, 0), new(12, 3)] + ]; + Polygon result = PolygonClipper.Union(subject, [], FillRule.NonZero); + SvgTestOutput.SaveSvg( + nameof(PolygonTests), + nameof(this.Union_DisjointTriangles_PreservesVertexSequence), + string.Empty, + subject, + [], + result, + subject); + + Assert.Equal(2, result.Count); + for (int i = 0; i < result.Count; i++) + { + Assert.Equal(3, result[i].Count); + Assert.Equal(subject[i], result[i]); + Assert.True(result[i].IsClosed); + Assert.Null(result[i].ParentIndex); + Assert.Equal(0, result[i].HoleCount); + } + } + private static Contour CreateSquare(double x, double y, double size) { Contour contour = From e38580a9bef61a45bafad668934aeb3ba69a3eac Mon Sep 17 00:00:00 2001 From: James Jackson-South Date: Mon, 2 Nov 2026 16:39:02 +1000 Subject: [PATCH 22/24] Set PolygonClipper V2 version floor and package metadata --- src/PolygonClipper/PolygonClipper.csproj | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/PolygonClipper/PolygonClipper.csproj b/src/PolygonClipper/PolygonClipper.csproj index c731a06..1c20f16 100644 --- a/src/PolygonClipper/PolygonClipper.csproj +++ b/src/PolygonClipper/PolygonClipper.csproj @@ -9,8 +9,8 @@ LICENSE https://github.com/SixLabors/PolygonClipper/ $(RepositoryUrl) - - + Polygon Clipping Boolean Geometry Stroking Offset Winding + A .NET library for polygon clipping, stroking, and offsets with double coordinates and explicit fill rules. Debug;Release true @@ -22,8 +22,7 @@ - - 1.0 + 2.0 From 8553f2b1aed676ef99a1009f9fa011bbbc1c72a7 Mon Sep 17 00:00:00 2001 From: James Jackson-South Date: Mon, 2 Nov 2026 16:56:41 +1000 Subject: [PATCH 23/24] Fix CI restore and project reference casing --- src/Directory.Build.props | 3 +++ tests/Directory.Build.props | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/src/Directory.Build.props b/src/Directory.Build.props index 4651c6c..5dcc7e8 100644 --- a/src/Directory.Build.props +++ b/src/Directory.Build.props @@ -26,6 +26,9 @@ + + + diff --git a/tests/Directory.Build.props b/tests/Directory.Build.props index 58abd83..36ab39b 100644 --- a/tests/Directory.Build.props +++ b/tests/Directory.Build.props @@ -22,7 +22,7 @@ - + From 2506dfb995e1ab1e2e2f54a11a44615eed187254 Mon Sep 17 00:00:00 2001 From: James Jackson-South Date: Mon, 23 Nov 2026 14:26:02 +1000 Subject: [PATCH 24/24] Optimize Martinez clipping and convex offsets --- src/PolygonClipper/Contour.cs | 10 +++ src/PolygonClipper/PolygonClipper.cs | 79 ++++++++++--------- src/PolygonClipper/PolygonOffsetter.cs | 76 +++++++++++++++--- src/PolygonClipper/PolygonUtilities.cs | 25 +++--- .../StablePriorityQueue{T,TComparer}.cs | 24 +++--- src/PolygonClipper/SweepEvent.cs | 15 +++- src/PolygonClipper/SweepEventComparer.cs | 4 +- tests/PolygonClipper.Benchmarks/Program.cs | 2 +- tests/PolygonClipper.Tests/ContourTests.cs | 15 ++++ .../QueueEntryComparerTests.cs | 12 +++ 10 files changed, 184 insertions(+), 78 deletions(-) diff --git a/src/PolygonClipper/Contour.cs b/src/PolygonClipper/Contour.cs index 86a0668..5a5db04 100644 --- a/src/PolygonClipper/Contour.cs +++ b/src/PolygonClipper/Contour.cs @@ -239,6 +239,16 @@ public void Add(in Vertex vertex) this.hasCachedOrientation = false; } + /// + /// Appends vertices in their stored order. + /// + /// The vertices to append. + internal void AddRange(ReadOnlySpan vertices) + { + this.vertices.AddRange(vertices); + this.hasCachedOrientation = false; + } + /// /// Removes the vertex at the specified index from the contour. /// diff --git a/src/PolygonClipper/PolygonClipper.cs b/src/PolygonClipper/PolygonClipper.cs index eb85764..d5d251c 100644 --- a/src/PolygonClipper/PolygonClipper.cs +++ b/src/PolygonClipper/PolygonClipper.cs @@ -410,14 +410,30 @@ private Polygon RunSweep(Box2 subjectBounds, Box2 clipBounds) int statusCount = this.statusLine.Count; int blockCount = after - first; + // A single ordinary continuation has no other ray to order or merge. + // Keep it in the outgoing list until the neighbor checks close the point. + bool singleContinuation = !open && blockCount == 1 && this.outgoing.Count == 1 && + this.outgoing[0].Ends is null && !this.outgoing[0].Delta.IsZero; + + SweepEventPoolList active; + while (true) { - this.BundleOutgoing(); - this.statusLine.ReplaceRange(first, blockCount, this.bundled.GetEventsSpan()); - blockCount = this.bundled.Count; - for (int i = 0; i < this.bundled.Count; i++) + if (singleContinuation) { - SweepEvent edge = this.bundled[i]; + active = this.outgoing; + } + else + { + this.BundleOutgoing(); + active = this.bundled; + } + + this.statusLine.ReplaceRange(first, blockCount, active.GetEventsSpan()); + blockCount = active.Count; + for (int i = 0; i < blockCount; i++) + { + SweepEvent edge = active[i]; edge.Active = true; } @@ -425,16 +441,24 @@ private Polygon RunSweep(Box2 subjectBounds, Box2 clipBounds) // incidence predicate missed a neighboring interval. Absorb it // before committing winding or immutable boundary history. bool lowerIncident = this.PossibleIntersection(first - 1, first, point, sourcePoint); - bool upperIncident = this.bundled.Count == 0 + bool upperIncident = blockCount == 0 ? lowerIncident - : !lowerIncident && this.PossibleIntersection(first + this.bundled.Count - 1, first + this.bundled.Count, point, sourcePoint); + : !lowerIncident && this.PossibleIntersection(first + blockCount - 1, first + blockCount, point, sourcePoint); + if (!lowerIncident && !upperIncident) { break; } - this.outgoing.Clear(); - this.outgoing.AddRange(this.bundled); + if (!singleContinuation) + { + this.outgoing.Clear(); + this.outgoing.AddRange(this.bundled); + } + + // An incident neighbor can add another ray at this point. + // Use the full bundle logic from this point on. + singleContinuation = false; foreach (SweepEvent edge in this.outgoing) { // Rebundling can replace a representative. Invalidate any @@ -471,9 +495,9 @@ private Polygon RunSweep(Box2 subjectBounds, Box2 clipBounds) bool below = InResult(winding, operation, subjectRule, clipRule); SweepEvent? previousBoundary = null; bool hasBoundaryContext = false; - for (int i = 0; i < this.bundled.Count; i++) + for (int i = 0; i < active.Count; i++) { - SweepEvent edge = this.bundled[i]; + SweepEvent edge = active[i]; winding = winding.Add(edge.Delta); edge.Above = winding; bool above = InResult(winding, operation, subjectRule, clipRule); @@ -538,7 +562,7 @@ private Polygon RunSweep(Box2 subjectBounds, Box2 clipBounds) // deaths, and changing bundles move the unchanged suffix. if (this.statusLine.Count != statusCount) { - for (int i = first + this.bundled.Count; i < this.statusLine.Count; i++) + for (int i = first + active.Count; i < this.statusLine.Count; i++) { SweepEvent edge = this.statusLine[i]; edge.Pos = i; @@ -1256,26 +1280,6 @@ private Polygon ConnectEdges(SweepEventPoolList resultEvents) { // Run already sorts completed boundary events. Work directly on their // pooled storage; no filtering copy or second ordering pass is needed. - // Assign positions to events - // The first loop ensures that every event gets its initial position based on its index in the list. - // This must be completed for all events before adjustments are made for right events to avoid inconsistent state. - for (int i = 0; i < resultEvents.Count; i++) - { - resultEvents[i].Pos = i; - } - - // Adjust positions for right events - // The second loop handles swapping positions for right events with their corresponding left events. - // This ensures that the `Pos` values are consistent between paired events after the initial assignment. - for (int i = 0; i < resultEvents.Count; i++) - { - SweepEvent sweepEvent = resultEvents[i]; - if (sweepEvent.Left) - { - (sweepEvent.OtherEvent.Pos, sweepEvent.Pos) = (sweepEvent.Pos, sweepEvent.OtherEvent.Pos); - } - } - using Buffer iterationBuffer = new(resultEvents.Count); Span iterationMap = iterationBuffer.GetSpan(); PrecomputeIterationOrder(resultEvents, iterationMap); @@ -1350,11 +1354,7 @@ private Polygon ConnectEdges(SweepEventPoolList resultEvents) lastExterior = contourId; } - for (int j = 0; j < count; j++) - { - contour.Add(vertices[j]); - } - + contour.AddRange(vertices[..count]); result.Add(contour); } @@ -1401,6 +1401,7 @@ private Polygon ConnectEdges(SweepEventPoolList resultEvents) /// /// The fully sorted, paired output events. /// Receives the next incident event index for every boundary endpoint. + /// Each event's position is set to its paired endpoint's index. private static void PrecomputeIterationOrder(SweepEventPoolList data, Span map) { int i = 0; @@ -1412,6 +1413,9 @@ private static void PrecomputeIterationOrder(SweepEventPoolList data, Span int rFrom = i; while (i < data.Count && xRef.Point == data[i].Point && !data[i].Left) { + // Crossing an edge must reach its opposite endpoint. Assign + // that index directly while visiting each incident event. + data[i].OtherEvent.Pos = i; i++; } @@ -1426,6 +1430,7 @@ private static void PrecomputeIterationOrder(SweepEventPoolList data, Span throw new InvalidOperationException("Expected left event"); } + data[i].OtherEvent.Pos = i; i++; } diff --git a/src/PolygonClipper/PolygonOffsetter.cs b/src/PolygonClipper/PolygonOffsetter.cs index a88d521..71f1add 100644 --- a/src/PolygonClipper/PolygonOffsetter.cs +++ b/src/PolygonClipper/PolygonOffsetter.cs @@ -33,6 +33,46 @@ public static Polygon Offset(Polygon polygon, double delta, FillRule fillRule, O Guard.IsTrue(polygon[i].IsClosed, nameof(polygon), "Offset requires closed contours. Use Stroke for open paths."); } + if (delta != 0 && polygon.Count == 1 && (uint)fillRule <= (uint)FillRule.Negative && + TryGetConvexStart(polygon[0], out int start, out bool counterClockwise)) + { + // A simple convex ring has winding +1 or -1 throughout its interior. + if (!PolygonClipper.Filled(counterClockwise ? 1 : -1, fillRule)) + { + return []; + } + + if (counterClockwise && start == 0) + { + return OffsetComponent(polygon, delta, options); + } + + // Match the sweep's source order before computing the joins. A new + // contour lets the stroker visit that order without editing the input. + ReadOnlySpan points = polygon[0].AsVertexSpan(); + Contour source = new(points.Length); + if (counterClockwise) + { + source.AddRange(points[start..]); + source.AddRange(points[..start]); + } + else + { + source.Add(points[start]); + for (int i = start - 1; i >= 0; i--) + { + source.Add(points[i]); + } + + for (int i = points.Length - 1; i > start; i--) + { + source.Add(points[i]); + } + } + + return OffsetComponent([source], delta, options); + } + // Resolve the requested filled area before outlining it. Raw overlaps and self-crossings // are not independent boundaries and must not introduce internal offset seams. Polygon area = PolygonClipper.Normalize(polygon, fillRule); @@ -117,7 +157,7 @@ private static Polygon OffsetComponent(Polygon component, double delta, OffsetOp Polygon boundaries = PolygonStroker.OffsetBoundaries(component, delta, options); - if (boundaries.Count == 1 && TryGetConvexStart(boundaries[0], out int start)) + if (boundaries.Count == 1 && TryGetConvexStart(boundaries[0], out int start, out bool counterClockwise) && counterClockwise) { // A strictly convex counterclockwise walk already bounds exactly the // Positive-filled result. Match Martinez's leftmost starting vertex @@ -140,32 +180,48 @@ private static Polygon OffsetComponent(Polygon component, double delta, OffsetOp } /// - /// Checks for a simple, strictly convex counterclockwise walk and finds its first sweep vertex. + /// Checks for a simple, strictly convex walk and finds its first sweep vertex. /// - /// A closed displaced walk with at least three vertices. + /// A closed contour. /// The index of the lexicographically smallest vertex. - /// Whether every turn is positive and the edge directions make exactly one full turn. - private static bool TryGetConvexStart(Contour contour, out int start) + /// Whether the convex contour turns counterclockwise. + /// Whether all turns have the same sign and the edge directions make exactly one full turn. + private static bool TryGetConvexStart(Contour contour, out int start, out bool counterClockwise) { ReadOnlySpan points = contour.AsVertexSpan(); + start = 0; + counterClockwise = false; + if (points.Length < 3) + { + return false; + } + Vertex previous = points[^1]; Vertex current = points[0]; bool previousUpper = current.Y > previous.Y || (current.Y == previous.Y && current.X > previous.X); int turns = 0; - start = 0; for (int i = 0; i < points.Length; i++) { Vertex next = points[i + 1 == points.Length ? 0 : i + 1]; double turn = PolygonUtilities.SignedArea(previous, current, next); if (!double.IsFinite(current.X) || !double.IsFinite(current.Y) || - !double.IsFinite(turn) || turn <= 0) + !double.IsFinite(turn) || turn == 0) + { + return false; + } + + if (i == 0) + { + counterClockwise = turn > 0; + } + else if ((turn > 0) != counterClockwise) { return false; } - // Positive turns restrict each direction change to less than half a turn. - // Crossing from the lower half-plane to the upper half-plane counts a full - // direction wrap. One wrap proves convexity; stars and repeated walks wrap more often. + // Same-sign turns move the direction by less than half a turn each time. + // Each full turn crosses from the lower half-plane to the upper half-plane once. + // A convex ring makes one full turn. Stars and repeated walks make more. // Endpoint comparisons classify the half-plane without overflowing edge subtraction. bool upper = next.Y > current.Y || (next.Y == current.Y && next.X > current.X); if (!previousUpper && upper && ++turns > 1) diff --git a/src/PolygonClipper/PolygonUtilities.cs b/src/PolygonClipper/PolygonUtilities.cs index cfd75d8..f6ef6f6 100644 --- a/src/PolygonClipper/PolygonUtilities.cs +++ b/src/PolygonClipper/PolygonUtilities.cs @@ -67,7 +67,7 @@ public static int FindIntersection(in Segment seg0, in Segment seg1, out Vertex pi0 = default; pi1 = default; - if (!TryGetIntersectionBoundingBox(seg0.Source, seg0.Target, seg1.Source, seg1.Target, out Box2 bbox)) + if (!TryGetIntersectionBoundingBox(seg0, seg1, out Box2 bbox)) { return 0; } @@ -226,28 +226,21 @@ private static int FindIntersectionImpl(in Segment seg0, in Segment seg1, out Ve /// /// Computes the bounding box of the intersection area of two line segments. /// - /// The first point of the first segment. - /// The second point of the first segment. - /// The first point of the second segment. - /// The second point of the second segment. + /// The first segment and its cached coordinate bounds. + /// The second segment and its cached coordinate bounds. /// The intersection bounds when the method returns true. /// /// if the segments intersect; otherwise, . /// private static bool TryGetIntersectionBoundingBox( - in Vertex a1, - in Vertex a2, - in Vertex b1, - in Vertex b2, + in Segment first, + in Segment second, out Box2 result) { - Vertex minA = Vertex.Min(a1, a2); - Vertex maxA = Vertex.Max(a1, a2); - Vertex minB = Vertex.Min(b1, b2); - Vertex maxB = Vertex.Max(b1, b2); - - Vertex interMin = Vertex.Max(minA, minB); - Vertex interMax = Vertex.Min(maxA, maxB); + // Segment construction already applies the same coordinate-wise Min + // and Max operations. Reuse them for every later adjacency check. + Vertex interMin = Vertex.Max(first.Min, second.Min); + Vertex interMax = Vertex.Min(first.Max, second.Max); if (interMin.X <= interMax.X && interMin.Y <= interMax.Y) { diff --git a/src/PolygonClipper/StablePriorityQueue{T,TComparer}.cs b/src/PolygonClipper/StablePriorityQueue{T,TComparer}.cs index 22cf6e5..a18ef69 100644 --- a/src/PolygonClipper/StablePriorityQueue{T,TComparer}.cs +++ b/src/PolygonClipper/StablePriorityQueue{T,TComparer}.cs @@ -96,7 +96,11 @@ public T Dequeue() { List data = this.heap; int count = data.Count; - ThrowIfEmpty(count); + if (count == 0) + { + ThrowEmpty(); + } + ref T dRef = ref MemoryMarshal.GetReference(CollectionsMarshal.AsSpan(data)); int maxIndex = count - 1; @@ -120,7 +124,11 @@ public T Dequeue() /// Thrown if the priority queue is empty. public T Peek() { - ThrowIfEmpty(this.Count); + if (this.heap.Count == 0) + { + ThrowEmpty(); + } + return this.heap[0]; } @@ -212,12 +220,10 @@ private void Heapify(List heap) } } + /// + /// Throws when an empty queue is read or dequeued. + /// + // Keep the throw outside the hot path without calling a helper for every valid read. [MethodImpl(MethodImplOptions.NoInlining)] - private static void ThrowIfEmpty(int count) - { - if (count == 0) - { - throw new InvalidOperationException("Queue is empty."); - } - } + private static void ThrowEmpty() => throw new InvalidOperationException("Queue is empty."); } diff --git a/src/PolygonClipper/SweepEvent.cs b/src/PolygonClipper/SweepEvent.cs index 8e6fcc8..7d504ed 100644 --- a/src/PolygonClipper/SweepEvent.cs +++ b/src/PolygonClipper/SweepEvent.cs @@ -113,9 +113,11 @@ public Vertex End public Vertex SourceEnd { get => this.interval.SourceEnd; set => this.interval.SourceEnd = value; } /// - /// Gets or sets the original supporting segment, preserved across rounded splits. + /// Gets a reference to the original supporting segment, preserved across rounded splits. /// - public Segment Support { get => this.interval.Support; set => this.interval.Support = value; } + // Intersection checks take this 64-byte value by reference. Forward the + // owned storage so each adjacent-pair check does not copy both supports. + public ref Segment Support => ref this.interval.Support; /// /// Gets or sets the signed subject and clip contributions of this interval. @@ -327,15 +329,20 @@ public void InitializeBoundary( /// private sealed class IntervalState { + /// + /// The original support and its cached coordinate bounds. + /// + private Segment support; + /// /// Gets or sets the next source contribution endpoint. /// public Vertex SourceEnd { get; set; } /// - /// Gets or sets the original supporting segment, preserved across rounded splits. + /// Gets a reference to the original support and its cached coordinate bounds. /// - public Segment Support { get; set; } + public ref Segment Support => ref this.support; /// /// Gets or sets the signed subject and clip contributions of this interval. diff --git a/src/PolygonClipper/SweepEventComparer.cs b/src/PolygonClipper/SweepEventComparer.cs index b649f15..0857b4c 100644 --- a/src/PolygonClipper/SweepEventComparer.cs +++ b/src/PolygonClipper/SweepEventComparer.cs @@ -56,7 +56,9 @@ public int Compare(SweepEvent? x, SweepEvent? y) double area = PolygonUtilities.SignedArea(x.Point, x.OtherEvent.Point, y.OtherEvent.Point); if (area != 0) { - return x.IsBelow(y.OtherEvent.Point) ? -1 : 1; + // IsBelow uses this determinant for a left event and its negative + // for a right event. Reuse its sign instead of evaluating it again. + return (x.Left ? area > 0 : area < 0) ? -1 : 1; } // Compare by polygon type: subject polygons have higher priority diff --git a/tests/PolygonClipper.Benchmarks/Program.cs b/tests/PolygonClipper.Benchmarks/Program.cs index fb508f1..619cb4b 100644 --- a/tests/PolygonClipper.Benchmarks/Program.cs +++ b/tests/PolygonClipper.Benchmarks/Program.cs @@ -28,6 +28,6 @@ public ShortRunConfig() this.AddExporter(DefaultExporters.Html, DefaultExporters.Csv); - this.AddJob(Job.ShortRun); + this.AddJob(Job.ShortRun.WithLaunchCount(3).WithWarmupCount(5).WithIterationCount(10)); } } diff --git a/tests/PolygonClipper.Tests/ContourTests.cs b/tests/PolygonClipper.Tests/ContourTests.cs index 971c67f..824d4b8 100644 --- a/tests/PolygonClipper.Tests/ContourTests.cs +++ b/tests/PolygonClipper.Tests/ContourTests.cs @@ -5,6 +5,21 @@ namespace SixLabors.PolygonClipper.Tests; public class ContourTests { + /// + /// Checks that bulk appends preserve vertex order and invalidate cached orientation. + /// + [Fact] + public void AddRange_AppendsVerticesAndInvalidatesOrientation() + { + Contour contour = [new Vertex(0, 0), new Vertex(1, 0), new Vertex(0, 1)]; + Assert.True(contour.IsCounterClockwise()); + + contour.AddRange([new Vertex(10, -10), new Vertex(10, -20)]); + + Assert.Equal([new Vertex(0, 0), new Vertex(1, 0), new Vertex(0, 1), new Vertex(10, -10), new Vertex(10, -20)], contour); + Assert.False(contour.IsCounterClockwise()); + } + [Theory] [InlineData(true)] [InlineData(false)] diff --git a/tests/PolygonClipper.Tests/QueueEntryComparerTests.cs b/tests/PolygonClipper.Tests/QueueEntryComparerTests.cs index 21d35ef..0239427 100644 --- a/tests/PolygonClipper.Tests/QueueEntryComparerTests.cs +++ b/tests/PolygonClipper.Tests/QueueEntryComparerTests.cs @@ -8,6 +8,18 @@ namespace SixLabors.PolygonClipper.Tests; /// public class QueueEntryComparerTests { + /// + /// Checks that empty reads and removals retain the queue's exception contract. + /// + [Fact] + public void Queue_EmptyReadAndRemoval_Throw() + { + StablePriorityQueue queue = new(default(QueueEntryComparer)); + + Assert.Throws(() => queue.Peek()); + Assert.Throws(() => queue.Dequeue()); + } + /// /// Checks point, interval, version and endpoint order with both heap entry paths. ///