Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-svg

Source of release 0.9.2

0.9.2 / src / svg / rgba.lucb

#==============================================================================================
#
#   svg/rgba - Compositing painted elements into linear RGBA
#
#   DESCRIPTION:
#       Draws a Drawing in color. Element by element in document order, all of its fill
#       outlines accumulate together (so holes cut by its fill rule stay open), then
#       composite source-over in the fill's paint; its stroke follows the same way. The
#       anti-aliasing is the coverage rasteriser's, unquantised. Flat paints are decoded
#       from sRGB to linear light before they blend, and gradients look up a 256-entry
#       linear ramp per pixel centre. Only the rows and columns an element can touch are
#       resolved, so large drawings with many small shapes stay cheap.
#
#==============================================================================================

## The accumulator cells an element can have touched: rows `row0..<row1` and cells
## `column0..<column1` of each (the last cell of a row is the spare one past the edge).
struct Span:
    var row0: usize = 0
    var row1: usize = 0
    var column0: usize = 0
    var column1: usize = 0

## The span of contours `first..<last` placed by `fit`, grown by `grow` pixels (a stroke's
## half width) plus a pixel of margin, clamped to a `width` by `height` bitmap.
func element_span(drawing: const Drawing*, first: usize, last: usize, fit: Placement, grow: f64, width: usize, height: usize) -> Span:
    var low_x = math.infinity
    var low_y = math.infinity
    var high_x = -math.infinity
    var high_y = -math.infinity
    for contour_index in first..<last:
        let contour = drawing.contours[contour_index]
        for index in contour.start..<contour.start + contour.length:
            let p = drawing.points[index]
            low_x = math.min(low_x, fit.offset_x + p.x * fit.scale)
            low_y = math.min(low_y, fit.offset_y + p.y * fit.scale)
            high_x = math.max(high_x, fit.offset_x + p.x * fit.scale)
            high_y = math.max(high_y, fit.offset_y + p.y * fit.scale)
    let margin = grow + 1.0
    let rows = (f64)height
    let cells = (f64)(width + 1)
    let row0 = (usize)math.clamp(math.floor(low_y - margin), 0.0, rows)
    let column0 = (usize)math.clamp(math.floor(low_x - margin), 0.0, cells)
    let row1 = (usize)math.clamp(math.ceil(high_y + margin), 0.0, rows)
    let column1 = (usize)math.clamp(math.ceil(high_x + margin) + 1.0, 0.0, cells)
    return Span(row0 = row0, row1 = row1 if row1 > row0 else row0, column0 = column0, column1 = column1 if column1 > column0 else column0)

## How an element's paint colors its pixels: flat `color` (linear), or when `gradient`
## is set, its ramp looked up through `space` (pixel centres into gradient space); either
## way at `alpha` times the coverage.
struct Shade:
    var color: Color = Color()
    var alpha: f64 = 1.0
    var gradient: bool = false
    var geometry: Gradient = Gradient()
    var space: Matrix = Matrix()

## The shade `source` paints with at `alpha`, filling `ramp` for a gradient. `current` is
## already linear.
func shade_of(drawing: const Drawing*, source: Paint, alpha: f64, current: Color, fit: Placement, ramp: f32[]) -> Shade:
    if source.gradient == 0:
        return Shade(color = current if source.current else to_linear(source.color), alpha = alpha)
    let geometry = drawing.gradients[source.gradient - 1]
    fill_ramp(drawing, &geometry, ramp)
    # Pixels to viewBox coordinates, then on into the gradient's space.
    let unplace = Matrix(a = 1.0 / fit.scale, d = 1.0 / fit.scale, e = -fit.offset_x / fit.scale, f = -fit.offset_y / fit.scale)
    return Shade(alpha = alpha, gradient = true, geometry = geometry, space = multiply(source.space, unplace))

## Resolve the accumulator over `span` as coverage, blend `shade` over the straight-alpha
## `pixels` by it, and clear what was read.
func composite(acc: f32[], width: usize, span: Span, shade: const Shade*, evenodd: bool, ramp: const f32[], pixels: f32[]):
    let stride = width + 1
    for row in span.row0..<span.row1:
        var sum: f32 = 0.0
        for column in span.column0..<span.column1:
            let cell = row * stride + column
            sum += acc[cell]
            acc[cell] = 0.0
            var cover = covered(sum, evenodd) * shade.alpha
            # The running sum leaves float residue (about 1e-7) past a shape's right
            # edge; under half a 16-bit level it is no coverage, not a faint pixel.
            if column >= width or cover < 1.0 / 131072.0:
                continue
            var color = shade.color
            if shade.gradient:
                let at = apply(shade.space, (f64)column + 0.5, (f64)row + 0.5)
                let entry = (usize)(gradient_offset(&shade.geometry, at) * (f64)(ramp_size - 1) + 0.5) * 4
                color = Color(r = (f64)ramp[entry], g = (f64)ramp[entry + 1], b = (f64)ramp[entry + 2])
                cover *= (f64)ramp[entry + 3]
                if cover <= 0.0:
                    continue
            let slot = (row * width + column) * 4
            let below = (f64)pixels[slot + 3] * (1.0 - cover)
            let total = cover + below
            pixels[slot] = (f32)((color.r * cover + (f64)pixels[slot] * below) / total)
            pixels[slot + 1] = (f32)((color.g * cover + (f64)pixels[slot + 1] * below) / total)
            pixels[slot + 2] = (f32)((color.b * cover + (f64)pixels[slot + 2] * below) / total)
            pixels[slot + 3] = (f32)total

