shaders.wgsl

   1/* Functions useful for debugging:
   2
   3// A heat map color for debugging (blue -> cyan -> green -> yellow -> red).
   4fn heat_map_color(value: f32, minValue: f32, maxValue: f32, position: vec2<f32>) -> vec4<f32> {
   5    // Normalize value to 0-1 range
   6    let t = clamp((value - minValue) / (maxValue - minValue), 0.0, 1.0);
   7
   8    // Heat map color calculation
   9    let r = t * t;
  10    let g = 4.0 * t * (1.0 - t);
  11    let b = (1.0 - t) * (1.0 - t);
  12    let heat_color = vec3<f32>(r, g, b);
  13
  14    // Create a checkerboard pattern (black and white)
  15    let sum = floor(position.x / 3) + floor(position.y / 3);
  16    let is_odd = fract(sum * 0.5); // 0.0 for even, 0.5 for odd
  17    let checker_value = is_odd * 2.0; // 0.0 for even, 1.0 for odd
  18    let checker_color = vec3<f32>(checker_value);
  19
  20    // Determine if value is in range (1.0 if in range, 0.0 if out of range)
  21    let in_range = step(minValue, value) * step(value, maxValue);
  22
  23    // Mix checkerboard and heat map based on whether value is in range
  24    let final_color = mix(checker_color, heat_color, in_range);
  25
  26    return vec4<f32>(final_color, 1.0);
  27}
  28
  29*/
  30
  31// Contrast and gamma correction adapted from https://github.com/microsoft/terminal/blob/1283c0f5b99a2961673249fa77c6b986efb5086c/src/renderer/atlas/dwrite.hlsl
  32// Copyright (c) Microsoft Corporation.
  33// Licensed under the MIT license.
  34fn color_brightness(color: vec3<f32>) -> f32 {
  35    // REC. 601 luminance coefficients for perceived brightness
  36    return dot(color, vec3<f32>(0.30, 0.59, 0.11));
  37}
  38
  39fn light_on_dark_contrast(enhancedContrast: f32, color: vec3<f32>) -> f32 {
  40    let brightness = color_brightness(color);
  41    let multiplier = saturate(4.0 * (0.75 - brightness));
  42    return enhancedContrast * multiplier;
  43}
  44
  45fn enhance_contrast(alpha: f32, k: f32) -> f32 {
  46    return alpha * (k + 1.0) / (alpha * k + 1.0);
  47}
  48
  49fn apply_alpha_correction(a: f32, b: f32, g: vec4<f32>) -> f32 {
  50    let brightness_adjustment = g.x * b + g.y;
  51    let correction = brightness_adjustment * a + (g.z * b + g.w);
  52    return a + a * (1.0 - a) * correction;
  53}
  54
  55fn apply_contrast_and_gamma_correction(sample: f32, color: vec3<f32>, enhanced_contrast_factor: f32, gamma_ratios: vec4<f32>) -> f32 {
  56    let enhanced_contrast = light_on_dark_contrast(enhanced_contrast_factor, color);
  57    let brightness = color_brightness(color);
  58
  59    let contrasted = enhance_contrast(sample, enhanced_contrast);
  60    return apply_alpha_correction(contrasted, brightness, gamma_ratios);
  61}
  62
  63struct GlobalParams {
  64    viewport_size: vec2<f32>,
  65    premultiplied_alpha: u32,
  66    pad: u32,
  67}
  68
  69var<uniform> globals: GlobalParams;
  70var<uniform> gamma_ratios: vec4<f32>;
  71var<uniform> grayscale_enhanced_contrast: f32;
  72var t_sprite: texture_2d<f32>;
  73var s_sprite: sampler;
  74
  75const M_PI_F: f32 = 3.1415926;
  76const GRAYSCALE_FACTORS: vec3<f32> = vec3<f32>(0.2126, 0.7152, 0.0722);
  77
  78struct Bounds {
  79    origin: vec2<f32>,
  80    size: vec2<f32>,
  81}
  82
  83struct Corners {
  84    top_left: f32,
  85    top_right: f32,
  86    bottom_right: f32,
  87    bottom_left: f32,
  88}
  89
  90struct Edges {
  91    top: f32,
  92    right: f32,
  93    bottom: f32,
  94    left: f32,
  95}
  96
  97struct Hsla {
  98    h: f32,
  99    s: f32,
 100    l: f32,
 101    a: f32,
 102}
 103
 104struct LinearColorStop {
 105    color: Hsla,
 106    percentage: f32,
 107}
 108
 109struct Background {
 110    // 0u is Solid
 111    // 1u is LinearGradient
 112    // 2u is PatternSlash
 113    tag: u32,
 114    // 0u is sRGB linear color
 115    // 1u is Oklab color
 116    color_space: u32,
 117    solid: Hsla,
 118    gradient_angle_or_pattern_height: f32,
 119    colors: array<LinearColorStop, 2>,
 120    pad: u32,
 121}
 122
 123struct AtlasTextureId {
 124    index: u32,
 125    kind: u32,
 126}
 127
 128struct AtlasBounds {
 129    origin: vec2<i32>,
 130    size: vec2<i32>,
 131}
 132
 133struct AtlasTile {
 134    texture_id: AtlasTextureId,
 135    tile_id: u32,
 136    padding: u32,
 137    bounds: AtlasBounds,
 138}
 139
 140struct TransformationMatrix {
 141    rotation_scale: mat2x2<f32>,
 142    translation: vec2<f32>,
 143}
 144
 145fn to_device_position_impl(position: vec2<f32>) -> vec4<f32> {
 146    let device_position = position / globals.viewport_size * vec2<f32>(2.0, -2.0) + vec2<f32>(-1.0, 1.0);
 147    return vec4<f32>(device_position, 0.0, 1.0);
 148}
 149
 150fn to_device_position(unit_vertex: vec2<f32>, bounds: Bounds) -> vec4<f32> {
 151    let position = unit_vertex * vec2<f32>(bounds.size) + bounds.origin;
 152    return to_device_position_impl(position);
 153}
 154
 155fn to_device_position_transformed(unit_vertex: vec2<f32>, bounds: Bounds, transform: TransformationMatrix) -> vec4<f32> {
 156    let position = unit_vertex * vec2<f32>(bounds.size) + bounds.origin;
 157    //Note: Rust side stores it as row-major, so transposing here
 158    let transformed = transpose(transform.rotation_scale) * position + transform.translation;
 159    return to_device_position_impl(transformed);
 160}
 161
 162fn to_tile_position(unit_vertex: vec2<f32>, tile: AtlasTile) -> vec2<f32> {
 163  let atlas_size = vec2<f32>(textureDimensions(t_sprite, 0));
 164  return (vec2<f32>(tile.bounds.origin) + unit_vertex * vec2<f32>(tile.bounds.size)) / atlas_size;
 165}
 166
 167fn distance_from_clip_rect_impl(position: vec2<f32>, clip_bounds: Bounds) -> vec4<f32> {
 168    let tl = position - clip_bounds.origin;
 169    let br = clip_bounds.origin + clip_bounds.size - position;
 170    return vec4<f32>(tl.x, br.x, tl.y, br.y);
 171}
 172
 173fn distance_from_clip_rect(unit_vertex: vec2<f32>, bounds: Bounds, clip_bounds: Bounds) -> vec4<f32> {
 174    let position = unit_vertex * vec2<f32>(bounds.size) + bounds.origin;
 175    return distance_from_clip_rect_impl(position, clip_bounds);
 176}
 177
 178fn distance_from_clip_rect_transformed(unit_vertex: vec2<f32>, bounds: Bounds, clip_bounds: Bounds, transform: TransformationMatrix) -> vec4<f32> {
 179    let position = unit_vertex * vec2<f32>(bounds.size) + bounds.origin;
 180    let transformed = transpose(transform.rotation_scale) * position + transform.translation;
 181    return distance_from_clip_rect_impl(transformed, clip_bounds);
 182}
 183
 184// https://gamedev.stackexchange.com/questions/92015/optimized-linear-to-srgb-glsl
 185fn srgb_to_linear(srgb: vec3<f32>) -> vec3<f32> {
 186    let cutoff = srgb < vec3<f32>(0.04045);
 187    let higher = pow((srgb + vec3<f32>(0.055)) / vec3<f32>(1.055), vec3<f32>(2.4));
 188    let lower = srgb / vec3<f32>(12.92);
 189    return select(higher, lower, cutoff);
 190}
 191
 192fn srgb_to_linear_component(a: f32) -> f32 {
 193    let cutoff = a < 0.04045;
 194    let higher = pow((a + 0.055) / 1.055, 2.4);
 195    let lower = a / 12.92;
 196    return select(higher, lower, cutoff);
 197}
 198
 199fn linear_to_srgb(linear: vec3<f32>) -> vec3<f32> {
 200    let cutoff = linear < vec3<f32>(0.0031308);
 201    let higher = vec3<f32>(1.055) * pow(linear, vec3<f32>(1.0 / 2.4)) - vec3<f32>(0.055);
 202    let lower = linear * vec3<f32>(12.92);
 203    return select(higher, lower, cutoff);
 204}
 205
 206/// Convert a linear color to sRGBA space.
 207fn linear_to_srgba(color: vec4<f32>) -> vec4<f32> {
 208    return vec4<f32>(linear_to_srgb(color.rgb), color.a);
 209}
 210
 211/// Convert a sRGBA color to linear space.
 212fn srgba_to_linear(color: vec4<f32>) -> vec4<f32> {
 213    return vec4<f32>(srgb_to_linear(color.rgb), color.a);
 214}
 215
 216/// Hsla to linear RGBA conversion.
 217fn hsla_to_rgba(hsla: Hsla) -> vec4<f32> {
 218    let h = hsla.h * 6.0; // Now, it's an angle but scaled in [0, 6) range
 219    let s = hsla.s;
 220    let l = hsla.l;
 221    let a = hsla.a;
 222
 223    let c = (1.0 - abs(2.0 * l - 1.0)) * s;
 224    let x = c * (1.0 - abs(h % 2.0 - 1.0));
 225    let m = l - c / 2.0;
 226    var color = vec3<f32>(m);
 227
 228    if (h >= 0.0 && h < 1.0) {
 229        color.r += c;
 230        color.g += x;
 231    } else if (h >= 1.0 && h < 2.0) {
 232        color.r += x;
 233        color.g += c;
 234    } else if (h >= 2.0 && h < 3.0) {
 235        color.g += c;
 236        color.b += x;
 237    } else if (h >= 3.0 && h < 4.0) {
 238        color.g += x;
 239        color.b += c;
 240    } else if (h >= 4.0 && h < 5.0) {
 241        color.r += x;
 242        color.b += c;
 243    } else {
 244        color.r += c;
 245        color.b += x;
 246    }
 247
 248    return vec4<f32>(color, a);
 249}
 250
 251/// Convert a linear sRGB to Oklab space.
 252/// Reference: https://bottosson.github.io/posts/oklab/#converting-from-linear-srgb-to-oklab
 253fn linear_srgb_to_oklab(color: vec4<f32>) -> vec4<f32> {
 254	let l = 0.4122214708 * color.r + 0.5363325363 * color.g + 0.0514459929 * color.b;
 255	let m = 0.2119034982 * color.r + 0.6806995451 * color.g + 0.1073969566 * color.b;
 256	let s = 0.0883024619 * color.r + 0.2817188376 * color.g + 0.6299787005 * color.b;
 257
 258	let l_ = pow(l, 1.0 / 3.0);
 259	let m_ = pow(m, 1.0 / 3.0);
 260	let s_ = pow(s, 1.0 / 3.0);
 261
 262	return vec4<f32>(
 263		0.2104542553 * l_ + 0.7936177850 * m_ - 0.0040720468 * s_,
 264		1.9779984951 * l_ - 2.4285922050 * m_ + 0.4505937099 * s_,
 265		0.0259040371 * l_ + 0.7827717662 * m_ - 0.8086757660 * s_,
 266		color.a
 267	);
 268}
 269
 270/// Convert an Oklab color to linear sRGB space.
 271fn oklab_to_linear_srgb(color: vec4<f32>) -> vec4<f32> {
 272	let l_ = color.r + 0.3963377774 * color.g + 0.2158037573 * color.b;
 273	let m_ = color.r - 0.1055613458 * color.g - 0.0638541728 * color.b;
 274	let s_ = color.r - 0.0894841775 * color.g - 1.2914855480 * color.b;
 275
 276	let l = l_ * l_ * l_;
 277	let m = m_ * m_ * m_;
 278	let s = s_ * s_ * s_;
 279
 280	return vec4<f32>(
 281		4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s,
 282		-1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s,
 283		-0.0041960863 * l - 0.7034186147 * m + 1.7076147010 * s,
 284		color.a
 285	);
 286}
 287
 288fn over(below: vec4<f32>, above: vec4<f32>) -> vec4<f32> {
 289    let alpha = above.a + below.a * (1.0 - above.a);
 290    let color = (above.rgb * above.a + below.rgb * below.a * (1.0 - above.a)) / alpha;
 291    return vec4<f32>(color, alpha);
 292}
 293
 294// A standard gaussian function, used for weighting samples
 295fn gaussian(x: f32, sigma: f32) -> f32{
 296    return exp(-(x * x) / (2.0 * sigma * sigma)) / (sqrt(2.0 * M_PI_F) * sigma);
 297}
 298
 299// This approximates the error function, needed for the gaussian integral
 300fn erf(v: vec2<f32>) -> vec2<f32> {
 301    let s = sign(v);
 302    let a = abs(v);
 303    let r1 = 1.0 + (0.278393 + (0.230389 + (0.000972 + 0.078108 * a) * a) * a) * a;
 304    let r2 = r1 * r1;
 305    return s - s / (r2 * r2);
 306}
 307
 308fn blur_along_x(x: f32, y: f32, sigma: f32, corner: f32, half_size: vec2<f32>) -> f32 {
 309  let delta = min(half_size.y - corner - abs(y), 0.0);
 310  let curved = half_size.x - corner + sqrt(max(0.0, corner * corner - delta * delta));
 311  let integral = 0.5 + 0.5 * erf((x + vec2<f32>(-curved, curved)) * (sqrt(0.5) / sigma));
 312  return integral.y - integral.x;
 313}
 314
 315// Selects corner radius based on quadrant.
 316fn pick_corner_radius(center_to_point: vec2<f32>, radii: Corners) -> f32 {
 317    if (center_to_point.x < 0.0) {
 318        if (center_to_point.y < 0.0) {
 319            return radii.top_left;
 320        } else {
 321            return radii.bottom_left;
 322        }
 323    } else {
 324        if (center_to_point.y < 0.0) {
 325            return radii.top_right;
 326        } else {
 327            return radii.bottom_right;
 328        }
 329    }
 330}
 331
 332// Signed distance of the point to the quad's border - positive outside the
 333// border, and negative inside.
 334//
 335// See comments on similar code using `quad_sdf_impl` in `fs_quad` for
 336// explanation.
 337fn quad_sdf(point: vec2<f32>, bounds: Bounds, corner_radii: Corners) -> f32 {
 338    let half_size = bounds.size / 2.0;
 339    let center = bounds.origin + half_size;
 340    let center_to_point = point - center;
 341    let corner_radius = pick_corner_radius(center_to_point, corner_radii);
 342    let corner_to_point = abs(center_to_point) - half_size;
 343    let corner_center_to_point = corner_to_point + corner_radius;
 344    return quad_sdf_impl(corner_center_to_point, corner_radius);
 345}
 346
 347fn quad_sdf_impl(corner_center_to_point: vec2<f32>, corner_radius: f32) -> f32 {
 348    if (corner_radius == 0.0) {
 349        // Fast path for unrounded corners.
 350        return max(corner_center_to_point.x, corner_center_to_point.y);
 351    } else {
 352        // Signed distance of the point from a quad that is inset by corner_radius.
 353        // It is negative inside this quad, and positive outside.
 354        let signed_distance_to_inset_quad =
 355            // 0 inside the inset quad, and positive outside.
 356            length(max(vec2<f32>(0.0), corner_center_to_point)) +
 357            // 0 outside the inset quad, and negative inside.
 358            min(0.0, max(corner_center_to_point.x, corner_center_to_point.y));
 359
 360        return signed_distance_to_inset_quad - corner_radius;
 361    }
 362}
 363
 364// Abstract away the final color transformation based on the
 365// target alpha compositing mode.
 366fn blend_color(color: vec4<f32>, alpha_factor: f32) -> vec4<f32> {
 367    let alpha = color.a * alpha_factor;
 368    let multiplier = select(1.0, alpha, globals.premultiplied_alpha != 0u);
 369    return vec4<f32>(color.rgb * multiplier, alpha);
 370}
 371
 372
 373struct GradientColor {
 374    solid: vec4<f32>,
 375    color0: vec4<f32>,
 376    color1: vec4<f32>,
 377}
 378
 379fn prepare_gradient_color(tag: u32, color_space: u32,
 380    solid: Hsla, colors: array<LinearColorStop, 2>) -> GradientColor {
 381    var result = GradientColor();
 382
 383    if (tag == 0u || tag == 2u) {
 384        result.solid = hsla_to_rgba(solid);
 385    } else if (tag == 1u) {
 386        // The hsla_to_rgba is returns a linear sRGB color
 387        result.color0 = hsla_to_rgba(colors[0].color);
 388        result.color1 = hsla_to_rgba(colors[1].color);
 389
 390        // Prepare color space in vertex for avoid conversion
 391        // in fragment shader for performance reasons
 392        if (color_space == 0u) {
 393            // sRGB
 394            result.color0 = linear_to_srgba(result.color0);
 395            result.color1 = linear_to_srgba(result.color1);
 396        } else if (color_space == 1u) {
 397            // Oklab
 398            result.color0 = linear_srgb_to_oklab(result.color0);
 399            result.color1 = linear_srgb_to_oklab(result.color1);
 400        }
 401    }
 402
 403    return result;
 404}
 405
 406fn gradient_color(background: Background, position: vec2<f32>, bounds: Bounds,
 407    solid_color: vec4<f32>, color0: vec4<f32>, color1: vec4<f32>) -> vec4<f32> {
 408    var background_color = vec4<f32>(0.0);
 409
 410    switch (background.tag) {
 411        default: {
 412            return solid_color;
 413        }
 414        case 1u: {
 415            // Linear gradient background.
 416            // -90 degrees to match the CSS gradient angle.
 417            let angle = background.gradient_angle_or_pattern_height;
 418            let radians = (angle % 360.0 - 90.0) * M_PI_F / 180.0;
 419            var direction = vec2<f32>(cos(radians), sin(radians));
 420            let stop0_percentage = background.colors[0].percentage;
 421            let stop1_percentage = background.colors[1].percentage;
 422
 423            // Expand the short side to be the same as the long side
 424            if (bounds.size.x > bounds.size.y) {
 425                direction.y *= bounds.size.y / bounds.size.x;
 426            } else {
 427                direction.x *= bounds.size.x / bounds.size.y;
 428            }
 429
 430            // Get the t value for the linear gradient with the color stop percentages.
 431            let half_size = bounds.size / 2.0;
 432            let center = bounds.origin + half_size;
 433            let center_to_point = position - center;
 434            var t = dot(center_to_point, direction) / length(direction);
 435            // Check the direct to determine the use x or y
 436            if (abs(direction.x) > abs(direction.y)) {
 437                t = (t + half_size.x) / bounds.size.x;
 438            } else {
 439                t = (t + half_size.y) / bounds.size.y;
 440            }
 441
 442            // Adjust t based on the stop percentages
 443            t = (t - stop0_percentage) / (stop1_percentage - stop0_percentage);
 444            t = clamp(t, 0.0, 1.0);
 445
 446            switch (background.color_space) {
 447                default: {
 448                    background_color = srgba_to_linear(mix(color0, color1, t));
 449                }
 450                case 1u: {
 451                    let oklab_color = mix(color0, color1, t);
 452                    background_color = oklab_to_linear_srgb(oklab_color);
 453                }
 454            }
 455        }
 456        case 2u: {
 457            let gradient_angle_or_pattern_height = background.gradient_angle_or_pattern_height;
 458            let pattern_width = (gradient_angle_or_pattern_height / 65535.0f) / 255.0f;
 459            let pattern_interval = (gradient_angle_or_pattern_height % 65535.0f) / 255.0f;
 460            let pattern_height = pattern_width + pattern_interval;
 461            let stripe_angle = M_PI_F / 4.0;
 462            let pattern_period = pattern_height * sin(stripe_angle);
 463            let rotation = mat2x2<f32>(
 464                cos(stripe_angle), -sin(stripe_angle),
 465                sin(stripe_angle), cos(stripe_angle)
 466            );
 467            let relative_position = position - bounds.origin;
 468            let rotated_point = rotation * relative_position;
 469            let pattern = rotated_point.x % pattern_period;
 470            let distance = min(pattern, pattern_period - pattern) - pattern_period * (pattern_width / pattern_height) /  2.0f;
 471            background_color = solid_color;
 472            background_color.a *= saturate(0.5 - distance);
 473        }
 474    }
 475
 476    return background_color;
 477}
 478
 479// --- quads --- //
 480
 481struct Quad {
 482    order: u32,
 483    border_style: u32,
 484    bounds: Bounds,
 485    content_mask: Bounds,
 486    background: Background,
 487    border_color: Hsla,
 488    corner_radii: Corners,
 489    border_widths: Edges,
 490}
 491var<storage, read> b_quads: array<Quad>;
 492
 493struct QuadVarying {
 494    @builtin(position) position: vec4<f32>,
 495    @location(0) @interpolate(flat) border_color: vec4<f32>,
 496    @location(1) @interpolate(flat) quad_id: u32,
 497    // TODO: use `clip_distance` once Naga supports it
 498    @location(2) clip_distances: vec4<f32>,
 499    @location(3) @interpolate(flat) background_solid: vec4<f32>,
 500    @location(4) @interpolate(flat) background_color0: vec4<f32>,
 501    @location(5) @interpolate(flat) background_color1: vec4<f32>,
 502}
 503
 504@vertex
 505fn vs_quad(@builtin(vertex_index) vertex_id: u32, @builtin(instance_index) instance_id: u32) -> QuadVarying {
 506    let unit_vertex = vec2<f32>(f32(vertex_id & 1u), 0.5 * f32(vertex_id & 2u));
 507    let quad = b_quads[instance_id];
 508
 509    var out = QuadVarying();
 510    out.position = to_device_position(unit_vertex, quad.bounds);
 511
 512    let gradient = prepare_gradient_color(
 513        quad.background.tag,
 514        quad.background.color_space,
 515        quad.background.solid,
 516        quad.background.colors
 517    );
 518    out.background_solid = gradient.solid;
 519    out.background_color0 = gradient.color0;
 520    out.background_color1 = gradient.color1;
 521    out.border_color = hsla_to_rgba(quad.border_color);
 522    out.quad_id = instance_id;
 523    out.clip_distances = distance_from_clip_rect(unit_vertex, quad.bounds, quad.content_mask);
 524    return out;
 525}
 526
 527@fragment
 528fn fs_quad(input: QuadVarying) -> @location(0) vec4<f32> {
 529    // Alpha clip first, since we don't have `clip_distance`.
 530    if (any(input.clip_distances < vec4<f32>(0.0))) {
 531        return vec4<f32>(0.0);
 532    }
 533
 534    let quad = b_quads[input.quad_id];
 535
 536    let background_color = gradient_color(quad.background, input.position.xy, quad.bounds,
 537        input.background_solid, input.background_color0, input.background_color1);
 538
 539    let unrounded = quad.corner_radii.top_left == 0.0 &&
 540        quad.corner_radii.bottom_left == 0.0 &&
 541        quad.corner_radii.top_right == 0.0 &&
 542        quad.corner_radii.bottom_right == 0.0;
 543
 544    // Fast path when the quad is not rounded and doesn't have any border
 545    if (quad.border_widths.top == 0.0 &&
 546            quad.border_widths.left == 0.0 &&
 547            quad.border_widths.right == 0.0 &&
 548            quad.border_widths.bottom == 0.0 &&
 549            unrounded) {
 550        return blend_color(background_color, 1.0);
 551    }
 552
 553    let size = quad.bounds.size;
 554    let half_size = size / 2.0;
 555    let point = input.position.xy - quad.bounds.origin;
 556    let center_to_point = point - half_size;
 557
 558    // Signed distance field threshold for inclusion of pixels. 0.5 is the
 559    // minimum distance between the center of the pixel and the edge.
 560    let antialias_threshold = 0.5;
 561
 562    // Radius of the nearest corner
 563    let corner_radius = pick_corner_radius(center_to_point, quad.corner_radii);
 564
 565    // Width of the nearest borders
 566    let border = vec2<f32>(
 567        select(
 568            quad.border_widths.right,
 569            quad.border_widths.left,
 570            center_to_point.x < 0.0),
 571        select(
 572            quad.border_widths.bottom,
 573            quad.border_widths.top,
 574            center_to_point.y < 0.0));
 575
 576    // 0-width borders are reduced so that `inner_sdf >= antialias_threshold`.
 577    // The purpose of this is to not draw antialiasing pixels in this case.
 578    let reduced_border =
 579        vec2<f32>(select(border.x, -antialias_threshold, border.x == 0.0),
 580                  select(border.y, -antialias_threshold, border.y == 0.0));
 581
 582    // Vector from the corner of the quad bounds to the point, after mirroring
 583    // the point into the bottom right quadrant. Both components are <= 0.
 584    let corner_to_point = abs(center_to_point) - half_size;
 585
 586    // Vector from the point to the center of the rounded corner's circle, also
 587    // mirrored into bottom right quadrant.
 588    let corner_center_to_point = corner_to_point + corner_radius;
 589
 590    // Whether the nearest point on the border is rounded
 591    let is_near_rounded_corner =
 592            corner_center_to_point.x >= 0 &&
 593            corner_center_to_point.y >= 0;
 594
 595    // Vector from straight border inner corner to point.
 596    let straight_border_inner_corner_to_point = corner_to_point + reduced_border;
 597
 598    // Whether the point is beyond the inner edge of the straight border.
 599    let is_beyond_inner_straight_border =
 600            straight_border_inner_corner_to_point.x > 0 ||
 601            straight_border_inner_corner_to_point.y > 0;
 602
 603    // Whether the point is far enough inside the quad, such that the pixels are
 604    // not affected by the straight border.
 605    let is_within_inner_straight_border =
 606        straight_border_inner_corner_to_point.x < -antialias_threshold &&
 607        straight_border_inner_corner_to_point.y < -antialias_threshold;
 608
 609    // Fast path for points that must be part of the background.
 610    //
 611    // This could be optimized further for large rounded corners by including
 612    // points in an inscribed rectangle, or some other quick linear check.
 613    // However, that might negatively impact performance in the case of
 614    // reasonable sizes for rounded corners.
 615    if (is_within_inner_straight_border && !is_near_rounded_corner) {
 616        return blend_color(background_color, 1.0);
 617    }
 618
 619    // Signed distance of the point to the outside edge of the quad's border. It
 620    // is positive outside this edge, and negative inside.
 621    let outer_sdf = quad_sdf_impl(corner_center_to_point, corner_radius);
 622
 623    // Approximate signed distance of the point to the inside edge of the quad's
 624    // border. It is negative outside this edge (within the border), and
 625    // positive inside.
 626    //
 627    // This is not always an accurate signed distance:
 628    // * The rounded portions with varying border width use an approximation of
 629    //   nearest-point-on-ellipse.
 630    // * When it is quickly known to be outside the edge, -1.0 is used.
 631    var inner_sdf = 0.0;
 632    if (corner_center_to_point.x <= 0 || corner_center_to_point.y <= 0) {
 633        // Fast paths for straight borders.
 634        inner_sdf = -max(straight_border_inner_corner_to_point.x,
 635                         straight_border_inner_corner_to_point.y);
 636    } else if (is_beyond_inner_straight_border) {
 637        // Fast path for points that must be outside the inner edge.
 638        inner_sdf = -1.0;
 639    } else if (reduced_border.x == reduced_border.y) {
 640        // Fast path for circular inner edge.
 641        inner_sdf = -(outer_sdf + reduced_border.x);
 642    } else {
 643        let ellipse_radii = max(vec2<f32>(0.0), corner_radius - reduced_border);
 644        inner_sdf = quarter_ellipse_sdf(corner_center_to_point, ellipse_radii);
 645    }
 646
 647    // Negative when inside the border
 648    let border_sdf = max(inner_sdf, outer_sdf);
 649
 650    var color = background_color;
 651    if (border_sdf < antialias_threshold) {
 652        var border_color = input.border_color;
 653
 654        // Dashed border logic when border_style == 1
 655        if (quad.border_style == 1) {
 656            // Position along the perimeter in "dash space", where each dash
 657            // period has length 1
 658            var t = 0.0;
 659
 660            // Total number of dash periods, so that the dash spacing can be
 661            // adjusted to evenly divide it
 662            var max_t = 0.0;
 663
 664            // Border width is proportional to dash size. This is the behavior
 665            // used by browsers, but also avoids dashes from different segments
 666            // overlapping when dash size is smaller than the border width.
 667            //
 668            // Dash pattern: (2 * border width) dash, (1 * border width) gap
 669            let dash_length_per_width = 2.0;
 670            let dash_gap_per_width = 1.0;
 671            let dash_period_per_width = dash_length_per_width + dash_gap_per_width;
 672
 673            // Since the dash size is determined by border width, the density of
 674            // dashes varies. Multiplying a pixel distance by this returns a
 675            // position in dash space - it has units (dash period / pixels). So
 676            // a dash velocity of (1 / 10) is 1 dash every 10 pixels.
 677            var dash_velocity = 0.0;
 678
 679            // Dividing this by the border width gives the dash velocity
 680            let dv_numerator = 1.0 / dash_period_per_width;
 681
 682            if (unrounded) {
 683                // When corners aren't rounded, the dashes are separately laid
 684                // out on each straight line, rather than around the whole
 685                // perimeter. This way each line starts and ends with a dash.
 686                let is_horizontal =
 687                        corner_center_to_point.x <
 688                        corner_center_to_point.y;
 689
 690                // When applying dashed borders to just some, not all, the sides.
 691                // The way we chose border widths above sometimes comes with a 0 width value.
 692                // So we choose again to avoid division by zero.
 693                // TODO: A better solution exists taking a look at the whole file.
 694                // this does not fix single dashed borders at the corners
 695                let dashed_border = vec2<f32>(
 696                        max(
 697                            quad.border_widths.bottom,
 698                            quad.border_widths.top,
 699                        ),
 700                        max(
 701                            quad.border_widths.right,
 702                            quad.border_widths.left,
 703                        )
 704                   );
 705
 706                let border_width = select(dashed_border.y, dashed_border.x, is_horizontal);
 707                dash_velocity = dv_numerator / border_width;
 708                t = select(point.y, point.x, is_horizontal) * dash_velocity;
 709                max_t = select(size.y, size.x, is_horizontal) * dash_velocity;
 710            } else {
 711                // When corners are rounded, the dashes are laid out clockwise
 712                // around the whole perimeter.
 713
 714                let r_tr = quad.corner_radii.top_right;
 715                let r_br = quad.corner_radii.bottom_right;
 716                let r_bl = quad.corner_radii.bottom_left;
 717                let r_tl = quad.corner_radii.top_left;
 718
 719                let w_t = quad.border_widths.top;
 720                let w_r = quad.border_widths.right;
 721                let w_b = quad.border_widths.bottom;
 722                let w_l = quad.border_widths.left;
 723
 724                // Straight side dash velocities
 725                let dv_t = select(dv_numerator / w_t, 0.0, w_t <= 0.0);
 726                let dv_r = select(dv_numerator / w_r, 0.0, w_r <= 0.0);
 727                let dv_b = select(dv_numerator / w_b, 0.0, w_b <= 0.0);
 728                let dv_l = select(dv_numerator / w_l, 0.0, w_l <= 0.0);
 729
 730                // Straight side lengths in dash space
 731                let s_t = (size.x - r_tl - r_tr) * dv_t;
 732                let s_r = (size.y - r_tr - r_br) * dv_r;
 733                let s_b = (size.x - r_br - r_bl) * dv_b;
 734                let s_l = (size.y - r_bl - r_tl) * dv_l;
 735
 736                let corner_dash_velocity_tr = corner_dash_velocity(dv_t, dv_r);
 737                let corner_dash_velocity_br = corner_dash_velocity(dv_b, dv_r);
 738                let corner_dash_velocity_bl = corner_dash_velocity(dv_b, dv_l);
 739                let corner_dash_velocity_tl = corner_dash_velocity(dv_t, dv_l);
 740
 741                // Corner lengths in dash space
 742                let c_tr = r_tr * (M_PI_F / 2.0) * corner_dash_velocity_tr;
 743                let c_br = r_br * (M_PI_F / 2.0) * corner_dash_velocity_br;
 744                let c_bl = r_bl * (M_PI_F / 2.0) * corner_dash_velocity_bl;
 745                let c_tl = r_tl * (M_PI_F / 2.0) * corner_dash_velocity_tl;
 746
 747                // Cumulative dash space upto each segment
 748                let upto_tr = s_t;
 749                let upto_r = upto_tr + c_tr;
 750                let upto_br = upto_r + s_r;
 751                let upto_b = upto_br + c_br;
 752                let upto_bl = upto_b + s_b;
 753                let upto_l = upto_bl + c_bl;
 754                let upto_tl = upto_l + s_l;
 755                max_t = upto_tl + c_tl;
 756
 757                if (is_near_rounded_corner) {
 758                    let radians = atan2(corner_center_to_point.y,
 759                                        corner_center_to_point.x);
 760                    let corner_t = radians * corner_radius;
 761
 762                    if (center_to_point.x >= 0.0) {
 763                        if (center_to_point.y < 0.0) {
 764                            dash_velocity = corner_dash_velocity_tr;
 765                            // Subtracted because radians is pi/2 to 0 when
 766                            // going clockwise around the top right corner,
 767                            // since the y axis has been flipped
 768                            t = upto_r - corner_t * dash_velocity;
 769                        } else {
 770                            dash_velocity = corner_dash_velocity_br;
 771                            // Added because radians is 0 to pi/2 when going
 772                            // clockwise around the bottom-right corner
 773                            t = upto_br + corner_t * dash_velocity;
 774                        }
 775                    } else {
 776                        if (center_to_point.y >= 0.0) {
 777                            dash_velocity = corner_dash_velocity_bl;
 778                            // Subtracted because radians is pi/2 to 0 when
 779                            // going clockwise around the bottom-left corner,
 780                            // since the x axis has been flipped
 781                            t = upto_l - corner_t * dash_velocity;
 782                        } else {
 783                            dash_velocity = corner_dash_velocity_tl;
 784                            // Added because radians is 0 to pi/2 when going
 785                            // clockwise around the top-left corner, since both
 786                            // axis were flipped
 787                            t = upto_tl + corner_t * dash_velocity;
 788                        }
 789                    }
 790                } else {
 791                    // Straight borders
 792                    let is_horizontal =
 793                            corner_center_to_point.x <
 794                            corner_center_to_point.y;
 795                    if (is_horizontal) {
 796                        if (center_to_point.y < 0.0) {
 797                            dash_velocity = dv_t;
 798                            t = (point.x - r_tl) * dash_velocity;
 799                        } else {
 800                            dash_velocity = dv_b;
 801                            t = upto_bl - (point.x - r_bl) * dash_velocity;
 802                        }
 803                    } else {
 804                        if (center_to_point.x < 0.0) {
 805                            dash_velocity = dv_l;
 806                            t = upto_tl - (point.y - r_tl) * dash_velocity;
 807                        } else {
 808                            dash_velocity = dv_r;
 809                            t = upto_r + (point.y - r_tr) * dash_velocity;
 810                        }
 811                    }
 812                }
 813            }
 814
 815            let dash_length = dash_length_per_width / dash_period_per_width;
 816            let desired_dash_gap = dash_gap_per_width / dash_period_per_width;
 817
 818            // Straight borders should start and end with a dash, so max_t is
 819            // reduced to cause this.
 820            max_t -= select(0.0, dash_length, unrounded);
 821            if (max_t >= 1.0) {
 822                // Adjust dash gap to evenly divide max_t.
 823                let dash_count = floor(max_t);
 824                let dash_period = max_t / dash_count;
 825                border_color.a *= dash_alpha(
 826                    t,
 827                    dash_period,
 828                    dash_length,
 829                    dash_velocity,
 830                    antialias_threshold);
 831            } else if (unrounded) {
 832                // When there isn't enough space for the full gap between the
 833                // two start / end dashes of a straight border, reduce gap to
 834                // make them fit.
 835                let dash_gap = max_t - dash_length;
 836                if (dash_gap > 0.0) {
 837                    let dash_period = dash_length + dash_gap;
 838                    border_color.a *= dash_alpha(
 839                        t,
 840                        dash_period,
 841                        dash_length,
 842                        dash_velocity,
 843                        antialias_threshold);
 844                }
 845            }
 846        }
 847
 848        // Blend the border on top of the background and then linearly interpolate
 849        // between the two as we slide inside the background.
 850        let blended_border = over(background_color, border_color);
 851        color = mix(background_color, blended_border,
 852                    saturate(antialias_threshold - inner_sdf));
 853    }
 854
 855    return blend_color(color, saturate(antialias_threshold - outer_sdf));
 856}
 857
 858// Returns the dash velocity of a corner given the dash velocity of the two
 859// sides, by returning the slower velocity (larger dashes).
 860//
 861// Since 0 is used for dash velocity when the border width is 0 (instead of
 862// +inf), this returns the other dash velocity in that case.
 863//
 864// An alternative to this might be to appropriately interpolate the dash
 865// velocity around the corner, but that seems overcomplicated.
 866fn corner_dash_velocity(dv1: f32, dv2: f32) -> f32 {
 867    if (dv1 == 0.0) {
 868        return dv2;
 869    } else if (dv2 == 0.0) {
 870        return dv1;
 871    } else {
 872        return min(dv1, dv2);
 873    }
 874}
 875
 876// Returns alpha used to render antialiased dashes.
 877// `t` is within the dash when `fmod(t, period) < length`.
 878fn dash_alpha(t: f32, period: f32, length: f32, dash_velocity: f32, antialias_threshold: f32) -> f32 {
 879    let half_period = period / 2;
 880    let half_length = length / 2;
 881    // Value in [-half_period, half_period].
 882    // The dash is in [-half_length, half_length].
 883    let centered = fmod(t + half_period - half_length, period) - half_period;
 884    // Signed distance for the dash, negative values are inside the dash.
 885    let signed_distance = abs(centered) - half_length;
 886    // Antialiased alpha based on the signed distance.
 887    return saturate(antialias_threshold - signed_distance / dash_velocity);
 888}
 889
 890// This approximates distance to the nearest point to a quarter ellipse in a way
 891// that is sufficient for anti-aliasing when the ellipse is not very eccentric.
 892// The components of `point` are expected to be positive.
 893//
 894// Negative on the outside and positive on the inside.
 895fn quarter_ellipse_sdf(point: vec2<f32>, radii: vec2<f32>) -> f32 {
 896    // Scale the space to treat the ellipse like a unit circle.
 897    let circle_vec = point / radii;
 898    let unit_circle_sdf = length(circle_vec) - 1.0;
 899    // Approximate up-scaling of the length by using the average of the radii.
 900    //
 901    // TODO: A better solution would be to use the gradient of the implicit
 902    // function for an ellipse to approximate a scaling factor.
 903    return unit_circle_sdf * (radii.x + radii.y) * -0.5;
 904}
 905
 906// Modulus that has the same sign as `a`.
 907fn fmod(a: f32, b: f32) -> f32 {
 908    return a - b * trunc(a / b);
 909}
 910
 911// --- shadows --- //
 912
 913struct Shadow {
 914    order: u32,
 915    blur_radius: f32,
 916    bounds: Bounds,
 917    corner_radii: Corners,
 918    content_mask: Bounds,
 919    color: Hsla,
 920}
 921var<storage, read> b_shadows: array<Shadow>;
 922
 923struct ShadowVarying {
 924    @builtin(position) position: vec4<f32>,
 925    @location(0) @interpolate(flat) color: vec4<f32>,
 926    @location(1) @interpolate(flat) shadow_id: u32,
 927    //TODO: use `clip_distance` once Naga supports it
 928    @location(3) clip_distances: vec4<f32>,
 929}
 930
 931@vertex
 932fn vs_shadow(@builtin(vertex_index) vertex_id: u32, @builtin(instance_index) instance_id: u32) -> ShadowVarying {
 933    let unit_vertex = vec2<f32>(f32(vertex_id & 1u), 0.5 * f32(vertex_id & 2u));
 934    var shadow = b_shadows[instance_id];
 935
 936    let margin = 3.0 * shadow.blur_radius;
 937    // Set the bounds of the shadow and adjust its size based on the shadow's
 938    // spread radius to achieve the spreading effect
 939    shadow.bounds.origin -= vec2<f32>(margin);
 940    shadow.bounds.size += 2.0 * vec2<f32>(margin);
 941
 942    var out = ShadowVarying();
 943    out.position = to_device_position(unit_vertex, shadow.bounds);
 944    out.color = hsla_to_rgba(shadow.color);
 945    out.shadow_id = instance_id;
 946    out.clip_distances = distance_from_clip_rect(unit_vertex, shadow.bounds, shadow.content_mask);
 947    return out;
 948}
 949
 950@fragment
 951fn fs_shadow(input: ShadowVarying) -> @location(0) vec4<f32> {
 952    // Alpha clip first, since we don't have `clip_distance`.
 953    if (any(input.clip_distances < vec4<f32>(0.0))) {
 954        return vec4<f32>(0.0);
 955    }
 956
 957    let shadow = b_shadows[input.shadow_id];
 958    let half_size = shadow.bounds.size / 2.0;
 959    let center = shadow.bounds.origin + half_size;
 960    let center_to_point = input.position.xy - center;
 961
 962    let corner_radius = pick_corner_radius(center_to_point, shadow.corner_radii);
 963
 964    // The signal is only non-zero in a limited range, so don't waste samples
 965    let low = center_to_point.y - half_size.y;
 966    let high = center_to_point.y + half_size.y;
 967    let start = clamp(-3.0 * shadow.blur_radius, low, high);
 968    let end = clamp(3.0 * shadow.blur_radius, low, high);
 969
 970    // Accumulate samples (we can get away with surprisingly few samples)
 971    let step = (end - start) / 4.0;
 972    var y = start + step * 0.5;
 973    var alpha = 0.0;
 974    for (var i = 0; i < 4; i += 1) {
 975        let blur = blur_along_x(center_to_point.x, center_to_point.y - y,
 976            shadow.blur_radius, corner_radius, half_size);
 977        alpha +=  blur * gaussian(y, shadow.blur_radius) * step;
 978        y += step;
 979    }
 980
 981    return blend_color(input.color, alpha);
 982}
 983
 984// --- path rasterization --- //
 985
 986struct PathRasterizationVertex {
 987    xy_position: vec2<f32>,
 988    st_position: vec2<f32>,
 989    color: Background,
 990    bounds: Bounds,
 991}
 992
 993var<storage, read> b_path_vertices: array<PathRasterizationVertex>;
 994
 995struct PathRasterizationVarying {
 996    @builtin(position) position: vec4<f32>,
 997    @location(0) st_position: vec2<f32>,
 998    @location(1) vertex_id: u32,
 999    //TODO: use `clip_distance` once Naga supports it
1000    @location(3) clip_distances: vec4<f32>,
1001}
1002
1003@vertex
1004fn vs_path_rasterization(@builtin(vertex_index) vertex_id: u32) -> PathRasterizationVarying {
1005    let v = b_path_vertices[vertex_id];
1006
1007    var out = PathRasterizationVarying();
1008    out.position = to_device_position_impl(v.xy_position);
1009    out.st_position = v.st_position;
1010    out.vertex_id = vertex_id;
1011    out.clip_distances = distance_from_clip_rect_impl(v.xy_position, v.bounds);
1012    return out;
1013}
1014
1015@fragment
1016fn fs_path_rasterization(input: PathRasterizationVarying) -> @location(0) vec4<f32> {
1017    let dx = dpdx(input.st_position);
1018    let dy = dpdy(input.st_position);
1019    if (any(input.clip_distances < vec4<f32>(0.0))) {
1020        return vec4<f32>(0.0);
1021    }
1022
1023    let v = b_path_vertices[input.vertex_id];
1024    let background = v.color;
1025    let bounds = v.bounds;
1026
1027    var alpha: f32;
1028    if (length(vec2<f32>(dx.x, dy.x)) < 0.001) {
1029        // If the gradient is too small, return a solid color.
1030        alpha = 1.0;
1031    } else {
1032        let gradient = 2.0 * input.st_position.xx * vec2<f32>(dx.x, dy.x) - vec2<f32>(dx.y, dy.y);
1033        let f = input.st_position.x * input.st_position.x - input.st_position.y;
1034        let distance = f / length(gradient);
1035        alpha = saturate(0.5 - distance);
1036    }
1037    let gradient_color = prepare_gradient_color(
1038        background.tag,
1039        background.color_space,
1040        background.solid,
1041        background.colors,
1042    );
1043    let color = gradient_color(background, input.position.xy, bounds,
1044        gradient_color.solid, gradient_color.color0, gradient_color.color1);
1045    return vec4<f32>(color.rgb * color.a * alpha, color.a * alpha);
1046}
1047
1048// --- paths --- //
1049
1050struct PathSprite {
1051    bounds: Bounds,
1052}
1053var<storage, read> b_path_sprites: array<PathSprite>;
1054
1055struct PathVarying {
1056    @builtin(position) position: vec4<f32>,
1057    @location(0) texture_coords: vec2<f32>,
1058}
1059
1060@vertex
1061fn vs_path(@builtin(vertex_index) vertex_id: u32, @builtin(instance_index) instance_id: u32) -> PathVarying {
1062    let unit_vertex = vec2<f32>(f32(vertex_id & 1u), 0.5 * f32(vertex_id & 2u));
1063    let sprite = b_path_sprites[instance_id];
1064    // Don't apply content mask because it was already accounted for when rasterizing the path.
1065    let device_position = to_device_position(unit_vertex, sprite.bounds);
1066    // For screen-space intermediate texture, convert screen position to texture coordinates
1067    let screen_position = sprite.bounds.origin + unit_vertex * sprite.bounds.size;
1068    let texture_coords = screen_position / globals.viewport_size;
1069
1070    var out = PathVarying();
1071    out.position = device_position;
1072    out.texture_coords = texture_coords;
1073
1074    return out;
1075}
1076
1077@fragment
1078fn fs_path(input: PathVarying) -> @location(0) vec4<f32> {
1079    let sample = textureSample(t_sprite, s_sprite, input.texture_coords);
1080    return sample;
1081}
1082
1083// --- underlines --- //
1084
1085struct Underline {
1086    order: u32,
1087    pad: u32,
1088    bounds: Bounds,
1089    content_mask: Bounds,
1090    color: Hsla,
1091    thickness: f32,
1092    wavy: u32,
1093}
1094var<storage, read> b_underlines: array<Underline>;
1095
1096struct UnderlineVarying {
1097    @builtin(position) position: vec4<f32>,
1098    @location(0) @interpolate(flat) color: vec4<f32>,
1099    @location(1) @interpolate(flat) underline_id: u32,
1100    //TODO: use `clip_distance` once Naga supports it
1101    @location(3) clip_distances: vec4<f32>,
1102}
1103
1104@vertex
1105fn vs_underline(@builtin(vertex_index) vertex_id: u32, @builtin(instance_index) instance_id: u32) -> UnderlineVarying {
1106    let unit_vertex = vec2<f32>(f32(vertex_id & 1u), 0.5 * f32(vertex_id & 2u));
1107    let underline = b_underlines[instance_id];
1108
1109    var out = UnderlineVarying();
1110    out.position = to_device_position(unit_vertex, underline.bounds);
1111    out.color = hsla_to_rgba(underline.color);
1112    out.underline_id = instance_id;
1113    out.clip_distances = distance_from_clip_rect(unit_vertex, underline.bounds, underline.content_mask);
1114    return out;
1115}
1116
1117@fragment
1118fn fs_underline(input: UnderlineVarying) -> @location(0) vec4<f32> {
1119    const WAVE_FREQUENCY: f32 = 2.0;
1120    const WAVE_HEIGHT_RATIO: f32 = 0.8;
1121
1122    // Alpha clip first, since we don't have `clip_distance`.
1123    if (any(input.clip_distances < vec4<f32>(0.0))) {
1124        return vec4<f32>(0.0);
1125    }
1126
1127    let underline = b_underlines[input.underline_id];
1128    if ((underline.wavy & 0xFFu) == 0u)
1129    {
1130        return blend_color(input.color, input.color.a);
1131    }
1132
1133    let half_thickness = underline.thickness * 0.5;
1134
1135    let st = (input.position.xy - underline.bounds.origin) / underline.bounds.size.y - vec2<f32>(0.0, 0.5);
1136    let frequency = M_PI_F * WAVE_FREQUENCY * underline.thickness / underline.bounds.size.y;
1137    let amplitude = (underline.thickness * WAVE_HEIGHT_RATIO) / underline.bounds.size.y;
1138
1139    let sine = sin(st.x * frequency) * amplitude;
1140    let dSine = cos(st.x * frequency) * amplitude * frequency;
1141    let distance = (st.y - sine) / sqrt(1.0 + dSine * dSine);
1142    let distance_in_pixels = distance * underline.bounds.size.y;
1143    let distance_from_top_border = distance_in_pixels - half_thickness;
1144    let distance_from_bottom_border = distance_in_pixels + half_thickness;
1145    let alpha = saturate(0.5 - max(-distance_from_bottom_border, distance_from_top_border));
1146    return blend_color(input.color, alpha * input.color.a);
1147}
1148
1149// --- monochrome sprites --- //
1150
1151struct MonochromeSprite {
1152    order: u32,
1153    pad: u32,
1154    bounds: Bounds,
1155    content_mask: Bounds,
1156    color: Hsla,
1157    tile: AtlasTile,
1158    transformation: TransformationMatrix,
1159}
1160var<storage, read> b_mono_sprites: array<MonochromeSprite>;
1161
1162struct MonoSpriteVarying {
1163    @builtin(position) position: vec4<f32>,
1164    @location(0) tile_position: vec2<f32>,
1165    @location(1) @interpolate(flat) color: vec4<f32>,
1166    @location(3) clip_distances: vec4<f32>,
1167}
1168
1169@vertex
1170fn vs_mono_sprite(@builtin(vertex_index) vertex_id: u32, @builtin(instance_index) instance_id: u32) -> MonoSpriteVarying {
1171    let unit_vertex = vec2<f32>(f32(vertex_id & 1u), 0.5 * f32(vertex_id & 2u));
1172    let sprite = b_mono_sprites[instance_id];
1173
1174    var out = MonoSpriteVarying();
1175    out.position = to_device_position_transformed(unit_vertex, sprite.bounds, sprite.transformation);
1176
1177    out.tile_position = to_tile_position(unit_vertex, sprite.tile);
1178    out.color = hsla_to_rgba(sprite.color);
1179    out.clip_distances = distance_from_clip_rect_transformed(unit_vertex, sprite.bounds, sprite.content_mask, sprite.transformation);
1180    return out;
1181}
1182
1183@fragment
1184fn fs_mono_sprite(input: MonoSpriteVarying) -> @location(0) vec4<f32> {
1185    let sample = textureSample(t_sprite, s_sprite, input.tile_position).r;
1186    let alpha_corrected = apply_contrast_and_gamma_correction(sample, input.color.rgb, grayscale_enhanced_contrast, gamma_ratios);
1187
1188    // Alpha clip after using the derivatives.
1189    if (any(input.clip_distances < vec4<f32>(0.0))) {
1190        return vec4<f32>(0.0);
1191    }
1192
1193    // convert to srgb space as the rest of the code (output swapchain) expects that
1194    return blend_color(input.color, alpha_corrected);
1195}
1196
1197// --- polychrome sprites --- //
1198
1199struct PolychromeSprite {
1200    order: u32,
1201    pad: u32,
1202    grayscale: u32,
1203    opacity: f32,
1204    bounds: Bounds,
1205    content_mask: Bounds,
1206    corner_radii: Corners,
1207    tile: AtlasTile,
1208}
1209var<storage, read> b_poly_sprites: array<PolychromeSprite>;
1210
1211struct PolySpriteVarying {
1212    @builtin(position) position: vec4<f32>,
1213    @location(0) tile_position: vec2<f32>,
1214    @location(1) @interpolate(flat) sprite_id: u32,
1215    @location(3) clip_distances: vec4<f32>,
1216}
1217
1218@vertex
1219fn vs_poly_sprite(@builtin(vertex_index) vertex_id: u32, @builtin(instance_index) instance_id: u32) -> PolySpriteVarying {
1220    let unit_vertex = vec2<f32>(f32(vertex_id & 1u), 0.5 * f32(vertex_id & 2u));
1221    let sprite = b_poly_sprites[instance_id];
1222
1223    var out = PolySpriteVarying();
1224    out.position = to_device_position(unit_vertex, sprite.bounds);
1225    out.tile_position = to_tile_position(unit_vertex, sprite.tile);
1226    out.sprite_id = instance_id;
1227    out.clip_distances = distance_from_clip_rect(unit_vertex, sprite.bounds, sprite.content_mask);
1228    return out;
1229}
1230
1231@fragment
1232fn fs_poly_sprite(input: PolySpriteVarying) -> @location(0) vec4<f32> {
1233    let sample = textureSample(t_sprite, s_sprite, input.tile_position);
1234    // Alpha clip after using the derivatives.
1235    if (any(input.clip_distances < vec4<f32>(0.0))) {
1236        return vec4<f32>(0.0);
1237    }
1238
1239    let sprite = b_poly_sprites[input.sprite_id];
1240    let distance = quad_sdf(input.position.xy, sprite.bounds, sprite.corner_radii);
1241
1242    var color = sample;
1243    if ((sprite.grayscale & 0xFFu) != 0u) {
1244        let grayscale = dot(color.rgb, GRAYSCALE_FACTORS);
1245        color = vec4<f32>(vec3<f32>(grayscale), sample.a);
1246    }
1247    return blend_color(color, sprite.opacity * saturate(0.5 - distance));
1248}
1249
1250// --- surfaces --- //
1251
1252struct SurfaceParams {
1253    bounds: Bounds,
1254    content_mask: Bounds,
1255}
1256
1257var<uniform> surface_locals: SurfaceParams;
1258var t_y: texture_2d<f32>;
1259var t_cb_cr: texture_2d<f32>;
1260var s_surface: sampler;
1261
1262const ycbcr_to_RGB = mat4x4<f32>(
1263    vec4<f32>( 1.0000f,  1.0000f,  1.0000f, 0.0),
1264    vec4<f32>( 0.0000f, -0.3441f,  1.7720f, 0.0),
1265    vec4<f32>( 1.4020f, -0.7141f,  0.0000f, 0.0),
1266    vec4<f32>(-0.7010f,  0.5291f, -0.8860f, 1.0),
1267);
1268
1269struct SurfaceVarying {
1270    @builtin(position) position: vec4<f32>,
1271    @location(0) texture_position: vec2<f32>,
1272    @location(3) clip_distances: vec4<f32>,
1273}
1274
1275@vertex
1276fn vs_surface(@builtin(vertex_index) vertex_id: u32) -> SurfaceVarying {
1277    let unit_vertex = vec2<f32>(f32(vertex_id & 1u), 0.5 * f32(vertex_id & 2u));
1278
1279    var out = SurfaceVarying();
1280    out.position = to_device_position(unit_vertex, surface_locals.bounds);
1281    out.texture_position = unit_vertex;
1282    out.clip_distances = distance_from_clip_rect(unit_vertex, surface_locals.bounds, surface_locals.content_mask);
1283    return out;
1284}
1285
1286@fragment
1287fn fs_surface(input: SurfaceVarying) -> @location(0) vec4<f32> {
1288    // Alpha clip after using the derivatives.
1289    if (any(input.clip_distances < vec4<f32>(0.0))) {
1290        return vec4<f32>(0.0);
1291    }
1292
1293    let y_cb_cr = vec4<f32>(
1294        textureSampleLevel(t_y, s_surface, input.texture_position, 0.0).r,
1295        textureSampleLevel(t_cb_cr, s_surface, input.texture_position, 0.0).rg,
1296        1.0);
1297
1298    return ycbcr_to_RGB * y_cb_cr;
1299}