From dcf2e4c72afedfc6f6cc1c69b3f9a9f484543ec3 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?S=C3=A9bastien=20Ros?=
<1165805+sebastienros@users.noreply.github.com>
Date: Sun, 29 Nov 2026 22:45:30 +0000
Subject: [PATCH] Add static SVG rendering through DrawingCanvas
SvgDocument loads an SVG document once into an immutable form
(SvgDocument.Load and Parse, with SvgLoadOptions and SvgLimits), and
DrawingCanvas.DrawSvg draws it through the existing canvas, so it works
with every backend and needs no native code. The code is in
src/ImageSharp.Drawing/Svg; everything there except SvgDocument,
SvgLoadOptions, SvgLimits, and SvgGenericFontFamilies is internal.
Supported: document structure with use, symbol, switch, and nested
viewports; shapes, paths, strokes with dashes and markers; gradients
and patterns; clipPath, mask, opacity, and blend modes; images (data
URIs, and files inside SvgLoadOptions.ResourceBaseDirectory); text with
textPath, bidirectional text, and font fallback; the filter primitives
of Filter Effects 1 and the CSS filter functions; CSS style sheets with
selectors level 4, custom properties, math functions, media queries,
and CSS Color 4 colors. Not supported: animation, scripting, SVG fonts,
and network references.
The resvg test suite (fetched by tests/SvgTools, not stored in the
repository) passes 1179 of the 1618 tests that the test run includes.
Changes outside the Svg folder, with no new public members:
- Path.TryParseSvgPath reads numbers with an exponent and starts the
command after Z at the right point.
- A path clip keeps the rows of its last band instead of rasterizing
the band for every row.
- SplitPathExtensions.GenerateDashes and CubicBezierLineSegment end for
geometry that they cannot walk or flatten.
- A canvas from CreateRegion places gradient brushes, layer effects,
and Apply in its own coordinates (CPU backend).
- Row loops for solid, gradient, and image brushes; reusable layer
band buffers; stored coverage of small fills in a retained scene.
src/ImageSharp.Drawing/Svg/SVG_DESIGN.md describes the design, the
measurements, and the known differences from browsers;
SVG_DECISIONS.md lists the choices made and their reasons.
---
.gitignore | 3 +
THIRD-PARTY-NOTICES | 158 +
.../CubicBezierLineSegment.cs | 165 +-
.../FlattenedPointBuilder.cs | 37 +-
.../Helpers/ValueListBuilder.cs | 7 +
src/ImageSharp.Drawing/Path.cs | 121 +-
.../Processing/Backends/CompositionCommand.cs | 8 +
.../Backends/DEFAULT_DRAWING_BACKEND.md | 32 +-
.../Processing/Backends/DEFAULT_RASTERIZER.md | 6 +-
.../Backends/DefaultDrawingBackend.Helpers.cs | 656 ++-
.../Backends/DefaultDrawingBackend.cs | 296 +-
.../Backends/DefaultRasterizer.Linearizer.cs | 303 +-
.../DefaultRasterizer.RetainedTypes.cs | 129 +-
.../DefaultRasterizer.StrokeLinearizer.cs | 80 +-
.../Backends/DrawingBackendScene.cs | 5 +
.../Backends/DrawingCommandBatch.cs | 32 +
.../Backends/FlushScene.RetainedTypes.cs | 17 +-
.../Backends/FlushScene.StoredCoverage.cs | 341 ++
.../Processing/Backends/FlushScene.cs | 5 +
.../Backends/ParallelExecutionHelper.cs | 19 +
.../Processing/Backends/StrokePathCommand.cs | 8 +
.../Processing/DRAWING_CANVAS.md | 10 +
.../Processing/DrawingCanvas.Svg.cs | 56 +
.../Processing/DrawingCanvas.cs | 72 +
.../DrawingCanvasBatcher{TPixel}.cs | 55 +-
.../Processing/DrawingCanvas{TPixel}.cs | 124 +-
.../Processing/GradientBrush.cs | 336 +-
.../Processing/ImageBrush.cs | 327 +-
.../Processing/LayerEffect.cs | 19 +
.../Processing/LinearGradientBrush.cs | 22 +
.../Processing/RadialGradientBrush.cs | 22 +-
.../Processing/SolidBrush.cs | 461 +-
src/ImageSharp.Drawing/SplitPathExtensions.cs | 41 +
.../Svg/Css/SvgBasicShapeKind.cs | 63 +
.../Svg/Css/SvgBlendMode.cs | 90 +
src/ImageSharp.Drawing/Svg/Css/SvgCascade.cs | 187 +
.../Svg/Css/SvgClipShape.cs | 78 +
.../Svg/Css/SvgColorInterpolation.cs | 25 +
.../Svg/Css/SvgCssAttributeOperator.cs | 45 +
.../Svg/Css/SvgCssAttributeSelector.cs | 47 +
.../Svg/Css/SvgCssAttributeValues.cs | 119 +
.../Svg/Css/SvgCssCombinator.cs | 35 +
.../Svg/Css/SvgCssComplexSelector.cs | 39 +
.../Svg/Css/SvgCssCompoundSelector.cs | 39 +
.../Svg/Css/SvgCssFunctionalSelector.cs | 56 +
.../Svg/Css/SvgCssLanguageRanges.cs | 131 +
.../Svg/Css/SvgCssMatcher.cs | 978 ++++
.../Svg/Css/SvgCssMediaQuery.cs | 925 ++++
.../Svg/Css/SvgCssParser.cs | 695 +++
src/ImageSharp.Drawing/Svg/Css/SvgCssRule.cs | 85 +
.../Svg/Css/SvgCssSelectorEquality.cs | 259 +
.../Svg/Css/SvgCssSelectorParser.cs | 1419 ++++++
.../Svg/Css/SvgCssSimpleSelector.cs | 46 +
.../Svg/Css/SvgCssSimpleSelectorKind.cs | 124 +
src/ImageSharp.Drawing/Svg/Css/SvgCssToken.cs | 92 +
.../Svg/Css/SvgCssTokenKind.cs | 135 +
.../Svg/Css/SvgCssTokenizer.cs | 637 +++
.../Svg/Css/SvgCustomProperties.cs | 160 +
.../Svg/Css/SvgCustomPropertyKind.cs | 25 +
.../Svg/Css/SvgCustomPropertyResolver.cs | 168 +
.../Svg/Css/SvgCustomPropertyValue.cs | 33 +
.../Svg/Css/SvgDashArray.cs | 58 +
.../Svg/Css/SvgDeclarationOrigin.cs | 27 +
src/ImageSharp.Drawing/Svg/Css/SvgDisplay.cs | 21 +
.../Svg/Css/SvgExtendedStyle.cs | 309 ++
src/ImageSharp.Drawing/Svg/Css/SvgFillRule.cs | 20 +
.../Svg/Css/SvgGeometryBox.cs | 55 +
.../Svg/Css/SvgGeometryStyle.cs | 271 ++
.../Svg/Css/SvgImageRendering.cs | 46 +
.../Svg/Css/SvgIsolation.cs | 20 +
src/ImageSharp.Drawing/Svg/Css/SvgMaskType.cs | 20 +
src/ImageSharp.Drawing/Svg/Css/SvgOverflow.cs | 33 +
.../Svg/Css/SvgPaintOrder.cs | 43 +
.../Svg/Css/SvgPendingValue.cs | 42 +
.../Svg/Css/SvgPropertyId.cs | 451 ++
.../Svg/Css/SvgPropertyParser.Geometry.cs | 669 +++
.../Svg/Css/SvgPropertyParser.Text.cs | 1622 +++++++
.../Svg/Css/SvgPropertyParser.Variables.cs | 129 +
.../Svg/Css/SvgPropertyParser.cs | 1055 ++++
.../Svg/Css/SvgPropertySet.cs | 177 +
.../Svg/Css/SvgShapePosition.cs | 57 +
.../Svg/Css/SvgShapeRadiusKind.cs | 25 +
.../Svg/Css/SvgShapeRendering.cs | 30 +
.../Svg/Css/SvgShorthand.cs | 44 +
.../Svg/Css/SvgSpecifiedStyle.cs | 523 ++
.../Svg/Css/SvgStrokeLineCap.cs | 25 +
.../Svg/Css/SvgStrokeLineJoin.cs | 35 +
.../Svg/Css/SvgStyleSheet.cs | 333 ++
.../Svg/Css/SvgStyleSources.cs | 43 +
.../Svg/Css/SvgSubstitutionBudget.cs | 66 +
.../Svg/Css/SvgTransformBox.cs | 39 +
.../Svg/Css/SvgVariableStyle.cs | 197 +
.../Svg/Css/SvgVariableSubstitution.cs | 377 ++
.../Svg/Css/SvgVectorEffect.cs | 20 +
.../Svg/Css/SvgVisibility.cs | 25 +
.../Svg/Filters/SvgEmitter.Filter.cs | 178 +
.../Svg/Filters/SvgFeBlend.cs | 97 +
.../Svg/Filters/SvgFeColorMatrix.cs | 215 +
.../Svg/Filters/SvgFeComponentTransfer.cs | 350 ++
.../Svg/Filters/SvgFeComposite.cs | 250 +
.../Svg/Filters/SvgFeConvolveMatrix.cs | 414 ++
.../Svg/Filters/SvgFeDiffuseLighting.cs | 80 +
.../Svg/Filters/SvgFeDisplacementMap.cs | 206 +
.../Svg/Filters/SvgFeDropShadow.cs | 175 +
.../Svg/Filters/SvgFeFlood.cs | 50 +
.../Svg/Filters/SvgFeGaussianBlur.cs | 600 +++
.../Svg/Filters/SvgFeImage.cs | 102 +
.../Svg/Filters/SvgFeMerge.cs | 114 +
.../Svg/Filters/SvgFeMorphology.cs | 440 ++
.../Svg/Filters/SvgFeOffset.cs | 201 +
.../Svg/Filters/SvgFePassThrough.cs | 38 +
.../Svg/Filters/SvgFeSpecularLighting.cs | 106 +
.../Svg/Filters/SvgFeTile.cs | 112 +
.../Svg/Filters/SvgFeTransparent.cs | 25 +
.../Svg/Filters/SvgFeTurbulence.cs | 406 ++
.../Svg/Filters/SvgFilterAttributeValue.cs | 67 +
.../Svg/Filters/SvgFilterAttributes.cs | 50 +
.../Svg/Filters/SvgFilterBuildContext.cs | 275 ++
.../Svg/Filters/SvgFilterBuildResult.cs | 38 +
.../Svg/Filters/SvgFilterBuilder.cs | 199 +
.../Svg/Filters/SvgFilterColor.cs | 248 +
.../Svg/Filters/SvgFilterEngine.cs | 1100 +++++
.../Svg/Filters/SvgFilterFunction.cs | 80 +
.../Svg/Filters/SvgFilterFunctionKind.cs | 66 +
.../Svg/Filters/SvgFilterGraph.cs | 70 +
.../Svg/Filters/SvgFilterImage.cs | 193 +
.../Svg/Filters/SvgFilterList.cs | 24 +
.../Svg/Filters/SvgFilterNode.cs | 55 +
.../Svg/Filters/SvgFilterOutcome.cs | 25 +
.../Svg/Filters/SvgFilterPrefetch.cs | 246 +
.../Svg/Filters/SvgFilterPrimitive.cs | 143 +
.../Filters/SvgFilterPrimitiveAttributes.cs | 84 +
.../Svg/Filters/SvgFilterRenderContext.cs | 121 +
.../Svg/Filters/SvgFilterScope.cs | 60 +
.../Svg/Filters/SvgFilterStyle.cs | 170 +
.../Svg/Filters/SvgFilterTables.cs | 252 +
.../Svg/Filters/SvgLightSource.cs | 265 +
.../Svg/Filters/SvgLighting.cs | 209 +
.../Svg/Filters/SvgPropertyParser.Filter.cs | 348 ++
.../Svg/Filters/SvgResolver.Filter.cs | 620 +++
.../Svg/Parsing/SvgAlign.cs | 60 +
.../Svg/Parsing/SvgAttributeId.cs | 531 ++
src/ImageSharp.Drawing/Svg/Parsing/SvgCalc.cs | 933 ++++
.../Svg/Parsing/SvgCalcExpression.cs | 148 +
.../Svg/Parsing/SvgCalcKind.cs | 35 +
.../Svg/Parsing/SvgCalcOperation.cs | 40 +
.../Svg/Parsing/SvgCalcOperationCode.cs | 50 +
.../Svg/Parsing/SvgCalcResult.cs | 47 +
.../Svg/Parsing/SvgCalcTable.cs | 142 +
.../Svg/Parsing/SvgCalcVariables.cs | 49 +
.../Svg/Parsing/SvgCircleAttributes.cs | 36 +
.../Svg/Parsing/SvgColorCache.cs | 37 +
.../Svg/Parsing/SvgColorParser.Css4.cs | 912 ++++
.../Svg/Parsing/SvgColorParser.cs | 389 ++
.../Svg/Parsing/SvgColorSpace.cs | 85 +
.../Svg/Parsing/SvgConditionalAttributes.cs | 31 +
.../Svg/Parsing/SvgCoordinateUnits.cs | 32 +
.../Svg/Parsing/SvgCssColor.cs | 690 +++
.../Svg/Parsing/SvgCssTransform.cs | 685 +++
.../Svg/Parsing/SvgElement.cs | 83 +
.../Svg/Parsing/SvgElementKind.cs | 311 ++
.../Svg/Parsing/SvgElementTree.cs | 503 ++
.../Svg/Parsing/SvgGradientAttributes.cs | 92 +
.../Svg/Parsing/SvgImageAttributes.cs | 44 +
.../Svg/Parsing/SvgLength.cs | 218 +
.../Svg/Parsing/SvgLengthUnit.cs | 110 +
.../Svg/Parsing/SvgLineAttributes.cs | 30 +
.../Svg/Parsing/SvgMarkerAttributes.cs | 58 +
.../Svg/Parsing/SvgMarkerOrient.cs | 65 +
.../Svg/Parsing/SvgMarkerOrientKind.cs | 30 +
.../Svg/Parsing/SvgMarkerUnits.cs | 25 +
.../Svg/Parsing/SvgMaskAttributes.cs | 43 +
.../Svg/Parsing/SvgNameTable.cs | 81 +
.../Svg/Parsing/SvgNames.cs | 364 ++
.../Svg/Parsing/SvgNumberParser.cs | 415 ++
.../Svg/Parsing/SvgPaint.cs | 185 +
.../Svg/Parsing/SvgPaintKind.cs | 42 +
.../Svg/Parsing/SvgPathAttributes.cs | 21 +
.../Svg/Parsing/SvgPatternAttributes.cs | 119 +
.../Svg/Parsing/SvgPointsAttributes.cs | 40 +
.../Svg/Parsing/SvgPreserveAspectRatio.cs | 127 +
.../Svg/Parsing/SvgReader.cs | 2027 ++++++++
.../Svg/Parsing/SvgReaderOptions.cs | 76 +
.../Svg/Parsing/SvgRectAttributes.cs | 42 +
.../Svg/Parsing/SvgReference.cs | 99 +
.../Svg/Parsing/SvgSpreadMethod.cs | 30 +
.../Svg/Parsing/SvgStringPool.cs | 39 +
.../Svg/Parsing/SvgTransformParser.cs | 137 +
.../Svg/Parsing/SvgUseAttributes.cs | 37 +
.../Svg/Parsing/SvgViewportAttributes.cs | 46 +
.../Svg/Rendering/SvgDeferredPaint.cs | 116 +
.../Svg/Rendering/SvgDrawFlags.cs | 33 +
.../Svg/Rendering/SvgEmitter.Compositing.cs | 138 +
.../Svg/Rendering/SvgEmitter.Layers.cs | 136 +
.../Svg/Rendering/SvgEmitter.cs | 663 +++
.../Svg/Rendering/SvgImagePaint.cs | 59 +
.../Svg/Rendering/SvgMaskLayerEffect.cs | 204 +
.../Svg/Rendering/SvgMaskMode.cs | 27 +
.../Svg/Rendering/SvgPatternPaint.cs | 122 +
.../Svg/Rendering/SvgPatternTile.cs | 129 +
.../Svg/Rendering/SvgPatternTileStore.cs | 193 +
.../Svg/Rendering/SvgRenderNode.cs | 100 +
.../Svg/Rendering/SvgRenderNodeKind.cs | 63 +
.../Svg/Rendering/SvgSceneAllocator.cs | 139 +
.../Svg/Rendering/SvgSceneCache.cs | 699 +++
.../Svg/Rendering/SvgTexture.cs | 243 +
.../Svg/Rendering/SvgTextureBrush.cs | 611 +++
.../Svg/Resolve/SvgClipKind.cs | 34 +
.../Svg/Resolve/SvgClipScope.cs | 39 +
.../Svg/Resolve/SvgClipTarget.cs | 68 +
.../Svg/Resolve/SvgCompositeScope.cs | 76 +
.../Svg/Resolve/SvgComputedStyle.Equality.cs | 186 +
.../Svg/Resolve/SvgComputedStyle.Geometry.cs | 47 +
.../Svg/Resolve/SvgComputedStyle.Variables.cs | 164 +
.../Svg/Resolve/SvgComputedStyle.cs | 1007 ++++
.../Svg/Resolve/SvgGradientKey.cs | 75 +
.../Svg/Resolve/SvgImageSource.cs | 409 ++
.../Svg/Resolve/SvgPaintCache.cs | 573 +++
.../Svg/Resolve/SvgPenKey.cs | 93 +
.../Svg/Resolve/SvgPooledList.cs | 200 +
.../Svg/Resolve/SvgResolveContext.cs | 72 +
.../Svg/Resolve/SvgResolvedGradient.cs | 57 +
.../Svg/Resolve/SvgResolver.Clip.cs | 620 +++
.../Svg/Resolve/SvgResolver.ClipShape.cs | 757 +++
.../Svg/Resolve/SvgResolver.Compositing.cs | 383 ++
.../Svg/Resolve/SvgResolver.Context.cs | 288 ++
.../Svg/Resolve/SvgResolver.Geometry.cs | 372 ++
.../Svg/Resolve/SvgResolver.Image.cs | 496 ++
.../Svg/Resolve/SvgResolver.Markers.cs | 670 +++
.../Svg/Resolve/SvgResolver.Mask.cs | 215 +
.../Svg/Resolve/SvgResolver.PathLength.cs | 121 +
.../Svg/Resolve/SvgResolver.Pattern.cs | 412 ++
.../Svg/Resolve/SvgResolver.Structure.cs | 88 +
.../Svg/Resolve/SvgResolver.Switch.cs | 209 +
.../Svg/Resolve/SvgResolver.Text.cs | 483 ++
.../Resolve/SvgResolver.TextDecorations.cs | 426 ++
.../Svg/Resolve/SvgResolver.cs | 1781 +++++++
.../Svg/Resolve/SvgStyleCache.cs | 525 ++
.../Svg/Resolve/SvgStyleContext.cs | 204 +
.../Svg/Resolve/SvgTransformTable.cs | 145 +
.../Svg/Resolve/SvgUnitBasis.cs | 108 +
.../Svg/Resolve/SvgUnits.cs | 128 +
.../Svg/Resolve/SvgViewBoxTransform.cs | 67 +
src/ImageSharp.Drawing/Svg/SVG_DECISIONS.md | 861 ++++
src/ImageSharp.Drawing/Svg/SVG_DESIGN.md | 2512 ++++++++++
.../Svg/SvgDocument.Render.cs | 230 +
src/ImageSharp.Drawing/Svg/SvgDocument.cs | 218 +
.../Svg/SvgGenericFontFamilies.cs | 138 +
src/ImageSharp.Drawing/Svg/SvgIntegerMath.cs | 26 +
src/ImageSharp.Drawing/Svg/SvgLimits.cs | 265 +
src/ImageSharp.Drawing/Svg/SvgLoadOptions.cs | 255 +
.../Svg/Text/Bidi/ArrayBuilder{T}.cs | 201 +
.../Svg/Text/Bidi/ArraySlice{T}.cs | 216 +
.../Svg/Text/Bidi/BidiAlgorithm.cs | 1642 +++++++
.../Bidi/BidiData.AsciiTables.Generated.cs | 75 +
.../Svg/Text/Bidi/BidiData.cs | 307 ++
.../Svg/Text/Bidi/BidiDictionary{T1,T2}.cs | 47 +
.../Svg/Text/Bidi/MappedArraySlice{T}.cs | 59 +
.../Svg/Text/Bidi/ReadOnlyArraySlice{T}.cs | 206 +
.../Text/Bidi/ReadOnlyMappedArraySlice{T}.cs | 59 +
.../Svg/Text/SvgAlignmentBaseline.cs | 95 +
.../Svg/Text/SvgBaselineShiftKind.cs | 30 +
.../Svg/Text/SvgDirection.cs | 20 +
.../Svg/Text/SvgDominantBaseline.cs | 80 +
.../Svg/Text/SvgFontChain.cs | 142 +
.../Svg/Text/SvgFontFace.cs | 93 +
.../Svg/Text/SvgFontFallback.cs | 206 +
.../Svg/Text/SvgFontFamilyName.cs | 86 +
.../Svg/Text/SvgFontFeatureSetting.cs | 34 +
.../Svg/Text/SvgFontKerning.cs | 25 +
src/ImageSharp.Drawing/Svg/Text/SvgFontKey.cs | 94 +
.../Svg/Text/SvgFontMatcher.cs | 447 ++
.../Svg/Text/SvgFontStyle.cs | 25 +
.../Svg/Text/SvgFontVariant.cs | 45 +
.../Svg/Text/SvgFontVariantEastAsian.cs | 62 +
.../Svg/Text/SvgFontVariantLigatures.cs | 62 +
.../Svg/Text/SvgFontVariantNumeric.cs | 57 +
.../Svg/Text/SvgFontVariantPosition.cs | 25 +
.../Svg/Text/SvgGenericFontFamily.cs | 40 +
.../Svg/Text/SvgGlyphOutlines.cs | 97 +
.../Svg/Text/SvgLengthAdjust.cs | 20 +
.../Svg/Text/SvgListRange.cs | 33 +
.../Svg/Text/SvgShapedGlyph.cs | 37 +
.../Svg/Text/SvgTextAnchor.cs | 25 +
.../Svg/Text/SvgTextAnchoring.Direction.cs | 73 +
.../Svg/Text/SvgTextAnchoring.cs | 109 +
.../Svg/Text/SvgTextAttributes.cs | 63 +
.../Svg/Text/SvgTextCharacter.cs | 64 +
.../Svg/Text/SvgTextCharacterFlags.cs | 41 +
.../Svg/Text/SvgTextCharacters.Tref.cs | 47 +
.../Svg/Text/SvgTextCharacters.cs | 354 ++
.../Svg/Text/SvgTextCluster.cs | 109 +
.../Svg/Text/SvgTextContent.cs | 88 +
.../Svg/Text/SvgTextDecorationLine.cs | 36 +
.../Svg/Text/SvgTextDecorationStyle.cs | 35 +
.../Svg/Text/SvgTextDirections.cs | 138 +
.../Svg/Text/SvgTextLayout.cs | 283 ++
.../Svg/Text/SvgTextNode.cs | 50 +
.../Svg/Text/SvgTextPathAttributes.cs | 53 +
.../Svg/Text/SvgTextPathMeasure.cs | 353 ++
.../Svg/Text/SvgTextPathMethod.cs | 20 +
.../Svg/Text/SvgTextPathSide.cs | 20 +
.../Svg/Text/SvgTextPathSpacing.cs | 20 +
.../Svg/Text/SvgTextPaths.OnPath.cs | 334 ++
.../Svg/Text/SvgTextPaths.cs | 54 +
.../Svg/Text/SvgTextPositioner.Baselines.cs | 286 ++
.../Svg/Text/SvgTextPositioner.Bidi.cs | 110 +
.../Text/SvgTextPositioner.LengthAdjust.cs | 523 ++
.../Svg/Text/SvgTextPositioner.Vertical.cs | 60 +
.../Svg/Text/SvgTextPositioner.cs | 187 +
.../Svg/Text/SvgTextRendering.cs | 30 +
.../Svg/Text/SvgTextResolveState.cs | 61 +
.../Svg/Text/SvgTextShaper.Direction.cs | 619 +++
.../Svg/Text/SvgTextShaper.Features.cs | 284 ++
.../Svg/Text/SvgTextShaper.cs | 470 ++
.../Svg/Text/SvgTextSpan.cs | 79 +
.../Svg/Text/SvgTextStyle.cs | 456 ++
.../Svg/Text/SvgTextTables.cs | 131 +
.../Svg/Text/SvgUnicodeBidi.cs | 40 +
.../Svg/Text/SvgWhiteSpace.cs | 40 +
.../Svg/Text/SvgWhiteSpaceCollapse.cs | 38 +
.../Svg/Text/SvgWritingMode.cs | 35 +
tests/Directory.Build.targets | 10 +
.../ImageSharp.Drawing.Benchmarks.csproj | 5 +
.../ImageSharp.Drawing.Benchmarks/Program.cs | 58 +-
.../Svg/LoadAndRenderSvg.cs | 172 +
.../Svg/LoadSvg.cs | 82 +
.../Svg/RenderSvg.cs | 275 ++
.../Svg/SvgBenchmarkCorpus.cs | 185 +
.../Svg/SvgBenchmarkFonts.cs | 96 +
.../Svg/SvgBenchmarkWarmup.cs | 64 +
.../Svg/SvgImageSharpRenderer.cs | 251 +
.../Svg/SvgInvocationCurve.cs | 283 ++
.../Svg/SvgPeakMemory.cs | 126 +
.../Svg/SvgReferenceRenderers.cs | 245 +
.../Svg/fonts.conf | 16 +
.../DrawingCanvasTests.RegionAndState.cs | 129 +
.../DrawingCanvasTests.SaveLayer.cs | 29 +
.../Processing/GradientBrushRendererTests.cs | 119 +
.../Processing/ImageBrushRendererTests.cs | 307 ++
...sWithDrawingCanvasTests.AssociatedAlpha.cs | 161 +
.../Processing/RectangleClipCoverageTests.cs | 92 +
.../Processing/SolidBrushRendererTests.cs | 366 ++
.../Shapes/ArcLineSegmentTest.cs | 15 +
.../Shapes/BezierLineSegmentTests.cs | 35 +
.../Shapes/PathTests.cs | 33 +
.../Svg/ResvgExpectedResults.txt | 1719 +++++++
.../Svg/SvgCascadeTests.cs | 429 ++
.../Svg/SvgColorParserTests.cs | 185 +
.../Svg/SvgCompositingRenderTests.cs | 55 +
.../Svg/SvgCompositingTests.cs | 420 ++
.../SvgCrossFeatureHostileDocumentTests.cs | 276 ++
.../Svg/SvgCrossFeatureRenderTests.cs | 68 +
.../Svg/SvgCssColorTests.cs | 169 +
.../Svg/SvgCssFeatureRenderTests.cs | 50 +
.../Svg/SvgCssHostileDocumentTests.cs | 348 ++
.../Svg/SvgCssUnitTests.cs | 350 ++
.../Svg/SvgCssVariableTests.cs | 288 ++
.../Svg/SvgDocumentHostileInputTests.cs | 361 ++
.../Svg/SvgDocumentRenderTests.cs | 189 +
.../Svg/SvgDocumentTests.cs | 453 ++
.../Svg/SvgFilterHostileDocumentTests.cs | 416 ++
.../Svg/SvgFilterIntegrationRenderTests.cs | 58 +
.../Svg/SvgFilterIntegrationTests.cs | 136 +
.../Svg/SvgFilterLightingRenderTests.cs | 55 +
.../Svg/SvgFilterLightingTests.cs | 425 ++
.../Svg/SvgFilterParallelTests.cs | 243 +
.../Svg/SvgFilterRenderTests.cs | 73 +
.../Svg/SvgFilterSpatialRenderTests.cs | 53 +
.../Svg/SvgFilterSpatialTests.cs | 407 ++
.../Svg/SvgFilterTests.cs | 1030 ++++
.../ImageSharp.Drawing.Tests/Svg/SvgGrowth.cs | 110 +
.../Svg/SvgIntegrationTests.cs | 371 ++
.../Svg/SvgLayerLimitTests.cs | 248 +
.../Svg/SvgLengthTests.cs | 104 +
.../Svg/SvgMaskLayerEffectTests.cs | 114 +
.../Svg/SvgMaskLayerPrototypeTests.cs | 81 +
.../Svg/SvgNestedImageTextTests.cs | 159 +
.../Svg/SvgNumberParserTests.cs | 185 +
.../Svg/SvgPaintContentTests.cs | 755 +++
.../Svg/SvgPaintTests.cs | 88 +
.../Svg/SvgPreserveAspectRatioTests.cs | 53 +
.../Svg/SvgPropertyParserTests.cs | 567 +++
.../Svg/SvgReaderTests.cs | 763 +++
.../Svg/SvgRenderTests.cs | 230 +
.../Svg/SvgResolverTests.cs | 518 ++
.../Svg/SvgResvgConformanceTests.cs | 999 ++++
.../Svg/SvgSceneCacheTests.cs | 720 +++
.../Svg/SvgSelectorTests.cs | 468 ++
.../Svg/SvgSequentialCollection.cs | 18 +
.../Svg/SvgStyleHostileDocumentTests.cs | 150 +
.../Svg/SvgStylePropertyTests.cs | 752 +++
.../Svg/SvgStyleSheetTests.cs | 553 +++
.../Svg/SvgSvg2FeatureTests.cs | 491 ++
.../Svg/SvgSvg2HostileDocumentTests.cs | 246 +
.../Svg/SvgSvg2RenderTests.cs | 86 +
.../Svg/SvgTextBaselineDecorationTests.cs | 207 +
.../Svg/SvgTextBidiTests.cs | 218 +
.../SvgTextDecorationBaselineRenderTests.cs | 67 +
.../Svg/SvgTextDirectionRenderTests.cs | 86 +
.../Svg/SvgTextDirectionTests.cs | 284 ++
.../Svg/SvgTextHostileDocumentTests.cs | 332 ++
.../Svg/SvgTextIntegrationRenderTests.cs | 58 +
.../Svg/SvgTextIntegrationTests.cs | 270 ++
.../Svg/SvgTextPathRenderTests.cs | 48 +
.../Svg/SvgTextPathTests.cs | 597 +++
.../Svg/SvgTextRenderTests.cs | 63 +
.../Svg/SvgTextTests.cs | 513 ++
.../Svg/SvgTextureReplayTests.cs | 118 +
.../Svg/SvgTransformParserTests.cs | 193 +
tests/ImageSharp.Drawing.Tests/TestImages.cs | 135 +
.../TestUtilities/TestMemoryAllocator.cs | 27 +-
.../Svg/Charts/chart-dashboard-synthetic.svg | 518 ++
.../compositing-dashboard-synthetic.svg | 300 ++
.../Compositing/pattern-chart-synthetic.svg | 57 +
.../Input/Svg/Css/css-features-synthetic.svg | 542 +++
.../Input/Svg/DesignTool/LICENSE-Carbon | 201 +
.../Input/Svg/DesignTool/carbon-crab.svg | 12 +
.../DesignTool/styled-landscape-synthetic.svg | 161 +
.../Svg/Features/clip-path-shape-root.svg | 5 +
.../Input/Svg/Features/clip-path-shape.svg | 81 +
tests/Images/Input/Svg/Features/clip-path.svg | 24 +
.../Svg/Features/cross-ch-attributes.svg | 22 +
.../Input/Svg/Features/cross-clip-ch.svg | 20 +
.../Svg/Features/cross-clip-mask-filter.svg | 39 +
.../Svg/Features/cross-clip-var-calc.svg | 34 +
.../Images/Input/Svg/Features/cross-color.svg | 61 +
.../Svg/Features/cross-d-path-length.svg | 21 +
.../Input/Svg/Features/cross-decoder.svg | 17 +
.../Svg/Features/cross-embedded-text.svg | 7 +
.../Svg/Features/cross-geometry-boxes.svg | 58 +
.../Images/Input/Svg/Features/cross-lang.svg | 18 +
.../Input/Svg/Features/cross-paint-origin.svg | 21 +
.../Svg/Features/cross-root-transform.svg | 5 +
.../Features/cross-text-path-transform.svg | 8 +
.../Svg/Features/cross-transform-clip.svg | 22 +
tests/Images/Input/Svg/Features/cross-var.svg | 45 +
tests/Images/Input/Svg/Features/css-calc.svg | 30 +
tests/Images/Input/Svg/Features/css-color.svg | 48 +
.../Input/Svg/Features/css-geometry.svg | 56 +
.../Input/Svg/Features/css-selectors.svg | 42 +
.../Input/Svg/Features/css-transform.svg | 39 +
tests/Images/Input/Svg/Features/css-var.svg | 63 +
tests/Images/Input/Svg/Features/css.svg | 32 +
.../Input/Svg/Features/current-color.svg | 22 +
.../Input/Svg/Features/display-visibility.svg | 16 +
tests/Images/Input/Svg/Features/fill-rule.svg | 9 +
.../Input/Svg/Features/filter-blend.svg | 45 +
.../Svg/Features/filter-blur-accuracy.svg | 32 +
.../Images/Input/Svg/Features/filter-blur.svg | 18 +
.../Input/Svg/Features/filter-bounds.svg | 21 +
.../Svg/Features/filter-color-matrix.svg | 23 +
.../Input/Svg/Features/filter-color-space.svg | 23 +
.../Features/filter-component-transfer.svg | 64 +
.../Input/Svg/Features/filter-composite.svg | 52 +
.../Input/Svg/Features/filter-convolve.svg | 56 +
.../Svg/Features/filter-displacement.svg | 51 +
.../Input/Svg/Features/filter-drop-shadow.svg | 24 +
.../Input/Svg/Features/filter-errors.svg | 21 +
.../Input/Svg/Features/filter-flood.svg | 18 +
.../Input/Svg/Features/filter-functions.svg | 31 +
.../Input/Svg/Features/filter-image.svg | 41 +
.../filter-integration-compositing.svg | 38 +
.../Features/filter-integration-content.svg | 49 +
.../Svg/Features/filter-integration-root.svg | 12 +
.../Svg/Features/filter-lighting-diffuse.svg | 40 +
.../Svg/Features/filter-lighting-errors.svg | 64 +
.../Svg/Features/filter-lighting-specular.svg | 39 +
.../Svg/Features/filter-lighting-units.svg | 46 +
.../Input/Svg/Features/filter-morphology.svg | 36 +
.../Svg/Features/filter-offset-merge.svg | 22 +
.../Svg/Features/filter-outside-canvas.svg | 14 +
.../Input/Svg/Features/filter-region.svg | 20 +
.../Input/Svg/Features/filter-subregion.svg | 28 +
.../Images/Input/Svg/Features/filter-tile.svg | 22 +
.../Input/Svg/Features/filter-transform.svg | 16 +
.../Input/Svg/Features/filter-turbulence.svg | 36 +
.../Input/Svg/Features/gradient-href.svg | 32 +
.../Input/Svg/Features/gradient-linear.svg | 55 +
.../Input/Svg/Features/gradient-radial.svg | 42 +
.../Svg/Features/gradient-transformed.svg | 22 +
tests/Images/Input/Svg/Features/image.svg | 20 +
.../Input/Svg/Features/integration-css.svg | 40 +
.../Svg/Features/integration-image-mask.svg | 17 +
.../Svg/Features/integration-marker-clip.svg | 33 +
.../Svg/Features/integration-mask-pattern.svg | 35 +
.../Svg/Features/integration-nesting.svg | 37 +
.../Features/integration-pattern-content.svg | 29 +
.../Input/Svg/Features/integration-use.svg | 29 +
.../Input/Svg/Features/lang-selector.svg | 24 +
tests/Images/Input/Svg/Features/marker.svg | 32 +
tests/Images/Input/Svg/Features/mask.svg | 23 +
.../Input/Svg/Features/mix-blend-mode.svg | 25 +
.../Input/Svg/Features/non-scaling-stroke.svg | 10 +
tests/Images/Input/Svg/Features/opacity.svg | 28 +
tests/Images/Input/Svg/Features/overflow.svg | 15 +
.../Images/Input/Svg/Features/paint-order.svg | 8 +
.../Images/Input/Svg/Features/path-length.svg | 15 +
tests/Images/Input/Svg/Features/pattern.svg | 33 +
.../Images/Input/Svg/Features/root-align.svg | 5 +
.../Input/Svg/Features/root-stretch.svg | 5 +
.../Input/Svg/Features/root-transform.svg | 5 +
.../Input/Svg/Features/shape-rendering.svg | 6 +
tests/Images/Input/Svg/Features/shapes.svg | 17 +
.../Input/Svg/Features/stroke-caps-joins.svg | 16 +
.../Input/Svg/Features/stroke-dash-scaled.svg | 5 +
.../Images/Input/Svg/Features/stroke-dash.svg | 11 +
.../Svg/Features/stroke-width-opacity.svg | 12 +
tests/Images/Input/Svg/Features/switch.svg | 19 +
.../Input/Svg/Features/text-baseline.svg | 9 +
tests/Images/Input/Svg/Features/text-bidi.svg | 22 +
.../Input/Svg/Features/text-compositing.svg | 24 +
.../Input/Svg/Features/text-decoration.svg | 21 +
.../Input/Svg/Features/text-direction.svg | 20 +
.../Input/Svg/Features/text-font-features.svg | 30 +
.../Svg/Features/text-integration-paint.svg | 50 +
.../Features/text-integration-vertical.svg | 21 +
.../Images/Input/Svg/Features/text-layout.svg | 16 +
.../Images/Input/Svg/Features/text-length.svg | 14 +
.../Input/Svg/Features/text-paint-use.svg | 27 +
.../Images/Input/Svg/Features/text-paint.svg | 22 +
tests/Images/Input/Svg/Features/text-path.svg | 23 +
.../Input/Svg/Features/transform-origin.svg | 42 +
.../Images/Input/Svg/Features/transforms.svg | 17 +
tests/Images/Input/Svg/Features/units.svg | 14 +
.../Images/Input/Svg/Features/use-symbol.svg | 27 +
.../Input/Svg/Features/viewbox-nested.svg | 38 +
.../Svg/Filters/filter-blur-synthetic.svg | 45 +
.../Svg/Filters/filter-chain-synthetic.svg | 50 +
.../Svg/Filters/filter-shadows-synthetic.svg | 224 +
.../Images/Input/Svg/Icons/Bootstrap/LICENSE | 21 +
.../Input/Svg/Icons/Bootstrap/bell-fill.svg | 3 +
.../Icons/Bootstrap/bookmark-star-fill.svg | 3 +
.../Input/Svg/Icons/Bootstrap/bug-fill.svg | 4 +
.../Input/Svg/Icons/Bootstrap/camera-fill.svg | 4 +
.../Svg/Icons/Bootstrap/chat-dots-fill.svg | 3 +
.../Input/Svg/Icons/Bootstrap/cloud-fill.svg | 3 +
.../Svg/Icons/Bootstrap/envelope-fill.svg | 3 +
.../Input/Svg/Icons/Bootstrap/gear-fill.svg | 3 +
.../Svg/Icons/Bootstrap/geo-alt-fill.svg | 3 +
.../Input/Svg/Icons/Bootstrap/heart-fill.svg | 3 +
.../Input/Svg/Icons/Bootstrap/house-fill.svg | 4 +
.../Svg/Icons/Bootstrap/lightning-fill.svg | 3 +
.../Input/Svg/Icons/Bootstrap/puzzle-fill.svg | 3 +
.../Svg/Icons/Bootstrap/shield-fill-check.svg | 3 +
.../Input/Svg/Icons/Bootstrap/star-fill.svg | 3 +
.../Input/Svg/Icons/Bootstrap/trash-fill.svg | 3 +
tests/Images/Input/Svg/Icons/Feather/LICENSE | 21 +
.../Input/Svg/Icons/Feather/activity.svg | 1 +
.../Input/Svg/Icons/Feather/alert-octagon.svg | 1 +
.../Input/Svg/Icons/Feather/archive.svg | 1 +
tests/Images/Input/Svg/Icons/Feather/box.svg | 1 +
.../Images/Input/Svg/Icons/Feather/camera.svg | 1 +
.../Input/Svg/Icons/Feather/compass.svg | 1 +
tests/Images/Input/Svg/Icons/Feather/cpu.svg | 1 +
.../Input/Svg/Icons/Feather/database.svg | 1 +
.../Input/Svg/Icons/Feather/feather.svg | 1 +
tests/Images/Input/Svg/Icons/Feather/gift.svg | 1 +
.../Images/Input/Svg/Icons/Feather/globe.svg | 1 +
.../Images/Input/Svg/Icons/Feather/heart.svg | 1 +
.../Images/Input/Svg/Icons/Feather/image.svg | 1 +
.../Images/Input/Svg/Icons/Feather/layers.svg | 1 +
.../Input/Svg/Icons/Feather/map-pin.svg | 1 +
.../Input/Svg/Icons/Feather/monitor.svg | 1 +
.../Input/Svg/Icons/Feather/settings.svg | 1 +
tests/Images/Input/Svg/Icons/Feather/star.svg | 1 +
tests/Images/Input/Svg/Icons/Feather/sun.svg | 1 +
.../Images/Input/Svg/Icons/Feather/truck.svg | 1 +
tests/Images/Input/Svg/Icons/Feather/user.svg | 1 +
tests/Images/Input/Svg/Icons/Feather/wifi.svg | 1 +
.../Input/Svg/Icons/Feather/x-octagon.svg | 1 +
tests/Images/Input/Svg/Icons/Feather/zap.svg | 1 +
.../Input/Svg/Icons/icon-sheet-synthetic.svg | 464 ++
.../Svg/Illustrations/LICENSE-Fluent-Emoji | 21 +
.../Input/Svg/Illustrations/fluent-moose.svg | 373 ++
.../Illustrations/fluent-soft-ice-cream.svg | 130 +
.../Input/Svg/Maps/street-map-synthetic.svg | 4265 +++++++++++++++++
.../Svg/Text/text-decorations-synthetic.svg | 50 +
.../Input/Svg/Text/text-heavy-synthetic.svg | 46 +
.../DrawSvg_CompositingFeature_clip-path.png | 3 +
.../DrawSvg_CompositingFeature_mask.png | 3 +
...wSvg_CompositingFeature_mix-blend-mode.png | 3 +
..._CompositingFeature_non-scaling-stroke.png | 3 +
.../DrawSvg_CompositingFeature_overflow.png | 3 +
...DrawSvg_CompositingFeature_paint-order.png | 3 +
...wSvg_CompositingFeature_root-transform.png | 3 +
...Svg_CompositingFeature_shape-rendering.png | 3 +
.../DrawSvg_CompositingFeature_switch.png | 3 +
...awSvg_CrossFeature_cross-ch-attributes.png | 3 +
.../DrawSvg_CrossFeature_cross-clip-ch.png | 3 +
...vg_CrossFeature_cross-clip-mask-filter.png | 3 +
...awSvg_CrossFeature_cross-clip-var-calc.png | 3 +
.../DrawSvg_CrossFeature_cross-color.png | 3 +
...awSvg_CrossFeature_cross-d-path-length.png | 3 +
.../DrawSvg_CrossFeature_cross-decoder.png | 3 +
...awSvg_CrossFeature_cross-embedded-text.png | 3 +
...wSvg_CrossFeature_cross-geometry-boxes.png | 3 +
.../DrawSvg_CrossFeature_cross-lang.png | 3 +
...rawSvg_CrossFeature_cross-paint-origin.png | 3 +
...wSvg_CrossFeature_cross-root-transform.png | 3 +
...CrossFeature_cross-text-path-transform.png | 3 +
...wSvg_CrossFeature_cross-transform-clip.png | 3 +
.../DrawSvg_CrossFeature_cross-var.png | 3 +
.../DrawSvg_CssFeature_css-calc.png | 3 +
.../DrawSvg_CssFeature_css-color.png | 3 +
.../DrawSvg_CssFeature_css-geometry.png | 3 +
.../DrawSvg_CssFeature_css-transform.png | 3 +
.../DrawSvg_CssFeature_css-var.png | 3 +
...gration_filter-integration-compositing.png | 3 +
...Integration_filter-integration-content.png | 3 +
...terIntegration_filter-integration-root.png | 3 +
...ingFeature_filter-lighting-diffuse-200.png | 3 +
...ingFeature_filter-lighting-diffuse-400.png | 3 +
...tingFeature_filter-lighting-errors-200.png | 3 +
...ngFeature_filter-lighting-specular-200.png | 3 +
...htingFeature_filter-lighting-units-200.png | 3 +
...gFeature_filter-lighting-units-400x200.png | 3 +
...DrawSvg_FilterFeature_filter-blend-200.png | 3 +
.../DrawSvg_FilterFeature_filter-blur-200.png | 3 +
.../DrawSvg_FilterFeature_filter-blur-500.png | 3 +
...FilterFeature_filter-blur-accuracy-400.png | 3 +
...rawSvg_FilterFeature_filter-bounds-200.png | 3 +
..._FilterFeature_filter-color-matrix-200.png | 3 +
...g_FilterFeature_filter-color-space-200.png | 3 +
...rFeature_filter-component-transfer-200.png | 3 +
...Svg_FilterFeature_filter-composite-200.png | 3 +
...g_FilterFeature_filter-drop-shadow-200.png | 3 +
...rawSvg_FilterFeature_filter-errors-200.png | 3 +
...DrawSvg_FilterFeature_filter-flood-200.png | 3 +
...Svg_FilterFeature_filter-functions-200.png | 3 +
...DrawSvg_FilterFeature_filter-image-200.png | 3 +
..._FilterFeature_filter-offset-merge-200.png | 3 +
...ilterFeature_filter-outside-canvas-200.png | 3 +
...rawSvg_FilterFeature_filter-region-200.png | 3 +
...Svg_FilterFeature_filter-subregion-200.png | 3 +
.../DrawSvg_FilterFeature_filter-tile-200.png | 3 +
.../DrawSvg_FilterFeature_filter-tile-300.png | 3 +
...Svg_FilterFeature_filter-transform-200.png | 3 +
...wSvg_FilterFeature_filter-convolve-200.png | 3 +
..._FilterFeature_filter-displacement-200.png | 3 +
...vg_FilterFeature_filter-morphology-200.png | 3 +
...vg_FilterFeature_filter-turbulence-200.png | 3 +
...vg_FilterFeature_filter-turbulence-500.png | 3 +
...rawSvg_Integration_integration-css-200.png | 3 +
...Integration_integration-image-mask-200.png | 3 +
...ntegration_integration-marker-clip-200.png | 3 +
...tegration_integration-mask-pattern-200.png | 3 +
...tegration_integration-mask-pattern-400.png | 3 +
...vg_Integration_integration-nesting-200.png | 3 +
...ration_integration-pattern-content-200.png | 3 +
...rawSvg_Integration_integration-use-200.png | 3 +
.../DrawSvg_PaintContent_image-200.png | 3 +
.../DrawSvg_PaintContent_marker-200.png | 3 +
.../DrawSvg_PaintContent_pattern-200.png | 3 +
.../DrawSvg_PaintContent_pattern-400.png | 3 +
.../DrawSvg_Corpus_carbon-crab.png | 3 +
.../DrawSvg_Corpus_fluent-moose.png | 3 +
.../DrawSvg_Corpus_fluent-soft-ice-cream.png | 3 +
...wSvg_Corpus_styled-landscape-synthetic.png | 3 +
.../DrawSvg_Feature_css-selectors.png | 3 +
.../SvgRenderTests/DrawSvg_Feature_css.png | 3 +
.../DrawSvg_Feature_current-color.png | 3 +
.../DrawSvg_Feature_display-visibility.png | 3 +
.../DrawSvg_Feature_fill-rule.png | 3 +
.../DrawSvg_Feature_gradient-href.png | 3 +
.../DrawSvg_Feature_gradient-linear.png | 3 +
.../DrawSvg_Feature_gradient-radial.png | 3 +
.../DrawSvg_Feature_gradient-transformed.png | 3 +
.../DrawSvg_Feature_opacity.png | 3 +
.../DrawSvg_Feature_root-align.png | 3 +
.../DrawSvg_Feature_root-stretch.png | 3 +
.../SvgRenderTests/DrawSvg_Feature_shapes.png | 3 +
.../DrawSvg_Feature_stroke-caps-joins.png | 3 +
.../DrawSvg_Feature_stroke-dash-scaled.png | 3 +
.../DrawSvg_Feature_stroke-dash.png | 3 +
.../DrawSvg_Feature_stroke-width-opacity.png | 3 +
.../DrawSvg_Feature_transform-origin.png | 3 +
.../DrawSvg_Feature_transforms.png | 3 +
.../SvgRenderTests/DrawSvg_Feature_units.png | 3 +
.../DrawSvg_Feature_use-symbol.png | 3 +
.../DrawSvg_Feature_viewbox-nested.png | 3 +
.../SvgRenderTests/DrawSvg_Icons_activity.png | 3 +
.../DrawSvg_Icons_alert-octagon.png | 3 +
.../SvgRenderTests/DrawSvg_Icons_archive.png | 3 +
.../DrawSvg_Icons_bell-fill.png | 3 +
.../DrawSvg_Icons_bookmark-star-fill.png | 3 +
.../Svg/SvgRenderTests/DrawSvg_Icons_box.png | 3 +
.../SvgRenderTests/DrawSvg_Icons_bug-fill.png | 3 +
.../DrawSvg_Icons_camera-fill.png | 3 +
.../SvgRenderTests/DrawSvg_Icons_camera.png | 3 +
.../DrawSvg_Icons_chat-dots-fill.png | 3 +
.../DrawSvg_Icons_cloud-fill.png | 3 +
.../SvgRenderTests/DrawSvg_Icons_compass.png | 3 +
.../Svg/SvgRenderTests/DrawSvg_Icons_cpu.png | 3 +
.../SvgRenderTests/DrawSvg_Icons_database.png | 3 +
.../DrawSvg_Icons_envelope-fill.png | 3 +
.../SvgRenderTests/DrawSvg_Icons_feather.png | 3 +
.../DrawSvg_Icons_gear-fill.png | 3 +
.../DrawSvg_Icons_geo-alt-fill.png | 3 +
.../Svg/SvgRenderTests/DrawSvg_Icons_gift.png | 3 +
.../SvgRenderTests/DrawSvg_Icons_globe.png | 3 +
.../DrawSvg_Icons_heart-fill.png | 3 +
.../SvgRenderTests/DrawSvg_Icons_heart.png | 3 +
.../DrawSvg_Icons_house-fill.png | 3 +
.../SvgRenderTests/DrawSvg_Icons_image.png | 3 +
.../SvgRenderTests/DrawSvg_Icons_layers.png | 3 +
.../DrawSvg_Icons_lightning-fill.png | 3 +
.../SvgRenderTests/DrawSvg_Icons_map-pin.png | 3 +
.../SvgRenderTests/DrawSvg_Icons_monitor.png | 3 +
.../DrawSvg_Icons_puzzle-fill.png | 3 +
.../SvgRenderTests/DrawSvg_Icons_settings.png | 3 +
.../DrawSvg_Icons_shield-fill-check.png | 3 +
.../DrawSvg_Icons_star-fill.png | 3 +
.../Svg/SvgRenderTests/DrawSvg_Icons_star.png | 3 +
.../Svg/SvgRenderTests/DrawSvg_Icons_sun.png | 3 +
.../DrawSvg_Icons_trash-fill.png | 3 +
.../SvgRenderTests/DrawSvg_Icons_truck.png | 3 +
.../Svg/SvgRenderTests/DrawSvg_Icons_user.png | 3 +
.../Svg/SvgRenderTests/DrawSvg_Icons_wifi.png | 3 +
.../DrawSvg_Icons_x-octagon.png | 3 +
.../Svg/SvgRenderTests/DrawSvg_Icons_zap.png | 3 +
.../SvgRenderTests/DrawSvg_Paris_paris.png | 3 +
.../SvgRenderTests/DrawSvg_Tiger_tiger.png | 3 +
...awSvg_Svg2Feature_clip-path-shape-root.png | 3 +
.../DrawSvg_Svg2Feature_clip-path-shape.png | 3 +
.../DrawSvg_Svg2Feature_lang-selector.png | 3 +
.../DrawSvg_Svg2Feature_path-length.png | 3 +
...Svg_Svg2TextFeature_text-font-features.png | 3 +
...DrawSvg_Svg2TextFeature_text-paint-use.png | 3 +
...xtDecorationAndBaselines_text-baseline.png | 3 +
...DecorationAndBaselines_text-decoration.png | 3 +
.../DrawSvg_TextBidi.png | 3 +
.../DrawSvg_TextDirection.png | 3 +
...TextIntegration_text-integration-paint.png | 3 +
...tIntegration_text-integration-vertical.png | 3 +
...wSvg_TextPathAndTextLength_text-length.png | 3 +
...rawSvg_TextPathAndTextLength_text-path.png | 3 +
.../DrawSvg_Text_text-compositing.png | 3 +
.../DrawSvg_Text_text-layout.png | 3 +
.../DrawSvg_Text_text-paint.png | 3 +
tests/SvgTools/README.md | 172 +
tests/SvgTools/compare-png.cs | 1002 ++++
tests/SvgTools/fetch-resvg-tests.cs | 328 ++
tests/SvgTools/render-svg.cs | 980 ++++
744 files changed, 103823 insertions(+), 698 deletions(-)
create mode 100644 src/ImageSharp.Drawing/Processing/Backends/FlushScene.StoredCoverage.cs
create mode 100644 src/ImageSharp.Drawing/Processing/DrawingCanvas.Svg.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Css/SvgBasicShapeKind.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Css/SvgBlendMode.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Css/SvgCascade.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Css/SvgClipShape.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Css/SvgColorInterpolation.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Css/SvgCssAttributeOperator.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Css/SvgCssAttributeSelector.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Css/SvgCssAttributeValues.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Css/SvgCssCombinator.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Css/SvgCssComplexSelector.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Css/SvgCssCompoundSelector.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Css/SvgCssFunctionalSelector.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Css/SvgCssLanguageRanges.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Css/SvgCssMatcher.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Css/SvgCssMediaQuery.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Css/SvgCssParser.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Css/SvgCssRule.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Css/SvgCssSelectorEquality.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Css/SvgCssSelectorParser.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Css/SvgCssSimpleSelector.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Css/SvgCssSimpleSelectorKind.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Css/SvgCssToken.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Css/SvgCssTokenKind.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Css/SvgCssTokenizer.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Css/SvgCustomProperties.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Css/SvgCustomPropertyKind.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Css/SvgCustomPropertyResolver.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Css/SvgCustomPropertyValue.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Css/SvgDashArray.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Css/SvgDeclarationOrigin.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Css/SvgDisplay.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Css/SvgExtendedStyle.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Css/SvgFillRule.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Css/SvgGeometryBox.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Css/SvgGeometryStyle.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Css/SvgImageRendering.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Css/SvgIsolation.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Css/SvgMaskType.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Css/SvgOverflow.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Css/SvgPaintOrder.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Css/SvgPendingValue.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Css/SvgPropertyId.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Css/SvgPropertyParser.Geometry.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Css/SvgPropertyParser.Text.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Css/SvgPropertyParser.Variables.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Css/SvgPropertyParser.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Css/SvgPropertySet.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Css/SvgShapePosition.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Css/SvgShapeRadiusKind.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Css/SvgShapeRendering.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Css/SvgShorthand.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Css/SvgSpecifiedStyle.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Css/SvgStrokeLineCap.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Css/SvgStrokeLineJoin.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Css/SvgStyleSheet.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Css/SvgStyleSources.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Css/SvgSubstitutionBudget.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Css/SvgTransformBox.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Css/SvgVariableStyle.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Css/SvgVariableSubstitution.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Css/SvgVectorEffect.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Css/SvgVisibility.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Filters/SvgEmitter.Filter.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Filters/SvgFeBlend.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Filters/SvgFeColorMatrix.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Filters/SvgFeComponentTransfer.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Filters/SvgFeComposite.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Filters/SvgFeConvolveMatrix.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Filters/SvgFeDiffuseLighting.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Filters/SvgFeDisplacementMap.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Filters/SvgFeDropShadow.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Filters/SvgFeFlood.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Filters/SvgFeGaussianBlur.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Filters/SvgFeImage.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Filters/SvgFeMerge.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Filters/SvgFeMorphology.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Filters/SvgFeOffset.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Filters/SvgFePassThrough.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Filters/SvgFeSpecularLighting.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Filters/SvgFeTile.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Filters/SvgFeTransparent.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Filters/SvgFeTurbulence.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Filters/SvgFilterAttributeValue.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Filters/SvgFilterAttributes.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Filters/SvgFilterBuildContext.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Filters/SvgFilterBuildResult.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Filters/SvgFilterBuilder.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Filters/SvgFilterColor.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Filters/SvgFilterEngine.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Filters/SvgFilterFunction.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Filters/SvgFilterFunctionKind.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Filters/SvgFilterGraph.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Filters/SvgFilterImage.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Filters/SvgFilterList.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Filters/SvgFilterNode.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Filters/SvgFilterOutcome.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Filters/SvgFilterPrefetch.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Filters/SvgFilterPrimitive.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Filters/SvgFilterPrimitiveAttributes.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Filters/SvgFilterRenderContext.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Filters/SvgFilterScope.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Filters/SvgFilterStyle.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Filters/SvgFilterTables.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Filters/SvgLightSource.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Filters/SvgLighting.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Filters/SvgPropertyParser.Filter.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Filters/SvgResolver.Filter.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Parsing/SvgAlign.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Parsing/SvgAttributeId.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Parsing/SvgCalc.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Parsing/SvgCalcExpression.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Parsing/SvgCalcKind.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Parsing/SvgCalcOperation.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Parsing/SvgCalcOperationCode.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Parsing/SvgCalcResult.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Parsing/SvgCalcTable.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Parsing/SvgCalcVariables.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Parsing/SvgCircleAttributes.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Parsing/SvgColorCache.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Parsing/SvgColorParser.Css4.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Parsing/SvgColorParser.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Parsing/SvgColorSpace.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Parsing/SvgConditionalAttributes.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Parsing/SvgCoordinateUnits.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Parsing/SvgCssColor.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Parsing/SvgCssTransform.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Parsing/SvgElement.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Parsing/SvgElementKind.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Parsing/SvgElementTree.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Parsing/SvgGradientAttributes.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Parsing/SvgImageAttributes.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Parsing/SvgLength.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Parsing/SvgLengthUnit.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Parsing/SvgLineAttributes.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Parsing/SvgMarkerAttributes.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Parsing/SvgMarkerOrient.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Parsing/SvgMarkerOrientKind.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Parsing/SvgMarkerUnits.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Parsing/SvgMaskAttributes.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Parsing/SvgNameTable.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Parsing/SvgNames.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Parsing/SvgNumberParser.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Parsing/SvgPaint.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Parsing/SvgPaintKind.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Parsing/SvgPathAttributes.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Parsing/SvgPatternAttributes.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Parsing/SvgPointsAttributes.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Parsing/SvgPreserveAspectRatio.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Parsing/SvgReader.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Parsing/SvgReaderOptions.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Parsing/SvgRectAttributes.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Parsing/SvgReference.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Parsing/SvgSpreadMethod.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Parsing/SvgStringPool.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Parsing/SvgTransformParser.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Parsing/SvgUseAttributes.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Parsing/SvgViewportAttributes.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Rendering/SvgDeferredPaint.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Rendering/SvgDrawFlags.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Rendering/SvgEmitter.Compositing.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Rendering/SvgEmitter.Layers.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Rendering/SvgEmitter.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Rendering/SvgImagePaint.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Rendering/SvgMaskLayerEffect.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Rendering/SvgMaskMode.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Rendering/SvgPatternPaint.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Rendering/SvgPatternTile.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Rendering/SvgPatternTileStore.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Rendering/SvgRenderNode.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Rendering/SvgRenderNodeKind.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Rendering/SvgSceneAllocator.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Rendering/SvgSceneCache.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Rendering/SvgTexture.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Rendering/SvgTextureBrush.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Resolve/SvgClipKind.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Resolve/SvgClipScope.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Resolve/SvgClipTarget.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Resolve/SvgCompositeScope.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Resolve/SvgComputedStyle.Equality.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Resolve/SvgComputedStyle.Geometry.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Resolve/SvgComputedStyle.Variables.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Resolve/SvgComputedStyle.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Resolve/SvgGradientKey.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Resolve/SvgImageSource.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Resolve/SvgPaintCache.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Resolve/SvgPenKey.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Resolve/SvgPooledList.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Resolve/SvgResolveContext.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Resolve/SvgResolvedGradient.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Resolve/SvgResolver.Clip.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Resolve/SvgResolver.ClipShape.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Resolve/SvgResolver.Compositing.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Resolve/SvgResolver.Context.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Resolve/SvgResolver.Geometry.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Resolve/SvgResolver.Image.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Resolve/SvgResolver.Markers.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Resolve/SvgResolver.Mask.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Resolve/SvgResolver.PathLength.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Resolve/SvgResolver.Pattern.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Resolve/SvgResolver.Structure.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Resolve/SvgResolver.Switch.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Resolve/SvgResolver.Text.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Resolve/SvgResolver.TextDecorations.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Resolve/SvgResolver.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Resolve/SvgStyleCache.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Resolve/SvgStyleContext.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Resolve/SvgTransformTable.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Resolve/SvgUnitBasis.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Resolve/SvgUnits.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Resolve/SvgViewBoxTransform.cs
create mode 100644 src/ImageSharp.Drawing/Svg/SVG_DECISIONS.md
create mode 100644 src/ImageSharp.Drawing/Svg/SVG_DESIGN.md
create mode 100644 src/ImageSharp.Drawing/Svg/SvgDocument.Render.cs
create mode 100644 src/ImageSharp.Drawing/Svg/SvgDocument.cs
create mode 100644 src/ImageSharp.Drawing/Svg/SvgGenericFontFamilies.cs
create mode 100644 src/ImageSharp.Drawing/Svg/SvgIntegerMath.cs
create mode 100644 src/ImageSharp.Drawing/Svg/SvgLimits.cs
create mode 100644 src/ImageSharp.Drawing/Svg/SvgLoadOptions.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/Bidi/ArrayBuilder{T}.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/Bidi/ArraySlice{T}.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/Bidi/BidiAlgorithm.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/Bidi/BidiData.AsciiTables.Generated.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/Bidi/BidiData.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/Bidi/BidiDictionary{T1,T2}.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/Bidi/MappedArraySlice{T}.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/Bidi/ReadOnlyArraySlice{T}.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/Bidi/ReadOnlyMappedArraySlice{T}.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/SvgAlignmentBaseline.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/SvgBaselineShiftKind.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/SvgDirection.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/SvgDominantBaseline.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/SvgFontChain.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/SvgFontFace.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/SvgFontFallback.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/SvgFontFamilyName.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/SvgFontFeatureSetting.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/SvgFontKerning.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/SvgFontKey.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/SvgFontMatcher.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/SvgFontStyle.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/SvgFontVariant.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/SvgFontVariantEastAsian.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/SvgFontVariantLigatures.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/SvgFontVariantNumeric.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/SvgFontVariantPosition.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/SvgGenericFontFamily.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/SvgGlyphOutlines.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/SvgLengthAdjust.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/SvgListRange.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/SvgShapedGlyph.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/SvgTextAnchor.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/SvgTextAnchoring.Direction.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/SvgTextAnchoring.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/SvgTextAttributes.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/SvgTextCharacter.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/SvgTextCharacterFlags.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/SvgTextCharacters.Tref.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/SvgTextCharacters.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/SvgTextCluster.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/SvgTextContent.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/SvgTextDecorationLine.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/SvgTextDecorationStyle.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/SvgTextDirections.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/SvgTextLayout.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/SvgTextNode.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/SvgTextPathAttributes.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/SvgTextPathMeasure.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/SvgTextPathMethod.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/SvgTextPathSide.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/SvgTextPathSpacing.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/SvgTextPaths.OnPath.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/SvgTextPaths.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/SvgTextPositioner.Baselines.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/SvgTextPositioner.Bidi.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/SvgTextPositioner.LengthAdjust.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/SvgTextPositioner.Vertical.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/SvgTextPositioner.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/SvgTextRendering.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/SvgTextResolveState.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/SvgTextShaper.Direction.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/SvgTextShaper.Features.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/SvgTextShaper.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/SvgTextSpan.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/SvgTextStyle.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/SvgTextTables.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/SvgUnicodeBidi.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/SvgWhiteSpace.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/SvgWhiteSpaceCollapse.cs
create mode 100644 src/ImageSharp.Drawing/Svg/Text/SvgWritingMode.cs
create mode 100644 tests/ImageSharp.Drawing.Benchmarks/Svg/LoadAndRenderSvg.cs
create mode 100644 tests/ImageSharp.Drawing.Benchmarks/Svg/LoadSvg.cs
create mode 100644 tests/ImageSharp.Drawing.Benchmarks/Svg/RenderSvg.cs
create mode 100644 tests/ImageSharp.Drawing.Benchmarks/Svg/SvgBenchmarkCorpus.cs
create mode 100644 tests/ImageSharp.Drawing.Benchmarks/Svg/SvgBenchmarkFonts.cs
create mode 100644 tests/ImageSharp.Drawing.Benchmarks/Svg/SvgBenchmarkWarmup.cs
create mode 100644 tests/ImageSharp.Drawing.Benchmarks/Svg/SvgImageSharpRenderer.cs
create mode 100644 tests/ImageSharp.Drawing.Benchmarks/Svg/SvgInvocationCurve.cs
create mode 100644 tests/ImageSharp.Drawing.Benchmarks/Svg/SvgPeakMemory.cs
create mode 100644 tests/ImageSharp.Drawing.Benchmarks/Svg/SvgReferenceRenderers.cs
create mode 100644 tests/ImageSharp.Drawing.Benchmarks/Svg/fonts.conf
create mode 100644 tests/ImageSharp.Drawing.Tests/Processing/GradientBrushRendererTests.cs
create mode 100644 tests/ImageSharp.Drawing.Tests/Processing/ImageBrushRendererTests.cs
create mode 100644 tests/ImageSharp.Drawing.Tests/Processing/RectangleClipCoverageTests.cs
create mode 100644 tests/ImageSharp.Drawing.Tests/Processing/SolidBrushRendererTests.cs
create mode 100644 tests/ImageSharp.Drawing.Tests/Svg/ResvgExpectedResults.txt
create mode 100644 tests/ImageSharp.Drawing.Tests/Svg/SvgCascadeTests.cs
create mode 100644 tests/ImageSharp.Drawing.Tests/Svg/SvgColorParserTests.cs
create mode 100644 tests/ImageSharp.Drawing.Tests/Svg/SvgCompositingRenderTests.cs
create mode 100644 tests/ImageSharp.Drawing.Tests/Svg/SvgCompositingTests.cs
create mode 100644 tests/ImageSharp.Drawing.Tests/Svg/SvgCrossFeatureHostileDocumentTests.cs
create mode 100644 tests/ImageSharp.Drawing.Tests/Svg/SvgCrossFeatureRenderTests.cs
create mode 100644 tests/ImageSharp.Drawing.Tests/Svg/SvgCssColorTests.cs
create mode 100644 tests/ImageSharp.Drawing.Tests/Svg/SvgCssFeatureRenderTests.cs
create mode 100644 tests/ImageSharp.Drawing.Tests/Svg/SvgCssHostileDocumentTests.cs
create mode 100644 tests/ImageSharp.Drawing.Tests/Svg/SvgCssUnitTests.cs
create mode 100644 tests/ImageSharp.Drawing.Tests/Svg/SvgCssVariableTests.cs
create mode 100644 tests/ImageSharp.Drawing.Tests/Svg/SvgDocumentHostileInputTests.cs
create mode 100644 tests/ImageSharp.Drawing.Tests/Svg/SvgDocumentRenderTests.cs
create mode 100644 tests/ImageSharp.Drawing.Tests/Svg/SvgDocumentTests.cs
create mode 100644 tests/ImageSharp.Drawing.Tests/Svg/SvgFilterHostileDocumentTests.cs
create mode 100644 tests/ImageSharp.Drawing.Tests/Svg/SvgFilterIntegrationRenderTests.cs
create mode 100644 tests/ImageSharp.Drawing.Tests/Svg/SvgFilterIntegrationTests.cs
create mode 100644 tests/ImageSharp.Drawing.Tests/Svg/SvgFilterLightingRenderTests.cs
create mode 100644 tests/ImageSharp.Drawing.Tests/Svg/SvgFilterLightingTests.cs
create mode 100644 tests/ImageSharp.Drawing.Tests/Svg/SvgFilterParallelTests.cs
create mode 100644 tests/ImageSharp.Drawing.Tests/Svg/SvgFilterRenderTests.cs
create mode 100644 tests/ImageSharp.Drawing.Tests/Svg/SvgFilterSpatialRenderTests.cs
create mode 100644 tests/ImageSharp.Drawing.Tests/Svg/SvgFilterSpatialTests.cs
create mode 100644 tests/ImageSharp.Drawing.Tests/Svg/SvgFilterTests.cs
create mode 100644 tests/ImageSharp.Drawing.Tests/Svg/SvgGrowth.cs
create mode 100644 tests/ImageSharp.Drawing.Tests/Svg/SvgIntegrationTests.cs
create mode 100644 tests/ImageSharp.Drawing.Tests/Svg/SvgLayerLimitTests.cs
create mode 100644 tests/ImageSharp.Drawing.Tests/Svg/SvgLengthTests.cs
create mode 100644 tests/ImageSharp.Drawing.Tests/Svg/SvgMaskLayerEffectTests.cs
create mode 100644 tests/ImageSharp.Drawing.Tests/Svg/SvgMaskLayerPrototypeTests.cs
create mode 100644 tests/ImageSharp.Drawing.Tests/Svg/SvgNestedImageTextTests.cs
create mode 100644 tests/ImageSharp.Drawing.Tests/Svg/SvgNumberParserTests.cs
create mode 100644 tests/ImageSharp.Drawing.Tests/Svg/SvgPaintContentTests.cs
create mode 100644 tests/ImageSharp.Drawing.Tests/Svg/SvgPaintTests.cs
create mode 100644 tests/ImageSharp.Drawing.Tests/Svg/SvgPreserveAspectRatioTests.cs
create mode 100644 tests/ImageSharp.Drawing.Tests/Svg/SvgPropertyParserTests.cs
create mode 100644 tests/ImageSharp.Drawing.Tests/Svg/SvgReaderTests.cs
create mode 100644 tests/ImageSharp.Drawing.Tests/Svg/SvgRenderTests.cs
create mode 100644 tests/ImageSharp.Drawing.Tests/Svg/SvgResolverTests.cs
create mode 100644 tests/ImageSharp.Drawing.Tests/Svg/SvgResvgConformanceTests.cs
create mode 100644 tests/ImageSharp.Drawing.Tests/Svg/SvgSceneCacheTests.cs
create mode 100644 tests/ImageSharp.Drawing.Tests/Svg/SvgSelectorTests.cs
create mode 100644 tests/ImageSharp.Drawing.Tests/Svg/SvgSequentialCollection.cs
create mode 100644 tests/ImageSharp.Drawing.Tests/Svg/SvgStyleHostileDocumentTests.cs
create mode 100644 tests/ImageSharp.Drawing.Tests/Svg/SvgStylePropertyTests.cs
create mode 100644 tests/ImageSharp.Drawing.Tests/Svg/SvgStyleSheetTests.cs
create mode 100644 tests/ImageSharp.Drawing.Tests/Svg/SvgSvg2FeatureTests.cs
create mode 100644 tests/ImageSharp.Drawing.Tests/Svg/SvgSvg2HostileDocumentTests.cs
create mode 100644 tests/ImageSharp.Drawing.Tests/Svg/SvgSvg2RenderTests.cs
create mode 100644 tests/ImageSharp.Drawing.Tests/Svg/SvgTextBaselineDecorationTests.cs
create mode 100644 tests/ImageSharp.Drawing.Tests/Svg/SvgTextBidiTests.cs
create mode 100644 tests/ImageSharp.Drawing.Tests/Svg/SvgTextDecorationBaselineRenderTests.cs
create mode 100644 tests/ImageSharp.Drawing.Tests/Svg/SvgTextDirectionRenderTests.cs
create mode 100644 tests/ImageSharp.Drawing.Tests/Svg/SvgTextDirectionTests.cs
create mode 100644 tests/ImageSharp.Drawing.Tests/Svg/SvgTextHostileDocumentTests.cs
create mode 100644 tests/ImageSharp.Drawing.Tests/Svg/SvgTextIntegrationRenderTests.cs
create mode 100644 tests/ImageSharp.Drawing.Tests/Svg/SvgTextIntegrationTests.cs
create mode 100644 tests/ImageSharp.Drawing.Tests/Svg/SvgTextPathRenderTests.cs
create mode 100644 tests/ImageSharp.Drawing.Tests/Svg/SvgTextPathTests.cs
create mode 100644 tests/ImageSharp.Drawing.Tests/Svg/SvgTextRenderTests.cs
create mode 100644 tests/ImageSharp.Drawing.Tests/Svg/SvgTextTests.cs
create mode 100644 tests/ImageSharp.Drawing.Tests/Svg/SvgTextureReplayTests.cs
create mode 100644 tests/ImageSharp.Drawing.Tests/Svg/SvgTransformParserTests.cs
create mode 100644 tests/Images/Input/Svg/Charts/chart-dashboard-synthetic.svg
create mode 100644 tests/Images/Input/Svg/Compositing/compositing-dashboard-synthetic.svg
create mode 100644 tests/Images/Input/Svg/Compositing/pattern-chart-synthetic.svg
create mode 100644 tests/Images/Input/Svg/Css/css-features-synthetic.svg
create mode 100644 tests/Images/Input/Svg/DesignTool/LICENSE-Carbon
create mode 100755 tests/Images/Input/Svg/DesignTool/carbon-crab.svg
create mode 100644 tests/Images/Input/Svg/DesignTool/styled-landscape-synthetic.svg
create mode 100644 tests/Images/Input/Svg/Features/clip-path-shape-root.svg
create mode 100644 tests/Images/Input/Svg/Features/clip-path-shape.svg
create mode 100644 tests/Images/Input/Svg/Features/clip-path.svg
create mode 100644 tests/Images/Input/Svg/Features/cross-ch-attributes.svg
create mode 100644 tests/Images/Input/Svg/Features/cross-clip-ch.svg
create mode 100644 tests/Images/Input/Svg/Features/cross-clip-mask-filter.svg
create mode 100644 tests/Images/Input/Svg/Features/cross-clip-var-calc.svg
create mode 100644 tests/Images/Input/Svg/Features/cross-color.svg
create mode 100644 tests/Images/Input/Svg/Features/cross-d-path-length.svg
create mode 100644 tests/Images/Input/Svg/Features/cross-decoder.svg
create mode 100644 tests/Images/Input/Svg/Features/cross-embedded-text.svg
create mode 100644 tests/Images/Input/Svg/Features/cross-geometry-boxes.svg
create mode 100644 tests/Images/Input/Svg/Features/cross-lang.svg
create mode 100644 tests/Images/Input/Svg/Features/cross-paint-origin.svg
create mode 100644 tests/Images/Input/Svg/Features/cross-root-transform.svg
create mode 100644 tests/Images/Input/Svg/Features/cross-text-path-transform.svg
create mode 100644 tests/Images/Input/Svg/Features/cross-transform-clip.svg
create mode 100644 tests/Images/Input/Svg/Features/cross-var.svg
create mode 100644 tests/Images/Input/Svg/Features/css-calc.svg
create mode 100644 tests/Images/Input/Svg/Features/css-color.svg
create mode 100644 tests/Images/Input/Svg/Features/css-geometry.svg
create mode 100644 tests/Images/Input/Svg/Features/css-selectors.svg
create mode 100644 tests/Images/Input/Svg/Features/css-transform.svg
create mode 100644 tests/Images/Input/Svg/Features/css-var.svg
create mode 100644 tests/Images/Input/Svg/Features/css.svg
create mode 100644 tests/Images/Input/Svg/Features/current-color.svg
create mode 100644 tests/Images/Input/Svg/Features/display-visibility.svg
create mode 100644 tests/Images/Input/Svg/Features/fill-rule.svg
create mode 100644 tests/Images/Input/Svg/Features/filter-blend.svg
create mode 100644 tests/Images/Input/Svg/Features/filter-blur-accuracy.svg
create mode 100644 tests/Images/Input/Svg/Features/filter-blur.svg
create mode 100644 tests/Images/Input/Svg/Features/filter-bounds.svg
create mode 100644 tests/Images/Input/Svg/Features/filter-color-matrix.svg
create mode 100644 tests/Images/Input/Svg/Features/filter-color-space.svg
create mode 100644 tests/Images/Input/Svg/Features/filter-component-transfer.svg
create mode 100644 tests/Images/Input/Svg/Features/filter-composite.svg
create mode 100644 tests/Images/Input/Svg/Features/filter-convolve.svg
create mode 100644 tests/Images/Input/Svg/Features/filter-displacement.svg
create mode 100644 tests/Images/Input/Svg/Features/filter-drop-shadow.svg
create mode 100644 tests/Images/Input/Svg/Features/filter-errors.svg
create mode 100644 tests/Images/Input/Svg/Features/filter-flood.svg
create mode 100644 tests/Images/Input/Svg/Features/filter-functions.svg
create mode 100644 tests/Images/Input/Svg/Features/filter-image.svg
create mode 100644 tests/Images/Input/Svg/Features/filter-integration-compositing.svg
create mode 100644 tests/Images/Input/Svg/Features/filter-integration-content.svg
create mode 100644 tests/Images/Input/Svg/Features/filter-integration-root.svg
create mode 100644 tests/Images/Input/Svg/Features/filter-lighting-diffuse.svg
create mode 100644 tests/Images/Input/Svg/Features/filter-lighting-errors.svg
create mode 100644 tests/Images/Input/Svg/Features/filter-lighting-specular.svg
create mode 100644 tests/Images/Input/Svg/Features/filter-lighting-units.svg
create mode 100644 tests/Images/Input/Svg/Features/filter-morphology.svg
create mode 100644 tests/Images/Input/Svg/Features/filter-offset-merge.svg
create mode 100644 tests/Images/Input/Svg/Features/filter-outside-canvas.svg
create mode 100644 tests/Images/Input/Svg/Features/filter-region.svg
create mode 100644 tests/Images/Input/Svg/Features/filter-subregion.svg
create mode 100644 tests/Images/Input/Svg/Features/filter-tile.svg
create mode 100644 tests/Images/Input/Svg/Features/filter-transform.svg
create mode 100644 tests/Images/Input/Svg/Features/filter-turbulence.svg
create mode 100644 tests/Images/Input/Svg/Features/gradient-href.svg
create mode 100644 tests/Images/Input/Svg/Features/gradient-linear.svg
create mode 100644 tests/Images/Input/Svg/Features/gradient-radial.svg
create mode 100644 tests/Images/Input/Svg/Features/gradient-transformed.svg
create mode 100644 tests/Images/Input/Svg/Features/image.svg
create mode 100644 tests/Images/Input/Svg/Features/integration-css.svg
create mode 100644 tests/Images/Input/Svg/Features/integration-image-mask.svg
create mode 100644 tests/Images/Input/Svg/Features/integration-marker-clip.svg
create mode 100644 tests/Images/Input/Svg/Features/integration-mask-pattern.svg
create mode 100644 tests/Images/Input/Svg/Features/integration-nesting.svg
create mode 100644 tests/Images/Input/Svg/Features/integration-pattern-content.svg
create mode 100644 tests/Images/Input/Svg/Features/integration-use.svg
create mode 100644 tests/Images/Input/Svg/Features/lang-selector.svg
create mode 100644 tests/Images/Input/Svg/Features/marker.svg
create mode 100644 tests/Images/Input/Svg/Features/mask.svg
create mode 100644 tests/Images/Input/Svg/Features/mix-blend-mode.svg
create mode 100644 tests/Images/Input/Svg/Features/non-scaling-stroke.svg
create mode 100644 tests/Images/Input/Svg/Features/opacity.svg
create mode 100644 tests/Images/Input/Svg/Features/overflow.svg
create mode 100644 tests/Images/Input/Svg/Features/paint-order.svg
create mode 100644 tests/Images/Input/Svg/Features/path-length.svg
create mode 100644 tests/Images/Input/Svg/Features/pattern.svg
create mode 100644 tests/Images/Input/Svg/Features/root-align.svg
create mode 100644 tests/Images/Input/Svg/Features/root-stretch.svg
create mode 100644 tests/Images/Input/Svg/Features/root-transform.svg
create mode 100644 tests/Images/Input/Svg/Features/shape-rendering.svg
create mode 100644 tests/Images/Input/Svg/Features/shapes.svg
create mode 100644 tests/Images/Input/Svg/Features/stroke-caps-joins.svg
create mode 100644 tests/Images/Input/Svg/Features/stroke-dash-scaled.svg
create mode 100644 tests/Images/Input/Svg/Features/stroke-dash.svg
create mode 100644 tests/Images/Input/Svg/Features/stroke-width-opacity.svg
create mode 100644 tests/Images/Input/Svg/Features/switch.svg
create mode 100644 tests/Images/Input/Svg/Features/text-baseline.svg
create mode 100644 tests/Images/Input/Svg/Features/text-bidi.svg
create mode 100644 tests/Images/Input/Svg/Features/text-compositing.svg
create mode 100644 tests/Images/Input/Svg/Features/text-decoration.svg
create mode 100644 tests/Images/Input/Svg/Features/text-direction.svg
create mode 100644 tests/Images/Input/Svg/Features/text-font-features.svg
create mode 100644 tests/Images/Input/Svg/Features/text-integration-paint.svg
create mode 100644 tests/Images/Input/Svg/Features/text-integration-vertical.svg
create mode 100644 tests/Images/Input/Svg/Features/text-layout.svg
create mode 100644 tests/Images/Input/Svg/Features/text-length.svg
create mode 100644 tests/Images/Input/Svg/Features/text-paint-use.svg
create mode 100644 tests/Images/Input/Svg/Features/text-paint.svg
create mode 100644 tests/Images/Input/Svg/Features/text-path.svg
create mode 100644 tests/Images/Input/Svg/Features/transform-origin.svg
create mode 100644 tests/Images/Input/Svg/Features/transforms.svg
create mode 100644 tests/Images/Input/Svg/Features/units.svg
create mode 100644 tests/Images/Input/Svg/Features/use-symbol.svg
create mode 100644 tests/Images/Input/Svg/Features/viewbox-nested.svg
create mode 100644 tests/Images/Input/Svg/Filters/filter-blur-synthetic.svg
create mode 100644 tests/Images/Input/Svg/Filters/filter-chain-synthetic.svg
create mode 100644 tests/Images/Input/Svg/Filters/filter-shadows-synthetic.svg
create mode 100644 tests/Images/Input/Svg/Icons/Bootstrap/LICENSE
create mode 100644 tests/Images/Input/Svg/Icons/Bootstrap/bell-fill.svg
create mode 100644 tests/Images/Input/Svg/Icons/Bootstrap/bookmark-star-fill.svg
create mode 100644 tests/Images/Input/Svg/Icons/Bootstrap/bug-fill.svg
create mode 100644 tests/Images/Input/Svg/Icons/Bootstrap/camera-fill.svg
create mode 100644 tests/Images/Input/Svg/Icons/Bootstrap/chat-dots-fill.svg
create mode 100644 tests/Images/Input/Svg/Icons/Bootstrap/cloud-fill.svg
create mode 100644 tests/Images/Input/Svg/Icons/Bootstrap/envelope-fill.svg
create mode 100644 tests/Images/Input/Svg/Icons/Bootstrap/gear-fill.svg
create mode 100644 tests/Images/Input/Svg/Icons/Bootstrap/geo-alt-fill.svg
create mode 100644 tests/Images/Input/Svg/Icons/Bootstrap/heart-fill.svg
create mode 100644 tests/Images/Input/Svg/Icons/Bootstrap/house-fill.svg
create mode 100644 tests/Images/Input/Svg/Icons/Bootstrap/lightning-fill.svg
create mode 100644 tests/Images/Input/Svg/Icons/Bootstrap/puzzle-fill.svg
create mode 100644 tests/Images/Input/Svg/Icons/Bootstrap/shield-fill-check.svg
create mode 100644 tests/Images/Input/Svg/Icons/Bootstrap/star-fill.svg
create mode 100644 tests/Images/Input/Svg/Icons/Bootstrap/trash-fill.svg
create mode 100644 tests/Images/Input/Svg/Icons/Feather/LICENSE
create mode 100644 tests/Images/Input/Svg/Icons/Feather/activity.svg
create mode 100644 tests/Images/Input/Svg/Icons/Feather/alert-octagon.svg
create mode 100644 tests/Images/Input/Svg/Icons/Feather/archive.svg
create mode 100644 tests/Images/Input/Svg/Icons/Feather/box.svg
create mode 100644 tests/Images/Input/Svg/Icons/Feather/camera.svg
create mode 100644 tests/Images/Input/Svg/Icons/Feather/compass.svg
create mode 100644 tests/Images/Input/Svg/Icons/Feather/cpu.svg
create mode 100644 tests/Images/Input/Svg/Icons/Feather/database.svg
create mode 100644 tests/Images/Input/Svg/Icons/Feather/feather.svg
create mode 100644 tests/Images/Input/Svg/Icons/Feather/gift.svg
create mode 100644 tests/Images/Input/Svg/Icons/Feather/globe.svg
create mode 100644 tests/Images/Input/Svg/Icons/Feather/heart.svg
create mode 100644 tests/Images/Input/Svg/Icons/Feather/image.svg
create mode 100644 tests/Images/Input/Svg/Icons/Feather/layers.svg
create mode 100644 tests/Images/Input/Svg/Icons/Feather/map-pin.svg
create mode 100644 tests/Images/Input/Svg/Icons/Feather/monitor.svg
create mode 100644 tests/Images/Input/Svg/Icons/Feather/settings.svg
create mode 100644 tests/Images/Input/Svg/Icons/Feather/star.svg
create mode 100644 tests/Images/Input/Svg/Icons/Feather/sun.svg
create mode 100644 tests/Images/Input/Svg/Icons/Feather/truck.svg
create mode 100644 tests/Images/Input/Svg/Icons/Feather/user.svg
create mode 100644 tests/Images/Input/Svg/Icons/Feather/wifi.svg
create mode 100644 tests/Images/Input/Svg/Icons/Feather/x-octagon.svg
create mode 100644 tests/Images/Input/Svg/Icons/Feather/zap.svg
create mode 100644 tests/Images/Input/Svg/Icons/icon-sheet-synthetic.svg
create mode 100644 tests/Images/Input/Svg/Illustrations/LICENSE-Fluent-Emoji
create mode 100644 tests/Images/Input/Svg/Illustrations/fluent-moose.svg
create mode 100644 tests/Images/Input/Svg/Illustrations/fluent-soft-ice-cream.svg
create mode 100644 tests/Images/Input/Svg/Maps/street-map-synthetic.svg
create mode 100644 tests/Images/Input/Svg/Text/text-decorations-synthetic.svg
create mode 100644 tests/Images/Input/Svg/Text/text-heavy-synthetic.svg
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgCompositingRenderTests/DrawSvg_CompositingFeature_clip-path.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgCompositingRenderTests/DrawSvg_CompositingFeature_mask.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgCompositingRenderTests/DrawSvg_CompositingFeature_mix-blend-mode.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgCompositingRenderTests/DrawSvg_CompositingFeature_non-scaling-stroke.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgCompositingRenderTests/DrawSvg_CompositingFeature_overflow.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgCompositingRenderTests/DrawSvg_CompositingFeature_paint-order.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgCompositingRenderTests/DrawSvg_CompositingFeature_root-transform.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgCompositingRenderTests/DrawSvg_CompositingFeature_shape-rendering.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgCompositingRenderTests/DrawSvg_CompositingFeature_switch.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgCrossFeatureRenderTests/DrawSvg_CrossFeature_cross-ch-attributes.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgCrossFeatureRenderTests/DrawSvg_CrossFeature_cross-clip-ch.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgCrossFeatureRenderTests/DrawSvg_CrossFeature_cross-clip-mask-filter.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgCrossFeatureRenderTests/DrawSvg_CrossFeature_cross-clip-var-calc.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgCrossFeatureRenderTests/DrawSvg_CrossFeature_cross-color.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgCrossFeatureRenderTests/DrawSvg_CrossFeature_cross-d-path-length.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgCrossFeatureRenderTests/DrawSvg_CrossFeature_cross-decoder.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgCrossFeatureRenderTests/DrawSvg_CrossFeature_cross-embedded-text.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgCrossFeatureRenderTests/DrawSvg_CrossFeature_cross-geometry-boxes.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgCrossFeatureRenderTests/DrawSvg_CrossFeature_cross-lang.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgCrossFeatureRenderTests/DrawSvg_CrossFeature_cross-paint-origin.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgCrossFeatureRenderTests/DrawSvg_CrossFeature_cross-root-transform.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgCrossFeatureRenderTests/DrawSvg_CrossFeature_cross-text-path-transform.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgCrossFeatureRenderTests/DrawSvg_CrossFeature_cross-transform-clip.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgCrossFeatureRenderTests/DrawSvg_CrossFeature_cross-var.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgCssFeatureRenderTests/DrawSvg_CssFeature_css-calc.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgCssFeatureRenderTests/DrawSvg_CssFeature_css-color.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgCssFeatureRenderTests/DrawSvg_CssFeature_css-geometry.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgCssFeatureRenderTests/DrawSvg_CssFeature_css-transform.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgCssFeatureRenderTests/DrawSvg_CssFeature_css-var.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgFilterIntegrationRenderTests/DrawSvg_FilterIntegration_filter-integration-compositing.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgFilterIntegrationRenderTests/DrawSvg_FilterIntegration_filter-integration-content.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgFilterIntegrationRenderTests/DrawSvg_FilterIntegration_filter-integration-root.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgFilterLightingRenderTests/DrawSvg_LightingFeature_filter-lighting-diffuse-200.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgFilterLightingRenderTests/DrawSvg_LightingFeature_filter-lighting-diffuse-400.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgFilterLightingRenderTests/DrawSvg_LightingFeature_filter-lighting-errors-200.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgFilterLightingRenderTests/DrawSvg_LightingFeature_filter-lighting-specular-200.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgFilterLightingRenderTests/DrawSvg_LightingFeature_filter-lighting-units-200.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgFilterLightingRenderTests/DrawSvg_LightingFeature_filter-lighting-units-400x200.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgFilterRenderTests/DrawSvg_FilterFeature_filter-blend-200.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgFilterRenderTests/DrawSvg_FilterFeature_filter-blur-200.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgFilterRenderTests/DrawSvg_FilterFeature_filter-blur-500.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgFilterRenderTests/DrawSvg_FilterFeature_filter-blur-accuracy-400.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgFilterRenderTests/DrawSvg_FilterFeature_filter-bounds-200.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgFilterRenderTests/DrawSvg_FilterFeature_filter-color-matrix-200.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgFilterRenderTests/DrawSvg_FilterFeature_filter-color-space-200.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgFilterRenderTests/DrawSvg_FilterFeature_filter-component-transfer-200.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgFilterRenderTests/DrawSvg_FilterFeature_filter-composite-200.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgFilterRenderTests/DrawSvg_FilterFeature_filter-drop-shadow-200.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgFilterRenderTests/DrawSvg_FilterFeature_filter-errors-200.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgFilterRenderTests/DrawSvg_FilterFeature_filter-flood-200.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgFilterRenderTests/DrawSvg_FilterFeature_filter-functions-200.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgFilterRenderTests/DrawSvg_FilterFeature_filter-image-200.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgFilterRenderTests/DrawSvg_FilterFeature_filter-offset-merge-200.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgFilterRenderTests/DrawSvg_FilterFeature_filter-outside-canvas-200.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgFilterRenderTests/DrawSvg_FilterFeature_filter-region-200.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgFilterRenderTests/DrawSvg_FilterFeature_filter-subregion-200.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgFilterRenderTests/DrawSvg_FilterFeature_filter-tile-200.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgFilterRenderTests/DrawSvg_FilterFeature_filter-tile-300.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgFilterRenderTests/DrawSvg_FilterFeature_filter-transform-200.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgFilterSpatialRenderTests/DrawSvg_FilterFeature_filter-convolve-200.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgFilterSpatialRenderTests/DrawSvg_FilterFeature_filter-displacement-200.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgFilterSpatialRenderTests/DrawSvg_FilterFeature_filter-morphology-200.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgFilterSpatialRenderTests/DrawSvg_FilterFeature_filter-turbulence-200.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgFilterSpatialRenderTests/DrawSvg_FilterFeature_filter-turbulence-500.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgIntegrationTests/DrawSvg_Integration_integration-css-200.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgIntegrationTests/DrawSvg_Integration_integration-image-mask-200.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgIntegrationTests/DrawSvg_Integration_integration-marker-clip-200.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgIntegrationTests/DrawSvg_Integration_integration-mask-pattern-200.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgIntegrationTests/DrawSvg_Integration_integration-mask-pattern-400.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgIntegrationTests/DrawSvg_Integration_integration-nesting-200.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgIntegrationTests/DrawSvg_Integration_integration-pattern-content-200.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgIntegrationTests/DrawSvg_Integration_integration-use-200.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgPaintContentTests/DrawSvg_PaintContent_image-200.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgPaintContentTests/DrawSvg_PaintContent_marker-200.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgPaintContentTests/DrawSvg_PaintContent_pattern-200.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgPaintContentTests/DrawSvg_PaintContent_pattern-400.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Corpus_carbon-crab.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Corpus_fluent-moose.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Corpus_fluent-soft-ice-cream.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Corpus_styled-landscape-synthetic.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Feature_css-selectors.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Feature_css.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Feature_current-color.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Feature_display-visibility.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Feature_fill-rule.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Feature_gradient-href.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Feature_gradient-linear.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Feature_gradient-radial.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Feature_gradient-transformed.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Feature_opacity.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Feature_root-align.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Feature_root-stretch.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Feature_shapes.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Feature_stroke-caps-joins.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Feature_stroke-dash-scaled.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Feature_stroke-dash.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Feature_stroke-width-opacity.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Feature_transform-origin.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Feature_transforms.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Feature_units.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Feature_use-symbol.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Feature_viewbox-nested.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Icons_activity.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Icons_alert-octagon.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Icons_archive.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Icons_bell-fill.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Icons_bookmark-star-fill.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Icons_box.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Icons_bug-fill.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Icons_camera-fill.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Icons_camera.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Icons_chat-dots-fill.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Icons_cloud-fill.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Icons_compass.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Icons_cpu.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Icons_database.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Icons_envelope-fill.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Icons_feather.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Icons_gear-fill.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Icons_geo-alt-fill.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Icons_gift.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Icons_globe.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Icons_heart-fill.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Icons_heart.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Icons_house-fill.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Icons_image.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Icons_layers.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Icons_lightning-fill.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Icons_map-pin.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Icons_monitor.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Icons_puzzle-fill.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Icons_settings.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Icons_shield-fill-check.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Icons_star-fill.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Icons_star.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Icons_sun.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Icons_trash-fill.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Icons_truck.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Icons_user.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Icons_wifi.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Icons_x-octagon.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Icons_zap.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Paris_paris.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgRenderTests/DrawSvg_Tiger_tiger.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgSvg2RenderTests/DrawSvg_Svg2Feature_clip-path-shape-root.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgSvg2RenderTests/DrawSvg_Svg2Feature_clip-path-shape.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgSvg2RenderTests/DrawSvg_Svg2Feature_lang-selector.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgSvg2RenderTests/DrawSvg_Svg2Feature_path-length.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgSvg2RenderTests/DrawSvg_Svg2TextFeature_text-font-features.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgSvg2RenderTests/DrawSvg_Svg2TextFeature_text-paint-use.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgTextDecorationBaselineRenderTests/DrawSvg_TextDecorationAndBaselines_text-baseline.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgTextDecorationBaselineRenderTests/DrawSvg_TextDecorationAndBaselines_text-decoration.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgTextDirectionRenderTests/DrawSvg_TextBidi.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgTextDirectionRenderTests/DrawSvg_TextDirection.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgTextIntegrationRenderTests/DrawSvg_TextIntegration_text-integration-paint.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgTextIntegrationRenderTests/DrawSvg_TextIntegration_text-integration-vertical.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgTextPathRenderTests/DrawSvg_TextPathAndTextLength_text-length.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgTextPathRenderTests/DrawSvg_TextPathAndTextLength_text-path.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgTextRenderTests/DrawSvg_Text_text-compositing.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgTextRenderTests/DrawSvg_Text_text-layout.png
create mode 100644 tests/Images/ReferenceOutput/Svg/SvgTextRenderTests/DrawSvg_Text_text-paint.png
create mode 100644 tests/SvgTools/README.md
create mode 100644 tests/SvgTools/compare-png.cs
create mode 100644 tests/SvgTools/fetch-resvg-tests.cs
create mode 100644 tests/SvgTools/render-svg.cs
diff --git a/.gitignore b/.gitignore
index 81d70e71b..647ed163c 100644
--- a/.gitignore
+++ b/.gitignore
@@ -222,6 +222,9 @@ artifacts/
# Tests
**/Images/ActualOutput
+# External SVG conformance tests, fetched by tests/SvgTools/fetch-resvg-tests.cs
+/tests/Images/External/
+
# sample output
/samples/DrawShapesWithImageSharp/Output/**
diff --git a/THIRD-PARTY-NOTICES b/THIRD-PARTY-NOTICES
index 261aa50aa..293a5e348 100644
--- a/THIRD-PARTY-NOTICES
+++ b/THIRD-PARTY-NOTICES
@@ -112,3 +112,161 @@ Version 2.0. The full license text is available in the gs1-syntax-dictionary
repository LICENSE file.
================================================================================
+
+RichTextKit (https://github.com/toptensoftware/RichTextKit)
+License: Apache-2.0
+
+The Unicode bidirectional algorithm in src/ImageSharp.Drawing/Svg/Text/Bidi is
+a temporary copy of the internal implementation of SixLabors.Fonts 3.2.1
+(src/SixLabors.Fonts/Unicode/BidiAlgorithm.cs and the types it needs).
+SixLabors.Fonts has the same owner and license as this software. Its
+src/SixLabors.Fonts/Unicode/README.md names RichTextKit among the sources of
+its Unicode code, so this notice applies to the copied files.
+
+Copyright (c) 2019-2020 Topten Software. All Rights Reserved.
+
+RichTextKit is distributed under the Apache License, Version 2.0. The full
+license text is available in the RichTextKit repository LICENSE file.
+
+================================================================================
+
+W3C specifications (https://www.w3.org/TR/filter-effects-1/, https://www.w3.org/TR/SVG11/, https://www.w3.org/TR/css-color-4/)
+License: W3C Software and Document License
+
+The feTurbulence filter primitive follows the reference code that the W3C
+specifications give for it: the random number generator, the lattice setup,
+the noise function, and the turbulence function of "Filter Effects Module
+Level 1" (section feTurbulence), with the gradient normalization of
+"Scalable Vector Graphics (SVG) 1.1 (Second Edition)" (chapter Filter
+Effects). The code was translated to C# and changed to compute four channels
+at a time.
+See also: src/ImageSharp.Drawing/Svg/Filters/SvgFeTurbulence.cs
+
+This software includes material copied from or derived from Filter Effects
+Module Level 1 (https://www.w3.org/TR/filter-effects-1/) and Scalable Vector
+Graphics (SVG) 1.1 (Second Edition) (https://www.w3.org/TR/SVG11/).
+Copyright (c) 2018 and 2011 World Wide Web Consortium.
+https://www.w3.org/copyright/software-license-2023/
+
+The conversions between CSS color spaces follow the sample code of "CSS Color
+Module Level 4" (section "Sample code for Color Conversions"): the white
+points, the conversion matrices, and the transfer functions. The code was
+translated to C#.
+See also: src/ImageSharp.Drawing/Svg/Parsing/SvgCssColor.cs
+
+This software includes material copied from or derived from CSS Color Module
+Level 4 (https://www.w3.org/TR/css-color-4/).
+Copyright (c) 2026 World Wide Web Consortium.
+https://www.w3.org/copyright/software-license-2023/
+
+The full license text is available at
+https://www.w3.org/copyright/software-license-2023/.
+
+================================================================================
+
+Jint (https://github.com/sebastienros/jint)
+License: BSD-2-Clause
+
+Portions of this software were adapted from the CSS tokenizer and the CSS
+syntax parser of the Jint project, including tokenization, escape, string,
+URL, and comment handling, and the rule and declaration error recovery.
+See also:
+ - src/ImageSharp.Drawing/Svg/Css/SvgCssTokenizer.cs
+ - src/ImageSharp.Drawing/Svg/Css/SvgCssParser.cs
+
+Copyright (c) 2013, Sebastien Ros
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+1. Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+2. Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+================================================================================
+
+Test and benchmark input files
+================================================================================
+
+The files below are inputs for tests and benchmarks under tests/Images/Input/Svg.
+They are not part of the SixLabors.ImageSharp.Drawing package. Each folder holds
+a copy of the license of its files.
+
+================================================================================
+
+Feather (https://github.com/feathericons/feather)
+License: MIT
+
+24 icons from the feather-icons 4.29.2 npm package, unchanged.
+Location: tests/Images/Input/Svg/Icons/Feather
+
+tests/Images/Input/Svg/Icons/icon-sheet-synthetic.svg is derived from these
+icons: it holds each of them as a symbol and draws the symbols in a grid.
+
+Copyright (c) 2013-2023 Cole Bemis
+
+Feather is distributed under the MIT License. The full license text is in
+tests/Images/Input/Svg/Icons/Feather/LICENSE.
+
+================================================================================
+
+Bootstrap Icons (https://github.com/twbs/icons)
+License: MIT
+
+16 icons from the bootstrap-icons 1.13.2 npm package, unchanged.
+Location: tests/Images/Input/Svg/Icons/Bootstrap
+
+tests/Images/Input/Svg/Icons/icon-sheet-synthetic.svg is derived from these
+icons: it holds each of them as a symbol and draws the symbols in a grid.
+
+Copyright (c) 2019-2024 The Bootstrap Authors
+
+Bootstrap Icons are distributed under the MIT License. The full license text
+is in tests/Images/Input/Svg/Icons/Bootstrap/LICENSE.
+
+================================================================================
+
+Fluent Emoji (https://github.com/microsoft/fluentui-emoji)
+License: MIT
+
+Two "Color" style emoji from commit 1ffb34c752ecf5d402f04cfb4b392c77f57c54bc.
+Location: tests/Images/Input/Svg/Illustrations
+ - fluent-moose.svg: assets/Moose/Color/moose_color.svg, unchanged.
+ - fluent-soft-ice-cream.svg: assets/Soft ice cream/Color/soft_ice_cream_color.svg,
+ modified: the blurred highlight group and its filter definition are removed.
+
+Copyright (c) Microsoft Corporation.
+
+Fluent Emoji is distributed under the MIT License. The full license text is in
+tests/Images/Input/Svg/Illustrations/LICENSE-Fluent-Emoji.
+
+================================================================================
+
+Carbon Design System pictograms (https://github.com/carbon-design-system/carbon)
+License: Apache-2.0
+
+One pictogram source file from the @carbon/pictograms 12.88.0 npm package
+(src/svg/crab.svg), unchanged.
+Location: tests/Images/Input/Svg/DesignTool/carbon-crab.svg
+
+Copyright 2015 IBM Corp.
+
+The Carbon pictograms are distributed under the Apache License, Version 2.0.
+The full license text is in tests/Images/Input/Svg/DesignTool/LICENSE-Carbon.
+
+================================================================================
diff --git a/src/ImageSharp.Drawing/CubicBezierLineSegment.cs b/src/ImageSharp.Drawing/CubicBezierLineSegment.cs
index acd6d747b..afd8f00c4 100644
--- a/src/ImageSharp.Drawing/CubicBezierLineSegment.cs
+++ b/src/ImageSharp.Drawing/CubicBezierLineSegment.cs
@@ -2,6 +2,7 @@
// Licensed under the Six Labors Split License.
using System.Numerics;
+using System.Runtime.CompilerServices;
using SixLabors.ImageSharp.Drawing.Helpers;
namespace SixLabors.ImageSharp.Drawing;
@@ -64,6 +65,18 @@ public CubicBezierLineSegment(PointF start, PointF controlPoint1, PointF control
{
}
+ ///
+ /// Receives the flattened points in order.
+ ///
+ private interface IPointSink
+ {
+ ///
+ /// Receives the next point.
+ ///
+ /// The point.
+ public void Add(PointF point);
+ }
+
///
/// Gets the control points.
///
@@ -76,7 +89,24 @@ public CubicBezierLineSegment(PointF start, PointF controlPoint1, PointF control
public PointF EndPoint => this.controlPoints[^1];
///
- public RectangleF Bounds => CalculateBounds(this.GetFlattenedPoints(Vector2.One));
+ public RectangleF Bounds
+ {
+ get
+ {
+ FlattenedCache? hit = Volatile.Read(ref this.flattenedCache);
+ if (hit is not null && hit.Scale == Vector2.One)
+ {
+ return CalculateBounds(hit.Points);
+ }
+
+ // The bounds are those of the points that a flattening at scale one gives. They are taken from
+ // the points as they are produced, in the same order, so the result is the same as from the
+ // retained array, without allocating one or replacing a cached flattening at the render scale.
+ BoundsSink sink = new();
+ Flatten(this.controlPoints, Vector2.One, ref sink);
+ return sink.ToBounds();
+ }
+ }
///
public int LinearVertexCount(Vector2 scale) => this.GetFlattenedPoints(scale).Length;
@@ -158,8 +188,22 @@ private static PointF[] FlattenCurve(PointF[] controlPoints, Vector2 scale)
// Flattened points are cached as a retained array, so use the builder to avoid
// the intermediate collection and copy a list would generate.
- FlattenedPointBuilder output = new(curveCount * 4);
+ BuilderSink output = new(new FlattenedPointBuilder(curveCount * 4));
+ Flatten(controlPoints, scale, ref output);
+ return output.Builder.Detach();
+ }
+ ///
+ /// Produces the flattened points of every cubic in in order.
+ ///
+ /// The receiver of the points.
+ /// The bezier control points; the length is a multiple of 3 plus 1.
+ /// The X/Y scale at which the curve is flattened.
+ /// The sink that each point is passed to.
+ private static void Flatten(PointF[] controlPoints, Vector2 scale, ref TSink output)
+ where TSink : struct, IPointSink
+ {
+ int curveCount = (controlPoints.Length - 1) / 3;
for (int curveIndex = 0; curveIndex < curveCount; curveIndex++)
{
int nodeIndex = curveIndex * 3;
@@ -173,16 +217,58 @@ private static PointF[] FlattenCurve(PointF[] controlPoints, Vector2 scale)
output.Add((PointF)p0);
}
- SubdivideAndAppend(0F, 1F, p0, p3, p0, p1, p2, p3, ref output, 0);
+ // A control point that is not finite, for example after an overflow in the arc conversion or in a
+ // transform, gives a curve without a shape. Its flatness test never passes, so the subdivision would
+ // run to the depth limit and produce about two million points. Such a curve keeps only its end points.
+ if (IsFinite(p0) && IsFinite(p1) && IsFinite(p2) && IsFinite(p3))
+ {
+ SubdivideAndAppend(0F, 1F, p0, p3, p0, p1, p2, p3, GetFlatnessSqrTolerance(p0, p1, p2, p3), ref output, 0);
+ }
+
output.Add((PointF)p3);
}
+ }
+
+ ///
+ /// Returns whether both coordinates of a point are finite.
+ ///
+ /// The point.
+ /// if neither coordinate is infinite or NaN.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ private static bool IsFinite(Vector2 point) => float.IsFinite(point.X) && float.IsFinite(point.Y);
- return output.Detach();
+ ///
+ /// Returns the squared flatness tolerance of one cubic: , or the rounding error of
+ /// the flatness test at the magnitude of the control points when that is larger.
+ ///
+ ///
+ /// The flatness test compares two points computed in single precision: the curve point at the middle of a span (a
+ /// sum of four products) and the middle of its chord. Each carries a rounding error of a few units in the last place
+ /// of the largest coordinate m, about m × 2^-24 per operation, so the measured deviation can be wrong by
+ /// up to about 8 × m × 2^-24 = m × 2^-21. When that exceeds the tolerance of 1/64, the test can fail at every
+ /// depth however flat the span is, and the subdivision runs to its depth limit: about two million points per cubic.
+ /// The tolerance therefore never goes below that error. It changes nothing while m is at most 2^15 = 32768
+ /// (2^15 × 2^-21 = 2^-6 = 1/64); above that, the polyline is as close to the curve as single precision can place
+ /// it. Since the deviation of a span shrinks four times per level and starts at most at the size of the control
+ /// polygon (a few times m), a span meets the tolerance within about 11 levels, so a cubic gives at most about
+ /// 2^11 points.
+ ///
+ /// The start point of the cubic.
+ /// The first control point of the cubic.
+ /// The second control point of the cubic.
+ /// The end point of the cubic.
+ /// The squared tolerance.
+ private static float GetFlatnessSqrTolerance(Vector2 p0, Vector2 p1, Vector2 p2, Vector2 p3)
+ {
+ Vector2 extent = Vector2.Max(Vector2.Max(Vector2.Abs(p0), Vector2.Abs(p1)), Vector2.Max(Vector2.Abs(p2), Vector2.Abs(p3)));
+ float roundingError = MathF.Max(extent.X, extent.Y) * (1F / (1 << 21));
+ return MathF.Max(FlatnessSqrTolerance, roundingError * roundingError);
}
///
/// Recursively subdivides the scaled cubic segment, appending midpoints in left-to-right order.
///
+ /// The receiver of the points.
/// The curve parameter at the start of the span.
/// The curve parameter at the end of the span.
/// The curve point at , carried down so each level evaluates one new point.
@@ -191,9 +277,10 @@ private static PointF[] FlattenCurve(PointF[] controlPoints, Vector2 scale)
/// The first control point of the cubic.
/// The second control point of the cubic.
/// The end point of the cubic.
- /// The builder receiving the appended points.
+ /// The squared flatness tolerance of the cubic ().
+ /// The receiver of the appended points.
/// The current recursion depth; used to bound the subdivision.
- private static void SubdivideAndAppend(
+ private static void SubdivideAndAppend(
float t0,
float t1,
Vector2 left,
@@ -202,8 +289,10 @@ private static void SubdivideAndAppend(
Vector2 p1,
Vector2 p2,
Vector2 p3,
- ref FlattenedPointBuilder output,
+ float flatnessSqrTolerance,
+ ref TSink output,
int depth)
+ where TSink : struct, IPointSink
{
// Normal finite curves reach the flatness test first. The limit prevents unbounded
// recursion for extreme input.
@@ -218,15 +307,17 @@ private static void SubdivideAndAppend(
// Compare the curve midpoint with the midpoint of the candidate line. An S-shaped cubic
// can cross its chord at the root midpoint while still bending on both sides. Subdivide the
// root once before trusting this test so the two bends are tested separately.
- Vector2 chordMid = (left + right) * 0.5F;
- if (depth > 0 && (mid - chordMid).LengthSquared() <= FlatnessSqrTolerance)
+ // Each end is halved before the sum, so two ends near the largest float do not overflow to infinity,
+ // which would fail the flatness test at every depth. Halving is exact, so the midpoint is the same value.
+ Vector2 chordMid = (left * 0.5F) + (right * 0.5F);
+ if (depth > 0 && (mid - chordMid).LengthSquared() <= flatnessSqrTolerance)
{
return;
}
- SubdivideAndAppend(t0, midT, left, mid, p0, p1, p2, p3, ref output, depth + 1);
+ SubdivideAndAppend(t0, midT, left, mid, p0, p1, p2, p3, flatnessSqrTolerance, ref output, depth + 1);
output.Add((PointF)mid);
- SubdivideAndAppend(midT, t1, mid, right, p0, p1, p2, p3, ref output, depth + 1);
+ SubdivideAndAppend(midT, t1, mid, right, p0, p1, p2, p3, flatnessSqrTolerance, ref output, depth + 1);
}
///
@@ -281,6 +372,58 @@ private static RectangleF CalculateBounds(ReadOnlySpan points)
return RectangleF.FromLTRB(minX, minY, maxX, maxY);
}
+ ///
+ /// Appends the flattened points to a .
+ ///
+ /// The builder.
+ private struct BuilderSink(FlattenedPointBuilder builder) : IPointSink
+ {
+ ///
+ /// The builder that holds the points.
+ ///
+ public FlattenedPointBuilder Builder = builder;
+
+ ///
+ public void Add(PointF point) => this.Builder.Add(point);
+ }
+
+ ///
+ /// Accumulates the bounds of the flattened points with the same operations as .
+ ///
+ private struct BoundsSink : IPointSink
+ {
+ private float minX;
+ private float minY;
+ private float maxX;
+ private float maxY;
+
+ ///
+ /// Initializes a new instance of the struct.
+ ///
+ public BoundsSink()
+ {
+ this.minX = float.MaxValue;
+ this.minY = float.MaxValue;
+ this.maxX = float.MinValue;
+ this.maxY = float.MinValue;
+ }
+
+ ///
+ public void Add(PointF point)
+ {
+ this.minX = MathF.Min(this.minX, point.X);
+ this.minY = MathF.Min(this.minY, point.Y);
+ this.maxX = MathF.Max(this.maxX, point.X);
+ this.maxY = MathF.Max(this.maxY, point.Y);
+ }
+
+ ///
+ /// Gets the bounds of the points received.
+ ///
+ /// The axis-aligned bounds.
+ public readonly RectangleF ToBounds() => RectangleF.FromLTRB(this.minX, this.minY, this.maxX, this.maxY);
+ }
+
///
/// An immutable pairing of a flatten scale with the point run baked at that scale.
///
diff --git a/src/ImageSharp.Drawing/FlattenedPointBuilder.cs b/src/ImageSharp.Drawing/FlattenedPointBuilder.cs
index 9000c6db0..b957b0fd9 100644
--- a/src/ImageSharp.Drawing/FlattenedPointBuilder.cs
+++ b/src/ImageSharp.Drawing/FlattenedPointBuilder.cs
@@ -8,12 +8,27 @@ namespace SixLabors.ImageSharp.Drawing;
///
///
/// Segment flatteners ultimately need to return a tightly-sized array that can be cached by the segment instance.
-/// This builder owns that array while points are appended.
+/// The builder appends into a scratch array that the thread reuses between builds, and
+/// copies the appended points into one array of the exact length. A build therefore allocates only its result,
+/// not the arrays that a growing buffer would discard.
///
internal struct FlattenedPointBuilder
{
///
- /// The owned backing array. Grows geometrically; trimmed to by .
+ /// The largest scratch array that a thread keeps between builds (32 KB), so one large curve does not
+ /// keep a large buffer alive on the thread.
+ ///
+ private const int MaxRetainedScratchLength = 4096;
+
+ ///
+ /// The scratch array of the thread. A builder takes it while it builds and gives it back in
+ /// , so a builder that starts while another is building gets its own array.
+ ///
+ [ThreadStatic]
+ private static PointF[]? threadScratch;
+
+ ///
+ /// The scratch array the points are appended to. Grows geometrically.
///
private PointF[] points;
@@ -28,7 +43,9 @@ internal struct FlattenedPointBuilder
/// The estimated number of points that will be appended.
public FlattenedPointBuilder(int capacity)
{
- this.points = new PointF[Math.Max(capacity, 4)];
+ PointF[]? scratch = threadScratch;
+ threadScratch = null;
+ this.points = scratch is not null && scratch.Length >= capacity ? scratch : new PointF[Math.Max(capacity, 64)];
this.count = 0;
}
@@ -60,21 +77,23 @@ public Span GetAppendSpan(int length)
public void Advance(int length) => this.count += length;
///
- /// Returns the owned point array, trimmed to the appended count.
+ /// Returns a new array with the appended points and gives the scratch array back to the thread.
///
///
- /// Ownership of the array transfers to the caller. The builder must not be appended to afterwards as further
- /// writes could mutate the detached array.
+ /// The builder must not be appended to afterwards.
///
/// The tightly-sized retained point array.
public PointF[] Detach()
{
- if (this.count != this.points.Length)
+ PointF[] result = this.points.AsSpan(0, this.count).ToArray();
+ if (this.points.Length <= MaxRetainedScratchLength)
{
- Array.Resize(ref this.points, this.count);
+ threadScratch = this.points;
}
- return this.points;
+ this.points = [];
+ this.count = 0;
+ return result;
}
///
diff --git a/src/ImageSharp.Drawing/Helpers/ValueListBuilder.cs b/src/ImageSharp.Drawing/Helpers/ValueListBuilder.cs
index 9c0cb602d..5cd7285af 100644
--- a/src/ImageSharp.Drawing/Helpers/ValueListBuilder.cs
+++ b/src/ImageSharp.Drawing/Helpers/ValueListBuilder.cs
@@ -123,6 +123,13 @@ public Span AppendSpan(int length)
/// The values written so far.
public readonly Span AsSpan() => this.values[..this.position];
+ ///
+ /// Removes the values from on and keeps the buffer, so one builder can serve as a stack or
+ /// collect several lists in turn.
+ ///
+ /// The new number of values, at most .
+ public void Truncate(int length) => this.position = length;
+
///
/// Returns the pooled array, if the builder rented one. An array of references is cleared first so
/// the pool does not keep them alive.
diff --git a/src/ImageSharp.Drawing/Path.cs b/src/ImageSharp.Drawing/Path.cs
index 0d0912e2f..7e193464c 100644
--- a/src/ImageSharp.Drawing/Path.cs
+++ b/src/ImageSharp.Drawing/Path.cs
@@ -4,6 +4,7 @@
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Numerics;
+using SixLabors.ImageSharp.Drawing.Svg;
namespace SixLabors.ImageSharp.Drawing;
@@ -344,10 +345,54 @@ public static bool TryParseSvgPath(string svgPath, [NotNullWhen(true)] out IPath
/// if the input value can be parsed and converted; otherwise, .
public static bool TryParseSvgPath(ReadOnlySpan svgPath, [NotNullWhen(true)] out IPath? value)
{
- value = null;
+ PathBuilder builder = new();
+ if (!TryAppendSvgPath(svgPath, builder))
+ {
+ value = null;
+ return false;
+ }
+
+ value = builder.Build();
+ return true;
+ }
+ ///
+ /// Converts SVG path data into an and keeps the commands before the first error.
+ ///
+ ///
+ /// SVG requires a renderer to draw path data up to, but not including, the command that contains the first error.
+ /// The public rejects the whole path instead, so the
+ /// SVG reader uses this method.
+ ///
+ /// The SVG path data.
+ ///
+ /// When this method returns, contains the path built from every command before the first error. The path is empty when
+ /// the first command is in error.
+ ///
+ /// if the whole path data parsed without error; otherwise, .
+ internal static bool TryParseSvgPathPrefix(ReadOnlySpan svgPath, out IPath value)
+ {
+ // SVG path data must start with a move command. Any other first command is the first error, so nothing renders.
+ // The public parser accepts such data and starts at the origin, and keeps that behavior.
+ ReadOnlySpan trimmed = svgPath.TrimStart();
PathBuilder builder = new();
+ bool complete = (trimmed.Length == 0 || trimmed[0] is 'M' or 'm') && TryAppendSvgPath(svgPath, builder);
+ value = builder.Build();
+ return complete;
+ }
+ ///
+ /// Appends the commands of SVG path data to .
+ ///
+ ///
+ /// Each command reads all of its operands before it appends geometry, so on failure the builder holds exactly the
+ /// commands before the one in error.
+ ///
+ /// The SVG path data.
+ /// The builder that receives the path commands.
+ /// if the whole path data parsed without error; otherwise, .
+ private static bool TryAppendSvgPath(ReadOnlySpan svgPath, PathBuilder builder)
+ {
PointF first = PointF.Empty;
PointF c = PointF.Empty;
PointF lastc = PointF.Empty;
@@ -540,7 +585,9 @@ public static bool TryParseSvgPath(ReadOnlySpan svgPath, [NotNullWhen(true
c = point;
break;
case 'Z':
- _ = builder.CloseFigure();
+ // A command after a close starts a new subpath at the start point of the closed one, so the builder
+ // moves there; a following move command replaces that start point.
+ _ = builder.CloseFigure().MoveTo(first);
c = first;
break;
case '~':
@@ -564,7 +611,6 @@ public static bool TryParseSvgPath(ReadOnlySpan svgPath, [NotNullWhen(true
previousOp = op;
}
- value = builder.Build();
return true;
}
@@ -620,7 +666,9 @@ private static bool TryTrimSeparator(ref ReadOnlySpan str)
private static bool TryFindScaler(ref ReadOnlySpan str, out float value)
{
ReadOnlySpan source = TrimSeparator(str);
- if (TryReadScalar(source, out value, out int length))
+
+ // Path data allows a trailing decimal point, as in "5.", in its number grammar.
+ if (SvgNumberParser.TryReadNumber(source, true, out value, out int length))
{
str = source[length..];
return true;
@@ -665,62 +713,6 @@ private static bool TryFindPoint(ref ReadOnlySpan str, bool relative, Poin
return false;
}
- ///
- /// Scans the length of the leading number token and parses it.
- ///
- /// The character data starting at the number.
- /// When this method returns, contains the parsed number.
- /// When this method returns, contains the number of characters consumed.
- /// if a finite number was parsed; otherwise, .
- private static bool TryReadScalar(ReadOnlySpan str, out float scaler, out int length)
- {
- // SVG path numbers can be tightly packed: "10-20" is two numbers, as is
- // "0.5.6". Stop at the first character that belongs to the next token.
- bool hasDot = false;
- for (int i = 0; i < str.Length; i++)
- {
- char ch = str[i];
-
- if (IsSeparator(ch))
- {
- length = i;
- return TryParseFloat(str[..length], out scaler);
- }
-
- if (ch == '.')
- {
- if (hasDot)
- {
- // Second decimal point starts a new number.
- length = i;
- return TryParseFloat(str[..length], out scaler);
- }
-
- hasDot = true;
- }
- else if ((ch is '-' or '+') && i > 0)
- {
- // A sign character mid-number starts a new number,
- // unless it follows an exponent indicator.
- char prev = str[i - 1];
- if (prev is not 'e' and not 'E')
- {
- length = i;
- return TryParseFloat(str[..length], out scaler);
- }
- }
- else if (char.IsLetter(ch))
- {
- // Hit a command letter; end this number.
- length = i;
- return TryParseFloat(str[..length], out scaler);
- }
- }
-
- length = str.Length;
- return TryParseFloat(str, out scaler);
- }
-
///
/// Returns whether the character is an SVG token separator (whitespace or comma).
///
@@ -752,13 +744,4 @@ private static ReadOnlySpan TrimSeparator(ReadOnlySpan data)
return data[idx..];
}
-
- ///
- /// Parses a culture-invariant float, rejecting non-finite values.
- ///
- /// The character data to parse.
- /// When this method returns, contains the parsed value.
- /// if a finite value was parsed; otherwise, .
- private static bool TryParseFloat(ReadOnlySpan str, out float value)
- => float.TryParse(str, CultureInfo.InvariantCulture, out value) && float.IsFinite(value);
}
diff --git a/src/ImageSharp.Drawing/Processing/Backends/CompositionCommand.cs b/src/ImageSharp.Drawing/Processing/Backends/CompositionCommand.cs
index 616c421ca..c99fc7beb 100644
--- a/src/ImageSharp.Drawing/Processing/Backends/CompositionCommand.cs
+++ b/src/ImageSharp.Drawing/Processing/Backends/CompositionCommand.cs
@@ -96,6 +96,7 @@ private CompositionCommand(
this.TargetBounds = targetBounds;
this.LayerBounds = layerBounds;
this.DestinationOffset = destinationOffset;
+ this.BrushOffset = destinationOffset;
this.clipDescriptor = clipDescriptor;
this.IsInsideLayer = isInsideLayer;
this.applyBarrier = applyBarrier;
@@ -149,6 +150,13 @@ private CompositionCommand(
///
public Point DestinationOffset { get; }
+ ///
+ /// Gets the offset from the coordinates of the canvas to the target, which the batcher bakes into the brush. It is
+ /// except for a glyph, whose destination offset also carries the whole-pixel part of
+ /// the glyph position, while its brush stays in the coordinates of the canvas.
+ ///
+ internal Point BrushOffset { get; init; }
+
///
/// Gets the source path carried by the command.
///
diff --git a/src/ImageSharp.Drawing/Processing/Backends/DEFAULT_DRAWING_BACKEND.md b/src/ImageSharp.Drawing/Processing/Backends/DEFAULT_DRAWING_BACKEND.md
index 6cd202f00..08a0fc904 100644
--- a/src/ImageSharp.Drawing/Processing/Backends/DEFAULT_DRAWING_BACKEND.md
+++ b/src/ImageSharp.Drawing/Processing/Backends/DEFAULT_DRAWING_BACKEND.md
@@ -128,6 +128,8 @@ The important separation is:
- the brush renderer decides color
- the backend executor binds the two together
+Two renderers avoid work that cannot change the result. The solid brush writes one pixel directly into the runs of full coverage when the blender gives that pixel there for every backdrop: an opaque color with normal source-over blending, or any color with normal source composition (the composition of `Clear`), at full opacity, into a pixel format with 8-bit or 16-bit integer channels and straight or no alpha (for 16-bit formats under source composition only an opaque or a transparent color). A transparent color under source composition writes the transparent pixel of zeros, which is what the blender writes, whatever the color channels of the brush. The solid brush blends the other pixels in pieces that start at multiples of the vector width of the blender, so every pixel takes the same blender loop as in one blend of the whole span. The proof rests on the straight-alpha blenders that `PixelBlenders` returns in ImageSharp 5.0.0-alpha.0.38 (the same equations and loop structure as in 4.1.2); a pixel format with associated alpha gets other blenders and is not admitted. For an opaque color under normal source-over blending at full opacity into `Rgba32`, on a processor with fused multiply-add, the solid brush also blends the partly covered pixels itself when every pixel of the piece is opaque or transparent: over an opaque pixel the equations of the blender reduce without rounding to one fused multiply-add per channel, `fma(s - b, c, b)`, and over a transparent pixel to the color with the alpha of the coverage (the pixel of zeros for coverage 0). Each pixel takes only its own lanes, so the loop that it would take in the blender does not matter. A piece with any other alpha goes to the blender unchanged. An exhaustive comparison with the blender (every pair of backdrop and color channel values with every coverage step of the rasterizer, and random rows with any coverage bit pattern) found no differing byte. Gradient renderers compute the positions of a whole span with one call before they interpolate the stops, and for `Rgba32` they pack the interpolated colors of the span with one bulk conversion (`FromAssociatedScaledVector4Destructive` or `FromUnassociatedScaledVector4Destructive`, after the alpha representation of the brush), which gives the bytes of the per-pixel encoder.
+
Renderers are memoized per scene item: `FillSceneItem.GetRenderer(...)` and `StrokeSceneItem.GetRenderer(...)` create the renderer on first use and cache it, and `RenderScene` warms every renderer before the parallel row pass so the hot loop never constructs one.
### Worker State
@@ -139,9 +141,11 @@ It owns worker-local scratch such as:
- raster scratch (`DefaultRasterizer.WorkerScratch`)
- a second scratch reserved for path clip rasterization
- a reusable path clip coverage buffer
+- one `PathClipBand` per clip descriptor index, which holds the rows of the last rasterized band of a path clip
+- one layer band buffer per nesting level of inline layers (`BeginLayerBand`), at least the tile height and at least as wide as the widest layer band of that level so far: the first band of a level sets the width, and a wider band grows the buffer to at least twice its width, capped at the destination width
- the brush workspace
-This is how the backend avoids allocating fresh buffers for every row item during the hot parallel pass. Each `Parallel.For` worker gets one instance through `localInit` and disposes it in `localFinally`.
+This is how the backend avoids allocating fresh buffers for every row item during the hot parallel pass. Each `Parallel.For` worker gets one instance through `localInit` and returns it to a pool in `localFinally`. The loops plan their tasks as `ParallelRowIterator` of ImageSharp does: at most one task per band and per 4,096 pixels (`ParallelExecutionSettings.DefaultMinimumPixelsProcessedPerTask`), and at most the configured degree of parallelism. When that gives one task (one band, at most 4,096 pixels, or a degree of 1), the loop runs on the calling thread with one rented state instead of a `Parallel.For`. This applies to the scene rows of each segment, to the write-back of an apply item, and to the composite of a scoped layer.
## The Big Picture Flow
@@ -270,7 +274,7 @@ sequenceDiagram
Render->>Worker: Dispose (localFinally)
```
-Each row replays its operation stream through a `SceneOperationCursor`. The operations are `FillItem`, `StrokeItem`, `BeginLayer`, and `EndLayer`. Layer execution is recursive rather than stack-backed: `BeginLayer` allocates a clean temporary `BandTarget`, the nested call renders into it from the same cursor, and the band is blended back with the layer's graphics options when the scope ends.
+Each row replays its operation stream through a `SceneOperationCursor`. The operations are `FillItem`, `StrokeItem`, `BeginLayer`, and `EndLayer`. Layer execution is recursive rather than stack-backed: `BeginLayer` takes the layer band buffer of its nesting level from the worker state (`WorkerState.BeginLayerBand`), clears the region of the band, and wraps it in a `BandTarget`; the nested call renders into it from the same cursor, and the band is blended back with the layer's graphics options when the scope ends (`EndLayerBand`). An inline layer covers at most one band and lives only until it is blended back, so one buffer per level serves every inline layer that the worker renders; a nested layer uses the buffer of the next level while its parent stays open. Before phase 6 of the SVG work each inline layer band allocated its own clean `Buffer2D`, whose managed wrapper objects were most of what a render of a document with many layers allocated during the scene render.
There are two important ownership patterns in that pass:
@@ -315,7 +319,11 @@ flowchart LR
E --> F[Pixels updated]
```
-Clip descriptors are applied by kind: rectangle clips narrow the span analytically, integer-region and region clips test rectangle membership, and path clips multiply the span by coverage rasterized from `PreparedPathClipState`, retained clip raster data built once per scene item at scene-creation time. Descriptors are recorded in canvas space and anchored through the item's destination offset so clips track the drawn geometry.
+Clip descriptors are applied by kind: rectangle clips narrow the span analytically (the interior columns, whose coverage on the axis is exactly 1, pass as one run without a test per column), integer-region and region clips test rectangle membership, and path clips multiply the span by coverage rasterized from `PreparedPathClipState`, retained clip raster data built once per scene item at scene-creation time. The rasterizer emits a path clip one band of 16 rows at a time, and a scene item asks for the same clip band for every span of each of its rows, so the worker keeps the emitted rows of the last band per clip index (`PathClipBand`) and rasterizes the band again only for another clip geometry or band; the clip coverage of a span is then a copy of its row. The path clip splits the span into runs of equal clip coverage with a vectorized search. Descriptors are recorded in canvas space and anchored through the item's destination offset so clips track the drawn geometry.
+
+A rectangle clip that cannot change any span of an item band is skipped. When the row handler is created for one band of one item, it intersects the band target with the item's interest (every span it passes on lies in that rectangle) and marks each intersecting rectangle clip, among the first 64 descriptors, whose interior rows and columns contain that rectangle. The interior is the set of pixels whose axis coverage is exactly 1 by the comparisons of the clip itself (`GetInteriorColumns`), so such a clip would pass every span on as one run with the multiplier 1 and the same slices: skipping it gives the next descriptor the same call. The root viewport clip of an SVG document and the viewport clips of `use` instances are the common case.
+
+A retained scene can store the coverage of its small fill items (`FlushScene.StoreSmallFillCoverage`, internal; items whose bands hold at most 128 x 128 pixels). The method runs the scan of every band of such an item once with a handler that records each call (row, start column, coverage values), and a replay then hands the recorded calls, in the same order and with copies of the same values, to the row handler of the band instead of scanning (`ExecuteFillOperation`). The emitted coverage depends only on the retained geometry and the band, so the pixels are those of a replay that scans. Only the scene cache of the SVG code calls it, for scenes that it keeps; a scene from `DrawingCanvas.CreateScene` stores nothing. The stored coverage is managed memory held by the scene (a table by item index, created only when the scene stores coverage), released with it, and its bytes are counted by the caller.
This is why the brush renderer can stay target-unbound. It receives the destination row slice and coverage data at execution time rather than owning the destination frame itself.
@@ -325,17 +333,21 @@ An apply item runs a caller-supplied image processor over a path region as part
`ExecuteApplyItem`:
-1. copies the covered target rectangle into a temporary `Image`
+1. copies the covered target rectangle into a temporary `Image`; the rectangle of the item is absolute (scene creation moves the canvas rectangle by the destination offset of the command, which is not zero on a region canvas), and the copy subtracts the absolute origin of the current target, which is the frame for the root target and the layer bounds for a scoped layer
2. runs the recorded operation through `Mutate`
3. writes the processed pixels back through an `ImageBrush` driven by the apply item's retained coverage, in parallel over the item's row bands
Write-back uses Src semantics: the item's graphics options were cloned via `CloneForClearOperation` (Src alpha composition at full blend), so the processed pixels replace the covered region outright, including transparency, instead of blending over it. Rows preceding the barrier are guaranteed complete because segments execute in order.
+An effect that can run on rows (`LayerEffect.ProcessesRows`, internal; the luminance effects of SVG masks) skips the image and the processor: the backend copies the covered rectangle into a clean pooled `Buffer2D` of the same size, the effect processes it in place (`LayerEffect.ProcessRows`) with the conversions that its operation would make, and the write-back reads the buffer through the image brush renderer with the placement and wrap of the general path (`ImageBrush.CreateRenderer`, internal). The pixels are the same as with the image and the processor.
+
+The image brush renderer, which writes the processed pixels back, has two shortcuts that keep its pixels. A span whose columns all lie inside the source region reads one run of the source row (every wrap mode maps a coordinate inside the region to itself). Under normal source composition at full opacity, into a format with 8-bit channels and straight alpha or no alpha, it copies the source pixel into each pixel of a run of coverage exactly 1 (the pixel of zeros for a transparent source pixel) and blends the rest of the row in pieces that start at multiples of the vector width of the blender: the proof of the clear of the solid brush, applied per pixel.
+
## Layer Composition
CPU layer composition is a separate concern from path rasterization.
-Inline layers composite band-by-band during row execution (`CompositeLayerBand`), and scoped layers composite as a whole after their segments finish (`CompositeLayerTarget`), both using `PixelBlender` with the layer's graphics options. Scoped composition partitions the overlap on the same absolute tile grid used for rendering so the parallel blend never shares a destination row between workers.
+Inline layers composite band-by-band during row execution (`CompositeLayerBand`), and scoped layers composite as a whole after their segments finish (`CompositeLayerTarget`), both using `PixelBlender` with the layer's graphics options. A layer blends with one amount, its blend percentage, so the composite calls the overload of `Blend` with a constant amount and caller scratch. It gives the same bytes as a row of equal amounts: both overloads run the same vector loops over the same groups of pixels and the same scalar tail, and pass the operator the amount clamped to [0, 1] in every lane; `GraphicsOptions.BlendPercentage` is validated to lie in [0, 1], where the clamp keeps the value to the bit. Scoped composition partitions the overlap on the same absolute tile grid used for rendering so the parallel blend never shares a destination row between workers.
`ComposeLayer()` additionally exposes frame-to-frame composition using `PixelBlender` for callers outside scene execution. That path exists because compositing an already-rasterized layer is a different problem from scanning geometry into coverage.
@@ -353,6 +365,7 @@ Owned by `FlushScene` (and therefore by the retained `DefaultDrawingBackendScene
- retained raster geometry and start-cover storage
- retained path clip raster data
- row and segment structures
+- the stored coverage of small fill items, when the scene stores it (managed memory, released with the scene)
Disposed when the scene is disposed; short-lived scenes are disposed after one replay entry.
@@ -361,17 +374,18 @@ Disposed when the scene is disposed; short-lived scenes are disposed after one r
Owned by `WorkerState` during execution:
- raster scratch and path-clip scratch
-- path-clip coverage buffer
+- path-clip coverage buffer and the path clip bands
+- the layer band buffers of inline layers, one per nesting level
- brush workspace
-Disposed when the worker completes (`localFinally`).
+Returned to the worker pool when the worker completes (`localFinally`); the path clip bands forget their geometry then, so a pooled state keeps no reference to a finished scene. The pool releases its states on a generation 2 collection when nothing rented one since the previous collection.
### Execution-scoped
Created during execution and released with it:
-- temporary layer `BandTarget` buffers
-- the temporary apply source image
+- the buffers of scoped layers (`ExecuteSceneSegments`), one per layer, from the memory allocator of the configuration
+- the temporary apply source image, or the pooled snapshot buffer of an effect that runs on rows
That ownership model keeps allocation and disposal aligned with real work lifetime.
diff --git a/src/ImageSharp.Drawing/Processing/Backends/DEFAULT_RASTERIZER.md b/src/ImageSharp.Drawing/Processing/Backends/DEFAULT_RASTERIZER.md
index af84f0df6..29b73c512 100644
--- a/src/ImageSharp.Drawing/Processing/Backends/DEFAULT_RASTERIZER.md
+++ b/src/ImageSharp.Drawing/Processing/Backends/DEFAULT_RASTERIZER.md
@@ -180,6 +180,8 @@ The output is `RasterizableGeometry`. The stroke builders (`CreatePathStrokeRast
It does not revisit the original contour data. It receives a `RasterizableItem` over retained data plus the band's `RasterizableBandInfo` and performs the minimum work needed to emit coverage rows for that band.
+Its output depends only on the retained geometry and the band. A retained scene that the SVG scene cache keeps runs it once per band of each small fill item with a recording handler and later hands the recorded calls to the row handler instead (`FlushScene.StoreSmallFillCoverage`, see `DEFAULT_DRAWING_BACKEND.md`).
+
```mermaid
sequenceDiagram
participant Exec as ExecuteRasterizableItem
@@ -251,7 +253,7 @@ That includes:
- retained line block chains for each band
- optional start-cover arrays for bands that need carry-in winding
-The retained line data uses specialized storage formats: `LineArrayX16Y16` and `LineArrayX32Y16` collect lines during building, and their retained block chains (`LineArrayX16Y16Block`, `LineArrayX32Y16Block`) are what execution iterates. Narrow geometries (band width below 128 pixels) pack both X endpoints into one 32-bit word, halving retained line memory.
+The retained line data uses specialized storage formats: the linearizer appends each line straight into the block chain of its band (`LineArrayX16Y16Block`, `LineArrayX32Y16Block`, through the static `LineArrayX16Y16.AppendLine` and `LineArrayX32Y16.AppendLine`), keeping the front block and its line count of every band in the two arrays that the retained geometry takes over, so building needs no collector object per band. Those chains are what execution iterates. Narrow geometries (band width below 128 pixels) pack both X endpoints into one 32-bit word, halving retained line memory.
These are storage-oriented types. They exist to retain compact fixed-point line segments so execution does not need to revisit contour data.
@@ -262,7 +264,7 @@ The linearizer is the retained-geometry builder. `Linearizer` is generic ove
Its responsibilities are:
- traverse prepared contours
-- apply the residual transform per-point as contours are read
+- apply the residual transform per-point as contours are read, once per point (the end of one segment is the start of the next), with one addition per axis when the residual only translates
- clip work to retained bounds
- convert coordinates into fixed-point
- decide whether a segment is contained or must be split
diff --git a/src/ImageSharp.Drawing/Processing/Backends/DefaultDrawingBackend.Helpers.cs b/src/ImageSharp.Drawing/Processing/Backends/DefaultDrawingBackend.Helpers.cs
index ab5c4bb59..5279dd7b9 100644
--- a/src/ImageSharp.Drawing/Processing/Backends/DefaultDrawingBackend.Helpers.cs
+++ b/src/ImageSharp.Drawing/Processing/Backends/DefaultDrawingBackend.Helpers.cs
@@ -29,6 +29,9 @@ public sealed partial class DefaultDrawingBackend
private readonly WorkerState workerState;
private readonly Rectangle interest;
+ // Bit i is set when clip descriptor i passes every span of this handler unchanged; see GetSkippedClips.
+ private readonly ulong skippedClips;
+
///
/// Initializes a new instance of the struct.
///
@@ -61,6 +64,64 @@ public FillCoverageRowHandler(
this.destinationOffset = destinationOffset;
this.brushWorkspace = brushWorkspace;
this.workerState = workerState;
+ this.skippedClips = clipState.Count == 0 ? 0 : GetSkippedClips(clipState, destinationOffset, target, interest);
+ }
+
+ ///
+ /// Finds the rectangle clips that cannot change a span of a handler.
+ ///
+ ///
+ ///
+ /// passes on only spans inside the band target and the interest, so every span lies in the
+ /// rectangle of their intersection. An intersecting rectangle clip whose interior rows and interior columns
+ /// (: the pixels whose axis coverage is exactly 1 by the comparisons of
+ /// ) contain that rectangle passes every such span on unchanged: the row coverage is
+ /// 1, the span starts and ends inside the interior, so forms one run of the
+ /// whole span with the multiplier 1 * 1 = 1, and hands the same span, unscaled, to
+ /// the next descriptor. Skipping the descriptor gives the next descriptor the same call.
+ ///
+ ///
+ /// The root viewport clip of an SVG document and the viewport clips of its use instances usually contain
+ /// the items they clip; without the skip every span pays for the rectangle tests.
+ ///
+ ///
+ /// The clip state of the item.
+ /// The destination offset used to place clip descriptors.
+ /// The band target.
+ /// The absolute bounds that the item can write.
+ /// A mask with bit i set when descriptor i can be skipped; descriptors from index 64 on are never skipped.
+ private static ulong GetSkippedClips(DrawingClipState clipState, Point destinationOffset, BandTarget target, Rectangle interest)
+ {
+ int left = Math.Max(target.AbsoluteLeft, interest.Left);
+ int right = Math.Min(target.AbsoluteLeft + target.Region.Width, interest.Right);
+ int top = Math.Max(target.AbsoluteTop, interest.Top);
+ int bottom = Math.Min(target.AbsoluteTop + target.Region.Height, interest.Bottom);
+ if (right <= left || bottom <= top)
+ {
+ return 0;
+ }
+
+ ulong skipped = 0;
+ int count = Math.Min(clipState.Count, 64);
+ for (int i = 0; i < count; i++)
+ {
+ DrawingClipDescriptor descriptor = clipState.GetDescriptor(i);
+ if (descriptor.Kind != DrawingClipKind.Rectangle || descriptor.Operation == ClipOperation.Difference)
+ {
+ continue;
+ }
+
+ RectangleF rectangle = descriptor.Rectangle;
+ rectangle.Offset(destinationOffset.X, destinationOffset.Y);
+ GetInteriorColumns(rectangle.Left, rectangle.Right, descriptor.EdgeMode, out int columnStart, out int columnEnd);
+ GetInteriorColumns(rectangle.Top, rectangle.Bottom, descriptor.EdgeMode, out int rowStart, out int rowEnd);
+ if (left >= columnStart && right <= columnEnd && top >= rowStart && bottom <= rowEnd)
+ {
+ skipped |= 1UL << i;
+ }
+ }
+
+ return skipped;
}
///
@@ -116,6 +177,12 @@ private void ApplyClipDescriptors(
return;
}
+ // A skipped descriptor would pass the span on unchanged (GetSkippedClips).
+ while (clipIndex < 64 && ((this.skippedClips >> clipIndex) & 1UL) != 0)
+ {
+ clipIndex++;
+ }
+
if (clipIndex == this.clipState.Count)
{
// Clip descriptors are applied recursively by narrowing or scaling the active span.
@@ -278,6 +345,8 @@ private void ApplyRectangleInterior(
Span destination,
Span coverage)
{
+ GetInteriorColumns(rectangle.Left, rectangle.Right, descriptor.EdgeMode, out int interiorStart, out int interiorEnd);
+
int x = clipStart;
while (x < clipEnd)
{
@@ -287,10 +356,7 @@ private void ApplyRectangleInterior(
// Rectangle edge coverage is constant across interior pixels and only changes
// at the left/right edge pixels, so collapse adjacent equal-coverage columns.
- while (x < clipEnd && GetAxisCoverage(x, rectangle.Left, rectangle.Right, descriptor.EdgeMode) == xCoverage)
- {
- x++;
- }
+ x = ExtendAxisRun(x, clipEnd, xCoverage, interiorStart, interiorEnd, rectangle.Left, rectangle.Right, descriptor.EdgeMode);
this.ApplyCoverageRun(clipIndex + 1, y, runStart, x, spanStart, multiplier, destination, coverage);
}
@@ -321,6 +387,8 @@ private void ApplyRectangleDifferenceInterior(
Span destination,
Span coverage)
{
+ GetInteriorColumns(rectangle.Left, rectangle.Right, descriptor.EdgeMode, out int interiorStart, out int interiorEnd);
+
int x = clipStart;
while (x < clipEnd)
{
@@ -330,10 +398,7 @@ private void ApplyRectangleDifferenceInterior(
// Subtraction uses the inverse coverage of the rectangle, but the same run
// coalescing applies: edge pixels differ, interior pixels share one value.
- while (x < clipEnd && GetAxisCoverage(x, rectangle.Left, rectangle.Right, descriptor.EdgeMode) == xCoverage)
- {
- x++;
- }
+ x = ExtendAxisRun(x, clipEnd, xCoverage, interiorStart, interiorEnd, rectangle.Left, rectangle.Right, descriptor.EdgeMode);
this.ApplyCoverageRun(clipIndex + 1, y, runStart, x, spanStart, multiplier, destination, coverage);
}
@@ -542,55 +607,58 @@ private void ApplyPathClip(
return;
}
+ // Path clips use the same retained rasterizer as fills. The rasterizer emits a whole band
+ // of rows at once, and one subject item asks for the same clip band once for every span of
+ // every row of the band, so the worker keeps the emitted band per clip index and rasterizes
+ // it again only for another clip geometry or band.
+ PathClipBand band = this.workerState.GetPathClipBand(clipIndex);
+ if (!band.Holds(rasterizable, localRowIndex))
+ {
+ DefaultRasterizer.RasterizableItem item = new(rasterizable, localRowIndex);
+ DefaultRasterizer.RasterizableBandInfo bandInfo = rasterizable.GetBandInfo(localRowIndex);
+ DefaultRasterizer.WorkerScratch scratch = this.workerState.GetOrCreatePathClipScratch(rasterizable.Width);
+ DefaultRasterizer.Context context = scratch.CreateContext(
+ bandInfo.IntersectionRule,
+ bandInfo.RasterizationMode,
+ bandInfo.LineCount);
+
+ band.Begin(rasterizable, localRowIndex, bandInfo.DestinationLeft, bandInfo.DestinationTop, bandInfo.Width, bandInfo.BandHeight);
+ PathClipBandRowHandler rowHandler = new(band);
+ DefaultRasterizer.ExecuteRasterizableItem(
+ ref context,
+ in item,
+ in bandInfo,
+ scratch.Scanline,
+ ref rowHandler);
+ }
+
+ // The clip row is materialized into worker-local coverage only for the subject span
+ // currently being painted, so rectangle and region clips stay on their cheaper
+ // span-slicing paths.
Span clipCoverage = this.workerState.GetOrCreatePathClipCoverage(coverage.Length);
clipCoverage = clipCoverage[..coverage.Length];
clipCoverage.Fill(descriptor.Operation == ClipOperation.Difference ? 1F : 0F);
-
- DefaultRasterizer.RasterizableItem item = new(rasterizable, localRowIndex);
- DefaultRasterizer.RasterizableBandInfo bandInfo = rasterizable.GetBandInfo(localRowIndex);
- DefaultRasterizer.WorkerScratch scratch = this.workerState.GetOrCreatePathClipScratch(rasterizable.Width);
- DefaultRasterizer.Context context = scratch.CreateContext(
- bandInfo.IntersectionRule,
- bandInfo.RasterizationMode,
- bandInfo.LineCount);
-
- PathClipCoverageRowHandler rowHandler = new(
- this.workerState,
- descriptor.Operation,
- y,
- startX,
- coverage.Length);
-
- // Path clips use the same retained rasterizer as fills. The clip row is materialized
- // into worker-local coverage only for the subject span currently being painted, so
- // rectangle and region clips stay on their cheaper span-slicing paths.
- DefaultRasterizer.ExecuteRasterizableItem(
- ref context,
- in item,
- in bandInfo,
- scratch.Scanline,
- ref rowHandler);
-
- int spanEnd = startX + coverage.Length;
- int runStart = startX;
- float runCoverage = clipCoverage[0];
- for (int x = startX + 1; x < spanEnd; x++)
+ band.CopyRow(y, startX, clipCoverage, descriptor.Operation);
+
+ // Coalesce equal clip coverage into runs so deeper clips and brush rendering are invoked
+ // per coverage run instead of once per pixel. The run ends are found with the vectorized
+ // integer search of the runtime on the bit patterns. Bit equality is float equality here:
+ // the values are the fill values +0 and 1, coverage that the rasterizer emitted (positive),
+ // zeros of unwritten band columns (+0), and 1 - c for c in 0 to 1 (never -0), so no value
+ // is -0 or NaN, the two cases where the comparisons differ.
+ // A deeper path clip reuses the same worker buffer, but it writes only the first
+ // (runEnd - runStart) entries, which lie before every entry this loop reads afterwards.
+ ReadOnlySpan clipBits = MemoryMarshal.Cast(clipCoverage);
+ int length = clipBits.Length;
+ int runStart = 0;
+ while (runStart < length)
{
- float pixelCoverage = clipCoverage[x - startX];
- if (pixelCoverage == runCoverage)
- {
- continue;
- }
-
- // Coalesce equal clip coverage into runs so deeper clips and brush rendering
- // are invoked per coverage run instead of once per pixel.
- this.ApplyCoverageRun(clipIndex + 1, y, runStart, x, startX, runCoverage, destination, coverage);
-
- runStart = x;
- runCoverage = pixelCoverage;
+ float runCoverage = clipCoverage[runStart];
+ int runLength = clipBits[(runStart + 1)..].IndexOfAnyExcept(clipBits[runStart]);
+ int runEnd = runLength < 0 ? length : runStart + 1 + runLength;
+ this.ApplyCoverageRun(clipIndex + 1, y, startX + runStart, startX + runEnd, startX, runCoverage, destination, coverage);
+ runStart = runEnd;
}
-
- this.ApplyCoverageRun(clipIndex + 1, y, runStart, spanEnd, startX, runCoverage, destination, coverage);
}
///
@@ -730,104 +798,136 @@ private static float GetAxisCoverage(
float coverage = MathF.Min(pixel + 1F, clipEnd) - MathF.Max(pixel, clipStart);
return Math.Clamp(coverage, 0F, 1F);
}
- }
-
- ///
- /// Writes retained path clip coverage into a worker-local span for one subject row.
- ///
- /// The pixel format.
- private readonly struct PathClipCoverageRowHandler : IRasterizerCoverageRowHandler
- where TPixel : unmanaged, IPixel
- {
- private readonly WorkerState workerState;
- private readonly ClipOperation operation;
- private readonly int targetY;
- private readonly int targetStartX;
- private readonly int targetLength;
///
- /// Initializes a new instance of the struct.
+ /// Advances past the columns that continue a run of equal axis coverage, as a column-by-column
+ /// comparison with would, but skips the interior columns in one step.
///
- /// The worker-local execution state that owns the clip coverage span.
- /// The clip operation represented by the path descriptor.
- /// The subject row being clipped.
- /// The subject span start.
- /// The subject span length.
- public PathClipCoverageRowHandler(
- WorkerState workerState,
- ClipOperation operation,
- int targetY,
- int targetStartX,
- int targetLength)
+ /// The first column after the start of the run.
+ /// The exclusive column where the walk ends.
+ /// The axis coverage of the first column of the run.
+ /// The first interior column from .
+ /// The exclusive last interior column from .
+ /// The clip interval start.
+ /// The clip interval end.
+ /// The edge mode.
+ /// The exclusive end column of the run.
+ private static int ExtendAxisRun(
+ int x,
+ int clipEnd,
+ float runCoverage,
+ int interiorStart,
+ int interiorEnd,
+ float clipStart,
+ float clipIntervalEnd,
+ DrawingClipEdgeMode edgeMode)
{
- this.workerState = workerState;
- this.operation = operation;
- this.targetY = targetY;
- this.targetStartX = targetStartX;
- this.targetLength = targetLength;
+ while (x < clipEnd)
+ {
+ if (x >= interiorStart && x < interiorEnd)
+ {
+ // Every interior column has coverage 1, so the run either ends here or
+ // continues through the whole interior.
+ if (runCoverage != 1F)
+ {
+ break;
+ }
+
+ x = Math.Min(interiorEnd, clipEnd);
+ continue;
+ }
+
+ if (GetAxisCoverage(x, clipStart, clipIntervalEnd, edgeMode) != runCoverage)
+ {
+ break;
+ }
+
+ x++;
+ }
+
+ return x;
}
///
- /// Records clip coverage emitted by the rasterizer for the target subject row.
+ /// Finds the interval of columns for which returns exactly 1 by
+ /// its comparisons alone, so the column walk can skip them.
///
- /// The absolute row emitted by the clip rasterizer.
- /// The absolute start column emitted by the clip rasterizer.
- /// The emitted clip coverage values.
- public void Handle(int y, int startX, Span coverage)
+ /// The clip interval start.
+ /// The clip interval end.
+ /// The edge mode.
+ /// The first interior column.
+ /// The exclusive last interior column; equal to the start when there is none.
+ private static void GetInteriorColumns(
+ float clipStart,
+ float clipEnd,
+ DrawingClipEdgeMode edgeMode,
+ out int interiorStart,
+ out int interiorEnd)
{
- if (y != this.targetY)
- {
- return;
- }
-
- int targetEndX = this.targetStartX + this.targetLength;
- int overlapStart = Math.Max(startX, this.targetStartX);
- int overlapEnd = Math.Min(startX + coverage.Length, targetEndX);
- if (overlapEnd <= overlapStart)
+ // Below 2^22 in magnitude every integer column x, x + 1, and x + 0.5 is exact in single
+ // precision, so the comparisons below are the comparisons of GetAxisCoverage. NaN and
+ // larger bounds fail these tests and keep the column walk.
+ const float limit = 1 << 22;
+ if (!(clipStart > -limit && clipEnd < limit && clipStart < clipEnd))
{
+ interiorStart = 0;
+ interiorEnd = 0;
return;
}
- Span clipCoverage = this.workerState.PathClipCoverage;
- int sourceOffset = overlapStart - startX;
- int targetOffset = overlapStart - this.targetStartX;
- int length = overlapEnd - overlapStart;
- Span source = coverage.Slice(sourceOffset, length);
- Span target = clipCoverage.Slice(targetOffset, length);
-
- if (this.operation == ClipOperation.Difference)
+ if (edgeMode == DrawingClipEdgeMode.Hard)
{
- int i = 0;
- if (Vector.IsHardwareAccelerated)
+ // Centre sampling returns 1 exactly when x + 0.5 >= clipStart and x + 0.5 <= clipEnd.
+ // Both tests are monotonic in x, so the columns that pass form one interval; its ends
+ // are within one column of the floors and are found with the same float tests.
+ int first = (int)MathF.Floor(clipStart) - 1;
+ while (!(first + 0.5F >= clipStart))
{
- int vectorCount = Vector.Count;
- int vectorLength = length - (length % vectorCount);
- Vector one = Vector.One;
- ReadOnlySpan> sourceVectors = MemoryMarshal.Cast>(source[..vectorLength]);
- Span> targetVectors = MemoryMarshal.Cast>(target[..vectorLength]);
-
- // Difference clips invert the clip coverage into the reusable target span.
- // Casting the vector-width prefix avoids per-lane loads and stores when SIMD is available.
- for (int j = 0; j < sourceVectors.Length; j++)
- {
- targetVectors[j] = one - sourceVectors[j];
- }
-
- i = vectorLength;
+ first++;
}
- for (; i < length; i++)
+ int last = (int)MathF.Floor(clipEnd) + 1;
+ while (!(last + 0.5F <= clipEnd))
{
- target[i] = 1F - source[i];
+ last--;
}
+ interiorStart = first;
+ interiorEnd = Math.Max(first, last + 1);
return;
}
- source.CopyTo(target);
+ // Area coverage is Min(x + 1, end) - Max(x, start). When x >= start and x + 1 <= end the two
+ // operands are x + 1 and x, both exact, so the difference is exactly 1. For integer x these
+ // tests hold from Ceiling(start) to Floor(end) - 1. Columns outside can still reach 1 through
+ // rounding; the walk compares those one by one.
+ interiorStart = (int)MathF.Ceiling(clipStart);
+ interiorEnd = Math.Max(interiorStart, (int)MathF.Floor(clipEnd));
}
}
+ ///
+ /// Writes the rows that the rasterizer emits for one band of a path clip into a .
+ ///
+ private readonly struct PathClipBandRowHandler : IRasterizerCoverageRowHandler
+ {
+ private readonly PathClipBand band;
+
+ ///
+ /// Initializes a new instance of the struct.
+ ///
+ /// The band that receives the emitted rows; ran on it.
+ public PathClipBandRowHandler(PathClipBand band) => this.band = band;
+
+ ///
+ /// Records one emitted span of clip coverage.
+ ///
+ /// The absolute row emitted by the clip rasterizer.
+ /// The absolute start column emitted by the clip rasterizer.
+ /// The emitted clip coverage values.
+ public void Handle(int y, int startX, Span coverage) => this.band.Write(y, startX, coverage);
+ }
+
///
/// Walks retained row-operation blocks without flattening them into another list.
///
@@ -941,6 +1041,215 @@ public BandTarget(Buffer2D owner, Rectangle bounds, GraphicsOptions? gra
public void Dispose() => this.owner?.Dispose();
}
+ ///
+ /// Holds the coverage that the rasterizer emitted for one band of one path clip geometry, so that every subject
+ /// span of the band reads its clip row without rasterizing the band again.
+ ///
+ ///
+ ///
+ /// A row stores the emitted values in a dense array over the columns of the band. Each row keeps the interval of
+ /// columns written since ; a column inside that interval that no span wrote holds 0, and a column
+ /// outside it counts as 0. This gives the same clip coverage as a direct copy of the emitted spans into a span that
+ /// holds the empty value of the clip: an intersecting clip fills with 0 and copies the values, a subtracting clip
+ /// fills with 1 and writes 1 - value, and 1 - 0 is exactly 1.
+ ///
+ ///
+ /// The band is keyed by the identity of the retained geometry and the band index. Retained geometry does not change
+ /// while its scene exists, so a key that matches holds the rows that the rasterizer would emit again.
+ ///
+ ///
+ private sealed class PathClipBand : IDisposable
+ {
+ private readonly MemoryAllocator allocator;
+ private IMemoryOwner? rowsOwner;
+ private int[] rowStarts = [];
+ private int[] rowEnds = [];
+ private DefaultRasterizer.RasterizableGeometry? geometry;
+ private int localRowIndex;
+ private int left;
+ private int top;
+ private int width;
+ private int height;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The allocator of the row storage.
+ public PathClipBand(MemoryAllocator allocator) => this.allocator = allocator;
+
+ ///
+ /// Gets a value indicating whether the band holds the rows of a clip geometry band.
+ ///
+ /// The clip geometry.
+ /// The band index local to the geometry.
+ /// when the rows were emitted for this geometry and band.
+ public bool Holds(DefaultRasterizer.RasterizableGeometry rasterizable, int rowIndex)
+ => ReferenceEquals(this.geometry, rasterizable) && this.localRowIndex == rowIndex;
+
+ ///
+ /// Empties the band and keys it to a clip geometry band before the rasterizer emits its rows.
+ ///
+ /// The clip geometry.
+ /// The band index local to the geometry.
+ /// The absolute column of the first column of the band.
+ /// The absolute row of the first row of the band.
+ /// The number of columns of the band.
+ /// The number of rows of the band.
+ public void Begin(
+ DefaultRasterizer.RasterizableGeometry rasterizable,
+ int rowIndex,
+ int destinationLeft,
+ int destinationTop,
+ int bandWidth,
+ int bandHeight)
+ {
+ int length = bandWidth * bandHeight;
+ if (this.rowsOwner is null || this.rowsOwner.Memory.Length < length)
+ {
+ // Null before allocating, as in WorkerState.GetOrCreateScratch.
+ this.geometry = null;
+ this.rowsOwner?.Dispose();
+ this.rowsOwner = null;
+ this.rowsOwner = this.allocator.Allocate(length);
+ }
+
+ if (this.rowStarts.Length < bandHeight)
+ {
+ this.rowStarts = new int[bandHeight];
+ this.rowEnds = new int[bandHeight];
+ }
+
+ this.rowStarts.AsSpan(0, bandHeight).Clear();
+ this.rowEnds.AsSpan(0, bandHeight).Clear();
+ this.geometry = rasterizable;
+ this.localRowIndex = rowIndex;
+ this.left = destinationLeft;
+ this.top = destinationTop;
+ this.width = bandWidth;
+ this.height = bandHeight;
+ }
+
+ ///
+ /// Stores one emitted span. The rasterizer emits only columns inside the band.
+ ///
+ /// The absolute row.
+ /// The absolute start column.
+ /// The emitted coverage values.
+ public void Write(int y, int startX, ReadOnlySpan coverage)
+ {
+ int row = y - this.top;
+ if ((uint)row >= (uint)this.height || coverage.Length == 0)
+ {
+ return;
+ }
+
+ int start = startX - this.left;
+ int end = start + coverage.Length;
+ Span values = this.rowsOwner!.Memory.Span.Slice(row * this.width, this.width);
+ int rowStart = this.rowStarts[row];
+ int rowEnd = this.rowEnds[row];
+ if (rowStart == rowEnd)
+ {
+ rowStart = start;
+ rowEnd = end;
+ }
+ else
+ {
+ // Columns between the written interval and the new span were not emitted: they hold 0.
+ if (start > rowEnd)
+ {
+ values[rowEnd..start].Clear();
+ }
+
+ if (end < rowStart)
+ {
+ values[end..rowStart].Clear();
+ }
+
+ rowStart = Math.Min(rowStart, start);
+ rowEnd = Math.Max(rowEnd, end);
+ }
+
+ coverage.CopyTo(values[start..end]);
+ this.rowStarts[row] = rowStart;
+ this.rowEnds[row] = rowEnd;
+ }
+
+ ///
+ /// Writes the clip coverage of one subject span into a span that holds the empty value of the clip:
+ /// the stored values for an intersecting clip, and one minus them for a subtracting clip.
+ ///
+ /// The absolute subject row.
+ /// The absolute start column of the subject span.
+ /// The clip coverage of the subject span, filled with 0 or 1 by the caller.
+ /// The clip operation.
+ public void CopyRow(int y, int targetStartX, Span target, ClipOperation operation)
+ {
+ int row = y - this.top;
+ if ((uint)row >= (uint)this.height)
+ {
+ return;
+ }
+
+ int overlapStart = Math.Max(this.left + this.rowStarts[row], targetStartX);
+ int overlapEnd = Math.Min(this.left + this.rowEnds[row], targetStartX + target.Length);
+ if (overlapEnd <= overlapStart)
+ {
+ return;
+ }
+
+ int length = overlapEnd - overlapStart;
+ ReadOnlySpan source = this.rowsOwner!.Memory.Span.Slice((row * this.width) + (overlapStart - this.left), length);
+ Span destination = target.Slice(overlapStart - targetStartX, length);
+
+ if (operation == ClipOperation.Difference)
+ {
+ int i = 0;
+ if (Vector.IsHardwareAccelerated)
+ {
+ int vectorCount = Vector.Count;
+ int vectorLength = length - (length % vectorCount);
+ Vector one = Vector.One;
+ ReadOnlySpan> sourceVectors = MemoryMarshal.Cast>(source[..vectorLength]);
+ Span> destinationVectors = MemoryMarshal.Cast>(destination[..vectorLength]);
+
+ // Difference clips invert the clip coverage into the reusable target span.
+ // Casting the vector-width prefix avoids per-lane loads and stores when SIMD is available.
+ for (int j = 0; j < sourceVectors.Length; j++)
+ {
+ destinationVectors[j] = one - sourceVectors[j];
+ }
+
+ i = vectorLength;
+ }
+
+ for (; i < length; i++)
+ {
+ destination[i] = 1F - source[i];
+ }
+
+ return;
+ }
+
+ source.CopyTo(destination);
+ }
+
+ ///
+ /// Forgets the key, so that a pooled worker state keeps no reference to the geometry of a finished scene.
+ ///
+ public void Reset() => this.geometry = null;
+
+ ///
+ /// Releases the row storage.
+ ///
+ public void Dispose()
+ {
+ this.geometry = null;
+ this.rowsOwner?.Dispose();
+ this.rowsOwner = null;
+ }
+ }
+
///
/// Holds the reusable worker-local scratch used while executing retained scene rows.
///
@@ -970,6 +1279,9 @@ private sealed class WorkerState : IDisposable
private DefaultRasterizer.WorkerScratch? pathClipScratch;
private IMemoryOwner? pathClipCoverageOwner;
private int pathClipCoverageLength;
+ private PathClipBand?[] pathClipBands = [];
+ private Buffer2D?[] layerBands = [];
+ private int layerBandDepth;
///
/// Initializes static members of the class,
@@ -1056,6 +1368,14 @@ public static WorkerState Rent(MemoryAllocator allocator, int destinatio
/// The state to recycle.
public static void Return(WorkerState state)
{
+ foreach (PathClipBand? band in state.pathClipBands)
+ {
+ band?.Reset();
+ }
+
+ // A row that threw inside a layer did not close it; the next renter starts with no open layer.
+ state.layerBandDepth = 0;
+
lock (PoolSync)
{
if (Pool.Count < MaxPooledStates)
@@ -1159,18 +1479,106 @@ public Span GetOrCreatePathClipCoverage(int requiredLength)
return this.PathClipCoverage;
}
+ ///
+ /// Returns the worker-local band of path clip coverage for one clip descriptor index. Nested path clips have
+ /// different indices, so each keeps its own band while the outer clip walks its row.
+ ///
+ /// The clip descriptor index.
+ /// The band for the index.
+ public PathClipBand GetPathClipBand(int clipIndex)
+ {
+ if (clipIndex >= this.pathClipBands.Length)
+ {
+ Array.Resize(ref this.pathClipBands, clipIndex + 1);
+ }
+
+ return this.pathClipBands[clipIndex] ??= new PathClipBand(this.allocator);
+ }
+
+ ///
+ /// Returns a transparent region for the layer that begins in the current band, one nesting level below the
+ /// layer that is open now, if any. Pair every call with .
+ ///
+ ///
+ ///
+ /// A layer of a scene row covers at most one band of the tile grid, and it lives only until it is composited
+ /// back into its parent at the end of the band. So every nesting level keeps one buffer of its own for the
+ /// worker: a nested layer renders while its parent stays open, and the layers of the following bands reuse the
+ /// buffer of their level. This replaces one allocation of a temporary buffer per layer band, whose managed
+ /// wrapper objects were most of what a render of a document with many layers allocated.
+ ///
+ ///
+ /// The region is cleared before it is handed out, as the temporary buffer was allocated clean. The pixels of a
+ /// layer depend only on that clear start and on what is drawn into it, so a reused buffer gives the same layer.
+ ///
+ ///
+ /// The width of the layer band.
+ /// The height of the layer band, at most the tile height.
+ /// The cleared region, valid until the matching .
+ public Buffer2DRegion BeginLayerBand(int width, int height)
+ {
+ int depth = this.layerBandDepth;
+ if (depth == this.layerBands.Length)
+ {
+ Array.Resize(ref this.layerBands, depth + 1);
+ }
+
+ Buffer2D? buffer = this.layerBands[depth];
+ if (buffer is null || buffer.Width < width || buffer.Height < height)
+ {
+ // Null before allocating; see GetOrCreateScratch. The first buffer of a level takes the width of its
+ // band, not the width of the target: deeply nested small layers on a wide target would otherwise hold one
+ // target-wide band per level. A wider band later grows the buffer to at least twice its width, capped at
+ // the destination width, so bands of increasing width reallocate a logarithmic number of times. It keeps
+ // the tile height, so it grows only in width.
+ int bufferWidth = Math.Max(width, Math.Min(2 * (buffer?.Width ?? 0), this.DestinationWidth));
+ int bufferHeight = Math.Max(height, DefaultRasterizer.DefaultTileHeight);
+ buffer?.Dispose();
+ this.layerBands[depth] = null;
+ buffer = this.allocator.Allocate2D(bufferWidth, bufferHeight);
+ this.layerBands[depth] = buffer;
+ }
+
+ Buffer2DRegion region = buffer.GetRegion(0, 0, width, height);
+ for (int y = 0; y < height; y++)
+ {
+ region.DangerousGetRowSpan(y).Clear();
+ }
+
+ this.layerBandDepth = depth + 1;
+ return region;
+ }
+
+ ///
+ /// Closes the layer band that the last opened, after it was composited.
+ ///
+ public void EndLayerBand() => this.layerBandDepth--;
+
///
/// Releases the worker-local scratch and brush workspace. The scratch fields are nulled
/// so a disposed state can never hand out spans over returned pool memory.
///
public void Dispose()
{
+ foreach (Buffer2D? buffer in this.layerBands)
+ {
+ buffer?.Dispose();
+ }
+
+ this.layerBands = [];
+ this.layerBandDepth = 0;
this.scratch?.Dispose();
this.scratch = null;
this.pathClipScratch?.Dispose();
this.pathClipScratch = null;
this.pathClipCoverageOwner?.Dispose();
this.pathClipCoverageOwner = null;
+ foreach (PathClipBand? band in this.pathClipBands)
+ {
+ band?.Dispose();
+ }
+
+ this.pathClipBands = [];
this.BrushWorkspace.Dispose();
}
diff --git a/src/ImageSharp.Drawing/Processing/Backends/DefaultDrawingBackend.cs b/src/ImageSharp.Drawing/Processing/Backends/DefaultDrawingBackend.cs
index 2b9f32424..b3c428456 100644
--- a/src/ImageSharp.Drawing/Processing/Backends/DefaultDrawingBackend.cs
+++ b/src/ImageSharp.Drawing/Processing/Backends/DefaultDrawingBackend.cs
@@ -231,12 +231,38 @@ private static void ExecuteSceneRows(
{
int requestedParallelism = configuration.MaxDegreeOfParallelism;
+ // A scene with layers or apply barriers runs one row loop per segment, and many segments
+ // hold a few small bands. Below the minimum of pixels per task that ImageSharp uses for
+ // its row loops, the bands run on the current thread, which saves waking the workers.
+ int partitionCount = ParallelExecutionHelper.GetPartitionCountForPixels(
+ requestedParallelism,
+ rows.Length,
+ (long)rows.Length * DefaultRasterizer.DefaultTileHeight * target.Region.Width);
+
+ if (partitionCount == 1)
+ {
+ WorkerState state = WorkerState.Rent(configuration.MemoryAllocator, target.Region.Width);
+ try
+ {
+ for (int rowIndex = 0; rowIndex < rows.Length; rowIndex++)
+ {
+ ExecuteSceneRow(configuration, canvasWidth, scene, rows[rowIndex], target, state);
+ }
+ }
+ finally
+ {
+ WorkerState.Return(state);
+ }
+
+ return;
+ }
+
// Each SceneRow owns one disjoint horizontal band of the target, so rows can execute in
// parallel with no synchronization: no two workers ever write the same destination pixel.
_ = Parallel.For(
fromInclusive: 0,
toExclusive: rows.Length,
- parallelOptions: ParallelExecutionHelper.CreateParallelOptions(requestedParallelism, rows.Length),
+ parallelOptions: ParallelExecutionHelper.CreateParallelOptions(requestedParallelism, partitionCount),
localInit: () => WorkerState.Rent(configuration.MemoryAllocator, target.Region.Width),
body: (rowIndex, _, state) =>
{
@@ -333,23 +359,28 @@ private static void ExecuteSceneRowOperations(
{
case FlushScene.SceneOperationKind.BeginLayer:
GraphicsOptions? layerOptions = scene.Layers[operation.ItemIndex]?.Options;
- using (BandTarget layerTarget = new(
- configuration.MemoryAllocator.Allocate2D(operation.LayerBounds.Width, operation.LayerBounds.Height, AllocationOptions.Clean),
- operation.LayerBounds,
- layerOptions))
- {
- ExecuteSceneRowOperations(
- ref cursor,
- configuration,
- canvasWidth,
- scene,
- layerTarget,
- scratch,
- state);
-
- CompositeLayerBand(configuration, layerTarget, target, state.BrushWorkspace);
- }
+ // The layer band renders into a cleared worker-local buffer of its nesting level, which stays with
+ // the worker for the next layer band of that level (see WorkerState.BeginLayerBand). A row that
+ // throws leaves the level open; returning the state to its pool resets it.
+ Rectangle layerBounds = operation.LayerBounds;
+ BandTarget layerTarget = new(
+ state.BeginLayerBand(layerBounds.Width, layerBounds.Height),
+ layerBounds.X,
+ layerBounds.Y,
+ layerOptions);
+
+ ExecuteSceneRowOperations(
+ ref cursor,
+ configuration,
+ canvasWidth,
+ scene,
+ layerTarget,
+ scratch,
+ state);
+
+ CompositeLayerBand(configuration, layerTarget, target, state.BrushWorkspace);
+ state.EndLayerBand();
break;
case FlushScene.SceneOperationKind.EndLayer:
@@ -365,7 +396,8 @@ private static void ExecuteSceneRowOperations(
sceneItem.ClipState,
sceneItem.PathClipState,
sceneItem.DestinationOffset,
- state);
+ state,
+ scene.StoredFillCoverage?[operation.ItemIndex]);
break;
case FlushScene.SceneOperationKind.StrokeItem:
@@ -459,33 +491,75 @@ private static void ExecuteApplyItemParallel(
where TPixel : unmanaged, IPixel
{
int rowBandCount = item.Rasterizable.RowBandCount;
+ int partitionCount = ParallelExecutionHelper.GetPartitionCountForPixels(
+ configuration.MaxDegreeOfParallelism,
+ rowBandCount,
+ (long)rowBandCount * DefaultRasterizer.DefaultTileHeight * item.Rasterizable.Width);
+
+ if (partitionCount == 1)
+ {
+ // Small items run on the current thread, as in ExecuteSceneRows.
+ WorkerState state = WorkerState.Rent(configuration.MemoryAllocator, target.Region.Width);
+ try
+ {
+ for (int localRowIndex = 0; localRowIndex < rowBandCount; localRowIndex++)
+ {
+ ExecuteApplyItemBand(renderer, item, target, localRowIndex, state);
+ }
+ }
+ finally
+ {
+ WorkerState.Return(state);
+ }
+
+ return;
+ }
_ = Parallel.For(
fromInclusive: 0,
toExclusive: rowBandCount,
- parallelOptions: ParallelExecutionHelper.CreateParallelOptions(configuration.MaxDegreeOfParallelism, rowBandCount),
+ parallelOptions: ParallelExecutionHelper.CreateParallelOptions(configuration.MaxDegreeOfParallelism, partitionCount),
localInit: () => WorkerState.Rent(configuration.MemoryAllocator, target.Region.Width),
body: (localRowIndex, _, state) =>
{
- if (item.Rasterizable.HasCoverage(localRowIndex))
- {
- DefaultRasterizer.WorkerScratch scratch = state.GetOrCreateScratch(Math.Max(target.Region.Width, item.Rasterizable.Width));
- ExecuteFillOperation(
- renderer,
- new DefaultRasterizer.RasterizableItem(item.Rasterizable, localRowIndex),
- target,
- scratch,
- item.ClipState,
- item.PathClipState,
- item.DestinationOffset,
- state);
- }
-
+ ExecuteApplyItemBand(renderer, item, target, localRowIndex, state);
return state;
},
localFinally: static state => WorkerState.Return(state));
}
+ ///
+ /// Writes the processed pixels of one row band of an apply item back to the target.
+ ///
+ /// The pixel format.
+ /// The image brush renderer that writes the processed pixels back.
+ /// The retained apply operation.
+ /// The active target receiving the processed pixels.
+ /// The row band index local to the item.
+ /// The worker-local execution state.
+ private static void ExecuteApplyItemBand(
+ BrushRenderer renderer,
+ FlushScene.ApplySceneItem item,
+ BandTarget target,
+ int localRowIndex,
+ WorkerState state)
+ where TPixel : unmanaged, IPixel
+ {
+ if (item.Rasterizable.HasCoverage(localRowIndex))
+ {
+ DefaultRasterizer.WorkerScratch scratch = state.GetOrCreateScratch(Math.Max(target.Region.Width, item.Rasterizable.Width));
+ ExecuteFillOperation(
+ renderer,
+ new DefaultRasterizer.RasterizableItem(item.Rasterizable, localRowIndex),
+ target,
+ scratch,
+ item.ClipState,
+ item.PathClipState,
+ item.DestinationOffset,
+ state);
+ }
+ }
+
///
/// Applies one retained processor operation to the current target.
///
@@ -506,15 +580,33 @@ private static void ExecuteApplyItem(
Rectangle readRect = item.InputRect;
readRect.Offset(-item.ReadOffset.X, -item.ReadOffset.Y);
- // Layer targets store their pixels at a layer-local origin, so the absolute source
- // rectangle must be translated before reading; the root target already reads absolute.
- if (item.OwnerLayer is not null)
+ // The source rectangle is absolute. Every target stores its pixels from its own absolute origin: a layer target
+ // from the layer bounds, and the root target from the bounds of the frame.
+ readRect.Offset(-target.AbsoluteLeft, -target.AbsoluteTop);
+
+ if (item.Effect is { ProcessesRows: true } effect)
{
- readRect = new Rectangle(
- readRect.X - target.AbsoluteLeft,
- readRect.Y - target.AbsoluteTop,
- readRect.Width,
- readRect.Height);
+ // The effect runs on a pooled snapshot of the same size and content as the image of the general path below
+ // (clean, then the overlap copied at the same place), and gives the pixels that its operation gives on that
+ // image (see LayerEffect.ProcessesRows). The write-back reads the snapshot with the same placement and wrap
+ // as the image brush of the general path, so the result is the same without the image and the processor.
+ using Buffer2D snapshot = configuration.MemoryAllocator.Allocate2D(
+ item.InputRect.Width,
+ item.InputRect.Height,
+ AllocationOptions.Clean);
+
+ CopyTargetToImage(target, readRect, snapshot.GetRegion());
+ effect.ProcessRows(configuration, snapshot);
+ BrushRenderer snapshotRenderer = ImageBrush.CreateRenderer(
+ configuration,
+ item.GraphicsOptions,
+ canvasWidth,
+ snapshot,
+ item.BrushBounds,
+ item.BrushOffset);
+
+ ExecuteApplyItemParallel(configuration, snapshotRenderer, item, target);
+ return;
}
using Image sourceImage = new(configuration, item.InputRect.Width, item.InputRect.Height);
@@ -578,6 +670,10 @@ private static void CopyTargetToImage(
/// The retained path clip raster data captured with the retained scene item.
/// The destination offset used to place clip descriptors.
/// The worker-local execution state.
+ ///
+ /// The stored coverage of the item (), which replaces the scan of the
+ /// band, or to scan.
+ ///
private static void ExecuteFillOperation(
BrushRenderer renderer,
DefaultRasterizer.RasterizableItem item,
@@ -586,15 +682,11 @@ private static void ExecuteFillOperation(
DrawingClipState clipState,
PreparedPathClipState? pathClipState,
Point destinationOffset,
- WorkerState state)
+ WorkerState state,
+ FlushScene.StoredCoverage? storedCoverage = null)
where TPixel : unmanaged, IPixel
{
DefaultRasterizer.RasterizableBandInfo bandInfo = item.Rasterizable.GetBandInfo(item.LocalRowIndex);
- DefaultRasterizer.Context context = scratch.CreateContext(
- bandInfo.IntersectionRule,
- bandInfo.RasterizationMode,
- bandInfo.LineCount);
-
FillCoverageRowHandler rowHandler = new(
renderer,
target,
@@ -605,6 +697,18 @@ private static void ExecuteFillOperation(
state,
bandInfo.Interest);
+ if (storedCoverage is not null)
+ {
+ // The calls that the scan below would make, recorded from the same scan of the same band.
+ storedCoverage.Replay(item.LocalRowIndex, scratch.Scanline, ref rowHandler);
+ return;
+ }
+
+ DefaultRasterizer.Context context = scratch.CreateContext(
+ bandInfo.IntersectionRule,
+ bandInfo.RasterizationMode,
+ bandInfo.LineCount);
+
DefaultRasterizer.ExecuteRasterizableItem(
ref context,
in item,
@@ -688,40 +792,84 @@ private static void CompositeLayerTarget(
int firstRowBandIndex = overlap.Top / DefaultRasterizer.DefaultTileHeight;
int lastRowBandIndex = (overlap.Bottom - 1) / DefaultRasterizer.DefaultTileHeight;
int rowBandCount = (lastRowBandIndex - firstRowBandIndex) + 1;
+ int partitionCount = ParallelExecutionHelper.GetPartitionCountForPixels(
+ configuration.MaxDegreeOfParallelism,
+ rowBandCount,
+ (long)overlap.Width * overlap.Height);
+
+ if (partitionCount == 1)
+ {
+ // Small layers composite on the current thread, as in ExecuteSceneRows.
+ WorkerState state = WorkerState.Rent(configuration.MemoryAllocator, overlap.Width);
+ try
+ {
+ for (int rowSlot = 0; rowSlot < rowBandCount; rowSlot++)
+ {
+ CompositeLayerTargetBand(configuration, source, destination, overlap, firstRowBandIndex + rowSlot, state);
+ }
+ }
+ finally
+ {
+ WorkerState.Return(state);
+ }
+
+ return;
+ }
_ = Parallel.For(
fromInclusive: 0,
toExclusive: rowBandCount,
- parallelOptions: ParallelExecutionHelper.CreateParallelOptions(configuration.MaxDegreeOfParallelism, rowBandCount),
+ parallelOptions: ParallelExecutionHelper.CreateParallelOptions(configuration.MaxDegreeOfParallelism, partitionCount),
localInit: () => WorkerState.Rent(configuration.MemoryAllocator, overlap.Width),
body: (rowSlot, _, state) =>
{
- int bandTop = (firstRowBandIndex + rowSlot) * DefaultRasterizer.DefaultTileHeight;
- Rectangle rowBand = new(overlap.X, bandTop, overlap.Width, DefaultRasterizer.DefaultTileHeight);
- Rectangle band = Rectangle.Intersect(overlap, rowBand);
-
- if (band.Width > 0 && band.Height > 0)
- {
- Buffer2DRegion sourceBand = source.Region.GetSubRegion(
- band.X - source.AbsoluteLeft,
- band.Y - source.AbsoluteTop,
- band.Width,
- band.Height);
- Buffer2DRegion destinationBand = destination.Region.GetSubRegion(
- band.X - destination.AbsoluteLeft,
- band.Y - destination.AbsoluteTop,
- band.Width,
- band.Height);
- BandTarget sourceTarget = new(sourceBand, band.X, band.Y, source.GraphicsOptions);
- BandTarget destinationTarget = new(destinationBand, band.X, band.Y, destination.GraphicsOptions);
- CompositeLayerBand(configuration, sourceTarget, destinationTarget, state.BrushWorkspace);
- }
-
+ CompositeLayerTargetBand(configuration, source, destination, overlap, firstRowBandIndex + rowSlot, state);
return state;
},
localFinally: static state => WorkerState.Return(state));
}
+ ///
+ /// Composites the part of a layer target that lies in one row band of the tile grid.
+ ///
+ /// The pixel format.
+ /// The active processing configuration.
+ /// The temporary layer target carrying the layer's graphics options.
+ /// The destination target to blend into.
+ /// The absolute overlap of the two targets.
+ /// The absolute row band index.
+ /// The worker-local execution state.
+ private static void CompositeLayerTargetBand(
+ Configuration configuration,
+ BandTarget source,
+ BandTarget destination,
+ Rectangle overlap,
+ int rowBandIndex,
+ WorkerState state)
+ where TPixel : unmanaged, IPixel
+ {
+ int bandTop = rowBandIndex * DefaultRasterizer.DefaultTileHeight;
+ Rectangle rowBand = new(overlap.X, bandTop, overlap.Width, DefaultRasterizer.DefaultTileHeight);
+ Rectangle band = Rectangle.Intersect(overlap, rowBand);
+
+ if (band.Width > 0 && band.Height > 0)
+ {
+ Buffer2DRegion sourceBand = source.Region.GetSubRegion(
+ band.X - source.AbsoluteLeft,
+ band.Y - source.AbsoluteTop,
+ band.Width,
+ band.Height);
+ Buffer2DRegion destinationBand = destination.Region.GetSubRegion(
+ band.X - destination.AbsoluteLeft,
+ band.Y - destination.AbsoluteTop,
+ band.Width,
+ band.Height);
+ BandTarget sourceTarget = new(sourceBand, band.X, band.Y, source.GraphicsOptions);
+ BandTarget destinationTarget = new(destinationBand, band.X, band.Y, destination.GraphicsOptions);
+ CompositeLayerBand(configuration, sourceTarget, destinationTarget, state.BrushWorkspace);
+ }
+ }
+
///
/// Composites one temporary layer band back into its destination band.
///
@@ -757,9 +905,13 @@ private static void CompositeLayerBand(
return;
}
+ // The whole layer blends with one amount, so the overload with a constant amount applies. It gives the same
+ // bytes as a span filled with that amount: both run the same vector loops over the same groups of pixels and
+ // the same scalar tail, and pass the operator the amount clamped to [0, 1] in every lane. The blend
+ // percentage of GraphicsOptions is validated to lie in [0, 1], and the clamp keeps an in-range value to the
+ // bit, so both forms pass the same value.
PixelBlender blender = PixelBlenders.GetPixelBlender(graphicsOptions);
- Span amounts = brushWorkspace.GetAmounts(overlap.Width);
- amounts[..overlap.Width].Fill(graphicsOptions.BlendPercentage);
+ float amount = graphicsOptions.BlendPercentage;
int sourceOffsetX = overlap.X - source.AbsoluteLeft;
int sourceOffsetY = overlap.Y - source.AbsoluteTop;
@@ -777,7 +929,7 @@ private static void CompositeLayerBand(
destinationRow,
destinationRow,
sourceRow,
- amounts[..overlap.Width],
+ amount,
brushWorkspace.GetBlendScratch(overlap.Width, 3));
}
}
diff --git a/src/ImageSharp.Drawing/Processing/Backends/DefaultRasterizer.Linearizer.cs b/src/ImageSharp.Drawing/Processing/Backends/DefaultRasterizer.Linearizer.cs
index cc527382b..ebee6e88d 100644
--- a/src/ImageSharp.Drawing/Processing/Backends/DefaultRasterizer.Linearizer.cs
+++ b/src/ImageSharp.Drawing/Processing/Backends/DefaultRasterizer.Linearizer.cs
@@ -3,16 +3,90 @@
using System.Buffers;
using System.Numerics;
+using System.Runtime.CompilerServices;
using SixLabors.ImageSharp.Memory;
namespace SixLabors.ImageSharp.Drawing.Processing.Backends;
internal static partial class DefaultRasterizer
{
+ ///
+ /// Maps geometry points to the local float space of an interest: the residual transform, then the whole-pixel
+ /// translation, then the interest origin, with the operations and their order of the linearizer.
+ ///
+ ///
+ ///
+ /// A residual that only translates maps a finite point with one addition per axis. That gives the value of
+ /// , which evaluates x * M11 + y * M21 + 0 * M31 + 1 * M41
+ /// (and the same for Y) and divides by x * M14 + y * M24 + 0 * M34 + 1 * M44. With a unit diagonal and zero
+ /// shear, perspective, and Z terms, every product except the translation is exact (the coordinate itself or a signed
+ /// zero), so in any order of evaluation, fused or not, the sum rounds once, to x + M41, and the divisor is
+ /// exactly 1. The sign of a zero result can differ, but the next step adds the whole-pixel translation, and
+ /// -0 + 0 is +0, so the local value is the same. A coordinate that is not finite takes the general
+ /// path, because the products of the divisor are then not zero.
+ ///
+ ///
+ /// The text documents of the SVG renderer place every glyph with such a residual, and their linearization is the
+ /// largest part of their scene build.
+ ///
+ ///
+ private readonly struct LocalMapping
+ {
+ private readonly Matrix4x4 residual;
+ private readonly bool hasResidual;
+ private readonly bool translationOnly;
+ private readonly int translateX;
+ private readonly int translateY;
+ private readonly int minX;
+ private readonly int minY;
+
+ ///
+ /// Initializes a new instance of the struct.
+ ///
+ /// The residual transform applied to each source point.
+ /// Whether is not the identity.
+ /// The whole-pixel X translation applied after the residual.
+ /// The whole-pixel Y translation applied after the residual.
+ /// The X origin of the interest.
+ /// The Y origin of the interest.
+ public LocalMapping(in Matrix4x4 residual, bool hasResidual, int translateX, int translateY, int minX, int minY)
+ {
+ this.residual = residual;
+ this.hasResidual = hasResidual;
+ this.translationOnly = hasResidual
+ && residual.M11 == 1F && residual.M12 == 0F && residual.M14 == 0F
+ && residual.M21 == 0F && residual.M22 == 1F && residual.M24 == 0F
+ && residual.M31 == 0F && residual.M32 == 0F && residual.M34 == 0F
+ && residual.M44 == 1F;
+ this.translateX = translateX;
+ this.translateY = translateY;
+ this.minX = minX;
+ this.minY = minY;
+ }
+
+ ///
+ /// Maps one geometry point.
+ ///
+ /// The geometry point.
+ /// The point relative to the interest origin.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public PointF Map(PointF point)
+ {
+ if (this.hasResidual)
+ {
+ point = this.translationOnly && float.IsFinite(point.X) && float.IsFinite(point.Y)
+ ? new PointF(point.X + this.residual.M41, point.Y + this.residual.M42)
+ : PointF.Transform(point, this.residual);
+ }
+
+ return new PointF((point.X + this.translateX) - this.minX, (point.Y + this.translateY) - this.minY);
+ }
+ }
+
///
/// Base class that lowers translated geometry into retained per-row line storage.
///
- /// The mutable per-row line collector type.
+ /// The retained line block type of a row band.
private abstract class Linearizer
where TL : class
{
@@ -65,10 +139,9 @@ protected Linearizer(
this.RowBandCount = rowBandCount;
this.Allocator = allocator;
this.BandTopStart = (firstBandIndex * PreferredRowHeight) - minY;
+ this.FinalLines = new TL?[rowBandCount];
this.FirstBlockLineCounts = new int[rowBandCount];
- this.LineCounts = new int[rowBandCount];
this.StartCoverTable = new IMemoryOwner?[rowBandCount];
- this.LineArrays = new TL?[rowBandCount];
}
///
@@ -142,20 +215,19 @@ protected Linearizer(
protected int BandTopStart { get; }
///
- /// Gets the mutable per-row line collectors used during lowering.
+ /// Gets the front retained line block of each row band, or for a band without lines.
///
- protected TL?[] LineArrays { get; }
+ ///
+ /// Lines are appended straight into these chains (, ),
+ /// so a band needs no collector object, and the retained geometry takes this array over as it is.
+ ///
+ public TL?[] FinalLines { get; }
///
/// Gets the valid front-block line count for each retained row band.
///
protected int[] FirstBlockLineCounts { get; }
- ///
- /// Gets the total retained line count for each row band.
- ///
- protected int[] LineCounts { get; }
-
///
/// Gets the retained start-cover storage for each row band.
///
@@ -227,68 +299,93 @@ protected virtual bool ProcessCore()
this.ProcessUncontained();
}
- if (!this.hasAnyCoverage)
- {
- return false;
- }
-
- this.FinalizeLines();
- return true;
+ return this.hasAnyCoverage;
}
///
/// Linearizes geometry that is fully contained inside the destination interest.
///
+ ///
+ /// The segments are those of , in the same order: segment s of a
+ /// contour runs from point s to point s + 1, and the closing segment of a closed contour runs from
+ /// its last point back to its first. Each point is transformed and converted to fixed point once, and the end of
+ /// one segment is reused as the start of the next. The conversion of a point is a function of the point alone, so
+ /// every segment receives the endpoints that a conversion per segment gives, and the retained lines are the same.
+ ///
protected void ProcessContained()
{
- SegmentEnumerator enumerator = this.Geometry.GetSegments();
- Matrix4x4 residual = this.Residual;
- bool hasResidual = this.HasResidual;
- while (enumerator.MoveNext())
+ LinearGeometry geometry = this.Geometry;
+ LocalMapping mapping = new(this.Residual, this.HasResidual, this.TranslateX, this.TranslateY, this.MinX, this.MinY);
+ ReadOnlySpan contours = geometry.GetContours();
+ for (int c = 0; c < contours.Length; c++)
{
- LinearSegment segment = enumerator.Current;
- PointF p0 = segment.Start;
- PointF p1 = segment.End;
- if (hasResidual)
+ ref readonly LinearContour contour = ref contours[c];
+ int segmentCount = contour.SegmentCount;
+ if (segmentCount <= 0)
{
- p0 = PointF.Transform(p0, residual);
- p1 = PointF.Transform(p1, residual);
+ continue;
}
- this.AddContainedLineF24Dot8(
- FloatToFixed24Dot8((p0.X + this.TranslateX) - this.MinX),
- FloatToFixed24Dot8((p0.Y + this.TranslateY) - this.MinY),
- FloatToFixed24Dot8((p1.X + this.TranslateX) - this.MinX),
- FloatToFixed24Dot8((p1.Y + this.TranslateY) - this.MinY),
- this.NextSegmentTag());
+ ReadOnlySpan points = geometry.GetContourPoints(in contour);
+ int lastPoint = points.Length - 1;
+ PointF first = mapping.Map(points[0]);
+ int firstX = FloatToFixed24Dot8(first.X);
+ int firstY = FloatToFixed24Dot8(first.Y);
+ int x0 = firstX;
+ int y0 = firstY;
+ for (int s = 0; s < segmentCount; s++)
+ {
+ int x1;
+ int y1;
+ if (s == lastPoint)
+ {
+ x1 = firstX;
+ y1 = firstY;
+ }
+ else
+ {
+ PointF p1 = mapping.Map(points[s + 1]);
+ x1 = FloatToFixed24Dot8(p1.X);
+ y1 = FloatToFixed24Dot8(p1.Y);
+ }
+
+ this.AddContainedLineF24Dot8(x0, y0, x1, y1, this.NextSegmentTag());
+ x0 = x1;
+ y0 = y1;
+ }
}
}
///
/// Linearizes geometry that intersects the destination interest bounds and requires clipping.
///
+ ///
+ /// The segments are visited as in , and each point is mapped once.
+ ///
protected void ProcessUncontained()
{
- SegmentEnumerator enumerator = this.Geometry.GetSegments();
- Matrix4x4 residual = this.Residual;
- bool hasResidual = this.HasResidual;
- while (enumerator.MoveNext())
+ LinearGeometry geometry = this.Geometry;
+ LocalMapping mapping = new(this.Residual, this.HasResidual, this.TranslateX, this.TranslateY, this.MinX, this.MinY);
+ ReadOnlySpan contours = geometry.GetContours();
+ for (int c = 0; c < contours.Length; c++)
{
- LinearSegment segment = enumerator.Current;
- PointF p0 = segment.Start;
- PointF p1 = segment.End;
- if (hasResidual)
+ ref readonly LinearContour contour = ref contours[c];
+ int segmentCount = contour.SegmentCount;
+ if (segmentCount <= 0)
{
- p0 = PointF.Transform(p0, residual);
- p1 = PointF.Transform(p1, residual);
+ continue;
}
- this.AddUncontainedLine(
- (p0.X + this.TranslateX) - this.MinX,
- (p0.Y + this.TranslateY) - this.MinY,
- (p1.X + this.TranslateX) - this.MinX,
- (p1.Y + this.TranslateY) - this.MinY,
- this.NextSegmentTag());
+ ReadOnlySpan points = geometry.GetContourPoints(in contour);
+ int lastPoint = points.Length - 1;
+ PointF first = mapping.Map(points[0]);
+ PointF p0 = first;
+ for (int s = 0; s < segmentCount; s++)
+ {
+ PointF p1 = s == lastPoint ? first : mapping.Map(points[s + 1]);
+ this.AddUncontainedLine(p0.X, p0.Y, p1.X, p1.Y, this.NextSegmentTag());
+ p0 = p1;
+ }
}
}
@@ -568,7 +665,6 @@ protected void AddContainedLineF24Dot8(int x0, int y0, int x1, int y1, uint tag)
{
int rowTop = bandTop + (band * bandExtent);
this.AppendLine(band, x0, y0 - rowTop, x1, y1 - rowTop, tag);
- this.LineCounts[band]++;
this.hasAnyCoverage = true;
}
@@ -576,7 +672,6 @@ protected void AddContainedLineF24Dot8(int x0, int y0, int x1, int y1, uint tag)
{
int rowTop = bandTop + ((band - 1) * bandExtent);
this.AppendLine(band - 1, x0, y0 - rowTop, x1, y1 - rowTop, tag);
- this.LineCounts[band - 1]++;
}
return;
@@ -634,7 +729,6 @@ protected void AddContainedLineF24Dot8(int x0, int y0, int x1, int y1, uint tag)
{
int rowTop = bandTopStart + (rowIndex0 * bandHeight);
this.AppendLine(rowIndex0, x0, y0 - rowTop, x1, y1 - rowTop, tag);
- this.LineCounts[rowIndex0]++;
this.hasAnyCoverage = true;
return;
}
@@ -643,13 +737,7 @@ protected void AddContainedLineF24Dot8(int x0, int y0, int x1, int y1, uint tag)
}
///
- /// Creates the mutable line collector used for one row band.
- ///
- /// The mutable line collector.
- protected abstract TL CreateLineArray();
-
- ///
- /// Appends one line segment into the retained row-band collector.
+ /// Appends one line segment to the retained block chain of a row band ().
///
/// The local row-band index.
/// The starting X coordinate relative to the row band.
@@ -659,29 +747,6 @@ protected void AddContainedLineF24Dot8(int x0, int y0, int x1, int y1, uint tag)
/// The segment profile tag.
protected abstract void AppendLine(int rowIndex, int x0, int y0, int x1, int y1, uint tag);
- ///
- /// Finalizes the mutable collectors into the retained line-block representation.
- ///
- protected abstract void FinalizeLines();
-
- ///
- /// Gets the mutable line collector for a row band, creating it on first use.
- ///
- /// The local row-band index.
- /// The mutable line collector.
- protected TL GetOrCreateLineArray(int rowIndex)
- {
- TL? lineArray = this.LineArrays[rowIndex];
- if (lineArray is not null)
- {
- return lineArray;
- }
-
- lineArray = this.CreateLineArray();
- this.LineArrays[rowIndex] = lineArray;
- return lineArray;
- }
-
///
/// Splits a contained line segment at row-band boundaries and appends each retained piece.
///
@@ -718,7 +783,6 @@ private void SplitAcrossBands(int x0, int y0, int x1, int y1, uint tag)
// Each retained segment is stored in the local coordinate space of its owning band.
this.AppendLine(currentBand, currentX, currentY - rowTop, nextX, bandBoundaryY - rowTop, tag);
- this.LineCounts[currentBand]++;
this.hasAnyCoverage = true;
currentX = nextX;
currentY = bandBoundaryY;
@@ -733,7 +797,6 @@ private void SplitAcrossBands(int x0, int y0, int x1, int y1, uint tag)
int finalRowTop = bandTopStart + (endBand * bandHeight);
this.AppendLine(endBand, currentX, currentY - finalRowTop, x1, y1 - finalRowTop, tag);
- this.LineCounts[endBand]++;
this.hasAnyCoverage = true;
}
@@ -946,7 +1009,7 @@ private static void UpdateCoverTableUp(Span covers, int y0, int y1)
///
/// Linearizer that finalizes retained lines into the 32-bit-X encoding.
///
- private sealed class LinearizerX32Y16 : Linearizer
+ private sealed class LinearizerX32Y16 : Linearizer
{
private readonly LinearGeometryProfileStorage profileStorage;
@@ -981,33 +1044,19 @@ public LinearizerX32Y16(
LinearGeometryProfileStorage profileStorage,
bool keepHorizontalLines)
: base(geometry, residual, translateX, translateY, minX, minY, width, height, firstBandIndex, rowBandCount, allocator, keepHorizontalLines)
- {
- this.profileStorage = profileStorage;
- this.FinalLines = new LineArrayX32Y16Block?[rowBandCount];
- }
-
- ///
- /// Gets the finalized retained line blocks for each row band.
- ///
- public LineArrayX32Y16Block?[] FinalLines { get; }
-
- ///
- protected override LineArrayX32Y16 CreateLineArray() => new(this.KeepHorizontalLines);
+ => this.profileStorage = profileStorage;
///
protected override void AppendLine(int rowIndex, int x0, int y0, int x1, int y1, uint tag)
- => this.GetOrCreateLineArray(rowIndex).AppendLine(x0, y0, x1, y1, tag);
-
- ///
- protected override void FinalizeLines()
- {
- for (int i = 0; i < this.RowBandCount; i++)
- {
- LineArrayX32Y16? lineArray = this.LineArrays[i];
- this.FinalLines[i] = lineArray?.GetFrontBlock();
- this.FirstBlockLineCounts[i] = lineArray?.GetFrontBlockLineCount() ?? 0;
- }
- }
+ => LineArrayX32Y16.AppendLine(
+ ref this.FinalLines[rowIndex],
+ ref this.FirstBlockLineCounts[rowIndex],
+ this.KeepHorizontalLines,
+ x0,
+ y0,
+ x1,
+ y1,
+ tag);
///
/// Executes the 32-bit-X linearization pass and returns the retained result.
@@ -1041,7 +1090,7 @@ public bool TryProcess(out LinearizedRasterData result)
///
/// Linearizer that finalizes retained lines into the packed 16-bit-X encoding.
///
- private sealed class LinearizerX16Y16 : Linearizer
+ private sealed class LinearizerX16Y16 : Linearizer
{
private readonly LinearGeometryProfileStorage profileStorage;
@@ -1076,33 +1125,19 @@ public LinearizerX16Y16(
LinearGeometryProfileStorage profileStorage,
bool keepHorizontalLines)
: base(geometry, residual, translateX, translateY, minX, minY, width, height, firstBandIndex, rowBandCount, allocator, keepHorizontalLines)
- {
- this.profileStorage = profileStorage;
- this.FinalLines = new LineArrayX16Y16Block?[rowBandCount];
- }
-
- ///
- /// Gets the finalized retained line blocks for each row band.
- ///
- public LineArrayX16Y16Block?[] FinalLines { get; }
-
- ///
- protected override LineArrayX16Y16 CreateLineArray() => new(this.KeepHorizontalLines);
+ => this.profileStorage = profileStorage;
///
protected override void AppendLine(int rowIndex, int x0, int y0, int x1, int y1, uint tag)
- => this.GetOrCreateLineArray(rowIndex).AppendLine(x0, y0, x1, y1, tag);
-
- ///
- protected override void FinalizeLines()
- {
- for (int i = 0; i < this.RowBandCount; i++)
- {
- LineArrayX16Y16? lineArray = this.LineArrays[i];
- this.FinalLines[i] = lineArray?.GetFrontBlock();
- this.FirstBlockLineCounts[i] = lineArray?.GetFrontBlockLineCount() ?? 0;
- }
- }
+ => LineArrayX16Y16.AppendLine(
+ ref this.FinalLines[rowIndex],
+ ref this.FirstBlockLineCounts[rowIndex],
+ this.KeepHorizontalLines,
+ x0,
+ y0,
+ x1,
+ y1,
+ tag);
///
/// Executes the 16-bit-X linearization pass and returns the retained result.
diff --git a/src/ImageSharp.Drawing/Processing/Backends/DefaultRasterizer.RetainedTypes.cs b/src/ImageSharp.Drawing/Processing/Backends/DefaultRasterizer.RetainedTypes.cs
index 5ba623f28..c0c616ace 100644
--- a/src/ImageSharp.Drawing/Processing/Backends/DefaultRasterizer.RetainedTypes.cs
+++ b/src/ImageSharp.Drawing/Processing/Backends/DefaultRasterizer.RetainedTypes.cs
@@ -203,70 +203,53 @@ public RasterizableBandInfo(
}
///
- /// Collects retained line segments whose X coordinates require 32-bit storage.
+ /// Appends retained line segments whose X coordinates require 32-bit storage to the block chain of a row band.
///
- internal sealed class LineArrayX32Y16
+ ///
+ /// The chain of a band is its front block and the number of valid lines in it; the linearizer keeps both in the
+ /// arrays that the retained geometry takes over, so a band needs no collector object. An empty band has no front
+ /// block and a count of 0, and its first line allocates the front block.
+ ///
+ internal static class LineArrayX32Y16
{
- private readonly bool retainTags;
- private LineArrayX32Y16Block? current;
-
- // Starting at full capacity forces the first AppendLine to allocate the front block,
- // so empty rows never pay for a block allocation.
- private int count = LineArrayX32Y16Block.LineCount;
-
///
- /// Initializes a new instance of the class.
+ /// Appends one retained line to the chain of a band.
///
+ /// The front block of the chain, or for an empty chain; replaced when a new block is needed.
+ /// The number of valid lines in .
///
/// Whether each line stores a profile tag. Only aliased fills need tags. Antialiased fills
- /// and strokes therefore use the smaller base block and do not allocate tag storage.
+ /// and strokes therefore use the smaller base block and do not allocate tag storage. The value
+ /// must be the same for every line of a chain.
///
- public LineArrayX32Y16(bool retainTags) => this.retainTags = retainTags;
-
- ///
- /// Gets the front block in the retained line chain.
- ///
- /// The front retained block, or when no lines were appended.
- public LineArrayX32Y16Block? GetFrontBlock() => this.current;
-
- ///
- /// Gets the number of valid lines in the front retained block.
- ///
- /// The number of valid front-block lines.
- public int GetFrontBlockLineCount() => this.current is null ? 0 : this.count;
-
- ///
- /// Appends one retained line to the chain.
- ///
/// The starting X coordinate in 24.8 fixed-point.
/// The starting Y coordinate in 24.8 fixed-point.
/// The ending X coordinate in 24.8 fixed-point.
/// The ending Y coordinate in 24.8 fixed-point.
/// The segment profile tag.
- public void AppendLine(int x0, int y0, int x1, int y1, uint tag)
+ public static void AppendLine(ref LineArrayX32Y16Block? front, ref int count, bool retainTags, int x0, int y0, int x1, int y1, uint tag)
{
int packedY0Y1 = Pack(y0, y1);
- LineArrayX32Y16Block? block = this.current;
- int currentCount = this.count;
- if (currentCount < LineArrayX32Y16Block.LineCount)
+ LineArrayX32Y16Block? block = front;
+ int currentCount = count;
+ if (block is not null && currentCount < LineArrayX32Y16Block.LineCount)
{
- // retainTags does not change during the collector's lifetime. When it is true,
- // every block in this chain was created as the tagged derived type.
- if (this.retainTags)
+ // When retainTags is true, every block in this chain was created as the tagged derived type.
+ if (retainTags)
{
- ((TaggedLineArrayX32Y16Block)block!).SetTagged(currentCount, packedY0Y1, x0, x1, tag);
+ ((TaggedLineArrayX32Y16Block)block).SetTagged(currentCount, packedY0Y1, x0, x1, tag);
}
else
{
- block!.Set(currentCount, packedY0Y1, x0, x1);
+ block.Set(currentCount, packedY0Y1, x0, x1);
}
- this.count = currentCount + 1;
+ count = currentCount + 1;
}
else
{
LineArrayX32Y16Block next;
- if (this.retainTags)
+ if (retainTags)
{
TaggedLineArrayX32Y16Block tagged = new(block);
tagged.SetTagged(0, packedY0Y1, x0, x1, tag);
@@ -278,8 +261,8 @@ public void AppendLine(int x0, int y0, int x1, int y1, uint tag)
next.Set(0, packedY0Y1, x0, x1);
}
- this.current = next;
- this.count = 1;
+ front = next;
+ count = 1;
}
}
@@ -482,71 +465,53 @@ private struct TagBuffer
}
///
- /// Collects retained line segments whose X coordinates fit in packed 16-bit storage.
+ /// Appends retained line segments whose X coordinates fit in packed 16-bit storage to the block chain of a row band.
///
- internal sealed class LineArrayX16Y16
+ ///
+ /// The chain of a band is held as for : its front block and the number of valid lines
+ /// in it, in the arrays that the retained geometry takes over.
+ ///
+ internal static class LineArrayX16Y16
{
- private readonly bool retainTags;
- private LineArrayX16Y16Block? current;
-
- // Starting at full capacity forces the first AppendLine to allocate the front block,
- // so empty rows never pay for a block allocation.
- private int count = LineArrayX16Y16Block.LineCount;
-
///
- /// Initializes a new instance of the class.
+ /// Appends one retained line to the chain of a band.
///
+ /// The front block of the chain, or for an empty chain; replaced when a new block is needed.
+ /// The number of valid lines in .
///
/// Whether each line stores a profile tag. Only aliased fills need tags. Antialiased fills
- /// and strokes therefore use the smaller base block and do not allocate tag storage.
+ /// and strokes therefore use the smaller base block and do not allocate tag storage. The value
+ /// must be the same for every line of a chain.
///
- public LineArrayX16Y16(bool retainTags) => this.retainTags = retainTags;
-
- ///
- /// Gets the front block in the retained line chain.
- ///
- /// The front retained block, or when no lines were appended.
- public LineArrayX16Y16Block? GetFrontBlock() => this.current;
-
- ///
- /// Gets the number of valid lines in the front retained block.
- ///
- /// The number of valid front-block lines.
- public int GetFrontBlockLineCount() => this.current is null ? 0 : this.count;
-
- ///
- /// Appends one retained line to the chain.
- ///
/// The starting X coordinate in 24.8 fixed-point.
/// The starting Y coordinate in 24.8 fixed-point.
/// The ending X coordinate in 24.8 fixed-point.
/// The ending Y coordinate in 24.8 fixed-point.
/// The segment profile tag.
- public void AppendLine(int x0, int y0, int x1, int y1, uint tag)
+ public static void AppendLine(ref LineArrayX16Y16Block? front, ref int count, bool retainTags, int x0, int y0, int x1, int y1, uint tag)
{
int packedY0Y1 = Pack(y0, y1);
int packedX0X1 = Pack(x0, x1);
- LineArrayX16Y16Block? block = this.current;
- int currentCount = this.count;
- if (currentCount < LineArrayX16Y16Block.LineCount)
+ LineArrayX16Y16Block? block = front;
+ int currentCount = count;
+ if (block is not null && currentCount < LineArrayX16Y16Block.LineCount)
{
- // retainTags does not change during the collector's lifetime. When it is true,
- // every block in this chain was created as the tagged derived type.
- if (this.retainTags)
+ // When retainTags is true, every block in this chain was created as the tagged derived type.
+ if (retainTags)
{
- ((TaggedLineArrayX16Y16Block)block!).SetTagged(currentCount, packedY0Y1, packedX0X1, tag);
+ ((TaggedLineArrayX16Y16Block)block).SetTagged(currentCount, packedY0Y1, packedX0X1, tag);
}
else
{
- block!.Set(currentCount, packedY0Y1, packedX0X1);
+ block.Set(currentCount, packedY0Y1, packedX0X1);
}
- this.count = currentCount + 1;
+ count = currentCount + 1;
}
else
{
LineArrayX16Y16Block next;
- if (this.retainTags)
+ if (retainTags)
{
TaggedLineArrayX16Y16Block tagged = new(block);
tagged.SetTagged(0, packedY0Y1, packedX0X1, tag);
@@ -558,8 +523,8 @@ public void AppendLine(int x0, int y0, int x1, int y1, uint tag)
next.Set(0, packedY0Y1, packedX0X1);
}
- this.current = next;
- this.count = 1;
+ front = next;
+ count = 1;
}
}
diff --git a/src/ImageSharp.Drawing/Processing/Backends/DefaultRasterizer.StrokeLinearizer.cs b/src/ImageSharp.Drawing/Processing/Backends/DefaultRasterizer.StrokeLinearizer.cs
index 3f077e429..0d38ff63c 100644
--- a/src/ImageSharp.Drawing/Processing/Backends/DefaultRasterizer.StrokeLinearizer.cs
+++ b/src/ImageSharp.Drawing/Processing/Backends/DefaultRasterizer.StrokeLinearizer.cs
@@ -20,7 +20,7 @@ internal static partial class DefaultRasterizer
/// ports of the corresponding members here, and WebGPUSceneEncoder.EncodeStrokePath
/// ports the contour preprocessing. Any behavioral change here must be mirrored there.
///
- /// The mutable per-row retained line collector type.
+ /// The retained line block type of a row band.
private abstract class StrokeLinearizer : Linearizer
where TL : class
{
@@ -102,13 +102,7 @@ protected override bool ProcessCore()
this.ProcessContour(contourPoints, contour.IsClosed, contourInterest == ContourInterest.Contained);
}
- if (!this.HasAnyCoverage)
- {
- return false;
- }
-
- this.FinalizeLines();
- return true;
+ return this.HasAnyCoverage;
}
///
@@ -1090,7 +1084,7 @@ private struct ContourState
///
/// Stroke linearizer that finalizes retained lines into the 32-bit-X encoding.
///
- private sealed class StrokeLinearizerX32Y16 : StrokeLinearizer
+ private sealed class StrokeLinearizerX32Y16 : StrokeLinearizer
{
///
/// Initializes a new instance of the class.
@@ -1123,30 +1117,21 @@ public StrokeLinearizerX32Y16(
bool keepHorizontalLines,
MemoryAllocator allocator)
: base(geometry, residual, stroke, translateX, translateY, minX, minY, width, height, firstBandIndex, rowBandCount, keepHorizontalLines, allocator)
- => this.FinalLines = new LineArrayX32Y16Block?[rowBandCount];
-
- ///
- /// Gets the finalized retained line blocks for each row band.
- ///
- public LineArrayX32Y16Block?[] FinalLines { get; }
-
- ///
- protected override LineArrayX32Y16 CreateLineArray() => new(false);
+ {
+ }
///
+ /// Stroke outlines retain no profile tags, so the chains use the base block.
protected override void AppendLine(int rowIndex, int x0, int y0, int x1, int y1, uint tag)
- => this.GetOrCreateLineArray(rowIndex).AppendLine(x0, y0, x1, y1, tag);
-
- ///
- protected override void FinalizeLines()
- {
- for (int i = 0; i < this.RowBandCount; i++)
- {
- LineArrayX32Y16? lineArray = this.LineArrays[i];
- this.FinalLines[i] = lineArray?.GetFrontBlock();
- this.FirstBlockLineCounts[i] = lineArray?.GetFrontBlockLineCount() ?? 0;
- }
- }
+ => LineArrayX32Y16.AppendLine(
+ ref this.FinalLines[rowIndex],
+ ref this.FirstBlockLineCounts[rowIndex],
+ false,
+ x0,
+ y0,
+ x1,
+ y1,
+ tag);
///
/// Executes the retained stroke linearization pass and returns the finalized payload.
@@ -1178,7 +1163,7 @@ public bool TryProcess(out LinearizedRasterData result)
///
/// Stroke linearizer that finalizes retained lines into the packed 16-bit-X encoding.
///
- private sealed class StrokeLinearizerX16Y16 : StrokeLinearizer
+ private sealed class StrokeLinearizerX16Y16 : StrokeLinearizer
{
///
/// Initializes a new instance of the class.
@@ -1211,30 +1196,21 @@ public StrokeLinearizerX16Y16(
bool keepHorizontalLines,
MemoryAllocator allocator)
: base(geometry, residual, stroke, translateX, translateY, minX, minY, width, height, firstBandIndex, rowBandCount, keepHorizontalLines, allocator)
- => this.FinalLines = new LineArrayX16Y16Block?[rowBandCount];
-
- ///
- /// Gets the finalized retained line blocks for each row band.
- ///
- public LineArrayX16Y16Block?[] FinalLines { get; }
-
- ///
- protected override LineArrayX16Y16 CreateLineArray() => new(false);
+ {
+ }
///
+ /// Stroke outlines retain no profile tags, so the chains use the base block.
protected override void AppendLine(int rowIndex, int x0, int y0, int x1, int y1, uint tag)
- => this.GetOrCreateLineArray(rowIndex).AppendLine(x0, y0, x1, y1, tag);
-
- ///
- protected override void FinalizeLines()
- {
- for (int i = 0; i < this.RowBandCount; i++)
- {
- LineArrayX16Y16? lineArray = this.LineArrays[i];
- this.FinalLines[i] = lineArray?.GetFrontBlock();
- this.FirstBlockLineCounts[i] = lineArray?.GetFrontBlockLineCount() ?? 0;
- }
- }
+ => LineArrayX16Y16.AppendLine(
+ ref this.FinalLines[rowIndex],
+ ref this.FirstBlockLineCounts[rowIndex],
+ false,
+ x0,
+ y0,
+ x1,
+ y1,
+ tag);
///
/// Executes the retained stroke linearization pass and returns the finalized payload.
diff --git a/src/ImageSharp.Drawing/Processing/Backends/DrawingBackendScene.cs b/src/ImageSharp.Drawing/Processing/Backends/DrawingBackendScene.cs
index 2b4e35bce..40842e37c 100644
--- a/src/ImageSharp.Drawing/Processing/Backends/DrawingBackendScene.cs
+++ b/src/ImageSharp.Drawing/Processing/Backends/DrawingBackendScene.cs
@@ -37,6 +37,11 @@ protected DrawingBackendScene(
///
public Rectangle Bounds { get; }
+ ///
+ /// Gets the resources that the scene keeps alive and disposes with itself, or for none.
+ ///
+ internal IReadOnlyList? OwnedResources => this.ownedResources;
+
///
public void Dispose()
{
diff --git a/src/ImageSharp.Drawing/Processing/Backends/DrawingCommandBatch.cs b/src/ImageSharp.Drawing/Processing/Backends/DrawingCommandBatch.cs
index 0690809f2..7695a9360 100644
--- a/src/ImageSharp.Drawing/Processing/Backends/DrawingCommandBatch.cs
+++ b/src/ImageSharp.Drawing/Processing/Backends/DrawingCommandBatch.cs
@@ -168,6 +168,38 @@ internal DrawingCommandBatch(
return scene;
}
+ ///
+ /// Returns whether the batch holds one retained scene command outside every layer and no other work: every other
+ /// command is a clip control, which draws nothing.
+ ///
+ /// if the only work of the batch is one retained scene outside every layer.
+ internal bool HasOnlyOneRootScene()
+ {
+ IReadOnlyList commands = this.Commands;
+ int rootScenes = 0;
+ for (int i = 0; i < commands.Count; i++)
+ {
+ switch (commands[i])
+ {
+ case RetainedSceneCompositionSceneCommand { IsInsideLayer: false }:
+ if (++rootScenes > 1)
+ {
+ return false;
+ }
+
+ break;
+
+ case PathCompositionSceneCommand { Command.Kind: CompositionCommandKind.BeginClip or CompositionCommandKind.EndClip }:
+ break;
+
+ default:
+ return false;
+ }
+ }
+
+ return rootScenes == 1;
+ }
+
///
/// Finds the retained scenes that hold ordered work, and the layers that must render as scoped
/// layers around them.
diff --git a/src/ImageSharp.Drawing/Processing/Backends/FlushScene.RetainedTypes.cs b/src/ImageSharp.Drawing/Processing/Backends/FlushScene.RetainedTypes.cs
index f64aadd4a..c90be5bf6 100644
--- a/src/ImageSharp.Drawing/Processing/Backends/FlushScene.RetainedTypes.cs
+++ b/src/ImageSharp.Drawing/Processing/Backends/FlushScene.RetainedTypes.cs
@@ -552,8 +552,9 @@ internal sealed class ApplySceneItem : IDisposable
/// Initializes a new instance of the class.
///
/// The image processing operation.
- /// The canvas-local rectangle containing the source pixels supplied to the operation.
- /// The canvas-local bounds within which the processed pixels are written.
+ /// The layer effect that the operation implements, or for a direct Apply operation.
+ /// The absolute rectangle containing the source pixels supplied to the operation.
+ /// The absolute bounds within which the processed pixels are written.
/// The offset subtracted from when reading the source pixels.
/// The offset used by the runtime image brush.
/// The graphics options used by the apply item.
@@ -565,6 +566,7 @@ internal sealed class ApplySceneItem : IDisposable
/// The layer that owned this item when it was recorded.
public ApplySceneItem(
Action operation,
+ LayerEffect? effect,
Rectangle inputRect,
Rectangle outputRect,
Point readOffset,
@@ -578,6 +580,7 @@ public ApplySceneItem(
DrawingCanvasLayer? ownerLayer)
{
this.Operation = operation;
+ this.Effect = effect;
this.InputRect = inputRect;
this.OutputRect = outputRect;
this.ReadOffset = readOffset;
@@ -597,12 +600,18 @@ public ApplySceneItem(
public Action Operation { get; }
///
- /// Gets the canvas-local rectangle containing the source pixels supplied to the operation.
+ /// Gets the layer effect that implements, or for a direct Apply
+ /// operation.
+ ///
+ public LayerEffect? Effect { get; }
+
+ ///
+ /// Gets the absolute rectangle containing the source pixels supplied to the operation.
///
public Rectangle InputRect { get; }
///
- /// Gets the canvas-local bounds within which the processed pixels are written.
+ /// Gets the absolute bounds within which the processed pixels are written.
///
public Rectangle OutputRect { get; }
diff --git a/src/ImageSharp.Drawing/Processing/Backends/FlushScene.StoredCoverage.cs b/src/ImageSharp.Drawing/Processing/Backends/FlushScene.StoredCoverage.cs
new file mode 100644
index 000000000..5f0a92fff
--- /dev/null
+++ b/src/ImageSharp.Drawing/Processing/Backends/FlushScene.StoredCoverage.cs
@@ -0,0 +1,341 @@
+// Copyright (c) Six Labors.
+// Licensed under the Six Labors Split License.
+
+using SixLabors.ImageSharp.Memory;
+
+namespace SixLabors.ImageSharp.Drawing.Processing.Backends;
+
+///
+/// The stored coverage of small fill items, which a scene that is replayed many times can keep so that a replay hands the
+/// coverage of those items to their row handlers without scanning their lines again.
+///
+internal sealed partial class FlushScene
+{
+ ///
+ /// The largest area, in pixels, of the bands of a fill item whose coverage stores
+ /// (128 x 128). Small items, such as glyphs, have many lines per pixel, so their scan costs much more than their
+ /// stored coverage; a large item, such as a background rectangle, has few lines per pixel and would store many values.
+ ///
+ internal const int MaxStoredCoverageItemPixels = 128 * 128;
+
+ ///
+ /// Gets the bytes of the stored coverage of the items of this scene ().
+ ///
+ public long StoredCoverageBytes { get; private set; }
+
+ ///
+ /// Gets the stored coverage of the fill items by item index (an item without stored coverage has
+ /// ), or when the scene stores none. A scene that is not kept by a
+ /// caller that stores coverage pays nothing for it, not even a field per item.
+ ///
+ public StoredCoverage?[]? StoredFillCoverage { get; private set; }
+
+ ///
+ /// Stores the coverage of every small fill item of this scene (), in the
+ /// order of the items, until the next item would take the bytes past .
+ ///
+ ///
+ ///
+ /// For each band of an item this runs the scan of a replay (
+ /// with the band information and a context of the band, as ExecuteFillOperation creates them) with a handler
+ /// that records every call: the row, the start column, and the coverage values. The emitted coverage depends only on
+ /// the retained geometry of the item and the band, not on the target, the clips, or the brush, which the row handler
+ /// applies after the emission. A replay hands the recorded calls, in their order and with equal values, to the row
+ /// handler of the band (), so it writes the pixels of a replay that scans.
+ ///
+ ///
+ /// The items are independent, so contiguous ranges of them are scanned at the same time, up to the degree of
+ /// parallelism of , each range with its own scratch from the allocator of the
+ /// configuration, which is returned before the method returns. The bound is then applied in the order of the items,
+ /// so the stored items do not depend on the number of threads.
+ ///
+ ///
+ /// Call it once, before the scene is rendered or shared: the stored coverage is read without a lock by every replay.
+ /// The stored coverage is managed memory, held by the scene and released with it.
+ ///
+ ///
+ /// The configuration that gives the allocator of the scratch and the degree of parallelism.
+ /// The most bytes that the stored coverage may take.
+ /// The bytes of the stored coverage, counted as .
+ public long StoreSmallFillCoverage(Configuration configuration, long maxBytes)
+ {
+ List items = [];
+ int width = 0;
+ for (int i = 0; i < this.FillItems.Length; i++)
+ {
+ FillSceneItem? item = this.FillItems[i];
+ if (item is not null && IsSmall(item.Rasterizable))
+ {
+ items.Add(i);
+ width = Math.Max(width, item.Rasterizable.Width);
+ }
+ }
+
+ if (items.Count == 0 || maxBytes <= 0)
+ {
+ return 0;
+ }
+
+ // At least 64 items per range, so that a range pays for its scratch.
+ StoredCoverage[] results = new StoredCoverage[items.Count];
+ int degree = configuration.MaxDegreeOfParallelism > 0 ? configuration.MaxDegreeOfParallelism : Environment.ProcessorCount;
+ int rangeCount = Math.Max(1, Math.Min(degree, items.Count / 64));
+ if (rangeCount == 1)
+ {
+ StoreRange(configuration.MemoryAllocator, this.FillItems, items, results, 0, items.Count, width);
+ }
+ else
+ {
+ _ = Parallel.For(
+ 0,
+ rangeCount,
+ new ParallelOptions { MaxDegreeOfParallelism = rangeCount },
+ range => StoreRange(
+ configuration.MemoryAllocator,
+ this.FillItems,
+ items,
+ results,
+ (int)((long)items.Count * range / rangeCount),
+ (int)((long)items.Count * (range + 1) / rangeCount),
+ width));
+ }
+
+ // The table by item index holds one reference per fill item of the scene.
+ StoredCoverage?[] stored = new StoredCoverage?[this.FillItems.Length];
+ long bytes = 24 + ((long)stored.Length * 8);
+ if (bytes > maxBytes)
+ {
+ return 0;
+ }
+
+ for (int i = 0; i < results.Length; i++)
+ {
+ if (bytes + results[i].Bytes > maxBytes)
+ {
+ break;
+ }
+
+ stored[items[i]] = results[i];
+ bytes += results[i].Bytes;
+ }
+
+ this.StoredFillCoverage = stored;
+ this.StoredCoverageBytes = bytes;
+ return bytes;
+ }
+
+ ///
+ /// Records the stored coverage of a range of items with one scratch.
+ ///
+ /// The allocator of the scratch.
+ /// The fill items of the scene.
+ /// The indices of the small items.
+ /// Receives the stored coverage of each item.
+ /// The first item of the range.
+ /// The item after the range.
+ /// The width of the widest small item.
+ private static void StoreRange(
+ MemoryAllocator allocator,
+ FillSceneItem?[] fillItems,
+ List items,
+ StoredCoverage[] results,
+ int start,
+ int end,
+ int width)
+ {
+ using DefaultRasterizer.WorkerScratch scratch = DefaultRasterizer.CreateWorkerScratch(allocator, width);
+ CoverageRecorder recorder = new(width);
+ for (int i = start; i < end; i++)
+ {
+ results[i] = StoredCoverage.Create(fillItems[items[i]]!.Rasterizable, scratch, ref recorder);
+ }
+ }
+
+ ///
+ /// Returns whether the bands of a fill item hold at most pixels.
+ ///
+ /// The retained geometry of the item.
+ /// for a small item.
+ private static bool IsSmall(DefaultRasterizer.RasterizableGeometry rasterizable)
+ => rasterizable.RowBandCount > 0
+ && (long)rasterizable.Width * rasterizable.RowBandCount * DefaultRasterizer.DefaultTileHeight <= MaxStoredCoverageItemPixels;
+
+ ///
+ /// A coverage handler that records every call in growing buffers.
+ ///
+ internal struct CoverageRecorder : IRasterizerCoverageRowHandler
+ {
+ private int[] calls;
+ private float[] values;
+
+ ///
+ /// Initializes a new instance of the struct.
+ ///
+ /// The widest item; the first value buffer holds one band of it.
+ public CoverageRecorder(int width)
+ {
+ this.calls = new int[96];
+ this.values = new float[Math.Max(64, width * DefaultRasterizer.DefaultTileHeight)];
+ this.CallCount = 0;
+ this.ValueCount = 0;
+ }
+
+ ///
+ /// Gets the number of recorded calls.
+ ///
+ public int CallCount { get; private set; }
+
+ ///
+ /// Gets the number of recorded values.
+ ///
+ public int ValueCount { get; private set; }
+
+ ///
+ /// Forgets the recorded calls and keeps the buffers.
+ ///
+ public void Reset()
+ {
+ this.CallCount = 0;
+ this.ValueCount = 0;
+ }
+
+ ///
+ public void Handle(int y, int startX, Span coverage)
+ {
+ int callIndex = this.CallCount * 3;
+ if (callIndex + 3 > this.calls.Length)
+ {
+ Array.Resize(ref this.calls, this.calls.Length * 2);
+ }
+
+ if (this.ValueCount + coverage.Length > this.values.Length)
+ {
+ Array.Resize(ref this.values, Math.Max(this.values.Length * 2, this.ValueCount + coverage.Length));
+ }
+
+ this.calls[callIndex] = y;
+ this.calls[callIndex + 1] = startX;
+ this.calls[callIndex + 2] = coverage.Length;
+ coverage.CopyTo(this.values.AsSpan(this.ValueCount));
+ this.CallCount++;
+ this.ValueCount += coverage.Length;
+ }
+
+ ///
+ /// Returns a copy of the recorded calls.
+ ///
+ /// Three ints per call.
+ public readonly int[] GetCalls() => this.calls.AsSpan(0, this.CallCount * 3).ToArray();
+
+ ///
+ /// Returns a copy of the recorded values.
+ ///
+ /// The values.
+ public readonly float[] GetValues() => this.values.AsSpan(0, this.ValueCount).ToArray();
+ }
+
+ ///
+ /// The coverage that the scan of each band of one fill item hands to its row handler.
+ ///
+ internal sealed class StoredCoverage
+ {
+ // For band b, the calls from bands[2b] to bands[2b + 2] and their values from bands[2b + 1] on.
+ private readonly int[] bands;
+
+ // Three ints per call: the row, the start column, and the number of values.
+ private readonly int[] calls;
+
+ // The coverage values of the calls, one after the other.
+ private readonly float[] values;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The first call and the first value of each band, and the counts after the last band.
+ /// The row, the start column, and the length of each call.
+ /// The coverage values.
+ private StoredCoverage(int[] bands, int[] calls, float[] values)
+ {
+ this.bands = bands;
+ this.calls = calls;
+ this.values = values;
+
+ // The object (header, method table, three references) and the three arrays (header, method table, length,
+ // and the elements rounded up to 8 bytes), as the 64-bit runtime lays them out.
+ this.Bytes = 40 + ArrayBytes(bands.Length) + ArrayBytes(calls.Length) + ArrayBytes(values.Length);
+ }
+
+ ///
+ /// Gets the managed bytes that the stored coverage holds.
+ ///
+ public long Bytes { get; }
+
+ ///
+ /// Records the calls of the scan of every band of an item.
+ ///
+ /// The retained geometry of the item.
+ /// The scratch of the scan, at least as wide as the item.
+ /// The recorder; its buffers are reused from item to item.
+ /// The stored coverage.
+ public static StoredCoverage Create(
+ DefaultRasterizer.RasterizableGeometry rasterizable,
+ DefaultRasterizer.WorkerScratch scratch,
+ ref CoverageRecorder recorder)
+ {
+ recorder.Reset();
+ int bandCount = rasterizable.RowBandCount;
+ int[] bands = new int[(bandCount + 1) * 2];
+ for (int band = 0; band < bandCount; band++)
+ {
+ bands[band * 2] = recorder.CallCount;
+ bands[(band * 2) + 1] = recorder.ValueCount;
+
+ // The calls of ExecuteFillOperation, for every band: a band without lines of its own can still emit in
+ // aliased mode, from the column crossings of its neighbours.
+ DefaultRasterizer.RasterizableBandInfo bandInfo = rasterizable.GetBandInfo(band);
+ DefaultRasterizer.Context context = scratch.CreateContext(
+ bandInfo.IntersectionRule,
+ bandInfo.RasterizationMode,
+ bandInfo.LineCount);
+
+ DefaultRasterizer.RasterizableItem item = new(rasterizable, band);
+ DefaultRasterizer.ExecuteRasterizableItem(ref context, in item, in bandInfo, scratch.Scanline, ref recorder);
+ }
+
+ bands[bandCount * 2] = recorder.CallCount;
+ bands[(bandCount * 2) + 1] = recorder.ValueCount;
+ return new StoredCoverage(bands, recorder.GetCalls(), recorder.GetValues());
+ }
+
+ ///
+ /// Hands the stored calls of one band to a row handler, in their order, each with a copy of its coverage values in
+ /// the scanline scratch, because a handler may scale the values of the span that it receives.
+ ///
+ /// The struct coverage handler type.
+ /// The local band index.
+ /// The scanline scratch, at least as wide as the item.
+ /// The row handler of the band.
+ public void Replay(int band, Span scanline, ref TRowHandler rowHandler)
+ where TRowHandler : struct, IRasterizerCoverageRowHandler
+ {
+ int call = this.bands[band * 2];
+ int callEnd = this.bands[(band * 2) + 2];
+ int value = this.bands[(band * 2) + 1];
+ for (; call < callEnd; call++)
+ {
+ int length = this.calls[(call * 3) + 2];
+ Span coverage = scanline[..length];
+ this.values.AsSpan(value, length).CopyTo(coverage);
+ value += length;
+ rowHandler.Handle(this.calls[call * 3], this.calls[(call * 3) + 1], coverage);
+ }
+ }
+
+ ///
+ /// Returns the bytes of an array of 4-byte elements on the 64-bit runtime.
+ ///
+ /// The number of elements.
+ /// The bytes.
+ private static long ArrayBytes(int length) => 24 + ((((long)length * 4) + 7) & ~7L);
+ }
+}
diff --git a/src/ImageSharp.Drawing/Processing/Backends/FlushScene.cs b/src/ImageSharp.Drawing/Processing/Backends/FlushScene.cs
index 15aabe368..e08bd766f 100644
--- a/src/ImageSharp.Drawing/Processing/Backends/FlushScene.cs
+++ b/src/ImageSharp.Drawing/Processing/Backends/FlushScene.cs
@@ -1198,9 +1198,14 @@ private static void ProcessPathCommand(
outputRect.X - (int)MathF.Floor(rawOutputBounds.Left),
outputRect.Y - (int)MathF.Floor(rawOutputBounds.Top));
+ // The output rectangle is in canvas coordinates. The write-back fill is placed at the destination offset, so
+ // the rectangle that the item reads moves by the same offset (it is not zero on a canvas of a region).
+ outputRect.Offset(command.DestinationOffset);
+
controlItems[commandIndex] = new SceneControlItem(
new ApplySceneItem(
command.ApplyBarrier.Operation,
+ command.ApplyBarrier.Effect,
outputRect,
outputRect,
command.ApplyBarrier.WriteBackOffset,
diff --git a/src/ImageSharp.Drawing/Processing/Backends/ParallelExecutionHelper.cs b/src/ImageSharp.Drawing/Processing/Backends/ParallelExecutionHelper.cs
index b5386c6ba..607987673 100644
--- a/src/ImageSharp.Drawing/Processing/Backends/ParallelExecutionHelper.cs
+++ b/src/ImageSharp.Drawing/Processing/Backends/ParallelExecutionHelper.cs
@@ -1,6 +1,8 @@
// Copyright (c) Six Labors.
// Licensed under the Six Labors Split License.
+using SixLabors.ImageSharp.Advanced;
+
namespace SixLabors.ImageSharp.Drawing.Processing.Backends;
///
@@ -36,6 +38,23 @@ public static int GetPartitionCount(int maxDegreeOfParallelism, int workItemCoun
public static int GetPartitionCount(int maxDegreeOfParallelism, int workItemCount, int secondaryLimit)
=> Math.Min(GetPartitionLimit(maxDegreeOfParallelism), Math.Min(workItemCount, secondaryLimit));
+ ///
+ /// Computes the number of partitions for row bands of pixels, with at least
+ /// pixels per partition,
+ /// as ParallelRowIterator of ImageSharp plans its steps. A result of 1 means the caller runs the
+ /// bands on the current thread without a parallel loop.
+ ///
+ /// The configured maximum degree of parallelism.
+ /// The number of row bands.
+ /// The number of pixels that the bands cover together.
+ /// The number of partitions to schedule, at least 1.
+ public static int GetPartitionCountForPixels(int maxDegreeOfParallelism, int bandCount, long pixelCount)
+ {
+ long minimum = ParallelExecutionSettings.DefaultMinimumPixelsProcessedPerTask;
+ long pixelLimit = Math.Max(1, (pixelCount + minimum - 1) / minimum);
+ return (int)Math.Max(1, Math.Min(GetPartitionCount(maxDegreeOfParallelism, bandCount), pixelLimit));
+ }
+
///
/// Creates the for a partitioned operation.
///
diff --git a/src/ImageSharp.Drawing/Processing/Backends/StrokePathCommand.cs b/src/ImageSharp.Drawing/Processing/Backends/StrokePathCommand.cs
index c81533c54..8dd95d2e5 100644
--- a/src/ImageSharp.Drawing/Processing/Backends/StrokePathCommand.cs
+++ b/src/ImageSharp.Drawing/Processing/Backends/StrokePathCommand.cs
@@ -120,6 +120,7 @@ internal StrokePathCommand(
this.RasterizerOptions = rasterizerOptions;
this.TargetBounds = targetBounds;
this.DestinationOffset = destinationOffset;
+ this.BrushOffset = destinationOffset;
this.Pen = pen;
this.IsInsideLayer = isInsideLayer;
this.SubPixelOffset = subPixelOffset;
@@ -155,6 +156,13 @@ internal StrokePathCommand(
///
public Point DestinationOffset { get; }
+ ///
+ /// Gets the offset from the coordinates of the canvas to the target, which the batcher bakes into the brush. It is
+ /// except for a glyph, whose destination offset also carries the whole-pixel part of
+ /// the glyph position, while its brush stays in the coordinates of the canvas.
+ ///
+ internal Point BrushOffset { get; init; }
+
///
/// Gets the stroke metadata for this command.
///
diff --git a/src/ImageSharp.Drawing/Processing/DRAWING_CANVAS.md b/src/ImageSharp.Drawing/Processing/DRAWING_CANVAS.md
index 3c8ee3bea..bd133a678 100644
--- a/src/ImageSharp.Drawing/Processing/DRAWING_CANVAS.md
+++ b/src/ImageSharp.Drawing/Processing/DRAWING_CANVAS.md
@@ -248,6 +248,8 @@ This is the architectural center of gravity: normalization that must be identica
After preparation, disposal replay walks the canvas timeline in order. Command-range entries become short-lived retained scenes through `backend.CreateScene(...)`, and those scenes are then rendered through `backend.RenderScene(...)`.
+A retained scene that the caller passed to `RenderScene(...)` is a command inside a range. When it is the only work of its range, the backend renders it directly. On the CPU backend a range that holds such scenes and other work becomes one short-lived scene, which runs the rows of each retained scene inside its own row bands, so every band receives all its work in one pass over the target. Other backends render each retained scene outside every layer as its own pass, between the runs of commands around it.
+
From that point the CPU and GPU paths diverge.
The CPU backend lowers each command batch into a row-oriented retained representation through `FlushScene` during `CreateScene(...)` and then composites into memory during `RenderScene(...)`.
@@ -357,6 +359,14 @@ The child:
The child canvas has local coordinates starting at `(0, 0)`, but its frame bounds resolve to the correct absolute position inside the parent target.
+Everything that a draw on the child places by coordinates moves by the destination offset of the child, so a draw on the child gives the pixels of the same draw on the parent with its coordinates moved by the offset of the region:
+
+- geometry and clips: the backends add the destination offset after the transform of the command
+- brushes: `DrawingCanvasBatcher.PrepareCommand` bakes the destination offset into the brush transform as a translation after the command transform, so gradient brushes and other brushes with spatial parameters follow the geometry; position-independent brushes are unchanged, and `ImageBrush` already anchors at the interest rectangle of the command, which includes the offset
+- apply barriers and layer effects: the rectangle that an apply item reads and writes is moved by the destination offset when the scene is created, so it is absolute like the target bounds
+
+A canvas over a whole frame has a zero destination offset, so these steps change nothing for it.
+
That distinction matters. It means the region API is a coordinate-system convenience, not a request to fork rendering into a totally separate backend pipeline.
## Why `DrawImage(...)` Is Special
diff --git a/src/ImageSharp.Drawing/Processing/DrawingCanvas.Svg.cs b/src/ImageSharp.Drawing/Processing/DrawingCanvas.Svg.cs
new file mode 100644
index 000000000..a055b0311
--- /dev/null
+++ b/src/ImageSharp.Drawing/Processing/DrawingCanvas.Svg.cs
@@ -0,0 +1,56 @@
+// Copyright (c) Six Labors.
+// Licensed under the Six Labors Split License.
+
+using SixLabors.ImageSharp.Drawing.Svg;
+
+namespace SixLabors.ImageSharp.Drawing.Processing;
+
+///
+/// SVG drawing on the canvas.
+///
+public abstract partial class DrawingCanvas
+{
+ ///
+ /// Draws an SVG document at its intrinsic size, with the top left corner of its viewport at .
+ ///
+ ///
+ /// The document renders through the regular fill, stroke, clip, and layer commands of this canvas, under the active
+ /// transform and graphics options. Content outside the viewport of the document is clipped.
+ ///
+ /// The document to draw.
+ /// The top left corner of the viewport, in local canvas coordinates.
+ /// is .
+ ///
+ /// Drawing the document needs more layer pixels at the same time than of its
+ /// load options allows. The canvas is not changed.
+ ///
+ public void DrawSvg(SvgDocument document, PointF origin)
+ {
+ Guard.NotNull(document, nameof(document));
+
+ this.DrawSvg(document, new RectangleF(origin, document.Size));
+ }
+
+ ///
+ /// Draws an SVG document into a destination rectangle. The viewBox of the document, or the rectangle of its
+ /// intrinsic size when it has none, fits the destination following the preserveAspectRatio of the root element.
+ ///
+ ///
+ /// The document renders through the regular fill, stroke, clip, and layer commands of this canvas, under the active
+ /// transform and graphics options. Content outside the destination is clipped. A destination with no area draws
+ /// nothing.
+ ///
+ /// The document to draw.
+ /// The destination rectangle, in local canvas coordinates.
+ /// is .
+ ///
+ /// Drawing the document at this size needs more layer pixels at the same time than
+ /// of its load options allows. The canvas is not changed.
+ ///
+ public void DrawSvg(SvgDocument document, RectangleF destination)
+ {
+ Guard.NotNull(document, nameof(document));
+
+ SvgEmitter.Draw(this, document, destination);
+ }
+}
diff --git a/src/ImageSharp.Drawing/Processing/DrawingCanvas.cs b/src/ImageSharp.Drawing/Processing/DrawingCanvas.cs
index eca7ac0c4..258446061 100644
--- a/src/ImageSharp.Drawing/Processing/DrawingCanvas.cs
+++ b/src/ImageSharp.Drawing/Processing/DrawingCanvas.cs
@@ -507,6 +507,78 @@ public abstract void DrawImage(
///
public abstract void Flush();
+ ///
+ /// Returns the drawing options of the active state, so that high-level drawing such as SVG rendering can compose its
+ /// own transforms with the caller's transform and keep the caller's graphics options.
+ ///
+ ///
+ /// The returned instance belongs to the active state. Callers must not change it. A canvas implementation that does
+ /// not track options returns the defaults.
+ ///
+ /// The drawing options of the active state.
+ internal virtual DrawingOptions GetActiveOptions() => new();
+
+ ///
+ /// Returns the processing configuration of the canvas, so that high-level drawing such as SVG filters can allocate
+ /// from its memory allocator, follow its degree of parallelism, and draw into nested canvases with it.
+ ///
+ ///
+ /// A canvas implementation without a configuration returns .
+ ///
+ /// The configuration.
+ internal virtual Configuration GetConfiguration() => Configuration.Default;
+
+ ///
+ /// Gives the canvas a resource that recorded commands use, such as the pooled pixels that a brush samples, so that
+ /// high-level drawing such as SVG filters can draw from pooled memory although the canvas defers its commands.
+ ///
+ ///
+ /// On success the canvas owns the resource. It disposes the resource after the recorded commands have rendered, when
+ /// the canvas is disposed, or moves it to the retained scene that returns, which disposes it
+ /// with the scene. A canvas implementation that does not track resources returns , and the
+ /// caller keeps the resource.
+ ///
+ /// The resource.
+ /// if the canvas took the resource; otherwise, .
+ internal virtual bool TryTakeOwnership(IDisposable resource) => false;
+
+ ///
+ /// Returns whether a retained scene that records now renders through
+ /// with the pixels that the same commands give when they are drawn here directly, so that high-level drawing such as
+ /// SVG rendering can keep the scene and replay it for a later draw with the same state.
+ ///
+ ///
+ /// That holds for a root canvas on the CPU backend with no open clip and no open layer. A region canvas shares the
+ /// command stream of its root canvas, whose scenes need the bounds of the root target. The clips of a canvas do not
+ /// apply to a retained scene. Inside a layer a retained scene renders under other rules than the commands drawn there.
+ /// A canvas implementation that cannot record scenes returns .
+ ///
+ /// Receives the bounds of the target frame, which a scene recorded for this canvas has.
+ /// if a recorded scene can stand in for the commands; otherwise, .
+ internal virtual bool TryGetSceneTarget(out Rectangle targetBounds)
+ {
+ targetBounds = default;
+ return false;
+ }
+
+ ///
+ /// Records what draws into a new canvas over the target frame of this canvas, and seals it into
+ /// a retained scene without rendering anything into the target.
+ ///
+ ///
+ /// Call it only when returns . The new canvas has the same pixel
+ /// format, backend, and target frame as this canvas, as its state, and no clip. It records
+ /// with , which also builds the scene and allocates its memory and the resources that
+ /// the scene owns. The canvas is released when this method returns. When throws, the recorded
+ /// commands are discarded and their resources are disposed.
+ ///
+ /// The configuration of the recording canvas.
+ /// The drawing options of the recording canvas.
+ /// Draws into the recording canvas.
+ /// The scene, or when recorded nothing.
+ internal virtual DrawingBackendScene? RecordScene(Configuration configuration, DrawingOptions options, Action draw)
+ => throw new NotSupportedException();
+
///
/// Releases the canvas. Disposing the root canvas closes any open layers and clips and
/// replays the recorded command timeline into the target frame; child region canvases
diff --git a/src/ImageSharp.Drawing/Processing/DrawingCanvasBatcher{TPixel}.cs b/src/ImageSharp.Drawing/Processing/DrawingCanvasBatcher{TPixel}.cs
index 62a6b26cc..a2bbc7297 100644
--- a/src/ImageSharp.Drawing/Processing/DrawingCanvasBatcher{TPixel}.cs
+++ b/src/ImageSharp.Drawing/Processing/DrawingCanvasBatcher{TPixel}.cs
@@ -143,7 +143,7 @@ public void AddComposition(in CompositionCommand composition)
}
this.hasBrushTransforms |= composition.Kind is CompositionCommandKind.FillLayer
- && composition.Transform != Matrix4x4.Identity;
+ && (composition.Transform != Matrix4x4.Identity || composition.BrushOffset != Point.Empty);
}
///
@@ -155,7 +155,7 @@ public void AddStrokePath(in StrokePathCommand command)
this.EnsureCommandCapacity(this.commandCount + 1);
this.commands[this.commandCount++] = new StrokePathCompositionSceneCommand(command);
this.hasDashes |= command.Pen.StrokePattern.Length >= 2;
- this.hasBrushTransforms |= command.Transform != Matrix4x4.Identity;
+ this.hasBrushTransforms |= command.Transform != Matrix4x4.Identity || command.BrushOffset != Point.Empty;
}
///
@@ -166,7 +166,7 @@ public void AddStrokeLineSegment(in StrokeLineSegmentCommand command)
{
this.EnsureCommandCapacity(this.commandCount + 1);
this.commands[this.commandCount++] = new LineSegmentCompositionSceneCommand(command);
- this.hasBrushTransforms |= command.Transform != Matrix4x4.Identity;
+ this.hasBrushTransforms |= command.Transform != Matrix4x4.Identity || command.DestinationOffset != Point.Empty;
}
///
@@ -177,7 +177,7 @@ public void AddStrokePolyline(in StrokePolylineCommand command)
{
this.EnsureCommandCapacity(this.commandCount + 1);
this.commands[this.commandCount++] = new PolylineCompositionSceneCommand(command);
- this.hasBrushTransforms |= command.Transform != Matrix4x4.Identity;
+ this.hasBrushTransforms |= command.Transform != Matrix4x4.Identity || command.DestinationOffset != Point.Empty;
}
///
@@ -719,7 +719,13 @@ private static void PrepareCommand(ref CompositionSceneCommand command)
if (command is PathCompositionSceneCommand pathCommand)
{
CompositionCommand composition = pathCommand.Command;
- if (composition.Kind == CompositionCommandKind.FillLayer && composition.Transform != Matrix4x4.Identity)
+ if (composition.Kind != CompositionCommandKind.FillLayer)
+ {
+ return;
+ }
+
+ Matrix4x4 brushTransform = GetBrushTransform(composition.Transform, composition.BrushOffset);
+ if (brushTransform != Matrix4x4.Identity)
{
// The batcher is the brush normalization boundary. Backends still use
// DrawingOptions.Transform for geometry, but brush coordinates are prepared
@@ -728,7 +734,7 @@ private static void PrepareCommand(ref CompositionSceneCommand command)
// glyph command reaches here because its composed transform carries the
// sub-pixel fraction, so the rebuild is skipped when nothing changed.
Brush brush = composition.Brush.Transform(
- composition.Transform,
+ brushTransform,
composition.RasterizerOptions.Interest,
composition.RasterizerOptions.Interest);
@@ -742,14 +748,14 @@ private static void PrepareCommand(ref CompositionSceneCommand command)
composition.TargetBounds,
composition.DestinationOffset,
composition.OwnerLayer,
- composition.SubPixelOffset);
+ composition.SubPixelOffset) with { BrushOffset = composition.BrushOffset };
}
}
}
else if (command is StrokePathCompositionSceneCommand strokePathCommand)
{
StrokePathCommand composition = strokePathCommand.Command;
- Matrix4x4 transform = composition.Transform;
+ Matrix4x4 transform = GetBrushTransform(composition.Transform, composition.BrushOffset);
bool hasTransform = transform != Matrix4x4.Identity;
Brush brush = hasTransform
? composition.Brush.Transform(
@@ -782,13 +788,16 @@ private static void PrepareCommand(ref CompositionSceneCommand command)
composition.Pen,
composition.IsInsideLayer,
composition.OwnerLayer,
- composition.SubPixelOffset);
+ composition.SubPixelOffset)
+ {
+ BrushOffset = composition.BrushOffset,
+ };
}
}
else if (command is LineSegmentCompositionSceneCommand lineSegmentCommand)
{
StrokeLineSegmentCommand composition = lineSegmentCommand.Command;
- Matrix4x4 transform = composition.Transform;
+ Matrix4x4 transform = GetBrushTransform(composition.Transform, composition.DestinationOffset);
if (transform != Matrix4x4.Identity)
{
Brush brush = composition.Brush.Transform(
@@ -818,7 +827,7 @@ private static void PrepareCommand(ref CompositionSceneCommand command)
else if (command is PolylineCompositionSceneCommand polylineCommand)
{
StrokePolylineCommand composition = polylineCommand.Command;
- Matrix4x4 transform = composition.Transform;
+ Matrix4x4 transform = GetBrushTransform(composition.Transform, composition.DestinationOffset);
if (transform != Matrix4x4.Identity)
{
Brush brush = composition.Brush.Transform(
@@ -846,6 +855,30 @@ private static void PrepareCommand(ref CompositionSceneCommand command)
}
}
+ ///
+ /// Returns the transform that maps the brush of a command from canvas coordinates to the target.
+ ///
+ ///
+ /// Backends place the geometry of a command with its transform and then its destination offset,
+ /// and they evaluate brushes at target pixel positions. The offset of the canvas is not zero for a
+ /// canvas made by , so the brush takes the same
+ /// translation as the geometry (the brush offset of the command, which leaves out the glyph position
+ /// that the destination offset of a glyph also carries). A canvas over a whole frame has a zero
+ /// offset and keeps its transform.
+ ///
+ /// The command transform.
+ /// The offset from canvas coordinates to target coordinates.
+ /// The brush transform.
+ private static Matrix4x4 GetBrushTransform(Matrix4x4 transform, Point brushOffset)
+ {
+ if (brushOffset == Point.Empty)
+ {
+ return transform;
+ }
+
+ return transform * Matrix4x4.CreateTranslation(brushOffset.X, brushOffset.Y, 0F);
+ }
+
///
/// Holds the clips and layers that were open in the stream, outermost first.
///
diff --git a/src/ImageSharp.Drawing/Processing/DrawingCanvas{TPixel}.cs b/src/ImageSharp.Drawing/Processing/DrawingCanvas{TPixel}.cs
index e21cbaa5f..2d040d72f 100644
--- a/src/ImageSharp.Drawing/Processing/DrawingCanvas{TPixel}.cs
+++ b/src/ImageSharp.Drawing/Processing/DrawingCanvas{TPixel}.cs
@@ -42,11 +42,12 @@ public sealed class DrawingCanvas : DrawingCanvas
private readonly DrawingCanvasBatcher batcher;
///
- /// Temporary image resources that must stay alive until queued commands are flushed.
+ /// Temporary image resources, and the resources given through ,
+ /// that must stay alive until queued commands are flushed.
/// Shared between the root canvas and its regions: only the root renders the timeline, so
/// region-deferred images must survive region disposal and release with the root.
///
- private readonly List> pendingImageResources;
+ private readonly List pendingImageResources;
///
/// Indicates whether this canvas owns final disposal of the shared batcher.
@@ -265,7 +266,7 @@ private DrawingCanvas(
bool ownsTextCache,
DrawingCanvasState defaultState,
bool ownsBatcher,
- List> pendingImageResources)
+ List pendingImageResources)
{
Guard.NotNull(configuration, nameof(configuration));
Guard.NotNull(backend, nameof(backend));
@@ -329,18 +330,14 @@ public override int Save(DrawingOptions options)
this.EnsureNotDisposed();
Guard.NotNull(options, nameof(options));
- // Reuse Save() to push the snapshot frame, then swap the top frame for one carrying
- // the caller's options while keeping clip, bounds and layer linkage identical.
- _ = this.Save();
+ // Push the frame that Save() would push, with the caller's options in place of the current
+ // ones: the same clip, bounds and layer linkage, and no layer to close on restore.
DrawingCanvasState current = this.ResolveState();
- DrawingCanvasState state = new(options, current.ClipState, current.TargetBounds, current.DestinationOffset)
+ this.savedStates.Push(new DrawingCanvasState(options, current.ClipState, current.TargetBounds, current.DestinationOffset)
{
- IsLayer = current.IsLayer,
- Layer = current.Layer,
- };
+ Layer = current.Layer
+ });
- _ = this.savedStates.Pop();
- this.savedStates.Push(state);
return this.savedStates.Count;
}
@@ -2043,6 +2040,76 @@ private static GraphicsOptions CreateTextGroupOptions(
return result;
}
+ ///
+ internal override DrawingOptions GetActiveOptions() => this.ResolveState().Options;
+
+ ///
+ internal override Configuration GetConfiguration() => this.configuration;
+
+ ///
+ internal override bool TryTakeOwnership(IDisposable resource)
+ {
+ this.EnsureNotDisposed();
+
+ // The resource joins the deferred image resources: Dispose releases it after the timeline has rendered, and
+ // CreateScene moves it to the scene that holds the commands recorded so far.
+ this.pendingImageResources.Add(resource);
+ return true;
+ }
+
+ ///
+ internal override bool TryGetSceneTarget(out Rectangle targetBounds)
+ {
+ // Only the CPU backend has been shown to replay a retained scene with the pixels of the commands drawn directly.
+ // A region does not own the stream, and an open clip or layer changes how a scene renders (see the base remarks).
+ if (!this.isDisposed
+ && this.ownsBatcher
+ && this.backend is DefaultDrawingBackend
+ && this.batcher.OpenLayerCount == 0
+ && this.ResolveState().ClipState.Count == 0)
+ {
+ targetBounds = this.targetFrame.Bounds;
+ return true;
+ }
+
+ targetBounds = default;
+ return false;
+ }
+
+ ///
+ internal override DrawingBackendScene? RecordScene(Configuration configuration, DrawingOptions options, Action draw)
+ {
+ // The recording canvas is a root canvas over the same frame, so its scene has the bounds that RenderScene of this
+ // canvas requires. It never renders: the scene takes its commands and resources, and the release below discards
+ // whatever a failed draw left behind.
+ DrawingCanvas recorder = new(configuration, options, this.backend, this.targetFrame);
+ try
+ {
+ draw(recorder);
+ return recorder.batcher.HasRecordedWork ? recorder.CreateScene() : null;
+ }
+ finally
+ {
+ recorder.ReleaseWithoutRendering();
+ }
+ }
+
+ ///
+ /// Releases a root canvas without rendering its recorded commands: the commands are dropped, and the resources that they
+ /// would have used are disposed.
+ ///
+ private void ReleaseWithoutRendering()
+ {
+ this.batcher.ClearCommandBatch();
+ this.DisposePendingImageResources();
+ if (this.ownsTextCache)
+ {
+ this.textCache.Clear();
+ }
+
+ this.isDisposed = true;
+ }
+
///
/// Resolves the currently active drawing state.
///
@@ -2181,17 +2248,31 @@ private void RenderRecordedTimeline()
}
///
- /// Renders one prepared command batch. A retained scene outside every layer renders as its own
- /// pass, and each run of commands between such scenes renders as one backend scene.
+ /// Renders one prepared command batch. On the CPU backend a batch whose retained scenes come with other work renders
+ /// as one backend scene. Otherwise a retained scene outside every layer renders as its own pass, and each run of
+ /// commands between such scenes renders as one backend scene.
///
///
- /// A retained scene outside every layer needs no work in the scene of its run, so it renders
- /// directly, with no scene to create for it.
+ ///
+ /// A retained scene outside every layer needs no work in the scene of its run, so a batch whose only work is that
+ /// scene renders it directly, with no scene to create for it.
+ ///
+ ///
+ /// A pass over the target for each retained scene and for each run between them reads and writes every touched row
+ /// band once per pass. The CPU backend can instead run the rows of each retained scene inside the row bands of one
+ /// backend scene for the whole batch (FlushScene.ProcessSceneCommand, the path of a retained scene inside a
+ /// layer and of ), so each band takes all its work while it is in the processor cache. Every
+ /// pixel receives the same operations in the same order as in the separate passes. A canvas that draws the 40 icon
+ /// documents of the SVG benchmarks at 1000 pixels, each after a clear and each from a retained scene, took a median of
+ /// 43 ms in separate passes and 20 ms in one pass (default threads; one process for each). Other backends keep the separate
+ /// passes: their merged path was not measured.
+ ///
///
/// The command batch to render.
private void RenderCommandBatch(DrawingCommandBatch commandBatch)
{
- if (!commandBatch.HasScenes)
+ if (!commandBatch.HasScenes
+ || (this.backend is DefaultDrawingBackend && !commandBatch.HasOnlyOneRootScene()))
{
this.RenderCommandRun(commandBatch);
return;
@@ -2492,6 +2573,8 @@ private CompositionSceneCommand CreateTextCompositionCommand(
// Clipping is resolved from the ordered begin/end-clip stream, which the canvas anchors
// at the state's destination offset. Glyph render locations only move the glyph geometry;
// they never re-anchor the clip stack, so no per-operation clip translation is required.
+ // The brush stays in the coordinates of the canvas: it moves by the destination offset of the state, not by the
+ // glyph position that the destination offset of the command also carries.
if (pen is null)
{
return new PathCompositionSceneCommand(
@@ -2503,7 +2586,7 @@ private CompositionSceneCommand CreateTextCompositionCommand(
state.TargetBounds,
destinationOffset,
state.Layer,
- subPixelOffset));
+ subPixelOffset) with { BrushOffset = state.DestinationOffset });
}
return new StrokePathCompositionSceneCommand(
@@ -2517,7 +2600,10 @@ private CompositionSceneCommand CreateTextCompositionCommand(
pen,
state.Layer is not null,
state.Layer,
- subPixelOffset));
+ subPixelOffset)
+ {
+ BrushOffset = state.DestinationOffset,
+ });
}
///
diff --git a/src/ImageSharp.Drawing/Processing/GradientBrush.cs b/src/ImageSharp.Drawing/Processing/GradientBrush.cs
index e1c5488bb..f23afb2f7 100644
--- a/src/ImageSharp.Drawing/Processing/GradientBrush.cs
+++ b/src/ImageSharp.Drawing/Processing/GradientBrush.cs
@@ -2,6 +2,7 @@
// Licensed under the Six Labors Split License.
using System.Numerics;
+using System.Runtime.CompilerServices;
namespace SixLabors.ImageSharp.Drawing.Processing;
@@ -156,6 +157,23 @@ internal abstract class GradientBrushRenderer : BrushRenderer<
{
private static readonly TPixel Transparent = Color.Transparent.ToPixel();
+ ///
+ /// Whether packs a row of interpolated vectors with one bulk conversion instead of one
+ /// per pixel. It holds for with both
+ /// encoders of ImageSharp 5.0.0-alpha.0.38. The per-pixel conversion scales by 255, adds one half, clamps to
+ /// [0, 255] (NaN to 0), and truncates. The bulk conversion clamps to [0, 1] (NaN to 0), scales by 255, adds
+ /// one half, truncates, and saturates. Both give the same byte for every float, NaN and infinities included.
+ /// The associated encoder first divides the color by its alpha with the same lane-wise operator
+ /// (UnassociateOperator) in both conversions; a lane-wise division and clamp give the same result at
+ /// every vector width.
+ ///
+ private static readonly bool EncodesInBulk = typeof(TPixel) == typeof(Rgba32);
+
+ ///
+ /// Whether the encoder takes associated colors, so the bulk conversion must divide by alpha.
+ ///
+ private static readonly bool EncodesAssociated = typeof(TEncoder) == typeof(AssociatedGradientPixelEncoder);
+
private readonly GradientColorStop[] colorStops;
private readonly GradientRepetitionMode repetitionMode;
@@ -208,6 +226,19 @@ protected GradientBrushRenderer(
}
}
+ ///
+ /// Maps a position on the complete gradient into the range that one repetition mode samples.
+ ///
+ private interface IRepetitionMode
+ {
+ ///
+ /// Maps the position in place.
+ ///
+ /// The position, which is not NaN.
+ /// when the pixel stays transparent.
+ public static abstract bool TryWrap(ref float position);
+ }
+
///
/// Gets a value indicating whether the brush has a gradient transform, so samples must be
/// mapped through before the gradient is evaluated.
@@ -226,82 +257,59 @@ protected GradientBrushRenderer(
/// The y-coordinate of the pixel in device space.
/// The blended gradient color converted to .
internal TPixel this[int x, int y]
+
+ // Evaluate at pixel centers so gradient sampling lines up with the
+ // rasterized coverage positions.
+ => this.ColorAt(this.PositionOnGradient(x + 0.5f, y + 0.5f));
+
+ ///
+ public override void Apply(
+ Span destinationRow,
+ ReadOnlySpan scanline,
+ int x,
+ int y,
+ BrushWorkspace workspace)
{
- get
- {
- // Evaluate at pixel centers so gradient sampling lines up with the
- // rasterized coverage positions.
- float fx = x + 0.5f;
- float fy = y + 0.5f;
+ Span overlays = workspace.GetOverlays(scanline.Length);
- // NaN signals that the parameterization is undefined at this point
- // (e.g. outside the valid branch of a conic); such pixels stay transparent.
- float positionOnCompleteGradient = this.PositionOnGradient(fx, fy);
- if (float.IsNaN(positionOnCompleteGradient))
- {
- return Transparent;
- }
+ // The positions of the whole row come first, from one call, so the per-pixel work below
+ // has no virtual call. The amount buffer is free here: this renderer does not read it otherwise.
+ Span positions = workspace.GetAmounts(scanline.Length);
+ this.PositionsOnGradient(x, y + 0.5f, positions);
+ if (EncodesInBulk)
+ {
+ // The first blend scratch row is free until the blend below fills it.
+ Span colors = workspace.GetBlendScratch(scanline.Length, 3)[..scanline.Length];
switch (this.repetitionMode)
{
case GradientRepetitionMode.Repeat:
- // The floor subtraction moves every position into [0, 1], so the pattern also
- // repeats before the start point. The remainder operator keeps the sign of a
- // negative position, and the brush then pads that position with the first stop.
- positionOnCompleteGradient -= MathF.Floor(positionOnCompleteGradient);
+ this.InterpolatedColorsAt(positions, colors);
break;
case GradientRepetitionMode.Reflect:
- // Reflection is symmetric about the start point, so the magnitude gives the
- // same color as the signed position. Every second period folds back on itself,
- // so alternate repetitions run the stops in reverse order.
- positionOnCompleteGradient = MathF.Abs(positionOnCompleteGradient) % 2;
- if (positionOnCompleteGradient > 1)
- {
- positionOnCompleteGradient = 2 - positionOnCompleteGradient;
- }
-
+ this.InterpolatedColorsAt(positions, colors);
break;
case GradientRepetitionMode.DontFill:
- if (positionOnCompleteGradient is > 1 or < 0)
- {
- return Transparent;
- }
-
+ this.InterpolatedColorsAt(positions, colors);
break;
case GradientRepetitionMode.None:
default:
- // do nothing. The following could be done, but is not necessary:
- // onLocalGradient = Math.Min(0, Math.Max(1, onLocalGradient));
+ this.InterpolatedColorsAt(positions, colors);
break;
}
- (GradientColorStop from, GradientColorStop to) = this.GetGradientSegment(positionOnCompleteGradient);
-
- if (from.Color == to.Color)
+ if (EncodesAssociated)
{
- return TEncoder.Encode(from.Color);
+ PixelOperations.Instance.FromAssociatedScaledVector4Destructive(this.Configuration, colors, overlays);
+ }
+ else
+ {
+ PixelOperations.Instance.FromUnassociatedScaledVector4Destructive(this.Configuration, colors, overlays);
}
-
- float onLocalGradient = (positionOnCompleteGradient - from.Ratio) / (to.Ratio - from.Ratio);
-
- return TEncoder.Encode(Vector4.Lerp(from.Color, to.Color, onLocalGradient));
}
- }
-
- ///
- public override void Apply(
- Span destinationRow,
- ReadOnlySpan scanline,
- int x,
- int y,
- BrushWorkspace workspace)
- {
- Span overlays = workspace.GetOverlays(scanline.Length);
-
- // TODO: Remove bounds checks.
- for (int i = 0; i < scanline.Length; i++)
+ else
{
- overlays[i] = this[x + i, y];
+ this.ColorsAt(positions, overlays);
}
this.Blender.BlendWithCoverage(
@@ -314,6 +322,31 @@ public override void Apply(
workspace.GetBlendScratch(scanline.Length, 3));
}
+ ///
+ /// Converts a row of gradient positions to pixels.
+ ///
+ /// The positions on the complete gradient.
+ /// The destination pixels, of the same length as .
+ private void ColorsAt(ReadOnlySpan positions, Span overlays)
+ {
+ switch (this.repetitionMode)
+ {
+ case GradientRepetitionMode.Repeat:
+ this.ColorsAt(positions, overlays);
+ break;
+ case GradientRepetitionMode.Reflect:
+ this.ColorsAt(positions, overlays);
+ break;
+ case GradientRepetitionMode.DontFill:
+ this.ColorsAt(positions, overlays);
+ break;
+ case GradientRepetitionMode.None:
+ default:
+ this.ColorsAt(positions, overlays);
+ break;
+ }
+ }
+
///
/// Calculates the position on the gradient for a given point.
/// This method is abstract as its content depends on the shape of the gradient.
@@ -329,33 +362,190 @@ public override void Apply(
protected abstract float PositionOnGradient(float x, float y);
///
- /// Finds the pair of adjacent color stops bracketing the given gradient position.
- /// Positions before the first stop return the first stop twice; positions after the
- /// last stop return the last stop twice, which yields the stable edge colors used
- /// by .
+ /// Calculates the positions on the gradient for the pixel centers of one row segment.
+ /// Element i must equal PositionOnGradient((x + i) + 0.5F, y) bit for bit; a derived
+ /// renderer overrides this only to remove the virtual call and the invariant branches per pixel.
///
- /// The position on the gradient, after repetition handling.
- /// The bracketing stops; equal when the position lies outside the stop range.
- private (GradientColorStop From, GradientColorStop To) GetGradientSegment(float positionOnCompleteGradient)
+ /// The device x-coordinate of the first pixel.
+ /// The device y-coordinate of the pixel centers of the row.
+ /// The destination for one position per pixel.
+ protected virtual void PositionsOnGradient(int x, float y, Span positions)
{
- // Stop counts are tiny, so a linear scan over the sorted stops beats a binary search.
- GradientColorStop localGradientFrom = this.colorStops[0];
- GradientColorStop localGradientTo = default;
+ for (int i = 0; i < positions.Length; i++)
+ {
+ positions[i] = this.PositionOnGradient((x + i) + 0.5F, y);
+ }
+ }
- foreach (GradientColorStop colorStop in this.colorStops)
+ ///
+ /// Converts a row of gradient positions to pixels with one repetition mode.
+ ///
+ /// The repetition mode.
+ /// The positions on the complete gradient.
+ /// The destination pixels, of the same length as .
+ private void ColorsAt(ReadOnlySpan positions, Span overlays)
+ where TMode : struct, IRepetitionMode
+ {
+ for (int i = 0; i < positions.Length; i++)
{
- localGradientTo = colorStop;
+ float position = positions[i];
- if (colorStop.Ratio > positionOnCompleteGradient)
+ // NaN signals that the parameterization is undefined at this point
+ // (e.g. outside the valid branch of a conic); such pixels stay transparent.
+ if (float.IsNaN(position) || !TMode.TryWrap(ref position))
{
- // we're done here, so break it!
- break;
+ overlays[i] = Transparent;
+ continue;
+ }
+
+ overlays[i] = this.InterpolateAt(position);
+ }
+ }
+
+ ///
+ /// Converts a row of gradient positions to the interpolated vectors that
+ /// would encode, one pixel at a time, into .
+ ///
+ /// The repetition mode.
+ /// The positions on the complete gradient.
+ /// The destination vectors, of the same length as .
+ private void InterpolatedColorsAt(ReadOnlySpan positions, Span colors)
+ where TMode : struct, IRepetitionMode
+ {
+ for (int i = 0; i < positions.Length; i++)
+ {
+ float position = positions[i];
+
+ // A transparent pixel is zero in every channel. Both encoders give that pixel for the zero vector.
+ if (float.IsNaN(position) || !TMode.TryWrap(ref position))
+ {
+ colors[i] = Vector4.Zero;
+ continue;
+ }
+
+ colors[i] = this.InterpolatedColorAt(position);
+ }
+ }
+
+ ///
+ /// Gets the pixel for one position on the complete gradient.
+ ///
+ /// The position, before repetition handling.
+ /// The gradient color converted to .
+ private TPixel ColorAt(float positionOnCompleteGradient)
+ {
+ if (float.IsNaN(positionOnCompleteGradient))
+ {
+ return Transparent;
+ }
+
+ bool inside = this.repetitionMode switch
+ {
+ GradientRepetitionMode.Repeat => RepeatMode.TryWrap(ref positionOnCompleteGradient),
+ GradientRepetitionMode.Reflect => ReflectMode.TryWrap(ref positionOnCompleteGradient),
+ GradientRepetitionMode.DontFill => DontFillMode.TryWrap(ref positionOnCompleteGradient),
+ _ => NoneMode.TryWrap(ref positionOnCompleteGradient),
+ };
+
+ return inside ? this.InterpolateAt(positionOnCompleteGradient) : Transparent;
+ }
+
+ ///
+ /// Interpolates the color stops at a position after repetition handling and encodes the result.
+ ///
+ /// The position on the gradient, after repetition handling.
+ /// The gradient color converted to .
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ private TPixel InterpolateAt(float position) => TEncoder.Encode(this.InterpolatedColorAt(position));
+
+ ///
+ /// Interpolates the color stops at a position after repetition handling.
+ ///
+ /// The position on the gradient, after repetition handling.
+ ///
+ /// The color in the alpha representation of the brush, which the encoder converts to .
+ ///
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ private Vector4 InterpolatedColorAt(float position)
+ {
+ // Find the bracketing stops: "to" is the first stop whose ratio is greater than the
+ // position, "from" the stop before it. Positions before the first stop return the first
+ // stop twice; positions after the last stop (or a NaN position from Repeat with an
+ // infinite input) return the last stop twice, which yields the stable edge colors used
+ // by GradientRepetitionMode.None. Stop counts are tiny, so a linear scan over the sorted
+ // stops beats a binary search.
+ GradientColorStop[] stops = this.colorStops;
+ int next = 0;
+ while (next < stops.Length && !(stops[next].Ratio > position))
+ {
+ next++;
+ }
+
+ ref GradientColorStop from = ref stops[next == 0 ? 0 : next - 1];
+ ref GradientColorStop to = ref stops[next == stops.Length ? next - 1 : next];
+
+ if (from.Color == to.Color)
+ {
+ return from.Color;
+ }
+
+ float onLocalGradient = (position - from.Ratio) / (to.Ratio - from.Ratio);
+ return Vector4.Lerp(from.Color, to.Color, onLocalGradient);
+ }
+
+ ///
+ /// : positions outside the stops take the edge colors.
+ ///
+ private readonly struct NoneMode : IRepetitionMode
+ {
+ ///
+ public static bool TryWrap(ref float position) => true;
+ }
+
+ ///
+ /// .
+ ///
+ private readonly struct RepeatMode : IRepetitionMode
+ {
+ ///
+ public static bool TryWrap(ref float position)
+ {
+ // The floor subtraction moves every position into [0, 1], so the pattern also
+ // repeats before the start point. The remainder operator keeps the sign of a
+ // negative position, and the brush then pads that position with the first stop.
+ position -= MathF.Floor(position);
+ return true;
+ }
+ }
+
+ ///
+ /// .
+ ///
+ private readonly struct ReflectMode : IRepetitionMode
+ {
+ ///
+ public static bool TryWrap(ref float position)
+ {
+ // Reflection is symmetric about the start point, so the magnitude gives the
+ // same color as the signed position. Every second period folds back on itself,
+ // so alternate repetitions run the stops in reverse order.
+ position = MathF.Abs(position) % 2;
+ if (position > 1)
+ {
+ position = 2 - position;
}
- localGradientFrom = localGradientTo;
+ return true;
}
+ }
- return (localGradientFrom, localGradientTo);
+ ///
+ /// : positions outside [0, 1] stay transparent.
+ ///
+ private readonly struct DontFillMode : IRepetitionMode
+ {
+ ///
+ public static bool TryWrap(ref float position) => position is <= 1 and >= 0;
}
///
diff --git a/src/ImageSharp.Drawing/Processing/ImageBrush.cs b/src/ImageSharp.Drawing/Processing/ImageBrush.cs
index 9ef93e5b4..a765e2113 100644
--- a/src/ImageSharp.Drawing/Processing/ImageBrush.cs
+++ b/src/ImageSharp.Drawing/Processing/ImageBrush.cs
@@ -5,6 +5,9 @@
using System.Diagnostics.CodeAnalysis;
using System.Numerics;
using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Runtime.Intrinsics;
+using SixLabors.ImageSharp.Memory;
namespace SixLabors.ImageSharp.Drawing.Processing;
@@ -288,7 +291,17 @@ public override BrushRenderer CreateRenderer(
{
if (this.UntypedImage is Image image)
{
- return new ImageBrushRenderer(configuration, options, canvasWidth, image, region, this.SourceRegion, this.Offset, this.WrapX, this.WrapY);
+ return new ImageBrushRenderer(
+ configuration,
+ options,
+ canvasWidth,
+ image.Frames.RootFrame.PixelBuffer,
+ image.Bounds,
+ region,
+ this.SourceRegion,
+ this.Offset,
+ this.WrapX,
+ this.WrapY);
}
// This will never be hit as the brush is always normalized by the drawing canvas
@@ -297,6 +310,42 @@ public override BrushRenderer CreateRenderer(
return null;
}
+ ///
+ /// Creates the renderer that an of an image with the pixels of a buffer, its whole
+ /// bounds as the source region, an offset, and on both axes would create, without the
+ /// image. The backend writes the processed pixels of an apply barrier back with it.
+ ///
+ /// The pixel format.
+ /// The configuration instance to use when performing operations.
+ /// The graphics options.
+ /// The canvas width for the current render pass.
+ /// The source pixels. The buffer must stay alive while the renderer is used.
+ /// The region of the target that the brush draws to.
+ /// An offset to apply to the texture while drawing.
+ /// The renderer.
+ internal static BrushRenderer CreateRenderer(
+ Configuration configuration,
+ GraphicsOptions options,
+ int canvasWidth,
+ Buffer2D pixels,
+ RectangleF region,
+ Point offset)
+ where TPixel : unmanaged, IPixel
+ {
+ Rectangle bounds = new(0, 0, pixels.Width, pixels.Height);
+ return new ImageBrushRenderer(
+ configuration,
+ options,
+ canvasWidth,
+ pixels,
+ bounds,
+ region,
+ bounds,
+ offset,
+ WrapMode.Repeat,
+ WrapMode.Repeat);
+ }
+
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
private static void ThrowIfInvalidImagePixelFormat()
@@ -309,7 +358,56 @@ private static void ThrowIfInvalidImagePixelFormat()
private sealed class ImageBrushRenderer : BrushRenderer
where TPixel : unmanaged, IPixel
{
- private readonly ImageFrame sourceFrame;
+ ///
+ /// The bit pattern of a coverage value of exactly one. Comparing the bits finds full coverage
+ /// with the vectorized integer search of the runtime.
+ ///
+ private const int FullCoverageBits = 0x3F800000;
+
+ ///
+ /// The shortest row for which the renderer looks for full-coverage runs. Shorter rows go to the
+ /// blender whole, because the search and the extra blender calls would cost more than they save.
+ ///
+ private const int MinimumSplitLength = 32;
+
+ ///
+ /// The shortest run of full coverage that the renderer copies directly.
+ ///
+ private const int MinimumCopyLength = 16;
+
+ ///
+ /// The number of pixels that the vector loops of process together.
+ /// See for why the renderer must split rows at multiples of it.
+ ///
+ private static readonly int BlendGroup = Vector512.IsHardwareAccelerated ? 4 : Vector256.IsHardwareAccelerated ? 2 : 1;
+
+ ///
+ /// Whether stores each color channel as an unsigned integer of 8 bits with straight
+ /// alpha or no alpha, which the proof in needs.
+ ///
+ private static readonly bool Is8BitStraightAlphaFormat =
+ typeof(TPixel) == typeof(Rgba32)
+ || typeof(TPixel) == typeof(Bgra32)
+ || typeof(TPixel) == typeof(Argb32)
+ || typeof(TPixel) == typeof(Abgr32)
+ || typeof(TPixel) == typeof(Rgb24)
+ || typeof(TPixel) == typeof(Bgr24);
+
+ ///
+ /// The pixel of zeros, which source composition at full coverage writes for a transparent source pixel.
+ ///
+ private static readonly TPixel TransparentPixel = TPixel.FromScaledVector4(Vector4.Zero);
+
+ ///
+ /// The pixels of the source image.
+ ///
+ private readonly Buffer2D sourcePixels;
+
+ ///
+ /// Whether the renderer copies the source pixels of full-coverage runs instead of blending them; see
+ /// .
+ ///
+ private readonly bool copyFullCoverage;
///
/// The region of the source image we will be using to draw from.
@@ -342,7 +440,8 @@ private sealed class ImageBrushRenderer : BrushRenderer
/// The configuration instance to use when performing operations.
/// The graphics options.
/// The canvas width for the current render pass.
- /// The image.
+ /// The pixels of the source image.
+ /// The bounds of the source image.
/// The region of the target image we will be drawing to.
/// The region of the source image we will be using to source pixels to draw from.
/// An offset to apply to the texture while drawing.
@@ -352,7 +451,8 @@ public ImageBrushRenderer(
Configuration configuration,
GraphicsOptions options,
int canvasWidth,
- Image image,
+ Buffer2D sourcePixels,
+ Rectangle sourceBounds,
RectangleF targetRegion,
RectangleF sourceRegion,
Point offset,
@@ -360,13 +460,19 @@ public ImageBrushRenderer(
WrapMode wrapY)
: base(configuration, options, canvasWidth)
{
- this.sourceFrame = image.Frames.RootFrame;
- this.sourceRegion = Rectangle.Intersect(image.Bounds, (Rectangle)sourceRegion);
+ this.sourcePixels = sourcePixels;
+ this.sourceRegion = Rectangle.Intersect(sourceBounds, (Rectangle)sourceRegion);
this.wrapX = wrapX;
this.wrapY = wrapY;
this.offsetY = (int)MathF.Floor(targetRegion.Top) + offset.Y;
this.offsetX = (int)MathF.Floor(targetRegion.Left) + offset.X;
+
+ // Normal source composition at full opacity is the write-back of an apply barrier, and of any image drawn
+ // with Src. The blender is compared with the shared instance, as the solid brush does.
+ this.copyFullCoverage = Is8BitStraightAlphaFormat
+ && options.BlendPercentage == 1F
+ && ReferenceEquals(this.Blender, PixelBlenders.NormalSrc);
}
///
@@ -383,7 +489,7 @@ public ImageBrushRenderer(
if (TryWrap(x - this.offsetX, this.sourceRegion.Width, this.sourceRegion.X, this.wrapX, out int srcX)
&& TryWrap(y - this.offsetY, this.sourceRegion.Height, this.sourceRegion.Y, this.wrapY, out int srcY))
{
- return this.sourceFrame[srcX, srcY];
+ return this.sourcePixels[srcX, srcY];
}
// None wrap mode outside the source region samples as transparent.
@@ -405,9 +511,54 @@ public override void Apply(
int baseX = x - this.offsetX;
bool rowInRange = TryWrap(y - this.offsetY, this.sourceRegion.Height, this.sourceRegion.Y, this.wrapY, out int sourceY);
Span sourceRow = rowInRange
- ? this.sourceFrame.PixelBuffer.DangerousGetRowSpan(sourceY)
+ ? this.sourcePixels.DangerousGetRowSpan(sourceY)
: default;
+ if (rowInRange && baseX >= 0 && baseX <= this.sourceRegion.Width - scanline.Length)
+ {
+ // Every coordinate of the span lies inside the region, where each wrap mode maps a coordinate c to
+ // c + regionStart (TryWrap), so the span reads one run of the source row.
+ scanline.CopyTo(coverageSpan);
+ sourceRow.Slice(baseX + this.sourceRegion.X, scanline.Length).CopyTo(overlaySpan);
+ }
+ else
+ {
+ this.GatherWrapped(sourceRow, rowInRange, baseX, scanline, coverageSpan, overlaySpan);
+ }
+
+ if (this.copyFullCoverage && destinationRow.Length >= MinimumSplitLength)
+ {
+ this.ApplySplit(destinationRow, overlaySpan, coverageSpan, workspace);
+ return;
+ }
+
+ this.Blender.BlendWithCoverage(
+ this.Configuration,
+ destinationRow,
+ destinationRow,
+ overlaySpan,
+ this.Options.BlendPercentage,
+ coverageSpan,
+ workspace.GetBlendScratch(scanline.Length, 3));
+ }
+
+ ///
+ /// Fills the coverage and the source pixels of a span pixel by pixel, through the wrap modes.
+ ///
+ /// The source row, or an empty span when the row is outside the region.
+ /// Whether the row maps into the source region.
+ /// The first coordinate of the span relative to the brush origin.
+ /// The coverage of the span.
+ /// Receives the coverage, 0 where nothing is sampled.
+ /// Receives the source pixels.
+ private void GatherWrapped(
+ Span sourceRow,
+ bool rowInRange,
+ int baseX,
+ ReadOnlySpan