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