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