# The kit Status: kit 0.8.0, contract 1, Sumi pass 8 (2026-10-06). This is kit/KIT.src.md. kit/KIT.md is this text plus an API section, a Scripting API section, a Scene data section and a Cast data section that scripts/kit-doc.mjs generates from kit/host-api's, kit/packs/shooter/api.ts's, kit/packs/scene/api.ts's and kit/engine's types and doc comments and the data in kit/packs; it also writes kit/packs/shooter/api.d.ts and kit/packs/scene/api.d.ts, the declarations a level's module is checked against. Edit this file, never KIT.md: a test fails when KIT.md or either api.d.ts is stale (brief R12). Pass 15 adds the 3D path section, generated from kit/engine3d and kit/host-api/rim.ts (D148–D154). ## The method Ink and light is silhouettes, outlines and light as events. Everything is a silhouette filled with ink, edged with a neon outline, and lit by the glow that outline throws. There are no textures, no sprites and no shading inside a shape — but one: a scene pack's backdrop, a picture the scene is drawn over, shown whole as it was drawn (below). Light is something that happens — outline bloom, trails, sparks, a hit's flash, a light that bends across a rock as it tumbles, a boss whose outline pulses with its health — and all the richness comes from it. Light is never visibility, except by one look option: a scene whose reveal is `lantern` shows its picture only inside a lantern's light. If a shape needs detail inside it, it gets a second silhouette, not a texture. Every entity is a signed-distance shape on one instanced quad: a circle, a capsule, a polygon of up to 8 points, or a polygon with one circle or capsule in union. The renderer evaluates the shape per pixel: ink inside, an outline at the edge, a glow beyond it. The outline's hue says what a thing is. The player wears the member's hue, enemy classes wear class hues, and nothing hostile wears the player's hue. Readable first: brighter is more dangerous or more valuable. ## Two renderers The kit has two: the 2D renderer (kit/engine, everything above and below this section) and, since pass 15, the 3D path (kit/engine3d, its own section at the end). A pack declares which one it uses, and a package carries only that one: a 2D package's bytes hold none of the 3D path, and the 3D path imports nothing of the 2D renderer but its pure arithmetic (the hue, the four curves). The method holds in both — ink, outlines in hues, light as events — and in 3D it is ink bodies with a fresnel rim in the character's hue, an outline, bloom from what glows, and props drawn as light (D149). The 3D path's budgets are its own (the local tier: a desktop at 1920 × 1080, D153); the ones below are the 2D renderer's. ## Budgets (ink & light §3; a look never changes them) - At most **4,000 instances** a frame. A push past it is dropped and counted (`RenderStats.dropped`). - At most **20,000 particles** (GPU, transform feedback). - At most **12 draw calls** a frame: 10–11 at full quality, 12 at the scaler's first step. A scene's backdrop and its fog are one call of those (a scene game has no particles, shockwaves or lens, so it stays well under). - At most **7 ms a frame on the phone at 120 Hz** (14 ms at 60 Hz). The quality scaler steps down before a frame drops, in this order and never otherwise: 1. the light layer to half resolution 2. bloom 5 → 3 levels 3. bloom 3 → 1 level 4. persistence to half resolution 5. particles 20k → 10k 6. particles 10k → 5k It never touches gameplay or the SDF glow. It steps back up after 2 s comfortably under budget. The HUD shows a dim `q` while it is below full. - At most **16 point lights** a frame, nearest to what they can light first. At most **4 shockwaves**. At most **32 sound voices**; a voice past that is dropped, not queued. - The simulation runs at a fixed **240 Hz**; rendering is on requestAnimationFrame with interpolation. A long frame is cut to 16 steps, not caught up. Everything stops while the page is hidden. - The backing store is at devicePixelRatio ≤ 2. ## What a package is A package is a static bundle with a manifest, played by a host in a sandboxed iframe over the contract (spec/SPEC.md, contract 1). A package built with this kit: - bundles the kit (scripts/build-package.mjs: esbuild, one classic script, ES2022, minified, no code splitting); - has **no network**, ever: no fetch, XHR, WebSocket, EventSource or beacon. Its files load only by element; - has **no audio files**: effects are synthesised (`engine/audio.ts`), and music is the host's, asked for by playlist name with `host.music()`; - has **no inline script or style and no data: URLs**, because the policy refuses them. Code and styles are files. Setting `element.style` from script is fine; - has **no storage**: localStorage throws in the sandbox. The game's state goes through `host.save()` and comes back in `hello.save` (`host.onSave`). A pack keeps it as the world state (`engine/state.ts`, below); - ships the fonts it draws with (Sora and JetBrains Mono, for the theme's `sans` and `mono`). ## The engine (kit/engine) - `renderer.ts`: `Renderer.create(canvas)`. Each frame the game fills `batch` (instances), `lights`, `shocks`, `particles` and `lens` (aberration, a coloured vignette), sets `view` (the world rectangle on screen), then calls `frame(dt, ink)`. A lost WebGL context calls `onLost`; pause the game there. - `sdf.ts`: `InstanceBatch.circle / line / poly / push`, `Look` {color, hot, outline, glow, k, ink, ring, lit}, `Sub` (a union's circle or capsule). - `shapes.ts`: shapes as point arrays (y down, the nose toward −y), `ShapeTable.id(poly)`, and `sdPolygon` / `sdPlaced`, which are the CPU twins of the shader's distance, for collisions. - `lights.ts`, `particles.ts` (`spawn`, `burst`), `shock.ts`, `post.ts`, `scaler.ts`, `loop.ts` (`Loop` with `step` and `render` hooks). - `input.ts`: three sources, touch, keyboard and gamepad, as peers; the last source that moved wins. - Touch: drag anywhere to move (relative); a second finger is the primary action; a quick tap is "go". - Keyboard: arrows or WASD move, space is the primary and "go", Enter is "go", Esc pauses. - Gamepad: standard mapping only, read once a sim tick. The left stick (0.15 radial deadzone, curve x·|x|) or the d-pad moves; A is the primary and "go", Start pauses, B is back. - Rumble: `input.rumble({strong, weak, ms})`. - The pad reaches a game only through its frame's `allow="gamepad"`; a host never reads it. - `audio.ts`: `Sfx`, with synthesised voices on the game's own AudioContext, unlocked by a gesture. The voices are shot, enemyShot, hit, wall, rock, kill, powerup, bomb, phase, bossDeath and ui, each normalised to −3 dBFS. `say(voice)` plays a cast card's voice (voice.ts). `setMuted` follows the host's mute. - `hud.tsx` (React): the DOM HUD over the canvas. Its style is `engine/hud.css`, written against the theme shim's variables. `toast.ts`: a line at the foot of the frame. `oklch.ts`: a hue at a lightness and chroma as sRGB, by arithmetic. - `colors.ts`: `readTokens(el, names)` reads CSS custom properties as linear RGB, for the renderer. - `looks.ts`: the looks (Ink, Paper, Neon) as recipes of the post stack — the light's and the bloom's weight, the outline glow, ink or paper, and the small passes (film grain, vignette, halftone, chromatic fringe). Set `renderer.look`; a look never changes a budget (no recipe adds a draw call). Recipes are kit/packs/looks.json. - `cast.ts`, `anim.ts`, `effects.ts`, `voice.ts`: a cast card as data — its shape (up to 8 points in a unit square, mirror, up to 2 unions), its five animation states with the four named curves, its effects, its voice on the synth bus (`Sfx.say`). The Cast data section below is generated from them. - `backdrop.ts`: the **backdrop layer**, the one place the kit draws a picture, and only for a scene pack (a real-time pack's API has no way to it). One 1600 × 900 image a scene, drawn as one textured quad under the SDF field — the renderer's `underlay`, into the scene target before the silhouettes — and darkened in the same draw: the **fog pass**. A scene's reveal is `full` by default — the whole picture as drawn; a `lantern` scene shows it only inside a radial at the lantern's point, feathered at the rim with a little of the member's hue, and ink outside it (pass 13, D132). It goes through the look's composite like everything else, written so the tone map gives the picture back as drawn. One draw call; its cost is timed like the post stack's and shown in a dev build's corner ("fog 0.1 ms"). - `director.ts`: the **director**, which exists only in a dev build (Sumi's own builds, with `?director=1`; a release bundle — every package — has none of it). It plays a seeded run with a scripted input (the fire held, the ship weaving, "go" on every card), the player invulnerable, at a time scale, and `advanceTo(point)` steps the game as fast as it simulates to a level's timed points (its start, each wave, the field, each boss phase, the clear card): the build's frame grid is captured there. A script never sees it. - `state.ts`: the **world state**, one shape for every pack — `flags` (name → boolean, number or string), `inventory` (item ids), `party` ({id, hp, stats}), `location` ({level or scene, room}), `custom` (a small open object for a pack) and the `version` of the package that wrote it. It is the save: - `serialize(state)` writes it compact (short keys, no whitespace); `load(blob, {version, renames})` reads any blob a kit ever wrote, keeping fields it doesn't know, defaulting missing ones and applying the build's rename table. A package never refuses a save: junk loads as a fresh state. - Change it with `setFlag`, `addItem`, `removeItem`, `setLocation` or `change(state, fn)`. Past 60 KB serialized (`STATE_MAX`) a change throws `StateTooLarge` and the state stays as it was. The build calls `warnIfLarge()`. - Save it with `host.save(state)` (sent a second after the last call; anything waiting goes before a pause or an exit) or `checkpoint(state)` (at once): every pack checkpoints at a scene, a level clear or the end of a fight. - No slots: a game that wants slots keeps them inside its own state. The host keeps the last three saves and offers reset and restore previous; the game never sees them. ## Packs ### shooter (kit/packs/shooter): Kaos's The rules are `Kaos` (game.ts): title → each level's waves → an asteroid field → its boss (three phases) → level clear, and after the last level "cleared"; or game over. It has lives, a score with a wave-clear multiplier, six powerups and bombs. `step(dt, input)` runs at 240 Hz and `draw(batch, alpha, dt, palette)` fills the frame. It is pure: no DOM. A game is a project: its cast cards and one **level script** per level (the Scripting API below). The build bundles the pack's runtime (runtime.tsx: the canvas, the HUD, the title, pause, game-over, clear and cleared cards, the save) with the scripts; project.ts turns each script's `defineLevel` into the rules' level data, every id checked against the cast. - **A card is its behaviour's.** An enemy card's behaviour is a class (dart, drone or wall), a boss card's one of the three bosses, an item card's one of the six powerups. The behaviour owns how it moves, what it fires and its hitbox; the card owns its numbers (in the behaviour's ranges), its hue (drawn at the behaviour's `light`, its lightness and chroma) and its silhouette (drawn at the behaviour's `size` in world units). A boss's moving parts are the behaviour's; its card's silhouette is the hull. A script never defines a behaviour, a shape or a colour. - **A level script** imports only `'@sumi/kit'`, exports `default defineLevel({...})`, and is type-checked under ES2022 with no DOM against api.d.ts, with the project's cast ids declared. It names waves of groups (a card × a count in a pattern, at a delay), an asteroid field, a boss and its phases' names, the drop order, the level's item, its playlist and its speeds, and may use the hooks (`onStart`, `onWave`, `onBossPhase`, `onClear`) through a `LevelContext`: the world state (saved at each clear), a group now, an item now, a line at the foot of the frame. - **The wide layout is the pack's** (world.ts, R38): the field's width follows the aspect (390 on a phone, up to 900), formations are laid out as shares of it, a wider field brings more of each group, and the vertical pacing (heights, times) is the same at every width. One script plays both. - **Music's cue points (D106, music.ts).** The game asks the host for a playlist by name (`host.music`) at three moments: the title card (the first level's song), a level's start (its slot's song — the build hands the game each slot's playlist; else the playlist its script names; else the game's), and the boss's arrival, its first phase (the boss slot's song, when it has one; a boss with none keeps the level's). Nothing is asked on a wave or a later phase. The member's choice on the title card (the game's songs, keep what plays, silence) is in the save; a new game starts on the game's songs. A script never names a slot's playlist: the build does. The rules' level data, which a script becomes: ```ts interface Group { class: 'dart' | 'drone' | 'wall'; count: number; pattern: 'line' | 'v' | 'sine' | 'pincer'; delay: number } type Wave = Group[]; interface Field { duration: number; density: number; sizes: [large, medium, small] } interface Level { n: number; waves: Wave[]; field: Field; boss: 'l1' | 'l2' | 'l3' } ``` - Counts are for a field 390 wide; a wider one gets × (W / 390)^0.7. Patterns place members in a share of the width. - The difficulty of level n is `difficulty(n)` = {enemySpeed 1 + 0.15k, shotSpeed 1 + 0.1k, rockDensity 1 + 0.2k} with k = n − 1. - The classes: - **dart**: hp 1. Comes in lines and dives. - **drone**: hp 4. Drifts in a sine and fires aimed shots. - **wall**: hp 16. Slow, and splits along its seam at half health. - **Rocks** come in three sizes: large → two medium → two small → sparks. - **Bosses:** - l1 is a heptagon with a turning core. - l2 is a hull with two blade arms that spiral. - l3 is a crown with two pods; it splits in two at 30%. - **Powerups** drop in a fixed order: Spread (to five), Rapid ×1.6, Shield (one free hit), Pierce (through one target), Speed ×1.3, Bomb (store three). - **Scoring:** dart 100, drone 250, wall 300, half 150, × the multiplier (up to ×5). A rock is 50 plus a size bonus. A boss is 5,000 + 2,500 a life left. - **The palette** (`Palette`): the member's hue, ink, stars, the three class hues, the boss, rock, powerups and the nebula. The cards' colours replace the classes', the boss's and the powerups'; the rest is packs/shooter/shooter.css. - **The world** is `shooterWorld(aspect)`: W = clamp(aspect × 844, 390, 900), H = 844. A narrower phone keeps 390 and a taller field. The member's hue is drawn in the world at the dark twin (`WORLD_HUE`), since the field is always ink. ### scene (kit/packs/scene): first person, point and click A scene game is a project whose chapters are **data**, not scripts (D82): each chapter is its scenes — a backdrop with a portrait crop, a light, hotspots with what each verb does to them, exits and death cards — and the build writes the chapter's module (`export default defineChapter({...})`) from that data and bundles it with the pack's runtime (runtime.tsx). No model writes a scene chapter's code; a model may propose its data, which the kit's own `chapterProblems` holds to the rules below (the Scene data section is generated from them). - **The screen.** The backdrop under its fog, the hotspots as SDF rings over it — faint (the theme's dim at 0.35) where the light doesn't reach, glowing in the accent where it does (a hotspot that is a cast card, in its hue), brighter under the pointer when the chosen verb has something to say there — and the DOM HUD on the Theme's tokens: the text pane, the verb row **Look · Take · Use · Open · Go · Talk · Hit**, the inventory (each item card's silhouette in its hue), an arrow at each edge an exit leaves by, and the death card. - **The aspects (R38, R40).** Wide shows the whole picture, the verb row beside the text at its foot; portrait shows the maker's 9:16 crop at the top of the frame, the text under it and the verbs and the inventory in a pull-up. One image, one crop: a hotspot wholly outside the crop is never seen upright. The validator judges it (D102): when an edge of its scene goes everywhere the hotspot leads, and the hotspot does nothing else, the edge is the phone's way — a note on the scenes line; otherwise an advisory, and a failure in a portrait-only game. - **A verb, then the thing.** A tap or a click on a hotspot answers with the chosen verb (Look until another is chosen). Use takes an item in hand first. The first response whose `when` holds answers; Go tries the hotspot's exits first; a verb with nothing to say there gets the pack's default line — the player card's barks when it has any, else the pack's table (defaults.json); Talk to a hotspot that is a card asks the card's barks first. Look on the scene itself says what it said on entering. - **The reveal** (a look option, the maker's; pass 13, D132). `full` (the default): the whole picture, as drawn. `lantern`: a light at the scene's lantern point, flickering, ink beyond its radius. Nothing else shows or hides the picture — the light never follows the pointer. A `light` effect is an event that sets a scene's reveal, and the state keeps it; a save from before pass 13 that says `lit` or `cursor` reads as `full`. - **Effects** run in order: say, give, remove, set, go, die, light, stat. A go enters the scene (or the encounter) after the rest; a die shows its card and stops the rest; a stat changes the party's numbers (D92: no XP in v1 — a reward is an item or a stat). - **Saves (R47–R51).** The world state is the save: flags, inventory, `location.scene`, and in `custom` the deaths and the scenes whose reveal an effect set. Every scene entered is a checkpoint, sent to the host at once; a death is one too (the scene as it was entered, the death counted), and **Try again** goes back to it. The title card has the game's name, the premise's line, **Continue** (when there is a save) and **New game**. A save from an older version is migrated: the build hands the game its rename table (a flag a sheet renamed), and `load` maps the old name to the new. - **The director** (dev builds) shows the title card, each scene as its reveal shows it — walked to from the chapter's start by its exits with Go — and each death card: the frame grid's points. - **Music's cue points (D106, music.ts).** The title card plays the first chapter's start scene's song; a scene asks for its own song when it is entered; a scene with no song of its own keeps what is playing (nothing is asked). The build hands the game each slot's playlist (a scene's, an encounter's); a playlist the data names stands when the slot has none. **Silence (D110):** a place whose playlist is `"silence"` (the maker's "silence here" on its song card, or the word in the data) stops the music on entering it — the game sends `music {stop}`, never `music {playlist: "silence"}`. ### combat (kit/packs/combat): turn by turn, every move a light Combat is data too (D91): an **encounter** is a node of a scene chapter beside its scenes — an exit or a go leads to it like a scene — with its foes, its backdrop (the room's, or a picture of its own), the intro the log opens with, a playlist, whether the party may flee, what a win does (effects; a `go` takes the party on) and the death card a lose shows. A card brings its four numbers (the Stats tab: HP · ATK · DEF · speed) and its **moves** to a fight; an enemy or a boss also brings its **weights** (how often it picks each move) and a **taunt** (one of its barks, said on its first turn). No model writes a fight's code; Build proposes data — moves for the cards that lack them, the foes' weights, the intro and the lose card's words — which lands drafted. The Combat data section is generated from the rules below, and rules.json (printed there) holds the constants. - **The rules (rules.json, D94).** Turns go by speed, the fastest first; on a tie the party first, then the encounter's order; a round has each fighter once. A hit is `max(min, power·power + atk·ATK + def·DEF)` with rules.json's weights (as shipped: max(1, power + ATK − DEF)). **Guard** halves the next hit the guarder takes (rounded down, never below the least). A foe picks by its weights among the moves it may play now (a heal only under half its HP). A move's `cost` is `{item, spend}` (D101): the move is in the menu only while its item is carried, and with `spend: true` playing it uses the item up (a last arrow, a draught); with `spend: false` carrying it is enough (the torch enables the Flare). An `item` move always has a cost, and heals `power`. - **The party's turn** is the menu: its attack and heal moves, **Guard**, **Item** (what it carries that a move can use), **Flee** when the encounter allows it. Several foes: a move, then the foe (tap it, or its HP bar). Keys: 1–9, Escape. - **The end.** Every foe at 0 (or fled): a win — the win effects, then on (its go) or back where the party came from. The party at 0: a lose — its death card, and **Try again** goes back to the moment before the encounter, HP as it was. **Flee**: back where it came from, HP as it stands. The party's HP is the world state's (`party`): it carries across scenes and saves, and a heal move or a stat effect changes it. - **Saves.** The moment before an encounter is a checkpoint (the scene the party came from); a fight is never saved mid-turn — a reload, or a save while it fights, is that checkpoint. A fight's end is one too. - **The screen (D93).** The room's backdrop under its fog, lit around the party; the party's silhouette at the lower left in the member's hue, the foes at the upper right in their class hues (several fan out), each drawn as the Cast room draws it; the turn-order strip at the top left, the HP bars in hues (never the money amber), the move menu (docked at the right on wide, at the foot on portrait) and the log line. **Every move is a light** in the mover's hue: an `arc` flies from the mover to the target, a `burst` flashes at the target, a `ring` rings the mover, `none` is only the hit's flash; a hit flashes the target's outline and plays its hit; a defeat plays the card's death, then it's gone. - **Simulate (D95)** fights an encounter 200 times — each under its own seed — with a greedy player (an item under a third of its HP; when the foes could kill it before its next turn, the blow that takes that away, else Guard; else the move and the foe that deal the most), the party at its full HP, and says "wins 62% · 3.4 turns · hp left 4.1" and which foe deals the most. It's free: it runs on the maker's machine (and on the server after Build, the same code, encounter.ts). **What the party carries (D100)** is what a player could have by then: walked from the first chapter's start by exits, gos and other encounters' wins, every `give` on the way — never by a way only this encounter's win opens — unless the maker sets it with the Combat view's toggles. A win rate outside 40–80% is out of the band: the Combat view offers **Tune** (priced, never automatic: D99), which moves the cards' numbers, powers and weights toward it. - **Music's cue points (D106).** An encounter asks for its own song at its intro (one with none keeps the scene's); on the way back — a win, a flee, Try again — the scene's song is asked for again, or, when the scene has none, what played before the fight. A silent encounter (D110) stops the music at its intro; a silent scene stops it again on the way back. - **The director** (dev builds) adds an encounter's intro, its first exchange (the light held mid-way), its win (the greedy player under the director's seed) and its lose card; each label carries simulate's line. ### Kaos Kaos is no longer a folder in the kit (Sumi pass 6): it is a Sumi project, the house's example — its cast as cards, its three levels as scripts against this API (server/examples/kaos), built by the same bundler as any project. The built-in Kaos package is its release build. ## Not in the kit - **No network, no storage, no audio files.** Real-time packs draw silhouettes, never pictures: the backdrop layer is the scene pack's alone, one picture a scene, and a real-time pack's API has no way to it. - **No textures, sprites, gradients inside shapes or smoke.** The fog is the scene pack's, over its backdrop, and nowhere else in 2D; in 3D the stage's haze is the one, and a body is never hazed. Neither renderer draws a texture on a character. - **No 3D package yet, and no 3D on a phone.** A 3D build is a dev build, played on a desktop (the local tier), until contract 2 carries a tier; a phone gets one plain line instead of the stage. The 3D path's own list is in its section. - **No overhead pack yet** (v1.x), **no XP, levels or a party of more than the player card** in combat v1 (D92), and **no fight outside a scene chapter**: an encounter is a chapter's node. - **No script in a scene chapter, and no parser.** A scene chapter is its data (the Scene data section); logic past a response's `when` and its effects is a later ruling. The verbs are buttons, never typed. - **No look past the three.** Ink, Paper and Neon are recipes (kit/packs/looks.json); a look never changes a budget. - **No leaderboard, music library, settings or member data.** The host has these. A game knows a hue, a name, its own save, the theme and the aspect, and nothing else. - **No volume control or duck message for the host's music.** Contract 1 has neither. **No stings** (a short cue on a hit or a win: v1.x) and **no audio in a package**: a song is the host's, asked for by playlist; its brief ships in `songs[]`, never its sound. - **No save slots, and no state past 60 KB.** One world state per member per package; the host keeps the history. - **No code from Sumi or KazokuAI.** A package imports neither, and neither imports a package. - **No behaviour, shape or colour in a level script, and no import but `'@sumi/kit'`.** Behaviours are the pack's, chosen on a card; a script places and times them. A script reaches nothing outside the kit: no DOM, timers, network or storage. - **No director in a package.** It exists only in Sumi's dev builds (the frame grid and the Level room's Play). - **No module scripts or dynamic import().** One classic script per package. ## API (generated) Generated by scripts/kit-doc.mjs from kit/host-api/index.ts, kit/host-api/theme.ts, kit/engine/state.ts: the game's side of the contract, which every package bundles, and the world state its save carries. Import them as `import { host, checkpoint } from '/host-api'` and `import { load, setFlag } from '/engine/state'`. The host's listener is live from the moment the bundle runs. ### `CONTRACT` (const) The contract this kit speaks. A host says which contract it speaks in `hello`; the kit expects 1. ```ts const CONTRACT = 1; ``` ### `SAVE_MAX` (const) The most a save may be: 65,536 bytes of UTF-8 (SPEC §4). A bigger save is not sent. ```ts const SAVE_MAX = 65536; ``` ### `LABEL_MAX` (const) The most a score's label may be: 24 characters (SPEC §4). A longer one is cut. ```ts const LABEL_MAX = 24; ``` ### `SAVE_DEBOUNCE_MS` (const) How long a world state waits before it is sent: the last one in a second goes. ```ts const SAVE_DEBOUNCE_MS = 1000; ``` ### `Mode` (type) The host's theme mode. ```ts type Mode = 'dark' | 'light'; ``` ### `ThemeTokens` (interface) The ten theme tokens, all always present, as CSS values (SPEC §4, the Theme). ```ts interface ThemeTokens { /** The page. */ bg: string; /** A card on the page. */ bg2: string; /** A divider. */ line: string; /** Text. */ fg: string; /** Secondary text. */ dim: string; /** The host's accent. */ accent: string; /** The sans font stack. A package has only the fonts it ships. */ sans: string; /** The mono font stack. */ mono: string; /** The lightness every member hue is drawn at in this mode, e.g. "76%". */ hueL: string; /** The chroma every member hue is drawn at in this mode, e.g. "0.15". */ hueC: string; } ``` ### `Theme` (interface) The host's theme: for the package's chrome (its HUD, menus, cards). The world is the game's own. ```ts interface Theme { mode: Mode; tokens: ThemeTokens; } ``` ### `Aspect` (type) A shape the host gives the game: taller than wide, or wider than tall. ```ts type Aspect = 'portrait' | 'wide'; ``` ### `InputKind` (type) What the game can be played with on this device. ```ts type InputKind = 'touch' | 'keys' | 'pad'; ``` ### `Member` (interface) The player, as the host tells it: a hue (0–359) and a display name. The member's id never crosses. ```ts interface Member { hue: number; name: string; } ``` ### `Hello` (interface) The host's first message, once, after the frame loads. ```ts interface Hello { /** The contract the host speaks. */ contract: number; theme: Theme; member: Member; /** The shape the host gives the game now. */ aspect: Aspect; /** The manifest's inputs the host offers on this device. */ inputs: InputKind[]; /** The member's last save for this package, or null. */ save: string | null; /** The host's sound is off at the start. */ muted: boolean; } ``` ### `HostEvents` (interface) What the host can tell the game, by event. ```ts interface HostEvents { /** The first message: the theme, the member, the aspect, the inputs, the save, the mute. */ hello: Hello; /** The host's theme changed. */ theme: Theme; /** The host changed the shape it gives the game. */ aspect: Aspect; /** The game is out of sight or under the host's UI: stop time and sound. */ pause: undefined; /** Back: carry on from where pause stopped. */ resume: undefined; /** The host's sound went off (true) or on (false). */ mute: boolean; } ``` ### `Host` (interface) The game's side of the contract. ```ts interface Host { /** The hello, once it has come (null before). */ readonly hello: Hello | null; /** The theme now: hello's, then each theme message's. */ readonly theme: Theme | null; /** The host's mute now. */ readonly muted: boolean; /** * Listen for one of the host's messages; returns a function that stops listening. A hello that has already come is * handed to a late `hello` listener at once, so a game can subscribe after the bundle has started. */ on(type: K, fn: (value: HostEvents[K]) => void): () => void; /** The game has taken hello in and can be shown. Sent once; before hello it does nothing. */ ready(): boolean; /** * Keep the game's state. A world state (engine/state) is serialized and sent a second after the last call (the * debounce), or at once before a pause or an exit. A string is the game's own blob, sent at once (debounce it * yourself: at a checkpoint, never every frame). Only after ready and only when it is at most SAVE_MAX bytes as * UTF-8; false when it won't be sent. */ save(state: WorldState | string): boolean; /** Save a world state now, with no debounce: the packs call it at their checkpoints (a scene, a level, a fight). */ checkpoint(state: WorldState): boolean; /** * The member's last save, as hello handed it (null when there is none): the listener is called once, at hello, or at * once when hello has already come. Read it with engine/state's load(). */ onSave(fn: (blob: string | null) => void): () => void; /** * A run ended: its score, a whole number ≥ 0, and an optional short label ("Level 3", cut to LABEL_MAX). Sent only * after ready; false when it wasn't (not a whole number, below 0, or too soon). */ score(value: number, label?: string): boolean; /** Ask the host to play a playlist by name, or (null) to stop the music. Sent only after ready. */ music(playlist: string | null): boolean; /** The player left the game: the host closes it. Sent any time after hello. */ exit(): boolean; } ``` ### `parseTheme` (function) A Theme as SPEC §4 says it is, or null. ```ts function parseTheme(v: unknown): Theme | null; ``` ### `parseHello` (function) A hello as SPEC §4 says it is, or null. ```ts function parseHello(d: Record): Hello | null; ``` ### `HostWindow` (interface) The window a host-api lives in, as far as it uses one (tests hand in a fake). ```ts interface HostWindow { readonly parent: unknown; addEventListener(type: 'message', fn: (e: { source: unknown; data: unknown }) => void): void; } ``` ### `createHost` (function) Make the game's side of the contract on a window. Packages use the ready-made `host` below; this exists for tests and for a page that hosts itself. ```ts function createHost(win: HostWindow, opts: { post?: (msg: object) => void; root?: HTMLElement | null; log?: (msg: string) => void } = {}): Host; ``` ### `host` (const) The package's host. Importing the kit starts listening at once, so the hello the host sends at the frame's load event is never missed. Outside a frame (a page opened on its own) it waits for a hello that never comes. ```ts const host: Host; ``` ### `checkpoint` (const) Save a world state now (the packs call it at their checkpoints): `host.checkpoint` on the package's host. ```ts const checkpoint = (state: WorldState): boolean => host.checkpoint(state); ``` ### `THEME_VARS` (const) The CSS variables the shim writes, by Theme token. `--hue` is the member's colour in the host's mode. ```ts const THEME_VARS = { bg: '--bg', bg2: '--bg2', line: '--line', fg: '--fg', dim: '--dim', accent: '--accent', sans: '--sans', mono: '--mono', hueL: '--hue-l', hueC: '--hue-c', } as const; ``` ### `memberColor` (function) The member's colour in this theme, drawn as the host draws it (the theme's hueL and hueC); null if they don't parse. ```ts function memberColor(theme: Theme, hue: number): string | null; ``` ### `applyTheme` (function) Write a Theme onto `root` (the documentElement): every token as its variable, `data-theme` as the mode, and, given the member's hue, `--hue` as their colour in this mode. ```ts function applyTheme(theme: Theme, root: HTMLElement, hue?: number): void; ``` ### `STATE_MAX` (const) The most the serialized state may be: 60 KB of UTF-8, under the contract's 64 KB save (SPEC §4). ```ts const STATE_MAX = 60 * 1024; ``` ### `STATE_WARN` (const) The size warnIfLarge() warns at: three quarters of STATE_MAX. ```ts const STATE_WARN = 45 * 1024; ``` ### `STATE_FORMAT` (const) The blob's own format, so the shape itself can change later. ```ts const STATE_FORMAT = 1; ``` ### `FlagValue` (type) A flag's value. ```ts type FlagValue = boolean | number | string; ``` ### `Json` (type) Any JSON value (a pack's custom object holds these). ```ts type Json = null | boolean | number | string | Json[] | { [k: string]: Json }; ``` ### `PartyMember` (interface) One member of the party: an id (a cast card's), hit points and stats (ATK, DEF, speed, …). ```ts interface PartyMember { id: string; hp: number; stats: Record; /** Fields a newer kit wrote that this one doesn't know, kept as they were. */ keep?: Record; } ``` ### `Location` (interface) Where the player is: a level (shooter, overhead) or a scene (scene pack), and a room within it. ```ts interface Location { level?: number; scene?: string; room?: string; keep?: Record; } ``` ### `WorldState` (interface) The world state: what the scripts read, what Story shows as "what the game knows", what the save carries. ```ts interface WorldState { /** The version of the package that wrote it (the manifest's version). */ version: string; flags: Record; inventory: string[]; party: PartyMember[]; location: Location; /** A small open object for a pack's own state. */ custom: Record; /** Fields a newer kit wrote that this one doesn't know, kept as they were. */ keep?: Record; } ``` ### `StateTooLarge` (class) The state would be over STATE_MAX: the change is refused and the state is unchanged. ```ts class StateTooLarge extends Error { constructor(readonly bytes: number); } ``` ### `createState` (function) A fresh state for a package version. ```ts function createState(version: string): WorldState; ``` ### `serialize` (function) The state as the save's blob: short keys, no whitespace. Throws StateTooLarge over STATE_MAX. ```ts function serialize(s: WorldState): string; ``` ### `sizeOf` (function) The serialized size in bytes, whatever it is (no guard). ```ts function sizeOf(s: WorldState): number; ``` ### `load` (function) Read a save's blob into a state, migrating forward. null, empty, or anything that isn't a world state gives a fresh one (at opts.version, else "0.0.0"); a field this kit doesn't know is kept, a missing one defaulted, renames applied. ```ts function load(blob: string | null, opts: LoadOptions = {}): WorldState; ``` ### `writtenBy` (function) The version a blob says wrote it, or null for a blob that isn't a world state. ```ts function writtenBy(blob: string | null): string | null; ``` ### `change` (function) Change the state through `fn`, all or nothing: when the result would serialize past STATE_MAX, StateTooLarge is thrown and the state is exactly as it was. ```ts function change(s: WorldState, fn: (draft: WorldState) => void): WorldState; ``` ### `setFlag` (const) Set a flag (refused past STATE_MAX). ```ts const setFlag = (s: WorldState, name: string, value: FlagValue) => change(s, (d) => void (d.flags[name] = value)); ``` ### `clearFlag` (const) Clear a flag. ```ts const clearFlag = (s: WorldState, name: string) => change(s, (d) => void delete d.flags[name]); ``` ### `addItem` (const) Add an item, once (refused past STATE_MAX). ```ts const addItem = (s: WorldState, item: string) => change(s, (d) => void (d.inventory.includes(item) || d.inventory.push(item))); ``` ### `removeItem` (const) Take an item out. ```ts const removeItem = (s: WorldState, item: string) => change(s, (d) => void (d.inventory = d.inventory.filter((x) => x !== item))); ``` ### `setLocation` (const) Move the player. ```ts const setLocation = (s: WorldState, at: Location) => change(s, (d) => void (d.location = { ...at, ...(d.location.keep ? { keep: d.location.keep } : {}) })); ``` ### `warnIfLarge` (function) The build's check (R47): a warning line when the state, as given, serializes to more than STATE_WARN bytes, or null. The build calls it with the largest state a project's sheets allow (every flag set to its longest value). ```ts function warnIfLarge(s: WorldState): string | null; ``` ## Scripting API (generated) Generated by scripts/kit-doc.mjs from kit/packs/shooter/api.ts; its declarations are kit/packs/shooter/api.d.ts. A level script is one TypeScript module that imports only from `'@sumi/kit'` (this API: any other import is a build error) and exports `default defineLevel({...})`. It names its cast by the cards' ids, which the build declares, so a wrong id or the wrong kind of card is a type error. A card's behaviour (how it moves, what it fires, its hitbox) is the pack's, chosen on the card: a script places and times things and never defines a behaviour. Hooks see the world state (`ctx.state`, the kit's state module) and may set flags and items, add a group now, drop an item now and show a line. ### `Pattern` (type) How a group comes in. line: across the width at once; v: a V, apex first; sine: one after another down the middle, each a step along a sine; pincer: half from each side, alternating, closing in from the upper edges. x positions are shares of the field's width (wide fields are wider, never taller); heights and times are the same at every width. ```ts type Pattern = 'line' | 'v' | 'sine' | 'pincer'; ``` ### `PATTERNS` (const) The patterns, in order. ```ts const PATTERNS: readonly Pattern[]; ``` ### `ProjectCast` (interface) The project's cards by id and kind. The build declares them (`declare module '@sumi/kit' { interface ProjectCast {…} }`), so a wrong id is a type error. ```ts interface ProjectCast {} ``` ### `EnemyId` (type) An enemy card's id: its behaviour (dart, drone or wall) and its numbers are the card's. ```ts type EnemyId = IdsOf<'enemy'>; ``` ### `BossId` (type) A boss card's id: its behaviour (boss-core, boss-blades or boss-crown) is the card's. ```ts type BossId = IdsOf<'boss'>; ``` ### `ItemId` (type) An item card's id: its behaviour is one of the six powerups. ```ts type ItemId = IdsOf<'item'>; ``` ### `Group` (interface) A group of one enemy card. ```ts interface Group { cast: EnemyId; /** How many, for a field 390 wide (1–40; a wider field gets × (W / 390)^0.7). */ count: number; pattern: Pattern; /** Seconds after the wave starts (0–60). */ delay: number; } ``` ### `GroupOptions` (interface) When a group comes in, after its wave starts. ```ts interface GroupOptions { /** Seconds after the wave starts (default 0). */ at?: number; } ``` ### `Wave` (interface) A wave: its groups, which come in at their delays. The next wave starts 1.6 s after every enemy of this one is gone (destroyed or off the field). ```ts interface Wave { groups: Group[]; /** What the wave is for, in a line (the sheet's note; the game never shows it). */ note?: string; } ``` ### `Field` (interface) The asteroid field after the waves: rocks for `seconds`, `density` a second (× the level's rock density and the field's width), large / medium / small in the shares `sizes` (summing to 1). A large rock splits into two medium, a medium into two small. ```ts interface Field { seconds: number; density: number; sizes: [number, number, number]; } ``` ### `Boss` (interface) The level's boss: its card, and a name for each of its three phases (at 100%, 60% and 30% of its health; a crown splits in two at its card's split share). The names label the frame grid and the playtest notes. ```ts interface Boss { cast: BossId; phases: string[]; } ``` ### `Dials` (interface) The level's speeds over its cards' own numbers (each 0.25–4). None: the pack's curve for level n, enemy speed 1 + 0.15(n − 1), shot speed 1 + 0.1(n − 1), rock density 1 + 0.2(n − 1). ```ts interface Dials { enemySpeed?: number; shotSpeed?: number; rockDensity?: number; } ``` ### `World` (interface) The world state as a hook reads it: the kit's state module's (KIT.md, engine/state.ts), saved at each level's clear. ```ts interface World { /** The version of the package that wrote it. */ readonly version: string; readonly flags: Readonly>; /** Item ids. */ readonly inventory: readonly string[]; readonly location: { readonly level?: number; readonly scene?: string; readonly room?: string }; } ``` ### `LevelContext` (interface) What a hook can do: read and change the world state (saved at each level's clear), add a group now, drop an item now, and show a line at the foot of the frame. A change past the state's 60 KB is refused (it throws). ```ts interface LevelContext { /** The level's number in the project. */ readonly level: number; /** The current wave's index, 0-based. */ readonly wave: number; /** The world state, read-only here: change it with the calls below. */ readonly state: World; setFlag(name: string, value: boolean | number | string): void; getFlag(name: string): boolean | number | string | undefined; addItem(id: string): void; hasItem(id: string): boolean; /** A group, now: its members come in as its pattern places them, from this moment, as part of the current wave. */ spawn(group: Group): void; /** An item card's powerup, dropped now at the share `x` (0–1) of the field's width, near the top. */ pickup(item: ItemId, x?: number): void; /** A line at the foot of the frame for a few seconds. */ toast(text: string): void; } ``` ### `LevelDef` (interface) A level, as its script defines it. ```ts interface LevelDef { /** The level's title (the sheet's). */ title?: string; /** The waves, in order (1–12). */ waves: Wave[]; /** The asteroid field after the waves; null or none: none, straight to the boss. */ field?: Field | null; /** The boss; null or none: the level clears once the waves (and the field) are done. */ boss?: Boss | null; /** What drops, in order, round and round, counted over the whole run: walls drop one when they split, a boss one at * each new phase (and at level 3's split). None: the project's item cards, in their order. */ pickups?: ItemId[]; /** The level's item: the one its sheet teaches (it should be in `pickups`). */ item?: ItemId | null; /** The playlist the host plays under this level (none: the game's). */ music?: string | null; dials?: Dials; /** When the level starts, before its first wave. */ onStart?(ctx: LevelContext): void; /** When a wave starts (0-based). */ onWave?(ctx: LevelContext, wave: number): void; /** When the boss enters a new phase (2 or 3), with that phase's name. */ onBossPhase?(ctx: LevelContext, phase: number, name: string): void; /** When the level is clear, before the clear card (the world state is saved just after). */ onClear?(ctx: LevelContext): void; } ``` ### `LevelModule` (interface) What `defineLevel` returns: the module's default export. ```ts interface LevelModule { readonly kind: 'shooter-level'; readonly def: LevelDef; } ``` ### `LevelError` (class) A level script that can't be played: each problem names where it is ("waves.1.groups.0.count: 1–40"). ```ts class LevelError extends Error { constructor(readonly problems: string[]); } ``` ### `levelProblems` (function) What's wrong with a level's definition (none: it can be played). The ids are checked against the cast when the game starts. ```ts function levelProblems(def: LevelDef): string[]; ``` ### `defineLevel` (function) A level: the module's default export (`export default defineLevel({...})`). Throws LevelError when it can't be played. ```ts function defineLevel(def: LevelDef): LevelModule; ``` ### `wave` (function) A wave of these groups. ```ts function wave(...groups: Group[]): Wave; ``` ### `group` (function) A group: `count` of the enemy card `cast`, placed by `pattern`, `at` seconds into its wave. ```ts function group(cast: EnemyId, count: number, pattern: Pattern, opts: GroupOptions = {}): Group; ``` ### `line` (const) A line of `count` across the width, at once. ```ts const line = (cast: EnemyId, count: number, opts?: GroupOptions): Group => group(cast, count, 'line', opts); ``` ### `v` (const) A V of `count`, apex in the middle and first. ```ts const v = (cast: EnemyId, count: number, opts?: GroupOptions): Group => group(cast, count, 'v', opts); ``` ### `sine` (const) `count` one after another down the middle, 0.45 s apart, each further along a sine. ```ts const sine = (cast: EnemyId, count: number, opts?: GroupOptions): Group => group(cast, count, 'sine', opts); ``` ### `pincer` (const) `count` from both sides, alternating, 0.28 s apart, closing in from the upper edges. ```ts const pincer = (cast: EnemyId, count: number, opts?: GroupOptions): Group => group(cast, count, 'pincer', opts); ``` ### `field` (function) The asteroid field: `seconds` long, `density` rocks a second, the shares of large, medium and small. ```ts function field(seconds: number, density = 1.1, sizes: [number, number, number] = [0.4, 0.35, 0.25]): Field; ``` ### `boss` (function) The boss card `cast`, its phases named. ```ts function boss(cast: BossId, ...phases: string[]): Boss; ``` ### `pickups` (function) The drop order: these item cards, round and round. ```ts function pickups(...items: ItemId[]): ItemId[]; ``` ## Scene data (generated) Generated by scripts/kit-doc.mjs from kit/packs/scene/api.ts; its declarations are kit/packs/scene/api.d.ts. A scene chapter is this data (D82): the build writes its module, `export default defineChapter({...})`, importing only `'@sumi/kit'` (this API), and the game boots it through `chapterProblems`, the rules below. A point is in the wide backdrop's unit coordinates (1600 × 900); items and cards are the cast's ids; scene ids are the project's, one chapter's each. ### `VERBS` (const) The seven verbs, in the row's order (R22). No parser: a verb, then the thing. ```ts const VERBS = ['look', 'take', 'use', 'open', 'go', 'talk', 'hit'] as const; ``` ### `Verb` (type) A verb. ```ts type Verb = (typeof VERBS)[number]; ``` ### `FlagValue` (type) A flag's value (the world state's). ```ts type FlagValue = boolean | number | string; ``` ### `Pt` (type) A point in unit coordinates of the wide backdrop: [0, 0] its top-left, [1, 1] its bottom-right (1600 × 900). ```ts type Pt = [number, number]; ``` ### `BACKDROP` (const) The backdrop's size: every scene's one image is 1600 × 900 (R49); a hotspot's points and the crop are shares of it. ```ts const BACKDROP = { w: 1600, h: 900 } as const; ``` ### `Lit` (type) How a scene's backdrop is revealed — a look option, the maker's (pass 13, D132): `full`, the whole picture as drawn (the default); `lantern`, only inside a flickering light at the scene's lantern point, ink outside it. Light is never visibility otherwise: a light that follows the pointer is gone, and an effect's light is an event (`light` sets this option for a scene). ```ts type Lit = 'full' | 'lantern'; ``` ### `LITS` (const) The reveals, the default first. ```ts const LITS: readonly Lit[]; ``` ### `asLit` (const) A reveal as an older Sumi wrote it: before pass 13 a scene was `lit` (now `full`) or followed the pointer (`cursor`, gone: `full`). Anything but `lantern` is `full`. ```ts const asLit = (v: unknown): Lit => (v === 'lantern' ? 'lantern' : 'full'); ``` ### `When` (interface) A condition: every field given must hold. `flag` with `is` (default true; `is: false` also holds when the flag was never set), `has` an item in the inventory — for Use, the item in hand — and `lacks` an item not in it. ```ts interface When { flag?: string; is?: FlagValue; has?: string; lacks?: string; } ``` ### `STATS` (const) The party's numbers a `stat` effect changes (D92: no XP in v1 — a reward is an item or a stat): `hp` heals or hurts (never below 1 outside a fight, never past `hp_max`), `hp_max` raises or lowers the most HP (and the HP with it), `atk`, `def` and `speed` the card's own numbers. ```ts const STATS = ['hp', 'hp_max', 'atk', 'def', 'speed'] as const; ``` ### `Stat` (type) A party number. ```ts type Stat = (typeof STATS)[number]; ``` ### `Effect` (type) What a response does, in order: `say` a line, `give` or `remove` an item (an item card's id), `set` a flag, `go` to a scene or an encounter, `die` with a death card, `light` — an event — sets a scene's reveal (this one's when `scene` is left out), and `stat`: the party's `stat` by `by` (±1–99). ```ts type Effect = | { do: 'say'; text: string } | { do: 'give'; item: string } | { do: 'remove'; item: string } | { do: 'set'; flag: string; value: FlagValue } | { do: 'go'; scene: string } | { do: 'die'; card: string } | { do: 'light'; lit: Lit; scene?: string } | { do: 'stat'; stat: Stat; by: number }; ``` ### `EFFECTS` (const) The effects, by name. ```ts const EFFECTS = ['say', 'give', 'remove', 'set', 'go', 'die', 'light', 'stat'] as const; ``` ### `Response` (interface) One answer to a verb: shown when its `when` holds — the first that holds answers — with its text, then its effects. ```ts interface Response { when?: When; text: string; effects: Effect[]; } ``` ### `Hotspot` (interface) A thing in a scene: a polygon of 3 to 8 points over the backdrop, a name, and what each verb does to it. A verb with no response that holds gets the pack's default line (the player card's barks when it has any, else the pack's table). `card`: the cast card it is (an enemy to Talk to), drawn in its hue when lit. ```ts interface Hotspot { id: string; name: string; points: Pt[]; card?: string | null; responses: Partial>; } ``` ### `Edge` (type) An edge of the frame an exit can leave by. ```ts type Edge = 'left' | 'right' | 'up' | 'down'; ``` ### `EDGES` (const) The edges. ```ts const EDGES: readonly Edge[]; ``` ### `Exit` (interface) A way out: Go on its hotspot (`via` a hotspot's id) or its edge (`via` an edge) takes the player `to` a scene or an encounter, when its `when` holds. An exit is tried before the hotspot's Go responses; the first that holds is taken. ```ts interface Exit { to: string; via: string; when?: When; } ``` ### `DeathCard` (interface) A death: its card's text over ink, and Try again (back to where the scene was entered). ```ts interface DeathCard { id: string; text: string; } ``` ### `Crop` (interface) The portrait crop (R49): a 9:16 rectangle of the wide backdrop, in its unit coordinates, that a portrait screen shows. ```ts interface Crop { x: number; y: number; w: number; h: number; } ``` ### `Scene` (interface) A scene: its backdrop (an image id, or null before there is one), the portrait crop, its reveal (`full` unless the maker chose `lantern`) and the lantern's radius (in backdrop pixels) and point, the playlist under it, what happens when it's entered, its hotspots, exits and death cards. ```ts interface Scene { id: string; title: string; backdrop: string | null; crop: Crop; lit: Lit; light_radius: number; lantern: Pt | null; music: string | null; on_enter: Effect[]; hotspots: Hotspot[]; exits: Exit[]; death_cards: DeathCard[]; } ``` ### `EncounterBackdrop` (type) An encounter's backdrop (R24, R49): a scene's — the room it happens in, by the scene's id — or a picture of its own, by an image id (shipped as scenes/.webp). ```ts type EncounterBackdrop = { scene: string } | { image: string }; ``` ### `Foe` (interface) A foe in an encounter: an enemy or a boss card, and how many of it (more than one fan out on the field). ```ts interface Foe { cast_id: string; count: number; } ``` ### `Encounter` (interface) An encounter (the combat pack, D91): a node of the chapter, reached by an exit or a go like a scene. Its backdrop, the foes, the `intro` the log opens with, its playlist, whether the party may `flee` (back to the scene it came from, HP as it stands), what a `win` does (effects; a `go` takes the party on, else back to the scene it came from), and the death card a `lose` shows (one of the chapter's: Try again goes back to the moment before the encounter, HP as it was). ```ts interface Encounter { id: string; title: string; backdrop: EncounterBackdrop; enemies: Foe[]; intro: string; music: string | null; flee: boolean; win: Effect[]; lose: string; } ``` ### `Chapter` (interface) A scene chapter: its number and title, its scenes, the one the player enters first, and its encounters. ```ts interface Chapter { n: number; title: string; start: string; scenes: Scene[]; encounters?: Encounter[]; } ``` ### `ChapterModule` (interface) What a chapter's module exports: `export default defineChapter({...})`. ```ts interface ChapterModule { kind: 'scene-chapter'; chapter: Chapter; } ``` ### `ProjectCast` (interface) The project's cards by id and kind. The build declares them (`declare module '@sumi/kit' { interface ProjectCast {…} }`); a chapter's items and cards are checked against the cast when the game starts. ```ts interface ProjectCast {} ``` ### `defineChapter` (function) A chapter's module (the build writes it from the chapter's data). ```ts function defineChapter(chapter: Chapter): ChapterModule; ``` ### `LIMITS` (const) The limits a chapter is held to. ```ts const LIMITS = { scenes: 40, hotspots: 24, points: 8, exits: 12, deathCards: 8, responses: 6, effects: 8, text: 600, title: 60, radius: [60, 900], encounters: 12, foes: 4, stat: 99, } as const; ``` ### `ID` (const) An id: a scene's, a hotspot's, a death card's — lower case, a letter first, up to 32. ```ts const ID = /^[a-z][a-z0-9_-]{0,31}$/; ``` ### `FLAG` (const) A flag's name (the Lines tab's rule). ```ts const FLAG = /^[a-z][a-z0-9_]{0,31}$/; ``` ### `DEFAULT_CROP` (const) The crop when the maker hasn't set one: the centre 9:16 slice of the wide image, its full height. ```ts const DEFAULT_CROP: Crop; ``` ### `cropAspectOk` (function) The crop's shape: 9:16 in backdrop pixels, within 1%. ```ts function cropAspectOk(c: Crop): boolean; ``` ### `fitCrop` (function) A crop moved and sized to fit: 9:16, inside the image, at least a quarter of its height. ```ts function fitCrop(c: Crop): Crop; ``` ### `inPolygon` (function) The point is inside the polygon (even-odd). ```ts function inPolygon(p: Pt, poly: readonly Pt[]): boolean; ``` ### `centreOf` (function) A polygon's centre (the mean of its points). ```ts function centreOf(poly: readonly Pt[]): Pt; ``` ### `outsideCrop` (function) A hotspot lies wholly outside the crop: no point of it inside, and the crop's centre not inside it — a portrait screen never shows it (the validator warns, and fails a portrait-only game). ```ts function outsideCrop(points: readonly Pt[], c: Crop): boolean; ``` ### `ChapterContext` (interface) What a chapter may name outside itself: the cast (an item, a card) and the other chapters' scenes and encounters. ```ts interface ChapterContext { cast?: readonly { id: string; kind: string }[]; /** scene ids of the project's other chapters (an exit or a go may cross into one) */ scenes?: readonly string[]; /** encounter ids of the project's other chapters (an exit or a go may lead to one) */ encounters?: readonly string[]; } ``` ### `encounterIn` (function) The encounter by its id, from any of these chapters, or null. ```ts function encounterIn(chapters: readonly Chapter[], id: string): Encounter | null; ``` ### `chapterProblems` (function) Why a chapter's data isn't one the pack can play, as lines ("scenes.1.hotspots.0.points: 3 to 8 points"); none: it is. The shape (every field, its limits, no unknown field), the ids (unique in the chapter, the exits' and effects' targets there), the crop (9:16 inside the image) and the cast it names. A backdrop not made yet is no problem here: the validator says so. ```ts function chapterProblems(v: unknown, ctx: ChapterContext = {}): string[]; ``` ## Combat data (generated) Generated by scripts/kit-doc.mjs from kit/packs/combat/api.ts (its declarations are kit/packs/combat/api.d.ts) and kit/packs/combat/rules.json, printed as it is. A card's moves, weights and taunt are this data, on its Stats tab beside its four numbers; an encounter is the Scene data's `Encounter`. The fight's rules read rules.json (D94): the hit's terms and its least, Guard's share, when a foe heals, the order's ties, simulate's player. Every move is a light (`MoveLight`), drawn in the mover's hue. ### `MOVE_KINDS` (const) What a move does: `attack` hits one foe; `guard` halves the next hit the mover takes; `heal` gives the mover back `power` HP (an enemy heals only when under half); `item` spends its `cost` item and heals `power`; `flee` leaves the fight (the player: back to the scene before it, if the encounter allows; an enemy: off the field). ```ts const MOVE_KINDS = ['attack', 'guard', 'heal', 'item', 'flee'] as const; ``` ### `MoveKind` (type) A move's kind. ```ts type MoveKind = (typeof MOVE_KINDS)[number]; ``` ### `LIGHT_KINDS` (const) How a move is drawn (D93: every move is a light, in the mover's hue): `arc`, a light that flies from the mover to the target; `burst`, a flash at the target; `ring`, rings round the mover; `none`, only the outline's flash on a hit. ```ts const LIGHT_KINDS = ['arc', 'burst', 'ring', 'none'] as const; ``` ### `MoveLight` (type) A move's light. ```ts type MoveLight = (typeof LIGHT_KINDS)[number]; ``` ### `MoveCost` (interface) What a move costs (D101): the item card it needs carried, and whether playing it spends the item (`spend: true`: the item leaves the inventory when the move plays — a last arrow, a torch that burns out; `false`: it only has to be carried — the torch enables the Flare). An `item` move always has a cost. ```ts interface MoveCost { item: string; spend: boolean; } ``` ### `Move` (interface) One move on a card's Stats tab. `cost`: the item it needs and whether it spends it (null: none) — a move with a cost is in the menu only while its item is carried. `power`: an attack's own share of the hit, a heal's HP. `note`: the log's words when it plays ("the Lantern-eater recoils from the light"). ```ts interface Move { id: string; name: string; kind: MoveKind; cost: MoveCost | null; light: MoveLight; power: number; note: string; } ``` ### `Weight` (interface) How often an enemy or a boss picks a move: its id and a weight (the chance is the weight over the sum of the weights of the moves it may pick now). A move with no weight, or weight 0, is never picked. ```ts interface Weight { move: string; weight: number; } ``` ### `CombatStats` (interface) A card's four numbers (the Stats tab): HP, attack, defence and speed (the turn order: the fastest first). ```ts interface CombatStats { hp: number; atk: number; def: number; speed: number; } ``` ### `CombatCard` (interface) A card as a fight reads it: the cast card's id, kind and name, its numbers, its moves and (an enemy's or a boss's) weights, and its taunt — the id of one of its Lines of kind bark, shown in the log on its first turn. ```ts interface CombatCard { id: string; kind: 'player' | 'enemy' | 'boss' | 'item'; name: string; stats?: CombatStats; moves?: Move[]; weights?: Weight[]; taunt?: string | null; lines?: { id?: string; kind: string; text: string }[]; } ``` ### `COMBAT_LIMITS` (const) The limits a card's combat data is held to. ```ts const COMBAT_LIMITS = { moves: 8, power: [0, 99], weight: [0, 99], name: 30, note: 120, } as const; ``` ### `MOVE_ID` (const) A move's id: lower case, a letter first, up to 24. ```ts const MOVE_ID = /^[a-z][a-z0-9_-]{0,23}$/; ``` ### `combatProblems` (function) Why a card's combat data — its moves, weights and taunt — isn't one the pack can fight with, as lines ("moves.1.cost: no card torch in the cast"); none: it is. The shape (every field, its limits, no unknown field), the ids (unique on the card), a cost that is an item card, an `item` move that has one, weights that name the card's moves, and a taunt that is one of the card's barks. `items`: the cast's item cards' ids (left out: a cost isn't checked). ```ts function combatProblems(card: Pick, ctx: { items?: readonly string[] } = {}): string[]; ``` ### `weightOf` (function) The weight a card gives a move (0 when none). ```ts function weightOf(card: Pick, move: string): number; ``` ### `fightProblem` (function) Why a card can't take its side in a fight, or null: a foe (an enemy or a boss) needs its numbers and at least one attack move with a weight; the player needs its numbers and at least one attack move. ```ts function fightProblem(card: CombatCard, side: 'party' | 'foe'): string | null; ``` ### kit/packs/combat/rules.json ```json { "note": "The combat pack's constants (DESIGN.md D94): a later ruling tunes them here, without code. kit/packs/combat/rules.ts is the one place they are read.", "damage": { "note": "A hit is the sum of each term times its weight, then at least min: max(min, power·power + atk·atk + def·def). With these weights, max(1, power + ATK − DEF).", "power": 1, "atk": 1, "def": -1, "min": 1 }, "guard": { "note": "Guard: the guarder's next hit taken is this share of itself, rounded down, never below damage.min; it lasts until that hit.", "factor": 0.5 }, "heal": { "note": "An enemy's heal move is in its choice only under this share of its HP; a heal never goes past the HP it started with.", "enemy_below": 0.5 }, "order": { "note": "Turn order: speed, the fastest first; on a tie the party goes first, then the encounter's order.", "ties": "party_first" }, "greedy": { "note": "Simulate's player (D95): Item when under item_below of its HP and one is carried; Guard when the enemies could kill it before its next turn; else the move and target that deal the most.", "item_below": 0.3333 }, "simulate": { "note": "Simulate runs this many fights, each under a fresh seed, and gives up on a fight after max_rounds.", "runs": 200, "max_rounds": 60 } } ``` ## Cast data (generated) Generated by scripts/kit-doc.mjs from kit/engine/cast.ts, kit/engine/anim.ts, kit/engine/voice.ts, kit/engine/effects.ts, kit/engine/looks.ts and the data in kit/packs they read, printed as it is. A cast card is this data: the Cast room's preview draws it with the renderer, and a build hands it to a level's script (`import { drawShape, localPoly } from '/engine/cast'`, `import { poseAt } from '/engine/anim'`). A behaviour is chosen from its pack's list and given numbers; its code is the pack's. ### Shape grammar #### `UnitPt` (type) A point in the card's unit square: x from 0 (left) to 1 (right), y from 0 (top) to 1 (bottom). (0.5, 0.5) is the shape's centre, where it turns and scales. ```ts type UnitPt = [number, number]; ``` #### `UnionCircle` (interface) A circle in union with the polygon: its centre and radius, in the unit square. ```ts interface UnionCircle { kind: 'circle'; x: number; y: number; /** 0.02–0.5 */ r: number; } ``` #### `UnionCapsule` (interface) A capsule in union with the polygon: its centre, radius, half length along its axis, and how far the axis is turned from vertical, in degrees. ```ts interface UnionCapsule { kind: 'capsule'; x: number; y: number; /** 0.02–0.5 */ r: number; /** half the length of the straight part, 0–0.5 */ h: number; /** −180–180 degrees; 0 is vertical */ rot: number; } ``` #### `Union` (type) A circle or a capsule in union. ```ts type Union = UnionCircle | UnionCapsule; ``` #### `CastShape` (interface) The shape grammar: a cast card's silhouette. - `points`: the polygon, in order round its edge, 3 to 8 points (none: no shape yet). Every point is inside the unit square. - `mirror_x`: the shape is symmetric about x = 0.5. Then `points` is the left half only (every x ≤ 0.5), from one end of the axis round to the other; a point on the axis (x = 0.5) is drawn once, every other point is drawn again mirrored, and the drawn polygon (the half and its mirror) still has at most 8 points. - `unions`: up to 2 circles or capsules joined to the polygon (an eye, a head, a fin). The first is a true union, one outline round both; the second is drawn as a second silhouette beneath, so the first's outline crosses it. - `morph`: a second point set with the same count as `points`, the shape an animation's morph track moves toward. ```ts interface CastShape { points: UnitPt[]; mirror_x: boolean; unions: Union[]; morph?: UnitPt[] | null; } ``` #### `SHAPE_MAX_POINTS` (const) At most this many points drawn (the renderer's shape table holds 8 a row). ```ts const SHAPE_MAX_POINTS = 8; ``` #### `SHAPE_MAX_UNIONS` (const) At most this many circles or capsules in union. ```ts const SHAPE_MAX_UNIONS = 2; ``` #### `AXIS_EPS` (const) Within this of x = 0.5, a mirrored shape's point is on the axis. ```ts const AXIS_EPS = 1e-3; ``` #### `NO_SHAPE` (const) An empty card: no shape yet. ```ts const NO_SHAPE: CastShape; ``` #### `drawnPoints` (function) The polygon as drawn: the points, or with `mirror_x` the half and its mirror (the axis's points once). `axis` says which points are on the axis (by default, those within AXIS_EPS of it); a morph's frame takes its points'. ```ts function drawnPoints(points: readonly UnitPt[], mirror: boolean, axis?: readonly boolean[]): UnitPt[]; ``` #### `shapeProblems` (function) What's wrong with a shape, as short lines (none: it's a shape the kit can draw). ```ts function shapeProblems(s: unknown): string[]; ``` #### `localPoly` (function) The drawn polygon in the renderer's local frame (centred on the unit square's middle, one unit across), with the morph `m` (0–1) of the way to the morph target. Null when there are fewer than 3 points. ```ts function localPoly(s: CastShape, m = 0): Pt[] | null; ``` #### `unionSub` (function) A union as the renderer's sub-shape, in the local frame. ```ts function unionSub(u: Union): Sub; ``` #### `drawShape` (function) Draw a card's shape: the polygon (with the first union joined), the second union beneath it. `row` is the shape table's row for the polygon (a script gets one from `ShapeTable.id(localPoly(shape))`); `size` is how many world units the unit square spans. A shape with no polygon is its unions: the first is the body and the second joins it, one outline round both (pass 6: Kaos's drone, a circle with a capsule across it). Returns the instances pushed. ```ts function drawShape(batch: InstanceBatch, row: number | null, s: CastShape, x: number, y: number, rot: number, size: number, look: Look): number; ``` ### Animation #### `ANIM_STATES` (const) A card's states. idle and move loop; attack, hit and death play once and hold their last pose. ```ts const ANIM_STATES = ['idle', 'move', 'attack', 'hit', 'death'] as const; ``` #### `LOOPING` (const) Which states loop. ```ts const LOOPING: Record; ``` #### `TRACKS` (const) The tracks a state can key: rotate (degrees), scale (× the card's size), offset ([x, y] in card sizes), glow (× the card's glow) and morph (0–1 of the way to the shape's morph target). ```ts const TRACKS = ['rotate', 'scale', 'offset', 'glow', 'morph'] as const; ``` #### `TRACK_RANGES` (const) Each track's range; a value outside it is refused. ```ts const TRACK_RANGES: Record = { rotate: [-360, 360], scale: [0.1, 4], offset: [-1, 1], glow: [0, 4], morph: [0, 1], }; ``` #### `CURVES` (const) The four curves (R45): how a keyframe's value arrives at it, as a function from the segment's progress (0–1) to the share of the change made (0 at 0, 1 at 1). A keyframe's curve shapes the segment that ends on it. ```ts const CURVES = { /** An overshooting entrance: past the value, then back onto it (peaks about 10% over). */ snap: (t: number) => { const s = 1.70158; const u = t - 1; return 1 + (s + 1) * u * u * u + s * u * u; }, /** Decelerating: fast at first, easing onto the value; never past it. */ settle: (t: number) => 1 - (1 - t) ** 3, /** Accelerating out: slow at first, leaving fast. */ exit: (t: number) => t ** 3, /** Linear: the same speed all the way (a turn that keeps turning). */ spin: (t: number) => t, } as const; ``` #### `Curve` (type) A curve's name. ```ts type Curve = keyof typeof CURVES; ``` #### `CURVE_NAMES` (const) The curves' names, in the order the editor offers them. ```ts const CURVE_NAMES = Object.keys(CURVES) as Curve[]; ``` #### `Keyframe` (interface) One keyframe: its time in the state's loop (ms), its value (offset's is [x, y]) and the curve it arrives on. ```ts interface Keyframe { t: number; v: number | [number, number]; curve: Curve; } ``` #### `AnimEvent` (interface) An effect fired at a time in the loop: one of the effects' names, in the card's hue or in `hue` (0–359). ```ts interface AnimEvent { t: number; effect: string; hue?: number; } ``` #### `StateAnim` (interface) One state: its length, its tracks (each a list of keyframes in time order) and its events. ```ts interface StateAnim { /** 100–10,000 ms */ loop_ms: number; tracks: Partial>; events: AnimEvent[]; } ``` #### `CastAnim` (type) A card's animation: any of the five states. A state with no keys rests. ```ts type CastAnim = Partial>; ``` #### `Pose` (interface) Where a card is at a moment: turned (degrees), scaled, offset (card sizes), its glow (×) and morph (0–1). ```ts interface Pose { rotate: number; scale: number; offset: [number, number]; glow: number; morph: number; } ``` #### `REST` (const) The pose with nothing keyed. ```ts const REST: Pose; ``` #### `MAX_KEYS` (const) At most this many keyframes on a track. ```ts const MAX_KEYS = 16; ``` #### `MAX_EVENTS` (const) At most this many events in a state. ```ts const MAX_EVENTS = 8; ``` #### `trackValue` (function) A track's value at `ms` into the loop. Before the first key it holds the first key's value; between two keys the second key's curve shapes the way; after the last key a looping state goes on round to the first key (on its curve), and a state that plays once holds the last. ```ts function trackValue(keys: readonly Keyframe[], ms: number, loopMs: number, looping: boolean): Keyframe['v'] | null; ``` #### `loopTime` (function) The time in the state's loop for `ms` since it started: wrapped when it loops, held at the end when it doesn't. ```ts function loopTime(state: Pick, ms: number, looping: boolean): number; ``` #### `poseAt` (function) The pose `ms` after the state started. ```ts function poseAt(state: StateAnim | undefined, ms: number, looping: boolean): Pose; ``` #### `eventsBetween` (function) The events whose time falls after `fromMs` and at or before `toMs` since the state started (both in the state's own clock, unwrapped), each once per pass round the loop. ```ts function eventsBetween(state: StateAnim | undefined, fromMs: number, toMs: number, looping: boolean): AnimEvent[]; ``` #### `animProblems` (function) What's wrong with a card's animation, as short lines (none: the animator can play it). ```ts function animProblems(a: unknown): string[]; ``` ### Voice #### `Wave` (type) The waveform: an oscillator, or noise through a band-pass at the pitch. ```ts type Wave = 'sine' | 'square' | 'saw' | 'triangle' | 'noise'; ``` #### `WAVES` (const) The waveforms, in the order the Voice tab offers them. ```ts const WAVES: readonly Wave[]; ``` #### `Envelope` (interface) The envelope, in seconds (a attack, d decay, r release) and the sustain's level (s, 0–1 of the peak). ```ts interface Envelope { a: number; d: number; s: number; r: number; } ``` #### `CastVoice` (interface) A voice: the waveform at `pitch_hz`, bent by `pitch_env` semitones (up when positive) over `length_ms`, shaped by the envelope; the release follows the length. ```ts interface CastVoice { wave: Wave; pitch_hz: number; envelope: Envelope; pitch_env: number; length_ms: number; } ``` #### `VOICE_RANGES` (const) Each number's range, inclusive: pitch 40–4,000 Hz, ±24 semitones of bend, 30–3,000 ms, the envelope in seconds. ```ts const VOICE_RANGES = { pitch_hz: [40, 4000], pitch_env: [-24, 24], length_ms: [30, 3000], a: [0, 1], d: [0, 2], s: [0, 1], r: [0, 2], } as const; ``` #### `VOICE_PRESETS` (const) The presets, by name (kit/packs/voices.json): chirp, thud, hiss, bell, growl. ```ts const VOICE_PRESETS: Record; ``` #### `voiceProblems` (function) What's wrong with a voice, as short lines (none: the synth can play it). ```ts function voiceProblems(v: unknown): string[]; ``` #### `VoiceTimes` (interface) When a voice's parts end, in seconds from its start. ```ts interface VoiceTimes { attack: number; decay: number; /** the release starts at the voice's length */ release: number; end: number; } ``` #### `voiceTimes` (function) When a voice's parts end: the attack, the decay, the release's start, the end. ```ts function voiceTimes(v: CastVoice): VoiceTimes; ``` #### `endPitch` (const) The pitch at the end of the voice: `pitch_hz` bent by `pitch_env` semitones, kept in range. ```ts const endPitch = (v: CastVoice) => Math.min(VOICE_RANGES.pitch_hz[1], Math.max(VOICE_RANGES.pitch_hz[0], v.pitch_hz * 2 ** (v.pitch_env / 12))); ``` #### kit/packs/voices.json ```json { "chirp": { "wave": "sine", "pitch_hz": 1400, "envelope": { "a": 0.005, "d": 0.08, "s": 0.25, "r": 0.06 }, "pitch_env": 7, "length_ms": 110 }, "thud": { "wave": "sine", "pitch_hz": 80, "envelope": { "a": 0.002, "d": 0.16, "s": 0, "r": 0.1 }, "pitch_env": -12, "length_ms": 200 }, "hiss": { "wave": "noise", "pitch_hz": 3200, "envelope": { "a": 0.03, "d": 0.2, "s": 0.35, "r": 0.2 }, "pitch_env": 0, "length_ms": 420 }, "bell": { "wave": "triangle", "pitch_hz": 880, "envelope": { "a": 0.002, "d": 0.9, "s": 0, "r": 0.7 }, "pitch_env": 0, "length_ms": 1100 }, "growl": { "wave": "saw", "pitch_hz": 90, "envelope": { "a": 0.05, "d": 0.3, "s": 0.6, "r": 0.25 }, "pitch_env": -5, "length_ms": 650 } } ``` ### Effects #### `EffectPreset` (interface) A preset as kit/packs/effects.json writes it: its label, its default rate (a second) and the most it may be. ```ts interface EffectPreset { label: string; rate: number; max: number; } ``` #### `EFFECTS` (const) The presets, by name (kit/packs/effects.json). ```ts const EFFECTS: Record; ``` #### `EFFECT_NAMES` (const) The presets' names: none, dust, sparks, trail, rings. ```ts const EFFECT_NAMES: string[]; ``` #### `Emitter` (interface) Where an effect plays: the card's centre and size (world units), and how fast it's moving (world units a second). ```ts interface Emitter { x: number; y: number; size: number; vx: number; vy: number; } ``` #### `MAX_RINGS` (const) At most this many rings at once. ```ts const MAX_RINGS = 8; ``` #### `Effects` (class) A card's effects: a steady emitter (`run`) and bursts (`burst`), with the rings it keeps. ```ts class Effects { /** Seeded or not, the presets jitter with this. */ rand: () => number; /** The preset `name` at `rate` a second for `dt` seconds (clamped to the preset's max). */ run(name: string, rate: number, dt: number, at: Emitter, color: RGB, sink: ParticleSink): void; /** One burst of the preset (an animation event): a handful of what it emits steadily. */ burst(name: string, at: Emitter, color: RGB, sink: ParticleSink): void; /** Age the rings and push the live ones (outline-only circles that grow and fade). Returns the instances pushed. */ draw(batch: InstanceBatch, dt: number): number; clear(): void; } ``` #### kit/packs/effects.json ```json { "none": { "label": "none", "rate": 0, "max": 0 }, "dust": { "label": "dust motes", "rate": 2, "max": 12 }, "sparks": { "label": "sparks", "rate": 6, "max": 30 }, "trail": { "label": "trail", "rate": 20, "max": 60 }, "rings": { "label": "rings", "rate": 0.8, "max": 4 } } ``` ### Looks #### `LookName` (type) The looks a pitch chooses from. ```ts type LookName = 'ink' | 'paper' | 'neon'; ``` #### `LookRecipe` (interface) A look's recipe: - `background`: the world's clear colour, `ink` or the theme's `bg` (paper); - `fill`: how much of a silhouette's own hue tints its fill (0: ink, or the paper itself); - `light`, `bloom`: the light layer's and the bloom's weight on screen (0 turns them off); - `glow`: × every outline's glow; - `tonemap`: Reinhard on (for light on ink) or off (for paper); - `grain` (0–0.2), `vignette` (0–1), `halftone` (0–1): the composite's small passes; - `fringe`: CSS pixels of red–blue split at the corners, through the lens. ```ts interface LookRecipe { label: string; line: string; background: 'ink' | 'bg'; fill: number; light: number; bloom: number; glow: number; tonemap: boolean; grain: number; vignette: number; halftone: number; fringe: number; } ``` #### `LOOKS` (const) The recipes, by name (kit/packs/looks.json). Ink is the default and is the engine as it was before looks. ```ts const LOOKS: Record; ``` #### `lookRecipe` (const) A look's recipe by name; anything else is Ink. ```ts const lookRecipe = (name: string | null | undefined): LookRecipe => (name && name in LOOKS ? LOOKS[name as LookName] : LOOKS.ink); ``` #### kit/packs/looks.json ```json { "ink": { "label": "Ink", "line": "silhouettes in ink, neon outlines, bloom", "background": "ink", "fill": 0, "light": 1, "bloom": 1, "glow": 1, "tonemap": true, "grain": 0, "vignette": 0.45, "halftone": 0, "fringe": 0 }, "paper": { "label": "Paper", "line": "flat fills on the theme's paper, no bloom; grain and a vignette", "background": "bg", "fill": 0.22, "light": 0, "bloom": 0, "glow": 0, "tonemap": false, "grain": 0.05, "vignette": 0.3, "halftone": 0, "fringe": 0 }, "neon": { "label": "Neon", "line": "heavy bloom and a chromatic fringe at the edges", "background": "ink", "fill": 0, "light": 1.15, "bloom": 1.8, "glow": 1.35, "tonemap": true, "grain": 0, "vignette": 0.5, "halftone": 0, "fringe": 2.2 } } ``` ### Behaviours #### kit/packs/shooter/behaviours.json ```json { "pack": "shooter", "note": "Kaos's behaviours as extracted (docs/KIT_SURVEY.md §2, kit/packs/shooter): the three classes, the three bosses and the six powerups. A card picks one and sets its numbers; the code is the pack's. size: the world units a card's unit square spans in play; light: the class's OKLCH lightness and chroma, at which the card's hue is drawn (pass 6).", "behaviours": [ { "id": "dart", "label": "dart · comes in, turns and dives", "kinds": ["enemy"], "line": "Enters in a line, a V or a pincer, then dives at the column the player was in when it turned.", "size": 24, "light": [0.701, 0.253], "params": [ {"key": "speed", "label": "Speed", "min": 60, "max": 240, "step": 10, "default": 120, "unit": "/s"}, {"key": "dive_after", "label": "Dive after", "min": 0.4, "max": 3, "step": 0.1, "default": 2.4, "unit": "s"}, {"key": "hp", "label": "Hearts", "min": 1, "max": 8, "step": 1, "default": 1, "unit": ""} ] }, { "id": "drone", "label": "drone · hovers in a sine and aims", "kinds": ["enemy"], "line": "Drops to a hover line, sweeps side to side in a sine and fires a shot aimed at the player; leaves after a while.", "size": 38, "light": [0.69, 0.2], "params": [ {"key": "speed", "label": "Speed", "min": 40, "max": 180, "step": 10, "default": 90, "unit": "/s"}, {"key": "fire_every", "label": "Fires every", "min": 0.8, "max": 6, "step": 0.1, "default": 2.4, "unit": "s"}, {"key": "leave_after", "label": "Leaves after", "min": 4, "max": 30, "step": 1, "default": 14, "unit": "s"}, {"key": "hp", "label": "Hearts", "min": 1, "max": 12, "step": 1, "default": 4, "unit": ""} ] }, { "id": "wall", "label": "wall · slow, splits at half health", "kinds": ["enemy"], "line": "Drifts down slowly and splits along its seam at half health into two halves that turn apart.", "size": 100, "light": [0.801, 0.14], "params": [ {"key": "speed", "label": "Speed", "min": 16, "max": 80, "step": 4, "default": 32, "unit": "/s"}, {"key": "split_at", "label": "Splits at", "min": 0.2, "max": 0.8, "step": 0.05, "default": 0.5, "unit": "of hp"}, {"key": "hp", "label": "Hearts", "min": 4, "max": 40, "step": 1, "default": 16, "unit": ""} ] }, { "id": "boss-core", "label": "boss · a turning core (level 1)", "kinds": ["boss"], "line": "Three phases; a core turns inside the hull and fires aimed bursts that come faster as it weakens.", "size": 210, "light": [0.652, 0.236], "params": [ {"key": "hp", "label": "Hit points", "min": 120, "max": 1200, "step": 20, "default": 420, "unit": ""}, {"key": "burst_every", "label": "Sweeps every", "min": 0.8, "max": 4, "step": 0.1, "default": 2.4, "unit": "s"} ] }, { "id": "boss-blades", "label": "boss · two blade arms that spiral (level 2)", "kinds": ["boss"], "line": "Three phases; two arms sweep round and fire from their tips, outward, as two spirals.", "size": 144, "light": [0.652, 0.236], "params": [ {"key": "hp", "label": "Hit points", "min": 160, "max": 1400, "step": 20, "default": 560, "unit": ""}, {"key": "turn", "label": "Arm turn", "min": 0.6, "max": 4, "step": 0.1, "default": 1.9, "unit": "rad/s"} ] }, { "id": "boss-crown", "label": "boss · a crown that splits in two (level 3)", "kinds": ["boss"], "line": "Three phases; at the split it breaks into two halves that take turns to charge.", "size": 220, "light": [0.652, 0.236], "params": [ {"key": "hp", "label": "Hit points", "min": 200, "max": 1600, "step": 20, "default": 720, "unit": ""}, {"key": "split_at", "label": "Splits at", "min": 0.1, "max": 0.6, "step": 0.05, "default": 0.3, "unit": "of hp"} ] }, {"id": "spread", "label": "powerup · spread", "kinds": ["item"], "line": "The shot fans out, up to five.", "params": [{"key": "steps", "label": "Up to", "min": 1, "max": 5, "step": 1, "default": 5, "unit": "shots"}], "size": 20, "light": [0.755, 0.126]}, {"id": "rapid", "label": "powerup · rapid", "kinds": ["item"], "line": "Fires faster.", "params": [{"key": "rate", "label": "Rate", "min": 1.1, "max": 2.5, "step": 0.1, "default": 1.6, "unit": "×"}], "size": 20, "light": [0.755, 0.126]}, {"id": "shield", "label": "powerup · shield", "kinds": ["item"], "line": "One hit taken for free.", "params": [{"key": "hits", "label": "Hits", "min": 1, "max": 1, "step": 1, "default": 1, "unit": ""}], "size": 20, "light": [0.755, 0.126]}, {"id": "pierce", "label": "powerup · pierce", "kinds": ["item"], "line": "A shot goes through one target.", "params": [{"key": "through", "label": "Through", "min": 1, "max": 3, "step": 1, "default": 1, "unit": ""}], "size": 20, "light": [0.755, 0.126]}, {"id": "speed", "label": "powerup · speed", "kinds": ["item"], "line": "Moves faster.", "params": [{"key": "rate", "label": "Rate", "min": 1.1, "max": 2, "step": 0.1, "default": 1.3, "unit": "×"}], "size": 20, "light": [0.755, 0.126]}, {"id": "bomb", "label": "powerup · bomb", "kinds": ["item"], "line": "Stores a bomb that clears the field (up to three).", "params": [{"key": "max", "label": "Hold up to", "min": 1, "max": 5, "step": 1, "default": 3, "unit": ""}], "size": 20, "light": [0.755, 0.126]} ] } ``` #### kit/packs/scene/behaviours.json ```json { "pack": "scene", "pass": 8, "note": "A scene game's cards need no behaviour: the player carries the light, an item is carried and used by its id, and an enemy is a hotspot's card, answering Talk with its barks.", "behaviours": [] } ``` #### kit/packs/combat/behaviours.json ```json { "pack": "combat", "pass": 9, "note": "The combat pack's behaviours arrive with the pack (pass 9).", "behaviours": [] } ``` ## 3D path (generated) Generated by scripts/kit-doc.mjs from kit/engine3d/budgets.ts, kit/engine3d/index.ts, kit/engine3d/renderer.ts, kit/engine3d/stage.ts, kit/engine3d/camera.ts, kit/engine3d/loader.ts, kit/engine3d/animator.ts, kit/host-api/rim.ts, kit/engine3d/look.ts, kit/engine3d/scaler.ts, kit/engine3d/tier.ts and kit/engine3d/stages/torii-ground.json, printed as it is. The kit's second renderer (D148): three.js (WebGPU first, WebGL2 where WebGPU isn't offered), beside the 2D renderer and never inside it. A pack declares which renderer it uses and a package carries only that one; a 3D pack imports `/engine3d` (one entry, `createStage3D`) and drives the rim through `host.rim` (`/host-api/rim`). The look is ink (D149): bodies in ink, a fresnel rim in the character's hue, an outline, bloom from what glows, props drawn as light; the theme changes the stage and the HUD only. Characters are assets (D154): a glb's bytes — a skin, its clips, props on named bones — carried inside the package's script. Until contract 2 carries a tier, a 3D build is a dev build, played on a desktop. ### What the 3D path does not have - no free camera: the stage camera is fixed (three-quarter framing, or the boss framing a pack requests); the right stick is never the camera’s - no shadows: the body is ink, lit by the lanterns and drawn by its rim and outline - no textures in the ink look: a character is a mesh, a rig and clips; a material or texture in the glTF is ignored - no image loads at run time and no fetch: assets arrive as bytes in the package’s own script (the contract’s connect-src is none) - no more than 4 point lights, 22 bones a character, 30,000 triangles a body, 6 characters - no physics, no ragdolls, no IK: poses come from clips and keyed procedural layers - no phone browser: a 3D build plays on the local tier (a desktop) and says so on a phone - no cel or animated looks yet (D151 reserves them); the ink look is the one recipe ### kit/engine3d/budgets.ts #### `RendererKind` (type) The renderer a pack declares (D148): the 2D kit's instanced SDF renderer, or this one. A package carries only its own. ```ts type RendererKind = '2d' | '3d'; ``` #### `BONE_BUDGET` (const) The most bones a character's skin may have (D145: the vroid body). A heavier rig is refused at load. ```ts const BONE_BUDGET = 22; ``` #### `TRIANGLE_BUDGET` (const) The most triangles a character's body may have (Tatara's ink recipe makes ≤ 30k). A heavier mesh is refused at load. ```ts const TRIANGLE_BUDGET = 30_000; ``` #### `PROP_TRIANGLE_BUDGET` (const) The most triangles a prop may have (D143). ```ts const PROP_TRIANGLE_BUDGET = 2_000; ``` #### `LIGHT_BUDGET` (const) The most point lights a stage may light (D149): the stage's lanterns and any the pack adds, together. ```ts const LIGHT_BUDGET = 4; ``` #### `CHARACTER_BUDGET` (const) The most characters on a stage at once. ```ts const CHARACTER_BUDGET = 6; ``` #### `LOCAL_TIER` (const) The local tier's ruler (D153): the desktop at 1920×1080, judged at 8.3 ms a frame (a 120 Hz display), never looser than 16.6 ms (60 Hz). Placeholders until the desktop GPU's reading rules them (docs/reports/pass-15.md has the readings). ```ts const LOCAL_TIER = { width: 1920, height: 1080, budgetMs: 8.3, floorMs: 16.6 } as const; ``` #### `STAGE_ASPECT` (const) The stage's shape: a 3D pack is wide-first; portrait letterboxes the stage at this aspect (D148, task 2). ```ts const STAGE_ASPECT = 16 / 9; ``` #### `ABSENT` (const) What the 3D path does not have, by design: a script that needs one of these needs a ruling first. ```ts const ABSENT = [ 'no free camera: the stage camera is fixed (three-quarter framing, or the boss framing a pack requests); the right stick is never the camera’s', 'no shadows: the body is ink, lit by the lanterns and drawn by its rim and outline', 'no textures in the ink look: a character is a mesh, a rig and clips; a material or texture in the glTF is ignored', 'no image loads at run time and no fetch: assets arrive as bytes in the package’s own script (the contract’s connect-src is none)', `no more than ${LIGHT_BUDGET} point lights, ${BONE_BUDGET} bones a character, ${TRIANGLE_BUDGET.toLocaleString('en-US')} triangles a body, ${CHARACTER_BUDGET} characters`, 'no physics, no ragdolls, no IK: poses come from clips and keyed procedural layers', 'no phone browser: a 3D build plays on the local tier (a desktop) and says so on a phone', 'no cel or animated looks yet (D151 reserves them); the ink look is the one recipe', ] as const; ``` ### kit/engine3d/index.ts #### `StageOptions` (interface) How a stage starts: its data (the default stage unless given), the theme's mode, the aspect, the renderer's options. ```ts interface StageOptions extends BootOptions { stage?: StageData; mode?: Mode; aspect?: Aspect; /** Step the scaler from the frames' times (true unless false: a test or a bench holds a level with `quality`). */ autoScale?: boolean; } ``` #### `StageCharacter` (interface) A character on the stage: what was loaded, its animator and its look. ```ts interface StageCharacter extends Character { animator: Animator; look: CharacterLook; } ``` #### `Readout3D` (interface) The budget readout (the corner's chip): the backend, the frame's time, its draw calls and the scaler's step. ```ts interface Readout3D { backend: Backend; gpu: string; /** A GPU-synced frame time, ms (one frame in 30 waits for the GPU), smoothed; null until the first. */ ms: number | null; /** The last frame's CPU time, ms (the update and the submit). */ cpuMs: number; /** Draw calls in the last frame, every pass counted. */ draws: number; /** The scaler's level (0: full) and what its last step did. */ level: number; step: string; /** The drawing buffer, pixels. */ width: number; height: number; } ``` #### `Stage3D` (interface) A stage. ```ts interface Stage3D { readonly backend: Backend; readonly gpu: string; readonly scaler: Scaler3D; readonly characters: ReadonlyMap; /** The framing now. */ readonly framing: FramingName; /** The stage's clock, seconds: rims and their presets run on it; tick advances it. Setting it moves no animator. */ time: number; /** Load a character from its glb's bytes and stand it at a place (a name in the stage's places, or a ground point). */ addCharacter(bytes: ArrayBuffer | Uint8Array, opts: CharacterOptions & { place?: string | GroundPt }): Promise; /** Play one of a character's clips (a crossfade from what plays). */ play(name: string, clip: string, opts?: PlayOptions): void; /** Add a procedural layer to a character's bones; returns its remover. */ layer(name: string, layer: BoneLayer): () => void; /** Turn character `a` to face character `b`. */ face(a: string, b: string): void; /** The theme's mode: the stage's night or paper (the body never changes, D146). */ setMode(mode: Mode): void; /** Cut to a framing: the stage's, or the boss's (D150). */ frame(f: FramingName): void; /** The aspect the host gives: wide fills the view, portrait letterboxes the stage. */ setAspect(aspect: Aspect): void; /** The view's size in CSS pixels: the canvas is placed and sized inside it (see `rect`). */ resize(w: number, h: number): void; /** Where the stage draws in the view, CSS pixels. */ rect(): Rect; /** The outline's thickness in pixels (1.6 unless set; 0 draws none — what a test compares against). */ outline(px: number): void; /** Hold the scaler at a level (0–5) and stop it stepping by itself; null lets it step again. */ quality(level: number | null): void; /** Advance every animator and rim by dt seconds, feed the scaler, and draw. */ tick(dt: number): void; /** Draw the frame as it is. */ render(): void; /** Wait for the GPU to finish what was submitted. */ gpuDone(): Promise; /** The GPU's time for the passes drawn since the last call, ms (null unless booted with `timestamps`). */ gpuTime(): Promise; readout(): Readout3D; } ``` ### kit/engine3d/renderer.ts #### `Backend` (type) The backend a stage draws with. ```ts type Backend = 'webgpu' | 'webgl2'; ``` #### `Booted` (interface) A booted renderer: three's, its backend and the GPU it named. ```ts interface Booted { renderer: WebGPURenderer; backend: Backend; gpu: string; /** Wait until the GPU has finished what was submitted (a frame time that includes the GPU's). */ gpuDone(): Promise; /** The GPU's time for the passes drawn since the last call, ms; null without timestamps. */ gpuTime(): Promise; } ``` #### `BootOptions` (interface) Boot options: force WebGL2 (the tests' SwiftShader runs), the device-pixel ratio, antialiasing, GPU timestamps. ```ts interface BootOptions { forceWebGL?: boolean; pixelRatio?: number; antialias?: boolean; /** Time each frame's passes on the GPU (timestamp queries, where the GPU has them): the bench's, never a game's. */ timestamps?: boolean; } ``` ### kit/engine3d/stage.ts #### `GroundPt` (type) A point on the ground: [x, z] in metres (a character is 1.75 m tall); +x right, +z toward the camera. ```ts type GroundPt = [number, number]; ``` #### `WorldPt` (type) A point in the world: [x, y, z] in metres. ```ts type WorldPt = [number, number, number]; ``` #### `StagePiece` (type) One piece of a stage. ```ts type StagePiece = /** The ground plane, `size` metres square, centred: lit by the lanterns at night, the page itself on paper. */ | { kind: 'ground'; size: number } /** The playing field's three-quarter grid: `rows` lines across and `rails` toward the back, inside the field. */ | { kind: 'grid'; rows: number; rails: number } /** A torii's silhouette at a ground point, scaled (1: 5.6 m tall); never hazed, drawn lighter than the night. */ | { kind: 'torii'; at: GroundPt; scale: number } /** A lantern at a world point: a glowing box and a point light of `light` candela-ish (34 is the plate's). */ | { kind: 'lantern'; at: WorldPt; light: number } /** Haze over the stage (exponential fog), its density by theme; the body is never hazed (D146). */ | { kind: 'haze'; dark: number; light: number }; ``` #### `StageData` (interface) A stage: its name, the playing field's rectangle on the ground, its pieces and where characters stand. ```ts interface StageData { name: string; /** The field: x from–to and z from–to (back to front), metres. */ field: { x: [number, number]; z: [number, number] }; pieces: StagePiece[]; /** Named places on the ground: `player` and `foe` at least. */ places: Record; } ``` #### `DEFAULT_STAGE` (const) The duel view's stage (stages/torii-ground.json): a 14 × 10.5 m field, two torii far back, two lanterns, haze. ```ts const DEFAULT_STAGE = TORII_GROUND as unknown as StageData; ``` #### `stageProblems` (function) What's wrong with a stage, as short lines (none: the 3D path can build it). ```ts function stageProblems(s: unknown): string[]; ``` #### `stageLights` (const) How many point lights a stage lights (its lanterns). ```ts const stageLights = (s: StageData): number => s.pieces.filter((p) => p.kind === 'lantern').length; ``` ### kit/engine3d/camera.ts #### `Framing` (interface) A framing: the vertical field of view (degrees), where the camera stands and the point it looks at. ```ts interface Framing { fov: number; eye: WorldPt; look: WorldPt; } ``` #### `FramingName` (type) The framings a pack may ask for: the stage's three-quarter view, and the boss's wider, lower one. ```ts type FramingName = 'stage' | 'boss'; ``` #### `FRAMINGS` (const) The framings (the plate's stage camera, and its boss variant: 8° wider, the eye 1.6 m lower, looking up a little). ```ts const FRAMINGS: Readonly> = { stage: { fov: 30, eye: [0.3, 3.7, 13.2], look: [0.3, 1.55, -2.6] }, boss: { fov: 38, eye: [0.3, 2.1, 12.4], look: [0.6, 2.2, -2.6] }, }; ``` #### `Rect` (interface) A rectangle in CSS pixels. ```ts interface Rect { x: number; y: number; w: number; h: number; } ``` #### `fitStage` (function) Where the stage draws in a view of `w` × `h`: wide fills it; portrait letterboxes a 16:9 band across the full width, centred, the bars ink. The HUD sits over the stage's rectangle and never scales with the scaler. ```ts function fitStage(w: number, h: number, aspect: 'portrait' | 'wide'): Rect; ``` ### kit/engine3d/loader.ts #### `Role` (type) A character's role on the stage: whose hue its rim is drawn in (the member's for the player, the class's for a foe). ```ts type Role = 'player' | 'foe' | 'boss'; ``` #### `CharacterOptions` (interface) What a stage needs to know to place a character. ```ts interface CharacterOptions { /** Its name on the stage, unique: the rim, the animator and the pack call it by this. */ name: string; /** Its hue, 0–359: the member's (the player) or its class's (a foe), drawn at the dark constants on ink (D149). */ hue: number; role: Role; /** Its height on the stage in metres (1.75 unless given). */ height?: number; } ``` #### `PropSpec` (interface) A prop's spec (D143): its kind, the bone it rides, the clips it's drawn in and those it's hidden in. ```ts interface PropSpec { kind: string; bone: string; shown_in: string[]; hidden_in: string[]; } ``` #### `Prop` (interface) A prop on a character: its mesh (a child of its bone) and its spec. ```ts interface Prop { mesh: Mesh; spec: PropSpec; } ``` #### `Character` (interface) A loaded character: its holder on the stage (place and face it by this), its model, body meshes, props and clips. ```ts interface Character { options: Required; holder: Group; model: Object3D; body: Mesh[]; props: Prop[]; clips: AnimationClip[]; /** The skin's bones by name. */ bones: Map; /** The body's triangles. */ triangles: number; } ``` #### `AssetRefused` (class) Refused at load: the line says what was over or missing. ```ts class AssetRefused extends Error {} } ``` #### `attachProp` (function) Put a prop on a named bone of a character (re-parented, keeping its world pose), held to the prop budget. ```ts function attachProp(c: Pick, mesh: Mesh, spec: PropSpec): Prop; ``` #### `faceToward` (function) Turn a character's holder to face a point on the ground. ```ts function faceToward(c: Pick, x: number, z: number): void; ``` ### kit/engine3d/animator.ts #### `BONE_CHANNELS` (const) A bone channel a layer keys: a turn about x, y or z (degrees), an offset along x, y or z (character heights), a scale. ```ts const BONE_CHANNELS = ['turn_x', 'turn_y', 'turn_z', 'offset_x', 'offset_y', 'offset_z', 'scale'] as const; ``` #### `CHANNEL_RANGES` (const) Each channel's range; a key outside it is refused (the 2D tracks' ranges: rotate, offset, scale). ```ts const CHANNEL_RANGES: Record = { turn_x: [-360, 360], turn_y: [-360, 360], turn_z: [-360, 360], offset_x: [-1, 1], offset_y: [-1, 1], offset_z: [-1, 1], scale: [0.1, 4], }; ``` #### `BoneLayer` (interface) A procedural layer: one bone's channel, keyed like a 2D track (a number a key; the curve shapes the way to it). ```ts interface BoneLayer { bone: string; channel: BoneChannel; /** 100–10,000 ms */ loop_ms: number; looping: boolean; keys: Keyframe[]; } ``` #### `PlayOptions` (interface) How a clip is played: the crossfade in from what played (s), its speed (×), and whether it loops. ```ts interface PlayOptions { fade?: number; speed?: number; loop?: boolean; /** A clip that plays once fades back to this one at its end (idle unless given; null holds the last pose). */ then?: string | null; } ``` #### `DEFAULT_FADE` (const) The crossfade when none is given, seconds (the plate's). ```ts const DEFAULT_FADE = 0.12; ``` #### `layerProblems` (function) What's wrong with a layer, as short lines (none: the animator can play it). ```ts function layerProblems(l: unknown, bones?: ReadonlySet): string[]; ``` #### `Animator` (class) A character's animator. ```ts class Animator { readonly mixer: AnimationMixer; readonly actions; readonly layers: BoneLayer[]; /** The clip playing now (the one fading in), or null. */ current: string | null; constructor(private readonly c: Pick); /** Each clip's weight now (0–1). */ weights(): Record; /** Play a clip, crossfading from whatever plays. A clip already playing keeps its time unless it played once and ended. */ play(name: string, opts: PlayOptions = {}): void; /** The clip's speed (×) from now. */ speed(name: string, x: number): void; /** Add a procedural layer (checked); returns a function that removes it. */ addLayer(layer: BoneLayer): () => void; /** Advance by dt seconds: the fade, the clips, a finished clip back to `then`, then the layers and the props. */ update(dt: number): void; /** * Hold a still pose (a plate's frame, a test's): `clip` at `t` seconds, crossfaded from idle as play would have it — * its weight rising over the fade at the start and falling over it at the end — with idle at `idleT` under it. * Nothing advances: the next update carries on from here. */ pose(clip: string, t: number, idleT = t): void; /** How far each prop is drawn (0–1): the weight of the clips that show it and don't hide it. */ drawn(p: Prop): number; } ``` ### kit/host-api/rim.ts #### `RIM_DEFAULT` (const) A character's rim when nothing has set it: pass 14's look. ```ts const RIM_DEFAULT = 0.5; ``` #### `RimEnvelope` (type) A rim preset's envelope: a pulse (attack, hold, a quadratic decay back to the base) or a hold (a level with a waver). ```ts type RimEnvelope = | { kind: 'pulse'; label: string; peak: number; attack: number; hold: number; decay: number; bloom: number } | { kind: 'hold'; label: string; level: number; wave: number; period: number; bloom: number }; ``` #### `RIM_PRESETS` (const) The four presets (D147): their times in seconds; `bloom` is what each adds to the bloom's strength at its peak. ```ts const RIM_PRESETS = { parry_pulse: { kind: 'pulse', label: 'parry pulse', peak: 1.0, attack: 0.03, hold: 0.05, decay: 0.32, bloom: 0.4 }, stance_break_bloom: { kind: 'pulse', label: 'stance-break bloom', peak: 1.0, attack: 0.08, hold: 0.3, decay: 0.9, bloom: 1.6 }, low_health_dim: { kind: 'hold', label: 'low-health dim', level: 0.15, wave: 0.06, period: 1.8, bloom: 0 }, powered: { kind: 'hold', label: 'powered', level: 0.9, wave: 0.05, period: 0.6, bloom: 0.5 }, } as const satisfies Record; ``` #### `RimPreset` (type) A preset's name. ```ts type RimPreset = keyof typeof RIM_PRESETS; ``` #### `RIM_PRESET_NAMES` (const) The presets' names, in the order a preview offers them. ```ts const RIM_PRESET_NAMES = Object.keys(RIM_PRESETS) as RimPreset[]; ``` #### `RimValue` (interface) A rim at a moment: its intensity (0–1), the bloom it adds, and (a pulse) whether it has finished. ```ts interface RimValue { intensity: number; bloom: number; done: boolean; } ``` #### `clampRim` (function) A value as a rim intensity: clamped to 0–1; not a number is the default. ```ts function clampRim(v: unknown): number; ``` #### `rimEnvelope` (function) The rim `t` seconds after `name` was called on a character whose base is `base`. ```ts function rimEnvelope(name: RimPreset, base: number, t: number): RimValue; ``` #### `Rim` (class) One character's rim: a base and at most one running preset, on the caller's clock (seconds). ```ts class Rim { base; preset: RimPreset | null; at; set(v: number): number; call(name: RimPreset, at: number): void; clear(): void; /** The rim at `now`; a finished pulse clears itself. */ value(now: number): RimValue; } ``` #### `RimWho` (type) Who a rim call is for: a character's name on the stage, or `player` (the stage's player character). ```ts type RimWho = string; ``` #### `RimControl` (interface) The pack's rim control, as `host.rim`: set a base, call a preset, clear it; `who` is `player` unless named. ```ts interface RimControl { /** Set the base intensity (0–1, clamped) of `who`'s rim; returns what it became. */ (value: number, who?: RimWho): number; /** Start a preset on `who`'s rim now (a pulse ends by itself; a hold stays until `clear`). */ preset(name: RimPreset, who?: RimWho): void; /** End `who`'s preset: back to its base. */ clear(who?: RimWho): void; /** `who`'s rim at `now` (seconds on the stage's clock): what the 3D path draws. */ value(who: RimWho, now: number): RimValue; } ``` #### `rim` (const) The rim control `host.rim` is: one registry per package. ```ts const rim: RimControl = Object.assign((value: number, who: RimWho = 'player') => rimOf(who).set(value), { preset: (name: RimPreset, who: RimWho = 'player') => rimOf(who).call(name, clock()), clear: (who: RimWho = 'player') => rimOf(who).clear(), value: (who: RimWho, now: number) => rimOf(who).value(now), }); ``` #### `setRimClock` (function) The stage's clock for presets (tests and the bench drive it). ```ts function setRimClock(fn: () => number): void; ``` #### `aliasRim` (function) Let `alias` (e.g. `player`) stand for a character's name: the stage calls it for its player character. ```ts function aliasRim(alias: string, name: string): void; ``` #### `resetRims` (function) Every rim back to the default with no preset, and no alias (a new run). ```ts function resetRims(): void; ``` #### `Host3D` (type) The package's host with its rim: the same `host` object, with `rim` installed when the 3D path is in the bundle. ```ts type Host3D = Host & { rim: RimControl }; ``` #### `host3d` (const) The package's host, typed with `rim` (the same object as host-api's `host`). ```ts const host3d = host as Host3D; ``` ### kit/engine3d/look.ts #### `INK` (const) The body's ink, both themes (D146). ```ts const INK = '#07070b'; ``` #### `RIM_L` (const) D15's dark constants: a rim and an outline sit on ink in both themes, so they are drawn at these. ```ts const RIM_L = 0.76; ``` #### `rimColor` (function) A hue at the rim's constants, as a linear colour. ```ts function rimColor(hue: number): Color; ``` #### `STAGE_THEMES` (const) The stage's colours by theme (the plate's): only the stage and the HUD change with it. ```ts const STAGE_THEMES = { dark: { bg: '#07070b', fog: '#0d0f17', ground: '#050608', paper: false, grid: '#20242f', edge: '#2f3545', torii: '#2a2d3a' }, light: { bg: '#f3f4f7', fog: '#eef0f4', ground: '#eceef3', paper: true, grid: '#d3d7df', edge: '#a9afbb', torii: '#e1e4ea' }, } as const; ``` #### `CharacterLook` (interface) A character's materials and the uniforms the stage drives each frame. ```ts interface CharacterLook { body: MeshStandardNodeMaterial; prop: MeshStandardNodeMaterial; hue: UniformNode; rim: UniformNode; prop_light: UniformNode; } ``` #### `rimWidth` (const) The rim's width (0–1: the plate's 0.4). ```ts const rimWidth = uniform(0.4); ``` #### `characterLook` (function) A character's look: ink lit by the lanterns with its rim in its hue; its props as light. ```ts function characterLook(hue: number, rimDefault: number): CharacterLook; ``` #### `BuiltStage` (interface) A stage built from its data: its group, its lights, and how to show it in a theme or without haze. ```ts interface BuiltStage { group: Group; lights: PointLight[]; setMode(mode: Mode): void; setHaze(on: boolean): void; } ``` #### `buildStage` (function) Build a stage's pieces (stage.ts) into the scene; its colours follow the theme. ```ts function buildStage(scene: Scene, data: StageData): BuiltStage; ``` #### `Post` (interface) The post: the scene with its emissive target, bloom from that target, an outline per character, composed by theme. ```ts interface Post { pipeline: RenderPipeline; bloom: BloomNode; outlines: Map; /** Compose for a theme, with an outline for every character in the map (one made for each newly added). */ compose(mode: Mode): void; /** Bloom's resolution (0.5, 0.25) and the outline's down-sampling (1, 2): the scaler's steps. */ setQuality(bloomScale: number, outlineRatio: number): void; /** The outline's thickness, pixels (the plate's 1.6). */ edge: UniformNode; } ``` #### `BLOOM_STRENGTH` (const) The bloom's strength with no preset lifting it (the plate's). ```ts const BLOOM_STRENGTH = 1.0; ``` #### `makePost` (function) Make the post for a scene, a camera and the characters (each its holder and its hue uniform). ```ts function makePost(renderer: WebGPURenderer, scene: Scene, camera: Camera, characters: Map): Post; ``` ### kit/engine3d/scaler.ts #### `Quality3D` (interface) What a level draws at. ```ts interface Quality3D { /** The 3D canvas's resolution against the CSS size × the device's pixels (1, 0.75, 0.5). */ renderScale: number; /** Bloom's resolution against the frame (0.5, 0.25). */ bloomScale: number; /** The outline's down-sampling (1: full resolution, 2: half). */ outlineRatio: number; /** Haze on. */ haze: boolean; } ``` #### `STEPS_3D` (const) What each step down does, in order (level n has the first n applied). ```ts const STEPS_3D = ['render scale 1.0 → 0.75', 'render scale 0.75 → 0.5', 'bloom ½ → ¼ resolution', 'outline full → ½ resolution', 'haze off'] as const; ``` #### `quality3dAt` (function) The quality at a level (0: full). ```ts function quality3dAt(level: number): Quality3D; ``` #### `budget3dFor` (const) The budget for a display: 8.3 ms at 120 Hz (faster than 90 Hz), the 16.6 ms floor at 60 (D153). ```ts const budget3dFor = (periodMs: number): number => (periodMs < 11 ? LOCAL_TIER.budgetMs : LOCAL_TIER.floorMs); ``` #### `Frame3D` (interface) One frame's numbers: its CPU time, its GPU-synced time (null when not sampled), and the gap since the last frame. ```ts interface Frame3D { cpuMs: number; gpuMs: number | null; gapMs: number; } ``` #### `Step3D` (interface) A step taken: when, from and to which level, what changed, and the numbers it was taken on. ```ts interface Step3D { at: number; from: number; to: number; what: string; avgMs: number; budgetMs: number; } ``` #### `Scaler3D` (class) The scaler: feed it a frame each frame; read `level` and apply quality3dAt(level). ```ts class Scaler3D { level; readonly log: Step3D[]; /** A forced budget in ms (a test's), or null to follow the display. */ override: number | null; /** The display's refresh period as measured, ms (the median of the last 15 gaps; 16.7 until then). */ period(): number; /** The budget now, ms. */ budget(): number; /** The average cost over the window so far, ms. */ average(): number; /** One frame; `now` in seconds. Returns the step taken, if any. */ feed(f: Frame3D, now: number): Step3D | null; /** Go to a level now (the preview's and the bench's), with an empty window. */ force(level: number, now = 0): Step3D | null; /** Back to full quality with an empty window. */ reset(): void; } ``` ### kit/engine3d/tier.ts #### `PHONE_REFUSAL` (const) What a phone sees in place of a 3D stage. ```ts const PHONE_REFUSAL = 'This one plays on a desktop, not in a phone browser.'; ``` #### `DeviceLike` (interface) The device as far as the tier asks: a coarse pointer (a finger), the screen's shorter side in CSS pixels, the UA. ```ts interface DeviceLike { coarse: boolean; shortSide: number; userAgent: string; } ``` #### `thisDevice` (function) The device this page runs on. ```ts function thisDevice(): DeviceLike; ``` #### `PHONE_UA` (const) A phone's user agent (web/src/play/tier.ts has the same: a test holds the two the same). ```ts const PHONE_UA = /\b(iPhone|iPod)\b|Android.+Mobile|Mobile Safari|\bMobi\b/; ``` #### `isPhone` (function) A phone: a phone's user agent, or a finger for a pointer on a screen under 768 CSS pixels on its short side. ```ts function isPhone(d: DeviceLike): boolean; ``` #### `tierRefusal` (function) The line a 3D stage shows instead of itself on this device, or null when it plays here. ```ts function tierRefusal(d: DeviceLike = thisDevice()): string | null; ``` ### kit/engine3d/stages/torii-ground.json ```json { "name": "torii-ground", "field": { "x": [-7, 7], "z": [-6, 4.5] }, "pieces": [ { "kind": "ground", "size": 80 }, { "kind": "grid", "rows": 5, "rails": 7 }, { "kind": "torii", "at": [-6.6, -16], "scale": 1 }, { "kind": "torii", "at": [6.4, -18], "scale": 1 }, { "kind": "lantern", "at": [-5.6, 3.0, -9], "light": 34 }, { "kind": "lantern", "at": [5.8, 3.3, -10.5], "light": 34 }, { "kind": "haze", "dark": 0.022, "light": 0.03 } ], "places": { "player": [-1.55, 1.2], "foe": [1.35, -0.9], "boss": [1.2, -1.6] } } ```