From 3991041f3aa7a9fae70450265f3160f2530037c1 Mon Sep 17 00:00:00 2001 From: Malcolm Nixon Date: Mon, 21 Sep 2026 11:21:00 -0400 Subject: [PATCH 01/13] Add DemaConsulting.CanvasNet.Drawing stroke-to-fill conversion (Drawing Phase 3: strokes) Implements PathStroker, StrokeStyle, LineCap, LineJoin, and internal helpers (StrokePathFlattener, DashSplitter, StrokeOutliner) that convert stroked paths into fillable outline geometry, reusing the existing PathFiller/ScanlineRasterizer NonZero rasterizer. Includes full companion artifacts: reqstream (system/subsystem/unit), design docs, verification docs, sysml2 model, .reviewmark.yaml entry, README and user guide updates, plus unit and end-to-end pixel-coverage tests. --- .reviewmark.yaml | 26 + README.md | 27 + docs/design/canvas-net.md | 77 +- docs/design/canvas-net/drawing.md | 56 +- .../design/canvas-net/drawing/path-stroker.md | 154 ++++ docs/design/introduction.md | 23 +- docs/reqstream/canvas-net.yaml | 55 ++ docs/reqstream/canvas-net/drawing.yaml | 63 ++ .../canvas-net/drawing/path-stroker.yaml | 189 +++++ docs/sysml2/model/canvas-net.sysml | 3 +- docs/sysml2/model/canvas-net/drawing.sysml | 3 +- .../canvas-net/drawing/path-stroker.sysml | 11 + docs/user_guide/introduction.md | 118 +++ docs/verification/canvas-net/drawing.md | 22 +- .../canvas-net/drawing/path-stroker.md | 127 ++++ requirements.yaml | 1 + .../Drawing/DashSplitter.cs | 395 ++++++++++ .../Drawing/LineCap.cs | 29 + .../Drawing/LineJoin.cs | 30 + .../Drawing/NamespaceDoc.cs | 25 +- .../Drawing/PathStroker.cs | 101 +++ .../Drawing/StrokeOutliner.cs | 695 ++++++++++++++++++ .../Drawing/StrokePathFlattener.cs | 103 +++ .../Drawing/StrokeStyle.cs | 172 +++++ .../Drawing/DashSplitterTests.cs | 123 ++++ .../Drawing/PathStrokerTests.cs | 381 ++++++++++ .../Drawing/StrokeOutlinerTests.cs | 87 +++ .../Drawing/StrokePathFlattenerTests.cs | 127 ++++ .../Drawing/StrokeStyleTests.cs | 107 +++ 29 files changed, 3261 insertions(+), 69 deletions(-) create mode 100644 docs/design/canvas-net/drawing/path-stroker.md create mode 100644 docs/reqstream/canvas-net/drawing/path-stroker.yaml create mode 100644 docs/sysml2/model/canvas-net/drawing/path-stroker.sysml create mode 100644 docs/verification/canvas-net/drawing/path-stroker.md create mode 100644 src/DemaConsulting.CanvasNet/Drawing/DashSplitter.cs create mode 100644 src/DemaConsulting.CanvasNet/Drawing/LineCap.cs create mode 100644 src/DemaConsulting.CanvasNet/Drawing/LineJoin.cs create mode 100644 src/DemaConsulting.CanvasNet/Drawing/PathStroker.cs create mode 100644 src/DemaConsulting.CanvasNet/Drawing/StrokeOutliner.cs create mode 100644 src/DemaConsulting.CanvasNet/Drawing/StrokePathFlattener.cs create mode 100644 src/DemaConsulting.CanvasNet/Drawing/StrokeStyle.cs create mode 100644 test/DemaConsulting.CanvasNet.Tests/Drawing/DashSplitterTests.cs create mode 100644 test/DemaConsulting.CanvasNet.Tests/Drawing/PathStrokerTests.cs create mode 100644 test/DemaConsulting.CanvasNet.Tests/Drawing/StrokeOutlinerTests.cs create mode 100644 test/DemaConsulting.CanvasNet.Tests/Drawing/StrokePathFlattenerTests.cs create mode 100644 test/DemaConsulting.CanvasNet.Tests/Drawing/StrokeStyleTests.cs diff --git a/.reviewmark.yaml b/.reviewmark.yaml index 799f3e07a..af0706362 100644 --- a/.reviewmark.yaml +++ b/.reviewmark.yaml @@ -318,6 +318,32 @@ reviews: - "test/DemaConsulting.CanvasNet.Tests/Drawing/EdgeFlattenerTests.cs" # unit tests - "test/DemaConsulting.CanvasNet.Tests/Drawing/ScanlineRasterizerTests.cs" # unit tests + # CanvasNet-Drawing-PathStroker Review (one per unit) + - id: CanvasNet-Drawing-PathStroker + title: Review that CanvasNet Drawing PathStroker Implementation is Correct + context: + - "docs/design/canvas-net.md" + - "docs/reqstream/canvas-net.yaml" + - "docs/design/canvas-net/drawing.md" + - "docs/reqstream/canvas-net/drawing.yaml" + paths: + - "docs/reqstream/canvas-net/drawing/path-stroker.yaml" # unit requirements + - "docs/design/canvas-net/drawing/path-stroker.md" # unit design + - "docs/verification/canvas-net/drawing/path-stroker.md" # unit verification + - "src/DemaConsulting.CanvasNet/Drawing/LineCap.cs" # supporting enum source + - "src/DemaConsulting.CanvasNet/Drawing/LineJoin.cs" # supporting enum source + - "src/DemaConsulting.CanvasNet/Drawing/StrokeStyle.cs" # public style source + - "src/DemaConsulting.CanvasNet/Drawing/StrokePathFlattener.cs" # internal helper source + - "src/DemaConsulting.CanvasNet/Drawing/DashSplitter.cs" # internal helper source + - "src/DemaConsulting.CanvasNet/Drawing/StrokeOutliner.cs" # internal helper source + - "src/DemaConsulting.CanvasNet/Drawing/PathStroker.cs" # unit source + - "src/DemaConsulting.CanvasNet/Drawing/NamespaceDoc.cs" # Drawing namespace documentation + - "test/DemaConsulting.CanvasNet.Tests/Drawing/StrokeStyleTests.cs" # unit tests + - "test/DemaConsulting.CanvasNet.Tests/Drawing/StrokePathFlattenerTests.cs" # unit tests + - "test/DemaConsulting.CanvasNet.Tests/Drawing/DashSplitterTests.cs" # unit tests + - "test/DemaConsulting.CanvasNet.Tests/Drawing/StrokeOutlinerTests.cs" # unit tests + - "test/DemaConsulting.CanvasNet.Tests/Drawing/PathStrokerTests.cs" # unit tests + # OTS-BuildMark Review (one per OTS item) - id: OTS-BuildMark title: Review that BuildMark Provides Required Functionality diff --git a/README.md b/README.md index a4aeaffed..d3e61f95f 100644 --- a/README.md +++ b/README.md @@ -33,6 +33,8 @@ image operations using `Span`, and supports independent-copy cropping for loa - ๐Ÿ” **Header-Only Probing** - `GetInfo` reads only image headers (dimensions/channels/alpha) without decoding pixel data, letting callers triage untrusted files before calling `Load` - ๐Ÿ–Œ๏ธ **Path Filling** - Antialiased nonzero/even-odd fill of closed vector paths onto a `Surface` +- ๐Ÿ–Š๏ธ **Stroke-to-Fill** - Convert stroked vector paths (caps, joins, dashes, miter limits) into + fillable outline geometry and render them through the same antialiased fill pipeline - โšก **Span-Based** - Fast, allocation-conscious row and pixel access - ๐Ÿ”„ **Multi-Target** - Supports .NET 8, 9, and 10 - ๐Ÿ“ฆ **NuGet Ready** - Easy integration via NuGet package @@ -103,6 +105,31 @@ var triangle = new PathBuilder() PathFiller.Fill(canvas, triangle, new Rgba32(0, 128, 255, 255)); // antialiased solid fill ``` +Stroking a vector path onto a surface: + +```csharp +using DemaConsulting.CanvasNet.Canvas; +using DemaConsulting.CanvasNet.Drawing; +using DemaConsulting.CanvasNet.Geometry; +using System.Numerics; + +var canvas = new Surface(64, 64); +var polyline = new PathBuilder() + .MoveTo(new Vector2(8, 48)) + .LineTo(new Vector2(32, 16)) + .LineTo(new Vector2(56, 48)) + .Build(); + +var style = new StrokeStyle( + width: 6f, + cap: LineCap.Round, + join: LineJoin.Round, + dashArray: [10f, 6f]); + +var strokedOutline = PathStroker.Stroke(polyline, style); +PathFiller.Fill(canvas, strokedOutline, new Rgba32(255, 128, 0, 255)); +``` + ## Building ```pwsh diff --git a/docs/design/canvas-net.md b/docs/design/canvas-net.md index 173a6149d..138e572a4 100644 --- a/docs/design/canvas-net.md +++ b/docs/design/canvas-net.md @@ -33,16 +33,19 @@ DEMA Consulting best practices. The system consists of four implemented subsyste or `Codecs`, and neither of those subsystems depends on `Geometry`. See _Geometry Subsystem Design_ (`geometry.md`). - **Drawing subsystem** (namespace `DemaConsulting.CanvasNet.Drawing`, folder - `src/DemaConsulting.CanvasNet/Drawing/`, flat โ€” no further nesting): an antialiased - scanline-coverage fill rasterizer for closed `Geometry.Path` geometry with solid-color paint โ€” - the `PathFiller` unit (a public static `Fill` entry point, with the supporting `FillRule` enum - and the internal `EdgeFlattener`/`ScanlineRasterizer` helpers documented inline). `Drawing` - consumes both the `Canvas` subsystem's `Surface` unit (via `Surface.CompositeOverSpan`) and the - `Geometry` subsystem's `Path`/`BezierFlattening`/`SvgArcConverter` units; neither `Canvas` nor - `Geometry` depends on `Drawing`. `Geometry` is deliberately distinct from `Drawing`: `Geometry` - describes shape geometry (paths, bounds, curve math) with no notion of pixels, color, or - rasterization, while `Drawing` turns that geometry into pixels. Strokes, gradients, and fonts - are reserved for later phases. See _Drawing Subsystem Design_ (`drawing.md`). + `src/DemaConsulting.CanvasNet/Drawing/`, flat โ€” no further nesting): solid-color vector + rendering for `Geometry.Path` geometry through two public entry points โ€” the `PathFiller` unit + (a public static `Fill` entry point, with the supporting `FillRule` enum and the internal + `EdgeFlattener`/`ScanlineRasterizer` helpers documented inline) and the `PathStroker` unit (a + public static `Stroke` entry point, with the supporting `LineCap`/`LineJoin`/`StrokeStyle` + types and the internal `StrokePathFlattener`/`DashSplitter`/`StrokeOutliner` helpers documented + inline). `Drawing` consumes both the `Canvas` subsystem's `Surface` unit (via + `Surface.CompositeOverSpan`) and the `Geometry` subsystem's `Path`/`PathBuilder`/ + `BezierFlattening`/`SvgArcConverter` units; neither `Canvas` nor `Geometry` depends on + `Drawing`. `Geometry` is deliberately distinct from `Drawing`: `Geometry` describes shape + geometry (paths, bounds, curve math) with no notion of pixels, color, or rasterization, while + `Drawing` turns that geometry into pixels. Gradients and fonts are reserved for later phases. + See _Drawing Subsystem Design_ (`drawing.md`). The `Codecs` subsystem depends on the `Canvas` subsystem's `Surface` unit (constructing surfaces and reading/writing rows via `Surface.GetRowSpanBytes`); the `Canvas` subsystem has no dependency @@ -71,15 +74,20 @@ _Path Unit Design_ (`geometry/path.md`), _BezierFlattening Unit Design_ (`geometry/bezier-flattening.md`), and _SvgArcConverter Unit Design_ (`geometry/svg-arc-converter.md`) for each unit's internal collaboration. -The `Drawing` subsystem's single unit, `PathFiller`, collaborates as follows: `PathFiller.Fill` -first delegates to the internal `EdgeFlattener` (which converts the target `Geometry.Path`'s -subpaths to closed polygons, flattening curves via `Geometry.BezierFlattening` and arcs via +The `Drawing` subsystem's two units collaborate as follows. `PathFiller.Fill` first delegates to +the internal `EdgeFlattener` (which converts the target `Geometry.Path`'s subpaths to closed +polygons, flattening curves via `Geometry.BezierFlattening` and arcs via `Geometry.SvgArcConverter`), then computes the flattened polygons' bounds and intersects them with the `Canvas.Surface`'s pixel extent (a no-op if the path is empty or the intersection is empty), then delegates to the internal `ScanlineRasterizer` (which rasterizes those polygons into per-row -antialiased coverage and composites each row directly via `Canvas.Surface.CompositeOverSpan`). See -_Drawing Subsystem Design_ (`drawing.md`) and _PathFiller Unit Design_ -(`drawing/path-filler.md`) for full detail. +antialiased coverage and composites each row directly via `Canvas.Surface.CompositeOverSpan`). +`PathStroker.Stroke` runs earlier in the pipeline: it flattens each source subpath while +preserving `Subpath.IsClosed`, applies optional dash-array and dash-offset semantics, offsets the +visible polyline segments into closed outline polygons with cap and join geometry, and assembles +those polygons into a new `Geometry.Path` via `PathBuilder`; callers render the returned outline +path through `PathFiller.Fill`. See _Drawing Subsystem Design_ (`drawing.md`), _PathFiller Unit +Design_ (`drawing/path-filler.md`), and _PathStroker Unit Design_ (`drawing/path-stroker.md`) for +full detail. ## External Interfaces @@ -191,6 +199,16 @@ The system exposes the following public API to external consumers: Throws `ArgumentNullException` for a null `surface`/`path`, and `ArgumentOutOfRangeException` for an undefined `fillRule` value or a non-finite or non-positive `flattenTolerance`. +- **LineCap** / **LineJoin**: Public enums selecting stroke end-cap and corner-join geometry. +- **StrokeStyle(float width, LineCap cap, LineJoin join, float miterLimit, IReadOnlyList? dashArray, float dashOffset)**: + Immutable public stroke-style snapshot. Throws `ArgumentOutOfRangeException` for invalid width, + enum, miter-limit, or dash-offset values, and `ArgumentException` for invalid dash-array + entries. +- **PathStroker.Stroke(Path, StrokeStyle, float)**: Converts a `Path` plus `StrokeStyle` into a + new closed-outline `Path` suitable for filling with `FillRule.NonZero`. No-ops by returning + `Path.Empty` when the stroke contributes no visible area. Throws `ArgumentNullException` for a + null `path`/`style`, and `ArgumentOutOfRangeException` for a non-finite or non-positive + `flattenTolerance`. | Interface | Direction | Format | Constraints | | -------------------------------- | ---------------- | ------------------------------ | ----------------------------- | @@ -221,6 +239,8 @@ The system exposes the following public API to external consumers: | `BezierFlattening.Flatten*(...)` | Inbound/Outbound | Method call / list append | `tolerance` greater than zero | | `SvgArcConverter.ToBeziers(...)` | Inbound/Outbound | Method call / list append | None | | `PathFiller.Fill(...)` | Inbound | Method call | Non-null; fillRule ok; tol>0 | +| `StrokeStyle(...)` | Inbound | Constructor call | Width > 0; valid style data | +| `PathStroker.Stroke(...)` | Inbound/Outbound | Method call / `Path` return | Non-null; tol > 0 | ## Dependencies @@ -238,10 +258,12 @@ subsystem introduces zero new runtime NuGet dependencies: it is implemented enti `System.Numerics.Vector2` and `System.Numerics.Matrix3x2`, which are in-box BCL types available natively on every target framework this library supports (net8.0, net9.0, net10.0) โ€” no custom point/vector wrapper types were introduced. The `Drawing` subsystem likewise introduces zero new -runtime NuGet dependencies: `PathFiller`, `FillRule`, `EdgeFlattener`, and `ScanlineRasterizer` -are implemented entirely against `System.Numerics.Vector2`, in-box `List`/array types, and the -existing `Geometry` and `Canvas` subsystem APIs (`Path`, `BezierFlattening`, `SvgArcConverter`, -`Surface.CompositeOverSpan`) โ€” no new package reference was added to the project file. The +runtime NuGet dependencies: `PathFiller`, `FillRule`, `EdgeFlattener`, `ScanlineRasterizer`, +`PathStroker`, `LineCap`, `LineJoin`, `StrokeStyle`, `StrokePathFlattener`, `DashSplitter`, and +`StrokeOutliner` are implemented entirely against `System.Numerics.Vector2`, in-box `List`/ +array types, and the existing `Geometry` and `Canvas` subsystem APIs (`Path`, `PathBuilder`, +`BezierFlattening`, `SvgArcConverter`, `Surface.CompositeOverSpan`) โ€” no new package reference +was added to the project file. The following OTS items are used for building and verifying this system (not consumed at runtime); see _OTS Integration Design_ (`docs/design/ots.md`) and each item's dedicated design document for @@ -393,6 +415,20 @@ measures (IEC 62304 ยง5.3.3). pixels into the destination `Surface` 4. **Output**: A new `Surface` containing the decoded pixels +**Path stroke conversion path:** + +1. **Input**: Method parameters `path`, `style`, and optional `flattenTolerance` +2. **Validation**: `PathStroker.Stroke` rejects a null `path` or `style` with + `ArgumentNullException`, and rejects a non-positive or non-finite + `flattenTolerance` with `ArgumentOutOfRangeException`; `StrokeStyle` itself already + validated width, cap, join, miter limit, dash array, and dash offset at construction time +3. **Processing**: Each subpath is flattened while preserving open/closed state, optional dashes + are split into visible runs, each visible run is converted into one or more closed outline + polygons with cap/join geometry, and those polygons are assembled into a new `Path` via + `PathBuilder` +4. **Output**: A new closed-outline `Path` suitable for rendering through `PathFiller.Fill` with + `FillRule.NonZero` + ## Design Constraints - **Simplicity**: Minimal functionality kept easy to understand and extend @@ -427,3 +463,4 @@ APIs, or framework-version-specific features are used. - **CI/CD Integration**: Automated build, test, and quality validation - **Requirements Traceability**: All features linked to passing tests - **Review Management**: Systematic file review using ReviewMark patterns + diff --git a/docs/design/canvas-net/drawing.md b/docs/design/canvas-net/drawing.md index 7d6ca86d2..4cd6de6b7 100644 --- a/docs/design/canvas-net/drawing.md +++ b/docs/design/canvas-net/drawing.md @@ -2,26 +2,26 @@ ![Drawing Structure](DrawingView.svg) -The `Drawing` subsystem is the fourth software subsystem in CanvasNet. It provides an -antialiased scanline-coverage fill rasterizer for closed `Geometry.Path` geometry with -solid-color paint (`PathFiller`), consuming both the `Canvas` subsystem's `Surface` unit and the -`Geometry` subsystem's vector primitives. +The `Drawing` subsystem is the fourth software subsystem in CanvasNet. It provides solid-color +vector rendering for `Geometry.Path` geometry through two public entry points: +direct path filling (`PathFiller`) and stroke-to-fill conversion (`PathStroker`). It consumes +both the `Canvas` subsystem's `Surface` unit and the `Geometry` subsystem's vector primitives. ### Purpose The `Drawing` subsystem groups the software units responsible for turning vector geometry into -rendered pixels on a `Canvas.Surface`. It has exactly one unit this phase, `PathFiller`, which -fills a closed `Geometry.Path` with a single solid color using an antialiased -signed-area/coverage-accumulation scanline algorithm supporting both nonzero and even-odd fill -rules. `Geometry` is deliberately distinct from `Drawing`: `Geometry` describes shape geometry -(paths, bounds, curve math) with no notion of pixels, color, or rasterization; `Drawing` is where -that geometry is turned into pixels. `Drawing` depends on both `Canvas` (`Surface`, -`Surface.CompositeOverSpan`) and `Geometry` (`Path`, `BezierFlattening`, `SvgArcConverter`); -neither `Canvas` nor `Geometry` has any dependency on `Drawing`. Strokes (outlining a path rather -than filling it), gradients (multi-color paint), and fonts/text rendering are all reserved for -later phases and are not implemented by this subsystem yet โ€” there is deliberate room for future -sibling units (for example a future `PathStroker` unit) alongside `PathFiller` within this same -subsystem. +rendered pixels on a `Canvas.Surface`. It currently contains two sibling units: +`PathFiller`, which fills a closed `Geometry.Path` with a single solid color using an +antialiased signed-area/coverage-accumulation scanline algorithm supporting both nonzero and +even-odd fill rules; and `PathStroker`, which converts a path stroke (configured by width, cap, +join, miter limit, and optional dashing) into closed outline geometry that `PathFiller` can +render unchanged. `Geometry` is deliberately distinct from `Drawing`: `Geometry` describes shape +geometry (paths, bounds, curve math) with no notion of pixels, color, or rasterization; +`Drawing` is where that geometry is turned into pixels. `Drawing` depends on both `Canvas` +(`Surface`, `Surface.CompositeOverSpan`) and `Geometry` (`Path`, `PathBuilder`, +`BezierFlattening`, `SvgArcConverter`); neither `Canvas` nor `Geometry` has any dependency on +`Drawing`. Gradients (multi-color paint) and fonts/text rendering remain reserved for later +phases. ### Units @@ -31,6 +31,11 @@ subsystem. `EdgeFlattener`/`ScanlineRasterizer` helpers, all documented inline within the `PathFiller` unit design rather than as their own units, because none of them has any independent behavior beyond supporting `PathFiller.Fill`; see _PathFiller Unit Design_ (`drawing/path-filler.md`) +- **PathStroker** โ€” a public static `Stroke` entry point that converts a `Path` centerline plus a + `StrokeStyle` into one or more closed outline polygons expressed as a new `Path`, together with + the supporting public `LineCap`, `LineJoin`, and `StrokeStyle` types and the internal + `StrokePathFlattener`/`DashSplitter`/`StrokeOutliner` helpers, all documented inline within the + `PathStroker` unit design; see _PathStroker Unit Design_ (`drawing/path-stroker.md`) ### Dependencies @@ -41,12 +46,19 @@ reference was introduced. Within the subsystem, `PathFiller.Fill` depends on the `EdgeFlattener` (to convert a `Path`'s subpaths to closed polygons, itself depending on `Geometry.BezierFlattening` and `Geometry.SvgArcConverter` to flatten curves and arcs) and the internal `ScanlineRasterizer` (to rasterize those polygons into per-row antialiased coverage and -composite each row via `Canvas.Surface.CompositeOverSpan`). +composite each row via `Canvas.Surface.CompositeOverSpan`). `PathStroker.Stroke` depends on the +internal `StrokePathFlattener` (to flatten each subpath while preserving `Subpath.IsClosed`), +`DashSplitter` (to apply dash-array and dash-offset semantics), and `StrokeOutliner` (to offset +segments and resolve joins/caps into closed polygons), plus `Geometry.PathBuilder` to assemble the +returned outline path. ### Callers -`PathFiller.Fill` is a public API entry point, invoked externally by consumers of the CanvasNet -package. It is exercised end to end by this subsystem's own unit tests, and by a -system-integration test that builds a `Path` via `PathBuilder` and fills it onto a `Surface` (see -`CanvasNetTests.cs`). The `Drawing` subsystem itself has no dependency on `Codecs`; it depends on -`Canvas` and `Geometry` as described above. +`PathFiller.Fill` and `PathStroker.Stroke` are public API entry points, invoked externally by +consumers of the CanvasNet package. `PathFiller` is exercised end to end by this subsystem's own +unit tests and by a system-integration test that builds a `Path` via `PathBuilder` and fills it +onto a `Surface` (see `CanvasNetTests.cs`). `PathStroker` is exercised end to end by its own unit +tests, which stroke a path, fill the returned outline path, and inspect the resulting pixels. The +`Drawing` subsystem itself has no dependency on `Codecs`; it depends on `Canvas` and `Geometry` +as described above. + diff --git a/docs/design/canvas-net/drawing/path-stroker.md b/docs/design/canvas-net/drawing/path-stroker.md new file mode 100644 index 000000000..664552cc3 --- /dev/null +++ b/docs/design/canvas-net/drawing/path-stroker.md @@ -0,0 +1,154 @@ + + +## PathStroker + +![Drawing Structure](DrawingView.svg) + +The `PathStroker` unit converts vector strokes into ordinary closed `Geometry.Path` outline +geometry that the existing `PathFiller` unit can rasterize unchanged. It also covers the public +`StrokeStyle`, `LineCap`, and `LineJoin` types, and the internal `StrokePathFlattener`, +`DashSplitter`, and `StrokeOutliner` helpers. + +### Purpose + +`PathStroker` exists so CanvasNet can render strokes without introducing a second rasterizer. +Rather than painting pixels directly, it transforms an input centerline path into one or more +closed outline polygons describing the exact area the stroke should occupy. The caller can then +render those polygons through `PathFiller.Fill(..., FillRule.NonZero, ...)`, obtaining the same +analytic antialiasing and compositing behavior fills already use. This design keeps stroke +rendering and fill rendering on one coverage-computation path, which reduces implementation +duplication and ensures the two public APIs agree on how pixel coverage is resolved. + +### Data Model + +| Type | Description | +| --- | --- | +| `LineCap` | Public enum selecting butt, round, or square end-cap geometry for open stroked segments. | +| `LineJoin` | Public enum selecting miter, round, or bevel corner-join geometry. | +| `StrokeStyle` | Public immutable style snapshot containing width, cap, join, miter limit, and dash settings. | +| `StrokePathFlattener` | Internal helper that flattens each subpath while preserving `Subpath.IsClosed`. | +| `DashSplitter` | Internal helper that applies dash-array and dash-offset semantics to a flattened polyline. | +| `StrokeOutliner` | Internal helper that converts one flattened polyline into outline polygons. | +| `PathStroker` | Public static entry point that orchestrates flattening, dashing, and outlining. | + +`StrokeStyle` is intentionally immutable and thread-safe after construction. The constructor +copies a non-empty dash array into a private read-only snapshot rather than retaining a caller's +mutable collection reference, so a stroke style cannot be changed after creation by mutating the +original list elsewhere. This is important because dash phase and width are visible rendering +behavior; a caller must be able to reuse the same `StrokeStyle` instance across many paths and +receive identical outline geometry every time. + +### Key Methods + +#### StrokeStyle.StrokeStyle(...) + +The constructor validates every public styling input at the API boundary, mirroring +`PathFiller.Fill`'s own validation conventions: + +- `Width` must be finite and greater than zero. +- `Cap` and `Join` must be defined enum values. +- `MiterLimit` must be finite and greater than or equal to one, matching the SVG/PostScript + interpretation of `stroke-miterlimit` as a ratio. +- `DashArray` may be null or empty for a solid stroke; otherwise every entry must be finite and + greater than or equal to zero, and the array must not consist entirely of zeros. +- `DashOffset` must be finite. + +This constructor deliberately performs all dash-array validation once, up front, rather than +having `PathStroker` rediscover invalid style data every time a path is stroked. The style is the +caller-controlled configuration object; rejecting bad values there keeps the conversion pipeline +itself focused only on geometry. + +#### PathStroker.Stroke(Path path, StrokeStyle style, float flattenTolerance) + +`Stroke` performs stroke-to-fill conversion in three geometry-only stages, then emits the result +as a brand-new `Path`: + +1. **Flatten while preserving open/closed state.** `StrokePathFlattener` walks each + `Subpath` exactly once, converting lines directly, flattening quadratic/cubic Beziers via + `BezierFlattening`, and converting arcs via `SvgArcConverter.ToBeziers` followed by cubic + flattening. Unlike `EdgeFlattener`, it never appends an implicit closing point for open + subpaths; `Subpath.IsClosed` is preserved verbatim because stroking must distinguish end caps + from shell rings. +2. **Apply dashing in path-length space.** `DashSplitter` interprets the dash array as + alternating on/off lengths, conceptually duplicates odd-length arrays to preserve the standard + repeating on/off cycle, phase-shifts the pattern by `DashOffset`, and returns only the visible + "on" segments. When a closed contour's visible dash run wraps across the seam, the helper + stitches the two halves back into one contiguous segment so the stroke has one join sequence + rather than two artificial caps at the seam. +3. **Outline each visible segment.** `StrokeOutliner` offsets each segment by half the stroke + width on both sides and resolves the corners and ends into plain polygon vertices: + - **Open segments** produce one closed polygon built from the left side, an end cap, the right + side in reverse, and the start cap. + - **Closed contours** produce two closed rings (outer and inner) wound in opposite directions + so `FillRule.NonZero` fills only the shell between them. + - **Miter joins** intersect the two offset lines and then compare the distance from the source + vertex to that intersection against `MiterLimit * Width`. When the ratio exceeds the limit, + the join falls back to a bevel. + - **Round joins and round caps** are tessellated as circular arcs whose sagitta is bounded by + `flattenTolerance`, reusing the same tolerance concept already established for curve + flattening elsewhere in the library. + +The returned path is assembled through `PathBuilder`; `PathStroker` never constructs `Path` +instances directly. Every emitted polygon becomes one closed subpath in the result, and +`Path.Empty` is returned when no outline polygon is produced. + +#### StrokeOutliner.Outline(...) (internal) + +`StrokeOutliner` carries most of the geometry-specific design decisions: + +- **Open-side join handling.** For an open polyline, the side of the stroke on the outside of a + turn receives the caller-selected join style (`Miter`, `Round`, or `Bevel`). The opposite side + is the clipped "inside" of the turn and is connected directly between its two offset endpoints, + because the visible outline there is the boundary of the union of two segment rectangles rather + than the infinite-line intersection of their offsets. +- **Closed-side join handling.** For a closed contour, both the outer and inner rings are genuine + offset curves, so each vertex is handled with the requested join style on that ring. +- **Degenerate subpaths.** A single point (or a path collapsed to one effective point after + duplicate-vertex simplification) renders as a cap-shaped mark: round creates a full circle, + square creates an axis-aligned width-by-width square, and butt creates nothing. + +The helper intentionally removes only redundant consecutive duplicate vertices. It does not try to +topologically simplify self-intersections or reorder segments; the contract is to preserve the +input path's authored shape, not to reinterpret it. + +### Complexity + +The total conversion cost is the sum of three bounded passes over the path data. Flattening is +the same adaptive-subdivision cost already documented for `BezierFlattening`; dashing is linear in +the number of emitted dash boundaries plus the number of polyline edges those boundaries cross; +and outlining is linear in the number of resulting polyline vertices plus the tessellated points +added for round joins and caps. A bevel or miter join adds at most two vertices per corner, while +round joins and caps add a number of vertices proportional to the swept arc angle divided by the +maximum allowed arc step derived from `flattenTolerance`. + +These properties are verified by design review and code review rather than timing-based unit +tests. This mirrors the existing `PathFiller` design decision: wall-clock assertions are not a +stable proof of algorithmic behavior on heterogeneous CI hardware, while the geometric pass +structure and bounded per-vertex/per-arc work are visible directly in the implementation. + +### Error Handling + +`PathStroker.Stroke` performs the public API validation: + +- `ArgumentNullException` when `path` or `style` is null. +- `ArgumentOutOfRangeException` when `flattenTolerance` is non-finite or less than or equal to + zero. + +The internal helpers assume they receive already-validated input from `PathStroker`. Likewise, +`StrokeStyle` performs its own constructor validation and throws `ArgumentOutOfRangeException` or +`ArgumentException` before a style instance is ever created. + +### Dependencies + +`PathStroker` depends on the `Geometry` subsystem's `Path`, `Subpath`, `PathCommand`, +`PathBuilder`, `BezierFlattening`, and `SvgArcConverter` types, and on `System.Numerics.Vector2` +for the underlying geometry math. It has no direct dependency on `Canvas.Surface` because it does +not rasterize; callers render its result through `PathFiller`, which in turn depends on the +`Canvas` subsystem. No new runtime NuGet package is introduced by this unit. + +### Callers + +`PathStroker.Stroke` is a public API entry point, invoked directly by consumers of the CanvasNet +package and indirectly by the README and User Guide examples that demonstrate stroking followed by +filling. The unit is exercised by `PathStrokerTests` end to end, and by dedicated internal-helper +tests for flattening, dash semantics, and outline geometry. diff --git a/docs/design/introduction.md b/docs/design/introduction.md index 1fc64615a..0600dc7af 100644 --- a/docs/design/introduction.md +++ b/docs/design/introduction.md @@ -38,8 +38,10 @@ software items, specifically: - **Drawing (Subsystem)** โ€” An antialiased scanline-coverage fill rasterizer for closed `Geometry.Path` geometry with solid-color paint: the `PathFiller` unit (a public static `Fill` entry point, covering the supporting `FillRule` enum and the internal - `EdgeFlattener`/`ScanlineRasterizer` helpers inline). Strokes, gradients, and fonts are - reserved for later phases. + `EdgeFlattener`/`ScanlineRasterizer` helpers inline), and the `PathStroker` unit (a public + static `Stroke` entry point, covering the supporting `LineCap`/`LineJoin`/`StrokeStyle` types + and the internal `StrokePathFlattener`/`DashSplitter`/`StrokeOutliner` helpers inline). + Gradients and fonts are reserved for later phases. The following OTS items are also covered: @@ -80,7 +82,9 @@ CanvasNet is organized into four subsystems under the system level: the `Canvas` flat โ€” no further nesting), the `Geometry` subsystem (the `Rect`, `Path`, `BezierFlattening`, and `SvgArcConverter` units, namespace `DemaConsulting.CanvasNet.Geometry`, flat โ€” no further nesting), and the `Drawing` subsystem (the `PathFiller` unit, covering the supporting `FillRule` enum and -the internal `EdgeFlattener`/`ScanlineRasterizer` helpers inline, namespace +the internal `EdgeFlattener`/`ScanlineRasterizer` helpers inline, and the `PathStroker` unit, +covering the supporting `LineCap`/`LineJoin`/`StrokeStyle` types and the internal +`StrokePathFlattener`/`DashSplitter`/`StrokeOutliner` helpers inline, namespace `DemaConsulting.CanvasNet.Drawing`, flat โ€” no further nesting). As additional functionality is added, further subsystems and nested subsystems would organize related units and provide architectural boundaries with well-defined interfaces and responsibilities. @@ -117,13 +121,21 @@ src/DemaConsulting.CanvasNet/ โ”œโ”€โ”€ EdgeFlattener.cs โ€” Converts a Path's subpaths into closed polygons โ”œโ”€โ”€ ScanlineRasterizer.cs โ€” Analytic coverage-accumulation scanline rasterizer โ”œโ”€โ”€ PathFiller.cs โ€” Public entry point: fills a Path onto a Surface + โ”œโ”€โ”€ LineCap.cs โ€” Stroke end-cap enumeration + โ”œโ”€โ”€ LineJoin.cs โ€” Stroke corner-join enumeration + โ”œโ”€โ”€ StrokeStyle.cs โ€” Immutable stroke-style configuration snapshot + โ”œโ”€โ”€ StrokePathFlattener.cs โ€” Flattens subpaths while preserving open/closed state + โ”œโ”€โ”€ DashSplitter.cs โ€” Applies dash-array and dash-offset semantics + โ”œโ”€โ”€ StrokeOutliner.cs โ€” Converts stroked polylines into outline polygons + โ”œโ”€โ”€ PathStroker.cs โ€” Public entry point: strokes a Path into outline geometry โ””โ”€โ”€ NamespaceDoc.cs โ€” Namespace-level XML documentation ``` This four-subsystem folder structure reflects the small number of subsystems in the system today. As the system grows with additional subsystems and units, the folder structure will -expand further to mirror the software architecture. `Canvas/Surface.cs` also gained a new -`CompositeOverSpan` method this phase, consumed internally by `Drawing/PathFiller.cs`. +expand further to mirror the software architecture. `Canvas/Surface.cs` also gained a +`CompositeOverSpan` method used internally by `Drawing/PathFiller.cs`, and the `Drawing` +subsystem now includes the additional stroking files listed above. ## Document Conventions @@ -152,3 +164,4 @@ Each software item has corresponding artifacts in parallel directory trees: - CanvasNet User Guide โ€” the compiled User Guide document for this repository. - CanvasNet Repository โ€” the CanvasNet source repository hosted on GitHub. + diff --git a/docs/reqstream/canvas-net.yaml b/docs/reqstream/canvas-net.yaml index 47fdf02ca..e24268e5b 100644 --- a/docs/reqstream/canvas-net.yaml +++ b/docs/reqstream/canvas-net.yaml @@ -787,3 +787,58 @@ sections: - PathFiller_Fill_NullPath_ThrowsArgumentNullException - PathFiller_Fill_NonPositiveFlattenTolerance_ThrowsArgumentOutOfRangeException - PathFiller_Fill_UndefinedFillRule_ThrowsArgumentOutOfRangeException + + - id: CanvasNet-Lib-DrawingPathStroke + title: >- + The library shall convert a Path stroke into a new closed Path suitable for nonzero-rule + filling, reflecting the configured width, cap shape, join shape, dash pattern, and + curve-flattening tolerance. + tags: [system] + justification: | + Stroke-to-fill conversion exposes standard vector stroking behavior while keeping one + rendering pipeline for both fills and strokes; callers can stroke a path, inspect or + reuse the returned outline geometry, then render it through the existing fill API. + children: + - CanvasNet-Drawing-PathStroke + tests: + - PathStroker_Stroke_HorizontalLineButtCap_FillsExactRectangleNoExtension + - PathStroker_Stroke_HorizontalLineRoundCap_FillsRectanglePlusSemicircularEnds + - PathStroker_Stroke_HorizontalLineSquareCap_FillsRectanglePlusHalfWidthExtension + - PathStroker_Stroke_RightAngleCornerMiterJoin_FillsSharpMiteredCorner + - PathStroker_Stroke_RightAngleCornerRoundJoin_FillsRoundedCorner + - PathStroker_Stroke_RightAngleCornerBevelJoin_FillsFlatBeveledCorner + - PathStroker_Stroke_DashedLine_FillsOnlyOnSegmentsLeavingGapsUnfilled + + - id: CanvasNet-Lib-DrawingPathStrokeNoOp + title: >- + The library shall return an empty Path, without throwing, when stroking an empty Path or + when the requested stroke contributes no visible area. + tags: [system] + justification: | + Callers routinely stroke optional or partially constructed geometry; an empty result + must be a cheap, well-defined no-op rather than a special case callers must detect. + children: + - CanvasNet-Drawing-PathStrokeNoOp + tests: + - PathStroker_Stroke_ClosedRectangle_FillsRingLeavingInteriorAndExteriorUnfilled + - PathStroker_Stroke_ZeroLengthSubpathRoundCap_FillsCircleOfRadiusHalfWidth + - PathStroker_Stroke_ZeroLengthSubpathSquareCap_FillsSquareOfSideWidth + - PathStroker_Stroke_ZeroLengthSubpathButtCap_ProducesNoFilledPixels + - PathStroker_Stroke_SinglePointSubpath_MatchesZeroLengthSubpathBehavior + - PathStroker_Stroke_EmptyPath_ReturnsEmptyPathNoOp + + - id: CanvasNet-Lib-DrawingPathStrokeValidation + title: >- + The library shall reject a null Path or stroke-style argument to the stroke operation + with ArgumentNullException, and shall reject a non-positive or non-finite + flatten-tolerance argument with ArgumentOutOfRangeException. + tags: [system] + justification: | + A null path or style cannot supply valid stroke geometry, and a non-positive or + non-finite flattening tolerance cannot bound curve approximation meaningfully. + children: + - CanvasNet-Drawing-PathStrokeValidation + tests: + - PathStroker_Stroke_NullPath_ThrowsArgumentNullException + - PathStroker_Stroke_NullStrokeStyle_ThrowsArgumentNullException + - PathStroker_Stroke_NonPositiveFlattenTolerance_ThrowsArgumentOutOfRangeException diff --git a/docs/reqstream/canvas-net/drawing.yaml b/docs/reqstream/canvas-net/drawing.yaml index 1d9c66522..43253839f 100644 --- a/docs/reqstream/canvas-net/drawing.yaml +++ b/docs/reqstream/canvas-net/drawing.yaml @@ -77,3 +77,66 @@ sections: - PathFiller_Fill_NullPath_ThrowsArgumentNullException - PathFiller_Fill_NonPositiveFlattenTolerance_ThrowsArgumentOutOfRangeException - PathFiller_Fill_UndefinedFillRule_ThrowsArgumentOutOfRangeException + + - id: CanvasNet-Drawing-PathStroke + title: >- + The Drawing subsystem shall convert a Path stroke into closed outline geometry whose + rendered appearance reflects the configured width, cap shape, join shape, dash + pattern, and curve-flattening tolerance. + justification: | + Solid-color stroke rendering is the natural companion to fill rendering; callers need + the standard vector-stroke appearance controls without a second rasterization API. + children: + - CanvasNet-Drawing-PathStroker-Stroke + - CanvasNet-Drawing-PathStroker-Caps + - CanvasNet-Drawing-PathStroker-Joins + - CanvasNet-Drawing-PathStroker-MiterLimit + - CanvasNet-Drawing-PathStroker-Dashing + - CanvasNet-Drawing-PathStroker-StyleValidation + - CanvasNet-Drawing-PathStroker-OpenClosedPreservation + - CanvasNet-Drawing-PathStroker-DashPhaseSemantics + tests: + - PathStroker_Stroke_HorizontalLineButtCap_FillsExactRectangleNoExtension + - PathStroker_Stroke_HorizontalLineRoundCap_FillsRectanglePlusSemicircularEnds + - PathStroker_Stroke_HorizontalLineSquareCap_FillsRectanglePlusHalfWidthExtension + - PathStroker_Stroke_RightAngleCornerMiterJoin_FillsSharpMiteredCorner + - PathStroker_Stroke_RightAngleCornerRoundJoin_FillsRoundedCorner + - PathStroker_Stroke_RightAngleCornerBevelJoin_FillsFlatBeveledCorner + - PathStroker_Stroke_DashedLine_FillsOnlyOnSegmentsLeavingGapsUnfilled + + - id: CanvasNet-Drawing-PathStrokeNoOp + title: >- + The Drawing subsystem shall return an empty path, without throwing, when stroking an + empty Path or a Path whose visible stroke reduces entirely to omitted dash gaps or + butt-capped zero-length segments. + justification: | + Callers routinely stroke conditional or partially constructed geometry; an empty + stroke result must be a cheap, well-defined no-op rather than a special case callers + must detect themselves. + children: + - CanvasNet-Drawing-PathStroker-DegenerateSubpaths + - CanvasNet-Drawing-PathStroker-ClosedContours + - CanvasNet-Drawing-PathStroker-EmptyNoOp + - CanvasNet-Drawing-PathStroker-ShellWinding + tests: + - PathStroker_Stroke_ClosedRectangle_FillsRingLeavingInteriorAndExteriorUnfilled + - PathStroker_Stroke_ZeroLengthSubpathRoundCap_FillsCircleOfRadiusHalfWidth + - PathStroker_Stroke_ZeroLengthSubpathSquareCap_FillsSquareOfSideWidth + - PathStroker_Stroke_ZeroLengthSubpathButtCap_ProducesNoFilledPixels + - PathStroker_Stroke_SinglePointSubpath_MatchesZeroLengthSubpathBehavior + - PathStroker_Stroke_EmptyPath_ReturnsEmptyPathNoOp + + - id: CanvasNet-Drawing-PathStrokeValidation + title: >- + The Drawing subsystem shall reject a null Path or stroke-style argument with + ArgumentNullException, and shall reject a non-positive or non-finite + flatten-tolerance argument with ArgumentOutOfRangeException. + justification: | + A null path or style cannot supply valid stroke geometry, and a non-positive or + non-finite flattening tolerance cannot bound curve approximation meaningfully. + children: + - CanvasNet-Drawing-PathStroker-Validation + tests: + - PathStroker_Stroke_NullPath_ThrowsArgumentNullException + - PathStroker_Stroke_NullStrokeStyle_ThrowsArgumentNullException + - PathStroker_Stroke_NonPositiveFlattenTolerance_ThrowsArgumentOutOfRangeException diff --git a/docs/reqstream/canvas-net/drawing/path-stroker.yaml b/docs/reqstream/canvas-net/drawing/path-stroker.yaml new file mode 100644 index 000000000..fce222ed3 --- /dev/null +++ b/docs/reqstream/canvas-net/drawing/path-stroker.yaml @@ -0,0 +1,189 @@ +--- +# cspell:ignore Outliner strokable +# Software Unit Requirements for PathStroker +# +# These requirements describe the design-level behavior of the PathStroker unit within the +# Drawing subsystem. PathStroker is a public static class exposing a single Stroke entry point; +# it is supported by the public StrokeStyle/LineCap/LineJoin types and the internal +# StrokePathFlattener/DashSplitter/StrokeOutliner helpers documented here as part of the same +# unit. + +sections: + - title: CanvasNet Requirements + sections: + - title: Drawing Requirements + sections: + - title: PathStroker Requirements + requirements: + - id: CanvasNet-Drawing-PathStroker-Stroke + title: >- + The PathStroker class shall convert a path and stroke style into a new path + whose closed subpaths describe the stroked area, suitable for filling with the + nonzero fill rule at the specified curve-flattening tolerance. + justification: | + Stroke-to-fill conversion lets the library reuse one antialiased rasterization + pipeline for both fills and strokes, while still exposing a public stroking API + callers can compose or inspect before rendering. + tests: + - PathStroker_Stroke_HorizontalLineButtCap_FillsExactRectangleNoExtension + + - id: CanvasNet-Drawing-PathStroker-Caps + title: >- + The PathStroker class shall support butt, round, and square end-cap shapes for + open stroked segments, rendering no extension, semicircular ends, or half-width + square extension respectively. + justification: | + End-cap shape is a visible part of a stroke's public appearance, especially for + open polylines and dashed segments whose individual dash runs each expose two + ends. + tests: + - PathStroker_Stroke_HorizontalLineButtCap_FillsExactRectangleNoExtension + - PathStroker_Stroke_HorizontalLineRoundCap_FillsRectanglePlusSemicircularEnds + - PathStroker_Stroke_HorizontalLineSquareCap_FillsRectanglePlusHalfWidthExtension + + - id: CanvasNet-Drawing-PathStroker-Joins + title: >- + The PathStroker class shall support miter, round, and bevel corner joins for + open stroked polylines, rendering a sharp point, rounded corner, or flat clipped + corner respectively. + justification: | + Join shape is a primary visible characteristic of vector strokes, and callers + need the standard corner styles offered by other 2D graphics APIs. + tests: + - PathStroker_Stroke_RightAngleCornerMiterJoin_FillsSharpMiteredCorner + - PathStroker_Stroke_RightAngleCornerRoundJoin_FillsRoundedCorner + - PathStroker_Stroke_RightAngleCornerBevelJoin_FillsFlatBeveledCorner + + - id: CanvasNet-Drawing-PathStroker-MiterLimit + title: >- + The PathStroker class shall fall back from a sharp mitered corner to a flat + beveled corner when the configured miter limit is exceeded. + justification: | + Sharp-angled strokes can produce unbounded miter spikes; a caller-configurable + limit keeps the rendered geometry bounded and matches the behavior callers expect + from SVG-style stroke rendering. + tests: + - PathStroker_Stroke_SharpAngleExceedingMiterLimit_FallsBackToBevel + + - id: CanvasNet-Drawing-PathStroker-ClosedContours + title: >- + The PathStroker class shall stroke a closed contour as a shell whose exterior and + interior boundaries remain unfilled outside the stroke band and within the + original contour's interior. + justification: | + A closed stroked outline is visually a ring, not a solid expansion of the + entire shape, so the returned path must preserve the hole between the outer and + inner boundaries. + tests: + - PathStroker_Stroke_ClosedRectangle_FillsRingLeavingInteriorAndExteriorUnfilled + + - id: CanvasNet-Drawing-PathStroker-Dashing + title: >- + The PathStroker class shall apply dash arrays and dash offsets so that only the + visible dash runs are stroked, leaving the gap runs unfilled. + justification: | + Dashed strokes are a standard vector-graphics feature and must be visibly + equivalent to repeatedly starting and stopping the stroke along the path. + tests: + - PathStroker_Stroke_DashedLine_FillsOnlyOnSegmentsLeavingGapsUnfilled + + - id: CanvasNet-Drawing-PathStroker-DegenerateSubpaths + title: >- + The PathStroker class shall stroke a zero-length or single-point subpath as a + cap-shaped mark: a full circle for round caps, a width-by-width square for + square caps, and no rendered area for butt caps. + justification: | + Degenerate path segments arise in real-world vector data and still need a + deterministic visible result where standard stroke semantics define one. + tests: + - PathStroker_Stroke_ZeroLengthSubpathRoundCap_FillsCircleOfRadiusHalfWidth + - PathStroker_Stroke_ZeroLengthSubpathSquareCap_FillsSquareOfSideWidth + - PathStroker_Stroke_ZeroLengthSubpathButtCap_ProducesNoFilledPixels + - PathStroker_Stroke_SinglePointSubpath_MatchesZeroLengthSubpathBehavior + + - id: CanvasNet-Drawing-PathStroker-EmptyNoOp + title: >- + The PathStroker class shall return an empty path, without throwing, when the + input path contains no strokable geometry or every visible dash run is omitted. + justification: | + Callers routinely compose paths incrementally or stroke conditional geometry; an + empty result must be a cheap, well-defined no-op rather than a special case. + tests: + - PathStroker_Stroke_EmptyPath_ReturnsEmptyPathNoOp + + - id: CanvasNet-Drawing-PathStroker-Validation + title: >- + The PathStroker class shall reject a null path or stroke style with + ArgumentNullException, and shall reject a non-positive or non-finite + flatten-tolerance argument with ArgumentOutOfRangeException. + justification: | + A null path or style cannot supply valid stroke geometry, and a non-positive or + non-finite flattening tolerance cannot bound curve approximation meaningfully. + tests: + - PathStroker_Stroke_NullPath_ThrowsArgumentNullException + - PathStroker_Stroke_NullStrokeStyle_ThrowsArgumentNullException + - PathStroker_Stroke_NonPositiveFlattenTolerance_ThrowsArgumentOutOfRangeException + + - id: CanvasNet-Drawing-PathStroker-StyleValidation + title: >- + The PathStroker unit shall reject an invalid stroke width, miter limit, or dash + pattern, while preserving the caller-specified valid stroke-style values without + modification. + justification: | + Stroke styling is entirely caller-controlled data; invalid style values must fail + fast at construction time, while valid values must round-trip exactly so later + stroke conversion is predictable. + tests: + - StrokeStyle_Constructor_NonPositiveWidth_ThrowsArgumentOutOfRangeException + - StrokeStyle_Constructor_MiterLimitBelowOne_ThrowsArgumentOutOfRangeException + - StrokeStyle_Constructor_DefaultMiterLimit_IsFour + - StrokeStyle_Constructor_NullOrEmptyDashArray_IsTreatedAsSolid + - StrokeStyle_Constructor_DashArrayWithNegativeEntry_ThrowsArgumentException + - StrokeStyle_Constructor_DashArrayAllZero_ThrowsArgumentException + - StrokeStyle_Constructor_ValidValues_PropertiesRoundTrip + + - id: CanvasNet-Drawing-PathStroker-OpenClosedPreservation + title: >- + The PathStroker unit shall preserve whether each source subpath is open or + closed while flattening curves, because open subpaths require end caps and closed + subpaths require shell boundaries with no caps. + justification: | + Filling deliberately ignores open-vs-closed state, but stroking cannot: the + rendered appearance changes visibly at every path end. + tests: + - StrokePathFlattener_Flatten_OpenSubpath_PreservesIsClosedFalse + - StrokePathFlattener_Flatten_ClosedSubpath_PreservesIsClosedTrueWithNoImplicitDuplicatePoint + - StrokePathFlattener_Flatten_CurveCommands_DelegatesToBezierFlattening + - StrokePathFlattener_Flatten_MultipleSubpaths_RemainSeparate + - StrokePathFlattener_Flatten_EmptyPath_ReturnsEmptyList + + - id: CanvasNet-Drawing-PathStroker-DashPhaseSemantics + title: >- + The PathStroker unit shall interpret odd-length dash arrays as repeating on/off + cycles, phase-shift the visible dash runs by the dash offset, and stitch a + closed contour's seam-crossing visible dash run into one contiguous segment. + justification: | + Dash patterns are visible public styling behavior; callers expect the same + repeating-cycle and seam-wrapping semantics they see in established vector + graphics systems. + tests: + - DashSplitter_Split_NullOrEmptyDashArray_ReturnsWholeSegmentUnchanged + - DashSplitter_Split_OddLengthDashArray_DuplicatesArrayConceptually + - DashSplitter_Split_WithDashOffset_ShiftsPhaseOfFirstSegment + - DashSplitter_Split_ClosedPolylineDashWrappingSeam_StitchesSegmentAcrossStartPoint + - DashSplitter_Split_PatternLongerThanPolyline_ReturnsSinglePartialOnSegment + - DashSplitter_Split_AllZeroDashArray_TreatedAsSolid + + - id: CanvasNet-Drawing-PathStroker-ShellWinding + title: >- + The PathStroker unit shall produce opposite-wound outer and inner shell + boundaries for a closed stroked contour, and shall bevel rather than spike a + sharp corner when the configured miter limit is exceeded. + justification: | + The returned outline path is intended for filling under the nonzero fill rule; + opposite winding between the outer and inner shell boundaries is what makes the + interior hole remain unfilled. + tests: + - StrokeOutliner_Outline_ClosedSubpath_ProducesTwoCounterWoundRings + - StrokeOutliner_Outline_MiterJoinWithinLimit_ProducesSharpVertex + - StrokeOutliner_Outline_MiterJoinExceedingLimit_FallsBackToBevelVertex diff --git a/docs/sysml2/model/canvas-net.sysml b/docs/sysml2/model/canvas-net.sysml index 8d5a24d63..de9b1d8fe 100644 --- a/docs/sysml2/model/canvas-net.sysml +++ b/docs/sysml2/model/canvas-net.sysml @@ -12,7 +12,7 @@ package CanvasNet { comment designRef /* Design: docs/design/canvas-net.md */ comment verificationRef /* Verification: docs/verification/canvas-net.md */ comment reqRef /* Requirements: docs/reqstream/canvas-net.yaml */ - comment /* The Drawing subsystem rasterizes Geometry.Path geometry onto a Canvas.Surface (PathFiller); strokes/gradients/fonts are reserved for later phases. */ + comment /* The Drawing subsystem renders Geometry.Path geometry onto a Canvas.Surface through PathFiller (direct fill) and PathStroker (stroke-to-fill conversion); gradients/fonts are reserved for later phases. */ part canvas : Canvas; part codecs : Codecs; @@ -20,4 +20,3 @@ package CanvasNet { part drawing : Drawing; } } - diff --git a/docs/sysml2/model/canvas-net/drawing.sysml b/docs/sysml2/model/canvas-net/drawing.sysml index 0f523c643..9a7781884 100644 --- a/docs/sysml2/model/canvas-net/drawing.sysml +++ b/docs/sysml2/model/canvas-net/drawing.sysml @@ -1,11 +1,12 @@ package CanvasNet { part def Drawing { - doc /* Antialiased scanline-coverage fill rasterizer subsystem for closed Geometry.Path geometry with solid-color paint (PathFiller, covering FillRule and the internal EdgeFlattener/ScanlineRasterizer helpers inline). Consumes Canvas.Surface and Geometry.Path; neither Canvas nor Geometry depends on Drawing. Strokes/gradients/fonts reserved for later phases. */ + doc /* Antialiased solid-color vector-rendering subsystem for Geometry.Path geometry. Provides both PathFiller (direct path filling) and PathStroker (stroke-to-fill conversion with standard cap/join/dash styling), consuming Canvas.Surface and Geometry.Path; neither Canvas nor Geometry depends on Drawing. Gradients/fonts remain reserved for later phases. */ comment designRef /* Design: docs/design/canvas-net/drawing.md */ comment verificationRef /* Verification: docs/verification/canvas-net/drawing.md */ comment reqRef /* Requirements: docs/reqstream/canvas-net/drawing.yaml */ part pathFiller : PathFiller; + part pathStroker : PathStroker; } } diff --git a/docs/sysml2/model/canvas-net/drawing/path-stroker.sysml b/docs/sysml2/model/canvas-net/drawing/path-stroker.sysml new file mode 100644 index 000000000..1010a370a --- /dev/null +++ b/docs/sysml2/model/canvas-net/drawing/path-stroker.sysml @@ -0,0 +1,11 @@ +package CanvasNet { + part def PathStroker { + doc /* Public static Stroke entry point converting a centerline Path plus StrokeStyle into closed outline Path geometry ready for nonzero-rule filling. Also covers the supporting public StrokeStyle/LineCap/LineJoin types and the internal StrokePathFlattener/DashSplitter/StrokeOutliner helpers inline; none has independent externally visible behavior of its own. */ + + comment sourceRef /* Source: src/DemaConsulting.CanvasNet/Drawing/LineCap.cs, src/DemaConsulting.CanvasNet/Drawing/LineJoin.cs, src/DemaConsulting.CanvasNet/Drawing/StrokeStyle.cs, src/DemaConsulting.CanvasNet/Drawing/StrokePathFlattener.cs, src/DemaConsulting.CanvasNet/Drawing/DashSplitter.cs, src/DemaConsulting.CanvasNet/Drawing/StrokeOutliner.cs, src/DemaConsulting.CanvasNet/Drawing/PathStroker.cs */ + comment testRef /* Test: test/DemaConsulting.CanvasNet.Tests/Drawing/StrokeStyleTests.cs, test/DemaConsulting.CanvasNet.Tests/Drawing/StrokePathFlattenerTests.cs, test/DemaConsulting.CanvasNet.Tests/Drawing/DashSplitterTests.cs, test/DemaConsulting.CanvasNet.Tests/Drawing/StrokeOutlinerTests.cs, test/DemaConsulting.CanvasNet.Tests/Drawing/PathStrokerTests.cs */ + comment designRef /* Design: docs/design/canvas-net/drawing/path-stroker.md */ + comment verificationRef /* Verification: docs/verification/canvas-net/drawing/path-stroker.md */ + comment reqRef /* Requirements: docs/reqstream/canvas-net/drawing/path-stroker.yaml */ + } +} diff --git a/docs/user_guide/introduction.md b/docs/user_guide/introduction.md index 101e8897e..eaea32c09 100644 --- a/docs/user_guide/introduction.md +++ b/docs/user_guide/introduction.md @@ -705,6 +705,98 @@ throwing, if `path` is empty or its bounds do not intersect `surface`'s pixel ex - `ArgumentOutOfRangeException`: Thrown when `fillRule` is not a defined `FillRule` value, when `flattenTolerance` is less than or equal to zero, or is not a finite value (NaN or infinity). +### PathStroker + +The `PathStroker` static class converts a `Geometry.Path` centerline into a new closed `Path` +describing the stroked area. Callers render the returned outline path through `PathFiller.Fill`, +reusing the same antialiased rasterizer as ordinary fills. Open subpaths honor end caps; closed +subpaths become shell rings suitable for `FillRule.NonZero`. + +#### LineCap + +```csharp +public enum LineCap +{ + Butt, + Round, + Square +} +``` + +Selects the visible end shape for an open stroked segment: no extension (`Butt`), semicircular +ends (`Round`), or half-width square extension (`Square`). + +#### LineJoin + +```csharp +public enum LineJoin +{ + Miter, + Round, + Bevel +} +``` + +Selects the visible corner shape where consecutive stroked segments meet: a sharp miter (with +limit-based bevel fallback), a rounded corner, or a flat bevel. + +#### StrokeStyle + +```csharp +public sealed class StrokeStyle +{ + public float Width { get; } + public LineCap Cap { get; } + public LineJoin Join { get; } + public float MiterLimit { get; } + public IReadOnlyList? DashArray { get; } + public float DashOffset { get; } +} +``` + +Immutable public stroke-style snapshot supplying width, cap, join, miter limit, optional dash +array, and optional dash offset. A null or empty dash array means a solid stroke. + +##### StrokeStyle Constructor + +```csharp +public StrokeStyle( + float width, + LineCap cap = LineCap.Butt, + LineJoin join = LineJoin.Miter, + float miterLimit = 4f, + IReadOnlyList? dashArray = null, + float dashOffset = 0f) +``` + +**Exceptions:** + +- `ArgumentOutOfRangeException`: Thrown when `width` is less than or equal to zero or non-finite, + when `cap` or `join` is not a defined enum value, when `miterLimit` is less than 1 or + non-finite, or when `dashOffset` is non-finite. +- `ArgumentException`: Thrown when `dashArray` contains a negative or non-finite entry, or when + every entry is zero. + +#### PathStroker Methods + +##### PathStroker.Stroke(Path path, StrokeStyle style, float flattenTolerance) + +```csharp +public static Path Stroke( + Path path, + StrokeStyle style, + float flattenTolerance = 0.25f) +``` + +Converts `path` into a new closed-outline `Path` representing the requested stroke. Returns +`Path.Empty` when the stroke contributes no visible area. + +**Exceptions:** + +- `ArgumentNullException`: Thrown when `path` or `style` is null. +- `ArgumentOutOfRangeException`: Thrown when `flattenTolerance` is less than or equal to zero, or + is not a finite value (NaN or infinity). + # Examples ## Example 1: Surface Pixel Access @@ -875,6 +967,32 @@ PathFiller.Fill(canvas, triangle, new Rgba32(0, 128, 255, 255)); Console.WriteLine(canvas[32, 40].A); // Output: 255 (well inside the triangle) ``` +## Example 10: Stroking a Vector Path + +```csharp +using DemaConsulting.CanvasNet.Canvas; +using DemaConsulting.CanvasNet.Drawing; +using DemaConsulting.CanvasNet.Geometry; +using System.Numerics; + +var canvas = new Surface(64, 64); +var polyline = new PathBuilder() + .MoveTo(new Vector2(8, 48)) + .LineTo(new Vector2(32, 16)) + .LineTo(new Vector2(56, 48)) + .Build(); + +var style = new StrokeStyle( + width: 6f, + cap: LineCap.Round, + join: LineJoin.Round, + dashArray: [10f, 6f]); + +var strokedOutline = PathStroker.Stroke(polyline, style); +PathFiller.Fill(canvas, strokedOutline, new Rgba32(255, 128, 0, 255)); +Console.WriteLine(canvas[32, 24].A); // Output: 255 (well inside one visible dash run) +``` + # References - [REF-1] Continuous Compliance Methodology () diff --git a/docs/verification/canvas-net/drawing.md b/docs/verification/canvas-net/drawing.md index fe2db2316..2e1255c64 100644 --- a/docs/verification/canvas-net/drawing.md +++ b/docs/verification/canvas-net/drawing.md @@ -2,16 +2,20 @@ This document describes the subsystem-level verification strategy for the `Drawing` subsystem (the `PathFiller` unit, covering the supporting `FillRule` enum and the internal -`EdgeFlattener`/`ScanlineRasterizer` helpers). +`EdgeFlattener`/`ScanlineRasterizer` helpers, and the `PathStroker` unit, covering the +supporting `LineCap`/`LineJoin`/`StrokeStyle` types and the internal +`StrokePathFlattener`/`DashSplitter`/`StrokeOutliner` helpers). ### Verification Approach -The `Drawing` subsystem is verified primarily through its single constituent unit's own tests -(see _PathFiller Unit Verification Design_, `drawing/path-filler.md`), exercising `PathFiller`'s -public API, and the internal `EdgeFlattener`/`ScanlineRasterizer` helpers (accessible to the test -project via `InternalsVisibleTo`), in isolation. Two system-level integration tests additionally -exercise the `Geometry`, `Drawing`, and `Canvas` subsystems together end to end (see the system -verification design, `../canvas-net.md`): +The `Drawing` subsystem is verified primarily through its constituent units' own tests: +_PathFiller Unit Verification Design_ (`drawing/path-filler.md`) and +_PathStroker Unit Verification Design_ (`drawing/path-stroker.md`). Those tests exercise both +public APIs directly, and the internal helper types (`EdgeFlattener`/`ScanlineRasterizer` and +`StrokePathFlattener`/`DashSplitter`/`StrokeOutliner`, respectively) in isolation where that +provides clearer evidence than end-to-end pixel checks alone. Two system-level integration tests +additionally exercise the `Geometry`, `Drawing`, and `Canvas` subsystems together end to end (see +the system verification design, `../canvas-net.md`): - Building a triangular `Path` via `PathBuilder`, filling it onto a `Surface` via `PathFiller.Fill`, and asserting fully-covered interior pixels, untouched exterior pixels, and @@ -32,5 +36,7 @@ verification design, `../canvas-net.md`): ### Acceptance Criteria The `Drawing` subsystem's verification passes when every unit test scenario described in -_PathFiller Unit Verification Design_ (`drawing/path-filler.md`) passes without error or +_PathFiller Unit Verification Design_ (`drawing/path-filler.md`) and +_PathStroker Unit Verification Design_ (`drawing/path-stroker.md`) passes without error or unexpected exception, and both system-level integration tests described above pass. + diff --git a/docs/verification/canvas-net/drawing/path-stroker.md b/docs/verification/canvas-net/drawing/path-stroker.md new file mode 100644 index 000000000..17a11ce3f --- /dev/null +++ b/docs/verification/canvas-net/drawing/path-stroker.md @@ -0,0 +1,127 @@ +## PathStroker Unit Verification Design + +This document describes the unit-level verification strategy for the `PathStroker` class and the +supporting `StrokeStyle`, `LineCap`, `LineJoin`, `StrokePathFlattener`, `DashSplitter`, and +`StrokeOutliner` types it covers inline. + +### Verification Approach + +The `PathStroker` unit is verified through a mix of end-to-end rendering assertions and narrower +internal geometry tests: + +- **End-to-end stroke rendering** (`PathStrokerTests.cs`) converts an input path to outline + geometry via `PathStroker.Stroke`, fills that returned path through the production + `PathFiller.Fill` pipeline, and asserts byte-exact pixel alpha values on the resulting + `Surface`. This proves the public API's observable behavior, not merely the intermediate outline + coordinates. +- **Style validation tests** (`StrokeStyleTests.cs`) verify constructor rejection of invalid + widths, miter limits, and dash arrays, plus round-trip preservation of valid values. +- **Flattening, dash, and outline helper tests** (`StrokePathFlattenerTests.cs`, + `DashSplitterTests.cs`, and `StrokeOutlinerTests.cs`) exercise the internal contracts that are + difficult to prove solely from rasterized pixels, such as seam stitching for a dashed closed + contour or opposite winding for shell rings. + +No mocks are required. The helpers are accessible to the test project through the existing +`InternalsVisibleTo` configuration already used elsewhere in the repository. + +### Test Environment + +- **Framework**: xUnit v3 running under the .NET SDK +- **Execution**: `dotnet test` invoked by `build.ps1` and the CI pipeline +- **Mocking**: None required; the unit has no injectable dependencies + +### Acceptance Criteria + +The unit passes verification when every scenario below passes without unexpected exception and +every expected pixel alpha or geometry assertion matches exactly. + +### Test Scenarios + +#### Stroke Conversion and Cap Shapes + +- `PathStroker_Stroke_HorizontalLineButtCap_FillsExactRectangleNoExtension` +- `PathStroker_Stroke_HorizontalLineRoundCap_FillsRectanglePlusSemicircularEnds` +- `PathStroker_Stroke_HorizontalLineSquareCap_FillsRectanglePlusHalfWidthExtension` + +These tests stroke a simple horizontal line and then fill the returned outline geometry. They +verify that butt caps stop exactly at the endpoints, square caps extend by half the width, and +round caps contribute the expected partial-coverage end pixels rather than a rectangular +extension. + +#### Join Shapes and Miter Limit + +- `PathStroker_Stroke_RightAngleCornerMiterJoin_FillsSharpMiteredCorner` +- `PathStroker_Stroke_RightAngleCornerRoundJoin_FillsRoundedCorner` +- `PathStroker_Stroke_RightAngleCornerBevelJoin_FillsFlatBeveledCorner` +- `PathStroker_Stroke_SharpAngleExceedingMiterLimit_FallsBackToBevel` + +These tests use the same right-angle polyline with width 4 so the corner-only pixels differ +clearly between join styles. The miter-limit scenario uses the same path with a deliberately small +limit, proving that the rendered result matches the bevel case rather than the unrestricted miter. + +#### Closed Contours, Dashing, and Degenerate Subpaths + +- `PathStroker_Stroke_ClosedRectangle_FillsRingLeavingInteriorAndExteriorUnfilled` +- `PathStroker_Stroke_DashedLine_FillsOnlyOnSegmentsLeavingGapsUnfilled` +- `PathStroker_Stroke_ZeroLengthSubpathRoundCap_FillsCircleOfRadiusHalfWidth` +- `PathStroker_Stroke_ZeroLengthSubpathSquareCap_FillsSquareOfSideWidth` +- `PathStroker_Stroke_ZeroLengthSubpathButtCap_ProducesNoFilledPixels` +- `PathStroker_Stroke_SinglePointSubpath_MatchesZeroLengthSubpathBehavior` +- `PathStroker_Stroke_EmptyPath_ReturnsEmptyPathNoOp` + +These scenarios verify the boundary conditions most likely to produce either missing geometry or +wrong winding: closed contours must leave their interior hole unfilled; dashed lines must paint +only visible runs; degenerate subpaths must follow cap semantics exactly; and an empty path must +remain a no-op. + +#### Public API Validation + +- `PathStroker_Stroke_NullPath_ThrowsArgumentNullException` +- `PathStroker_Stroke_NullStrokeStyle_ThrowsArgumentNullException` +- `PathStroker_Stroke_NonPositiveFlattenTolerance_ThrowsArgumentOutOfRangeException` + +These tests prove that the public entry point rejects invalid reference and tolerance arguments +before attempting any geometry conversion. + +#### StrokeStyle Constructor Validation + +- `StrokeStyle_Constructor_NonPositiveWidth_ThrowsArgumentOutOfRangeException` +- `StrokeStyle_Constructor_MiterLimitBelowOne_ThrowsArgumentOutOfRangeException` +- `StrokeStyle_Constructor_DefaultMiterLimit_IsFour` +- `StrokeStyle_Constructor_NullOrEmptyDashArray_IsTreatedAsSolid` +- `StrokeStyle_Constructor_DashArrayWithNegativeEntry_ThrowsArgumentException` +- `StrokeStyle_Constructor_DashArrayAllZero_ThrowsArgumentException` +- `StrokeStyle_Constructor_ValidValues_PropertiesRoundTrip` + +These tests verify that style validation is front-loaded at construction time and that valid +public styling values are preserved exactly. + +#### Internal Helper Semantics + +- `StrokePathFlattener_Flatten_OpenSubpath_PreservesIsClosedFalse` +- `StrokePathFlattener_Flatten_ClosedSubpath_PreservesIsClosedTrueWithNoImplicitDuplicatePoint` +- `StrokePathFlattener_Flatten_CurveCommands_DelegatesToBezierFlattening` +- `StrokePathFlattener_Flatten_MultipleSubpaths_RemainSeparate` +- `StrokePathFlattener_Flatten_EmptyPath_ReturnsEmptyList` +- `DashSplitter_Split_NullOrEmptyDashArray_ReturnsWholeSegmentUnchanged` +- `DashSplitter_Split_OddLengthDashArray_DuplicatesArrayConceptually` +- `DashSplitter_Split_WithDashOffset_ShiftsPhaseOfFirstSegment` +- `DashSplitter_Split_ClosedPolylineDashWrappingSeam_StitchesSegmentAcrossStartPoint` +- `DashSplitter_Split_PatternLongerThanPolyline_ReturnsSinglePartialOnSegment` +- `DashSplitter_Split_AllZeroDashArray_TreatedAsSolid` +- `StrokeOutliner_Outline_ClosedSubpath_ProducesTwoCounterWoundRings` +- `StrokeOutliner_Outline_MiterJoinWithinLimit_ProducesSharpVertex` +- `StrokeOutliner_Outline_MiterJoinExceedingLimit_FallsBackToBevelVertex` + +These tests verify the intermediate geometry contracts that feed the public API: preserving +open/closed state, applying SVG-style dash semantics, stitching seam-wrapping visible runs, and +producing shell rings with opposite winding for `FillRule.NonZero`. + +### Complexity Verification Policy + +Complexity expectations for dash splitting and outline generation are established in +_PathStroker Unit Design_ (`../../../design/canvas-net/drawing/path-stroker.md`) through design +analysis and code review only. There are intentionally **no** timing-based tests, elapsed-time +assertions, or `Stopwatch`-based guards in this unit's automated verification because those are +not stable compliance evidence on heterogeneous CI hardware. + diff --git a/requirements.yaml b/requirements.yaml index 13263c61b..20bbe5682 100644 --- a/requirements.yaml +++ b/requirements.yaml @@ -23,6 +23,7 @@ includes: - docs/reqstream/canvas-net/geometry/svg-arc-converter.yaml - docs/reqstream/canvas-net/drawing.yaml - docs/reqstream/canvas-net/drawing/path-filler.yaml + - docs/reqstream/canvas-net/drawing/path-stroker.yaml - docs/reqstream/canvas-net/platform-requirements.yaml - docs/reqstream/ots/xunit.yaml - docs/reqstream/ots/reqstream.yaml diff --git a/src/DemaConsulting.CanvasNet/Drawing/DashSplitter.cs b/src/DemaConsulting.CanvasNet/Drawing/DashSplitter.cs new file mode 100644 index 000000000..33ae19073 --- /dev/null +++ b/src/DemaConsulting.CanvasNet/Drawing/DashSplitter.cs @@ -0,0 +1,395 @@ +using System.Numerics; + +namespace DemaConsulting.CanvasNet.Drawing; + +// cspell:ignore Lerp + +/// +/// Splits a flattened polyline into the visible "on" segments of a dash pattern. +/// +/// +/// The splitter follows SVG dash semantics closely enough for stroke-to-fill conversion: +/// odd-length arrays are conceptually duplicated to make an even on/off cycle, the dash +/// offset phase-shifts the pattern along the path, and a closed polyline whose visible dash +/// wraps across the seam is stitched back into one contiguous emitted segment. +/// +internal static class DashSplitter +{ + /// + /// Splits into the visible "on" dash segments described by + /// and . + /// + /// The polyline vertices. + /// Whether the polyline represents a closed contour. + /// + /// Alternating on/off dash lengths. A , empty, or all-zero array + /// is treated as a solid stroke. + /// + /// The distance into the dash pattern at which the path starts. + /// Only the visible "on" segments, each preserving whether it remains closed. + internal static List<(List Points, bool IsClosed)> Split( + List points, + bool isClosed, + IReadOnlyList? dashArray, + float dashOffset) + { + if (points.Count == 0) + { + return []; + } + + if (IsSolidDash(dashArray)) + { + return [(new List(points), isClosed)]; + } + + var pattern = NormalizeDashArray(dashArray!); + var totalPatternLength = GetPatternLength(pattern); + if (totalPatternLength <= 0f) + { + return [(new List(points), isClosed)]; + } + + var edgeCount = isClosed ? points.Count : points.Count - 1; + if (edgeCount <= 0) + { + return IsDashOnAtStart(pattern, dashOffset) ? [(new List(points), isClosed)] : []; + } + + var cumulativeLengths = BuildCumulativeLengths(points, isClosed); + var totalLength = cumulativeLengths[^1]; + if (totalLength <= 0f) + { + return IsDashOnAtStart(pattern, dashOffset) ? [(new List(points), isClosed)] : []; + } + + var onIntervals = BuildOnIntervals(pattern, dashOffset, totalLength, isClosed, out var encounteredPositiveOffSpan); + if (onIntervals.Count == 0) + { + return []; + } + + if (isClosed && !encounteredPositiveOffSpan && onIntervals.Count == 1) + { + return [(new List(points), true)]; + } + + var segments = new List<(List Points, bool IsClosed)>(onIntervals.Count); + foreach (var interval in onIntervals) + { + var segment = ExtractIntervalPolyline(points, isClosed, cumulativeLengths, interval.Start, interval.End); + if (segment.Count != 0) + { + segments.Add((segment, false)); + } + } + + if (isClosed + && segments.Count > 1 + && IsNearZero(onIntervals[0].Start) + && IsNearZero(totalLength - onIntervals[^1].End)) + { + var stitched = new List(segments[^1].Points); + foreach (var point in segments[0].Points.Skip(1)) + { + AddPointIfDistinct(stitched, point); + } + + segments[^1] = (stitched, false); + segments.RemoveAt(0); + } + + return segments; + } + + /// + /// Determines whether should be treated as a solid stroke. + /// + private static bool IsSolidDash(IReadOnlyList? dashArray) + { + if (dashArray == null || dashArray.Count == 0) + { + return true; + } + + for (var i = 0; i < dashArray.Count; i++) + { + var value = dashArray[i]; + if (value != 0f) + { + return false; + } + } + + return true; + } + + /// + /// Duplicates an odd-length dash array to match SVG's alternating on/off semantics. + /// + private static float[] NormalizeDashArray(IReadOnlyList dashArray) + { + if (dashArray.Count % 2 == 0) + { + var even = new float[dashArray.Count]; + for (var i = 0; i < dashArray.Count; i++) + { + even[i] = dashArray[i]; + } + + return even; + } + + var duplicated = new float[dashArray.Count * 2]; + for (var i = 0; i < duplicated.Length; i++) + { + duplicated[i] = dashArray[i % dashArray.Count]; + } + + return duplicated; + } + + /// + /// Computes the total pattern length. + /// + private static float GetPatternLength(IReadOnlyList pattern) + { + var total = 0f; + foreach (var value in pattern) + { + total += value; + } + + return total; + } + + /// + /// Computes one cumulative path-length entry per vertex boundary, including the seam edge + /// for a closed polyline. + /// + private static float[] BuildCumulativeLengths(IReadOnlyList points, bool isClosed) + { + var edgeCount = isClosed ? points.Count : points.Count - 1; + var cumulative = new float[edgeCount + 1]; + for (var i = 0; i < edgeCount; i++) + { + var start = points[i]; + var end = points[(i + 1) % points.Count]; + cumulative[i + 1] = cumulative[i] + Vector2.Distance(start, end); + } + + return cumulative; + } + + /// + /// Determines whether the dash phase begins in an "on" interval. + /// + private static bool IsDashOnAtStart(IReadOnlyList pattern, float dashOffset) + { + var patternLength = GetPatternLength(pattern); + var offset = NormalizeModulo(dashOffset, patternLength); + var index = 0; + while (offset > 0f) + { + var length = pattern[index]; + if (length > 0f && offset < length) + { + break; + } + + offset -= length; + index = (index + 1) % pattern.Count; + } + + return index % 2 == 0; + } + + /// + /// Produces the path-length intervals where the dash pattern is "on". + /// + private static List<(float Start, float End)> BuildOnIntervals( + IReadOnlyList pattern, + float dashOffset, + float totalLength, + bool isClosed, + out bool encounteredPositiveOffSpan) + { + encounteredPositiveOffSpan = false; + var intervals = new List<(float Start, float End)>(); + var patternLength = GetPatternLength(pattern); + var offset = NormalizeModulo(dashOffset, patternLength); + + var dashIndex = 0; + while (offset > 0f) + { + var length = pattern[dashIndex]; + if (length > 0f && offset < length) + { + break; + } + + offset -= length; + dashIndex = (dashIndex + 1) % pattern.Count; + } + + var remainingInDash = pattern[dashIndex] - offset; + if (remainingInDash < 0f) + { + remainingInDash = 0f; + } + + var position = 0f; + while (position < totalLength) + { + if (remainingInDash <= 0f) + { + AdvanceDash(pattern, ref dashIndex, ref remainingInDash); + continue; + } + + var span = MathF.Min(remainingInDash, totalLength - position); + if (span <= 0f) + { + break; + } + + if (dashIndex % 2 == 0) + { + intervals.Add((position, position + span)); + } + else if (span > 0f) + { + encounteredPositiveOffSpan = true; + } + + position += span; + remainingInDash -= span; + } + + if (!isClosed) + { + return intervals; + } + + return intervals; + } + + /// + /// Advances to the next positive-length dash entry. + /// + private static void AdvanceDash(IReadOnlyList pattern, ref int dashIndex, ref float remainingInDash) + { + var traversed = 0; + do + { + dashIndex = (dashIndex + 1) % pattern.Count; + remainingInDash = pattern[dashIndex]; + traversed++; + } + while (remainingInDash <= 0f && traversed <= pattern.Count); + } + + /// + /// Extracts the sub-polyline between and + /// . + /// + private static List ExtractIntervalPolyline( + IReadOnlyList points, + bool isClosed, + IReadOnlyList cumulativeLengths, + float startDistance, + float endDistance) + { + var segment = new List(); + AddPointIfDistinct(segment, GetPointAtDistance(points, isClosed, cumulativeLengths, startDistance)); + + var edgeCount = cumulativeLengths.Count - 1; + for (var i = 1; i < edgeCount; i++) + { + if (cumulativeLengths[i] > startDistance && cumulativeLengths[i] < endDistance) + { + AddPointIfDistinct(segment, points[i % points.Count]); + } + } + + AddPointIfDistinct(segment, GetPointAtDistance(points, isClosed, cumulativeLengths, endDistance)); + return segment; + } + + /// + /// Evaluates the polyline point at the specified arc-length distance. + /// + private static Vector2 GetPointAtDistance( + IReadOnlyList points, + bool isClosed, + IReadOnlyList cumulativeLengths, + float distance) + { + if (distance <= 0f) + { + return points[0]; + } + + var totalLength = cumulativeLengths[^1]; + if (distance >= totalLength) + { + return isClosed ? points[0] : points[^1]; + } + + var edgeCount = cumulativeLengths.Count - 1; + for (var i = 0; i < edgeCount; i++) + { + var startLength = cumulativeLengths[i]; + var endLength = cumulativeLengths[i + 1]; + if (distance > endLength) + { + continue; + } + + var edgeStart = points[i]; + var edgeEnd = points[(i + 1) % points.Count]; + var edgeLength = endLength - startLength; + if (edgeLength <= 0f) + { + return edgeStart; + } + + var t = (distance - startLength) / edgeLength; + return Vector2.Lerp(edgeStart, edgeEnd, t); + } + + return isClosed ? points[0] : points[^1]; + } + + /// + /// Normalizes into the half-open interval + /// [0, modulus). + /// + private static float NormalizeModulo(float value, float modulus) + { + var normalized = value % modulus; + if (normalized < 0f) + { + normalized += modulus; + } + + return normalized; + } + + /// + /// Appends unless it duplicates the current final point. + /// + private static void AddPointIfDistinct(List points, Vector2 point) + { + if (points.Count == 0 || points[^1] != point) + { + points.Add(point); + } + } + + /// + /// Determines whether is close enough to zero to be treated as a + /// seam-aligned dash boundary. + /// + private static bool IsNearZero(float value) => MathF.Abs(value) <= 1e-5f; +} diff --git a/src/DemaConsulting.CanvasNet/Drawing/LineCap.cs b/src/DemaConsulting.CanvasNet/Drawing/LineCap.cs new file mode 100644 index 000000000..a1c1e823e --- /dev/null +++ b/src/DemaConsulting.CanvasNet/Drawing/LineCap.cs @@ -0,0 +1,29 @@ +namespace DemaConsulting.CanvasNet.Drawing; + +/// +/// Identifies the shape drawn at each exposed end of an open stroked subpath. +/// +/// +/// Caps affect only open subpaths (including dashed "on" segments produced from an otherwise +/// closed path). Closed subpaths have no exposed ends, so they ignore this setting. +/// +public enum LineCap +{ + /// + /// Ends the stroke exactly at the subpath's start and end points, with no extension + /// beyond those points. + /// + Butt, + + /// + /// Ends the stroke with a semicircle whose radius equals half the stroke width, centered + /// on the subpath's start or end point. + /// + Round, + + /// + /// Ends the stroke with a square whose center lies on the subpath's start or end point, + /// extending half the stroke width beyond the end in the path direction. + /// + Square +} diff --git a/src/DemaConsulting.CanvasNet/Drawing/LineJoin.cs b/src/DemaConsulting.CanvasNet/Drawing/LineJoin.cs new file mode 100644 index 000000000..448482363 --- /dev/null +++ b/src/DemaConsulting.CanvasNet/Drawing/LineJoin.cs @@ -0,0 +1,30 @@ +namespace DemaConsulting.CanvasNet.Drawing; + +/// +/// Identifies the shape drawn where two consecutive stroked segments meet. +/// +/// +/// The join style applies wherever a stroked polyline turns at a vertex. For +/// , excessively sharp angles fall back to a bevel when the computed +/// miter exceeds the configured . +/// +public enum LineJoin +{ + /// + /// Extends the two offset segment edges until they meet at a point, unless the miter + /// exceeds the configured limit, in which case a bevel is used instead. + /// + Miter, + + /// + /// Connects the two offset segment edges with a circular arc of radius half the stroke + /// width, centered on the vertex. + /// + Round, + + /// + /// Connects the two offset segment edges directly with a straight line between their + /// respective offset endpoints. + /// + Bevel +} diff --git a/src/DemaConsulting.CanvasNet/Drawing/NamespaceDoc.cs b/src/DemaConsulting.CanvasNet/Drawing/NamespaceDoc.cs index cb36e4cb5..cf1d94426 100644 --- a/src/DemaConsulting.CanvasNet/Drawing/NamespaceDoc.cs +++ b/src/DemaConsulting.CanvasNet/Drawing/NamespaceDoc.cs @@ -1,19 +1,22 @@ namespace DemaConsulting.CanvasNet.Drawing; /// -/// The namespace provides an antialiased, -/// scanline-coverage fill rasterizer () that paints a closed -/// onto a +/// The namespace provides two public vector +/// rendering entry points built on the same geometry-to-coverage pipeline: +/// fills a closed +/// directly onto a /// with a single solid /// color, resolving overlapping or -/// self-intersecting geometry via a caller-selected . This namespace -/// consumes both (for Path, curve -/// flattening, and arc conversion) and (for the -/// pixel buffer it paints into) - neither of those namespaces depends on this one, so future -/// changes here never ripple back into either foundational namespace. Stroking, gradient or -/// pattern paint, transform-aware fills, clip regions beyond the surface's own bounds, and -/// font/text rendering are all reserved for later phases; this namespace's sole responsibility -/// in this phase is solid-color fill. +/// self-intersecting geometry via a caller-selected ; and +/// converts a path stroke into closed fillable outline geometry +/// configured by , , and +/// . This namespace consumes both +/// (for Path, curve flattening, and +/// arc conversion) and (for the pixel buffer it +/// paints into) - neither of those namespaces depends on this one, so future changes here +/// never ripple back into either foundational namespace. Gradient or pattern paint, +/// transform-aware fills, clip regions beyond the surface's own bounds, and font/text +/// rendering remain reserved for later phases. /// internal static class NamespaceDoc { diff --git a/src/DemaConsulting.CanvasNet/Drawing/PathStroker.cs b/src/DemaConsulting.CanvasNet/Drawing/PathStroker.cs new file mode 100644 index 000000000..8db88fb71 --- /dev/null +++ b/src/DemaConsulting.CanvasNet/Drawing/PathStroker.cs @@ -0,0 +1,101 @@ +using DemaConsulting.CanvasNet.Geometry; +using Path = DemaConsulting.CanvasNet.Geometry.Path; + +// cspell:ignore Outliner + +namespace DemaConsulting.CanvasNet.Drawing; + +/// +/// Converts a vector path stroke into ordinary filled outline geometry consumable by +/// . +/// +/// +/// performs stroke-to-fill conversion only: +/// it returns a new whose closed subpaths describe the stroked area, ready +/// for a caller to render via using +/// . Rasterization stays entirely on the existing fill code +/// path, so stroking introduces no second rasterizer with independent antialiasing behavior. +/// +public static class PathStroker +{ + /// + /// Converts into closed outline geometry representing its stroke. + /// + /// The vector path to stroke. Must not be . + /// The stroke style to apply. Must not be . + /// + /// The maximum allowed deviation between each curve in and the + /// polyline used to approximate it before dashing and outlining. Must be finite and + /// greater than zero. Defaults to 0.25f. + /// + /// + /// A new containing one closed subpath per generated outline polygon, + /// or if the input path contributes no stroked area. + /// + /// + /// Thrown when or is + /// . + /// + /// + /// Thrown when is not finite or is less than or equal + /// to zero. + /// + public static Path Stroke(Path path, StrokeStyle style, float flattenTolerance = 0.25f) + { + ArgumentNullException.ThrowIfNull(path); + ArgumentNullException.ThrowIfNull(style); + + if (!float.IsFinite(flattenTolerance) || flattenTolerance <= 0f) + { + throw new ArgumentOutOfRangeException( + nameof(flattenTolerance), + flattenTolerance, + "Tolerance must be a finite value greater than zero."); + } + + var flattened = StrokePathFlattener.Flatten(path, flattenTolerance); + if (flattened.Count == 0) + { + return Path.Empty; + } + + var builder = new PathBuilder(); + var polygonCount = 0; + foreach (var subpath in flattened) + { + var dashedSegments = DashSplitter.Split( + subpath.Points, + subpath.IsClosed, + style.DashArray, + style.DashOffset); + + foreach (var dashedSegment in dashedSegments) + { + var outlines = StrokeOutliner.Outline( + dashedSegment.Points, + dashedSegment.IsClosed, + style, + flattenTolerance); + + foreach (var outline in outlines) + { + if (outline.Count < 3) + { + continue; + } + + builder.MoveTo(outline[0]); + for (var i = 1; i < outline.Count; i++) + { + builder.LineTo(outline[i]); + } + + builder.Close(); + polygonCount++; + } + } + } + + return polygonCount == 0 ? Path.Empty : builder.Build(); + } +} diff --git a/src/DemaConsulting.CanvasNet/Drawing/StrokeOutliner.cs b/src/DemaConsulting.CanvasNet/Drawing/StrokeOutliner.cs new file mode 100644 index 000000000..93bf9a6c6 --- /dev/null +++ b/src/DemaConsulting.CanvasNet/Drawing/StrokeOutliner.cs @@ -0,0 +1,695 @@ +using System.Numerics; + +// cspell:ignore Outliner outliner + +namespace DemaConsulting.CanvasNet.Drawing; + +/// +/// Converts a flattened polyline into one or more closed outline polygons representing the +/// area covered by stroking that polyline. +/// +/// +/// The outliner performs purely geometric conversion: it offsets each segment by half the +/// stroke width, resolves joins and caps into ordinary polygon vertices, and leaves +/// rasterization to . This keeps the stroke feature on the existing +/// fill code path rather than introducing a separate rasterizer. +/// +internal static class StrokeOutliner +{ + /// + /// The displacement below which vectors are treated as degenerate for join/cap math. + /// + private const float NearZeroDistance = 1e-6f; + + /// + /// Converts one flattened path segment into its closed outline polygon(s). + /// + /// The flattened polyline vertices. + /// Whether the polyline is a closed contour. + /// The stroke geometry to apply. + /// The tolerance used when tessellating round arcs. + /// One or more closed polygons representing the stroke area. + internal static List> Outline( + List points, + bool isClosed, + StrokeStyle style, + float flattenTolerance) + { + var simplified = SimplifyPoints(points, isClosed); + if (simplified.Count == 0) + { + return []; + } + + var halfWidth = style.Width / 2f; + if (simplified.Count == 1) + { + return CreatePointStrokePolygons(simplified[0], style.Cap, halfWidth, flattenTolerance); + } + + return isClosed + ? CreateClosedStrokePolygons(simplified, style, halfWidth, flattenTolerance) + : CreateOpenStrokePolygons(simplified, style, halfWidth, flattenTolerance); + } + + /// + /// Removes redundant duplicate vertices while preserving the semantic distinction between a + /// single-point path and a real segment chain. + /// + private static List SimplifyPoints(IReadOnlyList points, bool isClosed) + { + var simplified = new List(points.Count); + foreach (var point in points) + { + if (simplified.Count == 0 || simplified[^1] != point) + { + simplified.Add(point); + } + } + + if (isClosed && simplified.Count > 1 && simplified[0] == simplified[^1]) + { + simplified.RemoveAt(simplified.Count - 1); + } + + return simplified; + } + + /// + /// Produces the special-case stroke geometry for a degenerate subpath reduced to one + /// point. + /// + private static List> CreatePointStrokePolygons( + Vector2 center, + LineCap cap, + float halfWidth, + float flattenTolerance) + { + switch (cap) + { + case LineCap.Round: + return [CreateCirclePolygon(center, halfWidth, flattenTolerance)]; + + case LineCap.Square: + return + [ + new List + { + new(center.X - halfWidth, center.Y - halfWidth), + new(center.X + halfWidth, center.Y - halfWidth), + new(center.X + halfWidth, center.Y + halfWidth), + new(center.X - halfWidth, center.Y + halfWidth) + } + ]; + + case LineCap.Butt: + default: + return []; + } + } + + /// + /// Produces the stroke polygon for an open polyline, including caps. + /// + private static List> CreateOpenStrokePolygons( + IReadOnlyList points, + StrokeStyle style, + float halfWidth, + float flattenTolerance) + { + var frames = BuildSegmentFrames(points, isClosed: false); + var leftSide = BuildOpenSide(points, frames, +1f, style, halfWidth, flattenTolerance); + var rightSide = BuildOpenSide(points, frames, -1f, style, halfWidth, flattenTolerance); + if (leftSide.Count == 0 || rightSide.Count == 0) + { + return []; + } + + var polygon = new List(leftSide.Count + rightSide.Count + 32); + foreach (var point in leftSide) + { + AddPointIfDistinct(polygon, point); + } + + if (style.Cap == LineCap.Round) + { + var end = points[^1]; + var tangent = frames[^1].Tangent; + var leftEnd = points[^1] + frames[^1].Normal * halfWidth; + var rightEnd = points[^1] - frames[^1].Normal * halfWidth; + AppendArcThrough( + polygon, + end, + leftEnd - end, + rightEnd - end, + tangent * halfWidth, + halfWidth, + flattenTolerance, + includeStart: false, + includeEnd: true); + + AppendReversed(rightSide, polygon, skipFirst: true); + } + else + { + AppendReversed(rightSide, polygon, skipFirst: false); + } + + if (style.Cap == LineCap.Round) + { + var start = points[0]; + var tangent = frames[0].Tangent; + var leftStart = points[0] + frames[0].Normal * halfWidth; + var rightStart = points[0] - frames[0].Normal * halfWidth; + AppendArcThrough( + polygon, + start, + rightStart - start, + leftStart - start, + -tangent * halfWidth, + halfWidth, + flattenTolerance, + includeStart: false, + includeEnd: false); + } + + RemoveTrailingDuplicateOfFirst(polygon); + return polygon.Count >= 3 ? [polygon] : []; + } + + /// + /// Produces the outer and inner shell rings for a closed contour. + /// + private static List> CreateClosedStrokePolygons( + IReadOnlyList points, + StrokeStyle style, + float halfWidth, + float flattenTolerance) + { + var area = ComputeSignedArea(points); + var outerSideSign = area >= 0f ? -1f : +1f; + + var outerRing = BuildClosedSide(points, outerSideSign, style, halfWidth, flattenTolerance); + var innerRing = BuildClosedSide(points, -outerSideSign, style, halfWidth, flattenTolerance); + if (outerRing.Count < 3 || innerRing.Count < 3) + { + return []; + } + + if (ComputeSignedArea(outerRing) * ComputeSignedArea(innerRing) > 0f) + { + innerRing.Reverse(); + } + + return [outerRing, innerRing]; + } + + /// + /// Computes one tangent/normal pair per segment of an open or closed polyline. + /// + private static (Vector2 Tangent, Vector2 Normal)[] BuildSegmentFrames(IReadOnlyList points, bool isClosed) + { + var segmentCount = isClosed ? points.Count : points.Count - 1; + var frames = new (Vector2 Tangent, Vector2 Normal)[segmentCount]; + for (var i = 0; i < segmentCount; i++) + { + var start = points[i]; + var end = points[(i + 1) % points.Count]; + var direction = end - start; + var length = direction.Length(); + if (length <= NearZeroDistance) + { + frames[i] = (Vector2.UnitX, new Vector2(0f, 1f)); + continue; + } + + var tangent = direction / length; + frames[i] = (tangent, new Vector2(-tangent.Y, tangent.X)); + } + + return frames; + } + + /// + /// Builds one side of an open stroke polygon from start to end. + /// + private static List BuildOpenSide( + IReadOnlyList points, + IReadOnlyList<(Vector2 Tangent, Vector2 Normal)> frames, + float sideSign, + StrokeStyle style, + float halfWidth, + float flattenTolerance) + { + var side = new List(points.Count * 2); + AddPointIfDistinct(side, GetOpenEndpoint(points[0], frames[0].Tangent, frames[0].Normal, sideSign, style.Cap, -1f, halfWidth)); + + for (var i = 1; i < points.Count - 1; i++) + { + AppendOpenJoin(side, points[i], frames[i - 1], frames[i], sideSign, style, halfWidth, flattenTolerance); + } + + AddPointIfDistinct(side, GetOpenEndpoint(points[^1], frames[^1].Tangent, frames[^1].Normal, sideSign, style.Cap, +1f, halfWidth)); + return side; + } + + /// + /// Computes the start or end point of an open-side offset, including square-cap + /// extensions. + /// + private static Vector2 GetOpenEndpoint( + Vector2 point, + Vector2 tangent, + Vector2 normal, + float sideSign, + LineCap cap, + float capDirection, + float halfWidth) + { + var offset = sideSign * normal * halfWidth; + if (cap == LineCap.Square) + { + offset += capDirection * tangent * halfWidth; + } + + return point + offset; + } + + /// + /// Appends the join geometry for one interior vertex of an open stroke side. + /// + private static void AppendOpenJoin( + List side, + Vector2 vertex, + (Vector2 Tangent, Vector2 Normal) previousFrame, + (Vector2 Tangent, Vector2 Normal) nextFrame, + float sideSign, + StrokeStyle style, + float halfWidth, + float flattenTolerance) + { + var previousPoint = vertex + sideSign * previousFrame.Normal * halfWidth; + var nextPoint = vertex + sideSign * nextFrame.Normal * halfWidth; + var turn = Cross(previousFrame.Tangent, nextFrame.Tangent); + var dot = Vector2.Dot(previousFrame.Tangent, nextFrame.Tangent); + if (MathF.Abs(turn) <= NearZeroDistance && dot > 0f) + { + AddPointIfDistinct(side, nextPoint); + return; + } + + var isConvexOnThisSide = turn * sideSign < 0f; + if (!isConvexOnThisSide) + { + AddPointIfDistinct(side, previousPoint); + AddPointIfDistinct(side, nextPoint); + return; + } + + AppendStyledJoin( + side, + vertex, + previousFrame.Tangent, + nextFrame.Tangent, + previousFrame.Normal, + nextFrame.Normal, + sideSign, + style, + halfWidth, + flattenTolerance); + } + + /// + /// Builds one closed offset ring for a closed contour. + /// + private static List BuildClosedSide( + IReadOnlyList points, + float sideSign, + StrokeStyle style, + float halfWidth, + float flattenTolerance) + { + var frames = BuildSegmentFrames(points, isClosed: true); + var ring = new List(points.Count * 2); + for (var i = 0; i < points.Count; i++) + { + var previousFrame = frames[(i + frames.Length - 1) % frames.Length]; + var nextFrame = frames[i]; + var turn = Cross(previousFrame.Tangent, nextFrame.Tangent); + var dot = Vector2.Dot(previousFrame.Tangent, nextFrame.Tangent); + if (MathF.Abs(turn) <= NearZeroDistance && dot > 0f) + { + AddPointIfDistinct(ring, points[i] + sideSign * nextFrame.Normal * halfWidth); + continue; + } + + AppendStyledJoin( + ring, + points[i], + previousFrame.Tangent, + nextFrame.Tangent, + previousFrame.Normal, + nextFrame.Normal, + sideSign, + style, + halfWidth, + flattenTolerance); + } + + RemoveTrailingDuplicateOfFirst(ring); + return ring; + } + + /// + /// Appends the requested styled join between two offset segments. + /// + private static void AppendStyledJoin( + List target, + Vector2 vertex, + Vector2 previousTangent, + Vector2 nextTangent, + Vector2 previousNormal, + Vector2 nextNormal, + float sideSign, + StrokeStyle style, + float halfWidth, + float flattenTolerance) + { + var previousPoint = vertex + sideSign * previousNormal * halfWidth; + var nextPoint = vertex + sideSign * nextNormal * halfWidth; + + switch (style.Join) + { + case LineJoin.Round: + AddPointIfDistinct(target, previousPoint); + AppendArcShortest( + target, + vertex, + previousPoint - vertex, + nextPoint - vertex, + halfWidth, + flattenTolerance, + includeStart: false, + includeEnd: true); + break; + + case LineJoin.Bevel: + AddPointIfDistinct(target, previousPoint); + AddPointIfDistinct(target, nextPoint); + break; + + default: + if (TryCreateMiter(vertex, previousPoint, nextPoint, previousTangent, nextTangent, style.Width, style.MiterLimit, out var miter)) + { + AddPointIfDistinct(target, miter); + } + else + { + AddPointIfDistinct(target, previousPoint); + AddPointIfDistinct(target, nextPoint); + } + + break; + } + } + + /// + /// Computes the miter-join vertex and validates it against the configured limit. + /// + private static bool TryCreateMiter( + Vector2 vertex, + Vector2 previousPoint, + Vector2 nextPoint, + Vector2 previousTangent, + Vector2 nextTangent, + float strokeWidth, + float miterLimit, + out Vector2 miterPoint) + { + miterPoint = default; + if (!TryIntersectLines(previousPoint, previousTangent, nextPoint, nextTangent, out var intersection)) + { + return false; + } + + var halfWidth = strokeWidth / 2f; + var miterRatio = Vector2.Distance(vertex, intersection) / halfWidth; + if (!float.IsFinite(miterRatio) || miterRatio > miterLimit) + { + return false; + } + + miterPoint = intersection; + return true; + } + + /// + /// Intersects two infinite lines defined by point-plus-direction pairs. + /// + private static bool TryIntersectLines( + Vector2 pointA, + Vector2 directionA, + Vector2 pointB, + Vector2 directionB, + out Vector2 intersection) + { + var denominator = Cross(directionA, directionB); + if (MathF.Abs(denominator) <= NearZeroDistance) + { + intersection = default; + return false; + } + + var delta = pointB - pointA; + var t = Cross(delta, directionB) / denominator; + intersection = pointA + directionA * t; + return true; + } + + /// + /// Appends the shorter arc between two vectors around a common center. + /// + private static void AppendArcShortest( + List target, + Vector2 center, + Vector2 startVector, + Vector2 endVector, + float radius, + float flattenTolerance, + bool includeStart, + bool includeEnd) + { + var startAngle = MathF.Atan2(startVector.Y, startVector.X); + var endAngle = MathF.Atan2(endVector.Y, endVector.X); + var sweep = NormalizeSignedAngle(endAngle - startAngle); + AppendArc(target, center, startAngle, sweep, radius, flattenTolerance, includeStart, includeEnd); + } + + /// + /// Appends the arc from to + /// chosen so that it passes through . + /// + private static void AppendArcThrough( + List target, + Vector2 center, + Vector2 startVector, + Vector2 endVector, + Vector2 throughVector, + float radius, + float flattenTolerance, + bool includeStart, + bool includeEnd) + { + var startAngle = MathF.Atan2(startVector.Y, startVector.X); + var endAngle = MathF.Atan2(endVector.Y, endVector.X); + var sweep = NormalizeSignedAngle(endAngle - startAngle); + var throughAngle = MathF.Atan2(throughVector.Y, throughVector.X); + if (!AngleLiesOnSweep(startAngle, sweep, throughAngle)) + { + sweep = sweep > 0f ? sweep - 2f * MathF.PI : sweep + 2f * MathF.PI; + } + + AppendArc(target, center, startAngle, sweep, radius, flattenTolerance, includeStart, includeEnd); + } + + /// + /// Appends a tessellated circular arc. + /// + private static void AppendArc( + List target, + Vector2 center, + float startAngle, + float sweep, + float radius, + float flattenTolerance, + bool includeStart, + bool includeEnd) + { + var segmentCount = GetArcSegmentCount(radius, MathF.Abs(sweep), flattenTolerance); + for (var i = 0; i <= segmentCount; i++) + { + if (i == 0 && !includeStart) + { + continue; + } + + if (i == segmentCount && !includeEnd) + { + continue; + } + + var angle = startAngle + sweep * i / segmentCount; + var point = center + new Vector2(MathF.Cos(angle), MathF.Sin(angle)) * radius; + AddPointIfDistinct(target, point); + } + } + + /// + /// Computes the number of straight segments needed to keep an arc's sagitta within the + /// requested flattening tolerance. + /// + private static int GetArcSegmentCount(float radius, float sweepMagnitude, float flattenTolerance) + { + if (radius <= 0f || sweepMagnitude <= 0f) + { + return 1; + } + + if (flattenTolerance >= radius) + { + return Math.Max(1, (int)MathF.Ceiling(sweepMagnitude / (MathF.PI / 2f))); + } + + var cosine = 1f - flattenTolerance / radius; + cosine = Math.Clamp(cosine, -1f, 1f); + var maxAngle = 2f * MathF.Acos(cosine); + if (!float.IsFinite(maxAngle) || maxAngle <= 0f) + { + return 1; + } + + return Math.Max(1, (int)MathF.Ceiling(sweepMagnitude / maxAngle)); + } + + /// + /// Creates a full-circle polygon centered on . + /// + private static List CreateCirclePolygon(Vector2 center, float radius, float flattenTolerance) + { + var circle = new List(); + var segmentCount = Math.Max(4, GetArcSegmentCount(radius, 2f * MathF.PI, flattenTolerance)); + for (var i = 0; i < segmentCount; i++) + { + var angle = 2f * MathF.PI * i / segmentCount; + circle.Add(center + new Vector2(MathF.Cos(angle), MathF.Sin(angle)) * radius); + } + + return circle; + } + + /// + /// Appends in reverse order to . + /// + private static void AppendReversed(IReadOnlyList source, List target, bool skipFirst) + { + var endIndex = skipFirst ? source.Count - 2 : source.Count - 1; + for (var i = endIndex; i >= 0; i--) + { + AddPointIfDistinct(target, source[i]); + } + } + + /// + /// Removes a trailing duplicate of the first vertex when a helper already closed the loop + /// explicitly. + /// + private static void RemoveTrailingDuplicateOfFirst(List points) + { + if (points.Count > 1 && points[0] == points[^1]) + { + points.RemoveAt(points.Count - 1); + } + } + + /// + /// Appends unless it duplicates the current final point. + /// + private static void AddPointIfDistinct(List points, Vector2 point) + { + if (points.Count == 0 || points[^1] != point) + { + points.Add(point); + } + } + + /// + /// Computes the scalar 2D cross product. + /// + private static float Cross(Vector2 left, Vector2 right) => left.X * right.Y - left.Y * right.X; + + /// + /// Normalizes an angle into [-ฯ€, ฯ€]. + /// + private static float NormalizeSignedAngle(float angle) + { + while (angle <= -MathF.PI) + { + angle += 2f * MathF.PI; + } + + while (angle > MathF.PI) + { + angle -= 2f * MathF.PI; + } + + return angle; + } + + /// + /// Determines whether lies on the directed sweep starting at + /// and spanning . + /// + private static bool AngleLiesOnSweep(float startAngle, float sweep, float angle) + { + if (sweep >= 0f) + { + var delta = NormalizePositiveAngle(angle - startAngle); + var normalizedSweep = NormalizePositiveAngle(sweep); + return delta <= normalizedSweep + NearZeroDistance; + } + + var negativeDelta = NormalizePositiveAngle(startAngle - angle); + var normalizedNegativeSweep = NormalizePositiveAngle(-sweep); + return negativeDelta <= normalizedNegativeSweep + NearZeroDistance; + } + + /// + /// Normalizes an angle into [0, 2ฯ€). + /// + private static float NormalizePositiveAngle(float angle) + { + var normalized = angle % (2f * MathF.PI); + if (normalized < 0f) + { + normalized += 2f * MathF.PI; + } + + return normalized; + } + + /// + /// Computes the signed area of a polygon-like vertex sequence. + /// + private static float ComputeSignedArea(IReadOnlyList points) + { + var area = 0f; + for (var i = 0; i < points.Count; i++) + { + var current = points[i]; + var next = points[(i + 1) % points.Count]; + area += current.X * next.Y - current.Y * next.X; + } + + return area / 2f; + } +} diff --git a/src/DemaConsulting.CanvasNet/Drawing/StrokePathFlattener.cs b/src/DemaConsulting.CanvasNet/Drawing/StrokePathFlattener.cs new file mode 100644 index 000000000..b1a484634 --- /dev/null +++ b/src/DemaConsulting.CanvasNet/Drawing/StrokePathFlattener.cs @@ -0,0 +1,103 @@ +using System.Numerics; +using DemaConsulting.CanvasNet.Geometry; +using Path = DemaConsulting.CanvasNet.Geometry.Path; + +namespace DemaConsulting.CanvasNet.Drawing; + +/// +/// Converts each subpath into a polyline while preserving whether that +/// subpath was originally open or closed. +/// +/// +/// Unlike , which always appends an implicit closing edge because +/// fill semantics treat every subpath as closed, stroking must preserve the real open/closed +/// distinction from so that open subpaths receive end caps and +/// closed subpaths instead produce shell rings with no caps. +/// +internal static class StrokePathFlattener +{ + /// + /// Flattens every subpath of into a polyline plus its open/closed + /// state. + /// + /// The path to flatten. + /// + /// The maximum allowed curve-flattening deviation, forwarded to + /// . + /// + /// + /// One polyline per subpath of , in the same order as + /// . + /// + internal static List<(List Points, bool IsClosed)> Flatten(Path path, float tolerance) + { + var polylines = new List<(List Points, bool IsClosed)>(path.Subpaths.Count); + + foreach (var subpath in path.Subpaths) + { + var points = new List { subpath.Start }; + var current = subpath.Start; + + foreach (var command in subpath.Commands) + { + current = AppendCommand(current, command, tolerance, points); + } + + polylines.Add((points, subpath.IsClosed)); + } + + return polylines; + } + + /// + /// Converts one into polyline vertices appended to + /// , returning the new current point. + /// + private static Vector2 AppendCommand(Vector2 current, PathCommand command, float tolerance, List points) + { + switch (command.Type) + { + case PathCommandType.LineTo: + points.Add(command.EndPoint); + return command.EndPoint; + + case PathCommandType.QuadraticBezierTo: + BezierFlattening.FlattenQuadratic(current, command.Control1, command.EndPoint, tolerance, points); + return command.EndPoint; + + case PathCommandType.CubicBezierTo: + BezierFlattening.FlattenCubic(current, command.Control1, command.Control2, command.EndPoint, tolerance, points); + return command.EndPoint; + + case PathCommandType.ArcTo: + var segments = new List<(Vector2 Control1, Vector2 Control2, Vector2 End)>(); + SvgArcConverter.ToBeziers( + current, + command.Radius, + command.RotationDegrees, + command.LargeArc, + command.Sweep, + command.EndPoint, + segments); + + var segmentStart = current; + foreach (var segment in segments) + { + BezierFlattening.FlattenCubic( + segmentStart, + segment.Control1, + segment.Control2, + segment.End, + tolerance, + points); + segmentStart = segment.End; + } + + return command.EndPoint; + + case PathCommandType.Close: + default: + return current; + } + } +} diff --git a/src/DemaConsulting.CanvasNet/Drawing/StrokeStyle.cs b/src/DemaConsulting.CanvasNet/Drawing/StrokeStyle.cs new file mode 100644 index 000000000..cf0461d6b --- /dev/null +++ b/src/DemaConsulting.CanvasNet/Drawing/StrokeStyle.cs @@ -0,0 +1,172 @@ +using System.Collections.ObjectModel; + +namespace DemaConsulting.CanvasNet.Drawing; + +/// +/// Describes the geometry used when converting a path stroke into fillable outline polygons. +/// +/// +/// is immutable and thread-safe after construction. A caller builds +/// one style once, then reuses it across repeated calls to +/// apply the same width, cap, join, miter-limit, and dash behavior to different paths. +/// +public sealed class StrokeStyle +{ + /// + /// Initializes a new stroke-style snapshot. + /// + /// + /// The stroke width, in path-space units. Must be a finite value greater than zero. + /// + /// + /// The cap geometry applied to each exposed end of an open stroked segment. Must be a + /// defined value. Defaults to . + /// + /// + /// The join geometry applied where consecutive stroked segments meet. Must be a defined + /// value. Defaults to . + /// + /// + /// The SVG-style miter-limit ratio (miterLength / strokeWidth) above which a + /// miter join falls back to a bevel. Must be finite and greater than or equal to one. + /// Defaults to 4f. + /// + /// + /// Optional dash lengths alternating on/off along the stroked path. A + /// or empty list means a solid stroke. Every entry must be finite and greater than or + /// equal to zero, and the list must not consist entirely of zeros. + /// + /// + /// The distance, in path-space units, into the dash pattern at which stroking starts. + /// Must be finite. Defaults to 0f. + /// + /// + /// Thrown when is not finite or is less than or equal to zero; + /// when or is not a defined enum value; + /// when is not finite or is less than one; or when + /// is not finite. + /// + /// + /// Thrown when contains a negative or non-finite entry, or + /// when every entry is zero. + /// + public StrokeStyle( + float width, + LineCap cap = LineCap.Butt, + LineJoin join = LineJoin.Miter, + float miterLimit = 4f, + IReadOnlyList? dashArray = null, + float dashOffset = 0f) + { + if (!float.IsFinite(width) || width <= 0) + { + throw new ArgumentOutOfRangeException( + nameof(width), width, "Width must be a finite value greater than zero."); + } + + if (!Enum.IsDefined(cap)) + { + throw new ArgumentOutOfRangeException( + nameof(cap), cap, "Cap must be a defined LineCap value."); + } + + if (!Enum.IsDefined(join)) + { + throw new ArgumentOutOfRangeException( + nameof(join), join, "Join must be a defined LineJoin value."); + } + + if (!float.IsFinite(miterLimit) || miterLimit < 1f) + { + throw new ArgumentOutOfRangeException( + nameof(miterLimit), miterLimit, "Miter limit must be a finite value greater than or equal to one."); + } + + if (!float.IsFinite(dashOffset)) + { + throw new ArgumentOutOfRangeException( + nameof(dashOffset), dashOffset, "Dash offset must be a finite value."); + } + + Width = width; + Cap = cap; + Join = join; + MiterLimit = miterLimit; + DashArray = CopyDashArray(dashArray); + DashOffset = dashOffset; + } + + /// + /// Gets the stroke width, in path-space units. + /// + public float Width { get; } + + /// + /// Gets the cap geometry applied to each exposed end of an open stroked segment. + /// + public LineCap Cap { get; } + + /// + /// Gets the join geometry applied where consecutive stroked segments meet. + /// + public LineJoin Join { get; } + + /// + /// Gets the SVG-style miter-limit ratio above which a miter falls back to a bevel. + /// + public float MiterLimit { get; } + + /// + /// Gets the optional alternating on/off dash lengths, or for a + /// solid stroke. + /// + public IReadOnlyList? DashArray { get; } + + /// + /// Gets the distance into the dash pattern at which stroking starts. + /// + public float DashOffset { get; } + + /// + /// Copies and validates , producing an immutable snapshot or + /// for a solid stroke. + /// + /// The caller-supplied dash array. + /// The copied, read-only dash array snapshot, or . + private static IReadOnlyList? CopyDashArray(IReadOnlyList? dashArray) + { + if (dashArray == null || dashArray.Count == 0) + { + return null; + } + + var values = new float[dashArray.Count]; + var anyPositive = false; + for (var i = 0; i < dashArray.Count; i++) + { + var value = dashArray[i]; + if (!float.IsFinite(value) || value < 0f) + { + throw new ArgumentException( + "Dash array entries must be finite values greater than or equal to zero.", + nameof(dashArray)); + } + + if (value > 0f) + { + anyPositive = true; + } + + values[i] = value; + } + + if (!anyPositive) + { + throw new ArgumentException( + "Dash array entries must not all be zero.", + nameof(dashArray)); + } + + return new ReadOnlyCollection(values); + } +} diff --git a/test/DemaConsulting.CanvasNet.Tests/Drawing/DashSplitterTests.cs b/test/DemaConsulting.CanvasNet.Tests/Drawing/DashSplitterTests.cs new file mode 100644 index 000000000..76be372e3 --- /dev/null +++ b/test/DemaConsulting.CanvasNet.Tests/Drawing/DashSplitterTests.cs @@ -0,0 +1,123 @@ +using System.Numerics; +using DemaConsulting.CanvasNet.Drawing; + +namespace DemaConsulting.CanvasNet.Tests.Drawing; + +/// +/// Unit tests for the internal type. +/// +public class DashSplitterTests +{ + /// + /// Proves that a null or empty dash array leaves the input polyline unchanged. + /// + [Fact] + public void DashSplitter_Split_NullOrEmptyDashArray_ReturnsWholeSegmentUnchanged() + { + // Arrange + var points = new List { new(0, 0), new(10, 0) }; + + // Act + var nullDash = DashSplitter.Split(points, isClosed: false, dashArray: null, dashOffset: 0f); + var emptyDash = DashSplitter.Split(points, isClosed: false, dashArray: Array.Empty(), dashOffset: 0f); + + // Assert + Assert.Equal(points, Assert.Single(nullDash).Points); + Assert.Equal(points, Assert.Single(emptyDash).Points); + } + + /// + /// Proves that an odd-length dash array is conceptually duplicated. + /// + [Fact] + public void DashSplitter_Split_OddLengthDashArray_DuplicatesArrayConceptually() + { + // Arrange + var points = new List { new(0, 0), new(10, 0) }; + + // Act + var segments = DashSplitter.Split(points, isClosed: false, dashArray: [2f, 1f, 3f], dashOffset: 0f); + + // Assert + Assert.Equal(3, segments.Count); + Assert.Equal([new Vector2(0, 0), new Vector2(2, 0)], segments[0].Points); + Assert.Equal([new Vector2(3, 0), new Vector2(6, 0)], segments[1].Points); + Assert.Equal([new Vector2(8, 0), new Vector2(9, 0)], segments[2].Points); + } + + /// + /// Proves that dash offset phase-shifts the first visible segment. + /// + [Fact] + public void DashSplitter_Split_WithDashOffset_ShiftsPhaseOfFirstSegment() + { + // Arrange + var points = new List { new(0, 0), new(10, 0) }; + + // Act + var segments = DashSplitter.Split(points, isClosed: false, dashArray: [4f, 2f], dashOffset: 1f); + + // Assert + Assert.Equal(2, segments.Count); + Assert.Equal([new Vector2(0, 0), new Vector2(3, 0)], segments[0].Points); + Assert.Equal([new Vector2(5, 0), new Vector2(9, 0)], segments[1].Points); + } + + /// + /// Proves that a visible closed-path dash segment wrapping across the seam is stitched + /// into one emitted segment. + /// + [Fact] + public void DashSplitter_Split_ClosedPolylineDashWrappingSeam_StitchesSegmentAcrossStartPoint() + { + // Arrange + var points = new List + { + new(0, 0), + new(2, 0), + new(2, 2), + new(0, 2) + }; + + // Act + var segments = DashSplitter.Split(points, isClosed: true, dashArray: [3f, 5f], dashOffset: 2f); + + // Assert + var segment = Assert.Single(segments); + Assert.False(segment.IsClosed); + Assert.Equal([new Vector2(0, 2), new Vector2(0, 0), new Vector2(1, 0)], segment.Points); + } + + /// + /// Proves that a dash pattern longer than the polyline emits one partial "on" segment + /// when the path ends mid-dash. + /// + [Fact] + public void DashSplitter_Split_PatternLongerThanPolyline_ReturnsSinglePartialOnSegment() + { + // Arrange + var points = new List { new(0, 0), new(4, 0) }; + + // Act + var segments = DashSplitter.Split(points, isClosed: false, dashArray: [10f, 5f], dashOffset: 0f); + + // Assert + Assert.Equal([new Vector2(0, 0), new Vector2(4, 0)], Assert.Single(segments).Points); + } + + /// + /// Proves that an all-zero dash array is treated as a solid stroke. + /// + [Fact] + public void DashSplitter_Split_AllZeroDashArray_TreatedAsSolid() + { + // Arrange + var points = new List { new(0, 0), new(6, 0) }; + + // Act + var segments = DashSplitter.Split(points, isClosed: false, dashArray: [0f, 0f, 0f], dashOffset: 5f); + + // Assert + Assert.Equal(points, Assert.Single(segments).Points); + } +} diff --git a/test/DemaConsulting.CanvasNet.Tests/Drawing/PathStrokerTests.cs b/test/DemaConsulting.CanvasNet.Tests/Drawing/PathStrokerTests.cs new file mode 100644 index 000000000..8b714f26d --- /dev/null +++ b/test/DemaConsulting.CanvasNet.Tests/Drawing/PathStrokerTests.cs @@ -0,0 +1,381 @@ +using System.Numerics; +using DemaConsulting.CanvasNet.Canvas; +using DemaConsulting.CanvasNet.Drawing; +using DemaConsulting.CanvasNet.Geometry; +using Path = DemaConsulting.CanvasNet.Geometry.Path; + +namespace DemaConsulting.CanvasNet.Tests.Drawing; + +/// +/// Unit tests for . +/// +public class PathStrokerTests +{ + /// + /// Proves that a butt-capped horizontal line becomes an exact rectangle with no extension. + /// + [Fact] + public void PathStroker_Stroke_HorizontalLineButtCap_FillsExactRectangleNoExtension() + { + // Arrange + var path = new PathBuilder() + .MoveTo(new Vector2(2, 2)) + .LineTo(new Vector2(6, 2)) + .Build(); + var style = new StrokeStyle(2f, cap: LineCap.Butt); + + // Act + var surface = RenderStroke(path, style, 8, 5); + + // Assert + Assert.Equal((byte)255, surface[2, 1].A); + Assert.Equal((byte)255, surface[5, 2].A); + Assert.Equal((byte)0, surface[1, 1].A); + Assert.Equal((byte)0, surface[6, 1].A); + } + + /// + /// Proves that a round-capped horizontal line renders semicircular end caps. + /// + [Fact] + public void PathStroker_Stroke_HorizontalLineRoundCap_FillsRectanglePlusSemicircularEnds() + { + // Arrange + var path = new PathBuilder() + .MoveTo(new Vector2(2, 2)) + .LineTo(new Vector2(6, 2)) + .Build(); + var style = new StrokeStyle(2f, cap: LineCap.Round); + + // Act + var surface = RenderStroke(path, style, 8, 5); + + // Assert + Assert.Equal((byte)255, surface[2, 1].A); + Assert.Equal((byte)166, surface[1, 1].A); + Assert.Equal((byte)166, surface[6, 1].A); + Assert.Equal((byte)0, surface[0, 1].A); + } + + /// + /// Proves that a square-capped horizontal line extends by half the stroke width at each + /// end. + /// + [Fact] + public void PathStroker_Stroke_HorizontalLineSquareCap_FillsRectanglePlusHalfWidthExtension() + { + // Arrange + var path = new PathBuilder() + .MoveTo(new Vector2(2, 2)) + .LineTo(new Vector2(6, 2)) + .Build(); + var style = new StrokeStyle(2f, cap: LineCap.Square); + + // Act + var surface = RenderStroke(path, style, 9, 5); + + // Assert + Assert.Equal((byte)255, surface[1, 1].A); + Assert.Equal((byte)255, surface[6, 2].A); + Assert.Equal((byte)0, surface[0, 1].A); + Assert.Equal((byte)0, surface[7, 1].A); + } + + /// + /// Proves that a right-angle corner with a miter join renders the miter-only corner pixel. + /// + [Fact] + public void PathStroker_Stroke_RightAngleCornerMiterJoin_FillsSharpMiteredCorner() + { + // Arrange + var path = BuildRightAnglePath(); + var style = new StrokeStyle(4f, cap: LineCap.Butt, join: LineJoin.Miter, miterLimit: 4f); + + // Act + var surface = RenderStroke(path, style, 14, 12); + + // Assert + Assert.Equal((byte)255, surface[9, 2].A); + Assert.Equal((byte)255, surface[8, 2].A); + } + + /// + /// Proves that a right-angle corner with a round join renders the quarter-circle corner + /// coverage. + /// + [Fact] + public void PathStroker_Stroke_RightAngleCornerRoundJoin_FillsRoundedCorner() + { + // Arrange + var path = BuildRightAnglePath(); + var style = new StrokeStyle(4f, cap: LineCap.Butt, join: LineJoin.Round); + + // Act + var surface = RenderStroke(path, style, 14, 12); + + // Assert + Assert.Equal((byte)202, surface[8, 2].A); + Assert.Equal((byte)62, surface[9, 2].A); + } + + /// + /// Proves that a right-angle corner with a bevel join omits the miter-only corner pixel. + /// + [Fact] + public void PathStroker_Stroke_RightAngleCornerBevelJoin_FillsFlatBeveledCorner() + { + // Arrange + var path = BuildRightAnglePath(); + var style = new StrokeStyle(4f, cap: LineCap.Butt, join: LineJoin.Bevel); + + // Act + var surface = RenderStroke(path, style, 14, 12); + + // Assert + Assert.Equal((byte)0, surface[9, 2].A); + Assert.Equal((byte)128, surface[8, 2].A); + } + + /// + /// Proves that stroking a closed rectangle produces a ring with an unfilled center and an + /// unfilled exterior. + /// + [Fact] + public void PathStroker_Stroke_ClosedRectangle_FillsRingLeavingInteriorAndExteriorUnfilled() + { + // Arrange + var path = new PathBuilder() + .MoveTo(new Vector2(2, 2)) + .LineTo(new Vector2(6, 2)) + .LineTo(new Vector2(6, 6)) + .LineTo(new Vector2(2, 6)) + .Close() + .Build(); + var style = new StrokeStyle(2f); + + // Act + var surface = RenderStroke(path, style, 8, 8); + + // Assert + Assert.Equal((byte)255, surface[1, 3].A); + Assert.Equal((byte)0, surface[3, 3].A); + Assert.Equal((byte)0, surface[0, 0].A); + } + + /// + /// Proves that a sharp corner exceeding the miter limit falls back to bevel geometry. + /// + [Fact] + public void PathStroker_Stroke_SharpAngleExceedingMiterLimit_FallsBackToBevel() + { + // Arrange + var path = BuildRightAnglePath(); + var style = new StrokeStyle(4f, cap: LineCap.Butt, join: LineJoin.Miter, miterLimit: 1f); + + // Act + var surface = RenderStroke(path, style, 14, 12); + + // Assert + Assert.Equal((byte)0, surface[9, 2].A); + Assert.Equal((byte)128, surface[8, 2].A); + } + + /// + /// Proves that dashing leaves gaps unfilled between visible stroke segments. + /// + [Fact] + public void PathStroker_Stroke_DashedLine_FillsOnlyOnSegmentsLeavingGapsUnfilled() + { + // Arrange + var path = new PathBuilder() + .MoveTo(new Vector2(0, 2)) + .LineTo(new Vector2(10, 2)) + .Build(); + var style = new StrokeStyle(2f, cap: LineCap.Butt, dashArray: [2f, 2f]); + + // Act + var surface = RenderStroke(path, style, 11, 5); + + // Assert + Assert.Equal((byte)255, surface[0, 1].A); + Assert.Equal((byte)0, surface[2, 1].A); + Assert.Equal((byte)255, surface[4, 1].A); + Assert.Equal((byte)0, surface[6, 1].A); + } + + /// + /// Proves that a zero-length subpath with a round cap becomes a full circle. + /// + [Fact] + public void PathStroker_Stroke_ZeroLengthSubpathRoundCap_FillsCircleOfRadiusHalfWidth() + { + // Arrange + var path = new PathBuilder() + .MoveTo(new Vector2(2, 2)) + .LineTo(new Vector2(2, 2)) + .Build(); + var style = new StrokeStyle(2f, cap: LineCap.Round); + + // Act + var surface = RenderStroke(path, style, 5, 5); + + // Assert + Assert.Equal((byte)148, surface[1, 1].A); + Assert.Equal((byte)0, surface[0, 0].A); + } + + /// + /// Proves that a zero-length subpath with a square cap becomes a width-by-width square. + /// + [Fact] + public void PathStroker_Stroke_ZeroLengthSubpathSquareCap_FillsSquareOfSideWidth() + { + // Arrange + var path = new PathBuilder() + .MoveTo(new Vector2(2, 2)) + .LineTo(new Vector2(2, 2)) + .Build(); + var style = new StrokeStyle(2f, cap: LineCap.Square); + + // Act + var surface = RenderStroke(path, style, 5, 5); + + // Assert + Assert.Equal((byte)255, surface[1, 1].A); + Assert.Equal((byte)255, surface[2, 2].A); + Assert.Equal((byte)0, surface[0, 0].A); + } + + /// + /// Proves that a zero-length subpath with a butt cap contributes no fillable area. + /// + [Fact] + public void PathStroker_Stroke_ZeroLengthSubpathButtCap_ProducesNoFilledPixels() + { + // Arrange + var path = new PathBuilder() + .MoveTo(new Vector2(2, 2)) + .LineTo(new Vector2(2, 2)) + .Build(); + var style = new StrokeStyle(2f, cap: LineCap.Butt); + + // Act + var surface = RenderStroke(path, style, 5, 5); + + // Assert + Assert.Equal((byte)0, surface[1, 1].A); + Assert.Equal((byte)0, surface[2, 2].A); + } + + /// + /// Proves that a single-point subpath matches the zero-length-subpath cap behavior. + /// + [Fact] + public void PathStroker_Stroke_SinglePointSubpath_MatchesZeroLengthSubpathBehavior() + { + // Arrange + var singlePointPath = new PathBuilder() + .MoveTo(new Vector2(2, 2)) + .Build(); + var zeroLengthPath = new PathBuilder() + .MoveTo(new Vector2(2, 2)) + .LineTo(new Vector2(2, 2)) + .Build(); + var style = new StrokeStyle(2f, cap: LineCap.Round); + + // Act + var singlePoint = RenderStroke(singlePointPath, style, 5, 5); + var zeroLength = RenderStroke(zeroLengthPath, style, 5, 5); + + // Assert + for (var y = 0; y < 5; y++) + { + for (var x = 0; x < 5; x++) + { + Assert.Equal(zeroLength[x, y], singlePoint[x, y]); + } + } + } + + /// + /// Proves that stroking an empty path returns and renders no + /// pixels when subsequently filled. + /// + [Fact] + public void PathStroker_Stroke_EmptyPath_ReturnsEmptyPathNoOp() + { + // Arrange + var style = new StrokeStyle(2f); + + // Act + var stroked = PathStroker.Stroke(Path.Empty, style); + var surface = new Surface(3, 3); + PathFiller.Fill(surface, stroked, new Rgba32(255, 0, 0, 255)); + + // Assert + Assert.Same(Path.Empty, stroked); + Assert.Equal((byte)0, surface[1, 1].A); + } + + /// + /// Proves that a null path is rejected. + /// + [Fact] + public void PathStroker_Stroke_NullPath_ThrowsArgumentNullException() + { + // Arrange / Act / Assert + Assert.Throws(() => PathStroker.Stroke(null!, new StrokeStyle(1f))); + } + + /// + /// Proves that a null stroke style is rejected. + /// + [Fact] + public void PathStroker_Stroke_NullStrokeStyle_ThrowsArgumentNullException() + { + // Arrange + var path = new PathBuilder() + .MoveTo(new Vector2(0, 0)) + .LineTo(new Vector2(1, 0)) + .Build(); + + // Act / Assert + Assert.Throws(() => PathStroker.Stroke(path, null!)); + } + + /// + /// Proves that a non-positive or non-finite flatten tolerance is rejected. + /// + [Theory] + [InlineData(0f)] + [InlineData(-1f)] + [InlineData(float.NaN)] + [InlineData(float.PositiveInfinity)] + [InlineData(float.NegativeInfinity)] + public void PathStroker_Stroke_NonPositiveFlattenTolerance_ThrowsArgumentOutOfRangeException(float tolerance) + { + // Arrange + var path = new PathBuilder() + .MoveTo(new Vector2(0, 0)) + .LineTo(new Vector2(1, 0)) + .Build(); + var style = new StrokeStyle(1f); + + // Act / Assert + Assert.Throws(() => PathStroker.Stroke(path, style, tolerance)); + } + + private static Path BuildRightAnglePath() => new PathBuilder() + .MoveTo(new Vector2(4, 4)) + .LineTo(new Vector2(8, 4)) + .LineTo(new Vector2(8, 8)) + .Build(); + + private static Surface RenderStroke(Path path, StrokeStyle style, int width, int height, float flattenTolerance = 0.25f) + { + var stroked = PathStroker.Stroke(path, style, flattenTolerance); + var surface = new Surface(width, height); + PathFiller.Fill(surface, stroked, new Rgba32(255, 0, 0, 255), FillRule.NonZero, flattenTolerance); + return surface; + } +} diff --git a/test/DemaConsulting.CanvasNet.Tests/Drawing/StrokeOutlinerTests.cs b/test/DemaConsulting.CanvasNet.Tests/Drawing/StrokeOutlinerTests.cs new file mode 100644 index 000000000..4e8c26a6b --- /dev/null +++ b/test/DemaConsulting.CanvasNet.Tests/Drawing/StrokeOutlinerTests.cs @@ -0,0 +1,87 @@ +using System.Numerics; +using DemaConsulting.CanvasNet.Drawing; + +// cspell:ignore Outliner + +namespace DemaConsulting.CanvasNet.Tests.Drawing; + +/// +/// Unit tests for the internal type. +/// +public class StrokeOutlinerTests +{ + /// + /// Proves that a closed contour produces one outer ring and one inner ring wound in + /// opposite directions. + /// + [Fact] + public void StrokeOutliner_Outline_ClosedSubpath_ProducesTwoCounterWoundRings() + { + // Arrange + var points = new List + { + new(2, 2), + new(6, 2), + new(6, 6), + new(2, 6) + }; + var style = new StrokeStyle(2f); + + // Act + var polygons = StrokeOutliner.Outline(points, isClosed: true, style, flattenTolerance: 0.25f); + + // Assert + Assert.Equal(2, polygons.Count); + Assert.True(GetSignedArea(polygons[0]) * GetSignedArea(polygons[1]) < 0f); + } + + /// + /// Proves that a miter join within the configured limit emits the sharp intersection + /// vertex. + /// + [Fact] + public void StrokeOutliner_Outline_MiterJoinWithinLimit_ProducesSharpVertex() + { + // Arrange + var points = new List { new(4, 4), new(8, 4), new(8, 8) }; + var style = new StrokeStyle(4f, join: LineJoin.Miter, miterLimit: 4f); + + // Act + var polygon = Assert.Single(StrokeOutliner.Outline(points, isClosed: false, style, flattenTolerance: 0.25f)); + + // Assert + Assert.Contains(new Vector2(10, 2), polygon); + } + + /// + /// Proves that a miter join exceeding the configured limit falls back to bevel vertices. + /// + [Fact] + public void StrokeOutliner_Outline_MiterJoinExceedingLimit_FallsBackToBevelVertex() + { + // Arrange + var points = new List { new(4, 4), new(8, 4), new(8, 8) }; + var style = new StrokeStyle(4f, join: LineJoin.Miter, miterLimit: 1f); + + // Act + var polygon = Assert.Single(StrokeOutliner.Outline(points, isClosed: false, style, flattenTolerance: 0.25f)); + + // Assert + Assert.DoesNotContain(new Vector2(10, 2), polygon); + Assert.Contains(new Vector2(8, 2), polygon); + Assert.Contains(new Vector2(10, 4), polygon); + } + + private static float GetSignedArea(IReadOnlyList points) + { + var area = 0f; + for (var i = 0; i < points.Count; i++) + { + var current = points[i]; + var next = points[(i + 1) % points.Count]; + area += current.X * next.Y - current.Y * next.X; + } + + return area / 2f; + } +} diff --git a/test/DemaConsulting.CanvasNet.Tests/Drawing/StrokePathFlattenerTests.cs b/test/DemaConsulting.CanvasNet.Tests/Drawing/StrokePathFlattenerTests.cs new file mode 100644 index 000000000..8021d9258 --- /dev/null +++ b/test/DemaConsulting.CanvasNet.Tests/Drawing/StrokePathFlattenerTests.cs @@ -0,0 +1,127 @@ +using System.Numerics; +using DemaConsulting.CanvasNet.Drawing; +using DemaConsulting.CanvasNet.Geometry; +using Path = DemaConsulting.CanvasNet.Geometry.Path; + +namespace DemaConsulting.CanvasNet.Tests.Drawing; + +/// +/// Unit tests for the internal type. +/// +public class StrokePathFlattenerTests +{ + /// + /// Proves that an open subpath remains open after flattening. + /// + [Fact] + public void StrokePathFlattener_Flatten_OpenSubpath_PreservesIsClosedFalse() + { + // Arrange + var path = new PathBuilder() + .MoveTo(new Vector2(0, 0)) + .LineTo(new Vector2(3, 4)) + .Build(); + + // Act + var flattened = StrokePathFlattener.Flatten(path, 0.25f); + + // Assert + var subpath = Assert.Single(flattened); + Assert.False(subpath.IsClosed); + Assert.Equal([new Vector2(0, 0), new Vector2(3, 4)], subpath.Points); + } + + /// + /// Proves that a closed subpath remains closed without gaining an implicit duplicate start + /// point. + /// + [Fact] + public void StrokePathFlattener_Flatten_ClosedSubpath_PreservesIsClosedTrueWithNoImplicitDuplicatePoint() + { + // Arrange + var path = new PathBuilder() + .MoveTo(new Vector2(0, 0)) + .LineTo(new Vector2(4, 0)) + .LineTo(new Vector2(0, 4)) + .Close() + .Build(); + + // Act + var flattened = StrokePathFlattener.Flatten(path, 0.25f); + + // Assert + var subpath = Assert.Single(flattened); + Assert.True(subpath.IsClosed); + Assert.Equal(3, subpath.Points.Count); + Assert.NotEqual(subpath.Points[0], subpath.Points[^1]); + } + + /// + /// Proves that curve commands are delegated to the existing Bezier-flattening helpers. + /// + [Fact] + public void StrokePathFlattener_Flatten_CurveCommands_DelegatesToBezierFlattening() + { + // Arrange + const float tolerance = 0.25f; + var start = new Vector2(0, 0); + var quadraticControl = new Vector2(2, 4); + var quadraticEnd = new Vector2(4, 0); + var cubicControl1 = new Vector2(5, 2); + var cubicControl2 = new Vector2(7, 2); + var cubicEnd = new Vector2(8, 0); + var path = new PathBuilder() + .MoveTo(start) + .QuadraticBezierTo(quadraticControl, quadraticEnd) + .CubicBezierTo(cubicControl1, cubicControl2, cubicEnd) + .Build(); + + var expected = new List { start }; + BezierFlattening.FlattenQuadratic(start, quadraticControl, quadraticEnd, tolerance, expected); + BezierFlattening.FlattenCubic(quadraticEnd, cubicControl1, cubicControl2, cubicEnd, tolerance, expected); + + // Act + var flattened = StrokePathFlattener.Flatten(path, tolerance); + + // Assert + var subpath = Assert.Single(flattened); + Assert.Equal(expected, subpath.Points); + } + + /// + /// Proves that multiple subpaths remain separate flattened entries. + /// + [Fact] + public void StrokePathFlattener_Flatten_MultipleSubpaths_RemainSeparate() + { + // Arrange + var path = new PathBuilder() + .MoveTo(new Vector2(0, 0)) + .LineTo(new Vector2(1, 0)) + .MoveTo(new Vector2(5, 5)) + .LineTo(new Vector2(6, 5)) + .Close() + .Build(); + + // Act + var flattened = StrokePathFlattener.Flatten(path, 0.25f); + + // Assert + Assert.Equal(2, flattened.Count); + Assert.False(flattened[0].IsClosed); + Assert.True(flattened[1].IsClosed); + } + + /// + /// Proves that flattening an empty path yields no flattened subpaths. + /// + [Fact] + public void StrokePathFlattener_Flatten_EmptyPath_ReturnsEmptyList() + { + // Act + var flattened = StrokePathFlattener.Flatten(Path.Empty, 0.25f); + + // Assert + Assert.Empty(flattened); + } +} diff --git a/test/DemaConsulting.CanvasNet.Tests/Drawing/StrokeStyleTests.cs b/test/DemaConsulting.CanvasNet.Tests/Drawing/StrokeStyleTests.cs new file mode 100644 index 000000000..33806c006 --- /dev/null +++ b/test/DemaConsulting.CanvasNet.Tests/Drawing/StrokeStyleTests.cs @@ -0,0 +1,107 @@ +using DemaConsulting.CanvasNet.Drawing; + +namespace DemaConsulting.CanvasNet.Tests.Drawing; + +/// +/// Unit tests for . +/// +public class StrokeStyleTests +{ + /// + /// Proves that the constructor rejects a non-positive or non-finite width. + /// + [Theory] + [InlineData(0f)] + [InlineData(-1f)] + [InlineData(float.NaN)] + [InlineData(float.PositiveInfinity)] + [InlineData(float.NegativeInfinity)] + public void StrokeStyle_Constructor_NonPositiveWidth_ThrowsArgumentOutOfRangeException(float width) + { + // Arrange / Act / Assert + Assert.Throws(() => new StrokeStyle(width)); + } + + /// + /// Proves that the constructor rejects a miter limit below one. + /// + [Fact] + public void StrokeStyle_Constructor_MiterLimitBelowOne_ThrowsArgumentOutOfRangeException() + { + // Arrange / Act / Assert + Assert.Throws(() => new StrokeStyle(1f, miterLimit: 0.99f)); + } + + /// + /// Proves that the default miter limit is four. + /// + [Fact] + public void StrokeStyle_Constructor_DefaultMiterLimit_IsFour() + { + // Arrange / Act + var style = new StrokeStyle(3f); + + // Assert + Assert.Equal(4f, style.MiterLimit); + } + + /// + /// Proves that null or empty dash arrays are treated as a solid stroke. + /// + [Fact] + public void StrokeStyle_Constructor_NullOrEmptyDashArray_IsTreatedAsSolid() + { + // Arrange / Act + var nullStyle = new StrokeStyle(2f, dashArray: null); + var emptyStyle = new StrokeStyle(2f, dashArray: Array.Empty()); + + // Assert + Assert.Null(nullStyle.DashArray); + Assert.Null(emptyStyle.DashArray); + } + + /// + /// Proves that the constructor rejects any negative dash-array entry. + /// + [Fact] + public void StrokeStyle_Constructor_DashArrayWithNegativeEntry_ThrowsArgumentException() + { + // Arrange / Act / Assert + Assert.Throws(() => new StrokeStyle(2f, dashArray: [1f, -1f])); + } + + /// + /// Proves that the constructor rejects a dash array whose entries are all zero. + /// + [Fact] + public void StrokeStyle_Constructor_DashArrayAllZero_ThrowsArgumentException() + { + // Arrange / Act / Assert + Assert.Throws(() => new StrokeStyle(2f, dashArray: [0f, 0f, 0f])); + } + + /// + /// Proves that valid constructor arguments round-trip through the exposed properties. + /// + [Fact] + public void StrokeStyle_Constructor_ValidValues_PropertiesRoundTrip() + { + // Arrange / Act + var style = new StrokeStyle( + 5f, + LineCap.Round, + LineJoin.Bevel, + 7f, + [2f, 1f, 3f], + dashOffset: -0.5f); + + // Assert + Assert.Equal(5f, style.Width); + Assert.Equal(LineCap.Round, style.Cap); + Assert.Equal(LineJoin.Bevel, style.Join); + Assert.Equal(7f, style.MiterLimit); + Assert.NotNull(style.DashArray); + Assert.Equal([2f, 1f, 3f], style.DashArray.ToArray()); + Assert.Equal(-0.5f, style.DashOffset); + } +} From 890109fe5157d764b9e3f052e2167cfe66b79671 Mon Sep 17 00:00:00 2001 From: Malcolm Nixon Date: Mon, 21 Sep 2026 11:53:17 -0400 Subject: [PATCH 02/13] Fix round join/cap collapse when flattenTolerance/radius underflows float32 precision GetArcSegmentCount could return 1 (a single straight chord) whenever flattenTolerance / radius underflowed float32 precision (~1.19e-7), which happens once stroke half-width exceeds roughly 2e6 units for ordinary flatten tolerances. This silently degraded LineJoin.Round / LineCap.Round to a sharp straight edge with no error, and applied inconsistently since CreateCirclePolygon already guarded with Math.Max(4, ...) while AppendArc's join/cap call sites did not. GetArcSegmentCount now falls back to a conservative angle-based minimum segment count (one segment per PI/2 radians of sweep) whenever the tolerance-based computation underflows to zero, and applies that same floor uniformly to every call site (via Math.Max), so round joins/caps never collapse to a straight chord for any valid, finite radius/sweep. This mirrors BezierFlattening's MaxRecursionDepth convention of explicitly bounding pathological-input behavior instead of degrading silently. Adds regression tests proving: - a round join at extreme half-width still bulges substantially away from the equivalent bevel join's vertices (not just float32 noise), - typical-scale round-cap tessellation still matches the exact segment count implied by the flattening-tolerance formula. --- .../Drawing/StrokeOutliner.cs | 33 ++++++++-- .../Drawing/StrokeOutlinerTests.cs | 62 ++++++++++++++++++- 2 files changed, 90 insertions(+), 5 deletions(-) diff --git a/src/DemaConsulting.CanvasNet/Drawing/StrokeOutliner.cs b/src/DemaConsulting.CanvasNet/Drawing/StrokeOutliner.cs index 93bf9a6c6..095ff2d42 100644 --- a/src/DemaConsulting.CanvasNet/Drawing/StrokeOutliner.cs +++ b/src/DemaConsulting.CanvasNet/Drawing/StrokeOutliner.cs @@ -1,6 +1,6 @@ using System.Numerics; -// cspell:ignore Outliner outliner +// cspell:ignore Outliner outliner underflows underflowed namespace DemaConsulting.CanvasNet.Drawing; @@ -544,10 +544,30 @@ private static void AppendArc( } } + /// + /// The angle (in radians) swept by a single segment when falling back to the + /// angle-based minimum segment count heuristic (see ). + /// + private const float FallbackSegmentAngle = MathF.PI / 2f; + /// /// Computes the number of straight segments needed to keep an arc's sagitta within the /// requested flattening tolerance. /// + /// + /// At sufficiently large (or sufficiently small + /// ), flattenTolerance / radius underflows + /// float32 precision (below ~1.19e-7), which would make 1f - flattenTolerance / radius + /// round to exactly 1.0f and return 0. Rather + /// than let that precision loss silently collapse the arc to a single straight chord, this + /// method falls back to a conservative angle-based minimum segment count (one segment per + /// radians of sweep) so round joins/caps always produce a + /// genuinely curved outline for any valid, finite radius and sweep. This mirrors the + /// established convention (see + /// 's + /// MaxRecursionDepth) of explicitly bounding pathological-input behavior instead of + /// degrading silently. + /// private static int GetArcSegmentCount(float radius, float sweepMagnitude, float flattenTolerance) { if (radius <= 0f || sweepMagnitude <= 0f) @@ -555,9 +575,11 @@ private static int GetArcSegmentCount(float radius, float sweepMagnitude, float return 1; } + var fallbackCount = Math.Max(1, (int)MathF.Ceiling(sweepMagnitude / FallbackSegmentAngle)); + if (flattenTolerance >= radius) { - return Math.Max(1, (int)MathF.Ceiling(sweepMagnitude / (MathF.PI / 2f))); + return fallbackCount; } var cosine = 1f - flattenTolerance / radius; @@ -565,10 +587,13 @@ private static int GetArcSegmentCount(float radius, float sweepMagnitude, float var maxAngle = 2f * MathF.Acos(cosine); if (!float.IsFinite(maxAngle) || maxAngle <= 0f) { - return 1; + // flattenTolerance / radius underflowed to (effectively) zero: the tolerance-based + // computation cannot distinguish this arc from a full circle, so fall back to the + // angle-based heuristic instead of returning 1 (a single straight chord). + return fallbackCount; } - return Math.Max(1, (int)MathF.Ceiling(sweepMagnitude / maxAngle)); + return Math.Max(fallbackCount, (int)MathF.Ceiling(sweepMagnitude / maxAngle)); } /// diff --git a/test/DemaConsulting.CanvasNet.Tests/Drawing/StrokeOutlinerTests.cs b/test/DemaConsulting.CanvasNet.Tests/Drawing/StrokeOutlinerTests.cs index 4e8c26a6b..7a38c3a81 100644 --- a/test/DemaConsulting.CanvasNet.Tests/Drawing/StrokeOutlinerTests.cs +++ b/test/DemaConsulting.CanvasNet.Tests/Drawing/StrokeOutlinerTests.cs @@ -1,7 +1,8 @@ +using System.Linq; using System.Numerics; using DemaConsulting.CanvasNet.Drawing; -// cspell:ignore Outliner +// cspell:ignore Outliner underflows namespace DemaConsulting.CanvasNet.Tests.Drawing; @@ -72,6 +73,65 @@ public void StrokeOutliner_Outline_MiterJoinExceedingLimit_FallsBackToBevelVerte Assert.Contains(new Vector2(10, 4), polygon); } + /// + /// Proves that a round join at an extreme stroke half-width (large enough that + /// flattenTolerance / radius underflows float32 precision) still produces a + /// genuinely curved (multi-segment) outline rather than silently degrading into the same + /// straight chord a bevel join would produce. + /// + [Fact] + public void StrokeOutliner_Outline_RoundJoinAtExtremeScale_ProducesCurvedNotStraightJoin() + { + // Arrange: a sharp (~177 degree) turn so the round join's convex side sweeps a large + // angle, paired with a stroke half-width many orders of magnitude larger than the + // ~1.19e-7 relative float32 precision floor (so flattenTolerance / radius underflows to + // zero for any reasonable flattenTolerance). + var points = new List { new(0, 0), new(10, 0), new(0, 0.5f) }; + const float extremeWidth = 2e13f; + var halfWidth = extremeWidth / 2f; + var roundStyle = new StrokeStyle(extremeWidth, join: LineJoin.Round); + var bevelStyle = new StrokeStyle(extremeWidth, join: LineJoin.Bevel); + + // Act + var roundPolygon = Assert.Single(StrokeOutliner.Outline(points, isClosed: false, roundStyle, flattenTolerance: 0.25f)); + var bevelPolygon = Assert.Single(StrokeOutliner.Outline(points, isClosed: false, bevelStyle, flattenTolerance: 0.25f)); + + // Assert: the round join must contribute at least one vertex that sits substantially away + // from every vertex the (straight-chord) bevel join produces at the same geometry and + // scale. A genuine multi-segment arc bulges far off the previous/next tangent-point chord + // (here, by nearly the full half-width), whereas a collapsed single-chord arc endpoint + // would land within float32 noise (~halfWidth * 1.2e-7) of the bevel join's own vertex. + // The threshold below sits comfortably between those two scales. + var maxDistanceFromBevel = roundPolygon + .Select(roundVertex => bevelPolygon.Min(bevelVertex => Vector2.Distance(roundVertex, bevelVertex))) + .Max(); + Assert.True( + maxDistanceFromBevel > halfWidth * 0.1f, + $"Expected a round-join vertex more than {halfWidth * 0.1f} units from any bevel-join vertex " + + $"(found max {maxDistanceFromBevel}): a small distance indicates the flattenTolerance/radius " + + "underflow regression has returned and the round join collapsed to a single straight chord."); + } + + /// + /// Proves that the extreme-scale safety fallback does not change tessellation at ordinary, + /// well-conditioned scales: a round-capped point stroke must still produce exactly the + /// segment count implied by the flattening-tolerance formula. + /// + [Fact] + public void StrokeOutliner_Outline_RoundCapAtTypicalScale_MatchesExpectedSegmentCount() + { + // Arrange: with a half-width of 2 and a flattening tolerance of 0.25, the tolerance-based + // formula yields a maximum chord angle of roughly 1.010465 radians, which requires + // exactly 7 segments to sweep a full circle within tolerance. + var style = new StrokeStyle(4f, cap: LineCap.Round); + + // Act + var polygon = Assert.Single(StrokeOutliner.Outline([new Vector2(0, 0)], isClosed: false, style, flattenTolerance: 0.25f)); + + // Assert + Assert.Equal(7, polygon.Count); + } + private static float GetSignedArea(IReadOnlyList points) { var area = 0f; From bb59d770264d73290aca6712e4c6d45e2cdd3ead Mon Sep 17 00:00:00 2001 From: Malcolm Nixon Date: Mon, 21 Sep 2026 12:17:06 -0400 Subject: [PATCH 03/13] Fix 4 automated-review findings on stroke dashing/outlining - DashSplitter.GetPatternLength now sums in double (not float) and Split rejects a non-finite total pattern length before phase traversal, fixing an infinite loop reachable via a legal dash array such as [float.MaxValue, float.MaxValue] combined with a negative dashOffset. - DashSplitter's per-interval extraction now threads monotonic vertex and point-lookup cursors across all dash intervals instead of rescanning the whole polyline per interval, restoring the documented O(N + M) linear-pass cost instead of O(N * M). - StrokeOutliner.Outline now special-cases a closed subpath reduced to exactly two distinct points (zero signed area) by outlining it the same way an equivalent open single-segment stroke would be outlined, instead of producing a coincident outer/inner ring pair that FillRule.NonZero cancels to nothing. - StrokeOutliner.GetArcSegmentCount's flattenTolerance/radius underflow fallback now clamps to a minimum of 2 segments, so small sweep angles (at most 90 degrees) no longer collapse back to a single straight chord. Adds regression tests for all four fixes, including public-API-level coverage through PathStroker.Stroke and PathFiller pixel-coverage checks for the degenerate closed 2-point subpath case. --- .../Drawing/DashSplitter.cs | 138 +++++++++++++----- .../Drawing/StrokeOutliner.cs | 21 ++- .../Drawing/DashSplitterTests.cs | 29 ++++ .../Drawing/PathStrokerTests.cs | 55 +++++++ .../Drawing/StrokeOutlinerTests.cs | 44 ++++++ 5 files changed, 249 insertions(+), 38 deletions(-) diff --git a/src/DemaConsulting.CanvasNet/Drawing/DashSplitter.cs b/src/DemaConsulting.CanvasNet/Drawing/DashSplitter.cs index 33ae19073..37700a7a2 100644 --- a/src/DemaConsulting.CanvasNet/Drawing/DashSplitter.cs +++ b/src/DemaConsulting.CanvasNet/Drawing/DashSplitter.cs @@ -45,7 +45,15 @@ internal static class DashSplitter var pattern = NormalizeDashArray(dashArray!); var totalPatternLength = GetPatternLength(pattern); - if (totalPatternLength <= 0f) + if (totalPatternLength <= 0d) + { + return [(new List(points), isClosed)]; + } + + // A pattern length that is not finite (astronomically large dash entries summing beyond + // double range) cannot be phase-normalized or traversed at all; fall back to a solid + // stroke rather than risk any downstream arithmetic on a non-finite value. + if (!double.IsFinite(totalPatternLength)) { return [(new List(points), isClosed)]; } @@ -75,9 +83,25 @@ internal static class DashSplitter } var segments = new List<(List Points, bool IsClosed)>(onIntervals.Count); + + // Both cursors only ever move forward across this loop: onIntervals is produced by a + // single monotonic walk from 0 to totalLength in BuildOnIntervals, so successive + // Start/End values never decrease. Threading a shared vertex cursor and point-lookup + // cursor through every interval (instead of each call scanning again from the beginning) + // keeps the whole extraction pass O(edgeCount + onIntervals.Count) rather than + // O(edgeCount * onIntervals.Count). + var vertexCursor = 0; + var pointCursor = 0; foreach (var interval in onIntervals) { - var segment = ExtractIntervalPolyline(points, isClosed, cumulativeLengths, interval.Start, interval.End); + var segment = ExtractIntervalPolyline( + points, + isClosed, + cumulativeLengths, + interval.Start, + interval.End, + ref vertexCursor, + ref pointCursor); if (segment.Count != 0) { segments.Add((segment, false)); @@ -152,9 +176,20 @@ private static float[] NormalizeDashArray(IReadOnlyList dashArray) /// /// Computes the total pattern length. /// - private static float GetPatternLength(IReadOnlyList pattern) + /// + /// Summed in rather than : every entry is + /// individually finite (enforced by 's constructor validation), + /// but a legal pattern such as [float.MaxValue, float.MaxValue] would still overflow + /// a running sum to +Infinity. An infinite pattern length + /// then breaks phase normalization () and can turn the + /// phase-traversal loops in and + /// into an infinite loop, because subtracting any finite dash entry from + /// float.PositiveInfinity never reduces it. Double has ample headroom for the sum of + /// any number of finite float32 values, so this keeps the total representable. + /// + private static double GetPatternLength(IReadOnlyList pattern) { - var total = 0f; + var total = 0d; foreach (var value in pattern) { total += value; @@ -189,7 +224,7 @@ private static bool IsDashOnAtStart(IReadOnlyList pattern, float dashOffs var patternLength = GetPatternLength(pattern); var offset = NormalizeModulo(dashOffset, patternLength); var index = 0; - while (offset > 0f) + while (offset > 0d) { var length = pattern[index]; if (length > 0f && offset < length) @@ -220,7 +255,7 @@ private static bool IsDashOnAtStart(IReadOnlyList pattern, float dashOffs var offset = NormalizeModulo(dashOffset, patternLength); var dashIndex = 0; - while (offset > 0f) + while (offset > 0d) { var length = pattern[dashIndex]; if (length > 0f && offset < length) @@ -232,7 +267,10 @@ private static bool IsDashOnAtStart(IReadOnlyList pattern, float dashOffs dashIndex = (dashIndex + 1) % pattern.Count; } - var remainingInDash = pattern[dashIndex] - offset; + // By the loop invariant above, offset is now strictly less than pattern[dashIndex] (a + // finite float32 entry), so the remainder is safe to narrow back to float without any + // risk of the overflow this method exists to avoid. + var remainingInDash = (float)(pattern[dashIndex] - offset); if (remainingInDash < 0f) { remainingInDash = 0f; @@ -293,37 +331,64 @@ private static void AdvanceDash(IReadOnlyList pattern, ref int dashIndex, /// Extracts the sub-polyline between and /// . /// + /// + /// and are threaded in from + /// the caller and advance monotonically across every interval extracted from the same + /// polyline (see the call site in ): because successive intervals never + /// move backward along the path, each cursor only ever walks forward past a given vertex + /// or edge once across the whole extraction pass, making the combined cost linear in the + /// number of polyline edges plus the number of intervals rather than their product. + /// private static List ExtractIntervalPolyline( IReadOnlyList points, bool isClosed, IReadOnlyList cumulativeLengths, float startDistance, - float endDistance) + float endDistance, + ref int vertexCursor, + ref int pointCursor) { var segment = new List(); - AddPointIfDistinct(segment, GetPointAtDistance(points, isClosed, cumulativeLengths, startDistance)); + AddPointIfDistinct(segment, GetPointAtDistance(points, isClosed, cumulativeLengths, startDistance, ref pointCursor)); var edgeCount = cumulativeLengths.Count - 1; - for (var i = 1; i < edgeCount; i++) + + // Advance past any vertex boundaries at or before startDistance (including the implicit + // index 0 boundary, whose cumulative length is always zero). + while (vertexCursor < edgeCount && cumulativeLengths[vertexCursor] <= startDistance) { - if (cumulativeLengths[i] > startDistance && cumulativeLengths[i] < endDistance) - { - AddPointIfDistinct(segment, points[i % points.Count]); - } + vertexCursor++; + } + + // Emit every vertex strictly between startDistance and endDistance, advancing the cursor + // forward as each is consumed. + while (vertexCursor < edgeCount && cumulativeLengths[vertexCursor] < endDistance) + { + AddPointIfDistinct(segment, points[vertexCursor % points.Count]); + vertexCursor++; } - AddPointIfDistinct(segment, GetPointAtDistance(points, isClosed, cumulativeLengths, endDistance)); + AddPointIfDistinct(segment, GetPointAtDistance(points, isClosed, cumulativeLengths, endDistance, ref pointCursor)); return segment; } /// /// Evaluates the polyline point at the specified arc-length distance. /// + /// + /// is threaded in from the caller and only ever advances + /// forward: since every call made across one pass supplies a + /// non-decreasing (see ), + /// resuming the edge-bracket search from wherever the previous call left off - rather than + /// restarting from edge zero - keeps the search across all calls linear in the number of + /// polyline edges instead of quadratic in edges times calls. + /// private static Vector2 GetPointAtDistance( IReadOnlyList points, bool isClosed, IReadOnlyList cumulativeLengths, - float distance) + float distance, + ref int edgeCursor) { if (distance <= 0f) { @@ -337,38 +402,39 @@ private static Vector2 GetPointAtDistance( } var edgeCount = cumulativeLengths.Count - 1; - for (var i = 0; i < edgeCount; i++) + while (edgeCursor < edgeCount - 1 && distance > cumulativeLengths[edgeCursor + 1]) { - var startLength = cumulativeLengths[i]; - var endLength = cumulativeLengths[i + 1]; - if (distance > endLength) - { - continue; - } - - var edgeStart = points[i]; - var edgeEnd = points[(i + 1) % points.Count]; - var edgeLength = endLength - startLength; - if (edgeLength <= 0f) - { - return edgeStart; - } + edgeCursor++; + } - var t = (distance - startLength) / edgeLength; - return Vector2.Lerp(edgeStart, edgeEnd, t); + var startLength = cumulativeLengths[edgeCursor]; + var endLength = cumulativeLengths[edgeCursor + 1]; + var edgeStart = points[edgeCursor]; + var edgeEnd = points[(edgeCursor + 1) % points.Count]; + var edgeLength = endLength - startLength; + if (edgeLength <= 0f) + { + return edgeStart; } - return isClosed ? points[0] : points[^1]; + var t = (distance - startLength) / edgeLength; + return Vector2.Lerp(edgeStart, edgeEnd, t); } /// /// Normalizes into the half-open interval /// [0, modulus). /// - private static float NormalizeModulo(float value, float modulus) + /// + /// is a (the total dash pattern + /// length, see ) so that a pattern summing close to + /// still normalizes correctly instead of collapsing to + /// float.PositiveInfinity. + /// + private static double NormalizeModulo(float value, double modulus) { var normalized = value % modulus; - if (normalized < 0f) + if (normalized < 0d) { normalized += modulus; } diff --git a/src/DemaConsulting.CanvasNet/Drawing/StrokeOutliner.cs b/src/DemaConsulting.CanvasNet/Drawing/StrokeOutliner.cs index 095ff2d42..d01daa5d3 100644 --- a/src/DemaConsulting.CanvasNet/Drawing/StrokeOutliner.cs +++ b/src/DemaConsulting.CanvasNet/Drawing/StrokeOutliner.cs @@ -47,6 +47,18 @@ internal static List> Outline( return CreatePointStrokePolygons(simplified[0], style.Cap, halfWidth, flattenTolerance); } + if (isClosed && simplified.Count == 2) + { + // A closed contour needs at least three distinct vertices to enclose any area; with + // exactly two, the "outer" and "inner" offset rings built by CreateClosedStrokePolygons + // would be coincident (zero signed area) and then forced into opposite winding, which + // makes FillRule.NonZero cancel the whole band to nothing. Instead, treat this + // degenerate closed contour exactly as an equivalent open single-segment stroke would + // be outlined (with caps at both ends per style.Cap) - the only well-defined non-empty + // rendering of a closed path that immediately doubles back over the same segment. + return CreateOpenStrokePolygons(simplified, style, halfWidth, flattenTolerance); + } + return isClosed ? CreateClosedStrokePolygons(simplified, style, halfWidth, flattenTolerance) : CreateOpenStrokePolygons(simplified, style, halfWidth, flattenTolerance); @@ -589,8 +601,13 @@ private static int GetArcSegmentCount(float radius, float sweepMagnitude, float { // flattenTolerance / radius underflowed to (effectively) zero: the tolerance-based // computation cannot distinguish this arc from a full circle, so fall back to the - // angle-based heuristic instead of returning 1 (a single straight chord). - return fallbackCount; + // angle-based heuristic instead of returning 1 (a single straight chord). fallbackCount + // itself is exactly 1 for any sweep of at most FallbackSegmentAngle (PI/2, i.e. 90 + // degrees), which would silently collapse right back into the same single straight + // chord this fallback exists to eliminate; clamp to a minimum of 2 segments so every + // positive sweep - however small - still produces a genuinely curved (multi-segment) + // outline. + return Math.Max(2, fallbackCount); } return Math.Max(fallbackCount, (int)MathF.Ceiling(sweepMagnitude / maxAngle)); diff --git a/test/DemaConsulting.CanvasNet.Tests/Drawing/DashSplitterTests.cs b/test/DemaConsulting.CanvasNet.Tests/Drawing/DashSplitterTests.cs index 76be372e3..f50cc9c68 100644 --- a/test/DemaConsulting.CanvasNet.Tests/Drawing/DashSplitterTests.cs +++ b/test/DemaConsulting.CanvasNet.Tests/Drawing/DashSplitterTests.cs @@ -105,6 +105,35 @@ public void DashSplitter_Split_PatternLongerThanPolyline_ReturnsSinglePartialOnS Assert.Equal([new Vector2(0, 0), new Vector2(4, 0)], Assert.Single(segments).Points); } + /// + /// Proves that a dash array whose entries are each individually finite but whose summed + /// total pattern length overflows a naive float32 accumulation (e.g. two + /// entries) completes without hanging, even when combined + /// with a negative dash offset that forces phase normalization to traverse the pattern. + /// Prior to the fix, the overflowed () pattern length + /// made the phase-traversal loop subtract finite dash entries from infinity forever - an + /// effectively infinite loop. This test intentionally makes no timing assertion: it simply + /// relies on xUnit's normal test execution completing at all to prove the loop terminates. + /// + [Fact] + public void DashSplitter_Split_OverflowProneDashArrayWithNegativeOffset_CompletesWithoutHanging() + { + // Arrange: a dash pattern whose two entries individually are finite but whose float32 sum + // overflows to +Infinity, paired with a negative dash offset (both independently legal + // per StrokeStyle's validation) so phase normalization must traverse the pattern. + var points = new List { new(0, 0), new(10, 0) }; + + // Act + var segments = DashSplitter.Split( + points, + isClosed: false, + dashArray: [float.MaxValue, float.MaxValue], + dashOffset: -1f); + + // Assert: the call returned (did not hang) with a well-formed result + Assert.NotNull(segments); + } + /// /// Proves that an all-zero dash array is treated as a solid stroke. /// diff --git a/test/DemaConsulting.CanvasNet.Tests/Drawing/PathStrokerTests.cs b/test/DemaConsulting.CanvasNet.Tests/Drawing/PathStrokerTests.cs index 8b714f26d..8e699b239 100644 --- a/test/DemaConsulting.CanvasNet.Tests/Drawing/PathStrokerTests.cs +++ b/test/DemaConsulting.CanvasNet.Tests/Drawing/PathStrokerTests.cs @@ -162,6 +162,61 @@ public void PathStroker_Stroke_ClosedRectangle_FillsRingLeavingInteriorAndExteri Assert.Equal((byte)0, surface[0, 0].A); } + /// + /// Proves that a closed subpath reduced to exactly two distinct points (a zero-area, + /// degenerate closed contour that immediately doubles back over the same segment) still + /// renders as a stroked line segment, rather than vanishing entirely because its coincident + /// "outer" and "inner" offset rings would otherwise be forced into opposite winding and + /// cancel under FillRule.NonZero. The expected pixel coverage matches the equivalent + /// open, butt-capped, two-point stroke exactly (see + /// ). + /// + [Fact] + public void PathStroker_Stroke_ClosedTwoPointSubpath_FillsStrokedSegmentAreaNotEmpty() + { + // Arrange: a closed subpath (M ... L ... Z) with only two distinct points + var path = new PathBuilder() + .MoveTo(new Vector2(2, 2)) + .LineTo(new Vector2(6, 2)) + .Close() + .Build(); + var style = new StrokeStyle(2f, cap: LineCap.Butt); + + // Act: rasterize and sample actual pixel coverage, not just outline generation + var surface = RenderStroke(path, style, 8, 5); + + // Assert: coverage matches the equivalent open two-point butt-capped stroke + Assert.Equal((byte)255, surface[2, 1].A); + Assert.Equal((byte)255, surface[5, 2].A); + Assert.Equal((byte)0, surface[1, 1].A); + Assert.Equal((byte)0, surface[6, 1].A); + } + + /// + /// Proves that a dash array whose entries individually are finite but whose summed total + /// pattern length would overflow a naive float32 accumulation does not hang the public + /// entry point, when combined + /// with a negative dash offset. This test intentionally makes no timing assertion: it + /// relies only on xUnit's normal test execution completing to prove there is no infinite + /// loop reachable through the public stroking API. + /// + [Fact] + public void PathStroker_Stroke_OverflowProneDashArrayWithNegativeOffset_CompletesWithoutHanging() + { + // Arrange + var path = new PathBuilder() + .MoveTo(new Vector2(0, 0)) + .LineTo(new Vector2(10, 0)) + .Build(); + var style = new StrokeStyle(2f, dashArray: [float.MaxValue, float.MaxValue], dashOffset: -1f); + + // Act + var stroked = PathStroker.Stroke(path, style); + + // Assert: the call returned (did not hang) with a well-formed result + Assert.NotNull(stroked); + } + /// /// Proves that a sharp corner exceeding the miter limit falls back to bevel geometry. /// diff --git a/test/DemaConsulting.CanvasNet.Tests/Drawing/StrokeOutlinerTests.cs b/test/DemaConsulting.CanvasNet.Tests/Drawing/StrokeOutlinerTests.cs index 7a38c3a81..6654ab806 100644 --- a/test/DemaConsulting.CanvasNet.Tests/Drawing/StrokeOutlinerTests.cs +++ b/test/DemaConsulting.CanvasNet.Tests/Drawing/StrokeOutlinerTests.cs @@ -132,6 +132,50 @@ public void StrokeOutliner_Outline_RoundCapAtTypicalScale_MatchesExpectedSegment Assert.Equal(7, polygon.Count); } + /// + /// Proves that a round join with a small (~45 degree) sweep angle at an extreme stroke + /// half-width (large enough that flattenTolerance / radius underflows float32 + /// precision) still produces a genuinely multi-segment curved outline. Prior to the fix, + /// the underflow fallback's angle-based minimum segment count + /// (ceil(sweepMagnitude / (PI/2))) was exactly 1 for any sweep of at most 90 + /// degrees, which collapsed the arc right back into a single straight chord - the same + /// regression the fallback was supposed to eliminate, just for smaller sweep angles than + /// the previously covered near-180-degree case. + /// + [Fact] + public void StrokeOutliner_Outline_RoundJoinSmallSweepAtExtremeScale_ProducesMultiSegmentCurve() + { + // Arrange: a ~45 degree turn (well under the FallbackSegmentAngle of 90 degrees, so + // fallbackCount alone would be exactly 1 without the Math.Max(2, ...) floor), paired with + // a stroke half-width many orders of magnitude larger than the ~1.19e-7 relative float32 + // precision floor so flattenTolerance / radius underflows to zero for any reasonable + // flattenTolerance. + var points = new List + { + new(0, 0), + new(10, 0), + new(10 + 10 * MathF.Cos(-MathF.PI / 4f), 10 * MathF.Sin(-MathF.PI / 4f)) + }; + const float extremeWidth = 2e13f; + var roundStyle = new StrokeStyle(extremeWidth, join: LineJoin.Round); + var bevelStyle = new StrokeStyle(extremeWidth, join: LineJoin.Bevel); + + // Act + var roundPolygon = Assert.Single(StrokeOutliner.Outline(points, isClosed: false, roundStyle, flattenTolerance: 0.25f)); + var bevelPolygon = Assert.Single(StrokeOutliner.Outline(points, isClosed: false, bevelStyle, flattenTolerance: 0.25f)); + + // Assert: a genuinely curved (multi-segment) round join contributes at least one extra + // vertex beyond the two straight-chord endpoints a bevel join produces at the same + // geometry and scale. A collapsed single-chord round join would instead produce exactly + // the same vertex count as the bevel join. + Assert.True( + roundPolygon.Count > bevelPolygon.Count, + $"Expected the round join ({roundPolygon.Count} vertices) to contribute more vertices " + + $"than the equivalent bevel join ({bevelPolygon.Count} vertices): an equal count " + + "indicates the small-sweep-angle underflow fallback has collapsed back to a single " + + "straight chord."); + } + private static float GetSignedArea(IReadOnlyList points) { var area = 0f; From d4dc912f557df5e3b99ba3113e1c5fd656d9b8d3 Mon Sep 17 00:00:00 2001 From: Malcolm Nixon Date: Mon, 21 Sep 2026 12:49:04 -0400 Subject: [PATCH 04/13] Fix: closed-contour inner ring must use exact offset intersection, not styled join Closed-contour stroking built both the outer (outside) ring and the inner (hole) ring using the caller's requested LineJoin (Miter/Round/ Bevel) at every vertex. The two sides are not symmetric: only the outer side is a stylized convex corner; the inner side is the boundary of the hole left by the union of the two offset strips and must always be the exact offset-edge intersection, regardless of the requested join style. Applying Bevel or Round to the inner side chamfered/rounded away real stroke area at inner corners, producing an incorrect hole shape (e.g. for a stroked closed rectangle). BuildClosedSide and AppendStyledJoin now take an outer/inner distinction so only the outer ring honors StrokeStyle.Join; the inner ring always resolves to the geometrically exact edge intersection (falling back to the un-joined offset points only when the edges are parallel). Added regression tests rasterizing a closed rectangle with Bevel, Round, and Miter joins and comparing rendered pixel coverage at the inner corner against an independently hand-derived exact-intersection expectation. --- .../Drawing/StrokeOutliner.cs | 69 ++++++++++- .../Drawing/PathStrokerTests.cs | 110 ++++++++++++++++++ 2 files changed, 174 insertions(+), 5 deletions(-) diff --git a/src/DemaConsulting.CanvasNet/Drawing/StrokeOutliner.cs b/src/DemaConsulting.CanvasNet/Drawing/StrokeOutliner.cs index d01daa5d3..924c18d4d 100644 --- a/src/DemaConsulting.CanvasNet/Drawing/StrokeOutliner.cs +++ b/src/DemaConsulting.CanvasNet/Drawing/StrokeOutliner.cs @@ -192,6 +192,18 @@ private static List> CreateOpenStrokePolygons( /// /// Produces the outer and inner shell rings for a closed contour. /// + /// + /// The outer and inner offset rings are NOT symmetric for a closed contour: the outer + /// ring is the outside boundary of the stroke band, where every vertex is a convex corner + /// that the caller's requested (Miter/Round/Bevel) legitimately + /// stylizes. The inner ring is the boundary of the hole left by the union of the two + /// offset strips - at that same vertex, the inner side is the geometrically exact + /// intersection of the two offset edges, not a stylized corner. Applying Bevel or Round to + /// the inner side would chamfer/round away real stroke area (or, if the geometry required + /// it, add extraneous area) at every inner corner, producing a hole boundary with the + /// wrong shape. is therefore called once per ring with an + /// explicit outer/inner flag so only the outer ring honors . + /// private static List> CreateClosedStrokePolygons( IReadOnlyList points, StrokeStyle style, @@ -201,8 +213,8 @@ private static List> CreateClosedStrokePolygons( var area = ComputeSignedArea(points); var outerSideSign = area >= 0f ? -1f : +1f; - var outerRing = BuildClosedSide(points, outerSideSign, style, halfWidth, flattenTolerance); - var innerRing = BuildClosedSide(points, -outerSideSign, style, halfWidth, flattenTolerance); + var outerRing = BuildClosedSide(points, outerSideSign, style, halfWidth, flattenTolerance, isOuterSide: true); + var innerRing = BuildClosedSide(points, -outerSideSign, style, halfWidth, flattenTolerance, isOuterSide: false); if (outerRing.Count < 3 || innerRing.Count < 3) { return []; @@ -334,12 +346,24 @@ private static void AppendOpenJoin( /// /// Builds one closed offset ring for a closed contour. /// + /// The flattened, simplified closed-contour vertices. + /// The offset direction (+1/-1) for this ring relative to the normals. + /// The stroke geometry to apply. + /// Half the stroke width. + /// The tolerance used when tessellating round arcs. + /// + /// Whether this ring is the outer (outside boundary) side of the stroke band. When + /// (the inner/hole side), every vertex is forced to the exact + /// offset-edge intersection regardless of - see the remarks + /// on for why the two sides cannot share styling. + /// private static List BuildClosedSide( IReadOnlyList points, float sideSign, StrokeStyle style, float halfWidth, - float flattenTolerance) + float flattenTolerance, + bool isOuterSide) { var frames = BuildSegmentFrames(points, isClosed: true); var ring = new List(points.Count * 2); @@ -365,7 +389,8 @@ private static List BuildClosedSide( sideSign, style, halfWidth, - flattenTolerance); + flattenTolerance, + forceExactIntersection: !isOuterSide); } RemoveTrailingDuplicateOfFirst(ring); @@ -375,6 +400,24 @@ private static List BuildClosedSide( /// /// Appends the requested styled join between two offset segments. /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// When , ignores and always emits + /// the geometrically exact intersection of the two offset edges (falling back to the + /// un-joined offset points only when the edges are parallel and have no intersection). + /// This is required for the inner/hole ring of a closed contour, where the correct corner + /// is always the exact intersection point, never a stylized miter/round/bevel corner - see + /// the remarks on . + /// private static void AppendStyledJoin( List target, Vector2 vertex, @@ -385,11 +428,27 @@ private static void AppendStyledJoin( float sideSign, StrokeStyle style, float halfWidth, - float flattenTolerance) + float flattenTolerance, + bool forceExactIntersection = false) { var previousPoint = vertex + sideSign * previousNormal * halfWidth; var nextPoint = vertex + sideSign * nextNormal * halfWidth; + if (forceExactIntersection) + { + if (TryIntersectLines(previousPoint, previousTangent, nextPoint, nextTangent, out var intersection)) + { + AddPointIfDistinct(target, intersection); + } + else + { + AddPointIfDistinct(target, previousPoint); + AddPointIfDistinct(target, nextPoint); + } + + return; + } + switch (style.Join) { case LineJoin.Round: diff --git a/test/DemaConsulting.CanvasNet.Tests/Drawing/PathStrokerTests.cs b/test/DemaConsulting.CanvasNet.Tests/Drawing/PathStrokerTests.cs index 8e699b239..6a409085a 100644 --- a/test/DemaConsulting.CanvasNet.Tests/Drawing/PathStrokerTests.cs +++ b/test/DemaConsulting.CanvasNet.Tests/Drawing/PathStrokerTests.cs @@ -162,6 +162,116 @@ public void PathStroker_Stroke_ClosedRectangle_FillsRingLeavingInteriorAndExteri Assert.Equal((byte)0, surface[0, 0].A); } + /// + /// Proves that a closed contour's inner (hole) corner is always the geometrically exact + /// offset-edge intersection, never the outer style stylization, + /// using a Bevel join where the two constructions diverge sharply. + /// + /// + /// The rectangle (4,4)-(12,4)-(12,12)-(4,12) stroked with width 4 (half-width 2) produces + /// an exact 4x4 hole at (6,6)-(10,6)-(10,10)-(6,10), and an outer boundary at + /// (2,2)-(14,2)-(14,14)-(2,14). At the (4,4) corner, the two offset edges are the lines + /// x=6 (from the left edge) and y=6 (from the top edge); their exact intersection is + /// (6,6). Pixel [5,5] - the unit square [5,6) x [5,6) - lies entirely at x<6 or y<6 + /// (only the single corner point (6,6) touches x=y=6), so under the exact intersection it + /// is entirely outside the hole and must be fully covered (alpha 255). A Bevel join + /// instead connects the previous/next offset points (6,4) and (4,6) directly with a chord + /// (the line x+y=10): every corner of pixel [5,5] except (5,5) itself has x+y > 10, so + /// a buggy implementation that bevels the inner corner would incorrectly treat nearly all + /// of pixel [5,5] as hole (alpha 0) instead of stroke. Pixel [7,7] sits at the center of + /// the real hole (unaffected by the fix) and pixel [0,0] sits outside the outer boundary, + /// confirming the fix does not remove the hole entirely or expand the stroke outward. + /// + [Fact] + public void PathStroker_Stroke_ClosedRectangleBevelJoin_InnerCornerMatchesExactIntersectionNotBevel() + { + // Arrange + var path = new PathBuilder() + .MoveTo(new Vector2(4, 4)) + .LineTo(new Vector2(12, 4)) + .LineTo(new Vector2(12, 12)) + .LineTo(new Vector2(4, 12)) + .Close() + .Build(); + var style = new StrokeStyle(4f, join: LineJoin.Bevel); + + // Act + var surface = RenderStroke(path, style, 16, 16); + + // Assert: fully covered at the exact-intersection inner corner, and the hole interior and + // exterior remain unfilled + Assert.Equal((byte)255, surface[5, 5].A); + Assert.Equal((byte)0, surface[7, 7].A); + Assert.Equal((byte)0, surface[0, 0].A); + } + + /// + /// Proves that a closed contour's inner (hole) corner is always the geometrically exact + /// offset-edge intersection, never a rounded arc, using a Round join where the two + /// constructions diverge sharply. + /// + /// + /// Same rectangle and exact-intersection reasoning as + /// . + /// A Round join instead sweeps a quarter-circle arc of radius 2 (the half-width) centered + /// on the (4,4) vertex between the offset points (6,4) and (4,6): every corner of pixel + /// [5,5] except (5,5) itself is farther than radius 2 from (4,4) and within the swept + /// 0-90 degree sector, so a buggy implementation that rounds the inner corner would + /// incorrectly treat most of pixel [5,5] as hole (reduced alpha) instead of the fully + /// covered stroke the exact intersection requires. + /// + [Fact] + public void PathStroker_Stroke_ClosedRectangleRoundJoin_InnerCornerMatchesExactIntersectionNotArc() + { + // Arrange + var path = new PathBuilder() + .MoveTo(new Vector2(4, 4)) + .LineTo(new Vector2(12, 4)) + .LineTo(new Vector2(12, 12)) + .LineTo(new Vector2(4, 12)) + .Close() + .Build(); + var style = new StrokeStyle(4f, join: LineJoin.Round); + + // Act + var surface = RenderStroke(path, style, 16, 16); + + // Assert: fully covered at the exact-intersection inner corner, and the hole interior and + // exterior remain unfilled + Assert.Equal((byte)255, surface[5, 5].A); + Assert.Equal((byte)0, surface[7, 7].A); + Assert.Equal((byte)0, surface[0, 0].A); + } + + /// + /// Proves that a Miter join on a closed contour continues to produce the same exact + /// inner-corner coverage as Bevel/Round now do, confirming the outer/inner distinction + /// introduced for Bevel and Round does not regress the Miter path (which already computed + /// an edge intersection on both sides). + /// + [Fact] + public void PathStroker_Stroke_ClosedRectangleMiterJoin_InnerCornerMatchesExactIntersection() + { + // Arrange + var path = new PathBuilder() + .MoveTo(new Vector2(4, 4)) + .LineTo(new Vector2(12, 4)) + .LineTo(new Vector2(12, 12)) + .LineTo(new Vector2(4, 12)) + .Close() + .Build(); + var style = new StrokeStyle(4f, join: LineJoin.Miter); + + // Act + var surface = RenderStroke(path, style, 16, 16); + + // Assert: fully covered at the exact-intersection inner corner, and the hole interior and + // exterior remain unfilled + Assert.Equal((byte)255, surface[5, 5].A); + Assert.Equal((byte)0, surface[7, 7].A); + Assert.Equal((byte)0, surface[0, 0].A); + } + /// /// Proves that a closed subpath reduced to exactly two distinct points (a zero-area, /// degenerate closed contour that immediately doubles back over the same segment) still From ee946cc28ab02ef911fce0b1b49471637ada394d Mon Sep 17 00:00:00 2001 From: Malcolm Nixon Date: Mon, 21 Sep 2026 13:33:18 -0400 Subject: [PATCH 05/13] Fix concave closed-contour stroke joins and 7 other PR review findings 1. StrokeOutliner: fix concave (reflex) closed-contour stroke joins by determining outer/inner side per vertex from the local turn direction (matching the existing open-path logic) instead of a global per-ring flag, which was only correct for convex closed contours. 2. Rewrite the 3 ClosedRectangle*Join_InnerCornerMatchesExactIntersection* tests to assert directly on StrokeOutliner.Outline ring vertices instead of rasterized pixels, since the buggy and correct rectangle geometries rasterize pixel-identically under NonZero fill. Add concave-contour regression tests (ring-vertex and pixel-based) that do discriminate, verified to fail against both prior buggy StrokeOutliner.cs revisions. 3. Update path-stroker.md's closed-side join handling description to match the corrected per-vertex local-turn rule. 4. DashSplitter.IsDashOnAtStart: skip forward through zero-length dash entries at an exact phase boundary (offset == 0) so a pattern beginning with a zero-length 'on' entry correctly starts in the following 'off' entry instead of staying in the zero-length entry. Add a regression test on a zero-length path, verified to fail pre-fix. 5. Investigate the reported StrokeOutliner miter-limit halfWidth/Width denominator: re-derive the SVG miterLength/strokeWidth ratio from first principles and confirm (both mathematically and by reverting the code experimentally) that the existing halfWidth-based ratio already matches the standard 1/sin(theta/2) formula (~1.414 for a right angle) and that switching to the full Width, as literally suggested, would halve the ratio and break existing miter-limit tests. Fix the design doc and the TryCreateMiter XML doc comment, which stated the formula incorrectly, instead of the (already-correct) code. 6. docs/reqstream/canvas-net.yaml: move the visible-geometry stroke tests (closed-rectangle ring, round/square point-stroke marks) out of the PathStrokeNoOp requirement's linked tests and into the general PathStroke requirement; PathStrokeNoOp now only links genuinely no-area/empty cases. 7. docs/reqstream/canvas-net/drawing.yaml: move the DegenerateSubpaths, ClosedContours, and ShellWinding children (and their tests) from under the PathStrokeNoOp parent requirement to the general PathStroke requirement, leaving only EmptyNoOp under PathStrokeNoOp. 8. docs/user_guide/introduction.md: fix Example 10's sampled pixel, which was outside the visible dashed stroke for the documented geometry; replaced with a pixel on the stroke centerline inside a visible dash run, verified against the actual rendered output. --- .../design/canvas-net/drawing/path-stroker.md | 25 ++- docs/reqstream/canvas-net.yaml | 8 +- docs/reqstream/canvas-net/drawing.yaml | 14 +- docs/user_guide/introduction.md | 2 +- .../Drawing/DashSplitter.cs | 14 ++ .../Drawing/StrokeOutliner.cs | 69 ++++--- .../Drawing/DashSplitterTests.cs | 31 +++ .../Drawing/PathStrokerTests.cs | 177 +++++++++++------- .../Drawing/StrokeOutlinerTests.cs | 48 +++++ 9 files changed, 288 insertions(+), 100 deletions(-) diff --git a/docs/design/canvas-net/drawing/path-stroker.md b/docs/design/canvas-net/drawing/path-stroker.md index 664552cc3..d4043ec26 100644 --- a/docs/design/canvas-net/drawing/path-stroker.md +++ b/docs/design/canvas-net/drawing/path-stroker.md @@ -82,8 +82,13 @@ as a brand-new `Path`: - **Closed contours** produce two closed rings (outer and inner) wound in opposite directions so `FillRule.NonZero` fills only the shell between them. - **Miter joins** intersect the two offset lines and then compare the distance from the source - vertex to that intersection against `MiterLimit * Width`. When the ratio exceeds the limit, - the join falls back to a bevel. + vertex to that intersection against `MiterLimit * (Width / 2)`. This single offset line sits + half the stroke width from the source vertex, so this distance is exactly half of the SVG + "miter length" (the full tip-to-tip span across both offset lines), and `Width / 2` is + exactly half the stroke width - the ratio of the two halves equals the full + `miterLength / strokeWidth` SVG ratio (for example, `~1.414` for a right-angle join, matching + the standard `1 / sin(theta / 2)` formula). When the ratio exceeds the limit, the join falls + back to a bevel. - **Round joins and round caps** are tessellated as circular arcs whose sagitta is bounded by `flattenTolerance`, reusing the same tolerance concept already established for curve flattening elsewhere in the library. @@ -101,8 +106,20 @@ instances directly. Every emitted polygon becomes one closed subpath in the resu is the clipped "inside" of the turn and is connected directly between its two offset endpoints, because the visible outline there is the boundary of the union of two segment rectangles rather than the infinite-line intersection of their offsets. -- **Closed-side join handling.** For a closed contour, both the outer and inner rings are genuine - offset curves, so each vertex is handled with the requested join style on that ring. +- **Closed-side join handling.** For a closed contour, the two offset rings are not symmetric, and + which ring is locally the "outside of the turn" at a given vertex is not a fixed, ring-wide + property: for a convex closed contour every vertex agrees, but a concave (reflex) vertex flips + which ring is locally convex there. `StrokeOutliner` therefore resolves each vertex on each ring + independently, from the same local turn-direction sign used for open-path joins: the side that + is locally convex at that vertex receives the caller-selected join style (`Miter`, `Round`, or + `Bevel`), while the side that is locally concave at that vertex is forced to the geometrically + exact intersection of the two offset edges (falling back to the un-joined offset points only + when the edges are parallel and have no intersection), never a stylized corner - stylizing the + concave side would carve away or add stroke area. Because the two rings use opposite offset + signs, exactly one of them is locally convex at any given vertex, so the two treatments are + always assigned to the correct ring even as convexity flips along a concave contour. The two + rings are then wound in opposite directions so `FillRule.NonZero` fills only the shell between + them, regardless of how many vertices on each ring ended up locally reflex. - **Degenerate subpaths.** A single point (or a path collapsed to one effective point after duplicate-vertex simplification) renders as a cap-shaped mark: round creates a full circle, square creates an axis-aligned width-by-width square, and butt creates nothing. diff --git a/docs/reqstream/canvas-net.yaml b/docs/reqstream/canvas-net.yaml index e24268e5b..1cc1eae3a 100644 --- a/docs/reqstream/canvas-net.yaml +++ b/docs/reqstream/canvas-net.yaml @@ -808,6 +808,10 @@ sections: - PathStroker_Stroke_RightAngleCornerRoundJoin_FillsRoundedCorner - PathStroker_Stroke_RightAngleCornerBevelJoin_FillsFlatBeveledCorner - PathStroker_Stroke_DashedLine_FillsOnlyOnSegmentsLeavingGapsUnfilled + - PathStroker_Stroke_ClosedRectangle_FillsRingLeavingInteriorAndExteriorUnfilled + - PathStroker_Stroke_ZeroLengthSubpathRoundCap_FillsCircleOfRadiusHalfWidth + - PathStroker_Stroke_ZeroLengthSubpathSquareCap_FillsSquareOfSideWidth + - PathStroker_Stroke_SinglePointSubpath_MatchesZeroLengthSubpathBehavior - id: CanvasNet-Lib-DrawingPathStrokeNoOp title: >- @@ -820,11 +824,7 @@ sections: children: - CanvasNet-Drawing-PathStrokeNoOp tests: - - PathStroker_Stroke_ClosedRectangle_FillsRingLeavingInteriorAndExteriorUnfilled - - PathStroker_Stroke_ZeroLengthSubpathRoundCap_FillsCircleOfRadiusHalfWidth - - PathStroker_Stroke_ZeroLengthSubpathSquareCap_FillsSquareOfSideWidth - PathStroker_Stroke_ZeroLengthSubpathButtCap_ProducesNoFilledPixels - - PathStroker_Stroke_SinglePointSubpath_MatchesZeroLengthSubpathBehavior - PathStroker_Stroke_EmptyPath_ReturnsEmptyPathNoOp - id: CanvasNet-Lib-DrawingPathStrokeValidation diff --git a/docs/reqstream/canvas-net/drawing.yaml b/docs/reqstream/canvas-net/drawing.yaml index 43253839f..420c04a63 100644 --- a/docs/reqstream/canvas-net/drawing.yaml +++ b/docs/reqstream/canvas-net/drawing.yaml @@ -95,6 +95,9 @@ sections: - CanvasNet-Drawing-PathStroker-StyleValidation - CanvasNet-Drawing-PathStroker-OpenClosedPreservation - CanvasNet-Drawing-PathStroker-DashPhaseSemantics + - CanvasNet-Drawing-PathStroker-DegenerateSubpaths + - CanvasNet-Drawing-PathStroker-ClosedContours + - CanvasNet-Drawing-PathStroker-ShellWinding tests: - PathStroker_Stroke_HorizontalLineButtCap_FillsExactRectangleNoExtension - PathStroker_Stroke_HorizontalLineRoundCap_FillsRectanglePlusSemicircularEnds @@ -103,6 +106,10 @@ sections: - PathStroker_Stroke_RightAngleCornerRoundJoin_FillsRoundedCorner - PathStroker_Stroke_RightAngleCornerBevelJoin_FillsFlatBeveledCorner - PathStroker_Stroke_DashedLine_FillsOnlyOnSegmentsLeavingGapsUnfilled + - PathStroker_Stroke_ClosedRectangle_FillsRingLeavingInteriorAndExteriorUnfilled + - PathStroker_Stroke_ZeroLengthSubpathRoundCap_FillsCircleOfRadiusHalfWidth + - PathStroker_Stroke_ZeroLengthSubpathSquareCap_FillsSquareOfSideWidth + - PathStroker_Stroke_SinglePointSubpath_MatchesZeroLengthSubpathBehavior - id: CanvasNet-Drawing-PathStrokeNoOp title: >- @@ -114,16 +121,9 @@ sections: stroke result must be a cheap, well-defined no-op rather than a special case callers must detect themselves. children: - - CanvasNet-Drawing-PathStroker-DegenerateSubpaths - - CanvasNet-Drawing-PathStroker-ClosedContours - CanvasNet-Drawing-PathStroker-EmptyNoOp - - CanvasNet-Drawing-PathStroker-ShellWinding tests: - - PathStroker_Stroke_ClosedRectangle_FillsRingLeavingInteriorAndExteriorUnfilled - - PathStroker_Stroke_ZeroLengthSubpathRoundCap_FillsCircleOfRadiusHalfWidth - - PathStroker_Stroke_ZeroLengthSubpathSquareCap_FillsSquareOfSideWidth - PathStroker_Stroke_ZeroLengthSubpathButtCap_ProducesNoFilledPixels - - PathStroker_Stroke_SinglePointSubpath_MatchesZeroLengthSubpathBehavior - PathStroker_Stroke_EmptyPath_ReturnsEmptyPathNoOp - id: CanvasNet-Drawing-PathStrokeValidation diff --git a/docs/user_guide/introduction.md b/docs/user_guide/introduction.md index eaea32c09..bf8131ca7 100644 --- a/docs/user_guide/introduction.md +++ b/docs/user_guide/introduction.md @@ -990,7 +990,7 @@ var style = new StrokeStyle( var strokedOutline = PathStroker.Stroke(polyline, style); PathFiller.Fill(canvas, strokedOutline, new Rgba32(255, 128, 0, 255)); -Console.WriteLine(canvas[32, 24].A); // Output: 255 (well inside one visible dash run) +Console.WriteLine(canvas[20, 32].A); // Output: 255 (on the centerline, inside one visible dash run) ``` # References diff --git a/src/DemaConsulting.CanvasNet/Drawing/DashSplitter.cs b/src/DemaConsulting.CanvasNet/Drawing/DashSplitter.cs index 37700a7a2..7d6ccf9a4 100644 --- a/src/DemaConsulting.CanvasNet/Drawing/DashSplitter.cs +++ b/src/DemaConsulting.CanvasNet/Drawing/DashSplitter.cs @@ -219,6 +219,15 @@ private static float[] BuildCumulativeLengths(IReadOnlyList points, boo /// /// Determines whether the dash phase begins in an "on" interval. /// + /// + /// A zero-length dash entry occupies no visible extent along the path, so landing exactly + /// at its start - whether that is the initial phase ( + /// normalizes to exactly zero, which skips the traversal loop below entirely) or a phase + /// reached after exactly consuming every preceding entry - means the phase has already + /// moved past it. The trailing loop skips forward through any such zero-length entries so + /// the returned index always identifies the entry actually in effect at this phase, rather + /// than a zero-length entry the phase is only nominally "at." + /// private static bool IsDashOnAtStart(IReadOnlyList pattern, float dashOffset) { var patternLength = GetPatternLength(pattern); @@ -236,6 +245,11 @@ private static bool IsDashOnAtStart(IReadOnlyList pattern, float dashOffs index = (index + 1) % pattern.Count; } + while (offset == 0d && pattern[index] == 0f) + { + index = (index + 1) % pattern.Count; + } + return index % 2 == 0; } diff --git a/src/DemaConsulting.CanvasNet/Drawing/StrokeOutliner.cs b/src/DemaConsulting.CanvasNet/Drawing/StrokeOutliner.cs index 924c18d4d..532e010fe 100644 --- a/src/DemaConsulting.CanvasNet/Drawing/StrokeOutliner.cs +++ b/src/DemaConsulting.CanvasNet/Drawing/StrokeOutliner.cs @@ -193,16 +193,22 @@ private static List> CreateOpenStrokePolygons( /// Produces the outer and inner shell rings for a closed contour. /// /// - /// The outer and inner offset rings are NOT symmetric for a closed contour: the outer - /// ring is the outside boundary of the stroke band, where every vertex is a convex corner - /// that the caller's requested (Miter/Round/Bevel) legitimately - /// stylizes. The inner ring is the boundary of the hole left by the union of the two - /// offset strips - at that same vertex, the inner side is the geometrically exact - /// intersection of the two offset edges, not a stylized corner. Applying Bevel or Round to - /// the inner side would chamfer/round away real stroke area (or, if the geometry required - /// it, add extraneous area) at every inner corner, producing a hole boundary with the - /// wrong shape. is therefore called once per ring with an - /// explicit outer/inner flag so only the outer ring honors . + /// A closed contour's two offset rings are NOT symmetric, but which ring is "outer" vs + /// "inner" at a given vertex is a LOCAL property, not a fixed global one: for a convex + /// closed contour every vertex has the same ring as the convex (outer) side, but for a + /// concave (reflex) contour the locally convex side can flip between the two rings from + /// vertex to vertex. Treating one ring as globally "outer" (as the open-path code already + /// avoids doing, see ) would apply the caller's requested + /// (Miter/Round/Bevel) to a locally concave vertex - chamfering or + /// rounding away real stroke area, or adding extraneous area - and would force the exact + /// offset-edge intersection onto a locally convex vertex, losing the requested join style + /// there. therefore decides, independently at every vertex + /// and from the same local turn-direction sign used by the open-path join logic, whether + /// that vertex on that ring is the locally convex side (style the join) or the locally + /// concave side (force the exact intersection). Because the two rings use opposite side + /// signs, exactly one of them is locally convex at any given vertex, so the styled join and + /// the exact intersection are always applied to the correct ring at that vertex, even when + /// convexity flips along the contour. /// private static List> CreateClosedStrokePolygons( IReadOnlyList points, @@ -213,13 +219,18 @@ private static List> CreateClosedStrokePolygons( var area = ComputeSignedArea(points); var outerSideSign = area >= 0f ? -1f : +1f; - var outerRing = BuildClosedSide(points, outerSideSign, style, halfWidth, flattenTolerance, isOuterSide: true); - var innerRing = BuildClosedSide(points, -outerSideSign, style, halfWidth, flattenTolerance, isOuterSide: false); + var outerRing = BuildClosedSide(points, outerSideSign, style, halfWidth, flattenTolerance); + var innerRing = BuildClosedSide(points, -outerSideSign, style, halfWidth, flattenTolerance); if (outerRing.Count < 3 || innerRing.Count < 3) { return []; } + // Regardless of how many vertices were locally reflex on each ring, the two rings must + // still end up with opposite winding for FillRule.NonZero to render the band between them + // (rather than the solid disc of one ring or the empty complement) - flip the inner ring + // if the constructed rings happen to share the same winding sign. + if (ComputeSignedArea(outerRing) * ComputeSignedArea(innerRing) > 0f) { innerRing.Reverse(); @@ -351,19 +362,23 @@ private static void AppendOpenJoin( /// The stroke geometry to apply. /// Half the stroke width. /// The tolerance used when tessellating round arcs. - /// - /// Whether this ring is the outer (outside boundary) side of the stroke band. When - /// (the inner/hole side), every vertex is forced to the exact - /// offset-edge intersection regardless of - see the remarks - /// on for why the two sides cannot share styling. - /// + /// + /// Unlike the open-path join logic in - which can freely emit + /// the two un-joined offset points on the locally concave side because that side remains + /// part of the same single ring - a closed contour's two sides are built as two separate, + /// independent rings that are later combined as a NonZero-fill outer shell and hole. Each + /// vertex is therefore resolved with the same local turn-direction test used by + /// (is this side convex or concave AT THIS VERTEX, not + /// globally for the ring) to decide whether to honor (the + /// locally convex side) or force the exact offset-edge intersection (the locally concave + /// side, where a stylized corner would carve away or add stroke area). + /// private static List BuildClosedSide( IReadOnlyList points, float sideSign, StrokeStyle style, float halfWidth, - float flattenTolerance, - bool isOuterSide) + float flattenTolerance) { var frames = BuildSegmentFrames(points, isClosed: true); var ring = new List(points.Count * 2); @@ -379,6 +394,7 @@ private static List BuildClosedSide( continue; } + var isConvexOnThisSide = turn * sideSign < 0f; AppendStyledJoin( ring, points[i], @@ -390,7 +406,7 @@ private static List BuildClosedSide( style, halfWidth, flattenTolerance, - forceExactIntersection: !isOuterSide); + forceExactIntersection: !isConvexOnThisSide); } RemoveTrailingDuplicateOfFirst(ring); @@ -487,6 +503,17 @@ private static void AppendStyledJoin( /// /// Computes the miter-join vertex and validates it against the configured limit. /// + /// + /// -to-intersection distance is measured on a single offset line + /// that already sits half of away from the source vertex, + /// so it is exactly half of the SVG "miter length" (the full tip-to-tip span across both + /// offset lines). Dividing by strokeWidth / 2 therefore reproduces the standard SVG + /// miterLength / strokeWidth ratio (for example, ~1.414 for a right-angle + /// join) without needing to materialize the opposite offset line's mirrored intersection + /// point. Dividing by the full instead would halve the + /// computed ratio and silently make every value twice + /// as permissive as the documented SVG-style contract. + /// private static bool TryCreateMiter( Vector2 vertex, Vector2 previousPoint, diff --git a/test/DemaConsulting.CanvasNet.Tests/Drawing/DashSplitterTests.cs b/test/DemaConsulting.CanvasNet.Tests/Drawing/DashSplitterTests.cs index f50cc9c68..f95101425 100644 --- a/test/DemaConsulting.CanvasNet.Tests/Drawing/DashSplitterTests.cs +++ b/test/DemaConsulting.CanvasNet.Tests/Drawing/DashSplitterTests.cs @@ -149,4 +149,35 @@ public void DashSplitter_Split_AllZeroDashArray_TreatedAsSolid() // Assert Assert.Equal(points, Assert.Single(segments).Points); } + + /// + /// Proves that a dash pattern beginning with a zero-length "on" entry, evaluated on a + /// zero-length path, correctly starts in the following "off" entry rather than staying in + /// the zero-length "on" entry. + /// + /// + /// With dash pattern [0f, 2f] (a zero-length "on" entry followed by a 2-length + /// "off" entry) and the default zero dash offset, the phase-traversal loop in + /// IsDashOnAtStart normalizes to an offset of exactly zero, which - prior to the + /// fix - skipped the traversal loop entirely and left the phase index at 0 (the "on" + /// entry), even though a zero-length "on" entry has no visible extent and phase zero has + /// therefore already moved into the following "off" entry. A zero-length path (here, a + /// single point, which collapses to the edgeCount <= 0 special case in + /// Split) makes this phase-only decision the entire result: the path is either + /// emitted whole (if the phase starts "on") or produces no segments at all (if "off"). + /// The correct "off" phase must therefore produce zero segments. + /// + [Fact] + public void DashSplitter_Split_ZeroLengthLeadingDashEntryOnZeroLengthPath_StartsInFollowingOffEntry() + { + // Arrange: a single-point (zero-length) open subpath + var points = new List { new(2, 2) }; + + // Act + var segments = DashSplitter.Split(points, isClosed: false, dashArray: [0f, 2f], dashOffset: 0f); + + // Assert: the phase starts in the 2-length "off" entry following the zero-length "on" + // entry, so no segments are emitted + Assert.Empty(segments); + } } diff --git a/test/DemaConsulting.CanvasNet.Tests/Drawing/PathStrokerTests.cs b/test/DemaConsulting.CanvasNet.Tests/Drawing/PathStrokerTests.cs index 6a409085a..1c77f48a9 100644 --- a/test/DemaConsulting.CanvasNet.Tests/Drawing/PathStrokerTests.cs +++ b/test/DemaConsulting.CanvasNet.Tests/Drawing/PathStrokerTests.cs @@ -4,6 +4,8 @@ using DemaConsulting.CanvasNet.Geometry; using Path = DemaConsulting.CanvasNet.Geometry.Path; +// cspell:ignore Outliner unstroked + namespace DemaConsulting.CanvasNet.Tests.Drawing; /// @@ -168,41 +170,34 @@ public void PathStroker_Stroke_ClosedRectangle_FillsRingLeavingInteriorAndExteri /// using a Bevel join where the two constructions diverge sharply. /// /// - /// The rectangle (4,4)-(12,4)-(12,12)-(4,12) stroked with width 4 (half-width 2) produces - /// an exact 4x4 hole at (6,6)-(10,6)-(10,10)-(6,10), and an outer boundary at - /// (2,2)-(14,2)-(14,14)-(2,14). At the (4,4) corner, the two offset edges are the lines - /// x=6 (from the left edge) and y=6 (from the top edge); their exact intersection is - /// (6,6). Pixel [5,5] - the unit square [5,6) x [5,6) - lies entirely at x<6 or y<6 - /// (only the single corner point (6,6) touches x=y=6), so under the exact intersection it - /// is entirely outside the hole and must be fully covered (alpha 255). A Bevel join - /// instead connects the previous/next offset points (6,4) and (4,6) directly with a chord - /// (the line x+y=10): every corner of pixel [5,5] except (5,5) itself has x+y > 10, so - /// a buggy implementation that bevels the inner corner would incorrectly treat nearly all - /// of pixel [5,5] as hole (alpha 0) instead of stroke. Pixel [7,7] sits at the center of - /// the real hole (unaffected by the fix) and pixel [0,0] sits outside the outer boundary, - /// confirming the fix does not remove the hole entirely or expand the stroke outward. + /// The rectangle (4,4)-(12,4)-(12,12)-(4,12) stroked with width 4 (half-width 2) must + /// produce an exact 4x4 hole ring at (6,6)-(10,6)-(10,10)-(6,10). This asserts directly on + /// the polygon ring vertices produced by the internal + /// API rather than sampling rasterized pixels: for this convex rectangle, a buggy + /// implementation that instead bevels the inner corner produces the self-intersecting + /// eight-vertex ring (6,12)(4,10)(12,10)(10,12)(10,4)(12,6)(4,6)(6,4), which happens to + /// rasterize to the exact same pixel coverage as the correct four-vertex ring under + /// FillRule.NonZero (the extra self-overlapping "wings" cancel out) - so pixel sampling at + /// any coordinate cannot actually distinguish correct from buggy geometry here, while + /// asserting the exact ring vertex set does. /// [Fact] public void PathStroker_Stroke_ClosedRectangleBevelJoin_InnerCornerMatchesExactIntersectionNotBevel() { // Arrange - var path = new PathBuilder() - .MoveTo(new Vector2(4, 4)) - .LineTo(new Vector2(12, 4)) - .LineTo(new Vector2(12, 12)) - .LineTo(new Vector2(4, 12)) - .Close() - .Build(); + var points = new List { new(4, 4), new(12, 4), new(12, 12), new(4, 12) }; var style = new StrokeStyle(4f, join: LineJoin.Bevel); // Act - var surface = RenderStroke(path, style, 16, 16); - - // Assert: fully covered at the exact-intersection inner corner, and the hole interior and - // exterior remain unfilled - Assert.Equal((byte)255, surface[5, 5].A); - Assert.Equal((byte)0, surface[7, 7].A); - Assert.Equal((byte)0, surface[0, 0].A); + var polygons = StrokeOutliner.Outline(points, isClosed: true, style, flattenTolerance: 0.25f); + + // Assert: the ring touching the exact intersection point (6,6) is precisely the 4-vertex + // square hole, not an 8-vertex self-intersecting beveled ring + var innerRing = FindRingContaining(polygons, new Vector2(6, 6)); + Assert.Equal(4, innerRing.Count); + Assert.Contains(new Vector2(10, 6), innerRing); + Assert.Contains(new Vector2(10, 10), innerRing); + Assert.Contains(new Vector2(6, 10), innerRing); } /// @@ -211,65 +206,121 @@ public void PathStroker_Stroke_ClosedRectangleBevelJoin_InnerCornerMatchesExactI /// constructions diverge sharply. /// /// - /// Same rectangle and exact-intersection reasoning as - /// . - /// A Round join instead sweeps a quarter-circle arc of radius 2 (the half-width) centered - /// on the (4,4) vertex between the offset points (6,4) and (4,6): every corner of pixel - /// [5,5] except (5,5) itself is farther than radius 2 from (4,4) and within the swept - /// 0-90 degree sector, so a buggy implementation that rounds the inner corner would - /// incorrectly treat most of pixel [5,5] as hole (reduced alpha) instead of the fully - /// covered stroke the exact intersection requires. + /// Same rectangle and ring-vertex reasoning as + /// : + /// a buggy implementation that rounds the inner corner instead of forcing the exact + /// intersection would tessellate an arc at every inner corner, growing the inner ring well + /// past 4 vertices even though (as with Bevel) the rasterized pixel coverage of that buggy + /// ring happens to coincide with the correct ring's coverage for this convex rectangle. /// [Fact] public void PathStroker_Stroke_ClosedRectangleRoundJoin_InnerCornerMatchesExactIntersectionNotArc() { // Arrange - var path = new PathBuilder() - .MoveTo(new Vector2(4, 4)) - .LineTo(new Vector2(12, 4)) - .LineTo(new Vector2(12, 12)) - .LineTo(new Vector2(4, 12)) - .Close() - .Build(); + var points = new List { new(4, 4), new(12, 4), new(12, 12), new(4, 12) }; var style = new StrokeStyle(4f, join: LineJoin.Round); // Act - var surface = RenderStroke(path, style, 16, 16); - - // Assert: fully covered at the exact-intersection inner corner, and the hole interior and - // exterior remain unfilled - Assert.Equal((byte)255, surface[5, 5].A); - Assert.Equal((byte)0, surface[7, 7].A); - Assert.Equal((byte)0, surface[0, 0].A); + var polygons = StrokeOutliner.Outline(points, isClosed: true, style, flattenTolerance: 0.25f); + + // Assert: the ring touching the exact intersection point (6,6) is precisely the 4-vertex + // square hole, not a tessellated rounded-corner ring + var innerRing = FindRingContaining(polygons, new Vector2(6, 6)); + Assert.Equal(4, innerRing.Count); + Assert.Contains(new Vector2(10, 6), innerRing); + Assert.Contains(new Vector2(10, 10), innerRing); + Assert.Contains(new Vector2(6, 10), innerRing); } /// /// Proves that a Miter join on a closed contour continues to produce the same exact - /// inner-corner coverage as Bevel/Round now do, confirming the outer/inner distinction - /// introduced for Bevel and Round does not regress the Miter path (which already computed - /// an edge intersection on both sides). + /// inner-corner ring as Bevel/Round now do, confirming the local-turn-based outer/inner + /// distinction does not regress the Miter path (which already computed an edge + /// intersection on both sides). /// [Fact] public void PathStroker_Stroke_ClosedRectangleMiterJoin_InnerCornerMatchesExactIntersection() + { + // Arrange + var points = new List { new(4, 4), new(12, 4), new(12, 12), new(4, 12) }; + var style = new StrokeStyle(4f, join: LineJoin.Miter); + + // Act + var polygons = StrokeOutliner.Outline(points, isClosed: true, style, flattenTolerance: 0.25f); + + // Assert: the ring touching the exact intersection point (6,6) is precisely the 4-vertex + // square hole + var innerRing = FindRingContaining(polygons, new Vector2(6, 6)); + Assert.Equal(4, innerRing.Count); + Assert.Contains(new Vector2(10, 6), innerRing); + Assert.Contains(new Vector2(10, 10), innerRing); + Assert.Contains(new Vector2(6, 10), innerRing); + } + + /// + /// Proves that a CONCAVE (reflex-vertex) closed contour resolves the styled join versus + /// the exact offset-edge intersection independently at each vertex, from the LOCAL turn + /// direction there, rather than from a single ring-wide outer/inner assignment. + /// + /// + /// The L-shaped hexagon (0,0)-(6,0)-(6,3)-(3,3)-(3,6)-(0,6) has five ordinary convex + /// vertices and exactly one reflex (concave) vertex at (3,3), so which of the two offset + /// rings is locally convex there flips relative to every other vertex. Stroked with width + /// 2 (half-width 1) and a Bevel join, pixel [2,2] sits just inside the reflex vertex's + /// inner corner: under the corrected local-turn logic, the ring that is locally convex at + /// (3,3) is styled with a Bevel chord between (1,5) and (2,5) [a different ring than the + /// one styled at every other, convex, vertex], leaving [2,2] half-covered (alpha 128) by + /// that diagonal chord. A global (pre-fix) outer/inner assignment gets this backwards - + /// it bevels the wrong ring at (3,3) and forces the other ring to the exact intersection + /// point (2,2) - leaving pixel [2,2] fully covered (alpha 255) instead. Pixel [5,1] near + /// the ordinary convex corner (6,0)-(6,3) is unaffected by the bug either way, confirming + /// the fix does not disturb correct convex-vertex joins, and pixel [8,8] confirms the + /// stroke does not spuriously extend into the contour's unstroked exterior. + /// + [Fact] + public void PathStroker_Stroke_ConcaveClosedContourBevelJoin_AppliesJoinsByLocalVertexConvexity() { // Arrange var path = new PathBuilder() - .MoveTo(new Vector2(4, 4)) - .LineTo(new Vector2(12, 4)) - .LineTo(new Vector2(12, 12)) - .LineTo(new Vector2(4, 12)) + .MoveTo(new Vector2(0, 0)) + .LineTo(new Vector2(6, 0)) + .LineTo(new Vector2(6, 3)) + .LineTo(new Vector2(3, 3)) + .LineTo(new Vector2(3, 6)) + .LineTo(new Vector2(0, 6)) .Close() .Build(); - var style = new StrokeStyle(4f, join: LineJoin.Miter); + var style = new StrokeStyle(2f, join: LineJoin.Bevel); // Act - var surface = RenderStroke(path, style, 16, 16); + var surface = RenderStroke(path, style, 10, 10); - // Assert: fully covered at the exact-intersection inner corner, and the hole interior and - // exterior remain unfilled - Assert.Equal((byte)255, surface[5, 5].A); - Assert.Equal((byte)0, surface[7, 7].A); - Assert.Equal((byte)0, surface[0, 0].A); + // Assert + Assert.Equal((byte)128, surface[2, 2].A); + Assert.Equal((byte)255, surface[5, 1].A); + Assert.Equal((byte)0, surface[8, 8].A); + } + + /// + /// Finds the single polygon ring produced by that + /// contains the given vertex, failing the test if zero or more than one ring qualifies. + /// + private static List FindRingContaining(List> polygons, Vector2 vertex) + { + List? found = null; + foreach (var polygon in polygons) + { + if (!polygon.Contains(vertex)) + { + continue; + } + + Assert.Null(found); + found = polygon; + } + + Assert.NotNull(found); + return found; } /// diff --git a/test/DemaConsulting.CanvasNet.Tests/Drawing/StrokeOutlinerTests.cs b/test/DemaConsulting.CanvasNet.Tests/Drawing/StrokeOutlinerTests.cs index 6654ab806..7f31d2d89 100644 --- a/test/DemaConsulting.CanvasNet.Tests/Drawing/StrokeOutlinerTests.cs +++ b/test/DemaConsulting.CanvasNet.Tests/Drawing/StrokeOutlinerTests.cs @@ -176,6 +176,54 @@ public void StrokeOutliner_Outline_RoundJoinSmallSweepAtExtremeScale_ProducesMul "straight chord."); } + /// + /// Proves that a CONCAVE (reflex-vertex) closed contour resolves, independently at each + /// vertex, which of the two offset rings gets the styled and which + /// gets the exact offset-edge intersection - from the LOCAL turn direction at that vertex, + /// not from a single ring-wide outer/inner assignment. + /// + /// + /// The L-shaped hexagon (0,0)-(6,0)-(6,3)-(3,3)-(3,6)-(0,6) has five ordinary convex + /// vertices and exactly one reflex (concave) vertex at (3,3). At every convex vertex, ring + /// A carries the styled Bevel join and ring B carries the exact intersection point; at the + /// one reflex vertex, this flips - ring A must instead carry the exact intersection point + /// (4,4), and ring B must instead carry the styled Bevel join's two offset points, (1,5) + /// and (2,5). A global (pre-fix) outer/inner assignment gets exactly this vertex backwards: + /// it would emit the Bevel chord (3,4)/(4,3) on ring A and the exact intersection (2,2) on + /// ring B instead. + /// + [Fact] + public void StrokeOutliner_Outline_ConcaveClosedContourBevelJoin_ResolvesJoinPerVertexFromLocalTurn() + { + // Arrange + var points = new List + { + new(0, 0), + new(6, 0), + new(6, 3), + new(3, 3), + new(3, 6), + new(0, 6) + }; + var style = new StrokeStyle(2f, join: LineJoin.Bevel); + + // Act + var polygons = StrokeOutliner.Outline(points, isClosed: true, style, flattenTolerance: 0.25f); + + // Assert + Assert.Equal(2, polygons.Count); + var ringWithExactReflexIntersection = polygons[0]; + var ringWithStyledReflexJoin = polygons[1]; + + Assert.Contains(new Vector2(4, 4), ringWithExactReflexIntersection); + Assert.DoesNotContain(new Vector2(3, 4), ringWithExactReflexIntersection); + Assert.DoesNotContain(new Vector2(4, 3), ringWithExactReflexIntersection); + + Assert.Contains(new Vector2(1, 5), ringWithStyledReflexJoin); + Assert.Contains(new Vector2(2, 5), ringWithStyledReflexJoin); + Assert.DoesNotContain(new Vector2(2, 2), ringWithStyledReflexJoin); + } + private static float GetSignedArea(IReadOnlyList points) { var area = 0f; From 92427f81cc3b37f98ca4cad51751805c9173ea7f Mon Sep 17 00:00:00 2001 From: Malcolm Nixon Date: Mon, 21 Sep 2026 14:29:27 -0400 Subject: [PATCH 06/13] Fix catastrophic cancellation in dash-offset phase and generalize degenerate closed-contour detection to collinear contours Round 3 fixes for two automated-review findings plus a broader audit pass: DashSplitter.cs: - A small negative dashOffset against an astronomically large dash pattern (e.g. [float.MaxValue, float.MaxValue] with dashOffset -1) was silently discarded when normalizing into [0, patternLength) via 'normalized += patternLength' in double: adding a tiny residual to a ~1e38 magnitude modulus rounds straight back to the modulus, landing the phase at the wrong (first on) entry instead of the final unit of the preceding off entry. - Replaced the lossy normalize-then-walk-forward approach with a LocatePhase dispatcher that resolves the offset via the exact % remainder (never lossy) and then walks either forward (non-negative remainder) or backward from the end of the pattern (negative remainder). Both directions only ever compare/subtract against individual finite dash entries, never the huge total pattern length, so small offsets are never lost regardless of sign or pattern magnitude. - Added two regression tests asserting CORRECT phase/geometry output (not just completion) for a symmetric and an asymmetric extreme- magnitude-plus-small-negative-offset combination. StrokeOutliner.cs: - Generalized the degenerate-closed-contour special case from 'exactly two distinct points' to 'fewer than three distinct points, or any number of distinct points that are all collinear' via new IsDegenerateClosedContour/AreAllPointsCollinear helpers. A 3+ point closed contour that traces back and forth along one line is just as zero-area as the two-point case and was previously falling through to CreateClosedStrokePolygons, producing two coincident-band, opposite-winding rings that FillRule.NonZero cancels to nothing. - Added the same degenerate-contour guard as a defense-in-depth check at the top of CreateClosedStrokePolygons itself, so the method can never construct a cancelling ring pair even if called directly. - Added regression tests: a 3-point collinear closed contour and a collinear closed contour with a duplicate leading point, both at the StrokeOutliner unit level and the PathStroker pixel-rendering level. Broader audit (no further genuine issues found): - StrokeStyle's constructor already rejects non-finite Width, MiterLimit, DashOffset, and dash-array entries, so NaN/Infinity cannot reach StrokeOutliner or DashSplitter through the public API. - TryIntersectLines/TryCreateMiter already guard near-zero denominators and non-finite miter ratios from earlier rounds. - CreateClosedStrokePolygons was the only closed-contour ring construction call site; the new guard now covers it directly as well as its caller in Outline(). --- .../Drawing/DashSplitter.cs | 158 ++++++++++++------ .../Drawing/StrokeOutliner.cs | 95 ++++++++++- .../Drawing/DashSplitterTests.cs | 61 +++++++ .../Drawing/PathStrokerTests.cs | 30 ++++ .../Drawing/StrokeOutlinerTests.cs | 60 +++++++ 5 files changed, 340 insertions(+), 64 deletions(-) diff --git a/src/DemaConsulting.CanvasNet/Drawing/DashSplitter.cs b/src/DemaConsulting.CanvasNet/Drawing/DashSplitter.cs index 7d6ccf9a4..fa8940e72 100644 --- a/src/DemaConsulting.CanvasNet/Drawing/DashSplitter.cs +++ b/src/DemaConsulting.CanvasNet/Drawing/DashSplitter.cs @@ -181,7 +181,7 @@ private static float[] NormalizeDashArray(IReadOnlyList dashArray) /// individually finite (enforced by 's constructor validation), /// but a legal pattern such as [float.MaxValue, float.MaxValue] would still overflow /// a running sum to +Infinity. An infinite pattern length - /// then breaks phase normalization () and can turn the + /// then breaks phase normalization () and can turn the /// phase-traversal loops in and /// into an infinite loop, because subtracting any finite dash entry from /// float.PositiveInfinity never reduces it. Double has ample headroom for the sum of @@ -219,19 +219,52 @@ private static float[] BuildCumulativeLengths(IReadOnlyList points, boo /// /// Determines whether the dash phase begins in an "on" interval. /// + private static bool IsDashOnAtStart(IReadOnlyList pattern, float dashOffset) + { + var patternLength = GetPatternLength(pattern); + var (index, _) = LocatePhase(pattern, dashOffset, patternLength); + return index % 2 == 0; + } + + /// + /// Locates the dash entry containing the phase at , and how + /// much of that entry remains (in the forward-traversal direction) from that phase. + /// + /// + /// A signed offset is resolved via the exact % remainder against + /// (never a lossy addition of the offset to the modulus - + /// see the catastrophic-cancellation note on ), then + /// dispatched to a forward walk (from the start of the pattern) for a non-negative + /// remainder or a backward walk (from the end of the pattern) for a negative one. Both + /// walks only ever compare the residual distance against individual, finite dash entries - + /// never against the (potentially astronomically large) total pattern length - so a tiny + /// offset is never lost against a huge pattern magnitude in either direction. + /// + private static (int Index, float RemainingInDash) LocatePhase( + IReadOnlyList pattern, + float dashOffset, + double patternLength) + { + var offset = dashOffset % patternLength; + return offset >= 0d + ? LocatePhaseForward(pattern, offset) + : LocatePhaseBackward(pattern, -offset); + } + + /// + /// Walks forward from the start of the pattern to locate a non-negative phase offset. + /// /// /// A zero-length dash entry occupies no visible extent along the path, so landing exactly - /// at its start - whether that is the initial phase ( - /// normalizes to exactly zero, which skips the traversal loop below entirely) or a phase - /// reached after exactly consuming every preceding entry - means the phase has already - /// moved past it. The trailing loop skips forward through any such zero-length entries so - /// the returned index always identifies the entry actually in effect at this phase, rather - /// than a zero-length entry the phase is only nominally "at." + /// at its start - whether that is the initial phase ( is exactly + /// zero, which skips the traversal loop below entirely) or a phase reached after exactly + /// consuming every preceding entry - means the phase has already moved past it. The + /// trailing loop skips forward through any such zero-length entries so the returned index + /// always identifies the entry actually in effect at this phase, rather than a + /// zero-length entry the phase is only nominally "at." /// - private static bool IsDashOnAtStart(IReadOnlyList pattern, float dashOffset) + private static (int Index, float RemainingInDash) LocatePhaseForward(IReadOnlyList pattern, double offset) { - var patternLength = GetPatternLength(pattern); - var offset = NormalizeModulo(dashOffset, patternLength); var index = 0; while (offset > 0d) { @@ -250,46 +283,82 @@ private static bool IsDashOnAtStart(IReadOnlyList pattern, float dashOffs index = (index + 1) % pattern.Count; } - return index % 2 == 0; + // By the loop invariant above, offset is now strictly less than pattern[index] (a finite + // float32 entry), so the remainder is safe to narrow back to float without any risk of + // the overflow this two-way split exists to avoid. + var remaining = (float)(pattern[index] - offset); + return (index, remaining < 0f ? 0f : remaining); } /// - /// Produces the path-length intervals where the dash pattern is "on". + /// Walks backward from the end of the pattern to locate a negative phase offset. /// - private static List<(float Start, float End)> BuildOnIntervals( + /// + /// A negative dashOffset paired with an astronomically large pattern length (e.g. + /// two entries) cannot be resolved by normalizing into + /// [0, patternLength) via normalized += patternLength: double has roughly 16 + /// significant decimal digits, so adding a small residual (say, -1) to a ~1e38 + /// magnitude modulus rounds straight back to the modulus itself, silently discarding the + /// offset and landing the phase at the wrong (first "on") entry instead of the final unit + /// of the preceding "off" entry. Walking backward from the last pattern entry avoids this + /// entirely: (the offset's magnitude) is only ever + /// compared against and subtracted from individual dash entries - never added to or + /// subtracted from the huge total pattern length - so a small negative offset against an + /// enormous pattern remains exactly representable throughout. + /// + private static (int Index, float RemainingInDash) LocatePhaseBackward( IReadOnlyList pattern, - float dashOffset, - float totalLength, - bool isClosed, - out bool encounteredPositiveOffSpan) + double distanceFromWrap) { - encounteredPositiveOffSpan = false; - var intervals = new List<(float Start, float End)>(); - var patternLength = GetPatternLength(pattern); - var offset = NormalizeModulo(dashOffset, patternLength); - - var dashIndex = 0; - while (offset > 0d) + var index = pattern.Count - 1; + while (distanceFromWrap > 0d) { - var length = pattern[dashIndex]; - if (length > 0f && offset < length) + var length = pattern[index]; + if (length > 0f && distanceFromWrap <= length) { break; } - offset -= length; - dashIndex = (dashIndex + 1) % pattern.Count; + distanceFromWrap -= length; + index = (index - 1 + pattern.Count) % pattern.Count; } - // By the loop invariant above, offset is now strictly less than pattern[dashIndex] (a - // finite float32 entry), so the remainder is safe to narrow back to float without any - // risk of the overflow this method exists to avoid. - var remainingInDash = (float)(pattern[dashIndex] - offset); - if (remainingInDash < 0f) + if (distanceFromWrap <= 0d) { - remainingInDash = 0f; + // Landed exactly back on the wrap point (the start of the pattern); mirror the + // forward walk's zero-skip so a leading zero-length "on" entry is not mistaken for + // the active entry. + index = 0; + while (pattern[index] == 0f) + { + index = (index + 1) % pattern.Count; + } + + return (index, pattern[index]); } + // distanceFromWrap is now within (0, pattern[index]] - already small relative to the + // individual entry it was measured against, never the huge total pattern length - so it + // is safe to use directly as the remaining-in-dash distance. + var remaining = (float)distanceFromWrap; + return (index, remaining > pattern[index] ? pattern[index] : remaining); + } + + /// + /// Produces the path-length intervals where the dash pattern is "on". + /// + private static List<(float Start, float End)> BuildOnIntervals( + IReadOnlyList pattern, + float dashOffset, + float totalLength, + bool isClosed, + out bool encounteredPositiveOffSpan) + { + encounteredPositiveOffSpan = false; + var intervals = new List<(float Start, float End)>(); + var patternLength = GetPatternLength(pattern); + var (dashIndex, remainingInDash) = LocatePhase(pattern, dashOffset, patternLength); + var position = 0f; while (position < totalLength) { @@ -435,27 +504,6 @@ private static Vector2 GetPointAtDistance( return Vector2.Lerp(edgeStart, edgeEnd, t); } - /// - /// Normalizes into the half-open interval - /// [0, modulus). - /// - /// - /// is a (the total dash pattern - /// length, see ) so that a pattern summing close to - /// still normalizes correctly instead of collapsing to - /// float.PositiveInfinity. - /// - private static double NormalizeModulo(float value, double modulus) - { - var normalized = value % modulus; - if (normalized < 0d) - { - normalized += modulus; - } - - return normalized; - } - /// /// Appends unless it duplicates the current final point. /// diff --git a/src/DemaConsulting.CanvasNet/Drawing/StrokeOutliner.cs b/src/DemaConsulting.CanvasNet/Drawing/StrokeOutliner.cs index 532e010fe..cd83fcbff 100644 --- a/src/DemaConsulting.CanvasNet/Drawing/StrokeOutliner.cs +++ b/src/DemaConsulting.CanvasNet/Drawing/StrokeOutliner.cs @@ -47,15 +47,17 @@ internal static List> Outline( return CreatePointStrokePolygons(simplified[0], style.Cap, halfWidth, flattenTolerance); } - if (isClosed && simplified.Count == 2) - { - // A closed contour needs at least three distinct vertices to enclose any area; with - // exactly two, the "outer" and "inner" offset rings built by CreateClosedStrokePolygons - // would be coincident (zero signed area) and then forced into opposite winding, which - // makes FillRule.NonZero cancel the whole band to nothing. Instead, treat this - // degenerate closed contour exactly as an equivalent open single-segment stroke would - // be outlined (with caps at both ends per style.Cap) - the only well-defined non-empty - // rendering of a closed path that immediately doubles back over the same segment. + if (isClosed && IsDegenerateClosedContour(simplified)) + { + // A closed contour needs at least three NON-COLLINEAR distinct vertices to enclose + // any area. With fewer than three distinct vertices, or with any number of distinct + // vertices that all lie on one line (e.g. a 3+ point closed contour that traces back + // and forth along a single line), the "outer" and "inner" offset rings built by + // CreateClosedStrokePolygons would have zero signed area and then be forced into + // opposite winding, which makes FillRule.NonZero cancel the whole band to nothing. + // Instead, treat this degenerate closed contour exactly as an equivalent open + // multi-segment stroke would be outlined (with caps at both ends per style.Cap) - the + // only well-defined non-empty rendering of a closed path that encloses no area. return CreateOpenStrokePolygons(simplified, style, halfWidth, flattenTolerance); } @@ -87,6 +89,71 @@ private static List SimplifyPoints(IReadOnlyList points, bool return simplified; } + /// + /// Determines whether a closed contour encloses no area: either it has fewer than three + /// distinct vertices, or every distinct vertex lies on a single line. + /// + /// + /// This generalizes the original "exactly two distinct points" special case: a closed + /// contour with three or more distinct but COLLINEAR points (e.g. tracing + /// (0,0)->(1,0)->(2,0)->Close) is just as degenerate - it is a zero-area + /// band that would otherwise fall through to and + /// produce two coincident-band rings of opposite winding that cancel completely under + /// , even though a stroked degenerate line should still + /// render as a visible stroke. + /// + private static bool IsDegenerateClosedContour(IReadOnlyList points) => + points.Count < 3 || AreAllPointsCollinear(points); + + /// + /// Determines whether every point in lies on a single line. + /// + /// + /// Picks the first non-degenerate direction from points[0] to any later point (so + /// duplicate/near-duplicate leading points do not defeat the check), normalizes it, and + /// then confirms every remaining point's perpendicular distance from that line is within + /// . If every point coincides with points[0] (no + /// usable direction exists), the contour is fully collapsed and therefore trivially + /// collinear. + /// + private static bool AreAllPointsCollinear(IReadOnlyList points) + { + if (points.Count <= 2) + { + return true; + } + + var origin = points[0]; + var direction = Vector2.Zero; + for (var i = 1; i < points.Count; i++) + { + var candidate = points[i] - origin; + if (candidate.LengthSquared() > NearZeroDistance * NearZeroDistance) + { + direction = candidate; + break; + } + } + + if (direction == Vector2.Zero) + { + return true; + } + + var normalizedDirection = direction / direction.Length(); + for (var i = 1; i < points.Count; i++) + { + var offset = points[i] - origin; + var perpendicularDistance = normalizedDirection.X * offset.Y - normalizedDirection.Y * offset.X; + if (MathF.Abs(perpendicularDistance) > NearZeroDistance) + { + return false; + } + } + + return true; + } + /// /// Produces the special-case stroke geometry for a degenerate subpath reduced to one /// point. @@ -216,6 +283,16 @@ private static List> CreateClosedStrokePolygons( float halfWidth, float flattenTolerance) { + // Defense in depth: the dispatch in Outline() already routes degenerate (collinear or + // fewer-than-three-distinct-vertex) closed contours to CreateOpenStrokePolygons before + // ever reaching here, but re-checking here means this method can never itself produce the + // coincident-band, opposite-winding rings that FillRule.NonZero cancels to nothing, even + // if some future caller invokes it directly without going through that dispatch. + if (IsDegenerateClosedContour(points)) + { + return CreateOpenStrokePolygons(points, style, halfWidth, flattenTolerance); + } + var area = ComputeSignedArea(points); var outerSideSign = area >= 0f ? -1f : +1f; diff --git a/test/DemaConsulting.CanvasNet.Tests/Drawing/DashSplitterTests.cs b/test/DemaConsulting.CanvasNet.Tests/Drawing/DashSplitterTests.cs index f95101425..73fd41276 100644 --- a/test/DemaConsulting.CanvasNet.Tests/Drawing/DashSplitterTests.cs +++ b/test/DemaConsulting.CanvasNet.Tests/Drawing/DashSplitterTests.cs @@ -134,6 +134,67 @@ public void DashSplitter_Split_OverflowProneDashArrayWithNegativeOffset_Complete Assert.NotNull(segments); } + /// + /// Proves that a small negative dash offset against an astronomically large dash pattern + /// produces the CORRECT phase (not merely a non-hanging result): the offset must land in + /// the final unit of the preceding "off" entry rather than being silently swallowed by + /// catastrophic cancellation and snapping back to the start of the "on" entry. + /// + /// + /// With dash pattern [float.MaxValue, float.MaxValue] (an "on" entry followed by an + /// "off" entry, each individually finite but summing to a pattern length only + /// representable in ) and dashOffset: -1f, naively + /// normalizing the offset via modulus + (-1) in rounds + /// straight back to modulus - the tiny -1 is swallowed because doubles have + /// roughly 16 significant decimal digits and the modulus has 39. That silently moves the + /// phase to the start of the first ("on") entry instead of one unit before the end of the + /// second ("off") entry. The correct phase is one unit into the path's "off" span, so only + /// the remaining 9 units of the 10-unit path are "on". + /// + [Fact] + public void DashSplitter_Split_TinyNegativeOffsetAgainstHugePattern_ProducesCorrectPhase() + { + // Arrange + var points = new List { new(0, 0), new(10, 0) }; + + // Act + var segments = DashSplitter.Split( + points, + isClosed: false, + dashArray: [float.MaxValue, float.MaxValue], + dashOffset: -1f); + + // Assert: the first 1 unit is the tail of the "off" entry (invisible); the remaining 9 + // units are the following "on" entry. + var segment = Assert.Single(segments); + Assert.Equal([new Vector2(1, 0), new Vector2(10, 0)], segment.Points); + } + + /// + /// Proves correct phase resolution for a second extreme-magnitude-plus-small-negative- + /// offset combination, this time with an asymmetric pattern (a small "on" entry paired + /// with an astronomically large "off" entry). + /// + [Fact] + public void DashSplitter_Split_TinyNegativeOffsetAgainstAsymmetricHugePattern_ProducesCorrectPhase() + { + // Arrange: pattern [5 (on), float.MaxValue (off)], offset -2 lands 2 units before the end + // of the huge "off" entry, so the path starts 2 units into "off", then 5 units "on", then + // back into the (still enormous) "off" entry for the remainder of the 10-unit path. + var points = new List { new(0, 0), new(10, 0) }; + + // Act + var segments = DashSplitter.Split( + points, + isClosed: false, + dashArray: [5f, float.MaxValue], + dashOffset: -2f); + + // Assert + var segment = Assert.Single(segments); + Assert.Equal([new Vector2(2, 0), new Vector2(7, 0)], segment.Points); + } + /// /// Proves that an all-zero dash array is treated as a solid stroke. /// diff --git a/test/DemaConsulting.CanvasNet.Tests/Drawing/PathStrokerTests.cs b/test/DemaConsulting.CanvasNet.Tests/Drawing/PathStrokerTests.cs index 1c77f48a9..cc1b6c3ac 100644 --- a/test/DemaConsulting.CanvasNet.Tests/Drawing/PathStrokerTests.cs +++ b/test/DemaConsulting.CanvasNet.Tests/Drawing/PathStrokerTests.cs @@ -353,6 +353,36 @@ public void PathStroker_Stroke_ClosedTwoPointSubpath_FillsStrokedSegmentAreaNotE Assert.Equal((byte)0, surface[6, 1].A); } + /// + /// Proves that a closed subpath reduced to three or more DISTINCT but COLLINEAR points + /// (a zero-area closed contour tracing back and forth along a single line) still renders + /// as a stroked line segment, using the same pixel coverage as the equivalent open, + /// butt-capped stroke, rather than vanishing entirely. This generalizes + /// + /// to more than two collinear points. + /// + [Fact] + public void PathStroker_Stroke_ClosedThreePointCollinearSubpath_FillsStrokedSegmentAreaNotEmpty() + { + // Arrange: a closed subpath (M ... L ... L ... Z) with three distinct, collinear points + var path = new PathBuilder() + .MoveTo(new Vector2(2, 2)) + .LineTo(new Vector2(4, 2)) + .LineTo(new Vector2(6, 2)) + .Close() + .Build(); + var style = new StrokeStyle(2f, cap: LineCap.Butt); + + // Act: rasterize and sample actual pixel coverage, not just outline generation + var surface = RenderStroke(path, style, 8, 5); + + // Assert: coverage matches the equivalent open two-point butt-capped stroke + Assert.Equal((byte)255, surface[2, 1].A); + Assert.Equal((byte)255, surface[5, 2].A); + Assert.Equal((byte)0, surface[1, 1].A); + Assert.Equal((byte)0, surface[6, 1].A); + } + /// /// Proves that a dash array whose entries individually are finite but whose summed total /// pattern length would overflow a naive float32 accumulation does not hang the public diff --git a/test/DemaConsulting.CanvasNet.Tests/Drawing/StrokeOutlinerTests.cs b/test/DemaConsulting.CanvasNet.Tests/Drawing/StrokeOutlinerTests.cs index 7f31d2d89..d15c6c1c2 100644 --- a/test/DemaConsulting.CanvasNet.Tests/Drawing/StrokeOutlinerTests.cs +++ b/test/DemaConsulting.CanvasNet.Tests/Drawing/StrokeOutlinerTests.cs @@ -224,6 +224,66 @@ public void StrokeOutliner_Outline_ConcaveClosedContourBevelJoin_ResolvesJoinPer Assert.DoesNotContain(new Vector2(2, 2), ringWithStyledReflexJoin); } + /// + /// Proves that a closed contour reduced to three or more DISTINCT but COLLINEAR points + /// (a zero-area closed contour that traces back and forth along a single line) still + /// renders as a visible stroke, rather than vanishing entirely because its "outer" and + /// "inner" offset rings would otherwise be coincident (zero signed area) and forced into + /// opposite winding, which cancels completely under . This + /// generalizes the already-fixed exactly-two-point case to any number of collinear points. + /// + [Fact] + public void StrokeOutliner_Outline_ThreePointCollinearClosedContour_ProducesVisibleStroke() + { + // Arrange: a closed contour (M...L...L...Z) whose three distinct points all lie on the + // line y=2. + var points = new List { new(2, 2), new(4, 2), new(6, 2) }; + var style = new StrokeStyle(2f, cap: LineCap.Butt); + + // Act + var polygons = StrokeOutliner.Outline(points, isClosed: true, style, flattenTolerance: 0.25f); + + // Assert: a non-empty stroke covering the full [2,6] extent of the collinear points, + // one half-width above and below the line - exactly what an equivalent open stroke over + // the same points would produce. + var polygon = Assert.Single(polygons); + var minX = polygon.Min(p => p.X); + var maxX = polygon.Max(p => p.X); + var minY = polygon.Min(p => p.Y); + var maxY = polygon.Max(p => p.Y); + Assert.Equal(2f, minX); + Assert.Equal(6f, maxX); + Assert.Equal(1f, minY); + Assert.Equal(3f, maxY); + } + + /// + /// Proves that a closed contour mixing duplicate/near-duplicate points with otherwise + /// collinear points still renders as a visible stroke rather than vanishing. + /// + [Fact] + public void StrokeOutliner_Outline_CollinearClosedContourWithDuplicatePoints_ProducesVisibleStroke() + { + // Arrange: an exact duplicate of the first point, followed by collinear points, closing + // back to the start. + var points = new List { new(2, 2), new(2, 2), new(4, 2), new(6, 2) }; + var style = new StrokeStyle(2f, cap: LineCap.Butt); + + // Act + var polygons = StrokeOutliner.Outline(points, isClosed: true, style, flattenTolerance: 0.25f); + + // Assert + var polygon = Assert.Single(polygons); + var minX = polygon.Min(p => p.X); + var maxX = polygon.Max(p => p.X); + var minY = polygon.Min(p => p.Y); + var maxY = polygon.Max(p => p.Y); + Assert.Equal(2f, minX); + Assert.Equal(6f, maxX); + Assert.Equal(1f, minY); + Assert.Equal(3f, maxY); + } + private static float GetSignedArea(IReadOnlyList points) { var area = 0f; From 23c05466d1edcc41122a8e3a785953dbb328e68d Mon Sep 17 00:00:00 2001 From: Malcolm Nixon Date: Mon, 21 Sep 2026 15:14:04 -0400 Subject: [PATCH 07/13] Fix DashSplitter dash-extraction hang on long paths with fine dash patterns Accumulate cumulative path lengths and the dash-interval walking cursor in double instead of float. At path lengths in the tens of millions of units, float32's ULP can grow to meet or exceed a fine dash span (e.g. [1, 1]), so position += span could round back to the same position and the extraction loop would never terminate. Double keeps its ULP negligible at any length this library supports, and a defensive BitIncrement guard forces forward progress if a step ever still fails to advance. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../canvas-net/drawing/path-stroker.md | 1 + .../Drawing/DashSplitter.cs | 85 +++++++++++++------ .../Drawing/DashSplitterTests.cs | 55 ++++++++++++ 3 files changed, 117 insertions(+), 24 deletions(-) diff --git a/docs/verification/canvas-net/drawing/path-stroker.md b/docs/verification/canvas-net/drawing/path-stroker.md index 17a11ce3f..5998d795a 100644 --- a/docs/verification/canvas-net/drawing/path-stroker.md +++ b/docs/verification/canvas-net/drawing/path-stroker.md @@ -109,6 +109,7 @@ public styling values are preserved exactly. - `DashSplitter_Split_ClosedPolylineDashWrappingSeam_StitchesSegmentAcrossStartPoint` - `DashSplitter_Split_PatternLongerThanPolyline_ReturnsSinglePartialOnSegment` - `DashSplitter_Split_AllZeroDashArray_TreatedAsSolid` +- `DashSplitter_Split_FineDashPatternOnVeryLongPath_CompletesWithCorrectSegments` - `StrokeOutliner_Outline_ClosedSubpath_ProducesTwoCounterWoundRings` - `StrokeOutliner_Outline_MiterJoinWithinLimit_ProducesSharpVertex` - `StrokeOutliner_Outline_MiterJoinExceedingLimit_FallsBackToBevelVertex` diff --git a/src/DemaConsulting.CanvasNet/Drawing/DashSplitter.cs b/src/DemaConsulting.CanvasNet/Drawing/DashSplitter.cs index fa8940e72..9eb5152f7 100644 --- a/src/DemaConsulting.CanvasNet/Drawing/DashSplitter.cs +++ b/src/DemaConsulting.CanvasNet/Drawing/DashSplitter.cs @@ -66,7 +66,7 @@ internal static class DashSplitter var cumulativeLengths = BuildCumulativeLengths(points, isClosed); var totalLength = cumulativeLengths[^1]; - if (totalLength <= 0f) + if (totalLength <= 0d) { return IsDashOnAtStart(pattern, dashOffset) ? [(new List(points), isClosed)] : []; } @@ -202,10 +202,23 @@ private static double GetPatternLength(IReadOnlyList pattern) /// Computes one cumulative path-length entry per vertex boundary, including the seam edge /// for a closed polyline. /// - private static float[] BuildCumulativeLengths(IReadOnlyList points, bool isClosed) + /// + /// Accumulated in rather than : each + /// individual edge length is only float32-precise (it comes from + /// over float32 coordinates), but summing many edges of a + /// long path in float32 accumulates rounding error, and - critically - once the running + /// total's magnitude grows large enough that its float32 ULP (unit in the last place) + /// exceeds a typical edge or dash-span length, adding a further small value can round back + /// to the same total, silently discarding forward progress. A double-precision running + /// total keeps its ULP many orders of magnitude smaller at any length this library is + /// expected to support, so every dash-span comparison and step against it downstream (see + /// ) remains numerically meaningful instead of eventually + /// stalling. + /// + private static double[] BuildCumulativeLengths(IReadOnlyList points, bool isClosed) { var edgeCount = isClosed ? points.Count : points.Count - 1; - var cumulative = new float[edgeCount + 1]; + var cumulative = new double[edgeCount + 1]; for (var i = 0; i < edgeCount; i++) { var start = points[i]; @@ -347,29 +360,43 @@ private static (int Index, float RemainingInDash) LocatePhaseBackward( /// /// Produces the path-length intervals where the dash pattern is "on". /// - private static List<(float Start, float End)> BuildOnIntervals( + /// + /// , the running position cursor, and the emitted + /// interval boundaries are all rather than : + /// at path lengths in the millions of units, float32's ULP (unit in the last place) can + /// grow to meet or exceed a fine dash span (e.g. [1, 1]), so position += span + /// could round back to the same position and this loop would never reach + /// - an unconditional infinite loop, not merely a slow one. + /// Double keeps its ULP negligible relative to any dash span at path lengths this library + /// supports. As a second, magnitude-independent line of defense (in case some future caller + /// supplies a path long enough to exhaust even double precision), the loop explicitly + /// detects a step that fails to advance position and forces it to the next + /// representable value rather than silently spinning. + /// + private static List<(double Start, double End)> BuildOnIntervals( IReadOnlyList pattern, float dashOffset, - float totalLength, + double totalLength, bool isClosed, out bool encounteredPositiveOffSpan) { encounteredPositiveOffSpan = false; - var intervals = new List<(float Start, float End)>(); + var intervals = new List<(double Start, double End)>(); var patternLength = GetPatternLength(pattern); - var (dashIndex, remainingInDash) = LocatePhase(pattern, dashOffset, patternLength); + var (dashIndex, remainingInDashFloat) = LocatePhase(pattern, dashOffset, patternLength); + double remainingInDash = remainingInDashFloat; - var position = 0f; + var position = 0d; while (position < totalLength) { - if (remainingInDash <= 0f) + if (remainingInDash <= 0d) { AdvanceDash(pattern, ref dashIndex, ref remainingInDash); continue; } - var span = MathF.Min(remainingInDash, totalLength - position); - if (span <= 0f) + var span = Math.Min(remainingInDash, totalLength - position); + if (span <= 0d) { break; } @@ -378,12 +405,22 @@ private static (int Index, float RemainingInDash) LocatePhaseBackward( { intervals.Add((position, position + span)); } - else if (span > 0f) + else if (span > 0d) { encounteredPositiveOffSpan = true; } - position += span; + var nextPosition = position + span; + if (nextPosition <= position) + { + // Defensive guard: some step failed to advance position (only expected at + // magnitudes beyond what double precision can resolve against the dash span in + // play). Force forward progress to the next representable double so the loop is + // guaranteed to terminate rather than spin forever. + nextPosition = Math.BitIncrement(position); + } + + position = nextPosition; remainingInDash -= span; } @@ -398,7 +435,7 @@ private static (int Index, float RemainingInDash) LocatePhaseBackward( /// /// Advances to the next positive-length dash entry. /// - private static void AdvanceDash(IReadOnlyList pattern, ref int dashIndex, ref float remainingInDash) + private static void AdvanceDash(IReadOnlyList pattern, ref int dashIndex, ref double remainingInDash) { var traversed = 0; do @@ -407,7 +444,7 @@ private static void AdvanceDash(IReadOnlyList pattern, ref int dashIndex, remainingInDash = pattern[dashIndex]; traversed++; } - while (remainingInDash <= 0f && traversed <= pattern.Count); + while (remainingInDash <= 0d && traversed <= pattern.Count); } /// @@ -425,9 +462,9 @@ private static void AdvanceDash(IReadOnlyList pattern, ref int dashIndex, private static List ExtractIntervalPolyline( IReadOnlyList points, bool isClosed, - IReadOnlyList cumulativeLengths, - float startDistance, - float endDistance, + IReadOnlyList cumulativeLengths, + double startDistance, + double endDistance, ref int vertexCursor, ref int pointCursor) { @@ -469,11 +506,11 @@ private static List ExtractIntervalPolyline( private static Vector2 GetPointAtDistance( IReadOnlyList points, bool isClosed, - IReadOnlyList cumulativeLengths, - float distance, + IReadOnlyList cumulativeLengths, + double distance, ref int edgeCursor) { - if (distance <= 0f) + if (distance <= 0d) { return points[0]; } @@ -495,13 +532,13 @@ private static Vector2 GetPointAtDistance( var edgeStart = points[edgeCursor]; var edgeEnd = points[(edgeCursor + 1) % points.Count]; var edgeLength = endLength - startLength; - if (edgeLength <= 0f) + if (edgeLength <= 0d) { return edgeStart; } var t = (distance - startLength) / edgeLength; - return Vector2.Lerp(edgeStart, edgeEnd, t); + return Vector2.Lerp(edgeStart, edgeEnd, (float)t); } /// @@ -519,5 +556,5 @@ private static void AddPointIfDistinct(List points, Vector2 point) /// Determines whether is close enough to zero to be treated as a /// seam-aligned dash boundary. /// - private static bool IsNearZero(float value) => MathF.Abs(value) <= 1e-5f; + private static bool IsNearZero(double value) => Math.Abs(value) <= 1e-5d; } diff --git a/test/DemaConsulting.CanvasNet.Tests/Drawing/DashSplitterTests.cs b/test/DemaConsulting.CanvasNet.Tests/Drawing/DashSplitterTests.cs index 73fd41276..0925b4cdc 100644 --- a/test/DemaConsulting.CanvasNet.Tests/Drawing/DashSplitterTests.cs +++ b/test/DemaConsulting.CanvasNet.Tests/Drawing/DashSplitterTests.cs @@ -241,4 +241,59 @@ public void DashSplitter_Split_ZeroLengthLeadingDashEntryOnZeroLengthPath_Starts // entry, so no segments are emitted Assert.Empty(segments); } + + /// + /// Proves that a long path (millions of units) combined with a fine dash pattern + /// completes and produces numerically correct dash intervals, rather than hanging. + /// + /// + /// Prior to the fix, the path-length accumulator (position) in + /// BuildOnIntervals was a . At a magnitude of roughly + /// 17,000,000 units, float32's ULP (unit in the last place) grows to about 2, which is + /// larger than the 1-unit dash span in the [1, 1] pattern used here: adding a + /// 1-unit span to position would round straight back to the same value, so the + /// loop's exit condition (position < totalLength) was never reached - an + /// unconditional infinite loop, not merely a slow one. This test makes no timing + /// assertion (matching + /// above): it relies on the call actually returning at all to prove the loop terminates. + /// The path is built from unit-length edges (rather than one giant edge) so that a sample + /// of segments comfortably below float32's ~8,388,608 exact-integer boundary can be + /// asserted at their bit-exact expected positions: with a single giant edge, interpolating + /// a point uses t * hugeEdgeLength, which amplifies float32's relative rounding + /// error in t into an absolute error of roughly half a unit even for "small" + /// positions - an artifact of that interpolation shape, unrelated to the accumulator fix + /// under test here. Interpolating within short, unit-length edges avoids that amplification + /// entirely. + /// + [Fact] + public void DashSplitter_Split_FineDashPatternOnVeryLongPath_CompletesWithCorrectSegments() + { + // Arrange: a 17,000,000-unit straight path built from unit-length edges (so per-edge + // interpolation stays precise), comfortably past float32's ~16,777,216-unit + // exact-integer boundary, with a fine 1-on/1-off dash pattern. + const int length = 17_000_000; + var points = new List(length + 1); + for (var i = 0; i <= length; i++) + { + points.Add(new Vector2(i, 0)); + } + + // Act + var segments = DashSplitter.Split(points, isClosed: false, dashArray: [1f, 1f], dashOffset: 0f); + + // Assert: the call returned (did not hang) with exactly the expected number of "on" + // segments - itself strong evidence the interval-building loop correctly advanced across + // the whole path instead of stalling. The first segment and a segment comfortably below + // float32's 2^23 integer-precision boundary are asserted at their exact expected + // positions; the very last segment sits above that boundary, where Vector2's float32 + // coordinates cannot represent every unit integer exactly (a pre-existing, unrelated + // limitation of the public Vector2-based API, not of the dash-interval math itself under + // test here), so only a loose positional sanity check is made for it. + Assert.Equal(length / 2, segments.Count); + Assert.Equal([new Vector2(0, 0), new Vector2(1, 0)], segments[0].Points); + Assert.Equal( + [new Vector2(6_000_000, 0), new Vector2(6_000_001, 0)], + segments[3_000_000].Points); + Assert.True(segments[^1].Points[0].X >= length - 10f); + } } From fd3dd9af8176622769ee451777087ea1dfa0228d Mon Sep 17 00:00:00 2001 From: Malcolm Nixon Date: Mon, 21 Sep 2026 15:43:17 -0400 Subject: [PATCH 08/13] Fix closed-contour stroke inner-ring collapse when half-width exceeds inradius When a closed contour is stroked with a half-width that exceeds the contour's local inradius, BuildClosedSide's per-vertex exact offset-edge intersection construction produced a geometrically invalid inner ring: adjacent forced-intersection vertices' shared offset edge ran backwards relative to its source edge's direction (the offset lines had been pushed past each other), yielding an inverted, oversized ring rather than the correct empty erosion. Fed to NonZero fill as a hole, this carved out a nonsensical unfilled region - e.g. a 4x4 square stroked with Width: 10 left a bogus hole spanning roughly [1,7], larger than the square itself. BuildClosedSide now tracks which ring vertices are 'plain' forced exact-intersection points (one point per vertex, no styled-join points), and for each pair of adjacent plain vertices checks whether their shared offset edge still runs in the same direction as its source edge's tangent. CreateClosedStrokePolygons omits the inner ring entirely when this collapse is detected, so the whole interior renders as solid stroke - matching what a true geometric erosion by that half-width would produce once half-width exceeds the inradius. Adds StrokeOutliner_Outline_ClosedSquareHalfWidthExceedsInradius_ProducesNoInvalidHole (reproduces the reported bug; fails against the pre-fix code) and StrokeOutliner_Outline_ClosedSquareHalfWidthNearButBelowInradius_ProducesValidHole (confirms the ordinary near-threshold case still produces a valid, correctly nested hole). All prior StrokeOutliner/PathStroker tests, including the concave and collinear-degenerate regression tests, continue to pass unmodified. Updates the PathStroker design doc with a new bullet describing the inner-ring collapse detection and the verification doc's test listing for the two new StrokeOutlinerTests cases. --- .../design/canvas-net/drawing/path-stroker.md | 14 +- .../canvas-net/drawing/path-stroker.md | 4 +- .../Drawing/StrokeOutliner.cs | 75 ++++++++++- .../Drawing/StrokeOutlinerTests.cs | 124 +++++++++++++++++- 4 files changed, 209 insertions(+), 8 deletions(-) diff --git a/docs/design/canvas-net/drawing/path-stroker.md b/docs/design/canvas-net/drawing/path-stroker.md index d4043ec26..209cb4689 100644 --- a/docs/design/canvas-net/drawing/path-stroker.md +++ b/docs/design/canvas-net/drawing/path-stroker.md @@ -1,4 +1,4 @@ - + ## PathStroker @@ -120,6 +120,18 @@ instances directly. Every emitted polygon becomes one closed subpath in the resu always assigned to the correct ring even as convexity flips along a concave contour. The two rings are then wound in opposite directions so `FillRule.NonZero` fills only the shell between them, regardless of how many vertices on each ring ended up locally reflex. +- **Inner-ring collapse (half-width exceeding the local inradius).** The forced exact-edge + intersections above are only valid while the stroke half-width stays within the contour's local + inradius (the largest half-width for which the offset ring still nests inside the source + contour). Once half-width exceeds it somewhere along the contour, two adjacent forced + intersection vertices' shared offset edge runs backwards relative to its source edge's + direction, instead of forwards - the classic "erosion has gone empty" case from polygon + offsetting, except the naive per-vertex intersection construction does not notice on its own and + instead produces an invalid, oversized, wrongly wound ring. `StrokeOutliner` detects this + per-edge direction reversal while building each ring and, when found on the ring that would + otherwise become the hole, omits that ring entirely rather than emitting it as a hole - matching + what a true geometric erosion of the contour by that half-width would produce (an empty inner + boundary) and leaving the whole interior filled as solid stroke. - **Degenerate subpaths.** A single point (or a path collapsed to one effective point after duplicate-vertex simplification) renders as a cap-shaped mark: round creates a full circle, square creates an axis-aligned width-by-width square, and butt creates nothing. diff --git a/docs/verification/canvas-net/drawing/path-stroker.md b/docs/verification/canvas-net/drawing/path-stroker.md index 5998d795a..7247f7440 100644 --- a/docs/verification/canvas-net/drawing/path-stroker.md +++ b/docs/verification/canvas-net/drawing/path-stroker.md @@ -113,6 +113,8 @@ public styling values are preserved exactly. - `StrokeOutliner_Outline_ClosedSubpath_ProducesTwoCounterWoundRings` - `StrokeOutliner_Outline_MiterJoinWithinLimit_ProducesSharpVertex` - `StrokeOutliner_Outline_MiterJoinExceedingLimit_FallsBackToBevelVertex` +- `StrokeOutliner_Outline_ClosedSquareHalfWidthExceedsInradius_ProducesNoInvalidHole` +- `StrokeOutliner_Outline_ClosedSquareHalfWidthNearButBelowInradius_ProducesValidHole` These tests verify the intermediate geometry contracts that feed the public API: preserving open/closed state, applying SVG-style dash semantics, stitching seam-wrapping visible runs, and @@ -125,4 +127,4 @@ _PathStroker Unit Design_ (`../../../design/canvas-net/drawing/path-stroker.md`) analysis and code review only. There are intentionally **no** timing-based tests, elapsed-time assertions, or `Stopwatch`-based guards in this unit's automated verification because those are not stable compliance evidence on heterogeneous CI hardware. - + diff --git a/src/DemaConsulting.CanvasNet/Drawing/StrokeOutliner.cs b/src/DemaConsulting.CanvasNet/Drawing/StrokeOutliner.cs index cd83fcbff..fb90e09be 100644 --- a/src/DemaConsulting.CanvasNet/Drawing/StrokeOutliner.cs +++ b/src/DemaConsulting.CanvasNet/Drawing/StrokeOutliner.cs @@ -1,6 +1,6 @@ using System.Numerics; -// cspell:ignore Outliner outliner underflows underflowed +// cspell:ignore Outliner outliner underflows underflowed inradius namespace DemaConsulting.CanvasNet.Drawing; @@ -296,13 +296,31 @@ private static List> CreateClosedStrokePolygons( var area = ComputeSignedArea(points); var outerSideSign = area >= 0f ? -1f : +1f; - var outerRing = BuildClosedSide(points, outerSideSign, style, halfWidth, flattenTolerance); - var innerRing = BuildClosedSide(points, -outerSideSign, style, halfWidth, flattenTolerance); - if (outerRing.Count < 3 || innerRing.Count < 3) + var outerRing = BuildClosedSide(points, outerSideSign, style, halfWidth, flattenTolerance, out _); + if (outerRing.Count < 3) { return []; } + var innerRing = BuildClosedSide(points, -outerSideSign, style, halfWidth, flattenTolerance, out var innerRingCollapsed); + + // When the stroke half-width exceeds the contour's local inradius somewhere along its + // length, the "inner" ring's exact offset-edge intersection points (see BuildClosedSide's + // forceExactIntersection) are no longer a valid inward offset: the offset edges for two + // adjacent source edges have been pushed so far toward (and past) each other that the + // shared offset segment between their exact intersection points runs BACKWARDS relative + // to its source edge's direction, rather than forwards. BuildClosedSide detects this via + // innerRingCollapsed. Feeding such a ring to the NonZero fill as a hole would carve out a + // nonsensical region (potentially larger than the source contour itself, and wound so it + // no longer nests inside the outer ring) instead of correctly leaving the entire interior + // filled. Omit the hole entirely in that case, so the whole interior renders as solid + // stroke - the same outcome a true geometric erosion of the contour by half-width would + // produce once half-width exceeds the inradius (an empty inner boundary). + if (innerRing.Count < 3 || innerRingCollapsed) + { + return [outerRing]; + } + // Regardless of how many vertices were locally reflex on each ring, the two rings must // still end up with opposite winding for FillRule.NonZero to render the band between them // (rather than the solid disc of one ring or the empty complement) - flip the inner ring @@ -450,15 +468,28 @@ private static void AppendOpenJoin( /// locally convex side) or force the exact offset-edge intersection (the locally concave /// side, where a stylized corner would carve away or add stroke area). /// + /// + /// Set to when the stroke half-width exceeds this contour's local + /// inradius somewhere along its length, so that two adjacent forced exact-intersection + /// vertices' shared offset edge runs backwards relative to its source edge - the ring is + /// no longer a valid inward offset and must not be used as a fill hole. + /// private static List BuildClosedSide( IReadOnlyList points, float sideSign, StrokeStyle style, float halfWidth, - float flattenTolerance) + float flattenTolerance, + out bool collapsed) { var frames = BuildSegmentFrames(points, isClosed: true); var ring = new List(points.Count * 2); + + // Tracks, for each source vertex, the ring index of the single plain offset point emitted + // for it (see the remarks below), or -1 if that vertex instead emitted a styled join + // (Round/Bevel/Miter, or a Miter/exact-intersection fallback) that can contribute zero, + // one, or more than one point not directly tied to a single shared offset edge. + var plainPointIndex = new int[points.Count]; for (var i = 0; i < points.Count; i++) { var previousFrame = frames[(i + frames.Length - 1) % frames.Length]; @@ -468,10 +499,12 @@ private static List BuildClosedSide( if (MathF.Abs(turn) <= NearZeroDistance && dot > 0f) { AddPointIfDistinct(ring, points[i] + sideSign * nextFrame.Normal * halfWidth); + plainPointIndex[i] = ring.Count - 1; continue; } var isConvexOnThisSide = turn * sideSign < 0f; + var countBefore = ring.Count; AppendStyledJoin( ring, points[i], @@ -484,6 +517,38 @@ private static List BuildClosedSide( halfWidth, flattenTolerance, forceExactIntersection: !isConvexOnThisSide); + + // Only a locally concave (forceExactIntersection) vertex that emitted exactly one + // point is a "plain" vertex whose single point is the shared endpoint of two adjacent + // offset edges - see the collapse check below. A locally convex (styled-join) vertex, + // or a concave vertex whose lines were parallel and fell back to the two un-joined + // offset points, is excluded from that check. + plainPointIndex[i] = !isConvexOnThisSide && ring.Count - countBefore == 1 ? ring.Count - 1 : -1; + } + + // Detect inner-ring collapse: when the stroke half-width exceeds the contour's local + // inradius, two adjacent plain (forced exact-intersection) vertices' shared offset edge - + // which must run in the SAME direction as its source edge's tangent for the ring to be a + // valid inward offset - instead runs BACKWARDS, because the offset lines were pushed past + // each other. A single such reversal invalidates the whole ring as a hole (see + // CreateClosedStrokePolygons). + collapsed = false; + for (var i = 0; i < points.Count; i++) + { + var next = (i + 1) % points.Count; + var currentIndex = plainPointIndex[i]; + var nextIndex = plainPointIndex[next]; + if (currentIndex < 0 || nextIndex < 0) + { + continue; + } + + var edgeVector = ring[nextIndex] - ring[currentIndex]; + if (Vector2.Dot(edgeVector, frames[i].Tangent) <= NearZeroDistance) + { + collapsed = true; + break; + } } RemoveTrailingDuplicateOfFirst(ring); diff --git a/test/DemaConsulting.CanvasNet.Tests/Drawing/StrokeOutlinerTests.cs b/test/DemaConsulting.CanvasNet.Tests/Drawing/StrokeOutlinerTests.cs index d15c6c1c2..9e56b909e 100644 --- a/test/DemaConsulting.CanvasNet.Tests/Drawing/StrokeOutlinerTests.cs +++ b/test/DemaConsulting.CanvasNet.Tests/Drawing/StrokeOutlinerTests.cs @@ -2,7 +2,7 @@ using System.Numerics; using DemaConsulting.CanvasNet.Drawing; -// cspell:ignore Outliner underflows +// cspell:ignore Outliner underflows inradius namespace DemaConsulting.CanvasNet.Tests.Drawing; @@ -284,6 +284,107 @@ public void StrokeOutliner_Outline_CollinearClosedContourWithDuplicatePoints_Pro Assert.Equal(3f, maxY); } + /// + /// Proves that stroking a closed contour with a half-width that EXCEEDS the contour's + /// inradius (the largest half-width for which the stroke band still leaves an unfilled + /// hole) does not produce an invalid, collapsed "inner ring" hole - the entire interior + /// must instead render as solid stroke, exactly as a true geometric erosion of the contour + /// by that half-width would (an empty inner boundary once half-width exceeds the + /// inradius). + /// + /// + /// The 4x4 square (2,2)-(6,2)-(6,6)-(2,6) has an inradius of only 2 (half its 4-unit side + /// length). At Width: 10 (half-width 5), the naive per-vertex exact offset-edge + /// intersection used to build the inner/hole ring produces corners far OUTSIDE the + /// original square (around [-3,11] for the outer ring and a wrongly inverted, + /// oversized square around [1,7] for what would have been the "inner" ring, per the + /// original bug report), rather than correctly collapsing to nothing. Before the fix, this + /// produced two counter-wound rings and left a bogus, unfilled square hole spanning + /// roughly [1,7] - larger than the original 4x4 square itself. After the fix, the + /// inner ring's collapse is detected and the hole is omitted entirely, leaving a single + /// outer ring whose interior fully covers the original square (and a comfortable margin + /// beyond it). + /// + [Fact] + public void StrokeOutliner_Outline_ClosedSquareHalfWidthExceedsInradius_ProducesNoInvalidHole() + { + // Arrange: a 4x4 square (inradius 2) stroked with half-width 5, well past the inradius. + var points = new List + { + new(2, 2), + new(6, 2), + new(6, 6), + new(2, 6) + }; + var style = new StrokeStyle(10f); + + // Act + var polygons = StrokeOutliner.Outline(points, isClosed: true, style, flattenTolerance: 0.25f); + + // Assert: exactly one polygon (no hole) - the whole square interior renders as stroke. + var polygon = Assert.Single(polygons); + + // The entire original square, and a reasonable margin around it, must lie within the + // single outer polygon (no unfilled hole anywhere within the square). + Vector2[] mustBeCovered = + [ + new(4, 4), // center + new(2.5f, 2.5f), + new(5.5f, 2.5f), + new(5.5f, 5.5f), + new(2.5f, 5.5f), + new(2, 2), + new(6, 6) + ]; + foreach (var point in mustBeCovered) + { + Assert.True( + IsPointInPolygon(point, polygon), + $"Expected {point} to be covered by the stroke band (no unfilled hole), but it was not."); + } + } + + /// + /// Proves that a half-width comfortably NEAR but still below the contour's inradius still + /// produces the correct, valid (non-collapsed) hole - the fix for over-erosion must not + /// regress the ordinary case where the inner ring remains geometrically valid. + /// + [Fact] + public void StrokeOutliner_Outline_ClosedSquareHalfWidthNearButBelowInradius_ProducesValidHole() + { + // Arrange: the same 4x4 square (inradius 2), now stroked with half-width 1.9 - close to, + // but still below, the inradius. + var points = new List + { + new(2, 2), + new(6, 2), + new(6, 6), + new(2, 6) + }; + var style = new StrokeStyle(3.8f); + + // Act + var polygons = StrokeOutliner.Outline(points, isClosed: true, style, flattenTolerance: 0.25f); + + // Assert: two counter-wound rings (a genuine hole is still produced). + Assert.Equal(2, polygons.Count); + Assert.True(GetSignedArea(polygons[0]) * GetSignedArea(polygons[1]) < 0f); + + // The center of the square (the deepest interior point, furthest from every edge) must + // fall within the small remaining hole, not be covered by the stroke band. + var outerRing = polygons[0]; + var innerRing = polygons[1]; + Assert.True(IsPointInPolygon(new Vector2(4, 4), outerRing)); + Assert.True(IsPointInPolygon(new Vector2(4, 4), innerRing)); + + // The hole must remain nested well within the original square, not spill outside it. + foreach (var vertex in innerRing) + { + Assert.InRange(vertex.X, 2f, 6f); + Assert.InRange(vertex.Y, 2f, 6f); + } + } + private static float GetSignedArea(IReadOnlyList points) { var area = 0f; @@ -296,4 +397,25 @@ private static float GetSignedArea(IReadOnlyList points) return area / 2f; } + + /// + /// Determines whether a point lies within a simple polygon using the standard ray-casting + /// (even-odd crossing) test. + /// + private static bool IsPointInPolygon(Vector2 point, IReadOnlyList polygon) + { + var inside = false; + for (int i = 0, j = polygon.Count - 1; i < polygon.Count; j = i++) + { + var vi = polygon[i]; + var vj = polygon[j]; + if (((vi.Y > point.Y) != (vj.Y > point.Y)) && + (point.X < (vj.X - vi.X) * (point.Y - vi.Y) / (vj.Y - vi.Y) + vi.X)) + { + inside = !inside; + } + } + + return inside; + } } From db5cea61df20037436edb4872444674bca757280 Mon Sep 17 00:00:00 2001 From: Malcolm Nixon Date: Mon, 21 Sep 2026 16:03:16 -0400 Subject: [PATCH 09/13] Fix DashSplitter edge-length float32 overflow causing infinite dash loop BuildCumulativeLengths computed per-edge length via Vector2.Distance, which internally computes dx*dx + dy*dy in float32 before taking the square root. For a legal, finite edge spanning near-extreme float32 coordinates (e.g. near float.MinValue to near float.MaxValue), that intermediate squaring overflows to +Infinity even though the true distance is finite in double precision. The infinite edge length made totalLength infinite in BuildOnIntervals, and its while (position < totalLength) loop could never terminate since position can never reach infinity, hanging PathStroker.Stroke. Fix: widen the edge deltas to double before squaring and take the square root in double precision, so a legitimately huge-but-finite edge length never suffers a spurious float32 intermediate overflow. Added a regression test proving an edge spanning near-extreme float32 coordinates completes (rather than hanging) and produces finite dash segments. Verified the test reproduces the bug against the pre-fix code (OutOfMemoryException after the traversal loop ran unbounded for ~2 minutes), and passes with the fix. All 2103 existing tests (including prior hang-regression tests) continue to pass with zero regressions. --- .../Drawing/DashSplitter.cs | 39 ++++++++++----- .../Drawing/DashSplitterTests.cs | 50 +++++++++++++++++++ 2 files changed, 77 insertions(+), 12 deletions(-) diff --git a/src/DemaConsulting.CanvasNet/Drawing/DashSplitter.cs b/src/DemaConsulting.CanvasNet/Drawing/DashSplitter.cs index 9eb5152f7..b21e0950c 100644 --- a/src/DemaConsulting.CanvasNet/Drawing/DashSplitter.cs +++ b/src/DemaConsulting.CanvasNet/Drawing/DashSplitter.cs @@ -203,17 +203,30 @@ private static double GetPatternLength(IReadOnlyList pattern) /// for a closed polyline. /// /// - /// Accumulated in rather than : each - /// individual edge length is only float32-precise (it comes from - /// over float32 coordinates), but summing many edges of a - /// long path in float32 accumulates rounding error, and - critically - once the running - /// total's magnitude grows large enough that its float32 ULP (unit in the last place) - /// exceeds a typical edge or dash-span length, adding a further small value can round back - /// to the same total, silently discarding forward progress. A double-precision running - /// total keeps its ULP many orders of magnitude smaller at any length this library is - /// expected to support, so every dash-span comparison and step against it downstream (see - /// ) remains numerically meaningful instead of eventually - /// stalling. + /// Accumulated in rather than : summing + /// many edges of a long path in float32 accumulates rounding error, and - critically - + /// once the running total's magnitude grows large enough that its float32 ULP (unit in + /// the last place) exceeds a typical edge or dash-span length, adding a further small + /// value can round back to the same total, silently discarding forward progress. A + /// double-precision running total keeps its ULP many orders of magnitude smaller at any + /// length this library is expected to support, so every dash-span comparison and step + /// against it downstream (see ) remains numerically + /// meaningful instead of eventually stalling. + /// + /// Each edge length is computed via Math.Sqrt over + /// coordinate deltas rather than : + /// coordinates are float32, and for an edge spanning near-extreme float32 coordinates + /// (e.g. one endpoint near and the other near + /// ), 's internal + /// dx*dx + dy*dy computation is carried out in float32 and overflows to + /// well before the true distance would, even though + /// the same computation in double precision remains finite (float32's maximum magnitude + /// squared and doubled is still comfortably within double's representable range). Widening + /// the deltas to double before squaring avoids that spurious intermediate overflow, so a + /// legitimately huge but finite edge never poisons totalLength in + /// with and stalling + /// its while (position < totalLength) loop forever. + /// /// private static double[] BuildCumulativeLengths(IReadOnlyList points, bool isClosed) { @@ -223,7 +236,9 @@ private static double[] BuildCumulativeLengths(IReadOnlyList points, bo { var start = points[i]; var end = points[(i + 1) % points.Count]; - cumulative[i + 1] = cumulative[i] + Vector2.Distance(start, end); + var dx = (double)end.X - start.X; + var dy = (double)end.Y - start.Y; + cumulative[i + 1] = cumulative[i] + Math.Sqrt(dx * dx + dy * dy); } return cumulative; diff --git a/test/DemaConsulting.CanvasNet.Tests/Drawing/DashSplitterTests.cs b/test/DemaConsulting.CanvasNet.Tests/Drawing/DashSplitterTests.cs index 0925b4cdc..0ea6ede58 100644 --- a/test/DemaConsulting.CanvasNet.Tests/Drawing/DashSplitterTests.cs +++ b/test/DemaConsulting.CanvasNet.Tests/Drawing/DashSplitterTests.cs @@ -296,4 +296,54 @@ public void DashSplitter_Split_FineDashPatternOnVeryLongPath_CompletesWithCorrec segments[3_000_000].Points); Assert.True(segments[^1].Points[0].X >= length - 10f); } + + /// + /// Proves that an edge spanning near-extreme float32 coordinates (from near + /// to near ) - a legal, finite + /// pair of endpoints - completes and produces finite dash intervals, + /// rather than hanging. + /// + /// + /// Prior to the fix, per-edge length in BuildCumulativeLengths was computed via + /// , which internally computes dx*dx + dy*dy in + /// float32 before taking the square root. For this edge, that intermediate squaring + /// overflows float32's representable range and produces , + /// even though the true distance - while enormous - is finite in double precision. That + /// infinite edge length made totalLength infinite, and the traversal loop in + /// BuildOnIntervals (while (position < totalLength)) could never + /// terminate, since position can never reach infinity. This test makes no timing + /// assertion (matching the other hang-regression tests above): it relies on the call + /// actually returning at all to prove the loop terminates, and additionally asserts the + /// produced segment endpoints are finite. + /// + [Fact] + public void DashSplitter_Split_EdgeSpanningExtremeFloat32Coordinates_CompletesWithFiniteSegments() + { + // Arrange: a single edge from near float.MinValue to near float.MaxValue. Vector2.Distance + // computes dx*dx + dy*dy in float32, which overflows to +Infinity for this edge even + // though the true (double-precision) distance (~3.4e38) is finite. A dash pattern scaled + // to match that magnitude (rather than a fine [1, 1] pattern) keeps the number of + // traversal-loop iterations small, so the test exercises only the length computation + // itself rather than depending on the loop's (separately tested) large-iteration-count + // behavior. + var points = new List + { + new(float.MinValue / 2, 0), + new(float.MaxValue / 2, 0) + }; + + // Act + var segments = DashSplitter.Split(points, isClosed: false, dashArray: [1e38f, 1e38f], dashOffset: 0f); + + // Assert: the call returned (did not hang), and every emitted point is finite. + Assert.NotEmpty(segments); + foreach (var segment in segments) + { + foreach (var point in segment.Points) + { + Assert.True(float.IsFinite(point.X)); + Assert.True(float.IsFinite(point.Y)); + } + } + } } From 4795df0de8741f0e381a5389f1da0d54dad82431 Mon Sep 17 00:00:00 2001 From: Malcolm Nixon Date: Mon, 21 Sep 2026 16:34:49 -0400 Subject: [PATCH 10/13] Fix stroke outer-outline winding cancellation and StrokeOutliner float32 edge-length overflow - Normalize the winding of every independently-emitted OUTER stroke outline (open-line outlines, point-cap circles/squares, and closed-contour outer rings) to one fixed direction in StrokeOutliner, regardless of outline kind or source contour authoring order. PathStroker.Stroke emits each outline as an independent NonZero-filled subpath, so previously two overlapping outer outlines from the same Stroke call could carry opposite signed winding purely by chance and cancel to an incorrect unfilled hole in their overlap instead of reinforcing (unioning). Inner (hole) rings remain intentionally unnormalized, fixed up relative to their own outer ring so they stay the opposite winding, per the existing (correct) shell/hole invariant. - Compute the per-segment tangent/normal frame in BuildSegmentFrames using double-precision coordinate deltas before narrowing back to Vector2/float32, matching the pattern already used in DashSplitter.BuildCumulativeLengths. A finite edge spanning near-extreme float32 coordinates (e.g. -1e20 to 1e20) previously overflowed float32's dx*dx+dy*dy inside Vector2.Length() to Infinity, collapsing the tangent/normal to zero and silently dropping the stroke outline for that segment. - Add regression tests proving both defects reproduce pre-fix and are resolved post-fix, with zero regressions across all existing StrokeOutliner/PathStroker/DashSplitter tests. - Update the PathStroker design and verification docs to describe the outer-outline winding-normalization rule and list the new tests. --- .../design/canvas-net/drawing/path-stroker.md | 31 +++++ .../canvas-net/drawing/path-stroker.md | 20 ++- .../Drawing/StrokeOutliner.cs | 103 ++++++++++++--- .../Drawing/PathStrokerTests.cs | 46 +++++++ .../Drawing/StrokeOutlinerTests.cs | 125 ++++++++++++++++++ 5 files changed, 305 insertions(+), 20 deletions(-) diff --git a/docs/design/canvas-net/drawing/path-stroker.md b/docs/design/canvas-net/drawing/path-stroker.md index 209cb4689..318972fe5 100644 --- a/docs/design/canvas-net/drawing/path-stroker.md +++ b/docs/design/canvas-net/drawing/path-stroker.md @@ -81,6 +81,20 @@ as a brand-new `Path`: side in reverse, and the start cap. - **Closed contours** produce two closed rings (outer and inner) wound in opposite directions so `FillRule.NonZero` fills only the shell between them. + - **Outer-outline winding normalization.** `Stroke` appends every stroked subpath's outline(s) + as independent closed subpaths in one output `Path`, and the whole result is documented to be + filled with `FillRule.NonZero`. Because NonZero only reinforces (unions) two overlapping + subpaths when they carry the *same* signed winding, every independently-emitted **outer** + outline - an open-line outline, a point-cap circle or square, or a closed contour's outer + shell ring - is normalized to one fixed winding direction regardless of the source subpath's + authored orientation. Without this, two overlapping outer outlines produced by the same + `Stroke` call could end up with opposite signed winding purely by chance of which outline kind + produced each one (or by the caller's authored point order for a closed contour), and their + overlap would cancel to an incorrect unfilled hole instead of solid fill. A closed contour's + **inner** ring is deliberately *not* normalized to this same fixed direction: it is fixed up + relative to its own (already-normalized) outer ring instead, so it always remains the + opposite winding of that ring - the unrelated mechanism that makes `FillRule.NonZero` render + the shell between the two rings rather than the solid disc of one ring. - **Miter joins** intersect the two offset lines and then compare the distance from the source vertex to that intersection against `MiterLimit * (Width / 2)`. This single offset line sits half the stroke width from the source vertex, so this distance is exactly half of the SVG @@ -120,6 +134,23 @@ instances directly. Every emitted polygon becomes one closed subpath in the resu always assigned to the correct ring even as convexity flips along a concave contour. The two rings are then wound in opposite directions so `FillRule.NonZero` fills only the shell between them, regardless of how many vertices on each ring ended up locally reflex. +- **Outer-outline winding normalization.** Every independently-emitted OUTER outline - an + open-line outline (`CreateOpenStrokePolygons`), a point-cap circle or square + (`CreatePointStrokePolygons`), or a closed contour's outer shell ring + (`CreateClosedStrokePolygons`) - is normalized to one fixed signed-winding direction via a shared + `NormalizeOuterWinding` helper before it is returned. Without this, an open-line outline was + always wound one way, a point-cap circle/square the other way, and a closed contour's outer ring + simply followed whichever direction its source contour happened to be authored in - so two + overlapping outer outlines from the same `PathStroker.Stroke` call could easily end up with + opposite signed winding purely by coincidence, which `FillRule.NonZero` would then cancel to an + incorrect unfilled hole in their overlap instead of reinforcing (unioning) them. Reversing a + polygon's vertex order only flips its signed winding, never its silhouette, so this + normalization changes no filled shape on its own - it only removes the accidental sign mismatch + between independently-produced outer outlines. A closed contour's inner (hole) ring is + deliberately excluded from this normalization: it is fixed up separately, immediately after, to + remain the *opposite* winding of its own (already-normalized) outer ring, which is the unrelated, + pre-existing mechanism that makes the shell between the two rings render instead of the solid + disc of one ring. - **Inner-ring collapse (half-width exceeding the local inradius).** The forced exact-edge intersections above are only valid while the stroke half-width stays within the contour's local inradius (the largest half-width for which the offset ring still nests inside the source diff --git a/docs/verification/canvas-net/drawing/path-stroker.md b/docs/verification/canvas-net/drawing/path-stroker.md index 7247f7440..ba4ec6d7f 100644 --- a/docs/verification/canvas-net/drawing/path-stroker.md +++ b/docs/verification/canvas-net/drawing/path-stroker.md @@ -62,6 +62,7 @@ limit, proving that the rendered result matches the bevel case rather than the u #### Closed Contours, Dashing, and Degenerate Subpaths - `PathStroker_Stroke_ClosedRectangle_FillsRingLeavingInteriorAndExteriorUnfilled` +- `PathStroker_Stroke_OverlappingLineAndPointCapOutlines_FillsOverlapRegionSolid` - `PathStroker_Stroke_DashedLine_FillsOnlyOnSegmentsLeavingGapsUnfilled` - `PathStroker_Stroke_ZeroLengthSubpathRoundCap_FillsCircleOfRadiusHalfWidth` - `PathStroker_Stroke_ZeroLengthSubpathSquareCap_FillsSquareOfSideWidth` @@ -70,9 +71,11 @@ limit, proving that the rendered result matches the bevel case rather than the u - `PathStroker_Stroke_EmptyPath_ReturnsEmptyPathNoOp` These scenarios verify the boundary conditions most likely to produce either missing geometry or -wrong winding: closed contours must leave their interior hole unfilled; dashed lines must paint -only visible runs; degenerate subpaths must follow cap semantics exactly; and an empty path must -remain a no-op. +wrong winding: closed contours must leave their interior hole unfilled; two independently-emitted +outer outlines (an open-line outline and a point-cap circle) that overlap must render the overlap +region solidly filled rather than as a winding-cancellation hole; dashed lines must paint only +visible runs; degenerate subpaths must follow cap semantics exactly; and an empty path must remain +a no-op. #### Public API Validation @@ -111,14 +114,21 @@ public styling values are preserved exactly. - `DashSplitter_Split_AllZeroDashArray_TreatedAsSolid` - `DashSplitter_Split_FineDashPatternOnVeryLongPath_CompletesWithCorrectSegments` - `StrokeOutliner_Outline_ClosedSubpath_ProducesTwoCounterWoundRings` +- `StrokeOutliner_Outline_OpenLineAndPointCapCircle_ShareSameOuterWinding` +- `StrokeOutliner_Outline_ClosedContourReversedSourceWinding_NormalizesOuterRingConsistently` +- `StrokeOutliner_Outline_SegmentSpanningExtremeFloat32Coordinates_ProducesValidNonDegenerateOutline` - `StrokeOutliner_Outline_MiterJoinWithinLimit_ProducesSharpVertex` - `StrokeOutliner_Outline_MiterJoinExceedingLimit_FallsBackToBevelVertex` - `StrokeOutliner_Outline_ClosedSquareHalfWidthExceedsInradius_ProducesNoInvalidHole` - `StrokeOutliner_Outline_ClosedSquareHalfWidthNearButBelowInradius_ProducesValidHole` These tests verify the intermediate geometry contracts that feed the public API: preserving -open/closed state, applying SVG-style dash semantics, stitching seam-wrapping visible runs, and -producing shell rings with opposite winding for `FillRule.NonZero`. +open/closed state, applying SVG-style dash semantics, stitching seam-wrapping visible runs, +normalizing every independently-emitted outer outline (open-line outlines, point-cap circles, and +closed-contour outer rings) to a single consistent winding direction regardless of outline kind or +source authoring order, tolerating segments spanning near-extreme float32 coordinates without +overflowing to a degenerate outline, and producing shell rings with opposite winding for +`FillRule.NonZero`. ### Complexity Verification Policy diff --git a/src/DemaConsulting.CanvasNet/Drawing/StrokeOutliner.cs b/src/DemaConsulting.CanvasNet/Drawing/StrokeOutliner.cs index fb90e09be..1a0882774 100644 --- a/src/DemaConsulting.CanvasNet/Drawing/StrokeOutliner.cs +++ b/src/DemaConsulting.CanvasNet/Drawing/StrokeOutliner.cs @@ -167,19 +167,20 @@ private static List> CreatePointStrokePolygons( switch (cap) { case LineCap.Round: - return [CreateCirclePolygon(center, halfWidth, flattenTolerance)]; + var circle = CreateCirclePolygon(center, halfWidth, flattenTolerance); + NormalizeOuterWinding(circle); + return [circle]; case LineCap.Square: - return - [ - new List - { - new(center.X - halfWidth, center.Y - halfWidth), - new(center.X + halfWidth, center.Y - halfWidth), - new(center.X + halfWidth, center.Y + halfWidth), - new(center.X - halfWidth, center.Y + halfWidth) - } - ]; + var square = new List + { + new(center.X - halfWidth, center.Y - halfWidth), + new(center.X + halfWidth, center.Y - halfWidth), + new(center.X + halfWidth, center.Y + halfWidth), + new(center.X - halfWidth, center.Y + halfWidth) + }; + NormalizeOuterWinding(square); + return [square]; case LineCap.Butt: default: @@ -253,7 +254,13 @@ private static List> CreateOpenStrokePolygons( } RemoveTrailingDuplicateOfFirst(polygon); - return polygon.Count >= 3 ? [polygon] : []; + if (polygon.Count < 3) + { + return []; + } + + NormalizeOuterWinding(polygon); + return [polygon]; } /// @@ -302,6 +309,17 @@ private static List> CreateClosedStrokePolygons( return []; } + // Normalize the outer ring's own winding to the same fixed direction used for every other + // independently-emitted outer outline (open-line outlines, point-cap circles/squares - see + // NormalizeOuterWinding), regardless of the source contour's authored orientation. Without + // this, a source contour authored in reversed order flips outerSideSign's resulting + // winding to follow it, so two overlapping stroked elements from the same Stroke call can + // end up with opposite signed winding under FillRule.NonZero and cancel to a hole in their + // overlap instead of reinforcing (unioning). The inner ring is intentionally NOT + // normalized here - it is fixed up below to remain OPPOSITE the (now-normalized) outer + // ring, which is the unrelated, already-correct hole-vs-shell invariant. + NormalizeOuterWinding(outerRing); + var innerRing = BuildClosedSide(points, -outerSideSign, style, halfWidth, flattenTolerance, out var innerRingCollapsed); // When the stroke half-width exceeds the contour's local inradius somewhere along its @@ -337,6 +355,21 @@ private static List> CreateClosedStrokePolygons( /// /// Computes one tangent/normal pair per segment of an open or closed polyline. /// + /// + /// The edge delta and its length are computed in precision + /// rather than via subtraction and : + /// both of those operate in float32, and for an edge spanning near-extreme float32 + /// coordinates (e.g. one endpoint near -1e20 and the other near 1e20), the + /// float32 dx*dx + dy*dy computation overflows to + /// well before the true length would, even though the + /// same computation in double precision remains finite. That overflow would otherwise + /// collapse the tangent/normal for a legitimately huge but finite edge to something + /// degenerate (zero, NaN, or Infinity), silently producing no stroke area for + /// that segment - the same class of float32-overflow bug already fixed for edge-length + /// accumulation in . Normalizing in + /// double before narrowing back to keeps the tangent/normal + /// computation correct for any finite edge, however extreme its coordinates. + /// private static (Vector2 Tangent, Vector2 Normal)[] BuildSegmentFrames(IReadOnlyList points, bool isClosed) { var segmentCount = isClosed ? points.Count : points.Count - 1; @@ -345,15 +378,16 @@ private static (Vector2 Tangent, Vector2 Normal)[] BuildSegmentFrames(IReadOnlyL { var start = points[i]; var end = points[(i + 1) % points.Count]; - var direction = end - start; - var length = direction.Length(); + var dx = (double)end.X - start.X; + var dy = (double)end.Y - start.Y; + var length = Math.Sqrt(dx * dx + dy * dy); if (length <= NearZeroDistance) { frames[i] = (Vector2.UnitX, new Vector2(0f, 1f)); continue; } - var tangent = direction / length; + var tangent = new Vector2((float)(dx / length), (float)(dy / length)); frames[i] = (tangent, new Vector2(-tangent.Y, tangent.X)); } @@ -947,6 +981,45 @@ private static float NormalizePositiveAngle(float angle) return normalized; } + /// + /// Reverses in place, if necessary, so every independently-emitted + /// OUTER outline (an open-line outline, a point-cap circle or square, or a closed + /// contour's outer shell ring) ends up with the same fixed winding direction, regardless + /// of the source subpath's authored orientation. + /// + /// + /// + /// emits every stroked subpath's outline(s) as independent closed subpaths in one output + /// , documented to be filled with + /// . Under NonZero, two overlapping subpaths only reinforce + /// (union) each other when they carry the SAME signed winding; if their windings happen to + /// be opposite, their overlap's winding numbers cancel and NonZero incorrectly renders a + /// hole there instead of solid fill. Before this normalization, an open-line stroke + /// outline was always wound one way, point-cap circles/squares were always wound the other + /// way, and a closed contour's outer ring followed whatever direction its source contour + /// happened to be authored in - so two overlapping outer outlines from the very same + /// call could easily end up with opposite winding purely + /// by chance of which outline kind produced each one. Forcing every outer outline to the + /// same fixed sign (positive, matching this file's + /// convention) eliminates that chance cancellation while leaving each outline's actual + /// vertex positions - and therefore its filled shape - completely unchanged; reversing a + /// polygon's vertex order only flips its signed winding, not its silhouette. + /// + /// This must only ever be applied to an OUTER outline. A closed contour's INNER ring (the + /// hole) must remain the OPPOSITE winding of its own outer ring - that asymmetry is the + /// mechanism by which renders the shell between the two + /// rings rather than the solid disc of one ring - so callers fix the inner ring up + /// relative to the (already-normalized) outer ring instead of normalizing it here. + /// + /// + private static void NormalizeOuterWinding(List ring) + { + if (ComputeSignedArea(ring) < 0f) + { + ring.Reverse(); + } + } + /// /// Computes the signed area of a polygon-like vertex sequence. /// diff --git a/test/DemaConsulting.CanvasNet.Tests/Drawing/PathStrokerTests.cs b/test/DemaConsulting.CanvasNet.Tests/Drawing/PathStrokerTests.cs index cc1b6c3ac..f4c7a3f70 100644 --- a/test/DemaConsulting.CanvasNet.Tests/Drawing/PathStrokerTests.cs +++ b/test/DemaConsulting.CanvasNet.Tests/Drawing/PathStrokerTests.cs @@ -164,6 +164,52 @@ public void PathStroker_Stroke_ClosedRectangle_FillsRingLeavingInteriorAndExteri Assert.Equal((byte)0, surface[0, 0].A); } + /// + /// Proves that two independently-emitted OUTER stroke outlines from ONE + /// call - an open-line outline and an unrelated + /// point-cap circle - whose areas overlap render the overlap region as FULLY FILLED, not + /// as an unfilled hole. + /// + /// + /// Before the winding-normalization fix, an open-line outline was always wound clockwise + /// while a point-cap circle was always wound counterclockwise (see + /// the review thread that reported this defect). emits each stroked + /// subpath's outline as an independent closed subpath in one output , + /// documented to be filled with ; when two such outlines + /// overlap with opposite signed winding, their winding numbers in the overlap cancel to + /// zero and incorrectly renders a hole there instead of + /// solid fill. This path strokes a horizontal line (producing a rectangle-shaped outline, + /// ignoring its round-cap bulges) and, in a second subpath, a single point at the line's + /// midpoint using the SAME (so the resulting cap circle's + /// radius exactly equals the line's half-width) - the circle therefore sits entirely + /// within the line's rectangle. Before the fix, the whole circle region cancels to an + /// unfilled hole; after the fix, it reinforces and stays solidly filled. + /// + [Fact] + public void PathStroker_Stroke_OverlappingLineAndPointCapOutlines_FillsOverlapRegionSolid() + { + // Arrange: a horizontal line from (2,4) to (10,4), plus a zero-length point subpath at + // its midpoint (6,4), both stroked with the same Width: 4 (half-width 2) Round-cap style. + // The point subpath's round cap becomes a radius-2 circle centered at (6,4), which is + // entirely enclosed within the line's rectangle-shaped outline (x:[2,10], y:[2,6]). + var path = new PathBuilder() + .MoveTo(new Vector2(2, 4)) + .LineTo(new Vector2(10, 4)) + .MoveTo(new Vector2(6, 4)) + .LineTo(new Vector2(6, 4)) + .Build(); + var style = new StrokeStyle(4f, cap: LineCap.Round); + + // Act + var surface = RenderStroke(path, style, 13, 8); + + // Assert: the point-cap circle's center - deep inside both the circle and the + // surrounding line rectangle - must render fully opaque, not as an unfilled hole. + Assert.Equal((byte)255, surface[6, 4].A); + Assert.Equal((byte)255, surface[5, 3].A); + Assert.Equal((byte)255, surface[7, 4].A); + } + /// /// Proves that a closed contour's inner (hole) corner is always the geometrically exact /// offset-edge intersection, never the outer style stylization, diff --git a/test/DemaConsulting.CanvasNet.Tests/Drawing/StrokeOutlinerTests.cs b/test/DemaConsulting.CanvasNet.Tests/Drawing/StrokeOutlinerTests.cs index 9e56b909e..b0b5a5130 100644 --- a/test/DemaConsulting.CanvasNet.Tests/Drawing/StrokeOutlinerTests.cs +++ b/test/DemaConsulting.CanvasNet.Tests/Drawing/StrokeOutlinerTests.cs @@ -36,6 +36,86 @@ public void StrokeOutliner_Outline_ClosedSubpath_ProducesTwoCounterWoundRings() Assert.True(GetSignedArea(polygons[0]) * GetSignedArea(polygons[1]) < 0f); } + /// + /// Proves that every independently-emitted OUTER outline shares the same fixed winding + /// direction, regardless of the kind of geometry that produced it: an open-line stroke + /// outline and an unrelated point-cap circle must wind the same way. + /// + /// + /// Before the winding-normalization fix, an open-line outline was always wound one way + /// (clockwise, i.e. negative signed area) while a point-cap circle was always wound the + /// other way (counterclockwise, i.e. positive signed area) - see + /// the review thread that reported this defect. Two such outlines from the same + /// call would then carry opposite signed winding under + /// , so an overlap between them would cancel to a hole + /// instead of reinforcing (unioning). This test proves the two outline kinds now always + /// agree in sign. + /// + [Fact] + public void StrokeOutliner_Outline_OpenLineAndPointCapCircle_ShareSameOuterWinding() + { + // Arrange + var lineStyle = new StrokeStyle(2f, cap: LineCap.Round); + var linePoints = new List { new(2, 4), new(6, 4) }; + var pointStyle = new StrokeStyle(6f, cap: LineCap.Round); + var pointPoints = new List { new(4, 4) }; + + // Act + var linePolygon = Assert.Single(StrokeOutliner.Outline(linePoints, isClosed: false, lineStyle, flattenTolerance: 0.25f)); + var circlePolygon = Assert.Single(StrokeOutliner.Outline(pointPoints, isClosed: false, pointStyle, flattenTolerance: 0.25f)); + + // Assert + Assert.True( + GetSignedArea(linePolygon) * GetSignedArea(circlePolygon) > 0f, + "Expected the open-line outline and the point-cap circle to share the same signed " + + "winding direction, so overlapping strokes reinforce rather than cancel under " + + "FillRule.NonZero."); + } + + /// + /// Proves that a closed contour's OUTER ring normalizes to the same fixed winding + /// direction whether the source contour is authored clockwise or counterclockwise. + /// + /// + /// Before the winding-normalization fix, the outer ring's winding followed whichever + /// direction the source contour happened to be authored in, so a reversed-winding source + /// contour's outer ring would end up wound oppositely from an equivalent + /// forward-authored contour, and could cancel against it under + /// if the two overlapped. + /// + [Fact] + public void StrokeOutliner_Outline_ClosedContourReversedSourceWinding_NormalizesOuterRingConsistently() + { + // Arrange: the same 4x4 square authored once counterclockwise and once clockwise. + var counterClockwise = new List + { + new(2, 2), + new(6, 2), + new(6, 6), + new(2, 6) + }; + var clockwise = new List + { + new(2, 2), + new(2, 6), + new(6, 6), + new(6, 2) + }; + var style = new StrokeStyle(2f); + + // Act + var ccwPolygons = StrokeOutliner.Outline(counterClockwise, isClosed: true, style, flattenTolerance: 0.25f); + var cwPolygons = StrokeOutliner.Outline(clockwise, isClosed: true, style, flattenTolerance: 0.25f); + + // Assert: both outer rings (index 0) share the same signed-winding direction. + Assert.Equal(2, ccwPolygons.Count); + Assert.Equal(2, cwPolygons.Count); + Assert.True( + GetSignedArea(ccwPolygons[0]) * GetSignedArea(cwPolygons[0]) > 0f, + "Expected both source-winding variants' outer rings to share the same signed " + + "winding direction."); + } + /// /// Proves that a miter join within the configured limit emits the sharp intersection /// vertex. @@ -385,6 +465,51 @@ public void StrokeOutliner_Outline_ClosedSquareHalfWidthNearButBelowInradius_Pro } } + /// + /// Proves that a segment spanning near-extreme float32 coordinates - far enough apart + /// that the naive float32 dx*dx + dy*dy computation inside + /// overflows to even + /// though the true edge length remains comfortably finite - still produces a valid, + /// non-degenerate stroke outline. + /// + /// + /// A segment from (-1e20, 0) to (1e20, 0) has a true length of 2e20, + /// itself well within float32's representable range (max ~3.4e38). But squaring that delta + /// in float32 - (2e20)^2 = 4e40 - overflows float32's range before the square root + /// is ever taken, collapsing Vector2.Length() to + /// for a perfectly valid, finite edge. Before the fix, dividing the (finite) delta by that + /// infinite length produced a zero tangent/normal, which silently collapsed the segment's + /// offset to zero and dropped the whole outline (fewer than 3 vertices after + /// deduplication). This test proves the segment now offsets by the full half-width as + /// normal, with no NaN/Infinity coordinates anywhere in the result. + /// + [Fact] + public void StrokeOutliner_Outline_SegmentSpanningExtremeFloat32Coordinates_ProducesValidNonDegenerateOutline() + { + // Arrange: a horizontal segment whose endpoints are individually well within float32's + // representable range, but whose squared length overflows float32 before the fix. + var points = new List { new(-1e20f, 0f), new(1e20f, 0f) }; + var style = new StrokeStyle(2f, cap: LineCap.Butt); + + // Act + var polygons = StrokeOutliner.Outline(points, isClosed: false, style, flattenTolerance: 0.25f); + + // Assert: exactly one valid quadrilateral outline, offset by the full half-width (1) on + // each side, with every coordinate finite. + var polygon = Assert.Single(polygons); + Assert.Equal(4, polygon.Count); + foreach (var vertex in polygon) + { + Assert.True(float.IsFinite(vertex.X), $"Expected a finite X coordinate but found {vertex.X}."); + Assert.True(float.IsFinite(vertex.Y), $"Expected a finite Y coordinate but found {vertex.Y}."); + } + + Assert.Contains(polygon, vertex => MathF.Abs(vertex.Y - 1f) < 1e-6f); + Assert.Contains(polygon, vertex => MathF.Abs(vertex.Y - -1f) < 1e-6f); + Assert.Contains(polygon, vertex => MathF.Abs(vertex.X - -1e20f) < 1e13f); + Assert.Contains(polygon, vertex => MathF.Abs(vertex.X - 1e20f) < 1e13f); + } + private static float GetSignedArea(IReadOnlyList points) { var area = 0f; From 22dc298f89b6c7ac0ea7aec92f22145aa1c1e423 Mon Sep 17 00:00:00 2001 From: Malcolm Nixon Date: Mon, 21 Sep 2026 18:22:02 -0400 Subject: [PATCH 11/13] Fix float32 overflow in StrokeOutliner collinearity/area checks; update docs - Widen AreAllPointsCollinear and ComputeSignedArea to compute vertex differences, squared lengths, normalization, and shoelace cross products in double precision, mirroring the pattern already applied to BuildSegmentFrames/BuildCumulativeLengths. Fixes silent misclassification of large-but-legitimate non-collinear closed contours as degenerate, and unreliable outer/inner winding-sign selection, at near-extreme float32 vertex magnitudes. - ComputeSignedArea now returns double (sign-only consumers), and the outer/inner winding-sign comparison compares signs directly instead of multiplying two areas together, avoiding a secondary overflow/NaN risk. - Add a regression test proving a closed, non-collinear triangle with ~2.5e19-magnitude vertices was misclassified as degenerate pre-fix (1 outline instead of 2) and is correctly outlined as a shell post-fix. - Update docs/verification/canvas-net/drawing/path-stroker.md with all test names added across this session's fix rounds, grouped under new "Concave/Collinear Closed Contours" and "Robustness Against Extreme and Degenerate Numeric Input" subsections. - Update docs/reqstream/canvas-net/drawing/path-stroker.yaml: link the same newly-covered tests to existing requirements, and add new requirements for degenerate/collinear closed contours, overlapping-outline union rendering, inner-corner exact-intersection behavior, and per-vertex concave join resolution. - Update docs/design/canvas-net/drawing/path-stroker.md: document the collinear-closed-contour degenerate case alongside the existing single-point case, and add a "Double-Precision Internal Computations" subsection explaining why several internal computations are deliberately done in double precision despite the public float32-based API. --- .../design/canvas-net/drawing/path-stroker.md | 54 +++++++++- .../canvas-net/drawing/path-stroker.yaml | 102 +++++++++++++++++- .../canvas-net/drawing/path-stroker.md | 44 +++++++- .../Drawing/StrokeOutliner.cs | 81 ++++++++++---- .../Drawing/StrokeOutlinerTests.cs | 82 ++++++++++++++ 5 files changed, 341 insertions(+), 22 deletions(-) diff --git a/docs/design/canvas-net/drawing/path-stroker.md b/docs/design/canvas-net/drawing/path-stroker.md index 318972fe5..33d23e3c8 100644 --- a/docs/design/canvas-net/drawing/path-stroker.md +++ b/docs/design/canvas-net/drawing/path-stroker.md @@ -1,4 +1,4 @@ - + ## PathStroker @@ -165,12 +165,62 @@ instances directly. Every emitted polygon becomes one closed subpath in the resu boundary) and leaving the whole interior filled as solid stroke. - **Degenerate subpaths.** A single point (or a path collapsed to one effective point after duplicate-vertex simplification) renders as a cap-shaped mark: round creates a full circle, - square creates an axis-aligned width-by-width square, and butt creates nothing. + square creates an axis-aligned width-by-width square, and butt creates nothing. This same + single-point handling extends to a closed contour that has fewer than three distinct vertices + after simplification (for example, a closed two-point subpath) - a contour that small cannot + enclose any area, so `StrokeOutliner` treats it exactly as it would treat the equivalent open + multi-segment stroke, with caps at both ends per `style.Cap`, rather than attempting to build a + zero-area shell. +- **Degenerate closed contours: collinear vertices.** A closed contour is equally degenerate when + it has three or more distinct vertices that all lie on a single line - for example, a contour + that traces back and forth along one line before closing. Such a contour also encloses no area, + so building the usual outer/inner offset rings for it would produce two rings with zero signed + area that then get forced into opposite winding, which `FillRule.NonZero` cancels to nothing. + `StrokeOutliner` detects this case up front by checking whether every vertex's perpendicular + distance from the line through the first two distinct vertices is within a small tolerance, and + when so, routes the whole contour through the same open-stroke path used for the + fewer-than-three-vertex case above - the only well-defined non-empty rendering of a closed path + that encloses no area. The helper intentionally removes only redundant consecutive duplicate vertices. It does not try to topologically simplify self-intersections or reorder segments; the contract is to preserve the input path's authored shape, not to reinterpret it. +### Double-Precision Internal Computations + +Several of `StrokeOutliner`'s and `DashSplitter`'s internal computations are deliberately performed +in `double` precision and only narrowed back to `float` (or kept as `double` when only a sign +comparison is needed) at the end, even though the public API is entirely `float`-based +(`System.Numerics.Vector2`). This is a precision safeguard, not a change to the supported +coordinate range: `float` (32-bit) arithmetic on values that are each individually well within +`float`'s representable range can still overflow to `Infinity` or `NaN` partway through a +computation - most commonly when a squared distance, a cross-product term, or an accumulated sum +of several such terms exceeds `float.MaxValue` even though the true, final mathematical result +would not. An overflowed or `NaN` intermediate value silently produces a degenerate result (a +zeroed tangent/normal, a misclassified degenerate contour, or an unreliable winding sign) rather +than a visible error, so the safest place to avoid it is inside the computation itself, not at its +call sites. Concretely, this applies to: + +- **Per-segment tangent/normal computation** (edge delta and length), so an edge spanning + near-extreme coordinates still offsets correctly instead of collapsing to a zero-length + tangent/normal. +- **Collinearity testing for a closed contour** (vertex differences, squared length, direction + normalization, and perpendicular-distance cross products), so a legitimately non-collinear large + contour is not misclassified as degenerate merely because an intermediate squared length + overflowed. +- **Signed-area computation** (the shoelace cross-product terms and their running sum), used both + to pick which side of a closed contour is the outer ring and to confirm the outer and inner rings + end up with opposite winding, so that decision remains reliable even for contours near the edges + of the representable coordinate range. +- **Dash-length accumulation and dash-offset phase location** in `DashSplitter`, so a very long + polyline, a very large dash pattern, or a dash offset far larger in magnitude than the dash + pattern all resolve to the correct visible phase instead of an overflowed or oscillating result. + +Every one of these call sites only ever needs a sign, a ratio, or a normalized direction from the +result - never the literal double-precision magnitude exposed back through the public API - so +computing in `double` internally is a pure precision safeguard with no observable effect on +ordinary, non-extreme stroke geometry. + ### Complexity The total conversion cost is the sum of three bounded passes over the path data. Flattening is diff --git a/docs/reqstream/canvas-net/drawing/path-stroker.yaml b/docs/reqstream/canvas-net/drawing/path-stroker.yaml index fce222ed3..9d020bf4b 100644 --- a/docs/reqstream/canvas-net/drawing/path-stroker.yaml +++ b/docs/reqstream/canvas-net/drawing/path-stroker.yaml @@ -1,5 +1,5 @@ --- -# cspell:ignore Outliner strokable +# cspell:ignore Outliner strokable inradius # Software Unit Requirements for PathStroker # # These requirements describe the design-level behavior of the PathStroker unit within the @@ -40,6 +40,7 @@ sections: - PathStroker_Stroke_HorizontalLineButtCap_FillsExactRectangleNoExtension - PathStroker_Stroke_HorizontalLineRoundCap_FillsRectanglePlusSemicircularEnds - PathStroker_Stroke_HorizontalLineSquareCap_FillsRectanglePlusHalfWidthExtension + - StrokeOutliner_Outline_RoundCapAtTypicalScale_MatchesExpectedSegmentCount - id: CanvasNet-Drawing-PathStroker-Joins title: >- @@ -53,6 +54,8 @@ sections: - PathStroker_Stroke_RightAngleCornerMiterJoin_FillsSharpMiteredCorner - PathStroker_Stroke_RightAngleCornerRoundJoin_FillsRoundedCorner - PathStroker_Stroke_RightAngleCornerBevelJoin_FillsFlatBeveledCorner + - StrokeOutliner_Outline_RoundJoinAtExtremeScale_ProducesCurvedNotStraightJoin + - StrokeOutliner_Outline_RoundJoinSmallSweepAtExtremeScale_ProducesMultiSegmentCurve - id: CanvasNet-Drawing-PathStroker-MiterLimit title: >- @@ -76,6 +79,68 @@ sections: inner boundaries. tests: - PathStroker_Stroke_ClosedRectangle_FillsRingLeavingInteriorAndExteriorUnfilled + - StrokeOutliner_Outline_ClosedSquareHalfWidthExceedsInradius_ProducesNoInvalidHole + - StrokeOutliner_Outline_ClosedSquareHalfWidthNearButBelowInradius_ProducesValidHole + + - id: CanvasNet-Drawing-PathStroker-DegenerateClosedContours + title: >- + The PathStroker class shall render a degenerate closed contour - one with fewer + than three distinct vertices, or with three or more vertices that all lie on a + single line - as a visible stroke rather than an empty result. + justification: | + A closed contour that encloses no area still represents a visible line the + caller asked to stroke; silently rendering nothing for a degenerate closed + contour would be surprising and inconsistent with how a stroked open line or + point behaves. + tests: + - PathStroker_Stroke_ClosedTwoPointSubpath_FillsStrokedSegmentAreaNotEmpty + - PathStroker_Stroke_ClosedThreePointCollinearSubpath_FillsStrokedSegmentAreaNotEmpty + - StrokeOutliner_Outline_ThreePointCollinearClosedContour_ProducesVisibleStroke + - StrokeOutliner_Outline_CollinearClosedContourWithDuplicatePoints_ProducesVisibleStroke + + - id: CanvasNet-Drawing-PathStroker-OverlapUnion + title: >- + The PathStroker class shall render the overlapping region of two independently + emitted outer stroke outlines produced by the same Stroke call as solid union + fill, not as a canceled hole. + justification: | + Callers expect two overlapping strokes from a single stroking pass (for example + a stroked line whose point-cap circle overlaps a stroked closed contour) to + reinforce each other visually; incorrectly canceling their overlap to a hole + under the nonzero fill rule would be a visibly wrong rendering artifact. + tests: + - PathStroker_Stroke_OverlappingLineAndPointCapOutlines_FillsOverlapRegionSolid + - StrokeOutliner_Outline_OpenLineAndPointCapCircle_ShareSameOuterWinding + - StrokeOutliner_Outline_ClosedContourReversedSourceWinding_NormalizesOuterRingConsistently + + - id: CanvasNet-Drawing-PathStroker-InnerCornerExactIntersection + title: >- + The PathStroker class shall render a closed contour's inner stroke corner as the + exact offset-edge intersection point, distinct from the outer corner's styled + join (miter, round, or bevel). + justification: | + A closed contour's inner boundary is a hole edge, not a visible corner; applying + the outer join style to it would round or bevel a filled interior edge that + should instead follow the exact geometric intersection of the two adjoining + offset edges, regardless of which join style the caller configured. + tests: + - PathStroker_Stroke_ClosedRectangleBevelJoin_InnerCornerMatchesExactIntersectionNotBevel + - PathStroker_Stroke_ClosedRectangleRoundJoin_InnerCornerMatchesExactIntersectionNotArc + - PathStroker_Stroke_ClosedRectangleMiterJoin_InnerCornerMatchesExactIntersection + + - id: CanvasNet-Drawing-PathStroker-ConcaveJoinResolution + title: >- + The PathStroker class shall resolve each closed contour vertex's join + independently based on that vertex's own local convexity, so styled joins and + exact-intersection corners remain correct even when a contour's convexity varies + along its length (for example, a concave polygon). + justification: | + Real-world closed shapes are frequently concave; a caller must see the correct + join or exact-intersection corner at every vertex of such a shape, not only at + vertices of a globally convex contour. + tests: + - PathStroker_Stroke_ConcaveClosedContourBevelJoin_AppliesJoinsByLocalVertexConvexity + - StrokeOutliner_Outline_ConcaveClosedContourBevelJoin_ResolvesJoinPerVertexFromLocalTurn - id: CanvasNet-Drawing-PathStroker-Dashing title: >- @@ -87,6 +152,39 @@ sections: tests: - PathStroker_Stroke_DashedLine_FillsOnlyOnSegmentsLeavingGapsUnfilled + - id: CanvasNet-Drawing-PathStroker-DashRobustness + title: >- + The PathStroker class shall produce a correct, promptly-completing dashed + stroke result for dash arrays and dash offsets at the numeric edges of the + supported range, including a dash offset far larger in magnitude than the dash + pattern and a tiny negative offset applied against a very large dash pattern. + justification: | + Callers may supply dash arrays and offsets derived from arbitrary upstream data; + such pathological but valid combinations must still render the correct visible + dash phase and must never hang, rather than only being handled for typical + in-range values. + tests: + - PathStroker_Stroke_OverflowProneDashArrayWithNegativeOffset_CompletesWithoutHanging + - DashSplitter_Split_OverflowProneDashArrayWithNegativeOffset_CompletesWithoutHanging + - DashSplitter_Split_TinyNegativeOffsetAgainstHugePattern_ProducesCorrectPhase + - DashSplitter_Split_TinyNegativeOffsetAgainstAsymmetricHugePattern_ProducesCorrectPhase + + - id: CanvasNet-Drawing-PathStroker-NumericRobustness + title: >- + The PathStroker class shall produce a correct, finite stroke outline for + segments and closed contours whose vertex coordinates lie near the edges of the + supported floating-point range, rather than collapsing to a degenerate, NaN, or + Infinity result. + justification: | + Callers may supply geometry derived from upstream transforms or user input whose + coordinates approach the representable range's edges; a stroke result must + remain a valid, finite outline for any such legitimately large but finite input, + not merely for typical small-scale coordinates. + tests: + - StrokeOutliner_Outline_SegmentSpanningExtremeFloat32Coordinates_ProducesValidNonDegenerateOutline + - StrokeOutliner_Outline_ClosedContourWithExtremeFloat32NonCollinearCoordinates_ProducesValidShellOutline + - DashSplitter_Split_EdgeSpanningExtremeFloat32Coordinates_CompletesWithFiniteSegments + - id: CanvasNet-Drawing-PathStroker-DegenerateSubpaths title: >- The PathStroker class shall stroke a zero-length or single-point subpath as a @@ -173,6 +271,8 @@ sections: - DashSplitter_Split_ClosedPolylineDashWrappingSeam_StitchesSegmentAcrossStartPoint - DashSplitter_Split_PatternLongerThanPolyline_ReturnsSinglePartialOnSegment - DashSplitter_Split_AllZeroDashArray_TreatedAsSolid + - DashSplitter_Split_FineDashPatternOnVeryLongPath_CompletesWithCorrectSegments + - DashSplitter_Split_ZeroLengthLeadingDashEntryOnZeroLengthPath_StartsInFollowingOffEntry - id: CanvasNet-Drawing-PathStroker-ShellWinding title: >- diff --git a/docs/verification/canvas-net/drawing/path-stroker.md b/docs/verification/canvas-net/drawing/path-stroker.md index ba4ec6d7f..3d3f441d0 100644 --- a/docs/verification/canvas-net/drawing/path-stroker.md +++ b/docs/verification/canvas-net/drawing/path-stroker.md @@ -77,6 +77,48 @@ region solidly filled rather than as a winding-cancellation hole; dashed lines m visible runs; degenerate subpaths must follow cap semantics exactly; and an empty path must remain a no-op. +#### Concave/Collinear Closed Contours + +- `PathStroker_Stroke_ClosedRectangleBevelJoin_InnerCornerMatchesExactIntersectionNotBevel` +- `PathStroker_Stroke_ClosedRectangleRoundJoin_InnerCornerMatchesExactIntersectionNotArc` +- `PathStroker_Stroke_ClosedRectangleMiterJoin_InnerCornerMatchesExactIntersection` +- `PathStroker_Stroke_ConcaveClosedContourBevelJoin_AppliesJoinsByLocalVertexConvexity` +- `PathStroker_Stroke_ClosedTwoPointSubpath_FillsStrokedSegmentAreaNotEmpty` +- `PathStroker_Stroke_ClosedThreePointCollinearSubpath_FillsStrokedSegmentAreaNotEmpty` +- `StrokeOutliner_Outline_ConcaveClosedContourBevelJoin_ResolvesJoinPerVertexFromLocalTurn` +- `StrokeOutliner_Outline_ThreePointCollinearClosedContour_ProducesVisibleStroke` +- `StrokeOutliner_Outline_CollinearClosedContourWithDuplicatePoints_ProducesVisibleStroke` + +These tests verify that a closed contour's forced-exact-intersection inner corner is used in place +of its styled join (Miter, Round, or Bevel) regardless of which join style is configured; that join +resolution for a concave polygon is decided per-vertex from local convexity/turn direction rather +than by any single global winding decision, so styling stays correct even when convexity flips +along the contour; and that a degenerate closed contour - a 2-point subpath, a 3+ point subpath +whose distinct points are all collinear, or a collinear subpath containing duplicate points - still +renders a visible stroke rather than vanishing to nothing. + +#### Robustness Against Extreme and Degenerate Numeric Input + +- `PathStroker_Stroke_OverflowProneDashArrayWithNegativeOffset_CompletesWithoutHanging` +- `DashSplitter_Split_OverflowProneDashArrayWithNegativeOffset_CompletesWithoutHanging` +- `DashSplitter_Split_TinyNegativeOffsetAgainstHugePattern_ProducesCorrectPhase` +- `DashSplitter_Split_TinyNegativeOffsetAgainstAsymmetricHugePattern_ProducesCorrectPhase` +- `DashSplitter_Split_ZeroLengthLeadingDashEntryOnZeroLengthPath_StartsInFollowingOffEntry` +- `DashSplitter_Split_EdgeSpanningExtremeFloat32Coordinates_CompletesWithFiniteSegments` +- `StrokeOutliner_Outline_RoundJoinAtExtremeScale_ProducesCurvedNotStraightJoin` +- `StrokeOutliner_Outline_RoundCapAtTypicalScale_MatchesExpectedSegmentCount` +- `StrokeOutliner_Outline_RoundJoinSmallSweepAtExtremeScale_ProducesMultiSegmentCurve` +- `StrokeOutliner_Outline_ClosedContourWithExtremeFloat32NonCollinearCoordinates_ProducesValidShellOutline` + +These tests prove that dash-offset phase computation, dash extraction, round join/cap +tessellation, and closed-contour collinearity/winding classification all remain correct and +terminate promptly even when intermediate arithmetic would naively overflow or underflow float32 - +covering a huge dash pattern combined with a tiny negative offset (symmetric and asymmetric +patterns), an edge or closed contour spanning near-extreme float32 coordinate magnitudes, a +zero-length leading dash-array entry evaluated against a zero-length path, and a round join/cap +tessellated at extreme geometric scale - rather than hanging, misclassifying the contour as +degenerate, or producing `NaN`/`Infinity` coordinates. + #### Public API Validation - `PathStroker_Stroke_NullPath_ThrowsArgumentNullException` @@ -137,4 +179,4 @@ _PathStroker Unit Design_ (`../../../design/canvas-net/drawing/path-stroker.md`) analysis and code review only. There are intentionally **no** timing-based tests, elapsed-time assertions, or `Stopwatch`-based guards in this unit's automated verification because those are not stable compliance evidence on heterogeneous CI hardware. - + diff --git a/src/DemaConsulting.CanvasNet/Drawing/StrokeOutliner.cs b/src/DemaConsulting.CanvasNet/Drawing/StrokeOutliner.cs index 1a0882774..958dcad0e 100644 --- a/src/DemaConsulting.CanvasNet/Drawing/StrokeOutliner.cs +++ b/src/DemaConsulting.CanvasNet/Drawing/StrokeOutliner.cs @@ -115,6 +115,20 @@ private static bool IsDegenerateClosedContour(IReadOnlyList points) => /// . If every point coincides with points[0] (no /// usable direction exists), the contour is fully collapsed and therefore trivially /// collinear. + /// + /// Every vertex difference, squared-length, normalization, and cross-product used here is + /// computed in precision rather than via + /// arithmetic and /: + /// for a contour spanning near-extreme float32 coordinates (e.g. vertices near + /// ยฑ3e38), the float32 dx*dx + dy*dy computation in + /// candidate.LengthSquared() overflows to well + /// before the true squared length would, and normalizing an overflowed vector produces + /// components. Because a NaN comparison is always false, that + /// would make every point spuriously pass the perpendicular-distance check below and + /// misclassify a legitimately non-collinear large contour as degenerate. This is the same + /// class of float32-overflow bug already fixed for edge-length computations in + /// and . + /// /// private static bool AreAllPointsCollinear(IReadOnlyList points) { @@ -124,28 +138,37 @@ private static bool AreAllPointsCollinear(IReadOnlyList points) } var origin = points[0]; - var direction = Vector2.Zero; + var directionX = 0.0; + var directionY = 0.0; + var haveDirection = false; + const double nearZeroDistanceSquared = (double)NearZeroDistance * NearZeroDistance; for (var i = 1; i < points.Count; i++) { - var candidate = points[i] - origin; - if (candidate.LengthSquared() > NearZeroDistance * NearZeroDistance) + var candidateX = (double)points[i].X - origin.X; + var candidateY = (double)points[i].Y - origin.Y; + if (candidateX * candidateX + candidateY * candidateY > nearZeroDistanceSquared) { - direction = candidate; + directionX = candidateX; + directionY = candidateY; + haveDirection = true; break; } } - if (direction == Vector2.Zero) + if (!haveDirection) { return true; } - var normalizedDirection = direction / direction.Length(); + var directionLength = Math.Sqrt(directionX * directionX + directionY * directionY); + var normalizedDirectionX = directionX / directionLength; + var normalizedDirectionY = directionY / directionLength; for (var i = 1; i < points.Count; i++) { - var offset = points[i] - origin; - var perpendicularDistance = normalizedDirection.X * offset.Y - normalizedDirection.Y * offset.X; - if (MathF.Abs(perpendicularDistance) > NearZeroDistance) + var offsetX = (double)points[i].X - origin.X; + var offsetY = (double)points[i].Y - origin.Y; + var perpendicularDistance = normalizedDirectionX * offsetY - normalizedDirectionY * offsetX; + if (Math.Abs(perpendicularDistance) > NearZeroDistance) { return false; } @@ -301,7 +324,7 @@ private static List> CreateClosedStrokePolygons( } var area = ComputeSignedArea(points); - var outerSideSign = area >= 0f ? -1f : +1f; + var outerSideSign = area >= 0.0 ? -1f : +1f; var outerRing = BuildClosedSide(points, outerSideSign, style, halfWidth, flattenTolerance, out _); if (outerRing.Count < 3) @@ -342,9 +365,13 @@ private static List> CreateClosedStrokePolygons( // Regardless of how many vertices were locally reflex on each ring, the two rings must // still end up with opposite winding for FillRule.NonZero to render the band between them // (rather than the solid disc of one ring or the empty complement) - flip the inner ring - // if the constructed rings happen to share the same winding sign. - - if (ComputeSignedArea(outerRing) * ComputeSignedArea(innerRing) > 0f) + // if the constructed rings happen to share the same winding sign. Compare signs directly + // (rather than multiplying the two areas together and checking > 0) so that two + // individually-finite-but-extreme double areas can never spuriously overflow their + // product to Infinity or (Infinity * 0) to NaN. + var outerArea = ComputeSignedArea(outerRing); + var innerArea = ComputeSignedArea(innerRing); + if (outerArea != 0.0 && innerArea != 0.0 && Math.Sign(outerArea) == Math.Sign(innerArea)) { innerRing.Reverse(); } @@ -1014,7 +1041,7 @@ private static float NormalizePositiveAngle(float angle) /// private static void NormalizeOuterWinding(List ring) { - if (ComputeSignedArea(ring) < 0f) + if (ComputeSignedArea(ring) < 0.0) { ring.Reverse(); } @@ -1023,16 +1050,34 @@ private static void NormalizeOuterWinding(List ring) /// /// Computes the signed area of a polygon-like vertex sequence. /// - private static float ComputeSignedArea(IReadOnlyList points) + /// + /// Both the shoelace cross-product terms and their running sum are computed and + /// accumulated in precision, and the result is returned as + /// rather than narrowed back to : for + /// vertices near extreme float32 magnitudes (e.g. close to float.MaxValue), the + /// float32 products current.X * next.Y and current.Y * next.X - and their + /// running sum across every vertex, and even the true signed area itself for a large + /// enough contour - can overflow float32's finite range well before the true magnitude + /// would, even though the same computation in double precision remains finite. Every + /// caller of this method only ever inspects the SIGN of the result (never its magnitude), + /// so returning the full-precision double lets callers make a correct sign decision even + /// when the true area is too large to represent as a finite . An + /// overflowed or NaN result here would silently pick the wrong outer-ring side sign in + /// and defeat the opposite-winding check in + /// (a NaN comparison is always false) - the same class + /// of float32-overflow bug already fixed for edge-length computations in + /// and . + /// + private static double ComputeSignedArea(IReadOnlyList points) { - var area = 0f; + var area = 0.0; for (var i = 0; i < points.Count; i++) { var current = points[i]; var next = points[(i + 1) % points.Count]; - area += current.X * next.Y - current.Y * next.X; + area += (double)current.X * next.Y - (double)current.Y * next.X; } - return area / 2f; + return area / 2.0; } } diff --git a/test/DemaConsulting.CanvasNet.Tests/Drawing/StrokeOutlinerTests.cs b/test/DemaConsulting.CanvasNet.Tests/Drawing/StrokeOutlinerTests.cs index b0b5a5130..01cf4630a 100644 --- a/test/DemaConsulting.CanvasNet.Tests/Drawing/StrokeOutlinerTests.cs +++ b/test/DemaConsulting.CanvasNet.Tests/Drawing/StrokeOutlinerTests.cs @@ -510,6 +510,70 @@ public void StrokeOutliner_Outline_SegmentSpanningExtremeFloat32Coordinates_Prod Assert.Contains(polygon, vertex => MathF.Abs(vertex.X - 1e20f) < 1e13f); } + /// + /// Proves that a closed, genuinely non-collinear contour spanning near-extreme float32 + /// coordinates - large enough that the naive float32 dx*dx + dy*dy computation + /// inside overflows to + /// - is still correctly routed through + /// CreateClosedStrokePolygons (an outer ring plus a counter-wound inner ring), NOT + /// misclassified as a degenerate/collinear closed contour and collapsed to the open-stroke + /// path. + /// + /// + /// The contour is a right triangle with leg length 2.5e19. Its true (double + /// precision) leg length and enclosed area remain comfortably finite, and the three + /// vertices are unambiguously non-collinear. But squaring that leg length in float32 - + /// (2.5e19)^2 = 6.25e38 - overflows float32's representable range + /// (max ~3.4e38) before AreAllPointsCollinear's direction-normalization step can + /// even take a square root, collapsing the normalized direction to (0, 0). Every + /// subsequent perpendicular-distance check against that zeroed direction then evaluates to + /// zero, so before the fix, this perfectly ordinary large triangle was misclassified as a + /// degenerate/collinear closed contour and silently rendered via the open-stroke path + /// (a single band with caps at both ends) instead of a proper shell with a hole. + /// + [Fact] + public void StrokeOutliner_Outline_ClosedContourWithExtremeFloat32NonCollinearCoordinates_ProducesValidShellOutline() + { + // Arrange: a right triangle whose leg lengths are individually well within float32's + // representable range, but whose squared length (as computed by Vector2.LengthSquared()) + // overflows float32 before the fix. + var points = new List + { + new(0f, 0f), + new(2.5e19f, 0f), + new(0f, 2.5e19f) + }; + var style = new StrokeStyle(4f); + + // Act + var polygons = StrokeOutliner.Outline(points, isClosed: true, style, flattenTolerance: 0.25f); + + // Assert: correctly classified as a genuine (non-degenerate) closed contour, producing an + // outer ring and a counter-wound inner ring (the stroked band with its hole) - NOT the + // single open-stroke band that the pre-fix float32 overflow in AreAllPointsCollinear would + // have misclassified this large-but-legitimate triangle into producing. + Assert.Equal(2, polygons.Count); + + foreach (var polygon in polygons) + { + Assert.True(polygon.Count >= 3, "Expected each ring to be a valid polygon."); + foreach (var vertex in polygon) + { + Assert.True(float.IsFinite(vertex.X), $"Expected a finite X coordinate but found {vertex.X}."); + Assert.True(float.IsFinite(vertex.Y), $"Expected a finite Y coordinate but found {vertex.Y}."); + } + } + + // The outer and inner rings must be non-zero-area and oppositely wound (the shell/hole + // invariant), using a double-precision area computation so the assertion itself cannot be + // defeated by the same float32 overflow being proven fixed above. + var outerArea = GetSignedAreaDouble(polygons[0]); + var innerArea = GetSignedAreaDouble(polygons[1]); + Assert.True( + outerArea != 0.0 && innerArea != 0.0 && Math.Sign(outerArea) != Math.Sign(innerArea), + $"Expected oppositely-wound non-zero rings, but got outerArea={outerArea}, innerArea={innerArea}."); + } + private static float GetSignedArea(IReadOnlyList points) { var area = 0f; @@ -523,6 +587,24 @@ private static float GetSignedArea(IReadOnlyList points) return area / 2f; } + /// + /// Double-precision equivalent of , used by tests exercising + /// near-extreme float32 coordinates where the float32 shoelace computation itself would + /// overflow before the assertion could even inspect the true sign. + /// + private static double GetSignedAreaDouble(IReadOnlyList points) + { + var area = 0.0; + for (var i = 0; i < points.Count; i++) + { + var current = points[i]; + var next = points[(i + 1) % points.Count]; + area += (double)current.X * next.Y - (double)current.Y * next.X; + } + + return area / 2.0; + } + /// /// Determines whether a point lies within a simple polygon using the standard ray-casting /// (even-odd crossing) test. From 05c274da4a9a90785d23df87266cbfb824637621 Mon Sep 17 00:00:00 2001 From: Malcolm Nixon Date: Mon, 21 Sep 2026 18:34:34 -0400 Subject: [PATCH 12/13] Link new PathStroker unit requirements under Drawing subsystem PathStroke The 6 new unit-level requirements added for degenerate-closed-contour, overlap-union, inner-corner-exact-intersection, concave-join-resolution, dash-robustness, and numeric-robustness behavior were unreachable from any quality/system-tagged requirement, which the CI 'Build Documents' job's reqstream --enforce orphan check correctly flagged. Link them as children of the existing CanvasNet-Drawing-PathStroke subsystem requirement, alongside the other PathStroker unit requirements it already decomposes into. --- docs/reqstream/canvas-net/drawing.yaml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/docs/reqstream/canvas-net/drawing.yaml b/docs/reqstream/canvas-net/drawing.yaml index 420c04a63..efb05f1c2 100644 --- a/docs/reqstream/canvas-net/drawing.yaml +++ b/docs/reqstream/canvas-net/drawing.yaml @@ -98,6 +98,12 @@ sections: - CanvasNet-Drawing-PathStroker-DegenerateSubpaths - CanvasNet-Drawing-PathStroker-ClosedContours - CanvasNet-Drawing-PathStroker-ShellWinding + - CanvasNet-Drawing-PathStroker-DegenerateClosedContours + - CanvasNet-Drawing-PathStroker-OverlapUnion + - CanvasNet-Drawing-PathStroker-InnerCornerExactIntersection + - CanvasNet-Drawing-PathStroker-ConcaveJoinResolution + - CanvasNet-Drawing-PathStroker-DashRobustness + - CanvasNet-Drawing-PathStroker-NumericRobustness tests: - PathStroker_Stroke_HorizontalLineButtCap_FillsExactRectangleNoExtension - PathStroker_Stroke_HorizontalLineRoundCap_FillsRectanglePlusSemicircularEnds From fd6a735d2ac73b7940d77777a42d36b51e292ea9 Mon Sep 17 00:00:00 2001 From: Malcolm Nixon Date: Mon, 21 Sep 2026 18:57:34 -0400 Subject: [PATCH 13/13] Fix DashSplitter dash-boundary point interpolation to avoid depending on Vector2.Lerp's documented float32 subtraction formula GetPointAtDistance previously called Vector2.Lerp(edgeStart, edgeEnd, t) to turn a distance-along-path back into a point. Vector2.Lerp's documented contract computes start + (end - start) * amount with the subtraction performed on float32 endpoints: for an edge from -float.MaxValue to float.MaxValue, that subtraction overflows to +Infinity even though the true (double-precision) delta is finite, which would poison every downstream coordinate of the interpolated point with Infinity/NaN. Interpolate each coordinate explicitly as start + (end - start) * t in double precision before narrowing back to float, so the result no longer depends on whichever internal formula a given runtime happens to use for Vector2.Lerp. Added a regression test exercising a dash-interval boundary landing strictly inside a -float.MaxValue to float.MaxValue edge, asserting the interpolated point is finite and numerically matches the analytically expected position. Final sweep: reviewed every remaining Vector2/float subtraction, multiplication, division, Length()/LengthSquared()/Distance() call, and double-to-float narrowing in DashSplitter.cs and StrokeOutliner.cs. No further overflow-prone operations were found beyond what prior rounds already fixed; the small vertex-plus-halfWidth-offset computations used throughout StrokeOutliner's join/cap logic are bounded perturbations (not overflow-prone) and any precision loss there at astronomical coordinate magnitudes is an inherent limit of float32 vertex storage, not a fixable arithmetic-ordering bug. --- .../Drawing/DashSplitter.cs | 21 +++++++- .../Drawing/DashSplitterTests.cs | 52 +++++++++++++++++++ 2 files changed, 72 insertions(+), 1 deletion(-) diff --git a/src/DemaConsulting.CanvasNet/Drawing/DashSplitter.cs b/src/DemaConsulting.CanvasNet/Drawing/DashSplitter.cs index b21e0950c..46bb6a404 100644 --- a/src/DemaConsulting.CanvasNet/Drawing/DashSplitter.cs +++ b/src/DemaConsulting.CanvasNet/Drawing/DashSplitter.cs @@ -517,6 +517,23 @@ private static List ExtractIntervalPolyline( /// resuming the edge-bracket search from wherever the previous call left off - rather than /// restarting from edge zero - keeps the search across all calls linear in the number of /// polyline edges instead of quadratic in edges times calls. + /// + /// The interpolated point's X and Y coordinates are each computed as + /// start + (end - start) * t in precision rather than via + /// . The public contract of + /// is documented as computing + /// start + (end - start) * amount with the subtraction performed on float32 + /// endpoints, which for an edge spanning near-extreme float32 coordinates (e.g. one + /// endpoint near and the other near ) + /// would overflow that subtraction to even though the + /// true delta is finite in double precision - the same class of float32-overflow bug + /// already fixed for edge-length accumulation in . + /// Computing the delta explicitly in double before narrowing the final result back to + /// guarantees correctness for such edges regardless of how any + /// given runtime happens to implement + /// internally, rather than depending on an implementation detail outside its documented + /// contract. + /// /// private static Vector2 GetPointAtDistance( IReadOnlyList points, @@ -553,7 +570,9 @@ private static Vector2 GetPointAtDistance( } var t = (distance - startLength) / edgeLength; - return Vector2.Lerp(edgeStart, edgeEnd, (float)t); + var x = edgeStart.X + ((double)edgeEnd.X - edgeStart.X) * t; + var y = edgeStart.Y + ((double)edgeEnd.Y - edgeStart.Y) * t; + return new Vector2((float)x, (float)y); } /// diff --git a/test/DemaConsulting.CanvasNet.Tests/Drawing/DashSplitterTests.cs b/test/DemaConsulting.CanvasNet.Tests/Drawing/DashSplitterTests.cs index 0ea6ede58..54540a224 100644 --- a/test/DemaConsulting.CanvasNet.Tests/Drawing/DashSplitterTests.cs +++ b/test/DemaConsulting.CanvasNet.Tests/Drawing/DashSplitterTests.cs @@ -1,6 +1,8 @@ using System.Numerics; using DemaConsulting.CanvasNet.Drawing; +// cspell:ignore Lerp + namespace DemaConsulting.CanvasNet.Tests.Drawing; /// @@ -346,4 +348,54 @@ public void DashSplitter_Split_EdgeSpanningExtremeFloat32Coordinates_CompletesWi } } } + + /// + /// Proves that a dash interval boundary landing strictly inside an edge spanning extreme + /// float32 coordinates (from - to + /// ) produces a FINITE, numerically reasonable interpolated + /// point, rather than a point with /NaN + /// coordinates. + /// + /// + /// 's documented contract computes + /// start + (end - start) * t with the end - start subtraction performed on + /// float32 endpoints: for this edge, that subtraction is + /// float.MaxValue - (-float.MaxValue), which overflows float32's representable + /// range to , even though the true (double-precision) + /// delta - 2 * float.MaxValue - is finite. Relying on + /// for this step would therefore be + /// fragile: its documented formula would poison the interpolated point with + /// Infinity/NaN for this edge if evaluated literally as documented, even + /// though the edge itself is entirely legal and finite (whether or not a given runtime's + /// internal implementation happens to avoid that in practice is not part of its documented + /// contract). Interpolating each coordinate explicitly in + /// precision before narrowing back to guarantees correctness + /// regardless of that implementation detail. + /// + [Fact] + public void DashSplitter_Split_DashBoundaryInsideExtremeFloat32Edge_ProducesFinitePoint() + { + // Arrange: a single edge from -float.MaxValue to float.MaxValue (length ~6.8e38, finite in + // double precision). A dash pattern of [1e38 (on), 1e38 (off)] places the first "on"/"off" + // boundary at distance 1e38, which - since the edge is ~6.8e38 long - falls strictly + // inside the edge, forcing GetPointAtDistance to interpolate an interior point rather than + // simply returning one of the edge's own endpoints. + var points = new List { new(-float.MaxValue, 0f), new(float.MaxValue, 0f) }; + + // Act + var segments = DashSplitter.Split(points, isClosed: false, dashArray: [1e38f, 1e38f], dashOffset: 0f); + + // Assert: the first "on" segment runs from the edge start to the first dash boundary at + // distance 1e38 (strictly inside the edge), so its final point is the interpolated one. + var segment = Assert.Single(segments, s => s.Points[0] == points[0]); + var interpolated = segment.Points[^1]; + Assert.True(float.IsFinite(interpolated.X), $"Expected finite X but got {interpolated.X}"); + Assert.True(float.IsFinite(interpolated.Y), $"Expected finite Y but got {interpolated.Y}"); + + const double edgeLength = 2d * float.MaxValue; + const double expectedT = 1e38d / edgeLength; + var expectedX = -(double)float.MaxValue + edgeLength * expectedT; + Assert.Equal(expectedX, interpolated.X, Math.Abs(expectedX) * 1e-5); + Assert.Equal(0f, interpolated.Y); + } }