Writing a backend¶
A backend is a type with the eleven procs of RenderContext. It can live in pollock's repository or in a package of its own; nothing in pollock needs to know about it.
The shape of it¶
import pollock/context
importTextEngine() # the default text engine, for `drawGlyphs`
type
MyState = object
## Everything `save` and `restore` cover: the transform and the clip.
transform: Affine
clip: MyClip # however the native API represents a clip
MyContextOf*[E] = object
engine*: E # the text engine whose glyphs it draws
state: MyState
stack: seq[MyState]
error: string
# ... whatever the native API needs
MyContext* = MyContextOf[typeof(defaultTextEngine())]
proc newMyContext*[E](..., engine: E): MyContextOf[E] =
MyContextOf[E](engine: engine, state: MyState(transform: affineIdentity))
proc newMyContext*(...): MyContext =
newMyContext(..., defaultTextEngine())
proc clear*(ctx: var MyContext, color: Color) = ...
proc fillPath*(ctx: var MyContext, path: BezPath, paint: Paint, rule: FillRule) = ...
proc strokePath*(ctx: var MyContext, path: BezPath, paint: Paint, style: StrokeStyle) = ...
proc clipPath*(ctx: var MyContext, path: BezPath, rule: FillRule) = ...
# intersect ctx.state.clip with the path, under ctx.state.transform
proc save*(ctx: var MyContext) = ctx.stack.add ctx.state
proc restore*(ctx: var MyContext) =
if ctx.stack.len > 0: ctx.state = ctx.stack.pop()
proc transform*(ctx: var MyContext, affine: Affine) =
ctx.state.transform = ctx.state.transform * affine
proc currentTransform*(ctx: MyContext): Affine = ctx.state.transform
proc drawImage*(ctx: var MyContext, image: ImageData, dst: Rect, interp: Interpolation) = ...
proc drawGlyphs*[E](ctx: var MyContextOf[E], run: GlyphRun, paint: Paint) =
ctx.drawGlyphsAsPaths(ctx.engine, run, paint) # or draw natively, see below
proc finish*(ctx: var MyContext): RenderResult =
if ctx.error.len > 0: failure(ctx.error) else: success()
static:
doAssert MyContext is RenderContext
(The other procs take ctx: var MyContextOf[E] with an [E] on the proc as well; they are shown without it for brevity.)
Keep the transform and the clip together in one state object, and save and restore that object whole. Saving only the transform is an easy mistake: a clip set inside withClip would then stay in force after the block ends. If the native API has its own save and restore (cairo_save, CGContextSaveGState), call it from save and restore as well.
The static assertion at the end is worth keeping: it turns a missing or mistyped proc into a compile error in the backend's own module, with a message about the concept, instead of an error at some call site in a user's program.
Export your constructor and anything the user needs to get the result out (toImage, toSvg, a present). Keep the primitives themselves exported too; the concept needs to see them.
Text¶
The context is generic over the text engine it draws for, so that the engine is known at compile time: importTextEngine() brings in the module named by -d:pollockTextEngine (the pure Nim engine by default), typeof(defaultTextEngine()) is its engine type, and the plain MyContext is the pairing with it. A backend that keeps no engine of its own can leave all of that out, as the recording backend does, as long as it still has a drawGlyphs.
drawGlyphs gets a run and a paint. The simplest implementation, and the right one for a renderer without native glyph drawing, is drawGlyphsAsPaths(ctx, ctx.engine, run, paint) from pollock/context: it asks the engine for each glyph's drawing (an outline, color layers or a bitmap, in em units, cached on the font), scales it by the run's size, moves it to the glyph's position and draws it with fillPath and drawImage. A backend with native text makes a native font from run.font.data (and index), caches it keyed by the Font, and draws the glyph ids at their positions itself, unhinted and with grayscale antialiasing so it matches the reference; when E is SomeEngine can pick a native path for one engine and fall back for the others.
What pollock gives you¶
You do not have to write a path flattener or a stroker:
path.flatten(tolerance)turns aBezPathinto polylines, arcs included.path.toCubicsreplaces the arcs in a path with cubic curves, for a native API without elliptical arcs;toArc(el, start)gives an arc element's center, radii and angles for one that has them.strokeOutline(path, style, tolerance)turns a stroke into a fillable outline (fill it withfrNonZero). Use it when the native API has no stroking, or when its stroking does not match the rules.dash(polylines, style)applies a dash pattern on its own.transform(affine, path)andaffine.maxScaleconvert between user and device space; the CPU backend divides its device-space tolerance bymaxScale(the largest stretch in any direction) to get a user-space one that holds along every axis.colorAt(stops, t)andapplyExtend(t, extend)evaluate gradients. A linear gradient with no length, or a radial one with no radius, paints its last stop everywhere, as SVG specifies.ImageData.convert(format)converts pixel formats, andpollock/pngreads and writes PNG.drawGlyphsAsPaths(ctx, engine, run, paint)draws text throughfillPathanddrawImage, andengine.cachedDrawing(font, glyph)gives a glyph's outline for a backend that draws it some other way.
If the native API has fast paths for simple shapes, check for them: fillPath receives a BezPath, and path.elements makes an axis-aligned rectangle easy to recognize (a move, three lines and a close).
Every element kind has to be handled: a case over PathEl.kind without a branch for peArcTo is a compile error, which is on purpose, so that a new kind can't be silently dropped by a backend.
Device resources¶
Brushes, textures and layouts that belong to a device (Direct2D, WebGL) must be created by the backend from the Paint and ImageData values it is given. Cache them keyed by the value if creating them is slow; a backend owns its cache and drops it in finish or when the device is lost.
Own native handles with =destroy hooks so a context can be dropped without leaking, and disable =copy for types that hold a handle. If your users might build with --mm:refc, declare the hook under when defined(gcDestructors) with the =destroy(x: T) signature and give refc the older =destroy(x: var T) in the else branch: refc rejects the first form at compile time. pollock/backends/cairo in the repository is a worked example of a backend over a C library: hand-written bindings for just the calls it makes, flags from pkg-config at compile time, handles released in =destroy, and the transform kept in Nim so a singular or non-finite one can be skipped before the library sees it.
Nim has four targets: C, C++, Objective-C and JavaScript. A binding to a C library can usually serve both nim c and nim cpp, since C++ compiles C headers, but C++ is stricter about types: it won't pass a plain int where the C function takes an enum. Declare each enum as its own type under its C name, as the Cairo backend does, and the generated code casts the values for you:
type CairoFillRule {.importc: "cairo_fill_rule_t", header: "cairo.h".} = distinct cint
const cairoFillRuleEvenOdd = CairoFillRule(1)
A library with a C++ API (classes, templates, namespaces) is bound with importcpp instead, and the backend then compiles only under nim cpp. Say so in your documentation and run your tests with nim cpp. The core of pollock compiles under C++ like everything else, so nothing else changes.
Errors¶
Drawing calls must not raise. Record the first failure in the context and report it from finish:
Checking the result¶
pollock/samples has the scenes every backend renders:
import pollock/samples
for i, name in sampleNames:
var ctx = newMyContext(sampleWidth, sampleHeight)
ctx.drawSample(i)
doAssert ctx.finish().ok
# save the result as name.png and look at it
drawTextSample(ctx, trueType, cff) is the text scene; it takes the TrueType and CFF forms of Source Sans 3, which nimble fonts in a checkout of pollock downloads into tests/fonts/, and its golden is text.png.
If the backend can hand back pixels, compare them with the CPU backend's goldens in tests/golden/cpu/ using compareImages(a, b, tolerance) from pollock/testing. Antialiasing differs between renderers, so expect to allow a few levels of difference along edges; large differences mean something is wrong. The Cairo backend's test (tests/tcairo.nim) does this with a tolerance of 32 levels and allows 0.5% of the pixels to exceed it, which covers edge antialiasing and dash phases on curves while a missing or misplaced shape still fails.
Making it the default¶
Users can select any backend module with -d:pollockBackend=<module path>; import pollock then exports it. A backend package called pollock_webgpu is picked with -d:pollockBackend=pollock_webgpu. The module must export its constructor and the primitives.
Testing on targets you cannot run¶
nim check --os:windows yourbackend.nim and nim check --os:linux yourbackend.nim type-check platform code from any machine, and nim js does the same for a browser backend. Run whichever applies before you push.