## Rasterise `drawing` in color into `pixels`, `width * height * 4` floats, top-down
## RGBA in straight (not premultiplied) alpha. Color channels are LINEAR light, not
## encoded sRGB: every paint, including `current` (the sRGB color `currentColor` means,
## as parse_color returns it), is decoded before blending, and gradients blend their
## stops in sRGB first. The drawing is placed as `rasterize` places it, scaled uniformly
## from the viewBox and centred. Each element's fill, then its stroke, composites
## source-over in document order onto a transparent start, each as one shape by its
## fill rule (strokes nonzero), anti-aliased by exact area coverage. Text is not drawn; see
## rasterize_rgba_elements.
pub func rasterize_rgba(drawing: const Drawing*, width: u32, height: u32, pixels: f32[], current: Color) -> !:
    if pixels.length != (usize)width * (usize)height * 4:
        error(invalid, "the pixel buffer must hold width * height * 4 floats")
    for index in 0..<pixels.length:
        pixels[index] = 0.0
    try rasterize_rgba_elements(drawing, width, height, pixels, current, 0, drawing.element)

## As rasterize_rgba, but only shape elements `first..<last` (as contour_element counts
## them), composited over what `pixels` already holds. A caller that sets text draws
## the elements before each text run's `order`, then the run, and so on, then the rest.
pub func rasterize_rgba_elements(drawing: const Drawing*, width: u32, height: u32, pixels: f32[], current: Color,
                                 first: usize, last: usize) -> !:
    try rasterize_placed(drawing, width, height, placement(drawing, width, height), pixels, current, first, last)

## A window of the drawing as it lands in a `full_width` by `full_height` bitmap:
## the `width` by `height` pixels from (`left`, `top`) of it, into `pixels` as
## rasterize_rgba fills a whole bitmap. Each pixel covers exactly what the whole
## bitmap's pixel there does, so a large bitmap can be drawn window by window, from
## one parsed drawing, and a full bitmap need not exist (its sides may pass 4096).
pub func rasterize_rgba_window(drawing: const Drawing*, full_width: u32, full_height: u32, left: u32, top: u32,
                               width: u32, height: u32, pixels: f32[], current: Color) -> !:
    if pixels.length != (usize)width * (usize)height * 4:
        error(invalid, "the pixel buffer must hold width * height * 4 floats")
    for index in 0..<pixels.length:
        pixels[index] = 0.0
    let whole = placement(drawing, full_width, full_height)
    let fit = Placement(scale = whole.scale, offset_x = whole.offset_x - (f64)left, offset_y = whole.offset_y - (f64)top)
    try rasterize_placed(drawing, width, height, fit, pixels, current, 0, drawing.element)

## Shape elements `first..<last` placed by `fit` into a `width` by `height` bitmap,
## composited over what `pixels` holds.
func rasterize_placed(drawing: const Drawing*, width: u32, height: u32, fit: Placement, pixels: f32[], current: Color,
                      first: usize, last: usize) -> !:
    let acc = try accumulator(width, height)
    defer free(acc) in memory.heap
    if pixels.length != (usize)width * (usize)height * 4:
        error(invalid, "the pixel buffer must hold width * height * 4 floats")
    let ramp = try new f32[ramp_size * 4] --- in memory.heap
    defer free(ramp) in memory.heap
    let w = (usize)width
    let h = (usize)height
    let current_linear = to_linear(current)
    var start: usize = 0
    while start < drawing.contour_used:
        # The element's contours run from `start` to `end`, sharing one style.
        let head = drawing.contours[start]
        var end = start + 1
        while end < drawing.contour_used and drawing.contours[end].element == head.element:
            end += 1
        if head.element >= first and head.element < last:
            try composite_element(drawing, acc, w, h, start, end, fit, current_linear, ramp, pixels)
        start = end

## Composite the element of contours `first..<last`: its fill, then its stroke.
func composite_element(drawing: const Drawing*, acc: f32[], w: usize, h: usize, first: usize, last: usize, fit: Placement,
                       current_linear: Color, ramp: f32[], pixels: f32[]) -> !:
    let head = drawing.contours[first]
    if head.fill.painted:
        for index in first..<last:
            if drawing.contours[index].length >= 3:
                trace_fill(acc, w, h, drawing, drawing.contours[index], fit)
        let shade = shade_of(drawing, head.fill, head.fill_opacity, current_linear, fit, ramp)
        composite(acc, w, element_span(drawing, first, last, fit, 0.0, w, h), &shade, head.evenodd, ramp, pixels)
    if head.stroke.painted:
        for index in first..<last:
            if drawing.contours[index].length >= 1:
                try trace_stroke(acc, w, h, drawing, drawing.contours[index], fit)
        # Miters reach out to the limit times the half width, square caps √2 times.
        let reach = math.max(1.5, head.pen.miter_limit if head.pen.join == Join.miter else 1.0)
        let span = element_span(drawing, first, last, fit, stroke_half(head, fit) * reach, w, h)
        let shade = shade_of(drawing, head.stroke, head.stroke_opacity, current_linear, fit, ramp)
        composite(acc, w, span, &shade, false, ramp, pixels)

## The transform from viewBox coordinates to the pixels of a `width` by `height`
## bitmap, as both rasterisers place the drawing.
pub func pixel_transform(drawing: const Drawing*, width: u32, height: u32) -> Matrix:
    let fit = placement(drawing, width, height)
    return Matrix(a = fit.scale, d = fit.scale, e = fit.offset_x, f = fit.offset_y)