Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit 2e71da75aaffded93b7527894bf387211e23877e
parent 45e7e78cc19867a19f743d5ae7fb03b167636a57
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed,  4 Nov 2026 14:14:39 -0500

umtool: a caption chip in FREE SPACE only -- never over any of the card's words, read, unread or already read -- with a leader line to its phrase (operator, 4 Nov, on the stills: the curse chip covered "maledictio tabis vi sibat")

placeCaption searches the whole footage box for the nearest spot over no obstacle -- every word in view (any
post on the card), the card's furniture (avatars, names, dates, the mark, labels, counts), the attachments'
boxes and the clock with its badge -- judged as the card is when the caption comes in, while it is up and as it
goes; the card's own free space beats the frame's, the chip may take a narrower width (CAPTION_WIDTHS) to fit,
and `place` is a preference. A leader runs from the phrase's underline to the chip through free space only
(straight, else out along the underline to the text column's gutter and across). The chip, the underline and the
leader are static: a pan that moves the phrase while it is up ends the caption first. Play and the bench place
it by the same rule. The chip's drawing version (captionV) is 2. Unit tests: no placement overlaps a word box
(a hundred and twenty random cards), the leader crosses no word.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Mumtool/components/projects/review/PostItemPlayer.tsx | 55+++++++++++++++++++++++++++++++------------------------
Mumtool/report-to-video/post-caption.mjs | 275+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------------
Mumtool/report-to-video/post-caption.test.mjs | 81++++++++++++++++++++++++++++++++++++++++++++++++++++---------------------------
Mumtool/report-to-video/post-clock.test.mjs | 2+-
Mumtool/report-to-video/post-render.mjs | 79+++++++++++++++++++++++++++++++++++++++++++++++++++----------------------------
5 files changed, 348 insertions(+), 144 deletions(-)

diff --git a/umtool/components/projects/review/PostItemPlayer.tsx b/umtool/components/projects/review/PostItemPlayer.tsx @@ -50,7 +50,7 @@ import { WORD_ZOOM_HIGHLIGHT_ALPHA, findMatch, highlightAt, resolveWordZoom, tar type Rect = { x: number; y: number; width: number; height: number }; /** A zoom of the item, measured in its card page: its span on the item's clock, the card's region, the word's box. */ /** A caption of the item, placed in its card page: its span, its place, the phrase's box and lines when placed. */ -type LiveCaption = { i: number; span: { t0: number; t1: number; t2: number; t3: number }; scope: string; from: number; to: number; placed: ReturnType<typeof placeCaption>; base: Rect; lines: Rect[] }; +type LiveCaption = { i: number; span: { t0: number; t1: number; t2: number; t3: number }; scope: string; from: number; to: number; placed: NonNullable<ReturnType<typeof placeCaption>>; base: Rect; lines: Rect[] }; type LiveZoom = { i: number; span: ReturnType<typeof zoomSpan>; scope: string; from: number; to: number; color: string | null; region: Rect; word: Rect }; /** The card's children placed so the region shows `win` (zoomWindow) at z; their layout boxes measured before any transform. */ @@ -451,6 +451,8 @@ export default function PostItemPlayer({ const readFrame = useRef<HTMLIFrameElement | null>(null); const [zooms, setZooms] = useState<LiveZoom[]>([]); const [caps, setCaps] = useState<LiveCaption[]>([]); + // The clock's box (and its badge's) where it is placed: a caption covers neither. + const clockRect = useRef<Rect | null>(null); const boxes = useRef<Map<Element, Rect>>(new Map()); const zoomTimes = useMemo(() => (Array.isArray(entry.fx) && entry.fx.length ? wordZoomTimes(entry, undefined, plan.narration as never) : []), [entry, plan.narration]); // ---- read-follow, live: the page's geometry measured once it is drawn, the path from it ---- @@ -509,22 +511,32 @@ export default function PostItemPlayer({ } catch { cplan = []; } - const sizes = mountCaptions({ css: captionCss({ height: box.height, palette: paletteOfDoc(doc) }), chips: cplan.map((c) => ({ i: c.i, html: captionInnerHtml(c.text) })) }, doc); const k = box.height / 1080; - const inset = Math.round(10 * k); + const sizes = mountCaptions({ css: captionCss({ height: box.height, palette: paletteOfDoc(doc) }), chips: cplan.map((c) => ({ i: c.i, html: captionInnerHtml(c.text) })), k }, doc); + const inset = Math.round(12 * k); + // Free space only (as the build places it): the whole box, never over a word, the card's furniture, an attachment or the clock. + const bounds = { x: inset, y: inset, width: box.width - 2 * inset, height: box.height - 2 * inset }; + const fixed: Rect[] = [...(layout.slot ? plan.steps.flatMap((st) => stepBoxes(st, layout.slot) as Rect[]) : [])]; + if (clock && clockRect.current) fixed.push(clockRect.current); const placedCaps: LiveCaption[] = []; + type Geo = { error?: string; card: Rect; word: Rect; lines: Rect[]; avoid: Rect[]; obstacles: Rect[]; column: Rect | null }; for (const c of cplan) { + const looks: Geo[] = []; + for (const t of follow ? [c.span.t1, c.span.t0, c.span.t3 - 0.01] : [c.span.t1]) { + if (follow) applyFollowState(followStateAt(follow, route, t), doc); + looks.push(measureCaptionWords({ scope: c.scope, from: c.from, to: c.to, avoid: c.avoid }, doc) as Geo); + } if (follow) applyFollowState(followStateAt(follow, route, c.span.t1), doc); - const g = measureCaptionWords({ scope: c.scope, from: c.from, to: c.to, avoid: c.avoid }, doc) as { error?: string; card: Rect; word: Rect; lines: Rect[]; avoid: Rect[]; others: Rect[] }; + const g = looks[0]; const size = sizes.find((x) => x.i === c.i); if (g.error || !size) continue; - const bounds = { x: g.card.x + inset, y: g.card.y + inset, width: g.card.width - 2 * inset, height: g.card.height - 2 * inset }; - const placed = placeCaption({ word: g.word, chip: size, bounds, place: c.place, avoid: g.avoid, others: g.others, gap: Math.round(16 * k) }); + const placed = placeCaption({ word: g.word, sizes: size.sizes, bounds, card: g.card, column: g.column, place: c.place, obstacles: [...fixed, ...looks.flatMap((l) => l.obstacles ?? [])], gap: Math.round(10 * k) }); + if (!placed) continue; placedCaps.push({ i: c.i, span: c.span, scope: c.scope, from: c.from, to: c.to, placed, base: g.word, lines: g.lines }); } setCaps(placedCaps); return true; - }, [entry, zoomTimes, box.height, follow, layout.mode, plan.steps, plan.total, plan.narration]); + }, [entry, zoomTimes, box.height, follow, layout.mode, layout.slot, plan.steps, plan.total, plan.narration, clock]); // ---- the clock, live: mounted and placed once the page is drawn, set each tick ---- const [clockAt, setClockAt] = useState<{ x: number; y: number } | null>(null); const placeClock = useCallback(() => { @@ -541,16 +553,15 @@ export default function PostItemPlayer({ const route = follow && doc.querySelector("[data-post-flow]") ? followPath(follow, measureFollow(doc)) : null; if (follow && route) applyFollowState(followStateAt(follow, route, plan.total), doc); const at = size ? measureClockPlace({ size, inset: Math.round(22 * (box.height / 1080)) }, doc) : null; + clockRect.current = at && size ? { x: at.x - 240 * (box.height / 1080), y: at.y, width: size.width + 240 * (box.height / 1080), height: size.height } : null; if (follow && route) applyFollowState(followStateAt(follow, route, 0), doc); setClockAt(at ? { x: at.x, y: at.y } : null); }, [clock, box.height, follow, plan.total]); const onFrameLoad = useCallback(() => { let tries = 0; const tick = () => { - if (measure() || tries++ > 50) { - placeClock(); - return; - } + placeClock(); + if (measure() || tries++ > 50) return; setTimeout(tick, 100); }; tick(); @@ -577,24 +588,19 @@ export default function PostItemPlayer({ const doc = readFrame.current?.contentDocument; if (!doc) return; const k = box.height / 1080; - const list = capsUp.map((c) => { - let dx = 0; - let dy = 0; - let lines = c.lines; + const list = capsUp.flatMap((c) => { + // A pan moving its phrase ends it (as the build does): the chip never rides over words. if (follow) { - const g = measureCaptionWords({ scope: c.scope, from: c.from, to: c.to, avoid: [] }, doc) as { error?: string; word: Rect; lines: Rect[] }; - if (!g.error) { - dx = g.word.x - c.base.x; - dy = g.word.y - c.base.y; - lines = g.lines; - } + const g = measureCaptionWords({ scope: c.scope, from: c.from, to: c.to, avoid: [] }, doc) as { error?: string; word: Rect }; + if (!g.error && (Math.abs(g.word.y - c.base.y) > 1 || Math.abs(g.word.x - c.base.x) > 1)) return []; } const left = captionSlideAt(c.span, s); - const d = slideDir(c.placed.place); + const rel = c.placed.y >= c.base.y + c.base.height ? "below" : c.placed.y + c.placed.height <= c.base.y ? "above" : c.placed.x >= c.base.x ? "side-right" : "side-left"; + const d = slideDir(rel); const opacity = captionOpacityAt(c.span, s); - return { i: c.i, x: c.placed.x, y: c.placed.y, place: c.placed.place, notch: c.placed.notch, opacity, dx: dx + d.x * CAPTION_SLIDE * k * left, dy: dy + d.y * CAPTION_SLIDE * k * left, marks: lines, mark: opacity }; + return [{ i: c.i, x: c.placed.x, y: c.placed.y, max: c.placed.max, opacity, dx: d.x * CAPTION_SLIDE * k * left, dy: d.y * CAPTION_SLIDE * k * left, marks: c.lines, mark: opacity, leader: c.placed.leader }]; }); - setCaptionState({ list }, doc); + setCaptionState({ list, stroke: Math.max(2, Math.round(2.4 * k)) }, doc); }, [capsUp, s, follow, followNow, box.height]); const clockSt = useMemo(() => (clock ? clockStateAt(clock, s) : null), [clock, s]); useEffect(() => { @@ -626,6 +632,7 @@ export default function PostItemPlayer({ data-post-clock-gap={clockSt && clockSt.gapOpacity > 0 ? clockSt.gap : undefined} data-post-caption-fx={capsUp.length ? capsUp.map((c) => String(c.i)).join(" ") : undefined} data-post-caption-place={capsUp.length ? capsUp.map((c) => c.placed.place).join(" ") : undefined} + data-post-caption-covers={capsUp.length ? capsUp.map((c) => String(c.placed.covers)).join(" ") : undefined} data-post-follow-block={followNow?.current !== null && followNow?.current !== undefined ? String(followNow.current) : undefined} data-post-follow-offset={followNow && followRoute?.segments.length ? String(Math.round(followNow.offset)) : undefined} data-post-follow-pans={followRoute ? String(followRoute.segments.length) : undefined} diff --git a/umtool/report-to-video/post-caption.mjs b/umtool/report-to-video/post-caption.mjs @@ -240,51 +240,131 @@ export function overlappingCaptions(spans) { const area = (a, b) => Math.max(0, Math.min(a.x + a.width, b.x + b.width) - Math.max(a.x, b.x)) * Math.max(0, Math.min(a.y + a.height, b.y + b.height) - Math.max(a.y, b.y)); /** @param {Rect} r @param {Rect} b */ const inside = (r, b) => r.x >= b.x - 0.5 && r.y >= b.y - 0.5 && r.x + r.width <= b.x + b.width + 0.5 && r.y + r.height <= b.y + b.height + 0.5; +/** @param {Rect} r @param {number} m */ +const grow = (r, m) => ({ x: r.x - m, y: r.y - m, width: r.width + 2 * m, height: r.height + 2 * m }); +/** Whether segment a→b crosses rect r (sampled every 3 px). @param {number[]} a @param {number[]} b @param {Rect} r */ +function crosses(a, b, r) { + const n = Math.max(1, Math.ceil(Math.hypot(b[0] - a[0], b[1] - a[1]) / 3)); + for (let k = 0; k <= n; k += 1) { + const x = a[0] + ((b[0] - a[0]) * k) / n; + const y = a[1] + ((b[1] - a[1]) * k) / n; + if (x > r.x && x < r.x + r.width && y > r.y && y < r.y + r.height) return true; + } + return false; +} /** - * THE PLACE: the chip's box (`chip`: its size) by the phrase (`word`: its box), - * inside `bounds` (the card), covering no box in `avoid` (the words read while - * it is up). The asked place first, then below, above, side (right, then left); - * the first that fits and covers nothing wins, else the one that fits and - * covers least, else the asked one clamped inside. `{ x, y, width, height, - * place, covers, notch }` -- among places that cover no word read, the one - * covering fewest of the card's other words (`others`) wins; each vertical place - * is tried centred on the phrase, then its left and right edges aligned. - * `place` "below"|"above"|"side-right"|"side-left", - * `covers` how many avoided boxes it touches, `notch` the point (chip px) its - * pointer sits at along the edge that faces the phrase. - * @param {{ word: Rect, chip: { width: number, height: number }, bounds: Rect, place?: string, avoid?: Rect[], others?: Rect[], gap?: number }} o - * @returns {Rect & { place: string, covers: number, notch: number }} + * THE LEADER: a thin line from the phrase's underline to the chip, through free + * space only -- straight when nothing is in the way, else an elbow out along the + * underline (in the gap under the phrase's line) to the text column's gutter, + * along the gutter, then across to the chip. `[[x, y], …]` or null (none clear). + * @param {Rect} word @param {Rect} chip @param {Rect[]} obstacles @param {Rect | null} column */ -export function placeCaption({ word, chip, bounds, place = "below", avoid = [], others = [], gap = 14 }) { - const order = [place, ...CAPTION_PLACES.filter((p) => p !== place)].flatMap((p) => (p === "side" ? ["side-right", "side-left"] : [p])); - const clampX = (x) => Math.min(bounds.x + bounds.width - chip.width, Math.max(bounds.x, x)); - const clampY = (y) => Math.min(bounds.y + bounds.height - chip.height, Math.max(bounds.y, y)); +export function leaderPath(word, chip, obstacles, column) { + const uy = word.y + word.height; + const cy = chip.y + chip.height / 2; + const cx = chip.x + chip.width / 2; + // The chip's edge facing the phrase. + const end = chip.y >= uy ? [Math.min(chip.x + chip.width - 8, Math.max(chip.x + 8, word.x + word.width / 2)), chip.y] + : chip.y + chip.height <= word.y ? [Math.min(chip.x + chip.width - 8, Math.max(chip.x + 8, word.x + word.width / 2)), chip.y + chip.height] + : chip.x >= word.x + word.width ? [chip.x, cy] : [chip.x + chip.width, cy]; + const clear = (pts) => pts.slice(1).every((p, k) => obstacles.every((r) => !crosses(pts[k], p, grow(r, 1)))); + const start = [Math.min(Math.max(end[0], word.x + 4), word.x + word.width - 4), uy]; + const straight = [start, end]; + if (clear(straight)) return straight; + const tries = []; + for (const side of [1, -1]) { + const gx = column ? (side > 0 ? column.x + column.width + 10 : column.x - 10) : side > 0 ? word.x + word.width + 10 : word.x - 10; + const s = [side > 0 ? word.x + word.width : word.x, uy]; + const ey = chip.y <= uy && chip.y + chip.height >= uy ? uy : cy; + const ex = gx >= chip.x + chip.width ? chip.x + chip.width : gx <= chip.x ? chip.x : cx; + const pts = [s, [gx, uy], [gx, ey], [ex, ey]]; + // The first leg runs in the gap under the phrase's line (not judged); the rest through free space. + if (clear(pts.slice(1))) tries.push({ pts, len: Math.abs(gx - s[0]) + Math.abs(ey - uy) + Math.abs(ex - gx) }); + } + tries.sort((a, b) => a.len - b.len); + return tries[0]?.pts ?? null; +} + +/** + * THE PLACE (operator, 4 Nov: "a caption chip never covers ANY of the card's + * words -- read, unread or already read"): the chip in FREE SPACE -- over no + * `obstacles` (every word drawn, the card's header and counts, the attachments, + * the clock), inside `bounds` (the footage box) -- as near the phrase as it can + * be, with a leader to it through free space. `sizes`: the chip laid out at + * each width it may take (`{ width, height, max }`, widest first); `place` + * (below | above | side) a preference, `card` the card's box (a place on the + * card beats one off it). Every candidate is a grid of spots around the phrase + * and down the box; the cheapest clear one wins (distance, plus a cost off the + * card, against the preferred side, and without a clear leader). `{ x, y, + * width, height, max, place, covers, leader }` -- `covers` 0 unless no spot is + * free (then the least-covering, which the build warns about). + * @param {{ word: Rect, sizes: Array<{ width: number, height: number, max?: number }>, bounds: Rect, card?: Rect | null, column?: Rect | null, place?: string, obstacles?: Rect[], gap?: number, step?: number }} o + */ +export function placeCaption({ word, sizes, bounds, card = null, column = null, place = "below", obstacles = [], gap = 10, step = 6 }) { const cx = word.x + word.width / 2; const cy = word.y + word.height / 2; - const xs = [cx - chip.width / 2, word.x - 12, word.x + word.width + 12 - chip.width]; - const at = (p, a = 0) => { - if (p === "below") return { x: clampX(xs[a]), y: word.y + word.height + gap }; - if (p === "above") return { x: clampX(xs[a]), y: word.y - gap - chip.height }; - if (p === "side-right") return { x: word.x + word.width + gap, y: clampY(cy - chip.height / 2) }; - return { x: word.x - gap - chip.width, y: clampY(cy - chip.height / 2) }; - }; - const tries = order.flatMap((p) => (p === "below" || p === "above" ? [0, 1, 2] : [0]).map((a) => { - const r = { ...at(p, a), width: chip.width, height: chip.height }; - const covers = avoid.filter((b) => area(r, b) > 4).length; - const hides = others.filter((b) => area(r, b) > 4).length; - return { ...r, place: p, covers, hides, fits: inside(r, bounds) && area(r, word) <= 1 }; - })); - // Clear of the read: fewest other words hidden, then the asked order (a stable sort keeps it). - const pick = tries.filter((r) => r.fits && !r.covers).sort((a, b) => a.hides - b.hides)[0] ?? tries.filter((r) => r.fits).sort((a, b) => a.covers - b.covers || a.hides - b.hides)[0] ?? (() => { - const r = tries[0]; - return { ...r, x: clampX(r.x), y: clampY(r.y) }; - })(); - const vertical = pick.place === "below" || pick.place === "above"; - const pad = Math.min(24, vertical ? chip.width / 4 : chip.height / 4); - const notch = vertical ? Math.min(chip.width - pad, Math.max(pad, cx - pick.x)) : Math.min(chip.height - pad, Math.max(pad, cy - pick.y)); - const { fits, hides, ...out } = pick; - return { ...out, x: Math.round(out.x), y: Math.round(out.y), notch: Math.round(notch) }; + const blocked = obstacles.map((r) => grow(r, gap / 2)).concat([grow(word, gap / 2)]); + let best = null; + let least = null; + for (const [si, sz] of sizes.entries()) { + const xs = new Set(); + for (const x of [cx - sz.width / 2, word.x, word.x + word.width - sz.width, card ? card.x + 14 : bounds.x, card ? card.x + card.width + gap : bounds.x, column ? column.x : bounds.x]) xs.add(Math.round(x)); + for (let x = bounds.x; x + sz.width <= bounds.x + bounds.width; x += Math.max(24, step * 4)) xs.add(Math.round(x)); + for (const x0 of xs) { + const x = Math.min(bounds.x + bounds.width - sz.width, Math.max(bounds.x, x0)); + for (let y = bounds.y; y + sz.height <= bounds.y + bounds.height; y += step) { + const r = { x, y, width: sz.width, height: sz.height }; + const covers = blocked.filter((b) => area(r, b) > 0).length; + const mx = r.x + r.width / 2; + const my = r.y + r.height / 2; + let cost = Math.hypot(mx - cx, my - cy) + si * 40; + const onCard = card && inside(r, card); + if (!onCard) cost += 160; + const below = r.y >= word.y + word.height; + const above = r.y + r.height <= word.y; + const side = !below && !above; + if ((place === "below" && !below) || (place === "above" && !above) || (place === "side" && !side)) cost += 60; + if (covers) { + if (!least || covers < least.covers || (covers === least.covers && cost < least.cost)) least = { ...r, max: sz.max, covers, cost }; + continue; + } + if (best && cost >= best.cost) continue; + best = { ...r, max: sz.max, covers: 0, cost }; + } + } + } + // Its leader, through free space; a spot with none is passed over for the next clear one when there is one. + const pick = best ?? least; + if (!pick) return null; + let leader = leaderPath(word, pick, obstacles, column); + let out = pick; + if (!leader && best) { + // Search again, the ones with a clear leader only (fewer: the cost already ranked them). + const ranked = []; + for (const sz of sizes) { + for (let y = bounds.y; y + sz.height <= bounds.y + bounds.height; y += step * 2) { + for (let x = bounds.x; x + sz.width <= bounds.x + bounds.width; x += step * 4) { + const r = { x, y, width: sz.width, height: sz.height }; + if (blocked.some((b) => area(r, b) > 0)) continue; + ranked.push({ ...r, max: sz.max, covers: 0, cost: Math.hypot(x + sz.width / 2 - cx, y + sz.height / 2 - cy) + (card && inside(r, card) ? 0 : 160) }); + } + } + ranked.sort((a, b) => a.cost - b.cost); + for (const r of ranked.slice(0, 200)) { + const l = leaderPath(word, r, obstacles, column); + if (l) { + out = r; + leader = l; + break; + } + } + if (leader) break; + } + } + const where = card && inside(out, card) ? "card" : "off-card"; + const { cost, ...rest } = out; + return { ...rest, x: Math.round(rest.x), y: Math.round(rest.y), place: where, leader: leader ? leader.map(([x, y]) => [Math.round(x), Math.round(y)]) : null }; } // --------------------------------------------------------------------------- @@ -361,6 +441,9 @@ export function captionCss({ height = 1080, palette = {} } = {}) { .pcap[data-place="above"]::before { bottom: -${Math.round(n / 2 + 1)}px; left: calc(var(--notch) - ${n / 2}px); border-left: none; border-top: none; } .pcap[data-place="side-right"]::before { left: -${Math.round(n / 2 + 1)}px; top: calc(var(--notch) - ${n / 2}px); border-right: none; border-top: none; } .pcap[data-place="side-left"]::before { right: -${Math.round(n / 2 + 1)}px; top: calc(var(--notch) - ${n / 2}px); border-left: none; border-bottom: none; } +.pcap[data-place="free"]::before { display: none; } +.pcap-leader-line { stroke: ${pal.accent}; } +.pcap-leader-dot { fill: ${pal.accent}; } .pcap-mark { position: absolute; height: ${Math.max(2, Math.round(3 * k))}px; background: ${pal.accent}; border-radius: ${Math.max(1, Math.round(2 * k))}px; opacity: 0; } `; } @@ -369,12 +452,16 @@ export function captionCss({ height = 1080, palette = {} } = {}) { // THE DOM (self-contained: passed to page.evaluate by the build, called by Play). // --------------------------------------------------------------------------- +/** The widths a chip is laid out at (px at 1080): the widest first; a narrower one fits a smaller space. */ +export const CAPTION_WIDTHS = Object.freeze([620, 480, 380, 300]); + /** - * Mount the chips over the card page: `{ css, chips: [{ i, html }] }`, each - * laid out unplaced and hidden. Returns each one's size `[{ i, width, height }]`. - * @param {{ css?: string, chips?: Array<{ i: number, html: string }> } | null} arg + * Mount the chips over the card page: `{ css, chips: [{ i, html }], k }`, each + * laid out unplaced and hidden at every width of CAPTION_WIDTHS (× `k`). + * Returns each one's sizes `[{ i, sizes: [{ width, height, max }] }]`. + * @param {{ css?: string, chips?: Array<{ i: number, html: string }>, k?: number, widths?: number[] } | null} arg * @param {Document} [doc] - * @returns {Array<{ i: number, width: number, height: number }>} + * @returns {Array<{ i: number, sizes: Array<{ width: number, height: number, max: number }> }>} */ export function mountCaptions(arg, doc = document) { doc.querySelectorAll("[data-post-fx-captions], style[data-post-fx-captions-css]").forEach((el) => el.remove()); @@ -387,25 +474,38 @@ export function mountCaptions(arg, doc = document) { const layer = doc.createElement("div"); layer.setAttribute("data-post-fx-captions", ""); doc.body.appendChild(layer); + const k = (arg && arg.k) || 1; + const widths = (arg && arg.widths) || [620, 480, 380, 300]; return chips.map((c) => { const el = doc.createElement("div"); el.className = "pcap"; el.setAttribute("data-post-fx-caption", String(c.i)); el.innerHTML = c.html; layer.appendChild(el); - const b = el.getBoundingClientRect(); - return { i: c.i, width: Math.ceil(b.width), height: Math.ceil(b.height) }; + const sizes = []; + for (const w of widths) { + const max = Math.round(w * k); + el.style.maxWidth = `${max}px`; + const b = el.getBoundingClientRect(); + const s = { width: Math.ceil(b.width), height: Math.ceil(b.height), max }; + if (!sizes.some((x) => x.width === s.width && x.height === s.height)) sizes.push(s); + } + el.style.maxWidth = ""; + return { i: c.i, sizes }; }); } /** * The phrase's geometry as the card is drawn now: `{ scope, from, to, avoid: - * [indices] }` → `{ card, word, lines, avoid }` (px boxes; `lines` the - * phrase's box per line, for its underline) or `{ error }` when a word is not - * drawn or is cut off the card. + * [indices] }` → `{ card, word, lines, avoid, obstacles, column }` -- px boxes: + * `lines` the phrase's box per line (its underline), `obstacles` everything + * drawn a chip may not cover (every word in view, the card's header, its + * counts, a quote's or a picture's frame -- the phrase itself apart), `column` + * the phrase's text column; or `{ error }` when a word is not drawn or is cut + * off the card. * @param {{ scope: string, from: number, to: number, avoid?: number[] }} arg * @param {Document} [doc] - * @returns {{ error: string } | { error?: undefined, card: Rect, word: Rect, lines: Rect[], avoid: Rect[], others: Rect[] }} + * @returns {{ error: string } | { error?: undefined, card: Rect, word: Rect, lines: Rect[], avoid: Rect[], obstacles: Rect[], column: Rect | null }} */ export function measureCaptionWords(arg, doc = document) { const rect = (el) => { @@ -416,10 +516,12 @@ export function measureCaptionWords(arg, doc = document) { if (!card) return { error: "the card is not drawn" }; /** @type {Rect[]} */ const lines = []; + let column = null; for (let i = arg.from; i <= arg.to; i += 1) { const el = doc.querySelector(`[data-w="${arg.scope}:${i}"]`); if (!el) return { error: `word ${i} is not on the card` }; - const clip = el.closest(".words, .ptext, .qtext"); + const clip = el.closest(".words, .ptext, .qtext, .twords, .tt"); + if (clip && !column) column = rect(clip); const cb = (clip || card).getBoundingClientRect(); for (const r of Array.from(el.getClientRects())) { if (r.width === 0) continue; @@ -444,23 +546,41 @@ export function measureCaptionWords(arg, doc = document) { const el = doc.querySelector(`[data-w="${arg.scope}:${i}"]`); if (el) for (const r of Array.from(el.getClientRects())) if (r.width > 0) avoid.push({ x: r.left, y: r.top, width: r.width, height: r.height }); } - // Every other word drawn (any post on the card): a place hiding fewer of them is better. + // Everything drawn a chip may not cover: each word in view (inside what clips it, not faded out), then the + // card's furniture -- names, dates, the platform mark, avatars, counts, labels, a context shot or quote frame. /** @type {Rect[]} */ - const others = []; + const obstacles = []; const mine = new Set(Array.from({ length: arg.to - arg.from + 1 }, (_, k) => `${arg.scope}:${arg.from + k}`)); + const view = doc.defaultView; + const shown = (el) => { + for (let n = el; n && n !== doc.body; n = n.parentElement) { + const st = view ? view.getComputedStyle(n) : null; + if (st && (st.visibility === "hidden" || st.display === "none" || Number(st.opacity) < 0.05)) return false; + } + return true; + }; for (const el of Array.from(doc.querySelectorAll("[data-w]"))) { if (mine.has(el.getAttribute("data-w") || "")) continue; - for (const r of Array.from(el.getClientRects())) if (r.width > 0) others.push({ x: r.left, y: r.top, width: r.width, height: r.height }); + const clip = el.closest(".words, .ptext, .qtext, .twords, .tt, [data-thread-tile]") || card; + const cb = clip.getBoundingClientRect(); + for (const r of Array.from(el.getClientRects())) { + if (r.width <= 0 || r.bottom <= cb.top || r.top >= cb.bottom) continue; + obstacles.push({ x: r.left, y: Math.max(r.top, cb.top), width: r.width, height: Math.min(r.bottom, cb.bottom) - Math.max(r.top, cb.top) }); + } } - return { card: rect(card), word: { x: x0, y: y0, width: x1 - x0, height: y1 - y0 }, lines, avoid, others }; + for (const el of Array.from(card.querySelectorAll(".avatar, .name, .handle, .date, .pdate, .mark, .plabel, .repost, .replying, .counts > *, .pshot img, .sline, .strip"))) { + if (!shown(el)) continue; + for (const r of Array.from(el.getClientRects())) if (r.width > 0 && r.height > 0) obstacles.push({ x: r.left, y: r.top, width: r.width, height: r.height }); + } + return { card: rect(card), word: { x: x0, y: y0, width: x1 - x0, height: y1 - y0 }, lines, avoid, obstacles, column }; } /** - * Set the chips: `[{ i, x, y, place, notch, opacity, dx, dy, marks, mark }]` - * (`marks`: the underline's boxes under the phrase, `mark` their opacity); - * a chip not listed is hidden. `only`: "chip" | "mark" draws just that layer - * (the build shoots them apart), absent both. - * @param {{ list?: Array<Record<string, any>>, only?: string } | null} arg + * Set the chips: `[{ i, x, y, max, opacity, dx, dy, marks, mark, leader }]` + * (`marks`: the underline's boxes under the phrase, `leader` its line to the + * chip, `mark` their opacity); a chip not listed is hidden. `only`: "chip" | + * "mark" draws just that layer (the build shoots them apart), absent both. + * @param {{ list?: Array<Record<string, any>>, only?: string, stroke?: number } | null} arg * @param {Document} [doc] */ export function setCaptionState(arg, doc = document) { @@ -468,19 +588,20 @@ export function setCaptionState(arg, doc = document) { const only = arg && arg.only; const layer = doc.querySelector("[data-post-fx-captions]"); if (!layer) return; - layer.querySelectorAll(".pcap-mark").forEach((el) => el.remove()); + layer.querySelectorAll(".pcap-mark, .pcap-leader").forEach((el) => el.remove()); for (const el of Array.from(layer.querySelectorAll(".pcap"))) { const c = list.find((x) => String(x.i) === el.getAttribute("data-post-fx-caption")); if (!c || only === "mark") { el.style.opacity = "0"; continue; } - el.setAttribute("data-place", c.place); - el.style.setProperty("--notch", `${c.notch}px`); + el.setAttribute("data-place", "free"); + if (c.max) el.style.maxWidth = `${c.max}px`; el.style.transform = `translate(${Math.round(c.x + (c.dx || 0))}px, ${Math.round(c.y + (c.dy || 0))}px)`; el.style.opacity = String(c.opacity); } if (only === "chip") return; + const sw = (arg && arg.stroke) || 2; for (const c of list) { for (const l of c.marks || []) { const m = doc.createElement("div"); @@ -493,6 +614,34 @@ export function setCaptionState(arg, doc = document) { m.style.opacity = String(c.mark ?? c.opacity); layer.appendChild(m); } + if (Array.isArray(c.leader) && c.leader.length > 1) { + const ns = "http://www.w3.org/2000/svg"; + const svg = doc.createElementNS(ns, "svg"); + svg.setAttribute("class", "pcap-leader"); + svg.setAttribute("data-post-fx-caption-leader", String(c.i)); + svg.setAttribute("width", "100%"); + svg.setAttribute("height", "100%"); + svg.style.position = "absolute"; + svg.style.left = "0"; + svg.style.top = "0"; + svg.style.overflow = "visible"; + svg.style.opacity = String(c.mark ?? c.opacity); + const pl = doc.createElementNS(ns, "polyline"); + pl.setAttribute("points", c.leader.map((p) => `${p[0] + (c.ldx || 0)},${p[1] + (c.ldy || 0)}`).join(" ")); + pl.setAttribute("fill", "none"); + pl.setAttribute("stroke-width", String(sw)); + pl.setAttribute("stroke-linejoin", "round"); + pl.setAttribute("class", "pcap-leader-line"); + svg.appendChild(pl); + const last = c.leader[c.leader.length - 1]; + const dot = doc.createElementNS(ns, "circle"); + dot.setAttribute("cx", String(last[0])); + dot.setAttribute("cy", String(last[1])); + dot.setAttribute("r", String(sw * 1.6)); + dot.setAttribute("class", "pcap-leader-dot"); + svg.appendChild(dot); + layer.appendChild(svg); + } } } diff --git a/umtool/report-to-video/post-caption.test.mjs b/umtool/report-to-video/post-caption.test.mjs @@ -80,34 +80,59 @@ test("the plan: the words read while it is up are what it must not cover; two up assert.throws(() => captionPlan(base({ fx: [cap({ at: 2 }), cap({ at: 3, match: "amazing." })] })), /captions 1 and 2 are up at once/); }); -test("THE PLACE: below by default; a place over a word read while it is up is passed over; side when neither fits; fewest words hidden", () => { - const bounds = { x: 0, y: 0, width: 800, height: 600 }; - const word = { x: 300, y: 300, width: 100, height: 40 }; - const chip = { width: 240, height: 60 }; - const below = placeCaption({ word, chip, bounds }); - assert.equal(below.place, "below"); - assert.deepEqual([below.x, below.y, below.covers], [230, 354, 0]); - assert.equal(below.notch, 120); - // The next line is read while it is up: above. - const next = { x: 100, y: 350, width: 600, height: 40 }; - const above = placeCaption({ word, chip, bounds, avoid: [next] }); - assert.equal(above.place, "above"); - assert.equal(above.y, 300 - 14 - 60); - // Both lines read: to the side. - const prev = { x: 100, y: 250, width: 600, height: 40 }; - const side = placeCaption({ word: { ...word, x: 100 }, chip, bounds, avoid: [next, prev] }); - assert.equal(side.place, "side-right"); - assert.equal(side.covers, 0); - // Nothing is clear: the one covering least, and it says so. - const all = placeCaption({ word, chip, bounds: { x: 0, y: 200, width: 800, height: 250 }, avoid: [next, prev, { x: 0, y: 300, width: 300, height: 40 }, { x: 400, y: 300, width: 400, height: 40 }] }); - assert.ok(all.covers >= 1); - // Clear of the read either way: the place hiding fewer of the card's other words. - const fewer = placeCaption({ word, chip, bounds, others: [{ x: 200, y: 360, width: 400, height: 40 }] }); - assert.equal(fewer.place, "above"); - // Kept inside the card: a phrase at the edge pulls the chip in, the notch still under the phrase. - const edge = placeCaption({ word: { x: 700, y: 300, width: 80, height: 40 }, chip, bounds }); - assert.equal(edge.x, 800 - 240); - assert.equal(edge.notch, Math.min(240 - 24, 740 - 560)); +const overlapArea = (a, b) => Math.max(0, Math.min(a.x + a.width, b.x + b.width) - Math.max(a.x, b.x)) * Math.max(0, Math.min(a.y + a.height, b.y + b.height) - Math.max(a.y, b.y)); +/** A card of text: `rows` lines of words, `[{x, y, width, height}]`, from (x0, y0). */ +const textBlock = (x0, y0, rows, { words = 8, w = 70, h = 40, gapX = 14, lineH = 52 } = {}) => + Array.from({ length: rows }, (_, r) => Array.from({ length: words }, (_, c) => ({ x: x0 + c * (w + gapX), y: y0 + r * lineH, width: w, height: h }))).flat(); + +test("THE PLACE (operator, 4 Nov: \"a caption chip never covers ANY of the card's words\"): free space only -- below the text, off the card, or in a band -- never over a word, read or not", () => { + const card = { x: 40, y: 40, width: 760, height: 1000 }; + const bounds = { x: 12, y: 12, width: 1896, height: 1056 }; + const words = textBlock(80, 300, 8); // y 300..704: a block of text mid-card + const phrase = words[3 * 8 + 3]; + const obstacles = words.filter((w) => w !== phrase); + const sizes = [{ width: 480, height: 70, max: 480 }, { width: 340, height: 100, max: 340 }]; + const p = placeCaption({ word: phrase, sizes, bounds, card, column: { x: 80, y: 300, width: 680, height: 410 }, obstacles }); + assert.equal(p.covers, 0); + for (const w of words) assert.equal(overlapArea(p, w), 0, `over a word at ${w.x},${w.y}`); + assert.equal(p.place, "card", "the card's own free space beats the frame's"); + assert.ok(p.y >= 704 || p.y + p.height <= 300, "above or below the block, not inside it"); + assert.ok(Array.isArray(p.leader) && p.leader.length >= 2, "a leader to the phrase"); + // Its leader runs through free space: past the first leg (in the gap under the phrase's line), it crosses no word. + const legs = p.leader.slice(p.leader.length > 2 ? 1 : 0); + for (let k = 1; k < legs.length; k += 1) { + for (let q = 0; q <= 20; q += 1) { + const x = legs[k - 1][0] + ((legs[k][0] - legs[k - 1][0]) * q) / 20; + const y = legs[k - 1][1] + ((legs[k][1] - legs[k - 1][1]) * q) / 20; + for (const w of obstacles) assert.ok(!(x > w.x + 1 && x < w.x + w.width - 1 && y > w.y + 1 && y < w.y + w.height - 1), `leader through a word at ${x},${y}`); + } + } + // A card full of text: off the card, still over nothing (the attachment's box an obstacle too). + const full = textBlock(60, 60, 18, { words: 8 }); + const media = { x: 840, y: 240, width: 1060, height: 600 }; + const q = placeCaption({ word: full[5 * 8 + 2], sizes, bounds, card, obstacles: [...full.filter((_, i) => i !== 5 * 8 + 2), media] }); + assert.equal(q.covers, 0); + assert.equal(q.place, "off-card"); + for (const w of [...full, media]) assert.equal(overlapArea(q, w), 0); + // Below by default when both are free; above when asked. + const lone = { x: 300, y: 500, width: 100, height: 40 }; + const b = placeCaption({ word: lone, sizes, bounds, card }); + assert.ok(b.y >= 540); + const a = placeCaption({ word: lone, sizes, bounds, card, place: "above" }); + assert.ok(a.y + a.height <= 500); +}); + +test("THE PLACE, at random: over a hundred cards of words, the chip never overlaps a word box when the frame has room", () => { + let seed = 7; + const rnd = () => ((seed = (seed * 1103515245 + 12345) % 2147483648) / 2147483648); + for (let n = 0; n < 120; n += 1) { + const rows = 2 + Math.floor(rnd() * 12); + const words = textBlock(60 + rnd() * 40, 60 + rnd() * 300, rows, { words: 4 + Math.floor(rnd() * 5) }); + const k = Math.floor(rnd() * words.length); + const p = placeCaption({ word: words[k], sizes: [{ width: 300 + rnd() * 300, height: 60 + rnd() * 50 }], bounds: { x: 0, y: 0, width: 1920, height: 1080 }, card: { x: 40, y: 40, width: 800, height: 1000 }, obstacles: words.filter((_, i) => i !== k) }); + assert.equal(p.covers, 0, `card ${n}`); + for (const w of words) assert.equal(overlapArea(p, w), 0, `card ${n}: over a word`); + } }); test("the chip's markup: the part before the dash bold, every character escaped, CJK kept", () => { diff --git a/umtool/report-to-video/post-clock.test.mjs b/umtool/report-to-video/post-clock.test.mjs @@ -109,7 +109,7 @@ test("THE SEGMENT KEY (post-render.mjs postFxKeyFields): nothing for a plain ite assert.deepEqual(postFxKeyFields(plain, {}, post("z", "2026-11-02T22:00:00Z")), {}); assert.deepEqual(postFxKeyFields(plain, { postNarration: { rate: 1.08 } }, null), {}); // A caption: its drawing's version (the entry, in the key, carries its text and knobs). - assert.deepEqual(postFxKeyFields({ ...plain, fx: [{ kind: "caption", match: "x", text: "y" }] }, {}), { captionV: 1 }); + assert.deepEqual(postFxKeyFields({ ...plain, fx: [{ kind: "caption", match: "x", text: "y" }] }, {}), { captionV: 2 }); // The clock: from the item before -- its time, its being a clock item, the zone, the rewind. const clk = { ...plain, fx: [{ kind: "clock" }] }; const before = post("z", "2026-11-02T22:00:00Z", CLK); diff --git a/umtool/report-to-video/post-render.mjs b/umtool/report-to-video/post-render.mjs @@ -25,7 +25,7 @@ import { redactEntry, redactionOn, shownLine, termsFor } from "./post-redact.mjs import { bleepFilters, slursOn, takeBleeps } from "./post-slurs.mjs"; import { blurFilters, blurOn, censorEntry, labelFilter } from "./post-censor.mjs"; import { sceneEntry } from "./post-media-scene.mjs"; -import { CAPTION_SLIDE, captionCss, captionInnerHtml, captionPlan, measureCaptionWords, mountCaptions, placeCaption, setCaptionState, slideDir } from "./post-caption.mjs"; +import { CAPTION_OUT, CAPTION_SLIDE, captionCss, captionInnerHtml, captionPlan, measureCaptionWords, mountCaptions, placeCaption, setCaptionState, slideDir } from "./post-caption.mjs"; import { clockCss, clockFace, clockFrameTimes, clockHtml, clockPlan, clockStateAt, measureClockPlace, mountClock, setClockState } from "./post-clock.mjs"; import { WORD_ZOOM_DEFAULTS, findMatch, overlappingZooms, resolveWordZoom, targetScope, targetTextOf, wordZoomTimes, zoomSpan, zoomTarget, zoompanExprs } from "./word-zoom.mjs"; @@ -132,6 +132,7 @@ export function postSegmentArgs({ entry, box, plan, layout, cards, files, render captionFx.forEach((c, ci) => { const { span } = c; const D = Math.max(1 / fps, span.t3 - span.t0); + // Static: a pan that moves its phrase ends it first (shootCaptions), so nothing rides over words. const track = (axis) => trackExpr(c.track ?? [], axis); const layer = (shot, label, slide) => { const k = add(["-loop", "1", "-framerate", String(fps), "-t", num(D), "-i", shot.file]); @@ -286,7 +287,7 @@ async function loadChromium() { * stack layout. The page is a file beside them, so its faces and the parent * shot load from disk (an about:blank page may not read file: urls). */ -export async function renderPostCards(entry, { box, render, dir, manifestDir, layout, avatars = {}, zooms = [], redaction = null, follow = null, total = 0, captions = [], clock = null }) { +export async function renderPostCards(entry, { box, render, dir, manifestDir, layout, avatars = {}, zooms = [], redaction = null, follow = null, total = 0, captions = [], clock = null, obstacles = [] }) { await mkdir(dir, { recursive: true }); const fonts = { regular: render.fontRegular ? pathToFileURL(render.fontRegular).href : "", @@ -328,8 +329,9 @@ export async function renderPostCards(entry, { box, render, dir, manifestDir, la } await ctx.close(); if (zooms.length) out.zooms = await shootZooms(browser, entry, { box, render, dir, fonts, parentShotUrl, avatars, zooms, redaction, follow }); - if (captions.length) out.captions = await shootCaptions(browser, entry, { box, render, dir, fonts, parentShotUrl, avatars, captions, redaction, follow }); if (clock) out.clock = await shootClock(browser, entry, { box, render, dir, fonts, parentShotUrl, avatars, clock, redaction, follow, total }); + // A caption covers none of the attachments (`obstacles`: their boxes) nor the clock. + if (captions.length) out.captions = await shootCaptions(browser, entry, { box, render, dir, fonts, parentShotUrl, avatars, captions, redaction, follow, obstacles: [...obstacles, ...(out.clock ? [out.clock.box] : [])] }); } finally { await browser.close(); } @@ -475,7 +477,7 @@ async function shootZooms(browser, entry, { box, render, dir, fonts, parentShotU * frame over the caption's span: its `track`, which the chip rides. * `captions`: captionPlan's. Returns `[{ ...caption, chip, mark, slide, track, placed }]`. */ -export async function shootCaptions(browser, entry, { box, render, dir, fonts, parentShotUrl, avatars, captions, redaction = null, follow = null }) { +export async function shootCaptions(browser, entry, { box, render, dir, fonts, parentShotUrl, avatars, captions, redaction = null, follow = null, obstacles: fixed = [] }) { const fps = render.fps ?? 30; const k = box.height / 1080; const ctx = await browser.newContext({ viewport: { width: box.width, height: box.height }, deviceScaleFactor: 1, offline: true, serviceWorkers: "block" }); @@ -487,31 +489,45 @@ export async function shootCaptions(browser, entry, { box, render, dir, fonts, p await writeFile(file, postCardHtml(entry, { width: box.width, height: box.height, palette: render.palette, fonts, phase: "read", parentShotUrl, avatars: av, redaction, follow: !!follow, thread: follow?.thread ?? null }), "utf8"); await page.goto(pathToFileURL(file).href, { waitUntil: "load" }); await page.waitForSelector("body[data-post-ready='1']", { timeout: 15000 }); - const sizes = await page.evaluate(mountCaptions, { css: captionCss({ height: box.height, palette: render.palette }), chips: captions.map((c) => ({ i: c.i, html: captionInnerHtml(c.text) })) }); + await page.evaluate(() => document.fonts.ready.then(() => true)); + const sizes = await page.evaluate(mountCaptions, { css: captionCss({ height: box.height, palette: render.palette }), chips: captions.map((c) => ({ i: c.i, html: captionInnerHtml(c.text) })), k }); await page.evaluate(() => document.fonts.ready.then(() => true)); const fpath = follow ? followPath(follow, await page.evaluate(measureFollow)) : null; const stateAt = async (s) => { if (follow) await page.evaluate(applyFollowState, followStateAt(follow, fpath, s)); }; - const inset = Math.round(10 * k); - for (const c of captions) { - await stateAt(c.span.t1); - const geo = await page.evaluate(measureCaptionWords, { scope: c.scope, from: c.from, to: c.to, avoid: c.avoid }); - if (geo.error) throw new Error(`${entry.id}: caption ${c.i + 1}: the phrase is ${geo.error}`); - const size = sizes.find((x) => x.i === c.i); - const bounds = { x: geo.card.x + inset, y: geo.card.y + inset, width: geo.card.width - 2 * inset, height: geo.card.height - 2 * inset }; - const placed = placeCaption({ word: geo.word, chip: size, bounds, place: c.place, avoid: geo.avoid, others: geo.others, gap: Math.round(16 * k) }); - // The phrase's track while it is up (a pan moves it): measured each frame, kept where it changes. - const track = []; + const inset = Math.round(12 * k); + const bounds = { x: inset, y: inset, width: box.width - 2 * inset, height: box.height - 2 * inset }; + for (const c0 of captions) { + let c = c0; + // A pan moving the phrase while it is up: the caption is gone before it moves (the chip never rides over words). if (follow) { + let base = null; for (let f = Math.floor(c.span.t0 * fps); f <= Math.ceil(c.span.t3 * fps); f += 1) { await stateAt(f / fps); const g = await page.evaluate(measureCaptionWords, { scope: c.scope, from: c.from, to: c.to, avoid: [] }); if (g.error) continue; - track.push({ t: r3(f / fps), dx: Math.round(g.word.x - geo.word.x), dy: Math.round(g.word.y - geo.word.y) }); + base ??= g.word; + if (Math.abs(g.word.y - base.y) > 1 || Math.abs(g.word.x - base.x) > 1) { + const tm = r3(f / fps); + if (tm > c.span.t1 + 0.2) c = { ...c, span: { ...c.span, t2: r3(Math.max(c.span.t1, tm - CAPTION_OUT)), t3: tm }, cutByPan: tm }; + break; + } } - await stateAt(c.span.t1); } + // Its place: judged where the card is as it comes in, while it is up and as it goes (a pan's other words too). + const looks = []; + for (const s of follow ? [c.span.t1, c.span.t0, c.span.t3 - 0.01] : [c.span.t1]) { + await stateAt(s); + looks.push(await page.evaluate(measureCaptionWords, { scope: c.scope, from: c.from, to: c.to, avoid: c.avoid })); + } + await stateAt(c.span.t1); + const geo = looks[0]; + if (geo.error) throw new Error(`${entry.id}: caption ${c.i + 1}: the phrase is ${geo.error}`); + const obstacles = [...fixed, ...looks.flatMap((l) => l.obstacles ?? [])]; + const size = sizes.find((x) => x.i === c.i); + const placed = placeCaption({ word: geo.word, sizes: size.sizes, bounds, card: geo.card, column: geo.column, place: c.place, obstacles, gap: Math.round(10 * k) }); + if (!placed) throw new Error(`${entry.id}: caption ${c.i + 1}: the chip fits nowhere in the frame`); // Shot alone: the card hidden, the page clear. await page.evaluate(() => { const st = document.createElement("style"); @@ -525,19 +541,26 @@ export async function shootCaptions(browser, entry, { box, render, dir, fonts, p const y = Math.max(0, Math.floor(r.y - pad)); return { x, y, width: Math.min(box.width - x, Math.ceil(r.x + r.width + pad) - x), height: Math.min(box.height - y, Math.ceil(r.y + r.height + pad) - y) }; }; - const state = { i: c.i, x: placed.x, y: placed.y, place: placed.place, notch: placed.notch, opacity: 1, marks: geo.lines, mark: 1 }; - await page.evaluate(setCaptionState, { list: [state], only: "chip" }); + const state = { i: c.i, x: placed.x, y: placed.y, max: placed.max, opacity: 1, marks: geo.lines, mark: 1, leader: placed.leader }; + const stroke = Math.max(2, Math.round(2.4 * k)); + await page.evaluate(setCaptionState, { list: [state], only: "chip", stroke }); const chipClip = clipOf(placed); const chip = { file: path.join(dir, `caption-${c.i}.png`), x: chipClip.x, y: chipClip.y }; await page.screenshot({ path: chip.file, clip: chipClip, omitBackground: true }); - await page.evaluate(setCaptionState, { list: [state], only: "mark" }); - const markClip = clipOf({ x: geo.word.x, y: geo.word.y + geo.word.height * 0.6, width: geo.word.width, height: geo.word.height * 0.6 }); + await page.evaluate(setCaptionState, { list: [state], only: "mark", stroke }); + // The underline and the leader (which does not slide): their union. + const pts = [...(placed.leader ?? []), [geo.word.x, geo.word.y + geo.word.height * 0.6], [geo.word.x + geo.word.width, geo.word.y + geo.word.height * 1.2]]; + const mx0 = Math.min(...pts.map((p) => p[0])); + const my0 = Math.min(...pts.map((p) => p[1])); + const markClip = clipOf({ x: mx0, y: my0, width: Math.max(...pts.map((p) => p[0])) - mx0, height: Math.max(...pts.map((p) => p[1])) - my0 }); const mark = { file: path.join(dir, `caption-${c.i}-mark.png`), x: markClip.x, y: markClip.y }; await page.screenshot({ path: mark.file, clip: markClip, omitBackground: true }); await page.evaluate(setCaptionState, { list: [] }); await page.evaluate(() => document.querySelectorAll("style[data-pcap-solo]").forEach((el) => el.remove())); - const d = slideDir(placed.place); - out.push({ ...c, chip, mark, slide: { x: d.x * CAPTION_SLIDE * k, y: d.y * CAPTION_SLIDE * k }, track, placed: { ...placed, word: geo.word, covers: placed.covers } }); + const rel = placed.y >= geo.word.y + geo.word.height ? "below" : placed.y + placed.height <= geo.word.y ? "above" : placed.x >= geo.word.x ? "side-right" : "side-left"; + const d = slideDir(rel); + // What it would cover of the words read, or of anything drawn: none, unless nothing in the frame is free. + out.push({ ...c, chip, mark, slide: { x: d.x * CAPTION_SLIDE * k, y: d.y * CAPTION_SLIDE * k }, track: [], placed: { ...placed, rel, word: geo.word } }); } } finally { await ctx.close(); @@ -613,7 +636,7 @@ export async function shootClock(browser, entry, { box, render, dir, fonts, pare lines.push(`file ${q(shots.get(runs[runs.length - 1].key))}`); const list = path.join(fdir, "frames.ffconcat"); await writeFile(list, lines.join("\n") + "\n", "utf8"); - return { list, x: clip.x, y: clip.y, place: at.place, covers: at.covers, shots: shots.size }; + return { list, x: clip.x, y: clip.y, place: at.place, covers: at.covers, shots: shots.size, box: { x: at.x - Math.round(240 * k), y: at.y, width: size.width + Math.round(240 * k), height: size.height } }; } finally { await ctx.close(); } @@ -657,7 +680,7 @@ export function postZoomPlan(entry, render, total = Infinity) { * pace the gap knobs the pace resolved to (lead, tail, ramp, linger: * a cut-level pace changes them without touching the entry) */ -export const POST_CAPTION_DRAW_V = 1; +export const POST_CAPTION_DRAW_V = 2; export const POST_CLOCK_DRAW_V = 1; export function postFxKeyFields(entry, render, prev = null) { const out = {}; @@ -728,7 +751,7 @@ export async function buildPostSegment(entry, { render, outDir, manifestDir, box const capPlan = captionPlan(entry, render, { zooms: zoomPlan.map((z) => ({ ...z.span, i: z.i })), end: layout.mode === "stack" && plan.steps.length ? plan.steps[0].at : plan.total, schedule: plan.narration ?? undefined }); // Its clock (post-clock.mjs): the post's own time, run from the clock item before it. const clk = clockPlan(entry, render, prev); - const cards = await renderPostCards(entry, { box, render, dir: cardDir, manifestDir, layout, avatars, zooms: zoomPlan, redaction, follow: plan.follow ?? null, total: plan.total, captions: capPlan, clock: clk }); + const cards = await renderPostCards(entry, { box, render, dir: cardDir, manifestDir, layout, avatars, zooms: zoomPlan, redaction, follow: plan.follow ?? null, total: plan.total, captions: capPlan, clock: clk, obstacles: layout.slot ? plan.steps.flatMap((st) => stepBoxes(st, layout.slot)) : [] }); // NO HIDDEN TEXT IS EVER NARRATED (operator, 4 Nov): a part whose words are not in view, whole and lit, while it // is said -- or a context post drawn over its context size -- refuses the build (READ_IN_VIEW=warn: a note). if (cards.inView?.length) { @@ -771,7 +794,7 @@ export async function buildPostSegment(entry, { render, outDir, manifestDir, box if (cards.follow) await rm(path.dirname(cards.follow.list), { recursive: true, force: true }); // Through a rename: the record may be a link into the take this one was made --from (never written through). const recTmp = `${record}.${process.pid}.tmp`; - await writeFile(recTmp, JSON.stringify({ version: 1, id: entry.id, key, layout: layout.mode, total: plan.total, steps: plan.steps.length, ...(zooms.length ? { zooms: zooms.map((z) => ({ i: z.i, at: z.t, source: z.source, span: z.span, region: z.region, word: z.word })) } : {}), ...(cards.captions?.length ? { captions: cards.captions.map((c) => ({ i: c.i, at: c.t, source: c.source, span: c.span, place: c.placed.place, box: { x: c.placed.x, y: c.placed.y, width: c.placed.width, height: c.placed.height }, word: c.placed.word, covers: c.placed.covers, moves: c.track.filter((p, k, a) => k && (p.dx !== a[k - 1].dx || p.dy !== a[k - 1].dy)).length })) } : {}), ...(narration ? { narration: { take: take.file, ...plan.narration, gainDb: narration.gainDb, measured: narration.lufs, ...(bleeps ? { slurs: { mode: bleeps.mode, spans: bleeps.spans } } : {}) } } : {}), ...(cards.follow ? { follow: { blocks: plan.follow.blocks.length, shots: cards.follow.shots, frames: cards.follow.frames, pan: cards.follow.path.segments.length, max: cards.follow.path.max } } : {}) }, null, 2) + "\n", "utf8"); + await writeFile(recTmp, JSON.stringify({ version: 1, id: entry.id, key, layout: layout.mode, total: plan.total, steps: plan.steps.length, ...(zooms.length ? { zooms: zooms.map((z) => ({ i: z.i, at: z.t, source: z.source, span: z.span, region: z.region, word: z.word })) } : {}), ...(cards.captions?.length ? { captions: cards.captions.map((c) => ({ i: c.i, at: c.t, source: c.source, span: c.span, place: c.placed.place, rel: c.placed.rel, box: { x: c.placed.x, y: c.placed.y, width: c.placed.width, height: c.placed.height }, word: c.placed.word, covers: c.placed.covers, leader: c.placed.leader, ...(c.cutByPan ? { cutByPan: c.cutByPan } : {}) })) } : {}), ...(narration ? { narration: { take: take.file, ...plan.narration, gainDb: narration.gainDb, measured: narration.lufs, ...(bleeps ? { slurs: { mode: bleeps.mode, spans: bleeps.spans } } : {}) } } : {}), ...(cards.follow ? { follow: { blocks: plan.follow.blocks.length, shots: cards.follow.shots, frames: cards.follow.frames, pan: cards.follow.path.segments.length, max: cards.follow.path.max } } : {}) }, null, 2) + "\n", "utf8"); await rename(recTmp, record); emit("note", { message: narration @@ -780,7 +803,7 @@ export async function buildPostSegment(entry, { render, outDir, manifestDir, box }); if (cards.follow) emit("note", { message: `${entry.id}: read-follow -- ${plan.follow.blocks.filter((b) => b.start !== null).length} block(s) read, ${cards.follow.path.segments.length ? `the words panned ${cards.follow.path.segments.length} time(s) over ${Math.round(cards.follow.path.max)} px` : "no pan (the words fit)"}; ${cards.follow.shots} shot(s) for ${cards.follow.frames} frames` }); if (cards.clock) emit("note", { message: `${entry.id}: clock ${clockFace(clk.to, clk.zone).time} ${clockFace(clk.to, clk.zone).date} (${clk.mode === "none" ? "shown" : clk.mode === "rewind" ? "rewound" : "run forward"}${clk.mode === "none" ? "" : ` from the item before, ${clk.gap / 60000 | 0} min`}), ${cards.clock.place}${cards.clock.covers ? ` -- WARNING: over ${cards.clock.covers} word(s)` : ""}` }); - for (const c of cards.captions ?? []) emit("note", { message: `${entry.id}: caption ${c.i + 1} "${c.text}" at ${c.t.toFixed(2)} s (${c.source === "at" ? "set by hand" : c.source === "words" ? "from the take's words" : "the reading estimate"}${c.span.waited !== null ? `, after word zoom ${c.span.waited + 1}` : ""}), ${c.span.t0}–${c.span.t3} s, ${c.placed.place} the phrase${c.placed.covers ? ` -- WARNING: it covers ${c.placed.covers} word(s) read while it is up (no place by the phrase is clear: set its place, hold or at)` : ""}` }); + for (const c of cards.captions ?? []) emit("note", { message: `${entry.id}: caption ${c.i + 1} "${c.text}" at ${c.t.toFixed(2)} s (${c.source === "at" ? "set by hand" : c.source === "words" ? "from the take's words" : "the reading estimate"}${c.span.waited !== null ? `, after word zoom ${c.span.waited + 1}` : ""}), ${c.span.t0}–${c.span.t3} s, ${c.placed.rel} the phrase ${c.placed.place === "card" ? "on the card" : "off the card"}${c.placed.leader ? ", a leader to it" : ""}${c.cutByPan ? ` (gone at ${c.cutByPan} s, before the card pans its phrase)` : ""}${c.placed.covers ? ` -- WARNING: no free space in the frame, it covers ${c.placed.covers} thing(s) drawn (shorten its text)` : ""}` }); for (const z of zooms) emit("note", { message: `${entry.id}: word zoom ${z.i + 1} at ${z.t.toFixed(2)} s (${z.source === "at" ? "set by hand" : "from the take's words"}), ${z.span.scale}× over ${z.span.t0}–${z.span.t3} s` }); return seg; }