Skip to content

Commit a4e94b8

Browse files
Merge pull request #436 from SixLabors/js/gradient-alpha-and-pen-fill
Add gradient alpha interpolation option and Fill(Pen)
1 parent 6f792ac commit a4e94b8

56 files changed

Lines changed: 837 additions & 182 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎src/ImageSharp.Drawing.WebGPU/Shaders/WgslSource/fine.wgsl‎

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -430,6 +430,9 @@ fn image_extend_mode_i32(t: f32, mode: u32, max: i32) -> i32 {
430430
// Flag bit indicating the gradient carries an explicit center color, which
431431
// disables the single-triangle barycentric shortcut.
432432
const PATH_GRAD_HAS_EXPLICIT_CENTER_COLOR = 1u;
433+
// This flag bit shows that the payload colors are unassociated. The shader interpolates
434+
// these colors, and then it premultiplies the result.
435+
const PATH_GRAD_UNASSOCIATED_INTERPOLATION = 2u;
433436
// Info-stream layout: a 7-word header (center point, max ray distance, and four
434437
// center-color components) followed by 12-word edge records (start point, end
435438
// point, and four components for each endpoint color).
@@ -447,7 +450,8 @@ fn path_grad_load_point(offset: u32) -> vec2<f32> {
447450
return vec2<f32>(bitcast<f32>(info[offset]), bitcast<f32>(info[offset + 1u]));
448451
}
449452

450-
// Loads an associated color stored as four f32 words in the info stream.
453+
// Loads a color stored as four f32 words in the info stream. The flags of the
454+
// gradient give the alpha representation of the color.
451455
fn path_grad_load_color(offset: u32) -> vec4<f32> {
452456
return vec4<f32>(
453457
bitcast<f32>(info[offset]),
@@ -509,15 +513,28 @@ fn path_grad_point_on_triangle(v1: vec2<f32>, v2: vec2<f32>, v3: vec2<f32>, poin
509513
}
510514

511515
// Evaluates the path gradient brush at a point, returning an associated color.
512-
// Payload colors are associated before interpolation as required by CSS Color 4:
516+
// CSS Color 4 interpolates associated colors. SVG 2 interpolates unassociated colors,
517+
// so the shader premultiplies the result of an unassociated gradient.
513518
// https://www.w3.org/TR/css-color-4/#interpolation-alpha
519+
// https://www.w3.org/TR/SVG2/pservers.html#StopColorProperties
520+
fn evaluate_path_gradient(path_grad: CmdPathGrad, point: vec2<f32>) -> vec4<f32> {
521+
let color = interpolate_path_gradient(path_grad, point);
522+
if (path_grad.flags & PATH_GRAD_UNASSOCIATED_INTERPOLATION) != 0u {
523+
return premul_alpha(color);
524+
}
525+
526+
return color;
527+
}
528+
529+
// Interpolates the path gradient brush at a point. The result has the alpha
530+
// representation of the payload colors.
514531
// A three-edge gradient without an explicit center color interpolates
515532
// its vertex colors barycentrically. Otherwise a ray is cast from the point
516533
// away from the gradient center to find the nearest edge intersection; the
517534
// interpolated edge color is then mixed toward the center color by the ratio
518535
// of the point's distance from the edge to the center's distance from the
519536
// edge. Returns transparent when the point is not covered by any edge.
520-
fn evaluate_path_gradient(path_grad: CmdPathGrad, point: vec2<f32>) -> vec4<f32> {
537+
fn interpolate_path_gradient(path_grad: CmdPathGrad, point: vec2<f32>) -> vec4<f32> {
521538
let center = path_grad_load_point(path_grad.data_offset);
522539
let center_color = path_grad_load_color(path_grad.data_offset + 3u);
523540

‎src/ImageSharp.Drawing.WebGPU/WebGPUBackdropAcrylicLayerEffect.cs‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ public WebGPUBackdropAcrylicLayerEffect(float sigma, Color tint)
4848
/// <param name="color">The acrylic tint.</param>
4949
private void AddPasses(float sigma, Color color)
5050
{
51-
Vector4 vector = color.ToScaledVector4(PixelAlphaRepresentation.Unassociated);
51+
Vector4 vector = color.ToScaledVector4(PixelAlphaRepresentation.Associated);
5252

5353
// Source RGB is retained by (1 - tint alpha), while the constant row contributes the
5454
// premultiplied tint. Alpha is preserved so the backdrop keeps its existing coverage.
@@ -58,9 +58,9 @@ private void AddPasses(float sigma, Color color)
5858
tint.M22 = keep;
5959
tint.M33 = keep;
6060
tint.M44 = 1F;
61-
tint.M51 = vector.X * vector.W;
62-
tint.M52 = vector.Y * vector.W;
63-
tint.M53 = vector.Z * vector.W;
61+
tint.M51 = vector.X;
62+
tint.M52 = vector.Y;
63+
tint.M53 = vector.Z;
6464

6565
WebGPUColorMatrixLayerEffect tintEffect = new(tint);
6666
ReadOnlySpan<WebGPUShaderPass> tintPasses = tintEffect.GetShaderPasses();

‎src/ImageSharp.Drawing.WebGPU/WebGPUSceneEncoder.cs‎

Lines changed: 59 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -6398,6 +6398,7 @@ public static WebGPUEncodedScene Resolve(
63986398

63996399
gradientRamps.Add(new GpuGradientRampDescriptor(
64006400
gradientRamp.ColorStops,
6401+
gradientRamp.AlphaRepresentation,
64016402
gradientRowOffset + gradientRamp.RowIndex));
64026403
}
64036404

@@ -9229,7 +9230,7 @@ private static void AppendLinearGradientData(
92299230
{
92309231
uint indexMode = ((uint)gradientRowCount << 2) | MapExtendMode(brush.RepetitionMode);
92319232
AppendGradientRamp(ref gradientPixels);
9232-
gradientRamps.Add(new GpuGradientRampDescriptor(brush.ColorStops.ToArray(), gradientRowCount));
9233+
gradientRamps.Add(new GpuGradientRampDescriptor(brush.ColorStops.ToArray(), brush.AlphaRepresentation, gradientRowCount));
92339234
gradientRowCount++;
92349235

92359236
drawData.Add(indexMode);
@@ -9280,7 +9281,7 @@ private static void AppendRadialGradientData(
92809281
{
92819282
uint indexMode = ((uint)gradientRowCount << 2) | MapExtendMode(brush.RepetitionMode);
92829283
AppendGradientRamp(ref gradientPixels);
9283-
gradientRamps.Add(new GpuGradientRampDescriptor(brush.ColorStops.ToArray(), gradientRowCount));
9284+
gradientRamps.Add(new GpuGradientRampDescriptor(brush.ColorStops.ToArray(), brush.AlphaRepresentation, gradientRowCount));
92849285
gradientRowCount++;
92859286

92869287
PointF center0;
@@ -9330,7 +9331,7 @@ private static void AppendEllipticGradientData(
93309331
{
93319332
uint indexMode = ((uint)gradientRowCount << 2) | MapExtendMode(brush.RepetitionMode);
93329333
AppendGradientRamp(ref gradientPixels);
9333-
gradientRamps.Add(new GpuGradientRampDescriptor(brush.ColorStops.ToArray(), gradientRowCount));
9334+
gradientRamps.Add(new GpuGradientRampDescriptor(brush.ColorStops.ToArray(), brush.AlphaRepresentation, gradientRowCount));
93349335
gradientRowCount++;
93359336

93369337
// Brushes reach the encoder after batcher normalization, so gradient payload points are
@@ -9369,7 +9370,7 @@ private static void AppendSweepGradientData(
93699370
{
93709371
uint indexMode = ((uint)gradientRowCount << 2) | MapExtendMode(brush.RepetitionMode);
93719372
AppendGradientRamp(ref gradientPixels);
9372-
gradientRamps.Add(new GpuGradientRampDescriptor(brush.ColorStops.ToArray(), gradientRowCount));
9373+
gradientRamps.Add(new GpuGradientRampDescriptor(brush.ColorStops.ToArray(), brush.AlphaRepresentation, gradientRowCount));
93739374
gradientRowCount++;
93749375

93759376
float sweepDegrees = brush.EndAngleDegrees - brush.StartAngleDegrees;
@@ -9407,6 +9408,7 @@ private static void AppendPathGradientData(
94079408
{
94089409
ReadOnlySpan<PointF> points = brush.Points;
94099410
ReadOnlySpan<Color> colors = brush.Colors;
9411+
PixelAlphaRepresentation alphaRepresentation = brush.AlphaRepresentation;
94109412
int edgeCount = points.Length;
94119413
PointF center = default;
94129414

@@ -9432,7 +9434,7 @@ private static void AppendPathGradientData(
94329434
payload[0] = BitcastSingle(center.X);
94339435
payload[1] = BitcastSingle(center.Y);
94349436
payload[2] = BitcastSingle(maxDistance);
9435-
WriteAssociatedColor(payload, 3, brush.CenterColor);
9437+
WritePathGradientColor(payload, 3, brush.CenterColor, alphaRepresentation);
94369438

94379439
for (int i = 0; i < edgeCount; i++)
94389440
{
@@ -9446,14 +9448,22 @@ private static void AppendPathGradientData(
94469448
payload[payloadOffset + 1] = BitcastSingle(start.Y);
94479449
payload[payloadOffset + 2] = BitcastSingle(end.X);
94489450
payload[payloadOffset + 3] = BitcastSingle(end.Y);
9449-
WriteAssociatedColor(payload, payloadOffset + 4, colors[i % colors.Length]);
9450-
WriteAssociatedColor(payload, payloadOffset + 8, colors[(i + 1) % colors.Length]);
9451+
WritePathGradientColor(payload, payloadOffset + 4, colors[i % colors.Length], alphaRepresentation);
9452+
WritePathGradientColor(payload, payloadOffset + 8, colors[(i + 1) % colors.Length], alphaRepresentation);
9453+
}
9454+
9455+
// These bits match PATH_GRAD_HAS_EXPLICIT_CENTER_COLOR and PATH_GRAD_UNASSOCIATED_INTERPOLATION
9456+
// in fine.wgsl.
9457+
uint flags = brush.HasExplicitCenterColor ? 1U : 0U;
9458+
if (alphaRepresentation != PixelAlphaRepresentation.Associated)
9459+
{
9460+
flags |= 2U;
94519461
}
94529462

94539463
pathGradientData.Advance(payload.Length);
94549464
drawData.Add((uint)dataOffset);
94559465
drawData.Add((uint)edgeCount);
9456-
drawData.Add(brush.HasExplicitCenterColor ? 1U : 0U);
9466+
drawData.Add(flags);
94579467
drawData.Add(0U);
94589468
}
94599469

@@ -9475,12 +9485,13 @@ private static void AppendGradientRamp(ref OwnedStream<uint> gradientPixels)
94759485
}
94769486

94779487
/// <summary>
9478-
/// Evaluates the premultiplied gradient color at the normalized parameter.
9488+
/// Evaluates the gradient color at the normalized parameter.
94799489
/// </summary>
94809490
/// <param name="colorStops">The gradient color stops, ordered by ratio.</param>
9491+
/// <param name="alphaRepresentation">The alpha representation of the stop colors during interpolation.</param>
94819492
/// <param name="t">The normalized sample position in the range [0, 1].</param>
9482-
/// <returns>The associated floating-point sample.</returns>
9483-
public static Vector4 EvaluateGradientColor(ReadOnlySpan<ColorStop> colorStops, float t)
9493+
/// <returns>The floating-point sample in <paramref name="alphaRepresentation"/>.</returns>
9494+
public static Vector4 EvaluateGradientColor(ReadOnlySpan<ColorStop> colorStops, PixelAlphaRepresentation alphaRepresentation, float t)
94849495
{
94859496
// Walk the stop list once to find the enclosing interval, then interpolate within it.
94869497
ColorStop from = colorStops[0];
@@ -9498,16 +9509,16 @@ public static Vector4 EvaluateGradientColor(ReadOnlySpan<ColorStop> colorStops,
94989509

94999510
if (from.Color.Equals(to.Color) || to.Ratio == from.Ratio)
95009511
{
9501-
return from.Color.ToScaledVector4(PixelAlphaRepresentation.Associated);
9512+
return from.Color.ToScaledVector4(alphaRepresentation);
95029513
}
95039514

95049515
float localT = (t - from.Ratio) / (to.Ratio - from.Ratio);
95059516

9506-
// CSS Color 4 requires alpha premultiplication before interpolation. The ramp stores
9507-
// associated RGBA16Float directly, matching the fine shader's internal composition space.
9517+
// CSS Color 4 interpolates associated colors. SVG 2 interpolates unassociated colors.
9518+
// The stops use the alpha representation of the brush.
95089519
return Vector4.Lerp(
9509-
from.Color.ToScaledVector4(PixelAlphaRepresentation.Associated),
9510-
to.Color.ToScaledVector4(PixelAlphaRepresentation.Associated),
9520+
from.Color.ToScaledVector4(alphaRepresentation),
9521+
to.Color.ToScaledVector4(alphaRepresentation),
95119522
localT);
95129523
}
95139524

@@ -9533,16 +9544,17 @@ public static uint PackHalf2(float x, float y)
95339544
=> BitConverter.HalfToUInt16Bits((Half)x) | ((uint)BitConverter.HalfToUInt16Bits((Half)y) << 16);
95349545

95359546
/// <summary>
9536-
/// Writes one associated color to the path-gradient payload without reducing it to RGBA8 first.
9547+
/// Writes one color to the path-gradient payload without reducing it to RGBA8 first.
95379548
/// </summary>
95389549
/// <param name="destination">The payload receiving four consecutive floating-point words.</param>
95399550
/// <param name="offset">The destination word offset.</param>
9540-
/// <param name="color">The color to convert to associated components.</param>
9541-
private static void WriteAssociatedColor(Span<uint> destination, int offset, in Color color)
9551+
/// <param name="color">The color to write.</param>
9552+
/// <param name="alphaRepresentation">The alpha representation of the colors during interpolation.</param>
9553+
private static void WritePathGradientColor(Span<uint> destination, int offset, in Color color, PixelAlphaRepresentation alphaRepresentation)
95429554
{
95439555
// Path gradients interpolate endpoint colors directly in the shader. Keeping the source
95449556
// precision here matches the CPU renderer and defers quantization until target encoding.
9545-
Vector4 vector = color.ToScaledVector4(PixelAlphaRepresentation.Associated);
9557+
Vector4 vector = color.ToScaledVector4(alphaRepresentation);
95469558
destination[offset] = BitcastSingle(vector.X);
95479559
destination[offset + 1] = BitcastSingle(vector.Y);
95489560
destination[offset + 2] = BitcastSingle(vector.Z);
@@ -10430,9 +10442,8 @@ public void SpecializeBrushColors<TPixel>()
1043010442
return;
1043110443
}
1043210444

10433-
PixelAlphaRepresentation alphaRepresentation = TPixel.GetPixelTypeInfo().AlphaRepresentation;
10434-
this.SpecializeSolidColors<TPixel>(alphaRepresentation);
10435-
this.SpecializeGradientRamps<TPixel>(alphaRepresentation);
10445+
this.SpecializeSolidColors<TPixel>();
10446+
this.SpecializeGradientRamps<TPixel>();
1043610447
this.specializedPixelType = typeof(TPixel);
1043710448
}
1043810449

@@ -10442,22 +10453,16 @@ public void SpecializeBrushColors<TPixel>()
1044210453
/// it creates its CPU renderer.
1044310454
/// </summary>
1044410455
/// <typeparam name="TPixel">The pixel format of the target.</typeparam>
10445-
/// <param name="alphaRepresentation">The alpha representation of <typeparamref name="TPixel"/>.</param>
10446-
private void SpecializeSolidColors<TPixel>(PixelAlphaRepresentation alphaRepresentation)
10456+
private void SpecializeSolidColors<TPixel>()
1044710457
where TPixel : unmanaged, IPixel<TPixel>
1044810458
{
1044910459
for (int i = 0; i < this.solidColors.Count; i++)
1045010460
{
1045110461
GpuSolidColorDescriptor descriptor = this.solidColors[i];
10452-
Vector4 color = descriptor.Color.ToPixel<TPixel>().ToScaledVector4();
10453-
if (alphaRepresentation != PixelAlphaRepresentation.Associated)
10454-
{
10455-
// Associating rounds the product into binary16; see the precision contract on
10456-
// SpecializeBrushColors.
10457-
float alpha = color.W;
10458-
color *= alpha;
10459-
color.W = alpha;
10460-
}
10462+
10463+
// For a TPixel with unassociated alpha, the associated product rounds to binary16.
10464+
// The precision contract on SpecializeBrushColors gives the effect.
10465+
Vector4 color = descriptor.Color.ToPixel<TPixel>().ToAssociatedScaledVector4();
1046110466

1046210467
int wordIndex = checked((int)this.Layout.DrawDataBase + descriptor.DrawDataWordOffset);
1046310468
this.SetSceneWord(wordIndex, WebGPUSceneEncoder.PackHalf2(color.X, color.Y));
@@ -10471,8 +10476,7 @@ private void SpecializeSolidColors<TPixel>(PixelAlphaRepresentation alphaReprese
1047110476
/// encoders perform before blending.
1047210477
/// </summary>
1047310478
/// <typeparam name="TPixel">The pixel format of the target.</typeparam>
10474-
/// <param name="alphaRepresentation">The alpha representation of <typeparamref name="TPixel"/>.</param>
10475-
private void SpecializeGradientRamps<TPixel>(PixelAlphaRepresentation alphaRepresentation)
10479+
private void SpecializeGradientRamps<TPixel>()
1047610480
where TPixel : unmanaged, IPixel<TPixel>
1047710481
{
1047810482
if (this.gradientPixelsOwner is null)
@@ -10484,37 +10488,22 @@ private void SpecializeGradientRamps<TPixel>(PixelAlphaRepresentation alphaRepre
1048410488
for (int i = 0; i < this.gradientRamps.Count; i++)
1048510489
{
1048610490
GpuGradientRampDescriptor descriptor = this.gradientRamps[i];
10491+
bool associated = descriptor.AlphaRepresentation == PixelAlphaRepresentation.Associated;
1048710492
int rowBase = descriptor.RowIndex * WebGPUSceneEncoder.GradientRowWordCount;
1048810493
for (int x = 0; x < WebGPUSceneEncoder.GradientWidth; x++)
1048910494
{
1049010495
float t = x / (float)(WebGPUSceneEncoder.GradientWidth - 1);
10491-
Vector4 color = WebGPUSceneEncoder.EvaluateGradientColor(descriptor.ColorStops, t);
10492-
if (alphaRepresentation == PixelAlphaRepresentation.Associated)
10493-
{
10494-
color = TPixel.FromScaledVector4(color).ToScaledVector4();
10495-
}
10496-
else
10497-
{
10498-
// The CPU's straight-alpha encoder undoes the interpolation-time
10499-
// premultiplication before converting to TPixel, so the same division
10500-
// precedes the snap. Re-associating rounds the product into binary16;
10501-
// see the precision contract on SpecializeBrushColors.
10502-
float alpha = color.W;
10503-
if (alpha > 0)
10504-
{
10505-
color /= alpha;
10506-
color.W = alpha;
10507-
}
10508-
else
10509-
{
10510-
color = Vector4.Zero;
10511-
}
10496+
Vector4 color = WebGPUSceneEncoder.EvaluateGradientColor(descriptor.ColorStops, descriptor.AlphaRepresentation, t);
1051210497

10513-
color = TPixel.FromScaledVector4(color).ToScaledVector4();
10514-
float snappedAlpha = color.W;
10515-
color *= snappedAlpha;
10516-
color.W = snappedAlpha;
10517-
}
10498+
// The texel snaps through TPixel, as in the CPU gradient encoders. The ramp stores
10499+
// associated RGBA16Float, which is the composition space of the fine shader.
10500+
// For a TPixel with unassociated alpha, the associated product rounds to binary16.
10501+
// The precision contract on SpecializeBrushColors gives the effect.
10502+
TPixel pixel = associated
10503+
? TPixel.FromAssociatedScaledVector4(color)
10504+
: TPixel.FromUnassociatedScaledVector4(color);
10505+
10506+
color = pixel.ToAssociatedScaledVector4();
1051810507

1051910508
gradientPixels[rowBase + (x * 2)] = WebGPUSceneEncoder.PackHalf2(color.X, color.Y);
1052010509
gradientPixels[rowBase + (x * 2) + 1] = WebGPUSceneEncoder.PackHalf2(color.Z, color.W);
@@ -10749,10 +10738,12 @@ internal readonly struct GpuGradientRampDescriptor
1074910738
/// Initializes a new instance of the <see cref="GpuGradientRampDescriptor"/> struct.
1075010739
/// </summary>
1075110740
/// <param name="colorStops">The gradient color stops, ordered by ratio.</param>
10741+
/// <param name="alphaRepresentation">The alpha representation of the stop colors during interpolation.</param>
1075210742
/// <param name="rowIndex">The ramp texture row the gradient occupies.</param>
10753-
public GpuGradientRampDescriptor(ColorStop[] colorStops, int rowIndex)
10743+
public GpuGradientRampDescriptor(ColorStop[] colorStops, PixelAlphaRepresentation alphaRepresentation, int rowIndex)
1075410744
{
1075510745
this.ColorStops = colorStops;
10746+
this.AlphaRepresentation = alphaRepresentation;
1075610747
this.RowIndex = rowIndex;
1075710748
}
1075810749

@@ -10761,6 +10752,11 @@ public GpuGradientRampDescriptor(ColorStop[] colorStops, int rowIndex)
1076110752
/// </summary>
1076210753
public ColorStop[] ColorStops { get; }
1076310754

10755+
/// <summary>
10756+
/// Gets the alpha representation of the stop colors during interpolation.
10757+
/// </summary>
10758+
public PixelAlphaRepresentation AlphaRepresentation { get; }
10759+
1076410760
/// <summary>
1076510761
/// Gets the ramp texture row the gradient occupies.
1076610762
/// </summary>

‎src/ImageSharp.Drawing/ImageSharp.Drawing.csproj‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@
4545
</ItemGroup>
4646
<ItemGroup>
4747
<PackageReference Include="SixLabors.Fonts" Version="3.2.1" />
48-
<PackageReference Include="SixLabors.ImageSharp" Version="4.1.2" />
48+
<PackageReference Include="SixLabors.ImageSharp" Version="5.0.0-alpha.0.38" />
4949
<PackageReference Include="SixLabors.PolygonClipper" Version="2.0.0-alpha.0.2" />
5050
</ItemGroup>
5151
<ItemGroup>

0 commit comments

Comments
 (0)