// Terminal rasteriser: a coarse text-mode view of a render list, used for // headless runs and CI logs. (Real pixels come from the Canvas2D backend.) const SHADES = ' .:-=+*#%@'; const CW = 8, CH = 16; export function renderAscii(ops, screen) { const cols = Math.ceil(screen.w / CW), rows = Math.ceil(screen.h / CH); const grid = Array.from({ length: rows }, () => Array(cols).fill(' ')); const clips = [{ x: 0, y: 0, w: screen.w, h: screen.h }]; const inClip = (px, py) => { const c = clips[clips.length - 1]; return px >= c.x && py >= c.y && px < c.x + c.w && py < c.y + c.h; }; const lum = (c) => (0.299 * c.r + 0.587 * c.g + 0.114 * c.b) / 255; const shade = (c) => SHADES[Math.min(SHADES.length - 1, Math.floor(lum(c) * SHADES.length))]; const put = (cx, cy, ch) => { if (cx >= 0 && cy >= 0 && cx < cols && cy < rows && inClip(cx * CW + CW / 2, cy * CH + CH / 2)) grid[cy][cx] = ch; }; for (const op of ops) { const v = op.val; switch (op.tag) { case 'push-clip': { const c = clips[clips.length - 1]; const x0 = Math.max(c.x, v.x), y0 = Math.max(c.y, v.y); const x1 = Math.min(c.x + c.w, v.x + v.w), y1 = Math.min(c.y + c.h, v.y + v.h); clips.push({ x: x0, y: y0, w: Math.max(0, x1 - x0), h: Math.max(0, y1 - y0) }); break; } case 'pop-clip': if (clips.length < 2) throw new Error('pop-clip without push-clip'); clips.pop(); break; case 'fill-rect': { if (v.color.a < 40) break; for (let cy = Math.floor(v.rect.y / CH); cy <= Math.floor((v.rect.y + v.rect.h - 1) / CH); cy++) for (let cx = Math.floor(v.rect.x / CW); cx <= Math.floor((v.rect.x + v.rect.w - 1) / CW); cx++) put(cx, cy, shade(v.color)); break; } case 'circle': { if (!v.filled || v.color.a < 120) break; for (let cy = 0; cy < rows; cy++) for (let cx = 0; cx < cols; cx++) { const dx = cx * CW + CW / 2 - v.center.x, dy = cy * CH + CH / 2 - v.center.y; if (dx * dx + dy * dy <= v.radius * v.radius) put(cx, cy, shade(v.color)); } break; } case 'text': { const w = v.text.length; let x0 = v.origin.x; if (v.style.align === 'center') x0 -= (w * CW) / 2; else if (v.style.align === 'right') x0 -= w * CW; const cy = Math.floor(v.origin.y / CH); for (let i = 0; i < w; i++) put(Math.floor(x0 / CW) + i, cy, v.text[i]); break; } default: break; // stroke-rect / line: omitted in text mode } } return grid.map((r) => r.join('').replace(/\s+$/, '')).join('\n'); }