diff options
| author | Daisy Hollman <daisy@anthropic.com> | 2026-11-13 19:04:02 +0000 |
|---|---|---|
| committer | Daisy Hollman <daisy@anthropic.com> | 2026-11-13 19:04:02 +0000 |
| commit | c6c813be3f66c683330c57df03b7b0196c76ca7c (patch) | |
| tree | cf34011470e95fa71823070dc880542dfeb3a939 /plugins/theme-examples/hooks | |
| parent | 23c304a6387ed2fa207ceff27646d8514ee75235 (diff) | |
Add theme-examples: example backdrops for the Claude desktop appdaisy/theme-examples/add-plugin
An example plugin to read, copy and change: twenty animated scenes drawn
behind the chat in Claude Desktop, with frosted-glass panels, chosen per
project or per session with /custom-theme, and a short fireworks show.
Adds plugins/theme-examples and its entry in marketplace.json.
Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013UQQgZFQiVMThRLmS814y8
Diffstat (limited to 'plugins/theme-examples/hooks')
19 files changed, 6437 insertions, 0 deletions
diff --git a/plugins/theme-examples/hooks/fireworks.ts b/plugins/theme-examples/hooks/fireworks.ts new file mode 100644 index 00000000..1eba4b6a --- /dev/null +++ b/plugins/theme-examples/hooks/fireworks.ts @@ -0,0 +1,122 @@ +import type { Theme } from './themes' + +/** The word that sets a show off, whole and in any case: "merged", not "unmerged" or "emerged". */ +export const WORD = /\bmerged\b/i +/** A show's backdrop is its theme's id with one of these behind it; two, so a second show starts afresh. */ +export const SHOW_SUFFIXES = ['--fireworks-a', '--fireworks-b'] as const +/** The backdrop of a show in a session with no theme: the bursts over a night sky of their own. */ +export const NIGHT_ID = 'fireworks-night' +// No tint: no theme stands, so the panels keep the window's own color and the show asks no side of it. +export const NIGHT_GLASS = { blur: 10, opacity: 0.45 } + +type Burst = { x: number; y: number; hue: number; delay: number; size: number } + +// Bursts at the edges, and along the top edge over the conversation, so no spoke crosses the text being read. +// FOR PEOPLE SENSITIVE TO FLASHING LIGHT: each burst plays once, and their starts stand 1 s apart. Keep it so: a burst +// added, or a start moved nearer, makes the whole picture change more often. +const BURSTS: readonly Burst[] = [ + { x: 220, y: 230, hue: 48, delay: 0, size: 150 }, + { x: 1380, y: 200, hue: 330, delay: 1, size: 170 }, + { x: 800, y: 40, hue: 190, delay: 2, size: 120 }, + { x: 1470, y: 560, hue: 20, delay: 3, size: 140 }, + { x: 140, y: 620, hue: 280, delay: 4, size: 120 }, + { x: 1340, y: 380, hue: 300, delay: 5, size: 130 }, +] + +// Every name carries `fw`: the layer shares one document with a theme's own classes and keyframes. +// A burst RESTS open and its keyframes hide it ahead of its start and behind its end: where the app +// holds a scene still (no GPU, or animation off) the bursts then stand for the show, not vanish. +// Held still, only the bursts to the right of the words' column rest open (`fw-shut` rests the others closed): +// an open burst over the conversation or under the sidebar's labels would sit on text for as long as the +// scene is held. Running, the keyframes name every moment, so the class changes nothing. +// A person who asked their system for less motion asked for no picture either: there every burst rests closed. +const STYLE = + '<style>' + + '.fw-bloom{transform-box:view-box;transform:scale(1);opacity:.55;stroke-width:3;stroke-linecap:round;' + + 'animation:fw-bloom 1.7s cubic-bezier(.15,.7,.3,1) both}' + + '.fw-bloom.fw-shut{opacity:0}' + + '@keyframes fw-bloom{0%{transform:scale(0);opacity:0}12%{opacity:1}65%{transform:scale(1);opacity:1}' + + '100%{transform:scale(1.12);opacity:0}}' + + '@media (prefers-reduced-motion: reduce){.fw-bloom{animation:none;opacity:0}}' + + '</style>' + +// In picture units (1600 wide) the words' column ends at about 1150 WITH THE RIGHT PANEL OPEN at 1200, 1680 and 1920 +// wide, and at 1209 at 1440 wide: the three bursts that rest open begin at 1210, 1210 and 1330, so they clear it there +// by one unit, and a new burst is placed against 1210, not against this constant. With the panel shut the column runs +// further right (to about 1300, 1390 and 1470 to 1500 at 1680, 1440 and 1200 wide) and these three reach into it: no +// place clears the words in every state, and the veil under the column is what carries them there. +const WORDS_END_X = 1150 + +/** Whether a burst, held still, rests open: its whole reach to the right of the words' column with the right panel open. */ +export function restsOpen(spot: { x: number; size: number }): boolean { + return spot.x - spot.size > WORDS_END_X +} + +/** One burst: eighteen spokes opening from a bright core. */ +function burst(spot: Burst, lightness: number): string { + const spokes: string[] = [] + + for (let index = 0; index < 18; index += 1) { + const angle = (index / 18) * Math.PI * 2 + const inner = spot.size * 0.18 + const outer = spot.size * (index % 2 === 0 ? 1 : 0.72) + const fromX = (spot.x + Math.cos(angle) * inner).toFixed(1) + const fromY = (spot.y + Math.sin(angle) * inner).toFixed(1) + const toX = (spot.x + Math.cos(angle) * outer).toFixed(1) + const toY = (spot.y + Math.sin(angle) * outer).toFixed(1) + + spokes.push(`<line x1="${fromX}" y1="${fromY}" x2="${toX}" y2="${toY}"/>`) + } + + return ( + `<g class="${restsOpen(spot) ? 'fw-bloom' : 'fw-bloom fw-shut'}" style="transform-origin:${spot.x}px ${spot.y}px;` + + `animation-delay:${spot.delay.toFixed(2)}s" stroke="hsl(${spot.hue} 95% ${lightness}%)">` + + `<circle cx="${spot.x}" cy="${spot.y}" r="${(spot.size * 0.12).toFixed(1)}" ` + + `fill="hsl(${spot.hue} 100% ${lightness + 17}%)" stroke="none"/>${spokes.join('')}</g>` + ) +} + +/** The bursts alone, to lay over a scene: bright over a dark scene, deep over a pale one, so both read. */ +function layer(window: Theme['window']): string { + const lightness = window === 'dark' ? 68 : 40 + + return STYLE + BURSTS.map(spot => burst(spot, lightness)).join('') +} + +const built = new Map<string, string>() + +/** A theme's own scene with the bursts drawn over it: one document still, the theme never taken away. */ +export function sceneWithFireworks(theme: Theme, scene: string): string { + const cached = built.get(theme.id) + + if (cached !== undefined) { + return cached + } + + const end = scene.lastIndexOf('</svg>') + const whole = end === -1 ? scene : scene.slice(0, end) + layer(theme.window) + '</svg>' + + built.set(theme.id, whole) + + return whole +} + +/** The show of a session with no theme: the bursts over a night sky of their own. */ +export function nightScene(): string { + return ( + '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1600 1000" width="100%" height="100%" ' + + 'preserveAspectRatio="xMidYMid slice" font-family="system-ui,sans-serif" color="#e8ecff">' + + '<defs><linearGradient id="fw-sky" x1="0" y1="0" x2="0" y2="1">' + + '<stop offset="0" stop-color="#070b1c"/><stop offset="1" stop-color="#1a1436"/></linearGradient></defs>' + + '<rect width="1600" height="1000" fill="url(#fw-sky)"/>' + + layer('dark') + + '</svg>' + ) +} + +/** The theme id a show's backdrop id stands for, or nothing where the id is no show's. */ +export function themeIdOfShow(id: string): string | undefined { + const suffix = SHOW_SUFFIXES.find(candidate => id.endsWith(candidate)) + + return suffix === undefined ? undefined : id.slice(0, id.length - suffix.length) +} diff --git a/plugins/theme-examples/hooks/hooks.json b/plugins/theme-examples/hooks/hooks.json new file mode 100644 index 00000000..5a63f649 --- /dev/null +++ b/plugins/theme-examples/hooks/hooks.json @@ -0,0 +1 @@ +{ "modules": ["./register.tsx"] } diff --git a/plugins/theme-examples/hooks/project-key.ts b/plugins/theme-examples/hooks/project-key.ts new file mode 100644 index 00000000..27ed3d6a --- /dev/null +++ b/plugins/theme-examples/hooks/project-key.ts @@ -0,0 +1,238 @@ +// The key under which a project-wide theme is kept, made so that a session in a linked git worktree meets the choice of its project. +// Seven steps, (k1) to (k7). Every step that fails ends in the key every earlier version used: the prefix, then the session's root as answered. +// The first two calls are not caught here: register.tsx catches them, to the same end. +// (d3) to (d5) say what is kept in the process and which keys a read, a write and a clear take. +// Erasable TypeScript only, no import: it runs under node's own type stripping. + +/** What the stat of the engine answers. A missing or withheld path is a rejection, not an answer. */ +export interface StatAnswer { + kind: 'file' | 'directory' | 'other' + /** Absolute, every link followed. Absent where the engine gives none. */ + realPath?: string +} + +/** The four calls of the engine the key is made from. register.tsx binds them to the engine's own names. */ +export interface KeyEngine { + root(): Promise<string> + cwd(): Promise<string> + /** The root inside the repository of the session; null outside one. It may reject on an older engine. */ + repo(): Promise<string | null> + stat(path: string): Promise<StatAnswer> +} + +export type KeyStep = + | 'k1-cwd-apart' + | 'k2-no-repository' + | 'k3-no-real-path' + | 'k4-no-entry' + | 'k5-main-tree' + | 'k6-own-root' + | 'k6-other-marker' + | 'k6-cwd-spelling' + | 'k6-linked-worktree' + | 'k7-other-kind' + +export interface KeyAnswer { + /** Read first; the only key that is written. */ + key: string + /** (d4) the key of today, read behind `key` and cleared with it; null where it must not be read. */ + olderKey: string | null + /** (d3) false: valid for this ask alone, asked again when the next turn begins. */ + keep: boolean + /** Which end of the seven steps gave the key. For tests and a debug line. */ + step: KeyStep +} + +/** (d3) what is kept in the process beside the root it was made for. */ +export interface KeptKey { + forRoot: string + answer: KeyAnswer +} + +/** (k4) a fixed cap beside the count of separators: it guards a loop that should not be. */ +export const WALK_CAP = 64 + +const ENTRY_NAME = '.git' + +function lastSeparatorIndex(path: string): number { + return Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\')) +} + +function separatorOf(path: string): string { + return path.includes('/') ? '/' : '\\' +} + +function countSeparators(path: string): number { + let count = 0 + for (const sign of path) { + if (sign === '/' || sign === '\\') count += 1 + } + return count +} + +function isBelow(path: string, folder: string): boolean { + return path.startsWith(folder + '/') || path.startsWith(folder + '\\') +} + +function isAtOrBelow(path: string, folder: string): boolean { + return path === folder || isBelow(path, folder) +} + +async function statOrNull( + engine: KeyEngine, + path: string, +): Promise<StatAnswer | null> { + try { + return await engine.stat(path) + } catch { + return null + } +} + +async function realPathOrNull( + engine: KeyEngine, + path: string, +): Promise<string | null> { + const answer = await statOrNull(engine, path) + return answer?.realPath ?? null +} + +async function repoOrNull(engine: KeyEngine): Promise<string | null> { + try { + return await engine.repo() + } catch { + return null + } +} + +function keyOfToday( + prefix: string, + rootAsAnswered: string, + keep: boolean, + step: KeyStep, +): KeyAnswer { + return { key: prefix + rootAsAnswered, olderKey: null, keep, step } +} + +/** (k5) and the first two ends of (k6): the real path of the root, the key of today behind it where the strings part. */ +function keyOfRealRoot( + prefix: string, + rootAsAnswered: string, + realRoot: string, + step: KeyStep, +): KeyAnswer { + const key = prefix + realRoot + const today = prefix + rootAsAnswered + return { key, olderKey: today === key ? null : today, keep: true, step } +} + +interface WalkFind { + top: string + kind: StatAnswer['kind'] +} + +/** (k4) from the real root upward, one stat a step on the entry; a rejected step counts as no entry. */ +async function findWorkingTreeTop( + engine: KeyEngine, + realRoot: string, +): Promise<WalkFind | null> { + const steps = Math.min(countSeparators(realRoot), WALK_CAP) + let folder = realRoot + for (let step = 0; step < steps; step += 1) { + const entry = await statOrNull( + engine, + folder + separatorOf(realRoot) + ENTRY_NAME, + ) + if (entry !== null) return { top: folder, kind: entry.kind } + const cut = lastSeparatorIndex(folder) + if (cut <= 0) return null + folder = folder.slice(0, cut) + } + return null +} + +/** The seven steps. Every step that fails ends in the key of today; a rejection of the first two calls is the caller's to catch. It reads; it writes and keeps nothing. */ +export async function makeProjectKey( + engine: KeyEngine, + prefix: string, +): Promise<KeyAnswer> { + const rootAsAnswered = await engine.root() + const cwdAsAnswered = await engine.cwd() + + const realRoot = await realPathOrNull(engine, rootAsAnswered) + if (realRoot === null) + return keyOfToday(prefix, rootAsAnswered, true, 'k3-no-real-path') + const realCwd = await realPathOrNull(engine, cwdAsAnswered) + if (realCwd !== realRoot) + return keyOfToday(prefix, rootAsAnswered, false, 'k1-cwd-apart') + + const repoAsAnswered = await repoOrNull(engine) + if (repoAsAnswered === null) + return keyOfToday(prefix, rootAsAnswered, true, 'k2-no-repository') + + const realRepo = await realPathOrNull(engine, repoAsAnswered) + if (realRepo === null) + return keyOfToday(prefix, rootAsAnswered, true, 'k3-no-real-path') + + const find = await findWorkingTreeTop(engine, realRoot) + if (find === null) + return keyOfToday(prefix, rootAsAnswered, true, 'k4-no-entry') + + if (find.kind === 'directory') + return keyOfRealRoot(prefix, rootAsAnswered, realRoot, 'k5-main-tree') + if (find.kind !== 'file') + return keyOfToday(prefix, rootAsAnswered, true, 'k7-other-kind') + + if (realRepo === find.top) + return keyOfRealRoot(prefix, rootAsAnswered, realRoot, 'k6-own-root') + if (isBelow(realRepo, find.top) && isAtOrBelow(realRoot, realRepo)) { + return keyOfRealRoot(prefix, rootAsAnswered, realRoot, 'k6-other-marker') + } + // The belt: the engine climbed from a spelling that is not the real one. Folded to one unicode form for this one compare alone. + if (cwdAsAnswered.normalize('NFC') !== realCwd.normalize('NFC')) { + return keyOfToday(prefix, rootAsAnswered, true, 'k6-cwd-spelling') + } + const restBelowTop = realRoot.slice(find.top.length) + return { + key: prefix + realRepo + restBelowTop, + olderKey: null, + keep: true, + step: 'k6-linked-worktree', + } +} + +export interface KeyLookup { + answer: KeyAnswer + kept: KeptKey | null +} + +/** (d3) made once and kept beside the root; made again only when the root has moved, or where nothing was kept. */ +export async function projectKeyFor( + engine: KeyEngine, + prefix: string, + kept: KeptKey | null, +): Promise<KeyLookup> { + const rootAsAnswered = await engine.root() + if (kept !== null && kept.forRoot === rootAsAnswered) + return { answer: kept.answer, kept } + const answer = await makeProjectKey(engine, prefix) + return { + answer, + kept: answer.keep ? { forRoot: rootAsAnswered, answer } : null, + } +} + +/** (d4) the order of a read: the first key that holds a pick wins. */ +export function keysToRead(answer: KeyAnswer): string[] { + return answer.olderKey === null ? [answer.key] : [answer.key, answer.olderKey] +} + +/** (d5) a write goes to the new key alone. */ +export function keyToWrite(answer: KeyAnswer): string { + return answer.key +} + +/** (d5) a clear project-wide takes both where both are read, else the older pick comes back at the next read. */ +export function keysToClear(answer: KeyAnswer): string[] { + return keysToRead(answer) +} diff --git a/plugins/theme-examples/hooks/register.tsx b/plugins/theme-examples/hooks/register.tsx new file mode 100644 index 00000000..ffbb7035 --- /dev/null +++ b/plugins/theme-examples/hooks/register.tsx @@ -0,0 +1,1076 @@ +import { atom, read, update } from 'claude-code' +import type { EngineInterface, Register, Timer } from 'claude-code' + +import { + NIGHT_GLASS, + NIGHT_ID, + SHOW_SUFFIXES, + WORD, + nightScene, + sceneWithFireworks, + themeIdOfShow, +} from './fireworks' +import { keyToWrite, keysToClear, keysToRead, projectKeyFor } from './project-key' +import type { KeptKey, KeyEngine } from './project-key' +import { THEMES, sceneFault, sceneOf } from './themes' +import type { Theme } from './themes' +import type { ThemeChoice } from '../types' + +const PLUGIN = 'theme-examples' +const CARD = 'theme-card' +// Not `theme`: that is the engine's own command (the terminal's color theme). +const COMMAND = 'custom-theme' +const PREVIEW_MS = 20_000 +const FIREWORKS_COMMAND = 'fireworks' +const SHOW_MS = 7000 +// Holds 'off' where the person turned the show on the word off; absent, it is on. One key for every session and project. +const AUTO_KEY = 'fireworks:auto' +const SESSION_PREFIX = 'session:' +// How many sessions' own choices the store keeps: past it, the one written longest ago goes. +const SESSIONS_KEPT = 200 +// Said where a theme is set and the engine answers that nothing draws it. That answer is what the attached windows said of themselves at the moment of +// the set: one that attaches later still draws the theme, and one that draws themes under another name than this engine asks after draws it all the +// same. An engine with none of the three calls is answered the same way (setBackdrop's last line), and there nothing draws it. So the words hold +// whether or not the theme shows, and never say why. +const UNSHOWN = 'If no theme shows, this window may not draw themes yet' +const KEPT_UNSHOWN = `${UNSHOWN}. Your choice is saved.` +const SHOW_UNSHOWN = 'If none shows, this window may not draw them yet.' +// The module's own variables start over on a reload: so does a show in flight, which is fine for a show. +// `starting` from the tick a show is asked for until its timer stands: see `fireworks`. +let showEnding: Timer | 'starting' | undefined +let showCount = 0 +let previewEnding: Timer | undefined +// The loader's scan reads this reference: both names are written as string literals. +const choice = atom({ plugin: 'theme-examples', key: 'choice' } as const, {}, { + shape: 'choice-1', +}) + +/** What a set comes to on any engine, as far as this mod reads it: drawn or not. */ +type BackdropAnswer = { isDrawn: boolean } +type BackdropChoice = { id: string; glass: Theme['glass']; colorScheme?: Theme['window'] } +/** The engines this mod meets, for the type checker alone: the theme noun or the older call may be absent. */ +type AnyEngine = { + theme?: { set(args: unknown): Promise<BackdropAnswer>; clear(): Promise<unknown> } + // `toast` is named only so that this type shares a member with every engine's ui noun: the checker refuses one that shares none. + ui: { toast: EngineInterface['ui']['toast']; backdrop?(args: BackdropChoice | undefined): Promise<BackdropAnswer> } +} +// The way of setting a backdrop this engine took, learnt at the first set that can tell; a reload learns it again. +let taken: 'beside' | 'nested' | 'older' | 'none' | undefined + +/** + * A try may be followed by the next one only where the engine lacks the call (reaching for it throws a TypeError) or + * refuses the shape as one it does not know: in its own words for that, or by naming the member that this try alone + * bears, should those words ever move. Any other fault is the caller's to see. + * NO CALL IS ASKED AFTER AHEAD OF ITS TRY: the engine loads a module only where each call on its handle is called on the + * spot; one that is read, bound or passed keeps the whole module from loading. So each is made, and its fault judged. + */ +function isNotThisEnginesWay(error: unknown, member?: string): boolean { + return ( + error instanceof TypeError || + (error instanceof Error && + (error.message.includes('does not know the attribute') || (member !== undefined && error.message.includes(member)))) + ) +} + +/** + * Sets a backdrop by whichever call this engine has: the theme noun with the window's kind beside the backdrop, the + * theme noun with it inside the backdrop, or the older call on the ui noun. The calls are written out plainly, each in + * its own try: a call the engine lacks throws as it is reached for, and a shape it does not take it refuses. THE NEWEST FIRST: an engine that + * wants the kind beside the backdrop takes the one inside it too, and drops it without a word. + * THE SCENE's NAME GOES UNDER TWO NAMES AT ONCE in the newest shape: the newest engines read `scene`, the ones before + * them `id`. Each engine's own theme noun lets the members it knows cross and drops any other, so one shape serves both; + * a backdrop with the one name alone is refused by the engines that read the other, in words that name no unknown attribute. + * Answers nothing where no way was taken. + */ +async function setByAWay($: AnyEngine, backdrop: BackdropChoice): Promise<BackdropAnswer | undefined> { + if (taken === undefined || taken === 'beside') { + try { + const set = await $.theme!.set({ + backdrop: { scene: backdrop.id, id: backdrop.id, glass: backdrop.glass }, + ...(backdrop.colorScheme !== undefined && { overrideColorScheme: backdrop.colorScheme }), + }) + + // With no kind to hand over this shape is the next one's too: it tells nothing of the engine, so nothing is learnt. + // A belt: learnt wrongly here, the next set with a kind would be refused once and the ways walked anew. + if (backdrop.colorScheme !== undefined) { + taken = 'beside' + } + + return set + } catch (error) { + if (!isNotThisEnginesWay(error, 'overrideColorScheme')) throw error + } + } + + if (taken === undefined || taken === 'nested') { + try { + const set = await $.theme!.set({ + backdrop: { + id: backdrop.id, + glass: backdrop.glass, + ...(backdrop.colorScheme !== undefined && { colorScheme: backdrop.colorScheme }), + }, + }) + taken = 'nested' + + return set + } catch (error) { + if (!isNotThisEnginesWay(error)) throw error + } + } + + if (taken === undefined || taken === 'older') { + try { + // The older call is given the id and the glass alone. + const set = await $.ui.backdrop!({ id: backdrop.id, glass: backdrop.glass }) + taken = 'older' + + return set + } catch (error) { + if (!isNotThisEnginesWay(error)) throw error + } + } + + return undefined +} + +/** + * A way once learnt is the only one tried. Where the engine does not take it after all the ways are walked anew; an + * engine with none of them draws nothing, and the answer says so. + */ +async function setBackdrop($: AnyEngine, backdrop: BackdropChoice): Promise<BackdropAnswer> { + if (taken === 'none') { + return { isDrawn: false } + } + + const learnt = taken + const set = await setByAWay($, backdrop) + + if (set !== undefined) { + return set + } + + if (learnt !== undefined) { + taken = undefined + + const again = await setByAWay($, backdrop) + + if (again !== undefined) { + return again + } + } + + taken = 'none' + + return { isDrawn: false } +} + +/** Clears the backdrop by whichever call this engine has; an engine with neither is left alone. */ +async function clearBackdrop($: AnyEngine): Promise<void> { + try { + await $.theme!.clear() + + return + } catch (error) { + if (!isNotThisEnginesWay(error)) throw error + } + + try { + await $.ui.backdrop!(undefined) + } catch (error) { + if (!isNotThisEnginesWay(error)) throw error + } +} + +/** + * The scene's name as the engine hands it to the Backdrop hook: under `scene` on the newest engines, under `id` on the + * ones before them. Read under either, the newer first: a hook that knew the one name alone would find no theme on the + * other engines and pass the ask on, and nothing would say so. + */ +function sceneNameOf(props: { scene?: unknown; id?: unknown }): string | undefined { + if (typeof props.scene === 'string') { + return props.scene + } + + return typeof props.id === 'string' ? props.id : undefined +} + +function themeOf(id: string | undefined): Theme | undefined { + return THEMES.find(theme => theme.id === id) +} + +/** A name as typed, a title as shown and an id all come to one key: lower case, each run of anything else a hyphen. */ +function keyOf(text: string): string { + return text + .toLowerCase() + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-|-$/g, '') +} + +/** The theme a person named: by its id or its title, in any case, with spaces or hyphens between the words. */ +function themeNamed(text: string): Theme | undefined { + const key = keyOf(text) + + return THEMES.find(theme => theme.id === key || keyOf(theme.title) === key) +} + +/** How many single-letter edits turn one word into the other. */ +function editsBetween(from: string, to: string): number { + let row = Array.from({ length: to.length + 1 }, (_, column) => column) + + for (let line = 1; line <= from.length; line += 1) { + const next = [line] + + for (let column = 1; column <= to.length; column += 1) { + const swap = (row[column - 1] ?? 0) + (from[line - 1] === to[column - 1] ? 0 : 1) + + next.push(Math.min(swap, (row[column] ?? 0) + 1, (next[column - 1] ?? 0) + 1)) + } + + row = next + } + + return row[to.length] ?? 0 +} + +/** + * The theme whose name is nearest a mistyped one. A few edits away speaks first (one id can be the start of another: + * plotter-tide and plotter-tide-night); else the longest id the typed name starts with (a name with a wrong word behind + * it); else the first id that starts with what was typed; else none. + */ +function nearestTheme(text: string): Theme | undefined { + const key = keyOf(text) + + if (key === '') return undefined + + const byEdits = THEMES.map(theme => ({ theme, edits: editsBetween(key, theme.id) })).sort( + (one, other) => one.edits - other.edits, + ) + const nearest = byEdits[0] + + if (nearest !== undefined && nearest.edits <= Math.max(2, Math.floor(key.length / 3))) { + return nearest.theme + } + + const startsIt = THEMES.filter(theme => key.startsWith(theme.id)).sort( + (one, other) => other.id.length - one.id.length, + ) + + return startsIt[0] ?? THEMES.find(theme => theme.id.startsWith(key)) +} + +/** The two kinds of window, in the order the list and the card show them. */ +const WINDOWS = ['dark', 'light'] as const + +/** The themes made for one kind of window, a row each: the name to type, its title, what it is, and its twin's name. */ +function rowsFor(window: Theme['window']): string[] { + return THEMES.filter(theme => theme.window === window).map(theme => { + const twin = themeOf(theme.twin) + + return ` ${theme.id}: ${theme.title}. ${theme.blurb}${twin === undefined ? '' : ` (for ${twin.window} windows: ${twin.id})`}` + }) +} + +/** Every theme by the name to type, under the window it is made for. */ +function themeList(): string { + return [ + `Theme examples (${THEMES.length}):`, + ...WINDOWS.flatMap(window => [`For ${window} windows:`, ...rowsFor(window)]), + `Apply one with /${COMMAND} <name>, add "session" for this session only, /${COMMAND} off clears it.`, + ].join('\n') +} + +/** + * Shows a theme behind the chat, or with none clears the session's theme, and answers what a set came to. + * A clear takes away whatever theme stands, whichever mod set it, so `show` is given none only on a person's ask + * (off, a preview's end, a show's end) or to take a theme of this mod's own away, never over a window it left bare. + */ +async function show($: EngineInterface, id: string | undefined): Promise<BackdropAnswer | undefined> { + const theme = themeOf(id) + + if (theme === undefined) { + await clearBackdrop($) + + return undefined + } + + return setBackdrop($, { id: theme.id, glass: theme.glass, colorScheme: theme.window }) +} + +const PROJECT_PREFIX = 'project:' + +// The key made for a root is kept beside that root and made again only when the root has moved. A reload starts it over. +let keptProjectKey: KeptKey | null = null +// The end last told to the log: told again only when it changes, so a turn's start adds no line. +let toldKeyStep: string | undefined + +/** + * Says which end of the seven steps gave the project's key, or that the making failed: no path and no key. + * TO THE DEBUG LOG ALONE: with no option the engine's log call appends a line to the person's transcript. + * The engine leads every such line with the plugin's name: the text does not say it again. + */ +async function tellKeyStep($: EngineInterface, step: string): Promise<void> { + if (step === toldKeyStep) { + return + } + + toldKeyStep = step + + try { + await $.ui.log(`the project's key came by ${step}`, { to: 'debug' }) + } catch { + // An engine without that call, or one that refuses it: nothing more to tell. + } +} + +/** The engine's four calls as the key's maker asks them: the repository's root alone, and the stat's `dir` as its `directory`. */ +function keyEngineOf($: EngineInterface): KeyEngine { + return { + root: () => $.session.root(), + cwd: () => $.session.cwd(), + repo: async () => (await $.session.repo())?.root ?? null, + stat: async path => { + const { kind, realPath } = await $.fs.stat(path, { resolve: true }) + const told = kind === 'dir' ? 'directory' : kind + + return realPath === undefined ? { kind: told } : { kind: told, realPath } + }, + } +} + +/** The keys a project's choice is read under, in order; the one it is written under; the ones a clear takes away. */ +type ProjectKeys = { read: string[]; write: string; clear: string[] } + +/** + * One choice per project: a session in a linked git worktree shares the key of the matching folder in the main tree. + * A fault nobody foresaw in the making ends where each foreseen one does: in the key every earlier version used. + */ +async function projectKeys($: EngineInterface): Promise<ProjectKeys> { + try { + const found = await projectKeyFor(keyEngineOf($), PROJECT_PREFIX, keptProjectKey) + + keptProjectKey = found.kept + await tellKeyStep($, found.answer.step) + + return { read: keysToRead(found.answer), write: keyToWrite(found.answer), clear: keysToClear(found.answer) } + } catch { + const today = `${PROJECT_PREFIX}${await $.session.root()}` + + await tellKeyStep($, 'fault') + + return { read: [today], write: today, clear: [today] } + } +} + +/** What the store keeps for one session: its own theme's id, or null where it chose none. */ +type SessionChoice = { theme: string | null } + +/** An id an engine may not offer: a fault counts as no answer. */ +async function orNothing(ask: () => Promise<string | undefined>): Promise<string | undefined> { + try { + return await ask() + } catch { + return undefined + } +} + +/** + * The key a session's own choice is stored under: one per row a person sees in the desktop app, else one per + * Claude Code session. An empty id counts as none. With neither id there is no key, and the choice lasts as long + * as this process does. + */ +async function sessionKey($: EngineInterface): Promise<string | undefined> { + const id = + // The desktop app's own name for its row, unpromised: it outlives /clear and an archive. Unset (the terminal, another app), the next line serves. + (await orNothing(() => $.env.get('CLAUDE_CODE_HOST_SESSION_ID'))) || + (await orNothing(() => $.session.id())) + + return id === undefined || id === '' ? undefined : `${SESSION_PREFIX}${id}` +} + +/** The choice stored under a session's key, or nothing: none was made, or its theme is no longer in the table. */ +async function sessionChoice($: EngineInterface, key: string): Promise<SessionChoice | undefined> { + const stored = await $.store.get(key) + + if (typeof stored !== 'object' || stored === null || !('theme' in stored)) { + return undefined + } + + const theme = stored.theme + + return theme === null || (typeof theme === 'string' && themeOf(theme) !== undefined) ? { theme } : undefined +} + +/** + * Stores a session's own choice. The key is taken out first, so that the store's order is the order of the last + * writes and the cap drops the session that chose longest ago. Those are two writes: where the second fails, what + * stood is put back as far as the store lets it, so that a choice that was not applied does not cost the earlier one. + * The cap is housekeeping: its fault costs the choice nothing. + */ +async function keepForSession($: EngineInterface, key: string, id: string | undefined): Promise<void> { + const kept: SessionChoice = { theme: id ?? null } + const stood = await $.store.get(key) + + await $.store.delete(key) + + try { + await $.store.set(key, kept) + } catch (error) { + if (stood !== undefined) { + try { + await $.store.set(key, stood) + } catch { + // The first fault is the one to tell. + } + } + + throw error + } + + try { + const keys = (await $.store.keys()).filter(name => name.startsWith(SESSION_PREFIX)) + + for (const oldest of keys.slice(0, Math.max(0, keys.length - SESSIONS_KEPT))) { + await $.store.delete(oldest) + } + } catch { + // The next choice tries again. + } +} + +/** + * THE ONE WAY this mod changes which theme stands behind the chat: nothing else calls `show`. + * It asks the engine for a theme (or none) and only then keeps the choice: `keep` writes the store or the state. + * A set the engine refuses throws here with nothing written and what stood still shown. Where `keep` fails, the + * window is put back to what stood, so that what a person sees and what they are told agree, and that first + * fault is thrown on, whatever the put-back comes to. Each caller words its own plain sentence from the fault. + * It answers what the set came to: a set the engine takes may be drawn by no surface, and the choice is kept all the + * same (the engine hands what stands to a client that joins the session later and draws backdrops). A caller with a + * person to tell says so; one that runs unasked stays quiet. + */ +async function showThenKeep( + $: EngineInterface, + id: string | undefined, + keep?: () => Promise<unknown>, +): Promise<BackdropAnswer | undefined> { + const stood = await read($, choice) + const set = await show($, id) + + try { + await keep?.() + } catch (error) { + try { + await show($, stood.preview ?? stood.applied) + } catch { + // The first fault is the one to tell. + } + + throw error + } + + return set +} + +/** + * Applies a theme (or none) to this session, and with `forProject` to every later session of the project. + * A choice for this session alone is stored under the session's key; one for the project takes that key away. + */ +async function apply( + $: EngineInterface, + id: string | undefined, + forProject: boolean, +): Promise<BackdropAnswer | undefined> { + return showThenKeep($, id, async () => { + const own = await sessionKey($) + + // The session's key first: where that fails, nothing is written for the project, and "could not be applied" is true. + if (own !== undefined) { + await (forProject ? $.store.delete(own) : keepForSession($, own, id)) + } + + if (forProject) { + const keys = await projectKeys($) + + if (id === undefined) { + for (const key of keys.clear) { + await $.store.delete(key) + } + } else { + await $.store.set(keys.write, id) + } + } + + await update($, choice, (was): ThemeChoice => ({ + cardInBand: was.cardInBand, + cardAway: was.cardAway, + applied: id, + scope: forProject ? 'project' : 'session', + })) + }) +} + +/** A fault's own words. */ +function reasonOf(error: unknown): string { + return error instanceof Error ? error.message : String(error) +} + +/** + * Runs a step that must never cost a person their start or their prompt: its fault is told in one dim line of the + * transcript, which is not sent to the model: the one sign a person gets. No toast: one at every turn would nag. + */ +async function quietly($: EngineInterface, step: () => Promise<void>): Promise<void> { + try { + await step() + } catch (error) { + try { + await $.ui.log(`a step nobody waits on failed, and the window stays as it is (${reasonOf(error)})`) + } catch { + // An engine without that call, or one that refuses it: nothing more to tell. + } + } +} + +/** + * What is said where a theme is set that no surface draws. Only a project's choice is said to be saved: it is always + * stored. A session's own is stored under the id of the moment, and with no id not at all. No place is promised. + */ +function unshownNote(isSaved: boolean): string { + return isSaved ? KEPT_UNSHOWN : `${UNSHOWN}.` +} + +/** What became of a pick: a fault's one plain sentence; or none, and whether a theme was set that no surface draws. */ +type Picked = { fault: string } | { fault: undefined; isUnshown: boolean } + +/** + * Applies what a person picked, a theme or none, or says in one plain sentence why it could not: a scene that does + * not build, a set the engine refuses, a store that fails, in the fault's own words. A person must read why, not the + * engine's hint for authors. Nothing is kept then and the theme that stood stays. + * A clear promises nothing to see, so it is never unshown. + */ +async function applyOrSay( + $: EngineInterface, + theme: Theme | undefined, + forProject: boolean, +): Promise<Picked> { + const fault = theme === undefined ? undefined : sceneFault(theme) + + if (theme !== undefined && fault !== undefined) { + return { fault: `${theme.title} could not be drawn: ${fault}` } + } + + try { + const set = await apply($, theme?.id, forProject) + + return { fault: undefined, isUnshown: set?.isDrawn === false } + } catch (error) { + return { + fault: + theme === undefined + ? `The theme could not be cleared: ${reasonOf(error)}` + : `${theme.title} could not be applied: ${reasonOf(error)}`, + } + } +} + +/** The project's stored choice: a theme's id, or none. The first key that holds one wins. */ +async function projectChoice($: EngineInterface): Promise<string | undefined> { + for (const key of (await projectKeys($)).read) { + const stored = await $.store.get(key) + + if (typeof stored === 'string' && themeOf(stored) !== undefined) { + return stored + } + } + + return undefined +} + +/** + * Brings a session to the choice it is due: at a start, and at each turn's start, so that a session open while + * another one changed the project takes the change at its next turn. + * A session with a choice of its own in this process is left alone. A choice kept before the scope was is the + * session's own where it differs from the project's (it can only have come from this session), else the project's. + * A session whose own choice an earlier process stored takes that up again. Any other follows its project. + * ONE RULE FOR THE TWO IDS: the key of the moment is the only one read or written. Where this process holds the + * session's own choice and the store holds nothing under that key (the app's id came late), the choice is written + * there: the same process, so nothing is guessed. No choice is ever looked for under another key. + */ +async function followChoice($: EngineInterface): Promise<void> { + const now = await read($, choice) + const project = await projectChoice($) + const isOwn = now.scope === 'session' || (now.scope === undefined && now.applied !== undefined && now.applied !== project) + + if (now.preview !== undefined || showEnding !== undefined) { + return + } + + const key = await sessionKey($) + const kept = key === undefined ? undefined : await sessionChoice($, key) + + if (isOwn) { + if (key !== undefined && kept === undefined) { + await keepForSession($, key, now.applied) + } + + return + } + + if (kept !== undefined) { + const own = kept.theme ?? undefined + const take = (): Promise<unknown> => + update($, choice, (was): ThemeChoice => ({ ...was, applied: own, scope: 'session' })) + + // None chosen and none shown: the engine is asked nothing, or a clear would take another mod's theme away. + await (own === undefined && now.applied === undefined ? take() : showThenKeep($, own, take)) + + return + } + + if (now.applied === project) { + return + } + + // Asked first: a theme the engine refuses is not taken as applied, and the next turn tries it again. + await showThenKeep($, project, () => + update($, choice, (was): ThemeChoice => ({ ...was, applied: project, scope: 'project' })), + ) +} + +/** + * Ends a look at a theme unless it was applied meanwhile: back to what the session shows. + * An end runs from a timer, with nobody to tell: it runs `quietly`. One that comes after the mod is unloaded or the + * session is over is refused by the engine, and so is its note: nothing is left for the mod to do. + */ +async function endPreview($: EngineInterface, id: string): Promise<void> { + previewEnding = undefined + + const later = await read($, choice) + + if (later.preview === id) { + await showThenKeep($, later.applied, () => update($, choice, was => ({ ...was, preview: undefined }))) + } +} + +/** + * Ends a show: back to the theme the session shows, or to no backdrop where it has none. + * The flag is let go only once the window is back, however that went: an ask that came while the end waited on the + * engine would else start a show that this end then draws over. + */ +async function endFireworks($: EngineInterface): Promise<void> { + try { + const later = await read($, choice) + + await showThenKeep($, later.preview ?? later.applied) + } finally { + showEnding = undefined + } +} + +/** + * Seven seconds of fireworks: over the session's theme where it has one, else over a night sky of their own. + * ONE SHOW AT A TIME: a word or a command that comes while a show runs starts nothing and lengthens nothing, so + * however often the word is said the window changes twice in a show's seconds and no oftener. + * The flag is TAKEN IN THE SAME TICK AS IT IS TESTED, ahead of the first await: a command and a reply's block come on + * their own clocks, and a second ask that came while the first waited on the engine would else pass the test too. + * KNOWN: the timer's call stands outside the try. It throws only where the mod is already unloaded, and this load's + * flag goes with the load. A wait that another mod's hook refuses is not thrown here, it is never run: the flag then + * stays up, with no further show and no following of the project, until a reload. + * A show that no surface says it draws runs its seconds all the same: a window may draw it without having said so. + * The answer then bears one sentence more. + */ +async function fireworks($: EngineInterface): Promise<string> { + if (showEnding !== undefined) { + return 'Fireworks are already going.' + } + + showEnding = 'starting' + showCount += 1 + + // The theme stays: a show is a sibling backdrop that draws the theme's scene with the bursts over it. + const suffix = SHOW_SUFFIXES[showCount % SHOW_SUFFIXES.length] ?? SHOW_SUFFIXES[0] + // The one setter beside showThenKeep: a show's backdrop is no theme of the table, its answer is told, and nothing is kept, so nothing is to put back. + let set: BackdropAnswer + + try { + const now = await read($, choice) + const theme = themeOf(now.preview ?? now.applied) + + set = await setBackdrop( + $, + theme === undefined + ? { id: NIGHT_ID, glass: NIGHT_GLASS } + : { id: `${theme.id}${suffix}`, glass: theme.glass, colorScheme: theme.window }, + ) + } catch (error) { + // A show that did not begin costs a reply nothing, and the next word may try again. + showEnding = undefined + + return `Fireworks could not be shown: ${reasonOf(error)}` + } + + showEnding = $.clock.after(SHOW_MS, () => void quietly($, () => endFireworks($))) + + return set?.isDrawn === false ? `Fireworks. ${SHOW_UNSHOWN}` : 'Fireworks.' +} + +/** + * Whether a show may go off by itself on the word: yes, unless the person turned that off. + * A store that cannot be read counts as off: on a doubt no picture comes unasked. + */ +async function goesOffByItself($: EngineInterface): Promise<boolean> { + try { + return (await $.store.get(AUTO_KEY)) !== 'off' + } catch { + return false + } +} + +/** `/fireworks` alone starts a show, whatever the key holds; `auto off` and `auto on` write the key. */ +async function fireworksCommand($: EngineInterface, args: string): Promise<string> { + const words = args.trim().toLowerCase().split(/\s+/).join(' ') + + if (words === '') { + return fireworks($) + } + + if (words !== 'auto off' && words !== 'auto on') { + return 'Try /fireworks, /fireworks auto off or /fireworks auto on.' + } + + try { + await (words === 'auto off' ? $.store.set(AUTO_KEY, 'off') : $.store.delete(AUTO_KEY)) + } catch (error) { + return `That could not be kept: ${reasonOf(error)}` + } + + return words === 'auto off' + ? 'Fireworks no longer go off by themselves. /fireworks still starts a show.' + : 'Fireworks go off again when Claude says "merged".' +} + +type CardElements = Pick< + ReturnType<EngineInterface['ui']['resolve']>, + 'Box' | 'Text' | 'Button' +> + +/** Puts the card away, placed or above the prompt, until the command shows it again. */ +async function putCardAway($: EngineInterface): Promise<void> { + await update($, choice, was => ({ ...was, cardInBand: false, cardAway: true })) +} + +/** + * A pick on the card: the theme (or none) applied, and the card put away, as a menu closes on a choice. + * A pick that could not be kept is said, and the card stays for another. One that is kept and that no surface draws is said too. + */ +async function pick($: EngineInterface, theme: Theme | undefined, forProject: boolean): Promise<void> { + const picked = await applyOrSay($, theme, forProject) + + if (picked.fault !== undefined) { + void $.ui.toast(picked.fault) + + return + } + + if (picked.isUnshown) { + void $.ui.toast(unshownNote(forProject)) + } + + await putCardAway($) +} + +/** + * The card. Close and No theme stand at its head, so that it can be put away without scrolling past twenty rows. + * The themes stand under the list's two heads, by the kind of window each is made for: a mod cannot learn which kind + * the window is, and not every window follows its theme, so the card is where a person is steered. A theme made in + * both kinds names its twin on a line of its own: its twin stands under the other head, and a row must not grow wider. + * Each theme is its title, its blurb beneath, and its three buttons kept together. The desktop draws a button's + * `label` and never its children, and a row there does not wrap; other surfaces draw the children. So both are one + * short word that carries the state, and the theme's title on the row above says whose the three are: twenty + * buttons share each word, and the keys alone tell them apart. + * Applied is said only of the project's choice; a session's own choice is marked on This session. + */ +function card($: EngineInterface, { Box, Text, Button }: CardElements, now: ThemeChoice) { + // Spacing flows from each parent's gap: more between two themes than anywhere inside one, so that a row of + // buttons reads as its own theme's. A title and its buttons share a row, which wraps where the card is narrow. + return ( + <Box flexDirection="column" borderStyle="round" paddingX={1} gap="md"> + <Box flexDirection="row" gap={1}> + <Text bold>Theme examples</Text> + <Button key="off" label="No theme" onPress={() => pick($, undefined, true)}> + No theme + </Button> + {/* Where a surface carries it, the keyboard's ring starts here: Enter on Close changes nothing but the card. */} + <Button + key="close" + label="Close" + role="dismiss" + autoFocus + onPress={() => putCardAway($)} + > + Close + </Button> + </Box> + {WINDOWS.map(window => ( + <Box key={`group-${window}`} flexDirection="column" gap="md"> + <Text key={`head-${window}`} size="heading" bold>{`For ${window} windows`}</Text> + {THEMES.filter(theme => theme.window === window).map(theme => { + const twin = themeOf(theme.twin) + const applyWord = now.applied === theme.id && now.scope !== 'session' ? 'Applied' : 'Apply' + const sessionWord = now.applied === theme.id && now.scope === 'session' ? '✓ This session' : 'This session' + const previewWord = now.preview === theme.id ? 'Previewing' : 'Preview' + + return ( + <Box key={`theme-${theme.id}`} flexDirection="column" gap="xs"> + <Box flexDirection="row" flexWrap="wrap" justifyContent="space-between" columnGap="md" rowGap="xs"> + <Text bold={now.applied === theme.id}> + {now.applied === theme.id ? '✓ ' : ''} + {theme.title} + </Text> + <Box flexDirection="row" gap={1}> + <Button key={`apply-${theme.id}`} label={applyWord} onPress={() => pick($, theme, true)}> + {applyWord} + </Button> + <Button + key={`session-${theme.id}`} + label={sessionWord} + onPress={() => pick($, theme, false)} + > + {sessionWord} + </Button> + <Button + key={`preview-${theme.id}`} + label={previewWord} + onPress={async () => { + let set: BackdropAnswer | undefined + + try { + set = await showThenKeep($, theme.id, () => update($, choice, was => ({ ...was, preview: theme.id }))) + } catch (error) { + // A look that did not begin leaves an earlier one its own end. + void $.ui.toast(`${theme.title} could not be shown: ${reasonOf(error)}`) + + return + } + + // This look's seconds start now: an earlier timer is stopped, or it would end this look early. + previewEnding?.cancel() + previewEnding = $.clock.after(PREVIEW_MS, () => void quietly($, () => endPreview($, theme.id))) + + // A look stores nothing: the short form. Behind the timer's start: nothing stands between the state's write and its clock. + if (set?.isDrawn === false) { + void $.ui.toast(unshownNote(false)) + } + }} + > + {previewWord} + </Button> + </Box> + </Box> + <Text dimColor>{theme.blurb}</Text> + {twin === undefined ? [] : [<Text key={`twin-${theme.id}`} dimColor>{`For ${twin.window} windows: ${twin.title}`}</Text>]} + </Box> + ) + })} + </Box> + ))} + </Box> + ) +} + +export const register: Register = on => { + on('session.start', async ($, e, next) => { + // A refused name must not cost the session its backdrop: go on without the command. + try { + await $.command.register({ + name: COMMAND, + description: + 'A backdrop behind the chat: alone it shows the card; with a theme\'s name it applies that theme to this project (add "session" for this session only); "list" names them, "off" clears.', + }) + } catch (error) { + void $.ui.toast(`theme-examples: /${COMMAND} is not available (${String(error)})`) + } + + try { + await $.command.register({ + name: FIREWORKS_COMMAND, + description: + 'Fireworks behind the chat for a few seconds, over the theme if there is one (they also go off when Claude says "merged": /fireworks auto off stops that)', + }) + } catch (error) { + void $.ui.toast(`theme-examples: /${FIREWORKS_COMMAND} is not available (${String(error)})`) + } + + // A preview left in the state has no clock in this load (the module's own variables start over): its end + // never ran. Drop it, or this session would never follow its project again. + if ((await read($, choice)).preview !== undefined) { + await update($, choice, was => ({ ...was, preview: undefined })) + } + + // A session's own choice outlives a reload and a new process; any other follows the project's. + // Two steps, each quiet by itself: a choice that cannot be followed must not cost the window what the state holds. + await quietly($, () => followChoice($)) + await quietly($, async () => { + const shown = (await read($, choice)).applied + + if (themeOf(shown) !== undefined) { + await showThenKeep($, shown) + } + }) + + return next(e) + }) + + // A turn's start: an open session takes a change another session made to the project. It always passes on: + // a fault of its own must never cost the person their prompt. + on('prompt.submit', async ($, e, next) => { + await quietly($, () => followChoice($)) + + return next(e) + }) + + on('command.run', { command: COMMAND }, async ($, e) => { + const words = e.args.trim().split(/\s+/).filter(word => word !== '') + const last = words.at(-1)?.toLowerCase() + // A scope word is the last of two or more words, and only these two: any other word is part of the name. + const isScoped = words.length > 1 && (last === 'session' || last === 'project') + const forProject = !(isScoped && last === 'session') + const name = (isScoped ? words.slice(0, -1) : words).join(' ') + const key = keyOf(name) + + if (name === '') { + // A surface that draws no placed rows yet gets the card above the prompt. + const placed = await $.ui.place({ id: CARD }) + + await update($, choice, was => ({ ...was, cardInBand: !placed.isPlaced, cardAway: false })) + + return { text: 'Pick a theme on the card.' } + } + + if (key === 'list') { + return { text: themeList() } + } + + if (key === 'off') { + const cleared = await applyOrSay($, undefined, forProject) + + if (cleared.fault !== undefined) { + return { text: cleared.fault } + } + + return { + text: forProject + ? 'Theme cleared for this project. Other open sessions of it clear at their next turn.' + : 'Theme cleared for this session only. The project keeps its theme for other sessions.', + } + } + + const theme = themeNamed(name) + + if (theme === undefined) { + // One line: the reason stays in view. Nothing is applied and nothing is stored. + const nearest = nearestTheme(name) + + return { + text: + `No theme named "${name}". ` + + (nearest === undefined ? '' : `The nearest is ${nearest.id}. `) + + `/${COMMAND} list names all ${THEMES.length}; "session" as the last word is this session only.`, + } + } + + const picked = await applyOrSay($, theme, forProject) + + if (picked.fault !== undefined) { + return { text: picked.fault } + } + + // A mod cannot learn which kind the window is, so every answer says which kind the theme is made for, and names its twin as the list does. + const twin = themeOf(theme.twin) + const said = + (forProject + ? `${theme.title} applied to this project. Other open sessions of it take it at their next turn.` + : `${theme.title} applied to this session only.`) + + ` Made for ${theme.window} windows${twin === undefined ? '' : ` (for ${twin.window} windows: ${twin.id})`}.` + + return { text: picked.isUnshown ? `${said} ${unshownNote(forProject)}` : said } + }) + + on('command.run', { command: FIREWORKS_COMMAND }, async ($, e) => ({ text: await fireworksCommand($, e.args) })) + + // Every block of the model's reply comes through here once, as text, before it is stored. + on('session.append', { door: 'response' }, async ($, e, next) => { + const said = e.message.content.some( + block => block.type === 'text' && typeof block.text === 'string' && WORD.test(block.text), + ) + + if (said && (await goesOffByItself($))) { + await fireworks($) + } + + return next(e) + }) + + on('ui.render', { component: 'Backdrop' }, ($, e, next) => { + // Only a window has room behind the chat, and only its table has `Svg`. + if (e.props.plugin !== PLUGIN || e.surface !== 'desktop') { + return next(e) + } + + const name = sceneNameOf(e.props) + + if (name === undefined) { + return next(e) + } + + const { Svg } = $.ui.resolve(e) + + if (name === NIGHT_ID) { + return <Svg isInteractive alt="Fireworks bursting over a night sky" source={nightScene()} /> + } + + const showOf = themeOf(themeIdOfShow(name)) + + if (showOf !== undefined) { + return ( + <Svg + isInteractive + alt={`Fireworks over ${showOf.title}`} + source={sceneWithFireworks(showOf, sceneOf(showOf))} + /> + ) + } + + const theme = themeOf(name) + + if (theme === undefined) { + return next(e) + } + + return <Svg isInteractive alt={`${theme.title}: ${theme.blurb}`} source={sceneOf(theme)} /> + }) + + on('ui.render', { component: 'Placed' }, async ($, e, next) => { + if (e.props.plugin !== PLUGIN || e.props.id !== CARD) { + return next(e) + } + + const now = await read($, choice) + + // Put away: a placed row whose hook passes draws nothing. + if (now.cardAway === true) { + return next(e) + } + + return card($, $.ui.resolve(e), now) + }) + + on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => { + const now = await read($, choice) + + if (now.cardInBand !== true) { + return next(e) + } + + return card($, $.ui.resolve(e), now) + }) +} diff --git a/plugins/theme-examples/hooks/scenes/blueprint.ts b/plugins/theme-examples/hooks/scenes/blueprint.ts new file mode 100644 index 00000000..62d6c6d5 --- /dev/null +++ b/plugins/theme-examples/hooks/scenes/blueprint.ts @@ -0,0 +1,286 @@ +// Blueprint: a cyanotype sheet with one drawing on it that is alive. +// One subject, lower right: a comet's orbit plotted about a sun, inside an open graduated arc. The comet goes round it, +// quick near the sun and slow at the far end (Kepler's timing), its tail pointing away from the sun, a short trail of ink behind it on the orbit, +// a faint radius joining the two and an index tick riding the arc where that radius points. +// The reading column keeps only a ghost of the grid. A dark-window scene. + +const SUN_X = 1440 +const SUN_Y = 830 +const CHALK = '#cfe0f5' +const GOLD = '#f2c14e' +const NEAREST = 66 +const FARTHEST = 300 +const COMET_PERIOD_SECONDS = 180 +const TRAIL_LONGEST = 0.18 + +/** Pools of deeper wash, kept to the four corners: centre x, centre y, radius x, radius y. */ +const DEEP_POOLS: readonly (readonly [number, number, number, number])[] = [ + [-40, -40, 720, 520], + [1660, -60, 640, 460], + [1700, 1080, 600, 480], + [-80, 1080, 560, 420], +] + +function round(value: number): number { + return Math.round(value * 10) / 10 +} + +/** Deterministic stand-in for a random number, so every build is the same. */ +function hash(seed: number): number { + const value = Math.sin(seed * 127.1 + 311.7) * 43758.5453 + return value - Math.floor(value) +} + +/** Degrees grow clockwise on screen, the same way CSS rotate() turns. */ +function pointAt(centerX: number, centerY: number, radius: number, degrees: number): [number, number] { + const angle = (degrees * Math.PI) / 180 + return [round(centerX + radius * Math.cos(angle)), round(centerY + radius * Math.sin(angle))] +} + +function point(centerX: number, centerY: number, radius: number, degrees: number): string { + return pointAt(centerX, centerY, radius, degrees).join(' ') +} + +function arc(centerX: number, centerY: number, radius: number, from: number, to: number): string { + const sweep = to > from ? 1 : 0 + return `M${point(centerX, centerY, radius, from)}A${radius} ${radius} 0 0 ${sweep} ${point(centerX, centerY, radius, to)}` +} + +function circle(centerX: number, centerY: number, radius: number): string { + return `M${centerX - radius} ${centerY}a${radius} ${radius} 0 1 0 ${radius * 2} 0a${radius} ${radius} 0 1 0 ${-radius * 2} 0` +} + +/** Radial tick marks over a span of the circle; every `longEvery`-th tick starts further in. */ +function radialTicks( + centerX: number, + centerY: number, + inner: number, + longInner: number, + outer: number, + step: number, + longEvery: number, + from: number, + to: number, +): string { + let path = '' + for (let degrees = from; degrees <= to; degrees += step) { + const start = (degrees / step) % longEvery === 0 ? longInner : inner + path += `M${point(centerX, centerY, start, degrees)}L${point(centerX, centerY, outer, degrees)}` + } + return path +} + +/** + * A point of the comet's ellipse, unrounded. The sun is one focus; the far end points up and to the left, into the sheet. + * `turn` is degrees round the ellipse's own centre from the far end, clockwise on screen; `stretch` scales about that centre (1 is the orbit itself). + * All of the ellipse lies inside a 1200x800 window's crop. + */ +function cometPoint(turn: number, stretch: number): [number, number] { + const semiMajor = (NEAREST + FARTHEST) / 2 + const focusOffset = semiMajor - NEAREST + const semiMinor = Math.sqrt(semiMajor * semiMajor - focusOffset * focusOffset) + const alongX = Math.cos((225 * Math.PI) / 180) + const alongY = Math.sin((225 * Math.PI) / 180) + const acrossX = Math.cos((315 * Math.PI) / 180) + const acrossY = Math.sin((315 * Math.PI) / 180) + const angle = (turn * Math.PI) / 180 + const alongDistance = focusOffset + semiMajor * Math.cos(angle) * stretch + const acrossDistance = semiMinor * Math.sin(angle) * stretch + return [SUN_X + alongDistance * alongX + acrossDistance * acrossX, SUN_Y + alongDistance * alongY + acrossDistance * acrossY] +} + +function cometEllipse(): string { + let path = '' + for (let turn = 0; turn < 360; turn += 4) { + const [x, y] = cometPoint(turn, 1) + path += `${path === '' ? 'M' : 'L'}${round(x)} ${round(y)}` + } + return `${path}z` +} + +/** Where the comet is after a share (0..1) of its period, counted from its closest pass: Kepler's equation, solved by Newton's steps. Returns the turn in degrees. */ +function turnAtTime(share: number): number { + const semiMajor = (NEAREST + FARTHEST) / 2 + const eccentricity = (semiMajor - NEAREST) / semiMajor + const meanAnomaly = 2 * Math.PI * share + let eccentricAnomaly = meanAnomaly + for (let step = 0; step < 10; step += 1) { + eccentricAnomaly -= (eccentricAnomaly - eccentricity * Math.sin(eccentricAnomaly) - meanAnomaly) / (1 - eccentricity * Math.cos(eccentricAnomaly)) + } + return (eccentricAnomaly * 180) / Math.PI + 180 +} + +/** Equal-time marks along the plotted orbit: they bunch up at the far end, where the comet is slow. */ +function equalTimeMarks(count: number): string { + let path = '' + for (let index = 0; index < count; index += 1) { + const turn = turnAtTime(index / count) + const [innerX, innerY] = cometPoint(turn, 0.965) + const [outerX, outerY] = cometPoint(turn, 1.035) + path += `M${round(innerX)} ${round(innerY)}L${round(outerX)} ${round(outerY)}` + } + return path +} + +/** How far round the orbit each whole degree of turn is, given in shares (0..1) of its length, counted from the closest pass in the comet's direction. */ +function ellipseSharesFromNearest(): number[] { + const lengths: number[] = [0] + let [lastX, lastY] = cometPoint(180, 1) + for (let step = 1; step <= 360; step += 1) { + const [x, y] = cometPoint(180 + step, 1) + lengths.push((lengths[step - 1] ?? 0) + Math.hypot(x - lastX, y - lastY)) + lastX = x + lastY = y + } + const whole = lengths[360] ?? 1 + return lengths.map(length => length / whole) +} + +function shareAtTurn(shares: readonly number[], turn: number): number { + const steps = turn - 180 + const whole = Math.min(359, Math.floor(steps)) + const before = shares[whole] ?? 0 + const after = shares[whole + 1] ?? 1 + return before + (after - before) * (steps - whole) +} + +/** Two laps of the orbit from the closest pass, in the comet's direction, for the trail to slide along. */ +function twoLapOrbit(): string { + let path = '' + for (let turn = 180; turn <= 900; turn += 4) { + const [x, y] = cometPoint(turn, 1) + path += `${path === '' ? 'M' : 'L'}${round(x)} ${round(y)}` + } + return path +} + +/** + * The comet's motion, written out in keyframes at equal steps of time. Each pose turns a frame about the sun to face the comet; + * `cometRun` then slides out to the comet's distance (and grows the head and tail a little near the sun), `radiusRun` stretches a unit line out to it, + * `bearingRun` only turns, `trailRun` slides the trail's dash. Enough poses that straight-line blending between them stays on the ellipse. + */ +function cometKeyframes(count: number): string { + let run = '' + let radius = '' + let bearing = '' + let trail = '' + let previous = 0 + const lapShares = ellipseSharesFromNearest() + for (let index = 0; index <= count; index += 1) { + const [x, y] = cometPoint(turnAtTime(index / count), 1) + const distance = Math.hypot(x - SUN_X, y - SUN_Y) + let degrees = (Math.atan2(y - SUN_Y, x - SUN_X) * 180) / Math.PI + while (degrees < previous - 180) degrees += 360 + while (degrees > previous + 180) degrees -= 360 + previous = degrees + const percent = round((index / count) * 100) + const size = (0.72 + 58 / distance).toFixed(2) + run += `${percent}%{transform:rotate(${round(degrees)}deg) translateX(${round(distance)}px) scale(${size})}` + radius += `${percent}%{transform:rotate(${round(degrees)}deg) scaleX(${round(distance)})}` + bearing += `${percent}%{transform:rotate(${round(degrees)}deg)}` + // The trail is a dash on a two-lap copy of the orbit: its leading end sits `1 + share` laps along, so it never meets the path's start or end. + const share = index === count ? 1 : shareAtTurn(lapShares, turnAtTime(index / count)) + trail += `${percent}%{stroke-dashoffset:${(TRAIL_LONGEST - 1 - share).toFixed(4)}}` + } + return `@keyframes cometRun{${run}}@keyframes radiusRun{${radius}}@keyframes bearingRun{${bearing}}@keyframes trailRun{${trail}}` +} + +/** A body on a circular orbit about the sun: a solid disc going round anticlockwise, once per `period` seconds, from `startDegrees`. */ +function orbitingBody(orbitRadius: number, bodyRadius: number, period: number, startDegrees: number): string { + const delay = round(-((360 - startDegrees) / 360) * period) + return `<g class="orbit" style="animation-duration:${period}s;animation-delay:${delay}s"><circle cx="${SUN_X + orbitRadius}" cy="${SUN_Y}" r="${bodyRadius}" fill="#dce8f7"/></g>` +} + +/** The coating: one even Prussian blue where the text sits; the pools of deeper wash keep to the four corners. A little paper tooth. */ +function paper(): string { + const wash = DEEP_POOLS.map(pool => `<ellipse cx="${pool[0]}" cy="${pool[1]}" rx="${pool[2]}" ry="${pool[3]}" fill="url(#washDeep)"/>`).join('') + const grid = `<rect width="1600" height="1000" fill="url(#minorGrid)" mask="url(#notInColumn)"/><rect width="1600" height="1000" fill="url(#oddMajorGrid)" mask="url(#notInColumn)"/><rect width="1600" height="1000" fill="url(#evenMajorGrid)" mask="url(#fainterInColumn)"/>` + return `<rect width="1600" height="1000" fill="#22508e"/>${wash}<rect width="1600" height="1000" fill="url(#tooth)"/>${grid}` +} + +/** Specks of paper tooth for one 160-unit tile: they also keep the washes from banding under the app's blur. */ +function toothSpecks(): string { + let specks = '' + for (let index = 0; index < 46; index += 1) { + const x = round(hash(index + 3) * 160) + const y = round(hash(index + 71) * 160) + const light = hash(index + 131) > 0.45 + specks += `<rect x="${x}" y="${y}" width="${light ? 1.2 : 1.6}" height="1.2" fill="${light ? '#dce8f7' : '#0b2347'}" opacity="${light ? 0.07 : 0.1}"/>` + } + return specks +} + +/** The fixed drawing: an open graduated arc whose ends fade out, one inner orbit with one planet, short axes, the comet's orbit plotted in pale chalk with its equal-time marks. */ +function plottedDrawing(): string { + const x = SUN_X + const y = SUN_Y + const scale = `${arc(x, y, 318, 160, 290)}${arc(x, y, 330, 160, 290)}${radialTicks(x, y, 322, 313, 330, 5, 3, 160, 290)}` + const axes = `M${x - 346} ${y}H${x + 96}M${x} ${y - 346}V${y + 96}` + const sun = `<circle cx="${x}" cy="${y}" r="11" fill="none" stroke="${CHALK}" stroke-width="1.5" opacity=".7"/><circle cx="${x}" cy="${y}" r="4" fill="#dce8f7" opacity=".9"/>` + const planet = `<g opacity=".85">${orbitingBody(66, 4.5, 120, 250)}</g>` + const orbit = `<path fill="none" stroke="${CHALK}" stroke-width="1.4" opacity=".5" d="${cometEllipse()}"/><path class="fine" d="${equalTimeMarks(12)}"/>` + return `<path class="fine chain" d="${axes}"/><path class="medium" d="${circle(x, y, 66)}"/><path fill="none" stroke="url(#scaleFade)" stroke-width="1.4" opacity=".46" d="${scale}"/>${orbit}${sun}${planet}` +} + +/** One layer of the trail: a dash `share` of a lap long whose leading end rides with the comet. Three of them stacked make the trail fade toward its far end. */ +function trailLayer(share: number, width: number, opacity: number, timing: string, restShare: number, orbitTwice: string): string { + return `<path class="trailRun" pathLength="2" style="${timing};stroke-dasharray:0 ${(TRAIL_LONGEST - share).toFixed(2)} ${share} 3;stroke-dashoffset:${(TRAIL_LONGEST - 1 - restShare).toFixed(3)}" d="${orbitTwice}" fill="none" stroke="${GOLD}" stroke-width="${width}" opacity="${opacity}"/>` +} + +/** The comet: a small bright head, a tapering tail that always points away from the sun, and a faint radius from the sun to the head. A short trail of ink lies behind it on the orbit and an index tick rides the arc at its bearing. Never a line that fills up. */ +function comet(): string { + // A third of the way round at the first frame, well out on the sheet. Without animation it rests near the far end. + const timing = `animation-duration:${COMET_PERIOD_SECONDS}s;animation-delay:-${Math.round(COMET_PERIOD_SECONDS * 0.36)}s` + const [restX, restY] = cometPoint(turnAtTime(0.42), 1) + const restDistance = round(Math.hypot(restX - SUN_X, restY - SUN_Y)) + const restDegrees = round((Math.atan2(restY - SUN_Y, restX - SUN_X) * 180) / Math.PI) + const radius = `<path class="radiusRun" style="${timing};transform:rotate(${restDegrees}deg) scaleX(${restDistance})" d="M${SUN_X} ${SUN_Y}h1" fill="none" stroke="${CHALK}" stroke-width="1" opacity=".16"/>` + const body = `<g class="cometRun" style="${timing};transform:rotate(${restDegrees}deg) translateX(${restDistance}px)"><path d="M${SUN_X + 2} ${SUN_Y - 3.4}L${SUN_X + 58} ${SUN_Y}L${SUN_X + 2} ${SUN_Y + 3.4}z" fill="url(#tailFade)"/><circle cx="${SUN_X}" cy="${SUN_Y}" r="5" fill="#ffe08a"/></g>` + const orbitTwice = twoLapOrbit() + const restShare = shareAtTurn(ellipseSharesFromNearest(), turnAtTime(0.42)) + const trail = `${trailLayer(0.18, 1.6, 0.2, timing, restShare, orbitTwice)}${trailLayer(0.11, 2, 0.25, timing, restShare, orbitTwice)}${trailLayer(0.05, 2.6, 0.35, timing, restShare, orbitTwice)}` + const index = `<path class="bearingRun" style="${timing};transform:rotate(${restDegrees}deg)" d="M${SUN_X + 311} ${SUN_Y}h16" fill="none" stroke="${GOLD}" stroke-width="2" opacity=".75"/>` + return `${trail}${radius}${index}${body}` +} + +/** Stops of a left-to-right ramp that is full at the sheet's margins and `inside` strong behind the reading column, eased over 352 units a side so no seam shows. */ +function columnRamp(inside: number): string { + return `<stop offset="0" stop-color="#fff"/><stop offset=".1" stop-color="#fff"/><stop offset=".32" stop-color="#fff" stop-opacity="${inside}"/><stop offset=".7" stop-color="#fff" stop-opacity="${inside}"/><stop offset=".92" stop-color="#fff"/><stop offset="1" stop-color="#fff"/>` +} + +export function blueprintSvg(): string { + const style = ` +.medium{fill:none;stroke:${CHALK};stroke-width:1.1;opacity:.26} +.fine{fill:none;stroke:${CHALK};stroke-width:.8;opacity:.2} +.chain{stroke-dasharray:26 5 4 5} +.orbit,.cometRun,.radiusRun,.bearingRun{transform-origin:${SUN_X}px ${SUN_Y}px} +.orbit{animation:orbit 600s linear infinite} +.cometRun{animation:cometRun ${COMET_PERIOD_SECONDS}s linear infinite} +.radiusRun{animation:radiusRun ${COMET_PERIOD_SECONDS}s linear infinite} +.bearingRun{animation:bearingRun ${COMET_PERIOD_SECONDS}s linear infinite} +.trailRun{animation:trailRun ${COMET_PERIOD_SECONDS}s linear infinite} +@keyframes orbit{to{transform:rotate(-360deg)}} +${cometKeyframes(120)} +@media (prefers-reduced-motion: reduce){*{animation:none!important}}` + + const [fadeFromX, fadeFromY] = pointAt(SUN_X, SUN_Y, 324, 160) + const [fadeToX, fadeToY] = pointAt(SUN_X, SUN_Y, 324, 290) + const defs = ` +<radialGradient id="washDeep"><stop offset="0" stop-color="#0e2c58" stop-opacity=".78"/><stop offset=".4" stop-color="#0e2c58" stop-opacity=".46"/><stop offset=".72" stop-color="#0e2c58" stop-opacity=".15"/><stop offset="1" stop-color="#0e2c58" stop-opacity="0"/></radialGradient> +<linearGradient id="scaleFade" gradientUnits="userSpaceOnUse" x1="${fadeFromX}" y1="${fadeFromY}" x2="${fadeToX}" y2="${fadeToY}"><stop offset="0" stop-color="${CHALK}" stop-opacity="0"/><stop offset=".16" stop-color="${CHALK}"/><stop offset=".84" stop-color="${CHALK}"/><stop offset="1" stop-color="${CHALK}" stop-opacity="0"/></linearGradient> +<linearGradient id="tailFade"><stop offset="0" stop-color="${GOLD}" stop-opacity=".95"/><stop offset=".5" stop-color="${GOLD}" stop-opacity=".45"/><stop offset="1" stop-color="${GOLD}" stop-opacity="0"/></linearGradient> +<pattern id="tooth" width="160" height="160" patternUnits="userSpaceOnUse">${toothSpecks()}</pattern> +<pattern id="minorGrid" width="100" height="100" patternUnits="userSpaceOnUse"><path d="M20.5 0v100M40.5 0v100M60.5 0v100M80.5 0v100M0 20.5h100M0 40.5h100M0 60.5h100M0 80.5h100" stroke="${CHALK}" stroke-opacity=".07" fill="none"/></pattern> +<pattern id="oddMajorGrid" width="200" height="200" patternUnits="userSpaceOnUse"><path d="M100.5 0v200M0 100.5h200" stroke="${CHALK}" stroke-opacity=".14" fill="none"/></pattern> +<pattern id="evenMajorGrid" width="200" height="200" patternUnits="userSpaceOnUse"><path d="M.5 0v200M0 .5h200" stroke="${CHALK}" stroke-opacity=".14" fill="none"/></pattern> +<linearGradient id="notInColumnRamp">${columnRamp(0)}</linearGradient> +<linearGradient id="fainterInColumnRamp">${columnRamp(0.35)}</linearGradient> +<mask id="notInColumn" maskUnits="userSpaceOnUse" x="0" y="0" width="1600" height="1000"><rect width="1600" height="1000" fill="url(#notInColumnRamp)"/></mask> +<mask id="fainterInColumn" maskUnits="userSpaceOnUse" x="0" y="0" width="1600" height="1000"><rect width="1600" height="1000" fill="url(#fainterInColumnRamp)"/></mask>` + + return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1600 1000" width="100%" height="100%" preserveAspectRatio="xMidYMid slice" font-family="monospace" color="#888"><style>${style}</style><defs>${defs}</defs> +${paper()} +${plottedDrawing()} +${comet()} +</svg>` +} diff --git a/plugins/theme-examples/hooks/scenes/braille-stars.ts b/plugins/theme-examples/hooks/scenes/braille-stars.ts new file mode 100644 index 00000000..aa66ddb1 --- /dev/null +++ b/plugins/theme-examples/hooks/scenes/braille-stars.ts @@ -0,0 +1,438 @@ +// Braille Stars: a night sky rendered the way a terminal renders a picture in braille. +// The frame is a grid of cells of 2 by 4 dots; each cell gets a brightness, and that many of its dots are raised. +// Pure string building: no DOM, nothing brought in from outside this file. + +type Dot = { x: number; y: number } +type PaintName = 'dust' | 'haze' | 'cloud' | 'star' | 'warm' | 'orchid' | 'amber' | 'figure' | 'ridgeCrest' +type Paint = { colour: string; opacity: number; width: number } +type Layer = Map<PaintName, Dot[]> +type SpineSample = { x: number; y: number; t: number; tangentX: number; tangentY: number } +type BandReading = { brightness: number; along: number; across: number; underCards: number } +type ShimmerGroup = { first: Layer; second: Layer } +type TwinkleGroup = { small: Layer; medium: Layer; large: Layer } +type Figure = { stars: readonly (readonly [number, number, number])[]; joins: readonly (readonly [number, number])[] } +type StarCentre = { x: number; y: number; reach: number } + +const DOT_PITCH = 7 +const CELL_WIDTH = 19 +const CELL_HEIGHT = 33 +const CELL_INSET = 3 +// The sky sways by three degrees either way about the pole, so it is drawn a little past every edge. +const SKY_LEFT = -110 +const SKY_RIGHT = 1730 +const SKY_TOP = -100 +const SKY_BOTTOM = 1000 +const POLE_X = -120 +const POLE_Y = -140 +const SHIMMER_GROUPS = 8 +const SHIMMER_SECONDS = 40 + +/** A repeatable number in [0, 1) from two grid coordinates and a salt: every build draws the same sky. */ +function hashUnit(x: number, y: number, salt: number): number { + let h = (Math.imul(x | 0, 374761393) + Math.imul(y | 0, 668265263) + Math.imul(salt | 0, 2147483647)) | 0 + h = Math.imul(h ^ (h >>> 15), 0x85ebca6b) + h = Math.imul(h ^ (h >>> 13), 0xc2b2ae35) + h = h ^ (h >>> 16) + return (h >>> 0) / 4294967296 +} + +function smoothStep(low: number, high: number, value: number): number { + const t = Math.min(1, Math.max(0, (value - low) / (high - low))) + return t * t * (3 - 2 * t) +} + +/** Smooth noise in [0, 1): clumps the Milky Way so it does not read like an even spray. */ +function valueNoise(x: number, y: number, scale: number, salt: number): number { + const gx = Math.floor(x / scale) + const gy = Math.floor(y / scale) + const fx = smoothStep(0, 1, x / scale - gx) + const fy = smoothStep(0, 1, y / scale - gy) + const top = hashUnit(gx, gy, salt) * (1 - fx) + hashUnit(gx + 1, gy, salt) * fx + const bottom = hashUnit(gx, gy + 1, salt) * (1 - fx) + hashUnit(gx + 1, gy + 1, salt) * fx + return top * (1 - fy) + bottom * fy +} + +function dotX(cellColumn: number, dotColumn: number): number { + return cellColumn * CELL_WIDTH + CELL_INSET + dotColumn * DOT_PITCH +} + +function dotY(cellRow: number, dotRow: number): number { + return cellRow * CELL_HEIGHT + CELL_INSET + dotRow * DOT_PITCH +} + +// The order in which a cell's eight dots are raised while it brightens (dot = row * 2 + column). Spread out, so a half-lit cell looks like a letter, not a bar. +const RAISE_ORDER: readonly number[] = [2, 5, 0, 7, 3, 4, 1, 6] + +/** The dots of a cell at a brightness of 0 to 8, mirrored by the cell's own hash so neighbours are not copies of each other. A second variant gives the same cell another letter. */ +function raisedDots(cellColumn: number, cellRow: number, count: number, variant: number): Dot[] { + const mirror = hashUnit(cellColumn, cellRow, 40 + variant * 2) < 0.5 + const flip = hashUnit(cellColumn, cellRow, 41 + variant * 2) < 0.5 + const dots: Dot[] = [] + for (let rank = 0; rank < count; rank += 1) { + const dot = RAISE_ORDER[rank] ?? 0 + const dotColumn = mirror ? 1 - (dot % 2) : dot % 2 + const dotRow = flip ? 3 - (dot >> 1) : dot >> 1 + dots.push({ x: dotX(cellColumn, dotColumn), y: dotY(cellRow, dotRow) }) + } + return dots +} + +/** Dots are collected by paint, then each paint is written out in one path: a zero-length stroke with round caps is a dot. */ +function addDot(layer: Layer, paint: PaintName, x: number, y: number): void { + const dots = layer.get(paint) + if (dots === undefined) layer.set(paint, [{ x, y }]) + else dots.push({ x, y }) +} + +function sameDot(dots: readonly Dot[], dot: Dot): boolean { + return dots.some(other => other.x === dot.x && other.y === dot.y) +} + +// Flat tones only, each blended into the sky once when the scene is built: the browser never has to composite a see-through group. Sky: four blues, two warm whites and an orchid. Land: one dark blue. +const PAINTS: Record<PaintName, Paint> = { + dust: { colour: '#4c62b4', opacity: 0.7, width: 2.8 }, + haze: { colour: '#8ea6ff', opacity: 0.8, width: 3.5 }, + cloud: { colour: '#b4c2ff', opacity: 0.95, width: 4.1 }, + star: { colour: '#dde4ff', opacity: 0.95, width: 4.7 }, + warm: { colour: '#ffdcae', opacity: 0.95, width: 4.6 }, + orchid: { colour: '#c890d6', opacity: 0.85, width: 4 }, + amber: { colour: '#e9d3ad', opacity: 1, width: 4.4 }, + figure: { colour: '#fff1d0', opacity: 0.88, width: 4.4 }, + ridgeCrest: { colour: '#4a5ca6', opacity: 0.7, width: 4 }, +} + +const SKY_BASE = '#0d1536' +const LAND_BASE = '#070b1f' + +/** A tone laid over the sky at a given strength, worked out once: an opaque colour needs no blending when the frame is painted. */ +function blend(colour: string, opacity: number, base: string): string { + let out = '#' + for (let channel = 0; channel < 3; channel += 1) { + const top = parseInt(colour.slice(1 + channel * 2, 3 + channel * 2), 16) + const under = parseInt(base.slice(1 + channel * 2, 3 + channel * 2), 16) + out += Math.round(top * opacity + under * (1 - opacity)).toString(16).padStart(2, '0') + } + return out +} + +/** Row by row, with relative moves along a row: a third fewer characters than absolute moves. */ +function writeLayer(layer: Layer): string { + let out = '' + for (const [paint, dots] of layer) { + const look = PAINTS[paint] + dots.sort((first, second) => first.y - second.y || first.x - second.x) + let d = '' + let last: Dot | null = null + for (const dot of dots) { + d += last !== null && last.y === dot.y ? `m${dot.x - last.x} 0h0` : `M${dot.x} ${dot.y}h0` + last = dot + } + out += `<path d="${d}" stroke="${blend(look.colour, look.opacity, paint === 'ridgeCrest' ? LAND_BASE : SKY_BASE)}" stroke-width="${look.width}"/>` + } + return out +} + +/** The Milky Way's spine: a diagonal from the top right corner down to the hills, about thirty degrees off upright, its core low. */ +function milkyWaySpine(): SpineSample[] { + const points: { x: number; y: number; t: number }[] = [] + for (let step = 0; step <= 60; step += 1) { + const t = step / 60 + const x = (1 - t) * (1 - t) * 1830 + 2 * (1 - t) * t * 1430 + t * t * 1010 + const y = (1 - t) * (1 - t) * -60 + 2 * (1 - t) * t * 470 + t * t * 1040 + points.push({ x, y, t }) + } + return points.map((point, index) => { + const before = points[Math.max(0, index - 1)] ?? point + const after = points[Math.min(points.length - 1, index + 1)] ?? point + const length = Math.hypot(after.x - before.x, after.y - before.y) + return { x: point.x, y: point.y, t: point.t, tangentX: (after.x - before.x) / length, tangentY: (after.y - before.y) / length } + }) +} + +/** The Milky Way's brightness (0 to 1) at a point, how far along and across the band the point sits, and whether it lies under the cards. */ +function milkyWayAt(x: number, y: number, spine: readonly SpineSample[]): BandReading { + let nearest: SpineSample | undefined = undefined + let best = Infinity + for (const sample of spine) { + const distance = (sample.x - x) * (sample.x - x) + (sample.y - y) * (sample.y - y) + if (distance < best) { + best = distance + nearest = sample + } + } + if (nearest === undefined) return { brightness: 0, along: 0, across: 0, underCards: 1 } + const across = (x - nearest.x) * nearest.tangentY - (y - nearest.y) * nearest.tangentX + const halfWidth = (66 + 80 * smoothStep(0.15, 0.85, nearest.t)) * (0.7 + 0.6 * valueNoise(nearest.t * 900, 0, 130, 19)) + const band = Math.exp(-(across * across) / (halfWidth * halfWidth)) + const along = (0.62 + 0.38 * smoothStep(0.1, 0.7, nearest.t)) * (1 - smoothStep(0.86, 0.98, nearest.t)) + const laneCentre = 4 + 38 * Math.sin(nearest.t * 8) + 16 * Math.sin(nearest.t * 19 + 1) + const laneWidth = 22 + 12 * nearest.t + const lane = 1 - 0.93 * Math.exp(-((across - laneCentre) * (across - laneCentre)) / (laneWidth * laneWidth)) + const clump = 0.3 + 2 * valueNoise(x, y, 105, 11) * valueNoise(x, y, 41, 12) + // Under the cards (top right of the window) the band is held to its dimmest tones so it does not crawl through their text. + const underCards = 1 - smoothStep(1150, 1230, x) * (1 - smoothStep(230, 310, y)) + const brightness = Math.min(1, (0.3 * Math.pow(band, 0.8) + 0.86 * Math.pow(band, 1.2) * clump) * along * lane) * (0.25 + 0.75 * underCards) + return { brightness, along: nearest.t, across, underCards } +} + +/** 1 at the edges, low over the conversation column: the middle stays the sparsest and darkest part. */ +function calmFactor(x: number, y: number): number { + const insideX = smoothStep(330, 470, x) * (1 - smoothStep(1070, 1260, x)) + const insideY = smoothStep(30, 110, y) * (1 - smoothStep(860, 940, y)) + return 1 - 0.8 * insideX * insideY +} + +const TONES: readonly PaintName[] = ['dust', 'haze', 'cloud', 'star'] + +/** The paint of one dot of a band cell. Within a cell the first dots raised are the brightest and the last the dimmest: soft-edged letters, not stencils. */ +function bandPaint(tone: number, warm: boolean, orchid: boolean, rank: number, count: number): PaintName { + if (warm && rank < 3) return 'warm' + if (orchid && rank < 2) return 'orchid' + const step = (rank === 0 && count >= 3 ? 1 : 0) - (rank >= count - 1 && count >= 2 ? 1 : 0) - (rank >= count - 2 && count >= 4 ? 1 : 0) + return TONES[Math.min(3, Math.max(0, tone + step))] ?? 'dust' +} + +/** The Milky Way, cell by cell. Every cell has two letters (the same brightness give or take a dot, mirrored differently); groups of cells trade one for the other in turn, so the band's texture slowly rewrites itself from one end to the other. */ +function milkyWayCells(spine: readonly SpineSample[]): string { + const steady: Layer = new Map() + const groups: ShimmerGroup[] = [] + for (let group = 0; group < SHIMMER_GROUPS; group += 1) groups.push({ first: new Map(), second: new Map() }) + const pulses: Layer[] = [new Map(), new Map(), new Map(), new Map()] + for (let cellRow = Math.floor(SKY_TOP / CELL_HEIGHT); cellRow * CELL_HEIGHT < SKY_BOTTOM; cellRow += 1) { + for (let cellColumn = Math.floor(900 / CELL_WIDTH); cellColumn * CELL_WIDTH < SKY_RIGHT; cellColumn += 1) { + const centreX = cellColumn * CELL_WIDTH + CELL_WIDTH / 2 + const centreY = cellRow * CELL_HEIGHT + CELL_HEIGHT / 2 + const here = milkyWayAt(centreX, centreY, spine) + // The band is feathered toward the column: full strength at the edge of the window, a ghost of itself inside the column. + const brightness = here.brightness * Math.pow(calmFactor(centreX, centreY), 1.6) + const firstCount = Math.min(6, Math.floor(brightness * 7 + hashUnit(cellColumn, cellRow, 1) * 1.3 - 0.25)) + if (firstCount <= 0) continue + const secondCount = Math.min(7, Math.max(1, firstCount + (hashUnit(cellColumn, cellRow, 2) < 0.5 ? -1 : 1))) + // The core is warm, the middle has a little orchid, the rest is blue. Coloured cells sit on a checkerboard so two never share an edge and spell something. + const apart = (cellColumn + cellRow) % 2 === 0 + const warm = apart && brightness > 0.5 && hashUnit(cellColumn, cellRow, 4) < 0.5 + const orchid = !warm && apart && brightness > 0.22 && brightness < 0.6 && hashUnit(cellColumn, cellRow, 21) < 0.2 + const tone = brightness < 0.25 || here.underCards < 0.5 ? 0 : brightness < 0.45 ? 1 : brightness < 0.72 ? 2 : 3 + // About one band cell in nine is a variable star: the whole cell fades down and back on its own slow clock. + if (brightness > 0.22 && hashUnit(cellColumn, cellRow, 19) < 0.11) { + const pulse = pulses[Math.min(3, Math.floor(smoothStep(0.12, 0.88, here.along) * 4))] + if (pulse === undefined) continue + const pulseDots = raisedDots(cellColumn, cellRow, Math.min(6, firstCount + 1), 0) + for (const [rank, dot] of pulseDots.entries()) addDot(pulse, rank < 2 ? (warm ? 'warm' : 'star') : 'cloud', dot.x, dot.y) + continue + } + // Cells that change together lie together (one stretch of the band per group), so one change repaints one stretch, not the whole frame. + const group = groups[Math.floor(here.along * 0.999 * SHIMMER_GROUPS)] + if (group === undefined) continue + const first = raisedDots(cellColumn, cellRow, firstCount, 0) + const second = raisedDots(cellColumn, cellRow, secondCount, 1) + for (const [rank, dot] of first.entries()) { + addDot(sameDot(second, dot) ? steady : group.first, bandPaint(tone, warm, orchid, rank, firstCount), dot.x, dot.y) + } + for (const [rank, dot] of second.entries()) { + if (!sameDot(first, dot)) addDot(group.second, bandPaint(tone, warm, orchid, rank, secondCount), dot.x, dot.y) + } + } + } + let out = writeLayer(steady) + for (const [index, group] of groups.entries()) { + const delay = ((index * SHIMMER_SECONDS) / SHIMMER_GROUPS).toFixed(1) + out += `<g class="first" style="animation-delay:-${delay}s">${writeLayer(group.first)}</g><g class="second" style="animation-delay:-${delay}s">${writeLayer(group.second)}</g>` + } + for (const [index, pulse] of pulses.entries()) { + out += `<g class="pulse p${index}">${writeLayer(pulse)}</g>` + } + return out +} + +/** Which of six patches of sky a point lies in. Stars that twinkle together share a patch, so one change repaints one patch, not the whole frame. */ +function skyRegion(x: number, y: number): number { + if (x < 450) return y < 330 ? 0 : y < 640 ? 1 : 2 + if (x > 1150) return y < 480 ? 3 : 4 + return y < 500 ? 5 : x < 800 ? 2 : 4 +} + +/** Sparse field stars, one braille cell each. Some step between three dot patterns: that is the twinkle. */ +function fieldStars(spine: readonly SpineSample[]): string { + const steady: Layer = new Map() + const twinkleGroups: TwinkleGroup[] = [] + for (let group = 0; group < 6; group += 1) twinkleGroups.push({ small: new Map(), medium: new Map(), large: new Map() }) + for (let cellRow = Math.floor(SKY_TOP / CELL_HEIGHT); cellRow * CELL_HEIGHT < SKY_BOTTOM; cellRow += 1) { + for (let cellColumn = Math.floor(SKY_LEFT / CELL_WIDTH); cellColumn * CELL_WIDTH < SKY_RIGHT; cellColumn += 1) { + const centreX = cellColumn * CELL_WIDTH + CELL_WIDTH / 2 + const centreY = cellRow * CELL_HEIGHT + CELL_HEIGHT / 2 + const chance = 0.085 * calmFactor(centreX, centreY) * (0.5 + valueNoise(centreX, centreY, 240, 21)) + if (hashUnit(cellColumn, cellRow, 5) >= chance) continue + if (milkyWayAt(centreX, centreY, spine).brightness > 0.2) continue + const dotColumn = hashUnit(cellColumn, cellRow, 6) < 0.5 ? 0 : 1 + const dotRow = 1 + Math.floor(hashUnit(cellColumn, cellRow, 7) * 2) + const x = dotX(cellColumn, dotColumn) + const y = dotY(cellRow, dotRow) + const otherX = dotX(cellColumn, 1 - dotColumn) + const rank = hashUnit(cellColumn, cellRow, 8) + const calm = calmFactor(centreX, centreY) < 0.6 + const bright: PaintName = rank < 0.86 ? 'star' : rank < 0.96 ? 'warm' : 'amber' + if (calm || hashUnit(cellColumn, cellRow, 9) >= 0.36) { + addDot(steady, calm ? 'dust' : rank < 0.5 ? 'haze' : rank < 0.85 ? 'cloud' : bright, x, y) + if (!calm && rank > 0.8) addDot(steady, 'haze', otherX, y) + continue + } + const group = twinkleGroups[skyRegion(centreX, centreY)] + if (group === undefined) continue + addDot(group.small, 'cloud', x, y) + addDot(group.medium, bright, x, y) + addDot(group.medium, 'haze', otherX, y) + addDot(group.large, bright, x, y) + addDot(group.large, 'cloud', otherX, y) + addDot(group.large, 'cloud', x, y - DOT_PITCH) + addDot(group.large, 'haze', x, y + DOT_PITCH) + } + } + let out = writeLayer(steady) + for (const [index, group] of twinkleGroups.entries()) { + out += `<g class="tw t${index}"><g class="small">${writeLayer(group.small)}</g><g class="medium">${writeLayer(group.medium)}</g><g class="large">${writeLayer(group.large)}</g></g>` + } + return out +} + +// One figure. Its joins are dotted at the grid's own pitch, so even the lines are drawn in dots. Each star is a cell; a brighter star raises more dots (1, 2, 4 or 6). Its stars wink, a few at a time. +const FIGURES: readonly Figure[] = [ + // The Scorpion's head and body, beside the band; its tail is left to the cloud. + { + stars: [[1192, 276, 2], [1213, 305, 3], [1198, 335, 2], [1246, 324, 2], [1278, 348, 4], [1304, 382, 2], [1312, 417, 3], [1336, 439, 2]], + joins: [[0, 1], [1, 2], [1, 3], [3, 4], [4, 5], [5, 6], [6, 7]], + }, +] + +function figures(): string { + const winks: Layer[] = [new Map(), new Map(), new Map(), new Map()] + let lines = '' + for (const figure of FIGURES) { + const centres: StarCentre[] = [] + for (const [index, star] of figure.stars.entries()) { + const cellColumn = Math.floor(star[0] / CELL_WIDTH) + const cellRow = Math.floor(star[1] / CELL_HEIGHT) + const rows = star[2] >= 4 ? 3 : star[2] >= 3 ? 2 : 1 + const columns = star[2] >= 2 ? 2 : 1 + const wink = winks[index % 4] + if (wink === undefined) continue + for (let dotRow = 0; dotRow < rows; dotRow += 1) { + for (let dotColumn = 0; dotColumn < columns; dotColumn += 1) addDot(wink, 'figure', dotX(cellColumn, dotColumn), dotY(cellRow, 1 + dotRow)) + } + centres.push({ x: dotX(cellColumn, 0) + ((columns - 1) * DOT_PITCH) / 2, y: dotY(cellRow, 1) + ((rows - 1) * DOT_PITCH) / 2, reach: 8 + rows * 4 }) + } + for (const join of figure.joins) { + const from = centres[join[0]] + const to = centres[join[1]] + if (from === undefined || to === undefined) continue + const length = Math.hypot(to.x - from.x, to.y - from.y) + const unitX = (to.x - from.x) / length + const unitY = (to.y - from.y) / length + lines += `M${(from.x + unitX * from.reach).toFixed(1)} ${(from.y + unitY * from.reach).toFixed(1)}L${(to.x - unitX * to.reach).toFixed(1)} ${(to.y - unitY * to.reach).toFixed(1)}` + } + } + return `<path d="${lines}" stroke="${blend('#8ea6ff', 0.24, SKY_BASE)}" stroke-width="2.2" stroke-dasharray="0 8"/>` + winks.map((layer, index) => `<g class="wink p${index}">${writeLayer(layer)}</g>`).join('') +} + +/** The near hills: two flanks with a deep valley between them, because the prompt box sits over the middle. */ +function frontRidge(x: number): number { + return 990 - 140 * smoothStep(1000, 1640, x) - 180 * (1 - smoothStep(-60, 500, x)) - 10 * Math.sin(x / 173 + 0.6) - 6 * Math.sin(x / 61 + 2.1) +} + +function backRidge(x: number): number { + return 968 - 110 * smoothStep(1120, 1520, x) + 50 * smoothStep(1500, 1720, x) - 110 * (1 - smoothStep(60, 640, x)) - 12 * Math.sin(x / 227 + 2.4) - 6 * Math.sin(x / 83 + 0.3) +} + +/** A hill's outline. Filled flat behind the hill's dots, so the sky's dots stop at the hill. */ +function ridgeOutline(ridge: (x: number) => number): string { + let d = 'M-30 1010' + for (let x = -30; x <= 1630; x += 10) d += `L${x} ${ridge(x).toFixed(1)}` + return `${d}L1630 1010z` +} + +/** The near hill's rim: one row of dots just under its crest, in a dark tone that never competes with the sky. */ +function ridgeDots(): string { + const layer: Layer = new Map() + for (let cellColumn = -1; cellColumn * CELL_WIDTH < 1610; cellColumn += 1) { + for (let cellRow = Math.floor(720 / CELL_HEIGHT); cellRow * CELL_HEIGHT < 1010; cellRow += 1) { + for (let dot = 0; dot < 8; dot += 1) { + const x = dotX(cellColumn, dot % 2) + const y = dotY(cellRow, dot >> 1) + const depth = y - frontRidge(x) - 4 + if (depth >= 0 && depth < 8 && hashUnit(x, y, 13) < 0.94) addDot(layer, 'ridgeCrest', x, y) + } + } + } + return writeLayer(layer) +} + +// Where the soft light under the band lies: spine sample, long radius, short radius, gradient. +const GLOW_SPOTS: readonly (readonly [number, number, number, string])[] = [[14, 300, 110, 'glowBlue'], [32, 330, 150, 'glowCore'], [47, 280, 130, 'glowBlue']] + +/** A soft light under the band, so its dots sit in a cloud: three long ellipses laid along the spine, each breathing a little out of step. */ +function bandGlow(spine: readonly SpineSample[]): string { + let out = '' + for (const [index, spot] of GLOW_SPOTS.entries()) { + const sample = spine[spot[0]] + if (sample === undefined) continue + const angle = (Math.atan2(sample.tangentY, sample.tangentX) * 180) / Math.PI + out += `<ellipse class="breath b${index}" cx="${sample.x.toFixed(0)}" cy="${sample.y.toFixed(0)}" rx="${spot[1]}" ry="${spot[2]}" fill="url(#${spot[3]})" transform="rotate(${angle.toFixed(1)} ${sample.x.toFixed(0)} ${sample.y.toFixed(0)})"/>` + } + return out +} + +/** One shooting star: a run of dots that fades behind itself, heading down into the band's fringe. */ +function shootingStar(): string { + let out = '' + for (let index = 0; index < 20; index += 1) { + const opacity = Number(Math.pow(0.84, index).toFixed(2)) + out += `<path d="M${(1215 - index * 9.6).toFixed(1)} ${(470 - index * 6).toFixed(1)}h0" stroke="${blend(index < 3 ? '#fff6d0' : '#e6ebff', opacity, SKY_BASE)}" stroke-width="${index === 0 ? 5.4 : index < 4 ? 4.2 : 3.4}"/>` + } + return `<g class="shoot">${out}</g>` +} + +export function brailleStarsSvg(): string { + const spine = milkyWaySpine() + + const style = ` +path{fill:none;stroke-linecap:round} +.sky{transform-origin:${POLE_X}px ${POLE_Y}px;animation:turn 280s steps(560) -140s infinite alternate} +.second{stroke-opacity:0} +.first{animation:first ${SHIMMER_SECONDS}s steps(1) infinite}.second{animation:second ${SHIMMER_SECONDS}s steps(1) infinite} +.breath{animation:breath 74s steps(12) infinite alternate}.b1{animation-delay:-25s}.b2{animation-delay:-50s} +.pulse{animation:pulse 9s steps(1) infinite}.wink{animation:wink 9s steps(1) infinite}.p1{animation-duration:11s;animation-delay:-3s}.p2{animation-duration:13s;animation-delay:-8s}.p3{animation-duration:14s;animation-delay:-5s} +.tw .medium,.tw .large{stroke-opacity:0} +.tw .small{animation:small 11s steps(1) infinite}.tw .medium{animation:medium 11s steps(1) infinite}.tw .large{animation:large 11s steps(1) infinite} +.tw.t1 g{animation-duration:13s;animation-delay:-4s}.tw.t2 g{animation-duration:17s;animation-delay:-11s} +.tw.t3 g{animation-duration:9s;animation-delay:-6s}.tw.t4 g{animation-duration:19s;animation-delay:-2s}.tw.t5 g{animation-duration:14s;animation-delay:-8.5s} +.shoot{stroke-opacity:0;animation:shoot 46s linear -37.9s infinite} +@keyframes turn{from{transform:rotate(-3deg)}to{transform:rotate(3deg)}} +@keyframes first{0%{stroke-opacity:1}40%{stroke-opacity:.66}43%{stroke-opacity:.33}46%{stroke-opacity:0}90%{stroke-opacity:.33}93%{stroke-opacity:.66}96%{stroke-opacity:1}100%{stroke-opacity:1}} +@keyframes second{0%{stroke-opacity:0}40%{stroke-opacity:.33}43%{stroke-opacity:.66}46%{stroke-opacity:1}90%{stroke-opacity:.66}93%{stroke-opacity:.33}96%{stroke-opacity:0}100%{stroke-opacity:0}} +@keyframes breath{from{fill-opacity:.7}to{fill-opacity:1}} +@keyframes pulse{0%{stroke-opacity:1}30%{stroke-opacity:.8}36%{stroke-opacity:.65}42%{stroke-opacity:.5}48%{stroke-opacity:.35}70%{stroke-opacity:.5}76%{stroke-opacity:.6}82%{stroke-opacity:.8}88%{stroke-opacity:1}100%{stroke-opacity:1}} +@keyframes wink{0%{stroke-opacity:1}40%{stroke-opacity:.8}46%{stroke-opacity:.62}52%{stroke-opacity:.45}70%{stroke-opacity:.62}76%{stroke-opacity:.8}82%{stroke-opacity:1}100%{stroke-opacity:1}} +@keyframes small{0%{stroke-opacity:1}30%{stroke-opacity:.6}36%{stroke-opacity:.25}42%{stroke-opacity:0}92%{stroke-opacity:.3}96%{stroke-opacity:.7}100%{stroke-opacity:1}} +@keyframes medium{0%{stroke-opacity:0}30%{stroke-opacity:.4}36%{stroke-opacity:.75}42%{stroke-opacity:1}58%{stroke-opacity:.6}62%{stroke-opacity:.25}66%{stroke-opacity:0}80%{stroke-opacity:.4}84%{stroke-opacity:1}92%{stroke-opacity:.6}96%{stroke-opacity:.25}100%{stroke-opacity:0}} +@keyframes large{0%{stroke-opacity:0}58%{stroke-opacity:.4}62%{stroke-opacity:.75}66%{stroke-opacity:1}80%{stroke-opacity:.6}84%{stroke-opacity:0}100%{stroke-opacity:0}} +@keyframes shoot{0%,95%{stroke-opacity:0;transform:translate(0,0)}95.5%{stroke-opacity:1}99.2%{stroke-opacity:.9}100%{stroke-opacity:0;transform:translate(260px,162px)}} +@media (prefers-reduced-motion: reduce){*{animation:none!important}}` + + const defs = ` +<linearGradient id="night" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#080d26"/><stop offset="0.4" stop-color="#0b1230"/><stop offset="0.75" stop-color="#0f183e"/><stop offset="1" stop-color="#121c48"/></linearGradient> +<radialGradient id="glowBlue"><stop offset="0" stop-color="#2b3676" stop-opacity="0.32"/><stop offset="0.35" stop-color="#2b3676" stop-opacity="0.2"/><stop offset="0.7" stop-color="#2b3676" stop-opacity="0.07"/><stop offset="1" stop-color="#2b3676" stop-opacity="0"/></radialGradient> +<radialGradient id="glowCore"><stop offset="0" stop-color="#3d3a7c" stop-opacity="0.42"/><stop offset="0.4" stop-color="#30367a" stop-opacity="0.22"/><stop offset="0.72" stop-color="#2b3676" stop-opacity="0.07"/><stop offset="1" stop-color="#2b3676" stop-opacity="0"/></radialGradient>` + + return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1600 1000" width="100%" height="100%" preserveAspectRatio="xMidYMid slice" font-family="monospace" color="#888"><style>${style}</style><defs>${defs}</defs> +<rect width="1600" height="1000" fill="url(#night)"/> +<g class="sky"> +${bandGlow(spine)} +${milkyWayCells(spine)} +${fieldStars(spine)} +${figures()} +</g> +${shootingStar()} +<path d="${ridgeOutline(backRidge)}" style="fill:#0a1030"/><path d="${ridgeOutline(frontRidge)}" style="fill:#070b1f"/> +${ridgeDots()} +</svg>` +} diff --git a/plugins/theme-examples/hooks/scenes/classic.ts b/plugins/theme-examples/hooks/scenes/classic.ts new file mode 100644 index 00000000..8d8d0172 --- /dev/null +++ b/plugins/theme-examples/hooks/scenes/classic.ts @@ -0,0 +1,110 @@ +// The three first scenes: dark, soft, slow, made of gradients. +// Rules the dark scenes keep: +// no glyphs or text-sized marks; large, soft, slow shapes made of gradients (no filters, so no GPU is needed); +// the middle of the window, where the conversation sits, stays calm; the interest lives at the edges and corners. +const STILL = '@media (prefers-reduced-motion: reduce) { * { animation: none !important } }' + +function open(style: string, defs: string): string { + return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1600 1000" width="100%" height="100%" preserveAspectRatio="xMidYMid slice" font-family="monospace" color="#888"><style>${style} ${STILL}</style><defs>${defs}</defs>` +} + +function soft(id: string, color: string, peak: number): string { + return `<radialGradient id="${id}"><stop offset="0" stop-color="${color}" stop-opacity="${peak}"/><stop offset="1" stop-color="${color}" stop-opacity="0"/></radialGradient>` +} + +// A hint of calm down the middle. The app lays its own veil on the text column and owns legibility; this only keeps the centre from being the busiest part. +const CALM = `<radialGradient id="calm" cx="0.5" cy="0.55" r="0.6"><stop offset="0" stop-color="#000" stop-opacity="0.12"/><stop offset="0.6" stop-color="#000" stop-opacity="0.05"/><stop offset="1" stop-color="#000" stop-opacity="0"/></radialGradient>` +const calm = '<rect width="1600" height="1000" fill="url(#calm)"/>' + +/* Deep Water: light falling in from the top corners, slow caustic bands, a few big soft bubbles + up the far edges, and one turtle as a quiet silhouette in the bottom right corner. */ +export function deepWaterSvg(): string { + return `${open( + `.shaft{transform-origin:50% 0;animation:sway 38s ease-in-out infinite alternate} + .shaft.b{animation-duration:52s;animation-direction:alternate-reverse} + .band{animation:drift 70s ease-in-out infinite alternate} + .band.b{animation-duration:95s;animation-direction:alternate-reverse} + .bubble{animation:rise 46s linear infinite} + .honu{animation:glide 80s ease-in-out infinite alternate} + @keyframes sway{from{transform:skewX(-5deg)}to{transform:skewX(6deg)}} + @keyframes drift{from{transform:translateX(-90px)}to{transform:translateX(90px)}} + @keyframes rise{from{transform:translateY(0);opacity:0}12%{opacity:1}85%{opacity:1}to{transform:translateY(-1150px);opacity:0}} + @keyframes glide{from{transform:translate(0,0) rotate(-4deg)}to{transform:translate(-70px,-26px) rotate(3deg)}}`, + `<linearGradient id="deep" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#0f6f86"/><stop offset="0.45" stop-color="#0a4660"/><stop offset="1" stop-color="#041c30"/></linearGradient> + <linearGradient id="ray" x1="0" y1="0" x2="1" y2="0"><stop offset="0" stop-color="#bff3ff" stop-opacity="0"/><stop offset="0.5" stop-color="#bff3ff" stop-opacity="0.3"/><stop offset="1" stop-color="#bff3ff" stop-opacity="0"/></linearGradient> + <linearGradient id="down" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#fff"/><stop offset="0.92" stop-color="#000"/></linearGradient> + <mask id="fade" maskUnits="userSpaceOnUse" x="-400" y="-40" width="2400" height="900"><rect x="-400" y="-40" width="2400" height="900" fill="url(#down)"/></mask> + ${soft('caustic', '#9fe9f5', 0.2)} + ${soft('orb', '#c9f6ff', 0.22)}${soft('glint', '#e8fdff', 0.3)}${CALM}`, +)} +<rect width="1600" height="1000" fill="url(#deep)"/> +<g mask="url(#fade)"> +<g transform="translate(-60 0) skewX(-14)"><rect class="shaft" x="0" y="-40" width="460" height="900" fill="url(#ray)"/></g> +<g transform="translate(1180 0) skewX(11)"><rect class="shaft b" x="0" y="-40" width="520" height="900" fill="url(#ray)"/></g> +<g transform="translate(250 0) skewX(-20)"><rect class="shaft b" x="0" y="-40" width="420" height="900" fill="url(#ray)" opacity="0.55"/></g> +</g> +<g class="band"><ellipse cx="380" cy="130" rx="620" ry="70" fill="url(#caustic)"/><ellipse cx="1280" cy="170" rx="540" ry="56" fill="url(#caustic)"/></g> +<g class="band b"><ellipse cx="300" cy="900" rx="700" ry="80" fill="url(#caustic)"/><ellipse cx="1350" cy="880" rx="560" ry="64" fill="url(#caustic)"/></g> +<g class="bubble" style="animation-delay:-4s"><circle cx="70" cy="1060" r="46" fill="url(#orb)"/></g> +<g class="bubble" style="animation-delay:-21s"><circle cx="1535" cy="1080" r="62" fill="url(#orb)"/><circle cx="1518" cy="1060" r="15" fill="url(#glint)"/></g> +<g class="bubble" style="animation-delay:-33s"><circle cx="1470" cy="1050" r="30" fill="url(#orb)"/></g> +<g class="bubble" style="animation-delay:-14s"><circle cx="150" cy="1070" r="26" fill="url(#orb)"/></g> +<g transform="translate(1300 800)"><g class="honu" opacity="0.5"><g fill="#0b3a4d"> + <ellipse cx="0" cy="0" rx="92" ry="62"/> + <ellipse cx="108" cy="-10" rx="30" ry="20"/> + <path d="M40 -52 q60 -64 104 -40 q-44 10 -78 62z"/><path d="M36 52 q58 60 96 34 q-40 -6 -70 -54z"/> + <path d="M-58 -44 q-52 -30 -70 -6 q38 0 56 34z"/><path d="M-58 44 q-50 30 -66 8 q36 -2 54 -34z"/> + <path d="M-92 0 l-30 6 l28 6z"/></g> + <ellipse cx="0" cy="0" rx="70" ry="44" fill="#124d63"/></g></g> +${calm}</svg>` +} + +/* Aurora: a night sky that is almost black in the middle, with two wide ribbons of light swaying across the top + and a low ridge along the very bottom. */ +export function auroraSvg(): string { + return `${open( + `.ribbon{transform-origin:50% 0;animation:wave 44s ease-in-out infinite alternate} + .ribbon.b{animation-duration:63s;animation-direction:alternate-reverse} + .ribbon.c{transform-origin:50% 50%;animation-duration:90s} + .haze{animation:breathe 30s ease-in-out infinite alternate} + @keyframes wave{from{transform:translateX(-70px) skewX(-7deg) scaleY(0.94)}to{transform:translateX(70px) skewX(7deg) scaleY(1.08)}} + @keyframes breathe{from{opacity:0.55}to{opacity:1}}`, + `<linearGradient id="night" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#0c1136"/><stop offset="0.55" stop-color="#090b22"/><stop offset="1" stop-color="#05060f"/></linearGradient> + ${soft('green', '#5dffb5', 0.3)}${soft('violet', '#9f7bff', 0.26)}${soft('glow', '#3affc0', 0.2)}${soft('dusk', '#7a5cff', 0.18)}${CALM}`, +)} +<rect width="1600" height="1000" fill="url(#night)"/> +<ellipse class="haze" cx="260" cy="80" rx="520" ry="260" fill="url(#glow)"/> +<ellipse class="haze" cx="1400" cy="60" rx="480" ry="240" fill="url(#dusk)" style="animation-delay:-12s"/> +<g class="ribbon"><ellipse cx="-40" cy="230" rx="330" ry="150" fill="url(#green)"/><ellipse cx="260" cy="170" rx="360" ry="170" fill="url(#green)"/><ellipse cx="600" cy="230" rx="340" ry="140" fill="url(#green)"/><ellipse cx="930" cy="160" rx="360" ry="150" fill="url(#green)"/><ellipse cx="1270" cy="110" rx="340" ry="140" fill="url(#green)"/><ellipse cx="1600" cy="170" rx="330" ry="150" fill="url(#green)"/></g> +<g class="ribbon b"><ellipse cx="80" cy="110" rx="340" ry="130" fill="url(#violet)"/><ellipse cx="460" cy="80" rx="360" ry="140" fill="url(#violet)"/><ellipse cx="860" cy="290" rx="330" ry="120" fill="url(#violet)"/><ellipse cx="1220" cy="270" rx="350" ry="130" fill="url(#violet)"/><ellipse cx="1560" cy="80" rx="340" ry="140" fill="url(#violet)"/></g> +<g class="ribbon c"><ellipse cx="90" cy="430" rx="300" ry="260" fill="url(#green)"/><ellipse cx="150" cy="700" rx="260" ry="220" fill="url(#violet)"/><ellipse cx="1510" cy="460" rx="300" ry="270" fill="url(#violet)"/><ellipse cx="1470" cy="720" rx="260" ry="220" fill="url(#green)"/><ellipse cx="800" cy="330" rx="520" ry="150" fill="url(#green)" opacity="0.5"/></g> +<path d="M0 1000 L0 930 L180 880 L330 925 L520 868 L700 930 L900 892 L1080 938 L1260 876 L1430 926 L1600 884 L1600 1000Z" fill="#03040b"/> +${calm}</svg>` +} + +/* Ember: near-black with a warm glow pooled in the two bottom corners, and a handful of large soft embers + drifting up beside the conversation. Nothing bright crosses the middle or the sidebar's rows on the far left. */ +export function emberSvg(): string { + return `${open( + `.embers{animation:pulse 9s ease-in-out infinite alternate} + .embers.b{animation-duration:13s;animation-direction:alternate-reverse} + .ember{animation:lift 34s linear infinite} + @keyframes pulse{from{opacity:0.6;transform:scale(0.97)}to{opacity:1;transform:scale(1.04)}} + @keyframes lift{from{transform:translate(0,0);opacity:0}10%{opacity:0.9}70%{opacity:0.5}to{transform:translate(60px,-1100px);opacity:0}}`, + `<linearGradient id="dusk2" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#0d0709"/><stop offset="0.6" stop-color="#1c0b0e"/><stop offset="1" stop-color="#3a1210"/></linearGradient> + ${soft('fire', '#ff7a2a', 0.5)}${soft('coal', '#ff3d1a', 0.34)}${soft('mote', '#ffc27a', 0.75)}${soft('dim', '#ffc27a', 0.22)}${CALM}`, +)} +<rect width="1600" height="1000" fill="url(#dusk2)"/> +<ellipse class="embers b" cx="1380" cy="40" rx="620" ry="300" fill="url(#coal)" opacity="0.28"/> +<g style="transform-origin:120px 1000px" class="embers"><ellipse cx="120" cy="1010" rx="640" ry="520" fill="url(#fire)"/></g> +<g style="transform-origin:1500px 1000px" class="embers b"><ellipse cx="1500" cy="1020" rx="680" ry="560" fill="url(#coal)"/></g> +<ellipse cx="800" cy="1060" rx="900" ry="160" fill="url(#coal)" opacity="0.5"/> +<circle class="ember" cx="470" cy="1040" r="14" fill="url(#mote)" style="animation-delay:-3s"/> +<circle class="ember" cx="560" cy="1060" r="10" fill="url(#mote)" style="animation-delay:-17s"/> +<circle class="ember" cx="1380" cy="1050" r="18" fill="url(#mote)" style="animation-delay:-9s"/> +<circle class="ember" cx="1500" cy="1040" r="12" fill="url(#mote)" style="animation-delay:-25s"/> +<circle class="ember" cx="1250" cy="1070" r="9" fill="url(#mote)" style="animation-delay:-30s"/> +<circle class="ember" cx="120" cy="1080" r="18" fill="url(#dim)" style="animation-delay:-22s"/> +${calm}</svg>` +} + diff --git a/plugins/theme-examples/hooks/scenes/departure-board.ts b/plugins/theme-examples/hooks/scenes/departure-board.ts new file mode 100644 index 00000000..f251e045 --- /dev/null +++ b/plugins/theme-examples/hooks/scenes/departure-board.ts @@ -0,0 +1,266 @@ +// Departure Board: one big LED dot-matrix panel. A lattice of unlit dots runs edge to edge, and a slow diagonal swell of +// brightness passes through it on the left. Down the right-hand side, a tall board of an invented script is lit amber and +// runs off the frame's right and bottom edges. Every sixteen seconds one row re-letters, letter by letter from the left; +// a freshly lettered row glows a little brighter and settles over twenty seconds. Nothing else moves. +// +// Cheap to paint on purpose (it must hold 55 frames a second with no GPU): no mask and no group opacity anywhere. +// Fades that a mask used to make are painted over in the ground colour; rows carry their level in `fill-opacity`; +// the slow fades (the swell, a fresh row settling) move in small steps about once a second, so most frames paint nothing. + +const PITCH = 10 +const ROW_PITCH = 10 +const FIRST_ROW = 12 +const ROWS = 10 +const FIRST_SHOWN_ROW = 2 +const LAST_SHOWN_ROW = 8 +const GROUND = '#1f1710' +const LETTERS_PER_ROW = 7 +const LETTER_ADVANCE = 7 +const BOARD_COLUMN = 118 +const FLIP_SECONDS = 320 +const SWELL_SECONDS = 120 +const SWELL_STRIPES = 16 +const ALPHABET_SIZE = 28 +const AMBER = 'url(#dotAmber)' +const TEAL = 'url(#dotTeal)' + +/** One dot of the lattice, by column and row. */ +type Cell = { column: number; row: number } + +/** A negative delay starts an animation that many seconds into its cycle. */ +function delayOf(base: number, period: number): string { + const phase = ((base % period) + period) % period + return `-${phase.toFixed(2)}s` +} + +/** A small deterministic hash: the same build every time, with no random call and no clock. */ +function hashOf(seed: number): number { + let value = (seed * 2654435761) % 4294967296 + value = (value ^ (value >>> 13)) >>> 0 + value = (value * 1274126177) % 4294967296 + return ((value ^ (value >>> 16)) >>> 0) / 4294967296 +} + +/** One run of neighbouring cells in a row: a pitch-high rectangle that a dot pattern fills. */ +function runPath(start: number, end: number, row: number): string { + const width = (end - start + 1) * PITCH + return `M${start * PITCH} ${row * PITCH}h${width}v${PITCH}h-${width}z` +} + +/** Cells joined into one path of row runs. */ +function cellPath(cells: Cell[]): string { + const rows = new Map<number, number[]>() + for (const cell of cells) { + const columns = rows.get(cell.row) ?? [] + columns.push(cell.column) + rows.set(cell.row, columns) + } + let path = '' + for (const [row, columns] of rows) { + const sorted = [...columns].sort((a, b) => a - b) + let open = false + let start = 0 + let previous = 0 + for (const column of sorted) { + if (open && column === previous + 1) { + previous = column + continue + } + if (open) path += runPath(start, previous, row) + open = true + start = column + previous = column + } + if (open) path += runPath(start, previous, row) + } + return path +} + +/** + * The invented alphabet, from one kit of BROKEN strokes: a stem with a gap in it, one three-dot diagonal leaving + * the stem, one two-dot tick that floats free on the other side, and one loose dot. One grammar, so it looks like a script. + * No bar ever joins the stem, so it has no bracket, no E, F, H, 7 or T in it, whatever the alphabet; the gap keeps a stem + * from looking like a 1 or an I. + */ +function alphabet(): Cell[][] { + const letters: Cell[][] = [] + const seen = new Set<string>() + let seed = 1 + while (letters.length < ALPHABET_SIZE) { + seed += 1 + const stem = 1 + Math.floor(hashOf(seed * 3) * 3) + const gapAt = 1 + Math.floor(hashOf(seed * 5) * 4) + const side = hashOf(seed * 7) > 0.5 ? 1 : -1 + if ((stem === 1 && side < 0) || (stem === 3 && side > 0)) continue + const diagonalRow = hashOf(seed * 11) > 0.5 ? 0 : 6 + const tickRow = 2 + Math.floor(hashOf(seed * 13) * 3) + const cells: Cell[] = [] + for (let row = 0; row < 7; row += 1) { + if (row !== gapAt + 1) cells.push({ column: stem, row }) + } + for (let step = 1; step <= 3; step += 1) { + const column = stem + side * step + const row = diagonalRow === 0 ? step - 1 : 7 - step + if (column >= 0 && column <= 4) cells.push({ column, row }) + } + const tickColumn = side > 0 ? stem - 2 : stem + 2 + if (tickColumn >= 0 && tickColumn + 1 <= 4 && tickColumn - 1 !== stem && tickColumn + 2 !== stem) { + cells.push({ column: tickColumn, row: tickRow }, { column: tickColumn + 1, row: tickRow }) + } else { + cells.push({ column: side > 0 ? 0 : 4, row: tickRow }) + } + cells.push({ column: side > 0 ? 4 : 0, row: diagonalRow === 0 ? 6 : 0 }) + const key = cells.map(cell => `${cell.column},${cell.row}`).sort().join(' ') + if (seen.has(key)) continue + seen.add(key) + letters.push(cells) + } + return letters +} + +/** One letter cell: what it shows and what it will show; the two cross-fade when the row's turn comes. */ +function letter(x: number, y: number, seed: number, flipAt: number): string { + const first = Math.floor(hashOf(seed) * ALPHABET_SIZE) + const second = (first + 1 + Math.floor(hashOf(seed + 101) * (ALPHABET_SIZE - 1))) % ALPHABET_SIZE + const place = `x="${x}" y="${y}" style="animation-delay:${delayOf(FLIP_SECONDS / 2 - flipAt, FLIP_SECONDS)}"` + return `<use href="#letter${first}" class="was" ${place}/><use href="#letter${second}" class="next" ${place}/>` +} + +/** How bright a row rests: its own level, less at the top (just below the cards) and at the bottom (where a wide window crops). */ +function restingLevel(index: number): number { + const edge = index === FIRST_SHOWN_ROW ? 0.6 : index === LAST_SHOWN_ROW ? 0.55 : 1 + return (0.55 + 0.45 * hashOf(700 + index)) * edge +} + +/** A fresh row's glow and its settling: keyframes of `fill-opacity` that already hold the row's own level. */ +function freshKeyframes(index: number, fade: number, settle: number): string { + const rest = (restingLevel(index) * 0.74).toFixed(3) + const peak = (restingLevel(index) * 0.98).toFixed(3) + const gentle = 'animation-timing-function:steps(24)' + return `@keyframes fresh${index}{0%{fill-opacity:${peak};${gentle}}${settle.toFixed(2)}%{fill-opacity:${rest}}${(50 - 2 * fade).toFixed(2)}%{fill-opacity:${rest}}50%{fill-opacity:${peak};${gentle}}${(50 + settle).toFixed(2)}%{fill-opacity:${rest}}${(100 - 2 * fade).toFixed(2)}%{fill-opacity:${rest}}100%{fill-opacity:${peak}}}` +} + +/** + * The board: rows down the right side, from just below the cards to the bottom edge. Its last letters lie beyond the + * frame, so the crop cuts it. Rows keep the numbering of the full ten-row board, so their letters and turns stay put. + */ +function board(): string { + const x = BOARD_COLUMN * PITCH + let out = '' + let rules = '' + for (let index = FIRST_SHOWN_ROW; index <= LAST_SHOWN_ROW; index += 1) { + const row = FIRST_ROW + index * ROW_PITCH + const order = (index * 3 + 1) % ROWS + const flipAt = 13 + order * (FLIP_SECONDS / 2 / ROWS) + const freshDelay = delayOf(FLIP_SECONDS / 2 - flipAt - 1, FLIP_SECONDS) + let letters = '' + for (let position = 0; position < LETTERS_PER_ROW; position += 1) { + const gap = position >= 2 ? 1 : 0 + if (hashOf(900 + index * 17 + position) < 0.24) continue + letters += letter(x + (position * LETTER_ADVANCE + gap) * PITCH, row * PITCH, 500 + index * 13 + position, flipAt + position * 0.4) + } + const lampCells = [2, 3, 4].map(lampRow => ({ column: BOARD_COLUMN - 2, row: row + lampRow })) + const rest = (restingLevel(index) * 0.74).toFixed(3) + out += `<g style="fill-opacity:${rest};animation:fresh${index} ${FLIP_SECONDS}s linear ${freshDelay} infinite">${letters}</g><path class="lamp" style="animation-delay:${freshDelay}" d="${cellPath(lampCells)}" fill="${TEAL}"/>` + if (index > FIRST_SHOWN_ROW) rules += `M${x - 30} ${(row - 1) * PITCH}h520v${PITCH}h-520z` + } + return `<path d="${rules}" fill="url(#rule)"/><g fill="${AMBER}">${out}</g>` +} + +/** A horizontal slice of a slanted stripe, kept inside the left band: the stripe leans half a unit left per unit down. */ +function stripeSlice(left: number, width: number, from: number, to: number): string { + let path = '' + for (let y = 0; y < 1000; y += 50) { + const start = Math.max(from, left - y / 2) + const end = Math.min(to, left + width - y / 2) + if (end > start) path += `M${start.toFixed(0)} ${y}H${end.toFixed(0)}v50H${start.toFixed(0)}z` + } + return path +} + +/** + * The swell: diagonal stripes of brighter lattice dots, each fading up and down in turn, so a soft band of brightness + * drifts down the left band, under the sidebar's glass. It stays out from behind the lit letters. The stripes never + * move, so their dots stay on the lattice; each is cut in three along its length, fainter toward the reading column, + * which is the soft edge a mask used to give. + */ +function swell(): string { + let out = '' + const width = 150 + const parts = [{ from: 0, to: 290, level: 1 }, { from: 290, to: 360, level: 0.6 }, { from: 360, to: 420, level: 0.25 }] + for (let stripe = 0; stripe < SWELL_STRIPES; stripe += 1) { + const left = stripe * width + const delay = delayOf(30 - stripe * SWELL_SECONDS / SWELL_STRIPES, SWELL_SECONDS) + for (const part of parts) { + const path = stripeSlice(left, width, part.from, part.to) + if (path !== '') out += `<path class="swell" style="--peak:${part.level};animation-delay:${delay}" d="${path}"/>` + } + } + return `<g fill="url(#swellDot)">${out}</g>` +} + +/** A lit dot: a halo that stays inside the dot's own cell (so nothing can band), a core and a glint. */ +function dotPattern(id: string, halo: string, core: string, glint: string): string { + return `<radialGradient id="${id}Halo"><stop offset="0" stop-color="${halo}" stop-opacity="0.5"/><stop offset="0.5" stop-color="${halo}" stop-opacity="0.18"/><stop offset="1" stop-color="${halo}" stop-opacity="0"/></radialGradient>` + + `<pattern id="${id}" width="${PITCH}" height="${PITCH}" patternUnits="userSpaceOnUse"><rect width="${PITCH}" height="${PITCH}" fill="url(#${id}Halo)"/><circle cx="5" cy="5" r="2.5" fill="${core}"/><circle cx="5" cy="5" r="1.05" fill="${glint}"/></pattern>` +} + +function unlitPattern(id: string, radius: number, colour: string): string { + return `<pattern id="${id}" width="${PITCH}" height="${PITCH}" patternUnits="userSpaceOnUse"><circle cx="5" cy="5" r="${radius}" fill="${colour}"/></pattern>` +} + +function smooth(value: number): number { + const t = Math.max(0, Math.min(1, value)) + return t * t * (3 - 2 * t) +} + +/** How much of the lattice the reading column keeps: full in the side bands, a low even level across the middle, never zero. */ +function latticeLevel(x: number): number { + return 0.55 + 0.45 * smooth((0.34 - Math.min(x, 1 - x)) / 0.2) +} + +/** The lattice's fade toward the middle, painted OVER it in the ground colour: what a mask did, at a fraction of the cost. */ +function middleVeil(): string { + let stops = '' + for (let step = 0; step <= 24; step += 1) { + stops += `<stop offset="${(step / 24).toFixed(3)}" stop-color="${GROUND}" stop-opacity="${(1 - latticeLevel(step / 24)).toFixed(3)}"/>` + } + return `<linearGradient id="middleVeil" x1="0" y1="0" x2="1" y2="0">${stops}</linearGradient>` +} + +export function departureBoardSvg(): string { + const letters = alphabet() + const fade = (1.2 / FLIP_SECONDS * 100) + const settle = (20 / FLIP_SECONDS * 100) + const rowIndexes: number[] = [] + for (let index = FIRST_SHOWN_ROW; index <= LAST_SHOWN_ROW; index += 1) rowIndexes.push(index) + + const style = ` +.was{animation:was ${FLIP_SECONDS}s linear infinite} +.next{opacity:0;animation:next ${FLIP_SECONDS}s linear infinite} +@keyframes was{0%{opacity:1}${(50 - fade).toFixed(2)}%{opacity:1}50%{opacity:0}${(100 - fade).toFixed(2)}%{opacity:0}100%{opacity:1}} +@keyframes next{0%{opacity:0}${(50 - fade).toFixed(2)}%{opacity:0}50%{opacity:1}${(100 - fade).toFixed(2)}%{opacity:1}100%{opacity:0}} +${rowIndexes.map(index => freshKeyframes(index, fade, settle)).join('\n')} +@keyframes lamp{0%{fill-opacity:.9;animation-timing-function:steps(24)}${settle.toFixed(2)}%{fill-opacity:0}${(50 - 2 * fade).toFixed(2)}%{fill-opacity:0}50%{fill-opacity:.9;animation-timing-function:steps(24)}${(50 + settle).toFixed(2)}%{fill-opacity:0}${(100 - 2 * fade).toFixed(2)}%{fill-opacity:0}100%{fill-opacity:.9}} +.lamp{fill-opacity:0;animation:lamp ${FLIP_SECONDS}s linear infinite} +.swell{fill-opacity:0;animation:swell ${SWELL_SECONDS}s steps(20) infinite} +@keyframes swell{0%{fill-opacity:0}16%{fill-opacity:var(--peak)}32%{fill-opacity:0}100%{fill-opacity:0}} +@media (prefers-reduced-motion: reduce){*{animation:none!important}}` + + const defs = ` +${unlitPattern('unlit', 1.5, '#3a2b1d')} +${unlitPattern('rule', 1.6, '#523c1e')} +${unlitPattern('swellDot', 1.9, '#7a5526')} +${dotPattern('dotAmber', '#ee8f1c', '#f2a53a', '#ffe0aa')} +${dotPattern('dotTeal', '#2fb89c', '#5fd0b8', '#d8fff5')} +${middleVeil()} +${letters.map((cells, index) => `<path id="letter${index}" d="${cellPath(cells)}"/>`).join('')}` + + return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1600 1000" width="100%" height="100%" preserveAspectRatio="xMidYMid slice" font-family="monospace" color="#888"><style>${style}</style><defs>${defs}</defs> +<rect width="1600" height="1000" fill="${GROUND}"/> +<rect width="1600" height="1000" fill="url(#unlit)"/> +${swell()} +<rect width="1600" height="1000" fill="url(#middleVeil)"/> +${board()} +</svg>` +} diff --git a/plugins/theme-examples/hooks/scenes/dither-dunes.ts b/plugins/theme-examples/hooks/scenes/dither-dunes.ts new file mode 100644 index 00000000..be88204c --- /dev/null +++ b/plugins/theme-examples/hooks/scenes/dither-dunes.ts @@ -0,0 +1,364 @@ +// Dither Dunes: an ordered-dither desert, one terracotta sun. Two stocks: sand paper by day, umber paper by night. +// Pure string building: no DOM, no imports, the same output on every build. + +const WIDTH = 1600 +const HEIGHT = 1000 +/** One dither pixel is 5 units, so a 1200x800 window (scale 0.8) draws it 4 px wide exactly. */ +const CELL = 5 +/** The threshold matrix is 8x8 dither pixels: 64 tones, so shade runs smoothly. Tone layers are laid out, and moved, in whole tiles, so the dots never leave the grid. */ +const MATRIX = 8 +const TILE = CELL * MATRIX +const TILE_COLUMNS = WIDTH / TILE +const TILE_ROWS = HEIGHT / TILE +const TONES = MATRIX * MATRIX +/** Spare field above a crest, for the tone layers to move out of: they are clipped to the dune's outline and slide under it. */ +const MARGIN = 3 * TILE +/** Both inks stop near a third: above that the matrix draws crosses, and at this size they look like a fault. */ +const SOFT_CEILING = 0.34 +const DARK_CEILING = 0.28 +/** The dark ink only joins in where the shade is already this deep, so it never shows up in stray single pixels. */ +const DARK_FLOOR = 0.1 +const SUN_CENTER_X = 1376 +const SUN_CENTER_Y = 446 +const SUN_RADIUS = 34 +const BAYER: readonly (readonly number[])[] = bayerMatrix(MATRIX) + +/** + * A stock is the paper and the strengths of the one sand ink printed on it, and the sun's colour. + * haze prints the sky, lee the thin shadow under a crest where it crosses the conversation, soft prints sand at both edges of the window, + * strong only at the right edge, where no panel covers it. sands: the flat tone of each dune, back to front, a step apart. + */ +interface Stock { + readonly paper: string + readonly haze: string + readonly lee: string + readonly soft: string + readonly strong: string + readonly sun: string + readonly sands: readonly string[] +} + +const DAY: Stock = { paper: '#ece2cd', haze: '#e3d8c2', lee: '#d3c5a8', soft: '#bfad8b', strong: '#6f5d49', sun: '#c8573a', sands: ['#e8ddc7', '#e4d8c0', '#e0d3ba', '#dccfb4'] } +/** By night the same drawing is printed light on dark: the paper is umber, the dots are pale sand, nearer dunes are a step lighter. */ +const NIGHT: Stock = { paper: '#231d17', haze: '#2a231c', lee: '#40362a', soft: '#6b5c47', strong: '#988462', sun: '#c8573a', sands: ['#27211a', '#2b241c', '#2f271f', '#332b21'] } + +/** A point a crest line passes through; a third number of 1 marks a peak. */ +type CrestPoint = readonly [number, number, number?] + +/** + * Dunes, back to front: four long crests across the whole window. Each is everything under its crest line: a flat sand tone a shade + * apart from the one behind it (steps of about 3%, so under the conversation the land is there but nothing competes with text), + * plus dither shading at the window's edges only, strongest in the lee just under the crest and dissolving downward. + * tone: tone under the crest (0..1). reach: units it takes to dissolve. seconds: period of the light's creep. + * driftUnits, driftSeconds: how far the whole dune wanders sideways, and how long it takes. glint: the stretch of crest that catches the sun's colour (null: none). + */ +interface Dune { + readonly crest: readonly CrestPoint[] + readonly tone: number + readonly reach: number + readonly seconds: number + readonly driftUnits: number + readonly driftSeconds: number + readonly glint: readonly [number, number] | null +} + +const DUNES: readonly Dune[] = [ + { crest: [[0, 566], [250, 532, 1], [560, 592], [900, 604], [1200, 574], [1430, 524, 1], [1600, 552]], tone: 0.34, reach: 150, seconds: 104, driftUnits: 40, driftSeconds: 200, glint: null }, + { crest: [[0, 676], [330, 640, 1], [700, 724], [1000, 734], [1290, 644, 1], [1600, 706]], tone: 0.42, reach: 190, seconds: 88, driftUnits: -60, driftSeconds: 150, glint: null }, + { crest: [[0, 806], [200, 764, 1], [520, 864], [820, 904], [1100, 844], [1390, 724, 1], [1600, 794]], tone: 0.48, reach: 220, seconds: 96, driftUnits: 80, driftSeconds: 120, glint: [1230, 1600] }, + { crest: [[0, 934], [300, 904], [640, 962], [900, 972], [1250, 930, 1], [1600, 902]], tone: 0.5, reach: 160, seconds: 80, driftUnits: -100, driftSeconds: 100, glint: null }, +] + +/** A tone field to be dithered: the sky's haze, the sun, or one dune's shading in the soft or the strong ink. */ +interface Field { + readonly kind: 'haze' | 'sun' | 'soft' | 'strong' + readonly dune: Dune | null + readonly index: number +} + +/** How a stack of layers creeps: tiles per step on each axis, the period, and where in the period it starts. A period of 0 stands still. */ +interface Creep { + readonly x: number + readonly y: number + readonly seconds: number + readonly phase: number +} + +const STILL: Creep = { x: 0, y: 0, seconds: 0, phase: 0 } + +/** The ordered-dither threshold matrix, built by the usual doubling: each quarter is the smaller matrix times four, plus 0, 2, 3, 1. */ +function bayerMatrix(size: number): number[][] { + if (size === 1) return [[0]] + const half = bayerMatrix(size / 2) + const matrix: number[][] = [] + for (let y = 0; y < size; y += 1) { + const row: number[] = [] + for (let x = 0; x < size; x += 1) { + const top = y < size / 2 + const left = x < size / 2 + const quarter = top ? (left ? 0 : 2) : left ? 3 : 1 + row.push(4 * (half[y % (size / 2)]?.[x % (size / 2)] ?? 0) + quarter) + } + matrix.push(row) + } + return matrix +} + +/** The matrix's threshold for the dither pixel at a point (in units): a tone between 0 and 1. */ +function thresholdAt(x: number, y: number): number { + return ((BAYER[(y / CELL) % MATRIX]?.[(x / CELL) % MATRIX] ?? 0) + 0.5) / TONES +} + +function smoothstep(low: number, high: number, value: number): number { + const t = Math.min(1, Math.max(0, (value - low) / (high - low))) + return t * t * (3 - 2 * t) +} + +/** + * Height of a crest line at x. Between plain points it eases like a cosine, so it never overshoots. + * It runs into a peak steeply and concave, the way sand lies. + */ +function crestAt(points: readonly CrestPoint[], x: number): number { + let last = 0 + for (let index = 0; index < points.length; index += 1) { + const to = points[index] + if (to === undefined) continue + last = to[1] + if (x > to[0]) continue + const from = index === 0 ? undefined : points[index - 1] + if (from === undefined) return to[1] + const t = (x - from[0]) / (to[0] - from[0]) + let eased = (1 - Math.cos(Math.PI * t)) / 2 + if (to[2] === 1 && from[2] !== 1) eased = Math.pow(t, 1.7) + if (from[2] === 1 && to[2] !== 1) eased = 1 - Math.pow(1 - t, 1.7) + return from[1] + (to[1] - from[1]) * eased + } + return last +} + +/** The crest's height at x, on the dither grid. */ +function crestRow(dune: Dune, x: number): number { + return Math.round(crestAt(dune.crest, x + CELL / 2) / CELL) * CELL +} + +/** 0 under the conversation (24% to 76% of the width), 1 at the window's edges: where dots are allowed at all. */ +function edgeWeight(x: number): number { + const u = x / WIDTH + return Math.max(1 - smoothstep(0.06, 0.24, u), smoothstep(0.76, 0.93, u)) +} + +/** A dune's tone at a point. Above the crest it keeps the crest's tone. A slow swell keeps the bands from running parallel to the crest. */ +function duneTone(dune: Dune, index: number, x: number, y: number): number { + const depth = Math.max(0, y - crestAt(dune.crest, x)) + const swell = 0.86 + 0.14 * Math.sin(x / 120 + index * 2.3) + return dune.tone * swell * Math.pow(Math.max(0, 1 - depth / dune.reach), 1.4) +} + +/** The tone of a field at a point. */ +function fieldTone(field: Field, x: number, y: number): number { + if (field.kind === 'haze') { + const sides = Math.max(1 - smoothstep(0.08, 0.27, x / WIDTH), smoothstep(0.73, 0.92, x / WIDTH)) + return 0.2 * smoothstep(0, 620, y + 50 * Math.sin(x / 210)) * sides + } + if (field.kind === 'sun') { + const distance = Math.hypot(x - SUN_CENTER_X, y - SUN_CENTER_Y) + if (distance <= SUN_RADIUS) return 1 + if (distance <= SUN_RADIUS * 1.45) return 0.5 + return distance <= SUN_RADIUS * 1.9 ? 0.25 : 0 + } + const dune = field.dune + if (dune === null || y - crestAt(dune.crest, x) <= -MARGIN) return 0 + const tone = duneTone(dune, field.index, x, y) + if (field.kind === 'soft') return Math.min(SOFT_CEILING, tone * edgeWeight(x)) + /** The strong ink: the right edge only, and later than the soft ink. */ + return Math.min(DARK_CEILING, 1.4 * Math.max(0, tone * smoothstep(0.82, 0.97, x / WIDTH) - DARK_FLOOR)) +} + +/** + * One threshold of the matrix, drawn in tile units, between two tile columns: every tile whose pixel at that threshold passes the field's tone. + * Rows of runs; identical runs on consecutive rows are merged into taller boxes. + */ +function levelPath(level: number, firstColumn: number, lastColumn: number, field: Field): string { + let pixelColumn = 0 + let pixelRow = 0 + for (let y = 0; y < MATRIX; y += 1) { + for (let x = 0; x < MATRIX; x += 1) { + if (BAYER[y]?.[x] === level) { + pixelColumn = x + pixelRow = y + } + } + } + const threshold = (level + 0.5) / TONES + const open = new Map<string, number>() + let path = '' + for (let row = 0; row <= TILE_ROWS; row += 1) { + const seen = new Set<string>() + let runStart = -1 + for (let column = firstColumn; column <= lastColumn && row < TILE_ROWS; column += 1) { + const inked = column < lastColumn && fieldTone(field, column * TILE + (pixelColumn + 0.5) * CELL, row * TILE + (pixelRow + 0.5) * CELL) > threshold + if (inked && runStart < 0) runStart = column + if (!inked && runStart >= 0) { + const key = `${runStart} ${column - runStart}` + seen.add(key) + if (!open.has(key)) open.set(key, row) + runStart = -1 + } + } + for (const [key, firstRow] of [...open]) { + if (seen.has(key)) continue + const [start, length] = key.split(' ').map(Number) + path += `M${start ?? 0} ${firstRow}h${length ?? 0}v${row - firstRow}h${-(length ?? 0)}z` + open.delete(key) + } + } + return path +} + +/** A stack of threshold layers for one field in one ink. Every layer creeps a whole tile at a time, three tiles there and back, each a little after the last. */ +function layerStack(ink: string, firstColumn: number, lastColumn: number, field: Field, creep: Creep): string { + let layers = '' + for (let level = 0; level < TONES; level += 1) { + const path = levelPath(level, firstColumn, lastColumn, field) + if (path === '') continue + let motion = '' + if (creep.seconds !== 0) { + const delay = ((creep.phase + level * 2.9) % creep.seconds).toFixed(1) + motion = ` class="creep" style="--x:${creep.x * 3}px;--y:${creep.y * 3}px;animation-duration:${creep.seconds}s;animation-delay:-${delay}s"` + } + layers += `<path${motion} d="${path}" fill="url(#${ink}${level})"/>` + } + return layers +} + +/** The dune's outline, a staircase on the dither grid, so its edge is made of the pixels its shading is made of. It runs past both sides of the window, for the drift. */ +function outlinePath(dune: Dune): string { + const spare = 120 + let path = `M${-spare} ${HEIGHT}` + let previous = -1 + for (let x = -spare; x < WIDTH + spare; x += CELL) { + const top = crestRow(dune, x) + if (top !== previous) { + path += previous < 0 ? `V${top}` : `H${x}V${top}` + previous = top + } + } + return `${path}H${WIDTH + spare}V${HEIGHT}z` +} + +/** A lit crest: sun-coloured pixels lying on a stretch of crest, nearly solid for two pixels and thinning out over the four below, and toward both ends. */ +function glintPath(dune: Dune, stock: Stock): string { + if (dune.glint === null) return '' + const [from, to] = dune.glint + let path = '' + for (let x = from; x < to; x += CELL) { + const ends = Math.min(smoothstep(from, from + 120, x), 1 - smoothstep(to - 60, to + 60, x)) + for (let deep = 0; deep < 6; deep += 1) { + const y = crestRow(dune, x) + deep * CELL + const tone = deep < 2 ? 0.9 : 0.55 * Math.pow(1 - (deep - 2) / 4, 1.5) + if (tone * ends > thresholdAt(x, y)) path += `M${x} ${y}h${CELL}v${CELL}h${-CELL}z` + } + } + return `<path d="${path}" fill="${stock.sun}"/>` +} + +/** Where a crest crosses the conversation it still gets shaded in dots: a band two pixels deep, half then a quarter, in an ink barely apart from the sand. */ +function leePath(dune: Dune, stock: Stock): string { + let path = '' + for (let x = 240; x < 1360; x += CELL) { + const middle = 1 - edgeWeight(x) + for (let deep = 0; deep < 2; deep += 1) { + const y = crestRow(dune, x) + deep * CELL + if ((deep === 0 ? 0.5 : 0.25) * middle > thresholdAt(x, y)) path += `M${x} ${y}h${CELL}v${CELL}h${-CELL}z` + } + } + return `<path d="${path}" fill="${stock.lee}"/>` +} + +/** + * One dune. Its outline (the flat sand, the clip, the lee and the glint) wanders sideways one dither pixel at a time, while its dots stay where they are + * on the screen: the shape slides across a still dither screen, the way a one-bit game does it, so only the pixels along the crest ever change. + */ +function dunePart(dune: Dune, index: number, stock: Stock): string { + const outline = outlinePath(dune) + const softField: Field = { kind: 'soft', dune, index } + const strongField: Field = { kind: 'strong', dune, index } + const softLeft = layerStack('soft', 0, TILE_COLUMNS / 2, softField, { x: -1, y: 1, seconds: dune.seconds * 1.3, phase: index * 19 }) + const softRight = layerStack('soft', TILE_COLUMNS / 2, TILE_COLUMNS, softField, { x: 1, y: 1, seconds: dune.seconds * 1.3, phase: index * 23 }) + const strong = layerStack('strong', TILE_COLUMNS / 2, TILE_COLUMNS, strongField, { x: 1, y: 1, seconds: dune.seconds, phase: index * 29 }) + const wander = `style="--d:${dune.driftUnits}px;animation-duration:${dune.driftSeconds}s;animation-delay:-${(index * 31) % dune.driftSeconds}s;animation-timing-function:steps(${Math.abs(dune.driftUnits) / CELL})"` + const sand = stock.sands[index] ?? stock.paper + return `<clipPath id="c${index}"><path d="${outline}"/></clipPath><g class="drift" ${wander}><path d="${outline}" fill="${sand}"/><g clip-path="url(#c${index})"><g class="undrift" ${wander}><g transform="scale(${TILE})">${softLeft}${softRight}${strong}</g></g></g>${leePath(dune, stock)}${glintPath(dune, stock)}</g>` +} + +/** The sky is not left blank at the window's edges: a haze of the faintest ink gathers toward the horizon. Like the sand's dots it keeps out from under the conversation. */ +function skyPart(): string { + return `<g transform="scale(${TILE})">${layerStack('haze', 0, TILE_COLUMNS, { kind: 'haze', dune: null, index: 0 }, STILL)}</g>` +} + +/** The sun is dithered too: a solid disc inside two clean rings of its own dots, a half and a quarter. It starts clear of the far dune and climbs up and a little to the left, one pixel at a time. */ +function sunPart(): string { + return `<g class="rise"><g class="veer"><g transform="scale(${TILE})">${layerStack('sun', 0, TILE_COLUMNS, { kind: 'sun', dune: null, index: 0 }, STILL)}</g></g></g>` +} + +/** Grains blown along two crests, at the window's edges only: single soft pixels, stepping one pixel at a time, downwind. */ +function grainsPart(stock: Stock): string { + let out = '' + for (let grain = 0; grain < 22; grain += 1) { + const right = grain % 3 !== 0 + const startX = right ? 1260 + ((grain * 29) % 120) : 40 + ((grain * 31) % 120) + const dune = right ? DUNES[2] : DUNES[1] + if (dune === undefined) continue + const y = crestRow(dune, startX + 110) - CELL * (2 + ((grain * 37) % 5)) + const seconds = 34 + ((grain * 13) % 25) + out += `<rect class="grain" style="animation-duration:${seconds}s;animation-delay:-${(grain * 6.1).toFixed(1)}s" x="${startX - (startX % CELL)}" y="${y}" width="${CELL}" height="${CELL}" fill="${stock.soft}"/>` + } + return out +} + +/** One pattern per threshold of the matrix, each a single dither pixel in its place in the tile, in one ink. */ +function bayerPatterns(name: string, colour: string, levels: number): string { + let out = '' + for (let y = 0; y < MATRIX; y += 1) { + for (let x = 0; x < MATRIX; x += 1) { + const level = BAYER[y]?.[x] ?? 0 + if (level < levels) out += `<pattern id="${name}${level}" width="1" height="1" patternUnits="userSpaceOnUse"><rect x="${x / MATRIX}" y="${y / MATRIX}" width="${1 / MATRIX}" height="${1 / MATRIX}" fill="${colour}"/></pattern>` + } + } + return out +} + +/** The whole scene on one stock. */ +function sceneSvg(stock: Stock): string { + const style = ` +.creep{animation:creep 90s steps(3) infinite alternate} +.rise{animation:rise 200s steps(38) infinite alternate} +.veer{animation:veer 200s steps(19) infinite alternate} +.drift{animation:drift 120s steps(12) infinite alternate} +.undrift{animation:undrift 120s steps(12) infinite alternate} +.grain{animation:grain 50s steps(44) infinite} +@keyframes creep{from{transform:translate(0,0)}to{transform:translate(var(--x),var(--y))}} +@keyframes rise{from{transform:translate(0,0)}to{transform:translate(0,-${38 * CELL}px)}} +@keyframes veer{from{transform:translate(0,0)}to{transform:translate(-${19 * CELL}px,0)}} +@keyframes drift{from{transform:translate(0,0)}to{transform:translate(var(--d),0)}} +@keyframes undrift{from{transform:translate(0,0)}to{transform:translate(calc(var(--d) * -1),0)}} +@keyframes grain{0%{transform:translate(0,0);opacity:0}8%{opacity:1}80%{opacity:1}100%{transform:translate(${44 * CELL}px,0);opacity:0}} +@media (prefers-reduced-motion: reduce){*{animation:none!important}.grain{opacity:0}}` + const inked = Math.ceil(SOFT_CEILING * TONES) + const patterns = bayerPatterns('haze', stock.haze, inked) + bayerPatterns('soft', stock.soft, inked) + bayerPatterns('strong', stock.strong, inked) + bayerPatterns('sun', stock.sun, TONES) + const dunes = DUNES.map((dune, index) => dunePart(dune, index, stock)).join('') + return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${WIDTH} ${HEIGHT}" width="100%" height="100%" preserveAspectRatio="xMidYMid slice" font-family="monospace" color="#888"><style>${style}</style><defs>${patterns}</defs> +<rect width="${WIDTH}" height="${HEIGHT}" fill="${stock.paper}"/> +${skyPart()}${sunPart()}${dunes}${grainsPart(stock)} +</svg>` +} + +/** Dither Dunes: dunes on sand paper, for a light window. */ +export function ditherDunesSvg(): string { + return sceneSvg(DAY) +} + +/** Dither Dunes Night: the same dunes printed pale on umber paper, for a dark window. */ +export function ditherDunesNightSvg(): string { + return sceneSvg(NIGHT) +} diff --git a/plugins/theme-examples/hooks/scenes/halftone-dawn.ts b/plugins/theme-examples/hooks/scenes/halftone-dawn.ts new file mode 100644 index 00000000..36d99e17 --- /dev/null +++ b/plugins/theme-examples/hooks/scenes/halftone-dawn.ts @@ -0,0 +1,172 @@ +// Halftone Dawn and Halftone Dusk: one two-ink risograph sunrise printed on two stocks. Every mark is a round dot on one tilted screen; dot size is the only drawing tool. +// Pure string building: no DOM, no imports. Two exports: halftoneDawnSvg (cream stock, light windows) and halftoneDuskSvg (night-blue stock, dark windows). + +interface Wave { + seconds: number + length: number + rest: number + peak: number + sharp: number + name: string +} + +interface Stock { + paperTop: string + paperFoot: string + coral: string + coralOpacity: number + blue: string + blueOpacity: number + blend: string +} + +interface DotGroup { + band: number + width: number + d: string +} + +const WIDTH = 1600 +const HEIGHT = 1000 +const PITCH = 11 +const SCREEN_DEGREES = 15 +const SUN = { x: 1408, y: 786, radius: 220 } +// Each wave is a pulse, not a sine: dots rest at `rest` and swell (or thin) to `peak` while a narrow crest passes, so each ring stays a ring. +const SUN_WAVE: Wave = { seconds: 24, length: 132, rest: 0.8, peak: 1.32, sharp: 1.4, name: 'breathe' } +const HILL_WAVE: Wave = { seconds: 40, length: 560, rest: 1.03, peak: 0.7, sharp: 1.5, name: 'mist' } +const BAND = 12 +// Inks multiply on cream like real overprint; on the dark stock multiply would vanish, so they sit on top. +const DAWN_STOCK: Stock = { paperTop: '#f6ecdc', paperFoot: '#f2dcc6', coral: '#d45c3d', coralOpacity: 1, blue: '#6283b6', blueOpacity: 1, blend: 'multiply' } +const DUSK_STOCK: Stock = { paperTop: '#1b1f30', paperFoot: '#272a3f', coral: '#d9603a', coralOpacity: 0.86, blue: '#7f90ba', blueOpacity: 0.7, blend: 'normal' } + +function smooth(from: number, to: number, value: number): number { + const t = Math.min(1, Math.max(0, (value - from) / (to - from))) + return t * t * (3 - 2 * t) +} + +/** A single rounded hill: a bell of the given height and half-width. */ +function bell(x: number, peakX: number, halfWidth: number, height: number): number { + const t = (x - peakX) / halfWidth + return height * Math.exp(-t * t) +} + +/** 0 under the reading column, 1 at the side panels. */ +function awayFromColumn(x: number): number { + return Math.max(1 - smooth(300, 520, x), smooth(1080, 1260, x)) +} + +/** Far crest: ONE range across the whole sheet. Tall under the sidebar, a low quiet line below the prompt box, rising again in front of the sun. */ +function farCrest(x: number): number { + return 968 - 34 * awayFromColumn(x) - bell(x, 150, 250, 205) - bell(x, 1600, 330, 135) - 13 * Math.sin(x / 150 + 1) - 5 * Math.sin(x / 53) +} + +/** Near crest: darker foothills at the two sides only; under the column it is below the sheet. */ +function nearCrest(x: number): number { + return 1014 - bell(x, -50, 270, 190) - bell(x, 1340, 250, 100) - 7 * Math.sin(x / 90 + 2) +} + +/** Blue tone: a pale far range and darker foothills, lighter towards their feet like hills in mist. Each crest is dithered: dots grow from nothing over 36 px. */ +function hillTone(x: number, y: number): number { + const near = 0.42 * smooth(0, 36, y - nearCrest(x)) - 0.12 * smooth(36, 150, y - nearCrest(x)) + const far = 0.21 * smooth(0, 36, y - farCrest(x)) - 0.06 * smooth(36, 160, y - farCrest(x)) + // The floor is loud only at its two ends: under the column the dots carry a third of the weight. + return Math.max(near, far, 0) * (0.3 + 0.7 * awayFromColumn(x)) +} + +/** + * Coral tone: one centre, one continuous falloff. A level body, a soft rim, then a short halo of small clean dots that ends + * about 80 px beyond the rim. The hills hide it: it fades out over the same band in which their dots grow. + */ +function sunTone(x: number, y: number): number { + const d = Math.hypot(x - SUN.x, y - SUN.y) + const behindHills = 1 - smooth(2, 38, y - Math.min(farCrest(x), nearCrest(x))) + const body = d < SUN.radius ? 0.37 * (1 - Math.pow(d / SUN.radius, 4)) : 0 + const glow = 0.06 * Math.pow(1 - smooth(0, 150, d - SUN.radius * 0.9), 1.3) + return Math.max(body, glow) * behindHills +} + +/** Ring number around the sun: the sun's wave travels outward through these. */ +function sunBand(x: number, y: number): number { + return Math.hypot(x - SUN.x, y - SUN.y) / BAND +} + +/** The hills' own wave runs along the ground, away from the sun. */ +function hillBand(x: number): number { + return Math.abs(SUN.x - x) / BAND +} + +/** + * Dots of one ink, gathered by band (for the wave's delay) and by diameter (one stroke width per path). + * Both inks share one tilted lattice; the second ink sits half a cell over, so where they meet the dots interleave instead of colliding. + * Dots under 2.3 px are not drawn: at that size they look like dust, not print. + */ +function screen(toneAt: (x: number, y: number) => number, bandAt: (x: number, y: number) => number, wave: Wave, halfCell: boolean): string { + const turn = (SCREEN_DEGREES * Math.PI) / 180 + const cos = Math.cos(turn) + const sin = Math.sin(turn) + const reach = Math.ceil(2000 / PITCH) + const offset = halfCell ? 0.5 : 0 + const groups = new Map<string, DotGroup>() + for (let i = -reach; i <= reach; i += 1) { + for (let j = -reach; j <= reach; j += 1) { + const x = 800 + ((i + offset) * cos - (j + offset) * sin) * PITCH + const y = 500 + ((i + offset) * sin + (j + offset) * cos) * PITCH + if (x < -6 || x > WIDTH + 6 || y < -6 || y > HEIGHT + 6) continue + const diameter = 2 * PITCH * Math.sqrt(toneAt(x, y) / Math.PI) + if (diameter < 2.3) continue + const band = Math.floor(bandAt(x, y)) + const width = Math.round(diameter * 2) / 2 + const key = `${band}|${width}` + const group = groups.get(key) ?? { band, width, d: '' } + group.d += `M${x.toFixed(1)} ${y.toFixed(1)}h0` + groups.set(key, group) + } + } + let markup = '' + for (const group of groups.values()) { + const lag = (((group.band + 0.5) * BAND) / wave.length) % 1 + const delay = (lag * wave.seconds - wave.seconds).toFixed(2) + markup += `<path style="--w:${group.width}px;animation-delay:${delay}s" d="${group.d}"/>` + } + return markup +} + +/** Keyframes that walk the pulse in small steps: stroke width repaints a few times a second, never every frame. */ +function waveKeyframes(wave: Wave): string { + let frames = '' + for (let step = 0; step <= 12; step += 1) { + const pulse = Math.pow((1 + Math.cos((step / 12) * 2 * Math.PI)) / 2, wave.sharp) + const scale = wave.rest + (wave.peak - wave.rest) * pulse + frames += `${((step * 100) / 12).toFixed(2)}%{stroke-width:calc(var(--w)*${scale.toFixed(3)})}` + } + return `@keyframes ${wave.name}{${frames}}` +} + +/** One sheet: the same two plates on the given stock. */ +function sheetSvg(stock: Stock): string { + const sun = screen(sunTone, sunBand, SUN_WAVE, false) + const hills = screen(hillTone, hillBand, HILL_WAVE, true) + const style = ` +.ink{mix-blend-mode:${stock.blend}} +.ink path{fill:none;stroke-linecap:round;stroke-width:var(--w);animation:${SUN_WAVE.name} ${SUN_WAVE.seconds}s steps(4) infinite} +.blue path{animation-name:${HILL_WAVE.name};animation-duration:${HILL_WAVE.seconds}s} +${waveKeyframes(SUN_WAVE)} +${waveKeyframes(HILL_WAVE)} +@media (prefers-reduced-motion: reduce){*{animation:none!important}}` + return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${WIDTH} ${HEIGHT}" width="100%" height="100%" preserveAspectRatio="xMidYMid slice" font-family="monospace" color="#888"><style>${style}</style><defs> +<linearGradient id="paper" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="${stock.paperTop}"/><stop offset="1" stop-color="${stock.paperFoot}"/></linearGradient></defs> +<rect width="${WIDTH}" height="${HEIGHT}" fill="url(#paper)"/> +<g class="ink" stroke="${stock.coral}" stroke-opacity="${stock.coralOpacity}">${sun}</g> +<g class="ink blue" stroke="${stock.blue}" stroke-opacity="${stock.blueOpacity}">${hills}</g> +</svg>` +} + +/** Halftone Dawn: the cream sheet, for light windows. */ +export function halftoneDawnSvg(): string { + return sheetSvg(DAWN_STOCK) +} + +/** Halftone Dusk: the same plates on night-blue stock with an ember sun, for dark windows. */ +export function halftoneDuskSvg(): string { + return sheetSvg(DUSK_STOCK) +} diff --git a/plugins/theme-examples/hooks/scenes/honu-lagoon.ts b/plugins/theme-examples/hooks/scenes/honu-lagoon.ts new file mode 100644 index 00000000..c0e25b6e --- /dev/null +++ b/plugins/theme-examples/hooks/scenes/honu-lagoon.ts @@ -0,0 +1,334 @@ +// Honu Lagoon: a lagoon seen from above on a cell grid: every tile is a +// square with a glyph in it. A turtle (honu) swims in its own clear water on the right, a smaller coral animal drifts by the +// sidebar's edge, a sand island with trails of sand tiles fills the top right corner, a shoal lies along the bottom. +// It is a LIGHT-window scene. Pure string building, the same every time: animals and land are drawn from geometry, +// rasterised onto the grid. +const CELL = 15 +const COLUMNS = Math.ceil(1600 / CELL) +const ROWS = Math.ceil(1000 / CELL) +const GLYPHS = '$%tSX:;t$%S' + +type Cell = { x: number; y: number; kind: string; body?: boolean } +type Paint = { tile: string; glyph: string; opacity: number } +type Heading = readonly [number, number] + +/** Tile kinds: what each letter paints. Glyphs are tone on tone; sand fades toward the tips by colour AND a little by opacity. */ +const KINDS: Record<string, Paint> = { + q: { tile: '#ef7f8e', glyph: '#fbc4cb', opacity: 1 }, + p: { tile: '#e2486c', glyph: '#f6a0b2', opacity: 1 }, + r: { tile: '#d93a63', glyph: '#f28a9f', opacity: 1 }, + R: { tile: '#c22a52', glyph: '#ee7790', opacity: 1 }, + o: { tile: '#e8873a', glyph: '#fbd3a4', opacity: 1 }, + k: { tile: '#9c1f3d', glyph: '#de6c86', opacity: 1 }, + a: { tile: '#f2cf3a', glyph: '#b58f1c', opacity: 1 }, + b: { tile: '#f2d54e', glyph: '#bb9a2c', opacity: 1 }, + c: { tile: '#f3df7a', glyph: '#c2a646', opacity: 0.95 }, + d: { tile: '#f3e6a0', glyph: '#c8b878', opacity: 0.9 }, + g: { tile: '#8f9a52', glyph: '#c3cc8c', opacity: 1 }, + w: { tile: '#b8a85a', glyph: '#8a7c3c', opacity: 1 }, + l: { tile: '#e9d28a', glyph: '#b79d52', opacity: 1 }, + m: { tile: '#d9bd6a', glyph: '#a58a3c', opacity: 1 }, + n: { tile: '#a8923c', glyph: '#75642a', opacity: 1 }, + v: { tile: '#a8964c', glyph: '#75682e', opacity: 1 }, + f: { tile: '#f5efcf', glyph: '#c9c09a', opacity: 0.6 }, + u: { tile: '#e9d9a0', glyph: '#a98f4a', opacity: 0.75 }, +} + +function hash(x: number, y: number): number { + let h = (x * 374761393 + y * 668265263) >>> 0 + h = ((h ^ (h >>> 13)) * 1274126177) >>> 0 + return ((h ^ (h >>> 16)) >>> 0) / 4294967296 +} + +/** How far a point is from a line segment, and how far along it the nearest point lies. */ +function distanceToSegment(px: number, py: number, ax: number, ay: number, bx: number, by: number): { distance: number; along: number } { + const dx = bx - ax + const dy = by - ay + const along = Math.max(0, Math.min(1, ((px - ax) * dx + (py - ay) * dy) / (dx * dx + dy * dy))) + return { distance: Math.hypot(px - ax - along * dx, py - ay - along * dy), along } +} + +/** + * The cells of a turtle seen from above. `heading` is the unit vector it swims along; `size` scales it (1 = the big one); + * `sweep` is how far the front flippers are swept back, in degrees from straight out (0) to along the body (90). + * Everything is tested in the turtle's own frame: `a` along the heading, `b` across it. + */ +function turtleCells(heading: Heading, size: number, sweep: number, surge: number): Cell[] { + const [ux, uy] = heading + const vx = uy + const vy = -ux + const reach = Math.ceil(19 * size) + const cells: Cell[] = [] + const angle = ((90 - sweep) * Math.PI) / 180 + for (let y = -reach; y <= reach; y += 1) { + for (let x = -reach; x <= reach; x += 1) { + const a = (x * ux + y * uy) / size - surge + const b = (x * vx + y * vy) / size + const shell = (a / 5.6) ** 2 + (b / 4.4) ** 2 + if (shell <= 1) { + const pick = hash(x + 91, y + 17) + // A spine of dark scutes down the middle gives the shell an axis; the rim is ragged where a pale tile drops out. + const spine = Math.abs(b) <= 1.3 && Math.abs(a) <= 4.2 + if (shell > 0.82 && pick < 0.1) continue + const kind = spine ? (Math.round(a) % 2 === 0 ? 'k' : 'R') : shell < 0.5 ? (pick < 0.14 ? 'o' : pick < 0.6 ? 'r' : 'R') : shell < 0.85 ? (pick < 0.7 ? 'r' : 'p') : pick < 0.3 ? 'q' : 'p' + cells.push({ x, y, kind, body: true }) + continue + } + // The head and its neck: solid sand, in line with the body, so the leading end is plain to see. + if (a > 5.2 && a <= 7.6 && Math.abs(b) <= 1.1) { + cells.push({ x, y, kind: 'a', body: true }) + continue + } + if (Math.hypot(a + 6.2, b) <= 0.7) { + cells.push({ x, y, kind: 'c' }) + continue + } + let limb: number | undefined + for (const side of [1, -1]) { + const front = distanceToSegment(a, b, 3.3, side * 4.3, 3.3 - 4.5 * Math.cos(angle), side * (4.3 + 4.5 * Math.sin(angle))) + if (front.distance <= 1.05) limb = front.along + const back = distanceToSegment(a, b, -4.3, side * 3.3, -4.3 - 1.6 * Math.cos(0.8), side * (3.3 + 1.6 * Math.sin(0.8))) + if (back.distance <= 0.75) limb = 0.3 + back.along * 0.5 + } + if (limb !== undefined) cells.push({ x, y, kind: limb < 0.55 ? 'a' : limb < 0.85 ? 'b' : 'c' }) + } + } + return cells +} + +/** The second animal, like the clip's: mid-size, coral only, a rounded body with a blunt snout and two stubby fins. */ +function coralCells(): Cell[] { + const cells: Cell[] = [] + for (let y = -5; y <= 5; y += 1) { + for (let x = -5; x <= 6; x += 1) { + const body = (x / 3.1) ** 2 + ((y - 0.3) / 2.6) ** 2 + const head = x >= 3 && x <= 4 && Math.abs(y) <= 1 + const fin = (x === -1 || x === 0) && (y === -3 || y === 3 || y === 4) + if (body > 1 && !head && !fin) continue + const pick = hash(x + 33, y + 71) + const kind = head ? 'p' : body < 0.2 ? 'R' : body < 0.6 ? (pick < 0.5 ? 'r' : 'p') : pick < 0.55 ? 'p' : 'q' + cells.push({ x, y, kind, body: true }) + } + } + return cells +} + +/** Where each sand trail starts (column, row), how many rows it runs, and the row at which it kinks. */ +const TRAILS: readonly (readonly [number, number, number, number])[] = [ + [COLUMNS - 30, 4, 7, 3], + [COLUMNS - 13, 5, 19, 9], + [COLUMNS - 4, 5, 11, 5], +] + +/** One cell of the island, unless something already stands there or it is off the grid. */ +function putCell(cells: Cell[], taken: Set<string>, x: number, y: number, kind: string): void { + if (x < 0 || y < 0 || x >= COLUMNS || taken.has(`${x},${y}`)) return + taken.add(`${x},${y}`) + cells.push({ x, y, kind }) +} + +/** + * The island in the top right corner: an uneven blob whose top rows are olive and khaki and whose shore is pale sand, with + * foam on its left tip, and three diagonal trails of fading sand tiles running down and left toward the turtle's water. + */ +function islandCells(): Cell[] { + const cells: Cell[] = [] + const taken = new Set<string>() + const middle = COLUMNS - 15 + for (let y = 0; y < 7; y += 1) { + for (let x = COLUMNS - 36; x < COLUMNS; x += 1) { + const depth = 4.4 + Math.sin(x / 2.7) * 1.2 + (hash(x, 400) - 0.5) * 1.6 - Math.max(0, COLUMNS - 30 - x) * 0.5 + if (y > depth) continue + const pick = hash(x + 5, y + 900) + const heart = Math.hypot((x - middle) / 7, (y - 1.5) / 2.2) + const kind = heart < 1 && pick < 0.22 ? (pick < 0.08 ? 'g' : pick < 0.15 ? 'w' : 'v') : y >= depth - 0.9 ? (x < COLUMNS - 29 ? 'f' : 'd') : y === 0 ? (pick < 0.5 ? 'n' : 'm') : pick < 0.45 ? 'a' : pick < 0.8 ? 'l' : 'm' + putCell(cells, taken, x, y, kind) + } + } + // Three trails of sand running down and left in staggered clumps two to four cells wide, each with one kink; the longest + // passes within a cell of the turtle's home, so the animal seems to trail sand behind it. + for (const [startX, startY, length, kinkAt] of TRAILS) { + let x = startX + for (let step = 0; step < length; step += 1) { + const share = step / length + const kind = share < 0.4 ? 'a' : share < 0.75 ? 'b' : 'c' + const width = 3 + Math.floor(hash(startX + step, 31) * 2) + const shift = hash(startX, step + 9) < 0.4 ? 1 : 0 + for (let across = 0; across < Math.max(1, width); across += 1) putCell(cells, taken, x + across - shift, startY + step, kind) + x -= step === kinkAt ? 2 : step % 3 === 2 ? 0 : 1 + } + } + return cells +} + +/** A low bank of sand tiles along the bottom right, clear of the prompt box. */ +function shoalCells(): Cell[] { + const cells: Cell[] = [] + for (let y = ROWS - 7; y < ROWS; y += 1) { + for (let x = COLUMNS - 45; x < COLUMNS - 1; x += 1) { + const height = 3.6 + Math.sin(x / 3.1) * 1.4 + (hash(x, 77) - 0.5) * 2 - Math.max(0, COLUMNS - 38 - x) * 0.35 + if (ROWS - y <= height) cells.push({ x, y: y - 2, kind: 'u' }) + } + } + return cells +} + +function glyphAt(x: number, y: number): string { + return GLYPHS[Math.floor(hash(x + 7, y + 3) * GLYPHS.length)] ?? '$' +} + +/** Tiles of one kind in a single path; glyphs in one text per row with a per-glyph x list. */ +function mosaic(cells: Cell[]): string { + const byKind = new Map<string, Cell[]>() + for (const cell of cells) { + const list = byKind.get(cell.kind) ?? [] + list.push(cell) + byKind.set(cell.kind, list) + } + let out = '' + for (const [kind, list] of byKind) { + const paint = KINDS[kind] + if (paint === undefined) continue + const path = list.map(c => `M${c.x * CELL + 1} ${c.y * CELL + 1}h${CELL - 2}v${CELL - 2}h-${CELL - 2}z`).join('') + let group = `<path d="${path}" fill="${paint.tile}" stroke="#fff" stroke-opacity="0.24"/>` + const rows = new Map<number, Cell[]>() + for (const c of list) { + const row = rows.get(c.y) ?? [] + row.push(c) + rows.set(c.y, row) + } + for (const [y, row] of rows) { + group += `<text x="${row.map(c => c.x * CELL + CELL / 2).join(' ')}" y="${y * CELL + 11}" fill="${paint.glyph}">${row.map(c => glyphAt(c.x, y)).join('')}</text>` + } + out += paint.opacity === 1 ? group : `<g opacity="${paint.opacity}">${group}</g>` + } + return out +} + +/** One flat silhouette of the cells, grown by `grow` cells when a shadow should be broad. */ +function silhouette(cells: Cell[], grow: number, fill: string, opacity: number): string { + const seen = new Set<string>() + for (const c of cells) { + for (let dy = -grow; dy <= grow; dy += 1) { + for (let dx = -grow; dx <= grow; dx += 1) { + if (Math.abs(dx) + Math.abs(dy) <= grow) seen.add(`${(c.x + dx) * CELL} ${(c.y + dy) * CELL}`) + } + } + } + const d = [...seen].map(key => `M${key}h${CELL}v${CELL}h-${CELL}z`).join('') + return `<path d="${d}" fill="${fill}" opacity="${opacity}"/>` +} + +/** What lies under an animal: its shadow, `offset` cells right and down, and a dark underside for the body. */ +function under(cells: Cell[], shadowOpacity: number, offset: number): string { + const body = cells.filter(c => c.body === true) + return `<g transform="translate(${CELL * offset} ${CELL * offset})">${silhouette(cells, 0, '#0a6aa6', shadowOpacity)}</g><g transform="translate(0 2)">${silhouette(body, 0, '#7a1230', 0.5)}</g>` +} + +/** The stroke: how far the front flippers are swept back in each pose, and whether the shell has surged a cell forward. */ +const STROKE: readonly (readonly [number, number])[] = [ + [-45, 0], + [20, 1], + [85, 1], + [20, 0], +] + +/** The turtle: four stroke poses taking turns, the tips moving two cells at most from one to the next. */ +function turtle(across: string, along: string, heading: Heading, size: number, beat: number): string { + const poses = STROKE.map( + ([sweep, surge], index) => `<g class="pose" style="animation-duration:${beat}s;animation-delay:-${(beat * (4 - index)) / 4}s">${under(turtleCells(heading, size, sweep, surge), 0.38, 3)}${mosaic(turtleCells(heading, size, sweep, surge))}</g>`, + ) + return `<g class="${across}"><g class="${along}">${poses.join('')}</g></g>` +} + +/** Each patch of deeper water: column, row, width and height in cells. All of them lie right of the reading column. */ +const PATCHES: readonly (readonly [number, number, number, number])[] = [ + [84, 8, 20, 9], + [82, 22, 26, 12], + [86, 44, 22, 14], + [80, 56, 28, 9], + [92, 32, 16, 9], +] + +/** Large, faint stepped patches of deeper water: the only tile-shaped edges the water has, and none of them hard. */ +function patches(): string { + let d = '' + for (const [column, row, width, height] of PATCHES) { + for (let y = 0; y < height; y += 1) { + const inset = Math.round(Math.abs(y - height / 2) * 0.9 + (hash(column + y, row) - 0.5) * 3) + const run = Math.max(2, width - inset * 2) * CELL + d += `M${(column + inset) * CELL} ${(row + y) * CELL}h${run}v${CELL}h-${run}z` + } + } + return `<path d="${d}" fill="#0f7fb8" opacity="0.075"/>` +} + +/** A few sand tiles that dim and return, so the land is not frozen: a pale veil over about one tile in eighteen. */ +function twinkle(cells: Cell[]): string { + let out = '' + for (const c of cells) { + const pick = hash(c.x + 61, c.y + 13) + if (pick > 0.055) continue + out += `<rect class="dim" style="animation-duration:${9 + Math.floor(pick * 90)}s;animation-delay:-${Math.floor(hash(c.x, c.y + 5) * 12)}s" x="${c.x * CELL + 1}" y="${c.y * CELL + 1}" width="${CELL - 2}" height="${CELL - 2}" fill="#8fdbe6"/>` + } + return out +} + +function sparkle(x: number, y: number, size: number, delay: number, seconds: number): string { + return `<circle class="star" style="animation-delay:-${delay}s;animation-duration:${seconds}s" cx="${x}" cy="${y}" r="${size}" fill="#fff"/>` +} + +function glints(id: string, cx: number, cy: number, rx: number, ry: number, seconds: number, delay: number): string { + return `<g class="glints" style="animation-duration:${seconds + 9}s;animation-delay:-${delay}s"><ellipse cx="${cx}" cy="${cy}" rx="${rx}" ry="${ry}" fill="url(#dots)" mask="url(#${id})"/></g>` +} + +export function honuLagoonSvg(): string { + // Each animal's home and its one visible pose stand in the PLAIN style (the first keyframe's place): the app can stop a scene by + // taking every animation away, and what only keyframes place would fall to the top left corner, or not show at all. + const style = ` +text{font:800 ${CELL - 4}px ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;text-anchor:middle} +.pose{opacity:0;animation:turn 22s linear infinite} +.star{animation:twinkle 9s ease-in-out infinite} +.dim{opacity:0;animation:dim 11s ease-in-out infinite alternate} +.glints{animation:breathe 20s ease-in-out infinite alternate} +.field{animation:drift 52s ease-in-out infinite alternate} +.honuX{animation:honuX 170s infinite}.honuY{animation:honuY 170s infinite} +.coralY{animation:coralY 90s infinite} +@keyframes turn{0%{opacity:0}1.8%{opacity:1}25%{opacity:1}26.8%{opacity:0}100%{opacity:0}} +@keyframes twinkle{0%,100%{opacity:0}50%{opacity:.8}} +@keyframes breathe{from{opacity:.3}to{opacity:1}} +@keyframes dim{from{opacity:0}to{opacity:.3}} +@keyframes drift{from{transform:translate(-40px,-12px)}to{transform:translate(40px,12px)}} +@keyframes honuX{0%{transform:translateX(${91 * CELL}px);animation-timing-function:ease-in-out}45%{transform:translateX(${95 * CELL}px);animation-timing-function:ease-in-out}100%{transform:translateX(${91 * CELL}px)}} +@keyframes honuY{0%{transform:translateY(${32 * CELL}px);animation-timing-function:ease-in-out}45%{transform:translateY(${44 * CELL}px);animation-timing-function:ease-in-out}100%{transform:translateY(${32 * CELL}px)}} +@keyframes coralY{0%{transform:translate(${10 * CELL}px,${30 * CELL}px);animation-timing-function:ease-in-out}50%{transform:translate(${24 * CELL}px,${30 * CELL}px);animation-timing-function:ease-in-out}100%{transform:translate(${10 * CELL}px,${30 * CELL}px)}} +.honuX{transform:translateX(${91 * CELL}px)}.honuY{transform:translateY(${32 * CELL}px)}.coralY{transform:translate(${10 * CELL}px,${30 * CELL}px)}.pose:first-child{opacity:1} +@media (prefers-reduced-motion: reduce){*{animation:none!important}}` + + const defs = ` +<linearGradient id="water" x1="0" y1="0" x2="1" y2="0.03"><stop offset="0" stop-color="#5cc7d6"/><stop offset="0.05" stop-color="#6bcedb"/><stop offset="0.1" stop-color="#79d4e0"/><stop offset="0.16" stop-color="#86d9e4"/><stop offset="0.24" stop-color="#93dde8"/><stop offset="0.36" stop-color="#9fe0ea"/><stop offset="0.54" stop-color="#84d6e5"/><stop offset="0.7" stop-color="#4fbbdc"/><stop offset="0.86" stop-color="#22a0cf"/><stop offset="1" stop-color="#1493c9"/></linearGradient> +<radialGradient id="glow" cx="0.5" cy="0.5" r="0.5"><stop offset="0" stop-color="#d2f8fa" stop-opacity="0.28"/><stop offset="0.35" stop-color="#d2f8fa" stop-opacity="0.18"/><stop offset="0.7" stop-color="#d2f8fa" stop-opacity="0.06"/><stop offset="1" stop-color="#d2f8fa" stop-opacity="0"/></radialGradient> +<radialGradient id="sun" cx="0.5" cy="0.5" r="0.5"><stop offset="0" stop-color="#ffe9a0" stop-opacity="0.8"/><stop offset="0.2" stop-color="#ffe9a0" stop-opacity="0.58"/><stop offset="0.4" stop-color="#ffe9a0" stop-opacity="0.36"/><stop offset="0.6" stop-color="#ffe9a0" stop-opacity="0.18"/><stop offset="0.8" stop-color="#ffe9a0" stop-opacity="0.06"/><stop offset="1" stop-color="#ffe9a0" stop-opacity="0"/></radialGradient> +<radialGradient id="soft" cx="0.5" cy="0.5" r="0.5"><stop offset="0" stop-color="#fff"/><stop offset="0.3" stop-color="#fff" stop-opacity="0.7"/><stop offset="0.65" stop-color="#fff" stop-opacity="0.22"/><stop offset="1" stop-color="#fff" stop-opacity="0"/></radialGradient> +<pattern id="dots" width="${CELL}" height="${CELL}" patternUnits="userSpaceOnUse"><rect x="5" y="6.5" width="5" height="2" rx="1" fill="#eaffff" fill-opacity="0.75"/></pattern> +<pattern id="grid" width="${CELL}" height="${CELL}" patternUnits="userSpaceOnUse"><path d="M0 0.5h${CELL}M0.5 0v${CELL}" stroke="#dff7ff" stroke-opacity="0.08" fill="none"/></pattern> +<linearGradient id="east" x1="0" y1="0" x2="1" y2="0"><stop offset="0.64" stop-color="#fff" stop-opacity="0"/><stop offset="0.82" stop-color="#fff" stop-opacity="1"/></linearGradient> +<mask id="eastward" maskUnits="userSpaceOnUse" x="0" y="0" width="1600" height="1000"><rect width="1600" height="1000" fill="url(#east)"/></mask> +${['m1', 'm2', 'm3', 'm4'].map(id => `<mask id="${id}" maskContentUnits="objectBoundingBox"><rect width="1" height="1" fill="url(#soft)"/></mask>`).join('')}` + + const south: Heading = [Math.sin(0.26), Math.cos(0.26)] + + return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1600 1000" width="100%" height="100%" preserveAspectRatio="xMidYMid slice" font-family="monospace" color="#888"><style>${style}</style><defs>${defs}</defs> +<rect width="1600" height="1000" fill="url(#water)"/> +<ellipse cx="576" cy="400" rx="448" ry="420" fill="url(#glow)"/> +${patches()} +<ellipse cx="1600" cy="0" rx="560" ry="460" fill="url(#sun)"/> +<rect width="1600" height="1000" fill="url(#grid)" mask="url(#eastward)"/> +<g class="field">${glints('m1', 1400, 330, 170, 110, 9, 0)}${glints('m2', 180, 150, 170, 80, 11, 3)}${glints('m3', 1330, 800, 200, 130, 10, 5)}${glints('m4', 230, 800, 200, 90, 13, 2)}</g> +${mosaic(islandCells())}${mosaic(shoalCells())}${twinkle(islandCells())}${twinkle(shoalCells())} +<g class="coralY">${under(coralCells(), 0.2, 2)}${mosaic(coralCells())}</g> +${turtle('honuX', 'honuY', south, 1.1, 22)} +${sparkle(1470, 840, 2.4, 2.2, 8)}${sparkle(240, 470, 2, 3.6, 9)}${sparkle(1560, 520, 2, 6.1, 11)}${sparkle(1290, 300, 1.8, 0.7, 7)}${sparkle(1140, 900, 2, 4.9, 10)}${sparkle(110, 150, 1.8, 7.5, 9)}${sparkle(330, 880, 2.2, 1.9, 8)}${sparkle(1330, 960, 1.8, 5.5, 11)}${sparkle(60, 640, 2, 8.3, 7)} +</svg>` +} + diff --git a/plugins/theme-examples/hooks/scenes/koi-mosaic.ts b/plugins/theme-examples/hooks/scenes/koi-mosaic.ts new file mode 100644 index 00000000..85f7a30a --- /dev/null +++ b/plugins/theme-examples/hooks/scenes/koi-mosaic.ts @@ -0,0 +1,483 @@ +// Koi Mosaic: a koi pond seen from above. The koi are tile mosaics that swim a whole cell per step down one side of the pond and up the other; +// their stepped shadows lie down and right of them on the floor. Same family: square tiles on a cell grid, a quiet glyph in each tile. +// Pure string building: no DOM, nothing read from outside this file. + +const CELL = 20 +const COLUMNS = 80 +const ROWS = 50 + +type Cell = { x: number; y: number; kind: string } +type Tile = { across: number; kind: string } +type Step = { x: number; y: number } +type Paint = { tile: string; glyph: string; glyphOpacity: number; glyphs: string } +type Seed = { x: number; y: number; tone: string } +type Point = readonly [number, number] + +/** A deterministic 0..1 value for a cell, so every build is the same. */ +function hashOf(x: number, y: number, salt: number): number { + let h = Math.imul(x + 11, 374761393) ^ Math.imul(y + 7, 668265263) ^ Math.imul(salt + 3, 1274126177) + h = Math.imul(h ^ (h >>> 13), 1274126177) + h = h ^ (h >>> 16) + return (h >>> 0) / 4294967296 +} + +function tileAt(x: number, y: number): string { + return `M${x * CELL + 1} ${y * CELL + 1}h18v18h-18z` +} + +/** Whole cells in one path, each row's neighbours joined into one rectangle to keep the string short. */ +function blocksOf(keys: Iterable<string>, size: number): string { + const rows = new Map<number, number[]>() + for (const key of keys) { + const parts = key.split(',').map(Number) + const x = parts[0] ?? 0 + const y = parts[1] ?? 0 + const list = rows.get(y) ?? [] + list.push(x) + rows.set(y, list) + } + let d = '' + for (const [y, list] of rows) { + list.sort((a, b) => a - b) + let from = list[0] ?? 0 + for (let i = 1; i <= list.length; i += 1) { + const previous = list[i - 1] ?? 0 + const current = list[i] + if (current === previous + 1) continue + const width = (previous - from + 1) * size + d += `M${from * size} ${y * size}h${width}v${size}h-${width}z` + from = current ?? 0 + } + } + return d +} + +/** Tile kinds: what a cell letter paints. */ +const KINDS: Record<string, Paint> = { + // lily pad greens: main, vein, rim + a: { tile: '#2f8552', glyph: '#8fd09f', glyphOpacity: 0.5, glyphs: 'o:o;' }, + b: { tile: '#57b56f', glyph: '#1f6b45', glyphOpacity: 0.3, glyphs: ':;o' }, + c: { tile: '#267a50', glyph: '#8fd09f', glyphOpacity: 0.25, glyphs: ':;' }, + // bloom: petals and heart + p: { tile: '#edb4cc', glyph: '#ffffff', glyphOpacity: 0.7, glyphs: 'o' }, + q: { tile: '#eec25a', glyph: '#d9a93a', glyphOpacity: 0.8, glyphs: '*' }, + // pond-edge stones: warm grey-beige, the scene's one warm neutral + s: { tile: '#c9bf9a', glyph: '#6f8378', glyphOpacity: 0, glyphs: ':.;.' }, + t: { tile: '#8ea398', glyph: '#64796e', glyphOpacity: 0.4, glyphs: '.:;' }, + u: { tile: '#d9cfa8', glyph: '#7d9085', glyphOpacity: 0, glyphs: '.;:.' }, + v: { tile: '#7d968c', glyph: '#b9c8bd', glyphOpacity: 0.35, glyphs: ':.' }, +} + +/** Koi tile colours by map letter, three shades each so the fish looks made of tesserae; they become CSS classes so each slice stays short. */ +const KOI_FILLS: Record<string, readonly string[]> = { + O: ['#ec7c3c', '#e06c2e', '#d55f25'], + W: ['#f5f1e6', '#ece7d9', '#f8f5ec'], + C: ['#d14a3a', '#c03d2e', '#d85544'], + K: ['#48545b', '#3b464c', '#55626b'], + E: ['#26343c', '#26343c', '#26343c'], + f: ['#f5f1e6', '#ece7d9', '#f8f5ec'], + t: ['#f5f1e6', '#ece7d9', '#f8f5ec'], + T: ['#f5f1e6', '#ece7d9', '#f8f5ec'], +} +const KOI_OPACITY: Record<string, number> = { f: 0.85, t: 0.74, T: 0.95 } + +/** Which tiles carry which glyph class: light glyphs on the coloured tiles, quiet ones on the cream tiles. */ +const GLYPH_CLASSES: ReadonlyArray<{ className: string; kinds: string }> = [ + { className: 'kg', kinds: 'OCK' }, + { className: 'kw', kinds: 'WT' }, +] + +/** One koi heading left: a column of the map is one slice across the body. */ +const KOHAKU_BODY = ` +....ff.............. +...fff.............. +..WOOO.............. +.EOOOOOWWW.......... +WOOOOOOWWWOOOWW..... +WWOOOOOWWOOOOOW..... +WOOOOOWWWWOOOWW..... +.EWOOOOWWW.......... +..WWWO.............. +...fff.............. +....ff.............. +` +const TANCHO_BODY = ` +....ff.............. +...fff.............. +..WWWW.............. +.EWWWWKKWW.......... +WWCWWWKKKWWWWWW..... +WCCCWWWKWWWKKWW..... +WWCWWWWWWWKKWWW..... +.EWWWWWWWW.......... +..WWWW.............. +...fff.............. +....ff.............. +` +/** The tail fan, swept to either side: T is solid, t its translucent edge. */ +const TAIL_UP = ` +.................... +..................Tt +................TTTt +................TTT. +...............TTTT. +...............TTTTt +...............TTT.. +.................... +.................... +.................... +.................... +` +const TAIL_DOWN = ` +.................... +.................... +.................... +.................... +...............TTT.. +...............TTTTt +...............TTTT. +................TTT. +................TTTt +..................Tt +.................... +` + +/** The koi's two lanes: down the right side, then up the left. Each ends well outside the canvas, so the jump between them is never seen. */ +const RIGHT_LANE: readonly Point[] = [[70, -6], [69, 14], [69, 30], [64, 56]] +const LEFT_LANE: readonly Point[] = [[9, 56], [11, 36], [10, 18], [12, -6]] + +/** A wake beside each lane: the step it sits at, and how far to the side. */ +const WAKES: readonly Point[] = [[40, 5], [82, -4]] + +/** The four rings' fades, in percent of the period and opacity. Never more than two rings show at once. */ +const RING_TRACKS: ReadonlyArray<readonly Point[]> = [ + [[0, 0], [2, 0.16], [6, 0.12], [12, 0.06], [18, 0]], + [[0, 0], [9, 0.15], [15, 0.11], [21, 0.06], [27, 0]], + [[0, 0], [18, 0.13], [24, 0.09], [30, 0.05], [36, 0]], + [[0, 0], [27, 0.11], [33, 0.08], [39, 0.04], [45, 0]], +] + +function linesOf(map: string): string[] { + return map.split('\n').filter(line => line.length > 0) +} + +/** Slices of a koi map: for each column, the tiles across the body, counted from the spine. */ +function slicesOf(map: string): Tile[][] { + const lines = linesOf(map) + const spine = (lines.length - 1) / 2 + const slices: Tile[][] = [] + const length = (lines[0] ?? '').length + for (let k = 0; k < length; k += 1) { + const tiles: Tile[] = [] + for (let row = 0; row < lines.length; row += 1) { + const kind = (lines[row] ?? '')[k] + if (kind !== undefined && kind !== '.') tiles.push({ across: row - spine, kind }) + } + slices.push(tiles) + } + return slices +} + +/** One lane of the swim, a row per step: a slow line through the given points plus a weave of two cells, so the body, which follows the head cell by cell, is always in an S. */ +function walkLane(points: readonly Point[]): Step[] { + const steps: Step[] = [] + for (let i = 0; i + 1 < points.length; i += 1) { + const from = points[i] + const to = points[i + 1] + if (from === undefined || to === undefined) continue + const count = Math.abs(to[1] - from[1]) + for (let n = 0; n < count; n += 1) { + const y = from[1] + Math.sign(to[1] - from[1]) * n + const weave = 1.9 * Math.sin(((y - 8) * 2 * Math.PI) / 21) + steps.push({ x: Math.round(from[0] + ((to[0] - from[0]) * n) / count + weave), y }) + } + } + return steps +} + +function placeAt(steps: readonly Step[], index: number): Step { + const i = ((index % steps.length) + steps.length) % steps.length + const step = steps[i] ?? { x: 0, y: 0 } + return { x: step.x * CELL + 10, y: step.y * CELL + 10 } +} + +/** The head's place, one keyframe per step, gliding in a line from each to the next. Where the next place is more than a cell away (the jump from one lane's end to the other's start, off the canvas) the keyframe holds and then jumps, so nothing is seen flying across. */ +function swimKeyframes(name: string, steps: readonly Step[]): string { + let out = `@keyframes ${name}{` + for (let i = 0; i <= steps.length; i += 1) { + const place = placeAt(steps, i) + const next = placeAt(steps, i + 1) + const jumps = i < steps.length && Math.abs(next.x - place.x) + Math.abs(next.y - place.y) > 2 * CELL + const percent = i === steps.length ? '100' : ((i * 100) / steps.length).toFixed(3).replace(/\.?0+$/, '') + out += `${percent}%{transform:translate(${place.x}px,${place.y}px)${jumps ? ';animation-timing-function:step-end' : ''}}` + } + return `${out}}` +} + +/** The tiles of one slice, laid across x: one path per shade, then one row of glyphs per glyph class. */ +function sliceTiles(tiles: readonly Tile[], sliceIndex: number): string { + const byShade = new Map<string, string>() + for (const tile of tiles) { + const shade = tile.kind + Math.floor(hashOf(sliceIndex, tile.across + 9, 61) * 3) + byShade.set(shade, (byShade.get(shade) ?? '') + `M${tile.across * CELL - 9} -9h18v18h-18z`) + } + let out = '' + for (const [shade, d] of byShade) out += `<path class="k${shade}" d="${d}"/>` + for (const glyphClass of GLYPH_CLASSES) { + const marked = tiles.filter(tile => glyphClass.kinds.includes(tile.kind)) + if (marked.length === 0) continue + const glyphs = marked.map(tile => 'S%t:$;tS'[Math.floor(hashOf(sliceIndex, tile.across + 9, 62) * 8)] ?? '').join('') + out += `<text class="${glyphClass.className}" x="${marked.map(tile => tile.across * CELL).join(' ')}" y="4.5">${glyphs}</text>` + } + return out +} + +/** The same slice in plain blocks, for the shadow on the floor. */ +function sliceShadow(tiles: readonly Tile[]): string { + const list = tiles.map(tile => tile.across).sort((a, b) => a - b) + let out = '' + let from = list[0] ?? 0 + for (let i = 1; i <= list.length; i += 1) { + const previous = list[i - 1] ?? 0 + const current = list[i] + if (current === previous + 1) continue + out += `M${from * CELL - 10} -10h${(previous - from + 1) * CELL}v20h-${(previous - from + 1) * CELL}z` + from = current ?? 0 + } + return `<path d="${out}"/>` +} + +function paintSlice(tiles: readonly Tile[], sliceIndex: number, shadow: boolean): string { + if (tiles.length === 0) return '' + return shadow ? sliceShadow(tiles) : sliceTiles(tiles, sliceIndex) +} + +/** A koi is a train of slices that all follow the head's keyframes, each one step later: the body bends along its path. */ +function koi(bodyMap: string, steps: readonly Step[], seconds: number, startStep: number, shadow: boolean): string { + const body = slicesOf(bodyMap) + const tailUp = slicesOf(TAIL_UP) + const tailDown = slicesOf(TAIL_DOWN) + const stepSeconds = seconds / steps.length + let out = '' + for (let k = body.length - 1; k >= 0; k -= 1) { + const place = placeAt(steps, startStep - k) + const up = tailUp[k] ?? [] + const down = tailDown[k] ?? [] + let inner = paintSlice(body[k] ?? [], k, shadow) + if (up.length > 0 || down.length > 0) { + inner += `<g class="poseA">${paintSlice(up, k, shadow)}</g><g class="poseB">${paintSlice(down, k, shadow)}</g>` + } + out += `<g class="swim" transform="translate(${place.x} ${place.y})" style="animation-delay:-${((startStep - k) * stepSeconds).toFixed(2)}s">${inner}</g>` + } + return out +} + +/** Both koi in one layer: the fish themselves, or (for a shade layer) their plain shadows. */ +function fishLayer(steps: readonly Step[], seconds: number, kohakuStart: number, tanchoStart: number, className: string, attributes: string): string { + const shadow = className !== 'fish' + return `<g class="${className}"${attributes}>${koi(KOHAKU_BODY, steps, seconds, kohakuStart, shadow)}${koi(TANCHO_BODY, steps, seconds, tanchoStart, shadow)}</g>` +} + +/** Tiles of one kind in a single path; glyphs in one text per row with a per-glyph x list. */ +function mosaic(cells: readonly Cell[]): string { + const byKind = new Map<string, Cell[]>() + for (const cell of cells) { + const list = byKind.get(cell.kind) ?? [] + list.push(cell) + byKind.set(cell.kind, list) + } + let out = '' + for (const [kind, list] of byKind) { + const paint = KINDS[kind] + if (paint === undefined) continue + out += `<path d="${list.map(c => tileAt(c.x, c.y)).join('')}" fill="${paint.tile}" stroke="#fff" stroke-opacity="0.22"/>` + const rows = new Map<number, Cell[]>() + for (const c of list) { + const row = rows.get(c.y) ?? [] + row.push(c) + rows.set(c.y, row) + } + for (const [y, row] of rows) { + const xs = row.map(c => c.x * CELL + 10).join(' ') + const text = row.map(c => paint.glyphs[Math.floor(hashOf(c.x, c.y, 5) * paint.glyphs.length)] ?? '').join('') + out += `<text x="${xs}" y="${y * CELL + 14.5}" fill="${paint.glyph}" opacity="${paint.glyphOpacity}">${text}</text>` + } + } + return out +} + +/** Darker water around a thing: its footprint grown by `reach` cells, moved by (shiftX, shiftY) cells, on the grid so the edge steps. */ +function halo(cells: readonly Cell[], reach: number, shiftX: number, shiftY: number, opacity: number): string { + const seen = new Set<string>() + for (const c of cells) { + for (let dx = -reach; dx <= reach; dx += 1) { + for (let dy = -reach; dy <= reach; dy += 1) { + if (Math.abs(dx) + Math.abs(dy) > reach + (reach > 1 ? 1 : 0)) continue + seen.add(`${c.x + dx + shiftX},${c.y + dy + shiftY}`) + } + } + } + return `<path d="${blocksOf(seen, CELL)}" fill="#0d5a66" opacity="${opacity}"/>` +} + +/** A lily pad: a round cluster of green tiles with one notch cut to the middle, darker at the rim, a ring of light veins on the larger ones. */ +function lilyPad(centerX: number, centerY: number, radius: number, notchDegrees: number, bloom: Point | null): Cell[] { + const cells: Cell[] = [] + const notch = (notchDegrees * Math.PI) / 180 + const reach = Math.ceil(radius) + for (let dy = -reach; dy <= reach; dy += 1) { + for (let dx = -reach; dx <= reach; dx += 1) { + const distance = Math.hypot(dx, dy) + if (distance > radius) continue + let off = Math.atan2(dy, dx) - notch + while (off > Math.PI) off -= 2 * Math.PI + while (off < -Math.PI) off += 2 * Math.PI + if (distance > 0.6 && Math.abs(off) < 0.24 + 0.28 / Math.max(distance, 1)) continue + const x = centerX + dx + const y = centerY + dy + let kind = 'a' + if (distance > radius - 0.85) kind = 'c' + else if (radius > 3 && Math.abs(distance - radius * 0.5) < 0.5) kind = 'b' + cells.push({ x, y, kind }) + } + } + if (bloom !== null) { + for (const c of cells) { + const dx = c.x - (centerX + bloom[0]) + const dy = c.y - (centerY + bloom[1]) + if (dx === 0 && dy === 0) c.kind = 'q' + else if (Math.abs(dx) <= 1 && Math.abs(dy) <= 1) c.kind = 'p' + } + } + return cells +} + +/** The pond's stone rim in the bottom right corner: a quarter ring of cobbles two to three tiles thick, each cobble one tone, a little moss. */ +function stoneBank(): Cell[] { + const seeds: Seed[] = [] + for (let n = 0; n < 40; n += 1) seeds.push({ x: 62 + hashOf(n, 1, 31) * 20, y: 34 + hashOf(n, 2, 32) * 18, tone: 'su'[Math.floor(hashOf(n, 3, 33) * 2)] ?? 's' }) + const cells: Cell[] = [] + for (let y = 30; y < ROWS; y += 1) { + for (let x = 60; x < COLUMNS; x += 1) { + // a coarse wobble, so the rim's edges bulge instead of running true + const fromCorner = Math.hypot((x + 0.5 - 80) / 1.3, y + 0.5 - 50) + (hashOf(Math.floor(x / 2), Math.floor(y / 2), 34) - 0.5) * 0.9 + if (fromCorner < 4.4 || fromCorner > 6.9) continue + let tone = 's' + let bestDistance = Infinity + for (const seed of seeds) { + const d = Math.hypot(seed.x - x, seed.y - y) + if (d < bestDistance) { + bestDistance = d + tone = seed.tone + } + } + cells.push({ x, y, kind: hashOf(x, y, 35) < 0.06 ? 'c' : tone }) + } + } + return cells +} + +/** Deeper water in terraces growing out of a corner; the edge of each is a one-tile checker, so it looks like tesserae and not like banding. */ +function stairZone(cornerX: number, cornerY: number, radius: number, squash: number, opacity: number, fill: string): string { + const seen = new Set<string>() + for (let y = 0; y < ROWS; y += 1) { + for (let x = 0; x < COLUMNS; x += 1) { + const distance = Math.hypot(x + 0.5 - cornerX, (y + 0.5 - cornerY) * squash) + const coarse = Math.sin(x * 0.45 + cornerY) * 1.2 + Math.sin(y * 0.6 + cornerX) * 1.2 + const dither = (x + y) % 2 === 0 ? 1.1 : -1.1 + if (distance < radius + coarse + dither) seen.add(`${x},${y}`) + } + } + return `<path d="${blocksOf(seen, CELL)}" fill="${fill}" opacity="${opacity}"/>` +} + +/** A ring ripple on the grid: the whole cells a circle of this radius passes through, to be lightened a little. */ +function ringOutline(centerX: number, centerY: number, radius: number): string { + const seen = new Set<string>() + const reach = Math.ceil(radius) + 1 + for (let dy = -reach; dy <= reach; dy += 1) { + for (let dx = -reach; dx <= reach; dx += 1) { + if (Math.abs(Math.hypot(dx, dy) - radius) < 0.62) seen.add(`${centerX + dx},${centerY + dy}`) + } + } + return blocksOf(seen, CELL) +} + +/** Four rings that show one after another, each fainter, then nothing for the rest of the period. */ +function ripple(centerX: number, centerY: number, seconds: number, delaySeconds: number, family: string): string { + return [1.8, 3.6, 5.3, 7].map((radius, i) => `<path class="ring ${family}${i}" style="animation-duration:${seconds}s;animation-delay:-${delaySeconds.toFixed(2)}s" d="${ringOutline(centerX, centerY, radius)}"/>`).join('') +} + +/** The rings' fade, squeezed into the first `fraction` of the period: a long period can then hold one short ripple. */ +function ringKeyframes(family: string, fraction: number): string { + return RING_TRACKS.map((track, i) => `@keyframes ${family}${i}{${track.map(([percent, opacity]) => `${(percent * fraction).toFixed(2).replace(/\.?0+$/, '')}%{opacity:${opacity}}`).join('')}100%{opacity:0}}.${family}${i}{animation-name:${family}${i}}`).join('') +} + +/** A wake beside a lane: the ring set's period starts when the head of the koi that started at `startStep` reaches `wakeStep`. */ +function wakeRipple(steps: readonly Step[], seconds: number, wakeStep: number, startStep: number, shiftX: number): string { + const stepSeconds = seconds / steps.length + const delay = ((((startStep - wakeStep) % steps.length) + steps.length) % steps.length) * stepSeconds + const at = steps[wakeStep] ?? { x: 0, y: 0 } + return ripple(at.x + shiftX, at.y, seconds, delay, 'turn') +} + +function floatingPad(cells: readonly Cell[], className: string, seconds: number, delay: number): string { + return `<g class="${className}" style="animation-duration:${seconds}s;animation-delay:-${delay}s">${halo(cells, 0, 1, 1, 0.3)}${mosaic(cells)}</g>` +} + +export function koiMosaicSvg(): string { + // The pond is larger than the window: a koi swims down the right side, leaves by the bottom edge, and comes back up the left side. + const steps = [...walkLane(RIGHT_LANE), ...walkLane(LEFT_LANE)] + const seconds = Math.round(steps.length * 2.2) + const kohakuStart = 34 + const tanchoStart = 34 + 49 + + const bigPad = lilyPad(73, 20, 3.6, 150, [0, -1]) + const smallPad = lilyPad(75, 37, 2.6, 300, null) + const leftPad = lilyPad(7, 30, 3.6, 60, null) + const stones = stoneBank() + + const style = ` +text{font:700 12px ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;text-anchor:middle} +${Object.entries(KOI_FILLS).map(([kind, fills]) => fills.map((fill, i) => `.k${kind}${i}{fill:${fill}${KOI_OPACITY[kind] === undefined ? '' : `;opacity:${KOI_OPACITY[kind]}`}}`).join('')).join('')} +.fish path{stroke:#0d5a66;stroke-opacity:.3}.kg{fill:#fff1dc;opacity:.5}.kw{fill:#b7c3bd;opacity:.8} +.swim{animation:swim ${seconds}s linear infinite} +.poseA{animation:flipA 3.2s linear infinite}.poseB{animation:flipB 3.2s linear infinite} +.rockX{animation:rockX 37s ease-in-out infinite}.rockY{animation:rockY 41s ease-in-out infinite} +.glint{opacity:.02;animation:glint 13s ease-in-out infinite} +.swell{animation:swell 52s ease-in-out infinite alternate}.swell.b{animation-duration:67s;animation-direction:alternate-reverse} +.band{animation:sweep 71s linear infinite}.band.b{animation-duration:97s;animation-delay:-40s} +.ring{fill:#f2fffb;opacity:0;animation-timing-function:linear;animation-iteration-count:infinite} +${ringKeyframes('slow', 1)}${ringKeyframes('turn', 50 / seconds)} +@keyframes flipA{0%,37.5%{opacity:1}50%,87.5%{opacity:0}100%{opacity:1}} +@keyframes flipB{0%,37.5%{opacity:0}50%,87.5%{opacity:1}100%{opacity:0}} +@keyframes rockX{0%{transform:translate(0,0)}30%{transform:translate(20px,0)}55%{transform:translate(20px,20px)}80%{transform:translate(0,20px)}100%{transform:translate(0,0)}} +@keyframes rockY{0%{transform:translate(0,0)}35%{transform:translate(0,20px)}60%{transform:translate(-20px,20px)}85%{transform:translate(-20px,0)}100%{transform:translate(0,0)}} +@keyframes glint{0%,100%{opacity:.02}50%{opacity:.13}} +@keyframes swell{from{transform:translate(-50px,-16px)}to{transform:translate(60px,22px)}} +@keyframes sweep{from{transform:translate(-600px,0)}to{transform:translate(2300px,0)}} +${swimKeyframes('swim', steps)} +@media (prefers-reduced-motion: reduce){*{animation:none!important}.poseB,.ring{opacity:0}}` + + const defs = ` +<linearGradient id="water" x1="0" y1="0" x2="1" y2="0.62"><stop offset="0" stop-color="#6fc3bb"/><stop offset="0.2" stop-color="#90d5ca"/><stop offset="0.52" stop-color="#93d6cb"/><stop offset="0.74" stop-color="#4fb1b1"/><stop offset="1" stop-color="#17697d"/></linearGradient> +<radialGradient id="shallow" cx="0.5" cy="0.5" r="0.5"><stop offset="0" stop-color="#e6f7ee" stop-opacity="0.6"/><stop offset="1" stop-color="#e6f7ee" stop-opacity="0"/></radialGradient> +<radialGradient id="deep" cx="0.5" cy="0.5" r="0.5"><stop offset="0" stop-color="#17838c" stop-opacity="0.5"/><stop offset="1" stop-color="#17838c" stop-opacity="0"/></radialGradient> +<linearGradient id="beam" x1="0" y1="0" x2="1" y2="0"><stop offset="0" stop-color="#f2fffb" stop-opacity="0"/><stop offset="0.5" stop-color="#f2fffb" stop-opacity="0.08"/><stop offset="1" stop-color="#f2fffb" stop-opacity="0"/></linearGradient> +<pattern id="grid" width="20" height="20" patternUnits="userSpaceOnUse"><path d="M0 0.5h20M0.5 0v20" stroke="#f1fbf5" stroke-opacity="0.16" fill="none"/></pattern> +<linearGradient id="sides" x1="0" y1="0" x2="1" y2="0"><stop offset="0" stop-color="#fff" stop-opacity="1"/><stop offset="0.24" stop-color="#fff" stop-opacity="0.18"/><stop offset="0.76" stop-color="#fff" stop-opacity="0.18"/><stop offset="0.97" stop-color="#fff" stop-opacity="1"/></linearGradient> +<mask id="outward" maskUnits="userSpaceOnUse" x="0" y="0" width="1600" height="1000"><rect width="1600" height="1000" fill="url(#sides)"/></mask>` + + return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1600 1000" width="100%" height="100%" preserveAspectRatio="xMidYMid slice" font-family="monospace" color="#888"><style>${style}</style><defs>${defs}</defs> +<rect width="1600" height="1000" fill="url(#water)"/> +<g class="swell b"><ellipse cx="1440" cy="820" rx="560" ry="460" fill="url(#deep)"/><ellipse cx="40" cy="60" rx="440" ry="360" fill="url(#deep)" opacity="0.7"/></g> +${[28, 24, 20, 16, 12].map(radius => stairZone(86, 56, radius, 1.1, 0.045, '#0f6a73')).join('')}${[27, 23, 19, 15, 11].map(radius => stairZone(-4, -4, radius, 1.3, 0.04, '#0f6a73')).join('')}${stairZone(84, -6, 18, 1.2, 0.05, '#12767f')} +<rect width="1600" height="1000" fill="url(#grid)" mask="url(#outward)"/> +${WAKES.map(([step, shift]) => wakeRipple(steps, seconds, step, kohakuStart, shift) + wakeRipple(steps, seconds, step, tanchoStart, shift)).join('')} +${ripple(73, 29, 29, 4, 'slow')}${ripple(11, 14, 37, 20, 'slow')}${ripple(72, 46, 43, 31, 'slow')}${ripple(11, 43, 31, 9, 'slow')} +${fishLayer(steps, seconds, kohakuStart, tanchoStart, 'shade', ' transform="translate(40 40)" fill="#0d5a66" opacity="0.07"')}${fishLayer(steps, seconds, kohakuStart, tanchoStart, 'shade', ' transform="translate(20 20)" fill="#0d5a66" opacity="0.16"')} +${fishLayer(steps, seconds, kohakuStart, tanchoStart, 'fish', '')} +${halo(stones, 1, 0, 0, 0.22)}${mosaic(stones)} +${floatingPad(bigPad, 'rockX', 37, 5)}${floatingPad(smallPad, 'rockY', 53, 21)}${floatingPad(leftPad, 'rockY', 47, 30)} +</svg>` +} diff --git a/plugins/theme-examples/hooks/scenes/night-reef.ts b/plugins/theme-examples/hooks/scenes/night-reef.ts new file mode 100644 index 00000000..eee3f54b --- /dev/null +++ b/plugins/theme-examples/hooks/scenes/night-reef.ts @@ -0,0 +1,465 @@ +// Night Reef: the Honu Lagoon after dark. The tile mosaics are ANIMALS seen from above (a big turtle and a manta ray) +// that glide along the edges of the window, each over its own halo of light. +// The one idea is bioluminescence: the turtle's shell rim and the ray's edge glow teal, the shell's heart smoulders violet, +// and the plankton they disturb trails behind them in a glowing wake. The water carries a faint grid, and two drifting bands of moonlight at its sides; a low band of reef runs along the bottom right. +// Pure string building: no DOM, nothing brought in from outside, the same output on every call. + +type Cell = { x: number; y: number; kind: string } +type Paint = { tile: string; glyph: string; opacity?: number } +type Heading = 'up' | 'down' | 'left' | 'right' + +const CELL = 20 +const GLYPHS = '$%tSX:;t$%S' +const TEAL = '#4fe6cf' +const TEAL_INK = '#35c4ae' +const VIOLET = '#7a6cff' +const VIOLET_INK = '#9488ff' +// The one warm note, six tiles in all. To take it out, paint kind 'a' like 'q' and drop the tips in reefBand. +const WARM = '#e0a060' +const WARM_INK = '#c98a4c' + +/** Tile kinds: what a map letter paints. Glyphs sit one shade off their tile: texture, never text. */ +const KINDS: Record<string, Paint> = { + h: { tile: '#1d7f80', glyph: '#2a9a98' }, + H: { tile: '#27958f', glyph: '#38b0a6' }, + f: { tile: '#176a70', glyph: '#22838a' }, + s: { tile: '#124a56', glyph: '#1b6270' }, + p: { tile: '#4338b0', glyph: '#5247c4' }, + q: { tile: '#5a4de0', glyph: '#6b5ff0' }, + a: { tile: '#a87645', glyph: '#bd8852' }, + r: { tile: '#3a3099', glyph: '#483eae' }, + k: { tile: '#2c2580', glyph: '#3a3296' }, + t: { tile: '#176a70', glyph: '#22838a' }, + m: { tile: '#1d6672', glyph: '#247482' }, + M: { tile: '#258291', glyph: '#2f96a4' }, + u: { tile: '#176a70', glyph: '#22838a', opacity: 0.7 }, + v: { tile: '#176a70', glyph: '#22838a', opacity: 0.45 }, + w: { tile: '#176a70', glyph: '#22838a', opacity: 0.25 }, + x: { tile: '#16305c', glyph: '#1e3c6c' }, + y: { tile: '#1c4468', glyph: '#255478' }, +} + +/** The big turtle, heading up: a 3 by 3 head on a neck, an octagonal shell nine cells wide with symmetric scutes and two staggered amber spots. No tail: people saw a stem in it. Flippers are separate so they can change pose. */ +const TURTLE_BODY = ` +........hHh........ +........HHH........ +........hHh........ +.........h......... +........sss........ +.......sspss....... +......sspppss...... +.....sspqpapss..... +.....spprkrpps..... +.....spqkqkqps..... +.....spprkrpps..... +.....sspapqpss..... +......sspppss...... +.......sspss....... +........sss........ +` +/** Three poses of the LEFT flippers, all a wide sweep back (about 25, 35 and 45 degrees), never level and never upright. A comma is an empty row. */ +const TURTLE_FLIPPERS = [ + ` +, +, +, +, +, +, +...fff +fffff +ff +, +, +, +.....f +.....ff +`, + ` +, +, +, +, +, +, +....ff +..fff +ffff +ff +, +, +.....f +.....ff +`, + ` +, +, +, +, +, +, +.....f +...ff +..ff +.ff +ff +f +.....f +.....ff +`, +] + +/** The manta ray, heading up: a pointed nose, wings whose tips trail two cells behind the leading edge, a long thin tail that kinks and fades out (t u v w); two poses. */ +const MANTA = [ + ` +......m...... +.....mmm..... +...mmmMmmm... +.mmmmMMMmmmm. +mmmmmMMMmmmmm +mmm.mmMmm.mmm +m....mmm....m +......m...... +......t...... +......t...... +.....u....... +.....u....... +....v........ +....w........ +`, + ` +......m...... +.....mmm..... +..mmmmMmmmm.. +mmmmmMMMmmmmm +mmmmmMMMmmmmm +.mm.mmMmm.mm. +.....mmm..... +......m...... +......t...... +.....t....... +.....u....... +....u........ +....v........ +...w......... +`, +] + +/** A band of reef along the bottom right, three to six cells tall, uneven. */ +const CORAL = ` +....................yy...... +.....yy............yyyy..y.. +....yyyy....y.....yyxyyyyyy. +.y.yyxyy...yyy..yyyxxyyxxyy. +yyyyxxyyy.yyxyy.yxyxxyxxxyyy +yxyxxxxyyyyxxxyyyxxxxxxxxxyx +xxxxxxxxxxxxxxxxxxxxxxxxxxxx +` + +function hash(a: number, b: number): number { + let h = (Math.imul(a | 0, 374761393) + Math.imul(b | 0, 668265263)) >>> 0 + h = Math.imul(h ^ (h >>> 13), 1274126177) >>> 0 + return ((h ^ (h >>> 16)) >>> 0) / 4294967296 +} + +function cellsOf(map: string): Cell[] { + const cells: Cell[] = [] + const lines = map.split('\n').filter(line => line.length > 0).map(line => (line === ',' ? '' : line)) + lines.forEach((line, y) => { + for (let x = 0; x < line.length; x += 1) { + const kind = line[x] ?? '.' + if (kind !== '.') cells.push({ x, y, kind }) + } + }) + return cells +} + +/** Maps are drawn heading up; this turns the CELLS, so the glyphs stay upright whichever way the animal swims. */ +function facing(cells: Cell[], heading: Heading, height: number): Cell[] { + return cells.map(c => { + if (heading === 'down') return { x: c.x, y: height - 1 - c.y, kind: c.kind } + if (heading === 'left') return { x: c.y, y: c.x, kind: c.kind } + if (heading === 'right') return { x: height - 1 - c.y, y: c.x, kind: c.kind } + return c + }) +} + +function glyphAt(x: number, y: number): string { + return GLYPHS[(x * 7 + y * 13 + ((x * y) % 3) + 22) % GLYPHS.length] ?? '' +} + +function tilePath(list: Cell[]): string { + return list.map(c => `M${c.x * CELL + 1} ${c.y * CELL + 1}h18v18h-18z`).join('') +} + +function glyphRows(list: Cell[], fill: string): string { + const rows = new Map<number, Cell[]>() + for (const c of list) { + const row = rows.get(c.y) ?? [] + row.push(c) + rows.set(c.y, row) + } + let out = '' + for (const [y, row] of rows) { + const xs = row.map(c => c.x * CELL + 10).join(' ') + const text = row.map(c => glyphAt(c.x, y)).join('') + out += `<text x="${xs}" y="${y * CELL + 15}" fill="${fill}">${text}</text>` + } + return out +} + +/** Tiles of one kind in a single path; glyphs in one text per row with a per-glyph x list. */ +function mosaic(cells: Cell[]): string { + const byKind = new Map<string, Cell[]>() + for (const cell of cells) { + const list = byKind.get(cell.kind) ?? [] + list.push(cell) + byKind.set(cell.kind, list) + } + let out = '' + for (const [kind, list] of byKind) { + const paint = KINDS[kind] + if (paint === undefined) continue + const faded = paint.opacity === undefined ? '' : ` opacity="${paint.opacity}"` + out += `<g${faded}><path d="${tilePath(list)}" fill="${paint.tile}" stroke="#aab8ff" stroke-opacity="0.06"/>${glyphRows(list, paint.glyph)}</g>` + } + return out +} + +/** Cells on the outside of a shape: where an animal's glow lives. */ +function edgeCells(cells: Cell[]): Cell[] { + const filled = new Set(cells.map(c => `${c.x},${c.y}`)) + return cells.filter(c => !filled.has(`${c.x + 1},${c.y}`) || !filled.has(`${c.x - 1},${c.y}`) || !filled.has(`${c.x},${c.y + 1}`) || !filled.has(`${c.x},${c.y - 1}`)) +} + +/** A set of tiles that glow together: tile, a glyph one shade off it, one slow eased clock. */ +function litGroup(list: Cell[], className: string, colour: string, ink: string, seconds: number, delay: number): string { + if (list.length === 0) return '' + return `<g class="${className}" style="animation-duration:${seconds}s;animation-delay:-${delay.toFixed(1)}s"><path d="${tilePath(list)}" fill="${colour}"/>${glyphRows(list, ink)}</g>` +} + +/** Teal along an edge: groups whose clocks are spread evenly round one cycle, so part is always lit and nothing pops. */ +function tealEdge(cells: Cell[], share: number, seconds: number, seed: number, groupCount: number): string { + const groups: Cell[][] = [] + for (let i = 0; i < groupCount; i += 1) groups.push([]) + for (const c of cells) { + // Neighbours in a 2 by 2 block mostly share a group, so the glow comes in short runs along the edge. + const pick = hash(Math.floor(c.x / 2) + seed, Math.floor(c.y / 2) * 3) * 0.7 + hash(c.x + seed, c.y) * 0.3 + if (pick < share) groups[Math.floor((pick / share) * groupCount)]?.push(c) + } + return groups.map((list, i) => litGroup(list, 'rim', TEAL, TEAL_INK, seconds, (i * seconds) / groupCount)).join('') +} + +/** Violet in the shell's heart: the bright scutes smoulder, centre and ring on two clocks, never out. */ +function violetHeart(cells: Cell[], centreX: number, centreY: number): string { + const scutes = cells.filter(c => c.kind === 'q') + const inner = scutes.filter(c => Math.abs(c.x - centreX) + Math.abs(c.y - centreY) <= 1) + const outer = scutes.filter(c => Math.abs(c.x - centreX) + Math.abs(c.y - centreY) > 1) + const spine = cells.filter(c => c.kind === 'a') + return litGroup(inner, 'ember', VIOLET, VIOLET_INK, 17, 0) + litGroup(outer, 'ember', VIOLET, VIOLET_INK, 23, 9) + litGroup(spine, 'ember', WARM, WARM_INK, 19, 3) +} + +/** The glowing wake: plankton stirred up behind an animal. Drawn for an animal heading up (wake below it), then turned like the cells. + * Three bands, each dimmer and wider than the last, so it fades without a gradient. */ +function wake(widthCells: number, heightCells: number, lengthCells: number, heading: Heading, seed: number): string { + const bands = ['', '', ''] + const centre = (widthCells * CELL) / 2 + const count = lengthCells * 6 + for (let i = 0; i < count; i += 1) { + const along = Math.pow(hash(seed, i), 1.4) + const spread = (0.2 + along * 0.4) * widthCells * CELL + const px = Math.round(centre + (hash(seed + 1, i) - 0.5) * spread) + const py = Math.round(heightCells * CELL - 30 + along * lengthCells * CELL) + const size = hash(seed + 2, i) < 0.3 ? 3 : 2 + const x = heading === 'left' ? py : px + const y = heading === 'down' ? heightCells * CELL - py : heading === 'left' ? px : py + const band = Math.min(2, Math.floor(along * 3)) + bands[band] = (bands[band] ?? '') + `M${x} ${y}h${size}v${size}h-${size}z` + } + const strength = [0.85, 0.55, 0.3] + return bands.map((d, i) => `<path class="speck" style="animation-duration:${7 + i * 2}s;animation-delay:-${i * 2.7}s" d="${d}" fill="${TEAL}" fill-opacity="${strength[i] ?? 0}"/>`).join('') +} + +/** Poses shown one at a time. With three poses the order is 0 1 2 1, so limbs sweep back and forth. */ +function posed(poses: string[], seconds: number): string { + const className = poses.length === 3 ? ['pose3a', 'pose3b', 'pose3c'] : ['pose2a', 'pose2b'] + return poses.map((body, i) => `<g class="${className[i] ?? ''}" style="animation-duration:${seconds}s">${body}</g>`).join('') +} + +/** One stroke phase: the left flippers in one pose, the right in another, so the animal is never a mirror image of itself. */ +function strokePhase(left: number, right: number): Cell[] { + const leftCells = cellsOf(TURTLE_FLIPPERS[left] ?? '') + const rightCells = cellsOf(TURTLE_FLIPPERS[right] ?? '').map(c => ({ x: 18 - c.x, y: c.y, kind: c.kind })) + return leftCells.concat(rightCells) +} + +/** A few dash-ripples close around an animal: the water it has just disturbed. */ +function nearRipples(width: number, height: number, count: number, seed: number): string { + let d = '' + for (let i = 0; i < count; i += 1) { + const x = Math.round((-90 + hash(seed, i) * (width + 180)) / 20) * 20 + 6 + const y = Math.round((-70 + hash(seed + 1, i) * (height + 140)) / 20) * 20 + 9 + d += `M${x} ${y}h8v2h-8z` + } + return `<path class="speck" style="animation-duration:11s" d="${d}" fill="#5fd0c8" fill-opacity="0.4"/>` +} + +/** The turtle facing one way. The two long legs of its lap get everything; the short turns get one pose and no glow, to save characters. */ +function bigTurtle(heading: Heading, full: boolean): string { + const height = 15 + const body = facing(cellsOf(TURTLE_BODY), heading, height) + const strokes = [strokePhase(0, 2), strokePhase(1, 1), strokePhase(2, 0)].map(cells => facing(cells, heading, height)) + if (!full) return `<g transform="translate(40 -40)">${mosaic(strokes[1] ?? [])}${mosaic(body)}</g>` + const shellRim = body.filter(c => c.kind === 's') + return `${wake(19, height, 11, heading, 500)}${posed(strokes.map(mosaic), 7)}${mosaic(body)}${violetHeart(body, 9, 9)}${tealEdge(shellRim, 0.7, 12, 0, 6)}` +} + +/** The turtle's lap: down the right gutter, a short turn, back up, a short turn. Each heading is shown only on its own leg. */ +function turtleLap(): string { + const glow = `<ellipse class="halo" cx="190" cy="160" rx="300" ry="300" fill="url(#tealglow)"/><ellipse class="halo" style="animation-delay:-4s" cx="190" cy="150" rx="170" ry="180" fill="url(#violetglow)"/>` + return `${glow}${nearRipples(380, 300, 16, 801)}<g class="legdown">${bigTurtle('down', true)}</g><g class="legleft">${bigTurtle('left', false)}</g><g class="legup">${bigTurtle('up', true)}</g><g class="legright">${bigTurtle('right', false)}</g>` +} + +/** The ray's body cells, without its tail: only these glow. */ +function isRayBody(cell: Cell): boolean { + return 'mM'.includes(cell.kind) +} + +/** The ray facing one way; like the turtle, the short turns get one pose and no glow. */ +function manta(heading: Heading, full: boolean): string { + const height = 14 + const poses = MANTA.map(map => facing(cellsOf(map), heading, height)) + if (!full) return `<g transform="translate(-10 10)">${mosaic(poses[0] ?? [])}</g>` + // Under the sidebar's blur only mass and outline survive, so nearly the whole edge glows, on two clocks. + const tiles = poses.map(cells => mosaic(cells) + tealEdge(edgeCells(cells).filter(isRayBody), 0.9, 14, 70, 2)) + return `${wake(13, height, 6, heading, 600)}${posed(tiles, 9)}` +} + +/** The ray's lap, low on the far left: up, a short turn, down two cells further in, a short turn. It never leaves, so the frame is never one animal and empty water. */ +function rayLap(): string { + const glow = `<ellipse class="halo" style="animation-delay:-5s" cx="130" cy="110" rx="280" ry="240" fill="url(#tealglow)"/>` + return `${glow}${nearRipples(260, 180, 12, 811)}<g class="legdown">${manta('up', true)}</g><g class="legleft">${manta('right', false)}</g><g class="legup">${manta('down', true)}</g><g class="legright">${manta('left', false)}</g>` +} + +/** The reef band: dark tiles, a few teal anemones pulsing low down, and four single amber tips, never two side by side. */ +function reefBand(column: number, row: number): string { + const cells = cellsOf(CORAL).map(c => ({ x: c.x + column, y: c.y + row, kind: c.kind })) + const filled = new Set(cells.map(c => `${c.x},${c.y}`)) + const anemones = cells.filter(c => c.y > row + 2 && hash(c.x * 3 + 9, c.y * 11) < 0.08) + const tips = cells.filter(c => !filled.has(`${c.x},${c.y - 1}`) && c.x % 6 === 2).slice(0, 4) + return mosaic(cells) + litGroup(anemones, 'rim', TEAL, TEAL_INK, 12, 2) + litGroup(tips, 'ember', WARM, WARM_INK, 19, 5) +} + +/** Plankton: a swarm of small square specks that drifts in one body; three sub-groups twinkle on their own clocks; a few bright ones carry a halo. */ +function swarm(centreX: number, centreY: number, radiusX: number, radiusY: number, count: number, seed: number, driftSeconds: number, driftX: number, driftY: number): string { + const parts = ['', '', ''] + let violet = '' + let halos = '' + let bright = '' + for (let i = 0; i < count; i += 1) { + const angle = hash(seed, i * 2) * Math.PI * 2 + const reach = Math.pow(hash(seed, i * 2 + 1), 0.8) + const x = Math.round(centreX + Math.cos(angle) * radiusX * reach) + const y = Math.round(centreY + Math.sin(angle) * radiusY * reach) + const roll = hash(seed + 7, i) + if (roll < 0.1) { + halos += `<circle cx="${x + 2}" cy="${y + 2}" r="11" fill="url(#speckhalo)"/>` + bright += `M${x} ${y}h4v4h-4z` + } else if (roll < 0.36) { + violet += `M${x} ${y}h3v3h-3z` + } else { + const size = roll < 0.6 ? 3 : roll < 0.85 ? 2 : 1.5 + parts[i % 3] = (parts[i % 3] ?? '') + `M${x} ${y}h${size}v${size}h-${size}z` + } + } + const specks = parts.map((d, i) => `<path class="speck" style="animation-duration:${7 + i * 2}s;animation-delay:-${(hash(seed, 90 + i) * 9).toFixed(1)}s" d="${d}" fill="${TEAL}"/>`).join('') + const soft = `<path class="speck" style="animation-duration:10s;animation-delay:-${(hash(seed, 95) * 9).toFixed(1)}s" d="${violet}" fill="#8b7bff"/>` + const stars = `<g class="speck" style="animation-duration:11s;animation-delay:-${(hash(seed, 99) * 11).toFixed(1)}s">${halos}<path d="${bright}" fill="#b8fff0"/></g>` + return `<g class="drift" style="animation-duration:${driftSeconds}s;animation-delay:-${(hash(seed, 77) * driftSeconds).toFixed(0)}s;--dx:${driftX}px;--dy:${driftY}px">${specks}${soft}${stars}</g>` +} + +/** A thin scatter of the faintest specks through the reading column, so the middle is water and not a hole. */ +function middleScatter(): string { + let d = '' + for (let i = 0; i < 18; i += 1) d += `M${Math.round(470 + hash(51, i) * 700)} ${Math.round(60 + hash(52, i) * 860)}h1.5v1.5h-1.5z` + return `<path class="speck" style="animation-duration:13s" d="${d}" fill="${TEAL}" fill-opacity="0.3"/>` +} + +/** Grain: a tile of barely visible light and dark pixels that dithers the dark gradient so it cannot band. */ +function grainPattern(): string { + let light = '' + let dark = '' + for (let i = 0; i < 150; i += 1) { + const x = Math.floor(hash(11, i) * 48) * 2 + const y = Math.floor(hash(12, i) * 48) * 2 + if (i % 2 === 0) light += `M${x} ${y}h2v2h-2z` + else dark += `M${x} ${y}h2v2h-2z` + } + return `<pattern id="grain" width="96" height="96" patternUnits="userSpaceOnUse"><path d="${light}" fill="#9db4ff" fill-opacity="0.022"/><path d="${dark}" fill="#000" fill-opacity="0.09"/></pattern>` +} + +export function nightReefSvg(): string { + // The animals GLIDE: their laps are plain linear keyframes, no stepping and no held frames (a cell per step read like a stalled screen in the real app). + // The four upright drawings of a lap, and the limb poses, cross-fade over about 0.4 s instead of snapping. + // Delays are chosen so that time zero is a good composition. The still a reduced-motion user sees is set apart from it: + // the resting place of each animal and its one visible pose stand in the PLAIN style: the app can stop a scene by taking every + // animation away, and what only keyframes place would fall to the top of the window. The keyframes name every moment of the run. + const style = ` +text{font:700 13px ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;text-anchor:middle} +.rim{opacity:.5;animation:rim 12s ease-in-out infinite} +.ember{opacity:.7;animation:ember 17s ease-in-out infinite} +.halo{animation:halo 9s ease-in-out infinite} +.speck{opacity:.6;animation:speck 9s ease-in-out infinite} +.drift{animation:drift 55s ease-in-out infinite alternate} +.caustic{animation:caustic 110s ease-in-out infinite alternate} +.turtleway{animation:turtleway 128s linear infinite;animation-delay:-78s} +.legdown{animation:legdown 128s linear infinite;animation-delay:-78s}.legleft{animation:legleft 128s linear infinite;animation-delay:-78s}.legup{animation:legup 128s linear infinite;animation-delay:-78s}.legright{animation:legright 128s linear infinite;animation-delay:-78s} +.rayway{animation:rayway 128s linear infinite;animation-delay:-30s}.raylegs g{animation-delay:-30s} +.pose3a{animation:pose3a 8s linear infinite}.pose3b{animation:pose3b 8s linear infinite}.pose3c{animation:pose3c 8s linear infinite} +.pose2a{animation:pose2a 6s linear infinite}.pose2b{animation:pose2b 6s linear infinite} +@keyframes pose3a{0%{opacity:1}20%{opacity:1}25%{opacity:0}95%{opacity:0}100%{opacity:1}} +@keyframes pose3b{0%{opacity:0}20%{opacity:0}25%{opacity:1}45%{opacity:1}50%{opacity:0}70%{opacity:0}75%{opacity:1}95%{opacity:1}100%{opacity:0}} +@keyframes pose3c{0%{opacity:0}45%{opacity:0}50%{opacity:1}70%{opacity:1}75%{opacity:0}100%{opacity:0}} +@keyframes pose2a{0%{opacity:1}45%{opacity:1}50%{opacity:0}95%{opacity:0}100%{opacity:1}} +@keyframes pose2b{0%{opacity:0}45%{opacity:0}50%{opacity:1}95%{opacity:1}100%{opacity:0}} +@keyframes rim{0%,100%{opacity:.14}50%{opacity:.95}} +@keyframes ember{0%,100%{opacity:.35}50%{opacity:.9}} +@keyframes halo{0%,100%{opacity:.5}50%{opacity:1}} +@keyframes speck{0%,100%{opacity:.28}50%{opacity:1}} +@keyframes drift{from{transform:translate(0,0)}to{transform:translate(var(--dx),var(--dy))}} +@keyframes caustic{from{transform:translate(-90px,0)}to{transform:translate(90px,0)}} +@keyframes turtleway{0%{transform:translate(0,290px)}43.75%{transform:translate(0,570px)}50%{transform:translate(-40px,570px)}93.75%{transform:translate(-40px,290px)}100%{transform:translate(0,290px)}} +@keyframes rayway{0%{transform:translate(0,700px)}43.75%{transform:translate(0,420px)}50%{transform:translate(40px,420px)}93.75%{transform:translate(40px,700px)}100%{transform:translate(0,700px)}} +@keyframes legdown{0%{opacity:1}43.59%{opacity:1}43.91%{opacity:0}99.7%{opacity:0}100%{opacity:1}} +@keyframes legleft{0%{opacity:0}43.59%{opacity:0}43.91%{opacity:1}49.84%{opacity:1}50.16%{opacity:0}100%{opacity:0}} +@keyframes legup{0%{opacity:0}49.84%{opacity:0}50.16%{opacity:1}93.59%{opacity:1}93.91%{opacity:0}100%{opacity:0}} +@keyframes legright{0%{opacity:0}93.59%{opacity:0}93.91%{opacity:1}99.7%{opacity:1}100%{opacity:0}} +.pose3a,.pose3c,.pose2b,.legleft,.legdown,.legright{opacity:0}.turtleway{transform:translate(-40px,440px)}.rayway{transform:translate(40px,520px)} +@media (prefers-reduced-motion: reduce){*{animation:none!important}}` + + const defs = ` +<radialGradient id="water" gradientUnits="userSpaceOnUse" cx="720" cy="420" r="1050"><stop offset="0" stop-color="#1b2d5a"/><stop offset="0.3" stop-color="#13224a"/><stop offset="0.6" stop-color="#0a1430"/><stop offset="0.85" stop-color="#060c1f"/><stop offset="1" stop-color="#040816"/></radialGradient> +<linearGradient id="caustic" x1="0" y1="0" x2="1" y2="0"><stop offset="0" stop-color="#6f8fd6" stop-opacity="0"/><stop offset="0.5" stop-color="#6f8fd6" stop-opacity="0.085"/><stop offset="1" stop-color="#6f8fd6" stop-opacity="0"/></linearGradient> +<radialGradient id="deep" cx="0.5" cy="0.5" r="0.5"><stop offset="0" stop-color="#0d3a56" stop-opacity="0.6"/><stop offset="0.35" stop-color="#0d3a56" stop-opacity="0.34"/><stop offset="0.7" stop-color="#0d3a56" stop-opacity="0.1"/><stop offset="1" stop-color="#0d3a56" stop-opacity="0"/></radialGradient> +<pattern id="grid" width="20" height="20" patternUnits="userSpaceOnUse"><path d="M0 0.5h20M0.5 0v20" stroke="#9db4ff" stroke-opacity="0.045" fill="none"/></pattern> +<linearGradient id="edgeward" x1="0" y1="0" x2="1" y2="0"><stop offset="0" stop-color="#fff" stop-opacity="0.9"/><stop offset="0.24" stop-color="#fff" stop-opacity="0"/><stop offset="0.74" stop-color="#fff" stop-opacity="0"/><stop offset="1" stop-color="#fff"/></linearGradient> +<mask id="edges" maskUnits="userSpaceOnUse" x="0" y="0" width="1600" height="1000"><rect width="1600" height="1000" fill="url(#edgeward)"/></mask> + +<radialGradient id="tealglow" cx="0.5" cy="0.5" r="0.5"><stop offset="0" stop-color="${TEAL}" stop-opacity="0.24"/><stop offset="0.25" stop-color="${TEAL}" stop-opacity="0.15"/><stop offset="0.5" stop-color="${TEAL}" stop-opacity="0.07"/><stop offset="0.75" stop-color="${TEAL}" stop-opacity="0.02"/><stop offset="1" stop-color="${TEAL}" stop-opacity="0"/></radialGradient> +<radialGradient id="violetglow" cx="0.5" cy="0.5" r="0.5"><stop offset="0" stop-color="${VIOLET}" stop-opacity="0.2"/><stop offset="0.3" stop-color="${VIOLET}" stop-opacity="0.11"/><stop offset="0.6" stop-color="${VIOLET}" stop-opacity="0.04"/><stop offset="1" stop-color="${VIOLET}" stop-opacity="0"/></radialGradient> +<radialGradient id="speckhalo" cx="0.5" cy="0.5" r="0.5"><stop offset="0" stop-color="${TEAL}" stop-opacity="0.5"/><stop offset="0.4" stop-color="${TEAL}" stop-opacity="0.14"/><stop offset="1" stop-color="${TEAL}" stop-opacity="0"/></radialGradient> +${grainPattern()}` + + return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1600 1000" width="100%" height="100%" preserveAspectRatio="xMidYMid slice" font-family="monospace" color="#888"><style>${style}</style><defs>${defs}</defs> +<rect width="1600" height="1000" fill="url(#water)"/> +<g transform="skewX(-28)"><rect class="caustic" x="170" y="-20" width="280" height="1040" fill="url(#caustic)"/><rect class="caustic" style="animation-duration:95s;animation-delay:-20s;animation-direction:alternate-reverse" x="1420" y="-20" width="320" height="1040" fill="url(#caustic)"/></g> +<ellipse cx="1640" cy="1040" rx="900" ry="640" fill="url(#deep)"/> +<rect width="1600" height="1000" fill="url(#grid)" opacity="0.35"/><rect width="1600" height="1000" fill="url(#grid)" mask="url(#edges)"/> +<rect width="1600" height="1000" fill="url(#grain)"/> +${swarm(1330, 700, 190, 120, 48, 1, 61, -70, 30)}${swarm(1480, 880, 110, 90, 36, 2, 47, 60, -40)}${swarm(1180, 950, 150, 40, 30, 6, 67, 80, -14)}${swarm(210, 880, 210, 90, 46, 5, 53, 76, -30)}${middleScatter()} +${reefBand(64, 44)} +<g class="rayway"><g class="raylegs" transform="translate(${3 * CELL} 0)">${rayLap()}</g></g> +<g class="turtleway"><g transform="translate(${62 * CELL} 0)">${turtleLap()}</g></g> +</svg>` +} + diff --git a/plugins/theme-examples/hooks/scenes/paper-garden.ts b/plugins/theme-examples/hooks/scenes/paper-garden.ts new file mode 100644 index 00000000..e1b33c13 --- /dev/null +++ b/plugins/theme-examples/hooks/scenes/paper-garden.ts @@ -0,0 +1,457 @@ +// Paper Garden: cut-paper leaves laid in from the corners of a warm white sheet, and the same scene on dark kraft. +// Pure string building. Every piece of paper is a faceted (scissor-cut) outline in <defs>, +// drawn four times: far shadow, near shadow, a light lip up and left, then the paper itself. + +type Point = [number, number] + +/** 0 paints the cream sheet, 1 the dark kraft sheet. */ +type Stock = 0 | 1 + +/** Paint names are CSS classes, so the two stocks differ only in one block of fill rules. [cream, kraft] */ +const PAINTS: Record<string, [string, string]> = { + ground: ['#efe8d8', '#24211d'], + page: ['#f8f3e9', '#2e2b26'], + fleck: ['#8f7c50', '#b8ad8c'], + shadow: ['#5c4a26', '#000000'], + lip: ['#ffffff', '#f3ecd9'], + pale: ['#d3dbc1', '#39432f'], + sage: ['#b4c29f', '#4b5f45'], + mid: ['#8ba274', '#5d7455'], + fern: ['#7f9b6c', '#62795a'], + olive: ['#6f8a5c', '#6f8566'], + coral: ['#dc6549', '#c9604a'], + coralLight: ['#e58267', '#e4846a'], + coralDark: ['#c65a42', '#b5503a'], + seed: ['#8a3a2c', '#6e2c21'], +} + +/** Shadow and lip strengths per stock: dark paper needs heavier shadows and a fainter lip. */ +const TONES: [string, string] = [ + '.far{opacity:.05}.near{opacity:.11}.edge{opacity:.38}', + '.far{opacity:.2}.near{opacity:.35}.edge{opacity:.14}', +] + +/** How a piece moves. An empty name means it has no motion of its own; zero seconds means the class's own pace. */ +interface Motion { + name: string + lifting: boolean + seconds: number + delay: number + noLip: boolean +} + +const STILL: Motion = { name: '', lifting: false, seconds: 0, delay: 0, noLip: false } + +interface SingleLayer { + kind: 'single' + shape: string + x: number + y: number + turn: number + fill: string + lift: number + seconds: number + sway: string + lifting: boolean +} + +interface SprigLayer { + kind: 'sprig' + id: string + leaflet: string + length: number + bend: number + thick: number + pairs: number + bare: number + spread: number + segments: number + seed: number + x: number + y: number + turn: number + fill: string + lift: number + seconds: number + sway: string +} + +interface BloomLayer { + kind: 'bloom' +} + +type Layer = SingleLayer | SprigLayer | BloomLayer + +/** What one layer adds to the scene: its markup, and the outlines it needs in <defs>. */ +interface Built { + markup: string + shapes: Array<[string, string]> +} + +/** A repeatable number in 0..1 from two integers, so every build is the same. */ +function hash(a: number, b: number): number { + let h = (Math.round(a) * 374761393 + Math.round(b) * 668265263) >>> 0 + h = ((h ^ (h >>> 13)) * 1274126177) >>> 0 + return ((h ^ (h >>> 16)) >>> 0) / 4294967296 +} + +function jitter(seed: number, index: number, spread: number): number { + return 1 + (hash(seed, index) - 0.5) * 2 * spread +} + +/** Leans a point sideways by the square of its height, which bends a straight leaf into an arc. */ +function bendPoint(point: Point, length: number, amount: number): Point { + const height = Math.max(0, -point[1] / length) + return [point[0] + amount * length * height * height, point[1] + Math.abs(amount) * length * height * height * 0.18] +} + +function bendAll(points: Point[], length: number, amount: number): Point[] { + return points.map(point => bendPoint(point, length, amount)) +} + +function cubicAt(p0: Point, p1: Point, p2: Point, p3: Point, t: number): Point { + const u = 1 - t + return [ + u * u * u * p0[0] + 3 * u * u * t * p1[0] + 3 * u * t * t * p2[0] + t * t * t * p3[0], + u * u * u * p0[1] + 3 * u * u * t * p1[1] + 3 * u * t * t * p2[1] + t * t * t * p3[1], + ] +} + +function pointAt(points: Point[], index: number): Point { + return points[index] ?? [0, 0] +} + +/** A closed outline of straight snips through the given corners, in whole pixels. */ +function polygonPath(corners: Point[]): string { + return 'M' + corners.map(point => `${Math.round(point[0])} ${Math.round(point[1])}`).join('L') + 'Z' +} + +/** Cuts a smooth outline [start, c1, c2, end, c1, c2, end, ...] into straight snips about `snip` long, the way scissors would. */ +function facet(points: Point[], snip: number, seed: number): string { + const corners: Point[] = [pointAt(points, 0)] + for (let i = 1; i + 2 < points.length; i += 3) { + const p0 = pointAt(points, i - 1) + const p1 = pointAt(points, i) + const p2 = pointAt(points, i + 1) + const p3 = pointAt(points, i + 2) + const span = Math.hypot(p3[0] - p0[0], p3[1] - p0[1]) + Math.hypot(p1[0] - p0[0], p1[1] - p0[1]) * 0.5 + const cuts = Math.max(1, Math.round(span / snip)) + for (let k = 1; k <= cuts; k += 1) { + const point = cubicAt(p0, p1, p2, p3, k / cuts) + const wobble = k < cuts ? (hash(seed + i, k) - 0.5) * snip * 0.07 : 0 + corners.push([point[0] + wobble, point[1] - wobble]) + } + } + return polygonPath(corners) +} + +/** A broad pointed leaf with slits cut along its veins, so whatever lies underneath shows through. */ +function broadLeafPath(length: number, width: number, bend: number, seed: number, veins: number): string { + const fat = jitter(seed, 1, 0.1) + const outline: Point[] = [ + [-4, 0], [-4, 0], [-4, -length * 0.1], [-3, -length * 0.16], + [-width * 1.02 * fat, -length * 0.24], [-width * 0.74, -length * 0.8], [0, -length], + [width * 0.7, -length * 0.78], [width * 1.06 / fat, -length * 0.3], [3, -length * 0.16], + [4, -length * 0.1], [4, 0], [4, 0], + ] + let d = facet(bendAll(outline, length, bend), length / 9, seed) + for (let i = 0; i < veins; i += 1) { + for (const side of [-1, 1]) { + const from = -length * (0.3 + (0.5 * (i + (side > 0 ? 0.5 : 0))) / veins) + const span = width * (0.56 - 0.24 * (i / veins)) * jitter(seed, i * 2 + side + 5, 0.1) + const rise = length * 0.12 + const gap = 5 + width * 0.03 + const cut: Point[] = [ + [side * 9, from], + [side * (9 + span * 0.4), from - rise * 0.2 - gap], [side * (9 + span * 0.8), from - rise * 0.7 - gap], [side * (9 + span), from - rise], + [side * (9 + span * 0.85), from - rise * 0.6 + gap], [side * (9 + span * 0.4), from - rise * 0.1 + gap], [side * 9, from], + ] + d += facet(bendAll(cut, length, bend), span / 2.5, seed + i) + } + } + return d +} + +/** A long narrow blade of grass. */ +function bladePath(length: number, width: number, bend: number, seed: number): string { + const outline: Point[] = [ + [-width * 0.25, 0], [-width * 0.7, -length * 0.2], [-width * 0.6, -length * 0.7], [0, -length], + [width * 0.5, -length * 0.66], [width * 0.75, -length * 0.22], [width * 0.25, 0], + [width * 0.25, 0], [-width * 0.25, 0], [-width * 0.25, 0], + ] + return facet(bendAll(outline, length, bend), length / 7, seed) +} + +/** A paddle leaflet lying along +x from a narrow neck at the origin: the Matisse lobe. */ +function paddlePath(reach: number, thickness: number, seed: number): string { + const outline: Point[] = [ + [0, thickness * 0.3], + [reach * 0.3, thickness * 0.35], [reach * 0.96, thickness * 1.5], [reach, 0], + [reach * 1.02, -thickness * 1.35], [reach * 0.34, -thickness * 0.45], [0, -thickness * 0.3], + [0, -thickness * 0.3], [0, thickness * 0.3], [0, thickness * 0.3], + ] + return facet(outline, reach / 8, seed) +} + +/** A coin leaf on a short stalk, lying along +x: the eucalyptus leaf, cut a little out of round. */ +function coinPath(radius: number, seed: number): string { + const sides = 22 + const corners: Point[] = [[0, 2], [radius * 0.35, 2]] + for (let i = 1; i < sides; i += 1) { + const angle = Math.PI - (i / sides) * Math.PI * 2 + const reach = radius * jitter(seed, i, 0.035) + corners.push([radius * 1.3 + Math.cos(angle) * reach, -Math.sin(angle) * reach * 0.92]) + } + corners.push([radius * 0.35, -2], [0, -2]) + return polygonPath(corners) +} + +/** The big sheet the conversation lies on: straight top and bottom off the frame, long sides cut by hand with a slight wander. */ +function pagePath(left: number, right: number, seed: number): string { + const corners: Point[] = [] + const steps = 30 + for (let i = 0; i <= steps; i += 1) { + const wander = (hash(seed, i) - 0.5) * 7 + Math.sin(i * 0.45 + seed) * 6 + corners.push([left + wander, -40 + (1080 * i) / steps]) + } + for (let i = steps; i >= 0; i -= 1) { + const wander = (hash(seed + 5, i) - 0.5) * 6 + Math.sin(i * 0.4 + seed) * 5 + corners.push([right + wander, -40 + (1080 * i) / steps]) + } + return polygonPath(corners) +} + +/** A scalloped disc cut by hand: one layer of the bloom. */ +function discPath(radius: number, scallops: number, seed: number): string { + const sides = scallops * 4 + const corners: Point[] = [] + for (let i = 0; i < sides; i += 1) { + const angle = (i / sides) * Math.PI * 2 + const reach = radius * (1 + 0.09 * Math.cos(angle * scallops + seed)) * jitter(seed, i, 0.035) + corners.push([Math.cos(angle) * reach, Math.sin(angle) * reach]) + } + return polygonPath(corners) +} + +function fixed(value: number): number { + return Number(value.toFixed(1)) +} + +/** An offset on the page, expressed in a frame turned by `degrees`, to one decimal. */ +function turnedOffset(x: number, y: number, degrees: number): Point { + const angle = (degrees * Math.PI) / 180 + return [fixed(x * Math.cos(angle) - y * Math.sin(angle)), fixed(x * Math.sin(angle) + y * Math.cos(angle))] +} + +function useMarkup(shape: string, offset: Point, paint: string, tone: string): string { + return `<use href="#${shape}" transform="translate(${offset[0]} ${offset[1]})" class="${paint}${tone ? ` ${tone}` : ''}"/>` +} + +/** + * One piece of paper in the frame given by `place`. `facing` is how far that frame is turned from the page, + * so the shadow can always fall down and to the right of the page whatever way the piece lies. + */ +function paper(shape: string, place: string, facing: number, fill: string, lift: number, motion: Motion): string { + const far = turnedOffset(lift * 1.9, lift * 2.4, -facing) + const near = turnedOffset(lift * 0.9, lift * 1.15, -facing) + const lip = turnedOffset(-1.2, -1.2, -facing) + let shadows = useMarkup(shape, far, 'shadow', 'far') + useMarkup(shape, near, 'shadow', 'near') + if (motion.lifting) { + const more = turnedOffset(lift * 1.3, lift * 1.6, -facing) + const pace = motion.seconds ? `animation-duration:${motion.seconds}s;` : '' + shadows = `<g class="lift" style="--lx:${more[0]}px;--ly:${more[1]}px;${pace}animation-delay:-${motion.delay}s">${shadows}</g>` + } + const body = shadows + (motion.noLip ? '' : useMarkup(shape, lip, 'lip', 'edge')) + useMarkup(shape, [0, 0], fill, '') + const moving = motion.name ? `<g class="${motion.name}" style="animation-duration:${motion.seconds}s;animation-delay:-${motion.delay}s">${body}</g>` : body + return `<g transform="${place}">${moving}</g>` +} + +/** The stem between two heights, cut out on its own, so the sprig can flex at the joints. */ +function stemPiece(item: SprigLayer, from: number, to: number): string { + const left: Point[] = [] + const right: Point[] = [] + for (let k = 0; k <= 3; k += 1) { + const along = from + ((to - from) * k) / 3 + const half = item.thick * (1 - 0.8 * along) + 1 + left.push(bendPoint([-half, -along * item.length], item.length, item.bend)) + right.unshift(bendPoint([half, -along * item.length], item.length, item.bend)) + } + return polygonPath(left.concat(right)) +} + +/** + * A stem with leaflets up both sides. The stem is cut into segments that each flex about their lower joint, + * so the sway compounds towards the tip like a real stalk; each leaflet also stirs about its own neck. + */ +function sprig(item: SprigLayer, index: number): Built { + const count = item.pairs * 2 + const pieces: string[] = [] + for (let k = 0; k < item.segments; k += 1) pieces.push('') + for (let i = 0; i <= count; i += 1) { + const isTip = i === count + const side = i % 2 === 0 ? -1 : 1 + const along = isTip ? 0.985 : item.bare + (1 - item.bare) * ((i + 0.6) / (count + 1.4)) + const root = bendPoint([0, -along * item.length], item.length, item.bend) + const lean = Math.atan(2 * item.bend * along) * (180 / Math.PI) + const spread = (item.spread - 14 * along) * jitter(item.seed, i, 0.1) + const angle = isTip ? lean - 90 : lean - 90 + side * spread + const envelope = isTip ? 0.8 : 0.62 + 0.38 * Math.sin(Math.PI * (0.12 + 0.7 * (i / count))) + const scale = fixed(envelope * jitter(item.seed, i + 30, item.leaflet === 'coin' ? 0.22 : 0.08)) + const place = `translate(${Math.round(root[0])} ${Math.round(root[1])}) rotate(${fixed(angle)}) scale(${scale})` + const motion: Motion = { + name: 'stir', + lifting: true, + seconds: 7 + 2 * Math.round(hash(item.seed, i + 50) * 3), + delay: fixed(i * 1.3 + hash(item.seed, i + 70) * 3), + noLip: false, + } + const segment = Math.min(item.segments - 1, Math.floor(along * item.segments)) + pieces[segment] = (pieces[segment] ?? '') + paper(item.leaflet, place, item.turn + angle, item.fill, item.lift / scale, motion) + } + const shapes: Array<[string, string]> = [] + let body = '' + for (let k = item.segments - 1; k >= 0; k -= 1) { + const from = k / item.segments + const to = (k + 1) / item.segments + const id = `${item.id}Stem${k}` + shapes.unshift([id, stemPiece(item, from, Math.min(1, to + 0.01))]) + const joint = bendPoint([0, -from * item.length], item.length, item.bend) + const inner = paper(id, '', item.turn, item.fill, item.lift * 0.6, STILL) + (pieces[k] ?? '') + body + body = k === 0 ? inner : `<g class="flex" style="transform-origin:${Math.round(joint[0])}px ${Math.round(joint[1])}px;animation-duration:${11 + k * 6}s;animation-delay:-${fixed(hash(item.seed, k) * 20)}s">${inner}</g>` + } + const markup = + `<g class="${item.sway}" style="transform-origin:${item.x}px ${item.y}px;animation-duration:${item.seconds}s;animation-delay:-${fixed(hash(index, 7) * item.seconds)}s">` + + `<g transform="translate(${item.x} ${item.y}) rotate(${item.turn})">${body}</g></g>` + return { markup, shapes } +} + +/** A single big piece (leaf, blade, sheet) that sways about its stem end; zero seconds means it lies still. */ +function single(item: SingleLayer, index: number): string { + const motion: Motion = { name: '', lifting: item.lifting, seconds: 0, delay: fixed(hash(index, 3) * 14), noLip: item.fill === 'pale' } + const inner = paper(item.shape, `translate(${item.x} ${item.y}) rotate(${item.turn})`, item.turn, item.fill, item.lift, motion) + if (!item.seconds) return inner + return `<g class="${item.sway}" style="transform-origin:${item.x}px ${item.y}px;animation-duration:${item.seconds}s;animation-delay:-${fixed(hash(index, 7) * item.seconds)}s">${inner}</g>` +} + +/** Three hand-cut discs on a tapered stem, folded a little open: the one warm thing on the sheet. The head nods on the stem while the stem leans. */ +function bloom(): string { + const x = 1440 + const y = 832 + const rootX = 1570 + const rootY = 1100 + const stem = `M${rootX - 6} ${rootY}L1530 1000L1484 900L${x - 2} ${y}L${x + 3} ${y}L1492 896L1540 996L${rootX + 6} ${rootY}Z` + return ( + `<g class="swayWide" style="transform-origin:${rootX}px ${rootY}px;animation-duration:23s;animation-delay:-4s">` + + `<path d="${stem}" transform="translate(4 5)" class="shadow near"/><path d="${stem}" class="olive"/>` + + `<g transform="translate(${x} ${y})"><g class="nod"><g transform="scale(0.9)">` + + paper('discBack', 'translate(-5 4) rotate(8)', 8, 'coralDark', 4, { name: 'openBack', lifting: false, seconds: 19, delay: 3, noLip: false }) + + paper('discMiddle', 'translate(4 -3) rotate(-14)', -14, 'coral', 4, { name: 'open', lifting: false, seconds: 19, delay: 3, noLip: false }) + + paper('discFront', 'translate(-2 2) rotate(20)', 20, 'coralLight', 3, { name: 'open', lifting: false, seconds: 19, delay: 1, noLip: false }) + + '<circle r="13" class="coralDark"/><circle r="6" class="seed"/>' + + '</g></g></g></g>' + ) +} + +function layer(item: Layer, index: number): Built { + if (item.kind === 'bloom') return { markup: bloom(), shapes: [] } + if (item.kind === 'sprig') return sprig(item, index) + return { markup: single(item, index), shapes: [] } +} + +/** The outlines every scene needs, whatever the layers add. */ +function baseShapes(): Array<[string, string]> { + return [ + ['leafGreat', broadLeafPath(660, 150, 0.16, 5, 4)], + ['leafMid', broadLeafPath(440, 108, -0.2, 8, 3)], + ['bladeLong', bladePath(430, 30, 0.2, 4)], + ['bladeShort', bladePath(300, 24, -0.26, 6)], + ['paddle', paddlePath(150, 30, 12)], + ['coin', coinPath(31, 21)], + ['page', pagePath(422, 1196, 7)], + ['discBack', discPath(58, 5, 2)], + ['discMiddle', discPath(45, 6, 5)], + ['discFront', discPath(30, 5, 9)], + ] +} + +/** Back to front. turn 0 points up the page; each stem end sits off the sheet. Nothing here reaches x 432..1200. */ +const LAYERS: Layer[] = [ + // the page: its long edges fall in the gaps between the app's panels (24-27% and 75-77% of the width); margins are a darker, flecked paper + { kind: 'single', shape: 'page', x: 0, y: 0, turn: 0, fill: 'page', lift: 3, seconds: 0, sway: 'sway', lifting: false }, + // bottom left lives under the sidebar glass: one corner only, large, simple, low contrast, so it dissolves into a tone + { kind: 'single', shape: 'leafGreat', x: 20, y: 1190, turn: 14, fill: 'pale', lift: 4, seconds: 61, sway: 'sway', lifting: true }, + { kind: 'sprig', id: 'fern', leaflet: 'paddle', length: 520, bend: 0.1, thick: 6, pairs: 4, bare: 0.26, spread: 56, segments: 3, seed: 11, x: 190, y: 1130, turn: -10, fill: 'sage', lift: 5, seconds: 38, sway: 'sway' }, + // right edge, all below the cards and right of x 1400: a pale leaf, and over it a drooping coin branch in two stacked greens + { kind: 'single', shape: 'leafMid', x: 1720, y: 330, turn: 244, fill: 'pale', lift: 4, seconds: 23, sway: 'swayBack', lifting: true }, + { kind: 'sprig', id: 'under', leaflet: 'coin', length: 300, bend: 0.14, thick: 4, pairs: 2, bare: 0.34, spread: 60, segments: 2, seed: 53, x: 1680, y: 318, turn: 222, fill: 'sage', lift: 4, seconds: 19, sway: 'swayWide' }, + { kind: 'sprig', id: 'vine', leaflet: 'coin', length: 390, bend: -0.1, thick: 4, pairs: 2, bare: 0.3, spread: 64, segments: 3, seed: 29, x: 1672, y: 282, turn: 203, fill: 'fern', lift: 6, seconds: 14, sway: 'swayWide' }, + // bottom right: grass first, so nothing crosses the face of the bloom + { kind: 'single', shape: 'leafMid', x: 1600, y: 1150, turn: -12, fill: 'pale', lift: 4, seconds: 29, sway: 'swayBack', lifting: true }, + { kind: 'single', shape: 'bladeShort', x: 1630, y: 1060, turn: -26, fill: 'fern', lift: 7, seconds: 11, sway: 'swayWide', lifting: true }, + { kind: 'single', shape: 'bladeLong', x: 1680, y: 1090, turn: -44, fill: 'mid', lift: 6, seconds: 17, sway: 'swayWide', lifting: true }, + { kind: 'bloom' }, +] + +/** Short paper fibres for the margins, scattered by hash; the page sheet covers them in the middle. */ +function fleckPath(): string { + let d = '' + for (let i = 0; i < 26; i += 1) { + const x = Math.round(hash(i, 1) * 168) + const y = Math.round(hash(i, 2) * 206) + const angle = hash(i, 3) * Math.PI + const reach = 2 + hash(i, 4) * 3 + d += `M${x} ${y}l${fixed(Math.cos(angle) * reach)} ${fixed(Math.sin(angle) * reach)}l1 1z` + } + return d +} + +function paintRules(stock: Stock): string { + return Object.entries(PAINTS).map(([name, values]) => `.${name}{fill:${values[stock]}}`).join('') +} + +/** The whole scene on one stock of paper. */ +function sceneSvg(stock: Stock): string { + const style = + paintRules(stock) + TONES[stock] + + '.sway{animation:sway 40s ease-in-out infinite alternate}' + + '.swayWide{animation:swayWide 20s ease-in-out infinite alternate}' + + '.stir{animation:stir 12s ease-in-out infinite alternate}' + + '.lift{animation:lift 14s ease-in-out infinite alternate}' + + '.open{animation:open 19s ease-in-out infinite alternate}' + + '.openBack{animation:openBack 19s ease-in-out infinite alternate}' + + '.nod{animation:nod 11s ease-in-out infinite alternate}' + + '.swayBack{animation:swayBack 23s ease-in-out infinite alternate}' + + '.flex{animation:flex 17s ease-in-out infinite alternate}' + + '@keyframes sway{from{transform:rotate(-2.4deg)}to{transform:rotate(2.8deg)}}' + + '@keyframes swayWide{from{transform:rotate(-4deg)}to{transform:rotate(4.5deg)}}' + + '@keyframes stir{from{transform:rotate(-7deg)}to{transform:rotate(8deg)}}' + + '@keyframes lift{from{transform:translate(0,0)}to{transform:translate(var(--lx),var(--ly))}}' + + '@keyframes open{from{transform:scale(0.95) rotate(-4deg)}to{transform:scale(1.05) rotate(5deg)}}' + + '@keyframes openBack{from{transform:scale(0.98) rotate(3deg)}to{transform:scale(1.03) rotate(-3deg)}}' + + '@keyframes swayBack{from{transform:translate(-5px,3px) rotate(1.6deg)}to{transform:translate(4px,-4px) rotate(-1.8deg)}}' + + '@keyframes flex{from{transform:rotate(-3deg)}to{transform:rotate(3.6deg)}}' + + '@keyframes nod{from{transform:rotate(-9deg)}to{transform:rotate(7deg)}}' + + '@media (prefers-reduced-motion: reduce){*{animation:none!important}}' + const built = LAYERS.map(layer) + const shapes = baseShapes().concat(built.flatMap(part => part.shapes)) + const defs = + shapes.map(([id, d]) => `<path id="${id}" d="${d}" fill-rule="evenodd"/>`).join('') + + `<pattern id="flecks" width="173" height="211" patternUnits="userSpaceOnUse"><path class="fleck" opacity="0.09" d="${fleckPath()}"/></pattern>` + return ( + '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1600 1000" width="100%" height="100%" preserveAspectRatio="xMidYMid slice" font-family="monospace" color="#888">' + + `<style>${style}</style><defs>${defs}</defs>` + + '<rect width="1600" height="1000" class="ground"/><rect width="1600" height="1000" fill="url(#flecks)"/>' + + built.map(part => part.markup).join('') + + '</svg>' + ) +} + +/** Paper Garden: cream paper, for light windows. */ +export function paperGardenSvg(): string { + return sceneSvg(0) +} + +/** Paper Garden, Kraft: the same cut paper on dark kraft, for dark windows. */ +export function paperGardenKraftSvg(): string { + return sceneSvg(1) +} diff --git a/plugins/theme-examples/hooks/scenes/plotter-tide.ts b/plugins/theme-examples/hooks/scenes/plotter-tide.ts new file mode 100644 index 00000000..d7e85fec --- /dev/null +++ b/plugins/theme-examples/hooks/scenes/plotter-tide.ts @@ -0,0 +1,343 @@ +// Plotter Tide: a pen plotter drawing a chart coast. The land in the two lower corners is hatched in a rust pen; +// the sea is "water-lined" in a slate pen: every tide line is the coast pushed seaward by a gap that is always positive +// and grows with distance, so the lines crowd the shore, calm down further out, and never cross. +// A pen works through each set line by line; the oldest lines wash away and are drawn again, so the sheet is never finished. +// Two stocks: warm paper for a light window, blue-black night paper for a dark one. Pure string building. + +const WIDTH = 1600 +const HEIGHT = 1000 +/** The conversation sits between these; no ink goes between them. */ +const COLUMN_LEFT = 432 +const COLUMN_RIGHT = 1200 + +interface Stock { + paper: string + land: string + ink: string + rust: string +} + +const DAY: Stock = { paper: '#f3eee3', land: '#e8d6bd', ink: '#1f2a48', rust: '#c4552d' } +/** The same drawing in pale ink on blue-black paper. */ +const NIGHT: Stock = { paper: '#141a27', land: '#1c2333', ink: '#aab6d0', rust: '#e98a5e' } + +interface Point { + x: number + y: number +} + +interface Sample { + point: Point + inked: boolean +} + +/** One piece of land and the sea around it. An islet is a closed ring; a coast is an arc whose centre lies off the sheet. */ +interface Coast { + seed: number + isIslet: boolean + centreX: number + centreY: number + landRadius: number + bayDepth: number + lineCount: number + firstGap: number + gapGrowth: number + fullUntil: number + keepToward: number + angleFrom: number + angleTo: number + hatchLean: number +} + +/** One pen's work. A zero in drawShare, farFrom or coastWidth means "not used". */ +interface Job { + name: string + ink: string + width: number + opacity: number + opacityFade: number + cycleSeconds: number + cycleStart: number + absentShare: number + drawShare: number + farFrom: number + coastWidth: number + hidePen: boolean +} + +interface JobMarkup { + shapes: string + keyframes: string + strokes: string + farStrokes: string +} + +// The big coast: bottom right, where no panel sits over it. +const EAST_COAST: Coast = { + seed: 1, isIslet: false, centreX: 1650, centreY: 1050, landRadius: 300, bayDepth: 62, lineCount: 14, firstGap: 11, gapGrowth: 1.062, + fullUntil: 0.5, keepToward: 0.7, angleFrom: Math.PI * 0.95, angleTo: Math.PI * 1.55, hatchLean: 1, +} +// The spit: bottom left, under the quiet lower half of the sidebar. +const WEST_SPIT: Coast = { + seed: 2, isIslet: false, centreX: -50, centreY: 1070, landRadius: 300, bayDepth: 56, lineCount: 17, firstGap: 11, gapGrowth: 1.058, + fullUntil: 0.5, keepToward: 0.3, angleFrom: -Math.PI * 0.58, angleTo: Math.PI * 0.05, hatchLean: 1, +} +// The islet: small, right of the conversation and below the cards, so the top half of the sheet is not bare. +const ISLET: Coast = { + seed: 5, isIslet: true, centreX: 1436, centreY: 334, landRadius: 26, bayDepth: 7, lineCount: 5, firstGap: 7.5, gapGrowth: 1.2, + fullUntil: 1, keepToward: 0.5, angleFrom: 0, angleTo: Math.PI * 2, hatchLean: 1, +} + +/** A fixed pseudo-random number in 0..1 for a whole number, so every build is the same. */ +function hash(number: number): number { + const value = Math.sin(number * 127.1 + 311.7) * 43758.5453 + return value - Math.floor(value) +} + +function round(value: number): number { + return Math.round(value * 10) / 10 +} + +/** The coast's shape in -1..1 at a place `along` the shore (pixels). `calm` 0..1 smooths the small bays out, the way the sea does further from land. */ +function bays(along: number, coast: Coast, calm: number): number { + // An islet closes on itself, so its bays must fit a whole number of times into one turn. + const turn = along / coast.landRadius + const wide = coast.isIslet ? Math.sin(turn * 2 + coast.seed) : Math.sin(along / 97 + coast.seed * 1.7) + const middle = (coast.isIslet ? Math.sin(turn * 3 + coast.seed * 2) : Math.sin(along / 41 + coast.seed * 3.1)) * (1 - calm) + const small = (coast.isIslet ? Math.sin(turn * 5 + coast.seed * 3) : Math.sin(along / 17 + coast.seed * 5.3)) * (1 - calm) * (1 - calm) + return (wide + 0.55 * middle + 0.25 * small) / 1.8 +} + +/** Distance from the coast's centre to tide line `line` at `angle`; line 0 is the coast itself. */ +function radiusAt(angle: number, line: number, coast: Coast): number { + const along = angle * coast.landRadius + let radius = coast.landRadius + coast.bayDepth * bays(along, coast, 0) + let gap = coast.firstGap + for (let step = 1; step <= line; step += 1) { + const calm = Math.min(1, step / (coast.lineCount * 0.8)) + // Wider gaps in the bays, narrower off the headlands: that is what flattens the lines seaward. Never below 0.64 of the gap, about 7 px at the shore. + radius += gap * (1 - 0.36 * bays(along, coast, calm)) + gap *= coast.gapGrowth + } + return radius +} + +function pointAt(angle: number, line: number, coast: Coast): Point { + const radius = radiusAt(angle, line, coast) + return { x: coast.centreX + radius * Math.cos(angle), y: coast.centreY + radius * Math.sin(angle) } +} + +function isOnSheet(point: Point): boolean { + return point.x > -30 && point.x < WIDTH + 30 && point.y > -30 && point.y < HEIGHT + 30 +} + +/** Outside the reading column; each line stops a different distance short of it, so the ends do not make a wall. */ +function isOutsideColumn(point: Point, line: number, coast: Coast): boolean { + const shy = 80 * hash(line * 17 + coast.seed * 7) + return point.x < COLUMN_LEFT - shy || point.x > COLUMN_RIGHT + shy +} + +function isOnLand(point: Point, coast: Coast): boolean { + const dx = point.x - coast.centreX + const dy = point.y - coast.centreY + // atan2 answers in -pi..pi; the coast's own angles may lie a whole turn above that. + let angle = Math.atan2(dy, dx) + if (!coast.isIslet && angle < coast.angleFrom - 0.5) angle += Math.PI * 2 + return Math.hypot(dx, dy) < radiusAt(angle, 0, coast) - 5 +} + +function midway(first: Point, second: Point): string { + return `${round((first.x + second.x) / 2)} ${round((first.y + second.y) / 2)}` +} + +/** A smooth open path through the midpoints of the samples: one point per segment, so the string stays short. */ +function smoothPath(points: Point[]): string { + const first = points[0] + const second = points[1] + const third = points[2] + const last = points[points.length - 1] + if (points.length < 4 || !first || !second || !third || !last) return '' + let path = `M${round(first.x)} ${round(first.y)}Q${round(second.x)} ${round(second.y)} ${midway(second, third)}` + for (let index = 2; index < points.length - 1; index += 1) { + const here = points[index] + const next = points[index + 1] + if (here && next) path += `T${midway(here, next)}` + } + return `${path}T${round(last.x)} ${round(last.y)}` +} + +/** The same for a closed ring. */ +function smoothRing(points: Point[]): string { + const count = points.length + const closing = points[count - 1] + let path = '' + for (let index = 0; index < count; index += 1) { + const here = points[index] + const next = points[(index + 1) % count] + if (!here || !next || !closing) continue + if (index === 0) path = `M${midway(closing, here)}Q${round(here.x)} ${round(here.y)} ${midway(here, next)}` + else path += `T${midway(here, next)}` + } + return `${path}Z` +} + +/** The longest unbroken run of samples that may be inked. */ +function longestRun(samples: Sample[]): Point[] { + let best: Point[] = [] + let run: Point[] = [] + for (const sample of samples) { + if (sample.inked) run.push(sample.point) + else { + if (run.length > best.length) best = run + run = [] + } + } + return run.length > best.length ? run : best +} + +/** The coast and its tide lines, path strings, shore first. The outer lines are shorter pieces. */ +function tideLines(coast: Coast): string[] { + const paths: string[] = [] + for (let line = 0; line <= coast.lineCount; line += 1) { + const stepAngle = 16 / radiusAt((coast.angleFrom + coast.angleTo) / 2, line, coast) + const samples: Sample[] = [] + for (let angle = coast.angleFrom; angle <= coast.angleTo; angle += stepAngle) { + const point = pointAt(angle, line, coast) + samples.push({ point, inked: isOnSheet(point) && isOutsideColumn(point, line, coast) }) + } + const points = longestRun(samples) + const share = line / coast.lineCount + const fade = Math.max(0, (share - coast.fullUntil) / (1 - coast.fullUntil)) + const keep = Math.max(4, Math.floor(points.length * (1 - fade * (0.35 + 0.3 * hash(line + coast.seed * 31))))) + const slack = Math.max(points.length - keep, 0) + const start = Math.min(Math.max(Math.floor(slack * (coast.keepToward + (hash(line * 11 + coast.seed) - 0.5) * 0.4)), 0), slack) + const kept = points.slice(start, start + keep) + // The pen goes out along one line and comes back along the next, the way a plotter does. + if (line % 2 === 1) kept.reverse() + const path = smoothPath(kept) + if (path) paths.push(path) + } + return paths +} + +/** An islet's shore and tide lines: closed rings, shore first. */ +function isletRings(coast: Coast): string[] { + const paths: string[] = [] + for (let line = 0; line <= coast.lineCount; line += 1) { + const count = Math.max(12, Math.round((radiusAt(0, line, coast) * 6.3) / 14)) + const points: Point[] = [] + for (let index = 0; index < count; index += 1) points.push(pointAt((index / count) * Math.PI * 2 + line * 0.9, line, coast)) + paths.push(smoothRing(points)) + } + return paths +} + +/** The land, one filled shape under the hatching: the coast, closed through its centre, which lies off the sheet. */ +function landShape(coast: Coast, colour: string): string { + let path = '' + for (let angle = coast.angleFrom; angle <= coast.angleTo; angle += 0.04) { + const point = pointAt(angle, 0, coast) + path += `${path ? 'L' : 'M'}${round(point.x)} ${round(point.y)}` + } + if (!coast.isIslet) path += `L${coast.centreX} ${coast.centreY}` + return `<path d="${path}Z" style="fill:${colour}" fill-opacity="0.6"/>` +} + +/** Straight hatch strokes across the land, path strings in the order a pen would take them. */ +function landHatch(coast: Coast): string[] { + const paths: string[] = [] + const spacing = 15 + let stroke = 0 + for (let offset = -HEIGHT; offset < WIDTH + HEIGHT; offset += spacing) { + // One hatch line runs down-left from (offset, 0); walk it and keep the piece that lies on the land. + let first: Point | null = null + let last: Point | null = null + for (let step = 0; step < HEIGHT + 60; step += 4) { + const point = { x: offset - step * coast.hatchLean, y: step } + if (isOnSheet(point) && isOnLand(point, coast)) { + if (!first) first = point + last = point + } else if (first) break + } + if (!first || !last || Math.hypot(last.x - first.x, last.y - first.y) < 14) continue + const from = stroke % 2 === 0 ? first : last + const to = stroke % 2 === 0 ? last : first + paths.push(`M${round(from.x)} ${round(from.y)}L${round(to.x)} ${round(to.y)}`) + stroke += 1 + } + return paths +} + +/** One pen's job: the paths drawn strictly one after another on a shared cycle, each washed away again before its next turn. + * Returns the shapes for <defs>, the job's own keyframes, and the strokes (the far tide lines apart, so they can ride the tide further). */ +function penJob(paths: string[], job: Job): JobMarkup { + let shapes = '' + let strokes = '' + let farStrokes = '' + let heads = '' + let farHeads = '' + const stepSeconds = job.cycleSeconds / paths.length + // Normally a stroke takes exactly its turn; a job may ask for a shorter stroke, so its lines are rarely caught half made. + const drawnAt = job.drawShare > 0 ? job.drawShare : round(100 / paths.length) + const restUntil = 100 - job.absentShare - drawnAt + for (let line = 0; line < paths.length; line += 1) { + const id = `${job.name}${line}` + // Line k starts one step after line k - 1, so it is one step less far into its cycle. + const phase = (((job.cycleStart - line * stepSeconds) % job.cycleSeconds) + job.cycleSeconds) % job.cycleSeconds + const timing = `style="animation-delay:${round(-phase)}s"` + const opacity = round((job.opacity - job.opacityFade * (line / paths.length)) * 100) / 100 + shapes += `<path id="${id}" pathLength="1" d="${paths[line] ?? ''}"/>` + // The first path of a land job is the coast itself: a firmer line than the hatching. + const firm = line === 0 && job.coastWidth > 0 ? ` stroke-width="${job.coastWidth}" stroke-opacity="0.9"` : ` stroke-opacity="${opacity}"` + const isFar = job.farFrom > 0 && line >= job.farFrom + if (isFar) farStrokes += `<use href="#${id}" class="ink"${firm} ${timing}/>` + else strokes += `<use href="#${id}" class="ink"${firm} ${timing}/>` + if (!job.hidePen && isFar) farHeads += `<use href="#${id}" class="pen" ${timing}/>` + else if (!job.hidePen) heads += `<use href="#${id}" class="pen" ${timing}/>` + } + const keyframes = ` +.${job.name} .ink{animation:ink-${job.name} ${job.cycleSeconds}s linear infinite}.${job.name} .pen{animation:pen-${job.name} ${job.cycleSeconds}s linear infinite} +@keyframes ink-${job.name}{0%{stroke-dashoffset:1.01;opacity:1}${drawnAt}%{stroke-dashoffset:0;opacity:1}${round(drawnAt * 2.5)}%{stroke-dashoffset:0;opacity:.74}${restUntil}%{stroke-dashoffset:0;opacity:.74}${restUntil + drawnAt}%{stroke-dashoffset:-1.01}100%{stroke-dashoffset:-1.01;opacity:.74}} +@keyframes pen-${job.name}{0%{stroke-dashoffset:0;opacity:1}${drawnAt}%{stroke-dashoffset:-1;opacity:1}${drawnAt + 0.01}%{stroke-dashoffset:-1;opacity:0}100%{stroke-dashoffset:-1;opacity:0}}` + const near = `<g class="${job.name}" stroke="${job.ink}" stroke-width="${job.width}">${strokes}${heads}</g>` + const far = `<g class="${job.name}" stroke="${job.ink}" stroke-width="${job.width}">${farStrokes}${farHeads}</g>` + return { shapes, keyframes, strokes: near, farStrokes: far } +} + +/** The whole sheet on one stock. */ +function plotterTideSheet(stock: Stock): string { + const eastSea = penJob(tideLines(EAST_COAST).slice(1), { name: 'e', ink: stock.ink, width: 1.15, opacity: 1, opacityFade: 0.4, cycleSeconds: 136, cycleStart: 30, absentShare: 20, drawShare: 0, farFrom: 7, coastWidth: 0, hidePen: false }) + const westSea = penJob(tideLines(WEST_SPIT).slice(1), { name: 'w', ink: stock.ink, width: 1.15, opacity: 1, opacityFade: 0.4, cycleSeconds: 126, cycleStart: 75, absentShare: 20, drawShare: 0, farFrom: 8, coastWidth: 0, hidePen: false }) + const isletSea = penJob(isletRings(ISLET).slice(1), { name: 'i', ink: stock.ink, width: 1.1, opacity: 0.8, opacityFade: 0.3, cycleSeconds: 150, cycleStart: 40, absentShare: 14, drawShare: 5, farFrom: 0, coastWidth: 0, hidePen: true }) + const eastLand = penJob(tideLines(EAST_COAST).slice(0, 1).concat(landHatch(EAST_COAST)), { name: 'f', ink: stock.rust, width: 1, opacity: 0.8, opacityFade: 0, cycleSeconds: 118, cycleStart: 60, absentShare: 4, drawShare: 0, farFrom: 0, coastWidth: 1.3, hidePen: false }) + const westLand = penJob(tideLines(WEST_SPIT).slice(0, 1).concat(landHatch(WEST_SPIT)), { name: 'g', ink: stock.rust, width: 1, opacity: 0.8, opacityFade: 0, cycleSeconds: 104, cycleStart: 20, absentShare: 4, drawShare: 0, farFrom: 0, coastWidth: 1.3, hidePen: false }) + const isletLand = penJob(isletRings(ISLET).slice(0, 1), { name: 'j', ink: stock.rust, width: 1, opacity: 0.8, opacityFade: 0, cycleSeconds: 140, cycleStart: 9, absentShare: 6, drawShare: 6, farFrom: 0, coastWidth: 1.3, hidePen: true }) + const jobs = [eastSea, westSea, isletSea, eastLand, westLand, isletLand] + + const style = ` +path{fill:none;stroke-linecap:round;stroke-linejoin:round} +.ink{stroke-dasharray:1 2} +.pen{stroke-dasharray:.0001 3;stroke-width:8;opacity:0} +.tide{animation:tide 70s ease-in-out infinite alternate}${jobs.map(job => job.keyframes).join('')} +@keyframes tide{from{transform:translate(0,0)}to{transform:var(--move)}} +@media (prefers-reduced-motion: reduce){*{animation:none!important}}` + + return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${WIDTH} ${HEIGHT}" width="100%" height="100%" preserveAspectRatio="xMidYMid slice" font-family="monospace" color="#888"><style>${style}</style><defs>${jobs.map(job => job.shapes).join('')}</defs> +<rect width="${WIDTH}" height="${HEIGHT}" fill="${stock.paper}"/> +${landShape(EAST_COAST, stock.land)}${landShape(WEST_SPIT, stock.land)}${landShape(ISLET, stock.land)} +<g class="tide" style="--move:translate(-5px,-5px)">${eastSea.strokes}</g><g class="tide" style="--move:translate(-17px,-15px)">${eastSea.farStrokes}</g> +<g class="tide" style="--move:translate(5px,-5px);animation-delay:-35s">${westSea.strokes}</g><g class="tide" style="--move:translate(16px,-16px);animation-delay:-35s">${westSea.farStrokes}</g> +<g class="tide" style="--move:translate(-3px,3px);animation-delay:-36s">${isletSea.strokes}</g> +${eastLand.strokes}${westLand.strokes}${isletLand.strokes} +</svg>` +} + +/** Plotter Tide on warm paper, for a light window (scene.svg). */ +export function plotterTideSvg(): string { + return plotterTideSheet(DAY) +} + +/** Plotter Tide on blue-black night paper, for a dark window (scene-night.svg). */ +export function plotterTideNightSvg(): string { + return plotterTideSheet(NIGHT) +} diff --git a/plugins/theme-examples/hooks/scenes/snow-pines.ts b/plugins/theme-examples/hooks/scenes/snow-pines.ts new file mode 100644 index 00000000..c70b1ea9 --- /dev/null +++ b/plugins/theme-examples/hooks/scenes/snow-pines.ts @@ -0,0 +1,426 @@ +// Snow Pines: an ASCII forest in falling snow at dusk. A dark-window scene. +// Pure string building: no DOM, nothing read from outside, the same string on every call. + +const WIDTH = 1600 +const HEIGHT = 1000 + +type NeedleTone = 'shadow' | 'mid' | 'lit' +type Tone = NeedleTone | 'rim' | 'cap' + +interface Mark { + x: number + y: number + glyph: string +} + +interface Cell extends Mark { + tone: Tone +} + +interface Grid { + cellWidth: number + cellHeight: number + fontSize: number + weight: number +} + +interface Depth extends Grid { + rimChance: number + tile: Record<Tone, string> + glyph: Record<Tone, string> +} + +/** A pine: the column of its apex, the row of its foot, its height in rows. */ +type Stand = readonly [number, number, number] + +interface Wood { + from: number + to: number + tallest: number + chance: number +} + +interface SnowLayer { + id: string + seed: number + cellWidth: number + cellHeight: number + rows: number + seconds: readonly number[] + swaySeconds: number + density: number + everywhere: boolean + full: number + none: number + glyphs: string + fontSize: number + colour: string + opacity: number +} + +/** + * The three depths of forest: each has its own character grid, so far trees are small type and near trees large type. + * Every tree is built from cells, a coloured ground and a glyph per cell, like a terminal with background colours. + * Each depth has three needle values (shadow side, mid, lit side) and two snow values, so the light from the horizon models the trees. + */ +const FAR: Depth = { + cellWidth: 9, cellHeight: 11, fontSize: 10, weight: 700, rimChance: 0.5, + tile: { shadow: '#33336a', mid: '#3e4079', lit: '#4c5090', rim: '#6c70a6', cap: '#8a8ebe' }, + glyph: { shadow: '#565a96', mid: '#6a70a8', lit: '#8e94c8', rim: '#bcc1e6', cap: '#d6daf4' }, +} +const MIDDLE: Depth = { + cellWidth: 13, cellHeight: 16, fontSize: 15, weight: 700, rimChance: 0.65, + tile: { shadow: '#142d44', mid: '#1b4358', lit: '#275e68', rim: '#5a7396', cap: '#869fbe' }, + glyph: { shadow: '#44708a', mid: '#5a98a6', lit: '#78b6b0', rim: '#ccd6f2', cap: '#e8eeff' }, +} +const NEAR: Depth = { + cellWidth: 18, cellHeight: 22, fontSize: 21, weight: 700, rimChance: 0.75, + tile: { shadow: '#0c2832', mid: '#134048', lit: '#1a5456', rim: '#5a7396', cap: '#869fbe' }, + glyph: { shadow: '#3a7480', mid: '#4f9a96', lit: '#6cb4a6', rim: '#d0d9f2', cap: '#eef2ff' }, +} + +const NEEDLE_TONES: readonly NeedleTone[] = ['shadow', 'mid', 'lit'] + +/** A deterministic hash to 0..1, so every build is the same (nothing here is random at run time). */ +function hash(a: number, b: number, c: number): number { + let value = (a * 374761393 + b * 668265263 + c * 2147483647) | 0 + value = (value ^ (value >>> 13)) * 1274126177 + value = value ^ (value >>> 16) + return ((value >>> 0) % 100000) / 100000 +} + +/** Half-width of a pine at a row below its apex: a slim taper, with boughs that flare within a tier and tuck back in at the next. */ +function halfWidthAt(row: number, tierLength: number): number { + if (row === 0) return 0 + const within = (row - 1) % tierLength + return Math.max(1, Math.round(row * 0.25 + within * 0.55)) +} + +/** + * One pine, cell by cell, on its depth's grid. Light comes from the horizon in the middle of the frame: the bough ends that face it are lit, + * the far edge and the row tucked under each tier's overhang are in shadow, and a bough cell with nothing above it carries snow. + */ +function pineCells(cells: Map<string, Cell>, apexColumn: number, baseRow: number, height: number, tierLength: number, seed: number, depth: Depth): void { + const boughRows = height - (height > 12 ? 2 : 1) + const towardLight = (apexColumn + 0.5) * depth.cellWidth < WIDTH / 2 ? 1 : -1 + for (let row = 0; row < height; row += 1) { + const y = baseRow - height + 1 + row + const isTrunk = row >= boughRows + const half = isTrunk ? 0 : halfWidthAt(row, tierLength) + const halfAbove = row === 0 ? -1 : halfWidthAt(row - 1, tierLength) + for (let offset = -half; offset <= half; offset += 1) { + const x = apexColumn + offset + const chance = hash(x, y, seed) + const isExposed = !isTrunk && Math.abs(offset) > halfAbove + const facing = offset * towardLight + const slash = (offset < 0 || (offset === 0 && row % 2 === 0)) ? '/' : '\\' + let glyph = row === 0 ? '^' : isTrunk ? '|' : slash + if (!isExposed && offset !== 0 && Math.abs(offset) < half && hash(x, y, seed + 2) < 0.1) glyph = ':' + const within = (row - 1) % tierLength + let tone: Tone = 'mid' + if (within === 0 && row > 1) tone = 'shadow' + if (half >= 2 && facing <= -half + (half > 4 ? 1 : 0)) tone = 'shadow' + if (facing > 0 && facing >= half - 1 && within > 0) tone = 'lit' + if (tone === 'shadow' && hash(x, y, seed + 1) < 0.15) tone = 'mid' + if (isTrunk) tone = 'shadow' + if (isExposed && chance < depth.rimChance) tone = chance < 0.08 || row === 0 ? 'cap' : 'rim' + cells.set(`${x},${y}`, { x, y, glyph, tone }) + } + } +} + +function escapeGlyph(glyph: string): string { + return glyph === '<' ? '<' : glyph === '&' ? '&' : glyph +} + +/** + * ONE text element for a whole list of glyphs, with a per-glyph x list and y list, so every glyph sits on its grid cell whatever the font. + * One element, not one per row: what a browser pays for is the number of text elements, far more than the number of glyphs in them. + */ +function glyphRows(list: readonly Mark[], grid: Grid, colour: string, opacity: number): string { + if (list.length === 0) return '' + const sorted = [...list].sort((left, right) => left.y - right.y || left.x - right.x) + const xs = sorted.map(cell => cell.x * grid.cellWidth + grid.cellWidth / 2).join(' ') + const ys = sorted.map(cell => cell.y * grid.cellHeight + Math.round(grid.cellHeight * 0.8)).join(' ') + const text = sorted.map(cell => escapeGlyph(cell.glyph)).join('') + const faint = opacity < 1 ? ` fill-opacity="${opacity}"` : '' + return `<text x="${xs}" y="${ys}" fill="${colour}"${faint} style="font-size:${grid.fontSize}px;font-weight:${grid.weight}">${text}</text>` +} + +/** The coloured ground behind a list of cells: one rectangle per run of neighbours in a row, with no gaps, so there is no mesh of grid lines. */ +function tiles(list: readonly Mark[], grid: Grid, colour: string, opacity: number): string { + const rows = new Map<number, number[]>() + for (const cell of list) { + const row = rows.get(cell.y) + if (row) row.push(cell.x) + else rows.set(cell.y, [cell.x]) + } + let path = '' + for (const [y, columns] of rows) { + columns.sort((left, right) => left - right) + let start = columns[0] ?? 0 + let previous = start + for (let index = 1; index <= columns.length; index += 1) { + const column = columns[index] + if (column !== undefined && column === previous + 1) { + previous = column + continue + } + const width = (previous - start + 1) * grid.cellWidth + path += `M${start * grid.cellWidth} ${y * grid.cellHeight}h${width}v${grid.cellHeight}h-${width}z` + if (column === undefined) break + start = column + previous = column + } + } + const faint = opacity < 1 ? ` fill-opacity="${opacity}"` : '' + return `<path d="${path}" fill="${colour}"${faint}/>` +} + +function cellsOfTone(all: readonly Cell[], tone: Tone): Cell[] { + return all.filter(cell => cell.tone === tone) +} + +/** Which of the four waves of settling snow a snowy cell belongs to. */ +function waveOf(cell: Mark, seed: number): number { + return Math.floor(hash(cell.x, cell.y, seed + 5) * 4) +} + +/** A stand of pines at one depth: shadow ground under everything, mid and lit over it, a glyph in every cell, then the snowy cells, which arrive in four waves. */ +function forest(stands: readonly Stand[], depth: Depth, tierLength: number, seed: number): string { + const cells = new Map<string, Cell>() + for (const [column, baseRow, height] of stands) pineCells(cells, column, baseRow, height, tierLength, seed, depth) + const all = [...cells.values()] + const rims = cellsOfTone(all, 'rim') + const caps = cellsOfTone(all, 'cap') + let frost = '' + for (let which = 0; which < 4; which += 1) { + const rim = rims.filter(cell => waveOf(cell, seed) === which) + const cap = caps.filter(cell => waveOf(cell, seed) === which) + frost += `<g class="settle" style="animation-delay:-${which * 14}s">${tiles(rim, depth, depth.tile.rim, 1)}${tiles(cap, depth, depth.tile.cap, 1)}${glyphRows(rim, depth, depth.glyph.rim, 1)}${glyphRows(cap, depth, depth.glyph.cap, 1)}</g>` + } + // each cell's ground is painted once, in its own value, so the grounds can be faint without a group opacity + const shaded = cellsOfTone(all, 'shadow').concat(rims, caps) + return tiles(shaded, depth, depth.tile.shadow, 0.78) + tiles(cellsOfTone(all, 'mid'), depth, depth.tile.mid, 0.78) + tiles(cellsOfTone(all, 'lit'), depth, depth.tile.lit, 0.78) + + NEEDLE_TONES.map(tone => glyphRows(cellsOfTone(all, tone), depth, depth.glyph[tone], 1)).join('') + + // under the frost a snowy cell is an ordinary needle cell, so a bough never shows a hole while its snow is away + glyphRows(rims.concat(caps), depth, depth.glyph.mid, 1) + frost +} + +/** How far a point is from the reading column, 0 in the middle of the window and 1 at the left and right edges. */ +function edgeness(x: number): number { + const fromCentre = Math.abs(x - WIDTH * 0.51) / (WIDTH * 0.5) + return Math.min(1, Math.max(0, (fromCentre - 0.4) / 0.5)) +} + +/** Feathering for the brighter snow and the flake glyphs: 1 at the far left and right, falling in a straight line to 0 at the edge of the reading column. */ +function feather(x: number, full: number, none: number): number { + const left = (none - x) / (none - full) + const right = (x - (WIDTH - none + 30)) / (none - full) + return Math.min(1, Math.max(0, left, right)) +} + +/** The crests of the three snow hills, back to front. The whole ground leans: higher on the left, lower on the right. */ +function lean(x: number): number { + return (x - WIDTH / 2) * 0.03 +} +function backCrest(x: number): number { + return 716 - edgeness(x) * 52 + Math.sin(x * 0.0061 + 0.4) * 9 + lean(x) +} +function middleCrest(x: number): number { + return 790 - edgeness(x) * 30 + Math.sin(x * 0.0043 + 2.2) * 13 + lean(x) +} +function frontCrest(x: number): number { + return 880 - edgeness(x) * 20 + Math.sin(x * 0.0035 + 4.6) * 12 + lean(x) +} + +const FAR_WOODS: readonly Wood[] = [ + { from: -2, to: 52, tallest: 11, chance: 0.4 }, + { from: 58, to: 74, tallest: 5, chance: 0.34 }, + { from: 131, to: 141, tallest: 6, chance: 0.4 }, + { from: 147, to: 180, tallest: 8, chance: 0.4 }, +] + +/** The far tree line: a wood on the left, a smaller one on the right, and one small copse left of centre. */ +function farForest(): string { + const stands: Stand[] = [] + for (const wood of FAR_WOODS) { + for (let column = wood.from; column <= wood.to; column += 1) { + if (hash(column, 3, 11) > wood.chance) continue + const x = column * FAR.cellWidth + const middle = (wood.from + wood.to) / 2 + const taper = 1 - Math.abs(column - middle) / ((wood.to - wood.from) / 2 + 1) * 0.5 + const height = 3 + Math.floor(hash(column, 5, 11) * (wood.tallest - 3) * taper) + stands.push([column, Math.round(backCrest(x) / FAR.cellHeight) + Math.floor(hash(column, 7, 11) * 2), height]) + } + } + return forest(stands, FAR, 3, 17) +} + +/** Column of the apex and height in rows of each middle and near pine; the foot row is worked out from the ground. */ +const MIDDLE_PINES: ReadonlyArray<readonly [number, number]> = [ + [3, 13], [12, 16], [20, 11], + [121, 14], [113, 10], [98, 13], +] +const NEAR_PINES: ReadonlyArray<readonly [number, number]> = [ + [1, 25], [9, 19], [-4, 15], + [87, 21], [82, 14], +] + +/** Middle trees: a group on the left, a lighter one on the right, none under the reading column. */ +function middleForest(): string { + const stands = MIDDLE_PINES.map<Stand>(([column, height], index) => { + const x = column * MIDDLE.cellWidth + return [column, Math.round((middleCrest(x) + 34) / MIDDLE.cellHeight) + Math.floor(hash(index, 2, 23) * 2), height] + }) + return forest(stands, MIDDLE, 3, 29) +} + +/** Near trees: a low dark wall on the left, a lower one on the right, so the frame is not a mirror; their feet are below the window. */ +function nearForest(): string { + const stands = NEAR_PINES.map<Stand>(([column, height], index) => [column, 47 + Math.floor(hash(index, 9, 31) * 2), height]) + return forest(stands, NEAR, 4, 37) +} + +const CREST_GLYPHS = '_-_~_-' +const DRIFT_GLYPHS = '..-,_\'' + +/** The snow field is made of characters: rows of drift glyphs on the far grid, thick at each hill's crest and thinning below it, sparse under the reading column. */ +function hillMarks(crestAt: (x: number) => number, colour: string, opacity: number, rowsDeep: number, seed: number): string { + const marks: Mark[] = [] + const columns = Math.ceil(WIDTH / FAR.cellWidth) + for (let column = 0; column < columns; column += 1) { + const x = (column + 0.5) * FAR.cellWidth + const crestRow = Math.ceil(crestAt(x) / FAR.cellHeight) + const outside = feather(x, 300, 520) + const thin = 0.12 + 0.6 * outside + for (let below = 0; below < rowsDeep; below += 1) { + const pick = hash(column, below, seed) + const limit = (below === 0 ? 0.8 : 0.5 - below * (0.4 / rowsDeep)) * thin + if (pick > limit || (below > 0 && outside === 0)) continue + const which = Math.floor(hash(column, below, seed + 1) * 6) + const glyph = (below === 0 ? CREST_GLYPHS[which] : DRIFT_GLYPHS[which]) ?? '.' + marks.push({ x: column, y: crestRow + below, glyph }) + } + } + return glyphRows(marks, FAR, colour, opacity) +} + +/** A hill's body: one long smooth drift. The three drifts are close in value so no seam runs behind the text. */ +function hillBody(crestAt: (x: number) => number, fill: string, opacity: number): string { + let path = `M0 ${HEIGHT}V${crestAt(0).toFixed(1)}` + for (let x = 20; x <= WIDTH; x += 20) path += `L${x} ${crestAt(x).toFixed(1)}` + return `<path d="${path}V${HEIGHT}z" fill="${fill}" fill-opacity="${opacity}"/>` +} + +function snowField(): string { + return hillBody(backCrest, 'url(#field)', 1) + hillBody(middleCrest, '#433f76', 0.5) + hillBody(frontCrest, '#3b386e', 0.5) + + hillMarks(backCrest, '#c6caee', 0.4, 3, 41) + + hillMarks(middleCrest, '#a9aedc', 0.36, 4, 43) + + hillMarks(frontCrest, '#8388c0', 0.36, 5, 47) +} + +/** + * One layer of falling snow. The fall is continuous, and each of a layer's few bands of columns falls at its own speed. + * Every band is ONE text element (its flakes twice over, a screen apart, so the loop has no seam) that carries both motions itself: + * the fall on `transform`, the sideways sway on `translate`. Each moving element costs the browser a window-sized layer every frame, + * so there are six of them in all, and the two brighter layers, which only fall near the edges, are split left and right to keep them narrow. + */ +function snowLayer(layer: SnowLayer): string { + const columns = Math.ceil(WIDTH / layer.cellWidth) + 3 + const bandCount = layer.seconds.length + const fall = layer.rows * layer.cellHeight + const bands = layer.seconds.map((): Mark[] => []) + for (let row = 0; row < layer.rows; row += 1) { + for (let column = -2; column < columns; column += 1) { + const x = column * layer.cellWidth + const density = layer.everywhere ? layer.density : layer.density * feather(x, layer.full, layer.none) + if (hash(column, row, layer.seed) >= density) continue + const dotOnly = hash(column, row, layer.seed + 3) >= feather(x, 240, 470) + const glyph = dotOnly ? '.' : layer.glyphs[Math.floor(hash(column, row, layer.seed + 1) * layer.glyphs.length)] ?? '.' + const which = layer.everywhere ? Math.floor(hash(column, 0, layer.seed + 2) * bandCount) : x < WIDTH / 2 ? 0 : 1 + const band = bands[which] + const baseline = row * layer.cellHeight + Math.round(layer.cellHeight * 0.8) + if (band) band.push({ x: x + layer.cellWidth / 2, y: baseline - fall, glyph }, { x: x + layer.cellWidth / 2, y: baseline, glyph }) + } + } + return bands.map((flakes, which) => { + const seconds = layer.seconds[which] ?? 60 + const xs = flakes.map(flake => flake.x).join(' ') + const ys = flakes.map(flake => flake.y).join(' ') + const text = flakes.map(flake => flake.glyph).join('') + const fallDelay = (seconds * (0.23 + which * 0.31)).toFixed(2) + return `<text class="${layer.id}" x="${xs}" y="${ys}" style="animation:fall${layer.id} ${seconds}s linear -${fallDelay}s infinite,sway ${layer.swaySeconds}s ease-in-out -${which * 7 + layer.seed % 10}s infinite alternate">${text}</text>` + }).join('') +} + +/** Three layers of snow. Only the faint one falls everywhere; the other two keep to the edges and never cross the reading column. */ +const SNOW_LAYER_FAINT: SnowLayer = { id: 'a', seed: 51, cellWidth: 14, cellHeight: 20, rows: 52, seconds: [61], swaySeconds: 19, density: 0.011, everywhere: true, full: 0, none: 0, glyphs: '*.*\'.+', fontSize: 17, colour: '#b4bcec', opacity: 0.34 } +const SNOW_LAYER_MIDDLE: SnowLayer = { id: 'b', seed: 61, cellWidth: 16, cellHeight: 20, rows: 52, seconds: [43, 53], swaySeconds: 14.5, density: 0.06, everywhere: false, full: 0, none: 600, glyphs: '.*.*.+\'*', fontSize: 17, colour: '#c3cbf2', opacity: 0.5 } +const SNOW_LAYER_BRIGHT: SnowLayer = { id: 'c', seed: 71, cellWidth: 22, cellHeight: 26, rows: 40, seconds: [31, 38], swaySeconds: 11.5, density: 0.06, everywhere: false, full: 0, none: 470, glyphs: '*.*+', fontSize: 22, colour: '#d3daf8', opacity: 0.55 } +const SNOW_LAYERS: readonly SnowLayer[] = [SNOW_LAYER_FAINT, SNOW_LAYER_MIDDLE, SNOW_LAYER_BRIGHT] + +const CABIN_SHAPE: readonly string[] = [' /^\\ ', '/___\\', '|[] |'] + +/** The one accent: a small cabin on the middle grid between the right-hand trees: a pitched snowy roof, a dark wall, two amber glyphs for its lit window. */ +function cabin(): string { + const column = 103 + const row = Math.round((middleCrest(column * MIDDLE.cellWidth) + 8) / MIDDLE.cellHeight) + const roof: Mark[] = [] + const wall: Mark[] = [] + const pane: Mark[] = [] + CABIN_SHAPE.forEach((line, y) => { + for (let x = 0; x < line.length; x += 1) { + const glyph = line[x] ?? ' ' + if (glyph === ' ' && y < 2) continue + const cell = { x: column + x, y: row - 2 + y, glyph } + if (y < 2) roof.push(cell) + else if (glyph === '[' || glyph === ']') pane.push(cell) + else wall.push(cell) + } + }) + const left = column * MIDDLE.cellWidth + const top = row * MIDDLE.cellHeight + return `<ellipse class="glow" cx="${left + 26}" cy="${top + 20}" rx="44" ry="12" fill="url(#lamp)"/>` + + tiles(wall.concat(pane), MIDDLE, '#1c1c46', 1) + tiles(roof, MIDDLE, '#5a5c94', 1) + + glyphRows(roof, MIDDLE, '#d0d4f2', 0.9) + glyphRows(wall.filter(cell => cell.glyph !== ' '), MIDDLE, '#3c3f74', 1) + + `<g class="glow">${glyphRows(pane, MIDDLE, '#f0a040', 1)}</g>` +} + +export function snowPinesSvg(): string { + const fallFrames = SNOW_LAYERS.map(layer => `@keyframes fall${layer.id}{from{transform:translateY(0)}to{transform:translateY(${layer.rows * layer.cellHeight}px)}}`).join('') + const layerStyles = SNOW_LAYERS.map(layer => `.${layer.id}{fill:${layer.colour};fill-opacity:${layer.opacity};font-size:${layer.fontSize}px}`).join('') + const style = ` +text{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;text-anchor:middle} +${layerStyles} +.glow{animation:glow 7s ease-in-out infinite alternate} +.settle{animation:settle 160s linear infinite} +.dusk{animation:dusk 170s ease-in-out infinite alternate} +${fallFrames} +@keyframes sway{from{translate:-28px 0}to{translate:14px 0}} +@keyframes glow{from{fill-opacity:.7}to{fill-opacity:1}} +@keyframes settle{0%{fill-opacity:.1}12%{fill-opacity:.4}56%{fill-opacity:1}86%{fill-opacity:1}100%{fill-opacity:.1}} +@keyframes dusk{from{transform:translateX(-420px);fill-opacity:.5}to{transform:translateX(300px);fill-opacity:1}} +@media (prefers-reduced-motion: reduce){*{animation:none!important}}` + + const defs = ` +<linearGradient id="sky" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#181a46"/><stop offset="0.22" stop-color="#1c1d4d"/><stop offset="0.4" stop-color="#242253"/><stop offset="0.52" stop-color="#30295b"/><stop offset="0.6" stop-color="#3c3162"/><stop offset="0.67" stop-color="#483967"/><stop offset="0.74" stop-color="#52406b"/></linearGradient> +<linearGradient id="field" x1="0" y1="0" x2="0" y2="1"><stop offset="0.66" stop-color="#4b4679"/><stop offset="0.82" stop-color="#403c72"/><stop offset="1" stop-color="#37346a"/></linearGradient> +<radialGradient id="rose" cx="0.5" cy="0.5" r="0.5"><stop offset="0" stop-color="#a8607a" stop-opacity="0.32"/><stop offset="0.2" stop-color="#a45e7a" stop-opacity="0.27"/><stop offset="0.4" stop-color="#9e5c7a" stop-opacity="0.2"/><stop offset="0.6" stop-color="#985a7a" stop-opacity="0.12"/><stop offset="0.8" stop-color="#92587a" stop-opacity="0.05"/><stop offset="1" stop-color="#8c567a" stop-opacity="0"/></radialGradient> +<radialGradient id="lamp" cx="0.5" cy="0.5" r="0.5"><stop offset="0" stop-color="#ffb65c" stop-opacity="0.16"/><stop offset="1" stop-color="#ffb65c" stop-opacity="0"/></radialGradient> +<radialGradient id="hush" cx="0.5" cy="0.5" r="0.5"><stop offset="0.55" stop-color="#1b1c4b" stop-opacity="0.85"/><stop offset="1" stop-color="#1b1c4b" stop-opacity="0"/></radialGradient>` + + return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${WIDTH} ${HEIGHT}" width="100%" height="100%" preserveAspectRatio="xMidYMid slice" font-family="monospace" color="#888"><style>${style}</style><defs>${defs}</defs> +<rect width="${WIDTH}" height="${HEIGHT}" fill="url(#sky)"/> +<g class="dusk"><ellipse cx="1040" cy="760" rx="760" ry="240" fill="url(#rose)"/></g> +${farForest()} +${snowField()} +${cabin()} +${snowLayer(SNOW_LAYER_FAINT)} +${middleForest()} +${snowLayer(SNOW_LAYER_MIDDLE)} +${nearForest()} +${snowLayer(SNOW_LAYER_BRIGHT)} +<ellipse cx="1370" cy="150" rx="260" ry="170" fill="url(#hush)"/> +</svg>` +} diff --git a/plugins/theme-examples/hooks/scenes/teletext-clouds.ts b/plugins/theme-examples/hooks/scenes/teletext-clouds.ts new file mode 100644 index 00000000..15db67ff --- /dev/null +++ b/plugins/theme-examples/hooks/scenes/teletext-clouds.ts @@ -0,0 +1,251 @@ +// Block Clouds (id teletext-clouds): a night weather page with the text taken out. +// Cloud banks built from blocks on teletext's grid drift in from the sides. Pure string building. + +// One grid for everything: 80 blocks across (teletext's 40 characters, 2 blocks each). +// Teletext's separated graphics leave a gap around every block; here it is kept to a hairline. +const BLOCK_WIDTH = 20 +const BLOCK_HEIGHT = 16 +const GAP = 0.5 +const COLUMNS = 80 +const ROWS = 63 + +/** Teletext's blue, cyan, magenta and yellow at reduced value, so nothing shouts behind text. */ +const INK = { + belly: '#1a2788', + body: '#2636b4', + bodyLight: '#2c3fc6', + bodyHigh: '#3346dc', + top: '#4cc4d8', + topLit: '#9af0f8', + rose: '#a84e80', + deck: '#182568', + land: '#111a4c', + landTop: '#27367e', + sun: '#f0cf52', + sunShade: '#d2b040', + star: '#cfd8ff', +} + +type InkName = keyof typeof INK + +type Block = { column: number; row: number } + +type Hump = { x: number; y: number; rx: number; ry: number } + +type Layer = readonly [InkName, Block[]] + +type DriftingBank = { keyframes: string; svg: string } + +/** The one bank shape, measured back from its inner tip; every bank is this shape scaled and placed. */ +const HUMPS: readonly Hump[] = [ + { x: -430, y: -22, rx: 430, ry: 40 }, + { x: -350, y: -68, rx: 96, ry: 60 }, + { x: -236, y: -42, rx: 60, ry: 36 }, + { x: -150, y: -54, rx: 72, ry: 50 }, + { x: -86, y: -36, rx: 40, ry: 34 }, + { x: -24, y: -10, rx: 30, ry: 12 }, +] + +const STAR_PERIODS: readonly number[] = [7, 11, 13, 17, 19] + +/** A deterministic stand-in for a random number in 0..1, so every build is the same. */ +function hash(x: number, y: number, seed: number): number { + let value = (x * 374761393 + y * 668265263 + seed * 2147483647) | 0 + value = Math.imul(value ^ (value >>> 13), 1274126177) + value = value ^ (value >>> 16) + return (value >>> 0) / 4294967296 +} + +function keyOf(column: number, row: number): string { + return `${column},${row}` +} + +function blockOfKey(key: string): Block { + const parts = key.split(',') + return { column: Number(parts[0] ?? 0), row: Number(parts[1] ?? 0) } +} + +function listOf(blocks: ReadonlySet<string>): Block[] { + return [...blocks].map(blockOfKey) +} + +function blockPath(list: readonly Block[]): string { + const width = BLOCK_WIDTH - GAP + const height = BLOCK_HEIGHT - GAP + return list.map(block => `M${block.column * BLOCK_WIDTH + 1} ${block.row * BLOCK_HEIGHT + 1}h${width}v${height}h-${width}z`).join('') +} + +/** One path per ink, in the order given, so later inks paint over earlier ones. */ +function paths(layers: readonly Layer[]): string { + let out = '' + for (const [ink, list] of layers) { + if (list.length > 0) out += `<path d="${blockPath(list)}" fill="${INK[ink]}"/>` + } + return out +} + +function insideSomeHump(x: number, y: number, tipX: number, baseY: number, scale: number, direction: number): boolean { + for (const hump of HUMPS) { + const dx = (x - (tipX + hump.x * scale * direction)) / (hump.rx * scale) + const dy = (y - (baseY + hump.y * scale)) / (hump.ry * scale) + if (dx * dx + dy * dy <= 1) return true + } + return false +} + +/** + * A cloud bank: a union of ellipses (humps) sampled at block centres and cut at its base row. + * The underside is lumpy (some characters lose their lowest row) and rounded at its ends + * (the last row is drawn in two blocks from every end of the row above it, the row before by one). + */ +function bankBlocks(tipX: number, baseRow: number, scale: number, direction: number): Set<string> { + const baseY = baseRow * BLOCK_HEIGHT + const blocks = new Set<string>() + for (let row = 0; row < baseRow; row += 1) { + for (let column = -34; column < COLUMNS + 34; column += 1) { + if (row === baseRow - 1 && hash(Math.floor(column / 2), 1, baseRow) < 0.35) continue + const x = column * BLOCK_WIDTH + BLOCK_WIDTH / 2 + const y = row * BLOCK_HEIGHT + BLOCK_HEIGHT / 2 + if (insideSomeHump(x, y, tipX, baseY, scale, direction)) blocks.add(keyOf(column, row)) + } + } + for (const block of listOf(blocks)) { + const inset = block.row === baseRow - 1 ? 2 : block.row === baseRow - 2 ? 1 : 0 + if (inset === 0) continue + if (!blocks.has(keyOf(block.column - inset, block.row - inset)) || !blocks.has(keyOf(block.column + inset, block.row - inset))) blocks.delete(keyOf(block.column, block.row)) + } + return blocks +} + +/** + * Shades a cloud into a form: a lit top edge one block deep along the whole top, three body tones, and a darker belly row. + * Slow things keep it alive without moving it: a brighter light travels along the top edge, and a few blocks + * on the top edge come and go so the outline reshapes. The big right bank's belly row is rose, lit from below by the dusk. + */ +function cloud(blocks: ReadonlySet<string>, seed: number, warm: boolean): string { + const belly: Block[] = [] + const rose: Block[] = [] + const body: Block[] = [] + const bodyLight: Block[] = [] + const bodyHigh: Block[] = [] + const top: Block[] = [] + const travelling: Block[][] = [[], [], [], [], []] + let puffs = '' + for (const block of listOf(blocks)) { + const isTop = !blocks.has(keyOf(block.column, block.row - 1)) + const isBelly = !blocks.has(keyOf(block.column, block.row + 1)) + const chance = hash(Math.floor(block.column / 2), Math.floor(block.row / 3), seed) + if (isTop) { + top.push(block) + travelling[Math.floor(block.column / 3 + 400) % 5]?.push(block) + if (hash(block.column, block.row, seed + 1) < 0.08) { + const above = [{ column: block.column, row: block.row - 1 }] + puffs += `<g class="puff" style="animation-duration:${16 + (block.column % 5) * 3}s;animation-delay:-${(block.column * 7) % 23}s"><path d="${blockPath([block])}" fill="${INK.body}"/><path d="${blockPath(above)}" fill="${INK.top}"/></g>` + } + } else if (isBelly) (warm ? rose : belly).push(block) + else if (!blocks.has(keyOf(block.column, block.row - 2))) bodyHigh.push(block) + else if (!blocks.has(keyOf(block.column, block.row - 4)) || chance < 0.15) bodyLight.push(block) + else body.push(block) + } + const light = travelling + .map((list, group) => (list.length === 0 ? '' : `<path class="travel" style="animation-delay:-${(group * 1.4 + (seed % 5)).toFixed(1)}s" d="${blockPath(list)}" fill="${INK.topLit}"/>`)) + .join('') + return paths([['belly', belly], ['rose', rose], ['body', body], ['bodyLight', bodyLight], ['bodyHigh', bodyHigh], ['top', top]]) + puffs + light +} + +/** A bank slides a whole block at a time between two ends and back; at rest it sits midway. */ +function drifting(name: string, blocksEachWay: number, secondsPerBlock: number, delay: number, inner: string): DriftingBank { + const reach = blocksEachWay * BLOCK_WIDTH + const steps = blocksEachWay * 2 + return { + keyframes: `@keyframes ${name}{from{transform:translateX(-${reach}px)}to{transform:translateX(${reach}px)}}`, + svg: `<g style="animation:${name} ${steps * secondsPerBlock}s steps(${steps}) -${delay}s infinite alternate">${inner}</g>`, + } +} + +/** + * Stars are quarter blocks on the grid in the outer quarters of the upper sky; a few are yellow, and those under the sidebar are dim. + * Each twinkles on its own prime period and phase, dimming to about half and back. + */ +function stars(): string { + let out = '' + for (let index = 0; index < 26; index += 1) { + const column = Math.floor(hash(index, 2, 71) * 17) + (index % 2 === 0 ? 1 : 62) + const row = Math.floor(hash(index, 3, 71) * 26) + const x = column * BLOCK_WIDTH + const y = row * BLOCK_HEIGHT + const shape = `M${x + 5} ${y + 4}h10v8h-10z` + const fill = index % 5 === 2 ? INK.sun : INK.star + out += `<path class="star" style="animation-duration:${STAR_PERIODS[index % 5] ?? 7}s;animation-delay:-${(hash(index, 5, 71) * 19).toFixed(1)}s" d="${shape}" fill="${fill}" opacity="${(index % 2 === 0 ? 0.3 : 0.5 + hash(index, 4, 71) * 0.4).toFixed(2)}"/>` + } + return out +} + +/** Land in the bottom left corner only, in broad steps; nothing under the conversation or the prompt box. */ +function land(heights: readonly number[], firstColumn: number): string { + const body: Block[] = [] + const top: Block[] = [] + heights.forEach((height, index) => { + for (let dx = 0; dx < 4; dx += 1) { + for (let row = ROWS - height; row < ROWS; row += 1) (row === ROWS - height ? top : body).push({ column: firstColumn + index * 4 + dx, row }) + } + }) + return paths([['land', body], ['landTop', top]]) +} + +/** + * The sun band of a weather page, turned into a night light: a small disc of solid yellow blocks beside the cards, + * with a bite of sky taken out of its upper left so it is a moon. + */ +function disc(): string { + const bright: Block[] = [] + const shade: Block[] = [] + for (let row = 8; row < 32; row += 1) { + for (let column = 56; column < COLUMNS; column += 1) { + const dx = column * BLOCK_WIDTH + BLOCK_WIDTH / 2 - 1350 + const dy = row * BLOCK_HEIGHT + BLOCK_HEIGHT / 2 - 312 + const distance = Math.sqrt(dx * dx + dy * dy) + const bitten = Math.sqrt((dx + 44) * (dx + 44) + (dy + 34) * (dy + 34)) <= 56 + if (distance <= 60 && !bitten) (dy > 30 ? shade : bright).push({ column, row }) + } + } + return paths([['sun', bright], ['sunShade', shade]]) +} + +export function teletextCloudsSvg(): string { + // Two banks only: the big one low on the right, and a smaller echo low on the left. They breathe in and out in turn: + // one block every 8 s, fourteen blocks from end to end, so two minutes apart the picture is plainly different. + const banks = [ + drifting('driftA', 7, 8, 112, cloud(bankBlocks(300, 44, 1.25, 1), 5, false)), + drifting('driftB', 7, 8, 112, cloud(bankBlocks(1340, 56, 1.9, -1), 11, true)), + ] + + // One far deck runs the whole width low in the window, a few percent lighter than the sky, so the middle is a place and not a void. + const deckBlocks = new Set([...bankBlocks(1500, 47, 1.6, 1), ...bankBlocks(100, 47, 1.6, -1)]) + const deck = `<g style="animation:driftDeck 360s steps(24) -90s infinite alternate"><path d="${blockPath(listOf(deckBlocks))}" fill="${INK.deck}"/></g>` + + const style = ` +.travel{opacity:0;animation:travel 7s ease-in-out infinite} +.puff{animation:puff 16s steps(1) infinite} +.star{animation:star 9s steps(2) infinite} +@keyframes travel{0%,30%,100%{opacity:0}12%{opacity:1}} +@keyframes puff{0%,55%{opacity:1}56%,100%{opacity:0}} +@keyframes star{0%,100%{opacity:1}50%{opacity:.5}} +${banks.map(each => each.keyframes).join('\n')} +@keyframes driftDeck{from{transform:translateX(-240px)}to{transform:translateX(240px)}} +@media (prefers-reduced-motion: reduce){*{animation:none!important}}` + + // The banks dissolve while they move in under the conversation: a fixed mask fades them out between the panels and the text. + const defs = `<linearGradient id="sky" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#0a1238"/><stop offset="0.6" stop-color="#14225c"/><stop offset="1" stop-color="#1b2b6e"/></linearGradient> +<linearGradient id="edges" x1="0" y1="0" x2="1" y2="0"><stop offset="0.16" stop-color="#fff"/><stop offset="0.255" stop-color="#fff" stop-opacity="0"/><stop offset="0.76" stop-color="#fff" stop-opacity="0"/><stop offset="0.83" stop-color="#fff"/></linearGradient> +<mask id="fade" maskUnits="userSpaceOnUse" x="0" y="0" width="1600" height="1000"><rect width="1600" height="1000" fill="url(#edges)"/></mask>` + + return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1600 1000" width="100%" height="100%" preserveAspectRatio="xMidYMid slice" font-family="monospace" color="#888"><style>${style}</style><defs>${defs}</defs> +<rect width="1600" height="1000" fill="url(#sky)"/> +${stars()} +${disc()} +${deck} +<g mask="url(#fade)">${banks.map(each => each.svg).join('\n')}</g> +${land([9, 8, 6, 5, 3, 2], -4)} +</svg>` +} diff --git a/plugins/theme-examples/hooks/scenes/vector-range.ts b/plugins/theme-examples/hooks/scenes/vector-range.ts new file mode 100644 index 00000000..d46861b4 --- /dev/null +++ b/plugins/theme-examples/hooks/scenes/vector-range.ts @@ -0,0 +1,382 @@ +// Vector Range: a wireframe vector display. Phosphor line mountains at the left and right thirds, +// a perspective ground grid creeping toward the viewer, a small crescent. Green structure on black. +// The beam keeps retracing the ridges like a radar tube's phosphor: an amber flash at the head, a long green tail decaying behind it. +// Amber is used for the beam and the moon only. A wide, faint glow lifts the middle of the tube, where the text sits. +// Pure string building, no imports, the same string on every call. + +const WIDTH = 1600 +const HEIGHT = 1000 +const HORIZON = 745 +/** The grid's vanishing point sits under the right-hand cards, not under the prompt box. */ +const VANISH_X = 1230 +const SKY_TOP = '#030a08' +const SKY_LOW = '#071a15' +const GROUND_FAR = '#051210' +const GROUND_NEAR = '#030a08' +const HOT = '#9ff0dc' +const WARM = '#3fb89a' +const COLD = '#237a68' +const AMBER = '#ffb454' +const MOON_X = 1268 +const MOON_Y = 306 +const MOON_RADIUS = 30 + +/** A repeatable number in 0..1 from two integers, so every build draws the same range. */ +function hashUnit(index: number, salt: number): number { + let value = (Math.imul(index, 374761393) + Math.imul(salt, 668265263)) | 0 + value = Math.imul(value ^ (value >>> 13), 1274126177) + value ^= value >>> 16 + return (value >>> 0) / 4294967296 +} + +function round(value: number): number { + return Math.round(value * 10) / 10 +} + +/** A smooth bump: 1 at the centre, 0 at halfWidth away and beyond. */ +function lobe(x: number, centre: number, halfWidth: number): number { + const distance = Math.abs(x - centre) / halfWidth + if (distance >= 1) return 0 + const inner = 1 - distance * distance + return inner * inner +} + +/** A line drawn three times, widest and faintest first. That is the whole glow; no filter. */ +function glowLine(d: string, colour: string, width: number, opacity: number): string { + return ( + `<path d="${d}" stroke="${colour}" stroke-width="${round(width * 8)}" stroke-opacity="${Math.round(opacity * 7) / 100}"/>` + + `<path d="${d}" stroke="${colour}" stroke-width="${round(width * 3.2)}" stroke-opacity="${Math.round(opacity * 20) / 100}"/>` + + `<path d="${d}" stroke="${colour}" stroke-width="${width}" stroke-opacity="${opacity}"/>` + ) +} + +/** The beam's trace: a short amber head with a halo, and three longer, fainter green tails behind it, all ending at the head. */ +type TracePart = { name: string; length: number; width: number; opacity: number; colour: string } + +/** The longest tail; the beam must run this far past the ridge's end before it rests. */ +const LONGEST_TAIL = 0.42 + +const TRACE_PARTS: TracePart[] = [ + { name: 'tailLong', length: LONGEST_TAIL, width: 1.8, opacity: 0.4, colour: HOT }, + { name: 'tailMiddle', length: 0.24, width: 2, opacity: 0.6, colour: HOT }, + { name: 'tailShort', length: 0.12, width: 2.2, opacity: 0.85, colour: '#d6f2b0' }, + { name: 'halo', length: 0.07, width: 10, opacity: 0.2, colour: AMBER }, + { name: 'head', length: 0.07, width: 2.6, opacity: 1, colour: AMBER }, +] +const TRACE_TRAVEL = 1 + LONGEST_TAIL +/** Where the head sits along the ridge when motion is switched off. */ +const TRACE_REST_AT = 0.62 +/** Four beams share one cycle: each runs for a quarter of it while the other three rest. */ +const TRACE_CYCLE_SECONDS = 120 + +function trace(d: string, seconds: number, delay: number, shownAtRest: boolean): string { + // With motion switched off only one beam is left on the picture, caught mid-ridge; the others are parked past their ends. + return TRACE_PARTS.map( + part => + `<path d="${d}" pathLength="1" class="trace ${part.name}" stroke="${part.colour}" stroke-linecap="round" stroke-width="${part.width}" stroke-opacity="${part.opacity}" ` + + `stroke-dasharray="${part.length} 3" stroke-dashoffset="${Math.round((part.length - (shownAtRest ? TRACE_REST_AT : TRACE_TRAVEL)) * 1000) / 1000}" style="animation-duration:${seconds}s;animation-delay:-${delay}s"/>`, + ).join('') +} + +/** Keyframes for one trace part: its head runs from the path's start to past its end (so the tail leaves too), then rests + * for the other three quarters of the cycle, which is when the other beams run. */ +function traceKeyframes(): string { + return TRACE_PARTS.map(part => { + const start = part.length + const end = round((part.length - TRACE_TRAVEL) * 1000) / 1000 + return `@keyframes ${part.name}{0%{stroke-dashoffset:${start}}25%,100%{stroke-dashoffset:${end}}}` + }).join('') +} + +type MassifLayer = { + salt: number + step: number + maximumHeight: number + leftCentre: number + leftHalfWidth: number + leftScale: number + rightCentre: number + rightHalfWidth: number + fallLineAbove: number + fallLineOpacity: number + colour: string + width: number + opacity: number + dots: boolean + traceDelays: number[] + restBeamSide: number + seconds: number + delay: number + reach: number +} + +type RidgeVertex = { x: number; height: number; summit: boolean } + +/** A massif: tall at one or both edge thirds, sinking to nothing toward the middle so the reading column stays calm. */ +function massif(layer: MassifLayer): string { + const vertices: RidgeVertex[] = [] + let index = 0 + for (let x = -260; x <= WIDTH + 260; x += layer.step) { + const jitteredX = x + (hashUnit(index, layer.salt) - 0.5) * layer.step * 0.5 + const envelope = + lobe(jitteredX, layer.leftCentre, layer.leftHalfWidth) * layer.leftScale + + lobe(jitteredX, layer.rightCentre, layer.rightHalfWidth) + const saddle = index % 2 === 1 ? 0.6 : 1 + const roughness = 0.55 + 0.45 * hashUnit(index, layer.salt + 7) + const height = envelope * layer.maximumHeight * saddle * roughness + vertices.push({ x: round(jitteredX), height: round(height < 6 ? 0 : height), summit: index % 2 === 0 }) + index += 1 + } + const top = vertices.map(vertex => `${vertex.x} ${round(HORIZON - vertex.height)}`) + // The cover is painted with the sky itself, so a nearer ridge hides the lines of the ridges behind it. + const cover = `M${top.join('L')}L${WIDTH + 400} ${HORIZON}L-400 ${HORIZON}Z` + // The ridge line is drawn only where there is a ridge; flat stretches are left to the horizon. + let ridge = '' + let penDown = false + vertices.forEach((vertex, position) => { + const next = vertices[position + 1] + const flat = vertex.height === 0 && (!next || next.height === 0) + if (flat && !penDown) return + ridge += `${penDown ? 'L' : 'M'}${top[position] ?? ''}` + penDown = !flat + }) + // The beam only retraces what can be seen: the same ridge, cut a little outside the frame. + let traced = '' + penDown = false + vertices.forEach((vertex, position) => { + const next = vertices[position + 1] + const flat = vertex.height === 0 && (!next || next.height === 0) + const outside = vertex.x < -90 || vertex.x > WIDTH + 90 + if (outside || (flat && !penDown)) { + penDown = false + return + } + traced += `${penDown ? 'L' : 'M'}${top[position] ?? ''}` + penDown = !flat + }) + + // One fall line per summit: down to a shoulder, then on to the foot. Nothing crosses anything. + let fallLines = '' + let dots = '' + let litFaces = '' + vertices.forEach((vertex, position) => { + if (!vertex.summit || vertex.height < layer.fallLineAbove) return + // A spur leans well off the vertical, or it looks like a tent pole. + const side = hashUnit(position, layer.salt + 13) < 0.5 ? -1 : 1 + const lean = side * (0.55 + 0.4 * hashUnit(position, layer.salt + 19)) * layer.step + const shoulderX = round(vertex.x + lean * 0.5) + const shoulderY = round(HORIZON - vertex.height * (0.38 + 0.2 * hashUnit(position, layer.salt + 17))) + const footX = round(vertex.x + lean * 1.25) + const summitPoint = top[position] ?? '' + fallLines += `M${summitPoint}L${shoulderX} ${shoulderY}L${footX} ${HORIZON}` + dots += `M${summitPoint}h0` + // The face between the spur and the next saddle toward the moon catches a little light, so a peak has form. + const saddle = vertices[position + 1] + if (saddle) { + const faceFoot = Math.min(footX, saddle.x) + litFaces += `M${summitPoint}L${top[position + 1] ?? ''}L${faceFoot} ${HORIZON}L${Math.min(shoulderX, saddle.x)} ${shoulderY}Z` + } + }) + + return ( + `<g class="sway" style="animation-duration:${layer.seconds}s;animation-delay:-${layer.delay}s;--reach:${layer.reach}px">` + + `<path class="cover" d="${cover}"/>` + + `<path class="lit" d="${litFaces}"/>` + + `<path d="${fallLines}" stroke="${COLD}" stroke-width="1" stroke-opacity="${layer.fallLineOpacity}"/>` + + glowLine(ridge, layer.colour, layer.width, layer.opacity) + + // A vector beam dwells at the corners, so the summits are a little brighter than the lines between them. + (layer.dots ? `<path d="${dots}" stroke="${HOT}" stroke-width="2.6" stroke-linecap="round" stroke-opacity="0.6"/>` : '') + + // Dashes restart on every subpath, so each side of the massif gets its own beam, and they take turns. + traced + .split('M') + .filter(part => part.length > 0) + .map((part, side) => trace(`M${part}`, TRACE_CYCLE_SECONDS, layer.traceDelays[side] ?? 0, side === layer.restBeamSide)) + .join('') + + `</g>` + ) +} + +/** + * The far range: low rolling hills along the whole horizon. It repeats exactly every FAR_TILE units, + * so it can drift one way for ever. It is the only thing that crosses the reading column, so it is low and faint there. + */ +const FAR_STEP = 78 +const FAR_COUNT = 21 +const FAR_TILE = FAR_STEP * FAR_COUNT + +function farRange(): string { + let ridge = '' + for (let index = 0; index * FAR_STEP <= WIDTH + FAR_TILE + 200; index += 1) { + const wrapped = index % FAR_COUNT + const x = round(-100 + index * FAR_STEP + (hashUnit(wrapped, 3) - 0.5) * FAR_STEP * 0.4) + const height = round((wrapped % 2 === 1 ? 8 : 20) + hashUnit(wrapped, 5) * 20) + ridge += `${index === 0 ? 'M' : 'L'}${x} ${HORIZON - height}` + } + const cover = `${ridge}L${WIDTH + FAR_TILE + 300} ${HORIZON}L-100 ${HORIZON}Z` + return ( + `<g class="drift">` + + `<path class="cover" d="${cover}"/>` + + // One flat faint stroke: a paint that fades across the column would have to stand still while the ridge drifts under it. + `<path d="${ridge}" stroke="${COLD}" stroke-width="1.1" stroke-opacity="0.4"/>` + + `</g>` + ) +} + +/** Depth of the nearest cross line, and the count of cross lines travelling between the horizon and the viewer. */ +const NEAR_DEPTH = 1.5 +const CROSS_LINES = 11 +const CREEP_SECONDS = 12 + +function crossLineY(depth: number): number { + return round(HORIZON + ((HEIGHT - HORIZON) * NEAR_DEPTH) / depth) +} + +/** + * Every cross line walks the same road, from the horizon out past the bottom edge, one grid cell every CREEP_SECONDS. + * One set of keyframes holds the road; each line starts further along it. Perspective makes the road nonlinear, + * so the keyframes carry a stop per cell, and extra stops close to the viewer where it bends most. + */ +function creepKeyframes(): string { + const stops: string[] = [] + const total = CROSS_LINES + 1 + for (let step = 0; step <= total * 4; step += 1) { + const travelled = step / 4 + const depth = NEAR_DEPTH + CROSS_LINES - travelled + const nearViewer = depth < 5 + if (!nearViewer && step % 4 !== 0) continue + stops.push(`${round((travelled / total) * 100)}%{transform:translateY(${crossLineY(depth)}px)}`) + } + return `@keyframes creep{${stops.join('')}}` +} + +function groundGrid(): string { + let rays = '' + // The feet straddle the vanishing point so that no ray is a plain vertical, and the shallowest rays are left out: they only stack up. + for (let foot = -2200; foot <= 3400; foot += 400) { + rays += `M${VANISH_X} ${HORIZON}L${round(VANISH_X + foot * 1.2)} ${round(HORIZON + (HEIGHT - HORIZON) * 1.2)}` + } + let crossLines = '' + for (let line = 0; line <= CROSS_LINES; line += 1) { + const y = crossLineY(NEAR_DEPTH + line) + const delay = (CROSS_LINES - line) * CREEP_SECONDS + crossLines += `<path class="cross" transform="translate(0 ${y})" style="animation-delay:-${delay}s" d="M-100 0H1700"/>` + } + return ( + `<g stroke="url(#floorStroke)" stroke-width="1.2">` + + `<path d="${rays}" stroke-opacity="0.85"/>` + + crossLines + + `</g>` + + `<rect x="0" y="${HORIZON}" width="${WIDTH}" height="170" fill="url(#haze)"/>` + ) +} + +/** The moon: a proper crescent of two arcs at one weight, small, in the beam's amber. */ +function crescent(centreX: number, centreY: number, radius: number): string { + const topX = round(centreX - radius * 0.5) + const topY = round(centreY - radius * 0.866) + const bottomX = round(centreX + radius * 0.866) + const bottomY = round(centreY + radius * 0.5) + const inner = round(radius * 1.55) + const outline = `M${topX} ${topY}A${radius} ${radius} 0 0 1 ${bottomX} ${bottomY}A${inner} ${inner} 0 0 0 ${topX} ${topY}Z` + return glowLine(outline, AMBER, 1.25, 0.5) +} + +/** Stars in the left and right thirds only, three tiers; about one in four breathes, each on its own period. */ +function stars(): string { + let small = '' + let large = '' + let middling = '' + let breathing = '' + for (let index = 0; index < 64; index += 1) { + const onLeft = index % 2 === 0 + const x = round(onLeft ? 20 + hashUnit(index, 101) * 400 : 1205 + hashUnit(index, 101) * 375) + const y = round(16 + hashUnit(index, 103) * 470) + // No star may shine through the moon. + if (Math.hypot(x - MOON_X, y - MOON_Y) < MOON_RADIUS + 60) continue + if (index % 4 === 1) { + breathing += `<path class="breathe" style="animation-duration:${7 + (index % 5) * 3}s;animation-delay:-${round(hashUnit(index, 113) * 9)}s" d="M${x} ${y}h0"/>` + } else if (index % 3 === 0) { + large += `M${x} ${y}h0` + } else if (index % 3 === 2) { + middling += `M${x} ${y}h0` + } else { + small += `M${x} ${y}h0` + } + } + return ( + `<g stroke="${WARM}" stroke-linecap="round">` + + `<path d="${small}" stroke-width="1.9" stroke-opacity="0.45"/><path d="${middling}" stroke-width="2.4" stroke-opacity="0.6"/><path d="${large}" stroke-width="3" stroke-opacity="0.75"/>` + + `<g stroke-width="3.2">${breathing}</g></g>` + ) +} + +/** + * A stroke paint that is full at the edges and `low` across the reading column, with long soft shoulders. + * It does a mask's job without a mask: a mask over anything that moves makes the browser repaint an offscreen layer every frame. + */ +function fadeStroke(name: string, colour: string, low: number): string { + const half = round((1 + low) / 2) + return ( + `<linearGradient id="${name}" gradientUnits="userSpaceOnUse" x1="0" y1="0" x2="${WIDTH}" y2="0">` + + `<stop offset="0" stop-color="${colour}"/><stop offset="0.12" stop-color="${colour}"/><stop offset="0.24" stop-color="${colour}" stop-opacity="${half}"/>` + + `<stop offset="0.36" stop-color="${colour}" stop-opacity="${low}"/><stop offset="0.64" stop-color="${colour}" stop-opacity="${low}"/>` + + `<stop offset="0.76" stop-color="${colour}" stop-opacity="${half}"/><stop offset="0.88" stop-color="${colour}"/><stop offset="1" stop-color="${colour}"/></linearGradient>` + ) +} + +export function vectorRangeSvg(): string { + const style = ` +path{fill:none;stroke-linejoin:round} +.cover{fill:url(#sky);stroke:none} +.lit{fill:#9fe8cf;fill-opacity:.055;stroke:none} +.sway{animation:sway 120s ease-in-out infinite alternate} +.drift{animation:drift 520s linear infinite} +.cross{animation:creep ${(CROSS_LINES + 1) * CREEP_SECONDS}s linear infinite} +.trace{animation-timing-function:cubic-bezier(.3,.1,.7,.9);animation-iteration-count:infinite} +${TRACE_PARTS.map(part => `.${part.name}{animation-name:${part.name}}`).join('')} +.breathe{stroke-opacity:.55;animation:breathe 9s ease-in-out infinite} +@keyframes sway{from{transform:translateX(calc(var(--reach) * -1))}to{transform:translateX(var(--reach))}} +@keyframes drift{from{transform:translateX(0)}to{transform:translateX(-${FAR_TILE}px)}} +${traceKeyframes()} +@keyframes breathe{0%,100%{stroke-opacity:.12}50%{stroke-opacity:1}} +${creepKeyframes()} +@media (prefers-reduced-motion: reduce){*{animation:none!important}}` + + const defs = ` +<linearGradient id="sky" gradientUnits="userSpaceOnUse" x1="0" y1="0" x2="0" y2="${HORIZON}"><stop offset="0" stop-color="${SKY_TOP}"/><stop offset="1" stop-color="${SKY_LOW}"/></linearGradient> +<linearGradient id="ground" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="${GROUND_FAR}"/><stop offset="1" stop-color="${GROUND_NEAR}"/></linearGradient> +<linearGradient id="afterglow" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#16473a" stop-opacity="0"/><stop offset="0.35" stop-color="#16473a" stop-opacity="0.06"/><stop offset="0.65" stop-color="#16473a" stop-opacity="0.2"/><stop offset="0.85" stop-color="#16473a" stop-opacity="0.36"/><stop offset="1" stop-color="#16473a" stop-opacity="0.5"/></linearGradient> +<linearGradient id="haze" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="${GROUND_FAR}"/><stop offset="0.25" stop-color="${GROUND_FAR}" stop-opacity="0.95"/><stop offset="0.6" stop-color="${GROUND_FAR}" stop-opacity="0.5"/><stop offset="1" stop-color="${GROUND_FAR}" stop-opacity="0"/></linearGradient> +<radialGradient id="tube" cx="0.5" cy="0.5" r="0.5"><stop offset="0" stop-color="#1f5547" stop-opacity="0.34"/><stop offset="0.4" stop-color="#1f5547" stop-opacity="0.28"/><stop offset="0.75" stop-color="#1f5547" stop-opacity="0.16"/><stop offset="1" stop-color="#1f5547" stop-opacity="0"/></radialGradient> +${fadeStroke('floorStroke', '#2f9a82', 0.13)}${fadeStroke('horizonStroke', WARM, 0.12)}` + + const middleMassif = massif({ + salt: 11, step: 62, maximumHeight: 345, + leftCentre: 350, leftHalfWidth: 200, leftScale: 0.4, rightCentre: 1420, rightHalfWidth: 330, + fallLineAbove: 60, fallLineOpacity: 0.7, colour: WARM, width: 1.2, opacity: 0.36, dots: false, + traceDelays: [42, 102], restBeamSide: -1, seconds: 120, delay: 70, reach: 15, + }) + const nearMassif = massif({ + salt: 29, step: 50, maximumHeight: 200, + leftCentre: 60, leftHalfWidth: 340, leftScale: 0.6, rightCentre: 1590, rightHalfWidth: 310, + fallLineAbove: 40, fallLineOpacity: 0.6, colour: HOT, width: 1.3, opacity: 0.5, dots: true, + traceDelays: [72, 12], restBeamSide: 1, seconds: 120, delay: 5, reach: 40, + }) + + const horizonLine = glowLine(`M-100 ${HORIZON}H1700`, 'url(#horizonStroke)', 1, 0.28) + + return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${WIDTH} ${HEIGHT}" width="100%" height="100%" preserveAspectRatio="xMidYMid slice" font-family="monospace" color="#888"><style>${style}</style><defs>${defs}</defs> +<rect width="${WIDTH}" height="${HORIZON}" fill="url(#sky)"/> +<rect y="${HORIZON}" width="${WIDTH}" height="${HEIGHT - HORIZON}" fill="url(#ground)"/> +${stars()} +${crescent(MOON_X, MOON_Y, MOON_RADIUS)} +<rect y="${HORIZON - 270}" width="${WIDTH}" height="270" fill="url(#afterglow)"/> +${groundGrid()} +${farRange()} +${horizonLine} +${middleMassif} +${nearMassif} +<ellipse cx="800" cy="480" rx="1180" ry="760" fill="url(#tube)"/> +</svg>` +} + diff --git a/plugins/theme-examples/hooks/themes.ts b/plugins/theme-examples/hooks/themes.ts new file mode 100644 index 00000000..a6490cd8 --- /dev/null +++ b/plugins/theme-examples/hooks/themes.ts @@ -0,0 +1,223 @@ +import type { ThemeBackdropGlass } from 'claude-code' + +import { auroraSvg, deepWaterSvg, emberSvg } from './scenes/classic' +import { blueprintSvg } from './scenes/blueprint' +import { brailleStarsSvg } from './scenes/braille-stars' +import { departureBoardSvg } from './scenes/departure-board' +import { ditherDunesSvg, ditherDunesNightSvg } from './scenes/dither-dunes' +import { halftoneDawnSvg, halftoneDuskSvg } from './scenes/halftone-dawn' +import { honuLagoonSvg } from './scenes/honu-lagoon' +import { koiMosaicSvg } from './scenes/koi-mosaic' +import { nightReefSvg } from './scenes/night-reef' +import { paperGardenSvg, paperGardenKraftSvg } from './scenes/paper-garden' +import { plotterTideSvg, plotterTideNightSvg } from './scenes/plotter-tide' +import { snowPinesSvg } from './scenes/snow-pines' +import { teletextCloudsSvg } from './scenes/teletext-clouds' +import { vectorRangeSvg } from './scenes/vector-range' + +/** One theme: what the card and the list say, the glass over it, and its scene: a function that builds one SVG whose + * own CSS animates it. A scene says whether it is dark or light with its tint, picked from it. */ +export type Theme = { + id: string + title: string + blurb: string + /** Which window the scene is made for: the app uses a theme's tint only where its own text reads on it. */ + window: 'light' | 'dark' + /** The same scene made for the other kind of window, by its id, where there is one: the list and the card name it. */ + twin?: string + glass: ThemeBackdropGlass + scene: () => string +} + +export const THEMES: readonly Theme[] = [ + { + id: 'honu-lagoon', + title: 'Honu Lagoon', + blurb: 'A live ASCII lagoon from above: a tile turtle swims by a sand island', + window: 'light', + glass: { blur: 7, tint: '#e6fbff', opacity: 0.42 }, + scene: honuLagoonSvg, + }, + { + id: 'koi-mosaic', + title: 'Koi Mosaic', + blurb: 'A tiled koi pond from above: two koi, lily pads, slow ripples.', + window: 'light', + glass: { blur: 12, tint: '#eef8f1', opacity: 0.36 }, + scene: koiMosaicSvg, + }, + { + id: 'halftone-dawn', + title: 'Halftone Dawn', + blurb: 'A two-ink riso sunrise: halftone dots that breathe outward.', + window: 'light', + twin: 'halftone-dusk', + glass: { blur: 14, tint: '#f6ead9', opacity: 0.55 }, + scene: halftoneDawnSvg, + }, + { + id: 'halftone-dusk', + title: 'Halftone Dusk', + blurb: 'The riso sunrise on night-blue stock: an ember sun in breathing dots.', + window: 'dark', + twin: 'halftone-dawn', + glass: { blur: 14, tint: '#1f2336', opacity: 0.5 }, + scene: halftoneDuskSvg, + }, + { + id: 'plotter-tide', + title: 'Plotter Tide', + blurb: 'Pen-plotter tide lines drawing themselves on warm paper.', + window: 'light', + twin: 'plotter-tide-night', + glass: { blur: 0, tint: '#f4efe4', opacity: 0.32 }, + scene: plotterTideSvg, + }, + { + id: 'plotter-tide-night', + title: 'Plotter Tide, Night', + blurb: 'The plotter\'s tide chart in pale ink on blue-black night paper.', + window: 'dark', + twin: 'plotter-tide', + glass: { blur: 0, tint: '#141a27', opacity: 0.32 }, + scene: plotterTideNightSvg, + }, + { + id: 'dither-dunes', + title: 'Dither Dunes', + blurb: 'One-bit dunes on sand paper, shaded in dots, under a terracotta sun', + window: 'light', + twin: 'dither-dunes-night', + glass: { blur: 18, tint: '#f1e8d6', opacity: 0.34 }, + scene: ditherDunesSvg, + }, + { + id: 'dither-dunes-night', + title: 'Dither Dunes Night', + blurb: 'The same dunes after dark: pale dots on umber, an ember sun', + window: 'dark', + twin: 'dither-dunes', + glass: { blur: 18, tint: '#1c1712', opacity: 0.4 }, + scene: ditherDunesNightSvg, + }, + { + id: 'paper-garden', + title: 'Paper Garden', + blurb: 'Cut-paper leaves at the edges of a warm white sheet, one coral bloom.', + window: 'light', + twin: 'paper-garden-kraft', + glass: { blur: 16, tint: '#fbf6ec', opacity: 0.5 }, + scene: paperGardenSvg, + }, + { + id: 'paper-garden-kraft', + title: 'Paper Garden, Kraft', + blurb: 'Cut-paper leaves at the edges of dark kraft paper, one coral bloom.', + window: 'dark', + twin: 'paper-garden', + glass: { blur: 16, tint: '#35312a', opacity: 0.5 }, + scene: paperGardenKraftSvg, + }, + { + id: 'night-reef', + title: 'Night Reef', + blurb: 'The lagoon after dark: a turtle and a ray that glow as they swim', + window: 'dark', + glass: { blur: 14, tint: '#0a1430', opacity: 0.4 }, + scene: nightReefSvg, + }, + { + id: 'snow-pines', + title: 'Snow Pines', + blurb: 'An ASCII pine forest at dusk, snow drifting down through the trees.', + window: 'dark', + glass: { blur: 16, tint: '#14143a', opacity: 0.5 }, + scene: snowPinesSvg, + }, + { + id: 'braille-stars', + title: 'Braille Stars', + blurb: 'A slow night sky drawn dot by dot on a braille grid.', + window: 'dark', + glass: { blur: 20, tint: '#0a1430', opacity: 0.3 }, + scene: brailleStarsSvg, + }, + { + id: 'teletext-clouds', + title: 'Block Clouds', + blurb: 'Night clouds built from blocks on a teletext grid, drifting in', + window: 'dark', + glass: { blur: 12, tint: '#0d173f', opacity: 0.34 }, + scene: teletextCloudsSvg, + }, + { + id: 'vector-range', + title: 'Vector Range', + blurb: 'Phosphor mountains on black; an amber beam keeps retracing them.', + window: 'dark', + glass: { blur: 22, tint: '#0e2f27', opacity: 0.42 }, + scene: vectorRangeSvg, + }, + { + id: 'departure-board', + title: 'Departure Board', + blurb: 'An amber LED board re-lettering itself, row by row.', + window: 'dark', + glass: { blur: 14, tint: '#1a120b', opacity: 0.34 }, + scene: departureBoardSvg, + }, + { + id: 'blueprint', + title: 'Blueprint', + blurb: 'A cyanotype sheet; a comet goes round its plotted orbit in the corner.', + window: 'dark', + glass: { blur: 14, tint: '#0c2444', opacity: 0.42 }, + scene: blueprintSvg, + }, + { + id: 'deep-water', + title: 'Deep Water', + blurb: 'Light falling through deep water, and one quiet turtle', + window: 'dark', + glass: { blur: 14, tint: '#062c3a', opacity: 0.34 }, + scene: deepWaterSvg, + }, + { + id: 'aurora', + title: 'Aurora', + blurb: 'Northern lights swaying over a dark ridge', + window: 'dark', + glass: { blur: 18, tint: '#14123a', opacity: 0.3 }, + scene: auroraSvg, + }, + { + id: 'ember', + title: 'Ember', + blurb: 'A warm glow in the corners and a few embers rising', + window: 'dark', + glass: { blur: 12, tint: '#2a0d12', opacity: 0.3 }, + scene: emberSvg, + }, +] + +const built = new Map<string, string>() + +/** A theme's SVG, built the first time it is asked for: a session pays only for the scenes it shows. */ +export function sceneOf(theme: Theme): string { + const ready = built.get(theme.id) + if (ready !== undefined) return ready + const source = theme.scene() + built.set(theme.id, source) + return source +} + +/** Why a theme's scene cannot be drawn, in the fault's own words; nothing where it builds. */ +export function sceneFault(theme: Theme): string | undefined { + try { + sceneOf(theme) + + return undefined + } catch (error) { + return error instanceof Error ? error.message : String(error) + } +} |
