shaders.hlsl

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