Paint and the scene
How paint turns the fragment tree into a display list: primitives, clips, draw order, the stacking walk, damage culling, replay, vector routes, vector passes and batching.
Paint is the stage between layout and the renderer. It reads the fragment tree and computed styles
and writes one value, a display list, which the renderer draws without making any further decisions.
zgui-scene defines the display list, and zgui-paint fills it in.
zgui-layout · zgui-stylezgui-bitszgui-scenezgui-renderThe complete value the renderer consumes.
The display list
A display list is everything one frame draws, stored as data. It holds no device handle, context or renderer. This has three consequences:
| Property | Consequence |
|---|---|
| No device in the type | Paint runs and is tested headless. Most framework tests never open a window. |
| Printable and comparable | A scene prints as a stable transcript, so a change to what a frame draws is a reviewable diff. |
| One input, several consumers | The wgpu renderer and zgui_testkit_scene::CaptureRenderer read the same value. |
The type is Scene, reachable as zgui::scene:
pub struct Scene {
pub primitives: Primitives,
pub clips: ClipTable,
pub paints: PaintTable,
pub text_paints: TextPaintTable,
pub shader_params: ShaderParamsTable,
pub spatial: SpatialTree,
// private: the operation log, remap lists, bounds tree, pass plan, mark plan, viewport, …
}Primitives are stored in one array per kind:
// crates/zgui-scene/src/scene/primitives.rs
pub struct Primitives {
pub quads: Vec<Quad>,
pub shaded: Vec<ShadedQuad>,
pub shadows: Vec<Shadow>,
pub decorations: Vec<Decoration>,
pub mono_sprites: Vec<MonoSprite>,
pub subpixel_sprites: Vec<SubpixelSprite>,
pub color_sprites: Vec<ColorSprite>,
pub marks: Vec<MarkItem>,
pub mark_payloads: Vec<Arc<MarkPayload>>, // parallel to `marks`
pub vectors: Vec<VectorItem>,
pub externals: Vec<ExternalQuad>,
pub backdrops: Vec<BackdropFilter>,
pub groups: Vec<GroupBoundary>,
}A run of one kind is a contiguous slice. Every instanced struct is #[repr(C)], bytemuck::Pod
and padding-free, checked field by field at compile time in crates/zgui-scene/src/prim/layout.rs.
It copies into a GPU buffer as bytes, and a reordered field fails the build.
Anything variable-sized lives in a side table addressed by index: the clip chain, the paint, the
shader parameters, the matrix. A quad with a forty-stop conic-gradient has the same instance size
as a quad with a flat colour.
Every primitive's bounds is its ink: everything it paints, not its geometry. A shadow's bounds
include its blur. Damage tests and clip culls run against the ink, so under-reporting it leaves stale
pixels on screen.
Primitives
PrimitiveKind has thirteen variants. When two primitives have the same draw order, the variant
order breaks the tie. This is a batching preference, never a correctness mechanism.
// crates/zgui-scene/src/prim/kind.rs
pub enum PrimitiveKind {
GroupStart, Shadow, Quad, Shaded, Marks, Vector, Decoration,
MonoSprite, SubpixelSprite, ColorSprite, External, Backdrop, GroupEnd,
}| Kind | Type | Draws |
|---|---|---|
Quad | Quad | A rectangle with superellipse corners, a fill and a styled four-sided border. Backgrounds, borders, scrollbar parts, and recognised vector shapes. |
Shaded | ShadedQuad | A rectangle filled or covered by an application shader effect. Names a shader and a parameter block. |
Shadow | Shadow | One box-shadow, outer or inset. |
Marks | MarkItem | Many recognised shapes (discs, boxes, polylines, glyph cells) drawn from a shared payload with one paint. See Marks. |
Vector | VectorItem | A path for the general rasteriser, planned into a pass rather than drawn directly. |
Decoration | Decoration | One text decoration line. |
MonoSprite | MonoSprite | A single-channel coverage tile: a glyph or an atlas vector mask. |
SubpixelSprite | SubpixelSprite | A glyph tile with per-channel coverage. |
ColorSprite | ColorSprite | A full-colour tile: an image, a colour emoji, a CPU vector layer. Takes corner radii and an opacity. |
External | ExternalQuad | A texture the renderer did not produce, such as a video frame. |
Backdrop | BackdropFilter | A filter over the composite already beneath it. |
GroupStart / GroupEnd | GroupBoundary | A matched pair that redirects everything between them into a target, then composites it back with an opacity, blend mode and filter chain. |
A sprite is a rectangle of a texture drawn somewhere on screen. The texture is usually an atlas holding many small images, so a thousand glyphs bind one texture and draw in one call.
// crates/zgui-scene/src/prim/quad.rs
pub struct Quad {
pub order: DrawOrder, // always at offset zero
pub style: u32, // BorderStyle in the low byte, dash phase above
pub bounds: [f32; 4],
pub radii: [f32; 8], // two semi-axes per corner, clockwise from top left
pub border: [f32; 4], // top, right, bottom, left
pub fill: PaintRef,
pub stroke: PaintRef,
pub clip: u32, // ClipId
pub transform: u32, // SpatialId slot
pub shape: f32, // superellipse exponent; 2 is an ellipse
pub paint_origin: [f32; 2],
}Shadow carries three rectangles: the shape it blurs, the box it belongs to, and the pixels it
covers.
// crates/zgui-scene/src/prim/shadow.rs
pub struct Shadow {
pub order: DrawOrder,
pub blur: f32, // standard deviation, device pixels
pub bounds: [f32; 4], // everything it paints
pub shape_bounds: [f32; 4], // the blurred shape
pub radii: [f32; 8],
pub element_bounds: [f32; 4], // the casting box (outer) or the clipping box (inset)
pub element_radii: [f32; 8],
pub color: [f32; 4], // premultiplied, gamma-encoded sRGB
pub clip: u32,
pub transform: u32,
pub inset: u32,
pub shape: f32, // superellipse exponent of the corners
}For a drop shadow, shape_bounds is the border box offset and grown by the spread, and bounds is
that dilated by Shadow::BLUR_EXTENT = 3.0 standard deviations. For an inset shadow,
element_bounds is the padding box (so the shadow never covers the border), shape_bounds is
the hole (the padding box offset and shrunk by the spread, with concentric corners), and bounds is
the padding box.
MonoSprite and SubpixelSprite share a layout. They are separate types so that a batch never
mixes them, because they need different pipelines. A glyph run uses per-channel coverage only when
the device supports dual-source blending, the target it lands in is opaque, and its transform moves
it by whole device pixels. A run inside an isolated group, or under a fractional pan, scale or
rotation, uses MonoSprite.
ExternalQuad is the one primitive that is neither instanced nor Pod. Each is drawn on its own
with its own bind group.
Clips
A clip admits some pixels of a primitive and refuses the rest: a scrollport clipping its rows, a rounded button clipping its image.
// crates/zgui-scene/src/clip/
pub enum ClipLink {
RoundedRect {
rect: Rect<DevicePx, Device>,
radii: Corners<Vec2<DevicePx>>,
shape: CornerShape,
space: SpatialId,
},
Mask { tile: AtlasTile, transform: SpatialId, source: MaskSource },
}
pub enum ClipNode { Root, Link { link: ClipLink, parent: ClipId } }Clip chains form a trie stored innermost-first with parent pointers. Chains that share an outer
prefix share nodes, and a primitive carries a single u32.
ClipTable::resolveintersects every rectangle in a chain into one box and keeps at mostMAX_INLINE_ROUNDED = 2rounded tests. A fragment shader evaluates those per pixel.- A chain that needs more rounded tests, or more than one mask, is reported by
needs_group_targetand gets a group target. It is never silently truncated. common_ancestorandresidualsplit a chain into a shared part and a remainder. Vector pass planning uses them.
Scene::push_* culls with ClipTable::bounds_in(clip, space), which intersects only the links
measured in the same coordinate system as the primitive's ink. A row scrolled out of its port never
reaches an array, the bounds tree or the log. A link in another coordinate system is left to the
shader, which resolves the full chain through the frame's matrices, so content that a transform
moved into view is never wrongly culled.
Coordinate systems
A primitive names its coordinate system by a slot index into SpatialTree, not by a matrix. A
coordinate system is identified by the box that establishes it. Moving the box updates a node
instead of creating a new identity, and a thousand untransformed rows all resolve to one node.
Placements::of(&tree) flattens the tree into the dense matrix array that a shader indexes. Each
slot keeps an occupancy generation, so a name whose box has gone is refused rather than resolved
through a slot that another box now owns. Because a primitive carries only the slot, the scene can
record full names beside each log entry and check them with
Scene::record_spatial_dependencies(true) and check_spatial_dependencies(). These checks are
enabled when ZGUI_INVARIANTS is set.
Draw order
Every primitive carries a DrawOrder (u32); higher draws later. The order comes from an R-tree
over the inks inserted so far this frame (crates/zgui-scene/src/order/tree.rs):
let mut tree = BoundsTree::new();
assert_eq!(tree.insert(rect(0.0)), 1);
assert_eq!(tree.insert(rect(5.0)), 2, "overlaps the first, so it sorts above it");
assert_eq!(tree.insert(rect(100.0)), 1, "disjoint, so it reuses the low order");insert returns one more than the highest order among everything the rectangle intersects. Nodes
cache their subtree's highest order, and MAX_CHILDREN is 12. Two properties follow, and the rest
of the crate relies on them:
- Disjoint content reuses low orders, so a page of non-overlapping boxes draws in few calls.
- Equal order implies no overlap. Two primitives at the same order cannot cover the same pixel, so their sequence is free and is used for batching.
The tree compares device rectangles. Each primitive's ink is recorded in the space it is drawn in and placed through that space's matrix before insertion. A primitive in a transformed subtree is ordered against what it covers on screen, not against an untransformed box.
Two shortcuts reduce the number of queries without breaking the second property:
- Runs. A line of text is a few dozen glyphs side by side.
Scene::begin_runorders them against each other locally, files the whole run as one block above whatever its union overlaps, and gives each glyph the block's base plus its local order. That is one query instead of one per glyph. - Replayed chunks. A recorded chunk carries its members' orders relative to each other. A replay
asks the tree once where the chunk now sits (
insert_block) and adds the stored offsets.
Both can only err upwards: a primitive may take a higher order than its own query would give, never an order equal to something it overlaps.
insert_above_all ignores overlap and takes the global maximum plus one. Group markers use it, so
unrelated content cannot land inside the group's range. set_order_floor raises the minimum for
later inserts; a closing marker sets it to its own order plus one.
Draw order does not decide CSS painting order. Painting order comes from the sequence in which the walk emits primitives.
The stacking-order walk
A document is painted as a forest of stacking contexts, each established by a box with a
z-index, a transform, opacity below one, or a similar property. Inside a stacking context,
children are painted in the passes of CSS 2.1 Appendix E: negative stacking children, block
backgrounds, floats, inline content, positioned and zero-index children, positive stacking children.
// crates/zgui-paint/src/walk/stacking.rs
pub trait Visitor {
/// Asked once per child before it is ranked. Returning `false` drops its subtree.
fn descends(&mut self, store: &LayoutStore, key: BoxKey) -> bool { true }
/// Called on the way in. Returning `false` skips the box's subtree.
fn enter(&mut self, store: &LayoutStore, key: BoxKey) -> bool;
/// Called on the way out, only for a box whose `enter` returned `true`.
fn leave(&mut self, store: &LayoutStore, key: BoxKey);
}walk reads each box's layout child list, keeps the children that descends accepts, and only then
ranks them by (level, z_index, document position) with a stable sort. Ranking is the expensive
part, so a damaged corner of a long list ranks only the few rows it touches. The order of the kept
children is the same as a full sort would give. enter and leave are separate because a group
must open before its subtree and close after it, and an outline is drawn after the descendants it
sits over (Appendix E step ten).
For every box it reaches, the walk:
- Tests the subtree in
descends, before the box is ranked. If the damage misses the union of its fragments'subtree_ink(plus caret and selection marks), the subtree is counted as skipped and dropped. - Lowers the style with
PaintStyleCache::lower. The result is memoised on the identity of the shared computed-value groups, so a thousand identical buttons lower a handful of paint styles. - Applies running animations to a copy of the lowered style, because the cached entry is shared.
- Decides isolation:
None,Folded(alpha)orTarget. It opens a group or pushes a backdrop if needed. - Pushes the stacks: folded alpha, target opacity, text decorations and the text fill ramp.
- Paints each fragment, by replay or by encoding.
A subtree whose folded opacity is zero is refused before anything is pushed, with no style lookups, ink tests or child walk.
One fragment emits, in order (crates/zgui-paint/src/walk/order.rs):
- outer shadows;
- background, then border;
- inset shadows;
- content: glyphs, an image, drawings, a scrollbar part;
- after the box's descendants, its outline.
Groups and the opacity fold
Blend modes, filters, explicit isolation, clip-path and 3D transforms always need a group target.
Opacity does not, as long as no two primitives of the subtree overlap: multiplying the alpha into
each primitive's paint gives identical pixels at no cost. That decision is made over the fragment
tree's ink during layout, not over what a frame emitted, so a frame that painted half a subtree
gets the same answer as one that painted all of it.
Group markers are never culled, by clips or by damage. Half a pair would leave a target open.
Culling against damage
Damage is the set of device rectangles a frame must redraw. Everything outside it still holds
the previous frame's pixels. A DamageSet holds up to MAX_DAMAGE = 6 pairwise-disjoint rectangles,
or a "full" flag. How damage is collected and merged, mostly by layout's fragment diff, is covered in
Invalidation and damage.
The cull tests intersection, not a dirty bit. The renderer clears each damage rectangle before redrawing it, so everything that touches one must be emitted, whether it changed or not.
| Where | Tested | Saves |
|---|---|---|
Visitor::descends | Union of the subtree's ink, plus caret and selection marks | A whole subtree in constant time. A hover over a thousand-row table costs the rows near the pointer. |
Painter::paint | One fragment's cull_rect: its ink plus any read extent | One fragment. Its children are still visited, because they can paint outside it. |
Scene::push_* | The primitive's ink against same-space clip links | One primitive. |
Growing the damage before the walk
Some fragments read pixels they do not write: blur, drop-shadow filters and backdrop-filter.
Before the walk, zgui_paint::expand grows the damage over a registry of exactly those fragments:
// crates/zgui-paint/src/damage/accumulate.rs
pub const FULL_DAMAGE_SHARE: f64 = 0.5;
pub fn expand(store: &LayoutStore, damage: &mut DamageSet,
surface: Size<i32, Device>, scale: f32) -> Expansion;One grown rectangle can reach another group's source, so expansion runs to a fixpoint, bounded by the registry's length. It escalates to full damage when the damaged area passes half the surface or the bound runs out.
Expansion must run before the walk, not during or after it:
- Not during. The walk skips clean subtrees on their ink alone. A blurred panel over animating content would be skipped while its source region was cleared.
- Not after. A rectangle added after the walk is cleared and never redrawn.
read_extent_of and cull_rect call the same read_extent function as the expansion, so the region
read and the region repainted always agree.
Recording and replay
Besides the paint-style cache, paint keeps one record per fragment. A paint record owns an
Arc<ChunkPrims>: a self-contained copy of the primitives that fragment encoded. Records are kept
across frames whether or not a frame visits the fragment.
Capture happens before clip culling and draw-order insertion. A replay therefore pushes the complete painting through the current frame's ordinary clip, cull and ordering path, and a fragment can leave a scrollport and come back without a special case. Layout reports fragment retirement explicitly, and generational fragment keys stop a retired record from being matched to a fragment that reuses its slot.
// crates/zgui-paint/src/walk/replay.rs
pub enum Reuse { Encode, Replay(Size<DevicePx, Device>) }Record::revisionis unique per encoding. It gives the renderer's persistent GPU copy an identity that changes when the fragment re-encodes.- A replay offset is measured from the recorded border box, so repeated moves do not accumulate error.
- The record holds references on every clip, paint, shader parameter block, coordinate-system entry and atlas tile its chunk names (each atlas key once). They stay valid until the record is retired or evicted.
The record cache has a 64 MiB budget (PAINT_CHUNK_BYTES). Records selected this frame are pinned,
and the coldest others are evicted first. An evicted fragment's pixels stay in the composed target
until its next damaged visit re-encodes it.
What invalidates a record
Painted is the whole comparison: a Copy + Eq struct whose fields cover everything that can change
the painting without changing anything else in the record.
| Field | Detects |
|---|---|
style, clip, transform | A new lowered style, clip chain or coordinate system. |
transform_hash | A change of scale or rotation under the same SpatialId. Translation is excluded: the renderer places instances through the matrix, so a recording replays under any translation of its space. |
custom | A custom element repainting in place. |
pointer | An effect that reads the pointer position. Zero for every other box. |
content | An image or drawing source changing behind a stable node. |
cut | A line's cut or ellipsis moving inside an unmoved line box. |
scale | Device-scale-dependent bytes after a display-scale change. |
decorations, text_fill | text-decoration or a text gradient set on an ancestor. |
anim | Animations overriding a shared lowered style. Without it, the first frame of an animation would replay for its whole length. |
alpha | An ancestor's folded opacity. Stored as f32 bits so the struct is Eq. |
subpixel | Whether text runs keep per-channel coverage. Opening a group target or panning by a fraction of a pixel changes it without moving any other field. |
corners | Corner radii, which the lowered style does not hold. |
highlights | Caret and selection bands on a line. Without it, a blinking caret freezes. |
Replaying a chunk
pub fn replay_chunk(&mut self, chunk: &ChunkPrims, by: Size<DevicePx, Device>, source: u64) -> Range<u32>;- One order query per chunk. The chunk's members were ordered against each other at capture and have moved rigidly since, so the tree is asked once where the chunk sits and each member keeps its offset.
- Bounds are translated by
by. Shadows translate their element and shape rectangles, backdrops translate bounds and source, and marks move their origin. Clips the encoding created are re-interned at the moved position under the same id. - The offset is recorded.
Scene::chunk_offsetsrecords each replayed chunk's offset, so a renderer that keeps the chunk resident applies the offset in the shader and uploads nothing (see GPU tables and buffers). The frame arrays still hold the translated bytes for a renderer that does not. - Vector items replay at any offset. A moved item keeps its path and moves its placement and
ink, so the rasteriser's encoding stays valid (
VectorReplaysMoved).
SVG drawings and inherited paint
zgui-svg reads SVG into a flat list of Shapes (path, fill, stroke, clips), expressed in kurbo,
peniko and zgui's Color. Group transforms are applied to geometry, group opacity is folded into
paint, and clip paths are carried per shape, so a consumer walks a list instead of a tree.
Unsupported features (text, images, masks, filters, blend modes, patterns) are counted in
Unsupported, not silently dropped. Because group opacity is folded per shape, overlapping children
of a translucent group show through each other.
To tell an icon from a logo, the parser reads the document twice with two different root color
values. A paint that changes with the root colour uses currentColor and becomes Ink::Inherited.
Anything else keeps its own colour. If the two parses do not line up, the first is used unchanged:
an icon may stop following its element's colour, but a logo never loses its colours.
Inherited paint comes from the element, not from fill, because the SVG paint properties are not
part of zgui's cascade:
| Source | Meaning |
|---|---|
color | The default fill, so .icon:hover { color: … } themes an icon with no extra mechanism. |
--zgui-fill, --zgui-stroke, --zgui-stroke-width | Inherited overrides for fill, stroke and stroke width. |
Vector routes
Vector content (an icon, an SVG document, a canvas scene) can always be drawn by the general GPU path rasteriser. That rasteriser is expensive to build and needs a scratch pass per batch, so paint tries cheaper routes first and keeps the general route for what nothing else can draw. The application side is in Vector and canvas; how the general route is rasterised is in the renderer.
Paint chooses a route per shape (crates/zgui-paint/src/emit/vector/document.rs), trying the routes
in the order of this table. The first route that accepts the shape wins. Before that, the CPU layer
route may take a whole drawing at once.
| Route | Becomes | Takes | Counter |
|---|---|---|---|
| CPU layer (per drawing) | One ColorSprite from the image pool, or one per 512-pixel tile | A drawing with no series whose gradients or clips would otherwise need the general route, under a positive axis-aligned scale | vector_route_layer |
| Analytic | Quads | Parts made of circles, axis-aligned ellipses, rectangles, rounded rectangles or straight strokes, at most 256 shapes, kept two device pixels apart, under an axis-aligned uniform scale | vector_route_analytic |
| Marks | One MarkItem per part | The same shapes in any number (up to 2²²), overlapping or not, under any affine transform | vector_route_marks |
| Path glyphs | One glyph mark per part | Many copies of a few small repeated outlines (a scatter of triangles or stars) | vector_route_path_glyphs |
| Atlas mask | One MonoSprite per part | Small solid shapes with no clip of their own, under a scale, mirror or quarter turn | vector_route_mask |
| General | VectorItems | Everything else | vector_route_general |
When recognition fails on a large path (64 or more elements), the route remembers the decline for a
few frames, so the same path is not analysed again every frame. VectorTierChanges counts parts
that switch between the mask route and a decline.
Path-space retention
Every route reads the shape in its own space. The fit that places it in the fragment (a canvas view transform, a view-box fit) travels beside it:
- Shared parsed drawings. A source text is parsed once for every element that draws it, and the
same
Arcpaths are returned while the text stays the same (content/vectors/mod.rs). A new box is a new fit, never a new path. - General items in path space.
VectorItem::pathis the source path andVectorItem::placementis the fit. A scroll, a move or a new fit changes only the affine, so the rasteriser's content-keyed encoding stays valid. Equal drawings share one encoding. - Recognition caches. Analytic and marks recognition run on the source path under any uniform fit and are cached by path, so a pan or zoom recognises nothing again. A rotation or stretch places the path and recognises it again.
- Payloads in source units. A mark payload stays in the units it was recognised in, and the item
maps it with
axesandorigin. A pan or zoom keeps the same payload allocation and uploads nothing.
Analytic shapes
A part whose subpaths are all recognised as rectangles, rounded rectangles, circles, axis-aligned ellipses or straight strokes is drawn as quads with no raster at all. The quad shader antialiases the edges.
- Shapes must be two device pixels apart. A path paints each pixel once however many subpaths cover it; quads painted one by one do not.
- The transform must be axis-aligned with the same scale on both axes (at least 0.75), because the quad shader measures one pixel as the larger of its two axis steps.
- A shape clip is accepted only if it lowers to the quad's inline clip tests.
Marks
A mark is one item over a shared payload. It has one draw order, one clip, one paint and one ink rectangle, so a hundred thousand circles are one primitive.
// crates/zgui-scene/src/prim/marks.rs
pub struct MarkPayload {
pub discs: Vec<[f32; 4]>, // [cx, cy, outer radius, inner radius]
pub boxes: Vec<MarkBox>, // rounded, bordered rectangles
pub vertices: Vec<[f32; 2]>, // polylines; NaN separates runs
pub glyphs: Vec<[u32; 4]>, // a tile table, then one instance per glyph
}- Mapping. Payload coordinates map to local space by
MarkItem::axes, thenorigin. A replay that moves the item adds tooriginand leaves the payload untouched, so every copy shares it. Payloads are shared by identity (Arc) and uploaded once per allocation. - Separate or unioned. Shapes at least two device pixels apart are painted one by one. When they
come closer, the item is flagged
MarkFlags::UNION: the renderer sums their coverage into a bin and paints through the sum once, which matches the union a path paints. A part where an overlap could be a hole is declined, because a union would fill it. - Partial draws.
MarkItem::firstlets an item draw part of a large payload. A long canvas series uses this to draw only the chunks near the view.
Union bins are planned in zgui-scene (crates/zgui-scene/src/pass/marks.rs), like vector
passes, and the renderer executes the plan:
pub struct MarkPlan {
pub bins: Vec<MarkBin>, // one per union item that reaches the damage
pub pages: u32,
pub extent: Size<i32, Device>,
pub overflow: Vec<MarkBin>, // items that share the spare page
pub full_damage: bool,
}Bins are shelf-packed onto single-channel pages no larger than the surface, up to MAX_PAGES = 8.
Items past that take turns on one spare page. A bin outside every group holds only the damaged part
of its item. A renderer that widens a frame to full damage plans the bins again with
Scene::plan_marks. MarksUnionBins counts planned bins and MarksPayloadBytes counts payload
uploads. How marks are drawn covers the renderer side.
Canvas series (line and scatter plots over data arrays) are lowered to marks too. Their payloads are built once per data allocation, on a worker thread for large series, and reduced per device column on request. See Vector and canvas for the API.
Path glyphs
A shape made of many copies of a few small outlines is drawn like text. Each distinct outline is
rasterised once per device scale into the Mono atlas, as a sheet of sixteen quarter-pixel phase
cells (PHASES = 16). Each copy draws the cell nearest its own position, so a pan rasterises nothing
and a position is off by at most an eighth of a pixel. The result is a mark whose payload holds a
tile table and one anchor per copy. Copies that overlap are unioned like any mark.
| Requirement | Limit |
|---|---|
| Subpaths | At least 8. |
| Distinct outlines | At most 16 among the first 64, and at most one eighth of all, never more than 64. |
| Cell size | At most 64 device pixels. |
| Paint | Solid, with no clip or dash. |
| Transform | Keeps the axes. |
| Per frame | At most 64 new sheets covering 1 Mi texels. |
Overlapping copies under the even-odd rule, copies that wind both ways, and outlines that cross
themselves take another route, because an overlap could be a hole. PathGlyphTilesRasterised
counts phase cells.
Atlas masks
A small solid shape is rasterised on the CPU into a monochrome atlas tile and drawn as a
MonoSprite. A mask must be at most 1024 × 256 pixels and 64 KiB of texels. The shape must have no
clip of its own and no gradient, and the transform must keep the axes (any scale, mirror or quarter
turn; a stroke needs equal scales). The tile is keyed by geometry, not colour, so recolouring or
moving an icon reuses it.
Two rules stop the route from thrashing (crates/zgui-paint/src/content/vectors/mask.rs):
- Volatility. A shape whose mask request changed in three of the last four frames is volatile. Once the general rasteriser is built, volatile shapes are declined, because a raster per frame costs more than the GPU route. While it is not built, only volatile shapes with more than 4096 segments are declined, because declining one builds it.
- Per-frame budgets. With the general rasteriser built, a frame rasterises at most 32 new masks
covering 128 Ki texels, and the rest are declined. While it is not built, volatile shapes may
rasterise up to 256 new masks covering 1 Mi texels per frame. Cache hits cost nothing.
VectorMaskMissesandVectorMaskBudgetOverflowcount misses and refusals.
CPU layers
A drawing that would need the general route only because of a gradient or a clip can be rasterised
whole on the CPU into one premultiplied tile of the image pool and drawn as one ColorSprite
(crates/zgui-paint/src/content/vectors/layer.rs). The sprite takes the box's clip, transform and
opacity like an image, so a scroll or a move costs nothing, and a static page of such drawings never
builds the general rasteriser.
- Scale. The transform must be a scale with two positive axes. A tile is exact for one scale and one sixteenth-pixel phase. During a zoom, the tile of the nearest scale (from half to twice) is stretched as a provisional sprite, and the drawing is rasterised again three frames after it holds still. Two scales of a source are kept.
- Budget. New rasters are budgeted by estimated cost: about 8 ms per frame while the general rasteriser is not built. Once it exists, at most three new layers in about 2 ms per frame, and a new drawing waits for two stable frames unless it is cheap. A drawing that does not fit is deferred at most two frames. A drawing rasterised three times in 30 frames is drawn shape by shape for the next 30.
- Tiles. A layer larger than 2048 pixels on a side or 4 MiB is cut into tiles of 512 pixels, one sprite each. Only the tiles a frame redraws are rasterised, plus neighbours while budget remains, so an edit of one canvas shape re-rasterises only the tiles it touches.
- Memory. Layers are budgeted at four surfaces of RGBA8, between 16 and 128 MiB per window
(
VectorLayersBudget).
A deferred or provisional layer owes a frame: the window absorbs its rectangle into the next frame's
damage and requests that frame. Counters: vector_layers_rasterised, vector_layers_provisional,
vector_layers_deferred, vector_layers_demoted, vector_layer_tiles_rasterised and
vector_layer_bytes_live.
The general route
Everything else becomes VectorItems: the source path, its placement, fill and stroke paints, the
clip chain, any document clip paths, and two inks. ink is the device rectangle (transform applied),
which the pass planner and the rasteriser use. local_ink is in the subtree's own space, which the
clip cull reads. Fully transparent items, and items under a transform with no area, are dropped
before planning, so they never build the rasteriser.
A path rasteriser interpolates gradient stops in sRGB. A gradient on vector content in another interpolation space is therefore resolved into sRGB stops, close enough that the straight segments stay within one 8-bit step of the true curve.
Vector passes
A path rasteriser cannot draw into the middle of a frame: it submits its own commands and clears
whatever it targets. General items are therefore rasterised into scratch, and one ordinary draw
composites each pass back at the right point in the batch stream. Those points are decided in
zgui-scene, as a pure function of the display list and the damage, so a pass count is a property
of the scene that a test can assert without a device.
The rules, from crates/zgui-scene/src/pass/mod.rs:
| Rule | |
|---|---|
| 0 | An item with a clip the vector scene cannot express (a sampled mask) ends the current pass and gets a pass of its own. This is the only case where a clip costs a pass. |
| 1 | Drop every item whose ink misses the damage. This is the only damage cull on this path. |
| 2 | Sweep the remaining items in emission order into the current pass. The pass clip is the deepest chain all its items share; each item's remainder is its residual clip. |
| 3 | Start a new pass when a non-vector primitive emitted after an item already in the pass overlaps that item's own ink. |
| 4 | A group boundary ends the pass, because a composite is recorded into whichever target is open. |
| 5 | If a finished pass's single composite cannot sit above all its items and below everything painted over any of them, it becomes one pass per item. |
All rectangles are compared on the device. A vector item's device ink is recomputed from
local_ink under the matrices this frame draws with, and every other primitive's ink is placed
through its own space, so a replayed item inside a moved subtree is planned where it now is. The
overlap tests use a 64-pixel grid over the pass's inks (pass/cells.rs), so planning stays close to
linear in the number of items.
pub struct PlannedPass {
pub items: Range<usize>,
pub region: Rect<i32, Device>, // 16-pixel aligned, clamped to the surface
pub clip: ClipId, // the deepest chain every item applies
pub instanced: bool, // true only if no two items overlap
pub composite_order: DrawOrder, // the highest order among the items
pub clamped: bool, // the region was cut to the damage
pub overhangs: bool, // the items' ink goes past the surface edge
}composite_orderis the highest order in the pass, not the last item's, because draw order comes from overlap and does not rise with emission order.instancedis decided over whole-pixel inks, because two items that are disjoint only within a pixel would still blend that pixel twice.- Cut to damage. A pass outside every group has its region cut to the damage's bounding box, so
a pass the damage only partly reaches rasterises only that part. A pass inside a group keeps its
whole region, because a group target is drawn whole. If the frame has a backdrop filter (which
widens what the renderer redraws), passes are not cut. A renderer that widens a frame draws the
passes from
Scene::plan_uncut_passes. clampedandoverhangstell the rasteriser to clip the pass to its region, because passes share scratch layers.
Overlap policies
Overlap selects how rule 3 is read:
pub enum Overlap { PerItemInk /* default */, BoundingBox, BoundingBoxOrderBlind, Never }The default is exact. The weaker readings are kept as selectable policies so the difference stays measurable. The last column is the pass count on a test dashboard of twenty charts, each with a legend drawn over it:
| Policy | Tests a new primitive against | Passes on the dashboard |
|---|---|---|
PerItemInk | The ink of each earlier item in the pass | 1 |
BoundingBox | The bounding box of the items accumulated before it | 4 |
BoundingBoxOrderBlind | The bounding box of the whole pass, ignoring emission order | 20 |
Never | Nothing. Measures per-item compositing only; not a valid policy. |
PerItemInk is exact rather than conservative: the scratch is cleared to transparent, and
compositing a transparent texel leaves the destination unchanged.
VelloPasses and VectorClipLayers count passes and residual clip layers. ScenePassPlan::warning
fires at PassWarning::THRESHOLD = 4 passes on a partial frame. How a rasteriser packs passes into
scratch and splits a large frame into rounds is on
the renderer page.
A renderer must not re-derive any of this. It executes the plan: one VectorPass per
PlannedPass, in order. A plan that dropped a pass would draw every later composite from the wrong
pass.
Batching
Scene::finish(&damage) plans the vector passes and mark bins, then sorts one remap list per kind.
The primitive arrays stay in insertion order; the renderer reads them through the sorted remap lists.
| Arrays | Sort key |
|---|---|
| quads, shadows, decorations, marks, externals, backdrops | (order, 0, 0) |
| shaded rectangles | (order, shader, parameter block) |
| the three sprite arrays | (order, tile.texture, tile.tile) |
| groups | (order, u32::from(!is_start), 0) |
| vectors | unsorted; the pass plan orders their composites |
The sprite tie-break is free because equal order implies no overlap. Clustering by texture lets a batch run until the texture actually changes. The group key sorts a start before an end at the same order, so a degenerate empty group comes out start-first.
Scene::batches() then yields one Batch per draw call. It panics if finish has not run.
// crates/zgui-scene/src/batch/mod.rs
pub enum Batch {
Quads(Range<usize>),
Shaded { shader: ShaderId, params: ShaderParamsSlot, range: Range<usize> },
Shadows(Range<usize>),
Decorations(Range<usize>),
MonoSprites { texture: u32, range: Range<usize> },
SubpixelSprites { texture: u32, range: Range<usize> },
ColorSprites { texture: u32, range: Range<usize> },
Marks(Range<usize>),
Vector(usize), // an index into the pass plan
External(usize),
Backdrop(usize),
Group(usize),
}A batch is a range of sorted remap positions, which the renderer resolves to its persistent
arenas. The iterator merges the thirteen kinds by (DrawOrder, PrimitiveKind) and yields the longest
run it can take from one kind before another kind's next primitive must come first. Finding the two
lowest waiting keys is a linear scan; the second lowest is the bound the run may not cross.
| What ends a batch | Why |
|---|---|
| Another kind's next primitive sorts lower. | Draw order is a total order. |
| A sprite reaches a different texture. | A draw call binds one texture. |
| A shaded rectangle reaches a different effect or parameter block. | A draw binds one pipeline and one block. |
| A group marker. | The renderer changes target exactly there. |
| A vector composite, an external quad or a backdrop. | Each has its own bindings. |
Measured costs
From docs/performance.md, written by cargo xtask perf:
| Scenario | Primitives emitted | Primitives culled | Bounds-tree inserts |
|---|---|---|---|
| idle | 0 | 0 | 0 |
| hover-storm | 9 975 | 241 916 | 9 975 |
| scroll | 50 668 | 21 378 | 50 668 |
| cold-start | 1 101 | 5 224 | 1 101 |
| kitchen-sink | 129 834 | 205 348 | 130 194 |
A hover storm culls about twenty-four primitives for each one it emits; hover.primitives_emitted
is 41.56 per frame against a ceiling of 200. Bounds-tree inserts track what a frame emits, not the
document size. A scroll frame that brings a row into view emits about 404 primitives, which is the
visible port.
Counter::PrimitivesEmitted is incremented in Scene::push_*, and Counter::PrimitivesCulled by
clip refusals and skipped subtrees. PaintReport carries the same figures for one walk.
PaintReport::assert_emission_complete fails, naming the first fragment the damage reaches that
nothing was emitted for. It panics if PaintInput::record_emitted was off, so it cannot pass
vacuously.
Next
The renderer
The Renderer and VectorRaster contracts, the wgpu backend, partial redraw and presentation.
Invalidation and damage
The dirty bits, how they are cleared, and where damage comes from.
Vector and canvas
Drawing icons, documents and canvas scenes from an application.
Caches
Every cache in the pipeline, what invalidates it, and what a miss costs.
The text engine
How a text node becomes glyphs and then pixels: the four text seams, the font libraries behind them, flattening, shaping, line breaking, glyph rasterisation, and every cache on the way.
The renderer
The Renderer and VectorRaster contracts, the wgpu backend, frame planning, partial redraw, presentation, atlases, and how each visual feature is drawn.