Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

test(glyphgrid): pin the cross-module contracts; atlas layout single-sourced + degenerate-page guard

enes897518b893d6
diff --git a/src/renderer/glyphgrid/atlas.test.ts b/src/renderer/glyphgrid/atlas.test.ts
index 5d49fdb8c..78bb6431b 100644
--- a/src/renderer/glyphgrid/atlas.test.ts
+++ b/src/renderer/glyphgrid/atlas.test.ts
@@ -46,6 +46,32 @@ describe('GlyphAtlas', () => {
expect(rect).toEqual({ u0: 0.1, v0: 0, u1: 0.2, v1: 0.2 })
})
+ it('slotRect is correct past row 0', () => {
+ const atlas = new GlyphAtlas(fakeRasterizer(10, 20), 100) // 10 cols × 5 rows
+ expect(atlas.slotRect(10)).toEqual({ u0: 0, v0: 0.2, u1: 0.1, v1: 0.4 })
+ })
+
+ it('slotRect agrees with the shader uv derivation for every interesting slot', () => {
+ // gl-webgl2's shader computes: cols = floor(sizePx/cellW); cellUv = [cellW/sizePx, cellH/sizePx];
+ // origin = (slot % cols, floor(slot / cols)) * cellUv. This test IS the tie between the two
+ // copies of the layout math — if either side changes (atlas padding, page metrics), it fails.
+ const atlas = new GlyphAtlas(fakeRasterizer(10, 20), 100)
+ const cols = Math.floor(100 / 10)
+ const cellUv = [10 / 100, 20 / 100]
+ for (const slot of [0, 1, cols - 1, cols, cols + 1, atlas.capacity - 1]) {
+ const u0 = (slot % cols) * cellUv[0]
+ const v0 = Math.floor(slot / cols) * cellUv[1]
+ expect(atlas.slotRect(slot)).toEqual({ u0, v0, u1: u0 + cellUv[0], v1: v0 + cellUv[1] })
+ }
+ })
+
+ it('a degenerate page (sizePx < cellW) yields blank slots and a zero rect, never NaN', () => {
+ const atlas = new GlyphAtlas(fakeRasterizer(10, 20), 5)
+ expect(atlas.capacity).toBe(0)
+ expect(atlas.glyphFor(0x41, false, false)).toBe(0)
+ expect(atlas.slotRect(0)).toEqual({ u0: 0, v0: 0, u1: 0, v1: 0 })
+ })
+
it('sets dirty on new glyphs and clears on demand', () => {
const atlas = new GlyphAtlas(fakeRasterizer(), 100)
expect(atlas.dirty).toBe(false)
diff --git a/src/renderer/glyphgrid/atlas.ts b/src/renderer/glyphgrid/atlas.ts
index 5f8a25aec..005976ae7 100644
--- a/src/renderer/glyphgrid/atlas.ts
+++ b/src/renderer/glyphgrid/atlas.ts
@@ -11,7 +11,12 @@ export interface GlyphRasterizer {
export class GlyphAtlas {
private slots = new Map<string, number>()
- private nextSlot = 1 // slot 0 is permanently blank
+ /** Slot 0 is permanently blank and is never handed to the rasterizer: every space, every
+ * unknown code point and every cell of a not-yet-uploaded GPU buffer samples it. Its
+ * BLANKNESS is a contract on raster.ts — the page starts fully transparent and nothing may
+ * ever draw at (0,0) — not something this file can enforce, so the two must change together.
+ * If ink ever lands there, every space on the canvas grows a glyph. */
+ private nextSlot = 1
private dirtyFlag = false
constructor(
@@ -39,16 +44,35 @@ export class GlyphAtlas {
return cols * rows
}
+ /** Row-major top-left of a slot, in page PIXELS — the single copy of the layout math.
+ *
+ * Both consumers must agree exactly: `glyphFor` uses it to place the ink and `slotRect` to
+ * derive the uv rect the shader samples. Two hand-written copies would drift the moment
+ * either the page metrics or the padding changed, and the symptom is every glyph rendering
+ * a fraction of a cell off — not a crash, just permanently wrong text.
+ *
+ * On a DEGENERATE page (`sizePx < cellW`, so `cols === 0`) `slot % 0` is NaN, which would
+ * propagate silently into the uv rect. Capacity is 0 there, so no slot is ever allocated and
+ * the origin is simply (0,0) — the blank slot. */
+ private cellXY(slot: number): { x: number; y: number } {
+ const cols = Math.floor(this.sizePx / this.rasterizer.cellW)
+ if (cols <= 0) return { x: 0, y: 0 }
+ return {
+ x: (slot % cols) * this.rasterizer.cellW,
+ y: Math.floor(slot / cols) * this.rasterizer.cellH
+ }
+ }
+
glyphFor(code: number, bold: boolean, italic: boolean): number {
if (code === 0x20 || code === 0) return 0
const key = `${code}|${bold ? 1 : 0}${italic ? 1 : 0}`
const hit = this.slots.get(key)
if (hit !== undefined) return hit
+ // Covers the degenerate page too (capacity 0 → 1 >= 0), so nothing is ever rasterized onto a
+ // page that has no room for a single cell.
if (this.nextSlot >= this.capacity) return 0 // page full — degrade to blank, never throw
const slot = this.nextSlot++
- const cols = Math.floor(this.sizePx / this.rasterizer.cellW)
- const x = (slot % cols) * this.rasterizer.cellW
- const y = Math.floor(slot / cols) * this.rasterizer.cellH
+ const { x, y } = this.cellXY(slot)
this.rasterizer.draw(code, bold, italic, x, y)
this.slots.set(key, slot)
this.dirtyFlag = true
@@ -56,9 +80,10 @@ export class GlyphAtlas {
}
slotRect(slot: number): { u0: number; v0: number; u1: number; v1: number } {
- const cols = Math.floor(this.sizePx / this.rasterizer.cellW)
- const x = (slot % cols) * this.rasterizer.cellW
- const y = Math.floor(slot / cols) * this.rasterizer.cellH
+ // A degenerate page has no sampleable area at all: return the ZERO rect rather than let the
+ // division produce NaN, which the shader would turn into undefined texture reads.
+ if (this.capacity <= 0) return { u0: 0, v0: 0, u1: 0, v1: 0 }
+ const { x, y } = this.cellXY(slot)
return {
u0: x / this.sizePx,
v0: y / this.sizePx,
diff --git a/src/renderer/glyphgrid/cells.test.ts b/src/renderer/glyphgrid/cells.test.ts
index 236c03a1c..225c844fd 100644
--- a/src/renderer/glyphgrid/cells.test.ts
+++ b/src/renderer/glyphgrid/cells.test.ts
@@ -26,6 +26,22 @@ describe('glyphgrid cells', () => {
expect(readCell(buf, 1)).toEqual({ glyph: 0, fg: 0, bg: 0, flags: 0 })
})
+ it('pins the absolute byte order and lane positions', () => {
+ // The GL binding cannot re-derive either of these: gl-webgl2 binds lane 0..3 as one uvec4
+ // instanced attribute and the fragment shader unpacks each color with `c & 255u` as RED.
+ // A round-trip test would still pass if BOTH sides were swapped, so the absolute values are
+ // pinned here — this is the only place the wire format is stated, not merely echoed.
+ expect(packColor(0x12, 0x34, 0x56, 0x78)).toBe(0x78563412)
+ const buf = new Uint32Array(CELL_STRIDE)
+ const fg = packColor(1, 2, 3, 255)
+ const bg = packColor(9, 8, 7, 255)
+ writeCell(buf, 0, 4242, fg, bg, FLAG_BOLD)
+ expect(buf[0]).toBe(4242)
+ expect(buf[1]).toBe(fg)
+ expect(buf[2]).toBe(bg)
+ expect(buf[3]).toBe(FLAG_BOLD)
+ })
+
it('a packed color equals the lane it was written to, even with alpha >= 128', () => {
// `0xff << 24` is negative in JS, so an unguarded packColor returns a signed int while the
// Uint32Array lane reads back unsigned — the two would never compare equal, and a
diff --git a/src/renderer/glyphgrid/engine.test.ts b/src/renderer/glyphgrid/engine.test.ts
index 577aff013..e85177fe1 100644
--- a/src/renderer/glyphgrid/engine.test.ts
+++ b/src/renderer/glyphgrid/engine.test.ts
@@ -45,6 +45,10 @@ function fakeGL(): GlyphGL & {
},
uploadRows: (id, firstRow, rowCount, _cols, cells) => {
uploads.push([id, firstRow, rowCount])
+ // Recorded in the SAME log as the draws: a grid's rows must reach its GPU buffer before
+ // the drawGrid that reads them, or that frame draws the previous contents. Two separate
+ // logs could not express the interleaving, which is the only thing being asserted.
+ drawn.push(`UP:${id}`)
// COPIED: the engine hands over a live subarray VIEW of its CPU-side cells, so a later
// updateRow would rewrite what an earlier assertion is still looking at.
uploaded.push(new Uint32Array(cells))
@@ -130,6 +134,19 @@ describe('GlyphGridEngine', () => {
expect(e.drawOrder()).toEqual(['in'])
})
+ it('culls against the PADDED rect: a grid whose plate still overlaps the viewport is drawn', () => {
+ const e = new GlyphGridEngine(fakeGL(), atlas())
+ e.setViewport(100, 100, 1)
+ e.setCamera({ x: 0, y: 0, zoom: 1 })
+ // Cells start exactly at the right viewport edge (x=100, visible world rect is 0..100), so
+ // the character matrix alone is off-screen — but the plate is the node's opaque BODY and
+ // extends padPx further left, into view. Culling on the cell rect would leave a visible strip
+ // of the node body unpainted at every viewport edge.
+ e.register(spec('padded', 100, 0, { padPx: 8 }))
+ e.register(spec('bare', 100, 0, { padPx: 0 }))
+ expect(e.drawOrder()).toEqual(['padded'])
+ })
+
it('draws in z order ascending, ties by registration order', () => {
const e = new GlyphGridEngine(fakeGL(), atlas())
e.setViewport(800, 600, 1)
@@ -149,7 +166,25 @@ describe('GlyphGridEngine', () => {
e.register(spec('top', 10, 5))
e.register(spec('offscreen', 5000, 1))
e.frame()
- expect(gl.drawn).toEqual(['BEGIN', 'grid@0,0', 'grid@10,0', 'END'])
+ // The upload pass runs to completion BEFORE beginFrame — see the upload-before-draw test.
+ expect(gl.drawn).toEqual(['UP:bottom', 'UP:top', 'BEGIN', 'grid@0,0', 'grid@10,0', 'END'])
+ })
+
+ it('a visible dirty grid uploads its rows before the draw that reads them', () => {
+ const gl = fakeGL()
+ const e = new GlyphGridEngine(gl, atlas())
+ e.setViewport(800, 600, 1)
+ e.setCamera({ x: 0, y: 0, zoom: 1 })
+ const h = e.register(spec('a', 0, 0, { rows: 3 }))
+ e.frame() // consume the registration upload
+ gl.drawn.length = 0
+ h.updateRow(1, rowOf(2))
+ e.frame()
+ // Ordering, not mere presence: drawGrid reads the grid's own GPU buffer, so an upload landing
+ // after it would paint the PREVIOUS frame's rows and only correct itself on the next damage —
+ // a one-frame-stale terminal that no per-call assertion can see.
+ expect(gl.drawn.indexOf('UP:a')).toBeGreaterThanOrEqual(0)
+ expect(gl.drawn.indexOf('UP:a')).toBeLessThan(gl.drawn.indexOf('grid@0,0'))
})
it('updateRow rejects a wrong-length row', () => {
@@ -240,6 +275,10 @@ describe('GlyphGridEngine', () => {
// Stronger than "before the first drawGrid": beginFrame pushes uAtlasCols/uAtlasCell from
// the values uploadAtlas stored, so an upload landing after it would leave frame 1 sampling
// slot 0 everywhere and the uniforms permanently one upload stale.
+ // Self-sufficiency first: indexOf returns -1 for a MISSING entry, and -1 is less than every
+ // real index — so without this the two comparisons below would pass just as happily if the
+ // atlas upload had never been recorded at all.
+ expect(gl.drawn.indexOf('ATLAS')).toBeGreaterThanOrEqual(0)
expect(gl.drawn.indexOf('ATLAS')).toBeLessThan(gl.drawn.indexOf('BEGIN'))
expect(gl.drawn.indexOf('ATLAS')).toBeLessThan(gl.drawn.indexOf('grid@0,0'))
expect(a.dirty).toBe(false)
diff --git a/src/renderer/glyphgrid/engine.ts b/src/renderer/glyphgrid/engine.ts
index e7b180e9f..273d75ac5 100644
--- a/src/renderer/glyphgrid/engine.ts
+++ b/src/renderer/glyphgrid/engine.ts
@@ -196,16 +196,22 @@ export class GlyphGridEngine {
this.dirty = true
}
- /** Visible grid ids in draw order (z ascending, ties by registration order). Pure. */
+ /** Visible grid ids in draw order (z ascending, ties by registration order). Pure.
+ *
+ * Culled against the PADDED rect, not the character matrix: a grid draws its opaque plate
+ * (the node body, `padPx` world units wider on every side) before its cells, so a grid whose
+ * cells have just left the viewport may still owe it a visible strip of body. Culling on the
+ * cell rect alone would pop that strip away at every viewport edge — and, worse, would skip
+ * the plate that occludes whatever sits underneath it. */
drawOrder(): string[] {
const visible: Rect = visibleWorldRect(this.camera, this.viewW, this.viewH)
return [...this.grids.values()]
.filter((g) =>
rectsIntersect(visible, {
- x: g.originX,
- y: g.originY,
- w: g.cols * g.cellW,
- h: g.rows * g.cellH
+ x: g.originX - g.padPx,
+ y: g.originY - g.padPx,
+ w: g.cols * g.cellW + 2 * g.padPx,
+ h: g.rows * g.cellH + 2 * g.padPx
})
)
.sort((a, b) => a.z - b.z || a.seq - b.seq)
diff --git a/src/renderer/glyphgrid/gl-webgl2.ts b/src/renderer/glyphgrid/gl-webgl2.ts
index 1ccec7811..f435888aa 100644
--- a/src/renderer/glyphgrid/gl-webgl2.ts
+++ b/src/renderer/glyphgrid/gl-webgl2.ts
@@ -1,6 +1,7 @@
import type { Camera } from './camera'
import { CELL_STRIDE, unpackColor } from './cells'
import type { GlyphGL, GridDrawParams } from './gl'
+import { plateRectDevice } from './plate'
const VERT = `#version 300 es
// One instance per CELL. Two triangles from gl_VertexID (0..5), no vertex buffer.
@@ -95,38 +96,19 @@ export function createWebgl2GL(canvas: HTMLCanvasElement): GlyphGL | null {
* is what makes it occlude rather than tint whatever was drawn beneath. Callers therefore pass
* an OPAQUE bgColor; a translucent one would punch the frame's alpha down to that value.
*
- * Two constraints live here and are the easy things to get wrong:
- * - The scissor rect is in DEVICE pixels (the drawing buffer), never CSS px — hence the
- * `* dpr`, using the ratio captured at `resize` rather than reading devicePixelRatio now.
- * - GL's scissor origin is BOTTOM-LEFT while world/CSS Y grows downward, so Y is FLIPPED
- * against the drawing buffer height: `y = deviceH - (top + height)`.
+ * The rect math (camera projection, dpr, the Y flip, clamping) lives in the pure
+ * `plate.ts` — it is unit-tested there, since none of it is observable through a GL mock.
+ * What stays here is the GL state dance around it.
*/
// An arrow const, not a `function` declaration: declarations hoist above the `if (!gl) return`
// narrowing, so `gl` would be `WebGL2RenderingContext | null` inside the body.
const drawPlate = (g: GridDrawParams): void => {
- // world → screen (CSS px): screen = world * zoom + pan, exactly as the vertex shader does.
- const leftCss = (g.originX - g.padPx) * cam.zoom + cam.x
- const topCss = (g.originY - g.padPx) * cam.zoom + cam.y
- const wCss = (g.cols * g.cellW + 2 * g.padPx) * cam.zoom
- const hCss = (g.rows * g.cellH + 2 * g.padPx) * cam.zoom
- // CSS px → DEVICE px.
- const left = Math.round(leftCss * dpr)
- const top = Math.round(topCss * dpr)
- const width = Math.round(wCss * dpr)
- const height = Math.round(hCss * dpr)
- // Y FLIP: GL scissor origin is bottom-left.
- const bottom = deviceH - (top + height)
- // Clamp to the viewport: a scissor rect is allowed to hang outside it, but clamping keeps
- // the width/height non-negative after the origin is pushed to 0 (a negative extent is a
- // GL_INVALID_VALUE, and an off-screen grid should simply skip the plate).
- const x0 = Math.max(0, left)
- const y0 = Math.max(0, bottom)
- const x1 = Math.min(deviceW, left + width)
- const y1 = Math.min(deviceH, bottom + height)
- if (x1 <= x0 || y1 <= y0) return
+ // Null = the plate covers no pixel of the drawing buffer; skip it entirely.
+ const r = plateRectDevice(g, cam, dpr, deviceW, deviceH)
+ if (!r) return
const c = unpackColor(g.bgColor)
gl.enable(gl.SCISSOR_TEST)
- gl.scissor(x0, y0, x1 - x0, y1 - y0)
+ gl.scissor(r.x, r.y, r.w, r.h)
gl.clearColor(c.r / 255, c.g / 255, c.b / 255, c.a / 255)
gl.clear(gl.COLOR_BUFFER_BIT)
// Disabled again immediately: the scissor is global GL state, and leaving it on would clip
diff --git a/src/renderer/glyphgrid/plate.test.ts b/src/renderer/glyphgrid/plate.test.ts
new file mode 100644
index 000000000..7adb88b36
--- /dev/null
+++ b/src/renderer/glyphgrid/plate.test.ts
@@ -0,0 +1,82 @@
+import { describe, expect, it } from 'vitest'
+import type { GridDrawParams } from './gl'
+import { plateRectDevice } from './plate'
+
+/** A 5×2 grid of 8×20 cells → a 40×40 world rect at the given origin. */
+const grid = (over: Partial<GridDrawParams> = {}): GridDrawParams => ({
+ id: 'a',
+ cols: 5,
+ rows: 2,
+ cellW: 8,
+ cellH: 20,
+ originX: 10,
+ originY: 10,
+ bgColor: 0,
+ padPx: 0,
+ ...over
+})
+
+const CAM = { x: 0, y: 0, zoom: 1 }
+
+describe('plateRectDevice', () => {
+ it('flips Y against the drawing buffer height', () => {
+ // Derived by hand. World rect (10,10)-(50,50) at zoom 1, pan 0 → the same in CSS px. At
+ // dpr 1 that is device px too. GL's scissor origin is BOTTOM-left, so the rect's device y is
+ // the distance from the buffer's BOTTOM to the rect's BOTTOM edge: 100 - 50 = 50.
+ expect(plateRectDevice(grid(), CAM, 1, 200, 100)).toEqual({ x: 10, y: 50, w: 40, h: 40 })
+ })
+
+ it('scales into device pixels by dpr, not by devicePixelRatio at call time', () => {
+ // Same world rect at dpr 2 against a 400×200 drawing buffer: every extent doubles and the
+ // flip is taken against the DEVICE height (200 - (20 + 80) = 100), never the CSS one.
+ expect(plateRectDevice(grid(), CAM, 2, 400, 200)).toEqual({ x: 20, y: 100, w: 80, h: 80 })
+ })
+
+ it('applies the camera: pan then zoom, exactly as the vertex shader does', () => {
+ // screen = world * zoom + pan. Origin (10,10) at zoom 2 pan (5,5) → CSS (25,25), extent 80.
+ // Flip: 200 - (25 + 80) = 95.
+ expect(plateRectDevice(grid(), { x: 5, y: 5, zoom: 2 }, 1, 400, 200)).toEqual({
+ x: 25,
+ y: 95,
+ w: 80,
+ h: 80
+ })
+ })
+
+ it('expands the rect by padPx on every side, in world units', () => {
+ // padPx 5 grows the 40×40 rect to 50×50 and moves its top-left to (5,5).
+ // Flip: 100 - (5 + 50) = 45.
+ expect(plateRectDevice(grid({ padPx: 5 }), CAM, 1, 200, 100)).toEqual({
+ x: 5,
+ y: 45,
+ w: 50,
+ h: 50
+ })
+ })
+
+ it('clamps to the drawing buffer instead of returning a negative origin or extent', () => {
+ // Origin (-10,-10): the rect hangs off the left and the top. A scissor rect may legally sit
+ // outside the viewport, but pushing the origin to 0 without shrinking the extent would move
+ // the far edge — and a NEGATIVE extent is a GL_INVALID_VALUE.
+ // Visible CSS span: x 0..30, y 0..30 → device y from 100-30 = 70, height 30.
+ expect(plateRectDevice(grid({ originX: -10, originY: -10 }), CAM, 1, 200, 100)).toEqual({
+ x: 0,
+ y: 70,
+ w: 30,
+ h: 30
+ })
+ })
+
+ it('is null when the rect is entirely off-screen', () => {
+ // Null, not a zero-area rect: the caller must SKIP the clear, and a {w:0,h:0} scissor would
+ // still cost the state changes around it.
+ expect(plateRectDevice(grid({ originX: 500 }), CAM, 1, 200, 100)).toBeNull()
+ expect(plateRectDevice(grid({ originY: -500 }), CAM, 1, 200, 100)).toBeNull()
+ })
+
+ it('is null when the rect touches an edge without covering a pixel', () => {
+ // A 40-wide rect at x=-40 ends exactly at x=0: it shares an edge with the viewport and
+ // covers zero pixels, so it must be null rather than a zero-width scissor.
+ expect(plateRectDevice(grid({ originX: -40 }), CAM, 1, 200, 100)).toBeNull()
+ })
+})
diff --git a/src/renderer/glyphgrid/plate.ts b/src/renderer/glyphgrid/plate.ts
new file mode 100644
index 000000000..703ef60e1
--- /dev/null
+++ b/src/renderer/glyphgrid/plate.ts
@@ -0,0 +1,60 @@
+import type { Camera } from './camera'
+import type { GridDrawParams } from './gl'
+
+/** A rectangle in DEVICE pixels with a BOTTOM-LEFT origin — GL's scissor convention, not the
+ * browser's. Deliberately not camera.ts's `Rect`: that one is world-space and top-left, and
+ * sharing the type is exactly how a Y-flip gets forgotten. */
+export interface DeviceRect {
+ x: number
+ y: number
+ w: number
+ h: number
+}
+
+/**
+ * The occlusion plate's scissor rect: the grid's world rect expanded by `padPx`, projected
+ * through the camera and clamped to the drawing buffer. Pure, so the four coordinate hops below
+ * are testable without a GL context — which is the point of the extraction, since a Y-flip or a
+ * missing `* dpr` is invisible in a code review and obvious in a unit test.
+ *
+ * Returns null when the rect covers no pixel of the drawing buffer: the caller must SKIP the
+ * clear entirely. A clamped-empty rect is not merely wasteful — a NEGATIVE scissor extent is a
+ * GL_INVALID_VALUE, and clamping the origin to 0 without shrinking the extent would silently
+ * move the rect's far edge.
+ *
+ * The hops, in order:
+ * 1. world → screen (CSS px): `screen = world * zoom + pan`, exactly as the vertex shader does.
+ * 2. CSS px → DEVICE px via `dpr` — the ratio captured at `resize`, never `devicePixelRatio`
+ * read at call time (they disagree the moment a window crosses monitors mid-frame).
+ * 3. Y FLIP: GL's scissor origin is bottom-left while world/CSS Y grows downward, so the
+ * device y is measured from the buffer's BOTTOM: `deviceH - (top + height)`.
+ * 4. Clamp to [0, deviceW] × [0, deviceH].
+ */
+export function plateRectDevice(
+ g: GridDrawParams,
+ cam: Camera,
+ dpr: number,
+ deviceW: number,
+ deviceH: number
+): DeviceRect | null {
+ // (1) world → screen (CSS px).
+ const leftCss = (g.originX - g.padPx) * cam.zoom + cam.x
+ const topCss = (g.originY - g.padPx) * cam.zoom + cam.y
+ const wCss = (g.cols * g.cellW + 2 * g.padPx) * cam.zoom
+ const hCss = (g.rows * g.cellH + 2 * g.padPx) * cam.zoom
+ // (2) CSS px → DEVICE px.
+ const left = Math.round(leftCss * dpr)
+ const top = Math.round(topCss * dpr)
+ const width = Math.round(wCss * dpr)
+ const height = Math.round(hCss * dpr)
+ // (3) Y FLIP.
+ const bottom = deviceH - (top + height)
+ // (4) Clamp.
+ const x0 = Math.max(0, left)
+ const y0 = Math.max(0, bottom)
+ const x1 = Math.min(deviceW, left + width)
+ const y1 = Math.min(deviceH, bottom + height)
+ // `<=`, not `<`: a rect that only shares an edge with the viewport covers zero pixels.
+ if (x1 <= x0 || y1 <= y0) return null
+ return { x: x0, y: y0, w: x1 - x0, h: y1 - y0 }
+}
diff --git a/src/renderer/glyphgrid/raster.ts b/src/renderer/glyphgrid/raster.ts
index 0487d9fc5..f99404307 100644
--- a/src/renderer/glyphgrid/raster.ts
+++ b/src/renderer/glyphgrid/raster.ts
@@ -13,8 +13,9 @@ export interface RasterFont {
* Two invariants this file must not break:
* 1. The canvas is left fully TRANSPARENT except where a glyph is drawn — the atlas's slot 0
* (the cell at 0,0) is permanently blank and is what every space/unknown glyph samples. So
- * never clear/fill the canvas here: GlyphAtlas never asks for slot 0, and a fill would put
- * ink under it.
+ * never clear/fill the WHOLE canvas here: GlyphAtlas never asks for slot 0, and a
+ * full-surface fill would put ink under it. A slot-granular clear (evicting one glyph to
+ * reuse its cell) is a legitimate future need and does not violate this.
* 2. Every draw is CLIPPED to its cell rect, so a glyph wider than cellW (a CJK cell, an
* overhanging italic) cannot bleed into the neighbouring slot's texels. */
export function createCanvasRasterizer(