diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml index a87105fec..5d71e2069 100644 --- a/.github/workflows/build.yaml +++ b/.github/workflows/build.yaml @@ -227,6 +227,8 @@ jobs: path: | src/DemaConsulting.CanvasNet/bin/Release/*.nupkg src/DemaConsulting.CanvasNet/bin/Release/*.snupkg + src/DemaConsulting.CanvasNet.Svg/bin/Release/*.nupkg + src/DemaConsulting.CanvasNet.Svg/bin/Release/*.snupkg # Runs CodeQL security and quality analysis, gathering results to include # in the code quality report. diff --git a/.reviewmark.yaml b/.reviewmark.yaml index 6d415eb33..55f45cbd6 100644 --- a/.reviewmark.yaml +++ b/.reviewmark.yaml @@ -99,7 +99,7 @@ reviews: - "docs/reqstream/canvas-net.yaml" paths: - "requirements.yaml" # root requirements file - - "docs/reqstream/**/*.yaml" # all requirements files + - "docs/reqstream/canvas-net/**/*.yaml" # all requirements files # CanvasNet-Canvas Review (one per subsystem) - id: CanvasNet-Canvas @@ -252,39 +252,6 @@ reviews: - "test/DemaConsulting.CanvasNet.Tests/Codecs/GifCodecTests.cs" # unit tests - "test/DemaConsulting.CanvasNet.Tests/Codecs/GifFixtureTests.cs" # fixture conformance tests - # CanvasNet-Codecs-SvgCodec Review (one per unit) - - id: CanvasNet-Codecs-SvgCodec - title: Review that CanvasNet Codecs SvgCodec Implementation is Correct - context: - - "docs/design/canvas-net.md" - - "docs/reqstream/canvas-net.yaml" - - "docs/design/canvas-net/codecs.md" - - "docs/reqstream/canvas-net/codecs.yaml" - paths: - - "docs/reqstream/canvas-net/codecs/svg-codec.yaml" # unit requirements - - "docs/design/canvas-net/codecs/svg-codec.md" # unit design - - "docs/verification/canvas-net/codecs/svg-codec.md" # unit verification - - "docs/sysml2/model/canvas-net/codecs/svg-codec.sysml" # unit SysML2 model - - "src/DemaConsulting.CanvasNet/Codecs/SvgCodec.cs" # unit source (public API entry point) - - "src/DemaConsulting.CanvasNet/Codecs/Svg/**/*.cs" # unit source (partial-class implementation files) - - "src/DemaConsulting.CanvasNet/Codecs/Svg/SvgCodec.Filters.ColorMatrix.cs" # phase 5 filter partial - - "src/DemaConsulting.CanvasNet/Codecs/Svg/SvgCodec.Filters.ComponentTransfer.cs" # phase 5 filter partial - - "src/DemaConsulting.CanvasNet/Codecs/Svg/SvgCodec.Filters.Morphology.cs" # phase 5 filter partial - - "src/DemaConsulting.CanvasNet/Codecs/Svg/SvgCodec.Filters.Convolution.cs" # phase 5 filter partial - - "src/DemaConsulting.CanvasNet/Codecs/Svg/SvgCodec.Filters.DisplacementMap.cs" # phase 5 filter partial - - "src/DemaConsulting.CanvasNet/Codecs/Svg/SvgCodec.Filters.Tile.cs" # phase 5 filter partial - - "src/DemaConsulting.CanvasNet/Codecs/Svg/SvgCodec.Filters.DropShadow.cs" # phase 5 filter partial - - "src/DemaConsulting.CanvasNet/Codecs/Svg/SvgCodec.Filters.FeImage.cs" # phase 5 filter partial - - "src/DemaConsulting.CanvasNet/Codecs/Svg/SvgCodec.Filters.Lighting.cs" # phase 6 filter partial - - "src/DemaConsulting.CanvasNet/Codecs/Svg/SvgCodec.Filters.Turbulence.cs" # phase 6 filter partial - - "src/DemaConsulting.CanvasNet/Codecs/Svg/SvgCodec.Css.Parser.cs" # phase 7 CSS styling partial - - "src/DemaConsulting.CanvasNet/Codecs/Svg/SvgCodec.Css.Selectors.cs" # phase 7 CSS styling partial - - "src/DemaConsulting.CanvasNet/Codecs/Svg/SvgCodec.Css.Cascade.cs" # phase 7 CSS styling partial - - "src/DemaConsulting.CanvasNet/Codecs/Svg/SvgCodec.Filters.Blend.cs" # phase 8 filter partial - - "src/DemaConsulting.CanvasNet/Codecs/NamespaceDoc.cs" # Codecs namespace documentation - - "test/DemaConsulting.CanvasNet.Tests/Codecs/SvgCodecTests.cs" # unit tests - - "test/DemaConsulting.CanvasNet.Tests/Codecs/SvgFixtureTests.cs" # fixture conformance tests - # CanvasNet-Geometry Review (one per subsystem) - id: CanvasNet-Geometry title: Review that CanvasNet Geometry Subsystem Implementation is Correct @@ -331,6 +298,7 @@ reviews: - "src/DemaConsulting.CanvasNet/Geometry/PathCommandType.cs" # supporting data type source - "test/DemaConsulting.CanvasNet.Tests/Geometry/PathBuilderTests.cs" # unit tests - "test/DemaConsulting.CanvasNet.Tests/Geometry/PathTests.cs" # unit tests + - "test/DemaConsulting.CanvasNet.Tests/Geometry/PathCommandTests.cs" # unit tests # CanvasNet-Geometry-CornerRoundEffect Review (one per unit) - id: CanvasNet-Geometry-CornerRoundEffect @@ -568,6 +536,81 @@ reviews: - "src/DemaConsulting.CanvasNet/Rendering/Shapes.cs" # unit source - "test/DemaConsulting.CanvasNet.Tests/Rendering/ShapesTests.cs" # unit tests + # CanvasNetSvg-Architecture Review (one per system) + - id: CanvasNetSvg-Architecture + title: Review that CanvasNetSvg Architecture Satisfies Requirements + context: + - "README.md" + - "docs/user_guide/**/*.md" + paths: + - "docs/reqstream/canvas-net-svg.yaml" # system requirements + - "docs/design/introduction.md" # design introduction + - "docs/design/canvas-net-svg.md" # system design + - "docs/verification/introduction.md" # verification introduction + - "docs/verification/canvas-net-svg.md" # system verification + - "test/DemaConsulting.CanvasNet.Svg.Tests/SvgSystemIntegrationTests.cs" # integration tests + + # CanvasNetSvg-Design Review (one per system) + - id: CanvasNetSvg-Design + title: Review that CanvasNetSvg Design is Consistent and Complete + context: + - "docs/reqstream/canvas-net-svg.yaml" + paths: + - "docs/reqstream/canvas-net-svg/platform-requirements.yaml" # platform requirements + - "docs/design/introduction.md" # design introduction + - "docs/design/canvas-net-svg.md" # system design + - "docs/design/canvas-net-svg/**/*.md" # all system design documents + + # CanvasNetSvg-Verification Review (one per system) + - id: CanvasNetSvg-Verification + title: Review that CanvasNetSvg Verification is Consistent and Complete + context: + - "docs/reqstream/canvas-net-svg.yaml" + paths: + - "docs/verification/introduction.md" # verification introduction + - "docs/verification/canvas-net-svg.md" # system verification + - "docs/verification/canvas-net-svg/**/*.md" # all verification documents + + # CanvasNetSvg-AllRequirements Review (one per system) + - id: CanvasNetSvg-AllRequirements + title: Review that All CanvasNetSvg Requirements are Complete + context: + - "docs/design/canvas-net-svg.md" + - "docs/reqstream/canvas-net-svg.yaml" + paths: + - "docs/reqstream/canvas-net-svg/**/*.yaml" # all requirements files + + # CanvasNetSvg-SvgCodec Review (one per direct unit) + - id: CanvasNetSvg-SvgCodec + title: Review that CanvasNetSvg SvgCodec Implementation is Correct + context: + - "docs/design/canvas-net-svg.md" + - "docs/reqstream/canvas-net-svg.yaml" + paths: + - "docs/reqstream/canvas-net-svg/svg-codec.yaml" # unit requirements + - "docs/design/canvas-net-svg/svg-codec.md" # unit design + - "docs/verification/canvas-net-svg/svg-codec.md" # unit verification + - "docs/sysml2/model/canvas-net-svg/svg-codec.sysml" # unit SysML2 model + - "src/DemaConsulting.CanvasNet.Svg/SvgCodec.cs" # unit source (public API entry point) + - "src/DemaConsulting.CanvasNet.Svg/*.cs" # unit source (partial-class implementation files) + - "src/DemaConsulting.CanvasNet.Svg/SvgCodec.Filters.ColorMatrix.cs" # phase 5 filter partial + - "src/DemaConsulting.CanvasNet.Svg/SvgCodec.Filters.ComponentTransfer.cs" # phase 5 filter partial + - "src/DemaConsulting.CanvasNet.Svg/SvgCodec.Filters.Morphology.cs" # phase 5 filter partial + - "src/DemaConsulting.CanvasNet.Svg/SvgCodec.Filters.Convolution.cs" # phase 5 filter partial + - "src/DemaConsulting.CanvasNet.Svg/SvgCodec.Filters.DisplacementMap.cs" # phase 5 filter partial + - "src/DemaConsulting.CanvasNet.Svg/SvgCodec.Filters.Tile.cs" # phase 5 filter partial + - "src/DemaConsulting.CanvasNet.Svg/SvgCodec.Filters.DropShadow.cs" # phase 5 filter partial + - "src/DemaConsulting.CanvasNet.Svg/SvgCodec.Filters.FeImage.cs" # phase 5 filter partial + - "src/DemaConsulting.CanvasNet.Svg/SvgCodec.Filters.Lighting.cs" # phase 6 filter partial + - "src/DemaConsulting.CanvasNet.Svg/SvgCodec.Filters.Turbulence.cs" # phase 6 filter partial + - "src/DemaConsulting.CanvasNet.Svg/SvgCodec.Css.Parser.cs" # phase 7 CSS styling partial + - "src/DemaConsulting.CanvasNet.Svg/SvgCodec.Css.Selectors.cs" # phase 7 CSS styling partial + - "src/DemaConsulting.CanvasNet.Svg/SvgCodec.Css.Cascade.cs" # phase 7 CSS styling partial + - "src/DemaConsulting.CanvasNet.Svg/SvgCodec.Filters.Blend.cs" # phase 8 filter partial + - "src/DemaConsulting.CanvasNet.Svg/NamespaceDoc.cs" # Svg namespace documentation + - "test/DemaConsulting.CanvasNet.Svg.Tests/SvgCodecTests.cs" # unit tests + - "test/DemaConsulting.CanvasNet.Svg.Tests/SvgFixtureTests.cs" # fixture conformance tests + # OTS-BuildMark Review (one per OTS item) - id: OTS-BuildMark title: Review that BuildMark Provides Required Functionality diff --git a/CanvasNet.slnx b/CanvasNet.slnx index 194e23d3a..166d1c794 100644 --- a/CanvasNet.slnx +++ b/CanvasNet.slnx @@ -1,8 +1,10 @@ + + diff --git a/README.md b/README.md index e39b8345b..cc23a8aa4 100644 --- a/README.md +++ b/README.md @@ -32,7 +32,8 @@ image operations using `Span`, and supports independent-copy cropping for loa - πŸ—œοΈ **JPEG Codec** - Load baseline/progressive; save baseline JPEG - 🎞️ **GIF Codec** - Decode-only load of first GIF frame; `GetInfo` reports the true frame count - πŸ“ **SVG Codec** - Rasterize a common SVG subset, including markers/filters/clip-paths/masks and - weight/style-aware font matching, to a surface + weight/style-aware font matching, to a surface (ships as the separate + `DemaConsulting.CanvasNet.Svg` package) - πŸ” **Header-Only Probing** - `GetInfo` reads headers without decoding pixels (GIF excepted) - πŸ–ŒοΈ **Path Filling** - Antialiased nonzero/even-odd fill of vector paths - πŸ–ŠοΈ **Stroke-to-Fill** - Convert stroked paths into fillable outlines @@ -55,11 +56,24 @@ Or via Package Manager Console: Install-Package DemaConsulting.CanvasNet ``` +SVG rasterization requires the separate `DemaConsulting.CanvasNet.Svg` package: + +```bash +dotnet add package DemaConsulting.CanvasNet.Svg +``` + +Or via Package Manager Console: + +```powershell +Install-Package DemaConsulting.CanvasNet.Svg +``` + ## Usage ```csharp using DemaConsulting.CanvasNet.Canvas; using DemaConsulting.CanvasNet.Codecs; +using DemaConsulting.CanvasNet.Svg; using System.IO; // Create a surface, set a pixel, and crop an independent copy diff --git a/docs/design/canvas-net-svg.md b/docs/design/canvas-net-svg.md new file mode 100644 index 000000000..f46167a82 --- /dev/null +++ b/docs/design/canvas-net-svg.md @@ -0,0 +1,202 @@ +# System Design + + + +This document provides the system-level design for CanvasNetSvg. + +![CanvasNetSvg Structure](CanvasNetSvgView.svg) + + + +## Architecture + +CanvasNetSvg is a .NET library providing SVG (Scalable Vector Graphics) rasterization, +distributed as its own NuGet package (`DemaConsulting.CanvasNet.Svg`, namespace +`DemaConsulting.CanvasNet.Svg`), independent of, but depending on, the core `CanvasNet` system +(its own separate package, `DemaConsulting.CanvasNet`) β€” see the Dependencies section below. The +system consists of a single implemented unit: + +- **SvgCodec** (namespace `DemaConsulting.CanvasNet.Svg`, folder + `src/DemaConsulting.CanvasNet.Svg/`, flat β€” no further nesting): a hand-rolled, + decode/rasterize-only codec for a common real-world subset of SVG documents, rasterizing them + directly into a `DemaConsulting.CanvasNet.Canvas.Surface` pixel buffer. Unlike the `CanvasNet` + system's own raster codecs (`BmpCodec`, `PngCodec`, `TiffCodec`, `JpegCodec`), `SvgCodec` has no + `Save` method: an SVG document is XML markup, not pixel data, so there is no meaningful inverse + operation that would turn an arbitrary `Surface` back into equivalent vector markup. See + _SvgCodec Unit Design_ (`canvas-net-svg/svg-codec.md`). + +`CanvasNetSvg` is modeled as its own top-level software system (rather than as a further unit of +the `CanvasNet` system's `Codecs` subsystem, as it was in an earlier revision of this design) +because it is distributed as its own independently-versioned NuGet package β€” per +`software-items.md`'s rule that a software package contains exactly one software system, a system +whose entire content ships in a distinct package must itself be modeled as a distinct system, not +folded into the package it depends on. `CanvasNetSvg` contains exactly one unit, so no Subsystem +tier is interposed between the system and `SvgCodec`: inserting one here would not separate +anything (there is nothing else in the system to separate it from), unlike `CanvasNet`'s own +`Fonts` subsystem, whose single-unit shape exists to keep a consistent finer-grained +decomposition within a System that already contains several other subsystems. + +## External Interfaces + +The system exposes the following public API to external consumers, all on the static `SvgCodec` +class: + +- **SvgCodec.Load(Stream stream, int width, int height, fonts)** / + **SvgCodec.Load(string path, int width, int height, fonts)**: Loads a `Surface` by rasterizing + a supported SVG document from a stream or file path into a caller-requested `width`x`height` + raster, with an optional single-font-per-family `fonts` dictionary. Throws + `ArgumentNullException` for a null `stream`/`path`, `ArgumentException` for an empty/whitespace + `path`, `InvalidDataException` for malformed or unsupported SVG data, and + `ArgumentOutOfRangeException` (propagated, unwrapped, from `Surface`'s own constructor) for a + non-positive `width`/`height` or a `width`/`height` exceeding `Surface.MaxDimension` (8192). +- **SvgCodec.LoadWithFontFaces(Stream stream, int width, int height, fontFaces)** / + **SvgCodec.LoadWithFontFaces(string path, int width, int height, fontFaces)**: The richer + loading entry point, accepting more than one registered `SvgFontFace` (weight/style variant) + per font-family, matching each text element's own cascaded font-weight/font-style to the + closest registered face. Same exception contract as `Load` above. +- **SvgCodec.GetInfo(Stream stream)** / **SvgCodec.GetInfo(string path)**: Reports an SVG + document's resolved intrinsic width, height, channel count (always 4), and alpha presence + (always true) via the shared `Codecs.ImageInfo` record struct, given a stream or a file path, + without rasterizing the document, falling back from `viewBox` to `width`/`height` to a + 300x150 CSS default. Throws `ArgumentNullException` for a null `stream`/`path`, + `ArgumentException` for an empty/whitespace `path`, and `InvalidDataException` for malformed + SVG data. + + +| Interface | Direction | Format | Constraints | +| -------------------------------------- | ---------------- | ------------------------------ | ------------------------------- | +| `SvgCodec.Load(...)` | Inbound/Outbound | Method call / `Surface` return | Valid SVG stream or path; `0 < width, height <= 8192` | +| `SvgCodec.LoadWithFontFaces(...)` | Inbound/Outbound | Method call / `Surface` return | Valid SVG stream or path; `0 < width, height <= 8192` | +| `SvgCodec.GetInfo(...)` | Inbound/Outbound | Method call / `ImageInfo` return | Valid SVG stream or path | + + +See _SvgCodec Unit Design_ (`canvas-net-svg/svg-codec.md`) for the complete in-scope SVG feature +subset (shapes, path data, transforms, gradients, patterns, filters, clip-path/mask, markers, +image, text, and CSS styling) and every method's full parameter and exception detail. + +## Dependencies + +`CanvasNetSvg` depends on the separate `CanvasNet` system (its own package, +`DemaConsulting.CanvasNet`, referenced via a project reference from +`src/DemaConsulting.CanvasNet.Svg/DemaConsulting.CanvasNet.Svg.csproj`), specifically: + +- The `Canvas` subsystem's `Surface` unit β€” constructing the destination raster and compositing + filled/stroked pixels into it +- The `Geometry` subsystem's `Path`/`PathBuilder` (assembling transformed shape/glyph outlines) + and `SvgArcConverter` (converting elliptical arc path commands to Bezier curves) +- The `Drawing` subsystem's `PathFiller`/`PathStroker` (rasterizing the already-transformed, + pixel-space paths `SvgCodec` builds) and `Gradient`/`LinearGradient`/`RadialGradient`/ + `GradientStop`/`GradientSpread` (representing resolved gradient paint) +- The `Fonts` subsystem's `TrueTypeFont` (glyph outline/metrics/kerning lookup for text + rendering) +- The `Codecs` subsystem's shared `ImageInfo` record struct (the return type of `GetInfo`) β€” see + _Codecs Subsystem Design_ (`docs/design/canvas-net/codecs.md`) + +This is an ordinary, same-repository, system-to-system dependency: both `CanvasNet` and +`CanvasNetSvg` are produced by this repository, so it is neither an OTS Software Item (not a +third-party/external-program dependency) nor a Shared Package (that category is scoped to a +package produced by a _different_ repository within the same program). Beyond `CanvasNet`, +`SvgCodec` uses only the .NET base class library's `System.Xml.Linq` (`XDocument`/`XElement`) and +`System.Numerics` (`Matrix3x2`/`Vector2`) namespaces, available on every one of CanvasNetSvg's +target frameworks with no new runtime NuGet dependency. `CanvasNetSvg` introduces no new OTS +Software Item beyond those already used to build and verify the `CanvasNet` system (BuildMark, +FileAssert, Pandoc, ReqStream, ReviewMark, SarifMark, SonarMark, VersionMark, WeasyPrint, xUnit) +β€” see _OTS Integration Design_ (`docs/design/ots.md`). + +## Risk Control Measures + +`SvgCodec`'s `Load`/`LoadWithFontFaces` operations parse externally-supplied, potentially +untrusted SVG documents (XML markup that may embed references, gradients, filters, and +base64-encoded raster images). Risk control for this untrusted-input parsing is segregated +entirely within the single `SvgCodec` unit and falls into two distinct categories, each with its +own consistently-applied behavior: + +- **Tolerantly skipped, no-effect constructs** β€” a document containing one of these continues to + render the rest of its content rather than failing outright: a dangling `url(#id)` reference + (gradient, pattern, filter, clip-path, or mask) that resolves to no element, a well-formed but + out-of-scope/unrecognized element or filter primitive, an external (non-`data:`) `image` `href`, + and a nested `data:image/svg+xml` document. +- **Rejected reference cycles** β€” an unbounded self- or mutually-referencing chain (a `use` + element referencing itself directly or indirectly, a `marker` referencing a marker that + eventually references it again, a `mask`/`pattern` whose own content resolves back to itself) + is explicitly detected and rejected with a thrown `InvalidDataException`, rather than being + tolerated or silently skipped: recursing into a genuine cycle would otherwise never terminate. + +Beyond these two categories, explicit DTD/external-entity hardening (rejecting any document +containing a DOCTYPE declaration) and bounded element-nesting depth, total-element, +geometry-work, and number-list-length budgets likewise reject the offending document with a +thrown `InvalidDataException` once exceeded, rather than tolerating it β€” see _SvgCodec Unit +Design_ (`canvas-net-svg/svg-codec.md`) for the complete set of budgets and fallback behaviors. +No other segregation is required at the system level: `CanvasNetSvg` contains exactly one unit, +so this risk control is inherently contained within it (IEC 62304 Β§5.3.3). + +## Data Flow + +**SVG load/rasterize path:** + +1. **Input**: An SVG document (stream or file path), the caller-requested output raster + `width`/`height`, and an optional font dictionary +2. **Validation**: `Load`/`LoadWithFontFaces` reject a null `stream`/`path` with + `ArgumentNullException`, an empty/whitespace `path` with `ArgumentException`, and malformed or + resource-disproportionate SVG data (non-well-formed XML, a DOCTYPE declaration, a malformed + `viewBox`/`transform`/path `d` attribute, or a budget exceeded) with `InvalidDataException`; + a non-positive `width`/`height`, or a `width`/`height` exceeding `Surface.MaxDimension` (8192), + propagates, unwrapped, as `Surface`'s own `ArgumentOutOfRangeException` +3. **Processing**: Parses the document with `System.Xml.Linq`, builds an idβ†’element index, + resolves the root `viewBox`/`width`/`height` into an intrinsic size and computes the + `preserveAspectRatio`-driven fit transform into the requested raster, then recursively walks + the element tree β€” baking every composed transform directly into `Geometry.Path` points, + resolving presentation attributes/CSS cascade, gradients, patterns, clip-path/mask, and + filters, and rasterizing each renderable element via `Drawing.PathFiller`/`Drawing.PathStroker` + onto a new `Canvas.Surface`, with text elements shaped through `Fonts.TrueTypeFont` glyph + outlines +4. **Output**: A new `Canvas.Surface` containing the rasterized pixels + +**SVG GetInfo path:** + +1. **Input**: An SVG document (stream or file path) +2. **Validation**: Rejects a null `stream`/`path` with `ArgumentNullException`, an empty/ + whitespace `path` with `ArgumentException`, and malformed SVG data (up to and including the + root `svg` start-tag) with `InvalidDataException` +3. **Processing**: Reads only the root `svg` start-tag's own attributes via a forward-only, + character-budget-capped `XmlReader`, resolving intrinsic size by falling back from `viewBox` + to `width`/`height` to a 300x150 CSS default +4. **Output**: A `Codecs.ImageInfo` record struct reporting the resolved width, height, + `Channels = 4`, and `HasAlpha = true` + +## Design Constraints + +- **Simplicity**: Minimal functionality kept easy to understand and extend +- **Compliance**: All functionality must be traceable to requirements +- **Quality**: Zero warnings, full test coverage, complete documentation +- **Portability**: Compatible across supported .NET platforms +- **Decode-only**: `SvgCodec` provides no `Save`/encode direction (see Architecture above) + +### Platform Support + +The library targets the following frameworks, identical to the `CanvasNet` system it depends on, +enabling compatibility across modern, currently supported .NET runtimes: + +| Target Framework | Runtime / Environment | +| ---------------- | --------------------- | +| `net8.0` | .NET 8 LTS | +| `net9.0` | .NET 9 | +| `net10.0` | .NET 10 | + +The library is supported on the following operating systems: + +- **Windows** β€” primary developer and CI platform +- **Linux** β€” CI/CD and containerized environments +- **macOS** β€” developer workstations using Apple platforms + +Portability is achieved by restricting the implementation exclusively to Base Class Library (BCL) +APIs and the `CanvasNet` system's own public API, available across all target frameworks. No +platform-specific native interop, OS-specific APIs, or framework-version-specific features are +used. + +### Integration Patterns + +- **NuGet Packaging**: Standard .NET library packaging and distribution, referencing the + `CanvasNet` package as an ordinary NuGet dependency +- **CI/CD Integration**: Automated build, test, and quality validation +- **Requirements Traceability**: All features linked to passing tests diff --git a/docs/design/canvas-net/codecs/svg-codec.md b/docs/design/canvas-net-svg/svg-codec.md similarity index 94% rename from docs/design/canvas-net/codecs/svg-codec.md rename to docs/design/canvas-net-svg/svg-codec.md index afa50aa12..575143d07 100644 --- a/docs/design/canvas-net/codecs/svg-codec.md +++ b/docs/design/canvas-net-svg/svg-codec.md @@ -1,12 +1,18 @@ ## SvgCodec -![Codecs Structure](CodecsView.svg) +![CanvasNetSvg Structure](CanvasNetSvgView.svg) -The `SvgCodec` class is the fifth software unit in the `Codecs` subsystem, and the first codec -unit whose dependencies extend beyond `Canvas.Surface`. It provides hand-rolled, decode/ +`SvgCodec` is distributed as the separate `DemaConsulting.CanvasNet.Svg` NuGet package (namespace +`DemaConsulting.CanvasNet.Svg`), which references the core `DemaConsulting.CanvasNet` package. + +The `SvgCodec` class is the sole software unit of the `CanvasNetSvg` system - unlike the five +units of the `CanvasNet` system's `Codecs` subsystem, whose dependencies are limited to +`Canvas.Surface`, `SvgCodec`'s dependencies extend to `CanvasNet`'s `Geometry`, `Drawing`, and +`Fonts` subsystems as well (see the Dependencies section of _CanvasNetSvg System Design_, +`../canvas-net-svg.md`). It provides hand-rolled, decode/ rasterize-only support for a common real-world subset of SVG (Scalable Vector Graphics) documents, rendering them directly into a `Surface` pixel buffer. Unlike `BmpCodec`, `PngCodec`, `TiffCodec`, and `JpegCodec`, `SvgCodec` has no `Save` method: an SVG document is XML markup, not @@ -27,11 +33,11 @@ same reason as the other codecs: rasterizing an SVG document has no instance sta - Root `svg` sizing: `viewBox`/`width`/`height` resolve the document's intrinsic user-space origin/size, fit into the caller-requested raster via an optional `preserveAspectRatio` (`[defer] []` - all 10 aligns and both `meet`/`slice`; `defer` is parsed -and ignored - it only ever has an observable effect for a browser negotiating a *separately -fetched, cacheable* external image resource's own `preserveAspectRatio` against an embedding +and ignored - it only ever has an observable effect for a browser negotiating a _separately +fetched, cacheable_ external image resource's own `preserveAspectRatio` against an embedding ``/CSS reference, a negotiation this codec has no equivalent for even now that `` is partially supported, since its own supported `data:` URI case is neither separately fetched -nor cacheable) - see *ViewBox Fitting Policy* below +nor cacheable) - see _ViewBox Fitting Policy_ below - Shapes: `rect` (including `rx`/`ry` rounded corners), `circle`, `ellipse`, `line`, `polyline`, `polygon`, and `path` (the full `d` mini-language: `M`/`m`, `L`/`l`, `H`/`h`, `V`/`v`, `C`/`c`, `S`/`s`, `Q`/`q`, `T`/`t`, `A`/`a`, `Z`/`z`, in both absolute and relative forms) @@ -49,15 +55,15 @@ nor cacheable) - see *ViewBox Fitting Policy* below (`pad`/`reflect`/`repeat`), and a bounded, cycle-checked `href`/`xlink:href` template inheritance chain for color stops - `use`, referencing any element by id via `href`/`xlink:href`, with `x`/`y` translation (each - accepting a trailing `%`, resolved against the current viewport - see *Percentage-Based - Geometry Resolution* below), and, when the referenced element is a `symbol` with its own + accepting a trailing `%`, resolved against the current viewport - see _Percentage-Based + Geometry Resolution_ below), and, when the referenced element is a `symbol` with its own `viewBox`, a `preserveAspectRatio`-driven fit of that `viewBox` into the `use`/`symbol` - element's resolved `width`/`height` (see *ViewBox Fitting Policy* below) + element's resolved `width`/`height` (see _ViewBox Fitting Policy_ below) - `marker`, referenced from `line`/`polyline`/`polygon`/`path` via the `marker-start`/ `marker-mid`/`marker-end` presentation attributes (`url(#id)`), with `markerWidth`/ `markerHeight`, `refX`/`refY`, `markerUnits` (`strokeWidth`/`userSpaceOnUse`), `orient` (`auto`/`auto-start-reverse`/a fixed angle in degrees), an optional `viewBox`, and an optional - explicit `preserveAspectRatio` (see *ViewBox Fitting Policy* below) + explicit `preserveAspectRatio` (see _ViewBox Fitting Policy_ below) - `filter`, referenced from any renderable shape or `text` element, or from a `g`/`symbol` reference/`use` element (applied to the whole referenced subtree as a single unit), via the `filter` presentation attribute (`url(#id)`), with `x`/`y`/`width`/`height` filter-region @@ -70,26 +76,26 @@ nor cacheable) - see *ViewBox Fitting Policy* below `clip-path` presentation attribute (`url(#id)`), hard-clipping that element's own content to the union of the `clipPath` element's own direct `rect`/`circle`/`ellipse`/`polyline`/ `polygon`/`path`/`text` children, honoring `clipPathUnits` - (`userSpaceOnUse`/`objectBoundingBox`) and each child's own `clip-rule` - see *Clipping and - Masking* below + (`userSpaceOnUse`/`objectBoundingBox`) and each child's own `clip-rule` - see _Clipping and + Masking_ below - `mask`, referenced from any renderable shape/text/`g`/`symbol`/`use` element via the `mask` presentation attribute (`url(#id)`), attenuating that element's own alpha by the referenced `mask` element's own rendered content, evaluated as a luminance mask (the SVG-specification default), honoring `maskUnits`/`x`/`y`/`width`/`height` (the mask's own region box) and `maskContentUnits` (the mask content's own coordinate system) as independent attributes - see - *Clipping and Masking* below + _Clipping and Masking_ below - `pattern`, referenced from any renderable shape/text element's own `fill`/`stroke` presentation attribute (`url(#id)`) as a tiled paint server, honoring `patternUnits`/ `patternContentUnits` (`objectBoundingBox`/`userSpaceOnUse`, resolved as two independent attributes exactly as `clipPathUnits`/`maskContentUnits` already are), `patternTransform`, an optional `viewBox`/`preserveAspectRatio` pair, and a bounded, cycle-checked `href`/ - `xlink:href` template-inheritance chain for tile content - see *Pattern Paint-Server* below + `xlink:href` template-inheritance chain for tile content - see _Pattern Paint-Server_ below - `image`, whose `href`/`xlink:href` is a base64-encoded `data:` URI with a supported raster MIME type (`image/png`, `image/jpeg`, `image/bmp`, `image/tiff`, or `image/gif`), decoded through that format's own existing codec and drawn into the element's own `x`/`y`/`width`/`height` - placement rect, fitted per an optional `preserveAspectRatio` (see *ViewBox Fitting Policy* + placement rect, fitted per an optional `preserveAspectRatio` (see _ViewBox Fitting Policy_ below) - integrated with the same `clip-path`/`mask`/`filter`/opacity effects pipeline every - other renderable element already uses - see *Image* below + other renderable element already uses - see _Image_ below - `text`, with `x`/`y`, `font-family`, `font-size`, `fill`, `text-anchor` (`start`/`middle`/`end`), and `font-weight`/`font-style`, rendered through a caller-supplied dictionary of per-family `SvgFontFace` lists (or, via the legacy single-font-per-family @@ -103,9 +109,9 @@ constructs this codec does not implement. Encountering one of these does not fai document: `SvgCodec` silently skips just that element (and, for a container element, everything nested inside it) and continues walking the rest of the tree. This is a deliberate, tolerant-parsing policy distinct from the codec's malformed-input rejection policy (see -*Error Handling* below) β€” a document using an out-of-scope construct is not itself invalid SVG, +_Error Handling_ below) β€” a document using an out-of-scope construct is not itself invalid SVG, only partially outside this codec's supported feature set. Within a `style` element's own CSS -engine (see *CSS `" + + ""; + using var stream = ToStream(svg); + + // Act: rasterize the document onto a new Surface through the public API + var surface = SvgCodec.Load(stream, 10, 10); + + // Assert: the system produces the expected integrated rasterized pixel value + Assert.Equal(new Rgba32(11, 22, 33, 255), surface[5, 5]); + } + + /// + /// Proves that the system rasterizes a marker referenced from a line element's + /// marker-end attribute, placing it at the line's end vertex, through the public + /// API. See SvgCodecTests for the full unit test coverage of marker orientation, + /// scale, and reference-cycle rejection. + /// + [Fact] + public void CanvasNetSvg_SystemIntegration_SvgMarkerRendering_RendersMarkerAtLineEnd() + { + // Arrange: a horizontal line from (0,5) to (8,5); its marker-end places a 4x4 + // "userSpaceOnUse" red square anchored at (2,2) (refX/refY), so at the (8,5) end vertex + // the square occupies (6,3)-(10,7) + const string svg = """ + + + + + + + + + """; + + // Act: rasterize the document onto a new Surface through the public API + using var stream = ToStream(svg); + var surface = SvgCodec.Load(stream, 10, 10); + + // Assert: the marker's red square is visible past the line's own x2=8 end point + Assert.Equal(new Rgba32(255, 0, 0, 255), surface[9, 5]); + } + + /// + /// Proves that the system rasterizes a filter chain (feFlood/feComposite/feGaussianBlur/ + /// feMerge) referenced from a shape's filter attribute, through the public API. See + /// SvgCodecTests for the full unit test coverage of the individual filter + /// primitives. + /// + [Fact] + public void CanvasNetSvg_SystemIntegration_SvgFilterRendering_AppliesFilterChainToShape() + { + // Arrange + const string svg = """ + + + + + + + + + + + + + + + """; + + // Act: rasterize the document onto a new Surface through the public API + using var stream = ToStream(svg); + var surface = SvgCodec.Load(stream, 100, 100); + + // Assert: the rect's own fill remains fully opaque and unaffected at its center + Assert.Equal(new Rgba32(0, 128, 0, 255), surface[50, 50]); + + // Assert: just outside the rect's own edge (which a fill-only render would leave fully + // transparent), a softened orange halo pixel is visible - proving the filter chain + // actually ran end-to-end through the public API rather than being silently ignored + Assert.Equal(new Rgba32(255, 161, 0, 19), surface[61, 50]); + } + + /// + /// Proves that the system rasterizes a clipPath element referenced from a shape's + /// clip-path attribute, hard-clipping to the referenced shape, through the public + /// API. See SvgCodecTests for the full unit test coverage of clip/mask unit systems + /// and effect ordering. + /// + [Fact] + public void CanvasNetSvg_SystemIntegration_SvgClipPathRendering_ClipsContentToReferencedShape() + { + // Arrange: a 60x60 red rect at (20,20)-(80,80), clipped by a circle centered at (50,50) + // with radius 20 (i.e. covering (30,30)-(70,70)) + const string svg = """ + + + + + + + + + """; + + // Act: rasterize the document onto a new Surface through the public API + using var stream = ToStream(svg); + var surface = SvgCodec.Load(stream, 100, 100); + + // Assert: inside the clip circle, the rect's own red fill is visible + Assert.Equal(new Rgba32(255, 0, 0, 255), surface[50, 50]); + // Assert: outside the clip circle but inside the rect's own bounds, nothing was painted + Assert.Equal(0, surface[22, 22].A); + } + + /// + /// Proves that the system tiles a pattern element referenced from a shape's + /// fill attribute across the shape's own bounding box, through the public API. See + /// SvgCodecTests for the full unit test coverage of pattern unit systems, href + /// inheritance, and resource safety. + /// + [Fact] + public void CanvasNetSvg_SystemIntegration_SvgPatternRendering_TilesPatternAcrossShape() + { + // Arrange: a 60x60 bounding box (20,20)-(80,80); the pattern's own width/height (1,1) are + // objectBoundingBox-interpreted (the default patternUnits), so exactly one tile spans the + // whole bounding box + const string svg = """ + + + + + + + + + + """; + + // Act: rasterize the document onto a new Surface through the public API + using var stream = ToStream(svg); + var surface = SvgCodec.Load(stream, 100, 100); + + // Assert: the pattern's own tile content is visible inside the filled shape's bounding box + Assert.Equal(new Rgba32(0, 255, 0, 255), surface[50, 50]); + } + + /// + /// Proves that the system decodes and rasterizes an image element's base64-encoded + /// PNG data URI at the element's own placement rect, through the public API. See + /// SvgCodecTests for the full unit test coverage of other raster formats, + /// preserveAspectRatio, effects integration, and resource safety. + /// + [Fact] + public void CanvasNetSvg_SystemIntegration_SvgImageRendering_RendersEmbeddedRasterImage() + { + // Arrange: a 2x2 solid blue PNG, placed at (20,20) with a 60x60 placement rect + using var source = BuildSolidSurface(2, 2, new Rgba32(0, 0, 255, 255)); + var dataUri = BuildPngDataUri(source); + var svg = $""" + + + + """; + + // Act: rasterize the document onto a new Surface through the public API + using var stream = ToStream(svg); + var surface = SvgCodec.Load(stream, 100, 100); + + // Assert: the decoded blue pixel is visible inside the placement rect + Assert.Equal(new Rgba32(0, 0, 255, 255), surface[50, 50]); + // Assert: outside the placement rect, nothing was painted + Assert.Equal(0, surface[10, 10].A); + } + + /// + /// Proves that the system fits a wide (landscape) viewBox into a square raster, + /// letterboxing with transparent bars above and below the centered content, through the + /// public API. See SvgCodecTests for the full unit test coverage of other + /// preserveAspectRatio align/meet-or-slice combinations. + /// + [Fact] + public void CanvasNetSvg_SystemIntegration_SvgViewBoxFitting_LetterboxesWideViewBox() + { + // Arrange: 200x100 viewBox (2:1) into a 100x100 raster; scale equals 0.5, content + // occupies y equals 25 to 75, leaving transparent bars above/below + const string svg = ""; + + // Act: rasterize the document onto a new Surface through the public API + using var stream = ToStream(svg); + var surface = SvgCodec.Load(stream, 100, 100); + + // Assert: content band is filled + Assert.Equal(255, surface[50, 50].A); + // Assert: top and bottom letterbox bars are transparent + Assert.Equal(0, surface[50, 5].A); + Assert.Equal(0, surface[50, 95].A); + } + + /// + /// Proves that the system resolves a rect's width percentage against the + /// current viewport width rather than rejecting it, through the public API. See + /// SvgCodecTests for the full per-attribute-family basis matrix coverage. + /// + [Fact] + public void CanvasNetSvg_SystemIntegration_SvgPercentageGeometryResolution_ResolvesWidthPercentage() + { + // Arrange: width="50%" of a 100-wide viewBox resolves to width=50; the rect spans x=[0,50) + const string svg = ""; + + // Act: rasterize the document onto a new Surface through the public API + using var stream = ToStream(svg); + var surface = SvgCodec.Load(stream, 100, 100); + + // Assert: the percentage-resolved width is honored + Assert.Equal(new Rgba32(255, 0, 0, 255), surface[25, 5]); + Assert.Equal(0, surface[75, 5].A); + } + + /// + /// Proves that the system reports an SVG document's resolved viewBox dimensions via + /// the public entry point. See SvgCodecTests + /// for the full unit test coverage of the width/height/CSS-default fallback chain. + /// + [Fact] + public void CanvasNetSvg_SystemIntegration_SvgGetInfo_ReturnsViewBoxDimensions() + { + // Arrange + const string svg = ""; + + // Act: query the document's intrinsic size through the public API + using var stream = ToStream(svg); + var info = SvgCodec.GetInfo(stream); + + // Assert: the viewBox dimensions win over the width/height attributes + Assert.Equal(40, info.Width); + Assert.Equal(20, info.Height); + Assert.Equal(4, info.Channels); + Assert.True(info.HasAlpha); + } + + /// + /// Proves that the system renders an SVG text element's characters as glyph + /// outlines from a caller-supplied font, through the public API. See + /// SvgCodecTests/SvgFixtureTests for the full unit test coverage of + /// text-anchor, kerning, and font-family fallback. + /// + [Fact] + public void CanvasNetSvg_SystemIntegration_SvgTextRendering_RendersGlyphAtExpectedPosition() + { + // Arrange: font-size equals the font's em-square (100), so scale is 1:1; the square glyph + // for 'A' should render spanning x equals 10 to 60, y equals 10 to 60 (baseline at y=60) + const string svg = "A"; + var fonts = new Dictionary { ["TestFont"] = BuildTestFont() }; + + // Act: rasterize the document onto a new Surface through the public API + using var stream = ToStream(svg); + var surface = SvgCodec.Load(stream, 100, 100, fonts); + + // Assert: inside the glyph square + Assert.Equal(255, surface[35, 35].A); + // Assert: outside the glyph square (above baseline extent and off to the side) + Assert.Equal(0, surface[5, 5].A); + } + + /// + /// Proves that the system selects a registered bold face over a registered normal face for + /// a text element with font-weight="bold", through the public + /// + /// entry point. See SvgCodecTests for the full unit test coverage of font-style + /// matching and legacy single-font-per-family compatibility. + /// + [Fact] + public void CanvasNetSvg_SystemIntegration_SvgFontWeightStyleMatching_SelectsBoldFaceOverNormalFace() + { + // Arrange: font-size equals the shared 100-unit em-square, so scale is 1:1. The narrow + // face fills canvas x equals 10 to 60; the wide face fills canvas x equals 10 to 90 - x + // equals 75 is filled only by the wide (bold) face. + const string svg = """ + + A + A + + """; + var faces = new Dictionary> + { + ["TestFont"] = + [ + new SvgFontFace(BuildTestFont(), Weight: 400), + new SvgFontFace(BuildBoldTestFont(), Weight: 700) + ] + }; + + // Act: rasterize the document onto a new Surface through the public API + using var stream = ToStream(svg); + var surface = SvgCodec.LoadWithFontFaces(stream, 100, 100, faces); + + // Assert: the font-weight="bold" text selected the wide face + Assert.Equal(255, surface[75, 35].A); + // Assert: the sibling text with no font-weight still selected the narrow face + Assert.Equal(0, surface[75, 70].A); + } + + /// + /// Proves that the system rejects a null stream argument to + /// + /// with through the public API. See + /// SvgCodecTests for the full unit test coverage of the other null-argument + /// variants (null path, GetInfo overloads). + /// + [Fact] + public void CanvasNetSvg_SystemIntegration_SvgValidationNull_NullStreamThrowsArgumentNullException() + { + // Arrange, Act & Assert: passing a null stream through the public API is rejected + Assert.Throws(() => SvgCodec.Load((Stream)null!, 10, 10)); + } + + /// + /// Proves that the system rejects an empty path argument to + /// + /// with through the public API. See + /// SvgCodecTests for the full unit test coverage of the whitespace-only variant. + /// + [Fact] + public void CanvasNetSvg_SystemIntegration_SvgValidationEmptyPath_EmptyPathThrowsArgumentException() + { + // Arrange, Act & Assert: passing an empty path through the public API is rejected + Assert.Throws(() => SvgCodec.Load(string.Empty, 10, 10)); + } + + /// + /// Proves that the system rejects malformed (non-well-formed) SVG XML with + /// through the public API. See SvgCodecTests for + /// the full unit test coverage of the other malformed-input variants (viewBox, transform, + /// path data). + /// + [Fact] + public void CanvasNetSvg_SystemIntegration_SvgUnsupportedFormatValidation_MalformedXmlThrowsInvalidDataException() + { + // Arrange: an unclosed root element - not well-formed XML + const string svg = "(() => SvgCodec.Load(stream, 100, 100)); + } + + /// + /// Proves that the system rejects an SVG document containing a DOCTYPE declaration with + /// through the public API, defending against XXE + /// injection. See SvgCodecTests for the full unit test coverage of the external + /// entity variant and the GetInfo path. + /// + [Fact] + public void CanvasNetSvg_SystemIntegration_SvgXxeHardening_DoctypeDeclarationThrowsInvalidDataException() + { + // Arrange: a well-formed document that is otherwise entirely valid, except for a DOCTYPE + // declaration + const string svg = "]>"; + + // Act & Assert: the DOCTYPE-bearing document is rejected through the public API + using var stream = ToStream(svg); + Assert.Throws(() => SvgCodec.Load(stream, 100, 100)); + } + + /// + /// Proves that the system silently skips well-formed but out-of-scope SVG constructs, + /// continuing to render the rest of the document, through the public API. See + /// SvgCodecTests for the full unit test coverage of individual unsupported + /// construct kinds. + /// + [Fact] + public void CanvasNetSvg_SystemIntegration_SvgTolerateUnsupportedConstructs_StillRendersRestOfDocument() + { + // Arrange: a nested inner element is out of scope; the sibling plain rect after it + // should still render + const string svg = """ + + + + + """; + + // Act: rasterize the document onto a new Surface through the public API + using var stream = ToStream(svg); + var surface = SvgCodec.Load(stream, 100, 100); + + // Assert: the plain rect after the unsupported construct still rendered + Assert.Equal(255, surface[20, 20].A); + } + + /// + /// Proves that the system rejects a null stream argument to + /// with the same contract as + /// , + /// through the public API. See SvgCodecTests for the full unit test coverage of the + /// other GetInfo validation variants. + /// + [Fact] + public void CanvasNetSvg_SystemIntegration_SvgGetInfoValidation_NullStreamThrowsArgumentNullException() + { + // Arrange, Act & Assert: passing a null stream to GetInfo through the public API is + // rejected exactly as Load rejects one + Assert.Throws(() => SvgCodec.GetInfo((Stream)null!)); + } +} diff --git a/test/DemaConsulting.CanvasNet.Tests/CanvasNetTests.cs b/test/DemaConsulting.CanvasNet.Tests/CanvasNetTests.cs index 3a3ef9e84..cce477e74 100644 --- a/test/DemaConsulting.CanvasNet.Tests/CanvasNetTests.cs +++ b/test/DemaConsulting.CanvasNet.Tests/CanvasNetTests.cs @@ -372,52 +372,6 @@ public void CanvasNet_SystemIntegration_GifLoad_ReturnsExpectedPixel() Assert.Equal(new Rgba32(11, 22, 33, 255), surface[0, 0]); } - /// - /// Proves that the system can rasterize an SVG document into a Surface through the public - /// API, producing the expected integrated pixel result for a shape filled with a solid - /// color. Unlike the BMP/PNG/TIFF/JPEG system-integration tests above, there is no "Save" - /// half to this round-trip: SvgCodec is decode/rasterize-only (see SvgCodecTests/ - /// SvgFixtureTests for the full unit test coverage). - /// - [Fact] - public void CanvasNet_SystemIntegration_SvgLoad_ReturnsExpectedPixel() - { - // Arrange: a minimal SVG document with a viewBox matching the requested raster exactly, - // containing one rectangle filled with a distinct, fully opaque color - const string svg = ""; - using var stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(svg)); - - // Act: rasterize the document onto a new Surface through the public API - var surface = SvgCodec.Load(stream, 10, 10); - - // Assert: the system produces the expected integrated rasterized pixel value - Assert.Equal(new Rgba32(11, 22, 33, 255), surface[5, 5]); - } - - /// - /// Proves that the system can rasterize an SVG document whose color comes entirely from a - /// <style> element's CSS class selector - rather than a plain presentation - /// attribute - through the public API, integrating the whole CSS engine (style-element - /// parsing, selector matching, and the cascade chokepoint) with the rest of the rendering - /// pipeline. See SvgCodecTests/SvgFixtureTests for the full unit test - /// coverage of individual selectors/combinators/precedence tiers. - /// - [Fact] - public void CanvasNet_SystemIntegration_SvgLoadWithCssStyleElement_ReturnsExpectedPixel() - { - // Arrange: a minimal SVG document whose only source of color is a stylesheet class rule - - // the rect itself carries no fill attribute at all - const string svg = "" + - ""; - using var stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(svg)); - - // Act: rasterize the document onto a new Surface through the public API - var surface = SvgCodec.Load(stream, 10, 10); - - // Assert: the system produces the expected integrated rasterized pixel value - Assert.Equal(new Rgba32(11, 22, 33, 255), surface[5, 5]); - } - /// /// Proves that the system can composite a semi-transparent constant color over a Surface /// through the public API, producing the expected Porter-Duff "over" result. @@ -592,6 +546,31 @@ public void CanvasNet_SystemIntegration_BuildFlattenAndBoundPath_ReturnsExpected Assert.True(bounds.Height > 0); } + /// + /// Proves that the system can synthesize a standalone line-segment command via the public + /// factory and compute a sane tangent direction from it + /// via , through the public API - the shared + /// building block an external format-codec package (such as the SVG codec's marker/ + /// arrowhead rendering) needs to orient a decoration at a path segment's end, without + /// depending on this package's internal Path/PathBuilder construction. + /// + [Fact] + public void CanvasNet_SystemIntegration_LineToAndComputeTangents_ReturnsNormalizedDirection() + { + // Arrange: a standalone horizontal line segment from (0,0) to (10,0), synthesized + // directly via the public LineTo factory rather than via PathBuilder + var command = PathCommand.LineTo(new Vector2(10, 0)); + + // Act: compute the command's outgoing/incoming tangents from its start point + var (outgoing, incoming) = command.ComputeTangents(new Vector2(0, 0)); + + // Assert: both tangents are the same sane, unit-length direction of travel + Assert.NotNull(outgoing); + Assert.NotNull(incoming); + Assert.Equal(new Vector2(1, 0), outgoing); + Assert.Equal(new Vector2(1, 0), incoming); + } + /// /// Proves that the system silently no-ops, through PathFiller's public API, when filling /// an empty Path or a Path whose bounds do not intersect the target Surface - in both diff --git a/test/DemaConsulting.CanvasNet.Tests/DemaConsulting.CanvasNet.Tests.csproj b/test/DemaConsulting.CanvasNet.Tests/DemaConsulting.CanvasNet.Tests.csproj index 2be212ee9..f1dd78df7 100644 --- a/test/DemaConsulting.CanvasNet.Tests/DemaConsulting.CanvasNet.Tests.csproj +++ b/test/DemaConsulting.CanvasNet.Tests/DemaConsulting.CanvasNet.Tests.csproj @@ -93,13 +93,6 @@ - - - - PreserveNewest - - - diff --git a/test/DemaConsulting.CanvasNet.Tests/Geometry/PathCommandTests.cs b/test/DemaConsulting.CanvasNet.Tests/Geometry/PathCommandTests.cs new file mode 100644 index 000000000..16a59c3c4 --- /dev/null +++ b/test/DemaConsulting.CanvasNet.Tests/Geometry/PathCommandTests.cs @@ -0,0 +1,262 @@ +using System.Numerics; +using DemaConsulting.CanvasNet.Geometry; + +namespace DemaConsulting.CanvasNet.Tests.Geometry; + +/// +/// Unit tests for the PathCommand type's public API: the LineTo factory method and the +/// ComputeTangents instance method. +/// +public class PathCommandTests +{ + /// + /// Asserts that two unit-direction vectors are equal within a small tolerance, rather + /// than requiring bit-exact equality. computes + /// its result via an intermediate pipeline (to avoid the + /// float-precision overflow covered by other tests in this class), which can legitimately + /// differ from a purely -precision reference computation (such as + /// ) in the last representable bit, without either + /// result being wrong. + /// + /// The expected unit direction, computed via a reference method. + /// The actual unit direction returned by the method under test. + private static void AssertDirectionApproximatelyEqual(Vector2 expected, Vector2? actual) + { + Assert.NotNull(actual); + Assert.True( + Vector2.Distance(expected, actual.Value) < 1e-6f, + $"Expected direction approximately {expected} but was {actual.Value}."); + } + + /// + /// Proves that the public LineTo factory constructs a LineTo command carrying the given + /// end point, usable by a consumer outside this package that needs to synthesize a + /// standalone straight-line command (for example, an implicit closing edge that is not + /// itself recorded as its own PathCommand). + /// + [Fact] + public void PathCommand_LineTo_GivenEndPoint_ConstructsLineToCommandWithThatEndPoint() + { + // Arrange + var end = new Vector2(3, 4); + + // Act + var command = PathCommand.LineTo(end); + + // Assert + Assert.Equal(PathCommandType.LineTo, command.Type); + Assert.Equal(end, command.EndPoint); + } + + /// + /// Proves that a LineTo command's outgoing and incoming tangents are both the normalized + /// direction of travel from its start point to its end point. + /// + [Fact] + public void PathCommand_ComputeTangents_LineTo_ReturnsSameNormalizedDirectionForBothTangents() + { + // Arrange: a horizontal line segment from (0,0) to (5,0) + var command = PathCommand.LineTo(new Vector2(5, 0)); + + // Act + var (outgoing, incoming) = command.ComputeTangents(new Vector2(0, 0)); + + // Assert + Assert.Equal(new Vector2(1, 0), outgoing); + Assert.Equal(new Vector2(1, 0), incoming); + } + + /// + /// Proves that a LineTo command whose start and end points coincide has no meaningful + /// direction, returning null for both tangents rather than an undefined normalized + /// zero-length vector. + /// + [Fact] + public void PathCommand_ComputeTangents_LineToWithCoincidentStartAndEnd_ReturnsNullTangents() + { + // Arrange + var point = new Vector2(2, 2); + var command = PathCommand.LineTo(point); + + // Act + var (outgoing, incoming) = command.ComputeTangents(point); + + // Assert + Assert.Null(outgoing); + Assert.Null(incoming); + } + + /// + /// Proves that a LineTo command with very large but finite coordinates (magnitudes around + /// 1e20 to 1e25) still returns a valid unit tangent rather than null. Squaring such large + /// components in float precision overflows to positive infinity well before the + /// coordinates themselves overflow, which previously caused NormalizeOrNull to + /// misclassify a perfectly valid direction as degenerate. + /// + [Fact] + public void PathCommand_ComputeTangents_LineToWithLargeFiniteCoordinates_ReturnsValidNormalizedDirection() + { + // Arrange: a horizontal line segment whose end point has a huge but finite X coordinate + var start = new Vector2(1e20f, 0f); + var command = PathCommand.LineTo(new Vector2(1e25f, 0f)); + + // Act + var (outgoing, incoming) = command.ComputeTangents(start); + + // Assert: the direction is purely along +X, so both tangents are the unit X vector + Assert.NotNull(outgoing); + Assert.NotNull(incoming); + Assert.Equal(new Vector2(1, 0), outgoing); + Assert.Equal(new Vector2(1, 0), incoming); + } + + /// + /// Proves that a LineTo command still returns a valid unit tangent when its start and end + /// points are individually finite but so far apart (near opposite ends of the float + /// range) that computing their delta as a float Vector2 subtraction would itself overflow + /// to positive/negative infinity, before any widening of the squared-length step ever gets + /// a chance to help. The delta itself must be computed in double precision. + /// + [Fact] + public void PathCommand_ComputeTangents_LineToWithFarApartNearMaxFiniteCoordinates_ReturnsValidNormalizedDirection() + { + // Arrange: a horizontal line segment whose endpoints are each individually finite, but + // whose float-precision delta (EndPoint - start) would overflow to infinity + var start = new Vector2(-float.MaxValue, 0f); + var command = PathCommand.LineTo(new Vector2(float.MaxValue, 0f)); + + // Act + var (outgoing, incoming) = command.ComputeTangents(start); + + // Assert: the direction is unambiguously +X, so both tangents are the unit X vector + Assert.NotNull(outgoing); + Assert.NotNull(incoming); + Assert.Equal(new Vector2(1, 0), outgoing); + Assert.Equal(new Vector2(1, 0), incoming); + } + + /// + /// Proves that a QuadraticBezierTo command's outgoing tangent points toward its control + /// point, and its incoming tangent points away from that same control point toward its + /// end point. + /// + [Fact] + public void PathCommand_ComputeTangents_QuadraticBezierTo_PointsTowardThenAwayFromControlPoint() + { + // Arrange: a quadratic curve bowing upward from (0,0) to (4,0) via control (2,4) + var start = new Vector2(0, 0); + var control = new Vector2(2, 4); + var end = new Vector2(4, 0); + var command = PathCommand.QuadraticBezierTo(control, end); + + // Act + var (outgoing, incoming) = command.ComputeTangents(start); + + // Assert + AssertDirectionApproximatelyEqual(Vector2.Normalize(control - start), outgoing); + AssertDirectionApproximatelyEqual(Vector2.Normalize(end - control), incoming); + } + + /// + /// Proves that a QuadraticBezierTo command whose control point coincides with its start + /// point falls back to the straight start-to-end direction for its outgoing tangent, + /// rather than an undefined zero-length direction. + /// + [Fact] + public void PathCommand_ComputeTangents_QuadraticBezierToWithControlCoincidentWithStart_FallsBackToEndDirection() + { + // Arrange: control point equals start, so the curve is effectively a straight line + var start = new Vector2(0, 0); + var end = new Vector2(4, 0); + var command = PathCommand.QuadraticBezierTo(start, end); + + // Act + var (outgoing, incoming) = command.ComputeTangents(start); + + // Assert + AssertDirectionApproximatelyEqual(Vector2.Normalize(end - start), outgoing); + AssertDirectionApproximatelyEqual(Vector2.Normalize(end - start), incoming); + } + + /// + /// Proves that a CubicBezierTo command's outgoing tangent points toward its first control + /// point, and its incoming tangent points away from its second control point. + /// + [Fact] + public void PathCommand_ComputeTangents_CubicBezierTo_PointsTowardFirstThenAwayFromSecondControlPoint() + { + // Arrange: an S-shaped cubic curve from (0,0) to (6,0) + var start = new Vector2(0, 0); + var control1 = new Vector2(1, 3); + var control2 = new Vector2(5, -3); + var end = new Vector2(6, 0); + var command = PathCommand.CubicBezierTo(control1, control2, end); + + // Act + var (outgoing, incoming) = command.ComputeTangents(start); + + // Assert + AssertDirectionApproximatelyEqual(Vector2.Normalize(control1 - start), outgoing); + AssertDirectionApproximatelyEqual(Vector2.Normalize(end - control2), incoming); + } + + /// + /// Proves that a CubicBezierTo command whose control points both coincide with its start + /// and end points respectively falls back, in stages, to the straight start-to-end + /// direction for both tangents. + /// + [Fact] + public void PathCommand_ComputeTangents_CubicBezierToWithBothControlPointsCoincidentWithEndpoints_FallsBackToEndDirection() + { + // Arrange: both control points equal their nearest endpoint, so the curve is effectively + // a straight line + var start = new Vector2(0, 0); + var end = new Vector2(6, 0); + var command = PathCommand.CubicBezierTo(start, end, end); + + // Act + var (outgoing, incoming) = command.ComputeTangents(start); + + // Assert + AssertDirectionApproximatelyEqual(Vector2.Normalize(end - start), outgoing); + AssertDirectionApproximatelyEqual(Vector2.Normalize(end - start), incoming); + } + + /// + /// Proves that an ArcTo command returns null for both tangents: this method deliberately + /// does not compute an arc's tangent directly, since doing so correctly requires the same + /// Bezier conversion SvgArcConverter already performs, which this method does not + /// duplicate. + /// + [Fact] + public void PathCommand_ComputeTangents_ArcTo_ReturnsNullTangents() + { + // Arrange + var command = PathCommand.ArcTo(new Vector2(1, 1), 0, largeArc: false, sweep: false, new Vector2(2, 2)); + + // Act + var (outgoing, incoming) = command.ComputeTangents(new Vector2(0, 0)); + + // Assert + Assert.Null(outgoing); + Assert.Null(incoming); + } + + /// + /// Proves that a Close command returns null for both tangents: it carries no EndPoint of + /// its own to compute a direction from. + /// + [Fact] + public void PathCommand_ComputeTangents_Close_ReturnsNullTangents() + { + // Arrange + var command = PathCommand.Close(); + + // Act + var (outgoing, incoming) = command.ComputeTangents(new Vector2(0, 0)); + + // Assert + Assert.Null(outgoing); + Assert.Null(incoming); + } +}