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.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(glyphgrid): per-grid GPU buffers, row-range uploads, scissored occlusion plate
enes8e622bf3c0c0
diff --git a/src/renderer/glyphgrid/engine.test.ts b/src/renderer/glyphgrid/engine.test.tsindex 16bed332b..577aff013 100644--- a/src/renderer/glyphgrid/engine.test.ts+++ b/src/renderer/glyphgrid/engine.test.ts@@ -1,13 +1,35 @@import { describe, expect, it, vi } from 'vitest'import { GlyphAtlas } from './atlas'-import { CELL_STRIDE } from './cells'+import { CELL_STRIDE, packColor } from './cells'import { GlyphGridEngine, type GridSpec } from './engine'-import type { GlyphGL, GridDraw } from './gl'+import type { GlyphGL, GridDrawParams } from './gl'-function fakeGL(): GlyphGL & { drawn: string[] } {+/** [id, cols, rows] as passed to createGrid. */+type Created = [string, number, number]+/** [id, firstRow, rowCount] as passed to uploadRows — the row-range damage assertion. */+type Upload = [string, number, number]++function fakeGL(): GlyphGL & {+ drawn: string[]+ created: Created[]+ disposed: string[]+ uploads: Upload[]+ uploaded: Uint32Array[]+ params: GridDrawParams[]+} {const drawn: string[] = []+ const created: Created[] = []+ const disposed: string[] = []+ const uploads: Upload[] = []+ const uploaded: Uint32Array[] = []+ const params: GridDrawParams[] = []return {drawn,+ created,+ disposed,+ uploads,+ uploaded,+ params,resize: vi.fn(),// Recorded in `drawn` too: the atlas upload MUST land before beginFrame (which pushes the// atlas uniforms), let alone before any drawGrid of the same frame — otherwise the shader@@ -15,8 +37,23 @@ function fakeGL(): GlyphGL & { drawn: string[] } {uploadAtlas: vi.fn(() => {drawn.push('ATLAS')}),+ createGrid: (id, cols, rows) => {+ created.push([id, cols, rows])+ },+ disposeGrid: (id) => {+ disposed.push(id)+ },+ uploadRows: (id, firstRow, rowCount, _cols, cells) => {+ uploads.push([id, firstRow, rowCount])+ // 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))+ },beginFrame: () => drawn.push('BEGIN'),- drawGrid: (g: GridDraw & { id?: string }) => drawn.push(`grid@${g.originX},${g.originY}`),+ drawGrid: (g: GridDrawParams) => {+ params.push({ ...g })+ drawn.push(`grid@${g.originX},${g.originY}`)+ },endFrame: () => drawn.push('END'),dispose: vi.fn()}@@ -34,7 +71,7 @@ function loadedAtlas(sizePx = 512, cellW = 7, cellH = 15) {}}-const spec = (id: string, x: number, z = 0): GridSpec => ({+const spec = (id: string, x: number, z = 0, over: Partial<GridSpec> = {}): GridSpec => ({id,cols: 2,rows: 1,@@ -43,9 +80,14 @@ const spec = (id: string, x: number, z = 0): GridSpec => ({originX: x,originY: 0,z,- bgColor: 0+ bgColor: 0,+ padPx: 0,+ ...over})+/** A zeroed row buffer of the right length for a `cols`-wide grid. */+const rowOf = (cols: number): Uint32Array => new Uint32Array(cols * CELL_STRIDE)+describe('GlyphGridEngine', () => {it('an idle engine draws nothing; a dirty grid draws exactly one frame', () => {const gl = fakeGL()@@ -127,17 +169,17 @@ describe('GlyphGridEngine', () => {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), rows: 3 })+ const h = e.register(spec('a', 0, 0, { rows: 3 }))const row = new Uint32Array(2 * CELL_STRIDE)row[0] = 0xaa // row 1, col 0 → cellIndex 2row[CELL_STRIDE] = 0xbb // row 1, col 1 → cellIndex 3h.updateRow(1, row)- let submitted: Uint32Array | null = null- gl.drawGrid = (g) => {- submitted = g.cells- }+ // Cell data reaches the GPU through uploadRows now, not drawGrid. Registration already+ // marked all three rows dirty, so this frame uploads the range [0..2] — i.e. the whole+ // grid, indexed from its origin, which is exactly what the row-major claim is about.e.frame()- const cells = submitted as unknown as Uint32Array+ expect(gl.uploads).toEqual([['a', 0, 3]])+ const cells = gl.uploaded[0]expect(cells[2 * CELL_STRIDE]).toBe(0xaa)expect(cells[3 * CELL_STRIDE]).toBe(0xbb)})@@ -287,6 +329,25 @@ describe('lifecycle hardening', () => {expect(e.frame()).toBe(false)})+ it('a disposed handle never touches the GPU again', () => {+ 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))+ e.frame()+ h.dispose()+ gl.created.length = 0+ gl.uploads.length = 0+ // A resize on a dead handle must not reallocate a GPU buffer for a grid nobody draws, and+ // a late row write must not queue an upload against a disposed id.+ h.resize(9, 9)+ h.updateRow(0, rowOf(2))+ e.frame()+ expect(gl.created).toEqual([])+ expect(gl.uploads).toEqual([])+ })+it('a throwing GL submission does not lose damage', () => {const gl = fakeGL()const e = new GlyphGridEngine(gl, atlas())@@ -301,4 +362,112 @@ describe('lifecycle hardening', () => {;(gl as { beginFrame: unknown }).beginFrame = () => undefinedexpect(e.frame()).toBe(true) // damage was restored, next frame redraws})++ it('a throwing uploadRows keeps the grid range pending', () => {+ 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.uploads.length = 0+ h.updateRow(2, rowOf(2))+ const boom = new Error('context lost mid-upload')+ const ok = gl.uploadRows+ gl.uploadRows = () => {+ throw boom+ }+ expect(() => e.frame()).toThrow(boom)+ gl.uploadRows = ok+ // The range is cleared only AFTER uploadRows returns, so the row that never reached the+ // GPU is still owed — a range dropped here would leave that row stale forever.+ expect(e.frame()).toBe(true)+ expect(gl.uploads).toEqual([['a', 2, 1]])+ })+})++describe('per-grid buffers + row-range damage', () => {+ it('register creates the GPU grid; dispose disposes it', () => {+ const gl = fakeGL()+ const e = new GlyphGridEngine(gl, atlas())+ const h = e.register(spec('a', 0))+ expect(gl.created).toEqual([['a', 2, 1]])+ h.dispose()+ expect(gl.disposed).toEqual(['a'])+ })++ it('a single-row update uploads exactly that row, once', () => {+ 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() // registration uploads all rows once+ gl.uploads.length = 0+ h.updateRow(1, rowOf(2))+ e.frame()+ expect(gl.uploads).toEqual([['a', 1, 1]]) // firstRow 1, rowCount 1 — not the whole grid+ e.frame()+ expect(gl.uploads).toHaveLength(1) // clean → no re-upload+ })++ it('two touched rows coalesce into one contiguous range', () => {+ 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()+ gl.uploads.length = 0+ h.updateRow(0, rowOf(2))+ h.updateRow(2, rowOf(2))+ e.frame()+ // Contiguous-range policy: rows 0 and 2 widen ONE span that swallows the untouched row 1.+ // One slightly-too-wide bufferSubData beats two calls — a terminal's damage is a run.+ expect(gl.uploads).toEqual([['a', 0, 3]])+ })++ it('a hidden grid defers its upload until it becomes visible', () => {+ const gl = fakeGL()+ const e = new GlyphGridEngine(gl, atlas())+ e.setViewport(100, 100, 1)+ e.setCamera({ x: 0, y: 0, zoom: 1 })+ const h = e.register(spec('far', 5000, 0, { rows: 3 }))+ e.frame() // registration dirties the engine, but the grid is culled → nothing uploaded+ expect(gl.uploads).toEqual([])+ h.updateRow(1, rowOf(2))+ e.frame()+ expect(gl.uploads).toEqual([]) // still off-screen: the range persists, un-uploaded+ e.setCamera({ x: -5000, y: 0, zoom: 1 }) // pan it into view+ e.frame()+ // Everything owed since registration, in ONE upload — not one per deferred frame.+ expect(gl.uploads).toEqual([['far', 0, 3]])+ e.frame()+ expect(gl.uploads).toHaveLength(1)+ })++ it('drawGrid receives the plate params (bgColor, padPx) with the grid geometry', () => {+ const gl = fakeGL()+ const e = new GlyphGridEngine(gl, atlas())+ e.setViewport(800, 600, 1)+ e.setCamera({ x: 0, y: 0, zoom: 1 })+ const bg = packColor(20, 20, 24, 255)+ e.register(spec('a', 0, 0, { bgColor: bg, padPx: 8 }))+ e.frame()+ // Exact object: cell DATA must NOT travel here any more — it lives in the grid's own GPU+ // buffer, and re-sending it per draw is the ~90 MB/s this task exists to remove.+ expect(gl.params).toEqual([+ {+ id: 'a',+ cols: 2,+ rows: 1,+ cellW: 10,+ cellH: 20,+ originX: 0,+ originY: 0,+ bgColor: bg,+ padPx: 8+ }+ ])+ })})diff --git a/src/renderer/glyphgrid/engine.ts b/src/renderer/glyphgrid/engine.tsindex 386f49bd2..e7b180e9f 100644--- a/src/renderer/glyphgrid/engine.ts+++ b/src/renderer/glyphgrid/engine.ts@@ -18,6 +18,9 @@ export interface GridSpec {originY: numberz: numberbgColor: number+ /** Padding around the grid rect, in world units, that the opaque plate also covers — the node+ * body's inset. See gl.ts's GridDrawParams. */+ padPx: number}export interface GridHandle {@@ -43,9 +46,21 @@ export interface GridHandle {interface Grid extends GridSpec {/** Row-major: the cell at (row, col) starts at lane `(row * cols + col) * CELL_STRIDE`.- * This is the layout the instanced shader binds — see gl.ts / gl-webgl2.ts. */+ * This is the layout the instanced shader binds — see gl.ts / gl-webgl2.ts.+ *+ * Kept CPU-side even though the GPU now owns a copy: it is the culling-independent source a+ * HIDDEN grid's deferred upload replays from, and the only place a partial row write can be+ * merged before it becomes a range. */cells: Uint32Arrayseq: number // registration order — the z tie-break+ /** Inclusive contiguous damage range; `-1/-1` = clean.+ *+ * CONTIGUOUS BY POLICY: two touched rows widen ONE span that swallows the untouched rows+ * between them. A terminal's damage is overwhelmingly a single run (a scrolled region, an+ * edited line), and one slightly-too-wide bufferSubData is cheaper than N calls plus the+ * bookkeeping to track disjoint runs. */+ dirtyFrom: number+ dirtyTo: number}/**@@ -86,9 +101,14 @@ export class GlyphGridEngine {const grid: Grid = {...spec,cells: new Uint32Array(spec.cols * spec.rows * CELL_STRIDE),- seq: this.seq+++ seq: this.seq++,+ // A brand-new grid owes the GPU every row: createGrid only ZEROES the buffer, and the+ // owner's first writes may land before the first frame.+ dirtyFrom: 0,+ dirtyTo: spec.rows - 1}this.grids.set(spec.id, grid)+ this.gl.createGrid(spec.id, spec.cols, spec.rows)this.dirty = trueconst engine = this// Per-handle, not per-grid: once THIS handle is disposed every mutator below is a silent@@ -105,6 +125,10 @@ export class GlyphGridEngine {if (cells.length !== grid.cols * CELL_STRIDE)throw new Error(`glyphgrid: row length ${cells.length} != ${grid.cols * CELL_STRIDE}`)grid.cells.set(cells, row * grid.cols * CELL_STRIDE)+ // Widen the contiguous range. `dirtyTo` is -1 when clean, so Math.max picks up `row`+ // on its own; `dirtyFrom` needs the explicit clean check (-1 would win a Math.min).+ grid.dirtyFrom = grid.dirtyFrom < 0 ? row : Math.min(grid.dirtyFrom, row)+ grid.dirtyTo = Math.max(grid.dirtyTo, row)engine.dirty = true},setOrigin(x, y) {@@ -131,6 +155,11 @@ export class GlyphGridEngine {grid.cols = colsgrid.rows = rowsgrid.cells = new Uint32Array(cols * rows * CELL_STRIDE)+ // The GPU buffer is sized in cells, so a reshape must REALLOCATE it — bufferSubData+ // against the old size would either overrun or leave a tail of the previous shape.+ engine.gl.createGrid(grid.id, cols, rows)+ grid.dirtyFrom = 0+ grid.dirtyTo = rows - 1engine.dirty = true},dispose() {@@ -138,9 +167,11 @@ export class GlyphGridEngine {// holds whether or not the map still points at this grid.disposed = true// Identity-checked: only drop the map entry if it is still THIS grid, so a stale- // handle can never evict a grid that re-registered under the same id.+ // handle can never evict a grid that re-registered under the same id — nor free the GPU+ // buffer that grid is now drawing from.if (engine.grids.get(grid.id) !== grid) returnengine.grids.delete(grid.id)+ engine.gl.disposeGrid(grid.id)engine.dirty = true}}@@ -190,7 +221,22 @@ export class GlyphGridEngine {return !!this.atlas.source && (this.atlas.dirty || !this.atlasUploaded)}- /** Draw ONE frame if anything is dirty; returns whether it drew. */+ /**+ * Draw ONE frame if anything is dirty; returns whether it drew.+ *+ * The engine-wide `dirty` flag is the frame GATE (does anything need drawing at all); the+ * per-grid ranges decide UPLOAD granularity (how much of each grid reaches the GPU).+ *+ * **Damage-restore policy on a throw.** Two kinds of damage are in play and both must survive+ * a GL call that throws mid-frame (context lost, driver error):+ * - the frame-wide `dirty` flag, cleared up front and restored by the catch below;+ * - each grid's row range, which is cleared ONLY AFTER its `uploadRows` has RETURNED. That+ * ordering is the whole policy: a grid whose upload threw still owes those rows, and a grid+ * whose upload succeeded before the throw does not (its GPU buffer is current, and the+ * redraw the restored `dirty` flag schedules will draw from it). Clearing ranges up front —+ * or in one sweep after the loop — would either lose rows that never reached the GPU or+ * re-upload rows that did.+ */frame(): boolean {const uploadAtlas = this.atlasUploadPending()if (!this.dirty && !uploadAtlas) return false@@ -212,19 +258,43 @@ export class GlyphGridEngine {this.atlas.clearDirty()this.atlasUploaded = true}+ // Computed ONCE and reused by both passes: it allocates, filters and sorts, and the two+ // passes must agree on exactly which grids are visible this frame.+ const order = this.drawOrder()+ // Upload pass. Only VISIBLE grids upload: a hidden grid's range persists un-uploaded until+ // it scrolls back into view, which is what keeps a canvas of fifty terminals from paying+ // for the forty-five nobody can see. Their CPU-side cells stay authoritative, so the+ // deferred upload replays everything owed in one call, not one per skipped frame.+ for (const id of order) {+ const g = this.grids.get(id)+ if (!g || g.dirtyFrom < 0 || g.dirtyTo < g.dirtyFrom) continue+ const rowLanes = g.cols * CELL_STRIDE+ this.gl.uploadRows(+ g.id,+ g.dirtyFrom,+ g.dirtyTo - g.dirtyFrom + 1,+ g.cols,+ // A VIEW, not a copy — the GL layer hands it straight to bufferSubData.+ g.cells.subarray(g.dirtyFrom * rowLanes, (g.dirtyTo + 1) * rowLanes)+ )+ // Cleared only now that the upload has returned — see the damage-restore policy above.+ g.dirtyFrom = -1+ g.dirtyTo = -1+ }this.gl.beginFrame(this.camera)- for (const id of this.drawOrder()) {+ for (const id of order) {const g = this.grids.get(id)if (!g) continuethis.gl.drawGrid({- cells: g.cells,+ id: g.id,cols: g.cols,rows: g.rows,cellW: g.cellW,cellH: g.cellH,originX: g.originX,originY: g.originY,- bgColor: g.bgColor+ bgColor: g.bgColor,+ padPx: g.padPx})}this.gl.endFrame()diff --git a/src/renderer/glyphgrid/gl-webgl2.ts b/src/renderer/glyphgrid/gl-webgl2.tsindex 2d06bda65..1ccec7811 100644--- a/src/renderer/glyphgrid/gl-webgl2.ts+++ b/src/renderer/glyphgrid/gl-webgl2.ts@@ -1,6 +1,6 @@import type { Camera } from './camera'-import { CELL_STRIDE } from './cells'-import type { GlyphGL, GridDraw } from './gl'+import { CELL_STRIDE, unpackColor } from './cells'+import type { GlyphGL, GridDrawParams } from './gl'const VERT = `#version 300 es// One instance per CELL. Two triangles from gl_VertexID (0..5), no vertex buffer.@@ -66,21 +66,82 @@ export function createWebgl2GL(canvas: HTMLCanvasElement): GlyphGL | null {return loc}const aCellLoc = gl.getAttribLocation(program, 'aCell')- const cellBuf = gl.createBuffer()+ /** One GPU buffer PER GRID, so a change costs only the rows that changed (bufferSubData)+ * instead of re-uploading every visible grid's whole cell array into one shared buffer. */+ const grids = new Map<string, { buf: WebGLBuffer; cols: number; rows: number }>()const atlasTex = gl.createTexture()let atlasCols = 1let atlasCellUv: [number, number] = [0, 0]let view: [number, number] = [1, 1]+ /** Stored at resize because the plate's scissor rect is in DEVICE pixels and needs the+ * drawing buffer's height to flip Y — neither is derivable from the CSS-px viewport alone. */+ let dpr = 1+ // Seeded from the canvas so a plate drawn before the first resize() still clamps against the+ // real drawing buffer instead of a 1x1 placeholder.+ let deviceW = canvas.width+ let deviceH = canvas.height+ /** The camera of the frame in flight — the plate rect is computed on the CPU (world → screen),+ * so drawGrid needs it. */+ let cam: Camera = { x: 0, y: 0, zoom: 1 }gl.useProgram(program)gl.enable(gl.BLEND)gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA)+ /**+ * The occlusion plate: a scissored `clear` of the grid rect expanded by `padPx` world units.+ *+ * A clear, not a blended quad, on purpose — it WRITES the colour (blending is bypassed), which+ * 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)`.+ */+ // 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+ const c = unpackColor(g.bgColor)+ gl.enable(gl.SCISSOR_TEST)+ gl.scissor(x0, y0, x1 - x0, y1 - y0)+ 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+ // the next grid's cells (and the next frame's full-surface clear in beginFrame).+ gl.disable(gl.SCISSOR_TEST)+ }+return {- resize(w, h, dpr) {- canvas.width = Math.round(w * dpr)- canvas.height = Math.round(h * dpr)+ resize(w, h, ratio) {+ canvas.width = Math.round(w * ratio)+ canvas.height = Math.round(h * ratio)view = [w, h]+ dpr = ratio+ deviceW = canvas.width+ deviceH = canvas.heightgl.viewport(0, 0, canvas.width, canvas.height)},uploadAtlas(source, sizePx, cellW, cellH) {@@ -91,7 +152,44 @@ export function createWebgl2GL(canvas: HTMLCanvasElement): GlyphGL | null {atlasCols = Math.floor(sizePx / cellW)atlasCellUv = [cellW / sizePx, cellH / sizePx]},+ createGrid(id, cols, rows) {+ // Re-creating under a live id is the RESIZE path: drop the old buffer first, or every+ // reshape leaks one buffer for the life of the context.+ const prev = grids.get(id)+ if (prev) gl.deleteBuffer(prev.buf)+ const buf = gl.createBuffer()+ if (!buf) {+ grids.delete(id)+ return+ }+ gl.bindBuffer(gl.ARRAY_BUFFER, buf)+ // Size-only overload: allocates the storage zero-filled, so a grid drawn before its first+ // uploadRows samples slot 0 (the atlas's permanently blank glyph) rather than garbage.+ gl.bufferData(gl.ARRAY_BUFFER, cols * rows * CELL_STRIDE * 4, gl.DYNAMIC_DRAW)+ grids.set(id, { buf, cols, rows })+ },+ disposeGrid(id) {+ const g = grids.get(id)+ if (!g) return+ gl.deleteBuffer(g.buf)+ grids.delete(id)+ },+ uploadRows(id, firstRow, rowCount, cols, cells) {+ const expected = rowCount * cols * CELL_STRIDE+ // Throw rather than let bufferSubData run short/long: the offset below is computed from+ // firstRow, so a mismatched length silently scribbles across the neighbouring rows.+ if (cells.length !== expected)+ throw new Error(`glyphgrid: rows length ${cells.length} != ${expected}`)+ const g = grids.get(id)+ // No buffer = a grid disposed between the engine's upload and this call. Nothing to write.+ if (!g) return+ gl.bindBuffer(gl.ARRAY_BUFFER, g.buf)+ gl.bufferSubData(gl.ARRAY_BUFFER, firstRow * cols * CELL_STRIDE * 4, cells)+ },beginFrame(camera: Camera) {+ // COPIED, not aliased: the plate math reads this during the drawGrid calls that follow,+ // and a caller mutating its own camera object mid-frame would move grids apart.+ cam = { ...camera }gl.clearColor(0, 0, 0, 0)gl.clear(gl.COLOR_BUFFER_BIT)gl.useProgram(program)@@ -102,16 +200,26 @@ export function createWebgl2GL(canvas: HTMLCanvasElement): GlyphGL | null {gl.uniform2f(u('uAtlasCell'), atlasCellUv[0], atlasCellUv[1])gl.uniform1i(u('uAtlas'), 0)},- drawGrid(g: GridDraw) {- // g.bgColor is deliberately NOT read here: in Phase 0 every cell paints its own opaque- // bg lane in the fragment shader, so a separate background quad would only add overdraw.- // The field is consumed in Phase 1, where the quad also covers the grid's padding/border- // (the area outside cols*rows) and is what makes the painter's-algorithm occlusion total.+ drawGrid(g: GridDrawParams) {+ const grid = grids.get(g.id)+ // Never drawn without its own buffer: an unregistered id would otherwise draw whatever+ // buffer happened to be bound from the previous grid.+ if (!grid) return++ // --- (1) the plate: an opaque scissored clear of the grid rect expanded by padPx. It is+ // drawn BEFORE this grid's cells and AFTER everything below it in z, so painter's order+ // gives total occlusion of overlapping terminals with no depth buffer.+ drawPlate(g)++ // --- (2) the cells, instanced from the grid's own buffer.gl.uniform2f(u('uGridOrigin'), g.originX, g.originY)gl.uniform2f(u('uCell'), g.cellW, g.cellH)gl.uniform1f(u('uCols'), g.cols)- gl.bindBuffer(gl.ARRAY_BUFFER, cellBuf)- gl.bufferData(gl.ARRAY_BUFFER, g.cells, gl.DYNAMIC_DRAW)+ gl.bindBuffer(gl.ARRAY_BUFFER, grid.buf)+ // The attribute pointer captures the buffer bound AT THE MOMENT of the call — it is+ // per-bind state, not program state. With one buffer per grid every drawGrid rebinds, so+ // the pointer MUST be re-set here; hoisting it out of the loop would make every grid draw+ // the cells of whichever grid was bound when it last ran.gl.enableVertexAttribArray(aCellLoc)// 4 uint lanes, CELL_STRIDE * 4 bytes apart — this MUST mirror cells.ts one-to-one.gl.vertexAttribIPointer(aCellLoc, 4, gl.UNSIGNED_INT, CELL_STRIDE * 4, 0)@@ -122,7 +230,8 @@ export function createWebgl2GL(canvas: HTMLCanvasElement): GlyphGL | null {/* single-pass for now; flush point reserved for Phase 1 layering */},dispose() {- gl.deleteBuffer(cellBuf)+ for (const grid of grids.values()) gl.deleteBuffer(grid.buf)+ grids.clear()gl.deleteTexture(atlasTex)gl.deleteProgram(program)}diff --git a/src/renderer/glyphgrid/gl.ts b/src/renderer/glyphgrid/gl.tsindex a414fd8ba..b050a1487 100644--- a/src/renderer/glyphgrid/gl.ts+++ b/src/renderer/glyphgrid/gl.ts@@ -1,12 +1,17 @@import type { Camera } from './camera'-/** One grid submitted for drawing: the packed cell buffer plus where/how big it sits in world- * space. `cells` is laid out exactly as cells.ts writes it (cols*rows*CELL_STRIDE uint32- * lanes, [glyph, fg, bg, flags]) — the GL implementation binds those lanes as instanced- * vertex attributes, so the two files change together. */-export interface GridDraw {- /** cols*rows*CELL_STRIDE uint32 lanes, layout per cells.ts */- cells: Uint32Array+/** Per-draw parameters for one grid: where/how big it sits in world space, plus the plate.+ *+ * Cell DATA deliberately does NOT travel here — it lives in the grid's own GPU buffer, created+ * by `createGrid` and updated by `uploadRows`. Phase 0 re-sent every visible grid's whole cell+ * array on any change (~90 MB/s under the Phase-1b load of one busy terminal among fifty); the+ * per-grid buffer means a change costs exactly the rows that changed.+ *+ * Index mapping, unchanged and shared with cells.ts: `cellIndex = row * cols + col`, each cell+ * CELL_STRIDE uint32 lanes ([glyph slot, fg, bg, flags]). The GL implementation binds those+ * lanes as instanced vertex attributes, so the two files change together. */+export interface GridDrawParams {+ id: stringcols: numberrows: number/** cell size in world units (CSS px at zoom 1) */@@ -15,25 +20,44 @@ export interface GridDraw {/** world position of the grid's top-left corner */originX: numberoriginY: number- /** packColor() — the opaque background quad (occlusion!). See the note in gl-webgl2.ts's- * drawGrid: Phase 0 paints each cell's own bg in the fragment shader, so this field is- * accepted but only CONSUMED IN PHASE 1 (padding/borders around the grid). */+ /** packColor() — the opaque plate drawn BEFORE this grid's cells, covering the grid rect+ * expanded by `padPx` on every side. This is the Phase-1 occlusion story: painter's order+ * makes it cover anything drawn beneath it (overlapping terminals), and it fills the node+ * body's padding around the character matrix. */bgColor: number+ /** Plate padding around the grid rect, in WORLD units (scaled by the camera zoom like any+ * other world length). */+ padPx: number}/** Everything engine.ts is allowed to know about the GPU. Draw order is the painter's- * algorithm: the engine calls drawGrid back-to-front and each grid's opaque background- * occludes what was drawn beneath it — that is how overlapping terminals will occlude each- * other in Phase 1 without any depth buffer. */+ * algorithm: the engine calls drawGrid back-to-front and each grid's opaque plate occludes+ * what was drawn beneath it — that is how overlapping terminals occlude each other without+ * any depth buffer. */export interface GlyphGL {/** w/h in CSS px, dpr the device pixel ratio — sizes the backing store and the viewport. */resize(w: number, h: number, dpr: number): voiduploadAtlas(source: TexImageSource, sizePx: number, cellW: number, cellH: number): void+ /** Allocate the grid's GPU-side cell buffer (cols*rows*CELL_STRIDE uint32s, zeroed).+ * Re-calling with the same id REALLOCATES — that is the resize path. */+ createGrid(id: string, cols: number, rows: number): void+ disposeGrid(id: string): void+ /** Upload a contiguous row range into the grid's buffer (bufferSubData at byte offset+ * `firstRow * cols * CELL_STRIDE * 4`). `cells.length` MUST equal+ * `rowCount * cols * CELL_STRIDE` — a mismatch would scribble across neighbouring rows, so+ * it throws rather than truncating. */+ uploadRows(+ id: string,+ firstRow: number,+ rowCount: number,+ cols: number,+ cells: Uint32Array+ ): void/** Clears the frame and sets the camera uniforms. */beginFrame(camera: Camera): void- /** Draws the instanced cells in call order. Phase 0 paints each cell's own bg lane; the- * separate bgColor plate lands in Phase 1 — see gl-webgl2.ts drawGrid. */- drawGrid(g: GridDraw): void+ /** Draws the plate (a scissored clear of the padded grid rect) and then the instanced cells+ * from the grid's OWN buffer, in call order (painter's algorithm). */+ drawGrid(g: GridDrawParams): voidendFrame(): voiddispose(): void}diff --git a/src/renderer/glyphgrid/harness/GlyphGridHarness.tsx b/src/renderer/glyphgrid/harness/GlyphGridHarness.tsxindex 8bde0ce68..bd7e9e999 100644--- a/src/renderer/glyphgrid/harness/GlyphGridHarness.tsx+++ b/src/renderer/glyphgrid/harness/GlyphGridHarness.tsx@@ -22,6 +22,9 @@ const GRIDS = 40const CELL_W = 9const CELL_H = 18const ATLAS_PX = 1024+/** World-unit padding the occlusion plate adds around each grid — a stand-in for the terminal+ * node body's inset. Well under the 40/60 layout pitch, so plates stay separated. */+const PAD_PX = 8// --- Layout. Derived, not duplicated: register() below places grids from these same constants,// so the initial camera and the meter can never drift from where the grids actually are. ---@@ -103,7 +106,10 @@ export function GlyphGridHarness() {originX: (i % PER_ROW) * PITCH_X,originY: Math.floor(i / PER_ROW) * PITCH_Y,z: i,- bgColor: packColor(20, 20, 24, 255)+ bgColor: packColor(20, 20, 24, 255),+ // Non-zero so the occlusion plate is actually VISIBLE in the harness: it extends the+ // opaque body past the character matrix, the way a terminal node's padding does.+ padPx: PAD_PX}))}