RediWM is a Wayland compositor written in Zig (OpenGL ES) that includes everything in one process
Rendering implementation notes
Read when changing projection, the output pass, glass, window shapes, chrome, capture, or retained panel painting. General rules remain in AGENTS.md; test commands are in TESTING.md.
- Colours are premultiplied in wlroots rects; theme colours are
col.Straight. Create/recolour rects only viacol.createRect/setRect, pack pixels withStraight.argb()/Premul.argb(). Symptom of a mix-up: white border edges. - Window frames are shapes (
docs/plans/scene-graph-stage4.md).Toplevel.applyShapegivesframe_treeone rounded clip carrying the ring colour (× window opacity); the pass composites the ring over the body, so something must be drawn under every ring pixel: the titlebarChromeBuffer(a plain band) on top and the threeframe_fillsrects beside and below the client.chrome.outerBorder()resolveswindow_border_widthfor the outer ring.chrome.frameBorder()addswindow_inner_border_widthfor client offsets, side fills, footer and resize/layout geometry. The optional inner ring (toplevel/inner_border.zig) paintswindow_inner_borderin four disjoint, memoized perimeter strips, below corner accents and above the clipped client corners. Its width is reserved even when its color is transparent. Corner rasters and titlebar memos include it for live reloads.shadow_tree, the resize-grab tree and every xdg popup carrysetTreeUnclipped(a new node that hangs outside the window needs it too). The shadow is analytic (setTreeShadowonshadow_tree, the CPU formula's smoothstep); its leafshadow_nodehas no buffer and carries footprint, opacity and input only, so the projection damages that footprint itself. CSD windows have no shape and keep theborder_rectsoutline. A theme'swindow_shapemakes the clip a polygon (ui/window_shape.zig, anchored points resolved against the live frame inToplevel.shapePolygon):radiiis then unused,rediwm_clip.insetis how far in the largest rectangle wholly inside it lies (the opaque cover, the plain core and the damage rim all use it), and the shader'ssdpolywalks the same edges asrediwm_sd_polygon; keep the two, andwindow_shape.sdPolygon, in step. Anything that mirrorsrediwm_pass_shapein Zig must mirror it whole. The polygon distance is compiled only into two extra programs (POLY,shaped_poly[_external],rediwm_scene_renderer_enable_polygons), built on the firstchrome.polygonsReady()from layout code (never inside a pass); a polygon draw before that fails the pass, so draw and capture code readschrome.polygons. Circular switcher clips use an analytic annularsectorinstead of polygon vertices (scene_sector.h/.zig): CPU picking and GPU coverage share its exact distance function. The same optional programs render sectors; scale radii uniformly and transform the center/axis with the output, so fractional snapping never stretches a circle. Sector clips claim no opaque rectangular core. A positivesector_texture_heightopts a preview into radial texture mapping: the source's top follows the outer arc, and its full height extends inward. Changing that height damages the whole sector. Ordinary shapes keep rectangular sampling; the radial path removes the output transform from source UVs because the sector axis already carries it. Several buffers can share one radial image (a switcher thumbnail's surface and its subsurfaces): each covers the sector's box and names its part withBuffer.setSectorRect(fractions of the image), which reaches the shader assector_texture_rect; nothing of that draw, ring included, lands outside its part. The taskbar uses the same clip on its tree (Taskbar.applyClip) with its raster outer edge left hard (taskbar/shape.zigpaintPolygon: row spans, a distance only near an edge). A changed clip damages its rim itself (projection_resolve.c); a point the shape cuts away is declined by the pick (pick_world), so the pick falls to what is below. Window capture draws the client alone and is handed the shape explicitly. The ring is onemax(1, round(border * scale)). Without the shaped programs (chrome.shapesfalse) windows are square, with no ring or shadow. Optionalwindow_corner_*accents are four small immutable rasters owned by the frame tree (toplevel/corner_accents.zig), following that same shape just inside its ring. They decline input, inherit opacity, and memoize scale and theme; maximized/fullscreen/undecorated windows hide them. Each corner is keyed by the part of the outline it shows (window_shape.localKey), so a resize or a size animation moves the four nodes and paints none of them.window_corner_resize_extraadds length during a live resize grab. The normal chrome frame tick eases that extension in/out, including split resizes; it stops scheduling when settled. Begin/end wake the tick even without a client commit, and pending configure acknowledgements do not prolong the feedback. The grow/return durations and easing arewindow_corner_resize_ms,window_corner_restore_ms, andwindow_corner_resize_ease; live timing edits continue from the displayed length.window_corner_insetadds space beyond the frame ring, andwindow_corner_end_paddingshortens the stroke endpoints.window_corner_casing(_width)wraps the stroke in a band of its own (the stroke moves in by its width,reachcovers it);window_corner_cut_endscuts both at 45 degrees with the outer edge longest, the casing's sharp tip capped at its end.window_title_plate*paints an angled title label, limits text before its slant and leaves grouped tabs to their existing painter. Its tokens belong inTitlebarMemoso reload and partial title repaint agree. Plate inset, bevel, height-relative slant, control gap and text padding are theme tokens too; narrow frames clamp opposing cuts to prevent crossed edges. With a polygon outline (ChromeState.outline) the plate is also cut by the outline moved in by the inset (chrome_plate.distance), so chamfers keep an even margin; a step meant to hug the plate's slant has to be placed in px inwindow_shapeto match the plate's width and slant. The memo keys only the outline's edges near the plate, and not the frame's height: a window resized in height alone keeps its titlebar raster. Rasters that follow a distance field (the plate, the accents) ask for a distance only where an edge can be: a distance changes by at most one per pixel, sowindow_shape.saturatedRunpixels after one are as covered as it is. A per-pixel polygon distance over a whole box costs milliseconds. The plate's coverage is the same for every titlebar of one theme, scale and outline, sochrome_plate.maskkeeps the last one: a resize or a title change reads it and works out no distance.Toplevel.shapePolygonkeeps the parsed outline and the last frame's polygon: every client commit asks for it several times.resolveFittingrejects fixed cuts that overtake their opposite anchors on small frames, before clamping can turn a raised step backwards; the clip, plate, shadow and corner accents then share the rounded-rectangle fallback.chrome_control_right_padandchrome_control_offset_ymove the shared control rectangles, including painting and input.controlInsetsmeasures the polygon at the shifted control rows while leaving the icon centred.chrome_button_bevelcuts the moving control highlight and is part of the titlebar memo.start_menu_beveluses the shared beveled widget raster for both Start panels; their blur rounds inside the cut, and a beveled footer draws only its separator so it cannot leave square edges outside the panel. - Buffer size ≠ scene size at fractional scale (
round(len*s)vsround((off+len)*s)-round(off*s)). Chrome/panel buffers filter bilinearly: never re-raster per device-grid phase (ChromeBuffer.createcosts 2–8 ms). - Nested sessions never set buffer scale: judge sharpness at
REDIWM_SCALE=1, and debug visuals with IPC screenshots/buffer dumps, not hostgrim. Brief vanishing after a startup scale mismatch is not a bug. - GLES can NULL
wlr_scene_buffer.bufferafter upload (the texture stays): persist raster sizes. - Owned buffer destructors call
base.finish()before freeing or pooling. wlroots 0.20 delegates the destroy event and addon cleanup to the producer. Skipping it leaves consumers attached to freed storage (or the old incarnation of a pooled buffer). This applies to chrome, images, taskbar, panels and desktop tiles;zig build test-lifecyclechecks finalization after the last lock. - Glass is drawn by the output pass (stage 5,
docs/plans/scene-graph-stage5.md).glass.conly registers effects: a bufferless node just below its target, to which resolve gives the target's box. When an effect re-blurs,scene_output_draw.credirects the pass (rediwm_scene_pass_begin_backdrop) and draws the items below it into an image a quarter of the logical size of its padded extent (target + 3 sigma), blurs that and composites it through the shape (shaped program mode 3), keeping one blur per effect and output. A kept blur is re-taken only when a damage event from a leaf painted below the effect, or damage no event explains, meets that extent, or the region or sigma changed. Only leaves that put pixels on screen have damage events (an input-only node must not, or it reads as a change below glass), and the software cursor's damage counts as explained. Damage a new kind of change through the projection's events or it counts as below (safe, slower). Collect keeps items an effect reads even where surfaces above hide them (reads). Holds (a dragged titlebar at ≥ 0.98 opacity, camera motion) carry the blur and re-take it once released. Per output, so mixed scales stay idle (glass_hold.py); attribution is checked byglass_reblur.py. - Owned GL beside wlroots: wlroots draws with client-side vertex arrays, so
any GL work of ours must put
GL_ARRAY_BUFFER(and the rest of the state it touched) back before a wlroots pass runs, asscene_pass_leave()does; a quad VBO left bound makes wlroots draw half a rectangle. A border is drawn in the same pass as its body, never over it (docs/plans/scene-graph-stage1.md). - Commit only via
Output.commitFrameState, neverwlr_output_commit_state.commitIsRedundantskips commits with no damage, colour change, attach-render lock or cursor change; register anything new there. Skipped frames get callbacks fromvblank_timer, never immediately. A client commit with nothing new (no attach, no damage, no remap) changes no node and schedules no frame: its callbacks go through the scene'sframe_callbackshook (Output.frameCallbacksWanted), which arms the timer at idle unless a frame is coming anyway. Keep it that way: a setter or listener that reports a change on every commit brings back a whole frame per commit. Build output state throughServer.buildOutputState, including capture: the owned GLES2 pass is the only presenter (the session requires GLES2) and keeps one swapchain damage history. It reads graph geometry and the buffers, textures and wait points of the source nodes (docs/plans/scene-graph-stage3.md,scene-graph-stage6.md). - Latches are not frame callbacks.
Output.latch_seqcounts latching deadlines: a successful non-tearing buffer commit incommitFrameState, and thevblank_timerrefresh after a skipped commit (handleVblank). fifo-v1 barriers (fifo.zig) clear only on a latch of the surface's frame-pacing output, never on frame callbacks, which late render sends before it renders. A new commit path must go throughcommitFrameStateor the barrier waits for its forward-progress fallback (two refreshes; therediwm-msg perffifo.latecounter shows it). Releasing a held update applies client state: never from inside the frame or a projection walk (fifo.zigdefers it to an idle callback). - Shapes in the owned pass (
scene_pass.h): a window's rounded clip, ring and shadow arerediwm_scene_pass_add_*_shapedcalls, device pixels, snapped by the caller. The programs cost the driver about 430 KiB (a GL program costs 130-150 KiB whatever its size), soenable_shapesbuilds them on request, never with the renderer; before it a shaped draw fails the pass. Blend NONE is only valid insiderediwm_clip_opaque, minus the ring (scene_output_draw.cdraws a clipped item's ring-free core plain and the rest through the shape). The distance ramp is not area coverage (up to 18 of 208 levels at one pixel of a curved edge): that is expected. - Idle makes no wakeups: timers only for real deadlines, workers signal an
eventfd,
text.applySizeinstead of re-sizing faces, title changes repaint only their span and taskbar chip. Measure with per-thread context switches. - Damage: each reusable shm buffer tracks damage since its own last paint;
never write a busy one.
panel_paint.Backgroundkeeps the last full image (paintIncrementalrepairs; a buffer fromPanelBuffer.createRetainedcarries a stamp, so only what it missed is copied in, and only the damage back out — pass null when drawing over the retained image); widget settersmarkDirty/markPaintDirty, moves damage old and new bounds; convert publish damage at the real raster scale. Compositor-owned world buffers send full damage unless reported (Projection.damageBufferaftersetBuffer, orpresentOwned). Cache keys include visual state, text, geometry and Cairo transform; round globally before subtracting projection group origins. - Projection is resolve, then present (
projection_resolve.c,projection_present.c,scene_graph.h;projection.chas the overview).resolveturns the source tree into typed items (kind, unrounded layout-space edges, composed scale, content) listed in paint order per group and shows nothing;presentrounds once (rediwm_edges_snap, edges not origin+size) and turns what changed into damage events and screen damage. Geometry is derived only inresolve: a new rule (clip, opacity, fractional placement) is a field on the item, not a computation inpresent_leaf. A leaf or group leaves itspaintlist before the head is freed (detach,destroy_group). Buffer identity and damage are read from the source node bypresent, textures, single-pixel colours, wait points and opaque regions by the pass. A tree's rounded clip (rediwm_projection_set_tree_clip) is a field on each item (item.clip), resolved after the tree's own zoom and scale; an xdg popup lives under its parent's tree and must carryrediwm_projection_set_tree_unclipped. - The world has no second tree (
docs/plans/scene-graph-stage6.md). The source tree is disabled, so wlroots computes no outputs, frame callbacks, damage or picks for it; the graph does, with wlroots' own rules on our data. Feedback (rediwm_projection_feedback_*, called by the pass'scollect): per build, the pixels of each client surface that nothing above hides, over every output; an output is active when it shows more than a tenth of that, the primary one shows most (the later wins a tie);outputs_updateandoutput_enter/leavego out on the source buffer, again when an active output's scale, transform or subpixel changed. Frame callbacks of the world come fromServer.sendFrameDone, neverwlr_scene_output_send_frame_donealone; the pass emitsoutput_sampleon the source buffer. A layer-shell surface below the world (background, bottom) is no longer occluded by windows in wlroots' eyes: it keeps frame callbacks while covered. Damage: every change reachesp->pendingthroughdamage_boxand goes to the outputs once, at the end of each sync. A change of what a leaf itself shows is cut to what was visible of it at the last build (l->visible); a move, restyle or removal damages the old box (cut) and the new one; a restack damages what moved (damage_restacked), shadow footprints included; a destroyed node applies at once, because a capture can build before the next sync. A new kind of change that moves no leaf has to damage itself there (clip rims and shadows do). Picks:rediwm_projection_node_at(graph for the world, wlroots for the layout trees), neverwlr_scene_node_aton the root. GLES2 lets go of a plain buffer once uploaded, so "has content" is a buffer, a texture or a single-pixel colour (present_leaf,collect). - The veil (
rediwm_scene_output_set_veil, driven byreveal.zig) is black drawn over every entry and under the software cursor: the session's fade in from black and the greeter's fade out. It exists only on DRM and nested outputs. A change damages the whole output and counts as explained damage, so glass does not re-blur for it; scan-out waits until it is 0. - Client buffers:
wlr_client_buffer_apply_damageworks in place only without extra locks, so mark long-held locks ignorable. v4attach(buffer, 0, 0)still sets OFFSET; only nonzero dx/dy remaps. Don't resend unchangedset_buffer_scale; prefer compositor v5.