shaders.hlsl

   1#include "alpha_correction.hlsl"
   2
   3cbuffer GlobalParams: register(b0) {
   4    float4 gamma_ratios;
   5    float2 global_viewport_size;
   6    float grayscale_enhanced_contrast;
   7    uint _pad;
   8};
   9
  10Texture2D<float4> t_sprite: register(t0);
  11SamplerState s_sprite: register(s0);
  12
  13struct Bounds {
  14    float2 origin;
  15    float2 size;
  16};
  17
  18struct Corners {
  19    float top_left;
  20    float top_right;
  21    float bottom_right;
  22    float bottom_left;
  23};
  24
  25struct Edges {
  26    float top;
  27    float right;
  28    float bottom;
  29    float left;
  30};
  31
  32struct Hsla {
  33    float h;
  34    float s;
  35    float l;
  36    float a;
  37};
  38
  39struct LinearColorStop {
  40    Hsla color;
  41    float percentage;
  42};
  43
  44struct Background {
  45    // 0u is Solid
  46    // 1u is LinearGradient
  47    // 2u is PatternSlash
  48    uint tag;
  49    // 0u is sRGB linear color
  50    // 1u is Oklab color
  51    uint color_space;
  52    Hsla solid;
  53    float gradient_angle_or_pattern_height;
  54    LinearColorStop colors[2];
  55    uint pad;
  56};
  57
  58struct GradientColor {
  59  float4 solid;
  60  float4 color0;
  61  float4 color1;
  62};
  63
  64struct AtlasTextureId {
  65    uint index;
  66    uint kind;
  67};
  68
  69struct AtlasBounds {
  70    int2 origin;
  71    int2 size;
  72};
  73
  74struct AtlasTile {
  75    AtlasTextureId texture_id;
  76    uint tile_id;
  77    uint padding;
  78    AtlasBounds bounds;
  79};
  80
  81struct TransformationMatrix {
  82    float2x2 rotation_scale;
  83    float2 translation;
  84};
  85
  86static const float M_PI_F = 3.141592653f;
  87static const float3 GRAYSCALE_FACTORS = float3(0.2126f, 0.7152f, 0.0722f);
  88
  89float4 to_device_position_impl(float2 position) {
  90    float2 device_position = position / global_viewport_size * float2(2.0, -2.0) + float2(-1.0, 1.0);
  91    return float4(device_position, 0., 1.);
  92}
  93
  94float4 to_device_position(float2 unit_vertex, Bounds bounds) {
  95    float2 position = unit_vertex * bounds.size + bounds.origin;
  96    return to_device_position_impl(position);
  97}
  98
  99float4 distance_from_clip_rect_impl(float2 position, Bounds clip_bounds) {
 100    float2 tl = position - clip_bounds.origin;
 101    float2 br = clip_bounds.origin + clip_bounds.size - position;
 102    return float4(tl.x, br.x, tl.y, br.y);
 103}
 104
 105float4 distance_from_clip_rect(float2 unit_vertex, Bounds bounds, Bounds clip_bounds) {
 106    float2 position = unit_vertex * bounds.size + bounds.origin;
 107    return distance_from_clip_rect_impl(position, clip_bounds);
 108}
 109
 110float4 distance_from_clip_rect_transformed(float2 unit_vertex, Bounds bounds, Bounds clip_bounds, TransformationMatrix transformation) {
 111    float2 position = unit_vertex * bounds.size + bounds.origin;
 112    float2 transformed = mul(position, transformation.rotation_scale) + transformation.translation;
 113    return distance_from_clip_rect_impl(transformed, clip_bounds);
 114}
 115
 116// Convert linear RGB to sRGB
 117float3 linear_to_srgb(float3 color) {
 118    return pow(color, float3(2.2, 2.2, 2.2));
 119}
 120
 121// Convert sRGB to linear RGB
 122float3 srgb_to_linear(float3 color) {
 123    return pow(color, float3(1.0 / 2.2, 1.0 / 2.2, 1.0 / 2.2));
 124}
 125
 126/// Hsla to linear RGBA conversion.
 127float4 hsla_to_rgba(Hsla hsla) {
 128    float h = hsla.h * 6.0; // Now, it's an angle but scaled in [0, 6) range
 129    float s = hsla.s;
 130    float l = hsla.l;
 131    float a = hsla.a;
 132
 133    float c = (1.0 - abs(2.0 * l - 1.0)) * s;
 134    float x = c * (1.0 - abs(fmod(h, 2.0) - 1.0));
 135    float m = l - c / 2.0;
 136
 137    float r = 0.0;
 138    float g = 0.0;
 139    float b = 0.0;
 140
 141    if (h >= 0.0 && h < 1.0) {
 142        r = c;
 143        g = x;
 144        b = 0.0;
 145    } else if (h >= 1.0 && h < 2.0) {
 146        r = x;
 147        g = c;
 148        b = 0.0;
 149    } else if (h >= 2.0 && h < 3.0) {
 150        r = 0.0;
 151        g = c;
 152        b = x;
 153    } else if (h >= 3.0 && h < 4.0) {
 154        r = 0.0;
 155        g = x;
 156        b = c;
 157    } else if (h >= 4.0 && h < 5.0) {
 158        r = x;
 159        g = 0.0;
 160        b = c;
 161    } else {
 162        r = c;
 163        g = 0.0;
 164        b = x;
 165    }
 166
 167    float4 rgba;
 168    rgba.x = (r + m);
 169    rgba.y = (g + m);
 170    rgba.z = (b + m);
 171    rgba.w = a;
 172    return rgba;
 173}
 174
 175// Converts a sRGB color to the Oklab color space.
 176// Reference: https://bottosson.github.io/posts/oklab/#converting-from-linear-srgb-to-oklab
 177float4 srgb_to_oklab(float4 color) {
 178    // Convert non-linear sRGB to linear sRGB
 179    color = float4(srgb_to_linear(color.rgb), color.a);
 180
 181    float l = 0.4122214708 * color.r + 0.5363325363 * color.g + 0.0514459929 * color.b;
 182    float m = 0.2119034982 * color.r + 0.6806995451 * color.g + 0.1073969566 * color.b;
 183    float s = 0.0883024619 * color.r + 0.2817188376 * color.g + 0.6299787005 * color.b;
 184
 185    float l_ = pow(l, 1.0/3.0);
 186    float m_ = pow(m, 1.0/3.0);
 187    float s_ = pow(s, 1.0/3.0);
 188
 189    return float4(
 190        0.2104542553 * l_ + 0.7936177850 * m_ - 0.0040720468 * s_,
 191        1.9779984951 * l_ - 2.4285922050 * m_ + 0.4505937099 * s_,
 192        0.0259040371 * l_ + 0.7827717662 * m_ - 0.8086757660 * s_,
 193        color.a
 194    );
 195}
 196
 197// Converts an Oklab color to the sRGB color space.
 198float4 oklab_to_srgb(float4 color) {
 199    float l_ = color.r + 0.3963377774 * color.g + 0.2158037573 * color.b;
 200    float m_ = color.r - 0.1055613458 * color.g - 0.0638541728 * color.b;
 201    float s_ = color.r - 0.0894841775 * color.g - 1.2914855480 * color.b;
 202
 203    float l = l_ * l_ * l_;
 204    float m = m_ * m_ * m_;
 205    float s = s_ * s_ * s_;
 206
 207    float3 linear_rgb = float3(
 208        4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s,
 209        -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s,
 210        -0.0041960863 * l - 0.7034186147 * m + 1.7076147010 * s
 211    );
 212
 213    // Convert linear sRGB to non-linear sRGB
 214    return float4(linear_to_srgb(linear_rgb), color.a);
 215}
 216
 217// This approximates the error function, needed for the gaussian integral
 218float2 erf(float2 x) {
 219    float2 s = sign(x);
 220    float2 a = abs(x);
 221    x = 1. + (0.278393 + (0.230389 + 0.078108 * (a * a)) * a) * a;
 222    x *= x;
 223    return s - s / (x * x);
 224}
 225
 226float blur_along_x(float x, float y, float sigma, float corner, float2 half_size) {
 227    float delta = min(half_size.y - corner - abs(y), 0.);
 228    float curved = half_size.x - corner + sqrt(max(0., corner * corner - delta * delta));
 229    float2 integral = 0.5 + 0.5 * erf((x + float2(-curved, curved)) * (sqrt(0.5) / sigma));
 230    return integral.y - integral.x;
 231}
 232
 233// A standard gaussian function, used for weighting samples
 234float gaussian(float x, float sigma) {
 235    return exp(-(x * x) / (2. * sigma * sigma)) / (sqrt(2. * M_PI_F) * sigma);
 236}
 237
 238float4 over(float4 below, float4 above) {
 239    float4 result;
 240    float alpha = above.a + below.a * (1.0 - above.a);
 241    result.rgb = (above.rgb * above.a + below.rgb * below.a * (1.0 - above.a)) / alpha;
 242    result.a = alpha;
 243    return result;
 244}
 245
 246float2 to_tile_position(float2 unit_vertex, AtlasTile tile) {
 247    float2 atlas_size;
 248    t_sprite.GetDimensions(atlas_size.x, atlas_size.y);
 249    return (float2(tile.bounds.origin) + unit_vertex * float2(tile.bounds.size)) / atlas_size;
 250}
 251
 252// Selects corner radius based on quadrant.
 253float pick_corner_radius(float2 center_to_point, Corners corner_radii) {
 254    if (center_to_point.x < 0.) {
 255        if (center_to_point.y < 0.) {
 256            return corner_radii.top_left;
 257        } else {
 258            return corner_radii.bottom_left;
 259        }
 260    } else {
 261        if (center_to_point.y < 0.) {
 262            return corner_radii.top_right;
 263        } else {
 264            return corner_radii.bottom_right;
 265        }
 266    }
 267}
 268
 269float4 to_device_position_transformed(float2 unit_vertex, Bounds bounds,
 270                                      TransformationMatrix transformation) {
 271    float2 position = unit_vertex * bounds.size + bounds.origin;
 272    float2 transformed = mul(position, transformation.rotation_scale) + transformation.translation;
 273    float2 device_position = transformed / global_viewport_size * float2(2.0, -2.0) + float2(-1.0, 1.0);
 274    return float4(device_position, 0.0, 1.0);
 275}
 276
 277// Implementation of quad signed distance field
 278float quad_sdf_impl(float2 corner_center_to_point, float corner_radius) {
 279    if (corner_radius == 0.0) {
 280        // Fast path for unrounded corners
 281        return max(corner_center_to_point.x, corner_center_to_point.y);
 282    } else {
 283        // Signed distance of the point from a quad that is inset by corner_radius
 284        // It is negative inside this quad, and positive outside
 285        float signed_distance_to_inset_quad =
 286            // 0 inside the inset quad, and positive outside
 287            length(max(float2(0.0, 0.0), corner_center_to_point)) +
 288            // 0 outside the inset quad, and negative inside
 289            min(0.0, max(corner_center_to_point.x, corner_center_to_point.y));
 290
 291        return signed_distance_to_inset_quad - corner_radius;
 292    }
 293}
 294
 295float quad_sdf(float2 pt, Bounds bounds, Corners corner_radii) {
 296    float2 half_size = bounds.size / 2.;
 297    float2 center = bounds.origin + half_size;
 298    float2 center_to_point = pt - center;
 299    float corner_radius = pick_corner_radius(center_to_point, corner_radii);
 300    float2 corner_to_point = abs(center_to_point) - half_size;
 301    float2 corner_center_to_point = corner_to_point + corner_radius;
 302    return quad_sdf_impl(corner_center_to_point, corner_radius);
 303}
 304
 305GradientColor prepare_gradient_color(uint tag, uint color_space, Hsla solid, LinearColorStop colors[2]) {
 306    GradientColor output;
 307    if (tag == 0 || tag == 2) {
 308        output.solid = hsla_to_rgba(solid);
 309    } else if (tag == 1) {
 310        output.color0 = hsla_to_rgba(colors[0].color);
 311        output.color1 = hsla_to_rgba(colors[1].color);
 312
 313        // Prepare color space in vertex for avoid conversion
 314        // in fragment shader for performance reasons
 315        if (color_space == 1) {
 316            // Oklab
 317            output.color0 = srgb_to_oklab(output.color0);
 318            output.color1 = srgb_to_oklab(output.color1);
 319        }
 320    }
 321
 322    return output;
 323}
 324
 325float2x2 rotate2d(float angle) {
 326    float s = sin(angle);
 327    float c = cos(angle);
 328    return float2x2(c, -s, s, c);
 329}
 330
 331float4 gradient_color(Background background,
 332                      float2 position,
 333                      Bounds bounds,
 334                      float4 solid_color, float4 color0, float4 color1) {
 335    float4 color;
 336
 337    switch (background.tag) {
 338        case 0:
 339            color = solid_color;
 340            break;
 341        case 1: {
 342            // -90 degrees to match the CSS gradient angle.
 343            float gradient_angle = background.gradient_angle_or_pattern_height;
 344            float radians = (fmod(gradient_angle, 360.0) - 90.0) * (M_PI_F / 180.0);
 345            float2 direction = float2(cos(radians), sin(radians));
 346
 347            // Expand the short side to be the same as the long side
 348            if (bounds.size.x > bounds.size.y) {
 349                direction.y *= bounds.size.y / bounds.size.x;
 350            } else {
 351                direction.x *=  bounds.size.x / bounds.size.y;
 352            }
 353
 354            // Get the t value for the linear gradient with the color stop percentages.
 355            float2 half_size = bounds.size * 0.5;
 356            float2 center = bounds.origin + half_size;
 357            float2 center_to_point = position - center;
 358            float t = dot(center_to_point, direction) / length(direction);
 359            // Check the direct to determine the use x or y
 360            if (abs(direction.x) > abs(direction.y)) {
 361                t = (t + half_size.x) / bounds.size.x;
 362            } else {
 363                t = (t + half_size.y) / bounds.size.y;
 364            }
 365
 366            // Adjust t based on the stop percentages
 367            t = (t - background.colors[0].percentage)
 368                / (background.colors[1].percentage
 369                - background.colors[0].percentage);
 370            t = clamp(t, 0.0, 1.0);
 371
 372            switch (background.color_space) {
 373                case 0:
 374                    color = lerp(color0, color1, t);
 375                    break;
 376                case 1: {
 377                    float4 oklab_color = lerp(color0, color1, t);
 378                    color = oklab_to_srgb(oklab_color);
 379                    break;
 380                }
 381            }
 382            break;
 383        }
 384        case 2: {
 385            float gradient_angle_or_pattern_height = background.gradient_angle_or_pattern_height;
 386            float pattern_width = (gradient_angle_or_pattern_height / 65535.0f) / 255.0f;
 387            float pattern_interval = fmod(gradient_angle_or_pattern_height, 65535.0f) / 255.0f;
 388            float pattern_height = pattern_width + pattern_interval;
 389            float stripe_angle = M_PI_F / 4.0;
 390            float pattern_period = pattern_height * sin(stripe_angle);
 391            float2x2 rotation = rotate2d(stripe_angle);
 392            float2 relative_position = position - bounds.origin;
 393            float2 rotated_point = mul(relative_position, rotation);
 394            float pattern = fmod(rotated_point.x, pattern_period);
 395            float distance = min(pattern, pattern_period - pattern) - pattern_period * (pattern_width / pattern_height) /  2.0f;
 396            color = solid_color;
 397            color.a *= saturate(0.5 - distance);
 398            break;
 399        }
 400    }
 401
 402    return color;
 403}
 404
 405// Returns the dash velocity of a corner given the dash velocity of the two
 406// sides, by returning the slower velocity (larger dashes).
 407//
 408// Since 0 is used for dash velocity when the border width is 0 (instead of
 409// +inf), this returns the other dash velocity in that case.
 410//
 411// An alternative to this might be to appropriately interpolate the dash
 412// velocity around the corner, but that seems overcomplicated.
 413float corner_dash_velocity(float dv1, float dv2) {
 414    if (dv1 == 0.0) {
 415        return dv2;
 416    } else if (dv2 == 0.0) {
 417        return dv1;
 418    } else {
 419        return min(dv1, dv2);
 420    }
 421}
 422
 423// Returns alpha used to render antialiased dashes.
 424// `t` is within the dash when `fmod(t, period) < length`.
 425float dash_alpha(
 426    float t, float period, float length, float dash_velocity,
 427    float antialias_threshold
 428) {
 429    float half_period = period / 2.0;
 430    float half_length = length / 2.0;
 431    // Value in [-half_period, half_period]
 432    // The dash is in [-half_length, half_length]
 433    float centered = fmod(t + half_period - half_length, period) - half_period;
 434    // Signed distance for the dash, negative values are inside the dash
 435    float signed_distance = abs(centered) - half_length;
 436    // Antialiased alpha based on the signed distance
 437    return saturate(antialias_threshold - signed_distance / dash_velocity);
 438}
 439
 440// This approximates distance to the nearest point to a quarter ellipse in a way
 441// that is sufficient for anti-aliasing when the ellipse is not very eccentric.
 442// The components of `point` are expected to be positive.
 443//
 444// Negative on the outside and positive on the inside.
 445float quarter_ellipse_sdf(float2 pt, float2 radii) {
 446    // Scale the space to treat the ellipse like a unit circle
 447    float2 circle_vec = pt / radii;
 448    float unit_circle_sdf = length(circle_vec) - 1.0;
 449    // Approximate up-scaling of the length by using the average of the radii.
 450    //
 451    // TODO: A better solution would be to use the gradient of the implicit
 452    // function for an ellipse to approximate a scaling factor.
 453    return unit_circle_sdf * (radii.x + radii.y) * -0.5;
 454}
 455
 456/*
 457**
 458**              Quads
 459**
 460*/
 461
 462struct Quad {
 463    uint order;
 464    uint border_style;
 465    Bounds bounds;
 466    Bounds content_mask;
 467    Background background;
 468    Hsla border_color;
 469    Corners corner_radii;
 470    Edges border_widths;
 471};
 472
 473struct QuadVertexOutput {
 474    nointerpolation uint quad_id: TEXCOORD0;
 475    float4 position: SV_Position;
 476    nointerpolation float4 border_color: COLOR0;
 477    nointerpolation float4 background_solid: COLOR1;
 478    nointerpolation float4 background_color0: COLOR2;
 479    nointerpolation float4 background_color1: COLOR3;
 480    float4 clip_distance: SV_ClipDistance;
 481};
 482
 483struct QuadFragmentInput {
 484    nointerpolation uint quad_id: TEXCOORD0;
 485    float4 position: SV_Position;
 486    nointerpolation float4 border_color: COLOR0;
 487    nointerpolation float4 background_solid: COLOR1;
 488    nointerpolation float4 background_color0: COLOR2;
 489    nointerpolation float4 background_color1: COLOR3;
 490};
 491
 492StructuredBuffer<Quad> quads: register(t1);
 493
 494QuadVertexOutput quad_vertex(uint vertex_id: SV_VertexID, uint quad_id: SV_InstanceID) {
 495    float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u));
 496    Quad quad = quads[quad_id];
 497    float4 device_position = to_device_position(unit_vertex, quad.bounds);
 498
 499    GradientColor gradient = prepare_gradient_color(
 500        quad.background.tag,
 501        quad.background.color_space,
 502        quad.background.solid,
 503        quad.background.colors
 504    );
 505    float4 clip_distance = distance_from_clip_rect(unit_vertex, quad.bounds, quad.content_mask);
 506    float4 border_color = hsla_to_rgba(quad.border_color);
 507
 508    QuadVertexOutput output;
 509    output.position = device_position;
 510    output.border_color = border_color;
 511    output.quad_id = quad_id;
 512    output.background_solid = gradient.solid;
 513    output.background_color0 = gradient.color0;
 514    output.background_color1 = gradient.color1;
 515    output.clip_distance = clip_distance;
 516    return output;
 517}
 518
 519float4 quad_fragment(QuadFragmentInput input): SV_Target {
 520    Quad quad = quads[input.quad_id];
 521    float4 background_color = gradient_color(quad.background, input.position.xy, quad.bounds,
 522    input.background_solid, input.background_color0, input.background_color1);
 523
 524    bool unrounded = quad.corner_radii.top_left == 0.0 &&
 525        quad.corner_radii.top_right == 0.0 &&
 526        quad.corner_radii.bottom_left == 0.0 &&
 527        quad.corner_radii.bottom_right == 0.0;
 528
 529    // Fast path when the quad is not rounded and doesn't have any border
 530    if (quad.border_widths.top == 0.0 &&
 531        quad.border_widths.left == 0.0 &&
 532        quad.border_widths.right == 0.0 &&
 533        quad.border_widths.bottom == 0.0 &&
 534        unrounded) {
 535        return background_color;
 536    }
 537
 538    float2 size = quad.bounds.size;
 539    float2 half_size = size / 2.;
 540    float2 the_point = input.position.xy - quad.bounds.origin;
 541    float2 center_to_point = the_point - half_size;
 542
 543    // Signed distance field threshold for inclusion of pixels. 0.5 is the
 544    // minimum distance between the center of the pixel and the edge.
 545    const float antialias_threshold = 0.5;
 546
 547    // Radius of the nearest corner
 548    float corner_radius = pick_corner_radius(center_to_point, quad.corner_radii);
 549
 550    float2 border = float2(
 551        center_to_point.x < 0.0 ? quad.border_widths.left : quad.border_widths.right,
 552        center_to_point.y < 0.0 ? quad.border_widths.top : quad.border_widths.bottom
 553    );
 554
 555    // 0-width borders are reduced so that `inner_sdf >= antialias_threshold`.
 556    // The purpose of this is to not draw antialiasing pixels in this case.
 557    float2 reduced_border = float2(
 558        border.x == 0.0 ? -antialias_threshold : border.x,
 559        border.y == 0.0 ? -antialias_threshold : border.y
 560    );
 561
 562    // Vector from the corner of the quad bounds to the point, after mirroring
 563    // the point into the bottom right quadrant. Both components are <= 0.
 564    float2 corner_to_point = abs(center_to_point) - half_size;
 565
 566    // Vector from the point to the center of the rounded corner's circle, also
 567    // mirrored into bottom right quadrant.
 568    float2 corner_center_to_point = corner_to_point + corner_radius;
 569
 570    // Whether the nearest point on the border is rounded
 571    bool is_near_rounded_corner =
 572        corner_center_to_point.x >= 0.0 &&
 573        corner_center_to_point.y >= 0.0;
 574
 575    // Vector from straight border inner corner to point.
 576    //
 577    // 0-width borders are turned into width -1 so that inner_sdf is > 1.0 near
 578    // the border. Without this, antialiasing pixels would be drawn.
 579    float2 straight_border_inner_corner_to_point = corner_to_point + reduced_border;
 580
 581    // Whether the point is beyond the inner edge of the straight border
 582    bool is_beyond_inner_straight_border =
 583        straight_border_inner_corner_to_point.x > 0.0 ||
 584        straight_border_inner_corner_to_point.y > 0.0;
 585
 586    // Whether the point is far enough inside the quad, such that the pixels are
 587    // not affected by the straight border.
 588    bool is_within_inner_straight_border =
 589        straight_border_inner_corner_to_point.x < -antialias_threshold &&
 590        straight_border_inner_corner_to_point.y < -antialias_threshold;
 591
 592    // Fast path for points that must be part of the background
 593    if (is_within_inner_straight_border && !is_near_rounded_corner) {
 594        return background_color;
 595    }
 596
 597    // Signed distance of the point to the outside edge of the quad's border
 598    float outer_sdf = quad_sdf_impl(corner_center_to_point, corner_radius);
 599
 600    // Approximate signed distance of the point to the inside edge of the quad's
 601    // border. It is negative outside this edge (within the border), and
 602    // positive inside.
 603    //
 604    // This is not always an accurate signed distance:
 605    // * The rounded portions with varying border width use an approximation of
 606    //   nearest-point-on-ellipse.
 607    // * When it is quickly known to be outside the edge, -1.0 is used.
 608    float inner_sdf = 0.0;
 609    if (corner_center_to_point.x <= 0.0 || corner_center_to_point.y <= 0.0) {
 610        // Fast paths for straight borders
 611        inner_sdf = -max(straight_border_inner_corner_to_point.x,
 612                        straight_border_inner_corner_to_point.y);
 613    } else if (is_beyond_inner_straight_border) {
 614        // Fast path for points that must be outside the inner edge
 615        inner_sdf = -1.0;
 616    } else if (reduced_border.x == reduced_border.y) {
 617        // Fast path for circular inner edge.
 618        inner_sdf = -(outer_sdf + reduced_border.x);
 619    } else {
 620        float2 ellipse_radii = max(float2(0.0, 0.0), float2(corner_radius, corner_radius) - reduced_border);
 621        inner_sdf = quarter_ellipse_sdf(corner_center_to_point, ellipse_radii);
 622    }
 623
 624    // Negative when inside the border
 625    float border_sdf = max(inner_sdf, outer_sdf);
 626
 627    float4 color = background_color;
 628    if (border_sdf < antialias_threshold) {
 629        float4 border_color = input.border_color;
 630        // Dashed border logic when border_style == 1
 631        if (quad.border_style == 1) {
 632            // Position along the perimeter in "dash space", where each dash
 633            // period has length 1
 634            float t = 0.0;
 635
 636            // Total number of dash periods, so that the dash spacing can be
 637            // adjusted to evenly divide it
 638            float max_t = 0.0;
 639
 640            // Border width is proportional to dash size. This is the behavior
 641            // used by browsers, but also avoids dashes from different segments
 642            // overlapping when dash size is smaller than the border width.
 643            //
 644            // Dash pattern: (2 * border width) dash, (1 * border width) gap
 645            const float dash_length_per_width = 2.0;
 646            const float dash_gap_per_width = 1.0;
 647            const float dash_period_per_width = dash_length_per_width + dash_gap_per_width;
 648
 649            // Since the dash size is determined by border width, the density of
 650            // dashes varies. Multiplying a pixel distance by this returns a
 651            // position in dash space - it has units (dash period / pixels). So
 652            // a dash velocity of (1 / 10) is 1 dash every 10 pixels.
 653            float dash_velocity = 0.0;
 654
 655            // Dividing this by the border width gives the dash velocity
 656            const float dv_numerator = 1.0 / dash_period_per_width;
 657
 658            if (unrounded) {
 659                // When corners aren't rounded, the dashes are separately laid
 660                // out on each straight line, rather than around the whole
 661                // perimeter. This way each line starts and ends with a dash.
 662                bool is_horizontal = corner_center_to_point.x < corner_center_to_point.y;
 663                float border_width = is_horizontal ? border.x : border.y;
 664                dash_velocity = dv_numerator / border_width;
 665                t = is_horizontal ? the_point.x : the_point.y;
 666                t *= dash_velocity;
 667                max_t = is_horizontal ? size.x : size.y;
 668                max_t *= dash_velocity;
 669            } else {
 670                // When corners are rounded, the dashes are laid out clockwise
 671                // around the whole perimeter.
 672
 673                float r_tr = quad.corner_radii.top_right;
 674                float r_br = quad.corner_radii.bottom_right;
 675                float r_bl = quad.corner_radii.bottom_left;
 676                float r_tl = quad.corner_radii.top_left;
 677
 678                float w_t = quad.border_widths.top;
 679                float w_r = quad.border_widths.right;
 680                float w_b = quad.border_widths.bottom;
 681                float w_l = quad.border_widths.left;
 682
 683                // Straight side dash velocities
 684                float dv_t = w_t <= 0.0 ? 0.0 : dv_numerator / w_t;
 685                float dv_r = w_r <= 0.0 ? 0.0 : dv_numerator / w_r;
 686                float dv_b = w_b <= 0.0 ? 0.0 : dv_numerator / w_b;
 687                float dv_l = w_l <= 0.0 ? 0.0 : dv_numerator / w_l;
 688
 689                // Straight side lengths in dash space
 690                float s_t = (size.x - r_tl - r_tr) * dv_t;
 691                float s_r = (size.y - r_tr - r_br) * dv_r;
 692                float s_b = (size.x - r_br - r_bl) * dv_b;
 693                float s_l = (size.y - r_bl - r_tl) * dv_l;
 694
 695                float corner_dash_velocity_tr = corner_dash_velocity(dv_t, dv_r);
 696                float corner_dash_velocity_br = corner_dash_velocity(dv_b, dv_r);
 697                float corner_dash_velocity_bl = corner_dash_velocity(dv_b, dv_l);
 698                float corner_dash_velocity_tl = corner_dash_velocity(dv_t, dv_l);
 699
 700                // Corner lengths in dash space
 701                float c_tr = r_tr * (M_PI_F / 2.0) * corner_dash_velocity_tr;
 702                float c_br = r_br * (M_PI_F / 2.0) * corner_dash_velocity_br;
 703                float c_bl = r_bl * (M_PI_F / 2.0) * corner_dash_velocity_bl;
 704                float c_tl = r_tl * (M_PI_F / 2.0) * corner_dash_velocity_tl;
 705
 706                // Cumulative dash space upto each segment
 707                float upto_tr = s_t;
 708                float upto_r = upto_tr + c_tr;
 709                float upto_br = upto_r + s_r;
 710                float upto_b = upto_br + c_br;
 711                float upto_bl = upto_b + s_b;
 712                float upto_l = upto_bl + c_bl;
 713                float upto_tl = upto_l + s_l;
 714                max_t = upto_tl + c_tl;
 715
 716                if (is_near_rounded_corner) {
 717                    float radians = atan2(corner_center_to_point.y, corner_center_to_point.x);
 718                    float corner_t = radians * corner_radius;
 719
 720                    if (center_to_point.x >= 0.0) {
 721                        if (center_to_point.y < 0.0) {
 722                            dash_velocity = corner_dash_velocity_tr;
 723                            // Subtracted because radians is pi/2 to 0 when
 724                            // going clockwise around the top right corner,
 725                            // since the y axis has been flipped
 726                            t = upto_r - corner_t * dash_velocity;
 727                        } else {
 728                            dash_velocity = corner_dash_velocity_br;
 729                            // Added because radians is 0 to pi/2 when going
 730                            // clockwise around the bottom-right corner
 731                            t = upto_br + corner_t * dash_velocity;
 732                        }
 733                    } else {
 734                        if (center_to_point.y >= 0.0) {
 735                            dash_velocity = corner_dash_velocity_bl;
 736                            // Subtracted because radians is pi/1 to 0 when
 737                            // going clockwise around the bottom-left corner,
 738                            // since the x axis has been flipped
 739                            t = upto_l - corner_t * dash_velocity;
 740                        } else {
 741                            dash_velocity = corner_dash_velocity_tl;
 742                            // Added because radians is 0 to pi/2 when going
 743                            // clockwise around the top-left corner, since both
 744                            // axis were flipped
 745                            t = upto_tl + corner_t * dash_velocity;
 746                        }
 747                    }
 748                } else {
 749                    // Straight borders
 750                    bool is_horizontal = corner_center_to_point.x < corner_center_to_point.y;
 751                    if (is_horizontal) {
 752                        if (center_to_point.y < 0.0) {
 753                            dash_velocity = dv_t;
 754                            t = (the_point.x - r_tl) * dash_velocity;
 755                        } else {
 756                            dash_velocity = dv_b;
 757                            t = upto_bl - (the_point.x - r_bl) * dash_velocity;
 758                        }
 759                    } else {
 760                        if (center_to_point.x < 0.0) {
 761                            dash_velocity = dv_l;
 762                            t = upto_tl - (the_point.y - r_tl) * dash_velocity;
 763                        } else {
 764                            dash_velocity = dv_r;
 765                            t = upto_r + (the_point.y - r_tr) * dash_velocity;
 766                        }
 767                    }
 768                }
 769            }
 770            float dash_length = dash_length_per_width / dash_period_per_width;
 771            float desired_dash_gap = dash_gap_per_width / dash_period_per_width;
 772
 773            // Straight borders should start and end with a dash, so max_t is
 774            // reduced to cause this.
 775            max_t -= unrounded ? dash_length : 0.0;
 776            if (max_t >= 1.0) {
 777                // Adjust dash gap to evenly divide max_t
 778                float dash_count = floor(max_t);
 779                float dash_period = max_t / dash_count;
 780                border_color.a *= dash_alpha(t, dash_period, dash_length, dash_velocity, antialias_threshold);
 781            } else if (unrounded) {
 782                // When there isn't enough space for the full gap between the
 783                // two start / end dashes of a straight border, reduce gap to
 784                // make them fit.
 785                float dash_gap = max_t - dash_length;
 786                if (dash_gap > 0.0) {
 787                    float dash_period = dash_length + dash_gap;
 788                    border_color.a *= dash_alpha(t, dash_period, dash_length, dash_velocity, antialias_threshold);
 789                }
 790            }
 791        }
 792
 793        // Blend the border on top of the background and then linearly interpolate
 794        // between the two as we slide inside the background.
 795        float4 blended_border = over(background_color, border_color);
 796        color = lerp(background_color, blended_border,
 797                    saturate(antialias_threshold - inner_sdf));
 798    }
 799
 800    return color * float4(1.0, 1.0, 1.0, saturate(antialias_threshold - outer_sdf));
 801}
 802
 803/*
 804**
 805**              Shadows
 806**
 807*/
 808
 809struct Shadow {
 810    uint order;
 811    float blur_radius;
 812    Bounds bounds;
 813    Corners corner_radii;
 814    Bounds content_mask;
 815    Hsla color;
 816};
 817
 818struct ShadowVertexOutput {
 819    nointerpolation uint shadow_id: TEXCOORD0;
 820    float4 position: SV_Position;
 821    nointerpolation float4 color: COLOR;
 822    float4 clip_distance: SV_ClipDistance;
 823};
 824
 825struct ShadowFragmentInput {
 826  nointerpolation uint shadow_id: TEXCOORD0;
 827  float4 position: SV_Position;
 828  nointerpolation float4 color: COLOR;
 829};
 830
 831StructuredBuffer<Shadow> shadows: register(t1);
 832
 833ShadowVertexOutput shadow_vertex(uint vertex_id: SV_VertexID, uint shadow_id: SV_InstanceID) {
 834    float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u));
 835    Shadow shadow = shadows[shadow_id];
 836
 837    float margin = 3.0 * shadow.blur_radius;
 838    Bounds bounds = shadow.bounds;
 839    bounds.origin -= margin;
 840    bounds.size += 2.0 * margin;
 841
 842    float4 device_position = to_device_position(unit_vertex, bounds);
 843    float4 clip_distance = distance_from_clip_rect(unit_vertex, bounds, shadow.content_mask);
 844    float4 color = hsla_to_rgba(shadow.color);
 845
 846    ShadowVertexOutput output;
 847    output.position = device_position;
 848    output.color = color;
 849    output.shadow_id = shadow_id;
 850    output.clip_distance = clip_distance;
 851
 852    return output;
 853}
 854
 855float4 shadow_fragment(ShadowFragmentInput input): SV_TARGET {
 856    Shadow shadow = shadows[input.shadow_id];
 857
 858    float2 half_size = shadow.bounds.size / 2.;
 859    float2 center = shadow.bounds.origin + half_size;
 860    float2 point0 = input.position.xy - center;
 861    float corner_radius = pick_corner_radius(point0, shadow.corner_radii);
 862
 863    // The signal is only non-zero in a limited range, so don't waste samples
 864    float low = point0.y - half_size.y;
 865    float high = point0.y + half_size.y;
 866    float start = clamp(-3. * shadow.blur_radius, low, high);
 867    float end = clamp(3. * shadow.blur_radius, low, high);
 868
 869    // Accumulate samples (we can get away with surprisingly few samples)
 870    float step = (end - start) / 4.;
 871    float y = start + step * 0.5;
 872    float alpha = 0.;
 873    for (int i = 0; i < 4; i++) {
 874        alpha += blur_along_x(point0.x, point0.y - y, shadow.blur_radius,
 875                            corner_radius, half_size) *
 876                gaussian(y, shadow.blur_radius) * step;
 877        y += step;
 878    }
 879
 880    return input.color * float4(1., 1., 1., alpha);
 881}
 882
 883/*
 884**
 885**              Path Rasterization
 886**
 887*/
 888
 889struct PathRasterizationSprite {
 890    float2 xy_position;
 891    float2 st_position;
 892    Background color;
 893    Bounds bounds;
 894};
 895
 896StructuredBuffer<PathRasterizationSprite> path_rasterization_sprites: register(t1);
 897
 898struct PathVertexOutput {
 899    float4 position: SV_Position;
 900    float2 st_position: TEXCOORD0;
 901    nointerpolation uint vertex_id: TEXCOORD1;
 902    float4 clip_distance: SV_ClipDistance;
 903};
 904
 905struct PathFragmentInput {
 906    float4 position: SV_Position;
 907    float2 st_position: TEXCOORD0;
 908    nointerpolation uint vertex_id: TEXCOORD1;
 909};
 910
 911PathVertexOutput path_rasterization_vertex(uint vertex_id: SV_VertexID) {
 912    PathRasterizationSprite sprite = path_rasterization_sprites[vertex_id];
 913
 914    PathVertexOutput output;
 915    output.position = to_device_position_impl(sprite.xy_position);
 916    output.st_position = sprite.st_position;
 917    output.vertex_id = vertex_id;
 918    output.clip_distance = distance_from_clip_rect_impl(sprite.xy_position, sprite.bounds);
 919
 920    return output;
 921}
 922
 923float4 path_rasterization_fragment(PathFragmentInput input): SV_Target {
 924    float2 dx = ddx(input.st_position);
 925    float2 dy = ddy(input.st_position);
 926    PathRasterizationSprite sprite = path_rasterization_sprites[input.vertex_id];
 927
 928    Background background = sprite.color;
 929    Bounds bounds = sprite.bounds;
 930
 931    float alpha;
 932    if (length(float2(dx.x, dy.x))) {
 933        alpha = 1.0;
 934    } else {
 935        float2 gradient = 2.0 * input.st_position.xx * float2(dx.x, dy.x) - float2(dx.y, dy.y);
 936        float f = input.st_position.x * input.st_position.x - input.st_position.y;
 937        float distance = f / length(gradient);
 938        alpha = saturate(0.5 - distance);
 939    }
 940
 941    GradientColor gradient = prepare_gradient_color(
 942        background.tag, background.color_space, background.solid, background.colors);
 943
 944    float4 color = gradient_color(background, input.position.xy, bounds,
 945        gradient.solid, gradient.color0, gradient.color1);
 946    return float4(color.rgb * color.a * alpha, alpha * color.a);
 947}
 948
 949/*
 950**
 951**              Path Sprites
 952**
 953*/
 954
 955struct PathSprite {
 956    Bounds bounds;
 957};
 958
 959struct PathSpriteVertexOutput {
 960    float4 position: SV_Position;
 961    float2 texture_coords: TEXCOORD0;
 962};
 963
 964StructuredBuffer<PathSprite> path_sprites: register(t1);
 965
 966PathSpriteVertexOutput path_sprite_vertex(uint vertex_id: SV_VertexID, uint sprite_id: SV_InstanceID) {
 967    float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u));
 968    PathSprite sprite = path_sprites[sprite_id];
 969
 970    // Don't apply content mask because it was already accounted for when rasterizing the path
 971    float4 device_position = to_device_position(unit_vertex, sprite.bounds);
 972
 973    float2 screen_position = sprite.bounds.origin + unit_vertex * sprite.bounds.size;
 974    float2 texture_coords = screen_position / global_viewport_size;
 975
 976    PathSpriteVertexOutput output;
 977    output.position = device_position;
 978    output.texture_coords = texture_coords;
 979    return output;
 980}
 981
 982float4 path_sprite_fragment(PathSpriteVertexOutput input): SV_Target {
 983    return t_sprite.Sample(s_sprite, input.texture_coords);
 984}
 985
 986/*
 987**
 988**              Underlines
 989**
 990*/
 991
 992struct Underline {
 993    uint order;
 994    uint pad;
 995    Bounds bounds;
 996    Bounds content_mask;
 997    Hsla color;
 998    float thickness;
 999    uint wavy;
1000};
1001
1002struct UnderlineVertexOutput {
1003  nointerpolation uint underline_id: TEXCOORD0;
1004  float4 position: SV_Position;
1005  nointerpolation float4 color: COLOR;
1006  float4 clip_distance: SV_ClipDistance;
1007};
1008
1009struct UnderlineFragmentInput {
1010  nointerpolation uint underline_id: TEXCOORD0;
1011  float4 position: SV_Position;
1012  nointerpolation float4 color: COLOR;
1013};
1014
1015StructuredBuffer<Underline> underlines: register(t1);
1016
1017UnderlineVertexOutput underline_vertex(uint vertex_id: SV_VertexID, uint underline_id: SV_InstanceID) {
1018    float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u));
1019    Underline underline = underlines[underline_id];
1020    float4 device_position = to_device_position(unit_vertex, underline.bounds);
1021    float4 clip_distance = distance_from_clip_rect(unit_vertex, underline.bounds,
1022                                                    underline.content_mask);
1023    float4 color = hsla_to_rgba(underline.color);
1024
1025    UnderlineVertexOutput output;
1026    output.position = device_position;
1027    output.color = color;
1028    output.underline_id = underline_id;
1029    output.clip_distance = clip_distance;
1030    return output;
1031}
1032
1033float4 underline_fragment(UnderlineFragmentInput input): SV_Target {
1034    const float WAVE_FREQUENCY = 2.0;
1035    const float WAVE_HEIGHT_RATIO = 0.8;
1036
1037    Underline underline = underlines[input.underline_id];
1038    if (underline.wavy) {
1039        float half_thickness = underline.thickness * 0.5;
1040        float2 origin = underline.bounds.origin;
1041
1042        float2 st = ((input.position.xy - origin) / underline.bounds.size.y) - float2(0., 0.5);
1043        float frequency = (M_PI_F * WAVE_FREQUENCY * underline.thickness) / underline.bounds.size.y;
1044        float amplitude = (underline.thickness * WAVE_HEIGHT_RATIO) / underline.bounds.size.y;
1045
1046        float sine = sin(st.x * frequency) * amplitude;
1047        float dSine = cos(st.x * frequency) * amplitude * frequency;
1048        float distance = (st.y - sine) / sqrt(1. + dSine * dSine);
1049        float distance_in_pixels = distance * underline.bounds.size.y;
1050        float distance_from_top_border = distance_in_pixels - half_thickness;
1051        float distance_from_bottom_border = distance_in_pixels + half_thickness;
1052        float alpha = saturate(
1053            0.5 - max(-distance_from_bottom_border, distance_from_top_border));
1054        return input.color * float4(1., 1., 1., alpha);
1055    } else {
1056        return input.color;
1057    }
1058}
1059
1060/*
1061**
1062**              Monochrome sprites
1063**
1064*/
1065
1066struct MonochromeSprite {
1067    uint order;
1068    uint pad;
1069    Bounds bounds;
1070    Bounds content_mask;
1071    Hsla color;
1072    AtlasTile tile;
1073    TransformationMatrix transformation;
1074};
1075
1076struct MonochromeSpriteVertexOutput {
1077    float4 position: SV_Position;
1078    float2 tile_position: POSITION;
1079    nointerpolation float4 color: COLOR;
1080    float4 clip_distance: SV_ClipDistance;
1081};
1082
1083struct MonochromeSpriteFragmentInput {
1084    float4 position: SV_Position;
1085    float2 tile_position: POSITION;
1086    nointerpolation float4 color: COLOR;
1087    float4 clip_distance: SV_ClipDistance;
1088};
1089
1090StructuredBuffer<MonochromeSprite> mono_sprites: register(t1);
1091
1092MonochromeSpriteVertexOutput monochrome_sprite_vertex(uint vertex_id: SV_VertexID, uint sprite_id: SV_InstanceID) {
1093    float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u));
1094    MonochromeSprite sprite = mono_sprites[sprite_id];
1095    float4 device_position =
1096        to_device_position_transformed(unit_vertex, sprite.bounds, sprite.transformation);
1097    float4 clip_distance = distance_from_clip_rect_transformed(unit_vertex, sprite.bounds, sprite.content_mask, sprite.transformation);
1098    float2 tile_position = to_tile_position(unit_vertex, sprite.tile);
1099    float4 color = hsla_to_rgba(sprite.color);
1100
1101    MonochromeSpriteVertexOutput output;
1102    output.position = device_position;
1103    output.tile_position = tile_position;
1104    output.color = color;
1105    output.clip_distance = clip_distance;
1106    return output;
1107}
1108
1109float4 monochrome_sprite_fragment(MonochromeSpriteFragmentInput input): SV_Target {
1110    float sample = t_sprite.Sample(s_sprite, input.tile_position).r;
1111    float alpha_corrected = apply_contrast_and_gamma_correction(sample, input.color.rgb, grayscale_enhanced_contrast, gamma_ratios);
1112    return float4(input.color.rgb, input.color.a * alpha_corrected);
1113}
1114
1115/*
1116**
1117**              Polychrome sprites
1118**
1119*/
1120
1121struct PolychromeSprite {
1122    uint order;
1123    uint pad;
1124    uint grayscale;
1125    float opacity;
1126    Bounds bounds;
1127    Bounds content_mask;
1128    Corners corner_radii;
1129    AtlasTile tile;
1130};
1131
1132struct PolychromeSpriteVertexOutput {
1133    nointerpolation uint sprite_id: TEXCOORD0;
1134    float4 position: SV_Position;
1135    float2 tile_position: POSITION;
1136    float4 clip_distance: SV_ClipDistance;
1137};
1138
1139struct PolychromeSpriteFragmentInput {
1140    nointerpolation uint sprite_id: TEXCOORD0;
1141    float4 position: SV_Position;
1142    float2 tile_position: POSITION;
1143};
1144
1145StructuredBuffer<PolychromeSprite> poly_sprites: register(t1);
1146
1147PolychromeSpriteVertexOutput polychrome_sprite_vertex(uint vertex_id: SV_VertexID, uint sprite_id: SV_InstanceID) {
1148    float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u));
1149    PolychromeSprite sprite = poly_sprites[sprite_id];
1150    float4 device_position = to_device_position(unit_vertex, sprite.bounds);
1151    float4 clip_distance = distance_from_clip_rect(unit_vertex, sprite.bounds,
1152                                                    sprite.content_mask);
1153    float2 tile_position = to_tile_position(unit_vertex, sprite.tile);
1154
1155    PolychromeSpriteVertexOutput output;
1156    output.position = device_position;
1157    output.tile_position = tile_position;
1158    output.sprite_id = sprite_id;
1159    output.clip_distance = clip_distance;
1160    return output;
1161}
1162
1163float4 polychrome_sprite_fragment(PolychromeSpriteFragmentInput input): SV_Target {
1164    PolychromeSprite sprite = poly_sprites[input.sprite_id];
1165    float4 sample = t_sprite.Sample(s_sprite, input.tile_position);
1166    float distance = quad_sdf(input.position.xy, sprite.bounds, sprite.corner_radii);
1167
1168    float4 color = sample;
1169    if ((sprite.grayscale & 0xFFu) != 0u) {
1170        float3 grayscale = dot(color.rgb, GRAYSCALE_FACTORS);
1171        color = float4(grayscale, sample.a);
1172    }
1173    color.a *= sprite.opacity * saturate(0.5 - distance);
1174    return color;
1175}