text_fonts

source of font::color

1// Color glyphs from COLR and CPAL (decisions/F10.md, "Color2// emoji"): version 0's layers of plain colors and version 1's graphs of3// paints (solid colors, linear, radial and sweep gradients, transforms,4// clips by glyphs and boxes, and composite modes), varied at a variable5// face's position, drawn on the CPU into premultiplied RGBA as outlines6// are into coverage. Palette 0 gives the colors; an entry 0xFFFF takes7// the text's color.89import std::vector;10import std::option;11import std::math;1213import pkg::alloy::text::font::reader;14import pkg::alloy::text::font::face;15import pkg::alloy::text::font::outline;16import pkg::alloy::text::font::raster;17import variations;18import pkg::alloy::text;1920// The formats of COLR version 1's paints.21type PaintFormat = enum : u8 {22    ColrLayers = 1,23    Solid = 2,24    VarSolid = 3,25    LinearGradient = 4,26    VarLinearGradient = 5,27    RadialGradient = 6,28    VarRadialGradient = 7,29    SweepGradient = 8,30    VarSweepGradient = 9,31    Glyph = 10,32    ColrGlyph = 11,33    Transform = 12,34    VarTransform = 13,35    Translate = 14,36    VarTranslate = 15,37    Scale = 16,38    VarScale = 17,39    ScaleAroundCenter = 18,40    VarScaleAroundCenter = 19,41    ScaleUniform = 20,42    VarScaleUniform = 21,43    ScaleUniformAroundCenter = 22,44    VarScaleUniformAroundCenter = 23,45    Rotate = 24,46    VarRotate = 25,47    RotateAroundCenter = 26,48    VarRotateAroundCenter = 27,49    Skew = 28,50    VarSkew = 29,51    SkewAroundCenter = 30,52    VarSkewAroundCenter = 31,53    Composite = 32,54};5556// How a gradient's colors go on past its first and last stops.57type Extend = enum : u8 {58    Pad = 0,59    Repeat = 1,60    Reflect = 2,61};6263// How a composite paint puts its source over its backdrop: Porter and64// Duff's operators, then the W3C's blend modes.65type CompositeMode = enum : u8 {66    Clear = 0,67    Source = 1,68    Destination = 2,69    SourceOver = 3,70    DestinationOver = 4,71    SourceIn = 5,72    DestinationIn = 6,73    SourceOut = 7,74    DestinationOut = 8,75    SourceAtop = 9,76    DestinationAtop = 10,77    Xor = 11,78    Plus = 12,79    Screen = 13,80    Overlay = 14,81    Darken = 15,82    Lighten = 16,83    ColorDodge = 17,84    ColorBurn = 18,85    HardLight = 19,86    SoftLight = 20,87    Difference = 21,88    Exclusion = 22,89    Multiply = 23,90    Hue = 24,91    Saturation = 25,92    Color = 26,93    Luminosity = 27,94};9596// premultiplied colors are red, green, blue and alpha from 0 to 197const CLEAR: [f32 : 4] = [0.0, 0.0, 0.0, 0.0];98const NO_VARIATION: u32 = 0xFFFFFFFF;99// how deep paints may nest, so that a malformed font's cycles end, how100// many a glyph may visit, so that its shared paints do too, and how many101// composites, each holding two surfaces, may nest102const DEEPEST: u32 = 64;103const MOST_VISITS: u32 = 20000;104const DEEPEST_COMPOSITES: u32 = 4;105106// Coverage over a box of the surface, 0 outside it.107type Mask = struct {108    x0: u32,109    y0: u32,110    x1: u32,111    y1: u32,112    coverage: Vector<f32>, // row after row of the box113};114115fn coverage_at(self m: &Mask, x: u32, y: u32) -> f32 {116    if (x < m.x0 || x >= m.x1 || y < m.y0 || y >= m.y1) {117        return 0.0;118    }119    return m.coverage.get(((y - m.y0) * (m.x1 - m.x0) + x - m.x0) to u64);120}121122// A gradient's stops, sorted, and how it extends.123type ColorLine = struct {124    offsets: Vector<f32>,125    colors: Vector<[f32 : 4]>,126    extend: Extend,127};128129// What fills the clip: a color, or a gradient in the paint's own130// coordinates, which the inverse of its transform takes a pixel to.131type Shader = enum {132    Solid: [f32 : 4],133    Linear: Linear,134    Radial: Radial,135    Sweep: Sweep,136};137138// Along the line from (x0, y0) by (dx, dy).139type Linear = struct {140    inverse: Affine,141    x0: f32,142    y0: f32,143    dx: f32,144    dy: f32,145    line: ColorLine,146};147148// Between the circles (x0, y0, r0) and (x1, y1, r1), as canvases' radial149// gradients are.150type Radial = struct {151    inverse: Affine,152    x0: f32,153    y0: f32,154    r0: f32,155    x1: f32,156    y1: f32,157    r1: f32,158    line: ColorLine,159};160161// Around (x, y), counterclockwise from `start` to `end`, in degrees.162type Sweep = struct {163    inverse: Affine,164    x: f32,165    y: f32,166    start: f32,167    end: f32,168    line: ColorLine,169};170171// What drawing a face's color glyph reads, and the surface it draws on.172type Painter = struct {173    face: &Face,174    d: &[u8],175    colr: u64,176    colors: u64, // palette 0's first color record in CPAL, 0 for none177    color_count: u32,178    foreground: [f32 : 4], // straight179    took_foreground: bool,180    // COLR's variation index map and store, with the store's region181    // scalars at the face's position (none at its default)182    map: u64,183    store: u64,184    scalars: Vector<f32>,185    width: u32,186    height: u32,187    open: Vector<u32>, // the color glyphs being drawn, a cycle's end188    depth: u32,189    visits: u32,190    composites: u32,191};192193// Whether the face has a COLR record for the glyph.194pub fn has_colr_glyph(face: &Face, glyph: u32) -> bool {195    const colr = if (face.colors.colr is ::Some |c|) c else {196        return false;197    };198    if (face.colors.cpal is ::None) {199        return false;200    }201    const d = &face.data();202    return base_paint(&d, colr, glyph) is ::Some || base_layers(&d, colr, glyph) is ::Some;203}204205// The glyph's COLR paint at `scale` pixels a font unit, moved right by206// `shift` pixels: None when COLR has no record for it.207pub fn paint_glyph(208    face: &Face,209    glyph: u32,210    scale: f32,211    shift: f32,212    foreground: &TextColor213) -> Option<ColorMask> {214    const colr = if (face.colors.colr is ::Some |c|) c else {215        return ::None;216    };217    const cpal = if (face.colors.cpal is ::Some |c|) c else {218        return ::None;219    };220    const d = &face.data();221    const paint = base_paint(&d, colr, glyph);222    const layers = if (paint is ::None) base_layers(&d, colr, glyph) else Option<[u64 : 2]>::None;223    if (paint is ::None && layers is ::None) {224        return ::None;225    }226    var p = Painter {227        .face = &face,228        .d = &d,229        .colr = colr,230        .colors = 0,231        .color_count = u16_at(&d, cpal + 2),232        .foreground = [foreground.r, foreground.g, foreground.b, foreground.a],233        .took_foreground = false,234        .map = 0,235        .store = 0,236        .scalars = Vector<f32>::empty(),237        .width = 0,238        .height = 0,239        .open = Vector<u32>::empty(),240        .depth = 0,241        .visits = 0,242        .composites = 0243    };244    if (u16_at(&d, cpal + 4) > 0) {245        p.colors = cpal + u32_at(&d, cpal + 8) to u64 + u16_at(&d, cpal + 12) to u64 * 4;246    }247    if (u16_at(&d, colr) >= 1) {248        const map = u32_at(&d, colr + 26) to u64;249        const store = u32_at(&d, colr + 30) to u64;250        if (store != 0 && face.coords.length() > 0) {251            p.map = if (map == 0) 0 else colr + map;252            p.store = colr + store;253            p.scalars = region_scalars(&d, p.store, &face.coords.view());254        }255    }256    // the pixels it covers: its clip box's, else its glyphs' bounds257    const font = Affine { .a = scale, .b = 0.0, .c = 0.0, .d = -scale, .e = shift, .f = 0.0 };258    var bounds: [f32 : 4] = [1000000.0, 1000000.0, -1000000.0, -1000000.0];259    if (paint is ::Some |at|) {260        if (p.clip_box(glyph) is ::Some |box|) {261            add_box(&var bounds, &box, &font);262        } else {263            p.reach(at, &font, &var bounds);264        }265    } else if (layers is ::Some |range|) {266        for ([range[0]..range[0] + range[1]]) |k| {267            const layer = colr + u32_at(&d, colr + 8) to u64 + k * 4;268            add_outline(&var bounds, &face.drawn_outline(u16_at(&d, layer)), &font);269        }270    }271    if (272        !(bounds[0] < bounds[2] && bounds[2] - bounds[0] <= 2048.0)273        || !(bounds[1] < bounds[3] && bounds[3] - bounds[1] <= 2048.0)274        || !(abs(bounds[0]) < 1.0e6 && abs(bounds[1]) < 1.0e6)275    ) {276        return ::None;277    }278    p.visits = 0;279    const left = floor(bounds[0]) to i32;280    const top = floor(bounds[1]) to i32;281    const width = (ceil(bounds[2]) to i32 - left) to u32;282    const height = (ceil(bounds[3]) to i32 - top) to u32;283    if (width == 0 || height == 0 || width > 2048 || height > 2048) {284        return ::None;285    }286    p.width = width;287    p.height = height;288    // font units to the surface's pixels289    const t = Affine {290        .a = scale,291        .b = 0.0,292        .c = 0.0,293        .d = -scale,294        .e = shift - left to f32,295        .f = -top to f32296    };297    var surface = Vector<f32>::filled(0.0, width to u64 * height to u64 * 4);298    const none: Option<Mask> = ::None;299    if (paint is ::Some |at|) {300        var clip: Option<Mask> = ::None;301        if (p.clip_box(glyph) is ::Some |box|) {302            clip = p.box_mask(&box, &t, &none);303        }304        p.open.push(glyph);305        p.draw(at, &t, &clip, &var surface.items());306    } else if (layers is ::Some |range|) {307        // each layer a glyph in one color of the palette308        for ([range[0]..range[0] + range[1]]) |k| {309            const layer = colr + u32_at(&d, colr + 8) to u64 + k * 4;310            const mask = p.glyph_mask(u16_at(&d, layer), &t, &none);311            if (mask is ::Some) {312                const color = p.color(u16_at(&d, layer + 2), 1.0);313                p.fill(&Shader::Solid(color), &mask, &var surface.items());314            }315        }316    }317    var pixels = Vector<u8>::filled(0, width to u64 * height to u64 * 4);318    for (pixels.items(), surface.view()) |&var byte, value| {319        byte = (clamp(value, 0.0, 1.0) * 255.0 + 0.5) to u8;320    }321    return ::Some(ColorMask {322        .width = width,323        .height = height,324        .left = left,325        .top = top,326        .pixels = move pixels,327        .foreground = p.took_foreground328    });329}330331// The glyph's paint in BaseGlyphList, if COLR's version 1 has one.332fn base_paint(d: &[u8], colr: u64, glyph: u32) -> Option<u64> {333    if (u16_at(&d, colr) < 1 || u32_at(&d, colr + 14) == 0) {334        return ::None;335    }336    const list = colr + u32_at(&d, colr + 14) to u64;337    var low: u64 = 0;338    var high = u32_at(&d, list) to u64;339    while (low < high) {340        const middle = (low + high) / 2;341        const record = list + 4 + middle * 6;342        const g = u16_at(&d, record);343        if (g == glyph) {344            return ::Some(list + u32_at(&d, record + 2) to u64);345        }346        if (g < glyph) {347            low = middle + 1;348        } else {349            high = middle;350        }351    }352    return ::None;353}354355// The glyph's first layer and layer count in version 0's records.356fn base_layers(d: &[u8], colr: u64, glyph: u32) -> Option<[u64 : 2]> {357    const records = colr + u32_at(&d, colr + 4) to u64;358    var low: u64 = 0;359    var high = u16_at(&d, colr + 2) to u64;360    while (low < high) {361        const middle = (low + high) / 2;362        const record = records + middle * 6;363        const g = u16_at(&d, record);364        if (g == glyph) {365            const count = u16_at(&d, record + 4) to u64;366            return if (count == 0) ::None else ::Some([u16_at(&d, record + 2) to u64, count]);367        }368        if (g < glyph) {369            low = middle + 1;370        } else {371            high = middle;372        }373    }374    return ::None;375}376377// The glyph's clip box in font units (x0, y0, x1, y1), if ClipList has378// one.379fn clip_box(self p: &Painter, glyph: u32) -> Option<[f32 : 4]> {380    const d = &p.d;381    if (u16_at(&d, p.colr) < 1 || u32_at(&d, p.colr + 22) == 0) {382        return ::None;383    }384    const list = p.colr + u32_at(&d, p.colr + 22) to u64;385    var low: u64 = 0;386    var high = u32_at(&d, list + 1) to u64;387    while (low < high) {388        const middle = (low + high) / 2;389        const clip = list + 5 + middle * 7;390        if (glyph < u16_at(&d, clip)) {391            high = middle;392        } else if (glyph > u16_at(&d, clip + 2)) {393            low = middle + 1;394        } else {395            const box = list + u24_at(&d, clip + 4) to u64;396            var values: [f32 : 4] = [397                i16_at(&d, box + 1) to f32,398                i16_at(&d, box + 3) to f32,399                i16_at(&d, box + 5) to f32,400                i16_at(&d, box + 7) to f32401            ];402            if (u8_at(&d, box) == 2) {403                const base = u32_at(&d, box + 9);404                for ([..4 to u64]) |k| {405                    values[k] += p.delta(base, k to u32);406                }407            }408            return ::Some(values);409        }410    }411    return ::None;412}413414fn u24_at(d: &[u8], at: u64) -> u32 => (u16_at(&d, at) << 8) | u8_at(&d, at + 2);415416// The delta at the face's position of the varied value at the index.417fn delta(self p: &Painter, base: u32, k: u32) -> f32 {418    if (p.scalars.length() == 0 || base > NO_VARIATION - 1 - k) {419        return 0.0;420    }421    const index = base + k;422    var outer = index >> 16;423    var inner = index & 0xFFFF;424    if (p.map != 0) {425        const row = mapped_row(&p.d, p.map, index);426        outer = row[0];427        inner = row[1];428    }429    return store_delta(&p.d, p.store, outer, inner, &p.scalars.view());430}431432// The palette's color at the index (the text's for 0xFFFF), its alpha433// multiplied by `alpha`, premultiplied.434fn color(self p: &var Painter, index: u32, alpha: f32) -> [f32 : 4] {435    var c = CLEAR;436    if (index == 0xFFFF) {437        p.took_foreground = true;438        c = p.foreground;439    } else if (index < p.color_count && p.colors != 0) {440        const at = p.colors + index to u64 * 4;441        const d = &p.d;442        // blue, green, red, alpha443        c = [444            u8_at(&d, at + 2) to f32 / 255.0,445            u8_at(&d, at + 1) to f32 / 255.0,446            u8_at(&d, at) to f32 / 255.0,447            u8_at(&d, at + 3) to f32 / 255.0448        ];449    }450    const a = c[3] * clamp(alpha, 0.0, 1.0);451    return [c[0] * a, c[1] * a, c[2] * a, a];452}453454/* --- Paints --- */455456// Draws the paint at `at`, its coordinates taken to the surface's by457// `t`, within the clip (everywhere for None), over what the surface has.458fn draw(self p: &var Painter, at: u64, t: &Affine, clip: &Option<Mask>, surface: &var [f32]) {459    if (p.depth >= DEEPEST || p.visits >= MOST_VISITS) {460        return;461    }462    p.visits += 1;463    const d = &p.d;464    const format = if (PaintFormat::from(u8_at(&d, at) to u8) is ::Some |f|) f else {465        return;466    };467    p.depth += 1;468    defer p.depth -= 1;469    match (format) {470        ::ColrLayers {471            if (u32_at(&d, p.colr + 18) == 0) {472                return;473            }474            const list = p.colr + u32_at(&d, p.colr + 18) to u64;475            const first = u32_at(&d, at + 2) to u64;476            for ([first..first + u8_at(&d, at + 1) to u64]) |k| {477                if (k < u32_at(&d, list) to u64) {478                    p.draw(list + u32_at(&d, list + 4 + k * 4) to u64, &t, &clip, &var surface);479                }480            }481        }482        ::Solid, ::VarSolid {483            const base = if (format is ::VarSolid) u32_at(&d, at + 5) else NO_VARIATION;484            const alpha = f2dot14_at(&d, at + 3) + p.delta(base, 0) / 16384.0;485            const color = p.color(u16_at(&d, at + 1), alpha);486            p.fill(&Shader::Solid(color), &clip, &var surface);487        }488        ::LinearGradient, ::VarLinearGradient, ::RadialGradient, ::VarRadialGradient {489            const varied = format is ::VarLinearGradient || format is ::VarRadialGradient;490            const base = if (varied) u32_at(&d, at + 16) else NO_VARIATION;491            var v: [f32 : 6] = [0.0 : 6];492            for ([..6 to u64]) |k| {493                v[k] = i16_at(&d, at + 4 + k * 2) to f32 + p.delta(base, k to u32);494            }495            var line = p.color_line(at + u24_at(&d, at + 1) to u64, varied);496            const inverse = t.inverse();497            if (format is ::LinearGradient || format is ::VarLinearGradient) {498                // the line from p0 to p1 turned so that its colors run499                // along p0 to p2: p0 to p3, p1 projected on the normal of p0 p2500                const nx = v[5] - v[1];501                const ny = -(v[4] - v[0]);502                const n = nx * nx + ny * ny;503                if (n == 0.0) {504                    return;505                }506                const k = ((v[2] - v[0]) * nx + (v[3] - v[1]) * ny) / n;507                if (k == 0.0) {508                    return; // p1 on the line through p0 and p2509                }510                var linear = Linear {511                    .inverse = inverse,512                    .x0 = v[0],513                    .y0 = v[1],514                    .dx = nx * k,515                    .dy = ny * k,516                    .line = move line517                };518                p.fill(&Shader::Linear(move linear), &clip, &var surface);519            } else {520                // radii are unsigned521                var radial = Radial {522                    .inverse = inverse,523                    .x0 = v[0],524                    .y0 = v[1],525                    .r0 = u16_at(&d, at + 8) to f32 + p.delta(base, 2),526                    .x1 = v[3],527                    .y1 = v[4],528                    .r1 = u16_at(&d, at + 14) to f32 + p.delta(base, 5),529                    .line = move line530                };531                p.fill(&Shader::Radial(move radial), &clip, &var surface);532            }533        }534        ::SweepGradient, ::VarSweepGradient {535            const varied = format is ::VarSweepGradient;536            const base = if (varied) u32_at(&d, at + 12) else NO_VARIATION;537            var sweep = Sweep {538                .inverse = t.inverse(),539                .x = i16_at(&d, at + 4) to f32 + p.delta(base, 0),540                .y = i16_at(&d, at + 6) to f32 + p.delta(base, 1),541                // biased by 1, so that 360 degrees can be written542                .start = (f2dot14_at(&d, at + 8) + 1.0 + p.delta(base, 2) / 16384.0) * 180.0,543                .end = (f2dot14_at(&d, at + 10) + 1.0 + p.delta(base, 3) / 16384.0) * 180.0,544                .line = p.color_line(at + u24_at(&d, at + 1) to u64, varied)545            };546            p.fill(&Shader::Sweep(move sweep), &clip, &var surface);547        }548        ::Glyph {549            const mask = p.glyph_mask(u16_at(&d, at + 4), &t, &clip);550            if (mask is ::Some) {551                p.draw(at + u24_at(&d, at + 1) to u64, &t, &mask, &var surface);552            }553        }554        ::ColrGlyph {555            const glyph = u16_at(&d, at + 1);556            for (p.open.view()) |g| {557                if (g == glyph) {558                    return; // a cycle559                }560            }561            const paint = if (base_paint(&d, p.colr, glyph) is ::Some |b|) b else {562                return;563            };564            var inner: Option<Mask> = ::None;565            if (p.clip_box(glyph) is ::Some |box|) {566                inner = p.box_mask(&box, &t, &clip);567                if (inner is ::None) {568                    return;569                }570            }571            p.open.push(glyph);572            if (inner is ::Some) {573                p.draw(paint, &t, &inner, &var surface);574            } else {575                p.draw(paint, &t, &clip, &var surface);576            }577            p.open.pop();578        }579        ::Composite {580            const mode = if (CompositeMode::from(u8_at(&d, at + 4) to u8) is ::Some |m|) m else {581                return;582            };583            if (p.composites >= DEEPEST_COMPOSITES) {584                return;585            }586            p.composites += 1;587            defer p.composites -= 1;588            const size = surface.length();589            var source = Vector<f32>::filled(0.0, size);590            var backdrop = Vector<f32>::filled(0.0, size);591            p.draw(at + u24_at(&d, at + 1) to u64, &t, &clip, &var source.items());592            p.draw(at + u24_at(&d, at + 5) to u64, &t, &clip, &var backdrop.items());593            composite(&source.view(), &var backdrop.items(), mode);594            over(&backdrop.view(), &var surface);595        }596        else {597            // the transforms598            const local = p.transform(format, at);599            p.draw(at + u24_at(&d, at + 1) to u64, &local.then(&t), &clip, &var surface);600        }601    }602}603604// The transform a transforming paint makes, from its coordinates to its605// parent's.606fn transform(self p: &Painter, format: PaintFormat, at: u64) -> Affine {607    const d = &p.d;608    if (format is ::Transform || format is ::VarTransform) {609        const m = at + u24_at(&d, at + 4) to u64;610        const base = if (format is ::VarTransform) u32_at(&d, m + 24) else NO_VARIATION;611        var v: [f32 : 6] = [0.0 : 6];612        for ([..6 to u64]) |k| {613            v[k] = (u32_at(&d, m + k * 4) as i32) to f32 / 65536.0 + p.delta(614                base,615                k to u32616            ) / 65536.0;617        }618        return Affine { .a = v[0], .b = v[1], .c = v[2], .d = v[3], .e = v[4], .f = v[5] };619    }620    // the two-byte fields after the child's offset: how many, which are621    // angles or scales (F2DOT14), and whether a center ends them622    const varied = (format to u8 & 1) == 1;623    const plain = if (varied) (format to u8 - 1) else format to u8;624    var count: u64 = 0;625    var around = false;626    match (plain) {627        14, 16, 28 {628            count = 2;629        }630        18, 30 {631            count = 4;632            around = true;633        }634        20, 24 {635            count = 1;636        }637        22, 26 {638            count = 3;639            around = true;640        }641        else {}642    }643    const base = if (varied) u32_at(&d, at + 4 + count * 2) else NO_VARIATION;644    var v: [f32 : 4] = [0.0 : 4];645    for ([..count]) |k| {646        const delta = p.delta(base, k to u32);647        // a center's coordinates and a translation's are font units648        const units = plain == 14 || (around && k + 2 >= count);649        v[k] = if (units) i16_at(&d, at + 4 + k * 2) to f32 + delta else f2dot14_at(650            &d,651            at + 4 + k * 2652        ) + delta / 16384.0;653    }654    var m = IDENTITY;655    match (plain) {656        14 {657            m.e = v[0];658            m.f = v[1];659        }660        16, 18 {661            m.a = v[0];662            m.d = v[1];663        }664        20, 22 {665            m.a = v[0];666            m.d = v[0];667        }668        24, 26 {669            const angle = v[0] * 3.14159265358979;670            m.a = cos(angle);671            m.b = sin(angle);672            m.c = -sin(angle);673            m.d = cos(angle);674        }675        28, 30 {676            m.c = -tan(v[0] * 3.14159265358979);677            m.b = tan(v[1] * 3.14159265358979);678        }679        else {}680    }681    if (around) {682        const cx = v[count - 2];683        const cy = v[count - 1];684        // to the center, the transform, and back685        const to_center = Affine { .a = 1.0, .b = 0.0, .c = 0.0, .d = 1.0, .e = -cx, .f = -cy };686        const back = Affine { .a = 1.0, .b = 0.0, .c = 0.0, .d = 1.0, .e = cx, .f = cy };687        return to_center.then(&m).then(&back);688    }689    return m;690}691692// The color line at `at`: its stops sorted by offset, premultiplied.693fn color_line(self p: &var Painter, at: u64, varied: bool) -> ColorLine {694    const d = &p.d;695    const extend = if (Extend::from(u8_at(&d, at) to u8) is ::Some |e|) e else Extend::Pad;696    const count = u16_at(&d, at + 1) to u64;697    const size: u64 = if (varied) 10 else 6;698    var line = ColorLine {699        .offsets = Vector<f32>::with_capacity(count),700        .colors = Vector<[f32 : 4]>::with_capacity(count),701        .extend = extend702    };703    for ([..count]) |k| {704        const stop = at + 3 + k * size;705        const base = if (varied) u32_at(&d, stop + 6) else NO_VARIATION;706        const offset = f2dot14_at(&d, stop) + p.delta(base, 0) / 16384.0;707        const color = p.color(708            u16_at(&d, stop + 2),709            f2dot14_at(&d, stop + 4) + p.delta(base, 1) / 16384.0710        );711        // inserted after those at or before its offset, keeping their order712        var i = line.offsets.length();713        while (i > 0 && line.offsets.get(i - 1) > offset) {714            i -= 1;715        }716        line.offsets.insert(i, offset);717        line.colors.insert(i, color);718    }719    return move line;720}721722// The color at `t` along the line.723fn color_at(self line: &ColorLine, t: f32) -> [f32 : 4] {724    const n = line.offsets.length();725    if (n == 0) {726        return CLEAR;727    }728    const first = line.offsets.get(0);729    const last = line.offsets.get(n - 1);730    if (!(abs(t) < 1.0e30)) {731        return CLEAR;732    }733    var s = t;734    const span = last - first;735    if (span <= 0.0 && !(line.extend is ::Pad)) {736        return CLEAR; // nothing to repeat737    }738    if (span > 0.0) {739        match (line.extend) {740            ::Repeat {741                const u = (t - first) / span;742                s = first + (u - floor(u)) * span;743            }744            ::Reflect {745                // u's place in a period of two spans, back after the first746                const u = (t - first) / span;747                const m = u - 2.0 * floor(u * 0.5);748                s = first + (if (m >= 1.0) 2.0 - m else m) * span;749            }750            ::Pad {}751        }752    }753    if (s <= first) {754        return line.colors.get(0);755    }756    if (s >= last) {757        return line.colors.get(n - 1);758    }759    for ([1..n]) |k| {760        const at = line.offsets.get(k);761        if (s < at) {762            const before = line.offsets.get(k - 1);763            const f = if (at > before) (s - before) / (at - before) else 0.0;764            const a = &line.colors.get(k - 1);765            const b = &line.colors.get(k);766            return [767                a[0] + (b[0] - a[0]) * f,768                a[1] + (b[1] - a[1]) * f,769                a[2] + (b[2] - a[2]) * f,770                a[3] + (b[3] - a[3]) * f771            ];772        }773    }774    return line.colors.get(n - 1);775}776777// The shader's color at the surface's pixel (x, y), its center.778fn shade(self shader: &Shader, x: u32, y: u32) -> [f32 : 4] {779    const px = x to f32 + 0.5;780    const py = y to f32 + 0.5;781    match (shader) {782        ::Solid |c| {783            return c;784        }785        ::Linear |&l| {786            const u = l.inverse.a * px + l.inverse.c * py + l.inverse.e - l.x0;787            const v = l.inverse.b * px + l.inverse.d * py + l.inverse.f - l.y0;788            const n = l.dx * l.dx + l.dy * l.dy;789            return l.line.color_at(if (n > 0.0) (u * l.dx + v * l.dy) / n else 0.0);790        }791        ::Radial |&r| {792            const u = r.inverse.a * px + r.inverse.c * py + r.inverse.e;793            const v = r.inverse.b * px + r.inverse.d * py + r.inverse.f;794            if (r.radius_at(u, v) is ::Some |t|) {795                return r.line.color_at(t);796            }797            return CLEAR;798        }799        ::Sweep |&s| {800            const u = s.inverse.a * px + s.inverse.c * py + s.inverse.e - s.x;801            const v = s.inverse.b * px + s.inverse.d * py + s.inverse.f - s.y;802            var angle = atan2(v, u) * 57.2957795130823;803            if (angle < 0.0) {804                angle += 360.0;805            }806            if (s.end == s.start) {807                // only padding: before the angle the first color, after it the last808                if (!(s.line.extend is ::Pad)) {809                    return CLEAR;810                }811                return if (angle < s.start) s.line.color_at(0.0) else s.line.color_at(1.0);812            }813            return s.line.color_at((angle - s.start) / (s.end - s.start));814        }815    }816}817818// Where along the gradient the point (u, v) is: the largest t whose819// circle, its radius not below 0, passes through it.820fn radius_at(self r: &Radial, u: f32, v: f32) -> Option<f32> {821    const cdx = r.x1 - r.x0;822    const cdy = r.y1 - r.y0;823    const dr = r.r1 - r.r0;824    const pdx = u - r.x0;825    const pdy = v - r.y0;826    const a = cdx * cdx + cdy * cdy - dr * dr;827    const b = pdx * cdx + pdy * cdy + r.r0 * dr;828    const c = pdx * pdx + pdy * pdy - r.r0 * r.r0;829    if (abs(a) < 0.0001) {830        if (b == 0.0) {831            return ::None;832        }833        const t = c / (2.0 * b);834        return if (r.r0 + t * dr >= 0.0) ::Some(t) else ::None;835    }836    const discriminant = b * b - a * c;837    if (discriminant < 0.0) {838        return ::None;839    }840    const root = sqrt(discriminant);841    const t1 = (b + root) / a;842    const t2 = (b - root) / a;843    const high = max(t1, t2);844    const low = min(t1, t2);845    if (r.r0 + high * dr >= 0.0) {846        return ::Some(high);847    }848    if (r.r0 + low * dr >= 0.0) {849        return ::Some(low);850    }851    return ::None;852}853854// Fills the clip with the shader, over what the surface has.855fn fill(self p: &Painter, shader: &Shader, clip: &Option<Mask>, surface: &var [f32]) {856    var box: [u32 : 4] = [0, 0, p.width, p.height];857    if (clip is ::Some |&m|) {858        box = [m.x0, m.y0, m.x1, m.y1];859    }860    const solid = shader is ::Solid;861    var color = CLEAR;862    if (shader is ::Solid |c|) {863        color = c;864    }865    for ([box[1] to u64..box[3] to u64]) |y| {866        for ([box[0] to u64..box[2] to u64]) |x| {867            var coverage: f32 = 1.0;868            if (clip is ::Some |&m|) {869                coverage = m.coverage.get(870                    (y - box[1] to u64) * (box[2] - box[0]) to u64 + x - box[0] to u64871                );872                if (coverage <= 0.0) {873                    continue;874                }875            }876            if (!solid) {877                color = shader.shade(x to u32, y to u32);878            }879            const a = color[3] * coverage;880            if (a <= 0.0) {881                continue;882            }883            const i = (y * p.width to u64 + x) * 4;884            const keep = 1.0 - a;885            surface[i] = color[0] * coverage + surface[i] * keep;886            surface[i + 1] = color[1] * coverage + surface[i + 1] * keep;887            surface[i + 2] = color[2] * coverage + surface[i + 2] * keep;888            surface[i + 3] = a + surface[i + 3] * keep;889        }890    }891}892893// The glyph's outline as coverage on the surface at `t`, within the clip;894// None where they do not meet.895fn glyph_mask(self p: &Painter, glyph: u32, t: &Affine, clip: &Option<Mask>) -> Option<Mask> {896    return p.mask_of(&rasterize_within(&p.face.drawn_outline(glyph), &t, p.window()), &clip);897}898899// A clip box in font units as coverage on the surface at `t`, within the900// clip.901fn box_mask(self p: &Painter, box: &[f32 : 4], t: &Affine, clip: &Option<Mask>) -> Option<Mask> {902    var o = Outline::empty();903    const xs: [f32 : 4] = [box[0], box[0], box[2], box[2]];904    const ys: [f32 : 4] = [box[1], box[3], box[3], box[1]];905    for (xs, ys) |x, y| {906        o.points.push(OutlinePoint { .x = x, .y = y, .kind = PointKind::On });907    }908    o.ends.push(3);909    return p.mask_of(&rasterize_within(&o, &t, p.window()), &clip);910}911912fn window(self p: &Painter) -> [i32 : 4] => [0, 0, p.width to i32, p.height to i32];913914fn mask_of(self p: &Painter, g: &GlyphMask, clip: &Option<Mask>) -> Option<Mask> {915    var x0 = max(g.left, 0) to u32;916    var y0 = max(g.top, 0) to u32;917    var x1 = clamp(g.left + g.width to i32, 0, p.width to i32) to u32;918    var y1 = clamp(g.top + g.height to i32, 0, p.height to i32) to u32;919    if (clip is ::Some |&m|) {920        x0 = max(x0, m.x0);921        y0 = max(y0, m.y0);922        x1 = min(x1, m.x1);923        y1 = min(y1, m.y1);924    }925    if (x0 >= x1 || y0 >= y1) {926        return ::None;927    }928    var mask = Mask {929        .x0 = x0,930        .y0 = y0,931        .x1 = x1,932        .y1 = y1,933        .coverage = Vector<f32>::with_capacity((x1 - x0) to u64 * (y1 - y0) to u64)934    };935    for ([y0..y1]) |y| {936        const row = ((y to i32 - g.top) to u32 * g.width) to u64;937        for ([x0..x1]) |x| {938            var c = g.coverage.get(row + (x to i32 - g.left) to u64) to f32 / 255.0;939            if (clip is ::Some |&m|) {940                c *= m.coverage_at(x, y);941            }942            mask.coverage.push(c);943        }944    }945    return ::Some(move mask);946}947948/* --- Bounds --- */949950// Adds to the bounds what the paint's glyphs cover, at `t`.951fn reach(self p: &var Painter, at: u64, t: &Affine, bounds: &var [f32 : 4]) {952    if (p.depth >= DEEPEST || p.visits >= MOST_VISITS) {953        return;954    }955    p.visits += 1;956    const d = &p.d;957    const format = if (PaintFormat::from(u8_at(&d, at) to u8) is ::Some |f|) f else {958        return;959    };960    p.depth += 1;961    defer p.depth -= 1;962    match (format) {963        ::ColrLayers {964            if (u32_at(&d, p.colr + 18) == 0) {965                return;966            }967            const list = p.colr + u32_at(&d, p.colr + 18) to u64;968            const first = u32_at(&d, at + 2) to u64;969            for ([first..first + u8_at(&d, at + 1) to u64]) |k| {970                if (k < u32_at(&d, list) to u64) {971                    p.reach(list + u32_at(&d, list + 4 + k * 4) to u64, &t, &var bounds);972                }973            }974        }975        ::Glyph {976            add_outline(&var bounds, &p.face.drawn_outline(u16_at(&d, at + 4)), &t);977        }978        ::ColrGlyph {979            const glyph = u16_at(&d, at + 1);980            if (p.clip_box(glyph) is ::Some |box|) {981                add_box(&var bounds, &box, &t);982            } else if (base_paint(&d, p.colr, glyph) is ::Some |paint|) {983                p.reach(paint, &t, &var bounds);984            }985        }986        ::Composite {987            p.reach(at + u24_at(&d, at + 1) to u64, &t, &var bounds);988            p.reach(at + u24_at(&d, at + 5) to u64, &t, &var bounds);989        }990        ::Solid, ::VarSolid, ::LinearGradient, ::VarLinearGradient, ::RadialGradient, ::VarRadialGradient, ::SweepGradient, ::VarSweepGradient {}991        else {992            const local = p.transform(format, at);993            p.reach(at + u24_at(&d, at + 1) to u64, &local.then(&t), &var bounds);994        }995    }996}997998fn add_point(bounds: &var [f32 : 4], t: &Affine, x: f32, y: f32) {999    const px = t.a * x + t.c * y + t.e;1000    const py = t.b * x + t.d * y + t.f;1001    bounds[0] = min(bounds[0], px);1002    bounds[1] = min(bounds[1], py);1003    bounds[2] = max(bounds[2], px);1004    bounds[3] = max(bounds[3], py);1005}10061007fn add_box(bounds: &var [f32 : 4], box: &[f32 : 4], t: &Affine) {1008    add_point(&var bounds, &t, box[0], box[1]);1009    add_point(&var bounds, &t, box[0], box[3]);1010    add_point(&var bounds, &t, box[2], box[1]);1011    add_point(&var bounds, &t, box[2], box[3]);1012}10131014fn add_outline(bounds: &var [f32 : 4], o: &Outline, t: &Affine) {1015    for (o.points.view()) |&point| {1016        add_point(&var bounds, &t, point.x, point.y);1017    }1018}10191020/* --- Compositing --- */10211022// Puts the layer over the surface.1023fn over(layer: &[f32], surface: &var [f32]) {1024    for ([..layer.length() / 4]) |k| {1025        const i = k * 4;1026        const a = layer[i + 3];1027        if (a <= 0.0) {1028            continue;1029        }1030        const keep = 1.0 - a;1031        surface[i] = layer[i] + surface[i] * keep;1032        surface[i + 1] = layer[i + 1] + surface[i + 1] * keep;1033        surface[i + 2] = layer[i + 2] + surface[i + 2] * keep;1034        surface[i + 3] = a + surface[i + 3] * keep;1035    }1036}10371038// Puts the source on the backdrop by the mode, into the backdrop.1039fn composite(source: &[f32], backdrop: &var [f32], mode: CompositeMode) {1040    for ([..source.length() / 4]) |k| {1041        const i = k * 4;1042        const s: [f32 : 4] = [source[i], source[i + 1], source[i + 2], source[i + 3]];1043        const b: [f32 : 4] = [backdrop[i], backdrop[i + 1], backdrop[i + 2], backdrop[i + 3]];1044        if (s[3] <= 0.0 && b[3] <= 0.0) {1045            continue;1046        }1047        const r = blend(&s, &b, mode);1048        for ([..4 to u64]) |c| {1049            backdrop[i + c] = r[c];1050        }1051    }1052}10531054// The source over the backdrop by the mode, both premultiplied.1055fn blend(s: &[f32 : 4], b: &[f32 : 4], mode: CompositeMode) -> [f32 : 4] {1056    const sa = s[3];1057    const ba = b[3];1058    // Porter and Duff's: how much of the source and of the backdrop stay1059    var fs: f32 = 0.0;1060    var fb: f32 = 0.0;1061    match (mode) {1062        ::Clear {1063            return CLEAR;1064        }1065        ::Source {1066            fs = 1.0;1067        }1068        ::Destination {1069            fb = 1.0;1070        }1071        ::SourceOver {1072            fs = 1.0;1073            fb = 1.0 - sa;1074        }1075        ::DestinationOver {1076            fs = 1.0 - ba;1077            fb = 1.0;1078        }1079        ::SourceIn {1080            fs = ba;1081        }1082        ::DestinationIn {1083            fb = sa;1084        }1085        ::SourceOut {1086            fs = 1.0 - ba;1087        }1088        ::DestinationOut {1089            fb = 1.0 - sa;1090        }1091        ::SourceAtop {1092            fs = ba;1093            fb = 1.0 - sa;1094        }1095        ::DestinationAtop {1096            fs = 1.0 - ba;1097            fb = sa;1098        }1099        ::Xor {1100            fs = 1.0 - ba;1101            fb = 1.0 - sa;1102        }1103        ::Plus {1104            return [1105                min(s[0] + b[0], 1.0),1106                min(s[1] + b[1], 1.0),1107                min(s[2] + b[2], 1.0),1108                min(sa + ba, 1.0)1109            ];1110        }1111        else {1112            return blend_colors(&s, &b, mode);1113        }1114    }1115    return [s[0] * fs + b[0] * fb, s[1] * fs + b[1] * fb, s[2] * fs + b[2] * fb, sa * fs + ba * fb];1116}11171118// The W3C's blend modes: the colors mixed where both are, each kept1119// where only it is.1120fn blend_colors(s: &[f32 : 4], b: &[f32 : 4], mode: CompositeMode) -> [f32 : 4] {1121    const sa = s[3];1122    const ba = b[3];1123    const cs: [f32 : 3] = [1124        unpremultiply(s[0], sa),1125        unpremultiply(s[1], sa),1126        unpremultiply(s[2], sa)1127    ];1128    const cb: [f32 : 3] = [1129        unpremultiply(b[0], ba),1130        unpremultiply(b[1], ba),1131        unpremultiply(b[2], ba)1132    ];1133    var mixed: [f32 : 3] = [0.0, 0.0, 0.0];1134    match (mode) {1135        ::Hue {1136            mixed = set_luminosity(set_saturation(cs, saturation(cb)), luminosity(cb));1137        }1138        ::Saturation {1139            mixed = set_luminosity(set_saturation(cb, saturation(cs)), luminosity(cb));1140        }1141        ::Color {1142            mixed = set_luminosity(cs, luminosity(cb));1143        }1144        ::Luminosity {1145            mixed = set_luminosity(cb, luminosity(cs));1146        }1147        else {1148            for ([..3 to u64]) |c| {1149                mixed[c] = separable(cs[c], cb[c], mode);1150            }1151        }1152    }1153    var out: [f32 : 4] = [0.0, 0.0, 0.0, sa + ba - sa * ba];1154    for ([..3 to u64]) |c| {1155        out[c] = (1.0 - ba) * s[c] + (1.0 - sa) * b[c] + sa * ba * clamp(mixed[c], 0.0, 1.0);1156    }1157    return out;1158}11591160fn unpremultiply(c: f32, a: f32) -> f32 => if (a > 0.0) min(c / a, 1.0) else 0.0;11611162// A separable blend mode's color from the source's and the backdrop's.1163fn separable(s: f32, b: f32, mode: CompositeMode) -> f32 => match (mode) {1164    ::Screen s + b - s * b;1165    ::Overlay hard_light(b, s);1166    ::Darken min(s, b);1167    ::Lighten max(s, b);1168    ::ColorDodge if (b <= 0.0) 0.0 else if (s >= 1.0) 1.0 else min(1.0, b / (1.0 - s));1169    ::ColorBurn if (b >= 1.0) 1.0 else if (s <= 0.0) 0.0 else 1.0 - min(1.0, (1.0 - b) / s);1170    ::HardLight hard_light(s, b);1171    ::SoftLight soft_light(s, b);1172    ::Difference abs(s - b);1173    ::Exclusion s + b - 2.0 * s * b;1174    else s * b; // Multiply1175};11761177fn hard_light(s: f32, b: f32) -> f32 {1178    if (s <= 0.5) {1179        return b * 2.0 * s;1180    }1181    const t = 2.0 * s - 1.0;1182    return b + t - b * t;1183}11841185fn soft_light(s: f32, b: f32) -> f32 {1186    if (s <= 0.5) {1187        return b - (1.0 - 2.0 * s) * b * (1.0 - b);1188    }1189    const d = if (b <= 0.25) ((16.0 * b - 12.0) * b + 4.0) * b else sqrt(b);1190    return b + (2.0 * s - 1.0) * (d - b);1191}11921193fn luminosity(c: [f32 : 3]) -> f32 => 0.3 * c[0] + 0.59 * c[1] + 0.11 * c[2];11941195fn saturation(c: [f32 : 3]) -> f32 => max(c[0], max(c[1], c[2])) - min(c[0], min(c[1], c[2]));11961197// The color moved to the luminosity, brought back within 0 to 1.1198fn set_luminosity(c: [f32 : 3], l: f32) -> [f32 : 3] {1199    const d = l - luminosity(c);1200    var r: [f32 : 3] = [c[0] + d, c[1] + d, c[2] + d];1201    const lum = luminosity(r);1202    const low = min(r[0], min(r[1], r[2]));1203    const high = max(r[0], max(r[1], r[2]));1204    for ([..3 to u64]) |k| {1205        if (low < 0.0 && lum - low > 0.0) {1206            r[k] = lum + (r[k] - lum) * lum / (lum - low);1207        }1208        if (high > 1.0 && high - lum > 0.0) {1209            r[k] = lum + (r[k] - lum) * (1.0 - lum) / (high - lum);1210        }1211    }1212    return r;1213}12141215// The color with the saturation, its hue kept.1216fn set_saturation(c: [f32 : 3], s: f32) -> [f32 : 3] {1217    const high = max(c[0], max(c[1], c[2]));1218    const low = min(c[0], min(c[1], c[2]));1219    var r: [f32 : 3] = [0.0, 0.0, 0.0];1220    if (high > low) {1221        for ([..3 to u64]) |k| {1222            r[k] = (c[k] - low) * s / (high - low);1223        }1224    }1225    return r;1226}