diff --git a/src/ImageSharp.Drawing.WebGPU/Shaders/WgslSource/path_lowering.wgsl b/src/ImageSharp.Drawing.WebGPU/Shaders/WgslSource/path_lowering.wgsl
index 97206ce82..fbe824844 100644
--- a/src/ImageSharp.Drawing.WebGPU/Shaders/WgslSource/path_lowering.wgsl
+++ b/src/ImageSharp.Drawing.WebGPU/Shaders/WgslSource/path_lowering.wgsl
@@ -87,7 +87,7 @@ fn stroke_normalize_positive_angle(angle: f32) -> f32 {
// Port of the CPU stroker's GetArcSubdivisionCount (round join and cap tessellation): returns the
// number of interior vertices needed to keep the arc's chordal error within the arc detail scale.
-fn stroke_arc_subdivision_count(radius: f32, sweep: f32, arc_detail_scale: f32) -> u32 {
+fn stroke_arc_subdivision_count(radius: f32, sweep: f32, arc_detail_scale: f32, limit: u32) -> u32 {
let safe_radius = max(radius, TANGENT_THRESH);
let safe_scale = max(arc_detail_scale, 0.01);
let ratio = clamp(safe_radius / (safe_radius + (0.125 / safe_scale)), -1.0, 1.0);
@@ -97,7 +97,7 @@ fn stroke_arc_subdivision_count(radius: f32, sweep: f32, arc_detail_scale: f32)
}
// The f32 radius and acos can give more vertices than the CPU count. The CPU line estimate
// allows the arc limit, so the count is clamped to it.
- return min(u32(max(sweep / theta, 0.0)), arc_limit);
+ return min(u32(max(sweep / theta, 0.0)), limit);
}
// Port of the CPU stroker's AppendDirectedArcContour (round caps): steps through the positive
@@ -118,7 +118,7 @@ fn stroke_chain_arc(
// must rotate the start offset; absolute angles of the offsets are not computable here.
let cross_ft = (from_offset.x * to_offset.y) - (from_offset.y * to_offset.x);
let sweep = stroke_normalize_positive_angle(atan2(cross_ft, dot(from_offset, to_offset)));
- let n = stroke_arc_subdivision_count(radius, sweep, arc_detail_scale);
+ let n = stroke_arc_subdivision_count(radius, sweep, arc_detail_scale, arc_limit);
let step = sweep / f32(n + 1u);
let rot_c = cos(step);
let rot_s = sin(step);
@@ -144,7 +144,7 @@ fn stroke_calc_arc(
let cross_oo = (o1.x * o2.y) - (o1.y * o2.x);
let sweep = stroke_normalize_positive_angle(atan2(cross_oo, dot(o1, o2)));
stroke_chain_point(path_ix, last, v1 + o1, transform);
- let n = stroke_arc_subdivision_count(half_width, sweep, arc_detail_scale);
+ let n = stroke_arc_subdivision_count(half_width, sweep, arc_detail_scale, arc_limit);
let step = sweep / f32(n + 1u);
let rot_c = cos(step);
let rot_s = sin(step);
@@ -657,21 +657,45 @@ fn main(
if is_open {
// Start cap. The marker carries the first segment's tangent; the CPU stroker's
// caps chain from cap0 to cap1 so they splice into the offset edges.
- var tangent = pts.p1 - pts.p0;
- if dot(tangent, tangent) < TANGENT_THRESH * TANGENT_THRESH {
- tangent = vec2(TANGENT_THRESH, 0.);
+ let tangent = pts.p1 - pts.p0;
+ let start_cap = (style_flags & STYLE_FLAGS_START_CAP_MASK) >> 2u;
+ if all(tangent == vec2f(0.)) {
+ // Equal marker points denote a zero-length segment. Emit its entire
+ // outline here because the body has no direction and emits no lines.
+ if start_cap == STYLE_FLAGS_CAP_ROUND {
+ // Use one full turn as PolygonClipper does. Two cap budgets
+ // cover the full circle because each includes its final edge.
+ let full_turn = 6.283185307179586;
+ let count = max(4u, stroke_arc_subdivision_count(half_width, full_turn, arc_detail_scale, 2u * (arc_limit + 1u)));
+ let step = full_turn / f32(count);
+ let first = pts.p0 + vec2f(half_width, 0.);
+ var last = first;
+ for (var i = 1u; i < count; i += 1u) {
+ let angle = step * f32(i);
+ let next = pts.p0 + half_width * vec2f(cos(angle), sin(angle));
+ stroke_chain_point(path_ix, &last, next, transform);
+ }
+ stroke_chain_point(path_ix, &last, first, transform);
+ } else {
+ let p0 = pts.p0 + vec2f(-half_width, -half_width);
+ let p1 = pts.p0 + vec2f(half_width, -half_width);
+ let p2 = pts.p0 + vec2f(half_width, half_width);
+ let p3 = pts.p0 + vec2f(-half_width, half_width);
+ output_two_lines_with_transform(path_ix, p0, p1, p1, p2, transform);
+ output_two_lines_with_transform(path_ix, p2, p3, p3, p0, transform);
+ }
+ } else {
+ let offset_tangent = half_width * normalize(tangent);
+ let n = vec2(offset_tangent.y, -offset_tangent.x);
+ draw_cap(path_ix, start_cap, arc_detail_scale,
+ pts.p0, pts.p0 - n, pts.p0 + n, -offset_tangent, transform);
}
- let offset_tangent = half_width * normalize(tangent);
- let n = vec2(offset_tangent.y, -offset_tangent.x);
- draw_cap(path_ix, (style_flags & STYLE_FLAGS_START_CAP_MASK) >> 2u, arc_detail_scale,
- pts.p0, pts.p0 - n, pts.p0 + n, -offset_tangent, transform);
} else {
// Don't draw anything if the path is closed.
}
} else {
// CPU stroker port: stroke centerline segments are always straight lines, so the
// offset edges are straight offset lines; joins and caps carry all the curvature.
- // The encoder collapses micro-segments (1/64 px) exactly like the CPU stroker.
let p0 = pts.p0;
let p1 = pts.p1;
let seg = p1 - p0;
diff --git a/src/ImageSharp.Drawing.WebGPU/WebGPUSceneEncoder.cs b/src/ImageSharp.Drawing.WebGPU/WebGPUSceneEncoder.cs
index bb25b67d3..742c7832f 100644
--- a/src/ImageSharp.Drawing.WebGPU/WebGPUSceneEncoder.cs
+++ b/src/ImageSharp.Drawing.WebGPU/WebGPUSceneEncoder.cs
@@ -86,18 +86,9 @@ internal static class WebGPUSceneEncoder
private const int PtclClipWords = 9;
///
- /// Half the length of the synthetic horizontal segment substituted for point-like strokes so caps
- /// still render a dot. The full segment length equals , keeping
- /// the substitute just above the micro-segment collapse threshold.
+ /// The square of the minimum stroke segment length used by the CPU stroker.
///
- private const float PointStrokeSegmentHalfLength = 1F / 128F;
-
- ///
- /// The stroke micro-segment collapse threshold in pixels. Mirrors the CPU stroker's 1/64 px
- /// preprocessing in DefaultRasterizer.StrokeLinearizer so GPU strokes consume the same
- /// segment list the CPU stroker strokes.
- ///
- private const float StrokeMicroSegmentEpsilon = 1F / 64F;
+ private const float StrokeDirectionEpsilonSquared = DefaultRasterizer.StrokeDirectionEpsilon * DefaultRasterizer.StrokeDirectionEpsilon;
///
/// The largest scene segment count of one encoding. A range has at most this count. coarse.wgsl stores the segment index in 8 bits.
@@ -3429,7 +3420,7 @@ private void AppendPlainStroke(
GpuSceneDrawMonoid drawTagMonoid = GpuSceneDrawTag.Map(drawTag);
Rectangle interestBounds = ToTargetLocal(command.RasterizerOptions.Interest, this.rootTargetBounds);
(uint style0, uint style1, uint style2, uint style3, uint style4, uint style5, uint style6, uint style7, uint style8, uint style9) =
- GetStrokeStyle(command.GraphicsOptions, pen, widthScale, interestBounds);
+ GetStrokeStyle(command.GraphicsOptions, pen, widthScale, interestBounds, command.RasterizerOptions.CoverageBoost);
int pathTagCheckpoint = this.PathTags.Count;
int styleCheckpoint = this.Styles.Count;
bool appendStyle = !this.hasLastStyle ||
@@ -3572,7 +3563,7 @@ private void AppendExplicitStroke(
GpuSceneDrawMonoid drawTagMonoid = GpuSceneDrawTag.Map(drawTag);
Rectangle interestBounds = ToTargetLocal(rasterizerOptions.Interest, this.rootTargetBounds);
(uint style0, uint style1, uint style2, uint style3, uint style4, uint style5, uint style6, uint style7, uint style8, uint style9) =
- GetStrokeStyle(graphicsOptions, pen, widthScale, interestBounds);
+ GetStrokeStyle(graphicsOptions, pen, widthScale, interestBounds, rasterizerOptions.CoverageBoost);
int pathTagCheckpoint = this.PathTags.Count;
int styleCheckpoint = this.Styles.Count;
bool appendStyle = !this.hasLastStyle ||
@@ -3711,7 +3702,7 @@ private void AppendExplicitStroke(
GpuSceneDrawMonoid drawTagMonoid = GpuSceneDrawTag.Map(drawTag);
Rectangle interestBounds = ToTargetLocal(rasterizerOptions.Interest, this.rootTargetBounds);
(uint style0, uint style1, uint style2, uint style3, uint style4, uint style5, uint style6, uint style7, uint style8, uint style9) =
- GetStrokeStyle(graphicsOptions, pen, widthScale, interestBounds);
+ GetStrokeStyle(graphicsOptions, pen, widthScale, interestBounds, rasterizerOptions.CoverageBoost);
int pathTagCheckpoint = this.PathTags.Count;
int styleCheckpoint = this.Styles.Count;
bool appendStyle = !this.hasLastStyle ||
@@ -7448,7 +7439,7 @@ private static float Sum(Vector2 value)
/// Encodes the final line segments of a stroke centreline in target-local space.
///
///
- /// The encoder removes duplicate and sub-1/64-pixel segments and applies the same open/closed
+ /// The encoder removes segments with no usable direction and applies the same open/closed
/// contour rules as the CPU stroker. The shader receives lines only and expands those lines into
/// stroke bodies, joins, and caps.
///
@@ -7497,7 +7488,7 @@ private static int EncodeStrokePath(
for (int i = 0; i < contours.Length; i++)
{
LinearContour contour = contours[i];
- if (contour.PointCount == 0)
+ if (contour.PointCount < 2)
{
continue;
}
@@ -7561,25 +7552,15 @@ private static int EncodeStrokePath(
int segmentCount = keptCount - 1;
- // Match the CPU closure rule. A contour with at least three source points is closed
- // when it is declared closed or its endpoints are within one scaled stroke width.
- bool isClosed = false;
- if (contourPoints.Length >= 3)
- {
- PointF last = contourPoints[^1];
- float closeThreshold = MathF.Max(strokeWidth, 1E-3F);
- isClosed = contour.IsClosed ||
- firstPoint == last ||
- Vector2.DistanceSquared(firstPoint, last) <= closeThreshold * closeThreshold;
- }
-
- bool duplicateClosingPoint = keptCount > 1 && lastKept == firstPoint;
- int distinctPointCount = keptCount - (isClosed && duplicateClosingPoint ? 1 : 0);
+ bool isClosed = contour.IsClosed;
+ bool duplicateClosingPoint = isClosed && keptCount > 1 && lastKept == firstPoint;
+ int distinctPointCount = keptCount - (duplicateClosingPoint ? 1 : 0);
if (segmentCount == 0)
{
- EncodePointStrokeContour(pointLike, pointTranslateX, pointTranslateY, ref pathTags, ref pathData);
- outlineLength += (4D * PointStrokeSegmentHalfLength) + (2D * capChainLength);
+ Span pointSegment = [pointLike, pointLike];
+ EncodeOpenStrokeContour(pointSegment, pointTranslateX, pointTranslateY, ref pathTags, ref pathData);
+ outlineLength += GetPointStrokeOutlineLength(pen, halfWidth);
encodedContourCount++;
continue;
}
@@ -7598,11 +7579,10 @@ private static int EncodeStrokePath(
{
int emitCount = duplicateClosingPoint ? keptCount - 1 : keptCount;
- // Emit the final line back to the first point only when that gap survived the
- // micro-segment filter. A smaller gap is closed by the join alone.
+ // Add the closing segment when the path has a usable direction at the seam.
bool closingSegment = duplicateClosingPoint ||
(segmentCount > 1 &&
- Vector2.DistanceSquared(lastKept, firstPoint) > StrokeMicroSegmentEpsilon * StrokeMicroSegmentEpsilon);
+ Vector2.DistanceSquared(lastKept, firstPoint) > StrokeDirectionEpsilonSquared);
if (closingSegment && !duplicateClosingPoint)
{
@@ -7713,11 +7693,10 @@ private static int EncodeStrokePath(
// The open marker stores the start point and one point on its outgoing tangent. QuadTo
// selects this four-word marker layout; it does not represent a curve in the shader.
- PointF tangentPoint = GetStrokeMarkerTangentPoint(firstPoint, secondPoint);
openData[openDataIndex++] = BitcastSingle(firstPoint.X + pointTranslateX);
openData[openDataIndex++] = BitcastSingle(firstPoint.Y + pointTranslateY);
- openData[openDataIndex++] = BitcastSingle(tangentPoint.X + pointTranslateX);
- openData[openDataIndex] = BitcastSingle(tangentPoint.Y + pointTranslateY);
+ openData[openDataIndex++] = BitcastSingle(secondPoint.X + pointTranslateX);
+ openData[openDataIndex] = BitcastSingle(secondPoint.Y + pointTranslateY);
openTags[openTagIndex] = PackPathTag(PathTag.QuadToF32 | PathTag.SubpathEnd);
pathData.Advance(openData.Length);
@@ -7738,7 +7717,7 @@ private static int EncodeStrokePath(
}
///
- /// Gets the next stroke contour point that survives exact-duplicate and micro-segment collapse.
+ /// Gets the next point that gives the stroke segment a usable direction.
///
/// The source contour points.
/// The next source point index.
@@ -7766,9 +7745,7 @@ private static bool TryGetNextStrokePoint(
pointLike = point;
- // A non-duplicate micro segment updates the representative point but does not become
- // a stroke segment. Measure the next candidate from the last point that was retained.
- if (Vector2.DistanceSquared(previousKept, point) <= StrokeMicroSegmentEpsilon * StrokeMicroSegmentEpsilon)
+ if (Vector2.DistanceSquared(previousKept, point) <= StrokeDirectionEpsilonSquared)
{
continue;
}
@@ -7813,54 +7790,16 @@ private static void EncodeOpenStrokeContour(
// QuadTo selects the open-marker layout. These two points define a line tangent; no curve
// reaches the shader.
- PointF tangentPoint = GetStrokeMarkerTangentPoint(points[0], points[1]);
contourData[dataIndex++] = BitcastSingle(points[0].X + pointTranslateX);
contourData[dataIndex++] = BitcastSingle(points[0].Y + pointTranslateY);
- contourData[dataIndex++] = BitcastSingle(tangentPoint.X + pointTranslateX);
- contourData[dataIndex] = BitcastSingle(tangentPoint.Y + pointTranslateY);
+ contourData[dataIndex++] = BitcastSingle(points[1].X + pointTranslateX);
+ contourData[dataIndex] = BitcastSingle(points[1].Y + pointTranslateY);
contourTags[tagIndex] = PackPathTag(PathTag.QuadToF32 | PathTag.SubpathEnd);
pathData.Advance(contourData.Length);
pathTags.Advance(contourTags.Length);
}
- ///
- /// Encodes one point-like stroke contour as a tiny centered open segment.
- ///
- /// The point the contour collapsed to.
- /// The x translation to target-local space.
- /// The y translation to target-local space.
- /// The path-tag stream.
- /// The path-data stream.
- private static void EncodePointStrokeContour(
- PointF point,
- float pointTranslateX,
- float pointTranslateY,
- ref OwnedStream pathTags,
- ref OwnedStream pathData)
- {
- // A zero-length centreline has no tangent. Use the same short horizontal segment as the
- // CPU point-stroke path so cap construction has a stable direction.
- PointF start = new(point.X - PointStrokeSegmentHalfLength, point.Y);
- PointF end = new(point.X + PointStrokeSegmentHalfLength, point.Y);
- PointF tangentEnd = GetStrokeMarkerTangentPoint(start, end);
-
- Span contourData = pathData.GetAppendSpan(8);
- Span contourTags = pathTags.GetAppendSpan(2);
- contourData[0] = BitcastSingle(start.X + pointTranslateX);
- contourData[1] = BitcastSingle(start.Y + pointTranslateY);
- contourData[2] = BitcastSingle(end.X + pointTranslateX);
- contourData[3] = BitcastSingle(end.Y + pointTranslateY);
- contourTags[0] = PackPathTag(PathTag.LineToF32);
- contourData[4] = BitcastSingle(start.X + pointTranslateX);
- contourData[5] = BitcastSingle(start.Y + pointTranslateY);
- contourData[6] = BitcastSingle(tangentEnd.X + pointTranslateX);
- contourData[7] = BitcastSingle(tangentEnd.Y + pointTranslateY);
- contourTags[1] = PackPathTag(PathTag.QuadToF32 | PathTag.SubpathEnd);
- pathData.Advance(contourData.Length);
- pathTags.Advance(contourTags.Length);
- }
-
///
/// Encodes one explicit open two-point stroke centerline into Vello-style path tags and path data in target-local space.
///
@@ -7895,13 +7834,22 @@ private static int EncodeOpenSegmentStrokePath(
{
float pointTranslateX = destinationOffset.X - rootTargetBounds.X;
float pointTranslateY = destinationOffset.Y - rootTargetBounds.Y;
- NormalizePointStrokeSegment(ref start, ref end);
+ float lengthSquared = Vector2.DistanceSquared(start, end);
+ bool isPoint = lengthSquared <= StrokeDirectionEpsilonSquared;
+ if (isPoint)
+ {
+ end = start;
+ }
+
Span segmentPoints = [start, end];
EncodeOpenStrokeContour(segmentPoints, pointTranslateX, pointTranslateY, ref pathTags, ref pathData);
pathTags.Add(PackPathTag(PathTag.Path));
lineCount = EstimateStrokeLineCountForOpenSegment(pen, widthScale);
float halfWidth = pen.StrokeWidth * widthScale * 0.5F;
- double outlineLength = (2D * Vector2.Distance(start, end)) + (2D * GetStrokeCapChainLength(pen, halfWidth));
+ double outlineLength = isPoint
+ ? GetPointStrokeOutlineLength(pen, halfWidth)
+ : (2D * MathF.Sqrt(lengthSquared)) + (2D * GetStrokeCapChainLength(pen, halfWidth));
+
tileCrossings = BoundStrokeTileCrossings(outlineLength, residualStretch, lineCount);
rowCrossings = 2L * GetRowTileCrossings(start, end);
endCrossings = GetStrokeEndTileCrossings(lineCount, 1, pen, widthScale);
@@ -7953,21 +7901,13 @@ private static long GetInnerJoinTileCrossings(float innerExtent, float halfWidth
}
///
- /// Replaces a point-like explicit stroke segment with the tiny tangent segment used for point strokes.
+ /// Gets the perimeter of the footprint of a zero-length segment.
///
- /// The segment start point; replaced when the segment is point-like.
- /// The segment end point; replaced when the segment is point-like.
- private static void NormalizePointStrokeSegment(ref PointF start, ref PointF end)
- {
- if (Vector2.DistanceSquared(start, end) > StrokeMicroSegmentEpsilon * StrokeMicroSegmentEpsilon)
- {
- return;
- }
-
- PointF center = new((start.X + end.X) * 0.5F, (start.Y + end.Y) * 0.5F);
- start = new PointF(center.X - PointStrokeSegmentHalfLength, center.Y);
- end = new PointF(center.X + PointStrokeSegmentHalfLength, center.Y);
- }
+ /// The pen that defines the cap.
+ /// Half the stroke width.
+ /// The perimeter in pixels.
+ private static double GetPointStrokeOutlineLength(Pen pen, float halfWidth)
+ => pen.StrokeOptions.LineCap == LineCap.Round ? 2D * GetStrokeCapChainLength(pen, halfWidth) : 8D * halfWidth;
///
/// Encodes a rectangle as a fixed-size closed path.
@@ -8461,9 +8401,8 @@ private static int EstimateStrokeLineCount(LinearGeometry geometry, Pen pen, flo
{
LinearContour contour = geometry.Contours[i];
- // The stroke encoder can close an open contour whose ends meet, which adds one body
- // and one join, and it draws a two-point closed contour as a capped open segment. So
- // every contour gets the closing body, a join for each body and two caps.
+ // Reserve a join for each body and two caps. The extra body on an open path
+ // also covers the four edges of a square for a zero-length segment.
int bodies = contour.IsClosed ? contour.SegmentCount : contour.SegmentCount + 1;
total += (bodies * 2) + (bodies * joinCost) + (capCost * 2);
}
@@ -8622,18 +8561,6 @@ private static int GetStrokeArcLineCost(float radius, float angle, double arcDet
return Math.Max(1, (int)MathF.Ceiling(angle / theta));
}
- ///
- /// Returns the encoded tangent point used by the staged stroker's cap marker segment for one explicit open line segment.
- ///
- /// The subpath start point.
- /// The first segment end point.
- /// The tangent point, one third of the way from to .
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- private static PointF GetStrokeMarkerTangentPoint(PointF start, PointF end)
- => new(
- start.X + ((end.X - start.X) / 3F),
- start.Y + ((end.Y - start.Y) / 3F));
-
///
/// Reserves the exact stream growth needed for one begin-layer clip item.
///
@@ -8774,9 +8701,8 @@ private static void AppendIdentityTransform(ref OwnedStream transforms)
///
///
/// Word layout consumed by path_lowering.wgsl: 0 = style flags, 1 = device-space stroke width,
- /// 2 = packed draw flags, 3 = miter limit, 4 = arc detail scale, 5 = zero,
+ /// 2 = packed draw flags, 3 = miter limit, 4 = arc detail scale, 5 = coverage boost,
/// 6-9 = target-local interest rectangle as left, top, right, bottom.
- /// Strokes do not use antialiased text coverage boost data, so word 5 is zero in both modes.
///
/// Bits 0-10 of word 0 hold the arc limit: the interior vertex count of a round arc of
/// half a turn, from . The shader clamps the vertex count of
@@ -8789,6 +8715,7 @@ private static void AppendIdentityTransform(ref OwnedStream transforms)
/// The pen that defines stroke width, joins, caps, and miter limit.
/// The transform-derived scale applied to the stroke width.
/// The target-local raster interest bounds.
+ /// The coverage boost for antialiased text strokes.
/// The ten packed style words.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static (
@@ -8805,7 +8732,8 @@ private static (
GraphicsOptions options,
Pen pen,
float widthScale,
- Rectangle interestBounds)
+ Rectangle interestBounds,
+ float coverageBoost)
{
StyleFlags styleFlags = StyleFlags.Stroke
| EncodeStrokeJoinFlags(pen.StrokeOptions.LineJoin)
@@ -8825,7 +8753,7 @@ private static (
PackStyleDrawFlags(options),
BitcastSingle((float)pen.StrokeOptions.MiterLimit),
BitcastSingle((float)pen.StrokeOptions.ArcDetailScale),
- 0U,
+ options.Antialias ? BitcastSingle(coverageBoost) : 0U,
BitcastSingle(interestBounds.Left),
BitcastSingle(interestBounds.Top),
BitcastSingle(interestBounds.Right),
diff --git a/src/ImageSharp.Drawing/ArcLineSegment.cs b/src/ImageSharp.Drawing/ArcLineSegment.cs
index f10bf8545..170a93417 100644
--- a/src/ImageSharp.Drawing/ArcLineSegment.cs
+++ b/src/ImageSharp.Drawing/ArcLineSegment.cs
@@ -49,7 +49,15 @@ public ArcLineSegment(PointF from, PointF to, SizeF radius, float rotation, bool
}
else
{
- this.linePoints = EllipticArcFromEndParams(from, to, radius, rotation, largeArc, sweep);
+ PointF[] points = EllipticArcFromEndParams(from, to, radius, rotation, largeArc, sweep);
+ if (points.Length == 0)
+ {
+ points = [from, to];
+ }
+
+ // Keep the requested end so the next segment starts at the same point.
+ points[^1] = to;
+ this.linePoints = points;
}
this.Bounds = CalculateBounds(this.linePoints);
diff --git a/src/ImageSharp.Drawing/ClipPathExtensions.cs b/src/ImageSharp.Drawing/ClipPathExtensions.cs
index f6ec3809a..d595c0fb9 100644
--- a/src/ImageSharp.Drawing/ClipPathExtensions.cs
+++ b/src/ImageSharp.Drawing/ClipPathExtensions.cs
@@ -8,6 +8,10 @@ namespace SixLabors.ImageSharp.Drawing;
///
/// Provides extension methods to that allow the clipping of shapes.
///
+///
+/// Closed figures define filled areas. Open figures retain their line segments and points.
+/// Results can contain closed figures, open lines, and isolated points.
+///
public static class ClipPathExtensions
{
///
@@ -57,7 +61,7 @@ public static IPath Clip(this IPath subjectPath, BooleanOperation operation, IEn
///
/// The subject path.
/// The boolean operation to perform.
- /// The fill rule used to interpret the subject and clipping paths.
+ /// The fill rule for closed figures in both operands.
/// The clipping paths.
/// The clipped .
public static IPath Clip(
@@ -72,7 +76,7 @@ public static IPath Clip(
///
/// The subject path.
/// The boolean operation to perform.
- /// The fill rule used to interpret the subject and clipping paths.
+ /// The fill rule for closed figures in both operands.
/// The clipping paths.
/// The clipped .
public static IPath Clip(
diff --git a/src/ImageSharp.Drawing/ImageSharp.Drawing.csproj b/src/ImageSharp.Drawing/ImageSharp.Drawing.csproj
index 5c205032d..090e5edf7 100644
--- a/src/ImageSharp.Drawing/ImageSharp.Drawing.csproj
+++ b/src/ImageSharp.Drawing/ImageSharp.Drawing.csproj
@@ -46,7 +46,7 @@
-
+
diff --git a/src/ImageSharp.Drawing/LinearLineSegment.cs b/src/ImageSharp.Drawing/LinearLineSegment.cs
index b3a5dc112..acbaf1df1 100644
--- a/src/ImageSharp.Drawing/LinearLineSegment.cs
+++ b/src/ImageSharp.Drawing/LinearLineSegment.cs
@@ -50,6 +50,26 @@ public LinearLineSegment(PointF[] points)
this.Bounds = CalculateBounds(points);
}
+ ///
+ /// Initializes a new instance of the class for an isolated point.
+ ///
+ /// The location of the point.
+ internal LinearLineSegment(PointF point)
+ : this([point], new RectangleF(point.X, point.Y, 0, 0))
+ {
+ }
+
+ ///
+ /// Initializes a new instance of the class with known bounds.
+ ///
+ /// The vertices owned by this segment.
+ /// The bounds of the vertices.
+ private LinearLineSegment(PointF[] points, RectangleF bounds)
+ {
+ this.points = points;
+ this.Bounds = bounds;
+ }
+
///
/// Gets the start point.
///
@@ -109,7 +129,7 @@ public LinearLineSegment Transform(Matrix4x4 matrix)
transformedPoints[i] = PointF.Transform(this.points[i], matrix);
}
- return new LinearLineSegment(transformedPoints);
+ return new LinearLineSegment(transformedPoints, CalculateBounds(transformedPoints));
}
///
diff --git a/src/ImageSharp.Drawing/NormalizePathExtensions.cs b/src/ImageSharp.Drawing/NormalizePathExtensions.cs
index 8e8a15431..01a000466 100644
--- a/src/ImageSharp.Drawing/NormalizePathExtensions.cs
+++ b/src/ImageSharp.Drawing/NormalizePathExtensions.cs
@@ -11,11 +11,11 @@ namespace SixLabors.ImageSharp.Drawing;
public static class NormalizePathExtensions
{
///
- /// Creates a normalized positive-winding polygon representation of the specified path.
+ /// Resolves self-intersections and overlaps using the non-zero fill rule.
///
/// The path to normalize.
///
- /// A path whose contours represent the normalized filled area of using positive winding.
+ /// A path whose contours enclose the regions of with non-zero winding.
///
public static IPath Normalize(this IPath path) => NormalizedShapeGenerator.NormalizeShape(path);
}
diff --git a/src/ImageSharp.Drawing/PolygonGeometry/ClippedShapeGenerator.cs b/src/ImageSharp.Drawing/PolygonGeometry/ClippedShapeGenerator.cs
index 1397e9f43..f8cabe384 100644
--- a/src/ImageSharp.Drawing/PolygonGeometry/ClippedShapeGenerator.cs
+++ b/src/ImageSharp.Drawing/PolygonGeometry/ClippedShapeGenerator.cs
@@ -15,7 +15,7 @@ namespace SixLabors.ImageSharp.Drawing.PolygonGeometry;
/// It converts subject and clip paths to clipper polygons, applies the specified
/// , and converts the resulting polygon contours back into
/// instances suitable for rendering or further processing.
-/// clip operands are handled as rect-sets on dedicated fast paths.
+/// Rectangle intersection with an integer region uses the region's rectangle set directly.
///
internal static class ClippedShapeGenerator
{
@@ -86,16 +86,11 @@ clipList[0] is IRegionPath candidate
return clippedRectangle;
}
- PCPolygon s = PolygonClipperFactory.FromClosedPath(subject, intersectionRule);
+ PCPolygon s = PolygonClipperFactory.FromPath(subject);
+ PCPolygon c = PolygonClipperFactory.FromPaths(clip);
+ FillRule subjectRule = ToFillRule(intersectionRule);
- if (singleRegionPath is not null)
- {
- return GenerateRegionClippedShapes(operation, s, singleRegionPath);
- }
-
- PCPolygon c = PolygonClipperFactory.FromClosedPaths(clip, clipIntersectionRule);
-
- return GenerateClippedShapes(operation, s, c);
+ return ToComplexPolygon(Clip(operation, s, c, subjectRule, ToFillRule(clipIntersectionRule)));
}
///
@@ -125,18 +120,21 @@ public static ComplexPolygon GenerateClippedShapes(
return clippedRectangle;
}
- PCPolygon s = PolygonClipperFactory.FromClosedPath(subject, intersectionRule);
-
- if (clip is IRegionPath regionPathAfterFastPath)
- {
- return GenerateRegionClippedShapes(operation, s, regionPathAfterFastPath);
- }
-
- PCPolygon c = PolygonClipperFactory.FromClosedPath(clip, clipIntersectionRule);
+ PCPolygon s = PolygonClipperFactory.FromPath(subject);
+ PCPolygon c = PolygonClipperFactory.FromPath(clip);
+ FillRule subjectRule = ToFillRule(intersectionRule);
- return GenerateClippedShapes(operation, s, c);
+ return ToComplexPolygon(Clip(operation, s, c, subjectRule, ToFillRule(clipIntersectionRule)));
}
+ ///
+ /// Maps the path fill rule to the equivalent clipping fill rule.
+ ///
+ /// The rule used to fill the source path.
+ /// The rule used to fill the source polygon.
+ private static FillRule ToFillRule(IntersectionRule rule)
+ => rule == IntersectionRule.NonZero ? FillRule.NonZero : FillRule.EvenOdd;
+
///
/// Attempts the rectangle-by-region fast path: intersecting an axis-aligned rectangle
/// subject with a rect-set region needs no polygon clipper at all.
@@ -184,135 +182,59 @@ private static bool TryClipRectangleByRegion(
private static RectangleF ToRectangleF(Rectangle rectangle)
=> new(rectangle.X, rectangle.Y, rectangle.Width, rectangle.Height);
- ///
- /// Applies a boolean operation between a subject polygon and a rect-set region operand.
- ///
- /// The boolean operation to perform.
- /// The converted subject polygon.
- /// The rect-set clip operand.
- /// The representing the result of the boolean operation.
- private static ComplexPolygon GenerateRegionClippedShapes(BooleanOperation operation, PCPolygon subject, IRegionPath regionPath)
- {
- IReadOnlyList rectangles = regionPath.Rectangles;
- if (operation == BooleanOperation.Intersection)
- {
- PCPolygon result = [];
-
- // RegionPath is a rect-set operand: S & (r0 | r1 | ...) is the union of
- // each per-rectangle intersection. Keeping that algebra explicit avoids
- // asking the generic polygon clipper to infer region union semantics from
- // adjacent/disjoint rectangle contours.
- for (int i = 0; i < rectangles.Count; i++)
- {
- PCPolygon clip = PolygonClipperFactory.FromRectangle(rectangles[i]);
- result.Join(PolygonClipperAction.Intersection(subject, clip));
- }
-
- return ToComplexPolygon(result);
- }
-
- PCPolygon current = subject;
- for (int i = 0; i < rectangles.Count; i++)
- {
- PCPolygon clip = PolygonClipperFactory.FromRectangle(rectangles[i]);
- current = operation switch
- {
- BooleanOperation.Xor => PolygonClipperAction.Xor(current, clip),
- BooleanOperation.Difference => PolygonClipperAction.Difference(current, clip),
- BooleanOperation.Union => PolygonClipperAction.Union(current, clip),
- _ => PolygonClipperAction.Intersection(current, clip),
- };
- }
-
- return ToComplexPolygon(current);
- }
-
///
/// Applies a boolean operation between two converted polygons.
///
/// The boolean operation to perform.
/// The converted subject polygon.
/// The converted clip polygon.
- /// The representing the result of the boolean operation.
- private static ComplexPolygon GenerateClippedShapes(BooleanOperation operation, PCPolygon subject, PCPolygon clip)
- {
- PCPolygon result = operation switch
+ /// The rule used to fill the subject.
+ /// The rule used to fill the clip polygon.
+ /// The selected boundaries, open lines, and isolated points.
+ private static PCPolygon Clip(
+ BooleanOperation operation,
+ PCPolygon subject,
+ PCPolygon clip,
+ FillRule subjectRule,
+ FillRule clipRule)
+ => operation switch
{
- BooleanOperation.Xor => PolygonClipperAction.Xor(subject, clip),
- BooleanOperation.Difference => PolygonClipperAction.Difference(subject, clip),
- BooleanOperation.Union => PolygonClipperAction.Union(subject, clip),
- _ => PolygonClipperAction.Intersection(subject, clip),
+ BooleanOperation.Xor => PolygonClipperAction.Xor(subject, clip, subjectRule, clipRule),
+ BooleanOperation.Difference => PolygonClipperAction.Difference(subject, clip, subjectRule, clipRule),
+ BooleanOperation.Union => PolygonClipperAction.Union(subject, clip, subjectRule, clipRule),
+ _ => PolygonClipperAction.Intersection(subject, clip, subjectRule, clipRule),
};
- return ToComplexPolygon(result);
- }
-
///
- /// Converts a PolygonClipper result polygon into a .
+ /// Converts a PolygonClipper result into a path with the same figure closure.
///
/// The polygon produced by the clipper.
/// The converted .
- private static ComplexPolygon ToComplexPolygon(PCPolygon result)
+ public static ComplexPolygon ToComplexPolygon(PCPolygon result)
{
IPath[] shapes = new IPath[result.Count];
- int index = 0;
for (int i = 0; i < result.Count; i++)
{
- shapes[index++] = new Polygon(CreateContourPoints(result, i));
- }
-
- return new(shapes);
- }
-
- ///
- /// Converts a PolygonClipper contour to ImageSharp points and normalizes winding for parent/child rings.
- ///
- /// The polygon containing the contour hierarchy.
- /// The contour index to convert.
- /// The converted point array.
- public static PointF[] CreateContourPoints(PCPolygon polygon, int contourIndex)
- {
- Contour contour = polygon[contourIndex];
- PointF[] points = new PointF[contour.Count];
- bool reverse = ShouldReverseForNonZeroWinding(polygon, contourIndex);
-
- if (!reverse)
- {
- for (int i = 0; i < contour.Count; i++)
+ Contour contour = result[i];
+ if (contour.Count == 1)
{
- Vertex vertex = contour[i];
- points[i] = new PointF((float)vertex.X, (float)vertex.Y);
+ Vertex vertex = contour[0];
+ PointF point = new((float)vertex.X, (float)vertex.Y);
+ shapes[i] = new Path(new LinearLineSegment(point));
+ continue;
}
- return points;
- }
-
- for (int sourceIndex = contour.Count - 1, targetIndex = 0; sourceIndex >= 0; sourceIndex--, targetIndex++)
- {
- Vertex vertex = contour[sourceIndex];
- points[targetIndex] = new PointF((float)vertex.X, (float)vertex.Y);
- }
-
- return points;
- }
+ PointF[] points = new PointF[contour.Count];
+ for (int j = 0; j < contour.Count; j++)
+ {
+ Vertex vertex = contour[j];
+ points[j] = new PointF((float)vertex.X, (float)vertex.Y);
+ }
- ///
- /// Ensures child contours (holes/islands) use opposite winding to their direct parent.
- /// This keeps clipped output deterministic when consumed with the NonZero fill rule.
- ///
- /// The polygon containing contour hierarchy information.
- /// The contour index to inspect.
- /// when the contour should be reversed.
- private static bool ShouldReverseForNonZeroWinding(PCPolygon polygon, int contourIndex)
- {
- Contour contour = polygon[contourIndex];
- if (contour.ParentIndex is not int parentIndex || (uint)parentIndex >= (uint)polygon.Count)
- {
- return false;
+ shapes[i] = contour.IsClosed ? new Polygon(points) : new Path(points);
}
- Contour parentContour = polygon[parentIndex];
- return contour.IsCounterClockwise() == parentContour.IsCounterClockwise();
+ return new(shapes);
}
}
diff --git a/src/ImageSharp.Drawing/PolygonGeometry/NormalizedShapeGenerator.cs b/src/ImageSharp.Drawing/PolygonGeometry/NormalizedShapeGenerator.cs
index 8cd40d2e6..ec7173156 100644
--- a/src/ImageSharp.Drawing/PolygonGeometry/NormalizedShapeGenerator.cs
+++ b/src/ImageSharp.Drawing/PolygonGeometry/NormalizedShapeGenerator.cs
@@ -10,19 +10,14 @@ namespace SixLabors.ImageSharp.Drawing.PolygonGeometry;
///
/// Generates normalized polygon shapes from paths.
///
-///
-/// Normalization converts the incoming path contours to a positive-winding polygon representation.
-/// This gives later boolean operations a stable contour set instead of preserving ambiguous
-/// self-intersections, overlaps, or parity-dependent contour relationships from the source path.
-///
internal static class NormalizedShapeGenerator
{
///
- /// Normalizes the specified path.
+ /// Resolves self-intersections and overlaps using the non-zero fill rule.
///
/// The path to normalize.
///
- /// A containing the normalized positive-winding contours.
+ /// A containing the boundaries of the filled area.
///
public static ComplexPolygon NormalizeShape(IPath path)
{
@@ -45,12 +40,6 @@ public static ComplexPolygon NormalizeShape(IPath path)
ring.Add(new Vertex(p.X, p.Y));
}
- // PolygonClipper expects closed rings to repeat their start point.
- if (sp.IsClosed)
- {
- ring.Add(ring[0]);
- }
-
rings.Add(ring);
}
@@ -60,14 +49,7 @@ public static ComplexPolygon NormalizeShape(IPath path)
return new([]);
}
- PCPolygon result = PolygonClipperAction.Normalize(rings);
-
- IPath[] shapes = new IPath[result.Count];
- for (int i = 0; i < result.Count; i++)
- {
- shapes[i] = new Polygon(ClippedShapeGenerator.CreateContourPoints(result, i));
- }
-
- return new(shapes);
+ PCPolygon result = PolygonClipperAction.Normalize(rings, FillRule.NonZero);
+ return ClippedShapeGenerator.ToComplexPolygon(result);
}
}
diff --git a/src/ImageSharp.Drawing/PolygonGeometry/PolygonClipperFactory.cs b/src/ImageSharp.Drawing/PolygonGeometry/PolygonClipperFactory.cs
index 115b0c2ec..9283903a2 100644
--- a/src/ImageSharp.Drawing/PolygonGeometry/PolygonClipperFactory.cs
+++ b/src/ImageSharp.Drawing/PolygonGeometry/PolygonClipperFactory.cs
@@ -3,151 +3,85 @@
using SixLabors.PolygonClipper;
using PCPolygon = SixLabors.PolygonClipper.Polygon;
-using PolygonClipperAction = SixLabors.PolygonClipper.PolygonClipper;
namespace SixLabors.ImageSharp.Drawing.PolygonGeometry;
///
-/// Builders for from ImageSharp paths.
-/// Converts ImageSharp paths to the format required by PolygonClipper.
+/// Converts ImageSharp paths to PolygonClipper contours.
///
-///
-/// PolygonClipper computes parent-child relationships, depth, and orientation during its
-/// sweep line algorithm, so we only need to provide contours with vertices.
-///
internal static class PolygonClipperFactory
{
///
- /// Creates a polygon from multiple paths.
+ /// Creates a polygon from the open and closed figures of multiple paths.
///
/// The paths to convert.
- /// A containing all flattened paths as contours.
- public static PCPolygon FromClosedPaths(IEnumerable paths)
- => FromClosedPaths(paths, IntersectionRule.NonZero);
-
- ///
- /// Creates a polygon area from multiple paths using the specified fill rule.
- ///
- /// The paths to convert.
- /// The fill rule used to interpret the input paths.
- /// A containing the converted contours.
- public static PCPolygon FromClosedPaths(IEnumerable paths, IntersectionRule intersectionRule)
+ /// The converted contours.
+ public static PCPolygon FromPaths(IEnumerable paths)
{
PCPolygon polygon = [];
foreach (IPath path in paths)
{
- if (path is IRegionPath regionPath)
- {
- AddRegionRectangles(regionPath.Rectangles, polygon);
- continue;
- }
-
- polygon = FromSimpleClosedPaths(path.Flatten(), polygon);
+ AddPath(path, polygon);
}
- return ApplyIntersectionRule(polygon, intersectionRule);
+ return polygon;
}
///
- /// Creates a polygon area from a path using the specified fill rule.
+ /// Creates a polygon from the open and closed figures of a path.
///
/// The path to convert.
- /// The fill rule used to interpret the path.
- /// A containing the converted contours.
- public static PCPolygon FromClosedPath(IPath path, IntersectionRule intersectionRule)
- {
- if (path is IRegionPath regionPath)
- {
- PCPolygon regionPolygon = [];
- AddRegionRectangles(regionPath.Rectangles, regionPolygon);
-
- return ApplyIntersectionRule(regionPolygon, intersectionRule);
- }
-
- PCPolygon polygon = FromSimpleClosedPaths(path.AsClosedPath().Flatten());
-
- return ApplyIntersectionRule(polygon, intersectionRule);
- }
-
- ///
- /// Creates a polygon from one axis-aligned integer rectangle.
- ///
- /// The rectangle to convert.
- /// A containing one rectangle contour.
- public static PCPolygon FromRectangle(Rectangle rectangle)
+ /// The converted contours.
+ public static PCPolygon FromPath(IPath path)
{
PCPolygon polygon = [];
- AddRectangle(rectangle, polygon);
+ AddPath(path, polygon);
return polygon;
}
///
- /// Adds an integer region as rectangle contours without first exporting its boundary path.
+ /// Adds a path's contours to the polygon.
///
- /// The normalized rectangles that cover the region.
- /// The polygon receiving the rectangle contours.
- private static void AddRegionRectangles(IReadOnlyList rectangles, PCPolygon polygon)
+ /// The source path.
+ /// The polygon receiving the contours.
+ private static void AddPath(IPath path, PCPolygon polygon)
{
- // Skia clips regions as rectangle sets. Preserve that model at the polygon boundary so
- // disjoint dirty-region islands are unioned by coverage instead of being inferred from
- // boundary-link geometry.
- for (int i = 0; i < rectangles.Count; i++)
+ if (path is IRegionPath regionPath)
{
- AddRectangle(rectangles[i], polygon);
- }
- }
-
- ///
- /// Adds one rectangle contour to a polygon.
- ///
- /// The rectangle to add.
- /// The polygon receiving the rectangle contour.
- private static void AddRectangle(Rectangle rectangle, PCPolygon polygon)
- {
- Contour contour =
- [
- new Vertex(rectangle.Left, rectangle.Top),
- new Vertex(rectangle.Right, rectangle.Top),
- new Vertex(rectangle.Right, rectangle.Bottom),
- new Vertex(rectangle.Left, rectangle.Bottom)
- ];
-
- polygon.Add(contour);
- }
+ // The rectangles have disjoint interiors. Shared edges cancel
+ // when the sweep processes the whole region as one operand.
+ IReadOnlyList rectangles = regionPath.Rectangles;
+ for (int i = 0; i < rectangles.Count; i++)
+ {
+ Rectangle rectangle = rectangles[i];
+ Contour contour =
+ [
+ new Vertex(rectangle.Left, rectangle.Top),
+ new Vertex(rectangle.Right, rectangle.Top),
+ new Vertex(rectangle.Right, rectangle.Bottom),
+ new Vertex(rectangle.Left, rectangle.Bottom)
+ ];
+
+ polygon.Add(contour);
+ }
- ///
- /// Converts closed simple paths to PolygonClipper contours.
- ///
- /// Closed simple paths.
- /// Optional existing polygon to populate.
- /// The constructed .
- ///
- /// This method simply converts ImageSharp paths to PolygonClipper contours by copying vertices.
- /// PolygonClipper's sweep line algorithm will determine parent-child relationships, depth,
- /// and proper orientation during clipping operations. We only need to ensure paths are
- /// closed and have sufficient vertices.
- ///
- public static PCPolygon FromSimpleClosedPaths(IEnumerable paths, PCPolygon? polygon = null)
- {
- polygon ??= [];
+ return;
+ }
- foreach (ISimplePath p in paths)
+ foreach (ISimplePath figure in path.Flatten())
{
- if (!p.IsClosed)
+ ReadOnlySpan points = figure.Points.Span;
+ if (points.IsEmpty)
{
continue;
}
- ReadOnlySpan points = p.Points.Span;
- if (points.Length < 3)
+ Contour contour = new(points.Length)
{
- continue;
- }
-
- Contour contour = [];
+ IsClosed = figure.IsClosed
+ };
- // Copy all vertices
for (int i = 0; i < points.Length; i++)
{
contour.Add(new Vertex(points[i].X, points[i].Y));
@@ -155,31 +89,5 @@ public static PCPolygon FromSimpleClosedPaths(IEnumerable paths, PC
polygon.Add(contour);
}
-
- return polygon;
}
-
- ///
- /// Prepares a polygon so the boolean clipper reproduces the requested fill rule.
- ///
- ///
- /// The clipper classifies coverage by even-odd boundary crossings, which is orientation
- /// independent: a point is inside when an odd number of the polygon's edges lie below it,
- /// regardless of edge direction. Even-odd input already matches that model and is returned
- /// unchanged. Non-zero input differs from even-odd only where the outline covers a region more
- /// than once, that is where contours self-overlap or self-intersect (winding of magnitude two
- /// or more, common in glyph outlines with overlapping components or crossings introduced by
- /// curve flattening). Non-zero fills such a region while even-odd punches it out as a hole,
- /// which is what produced clipped glyphs with spurious holes. Reorienting the contours cannot
- /// fix this, because even-odd ignores direction, so the overlapping regions must actually be
- /// merged. performs that self-union and yields an
- /// equivalent simple polygon whose even-odd boundary equals the non-zero fill.
- ///
- /// The polygon to prepare.
- /// The fill rule used to interpret the polygon.
- /// A containing the prepared contours.
- private static PCPolygon ApplyIntersectionRule(PCPolygon polygon, IntersectionRule intersectionRule)
- => intersectionRule == IntersectionRule.NonZero
- ? PolygonClipperAction.Normalize(polygon)
- : polygon;
}
diff --git a/src/ImageSharp.Drawing/PolygonGeometry/StrokedShapeGenerator.cs b/src/ImageSharp.Drawing/PolygonGeometry/StrokedShapeGenerator.cs
index 70b8774d5..f3d5ae336 100644
--- a/src/ImageSharp.Drawing/PolygonGeometry/StrokedShapeGenerator.cs
+++ b/src/ImageSharp.Drawing/PolygonGeometry/StrokedShapeGenerator.cs
@@ -1,6 +1,7 @@
// Copyright (c) Six Labors.
// Licensed under the Six Labors Split License.
+using System.Numerics;
using SixLabors.PolygonClipper;
using PCPolygon = SixLabors.PolygonClipper.Polygon;
@@ -24,32 +25,30 @@ internal static class StrokedShapeGenerator
///
public static ComplexPolygon GenerateStrokedShapes(IPath path, float width, StrokeOptions options)
{
- // Convert the flattened contours to clipper rings first; the stroker handles
- // open and closed contours differently, so closedness must be preserved.
+ // Use the same vertices as Draw. Path.Flatten can drop short segments
+ // before PolygonClipper has a chance to use their direction.
+ LinearGeometry geometry = path.ToLinearGeometry(Vector2.One);
PCPolygon rings = [];
- foreach (ISimplePath sp in path.Flatten())
+ foreach (LinearContour contour in geometry.GetContours())
{
- ReadOnlySpan span = sp.Points.Span;
-
+ ReadOnlySpan span = geometry.GetContourPoints(contour);
if (span.Length < 2)
{
continue;
}
- Contour ring = new(span.Length);
+ Contour ring = new(span.Length)
+ {
+ IsClosed = contour.IsClosed
+ };
+
for (int i = 0; i < span.Length; i++)
{
PointF p = span[i];
ring.Add(new Vertex(p.X, p.Y));
}
- // PolygonClipper expects closed rings to repeat their start point.
- if (sp.IsClosed)
- {
- ring.Add(ring[0]);
- }
-
rings.Add(ring);
}
@@ -61,14 +60,7 @@ public static ComplexPolygon GenerateStrokedShapes(IPath path, float width, Stro
PCPolygon result = PolygonStroker.Stroke(rings, width, CreateStrokeOptions(options));
- IPath[] shapes = new IPath[result.Count];
- int index = 0;
- for (int i = 0; i < result.Count; i++)
- {
- shapes[index++] = new Polygon(ClippedShapeGenerator.CreateContourPoints(result, i));
- }
-
- return new(shapes);
+ return ClippedShapeGenerator.ToComplexPolygon(result);
}
///
diff --git a/src/ImageSharp.Drawing/Processing/Backends/DefaultRasterizer.Stroke.cs b/src/ImageSharp.Drawing/Processing/Backends/DefaultRasterizer.Stroke.cs
index 1e6e453f0..50f9bcbd5 100644
--- a/src/ImageSharp.Drawing/Processing/Backends/DefaultRasterizer.Stroke.cs
+++ b/src/ImageSharp.Drawing/Processing/Backends/DefaultRasterizer.Stroke.cs
@@ -14,7 +14,7 @@ internal static partial class DefaultRasterizer
/// The length threshold below which a segment direction, arc radius, or edge extent is treated as degenerate.
/// Mirrored on the GPU as TANGENT_THRESH in path_lowering.wgsl; the two must stay in lockstep.
///
- private const float StrokeDirectionEpsilon = 1e-6F;
+ public const float StrokeDirectionEpsilon = 1e-6F;
///
/// The cross-product magnitude below which two offset support lines are treated as parallel
@@ -383,7 +383,7 @@ private static StrokeRasterizableGeometry CreateRetainedStrokeRasterizableGeomet
bandTop,
options.IntersectionRule,
options.RasterizationMode,
- coverageBoost: 0F,
+ options.CoverageBoost,
hasStartCovers,
options.Interest);
}
@@ -454,7 +454,7 @@ private static StrokeRasterizableGeometry CreateRetainedStrokeRasterizableGeomet
bandTop,
options.IntersectionRule,
options.RasterizationMode,
- coverageBoost: 0F,
+ options.CoverageBoost,
hasStartCovers,
options.Interest);
}
@@ -833,7 +833,6 @@ private readonly struct DirectLineSegmentBandRasterizer
{
private readonly Vector2 start;
private readonly Vector2 end;
- private readonly Vector2 translation;
private readonly StrokeStyle stroke;
private readonly int width;
private readonly int height;
@@ -857,12 +856,13 @@ private DirectLineSegmentBandRasterizer(
int translateY,
in RasterizableBandInfo bandInfo)
{
- this.translation = new(
+ Vector2 translation = new(
translateX - bandInfo.DestinationLeft,
translateY - bandInfo.DestinationTop);
- this.start = start;
- this.end = end;
+ // The body and the round caps use the same band-local coordinates.
+ this.start = (Vector2)start + translation;
+ this.end = (Vector2)end + translation;
this.stroke = stroke;
this.width = bandInfo.Width;
this.height = bandInfo.BandHeight;
@@ -914,11 +914,9 @@ private void Rasterize(Span scanline, ref TRowHandler rowHan
return;
}
- Vector2 translatedStart = this.start + this.translation;
- Vector2 translatedEnd = this.end + this.translation;
- if (!TryGetDirection(translatedStart, translatedEnd, out Vector2 tangent, out _))
+ if (!TryGetDirection(this.start, this.end, out Vector2 tangent, out _))
{
- this.RasterizePointLike(translatedStart, scanline, ref rowHandler);
+ this.RasterizePointLike(this.start, scanline, ref rowHandler);
return;
}
@@ -928,10 +926,10 @@ private void Rasterize(Span scanline, ref TRowHandler rowHan
float halfWidth = this.stroke.HalfWidth;
Vector2 normal = GetStrokeOffsetNormal(tangent) * halfWidth;
Vector2 extension = this.stroke.LineCap == LineCap.Square ? tangent * halfWidth : Vector2.Zero;
- Vector2 p0 = translatedStart + normal - extension;
- Vector2 p1 = translatedEnd + normal + extension;
- Vector2 p2 = translatedEnd - normal + extension;
- Vector2 p3 = translatedStart - normal - extension;
+ Vector2 p0 = this.start + normal - extension;
+ Vector2 p1 = this.end + normal + extension;
+ Vector2 p2 = this.end - normal + extension;
+ Vector2 p3 = this.start - normal - extension;
for (int row = 0; row < this.height; row++)
{
diff --git a/src/ImageSharp.Drawing/Processing/Backends/DefaultRasterizer.StrokeLinearizer.cs b/src/ImageSharp.Drawing/Processing/Backends/DefaultRasterizer.StrokeLinearizer.cs
index a454c8433..3f077e429 100644
--- a/src/ImageSharp.Drawing/Processing/Backends/DefaultRasterizer.StrokeLinearizer.cs
+++ b/src/ImageSharp.Drawing/Processing/Backends/DefaultRasterizer.StrokeLinearizer.cs
@@ -24,13 +24,6 @@ internal static partial class DefaultRasterizer
private abstract class StrokeLinearizer : Linearizer
where TL : class
{
- ///
- /// The 1/64 px length below which a contour segment is collapsed forward onto the last
- /// kept point so every surviving segment carries a well conditioned tangent. Mirrored by
- /// the GPU encoder's WebGPUSceneEncoder.StrokeMicroSegmentEpsilon.
- ///
- private const float StrokeMicroSegmentEpsilon = 1F / 64F;
-
private readonly StrokeStyle stroke;
///
@@ -94,7 +87,7 @@ protected override bool ProcessCore()
for (int contourIndex = 0; contourIndex < contours.Length; contourIndex++)
{
LinearContour contour = contours[contourIndex];
- if (contour.PointCount == 0)
+ if (contour.PointCount < 2)
{
continue;
}
@@ -106,9 +99,7 @@ protected override bool ProcessCore()
continue;
}
- bool isClosed = this.IsContourClosedForEmission(contourPoints, contour.IsClosed);
-
- this.ProcessContour(contourPoints, isClosed, contourInterest == ContourInterest.Contained);
+ this.ProcessContour(contourPoints, contour.IsClosed, contourInterest == ContourInterest.Contained);
}
if (!this.HasAnyCoverage)
@@ -149,47 +140,6 @@ private ContourInterest GetContourInterest(ReadOnlySpan contourPoints)
return ContourInterest.Clipped;
}
- ///
- /// Returns whether a contour should be treated as closed when emitting stroke geometry.
- /// A contour is closed when it is declared closed, its first and last points coincide, or
- /// the endpoint gap is at most max(strokeWidth, 1e-3). Mirrored at encode time by
- /// WebGPUSceneEncoder.EncodeStrokePath; both must stay in lockstep.
- ///
- /// The contour points.
- /// Indicates whether the contour is explicitly closed.
- /// when the contour should be stroked as closed; otherwise .
- private bool IsContourClosedForEmission(ReadOnlySpan contourPoints, bool isDeclaredClosed)
- {
- // Fewer than three points cannot enclose area, so such contours always stroke open.
- if (contourPoints.Length < 3)
- {
- return false;
- }
-
- PointF first = this.TransformPoint(contourPoints[0]);
- PointF last = this.TransformPoint(contourPoints[^1]);
-
- if (isDeclaredClosed || first == last)
- {
- return true;
- }
-
- // Near-closure: a gap no wider than the stroke itself is visually sealed by the
- // stroke body, so emit a wrap join instead of two caps facing across a slit.
- Vector2 delta = first - last;
- float closeThreshold = MathF.Max(this.stroke.Width, 1E-3F);
- return delta.LengthSquared() <= closeThreshold * closeThreshold;
- }
-
- ///
- /// Applies the residual transform to one source point when one is present.
- ///
- /// The source point.
- /// The transformed point.
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- private PointF TransformPoint(PointF point)
- => this.HasResidual ? PointF.Transform(point, this.Residual) : point;
-
///
/// Processes one centerline contour.
///
@@ -233,10 +183,8 @@ private void ProcessContour(ReadOnlySpan contourPoints, bool isClosed, b
/// Builds one contour-local stroke segment array while collapsing immediate duplicate points.
///
///
- /// Exact duplicates are skipped outright and sub-1/64 px micro-segments are collapsed
- /// forward onto the last kept point so every surviving segment carries a well conditioned
- /// tangent for join math. Ported to encode time on the GPU path by
- /// WebGPUSceneEncoder.EncodeStrokePath; both must stay in lockstep.
+ /// Segments without a usable direction collapse onto the last retained point.
+ /// The GPU encoder applies the same rule.
///
/// The contiguous contour points.
/// Indicates whether the contour is closed.
@@ -274,9 +222,7 @@ private int BuildContourSegments(
continue;
}
- // When the candidate segment is rejected as a micro-segment, previousPoint stays
- // anchored on the last kept point so the run collapses forward; pointLike still
- // tracks the newest source point so a fully degenerate contour falls back to it.
+ // Keep the previous point until a segment has a usable direction.
if (TryCreateStrokeContourSegment(previousPoint, point, out StrokeContourSegment segment))
{
distinctPointCount++;
@@ -296,9 +242,7 @@ private int BuildContourSegments(
distinctPointCount--;
}
- // Bridge back to the first point when a closed contour does not already end on it.
- // A sub-1/64 px gap fails TryCreateStrokeContourSegment and is bridged by the wrap
- // join instead, matching the GPU encoder.
+ // Add the closing segment when the path has a usable direction at the seam.
if (isClosed &&
segmentCount > 1 &&
previousPoint != firstPoint &&
@@ -319,14 +263,6 @@ private int BuildContourSegments(
/// when a non-degenerate segment exists.
private static bool TryCreateStrokeContourSegment(PointF start, PointF end, out StrokeContourSegment segment)
{
- // Segments shorter than 1/64 px cannot produce a numerically stable tangent, so
- // they are rejected here and collapsed forward by the caller.
- if (Vector2.DistanceSquared(start, end) <= StrokeMicroSegmentEpsilon * StrokeMicroSegmentEpsilon)
- {
- segment = default;
- return false;
- }
-
if (!TryGetDirection(start, end, out Vector2 tangent, out float length))
{
segment = default;
@@ -551,10 +487,21 @@ private void EmitPointStrokeContour(PointF point, bool contained)
float halfWidth = this.stroke.HalfWidth;
if (this.stroke.LineCap == LineCap.Round)
{
- // A round-capped point is a full circle emitted as two half arcs.
- Vector2 startOffset = new(halfWidth, 0F);
- this.EmitDirectedArcContour(center, startOffset, -startOffset, contained);
- this.EmitDirectedArcContour(center, -startOffset, startOffset, contained);
+ // PolygonClipper divides the full turn into equal steps from the positive X axis.
+ // Two semicircles can give a different vertex count and different edges.
+ int count = Math.Max(4, GetArcSubdivisionCount(halfWidth, Math.Tau, this.stroke.ArcDetailScale));
+ double step = Math.Tau / count;
+ PointF first = new(center.X + halfWidth, center.Y);
+ PointF previous = first;
+ for (int i = 1; i < count; i++)
+ {
+ (double sin, double cos) = Math.SinCos(step * i);
+ PointF next = new((float)(center.X + (cos * halfWidth)), (float)(center.Y + (sin * halfWidth)));
+ this.EmitLine(previous, next, contained);
+ previous = next;
+ }
+
+ this.EmitLine(previous, first, contained);
return;
}
diff --git a/tests/ImageSharp.Drawing.Tests/PolygonGeometry/PolygonClippingTests.cs b/tests/ImageSharp.Drawing.Tests/PolygonGeometry/PolygonClippingTests.cs
index 0d70cef18..0ab1deb5f 100644
--- a/tests/ImageSharp.Drawing.Tests/PolygonGeometry/PolygonClippingTests.cs
+++ b/tests/ImageSharp.Drawing.Tests/PolygonGeometry/PolygonClippingTests.cs
@@ -29,6 +29,62 @@ public class PolygonClippingTests
private static ComplexPolygon Clip(IPath shape, params IPath[] hole)
=> ClippedShapeGenerator.GenerateClippedShapes(BooleanOperation.Difference, shape, hole);
+ ///
+ /// Checks that either operand can supply an open line.
+ ///
+ /// Whether the line is the subject.
+ [Theory]
+ [InlineData(true)]
+ [InlineData(false)]
+ public void Intersection_OpenLineAndRectangle_ReturnsOpenLine(bool lineIsSubject)
+ {
+ IPath line = new Path([new PointF(-5, 5), new PointF(15, 5)]);
+ IPath rectangle = new RectanglePolygon(0, 0, 10, 10);
+
+ IPath result = lineIsSubject ? line.Clip(rectangle) : rectangle.Clip(line);
+
+ ISimplePath figure = Assert.Single(result.Flatten());
+ Assert.False(figure.IsClosed);
+ Assert.Equal(new[] { new PointF(0, 5), new PointF(10, 5) }, figure.Points.ToArray());
+ }
+
+ ///
+ /// Checks that crossing lines produce a point that can be transformed and clipped again.
+ ///
+ [Fact]
+ public void Intersection_CrossingLines_ReturnsReusablePoint()
+ {
+ IPath first = new Path([new PointF(0, 0), new PointF(10, 10)]);
+ IPath second = new Path([new PointF(0, 10), new PointF(10, 0)]);
+
+ IPath point = first.Clip(second);
+ ISimplePath figure = Assert.Single(point.Flatten());
+ Assert.False(figure.IsClosed);
+ Assert.Equal(new PointF(5, 5), Assert.Single(figure.Points.ToArray()));
+
+ IPath translated = point.Transform(Matrix4x4.CreateTranslation(1, 2, 0));
+ IPath clipped = translated.Clip(new RectanglePolygon(0, 0, 10, 10));
+ ISimplePath result = Assert.Single(clipped.Flatten());
+ Assert.False(result.IsClosed);
+ Assert.Equal(new PointF(6, 7), Assert.Single(result.Points.ToArray()));
+ }
+
+ ///
+ /// Checks that internal rectangle boundaries do not split a clipped line.
+ ///
+ [Fact]
+ public void Intersection_OpenLineAcrossRegionBands_ReturnsOneOpenLine()
+ {
+ Region region = new(new Rectangle(0, 0, 10, 10));
+ region.Add(new Rectangle(0, 10, 5, 10));
+ IPath line = new Path([new PointF(2, -1), new PointF(2, 21)]);
+
+ ISimplePath result = Assert.Single(line.Clip(region.ToPath()).Flatten());
+ Assert.False(result.IsClosed);
+ Assert.Equal(new PointF(2, 0), result.Points.Span[0]);
+ Assert.Equal(new PointF(2, 20), result.Points.Span[^1]);
+ }
+
[Fact]
public void OverlappingTriangleCutRightSide()
{
diff --git a/tests/ImageSharp.Drawing.Tests/Processing/Backends/DefaultRasterizerStrokeTests.cs b/tests/ImageSharp.Drawing.Tests/Processing/Backends/DefaultRasterizerStrokeTests.cs
index 62162a971..1d0977719 100644
--- a/tests/ImageSharp.Drawing.Tests/Processing/Backends/DefaultRasterizerStrokeTests.cs
+++ b/tests/ImageSharp.Drawing.Tests/Processing/Backends/DefaultRasterizerStrokeTests.cs
@@ -1,7 +1,10 @@
// Copyright (c) Six Labors.
// Licensed under the Six Labors Split License.
+using SixLabors.ImageSharp.Drawing.Processing;
using SixLabors.ImageSharp.Drawing.Processing.Backends;
+using SixLabors.ImageSharp.PixelFormats;
+using SixLabors.ImageSharp.Processing;
namespace SixLabors.ImageSharp.Drawing.Tests.Processing.Backends;
@@ -44,4 +47,91 @@ public void GetArcSubdivisionCount_LargeRadius_StaysBelowGpuBound()
Assert.InRange(count, 1, 1023);
}
+
+ ///
+ /// Checks that the CPU stroke joins the ends only when the path is closed.
+ ///
+ /// Whether the path is closed.
+ /// Whether both ends have the same coordinates.
+ [Theory]
+ [InlineData(false, false)]
+ [InlineData(false, true)]
+ [InlineData(true, false)]
+ [InlineData(true, true)]
+ public void Stroke_UsesDeclaredClosure(bool isClosed, bool endsMeet)
+ {
+ using Image image = new(64, 64, Color.White.ToPixel());
+ image.Mutate(context => context.Paint(canvas => DrawClosureTestPath(canvas, isClosed, endsMeet)));
+
+ Rgba32 expected = (isClosed ? Color.Black : Color.White).ToPixel();
+ Assert.Equal(expected, image[21, 21]);
+ }
+
+ ///
+ /// Draws the dashed ellipse from issue 430.
+ ///
+ /// The canvas to draw on.
+ internal static void DrawDashedEllipse(DrawingCanvas canvas)
+ {
+ IPath ellipse = new EllipsePolygon(128, 128, 200, 200);
+ StrokeOptions stroke = new() { LineJoin = LineJoin.Miter, LineCap = LineCap.Butt };
+ Pen dashed = new PatternPen(new PenOptions(Color.Black, 2, [4F, 2F, 1F, 2F]) { StrokeOptions = stroke });
+ canvas.Draw(dashed, ellipse);
+ }
+
+ ///
+ /// Draws a clipped point and segments with equal or close endpoints.
+ ///
+ /// The canvas to draw on.
+ /// The stroke cap.
+ internal static void DrawPointAndSegments(DrawingCanvas canvas, LineCap cap)
+ {
+ Pen pen = new SolidPen(new PenOptions(Color.Black, 10) { StrokeOptions = new StrokeOptions { LineCap = cap } });
+ Path first = new([new PointF(8, 8), new PointF(24, 24)]);
+ Path second = new([new PointF(8, 24), new PointF(24, 8)]);
+ IPath point = first.Clip(second);
+ PointF zeroStart = new(32, 16);
+ PointF zeroLineStart = new(48, 16);
+ PointF shortStart = new(64, 16);
+ PointF shortEnd = new(64.005F, 16.005F);
+ PointF shortLineStart = new(80, 16);
+ PointF shortLineEnd = new(80.005F, 16.005F);
+ Path zeroPath = new([zeroStart, zeroStart]);
+ Path shortPath = new([shortStart, shortEnd]);
+
+ canvas.Draw(pen, point);
+ canvas.Draw(pen, zeroPath);
+ canvas.DrawLine(pen, zeroLineStart, zeroLineStart);
+
+ // These short diagonal lines still give square caps a direction.
+ canvas.Draw(pen, shortPath);
+ canvas.DrawLine(pen, shortLineStart, shortLineEnd);
+ }
+
+ ///
+ /// Draws a path with a miter corner at its start when it is closed.
+ ///
+ /// The canvas to draw on.
+ /// Whether the path is closed.
+ /// Whether both ends have the same coordinates.
+ internal static void DrawClosureTestPath(DrawingCanvas canvas, bool isClosed, bool endsMeet)
+ {
+ PointF[] points =
+ [
+ new(24, 24),
+ new(54, 24),
+ new(24, 54),
+ new(24, endsMeet ? 24 : 30)
+ ];
+
+ // Only the miter at the start covers pixel (21, 21). The open path
+ // uses butt caps, even when the gap is shorter than the stroke width.
+ IPath path = isClosed ? new Polygon(points) : new Path(points);
+ SolidPen pen = new(new PenOptions(Color.Black, 10)
+ {
+ StrokeOptions = new StrokeOptions { LineCap = LineCap.Butt, LineJoin = LineJoin.Miter },
+ });
+
+ canvas.Draw(pen, path);
+ }
}
diff --git a/tests/ImageSharp.Drawing.Tests/Processing/Backends/WebGPUDrawingBackendTests.cs b/tests/ImageSharp.Drawing.Tests/Processing/Backends/WebGPUDrawingBackendTests.cs
index 5715f09ed..e3afeffe1 100644
--- a/tests/ImageSharp.Drawing.Tests/Processing/Backends/WebGPUDrawingBackendTests.cs
+++ b/tests/ImageSharp.Drawing.Tests/Processing/Backends/WebGPUDrawingBackendTests.cs
@@ -1986,6 +1986,117 @@ void DrawAction(DrawingCanvas canvas)
AssertBackendPairReferenceOutputs(provider, null, defaultImage, nativeSurfaceImage);
}
+ ///
+ /// Checks that the GPU stroke joins the ends only when the path is closed.
+ ///
+ /// Whether the path is closed.
+ /// Whether both ends have the same coordinates.
+ [WebGPUTheory]
+ [InlineData(false, false)]
+ [InlineData(false, true)]
+ [InlineData(true, false)]
+ [InlineData(true, true)]
+ public void Stroke_UsesDeclaredClosure(bool isClosed, bool endsMeet)
+ {
+ using WebGPUDrawingBackend backend = new();
+ using Image image = RenderWithNativeSurfaceWebGpuBackend(
+ 64,
+ 64,
+ backend,
+ new DrawingOptions(),
+ canvas =>
+ {
+ canvas.Clear(Brushes.Solid(Color.White));
+ DefaultRasterizerStrokeTests.DrawClosureTestPath(canvas, isClosed, endsMeet);
+ });
+
+ Rgba32 expected = (isClosed ? Color.Black : Color.White).ToPixel();
+ Assert.Equal(expected, image[21, 21]);
+ }
+
+ ///
+ /// Checks that both backends preserve the dash pattern around the ellipse.
+ ///
+ /// The pixel format.
+ /// The white test image.
+ [WebGPUTheory]
+ [WithSolidFilledImages(256, 256, "White", PixelTypes.Rgba32)]
+ public void Stroke_EllipseWithMiterDashPattern_PreservesGaps(TestImageProvider provider)
+ where TPixel : unmanaged, IPixel
+ => AssertStrokeMatchesOutline(
+ provider,
+ null,
+ DefaultRasterizerStrokeTests.DrawDashedEllipse,
+ backendTolerancePercent: 0.002F,
+ referenceTolerancePercent: 0.0003F);
+
+ ///
+ /// Checks the stroke of a point, a zero-length segment, and a short segment.
+ ///
+ /// The pixel format.
+ /// The white test image.
+ /// The stroke cap.
+ [WebGPUTheory]
+ [WithSolidFilledImages(96, 32, "White", PixelTypes.Rgba32, LineCap.Butt)]
+ [WithSolidFilledImages(96, 32, "White", PixelTypes.Rgba32, LineCap.Square)]
+ [WithSolidFilledImages(96, 32, "White", PixelTypes.Rgba32, LineCap.Round)]
+ public void Stroke_DistinguishesPointFromZeroLengthSegment(TestImageProvider provider, LineCap cap)
+ where TPixel : unmanaged, IPixel
+ {
+ // The CPU samples round caps directly. The outline uses straight segments.
+ // The largest measured differences were 0.11815% for round, 0.00546% for square,
+ // and 0.00029% for butt.
+ float tolerancePercent = cap switch
+ {
+ LineCap.Round => 0.125F,
+ LineCap.Square => 0.006F,
+ _ => 0.0003F
+ };
+
+ AssertStrokeMatchesOutline(
+ provider,
+ $"{cap}",
+ canvas => DefaultRasterizerStrokeTests.DrawPointAndSegments(canvas, cap),
+ tolerancePercent,
+ tolerancePercent);
+ }
+
+ ///
+ /// Compares the backend strokes with each other and with reference fills of the PolygonClipper outline.
+ ///
+ /// The pixel format.
+ /// The white test image.
+ /// The details for the stroke image file names.
+ /// Draws the native stroke.
+ /// The maximum difference between the backends, in percent.
+ /// The maximum difference from each reference, in percent.
+ private static void AssertStrokeMatchesOutline(
+ TestImageProvider provider,
+ string testName,
+ CanvasAction drawStroke,
+ float backendTolerancePercent,
+ float referenceTolerancePercent)
+ where TPixel : unmanaged, IPixel
+ {
+ DrawingOptions options = new();
+ using Image defaultImage = provider.GetImage();
+ RenderWithDefaultBackend(defaultImage, options, drawStroke);
+
+ using WebGPUDrawingBackend backend = new();
+ using Image initialImage = provider.GetImage();
+ using Image nativeImage = RenderWithNativeSurfaceWebGpuBackend(
+ initialImage.Width,
+ initialImage.Height,
+ backend,
+ options,
+ canvas => drawStroke(canvas),
+ initialImage);
+
+ DebugSaveBackendPair(provider, testName, defaultImage, nativeImage);
+ AssertBackendPairSimilarity(defaultImage, nativeImage, backendTolerancePercent);
+ AssertBackendPairReferenceOutputs(provider, testName, defaultImage, nativeImage, referenceTolerancePercent);
+ }
+
[WebGPUTheory]
[WithSolidFilledImages(256, 256, "White", PixelTypes.Rgba32, LineCap.Square)]
[WithSolidFilledImages(256, 256, "White", PixelTypes.Rgba32, LineCap.Round)]
@@ -2159,8 +2270,7 @@ public void DrawPath_StrokeImageBrushMiterJoin_MatchesDefaultOutput(Test
// sqrt(m^2 + 1) half widths from the corner. The centerline here turns back at (100, 112.5) by
// almost 180 degrees. For half width 5 and limit 4, the bevel then covers part of column 79,
// outside bounds that are inflated by m half widths (x = 80). Both backends must draw the bevel
- // pixels of column 79. The edge pixels differ by one 8-bit level between the CPU and the GPU:
- // 0.0003% measured. A bevel column that one backend cuts gives 0.0011%.
+ // pixels of column 79. The remaining edges can differ by one 8-bit channel level.
[WebGPUTheory]
[WithSolidFilledImages(200, 160, "White", PixelTypes.Rgba32)]
public void DrawPath_StrokeMiterJoinReversal_MatchesDefaultOutput(TestImageProvider provider)
@@ -2203,7 +2313,12 @@ public void DrawPath_StrokeMiterJoinReversal_MatchesDefaultOutput(TestIm
RenderWithDefaultBackend(referenceImage, drawingOptions, canvas => canvas.Fill(pen.StrokeFill, outline));
DebugSaveBackendPair(provider, null, defaultImage, nativeSurfaceImage);
- AssertBackendPairSimilarity(defaultImage, nativeSurfaceImage, 0.0004F);
+ // The measured difference between the CPU and WebGPU images is 0.00042%.
+ AssertBackendPairSimilarity(defaultImage, nativeSurfaceImage, 0.00043F);
+
+ ImageComparer comparer = ImageComparer.Tolerant(0F, 3 * 257);
+ comparer.VerifySimilarity(referenceImage, defaultImage);
+ comparer.VerifySimilarity(referenceImage, nativeSurfaceImage);
for (int y = 0; y < referenceImage.Height; y++)
{
Assert.Equal(referenceImage[79, y], defaultImage[79, y]);
diff --git a/tests/ImageSharp.Drawing.Tests/Shapes/NormalizePathExtensionsTests.cs b/tests/ImageSharp.Drawing.Tests/Shapes/NormalizePathExtensionsTests.cs
index d5c78140a..88b6f522d 100644
--- a/tests/ImageSharp.Drawing.Tests/Shapes/NormalizePathExtensionsTests.cs
+++ b/tests/ImageSharp.Drawing.Tests/Shapes/NormalizePathExtensionsTests.cs
@@ -15,12 +15,16 @@ public void Normalize_SimpleRectangle_PreservesBounds()
Assert.Equal(path.Bounds, normalized.Bounds);
}
- [Fact]
- public void Normalize_SelfIntersectingBowtie_KeepsOnlyThePositiveWindingLobe()
+ ///
+ /// Checks that normalization keeps both lobes in either vertex order.
+ ///
+ /// Whether to reverse the contour before normalization.
+ [Theory]
+ [InlineData(false)]
+ [InlineData(true)]
+ public void Normalize_SelfIntersectingBowtie_KeepsBothLobes(bool reverse)
{
- // The bowtie crosses itself at (50, 50), giving its two lobes opposite winding.
- // Normalization fills using positive winding, so only the positively wound lobe
- // survives; reversing the point order keeps the opposite lobe.
+ // The lobes meet at (50, 50). Their winding counts are +1 and -1.
PointF[] points =
[
new PointF(0, 0),
@@ -29,12 +33,18 @@ public void Normalize_SelfIntersectingBowtie_KeepsOnlyThePositiveWindingLobe()
new PointF(0, 100),
];
- IPath normalized = new Polygon(points).Normalize();
- Assert.Equal(RectangleF.FromLTRB(0, 0, 50, 100), normalized.Bounds);
-
- Array.Reverse(points);
- IPath reversed = new Polygon(points).Normalize();
- Assert.Equal(RectangleF.FromLTRB(50, 0, 100, 100), reversed.Bounds);
+ if (reverse)
+ {
+ // Reversing the vertices swaps the winding signs of the two lobes.
+ // Both counts remain nonzero, so both lobes must remain filled.
+ Array.Reverse(points);
+ }
+
+ ComplexPolygon normalized = Assert.IsType(new Polygon(points).Normalize());
+ Assert.Collection(
+ normalized.Paths.OrderBy(x => x.Bounds.Left),
+ left => Assert.Equal(RectangleF.FromLTRB(0, 0, 50, 100), left.Bounds),
+ right => Assert.Equal(RectangleF.FromLTRB(50, 0, 100, 100), right.Bounds));
}
[Fact]
diff --git a/tests/Images/ReferenceOutput/Drawing/DrawingCanvasTests/Clear_WithClipPath_MatchesReference_Rgba32.png b/tests/Images/ReferenceOutput/Drawing/DrawingCanvasTests/Clear_WithClipPath_MatchesReference_Rgba32.png
index f7bbaa734..4d32ca3d1 100644
--- a/tests/Images/ReferenceOutput/Drawing/DrawingCanvasTests/Clear_WithClipPath_MatchesReference_Rgba32.png
+++ b/tests/Images/ReferenceOutput/Drawing/DrawingCanvasTests/Clear_WithClipPath_MatchesReference_Rgba32.png
@@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
-oid sha256:a4beab8a3520289cfdd18958f3475daee41c4e177aa0678eaaa73ae8ed246e23
-size 10719
+oid sha256:9c9c2c25dd509e50e57542ddd28acb980497e05c941b2b0269bbde5d9611295d
+size 15160
diff --git a/tests/Images/ReferenceOutput/Drawing/DrawingCanvasTests/DrawImage_WithClipPathAndTransform_MatchesReference_Rgba32.png b/tests/Images/ReferenceOutput/Drawing/DrawingCanvasTests/DrawImage_WithClipPathAndTransform_MatchesReference_Rgba32.png
index 86751ed03..044694bde 100644
--- a/tests/Images/ReferenceOutput/Drawing/DrawingCanvasTests/DrawImage_WithClipPathAndTransform_MatchesReference_Rgba32.png
+++ b/tests/Images/ReferenceOutput/Drawing/DrawingCanvasTests/DrawImage_WithClipPathAndTransform_MatchesReference_Rgba32.png
@@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
-oid sha256:901a86f282672511672e7889ff12fc6bc750743f4ace095ea8e234c0c23bb2f7
-size 10885
+oid sha256:f3242e0d678df72546cc4fceb4b5cda28f73ad5516f7dba4cff8c1d3e245fc35
+size 16128
diff --git a/tests/Images/ReferenceOutput/Drawing/DrawingCanvasTests/DrawText_FillAndStroke_MatchesReference_Rgba32.png b/tests/Images/ReferenceOutput/Drawing/DrawingCanvasTests/DrawText_FillAndStroke_MatchesReference_Rgba32.png
index 05bdeebff..de4b8a7fd 100644
--- a/tests/Images/ReferenceOutput/Drawing/DrawingCanvasTests/DrawText_FillAndStroke_MatchesReference_Rgba32.png
+++ b/tests/Images/ReferenceOutput/Drawing/DrawingCanvasTests/DrawText_FillAndStroke_MatchesReference_Rgba32.png
@@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
-oid sha256:afc6e54941da95e60b7430df83ebe7c16211fbce15fb82e72aa16e2226a58329
-size 19066
+oid sha256:5d36383f7d96f1dcfec7d10734d1b147c6785da92dbaf1113174d7fd405cde07
+size 21804
diff --git a/tests/Images/ReferenceOutput/Drawing/DrawingCanvasTests/DrawText_LineLayoutsAlongDifferentPaths_MatchesReference_Rgba32.png b/tests/Images/ReferenceOutput/Drawing/DrawingCanvasTests/DrawText_LineLayoutsAlongDifferentPaths_MatchesReference_Rgba32.png
index 6a5b63226..ed2d06777 100644
--- a/tests/Images/ReferenceOutput/Drawing/DrawingCanvasTests/DrawText_LineLayoutsAlongDifferentPaths_MatchesReference_Rgba32.png
+++ b/tests/Images/ReferenceOutput/Drawing/DrawingCanvasTests/DrawText_LineLayoutsAlongDifferentPaths_MatchesReference_Rgba32.png
@@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
-oid sha256:dcaf6fa8d7bc73a863ce77c6d60fd4303deaf058f69d36f80f9757f0668034c7
-size 29796
+oid sha256:ccd819ee2abf6a450bf95984c3bc8ac32138a781732b6830854f06846c130945
+size 38634
diff --git a/tests/Images/ReferenceOutput/Drawing/DrawingCanvasTests/DrawText_PenOnly_MatchesReference_Rgba32.png b/tests/Images/ReferenceOutput/Drawing/DrawingCanvasTests/DrawText_PenOnly_MatchesReference_Rgba32.png
index 57b6f3d3a..206cef915 100644
--- a/tests/Images/ReferenceOutput/Drawing/DrawingCanvasTests/DrawText_PenOnly_MatchesReference_Rgba32.png
+++ b/tests/Images/ReferenceOutput/Drawing/DrawingCanvasTests/DrawText_PenOnly_MatchesReference_Rgba32.png
@@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
-oid sha256:b20c0ef9ce4499b3be9a131a0babac26d984a34e50c773528e7b0f1668b2e50d
-size 4430
+oid sha256:5e354e251362cf9d4ec9a8ed343734a0b0eb4d587054933d94a9c31ad6857c97
+size 6434
diff --git a/tests/Images/ReferenceOutput/Drawing/DrawingCanvasTests/DrawText_TextBlockAlongPath_MatchesReference_Rgba32.png b/tests/Images/ReferenceOutput/Drawing/DrawingCanvasTests/DrawText_TextBlockAlongPath_MatchesReference_Rgba32.png
index f209923a2..945c15eac 100644
--- a/tests/Images/ReferenceOutput/Drawing/DrawingCanvasTests/DrawText_TextBlockAlongPath_MatchesReference_Rgba32.png
+++ b/tests/Images/ReferenceOutput/Drawing/DrawingCanvasTests/DrawText_TextBlockAlongPath_MatchesReference_Rgba32.png
@@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
-oid sha256:b05666093fa36c931de9edd002331b80f8434278dbeb83670a1c5fdc6fb2200c
-size 21401
+oid sha256:4e57c7e742f9b726c5ecca63735c78aaa36780e38deb8e13cfbdfa337f8f3c82
+size 31793
diff --git a/tests/Images/ReferenceOutput/Drawing/DrawingCanvasTests/DrawText_WithWrappingAlignmentAndLineSpacing_MatchesReference_Rgba32.png b/tests/Images/ReferenceOutput/Drawing/DrawingCanvasTests/DrawText_WithWrappingAlignmentAndLineSpacing_MatchesReference_Rgba32.png
index 5e2ebf4db..332188ba6 100644
--- a/tests/Images/ReferenceOutput/Drawing/DrawingCanvasTests/DrawText_WithWrappingAlignmentAndLineSpacing_MatchesReference_Rgba32.png
+++ b/tests/Images/ReferenceOutput/Drawing/DrawingCanvasTests/DrawText_WithWrappingAlignmentAndLineSpacing_MatchesReference_Rgba32.png
@@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
-oid sha256:42231b83df172f6b586870bfed5a3917d1fdb2551512e67ae8d0e2a3831f9793
-size 38247
+oid sha256:15db387a17e65cf3ff3fba2ff23e9eedd22a12f1ea1aef4b9b400caffca29a77
+size 52356
diff --git a/tests/Images/ReferenceOutput/Drawing/DrawingCanvasTests/Draw_WithPatternAndGradientPens_MatchesReference_Rgba32.png b/tests/Images/ReferenceOutput/Drawing/DrawingCanvasTests/Draw_WithPatternAndGradientPens_MatchesReference_Rgba32.png
index a0842ff7c..094d417b1 100644
--- a/tests/Images/ReferenceOutput/Drawing/DrawingCanvasTests/Draw_WithPatternAndGradientPens_MatchesReference_Rgba32.png
+++ b/tests/Images/ReferenceOutput/Drawing/DrawingCanvasTests/Draw_WithPatternAndGradientPens_MatchesReference_Rgba32.png
@@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
-oid sha256:152793cb12322141066df53626bf2809e9c4a49684c8467985c7ded6ee1fd578
-size 8500
+oid sha256:53f8434506e0a0b02dcf1e6d2efe77917a10e8441ea93d1de0fd181ec364960e
+size 12447
diff --git a/tests/Images/ReferenceOutput/Drawing/ProcessWithDrawingCanvasTests/CanRotateOutlineFont_Issue175_Solid300x200_(255,255,255,255)_F(OpenSans-Regular.ttf)-S(32)-A(75)-STR(1)-Quic).png b/tests/Images/ReferenceOutput/Drawing/ProcessWithDrawingCanvasTests/CanRotateOutlineFont_Issue175_Solid300x200_(255,255,255,255)_F(OpenSans-Regular.ttf)-S(32)-A(75)-STR(1)-Quic).png
index f603243c6..262d1c1be 100644
--- a/tests/Images/ReferenceOutput/Drawing/ProcessWithDrawingCanvasTests/CanRotateOutlineFont_Issue175_Solid300x200_(255,255,255,255)_F(OpenSans-Regular.ttf)-S(32)-A(75)-STR(1)-Quic).png
+++ b/tests/Images/ReferenceOutput/Drawing/ProcessWithDrawingCanvasTests/CanRotateOutlineFont_Issue175_Solid300x200_(255,255,255,255)_F(OpenSans-Regular.ttf)-S(32)-A(75)-STR(1)-Quic).png
@@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
-oid sha256:6de44d0c57b8038039d2ab99cd00c8c4277dc8b48024ddf5b68d8a0251ec273e
-size 2579
+oid sha256:5f81f30cd7edc8c63e4e84467fe960923a3f086c50c0f9b1bcaf3c2adf1144b7
+size 6355
diff --git a/tests/Images/ReferenceOutput/Drawing/ProcessWithDrawingCanvasTests/CanRotateOutlineFont_Issue175_Solid300x200_(255,255,255,255)_F(OpenSans-Regular.ttf)-S(40)-A(90)-STR(2)-Quic).png b/tests/Images/ReferenceOutput/Drawing/ProcessWithDrawingCanvasTests/CanRotateOutlineFont_Issue175_Solid300x200_(255,255,255,255)_F(OpenSans-Regular.ttf)-S(40)-A(90)-STR(2)-Quic).png
index 53373ee74..95762761d 100644
--- a/tests/Images/ReferenceOutput/Drawing/ProcessWithDrawingCanvasTests/CanRotateOutlineFont_Issue175_Solid300x200_(255,255,255,255)_F(OpenSans-Regular.ttf)-S(40)-A(90)-STR(2)-Quic).png
+++ b/tests/Images/ReferenceOutput/Drawing/ProcessWithDrawingCanvasTests/CanRotateOutlineFont_Issue175_Solid300x200_(255,255,255,255)_F(OpenSans-Regular.ttf)-S(40)-A(90)-STR(2)-Quic).png
@@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
-oid sha256:784533ea4c6cecb17b4047f66cc1711d77968e7653fd63a8ee93d29cc59afd4d
-size 2519
+oid sha256:3cda17bd4683f1a4eb797911742d0603bb6370742665cad19aeecbb104aefe9d
+size 6747
diff --git a/tests/Images/ReferenceOutput/Drawing/ProcessWithDrawingCanvasTests/DrawComplexPolygon__Dashed.png b/tests/Images/ReferenceOutput/Drawing/ProcessWithDrawingCanvasTests/DrawComplexPolygon__Dashed.png
index ff3837567..301c42808 100644
--- a/tests/Images/ReferenceOutput/Drawing/ProcessWithDrawingCanvasTests/DrawComplexPolygon__Dashed.png
+++ b/tests/Images/ReferenceOutput/Drawing/ProcessWithDrawingCanvasTests/DrawComplexPolygon__Dashed.png
@@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
-oid sha256:b4a28e40d958bf024ce956cfaca83994b393b29516beacb6b05db3d4e4d200ce
-size 8131
+oid sha256:bc8efe48244a1df6e9ba79dc825381c3b1a865211648c6d0f8998c5d6f6b6c98
+size 9354
diff --git a/tests/Images/ReferenceOutput/Drawing/ProcessWithDrawingCanvasTests/DrawPathCircleUsingAddArc_359.png b/tests/Images/ReferenceOutput/Drawing/ProcessWithDrawingCanvasTests/DrawPathCircleUsingAddArc_359.png
index e593be7c6..b416227ce 100644
--- a/tests/Images/ReferenceOutput/Drawing/ProcessWithDrawingCanvasTests/DrawPathCircleUsingAddArc_359.png
+++ b/tests/Images/ReferenceOutput/Drawing/ProcessWithDrawingCanvasTests/DrawPathCircleUsingAddArc_359.png
@@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
-oid sha256:da070c2488e14e11b2a3032f91ad5f7c296881a740de294a25d3fc26fdea6f8c
-size 1674
+oid sha256:e314d5e04582a55877ee0d42de7e648e9544fa30a94ab9c0c7809f89b5eea43c
+size 4393
diff --git a/tests/Images/ReferenceOutput/Drawing/ProcessWithDrawingCanvasTests/FontShapesAreRenderedCorrectlyWithAPenPatterned_Solid1100x200_(255,255,255,255)_pen_OpenSans-Regular.ttf-50-Sphi-(150,50).png b/tests/Images/ReferenceOutput/Drawing/ProcessWithDrawingCanvasTests/FontShapesAreRenderedCorrectlyWithAPenPatterned_Solid1100x200_(255,255,255,255)_pen_OpenSans-Regular.ttf-50-Sphi-(150,50).png
index 05f3920be..0f52a4739 100644
--- a/tests/Images/ReferenceOutput/Drawing/ProcessWithDrawingCanvasTests/FontShapesAreRenderedCorrectlyWithAPenPatterned_Solid1100x200_(255,255,255,255)_pen_OpenSans-Regular.ttf-50-Sphi-(150,50).png
+++ b/tests/Images/ReferenceOutput/Drawing/ProcessWithDrawingCanvasTests/FontShapesAreRenderedCorrectlyWithAPenPatterned_Solid1100x200_(255,255,255,255)_pen_OpenSans-Regular.ttf-50-Sphi-(150,50).png
@@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
-oid sha256:9ef455d55c25335f7a4e2f06839d12c19e0dba2c2ee98ffbc935340dfe08deb9
-size 17403
+oid sha256:4ee839a9c44cfa7093afb23f2136c711cefd5b1780854edb0512db6f904e2ed1
+size 38085
diff --git a/tests/Images/ReferenceOutput/Drawing/ProcessWithDrawingCanvasTests/FontShapesAreRenderedCorrectlyWithAPenPatterned_Solid200x150_(255,255,255,255)_pen_SixLaborsSampleAB.woff-50-ABAB-(0,0).png b/tests/Images/ReferenceOutput/Drawing/ProcessWithDrawingCanvasTests/FontShapesAreRenderedCorrectlyWithAPenPatterned_Solid200x150_(255,255,255,255)_pen_SixLaborsSampleAB.woff-50-ABAB-(0,0).png
index 35aee48da..a29acd6df 100644
--- a/tests/Images/ReferenceOutput/Drawing/ProcessWithDrawingCanvasTests/FontShapesAreRenderedCorrectlyWithAPenPatterned_Solid200x150_(255,255,255,255)_pen_SixLaborsSampleAB.woff-50-ABAB-(0,0).png
+++ b/tests/Images/ReferenceOutput/Drawing/ProcessWithDrawingCanvasTests/FontShapesAreRenderedCorrectlyWithAPenPatterned_Solid200x150_(255,255,255,255)_pen_SixLaborsSampleAB.woff-50-ABAB-(0,0).png
@@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
-oid sha256:8de455a71b21936c72cacb7e7fcd3fb72db733d5453f3a7c201ff3b151e8fafa
-size 782
+oid sha256:20515b0028bd2bcb94a5b53e2882b5993fbd1a21da004472f8aa602f814d0ae0
+size 3112
diff --git a/tests/Images/ReferenceOutput/Drawing/ProcessWithDrawingCanvasTests/FontShapesAreRenderedCorrectlyWithAPenPatterned_Solid900x150_(255,255,255,255)_pen_OpenSans-Regular.ttf-50-Sphi-(0,0).png b/tests/Images/ReferenceOutput/Drawing/ProcessWithDrawingCanvasTests/FontShapesAreRenderedCorrectlyWithAPenPatterned_Solid900x150_(255,255,255,255)_pen_OpenSans-Regular.ttf-50-Sphi-(0,0).png
index 21d70e20c..cd6915b11 100644
--- a/tests/Images/ReferenceOutput/Drawing/ProcessWithDrawingCanvasTests/FontShapesAreRenderedCorrectlyWithAPenPatterned_Solid900x150_(255,255,255,255)_pen_OpenSans-Regular.ttf-50-Sphi-(0,0).png
+++ b/tests/Images/ReferenceOutput/Drawing/ProcessWithDrawingCanvasTests/FontShapesAreRenderedCorrectlyWithAPenPatterned_Solid900x150_(255,255,255,255)_pen_OpenSans-Regular.ttf-50-Sphi-(0,0).png
@@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
-oid sha256:34fd9ba5131c64198ddb0a6c81cf518350f38fdff5284b7e6cefcf94a79fc76a
-size 16825
+oid sha256:ee2c7edfa8aec7afc14b47877fa7ca05f52da966e330042bd79178e46ea1190f
+size 36046
diff --git a/tests/Images/ReferenceOutput/Drawing/ProcessWithDrawingCanvasTests/FontShapesAreRenderedCorrectlyWithAPen_Solid1100x200_(255,255,255,255)_pen_OpenSans-Regular.ttf-50-Sphi-(150,50).png b/tests/Images/ReferenceOutput/Drawing/ProcessWithDrawingCanvasTests/FontShapesAreRenderedCorrectlyWithAPen_Solid1100x200_(255,255,255,255)_pen_OpenSans-Regular.ttf-50-Sphi-(150,50).png
index 580f7a7f2..943db2339 100644
--- a/tests/Images/ReferenceOutput/Drawing/ProcessWithDrawingCanvasTests/FontShapesAreRenderedCorrectlyWithAPen_Solid1100x200_(255,255,255,255)_pen_OpenSans-Regular.ttf-50-Sphi-(150,50).png
+++ b/tests/Images/ReferenceOutput/Drawing/ProcessWithDrawingCanvasTests/FontShapesAreRenderedCorrectlyWithAPen_Solid1100x200_(255,255,255,255)_pen_OpenSans-Regular.ttf-50-Sphi-(150,50).png
@@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
-oid sha256:be35a336f12a7e7511fa90243f731ab5e8dedcad85df938f716ac0603b1d9b92
-size 15152
+oid sha256:4fe14852d62ad698b2db8b77cc0c9f2be1de0eccc54515b05e8d7a358c473128
+size 30955
diff --git a/tests/Images/ReferenceOutput/Drawing/ProcessWithDrawingCanvasTests/FontShapesAreRenderedCorrectlyWithAPen_Solid200x150_(255,255,255,255)_pen_SixLaborsSampleAB.woff-50-ABAB-(0,0).png b/tests/Images/ReferenceOutput/Drawing/ProcessWithDrawingCanvasTests/FontShapesAreRenderedCorrectlyWithAPen_Solid200x150_(255,255,255,255)_pen_SixLaborsSampleAB.woff-50-ABAB-(0,0).png
index e51cf4369..2f5325cb0 100644
--- a/tests/Images/ReferenceOutput/Drawing/ProcessWithDrawingCanvasTests/FontShapesAreRenderedCorrectlyWithAPen_Solid200x150_(255,255,255,255)_pen_SixLaborsSampleAB.woff-50-ABAB-(0,0).png
+++ b/tests/Images/ReferenceOutput/Drawing/ProcessWithDrawingCanvasTests/FontShapesAreRenderedCorrectlyWithAPen_Solid200x150_(255,255,255,255)_pen_SixLaborsSampleAB.woff-50-ABAB-(0,0).png
@@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
-oid sha256:1f6013541369013118713742c04a1883513b9758979c86eec106a3ace342f318
-size 721
+oid sha256:3a72a1a1e03926086bd1fabc8cac1584f5573ea9ac552c56b779bf5526fa197d
+size 2559
diff --git a/tests/Images/ReferenceOutput/Drawing/ProcessWithDrawingCanvasTests/FontShapesAreRenderedCorrectlyWithAPen_Solid900x150_(255,255,255,255)_pen_OpenSans-Regular.ttf-50-Sphi-(0,0).png b/tests/Images/ReferenceOutput/Drawing/ProcessWithDrawingCanvasTests/FontShapesAreRenderedCorrectlyWithAPen_Solid900x150_(255,255,255,255)_pen_OpenSans-Regular.ttf-50-Sphi-(0,0).png
index c9592d88c..c4ff6581f 100644
--- a/tests/Images/ReferenceOutput/Drawing/ProcessWithDrawingCanvasTests/FontShapesAreRenderedCorrectlyWithAPen_Solid900x150_(255,255,255,255)_pen_OpenSans-Regular.ttf-50-Sphi-(0,0).png
+++ b/tests/Images/ReferenceOutput/Drawing/ProcessWithDrawingCanvasTests/FontShapesAreRenderedCorrectlyWithAPen_Solid900x150_(255,255,255,255)_pen_OpenSans-Regular.ttf-50-Sphi-(0,0).png
@@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
-oid sha256:912713a4fc32242beb54f9b5431efbed31c6f1bacc8aa82f169310d83c376244
-size 14644
+oid sha256:df75200415f775f3236cc6cda0d95da689c1fe49454c91d3255b2f236001f9ec
+size 29430
diff --git a/tests/Images/ReferenceOutput/Drawing/WebGPUDrawingBackendTests/DrawPath_PointStroke_LineCap_MatchesDefaultOutput_Round_Default.png b/tests/Images/ReferenceOutput/Drawing/WebGPUDrawingBackendTests/DrawPath_PointStroke_LineCap_MatchesDefaultOutput_Round_Default.png
index 024597cfd..3f7564852 100644
--- a/tests/Images/ReferenceOutput/Drawing/WebGPUDrawingBackendTests/DrawPath_PointStroke_LineCap_MatchesDefaultOutput_Round_Default.png
+++ b/tests/Images/ReferenceOutput/Drawing/WebGPUDrawingBackendTests/DrawPath_PointStroke_LineCap_MatchesDefaultOutput_Round_Default.png
@@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
-oid sha256:e66b8c19404367f773df2f385ebdaf782582a8ee818e0f2a8978e6d70a6421b0
-size 467
+oid sha256:a67ae75b0965797e4fb8670bcd45e296d8918dadff6622207308546a89632585
+size 2103
diff --git a/tests/Images/ReferenceOutput/Drawing/WebGPUDrawingBackendTests/DrawPath_PointStroke_LineCap_MatchesDefaultOutput_Round_WebGPU_NativeSurface.png b/tests/Images/ReferenceOutput/Drawing/WebGPUDrawingBackendTests/DrawPath_PointStroke_LineCap_MatchesDefaultOutput_Round_WebGPU_NativeSurface.png
index 11fd80d4a..3f7564852 100644
--- a/tests/Images/ReferenceOutput/Drawing/WebGPUDrawingBackendTests/DrawPath_PointStroke_LineCap_MatchesDefaultOutput_Round_WebGPU_NativeSurface.png
+++ b/tests/Images/ReferenceOutput/Drawing/WebGPUDrawingBackendTests/DrawPath_PointStroke_LineCap_MatchesDefaultOutput_Round_WebGPU_NativeSurface.png
@@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
-oid sha256:64d12dbda62fd48b1b60e2011d4e3adc53ef5a460eea42980a0f437d5f9f8cc0
-size 510
+oid sha256:a67ae75b0965797e4fb8670bcd45e296d8918dadff6622207308546a89632585
+size 2103
diff --git a/tests/Images/ReferenceOutput/Drawing/WebGPUDrawingBackendTests/DrawText_WithWebGPUCoverageBackend_RendersAndReleasesPreparedCoverage_Default.png b/tests/Images/ReferenceOutput/Drawing/WebGPUDrawingBackendTests/DrawText_WithWebGPUCoverageBackend_RendersAndReleasesPreparedCoverage_Default.png
index eb3e68769..112485707 100644
--- a/tests/Images/ReferenceOutput/Drawing/WebGPUDrawingBackendTests/DrawText_WithWebGPUCoverageBackend_RendersAndReleasesPreparedCoverage_Default.png
+++ b/tests/Images/ReferenceOutput/Drawing/WebGPUDrawingBackendTests/DrawText_WithWebGPUCoverageBackend_RendersAndReleasesPreparedCoverage_Default.png
@@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
-oid sha256:5a5db7127271bad880ce0650122ce26eb2eb62712ee7c37248dd290538fd32c4
-size 33191
+oid sha256:0c860d057b3c4451cdf0c32a42474dc0194667dd9a2d48a617faeef55ad6d48f
+size 48338
diff --git a/tests/Images/ReferenceOutput/Drawing/WebGPUDrawingBackendTests/DrawText_WithWebGPUCoverageBackend_RendersAndReleasesPreparedCoverage_WebGPU_NativeSurface.png b/tests/Images/ReferenceOutput/Drawing/WebGPUDrawingBackendTests/DrawText_WithWebGPUCoverageBackend_RendersAndReleasesPreparedCoverage_WebGPU_NativeSurface.png
index bdc36a98f..1edbe2c1f 100644
--- a/tests/Images/ReferenceOutput/Drawing/WebGPUDrawingBackendTests/DrawText_WithWebGPUCoverageBackend_RendersAndReleasesPreparedCoverage_WebGPU_NativeSurface.png
+++ b/tests/Images/ReferenceOutput/Drawing/WebGPUDrawingBackendTests/DrawText_WithWebGPUCoverageBackend_RendersAndReleasesPreparedCoverage_WebGPU_NativeSurface.png
@@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
-oid sha256:2b3fd5577ab3c9e7ae6c797633437be586db961fb9d544d98dc45c5051fe3473
-size 33189
+oid sha256:31dc27bdca6f453a91ad54edc694b302fefb43eefbcf995b23e0c826272b61c8
+size 48239
diff --git a/tests/Images/ReferenceOutput/Drawing/WebGPUDrawingBackendTests/Stroke_DistinguishesPointFromZeroLengthSegment_Butt_Default.png b/tests/Images/ReferenceOutput/Drawing/WebGPUDrawingBackendTests/Stroke_DistinguishesPointFromZeroLengthSegment_Butt_Default.png
new file mode 100644
index 000000000..b89861efb
--- /dev/null
+++ b/tests/Images/ReferenceOutput/Drawing/WebGPUDrawingBackendTests/Stroke_DistinguishesPointFromZeroLengthSegment_Butt_Default.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:c525131691b2c483b6fb92dce763f444e91fb098e076c897962a89a40370f5a0
+size 259
diff --git a/tests/Images/ReferenceOutput/Drawing/WebGPUDrawingBackendTests/Stroke_DistinguishesPointFromZeroLengthSegment_Butt_WebGPU_NativeSurface.png b/tests/Images/ReferenceOutput/Drawing/WebGPUDrawingBackendTests/Stroke_DistinguishesPointFromZeroLengthSegment_Butt_WebGPU_NativeSurface.png
new file mode 100644
index 000000000..5ea0c17fa
--- /dev/null
+++ b/tests/Images/ReferenceOutput/Drawing/WebGPUDrawingBackendTests/Stroke_DistinguishesPointFromZeroLengthSegment_Butt_WebGPU_NativeSurface.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:f2a72d38f4c51ac12e2bacc0db675e173630009d596f3aa40a028396175f8515
+size 252
diff --git a/tests/Images/ReferenceOutput/Drawing/WebGPUDrawingBackendTests/Stroke_DistinguishesPointFromZeroLengthSegment_Round_Default.png b/tests/Images/ReferenceOutput/Drawing/WebGPUDrawingBackendTests/Stroke_DistinguishesPointFromZeroLengthSegment_Round_Default.png
new file mode 100644
index 000000000..4f6046323
--- /dev/null
+++ b/tests/Images/ReferenceOutput/Drawing/WebGPUDrawingBackendTests/Stroke_DistinguishesPointFromZeroLengthSegment_Round_Default.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:d9c944ee3cb286994b45bfee52669e3739fd012f43f5c8c0b9f985406a5291b7
+size 538
diff --git a/tests/Images/ReferenceOutput/Drawing/WebGPUDrawingBackendTests/Stroke_DistinguishesPointFromZeroLengthSegment_Round_WebGPU_NativeSurface.png b/tests/Images/ReferenceOutput/Drawing/WebGPUDrawingBackendTests/Stroke_DistinguishesPointFromZeroLengthSegment_Round_WebGPU_NativeSurface.png
new file mode 100644
index 000000000..7179025f8
--- /dev/null
+++ b/tests/Images/ReferenceOutput/Drawing/WebGPUDrawingBackendTests/Stroke_DistinguishesPointFromZeroLengthSegment_Round_WebGPU_NativeSurface.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:298a3eb0a222981cce634d36997fee94d57497bddd778450d9efdeb53262b39a
+size 523
diff --git a/tests/Images/ReferenceOutput/Drawing/WebGPUDrawingBackendTests/Stroke_DistinguishesPointFromZeroLengthSegment_Square_Default.png b/tests/Images/ReferenceOutput/Drawing/WebGPUDrawingBackendTests/Stroke_DistinguishesPointFromZeroLengthSegment_Square_Default.png
new file mode 100644
index 000000000..213747c1f
--- /dev/null
+++ b/tests/Images/ReferenceOutput/Drawing/WebGPUDrawingBackendTests/Stroke_DistinguishesPointFromZeroLengthSegment_Square_Default.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:67aea6e3afff9e0d4770ec5734bceca22c9375b42980ffd31f9dccb4ffe3ad82
+size 384
diff --git a/tests/Images/ReferenceOutput/Drawing/WebGPUDrawingBackendTests/Stroke_DistinguishesPointFromZeroLengthSegment_Square_WebGPU_NativeSurface.png b/tests/Images/ReferenceOutput/Drawing/WebGPUDrawingBackendTests/Stroke_DistinguishesPointFromZeroLengthSegment_Square_WebGPU_NativeSurface.png
new file mode 100644
index 000000000..471076d8d
--- /dev/null
+++ b/tests/Images/ReferenceOutput/Drawing/WebGPUDrawingBackendTests/Stroke_DistinguishesPointFromZeroLengthSegment_Square_WebGPU_NativeSurface.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:835695520e7f5313bc14ebc05dc5daf470cd45b27f88730388417c2d80a8a93a
+size 372
diff --git a/tests/Images/ReferenceOutput/Drawing/WebGPUDrawingBackendTests/Stroke_EllipseWithMiterDashPattern_PreservesGaps_Default.png b/tests/Images/ReferenceOutput/Drawing/WebGPUDrawingBackendTests/Stroke_EllipseWithMiterDashPattern_PreservesGaps_Default.png
new file mode 100644
index 000000000..59bf2c90b
--- /dev/null
+++ b/tests/Images/ReferenceOutput/Drawing/WebGPUDrawingBackendTests/Stroke_EllipseWithMiterDashPattern_PreservesGaps_Default.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:c19ee0acb0b599848dacbc494931744a54ffa59bfbf5c7016ee4c5d541f4a228
+size 6782
diff --git a/tests/Images/ReferenceOutput/Drawing/WebGPUDrawingBackendTests/Stroke_EllipseWithMiterDashPattern_PreservesGaps_WebGPU_NativeSurface.png b/tests/Images/ReferenceOutput/Drawing/WebGPUDrawingBackendTests/Stroke_EllipseWithMiterDashPattern_PreservesGaps_WebGPU_NativeSurface.png
new file mode 100644
index 000000000..abe96ac7f
--- /dev/null
+++ b/tests/Images/ReferenceOutput/Drawing/WebGPUDrawingBackendTests/Stroke_EllipseWithMiterDashPattern_PreservesGaps_WebGPU_NativeSurface.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:045154ce2a261c1d68b68a676321a1343389e19185eb2f685f3cd5352dbc7f91
+size 6772
diff --git a/tests/Images/ReferenceOutput/Issue_330/OffsetTextOutlines_Rgba32_Solid2084x2084_(138,43,226,255).png b/tests/Images/ReferenceOutput/Issue_330/OffsetTextOutlines_Rgba32_Solid2084x2084_(138,43,226,255).png
index 9afca6047..b7d5a02e3 100644
--- a/tests/Images/ReferenceOutput/Issue_330/OffsetTextOutlines_Rgba32_Solid2084x2084_(138,43,226,255).png
+++ b/tests/Images/ReferenceOutput/Issue_330/OffsetTextOutlines_Rgba32_Solid2084x2084_(138,43,226,255).png
@@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
-oid sha256:08b3c17d2a334bafbdaf614c7c46ac93f4fcb9b5eeb9fe605a048dd93f7dfafe
-size 132091
+oid sha256:296e012fa501da04c837fa2a7b24153c663a80d01a7db564595bdfc2c76a7744
+size 169959
diff --git a/tests/Images/ReferenceOutput/Issue_367/BrushAndTextAlign_Rgba32.png b/tests/Images/ReferenceOutput/Issue_367/BrushAndTextAlign_Rgba32.png
index 920eeb24b..e777a6db4 100644
--- a/tests/Images/ReferenceOutput/Issue_367/BrushAndTextAlign_Rgba32.png
+++ b/tests/Images/ReferenceOutput/Issue_367/BrushAndTextAlign_Rgba32.png
@@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
-oid sha256:3a3ac3c4b0fa33dd5a277497f989b93f9e74937aff2b9b910082b8c855d54a8b
-size 8367
+oid sha256:ae08d23fbb8bc64061c083e2437618287d9bd2299d52e221f0ad2a974f744a03
+size 11917
diff --git a/tests/Images/ReferenceOutput/Issue_397/DrawTextWithIntersectingClip_Difference_IntersectingClip.png b/tests/Images/ReferenceOutput/Issue_397/DrawTextWithIntersectingClip_Difference_IntersectingClip.png
index c1557ee7d..2260f9d57 100644
--- a/tests/Images/ReferenceOutput/Issue_397/DrawTextWithIntersectingClip_Difference_IntersectingClip.png
+++ b/tests/Images/ReferenceOutput/Issue_397/DrawTextWithIntersectingClip_Difference_IntersectingClip.png
@@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
-oid sha256:192c3cd765feeef8f0b5a34295a61b129af869d819de6601b3c4ba6e48961374
-size 4600
+oid sha256:adf59769f23c6f5a39d7f9562c661300fef9ff124f663422a778363361e2e935
+size 6338
diff --git a/tests/Images/ReferenceOutput/Issue_397/DrawTextWithIntersectingClip_Intersection_IntersectingClip.png b/tests/Images/ReferenceOutput/Issue_397/DrawTextWithIntersectingClip_Intersection_IntersectingClip.png
index 60249b2b5..12e16c02b 100644
--- a/tests/Images/ReferenceOutput/Issue_397/DrawTextWithIntersectingClip_Intersection_IntersectingClip.png
+++ b/tests/Images/ReferenceOutput/Issue_397/DrawTextWithIntersectingClip_Intersection_IntersectingClip.png
@@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
-oid sha256:c3182516e904f7069752444240f7ac0d90337175cb8c48739a348ef42bab7c69
-size 4330
+oid sha256:56f310f0cb282fbcdc7418acf9831977293b7ea5082283389c989f0718c70e8b
+size 5885
diff --git a/tests/Images/ReferenceOutput/Issue_397/DrawTextWithNonIntersectingClip_Difference_NonIntersectingClip.png b/tests/Images/ReferenceOutput/Issue_397/DrawTextWithNonIntersectingClip_Difference_NonIntersectingClip.png
index 1f08251c2..199e63e21 100644
--- a/tests/Images/ReferenceOutput/Issue_397/DrawTextWithNonIntersectingClip_Difference_NonIntersectingClip.png
+++ b/tests/Images/ReferenceOutput/Issue_397/DrawTextWithNonIntersectingClip_Difference_NonIntersectingClip.png
@@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
-oid sha256:18d66c60ec48153e1bdc95c05eadfe6eaffd8d9c3d18e7c6027b38dc56c479ce
-size 4739
+oid sha256:6ebadb46a1c3f77370b2961a268610f136237951a77270a53c9a71a3bb7f47b3
+size 6702
diff --git a/tests/Images/ReferenceOutput/Issue_397/DrawTextWithNonIntersectingClip_Intersection_NonIntersectingClip.png b/tests/Images/ReferenceOutput/Issue_397/DrawTextWithNonIntersectingClip_Intersection_NonIntersectingClip.png
index 819a0e3c3..af28f4026 100644
--- a/tests/Images/ReferenceOutput/Issue_397/DrawTextWithNonIntersectingClip_Intersection_NonIntersectingClip.png
+++ b/tests/Images/ReferenceOutput/Issue_397/DrawTextWithNonIntersectingClip_Intersection_NonIntersectingClip.png
@@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
-oid sha256:9deb115879382e982756b7d15a5628e1a9a5d977eb9c9806d66ea404fcc123b8
-size 4183
+oid sha256:95ab03f4d74430d208d8aab0e3fd72b39d13d92b49529101f9f883b2f86c7765
+size 5821