moongfx

    Two-dimensional drawing for MoonBit: paths, fill and stroke tessellation, glyph atlas and a software rasteriser.

    2d
    graphics
    canvas
    path
    tessellation
    triangulation
    stroke
    fill
    bezier
    arc
    antialiasing
    rasterizer
    software-renderer
    glyph
    atlas
    text
    gradient
    clipping
    gpu
    renderer
    Download zip
    Version
    0.0.1
    License
    Apache-2.0
    Last updated
    2 hours ago
    Downloads
    1

    moongfx


    #Install

    moon add moonbitstack/moongfx

    One import gives you the drawing contract; the software backend lives in its own package, so a program that only tessellates never pulls in a frame buffer.

    PackageWhat it holds
    moonbitstack/moongfxPaths, tessellation, paints, masks, clipping, the glyph atlas, and the Canvas and Backend contracts
    moonbitstack/moongfx/softThe software backend: an RGBA frame buffer with antialiasing, gradients, images and clips
    moonbitstack/moongfx/gpuThe batch format a GPU backend uploads: vertices, index ranges, draw calls, textures

    #A first drawing

    A canvas needs something to draw into. The software backend is one; it owns the pixels and hands them back as a Surface.

    let surface = @soft.Surface::new(120, 80)
    let canvas = @moongfx.Canvas::new(surface)
    canvas.clear(@moonrgba.Color::rgb(250, 248, 244))
    canvas.fill_circle(
    @moonmath.Vec2::new(60.0, 40.0),
    28.0,
    @moongfx.solid(@moonrgba.Color::rgb(226, 88, 74)),
    )
    let (r, g, b, a) = surface.pixel(60, 40)
    assert_eq(r > 0.8, true)
    assert_eq(a > 0.99, true)

    Coordinates are in pixels with y pointing down, the convention a screen uses, and one unit is one pixel until a transform says otherwise. Geometry is Float — 32-bit — which is what makes a path comparable with what another rasteriser draws from the same numbers.

    #Paths

    A path is a list of straight and curved steps. The builder chains, and the shape helpers cover what a chart or a widget actually draws.

    let badge = @moongfx.Path::builder()
    .rounded_rect(
    { min_x: 8.0, min_y: 8.0, max_x: 108.0, max_y: 64.0 },
    @moongfx.Corners::same(12.0),
    )
    .build()
    let curve = @moongfx.Path::builder()
    .move_to(@moonmath.Vec2::new(0.0, 40.0))
    .quad_to(@moonmath.Vec2::new(30.0, 0.0), @moonmath.Vec2::new(60.0, 40.0))
    .cubic_to(
    @moonmath.Vec2::new(75.0, 60.0),
    @moonmath.Vec2::new(90.0, 20.0),
    @moonmath.Vec2::new(110.0, 40.0),
    )
    .build()
    assert_eq(badge.is_empty(), false)
    assert_eq(curve.bounds().width() > 100.0, true)

    An arc stays an arc rather than becoming a chain of curves, so its bounds are exact and its flattening is exact too. arc_to takes the endpoint form an SVG A command uses and turns it into cubics, because an ellipse under a skew is still an ellipse.

    let quarter = @moongfx.Path::builder()
    .move_to(@moonmath.Vec2::new(10.0, 0.0))
    .arc_to(10.0, 10.0, 0.0, false, true, @moonmath.Vec2::new(0.0, 10.0))
    .build()
    assert_eq(quarter.bounds().max_x <= 10.001, true)

    #Flattening

    Curves are split into straight segments before they reach a tessellator, and how closely they follow the curve is a tolerance you choose. Three presets cover the ordinary cases; they are named, not magic numbers.

    let circle = @moongfx.Path::builder()
    .circle(@moonmath.Vec2::new(0.0, 0.0), 100.0)
    .build()
    let coarse = circle.flatten(flatten=@moongfx.coarse)
    let fine = circle.flatten(flatten=@moongfx.fine)
    assert_eq(fine[0].points().length() > coarse[0].points().length(), true)

    #Filling

    A fill becomes triangles that cover exactly the inside, with no overlap, so a translucent fill inks its area once. The two rules every 2D format has are both here.

    let star = @moongfx.Path::builder()
    .move_to(@moonmath.Vec2::new(60.0, 10.0))
    .line_to(@moonmath.Vec2::new(95.0, 120.0))
    .line_to(@moonmath.Vec2::new(5.0, 50.0))
    .line_to(@moonmath.Vec2::new(115.0, 50.0))
    .line_to(@moonmath.Vec2::new(25.0, 120.0))
    .close()
    .build()
    let filled = @moongfx.fill(star)
    let holed = @moongfx.fill(star, rule=@moongfx.EvenOdd)
    assert_eq(filled.length() > 0, true)
    assert_eq(holed.length() < filled.length(), true)

    A subpath wound the other way punches a hole, which is how a ring or a window is drawn:

    let ring = @moongfx.Path::builder()
    .circle(@moonmath.Vec2::new(50.0, 50.0), 40.0)
    .move_to(@moonmath.Vec2::new(70.0, 50.0))
    .arc(@moonmath.Vec2::new(50.0, 50.0), 20.0, 0.0, -6.283185307179586)
    .close()
    .build()
    let triangles = @moongfx.fill(ring)
    let mut area : Double = 0.0
    for triangle in triangles {
    area = area + triangle.area().to_double().abs()
    }
    assert_eq(area > 3000.0 && area < 4000.0, true)

    #Stroking

    A stroke is wider than a hairline, turns its corners the way you ask, and can be dashed. The outline is built first and then filled, which is what keeps a sharp corner from being inked twice.

    let zigzag = @moongfx.Path::builder()
    .move_to(@moonmath.Vec2::new(0.0, 0.0))
    .line_to(@moonmath.Vec2::new(40.0, -20.0))
    .line_to(@moonmath.Vec2::new(80.0, 20.0))
    .build()
    let rounded = @moongfx.Stroke::new(8.0)
    .with_join(@moongfx.Round)
    .with_cap(@moongfx.Round)
    let outlined = @moongfx.stroke(zigzag, rounded)
    assert_eq(outlined.length() > 0, true)

    KnobWhat it does
    widthThe width of the line, in drawing units
    joinMiter, Bevel or Round, for the outside of a corner
    capButt, Square or Round, for the end of an open path
    miter_limitHow far a miter may reach before it is bevelled instead, as a multiple of the width
    dashLengths alternating on and off, with dash_offset for the phase
    toleranceHow closely the outline follows a curve

    let dashed = @moongfx.Stroke::new(6.0).with_dashes([12.0, 8.0], offset=4.0)
    let dashed_triangles = @moongfx.stroke(zigzag, dashed)
    assert_eq(dashed_triangles.length() > 0, true)

    #Paints

    Solid colours, linear and radial gradients, and images all fill the same way: a paint answers "what colour here" in device space, so a backend only has to shade.

    let ramp = @moongfx.Gradient::new([
    { offset: 0.0, color: @moonrgba.Color::rgb(250, 200, 80) },
    { offset: 0.5, color: @moonrgba.Color::rgb(232, 120, 90) },
    { offset: 1.0, color: @moonrgba.Color::rgb(90, 120, 220) },
    ])
    let sweep = @moongfx.linear(
    @moonmath.Vec2::new(0.0, 0.0),
    @moonmath.Vec2::new(100.0, 0.0),
    ramp,
    )
    let (red, _, _, _) = sweep.sample(@moonmath.Vec2::new(0.0, 0.0))
    assert_eq(red > 0.9, true)

    A gradient spreads its ends three ways: Pad holds the first and last colour, Repeat starts the ramp again, and Reflect runs it backwards on every other turn.

    let tiled = @moongfx.Gradient::new(
    [
    { offset: 0.0, color: @moonrgba.Color::rgb(0, 0, 0) },
    { offset: 1.0, color: @moonrgba.Color::rgb(255, 255, 255) },
    ],
    spread=@moongfx.Repeat,
    )
    let stripes = @moongfx.linear(
    @moonmath.Vec2::new(0.0, 0.0),
    @moonmath.Vec2::new(10.0, 0.0),
    tiled,
    )
    let (shade, _, _, _) = stripes.sample(@moonmath.Vec2::new(2.5, 0.0))
    assert_eq(shade > 0.2 && shade < 0.3, true)

    A radial gradient takes a centre, a radius and an optional focus; the colour at a point is the one where the ray from the focus crosses the circle, which is the highlight a radial gradient is usually used for.

    let glow = @moongfx.radial(
    @moonmath.Vec2::new(50.0, 50.0),
    40.0,
    @moongfx.Gradient::two(@moonrgba.Color::rgb(255, 255, 255), @moonrgba.Color::rgb(20, 30, 60)),
    )
    let (edge, _, _, _) = glow.sample(@moonmath.Vec2::new(90.0, 50.0))
    assert_eq(edge < 0.2, true)

    An image is a paint through a transform, so it can be scaled, turned or skewed like anything else:

    let bytes : Array[Byte] = [
    b'\xFF', b'\x00', b'\x00', b'\xFF',
    ]
    let dot = try {
    @moonimage.Image::of(1, 1, @moonimage.PixelFormat::Rgba8, Bytes::from_array(bytes))
    } catch {
    _ => @moonimage.Image::new(1, 1, @moonimage.PixelFormat::Rgba8)
    }
    let tile = @moongfx.Texture({
    image: dot,
    transform: @moonmath.Affine2::from_scale(@moonmath.Vec2::new(8.0, 8.0)),
    filter: @moongfx.Nearest,
    })
    let (r, _, _, _) = tile.sample(@moonmath.Vec2::new(4.0, 4.0))
    assert_eq(r > 0.9, true)

    #Clipping and transforms

    A canvas keeps a transform stack and a clip stack. Both apply to everything drawn after them, and both are undone by restore.

    let surface = @soft.Surface::new(100, 100)
    let canvas = @moongfx.Canvas::new(surface)
    canvas.save()
    canvas.translate(50.0, 50.0)
    canvas.rotate(0.5)
    canvas.clip(
    @moongfx.Path::builder().circle(@moonmath.Vec2::new(0.0, 0.0), 30.0).build(),
    )
    canvas.fill_rect(
    { min_x: -40.0, min_y: -40.0, max_x: 40.0, max_y: 40.0 },
    @moongfx.solid(@moonrgba.Color::rgb(40, 44, 60)),
    )
    canvas.restore()
    let (_, _, _, inside) = surface.pixel(50, 50)
    let (_, _, _, outside) = surface.pixel(2, 2)
    assert_eq(inside > 0.9, true)
    assert_eq(outside, 0.0)

    A clip is rasterised into an eight-bit coverage mask, and a backend multiplies it into every pixel it writes. That is the same arithmetic on the CPU and on a GPU, so a clipped shape looks the same whichever backend drew it.

    #Text

    Glyphs are rasterised once, packed into a shelf atlas, and then drawn as quads that sample one texture. The atlas grows while it can and is cleared when it cannot, so a long run of text never runs out of room.

    let surface = @soft.Surface::new(200, 40)
    let canvas = @moongfx.Canvas::new(surface)
    let face = @moongfx.DemoFace::new()
    let cache = @moongfx.GlyphCache::new(face)
    let ink = @moongfx.solid(@moonrgba.Color::rgb(20, 20, 30))
    let advance = canvas.fill_text(@moonmath.Vec2::new(8.0, 30.0), "MOON", 24.0, ink, cache)
    assert_eq(advance, 72.0)
    assert_eq(cache.misses() > 0, true)

    DemoFace is a five by seven face built into the library, so that text can be drawn, and compared against a reference, with no font file and no I/O. Any font library can feed the atlas instead: GlyphSource asks for coverage at a size and nothing else, which is exactly what a parser and a rasteriser produce.

    #Backends

    Canvas never touches a pixel. It moves a path into device space, tessellates it, rasterises a clip, and hands a backend triangles and masks. The software backend fills a frame buffer; the gpu package is the format the next one will upload.

    let builder = @gpu.BatchBuilder::new()
    let square = @moongfx.Path::builder()
    .rect({ min_x: 0.0, min_y: 0.0, max_x: 16.0, max_y: 16.0 })
    .build()
    builder.fill(@moongfx.fill(square), @moongfx.solid(@moonrgba.Color::rgb(80, 120, 200)))
    let batch = builder.build()
    assert_eq(batch.triangle_count(), 2)
    assert_eq(batch.draw_count(), 1)
    assert_eq(batch.indices.length(), 6)

    A batch is a vertex buffer, an index buffer, and one draw call per paint. A draw call names the paint, the texture it samples — a glyph atlas, a clip mask, a photograph — and the clip in force. Nothing in it is specific to one graphics API.

    #Reading a surface back

    Surface::to_image unpremultiplies and hands over an image, which moonimage can encode. That is how the reference images were made and compared.

    let surface = @soft.Surface::new(8, 8)
    let canvas = @moongfx.Canvas::new(surface)
    canvas.clear(@moonrgba.Color::rgb(255, 255, 255))
    let image = surface.to_image()
    assert_eq(image.width.to_int(), 8)
    assert_eq(image.format, @moonimage.PixelFormat::Rgba8)

    #Conformance

    Six scenes — fills with holes, joins and dashes, gradients, glyphs, clips, curves — are drawn twice: once by this library's software backend, and once by tiny-skia from the same coordinates. The two are compared pixel by pixel in premultiplied space; the reference images and the program that draws them are in integration/ and scripts/refs/.

    SceneMean differenceWorst pixel
    fill0.000450.15
    stroke0.001050.69
    gradient0.000280.25
    text0.000000.00
    clip0.000140.20
    curves0.000670.29

    Two of those scenes — the stroke and the curves — are also drawn by raqote, a rasteriser that shares no code with tiny-skia. Against it the stroke agrees to a mean of 0.0018 and the curves to 0.0015, which is the same order as the two references differ from each other: the drawing sits between two independent implementations rather than matching one of them.

    The worst pixel is one on an edge, where the two sides sample differently: this rasteriser takes eight samples down each pixel row where the reference integrates exactly, and a round join is a chain of chords at the stroke's flattening tolerance where the reference draws an arc. The text scene agrees to the last bit because the atlas, the blit and the reference all draw the same rectangles.

    #API

    #Types

    TypeWhereWhat it is
    PathmoongfxA sequence of MoveTo, LineTo, QuadTo, CubicTo, Arc and Close steps
    PathBuildermoongfxChains the steps and the shape helpers into a Path
    ArcmoongfxA circular arc: centre, radius, start angle, sweep
    CornersmoongfxFour corner radii, for a rounded rectangle
    BoundsmoongfxAn axis-aligned box, possibly empty
    TrianglemoongfxThree corners; what a backend fills
    FillRulemoongfxNonZero or EvenOdd
    FlattenmoongfxA flattening tolerance, with coarse, standard and fine presets
    StrokemoongfxWidth, join, cap, miter limit, dashes, tolerance
    Join, CapmoongfxThe corner and end styles
    PaintmoongfxSolid, Linear, Radial or Texture
    Gradient, Stop, SpreadmoongfxThe colours of a ramp and what happens past its ends
    LinearGradient, RadialGradientmoongfxGeometry and a ramp
    ImagePattern, FiltermoongfxAn image, where it lands, how it is resampled
    MaskmoongfxEight-bit coverage: a clip, or a rasterised glyph
    QuadmoongfxFour corners in device space
    CanvasmoongfxTransform stack, clip stack, and the drawing calls
    BackendmoongfxWhat a rasteriser implements
    Atlas, Region, ShelfmoongfxShelf packing for coverage
    Glyph, GlyphSource, GlyphCache, GlyphKey, GlyphEntrymoongfxRasterised glyphs and the cache that packs them
    DemoFacemoongfxA built-in five by seven face
    Surfacemoongfx/softThe frame buffer, with pixel and to_image
    Batch, BatchBuilder, DrawCall, Vertex, Texturemoongfx/gpuWhat a GPU backend uploads

    #Functions

    FunctionWhat it does
    fill(path, rule~, flatten~)The path as triangles
    stroke(path, stroke, flatten~)The stroke as triangles
    fill_contours(contours, rule)The same, from polygons you already have
    rasterize(triangles, width, height)The triangles as a coverage mask
    solid, linear, radialThe paints that are not an image
    measure_text(cache, text, size)How wide a run will be
    Canvas::fill, Canvas::stroke_path, Canvas::clipDraw through a canvas
    Canvas::fill_textDraw a run, returning the advance

    #What it is not

    No window, no event loop, no device. This is the drawing half of a UI toolkit: it turns paths, glyphs and paints into pixels or into a batch, and leaves the pixels to whoever owns a window and the batch to whoever owns a GPU.

    #License

    Apache-2.0.

    Affine2

    The plane's point and direction type, re-exported from moonmath so that a caller drawing with this library does not import two vector types.

    Vec2

    The plane's point and direction type, re-exported from moonmath so that a caller drawing with this library does not import two vector types.

    Backend

    pub(open) trait Backend {
    fn width(Self) -> Int
    fn height(Self) -> Int
    fn clear(Self,
    Color
    ) -> Unit
    fn fill_triangles(Self, Array[Triangle], Paint) -> Unit
    fn fill_mask(Self, Mask, Bounds, Quad, Paint) -> Unit
    fn draw_image(Self,
    Image
    , Quad, Float) -> Unit
    fn push_clip(Self, Mask) -> Unit
    fn pop_clip(Self) -> Unit
    fn flush(Self) -> Unit
    }

    The thing a canvas draws into.

    A backend only ever sees geometry in device space — triangles already tessellated, masks already rasterised, paints already moved — so the work a backend has to do is shading and compositing, and swapping one backend for another cannot change what a caller wrote.

    Coverage arrives as a mask because that is the one representation both a software rasteriser and a GPU can produce and consume: the software one computes it, the GPU one samples it from a texture of the clip or the glyph.

    GlyphSource

    pub(open) trait GlyphSource {
    fn glyph(Self, code : Char, size : Float) -> Glyph?
    fn ascent(Self, size : Float) -> Float
    fn descent(Self, size : Float) -> Float
    }

    Where glyph outlines come from.

    The contract is deliberately at the mask: a font library parses the file, applies its hinting or its variable-font instance and hands back coverage at a size, and the atlas only has to pack it. That is also the shape a GPU backend wants, since the atlas ends up as one texture.

    Arc

    pub(all) struct Arc {
    centre :
    Vec2

    radius : Float
    start : Float
    sweep : Float
    } derive(Eq,
    Debug
    )

    A circle arc kept as an arc rather than as a chain of curves, so that flattening can place points exactly where the tolerance asks for them and bounds come out exact.

    start is the radian angle of the first point, measured from +x towards +y; sweep is how far the arc turns, negative running the other way. A sweep of a whole turn or more is legal and closes the arc on itself.

    Arc::end_point

    fn Arc::end_point(self : Arc) ->
    Vec2

    The last point the arc passes through.

    Arc::point_at

    fn Arc::point_at(self : Arc, angle : Float) ->
    Vec2

    The point on the arc at angle radians.

    Arc::start_point

    fn Arc::start_point(self : Arc) ->
    Vec2

    The first point the arc passes through.

    Atlas

    pub struct Atlas {
    width : Int
    height : Int
    max_height : Int
    shelves : Array[Shelf]
    data : Array[Byte]
    occupied : Int
    }

    A coverage atlas packed in shelves.

    Shelves are the cheapest packing that wastes little on glyphs, which are all about the same height in a run of text: a glyph goes on the first shelf tall enough with room left, and a new shelf is started below the last when none has room. Each cell keeps one pixel of padding so that a bilinear sample cannot read a neighbour.

    The atlas grows by doubling its height while it may, and the caller evicts by clearing it and adding back the glyphs worth keeping — a glyph cache knows which those are, an atlas does not.

    Atlas::alloc

    fn Atlas::alloc(self : Atlas, width : Int, height : Int) -> Region?

    A cell width by height with room for the glyph and its padding, or nothing when the atlas has no room left.

    The cell grows the atlas first when it may, so a caller only sees a failure once the atlas is at its largest.

    Atlas::clear

    fn Atlas::clear(self : Atlas) -> Unit

    Throw everything away, ready for a fresh pack.

    Atlas::coverage

    fn Atlas::coverage(self : Atlas, x : Int, y : Int) -> Float

    The coverage at a point of the atlas.

    Atlas::fullness

    fn Atlas::fullness(self : Atlas) -> Float

    The share of the atlas in use, from zero to one.

    Atlas::height

    fn Atlas::height(self : Atlas) -> Int

    The atlas height in pixels.

    Atlas::new

    fn Atlas::new(width : Int, height : Int, max_height? : Int) -> Atlas

    An empty atlas.

    Atlas::occupied

    fn Atlas::occupied(self : Atlas) -> Int

    The area spoken for, in pixels.

    Atlas::width

    fn Atlas::width(self : Atlas) -> Int

    The atlas width in pixels.

    Atlas::write

    fn Atlas::write(self : Atlas, region : Region, mask : Mask) -> Unit

    Copy a mask into the cell, and its origin into the shelf, so the atlas is ready to be sampled.

    Bounds

    pub(all) struct Bounds {
    min_x : Float
    min_y : Float
    max_x : Float
    max_y : Float
    } derive(Eq,
    Debug
    )

    An axis-aligned rectangle in drawing space, kept as its two corners so that a box accumulates points without needing a normalised form.

    An empty box has min_x > max_x; Bounds::nothing builds one. Points are only added while flattening, so the empty box never reaches a rasteriser.

    Bounds::add_point

    fn Bounds::add_point(self : Bounds, p :
    Vec2
    ) -> Bounds

    The box grown to hold p.

    Bounds::centre

    The point in the middle; the zero vector for an empty box.

    Bounds::contains

    fn Bounds::contains(self : Bounds, p :
    Vec2
    ) -> Bool

    Whether p lies in the box, borders included.

    Bounds::expand

    fn Bounds::expand(self : Bounds, amount : Float) -> Bounds

    The box grown by amount on every side; a negative amount shrinks it.

    Bounds::height

    fn Bounds::height(self : Bounds) -> Float

    Bounds::intersect

    fn Bounds::intersect(self : Bounds, other : Bounds) -> Bounds

    The overlap of two boxes, empty when they miss each other.

    Bounds::is_empty

    fn Bounds::is_empty(self : Bounds) -> Bool

    Whether the box still holds nothing.

    Bounds::nothing

    fn Bounds::nothing() -> Bounds

    The box that holds nothing.

    Bounds::union

    fn Bounds::union(self : Bounds, other : Bounds) -> Bounds

    The smallest box holding both.

    Bounds::width

    fn Bounds::width(self : Bounds) -> Float

    Canvas

    pub struct Canvas {
    backend : &Backend
    transform :
    Affine2

    clip_depth : Int
    saved_transforms : Array[
    Affine2
    ]
    saved_depths : Array[Int]
    }

    A drawing surface you hand paths, strokes and paints to, in whatever coordinates suit you.

    The canvas holds the transform and the clip stack and does the geometry — moving a path into device space, tessellating it, rasterising a clip — so a backend receives only triangles and masks. That split is why the same program draws into the software rasteriser and, once one exists, into a GPU pipeline without changing a line.

    Canvas::apply

    fn Canvas::apply(self : Canvas, affine :
    Affine2
    ) -> Unit

    Draw in a space moved by affine.

    Canvas::clear

    fn Canvas::clear(self : Canvas, color :
    Color
    ) -> Unit

    Fill everything with one colour, replacing what was there.

    Canvas::clip

    fn Canvas::clip(self : Canvas, path : Path, rule? : FillRule, flatten? : Flatten) -> Unit

    Narrow everything drawn from now on to the inside of path.

    Canvas::device_transform

    fn Canvas::device_transform(self : Canvas) ->
    Affine2

    The transform from the coordinates the caller draws in to device pixels.

    Canvas::draw_image

    fn Canvas::draw_image(self : Canvas, image :
    Image
    , quad : Quad, opacity? : Float) -> Unit

    Draw an image through a quad given in the coordinates the caller draws in.

    Canvas::draw_image_in

    fn Canvas::draw_image_in(self : Canvas, image :
    Image
    , box : Bounds, opacity? : Float) -> Unit

    Draw an image into a box, stretched to fit it.

    Canvas::fill

    fn Canvas::fill(self : Canvas, path : Path, paint : Paint, rule? : FillRule, flatten? : Flatten) -> Unit

    Fill path under rule.

    Canvas::fill_circle

    fn Canvas::fill_circle(self : Canvas, centre :
    Vec2
    , radius : Float, paint : Paint) -> Unit

    Fill a circle.

    Canvas::fill_rect

    fn Canvas::fill_rect(self : Canvas, box : Bounds, paint : Paint) -> Unit

    Fill a rectangle.

    Canvas::fill_rounded_rect

    fn Canvas::fill_rounded_rect(self : Canvas, box : Bounds, corners : Corners, paint : Paint) -> Unit

    Fill a rectangle with round corners.

    Canvas::fill_text

    fn Canvas::fill_text(self : Canvas, at :
    Vec2
    , text : StringView, size : Float, paint : Paint, cache : GlyphCache) -> Float

    Draw text with its baseline starting at at, and return how far the pen moved.

    The size is in pixels per em of the source, the paint is applied through the glyph's coverage, and the whole run goes through the current transform, so text follows the same space as the paths around it.

    Canvas::flush

    fn Canvas::flush(self : Canvas) -> Unit

    Let the backend do whatever it defers.

    Canvas::height

    fn Canvas::height(self : Canvas) -> Int

    The height of the target in pixels.

    Canvas::new

    fn Canvas::new(backend : &Backend) -> Canvas

    A canvas drawing into backend, with an identity transform and no clip.

    Canvas::restore

    fn Canvas::restore(self : Canvas) -> Unit

    Go back to the transform and clip of the matching save, undoing any clip pushed since.

    Canvas::rotate

    fn Canvas::rotate(self : Canvas, radians : Float) -> Unit

    Turn the axes anticlockwise by radians in a space whose y points up; on a screen whose y points down the shape turns the other way, which is what the arithmetic of the space says.

    Canvas::save

    fn Canvas::save(self : Canvas) -> Unit

    Remember the transform and the depth of the clip stack.

    Canvas::scale

    fn Canvas::scale(self : Canvas, x : Float, y : Float) -> Unit

    Scale both axes.

    Canvas::stroke_circle

    fn Canvas::stroke_circle(self : Canvas, centre :
    Vec2
    , radius : Float, style : Stroke, paint : Paint) -> Unit

    Stroke a circle.

    Canvas::stroke_path

    fn Canvas::stroke_path(self : Canvas, path : Path, style : Stroke, paint : Paint, flatten? : Flatten) -> Unit

    Stroke path with style.

    Canvas::stroke_rounded_rect

    fn Canvas::stroke_rounded_rect(self : Canvas, box : Bounds, corners : Corners, style : Stroke, paint : Paint) -> Unit

    Stroke a rectangle with round corners.

    Canvas::translate

    fn Canvas::translate(self : Canvas, x : Float, y : Float) -> Unit

    Move the origin.

    Canvas::width

    fn Canvas::width(self : Canvas) -> Int

    The width of the target in pixels.

    Cap

    pub(all) enum Cap {
    Butt
    Round
    Square
    } derive(Eq,
    Debug
    )

    How an open end of a stroke finishes.

    Contour

    pub(all) struct Contour {
    points : Array[
    Vec2
    ]
    closed : Bool
    } derive(
    Debug
    )

    One subpath, flattened into the straight segments a tessellator or a rasteriser works on.

    closed is what the writer said, not what filling does: filling closes every contour, stroking leaves an open one open so it gets caps.

    Contour::is_closed

    fn Contour::is_closed(self : Contour) -> Bool

    Whether the subpath was closed.

    Contour::length

    fn Contour::length(self : Contour) -> Int

    The number of points.

    Contour::points

    The points, in drawing order.

    Corners

    pub(all) struct Corners {
    top_left : Float
    top_right : Float
    bottom_right : Float
    bottom_left : Float
    } derive(Eq,
    Debug
    )

    How round each corner of a rounded rectangle is, in the order the corners are named rather than the order they are drawn.

    Corners::none

    fn Corners::none() -> Corners

    Square corners.

    Corners::same

    fn Corners::same(radius : Float) -> Corners

    Every corner with the same radius.

    DemoFace

    pub struct DemoFace {
    rows : Array[(Char, Array[Int])]
    }

    A face whose letters are drawn on a five by seven grid, one cell a pixel at size eight.

    It exists so that text can be drawn, and compared against a reference, with no font file and no I/O: the outlines are rectangles, so every stage between the grid and the frame buffer is the same one a real face goes through. Capitals only — a lowercase letter is drawn as its capital.

    DemoFace::ascent

    fn DemoFace::ascent(self : DemoFace, size : Float) -> Float

    The face's trait methods are callable directly, so a caller can ask a face for a glyph without naming the trait.

    DemoFace::descent

    fn DemoFace::descent(self : DemoFace, size : Float) -> Float

    The face's trait methods are callable directly, so a caller can ask a face for a glyph without naming the trait.

    DemoFace::glyph

    fn DemoFace::glyph(self : DemoFace, code : Char, size : Float) -> Glyph?

    The face's trait methods are callable directly, so a caller can ask a face for a glyph without naming the trait.

    DemoFace::new

    fn DemoFace::new() -> DemoFace

    The face.

    FillRule

    pub(all) enum FillRule {
    NonZero
    EvenOdd
    } derive(Eq,
    Debug
    )

    Which points count as inside a path that crosses itself.

    Filter

    pub(all) enum Filter {
    Nearest
    Bilinear
    } derive(Eq,
    Debug
    )

    How an image is resampled when it is drawn larger or smaller than its pixels, or through a transform.

    Flatten

    pub(all) struct Flatten {
    tolerance : Float
    } derive(Eq,
    Debug
    )

    How far a flattened curve may sit from the curve it replaces, in the units of the coordinates the path holds.

    The presets below are the ones to reach for: a quarter of a pixel looks smooth at normal scale, half a pixel is enough for a preview, and five hundredths is for output that is looked at closely.

    Flatten::new

    fn Flatten::new(tolerance : Float) -> Flatten

    A tolerance of your own, in the same units as the coordinates.

    Glyph

    pub(all) struct Glyph {
    mask : Mask
    left : Int
    top : Int
    advance : Float
    } derive(
    Debug
    )

    One glyph, already rasterised: its coverage and where that coverage sits relative to the pen.

    The mask is in drawing space — y down, the origin at the pen position on the baseline — which is the orientation a rasteriser produces and a backend samples, so nothing has to be flipped later.

    GlyphCache

    pub struct GlyphCache {
    source : &GlyphSource
    atlas : Atlas
    entries : Map[GlyphKey, GlyphEntry]
    clock : Int
    hits : Int
    misses : Int
    resets : Int
    }

    The glyphs a text run needs, rasterised once each and packed into one atlas.

    The cache owns the atlas, so a backend sees a single mask for every glyph in a run and a text pass costs one texture upload rather than one per letter. A glyph's rasterisation is asked of the source when it is missing, and never again while it stays in the atlas.

    GlyphCache::atlas

    fn GlyphCache::atlas(self : GlyphCache) -> Atlas

    The atlas the glyphs live in.

    GlyphCache::entry

    fn GlyphCache::entry(self : GlyphCache, code : Char, size : Float) -> GlyphEntry?

    The glyph for code at size pixels per em, rasterising and packing it the first time.

    GlyphCache::hits

    fn GlyphCache::hits(self : GlyphCache) -> Int

    How many glyph lookups found their glyph already packed.

    GlyphCache::mask

    fn GlyphCache::mask(self : GlyphCache) -> Mask

    The atlas as a mask, which is what a backend samples.

    GlyphCache::misses

    fn GlyphCache::misses(self : GlyphCache) -> Int

    How many had to rasterise.

    GlyphCache::new

    fn GlyphCache::new(source : &GlyphSource, width? : Int, height? : Int, max_height? : Int) -> GlyphCache

    A cache whose atlas starts at width by height and may grow downwards to max_height.

    GlyphCache::resets

    fn GlyphCache::resets(self : GlyphCache) -> Int

    How many times the atlas was thrown away and rebuilt because it had no room.

    GlyphEntry

    pub(all) struct GlyphEntry {
    region : Region
    left : Int
    top : Int
    advance : Float
    used : Int
    } derive(
    Debug
    )

    A glyph once it is in the atlas: where its coverage sits, where it draws, and when it was last asked for.

    GlyphKey

    pub(all) struct GlyphKey {
    code : Int
    size : Int
    } derive(Eq, Hash,
    Debug
    )

    What a glyph is cached under: the code point and the size in quarter pixels, which is finer than any rasteriser distinguishes and coarse enough that one text run shares its glyphs.

    Gradient

    pub(all) struct Gradient {
    stops : Array[Stop]
    spread : Spread
    } derive(
    Debug
    )

    The colours of a gradient, shared by the linear and radial kinds.

    Gradient::at

    The colour of this gradient at t, with the spread applied.

    Gradient::new

    fn Gradient::new(stops : Array[Stop], spread? : Spread) -> Gradient

    A gradient from a list of stops, sorted by offset so that a caller may pass them in any order.

    Gradient::two

    A gradient between two colours, padded at both ends.

    ImagePattern

    pub(all) struct ImagePattern {
    image :
    Image

    transform :
    Affine2

    filter : Filter
    }

    An image mapped through a transform, drawn as a fill.

    Join

    pub(all) enum Join {
    Miter
    Bevel
    Round
    } derive(Eq,
    Debug
    )

    How the outer side of a corner is filled in.

    LinearGradient

    A gradient running from one point to another.

    Mask

    pub(all) struct Mask {
    width : Int
    height : Int
    data : Array[Byte]
    } derive(Eq,
    Debug
    )

    An eight-bit coverage map: how much of each pixel a shape covers, from zero to 255.

    The same type serves as a clip region and as a glyph's rasterised outline, so a backend has one thing to learn.

    Mask::at

    fn Mask::at(self : Mask, x : Int, y : Int) -> Int

    The coverage at a pixel, 0 to 255.

    Mask::coverage

    fn Mask::coverage(self : Mask, x : Int, y : Int) -> Float

    The coverage at a pixel, from zero to one.

    Mask::height

    fn Mask::height(self : Mask) -> Int

    The mask's height in pixels.

    Mask::intersect

    fn Mask::intersect(self : Mask, other : Mask) -> Mask

    The mask that covers only where both masks do, which is how a clip stack narrows.

    Mask::new

    fn Mask::new(width : Int, height : Int) -> Mask

    An empty mask.

    Mask::set

    fn Mask::set(self : Mask, x : Int, y : Int, value : Int) -> Unit

    Set one pixel's coverage, clamped to the byte range.

    Mask::width

    fn Mask::width(self : Mask) -> Int

    The mask's width in pixels.

    Paint

    pub(all) enum Paint {
    Solid(
    Color
    )
    Linear(LinearGradient)
    Radial(RadialGradient)
    Texture(ImagePattern)
    }

    What colour a fill or a stroke puts down.

    A paint carries no geometry of its own except the gradients' own points, which are already in the space being drawn in: the canvas moves them with the path.

    Paint::sample

    fn Paint::sample(self : Paint, p :
    Vec2
    ) -> (Float, Float, Float, Float)

    The paint's colour at p, as straight sRGB channels and alpha, each from zero to one.

    This is the reference the backends implement; a GPU backend evaluates the same expressions in a fragment shader.

    Path

    pub(all) struct Path {
    els : Array[PathEl]
    } derive(
    Debug
    )

    A sequence of straight and curved steps, the unit every operation here takes.

    Immutable: the builder produces one, and transform and the shape helpers return new ones. Filling closes every subpath; stroking honours Close.

    Path::bounds

    fn Path::bounds(self : Path) -> Bounds

    The smallest box holding every point the path draws to.

    Curves contribute their extrema, not just their end points, and arcs their axis-aligned extremes, so the box is tight enough to size a clip or an atlas cell against.

    Path::builder

    fn Path::builder() -> PathBuilder

    A builder for a new path.

    Path::elements

    fn Path::elements(self : Path) -> Array[PathEl]

    The steps, in drawing order.

    Path::flatten

    fn Path::flatten(self : Path, flatten? : Flatten) -> Array[Contour]

    The path as polygons, one per subpath, each within flatten.tolerance of the curve it replaces.

    Straight steps and arcs are exact — an arc is stepped by the angle its radius allows — and quadratics and cubics are split until their control points sit within the tolerance of the chord.

    Path::is_empty

    fn Path::is_empty(self : Path) -> Bool

    Whether the path draws nothing.

    Path::new

    fn Path::new() -> Path

    The path with no steps in it.

    Path::transform

    fn Path::transform(self : Path, affine :
    Affine2
    ) -> Path

    The path with every point run through affine.

    Circular arcs stay arcs under a transform that only rotates, scales evenly and moves; anything else — a skew, unequal scales — turns them into cubics first, because an arc under such a transform is elliptical.

    PathBuilder

    pub struct PathBuilder {
    els : Array[PathEl]
    current :
    Vec2

    start :
    Vec2

    open : Bool
    }

    A path under construction.

    Every step returns the builder, so a path reads as one chain. A step that draws needs somewhere to draw from: when the previous subpath was closed, or nothing has been drawn yet, a line_to starts a new subpath at that point instead of failing.

    PathBuilder::append

    fn PathBuilder::append(self : PathBuilder, path : Path) -> PathBuilder

    Add every step of path, so one path can be built from several.

    PathBuilder::arc

    fn PathBuilder::arc(self : PathBuilder, centre :
    Vec2
    , radius : Float, start_angle : Float, sweep_angle : Float) -> PathBuilder

    A circular arc from start_angle sweeping sweep_angle radians.

    The arc starts where its own geometry says it does; when that is not the current point the builder adds a line first, so a chain of arcs and lines stays connected.

    PathBuilder::arc_to

    fn PathBuilder::arc_to(self : PathBuilder, rx : Float, ry : Float, rotation : Float, large_arc : Bool, sweep_flag : Bool, p :
    Vec2
    ) -> PathBuilder

    An elliptical arc in the endpoint form SVG's A command uses.

    rx and ry are the radii before rotation, rotation turns the ellipse in radians, and large_arc and sweep_flag pick which of the four arcs through the two end points is meant. A zero radius draws a straight line, as the specification says. The arc reaches the end point already given, so the builder does not add one.

    PathBuilder::build

    fn PathBuilder::build(self : PathBuilder) -> Path

    The finished path. The builder must not be used afterwards.

    PathBuilder::circle

    fn PathBuilder::circle(self : PathBuilder, centre :
    Vec2
    , radius : Float) -> PathBuilder

    A full circle, drawn anticlockwise from its rightmost point.

    PathBuilder::close

    fn PathBuilder::close(self : PathBuilder) -> PathBuilder

    Close the current subpath with a straight line back to where it started.

    PathBuilder::cubic_to

    Draw a cubic curve to p with two control points.

    PathBuilder::ellipse

    fn PathBuilder::ellipse(self : PathBuilder, centre :
    Vec2
    , radius_x : Float, radius_y : Float) -> PathBuilder

    An ellipse, as four cubic steps of three quarters of a turn each.

    PathBuilder::line_to

    Draw a straight line to p.

    PathBuilder::move_to

    Start a new subpath at p.

    PathBuilder::polyline

    fn PathBuilder::polyline(self : PathBuilder, points : Array[
    Vec2
    ], closed? : Bool) -> PathBuilder

    A chain of straight lines through points.

    PathBuilder::quad_to

    Draw a quadratic curve to p, bending towards control.

    PathBuilder::rect

    fn PathBuilder::rect(self : PathBuilder, box : Bounds) -> PathBuilder

    A rectangle, drawn clockwise in the order the two corners are given.

    PathBuilder::rounded_rect

    fn PathBuilder::rounded_rect(self : PathBuilder, box : Bounds, corners : Corners) -> PathBuilder

    A rectangle with round corners, as CSS and SVG both define it: a radius is clamped to half the shorter side, so an oversized radius gives a capsule rather than an overlap.

    Quad

    Where a mask or an image lands on the target: four corners in device space, clockwise from the top left, each the corner the name says.

    The quad is what lets a glyph, a rasterised clip or a photograph be drawn through any affine transform without the backend knowing about transforms.

    Quad::bounds

    fn Quad::bounds(self : Quad) -> Bounds

    The box the four corners span.

    Quad::map

    The quad through an affine transform.

    Quad::of_bounds

    fn Quad::of_bounds(box : Bounds) -> Quad

    The quad covering a box, corners in its own order.

    RadialGradient

    A gradient running outwards from a circle: the colour at t is the one at that fraction of the way from focus to the circle of radius about centre, measured along the ray through the point.

    Region

    pub(all) struct Region {
    x : Int
    y : Int
    width : Int
    height : Int
    } derive(Eq,
    Debug
    )

    A rectangle inside a mask or an atlas, in pixels.

    Region::bounds

    fn Region::bounds(self : Region) -> Bounds

    The region as a box, for the backend calls that take one.

    Region::is_empty

    fn Region::is_empty(self : Region) -> Bool

    Whether the region holds any pixels.

    Shelf

    pub struct Shelf {
    y : Int
    height : Int
    cursor : Int
    }

    One horizontal band of an atlas, with the height of its tallest cell and how far along it the next cell goes.

    Spread

    pub(all) enum Spread {
    Pad
    Repeat
    Reflect
    } derive(Eq,
    Debug
    )

    What happens to a gradient parameter that falls outside the stop range.

    Stop

    pub(all) struct Stop {
    offset : Float
    color :
    Color

    } derive(
    Debug
    )

    A colour and where it sits along a gradient.

    Stroke

    pub(all) struct Stroke {
    width : Float
    join : Join
    cap : Cap
    miter_limit : Float
    dash : Array[Float]
    dash_offset : Float
    tolerance : Float
    } derive(
    Debug
    )

    Everything about how a path is stroked: the width, what happens at corners and ends, the miter limit that stops a sharp corner running away, and an optional dash pattern.

    Stroke::new(width) gives the common case — miter joins up to the usual limit of four, butt caps, no dashes — and the with_ methods change one thing at a time.

    Stroke::new

    fn Stroke::new(width : Float) -> Stroke

    A solid stroke of width, miter joins limited to four, butt caps.

    Stroke::with_cap

    fn Stroke::with_cap(self : Stroke, cap : Cap) -> Stroke

    The same stroke with a different end.

    Stroke::with_dashes

    fn Stroke::with_dashes(self : Stroke, pattern : Array[Float], offset? : Float) -> Stroke

    The same stroke, dashed. The pattern alternates on and off lengths starting with on; an odd-length pattern repeats with the first length carried over.

    Stroke::with_join

    fn Stroke::with_join(self : Stroke, join : Join) -> Stroke

    The same stroke with a different corner.

    Stroke::with_miter_limit

    fn Stroke::with_miter_limit(self : Stroke, limit : Float) -> Stroke

    The same stroke with a different miter limit: the ratio of miter length to width above which a corner is bevelled instead.

    Stroke::with_tolerance

    fn Stroke::with_tolerance(self : Stroke, flatten : Flatten) -> Stroke

    The same stroke, flattening its curves to flatten's tolerance.

    Triangle

    Three corners, the shape every backend takes.

    Winding is not part of the contract: a backend fills the triangle either way, so a tessellator may emit both orientations in one path.

    Triangle::area

    fn Triangle::area(self : Triangle) -> Float

    The signed area, positive when the corners run anticlockwise in a space whose y axis points up.

    Triangle::bounds

    fn Triangle::bounds(self : Triangle) -> Bounds

    The box the three corners span.

    coarse

    let coarse : Flatten

    Half a pixel: for previews and thumbnails.

    fill

    fn fill(path : Path, rule? : FillRule, flatten? : Flatten) -> Array[Triangle]

    The path filled under rule, as triangles that cover exactly the inside.

    The flattening is the one filling needs: every subpath counts as closed. The output never overlaps itself — the plane is cut into horizontal slabs at every vertex, and each slab is filled by walking its crossings in order — so a backend can draw the triangles one by one without blending twice.

    fill_contours

    fn fill_contours(contours : Array[Contour], rule : FillRule) -> Array[Triangle]

    The polygons filled under rule. Filling closes every contour, whatever its own flag says.

    fine

    let fine : Flatten

    A twentieth of a pixel: for large output, where a quarter would show.

    linear

    A linear gradient between two points.

    measure_text

    fn measure_text(cache : GlyphCache, text : StringView, size : Float) -> Float

    The width text will take at size, without drawing it.

    mix

    A colour t of the way from a to b, in sRGB with straight alpha.

    radial

    A radial gradient with the focus at the centre, which is the common case: the colour runs outwards evenly.

    rasterize

    fn rasterize(triangles : Array[Triangle], width : Int, height : Int) -> Mask

    The coverage of triangles over a width by height target.

    Triangles that meet along an edge add up to full coverage rather than overshooting, and triangles that overlap saturate, so a tessellation that touches itself — a stroke's joins, say — inks its area once.

    solid

    A paint of one colour.

    standard

    let standard : Flatten

    A quarter of a pixel: the default, and smooth at normal scale.

    stroke

    fn stroke(path : Path, style : Stroke, flatten? : Flatten) -> Array[Triangle]

    The stroke drawn along path, as triangles covering exactly the inked area.

    The outline is built first — both sides of the line, with its joins and caps — and then filled with the non-zero rule, which is what makes a tight corner or a self-crossing path come out right instead of being inked twice.