Skip to content
defnotmidPublic

About

2D vector canvas for Odin: paths, text, gradients and SVG filters, drawn by exact per-pixel curve coverage on the CPU or the GPU.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Latest commit

 

History

170 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

ovg

ovg's mascot: a pixel-art chameleon on a branch, its tail a spiral

Odin vector graphics. A 2D vector canvas for Odin that started as a port of femtovg (the nanovg lineage) and grew well beyond it.

From femtovg: the canvas API (paths, strokes, gradients, image paints, scissoring, compositing, render-to-image), recording commands for a backend. Fills and strokes no longer tessellate: every path is drawn by exact per-pixel coverage of its curves (see Shapes below).

Added in ovg:

  • Dashes: dash arrays, offsets and pathLength.
  • Path morphs: path_morph_prepare / path_morph_eval blend any two paths (contours paired, resampled by arc length, holes kept; unpaired contours grow from or shrink to a point), with text (text_layout_path) and SVG geometry (svg.element_path) as paths to morph.
  • Path booleans: union, difference, intersection, xor and simplify of filled paths, keeping their curves (see Path booleans below).
  • Layers: group opacity, clip paths, alpha and luminance masks, 16 blend modes and patterns, each sized to its content.
  • Bloom: a filter primitive, .Bloom: the light above a threshold, a Gaussian over it, a share of that added, in linear light, with no pass at the layer's size but the add (o3d's scene.bloom takes the same numbers and gives the same glow).
  • SVG filters: every SVG 1.1 primitive (blur, drop shadow, offset, flood, composite, merge, blend, colour matrix, component transfer, morphology, turbulence, diffuse / specular lighting, tile, displacement map, convolve matrix, image), with filter regions, subregions and linearRGB.
  • SVG import (ovg/svg): svg.parse / svg.draw with CSS styling, <use>, gradients, patterns, masks, filters and text, plus per-element overrides for animation (88.5% of the resvg test suite).
  • Lottie import (ovg/lottie): lottie.parse / lottie.draw for After Effects (Bodymovin) animations: precomps, mattes, masks, trim paths, eased keyframes, layer effects (blur, drop shadow, fill, tint, tritone) and text layers with text animators.
  • Text: OpenType shaping with oglyph (Odin, MIT, written alongside ovg and checked against HarfBuzz) (ligatures, kerning, mark positioning, Arabic, Indic and the other complex scripts, bidi), per-glyph font fallback, multi-style layout and baselines, drawn as vector outlines; colour emoji from COLR v0 / v1 fonts, also vectors (Noto Color Emoji bundled as an optional fallback).
  • Custom shader programs: register compiled shaders (oksl's SkSL or Shadertoy GLSL) and run them as layers, with image, video or group children.
  • Recording and playback: record a frame's commands on one thread and play them on the GPU thread, for parallel frame building.
  • Motion blur input: each frame's velocity and nearness per pixel, from how each draw moves (set_motion), through groups and layers, for a motion blur pass such as o3d's (see Motion blur below).
  • Editor overlays: a shape kept in document units drawn at many places with one paint (fill_shapes), its outline as a hairline a constant number of pixels wide at any zoom (hairline_shape), and anchors and handles as markers, filled and outlined in one call (draw_markers), each pixel's coverage in closed form (see Shapes below).

Two backends: a software rasterizer and an SDL_GPU backend (SDL3's GPU API: Vulkan on Linux and Windows, Metal on macOS). Fonts are read and text shaped by oglyph, shapes' coverage and path booleans computed by ocurves, images decoded and PNGs written by oicut, the shaders compiled by oksl (all Odin, MIT), read through the deps collection: clone them next to ovg and build with -collection:deps=.. (the directory holding all five). ovg builds with Odin dev-2026-11a, as CI does. The other dependencies are Odin's own vendor packages:

package needs
ovg (core + software backend) deps:oglyph/font, deps:oglyph/shape, deps:oglyph/collection (oglyph v0.1.0), deps:ocurves (ocurves v0.1.0), deps:oicut/image, deps:oicut/common (oicut v0.1.0), deps:oksl (oksl v0.1.2)
ovg/svg (SVG import), ovg/lottie (Lottie import) ovg; packages on top of core, so a program that reads neither imports only ovg
ovg/sdlgpu (GPU backend) ovg, vendor:sdl3; SDL 3 at runtime (the system library on Linux/macOS, the bundled DLL on Windows)

Use

git clone https://github.com/defnotmid/ovg
git clone -b v0.1.0 https://github.com/defnotmid/oglyph
git clone -b v0.1.0 https://github.com/defnotmid/ocurves
git clone -b v0.1.0 https://github.com/defnotmid/oicut
git clone -b v0.1.2 https://github.com/defnotmid/oksl
import vg "deps:ovg"   // -collection:deps=.. (the directory holding ovg, oglyph, ocurves, oicut and oksl)
import image "deps:oicut/image"

sw: vg.Software_Backend
vg.software_backend_init(&sw)
c: vg.Canvas
vg.canvas_init(&c, vg.software_backend(&sw))

vg.set_size(&c, 640, 360)
vg.clear_rect(&c, 0, 0, 640, 360, vg.WHITE)

p: vg.Path
vg.path_rounded_rect(&p, 40, 40, 200, 120, 16)
vg.fill_path(&c, &p, vg.paint_linear_gradient(40, 40, 240, 160, vg.rgb(255, 80, 0), vg.rgb(0, 60, 255)))
stroke := vg.paint_color(vg.BLACK)
stroke.stroke.line_width = 3
vg.stroke_path(&c, &p, stroke)

vg.flush(&c)
image.write_png("out.png", sw.pixels, int(sw.width), int(sw.height))

SDL_GPU

import vgsdl "ovg/sdlgpu"

gpu: vgsdl.SDL_Backend
vgsdl.init(&gpu)                // own headless device (or pass the host's)
c: vg.Canvas
vg.canvas_init(&c, vgsdl.backend(&gpu))
// ... draw ...
vg.flush(&c)                    // renders into the backend's offscreen texture
shot, _ := vg.screenshot(&c)    // RGBA8, top-down
  • init(&gpu, device) borrows the host's ^sdl.GPUDevice (e.g. the one its window renders with). With no device it initializes SDL video, falling back to the offscreen video driver when there is no display, and creates a headless device accepting SPIR-V or MSL. SDL_GPU_DRIVER picks SDL's driver.
  • vg.flush(&c, vgsdl.output(&o)) renders the screen into a caller texture (vgsdl.Output: texture, format, size). With o.command_buffer set, the frame is recorded into that command buffer and the caller submits it; that is required for swapchain textures, which belong to the command buffer that acquired them. Otherwise the backend submits and waits.
  • vgsdl.image_texture(&c, id) is the ^sdl.GPUTexture behind a canvas image, and vgsdl.offscreen_texture(&gpu) is the default screen texture, for compositing in host UI code. vgsdl.read_texture copies a texture back. vgsdl.image_borrow_texture(&c, id, texture, w, h, format) is the other way round: an image that draws a texture the caller keeps (another renderer's output), never released with the image; given its id again it points the image at a new texture without allocating, frame after frame.
  • Each flush records one command buffer (its streams uploaded in a copy pass: vertices, paints, shape instances and shape words; then a render pass per target run) and waits on a fence, unless gpu.frames_in_flight (at most 3) lets that many frames keep running while the next is recorded; reading a frame back waits for its own copy. Image uploads use their own command buffers, submitted before the frame's. An update_image of the same size as the image's last goes through transfer buffers the image keeps, as many as such updates had in flight at once (3 to 4 at 2 frames in flight), until it is deleted or updated at another size; an image filled once keeps none. Filter intermediates and the buffers a frame needs are created before its command buffer is recorded: SDL_GPU submits a command buffer when it creates a texture, a submit may defragment memory (moving textures), and a texture the frame had already bound then lost the draws made into it (rare, history-dependent pixel errors on RADV).
  • A device shared between threads needs a Retired table: vgsdl.init(&gpu, device, retired = &table). On SDL's Vulkan driver a texture or buffer released on one thread while another presents can be written after it is freed (a presenting submit may defragment memory, or on a device with no claimed window, any submit). With a table the backend's releases wait in it, from any thread, until retired_release gives them back, called between presents on the thread that presents, even when it skips a present, since nothing else frees them. The caller's own objects go in with retire_texture and retire_buffer. Transfer buffers stay out: SDL makes them dedicated allocations, which a defrag never moves, so queuing them would only hold memory. Without a table everything is released at once, as a device used from one thread can be.
  • Redundant state is skipped within a render pass: uniforms, samplers and scissor are set only when they change.
  • Shape draws aren't scissored by draw: each instance carries its scissor's pixels, and the vertex shader marks those whose quad reaches out of them, whose pixels then test them, so shapes under different scissors draw in one call.
  • Shapes a caller keeps (Shape, found by its id) upload once into the backend's shape store and are drawn from it every frame; a frame's new words (new shapes, paths filled this frame, group grids) go up in one copy. Nothing is freed shape by shape: when a frame's shapes don't fit, the store starts over in a buffer four times their size. gpu.stats counts a frame's shape instances, the words it uploaded and whether the store started over (shape_restarts).
  • Pipelines are cached by blend factors, target format, fragment shader (quads, shapes, box shapes, groups, hairlines, groups of markers, and motion blur's composite and resolve) and second target (a velocity twin's, or the resolve's nearness). There is no depth or stencil buffer. Blur intermediates are kept per image shape and released after 30 frames unused.
  • Gray8 images are stored as R8, Gray16 as R16, RGBA16F as R16G16B16A16_FLOAT. Generate_Mipmaps is ignored.
  • Tested on Linux (Vulkan, RADV) and macOS (Metal, Apple M4: tests and tools/sdlgpu_parity pass). The Windows path compiles (odin check -target:windows_amd64) but is untested.
  • New images are cleared to transparent: SDL_GPU leaves texture contents undefined (garbage on Metal), and a partly updated image samples texels it never wrote.
  • On Windows the backend runs on Vulkan: oksl writes SPIR-V and MSL, not D3D12's DXIL.

Shaders

The shaders are GLSL ES 3.0 in shaders/, compiled by oksl when the backend starts (init, about 4 ms for all of them) to the device's SPIR-V (Vulkan) or MSL (Metal): nothing is compiled ahead of time and no shader toolchain is needed. shaders.odin lists the units: quad.vert and shape.vert (instances pulled from a storage buffer by gl_VertexID, six vertices an instance), and the fragment units main.frag (clears, image copies), filter.frag, shape.frag (with SHAPE_BOX for instances without rotation or skew), group.frag, markers.frag and velocity.frag, each compiled after common.glsl (the paints and the paint's colour) and, for shapes, ocurves' curves.glsl (its curves.GLSL, from the same package as the words it reads) and shapes.glsl. Each fragment unit but the filters' and the motion passes' has a MOTION variant writing a second target (a velocity twin). SDL_GPU has no specialization constants, so the shader type and glyph mode come from the paint row and are branched on at runtime, as in femtovg. A unit's samplers and storage buffers are checked at compile against the order the renderer binds them (shader_bindings_ok), and test_shaders_compile compiles every unit for SPIR-V, MSL and oksl's CPU program, linked with its vertex shader, without a GPU.

Recording on other threads

A recording canvas (canvas_init_recording) draws like any canvas but never touches a backend, so frames can be built on worker threads and drawn on the thread that owns the GPU:

rc: vg.Canvas
vg.canvas_init_recording(&rc)       // on any thread
rec: vg.Recorded_Frame
// ... draw on rc ...
vg.canvas_take(&rc, &rec)           // like flush: the frame moves into rec

p: vg.Player                        // on the backend's thread, one per recording canvas
vg.player_init(&p, vgsdl.backend(&gpu), &shared)
vg.player_apply(&p, &rec)           // image allocations, uploads, frees, programs
vg.player_render(&p, &rec)          // what flush would have rendered

Image ids are issued by the recording canvas; its allocations, uploads (pixels copied into the frame) and frees become Image_Ops that the player applies to a mirror of its images with the same ids, then renders. The arrays swap between canvas and frame, so both keep their capacity. Frames of one recording canvas are played in order. create_image_shared(c, src, key, stable) makes an image every player of a Shared_Images table shares (one texture for N recording canvases); a stable source is borrowed instead of copied. Programs registered on a recording canvas are created by the player (their blobs must outlive the frames using them). The pixels are the same as drawing on the player's backend directly (player_test.odin).

Motion blur

With canvas_motion_blur(&c, true) (switched between frames) a frame also records how its draws move, and the backend gives each screen pixel's velocity (pixels, the middle of the shutter minus its opening) and nearness (larger is nearer), as o3d's motion blur pass takes them:

vg.canvas_motion_blur(&c, true)
// for each node, still ones too:
vg.set_motion(&c, vg.transform_multiply(vg.transform_inverse(mid), open))
// ... draw it ...
vg.flush(&c)
v, n := vg.software_backend_velocity(&sw)       // [][2]f32, []f32
vt, nt := vgsdl.velocity_textures(&gpu)          // R16G16_FLOAT, R16_FLOAT
  • set_motion(c, opened) maps a point's place at the middle of the shutter (drawing coordinates) to its place at the opening, for what is drawn until a restore. Each call starts a surface nearer than everything drawn before it, and so does drawing on after a restore brings an earlier one back.
  • A draw's motion goes over the pixel's by the draw's coverage (its final alpha), whatever its blend mode, over still, farthest ground: the outputs are premultiplied by coverage, as the blend leaves them.
  • Groups and layers composite their content's motion as they composite its pixels: faded, clipped and masked. Filters don't apply to motion: where one spreads a layer (a blur's halo), the motion stays where its content drew. Programs and external work write no motion.
  • The screen and each layer's content keep a velocity twin, (a * velocity, a * nearness, a) per pixel: [4]f32 in the software backend, R16G16B16A16_FLOAT on the GPU, whose shape shaders write it as a second target. tools/sdlgpu_parity draws every scene again with motion blur: its pixels don't change, and the velocity and nearness match the software backend's (motion_test.odin checks them against each draw's motion).
  • Cost: off, nothing more is recorded, allocated or drawn (the software rasterizer's loops are specialized on whether a draw moves); on, the twins' memory and a twin write per covered pixel.

Filters and paint extras

SVG filter primitives and paint options, implemented once in shaders/filter.frag, which both backends run: SDL_GPU on the GPU, the software backend on oksl's CPU program, each pass's paint from the same filter_plan.

filter_image(c, target, filter, source) records a filter that runs at flush, in order with drawing. Inputs and target are images of one size; the target may be one of the inputs. Filters read premultiplied color (Gray8/Gray16 as a GPU sampler returns them) and write premultiplied color.

Image_Filter SVG semantics
Gaussian_Blur{sigma} feGaussianBlur one sigma (pixels), transparent beyond the image
Blur_XY{sigma_x, sigma_y, edge} stdDeviation="x y" per-axis sigma (<= 0 leaves the axis), edge .Transparent or .Clamp
Color_Matrix{m} feColorMatrix 4x5 rows on straight color, offsets in 0..1, clamped; helpers color_matrix_saturate, color_matrix_hue_rotate, color_matrix_luminance_to_alpha, COLOR_MATRIX_IDENTITY
Color_Space_Convert{to_linear} color-interpolation-filters sRGB <-> linearRGB on straight color
Blend{mode, backdrop} feBlend, mix-blend-mode the 16 W3C blend modes, source (in) onto backdrop (in2), composited source-over; blend_pixel(mode, s, b) is the same on one premultiplied pixel on the CPU (hit-testing through a blended layer), tested equal to the filter
Composite{op, k, backdrop} feComposite over, in, out, atop, xor, lighter, arithmetic k1..k4 (clamped, color <= alpha)
Component_Transfer{lut} feComponentTransfer straight channels through a 256 x 1 RGBA8 table (component_transfer_lut from Transfer_Functions: identity, table, discrete, linear, gamma, truncated to 8 bits as resvg)
Morphology{radius, dilate, valid} feMorphology per-channel min / max over a box (at most MORPHOLOGY_MAX_RADIUS), two separable passes; a fractional radius blends in the next ring by its fraction, so animated radii move smoothly
Lighting{...} feDiffuseLighting, feSpecularLighting the spec's Sobel normals (edge kernels at valid's border) under a distant, point or spot light, rounded as resvg
Tile{rect} feTile the source's rect repeated
Displacement_Map{displacement, scale, channels, valid} feDisplacementMap nearest pixel at p + scale (map - 0.5) (map premultiplied, as resvg)
Convolve_Matrix{kernel, order, target, divisor, bias, edge, preserve_alpha, valid} feConvolveMatrix up to CONVOLVE_MAX_KERNEL (36) values, edge duplicate / wrap / none
Turbulence{params, offset, scale, region} feTurbulence the spec's reference noise over the whole target, from the seed's lattice image (turbulence_lattice_pixels), in f32 on every backend; region is the stitch tile

Blur kernels span 3 sigma each side and are exact up to BLUR_MAX_EXACT_SIGMA (8); beyond that both backends keep BLUR_MAX_TAPS (24) taps each side, a truncated, renormalized kernel, so blur a downscaled copy for wider blurs. feOffset and feFlood need no filter: draw the source image paint offset into a cleared target, or clear_rect / fill a rectangle with the flood color. The neighbourhood filters take valid (x0, y0, x1, y1 pixels), the edge of the image as the spec sees it (the filter region, as resvg crops to it). GPU and software agree within 2/255 except where a filter amplifies a one-step input difference: lighting at dark antialiased edges after the linearRGB -> sRGB conversion, and sharpening kernels.

SVG filter effects on layers (filter.odin, Layer_Params.filter): a Filter is a list of primitives (every SVG 1.1 one; feImage shows an image from Filter.images) reading the source graphic, its alpha or earlier results, computed in linear RGB unless srgb; component transfer tables and convolution kernels live in Filter.values. A linear RGB filter's images are RGBA16F (8-bit linear light keeps 9 of sRGB's first 49 levels), each released after the last primitive reading it; an sRGB filter's are the layer's (RGBA8, or RGBA16F in an RGBA16F offscreen image). feTurbulence is the spec's reference Perlin noise: a filter pass in f32 on every backend, reading the seed's lattice (computed once on the CPU, kept by Layer_Stack, its whole numbers in RGBA16F); it rounds to 8 bits as resvg does, and stays unrounded in an RGBA16F offscreen image. The transfer tables are computed on the CPU and uploaded; the other primitives are filter passes. Filter.region (Filter_Region{units, x, y, w, h, bbox}, .User_Space_On_Use or .Object_Bounding_Box with the caller's bounding box; FILTER_REGION_DEFAULT is SVG's -10% / 120%) cuts the source graphic before filtering and every result after, on the whole device pixels of the region's bounding box (as resvg), and bounds the layer's window; the zero value is no region (the whole canvas). A primitive's subregion cuts its own result.

Path booleans

path_boolean(out, {a, rule}, {b, rule}, op, &scratch) appends a op b (Union, Difference: a minus b, Intersection, Xor) to out; path_simplify resolves one path's overlaps and self-crossings under its fill rule, path_boolean_many folds any number of operands, and path_divide splits the operands into every region they make (Illustrator's divide: one Path, each face a Range of its contours, the shapes nested in a face as its holes, and which operands each face lies inside in Bool_Scratch.core.faces_in). The result keeps the operands' own curves: each output segment is a range of an input line or cubic (a whole one copied bit for bit), cut where the operands meet, and Bool_Scratch records where each came from (the segment of its operand path and the t range on it) so an editor keeps its anchors. Output contours are Solid-wound with holes reversed and never cross, so either fill rule fills the result alike; each is one boundary, appended region by region (the parts of the result joined across curves, each its outline then its holes; Bool_Scratch.core.faces gives each region's contours). On an error (non-finite input, the .Boolean_Steps work limit, or an arrangement that doesn't hold together) out is unchanged.

  • How (ocurves' bool.odin and bool_kernel.odin): one arrangement of every operand's pieces, monotone in x and y, in f64. Pieces are cut wherever two come within eps = 8 f32 ulps of the largest coordinate (a near-set search that drops a pair only when it has proved them farther apart, so no crossing is missed); cut points within eps merge into vertices, pieces are cut where a vertex lies within eps of them, edges that share no vertex but still come within eps are cut and merged, until nothing changes. Edges along the same curve between the same vertices merge with their windings summed (abutting and identical shapes), edges are ordered around each vertex, faces walked, and each face's winding per operand propagated from each component's outer face; the edges between kept and dropped faces are traced into contours. Shapes closer than eps fuse; points farther from every outline are classified exactly.
  • Shared data: a Path is ocurves' contour table, so the operands are copied into one table as they are (path_append) and the result is one too, and every cubic evaluation, sub-range, extremum, bound and area comes from ocurves' cubic.odin, as fills, strokes, dashes and flattening do.
  • Checked by tools/bool_suite (random polygons, self-crossing ones included, cubic blobs, circles and grid-aligned rects with shared edges and corners, tangent circles; every op under both rules, each result's fill compared with the operands' on a grid away from the outlines, and its winding at most 1; each result's regions tile it, each one Solid contour then its holes, and hold every sample inside it once; each divide's faces cover the union once): 2,000 cases, 16,000 results and 2,000 divides, none wrong, for each of seeds 1 and 7. Area identities (union + intersection = a + b), curve preservation and the kernel's no-missed-crossing contract are tests.
  • Cost (-o:speed, median of 15): a rect minus a circle 29 us, two overlapping glyphs 0.29 ms, a plate minus 30 holes 0.9 ms, two 64-rect grids sharing edges 8 ms; no allocation with a warm scratch.

Colour fonts

Faces with COLR / CPAL tables draw their colour glyphs through the same fill_glyph_outlines call, as vector fills at the output resolution (crisp at any size, under any transform):

vg.font_collection_set_emoji(&fonts, vg.EMOJI_FONT_DATA) // optional emoji fallback
vg.text_layout(&fonts, {{text = "Hello 👋🔥 👩‍💻 🇯🇵", style = {size = 48}}}, {x = 10, y = 60}, &layout)
for run in layout.runs {
	font := vg.text_layout_font(&layout, run)
	vg.fill_glyph_outlines(&c, font, layout.glyphs[run.first:][:run.count], run.em, vg.paint_color(vg.BLACK), &path)
}
  • COLR v0: each layer glyph filled with its palette colour.
  • COLR v1: PaintColrLayers, PaintGlyph, PaintSolid, linear, radial and sweep gradients (pad / repeat / reflect; sweeps map onto the conic gradient), every PaintTransform / Translate / Scale / Rotate / Skew form (around a centre too), PaintColrGlyph, ClipBox. Variable fields use the default instance (VarIndex ignored).
  • PaintComposite has no isolated group: source-over and destination-over draw in order, src-in / src-atop / dest-in / dest-atop fill one side's outlines with the other side's paint (what fonts use them for), other modes (out, xor, plus, the blend modes) draw the backdrop alone. Nested PaintGlyph clips keep the innermost outline.
  • Palette 0. Index 0xFFFF is the text's paint: its colour, or a gradient / image paint as is; the text colour's alpha also scales palette colours, so fill-opacity and fades apply. Layers fade one by one (no group opacity).
  • Not drawn: bitmap colour glyphs (sbix, CBDT / CBLC) and SVG glyphs. Their outline is used when the face has one; fallback skips glyphs a bitmap colour face has no outline for.
  • Fallback: font_collection_set_emoji sets a face tried after the collection's faces (never matched by family). Emoji sequences stay in one face so shaping forms their ligatures: a rune followed by U+FE0F (or after a joiner in a colour face) takes a colour face, and ZWJ, variation selectors, skin-tone modifiers, keycaps and tags follow the rune before them. Leftover invisible format characters draw nothing.
  • EMOJI_FONT_DATA is Noto Color Emoji's COLRv1 build (SIL OFL 1.1, 5.0 MB, flags included; assets/Noto-COLRv1.ttf). It is linked only into programs that reference it; Noto-COLRv1-noflags.ttf (3.0 MB) can be passed instead.
  • Cost: each colour glyph's paint graph is flattened once per face into fill rows (outline, transform, solid or gradient) and its outlines cached, so a warm glyph draws without parsing or allocating. A line of 20 Noto emoji (321 fills) builds in 0.41 ms at 64 px and 0.87 ms at 512 px (layout, shapes, commands; Ryzen 9 9900X3D, -o:speed); the SDL_GPU frame with readback takes 1.7 ms at 64 px.

SVG import

ovg/svg parses SVG markup (svg/svg.odin, with a copy of core:encoding/xml in svg/xml: Odin dev-2026-11's drops an element's attributes past its 8th in a small file and never returns from a <![ that doesn't start CDATA, and the copy fixes both until Odin's does) into an svg.Document, a render-ready, data-oriented copy in the spirit of usvg: flat tables of nodes (parent / first child / next indices, local transform, object bounding box, effects by index), shapes (path data stored once in one contour table, geometry, each shape a range of it; computed style), text chunks and pieces, images and decoded bitmaps, paint servers and stops, clip paths, masks, filters, dashes, element ids (id_map) and a string arena. svg.layout lays the document's text out with a Font_Collection into an svg.Layout (positioned glyphs, runs per text), again only when the document or the fonts change. svg.draw (svg/draw.odin) walks the tables with that layout and issues canvas and layer calls; document and layout are read-only while drawing, so many canvases (threads) can draw one document, each with its own svg.Renderer (scratch paths, override table, and the document's canvas images, made by svg.renderer_bind).

import "deps:ovg/svg"

doc, err := svg.parse(data, {load_file = my_loader, fonts = &fonts})
defer svg.destroy(&doc)
text: svg.Layout                       // the text laid out: once per document and fonts
svg.layout(&doc, &fonts, &text)
defer svg.layout_destroy(&text)
r: svg.Renderer                        // one per document and canvas
svg.renderer_bind(&r, &c, &doc)        // the document's images on this canvas
vg.layer_stack_begin(&ls, &c, w, h, nil, doc.uses_blend)
ovs := [?]svg.Override{{id = "wing", transform = vg.transform_rotation(a)}, {id = "sun", fill = vg.RED}}
svg.draw(&c, &ls, &r, &doc, &text, vg.transform_scaling(w / doc.width, h / doc.height), ovs[:])
vg.layer_stack_end(&ls, &c)
  • Parsing resolves <defs>, <use> (elements, symbols, nested svg), presentation attributes, style, <style> sheets (type, class, id, attribute, :first-child, descendant and child selectors, specificity, !important), inheritance, currentColor, units (px, %, em, ex, pt, pc, mm, cm, in), viewBox / preserveAspectRatio, switch / systemLanguage. Shapes: path, rect (rx/ry), circle, ellipse, line, polyline, polygon (rect and ellipse paths start where SVG's do, for dashes). Paint: fill / stroke (colors incl. CSS names, rgb(), hsl(), gradients, patterns, fallbacks), opacities, fill-rule, dashes, caps / joins / miter limit, pathLength, visibility, display, opacity, mix-blend-mode, isolation, shape-rendering. Linear and radial gradients (focal fx/fy/fr, href inheritance, units, transforms, spread), patterns (units, content units, viewBox, transform, nested), clip paths (units, transform, nested, clip-rule; a single shape becomes a path clip, anything else an alpha mask), masks (units, content units, luminance / alpha, nested), filters (as above, units, regions, subregions, primitive units). Text: text / tspan chunks with x / y / dx / dy lists, rotate, font family lists, size, weight, style, letter-spacing, text-anchor (on the glyph extent, as resvg), dominant-baseline, textPath (a path href or SVG 2's path attribute, the referenced path's transform, startOffset as a length or a percentage of the path, side; not nested, no positions of its own, method and spacing ignored; text after it continues from its last glyph), CSS whitespace collapsing (the XML reader trims bodies, so text whitespace is protected before parsing), white-space (pre, pre-wrap and pre-line keep newlines as line breaks), line-height, and SVG 2 wrapped text: shape-inside naming a rect (less shape-padding; other shapes and shape-subtract are not wrapped into) and inline-size, laid out as one chunk by text_layout's width, text-align (else text-anchor) placing each line, a shape-inside's lines from its top as Inkscape stacks them (Line_Top) and those reaching below it not drawn (svg.Text.wrap keeps the area). Inkscape 1.4.4's tutorial-tracing-pixelart.svg: its 29 wrapped texts (111 lines, mixed Liberation Serif and Sans) break where Inkscape breaks them, every baseline within 0.0012 px of its plain-SVG export. Images: data: URIs and other hrefs through svg.Parse_Options.load_file; raster (oicut's image: PNG, JPEG, GIF, BMP, TGA, QOI, WebP) or SVG (its tree joins the document under a viewport group).
  • svg.draw(c, ls, r, doc, transform, overrides) draws in the document's width x height space. Effects map to one layer (opacity, path clip or clip-as-mask, mask, filter, blend), two when a non-path clip meets a mask; a single fill or stroke folds opacity into the alpha. Pattern tiles render at the current scale (nearest sampling, as resvg). svg.Override{id, transform, replace_transform, opacity, fill, stroke, visible} changes every instance of an id per draw (the transform applies inside the element's own transform; fill / stroke reach inheriting descendants), with no allocation once the renderer is warm. An element with an id and display="none" is kept (not drawn) so visible = true can show it: one file holds a sprite's alternate parts.
  • A <use> of an element or a symbol is a .Use node drawing, under its own transform and effects, the node its target converted to (data): the target's own node when it is in the drawing (wherever the use is, before it or after), else a definition converted once outside it (parent -1). A use whose copy would start from the same computed style and viewport as a definition's draws that one, so an id names one node per style and an override reaches every use; a use under another inherited style gets its own definition, carrying the same id. Each use still counts the elements and depth its copy would have against the limits. A use of a use refers to the use; uses in clip paths and of nested svgs are copies. On Inkscape's pixel-art tutorial (1.9 MB) its 227 uses share 29 definitions: 7% fewer nodes, parsing 5% faster, the image the same.
  • For editors: Parse_Options.keep_attributes keeps the attributes named (inkscape:label, class, ...) in doc.attributes, by node, and keep_groups gives every <g> a node of its own (otherwise one with no id, transform or effect folds into its parent).
  • svg.element_path(doc, out, id, text) appends the filled geometry (the whole document or one element's subtree, under its transforms, text with a layout) to a Path, returning the fill rule (and whether shapes mix rules); strokes, images, clips, masks and filters are ignored.
  • Unsupported (warned in doc.warnings): tref, textLength, markers, feImage referencing an element (images work), CSS filter functions, BackgroundImage inputs, DTD entities, WebP and svgz images, context-fill. Strokes under non-uniform scale or skew are expanded in device space (uniform width), images sample bilinear (resvg: bicubic).
  • tools/svg_suite checks it against the resvg test suite: run.sh renders the curated subset in tools/svg_suite/tests (64 files from structure, shapes, painting, paint servers, masking and filters, all passing) on the software backend and compares with the reference PNGs (a pixel is off beyond 24/255 premultiplied; a test passes with at most 1% off). On the full suite's categories for these features (1037 files, fonts from the suite for text) 88.5% pass: shapes 98.5%, masking 97.8%, painting 94.8%, paint servers 90.9%, filters 87.0%, text 82.4%, structure 74.6% (bicubic image sampling, WebP / svgz, DTD entities, SVG-in-image edge cases); 93% with a 48/255, 2% tolerance. The resvg tests of the later filter primitives (feComponentTransfer, feConvolveMatrix, lighting and lights, feMorphology, feTurbulence, feDisplacementMap, feTile, feImage: 169 files) pass at 86.4% (feTile misses are feOffset's subpixel shift, which resvg truncates; feImage misses reference elements). Over the whole text directory (386 files, unsupported features included) shaping took the pass count from 196 to 204 (ligatures across fonts, Arabic, Malayalam, Source Sans Pro kerning). -bench: times a file: a 1.9 MB Inkscape illustration (16 k shapes) parses in 32 ms and records in 12 ms.

Untrusted input

SVG and Lottie files may come from anyone: parsing and drawing are bounded by Limits (limits.odin), one table row per kind of work a small file can multiply: nesting depth, SVG elements (what each <use> draws and each element's copy of a filter included), CSS selector steps, nodes and effect passes per SVG draw, filter primitives, feTurbulence octaves, star points, repeater copies, repeated contours and layers per Lottie draw, dashes per stroke, COLR paints per glyph and decoded image pixels. Past a limit the work is cut short (a stroke with too many dashes draws undashed) and the limit is reported: a warning in doc.warnings, lottie.Renderer.limited after a draw, Canvas.limited for dashes. svg.Parse_Options.limits and lottie.Parse_Options.limits replace DEFAULT_LIMITS, Canvas.limits the canvas's; a new limit is a row in the table and one budget_take (a running total) or budget_cap (one value) where the work happens.

Fonts are read and shaped safely. oglyph's font and shape check every read: a corrupt or truncated font gives wrong glyphs or a load error, never a read out of bounds. Their work is bounded by the font's own data (a table varying over another number of axes than fvar's is ignored, as the spec requires) and shaping by HarfBuzz's limits on buffer growth and lookup steps per character. oglyph's tests mutate the layout and variation tables of real fonts and shapes and draws them with bounds checks on.

Lottie import

ovg/lottie parses Lottie (lottie/lottie.odin; Bodymovin JSON, After Effects exports; with core:encoding/json into a scratch arena) into a lottie.Document: flat tables of compositions (the root, then precomp assets), layers (kind, parent, matte layer, in / out / start / stretch, transform, shapes, masks, precomp or bitmap index), shape items (a group's children contiguous, props by slot), transforms, masks, dashes and animatable properties, whose keyframes, values (easing handles, spatial tangents included) and bezier paths are stored once. lottie.draw (lottie/draw.odin) evaluates it at a frame: properties interpolate per draw (binary search, cubic-bezier easing, hold, arc-length spatial position, path vertices), shape geometry builds per layer into the renderer's cubic contours (trim paths cut them), paints walk the shape tree bottom to top, and masks, track mattes, blend modes and group opacity over overlapping paints go through the layer stack. The document is read-only while drawing; each canvas has its own lottie.Renderer, which allocates nothing once warm.

import "deps:ovg/lottie"

doc, err := lottie.parse(data, {load_file = my_loader})   // image assets that aren't data: URIs
defer lottie.destroy(&doc)
r: lottie.Renderer                     // one per document and canvas
lottie.renderer_bind(&r, &c, &doc)     // the document's image assets on this canvas
vg.layer_stack_begin(&ls, &c, w, h, nil, doc.uses_blend)
lottie.draw(&c, &ls, &r, &doc, lottie.frame_at(&doc, seconds), vg.transform_scaling(w / doc.width, h / doc.height))
vg.layer_stack_end(&ls, &c)
  • Layers: precomp (time remap, stretch, start time; clipped to its size), solid, image, null, shape; parenting; in / out points; transforms (anchor, position or separated x / y, scale, rotation, opacity, skew and skew axis); track mattes (alpha, alpha inverted, luma, luma inverted; chained, tp or the layer above); masks (add, subtract, intersect, inverted, opacity, expansion); blend modes (Normal to Luminosity). Layer properties key in comp frames, as lottie-web.
  • Shapes: group (transform, opacity), rect (roundness; paths start where AE's do, for trims), ellipse, path (static and animated), polystar (star and polygon, roundness), fill (rule), stroke (width, caps, joins, miter, dashes and offset), gradient fill / stroke (linear, radial with highlight length and angle; color stops merged with opacity stops, coincident stops as hard edges), trim paths (simultaneous and individual, offset, wrapping), repeater (copies, offset, transform, start / end opacity, above / below).
  • Keyframes: temporal bezier easing per dimension, hold, spatial bezier position (to / ti), the old format's e end values; markers.
  • Layer effects (ef, parameters keyframed like any property), each a filter layer (filter.odin) around the layer's content, inside its masks, as lottie-web's SVG filters: Gaussian Blur (29; blurriness x 0.3 = sigma, both / horizontal / vertical), Drop Shadow (25; colour, opacity, direction, distance, softness / 4 = sigma), Fill (21; colour, opacity), Tint (20; black / white mapping of the linear-RGB gray, amount over the source) and Tritone (23; shadows / midtones / highlights table). A layer with effects composites its opacity as a group.
  • Text layers (ty 5): the document keyframe at the frame (text, font, size, fill / stroke colour, stroke width with stroke over or under the fill, justification left / right / center, tracking, line height, baseline shift, all caps, box text sz / ps wrapped greedily at spaces) is laid out with lottie.Renderer.fonts (a Font_Collection: the fonts list's family and style pick the face; shaping, kerning, per-glyph fallback and colour emoji as for any text; without a collection, the bundled Vera). Families missing from the collection collect in lottie.Renderer.missing. Text animators (t.a): range selectors by characters, characters excluding spaces, words or lines; start / end / offset in percent or indices; shapes square, ramp up / down, triangle, round and smooth; amount, ease high / low, smoothness; they animate anchor, position, scale, rotation, skew, opacity, fill / stroke colour, stroke width and tracking per letter (a letter's matrix pivots on its anchor group, characters / words / lines, from the shaped layout's glyph positions; lottie.selector_mult is lottie-web's selector math). Positions follow the font's own advances and kerning, so spacing differs slightly from a browser's.
  • Overrides (lottie.Override) replace a layer's transform, opacity, fill / stroke colour (text included), visibility, and a text layer's string (text).
  • Skipped with a warning in doc.warnings: other effects (stroke, levels, matte ...), layer styles, merge paths, round corners and other shape modifiers, text on a path, embedded glyphs (chars: drawn with the font), randomized selectors (kept in order), expression selectors, animator hue / saturation / brightness, cameras and 3D (drawn flat), auto-orient, mask feather, the add / hard mix blend modes; expressions are ignored (their keyframed values play).
  • Layer_Params.mask_invert (layers.odin) shows a layer where its mask is transparent (inverted mattes).
  • tools/lottie_suite compares renders with lottie-web (5.12.2, SVG renderer, headless Chromium) references: run.sh checks 13 small files from Skia's skottie resources, lottie-web's tests and ovg's own effect and text files (39 frames, all within 2% of pixels off by more than 32/255, text files within 6%: glyph edges differ from Chromium's font rasterizer though the layout matches; mean errors 0.02 to 4/255, mostly antialiasing). By eye on others: lottie-web's starfish, lights and dalek match except where expressions drive values; skewed strokes keep a uniform width (as for SVG). -bench: times a file: lottie-web's bodymovin.json (1.1 MB, 332 layers) parses in 27 ms and records a frame (evaluation, geometry, draw calls) in 0.12 ms; adrock.json (127 kB) parses in 2.2 ms and records in 24 µs.

Custom programs

program.odin: a host-supplied fragment shader run over a whole image, the way shading languages are hosted without ovg knowing them (onimite registers oksl output). A run is a recorded command executed in order at flush, like filter_image.

prog, err := vg.create_program(&c, {
	frag_spirv = spirv, frag_msl = msl, frag_msl_entry = "main0",
	vert_spirv = vert_spv, vert_msl = vert_msl, vert_msl_entry = "vs_main",
	uniform_size = size_of(Params), num_samplers = 1,
	cpu = my_cpu_shader, cpu_user = &state,   // software backend
})
vg.run_program(&c, prog, target, mem.ptr_to_bytes(&params), {photo}, {.Opaque})
vg.fill_path(&c, &p, vg.paint_image(target, x, y, w, h, 0))  // target flagged Premultiplied
  • The target (RGBA8, or RGBA16F: half floats kept unclamped, for feedback buffers a later run samples) is cleared, then fully shaded. The output is premultiplied. .Opaque clears to opaque black and keeps alpha 1 (Shadertoy). Uniform bytes are copied into the frame (Frame.bytes, 16-byte aligned). Channel n samples channels[n]; unbound channels read transparent black, and a channel may not be the target.
  • SDL_GPU: the program gets its own render pass and one quad, with one pipeline cached per (target format, opaque). Bindings follow SDL_GPU's convention, as oksl emits them:
    • Vertex input: position in target pixels at location 0, uv (0..1 from the top-left) at location 1.
    • Vertex uniform: the target size as a vec4 (set 1).
    • Fragment: uv at location 0, channel samplers at set 2 (binding n), the uniform block at set 3.
    • Sampler filtering and wrap follow each channel image's Nearest / Repeat_X / Repeat_Y flags.
  • read_image copies an image's texels back as stored (RGBA16F: four f16 per pixel), as of the last flush; update_image takes the same layout.
  • Software: calls cpu(user, uniforms, w, h, out, stride, format, sampler) (out holds format texels: RGBA8, or RGBA16F as [4]f16). sampler.images holds the channel images as oksl's bound images (oksl.Channel_Image): nearest or linear, clamp or repeat by each image's flags as the GPU's samplers are, texels as stored, an unbound channel's entry empty (oksl reads transparent black there); sampler.sizes gives each channel's size in texels and its layers (GLSL textureSize), 0 x 0 x 0 when unbound. An oksl CPU program runs as oksl.run(..., {channel_images = sampler.images[:], channel_sizes = sampler.sizes[:]}) and may split the image across threads.
  • Backends without programs leave create_program nil, and creating one then returns .Unsupported_Operation.
  • run_external(c, fn, user) runs host work at its place in the frame: fn(user, gpu, images) sees what earlier commands made, and later draws see its output (a 3D render into a canvas image that samples this frame's video frame, say). images is the store the frame's images live in (the canvas's, or the player's when a recording plays). On SDL_GPU gpu is the frame's ^sdl.GPUCommandBuffer, outside any pass; fn records into it (closing the passes it opens) without submitting it or creating textures, and vgsdl.image_store_texture(images, id) gives an image's texture. The software backend calls fn with gpu = nil; it reads and writes an image's pixels through image_store_get(images, id). ovg doesn't track the images fn touches (layers neither bound nor redirect it). On a recording canvas user must outlive the frame's playback; every player_render calls fn.

Paints:

  • Paint.spread: .Pad, .Reflect, .Repeat (SVG spreadMethod) for linear, radial and box gradients, two-stop and multi-stop.
  • Gradient colors interpolate in straight alpha (SVG): two stops with different alphas use the ramp texture, like multi-stop gradients. Ramps are 256 half floats, so a gradient keeps more than 8 bits in an RGBA16F target, and an 8-bit one rounds it once.
  • paint_radial_gradient_focal_stops(cx, cy, r, fx, fy, fr, stops): SVG's two-point conical radial gradient (Paint_Radial_Gradient.focal), in the shader and the software backend; a focal point outside the circle moves onto it.
  • Round and square caps draw a dot on zero-length subpaths and zero dashes (SVG); fills of contours without area draw nothing.
  • Paint.transform: maps paint space to the current space before the canvas transform (gradientTransform, patternTransform, objectBoundingBox units); the zero value is the identity. Works for every paint, image paints included.

Design

Data out is data in. ovg is a chain of stages, each reading the tables the one before wrote: parse (bytes to document tables), evaluate (a document at a time to its values), record (values to a frame's vertices, pieces, paints and commands) and render (a frame to pixels). The rules every part follows:

  • A stage reads tables and writes tables; it doesn't reach back into an earlier stage's inputs.

  • Each value is computed once, at the earliest stage that knows its inputs: what a file fixes at parse, what a frame fixes once per frame.

  • Scratch belongs to a long-lived owner (parser, renderer, canvas) and only grows: once warm, a frame allocates nothing (tools/bench, the *_no_allocation_when_warm tests).

  • Variable-length data is flat arrays addressed by ranges; payloads few rows carry live in side tables; kinds and properties are enum-indexed table rows (svg.props, lottie.EFFECTS, LIMIT_INFO).

  • Canvas records, backends draw. Drawing calls record Commands: shape instances whose words go into the frame (each shape once), with their paint rows (clears, filters and programs are the backend's own quads); flush hands a Frame to the backend. A backend is a Backend value (data pointer + procedures).

  • One way to draw a path: its shape. A fill or a stroke is a Shape (shape.odin) whose pixels take their exact area coverage. What makes a path long-lived owns its shape, built once and drawn under any transform (fill_shape; fill_shapes draws one at many transforms with one paint row, as an editor's anchors; a Paint_Slot kept beside each of a few paints gives many shapes, fills and hairlines alike, the paint's one row until the state changes, as a map's or a document's appearances): fonts own glyph shapes, SVG documents their elements' fills and strokes; their cubics and stroke outlines are within 1/4096 of their size, or the tol they are built with (shape_from_path, shape_from_stroke: a shape drawn magnified wants the pixel fraction it may miss by at its largest scale). fill_path and stroke_path build one for paths made on the fly (in drawing coordinates, cubics within 1/16 px). A stroke is its outline (stroke.odin: lines and quadratics offset as such, joins, caps, dashes along the curves) filled non-zero, so each pixel paints once however the stroke overlaps itself. Contours keep their winding, so non-zero and even-odd holes are exact.

  • Hairlines without a stroke. A shape built with outline (shape_from_path) keeps its contours as drawn beside its fill: each cell lists the pieces that draw, horizontal ones included, and not the edges that only close contours the path leaves open. hairline_shape (hairline_shapes for many places) draws them as a line width pixels wide under any transform, so a document kept in its own units draws its selection outlines and handles at every zoom with nothing rebuilt. A pixel takes its share within width / 2 of each piece across the piece's nearest point (the pixel box filtering a straight band), the largest: against 64 x 64 samples of the true band that is within 0.01 on curves and straight runs, and within about 0.1 to 0.3 on a pixel or two at sharp corners and open ends, which round. Outlining the 15,457 shapes of Inkscape's pixel-art tutorial at 1 px (1920 x 1080, RX 9070 XT): 2.3 ms a frame, 0.43 ms of it recording, where stroke_path per shape takes 30.5 ms (26.5 ms recording), the images within 16 levels; the outlines add 29% to building the shapes and 20% to their words.

  • Coarse levels for shapes drawn small. A kept shape whose detail thins out (shape_build: shape_from_path, shape_from_stroke, glyph shapes) also keeps up to six coarser copies of its curves (SHAPE_LEVELS), each within a power of two of its size from 1/8192 to 1/16 (SHAPE_LEVEL_FINEST, SHAPE_LEVEL_COARSEST). Each contour is simplified between pinned points (its start, its extreme points, the ends of edges its outline skips): runs of tiny curves merge into lines, then farthest-point splits (Ramer-Douglas-Peucker), run once for every level, keep the ends that matter; a copy is kept when it has at most a quarter of the curves of the last one, so a shape gains at most a third of its words and a simple one none. Each draw takes the coarsest copy within 1/8 px of the shape at the most its transform stretches any way (shape_level), its fill and its hairline alike, and the SDL_GPU store places only the copies drawn; shapes built for one frame (fill_path, stroke_path, a layout's variable-font glyphs) keep none. Neighbouring shapes stay joined within what their antialiased edges already leave. A map application's map of 17,758 urban areas (RX 9070 XT, 1280 x 800): everything selected 67.7 ms a frame at zoom 0.15, 2.8 to 3.1 ms with the copies, 28.4 to 28.8 at 0.32, 3.2 to 3.6, the map alone 11.4 to 11.8 at 0.32, 2.0; building its shapes takes 3.25 s of CPU from 2.0, and the process 1.23 GB from 1.13.

  • Markers. draw_markers draws squares or circles a fixed size in pixels at many points, filled with one paint and outlined with another (either optional), every outline over every fill: an editor's anchors and handles (fill_markers for one paint). They are shape instances without words (the unit square or circle scaled and placed) in one group: the GPU draws a record per run of cells about a marker's size, and each pixel takes the union of its cell's markers' fills and of their outlines in closed form (cv.marker: the square exact, the circle's edge straight across the pixel, within 0.054 at a 2.5 px radius), then each paint once, stopping once nothing more could change it. The tutorial's 62,962 anchors (filled and outlined squares) and 117,000 handles (circles) at 3.5 px x 2 on 2560 x 1440, with its outlines: on an M4 8.5 ms of GPU a frame where each marker as a shape took 49.6 ms (5.75 against 67.9 zoomed out to half, the markers piled up); on an RX 9070 XT 3.5 against 11.5 ms.

  • The software backend is the pixel reference for the GPU backend. It runs the GPU's own shaders (shape.frag, group.frag, markers.frag, filter.frag and velocity.frag's composite) on oksl's CPU program, over 2x2 quads of each instance's or pass's pixels as a GPU rasterizes them, compiled from the same sources the first time a frame draws with them, an instance's uv and data (the same at each of its pixels) passed as uniforms where the GPU interpolates them flat, and rc, fpos and a quad's texture coordinates worked out from the pixel's position where the GPU interpolates them across the quad, and a filter pass's paint as uniforms where the GPU reads it from a buffer (shader_cpu_defines). Textures are bound to oksl as images, which it filters by the GPU's rule (RADV's), and it uses the top-left fill rule. Only clears, blending into the target and the velocity resolve (a copy out of the screen's twin) are its own Odin. tools/sdlgpu_parity renders the scenes in tools/scenes on both backends and diffs them; on an RX 9070 XT (Vulkan, RADV) all 35 checks match, with a mean difference under 0.1 / 255 in each: most pixels within one or two 8-bit steps, a few edge pixels of text, emoji and filters further apart.

  • The software backend draws a frame in row bands of 16 rows: the clears and shape draws between target switches, filters, programs and externals are a run, each instance is binned once into the bands it reaches (counted, summed, filled), and each band draws its own in order, so every pixel gets the same draws in the same order on any number of threads. Bands run on the caller's Software_Backend.pool (oicut's Work_Pool; nil draws them all on the calling thread), as do blurs and morphology (two banded passes) and the other filters. Images flagged .Transient, which the layer stack's layers, tiles and offscreen images are (cleared as they become targets, holding nothing between frames), get their pixels for one render from one block the backend keeps at its largest render, so players sharing a backend hold one render's layers between them, not a set each. onimite's software renders at 24 threads, its frame builders recording for one player where each of 23 drew on a backend of its own, peak at 266 MB for the whole otfx video (4,833 MB before) and 201 MB for its burn scene (2,584 MB). On one thread, 30 frames of the burn take 100.4 -> 101.2 s, and a full-HD frame of 72 lines of 14 px text (half of them translucent groups) and 3,000 small rects draws 1 to 3% slower (145 -> 148-150 ms a flush at p50).

  • Layers cover what is drawn into them (layers.odin, Skia's saveLayer: group opacity, blur, SVG filters, clip paths, masks, blend modes). Drawing between layer_push and layer_pop is recorded against a stand-in target; the pop takes the device bounds of those commands, grows them by how far the blur and filter reach, cuts them to the clip path, the mask and the canvas, and points the commands at a pooled image of that window (sizes in steps of 1/8 of the next power of two). A render target can sit at an origin (set_render_target(c, img, origin)), so the layer is still drawn in canvas coordinates and pixels match a full-frame layer. Layers with nothing to show drop their commands; a layer a child blends with covers the whole canvas. A layer composites under the scissor of its push, cut at the whole pixels it covers, so a blur's spread or a flood stops at a scissored box's edge; a scissor set inside the layer cuts only its drawing. A layer with only an opacity over shapes (one image and scissor, source-over) needs no image: it becomes a group (Cmd_Draw_Shapes.group), whose pixels composite its shapes in order and take the opacity once, as the layer would. On the GPU a group is a grid of cells about one shape in size, each listing the shapes that meet it, drawn as quads over the cells that list any, so a pixel looks at the few shapes near it. Each layer was a render pass, a few microseconds of GPU time however small: a Lottie repeater's 49 fading copies (720p, RADV) took 1.09 ms, now 0.14 ms (M4 8.4 -> 0.6 ms).

  • Offscreen images can keep more than 8 bits (layer_image_begin(ls, c, w, h, .RGBA16F)): what is drawn into one is stored as an RGBA8 image would store it (premultiplied, sRGB-encoded) in half floats, so a faint gradient keeps the levels an 8-bit texel rounds away (a low-alpha flare bands once the sRGB curve spreads each 8-bit step over many output codes). Layers and pattern tiles made inside it take its format, feTurbulence there is unrounded and gradient ramps are half floats, so only content that is 8-bit to begin with (images) and feComponentTransfer (an 8-bit table looked up at an 8-bit index, as resvg) keep 8-bit levels. Values pass 1 only where a composite adds (.Lighter, or blend factors that add), and stay: a GPU's blend unit clamps a unorm target's source and result but nothing on a float target, and the software backend blends the same way.

  • Backdrop blur (layer_backdrop_blur(ls, c, path, sigma), CSS backdrop-filter: blur()): in draw order, what the target holds under the path is copied out (grown by the blur's reach, into a pooled image), blurred (edges repeated at the target's), and the path filled with it, its edge by exact coverage; a translucent panel drawn next sits on frosted glass. It reads the target, so drawing to the screen takes a root layer (layer_stack_begin(..., root_layer = true)); inside a pushed layer it draws nothing.

  • Images are top-down on both backends, including images rendered into (SDL_GPU puts y = 0 at the top of every target), so a render target can be used as an image paint without Flip_Y.

  • Paints are plain values. Multi-stop gradients borrow their stop slice; it only has to live for the draw call.

  • Shapes (shape.odin, over the core-only ocurves and its GPU twin curves.glsl, which other renderers use alone: the word layout, coverage of a box footprint, coverage_affine of any parallelogram (coverage_jacobian from a 3D footprint's Jacobian), winding at a point for sample masks, a mean coverage to fade to when minified) are filled by exact per-pixel coverage: a Shape is quadratic curves, each monotone in x and y, cut into the columns of a grid of cells, each cell listing its pieces and its backdrop (the winding number right of it), built once from a path or a glyph (shape_from_path, shape_from_glyph) in time linear in its pieces; fill_shape draws it under any transform for the cost of its bounds. A pixel's coverage is the area of its footprint inside the shape, integrated in closed form (Green's theorem) over the pieces in the cells it covers, plus the backdrop over its rows: exact under any transform (the footprint is a parallelogram, a box without rotation or skew), and a pixel's cost is the pieces near it, not the shape's size (16 lines of text, each one shape, at 150 px on 4K: 2.2 ms with rows of curves, 0.93 ms with cells). Against 8x8-supersampled small italic text the mean error is 0.0005 (the two-ray estimate ovg used before: 0.008); rotated pixels are about 20 times closer. On the GPU a run of shapes is one instanced draw, its instances pulled from a storage buffer (the box shader for upright instances, the parallelogram one for the rest); a pixel scans its cells and integrates the few pieces crossing it after the scan, so pixels running together integrate together. Shapes kept by their owner upload once into the backend's store; a frame's own words (paths filled this frame) go up with it. Against the two-ray estimate (4K, Linux / M4): dense upright text costs 17% / 18% more, rotated text 50% / 26% more. The software backend runs the same shape shaders (parity: max diff 1 in the curves scene).

  • Text reads fonts with oglyph/font (core only: the table directory, cmap, hmtx, kern and GPOS pair kerning, glyf with composites, CFF Type 2 charstrings; bounds-checked; outlines placed by hmtx's side bearing as HarfBuzz places them, and checked glyph by glyph against fontTools). fill_glyph_outlines fills each glyph as the font's shape (font_glyph_shape: built on first use with the font's allocator, font_load's (a collection's fonts take the collection's), whatever the drawing code runs under; owned by the font, freed by font_destroy), all sharing one paint row: a run costs no outline work, and draws in one call. Opaque runs draw each glyph as it is; a run with global alpha, a translucent paint or another blend fills as one, a group of its glyphs in white tinted by the paint (see Layers), so overlapping glyphs never darken where they meet. Feathered and aliased paints fill the outlines as one shape (a feather widens each pixel's footprint; aliased takes each pixel center's winding). Text has this one path, exact at any position, transform and size: there is no glyph atlas.

  • Font collections are oglyph's (deps:oglyph/collection: the faces, their files' shaping tables and plans, family matching and fallback, usable without ovg). Font_Collection embeds one (faces, fallback, emoji, default_family read through) with what drawing makes of each face, a Font per Face_Id (its glyphs' shapes and COLR paint), and the layouts' scratch; it tells oglyph that a glyph a face has only as a bitmap counts as missing, ovg drawing outlines. Faces and fonts never move (oglyph's Rows), so other threads may draw with fonts they hold the ids of while font_collection_add adds faces.

  • Text layout (text_layout over a Font_Collection, used by SVG text and onimite) picks each piece's face by family, weight and style (text that names no family uses Font_Collection.default_family when set; the collection keeps its faces indexed by family, with what a find scores, so finding one is a binary search and a sweep of the family, not a scan: 0.23 us for a 72-face family among 2,380 faces, from 15 us) and shapes with oglyph/shape: each line is split into segments of one font (per-glyph fallback, oglyph's collection_fallback, picks the first face covering a codepoint, keeps emoji sequences in one colour face and marks with their base), size, script and bidi level (each character's Unicode script, characters of every script taking the script around them; levels from oglyph's bidi_levels, UAX #9's weak and neutral rules for a left-to-right paragraph over the Unicode database's bidi classes: spaces, punctuation and emoji between right-to-left text join it, others keep the paragraph's direction), each segment is shaped (GSUB: ligatures, contextual alternates, Arabic joining, Indic reordering; GPOS: pair / class kerning, mark positioning) and the segments are placed in bidi visual order (right-to-left runs reversed, numbers after right-to-left letters kept in order inside them). Faces without GPOS kern with their legacy kern table. Text_Style.features turns OpenType features on or off per piece over the shaper's defaults ({{"smcp", 1}, {"liga", 0}, {"salt", 2}}: small caps, no ligatures, the second alternate; the last of a tag wins, as CSS font-feature-settings): a segment whose pieces all set the same features shapes with them over all of it, else each piece's apply over its own codepoints. Letter-spacing turns off liga / clig / dlig (CSS) unless the piece sets them, and is not added after attached marks. What a font file says whatever the instance is a row of Font_Files (oglyph's Files), one per face of each file: its family, weight and style, its layout tables (prepared on first use) and its plans (per FeatureVariations record, script, direction and features, each made on first use). A collection keeps a table of its own, or shares one with other collections (font_collection_init(&c, files = &files)), so every instance of a file, in any of them, uses the one row: another instance costs about its glyphs (Adwaita Sans, 14 glyphs at a new weight: 54 us where it took 357 with its own tables). Rows never move, and only making one (or its tables, or a plan) takes the table's lock, so collections sharing it may each run on their own threads. The collection pools Text_Shapers (glyph buffer and the layout's tables), so layouts may run concurrently on one collection; a warm shaper does not allocate. Every call shapes what it is given: a Text_Layout is data out, kept by the caller and drawn again while its text is unchanged. Text_Layout.advances gives each glyph's pen step (its advance, plus letter spacing after a base), to place a caret: a glyph ends at its pen plus its advance, and a mark doesn't step. text_layout_fit(&layout, line, width) cuts a line short for an ellipsis: it keeps the text before cut, as much as fits width, in text order and only between clusters (never inside a grapheme, ligature or syllable), its glyphs (those whose cluster is below cut) kept wide; it reads the layout and allocates nothing. A collection names its faces by Face_Id (runs, font_collection_find, font_collection_glyph), and font_collection_face / font_collection_font give a face's record or font for immediate use: keep the id, not the pointer. A layout records the collection it was laid out with, so text_layout_font(&layout, run) gives a run's font (and text_layout_path, text_layout_on_path need nothing more). Ids stay with their faces as faces are added before or after them, so a layout outlives faces added to its collection; a removed face's id, a replaced emoji face's (Font_Collection.emoji is a Maybe), Face_Id{} and another collection's ids name no face (nil). Variable fonts draw the instance they were loaded at: font_load(data, 0, variations = {{"wght", 700}}), or font_collection_add(&fonts, data, variations = ...), which gives the face the instance's weight (wght) and style (ital, slnt) so text picks it by weight; Text_Style.variations (CSS font-variation-settings) picks the face whose instance those settings select, so instances apart in any axis (wdth, opsz) are told apart. Settings no face of the collection is make that instance of the face weight and style pick, the layout's own (Text_Layout.instances: a copy of the face sharing its file's tables and plans, kept for the layout's next text and changed in place, so an animated axis allocates nothing once warm). Its glyphs are built into each frame that draws them instead of kept as shapes: on an M4, 13 us of recording for a 20-glyph headline and 30 us for a 600-glyph paragraph where kept shapes take 0.4 and 9, the GPU's time within 2%. Text at one instance for many frames, or drawn after the layout's next text from its runs, should add the instance to the collection. A font is one instance for its life: its outlines, advances, glyph boxes and shaping follow it (oglyph/font lists a face's axes and named instances, and ft.name_string names them: "Weight", "Bold"). Not handled: explicit bidi controls (U+202A..U+202E, U+2066..U+2069), a right-to-left paragraph direction, vertical text, MVAR's varied line metrics (ascent and descent stay the default instance's). All text, UI labels too, lays out this one way.

  • Wrapping: with Text_Options.width, a paragraph wider than it breaks into lines that fit at oglyph's line_breaks opportunities (UAX #14): each line ends at its last opportunity where it fits (or at a mandatory break); a word wider than the width has a line of its own; the spaces a line breaks after hang past its end, outside its width and alignment. Each Text_Line carries its baseline y and the codepoints it holds (text_start, text_end, in clusters' indices, tiling the text: a newline or the spaces of a break are the line's before it), and every line is returned, however many the caller has room for. align places each line by its own width at x; Text_Baseline.Line_Top puts y at the top of the first line's box and stacks the lines as CSS line boxes, as Inkscape lays out SVG 2 text: each as high as its tallest inline box (the first piece's face and size, and each run's), every box a line height high with its face's em box centred in it (font_em_box: the OS/2 typographic ascent and descent, else hhea's, scaled to fill the em), and Text_Line.above / below give each box's reach. Against Inkscape 1.4.4's own lines (its plain-SVG export) of the 24 single-font paragraphs of its tutorial-tracing-pixelart.svg (Liberation Sans and Serif, 6 to 8 px, line heights 120 to 150%, 230 to 300 px wide): all 98 lines break where it breaks them, every baseline within 0.0012 px of its. A paragraph that fits takes the one-line path as before; one that doesn't is shaped once to measure and again line by line, each line with its own bidi order: a 360-glyph paragraph in Noto Sans at 14 px lays out in 15 us, wrapped into 9 lines at 300 px in 34 us (-o:speed).

  • Shaping is oglyph's (deps:oglyph/shape; its README has the details): HarfBuzz's shapers and lookups, checked against HarfBuzz with no differences over its corpora, about HarfBuzz's speed (0.99-1.10x its time on sentences, 0.66-0.90x on words and random strings).

  • Text on a path (text_path.odin, SVG textPath): text_path_set measures a path (flattened, each point's distance along it) into a Text_Path; text_layout_on_path moves a layout made from x = 0, y = 0 onto it, x becoming a distance along the path (start offsets it) and y an offset across it. Each glyph sits where its middle falls, turned to the path's direction there: Text_Layout.turns holds each glyph's direction (cos, sin), {0, 0} for a glyph off either end (not drawn). A path of one closed contour takes one circuit of text, wrapping round past its end (SVG 2): the glyphs whose middles lie within a path's length after x = 0, around it or before it, as anchor (the text's align, SVG text-anchor) says. side = .Right runs along the path reversed. text_layout_path follows the turns; to draw, turn each glyph about its origin (apply_transform(c, {t.x, t.y, -t.y, t.x, g.x, g.y}), then the glyph at 0, 0), as svg.draw does.

  • Font information (cold, for font pickers and glyph browsers): font_info reads a font's typographic family and subfamily, full and PostScript names, glyph count and the GSUB / GPOS feature tags it has (what features can set); font_glyph_names gives every glyph's name (post formats 1 and 2, or the CFF charset; none for CID-keyed fonts), slices of the font data; font_codepoints gives the characters it maps to a glyph, ascending (the cmap's ranges walked in order and clamped to Unicode, so a malformed table costs at most one pass over them). Checked against fontTools over 2,380 installed faces: names, feature lists, glyph names and code points (5.6 million) all agree.

Implementation notes

  • Software + SDL_GPU backends (femtovg: OpenGL / wgpu) behind a runtime backend interface.
  • The software backend matches the GPU shader: the same shape coverage, one gradient formula for linear/box/radial (the radial path was off by half a feather), no double Flip_Y, GPU texel conversions, rounding to 8 bits, rotated-scissor mask, the GPU blur coefficients.
  • clear_rect clears only its rectangle (∩ scissor) with premultiplied color.
  • Second blur pass reads the intermediate as premultiplied (straight-alpha sources were premultiplied twice).
  • realloc_image frees the old backend image.
  • Gradient ramps pad past the last stop.
  • Paths are plain data, read-only while drawn: a Path is ocurves' contour table (every contour's points, each segment's kind, a row per contour), which the path_* calls write the way a fill reads it (a close's line back to the start is a segment, drawing after a close starts at the closed contour's start, path_solidity winds the contour as it stands), and fills, strokes, dashes, booleans and hit tests walk its rows as they are. fill_path builds the path's shape into the frame. Scratch and frame buffers reuse their allocations; paints never allocate.

Test

# with oglyph, ocurves, oicut and oksl cloned next to ovg (see Use); every build takes -collection:deps=..
# (fonts and shaping are tested in oglyph: odin test font / shape there; shapes' words and booleans in ocurves)
odin test . -collection:deps=.. -vet -strict-style    # core + software backend
odin test svg -collection:deps=.. -vet -strict-style  # SVG import: parsing, drawing, hostile files
odin test lottie -collection:deps=.. -vet -strict-style # Lottie import: parsing, drawing, hostile files
./tools/svg_suite/run.sh                              # SVG import vs resvg reference PNGs
./tools/lottie_suite/run.sh                           # Lottie import vs lottie-web reference PNGs
odin run tools/bench -collection:deps=.. -o:speed     # CPU time and allocations per warm frame, generated workloads
odin check sdlgpu -collection:deps=.. -no-entry-point -vet -strict-style  # SDL_GPU backend
odin test sdlgpu -collection:deps=.. -vet -strict-style  # its release table; needs the SDL3 library, no GPU
odin run tools/sdlgpu_parity -collection:deps=.. -- out_dir # SDL_GPU vs software, headless
odin check sdlgpu -collection:deps=.. -no-entry-point -target:darwin_arm64    # macOS / Windows compile
odin check sdlgpu -collection:deps=.. -no-entry-point -target:windows_amd64

assets/Vera.ttf is Bitstream Vera Sans (LICENSES/Bitstream-Vera.txt), used by the tests and as a Font_Collection's default fallback face. assets/colr_test.ttf is a tiny COLR v0 / v1 test font made by tools/colr_test_font/build.py (fontTools).

License

MIT, see LICENSE. Third-party notices are in THIRD_PARTY_NOTICES.md.

The mascot, a chameleon (it changes colour, its tail is a spiral and its tongue a curve), is drawn by tools/mascot (odin run tools/mascot -collection:deps=.. -- assets): assets/logo.svg keeps its skins (green, pink, blue), eyes, mouths and tongue as layers a script can switch by id, each colour one traced path, plus a hidden silhouette (the whole chameleon as one outline) for svg.element_path(&doc, &p, "silhouette").

About

2D vector canvas for Odin: paths, text, gradients and SVG filters, drawn by exact per-pixel curve coverage on the CPU or the GPU.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages