shaders.metal

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