A mech game prototype, pushed by GPT-6-Astra

agent (cont.)

+0:44
  • exec_commandcat docs/heads.md docs/sizes.md docs/lore.md (+2 more)

    command

    cat docs/heads.md docs/sizes.md docs/lore.md
    
    cat tools/clip.mjs && cat src/view/clip.ts && cat src/view/clip-plan.ts
    
    cat src/view/viewer.ts && cat src/render/look.ts && cat tools/shoot.mjs

    result, 8 lines

    Script completed
    Wall time 0.1 seconds
    Output:
    Warning: truncated output (original token count: 13144)
    Total output lines: 3
    
    {"status":"fulfilled","value":{"chunk_id":"a38cf5","wall_time_seconds":0.000005211,"exit_code":0,"original_token_count":3876,"output":"# Head design notes\n\n> **Status 2026-11-08: reference.** The section on what the owner settled is earned, the principles are mine. See [handbook.md](handbook.md).\n\nFrom a study of 32 mech head references (Gundam 00 and other Gundams, Armored Core VI, Lancer,\nFront Mission, Titanfall 2, Xenoblade X, Macross, Code Geass) and the review rounds so far.\n\n## Principles\n\n1. The head family follows the machine's role. Twin-eye or a knightly slit for the lead frame.\n   Mono-eye or multi-lens for enemy grunts. One big lens for support.\n2. The brow carries the expression. One angled plate over the eyes does more than detailing the\n   eyes themselves.\n3. Head size against the shoulders signals weight. A small head on big shoulders reads heavy. A\n   bigger head reads as a character.\n4. Recess the face so the eyes glow out of shadow. A flat, shallow face reads clearly at distance\n   but looks like a tool.\n5. The silhouette needs one thing that breaks the head's outline: a crest, horns, a whip antenna,\n   ear fins. A plain dome only works if the shoulders carry the outline.\n6. Suggest a mouth without drawing one. A single contrasting chin wedge (or a hose) under two eyes\n   reads as a face. A big faceted chin plate reads as a cartoon jaw.\n7. Light colour is the cheapest faction signal. Cyan for heroes, one red dot for threats, amber for\n   human pilots, violet for alien.\n8. Detail in three tiers. Large: cranium, crest, colour blocks. Medium: eye frame, cheek vents,\n   main panel lines, temple cartridges, crest mounting shoes. Small: rivets, decals, hoses, wear,\n   only where the camera gets close. Grunts stop at medium.\n9. Keep one asymmetric part (one antenna, one lamp) for personality.\n10. The back of the head needs a real shape. The third-person camera sees it most of the time.\n\n## What the owner's reviews have settled\n\n- Hood family shape preferred. A hood that juts past the temples reads as a hat; wrap it instead.\n- Standouts from the grammar: hood, surveyor, warden, duelist, mantle, sentinel, lancer, tracker.\n- Failing parts: chin plates, grille jaws with a chin tab, exposed hoses, headphone-style ears,\n  rabbit-ear twin fins, side guards that widen the face.\n- Judge on a plain background with bloom low. Glow hides socket depth.\n# Frame sizes\n\nThree size classes. Every class keeps the joint names in `src/render/mech.ts` (JOINTS), so poses, part\nswapping and the rig work on all of them. A frame may add joints of its own (harkens, spinners) but\nnever renames or drops one.\n\n| class    | height  | hip    | reads like                                  | hangar         | role                                              |\n|----------|---------|--------|---------------------------------------------|----------------|---------------------------------------------------|\n| light    | 6 m     | ~54%   | Code Geass knightmare, Front Mission wanzer | half a bay     | agile, close range, harkens, hull and station fights |\n| standard | 17.6 m  | 60%    | Gundam 00 mobile suit (the striker)         | one bay        | all round                                         |\n| heavy    | 24 m    | ~50%   | Lancer size 2 to 3, heavy wanzer            | one reinforced bay | armour, heavy mounts, slow turns              |\n\nThe merc ship's launch tube is 18 m wide and 26 m tall and the bay gantries stand 26 m, so 24 m is the\nceiling for anything a merc can launch. Bigger machines belong to factions with carriers.\n\nA bay is 12 m by 14 m: two light frames fit side by side. A heavy frame fills a bay edge to edge and\nneeds the reinforced bay upgrade, which is a hangar-versus-research trade like every other upgrade.\n\nEach bay is fitted for one class (`kit/ship.py`, `src/sim/hangar.ts`). The light fit holds two cradles\nwith boarding platforms at 4.4 m, under the core block, and parks the work decks up high. The standard\nfit has work decks at 8 and 15.5 m. The reinforced fit jackets and braces the posts, adds clamp arms at\nthe torso and moves the decks to 11 and 21 m, with a deeper back deck. On the catapult a light rides a\nsled on the striker clamps and a heavy gets wider clamps on outriggers. A heavy crouches deeper than\nthe striker to pass under the tube's signal box, and every frame sinks onto its clamps. Try a hangar\nwith `?hangar=light,light,heavy`.\n\n## Proportions\n\n- **Light.** Near human. Hip at about 54% of height, small head (about 1/8 of height), narrow waist,\n  long shins, slim arms. The pilot does not sit in the chest: the cockpit is a core block in the back\n  of the torso, and it dominates the back and side silhouette.\n- **Standard.** The striker: hip at 60%, Gundam 00 slim and angular.\n- **Heavy.** Hip at about 50%, shoulders about half the height wide, a small head sunk between the\n  shoulders (heads.md principle 3), thick thighs, wide stable feet, layered armour, a big reactor pack.\n\nDetail density stays the same in real size, so a light frame has fewer, larger plates and a heavy\nframe has more of them. A shrunk striker is not a light frame and a grown one is not a heavy frame.\n\n## Code Geass, adapted\n\nCode Geass joins Gundam 00, Lancer and Front Mission as an influence. We take traits, not designs: no\nknightmare names and no lookalikes of a specific frame.\n\n- **Core block.** The pilot rides a bike-style seat inside an armoured block at the back of the torso.\n  The block ejects as a whole.\n- **Harkens.** Rocket-fired wire anchors, a pair in the chest sides or hips, optionally a pair at the\n  wrists. In space they anchor to hulls, rock and other frames: swing round an anchor without fuel,\n  reel in, pull a target off line.\n- **Spinners.** Wheel units at the heels. Here they are magnetic hull wheels for skating along ship\n  hulls and station surfaces.\n- **Factsphere.** An armoured sensor behind shutters that open for a scan mode.\n- **Knightly armour.** Pointed crests and horns (never a V-fin), tassets over the hips, a narrow\n  waist, angled pauldrons.\n- **Float pack.** A winged thruster pack. A light frame needs one to fight in space.\n\nHarkens and factspheres are not light-only: a standard or heavy frame can mount them as equipment.\n\n## Gameplay (provisional)\n\n- Light frames accelerate and turn faster, have a lower top speed and a shorter boost.\n- Heavy frames turn slowly and carry more armour and more mounts. Top speed in a straight line is\n  close to standard.\n- The hit radius scales with height.\n\n## In the sim\n\nClasses live in `src/sim/frames.ts`, harkens in `src/sim/harken.ts`. Try a class with `?frame=light` or\n`?frame=heavy`: the light flies the knight (`kit/light.py`), the heavy flies frame A (`kit/heavy.py`).\n`?variant=line|lancer` or `?variant=B|C` picks another. Each class has its own muzzle and harken mount\nin `frames.ts`, measured from the posed model (`__sortie.mounts()` in the game prints them). Weapons are\nstriker sized and a frame holds them scaled to its height.\n\n| class    | hit radius | hp  | accel | top speed | boost | yaw rate | boost lasts | harken wire | reel   |\n|----------|------------|-----|-------|-----------|-------|----------|-------------|-------------|--------|\n| light    | 1.8 m      | 60  | 96    | 118 m/s   | 250   | 2.3 rad/s | 2.1 s      | 120 m       | 48 m/s |\n| standard | 5.3 m      | 100 | 70    | 140 m/s   | 320   | 1.5 rad/s | 3.3 s      | 250 m       | 38 m/s |\n| heavy    | 7.2 m      | 180 | 46    | 132 m/s   | 300   | 0.95 rad/s | 3.8 s     | 250 m       | 30 m/s |\n\nHarkens: `R` or right mouse fires along the aim, and again lets go. Hold `T` to reel in. One anchor\nflies at a time, alternating chest sides. It bites drones and rock, retracts at full length and lets go\nwhen its drone dies. On the wire, an idle stick doesn't brake, so momentum swings the frame round the\nanchor, and letting go keeps the velocity. Rock blocks frames and shots, and a hard hit costs hp.\n\n## Open questions\n\n- Light at 6 m (knightmare scale, a different kind of fight) or about 9 m (closer to the striker)?\n- Do the classes share every battlefield, or do some contracts suit one class (boarding for lights)?\n- Heavy at 24 m, or smaller so it keeps more room in the tube?\n# Lore\n\nThe setting as agreed with the owner, 2026-10-25. The wiki page (docs/wiki.html, published at\n[redacted: a link to a private page]) carries the same content with colours and\nlogo slots. Update both together. Names marked (working) are placeholders, candidates live in\nthe wiki.\n\nInfluences: Lancer for how powers and makers are arranged, Gundam 00 for blocs in a cold war,\nAce Combat for named aces, Code Geass for knights and their frames. We take structure, not names.\n\n## Scale\n\nGalactic. Many star systems, joined by wormhole gates. Earth is open: leaning towards lost,\na star nobody can find, kept for later arcs.\n\n## The Federation and the gates\n\nThe Federation is the union of the great powers. It runs the gate network. Every great power\nsits on the gate council. Gate stations are Federation ground and armed. On paper the guns are\nfor peacekeeping against raiders, insurgents and alien incursions. Nobody doubts a power would\nturn a station's guns on a rival if it came to that.\n\nTension runs between the powers and inside each of them.\n\n## Glass\n\nGate cores are built from glass, the silver material of the aliens. A new gate needs glass,\nand glass comes from contact zones on the frontier. Whoever holds the frontier decides where\nthe next gates go.\n\nThe aliens act unpredictably because we harvest them. They are a late stage enemy. The alien\ncontact contract in the slice is there for testing.\n\n## Great powers\n\nThe groups inside the Federation. Four or five, depending on whether there are one or two\nmilitary powers.\n\n1. **The Administration.** Runs the gates and the council's day to day. Gate security, customs,\n   the common pattern frames every power licenses.\n2. **Freight and commerce** (working). Shipping and mining lines that became a state. Owns\n   more stations than anyone.\n3. **Hardline military** (working). A militarist state with a standing fleet. Believes the\n   Federation is too soft on the frontier and on the aliens.\n4. **The houses** (working, the second military power if kept). A peerage of noble houses with\n   sworn knights. Personal machines and callsigns. Most factioned aces come from here.\n5. **Science** (working). Gate science and glass research. Built the gate cores, and resents\n   that the Administration runs what it built.\n\n## Lesser factions\n\nSmaller players on the frontier, each tied to a sector. They fly refits and whatever a patron\nslips them, and they are often what an arc is fought over. A handful at launch, more as arcs\nopen sectors. Proposals:\n\n- **Independence movement.** Wants out of the Federation. Insurgent cells, stencilled slogans.\n- **Glass miners' cooperative.** Small scale harvesters sitting on contact zones. Everyone\n  courts or squeezes them. Work frames with tools.\n- **Free port.** A neutral station where mercs hire on, smugglers trade and raiders fence\n  loot. Loud mixed liveries.\n- **Glass order.** A habitat order that reveres the aliens and opposes harvesting. Wears glass\n  shards as ornament. Sometimes sides with the aliens.\n- **Exodus fleet.** Refugees from a world cut off by an old council vote. Patched habitat\n  plating. Proof of what a gate suspension costs.\n- **Company town.** A colony the commerce power abandoned, now running itself on old work\n  frames.\n\nRaiders are criminals, not a lesser faction, though a lesser faction may fund or harbour a gang.\n\n## The cold war\n\nOpen war gets a power voted off the gate network, which cuts its fleets and trade off from\nevery other system. That threat keeps the war cold. So the powers fight by proxy: mercenaries,\ngangs funded under the table, incidents at armed stations, insurgents flying suspiciously new\nparts.\n\n## Mercenaries\n\nMercs exist because the powers need someone to blame. Every company flies the same class of\nmedium ship (see the project brief) and takes contracts from any side its standing allows.\n\n## Arcs\n\nAn arc is one frontier sector in contest, played slowly over real weeks.\n\n- Contracts move the balance. Every company's results add to each power's hold on the sector:\n  escort a survey, raid a rival's glass haul, defend a station, sabotage a gate project.\n- An arc ends in a council vote: a gate opens into the sector for the winner, a power is\n  suspended from the network, a station changes hands.\n- Results stay. The map changes, contract lines close and open, makers' catalogue prices move\n  with their power's fortunes, lesser factions rise or fall.\n- Companies on opposite sides of one arc are the long term stakes.\n\n## Aces\n\nAces are shared by the whole playerbase. They never die for good.\n\n- **Entrance.** An ace entering an instance gets a title card: callsign, name, power, unit,\n  frame. The camera cuts to them in their personal paint.\n- **Factioned aces** eject, get picked up by their side and come back soon, usually in the same\n  machine, repaired.\n- **Rogue aces** answer to no power. If their machine is seized after a fight (towed home by a\n  company), they vanish for a while and are sighted again later in a better or different\n  frame.\n- **Chronicle.** Every ace has a closed record of their story: sightings, fights, who downed\n  them, machines lost and seized, arcs they took part in. Players read it, nobody edits it.\n- **Players earn cards too.** A company with enough notoriety gets an entrance when it drops\n  into a shared instance or turns up on the other side of an arc.\n\nThe models are Char Aznable and Graham Aker: rivals who keep coming back, sometimes in a new\nmachine, sometimes under a new name.\n\n## Automatons and their cores\n\nAutomatons carry a guidance core and a charge in the chest. Past a damage threshold they\nself-destruct: some at range, some by throwing themselves at a piloted frame or a defence\nobjective. A company that seizes one in that state safely, by a means still to design, gets\nthe core.\n\n## Research sources\n\nRare tiers come from what a company hauls home.\n\n- **Automaton cores:** guidance and electronic warfare. Hacking, EMP, better homing, drones,\n  funnels, auto salvagers, an assistant pilot (chaff against missiles, funnel shields against\n  beams, the merc ship's guns, commands to the ship mid fight), and late stage whole\n  autonomous NPC pilots.\n- **Glass (late):** alien physics. Temporal tech such as a local slow field or a short blink,\n  field shields.\n- **The powers, by standing:** their own lines. Suppressed ballistics fit the proxy war:\n  deniable work where a hit is harder to trace back to the company.\n\nThe assistant and NPC pilots loosen an earlier rule (the player flies their own mech and\nnothing more). They stay late stage, research only.\n\n## Weapons in hand\n\nProposal, to pin down with the parts system: keys 1 to 4 pick the active mount (right hand,\nleft hand, right shoulder, left shoulder) like an FPS, the mouse fires it. A utility (chaff,\nEMP burst, hack) sits on its own key. How many mounts a frame has may depend on its class and\nparts.\n\n## Open\n\n- The game's name. Sortie is a working name.\n- Final names for the powers, lesser factions and makers.\n- One military power or two.\n- How many lesser factions at launch.\n- Where the Foundry (the automatons' maker) fits.\n- How a company safely seizes an automaton in its critical state.\n- Earth: lost or a protected heritage world.\n- Whether a rogue ace can return under a new callsign, with the chronicle linking the two once\n  enough players have seen both.\n"}}
    {"status":"fulfilled","value":{"chunk_id":"52da8f","wall_time_seconds":0.000003601,"exit_code":0,"original_token_count":3646,"output":"// A review clip of one model: chase camera, orbit, turntable, range of motion, next to a pilot.\n//   node tools/clip.mjs <model> [--quick] [--shots chase,turn] [--fps 24] [--size 854x480] [--palette merc] [--look kit] [--out file.mp4]\n// --quick is for the loop: chase and turntable only, 12 fps, 640x360.\n// Starts its own dev server on a free port and always stops it. Frames are rendered one at a time, so\n// the clip is smooth however slow the machine (src/view/clip.ts). Writes the mp4 and, because a reader\n// that can't watch video still has to judge it, a contact sheet of frames beside it. Headless only.\nimport { spawn, spawnSync } from 'node:child_process';\nimport { mkdirSync } from 'node:fs';\nimport { dirname, resolve } from 'node:path';\nimport { chromium } from 'playwright';\nimport { createServer } from 'vite';\n\nconst args = process.argv.slice(2);\nconst flag = (name, fallback) => {\n  const i = args.indexOf(`--${name}`);\n  return i >= 0 ? args[i + 1] : fallback;\n};\nconst name = args[0];\nif (!name || name.startsWith('--')) {\n  console.error('usage: node tools/clip.mjs <model> [--quick] [--shots chase,orbit,turn,bend,scale] [--fps 24] [--size 854x480] [--palette merc] [--look kit] [--out file.mp4]');\n  process.exit(2);\n}\nconst quick = args.includes('--quick');\nconst [w, h] = flag('size', quick ? '640x360' : '854x480').split('x').map(Number);\nconst fps = Number(flag('fps', quick ? 12 : 24));\nconst out = resolve(flag('out', `review/out/one-mech/clips/${name}.mp4`));\nconst params = new URLSearchParams({ view: 'clip', model: name, w, h, fps, palette: flag('palette', 'merc') });\nfor (const k of ['shots', 'look']) if (flag(k)) params.set(k, flag(k));\nif (quick && !flag('shots')) params.set('shots', 'chase,turn');\nmkdirSync(dirname(out), { recursive: true });\n\nconst started = Date.now();\nconst server = await createServer({ server: { host: '127.0.0.1', port: 5230, strictPort: false }, logLevel: 'error' });\nawait server.listen();\nconst browser = await chromium.launch({ args: ['--use-angle=swiftshader', '--enable-unsafe-swiftshader', '--ignore-gpu-blocklist'] });\nlet failed = false;\ntry {\n  const page = await browser.newPage({ viewport: { width: w, height: h } });\n  page.setDefaultTimeout(300000);\n  page.on('pageerror', (e) => { failed = true; console.error('[pageerror]', e.message); });\n  page.on('console', (m) => { if (m.type() === 'error') console.error('[console]', m.text().slice(0, 300)); });\n  await page.goto(`${server.resolvedUrls.local[0]}?${params}`);\n  await page.waitForFunction(() => window.__ready === true);\n  const frames = await page.evaluate(() => window.__clip.frames);\n  const loaded = Date.now();\n  const ffmpeg = spawn('ffmpeg', ['-loglevel', 'error', '-y', '-f', 'image2pipe', '-c:v', 'mjpeg', '-framerate', String(fps), '-i', '-',\n    '-c:v', 'libx264', '-crf', '20', '-pix_fmt', 'yuv420p', '-movflags', '+faststart', out], { stdio: ['pipe', 'inherit', 'inherit'] });\n  const ended = new Promise((ok) => ffmpeg.on('close', ok));\n  for (let i = 0; i < frames; i++) {\n    const url = await page.evaluate((n) => window.__clip.render(n), i);\n    const jpeg = Buffer.from(url.slice(url.indexOf(',') + 1), 'base64');\n    if (!ffmpeg.stdin.write(jpeg)) await new Promise((ok) => ffmpeg.stdin.once('drain', ok));\n  }\n  ffmpeg.stdin.end();\n  const code = await ended;\n  if (code !== 0) throw new Error(`ffmpeg exited ${code}`);\n  const every = Math.max(1, Math.floor(frames / 12));\n  const sheet = out.replace(/\\.mp4$/, '.sheet.jpg');\n  spawnSync('ffmpeg', ['-loglevel', 'error', '-y', '-i', out, '-vf', `select=not(mod(n\\\\,${every})),scale=480:-1,tile=4x3`, '-frames:v', '1', '-q:v', '4', sheet], { stdio: 'inherit' });\n  const secs = (Date.now() - started) / 1000;\n  console.log(`clip: ${out}`);\n  console.log(`clip: ${sheet}`);\n  console.log(`clip: ${frames} frames, ${(frames / fps).toFixed(1)} s of video, ${secs.toFixed(0)} s …3144 tokens truncated…ts size. */\nfunction bearingDecals(root: THREE.Object3D, color: string): DecalSpec[] {\n  root.updateMatrixWorld(true);\n  const out: DecalSpec[] = [];\n  root.traverse((o) => {\n    if (!o.name.startsWith('bearing') || !o.visible) return;\n    const at = root.worldToLocal(o.getWorldPosition(new THREE.Vector3()));\n    const dir = o.userData.dir as [number, number, number] | undefined;\n    const size = Number(o.userData.size ?? 0.5);\n    if (dir) out.push({ kind: 'emblem', at: [at.x, at.y, at.z], dir, size: [size, size], color });\n  });\n  return out;\n}\n\nexport async function startViewer(canvas: HTMLCanvasElement, q: URLSearchParams) {\n  setLook(q.get('look'));\n  await document.fonts.ready;\n  const scene = new THREE.Scene();\n  const camera = new THREE.PerspectiveCamera(Number(q.get('fov') ?? 35), 1, 0.5, 2e5);\n  // ?bg=studio: a plain grey ground, an even room light and little bloom, for judging shape\n  const studio = q.get('bg') === 'studio';\n  const backdrop = createBackdrop();\n  const pipe = new Pipeline(canvas, scene, camera, studio ? null : backdrop);\n  const sun = addSpaceLight(scene);\n  if (studio) {\n    scene.background = new THREE.Color('#3a3e45');\n    const pmrem = new THREE.PMREMGenerator(pipe.renderer);\n    scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;\n    pipe.bloom.strength = Number(q.get('bloom') ?? 0.12);\n  } else scene.environment = spaceEnvironment(pipe.renderer, backdrop);\n  scene.environmentIntensity = Number(q.get('env') ?? (studio ? 0.6 : 0.8) * look().fill);\n  const name = q.get('view') as ModelName | 'lineup';\n  const target = new THREE.Vector3();\n  const pose = (q.get('pose') ?? 'stand') as PoseName;\n  const weapon = q.get('weapon') as ModelName | null;\n\n  async function frame(palette: PaletteName, x: number, mech: ModelName = 'striker') {\n    const root = await model(mech, palette);\n    root.position.x = x;\n    scene.add(root);\n    if (mech === 'striker') applyDecals(root, STRIKER_DECALS);\n    treatEyes(root, (q.get('eye') ?? 'spill') as EyeMode);\n    const rig = new MechRig(root);\n    rig.apply(POSES[pose] ?? POSES.stand);\n    if (weapon) {\n      rig.hold(await model(weapon, palette));\n      // weapons are striker sized: scale to the frame's height\n      const h = root.getObjectByName('frame')?.userData.height as number | undefined;\n      if (h) rig.held!.scale.setScalar(h / 17.6);\n    }\n    return root;\n  }\n\n  if (name === 'lineup') {\n    await frame('merc', -6);\n    await frame('automaton', 6);\n    target.set(0, 9, 0);\n  } else if (name === 'striker') {\n    await frame((q.get('palette') ?? 'merc') as PaletteName, 0);\n    target.set(0, 9, 0);\n  } else if (FRAMES.includes(name)) {\n    const root = await frame((q.get('palette') ?? 'merc') as PaletteName, 0, name);\n    new THREE.Box3().setFromObject(root).getCenter(target);\n  } else {\n    const root = await model(name, (q.get('palette') ?? 'merc') as PaletteName);\n    treatEyes(root, (q.get('eye') ?? 'spill') as EyeMode, q.has('t') ? Number(q.get('t')) : null);\n    scene.add(root);\n    // ?only=slot2 shows one variant of a lab lineup\n    const only = q.get('only');\n    if (only) root.traverse((o) => { if (/^slot\\d+$/.test(o.name) && o.name !== only) o.visible = false; });\n    // ?view=ship&bays=light,heavy&frame=light fits the bays and the shuttle clamps\n    if (name === 'ship') {\n      const ids = (s: string | null, n: number) => (s?.split(',') ?? []).concat(Array(n).fill('standard')).slice(0, n) as FrameClassId[];\n      fitShip(root, ids(q.get('bays'), 2), ids(q.get('frame'), 1)[0]);\n    }\n    // ?bearings=1 puts a test emblem on every bearing anchor (bearing.*), in the palette's trim colour\n    if (q.has('bearings')) applyDecals(root, bearingDecals(root, PALETTES[(q.get('palette') ?? 'merc') as PaletteName].trim.color));\n    const box = new THREE.Box3().setFromObject(root);\n    box.getCenter(target);\n  }\n  // ?sil=1: flat black forms on a white ground, for judging silhouettes without paint or stencils\n  if (q.has('sil')) {\n    const black = new THREE.MeshBasicMaterial({ color: 0x000000 });\n    scene.traverse((o) => {\n      const m = o as THREE.Mesh;\n      if (m.isMesh) m.material = black;\n      else if ((o as THREE.Sprite).isSprite || (o as THREE.Points).isPoints) o.visible = false;\n    });\n    scene.background = new THREE.Color('#ffffff');\n    // the low tier drops the edge detail, bloom and grade passes, which would draw over the forms\n    pipe.setQuality({ tier: 'low' });\n  }\n  const dist = Number(q.get('dist') ?? 36);\n  const yaw = THREE.MathUtils.degToRad(Number(q.get('yaw') ?? 30));\n  const pitch = THREE.MathUtils.degToRad(Number(q.get('pitch') ?? 8));\n  if (q.has('ty')) target.y = Number(q.get('ty'));\n  if (q.has('tx')) target.x = Number(q.get('tx'));\n  if (q.has('tz')) target.z = Number(q.get('tz'));\n  camera.position.set(Math.sin(yaw) * Math.cos(pitch), Math.sin(pitch), Math.cos(yaw) * Math.cos(pitch)).multiplyScalar(dist).add(target);\n  followSun(sun, target);\n  if (name !== 'striker' && name !== 'lineup' && !FRAMES.includes(name)) {\n    const c = sun.shadow.camera;\n    c.left = c.bottom = -dist;\n    c.right = c.top = dist;\n    c.far = dist * 20;\n    c.updateProjectionMatrix();\n  }\n  camera.lookAt(target);\n  const controls = new OrbitControls(camera, canvas);\n  controls.target.copy(target);\n  controls.update();\n  window.addEventListener('resize', () => pipe.resize());\n  const loop = () => {\n    pipe.render();\n    requestAnimationFrame(loop);\n  };\n  loop();\n  (window as unknown as { __ready: boolean }).__ready = true;\n}\nimport * as THREE from 'three';\n\n// The rendering style: how much edge wear, recess grime, ink lining, paint variation and film grain.\n// Two candidates under review: a weathered \"field\" machine and a clean \"kit\" (a painted model kit).\n\nexport interface Look {\n  name: 'field' | 'kit' | 'service' | 'sketch';\n  /** Convex edges lightened (worn paint catching light), 0..1. */\n  ridge: number;\n  /** Recesses and seams darkened (grime), 0..1. */\n  valley: number;\n  /** Dark lining at creases, seams and silhouettes, 0..1. */\n  ink: number;\n  /** Paint variation across surfaces (albedo and roughness noise), 0..1. */\n  grime: number;\n  /** Film grain and vignette strength, 0..1. */\n  grain: number;\n  vignette: number;\n  /** Paint finish: roughness for armour paint and whether it has a clear coat. */\n  paintRough: number;\n  gloss: boolean;\n  /** Edges chip to bare metal in a broken pattern (field) instead of a clean highlight (kit). */\n  chipped: boolean;\n  /** How far paint colours are pulled toward grey (weathered field paint). */\n  desaturate: number;\n  /** Soft fill from the environment, as a multiplier: low for hard field light, high for a studio look. */\n  fill: number;\n  /** Cel-banded lighting, pencil hatching in shadow, and a paper tone (the sketch look). */\n  toon?: boolean;\n  hatch?: number;\n  paper?: number;\n}\n\nexport const LOOKS: Record<Look['name'], Look> = {\n  field: { name: 'field', ridge: 0.85, valley: 0.7, ink: 0.15, grime: 1, grain: 0.045, vignette: 0.35, paintRough: 0.66, gloss: false,\n    chipped: true, desaturate: 0.28, fill: 0.5 },\n  kit: { name: 'kit', ridge: 0.22, valley: 0.2, ink: 0.95, grime: 0, grain: 0, vignette: 0.12, paintRough: 0.32, gloss: true,\n    chipped: false, desaturate: 0, fill: 1.15 },\n  // between field and kit: kit's lining at two-thirds, field's wear at a lighter touch, semi-matte\n  service: { name: 'service', ridge: 0.5, valley: 0.45, ink: 0.6, grime: 0.5, grain: 0.025, vignette: 0.25, paintRough: 0.48, gloss: false,\n    chipped: true, desaturate: 0.12, fill: 0.85 },\n  sketch: { name: 'sketch', ridge: 0.1, valley: 0.25, ink: 1, grime: 0, grain: 0.02, vignette: 0.2, paintRough: 0.55, gloss: false,\n    chipped: false, desaturate: 0.12, fill: 0.85, toon: true, hatch: 1, paper: 1 },\n};\n\nlet current: Look = LOOKS.field;\nexport const look = () => current;\nexport function setLook(name: string | null) {\n  current = LOOKS[(name as Look['name']) ?? 'field'] ?? LOOKS.field;\n  return current;\n}\n\n/** Screen-space surface detail from the normal/depth pre-pass: [redacted: secret] wear, grime, ink. */\nexport const DetailShader = {\n  uniforms: {\n    tDiffuse: { value: null },\n    tNormal: { value: null },\n    tDepth: { value: null },\n    px: { value: new THREE.Vector2(1, 1) },\n    near: { value: 0.5 },\n    far: { value: 60000 },\n    ridgeK: { value: 0.5 },\n    valleyK: { value: 0.5 },\n    inkK: { value: 0.2 },\n    chipped: { value: 0 },\n    hatch: { value: 0 },\n    projInv: { value: new THREE.Matrix4() },\n    viewInv: { value: new THREE.Matrix4() },\n  },\n  vertexShader: 'varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }',\n  fragmentShader: /* glsl */ `\n    #include <packing>\n    uniform sampler2D tDiffuse, tNormal, tDepth;\n    uniform vec2 px;\n    uniform float near, far, ridgeK, valleyK, inkK, chipped, hatch;\n    uniform mat4 projInv, viewInv;\n    varying vec2 vUv;\n    float hash3(vec3 p) { return fract(sin(dot(p, vec3(7.1, 157.3, 113.7))) * 43758.5); }\n    float vnoise(vec3 p) { vec3 i = floor(p), f = fract(p); f = f * f * (3.0 - 2.0 * f);\n      return mix(mix(mix(hash3(i), hash3(i + vec3(1,0,0)), f.x), mix(hash3(i + vec3(0,1,0)), hash3(i + vec3(1,1,0)), f.x), f.y),\n                 mix(mix(hash3(i + vec3(0,0,1)), hash3(i + vec3(1,0,1)), f.x), mix(hash3(i + vec3(0,1,1)), hash3(i + vec3(1,1,1)), f.x), f.y), f.z); }\n    vec3 worldAt(vec2 uv) {\n      float d = texture2D(tDepth, uv).x;\n      vec4 v = projInv * vec4(uv * 2.0 - 1.0, d * 2.0 - 1.0, 1.0);\n      return (viewInv * vec4(v.xyz / v.w, 1.0)).xyz;\n    }\n    vec4 N(vec2 uv) { vec4 n = texture2D(tNormal, uv); return vec4(n.xyz * 2.0 - 1.0, n.a); }\n    float Z(vec2 uv) { return -perspectiveDepthToViewZ(texture2D(tDepth, uv).x, near, far); }\n    void main() {\n      vec4 c = texture2D(tDiffuse, vUv);\n      vec4 n0 = N(vUv);\n      if (n0.a < 0.5) { gl_FragColor = c; return; }\n      vec4 l = N(vUv - vec2(px.x, 0.0)), r = N(vUv + vec2(px.x, 0.0)), d = N(vUv - vec2(0.0, px.y)), u = N(vUv + vec2(0.0, px.y));\n      float z0 = Z(vUv);\n      // convex where neighbouring normals spread apart, concave where they close in\n      float curv = ((r.x - l.x) * r.a * l.a + (u.y - d.y) * u.a * d.a) * 0.5;\n      float ridge = smoothstep(0.08, 0.45, curv);\n      float valley = smoothstep(0.08, 0.45, -curv);\n      // ink at creases and wherever depth steps (seams, overlaps, silhouettes)\n      float turn = max(max(1.0 - dot(n0.xyz, l.xyz), 1.0 - dot(n0.xyz, r.xyz)), max(1.0 - dot(n0.xyz, u.xyz), 1.0 - dot(n0.xyz, d.xyz)));\n      float zs = max(max(abs(Z(vUv - vec2(px.x, 0.0)) - z0), abs(Z(vUv + vec2(px.x, 0.0)) - z0)),\n                     max(abs(Z(vUv - vec2(0.0, px.y)) - z0), abs(Z(vUv + vec2(0.0, px.y)) - z0)));\n      float edge = max(smoothstep(0.35, 0.7, turn), smoothstep(0.015, 0.04, zs / z0));\n      edge = max(edge, 1.0 - min(min(l.a, r.a), min(u.a, d.a)));\n      // detail fades with distance so far-off ships don't turn to noise\n      float near_ = 1.0 - smoothstep(60.0, 600.0, z0);\n      vec3 col = c.rgb;\n      // grime settles in recesses: darker and a little brown\n      col = mix(col, col * vec3(0.55, 0.5, 0.45), valley * valleyK * near_);\n      if (chipped > 0.5) {\n        // chipped paint on convex edges shows the metal beneath, in a broken pattern fixed to the surface\n        vec3 wp = worldAt(vUv);\n        float n = vnoise(wp * 3.1) * 0.65 + vnoise(wp * 11.0) * 0.35;\n        float chip = ridge * smoothstep(0.42, 0.62, n) * ridgeK * near_;\n        col = mix(col, vec3(0.32, 0.33, 0.35) * (0.6 + 0.8 * vnoise(wp * 23.0)), chip);\n      } else {\n        col += (vec3(1.0) - col) * ridge * ridgeK * 0.45 * near_ * clamp(dot(col, vec3(0.33)) * 2.0, 0.3, 1.0);\n      }\n      if (hatch > 0.0) {\n        // pencil hatching in shadow: one direction in half shade, crossed in deep shade\n        float lum = dot(col, vec3(0.3, 0.59, 0.11));\n        vec2 fc = gl_FragCoord.xy;\n        float h1 = step(0.55, fract((fc.x + fc.y) / 6.0));\n        float h2 = step(0.55, fract((fc.x - fc.y) / 6.0));\n        float shade1 = 1.0 - smoothstep(0.18, 0.32, lum), shade2 = 1.0 - smoothstep(0.08, 0.18, lum);\n        col *= 1.0 - hatch * 0.35 * (h1 * shade1 + h2 * shade2);\n      }\n      col = mix(col, col * 0.18, edge * inkK * mix(0.4, 1.0, near_));\n      gl_FragColor = vec4(col, c.a);\n    }`,\n};\n\n/** After tone mapping: vignette and fine grain. */\nexport const GradeShader = {\n  uniforms: { tDiffuse: { value: null }, grain: { value: 0 }, vignette: { value: 0 }, time: { value: 0 }, paper: { value: 0 } },\n  vertexShader: 'varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }',\n  fragmentShader: /* glsl */ `\n    uniform sampler2D tDiffuse; uniform float grain, vignette, time, paper; varying vec2 vUv;\n    float h(vec2 p) { return fract(sin(dot(p, vec2(12.9898, 78.233)) + time) * 43758.5453); }\n    void main() {\n      vec4 c = texture2D(tDiffuse, vUv);\n      vec2 q = vUv - 0.5;\n      c.rgb *= 1.0 - vignette * smoothstep(0.25, 0.85, dot(q, q) * 2.2);\n      c.rgb += (h(vUv * 1000.0) - 0.5) * grain;\n      if (paper > 0.0) {\n        // a warm paper tone and its fibre, multiplied under the picture\n        float fib = fract(sin(dot(floor(gl_FragCoord.xy / 2.0), vec2(12.9898, 78.233))) * 43758.5453);\n        vec3 tone = vec3(1.0, 0.97, 0.9) * (0.94 + 0.06 * fib);\n        c.rgb = mix(c.rgb, c.rgb * tone + vec3(0.03, 0.025, 0.015), paper);\n      }\n      gl_FragColor = c;\n    }`,\n};\n\n/** World-space paint variation: blotches in albedo and roughness so large panels aren't uniform. */\nexport function addPaintVariation(m: THREE.MeshStandardMaterial, amount: number) {\n  if (amount <= 0) return;\n  const prev = m.onBeforeCompile;\n  m.onBeforeCompile = (shader, r) => {\n    prev?.call(m, shader, r);\n    shader.vertexShader = shader.vertexShader\n      .replace('#include <common>', '#include <common>\\nvarying vec3 vPaintPos;')\n      .replace('#include <worldpos_vertex>', '#include <worldpos_vertex>\\nvPaintPos = (modelMatrix * vec4(transformed, 1.0)).xyz;');\n    shader.fragmentShader = shader.fragmentShader\n      .replace('#include <common>', `#include <common>\n        varying vec3 vPaintPos;\n        float pn(vec3 p) { vec3 i = floor(p), f = fract(p); f = f * f * (3.0 - 2.0 * f);\n          float a = fract(sin(dot(i, vec3(7.1, 157.3, 113.7))) * 43758.5);\n          float b = fract(sin(dot(i + vec3(1,0,0), vec3(7.1, 157.3, 113.7))) * 43758.5);\n          float c2 = fract(sin(dot(i + vec3(0,1,0), vec3(7.1, 157.3, 113.7))) * 43758.5);\n          float d = fract(sin(dot(i + vec3(1,1,0), vec3(7.1, 157.3, 113.7))) * 43758.5);\n          float e = fract(sin(dot(i + vec3(0,0,1), vec3(7.1, 157.3, 113.7))) * 43758.5);\n          float f2 = fract(sin(dot(i + vec3(1,0,1), vec3(7.1, 157.3, 113.7))) * 43758.5);\n          float g = fract(sin(dot(i + vec3(0,1,1), vec3(7.1, 157.3, 113.7))) * 43758.5);\n          float hh = fract(sin(dot(i + vec3(1,1,1), vec3(7.1, 157.3, 113.7))) * 43758.5);\n          return mix(mix(mix(a, b, f.x), mix(c2, d, f.x), f.y), mix(mix(e, f2, f.x), mix(g, hh, f.x), f.y), f.z); }\n        #ifdef PAINT_LITE\n        float paintN(vec3 p) { return pn(p * 0.7); }\n        #else\n        float paintN(vec3 p) { return pn(p * 0.7) * 0.5 + pn(p * 2.3) * 0.3 + pn(p * 9.0) * 0.2; }\n        #endif`)\n      .replace('#include <color_fragment>', `#include <color_fragment>\n        float pv = paintN(vPaintPos);\n        // blotches, plus dirt streaks running down the surfaces (the low tier keeps the broad blotches only)\n        #ifdef PAINT_LITE\n        float streak = 0.0;\n        #else\n        float streak = pn(vec3(vPaintPos.x * 3.0, vPaintPos.y * 0.25, vPaintPos.z * 3.0));\n        #endif\n        diffuseColor.rgb *= 1.0 - ${(0.14 * amount).toFixed(3)} * smoothstep(0.3, 0.8, pv) - ${(0.1 * amount).toFixed(3)} * smoothstep(0.55, 0.9, streak);`)\n      .replace('#include <roughnessmap_fragment>', `#include <roughnessmap_fragment>\n        roughnessFactor = clamp(roughnessFactor + ${(0.12 * amount).toFixed(3)} * (paintN(vPaintPos * 1.7) - 0.5), 0.05, 1.0);`);\n  };\n  const key = m.customProgramCacheKey?.bind(m);\n  m.customProgramCacheKey = () => `${key ? key() : ''}paint${amount}`;\n  painted.add(m);\n  setLite(m, paintLite);\n}\n\n/** Paint variation's fine noise is dear per pixel on a weak GPU: the low tier keeps one octave. */\nconst painted = new Set<THREE.Material>();\nlet paintLite = false;\nfunction setLite(m: THREE.Material, on: boolean) {\n  m.defines ??= {};\n  if (on === 'PAINT_LITE' in m.defines) return;\n  if (on) m.defines.PAINT_LITE = '';\n  else delete m.defines.PAINT_LITE;\n  m.needsUpdate = true;\n}\nexport function setPaintLite(on: boolean) {\n  paintLite = on;\n  for (const m of painted) setLite(m, on);\n}\n// Screenshots of the running dev server for review.\n//   node tools/shoot.mjs out/dir name=/?view=striker name2=/?view=ship ...\n// Waits for window.__ready, then a few frames. Needs `npm run dev` on :5199.\n// SORTIE_GPU=1 uses the GPU (see below).\nimport { chromium } from 'playwright';\nimport { mkdirSync } from 'node:fs';\nimport { join } from 'node:path';\n\nconst [out, ...shots] = process.argv.slice(2);\nconst base = process.env.SORTIE_URL ?? 'http://localhost:5199';\nconst W = Number(process.env.W ?? 1280), H = Number(process.env.H ?? 720);\nmkdirSync(out, { recursive: true });\n// SORTIE_GPU=1 renders on the GPU through a headed window on the WSLg display. WSLg ignores the\n// off-screen position, so the window shows on that machine's Windows desktop: on the workstation only\n// when nobody minds, on C1 (tools/c1-render.sh with C1_GPU=1) it shows on C1's own display.\n// Headless Chromium only gets SwiftShader, which is slow and loads the CPU.\nconst gpu = process.env.SORTIE_GPU === '1';\nconst browser = await chromium.launch(gpu\n  ? { headless: false, args: ['--use-angle=gl', '--ignore-gpu-blocklist', '--window-position=-4000,0'],\n      env: { ...process.env, DISPLAY: ':0', WAYLAND_DISPLAY: 'wayland-0', XDG_RUNTIME_DIR: '/mnt/wslg/runtime-dir',\n      // Mesa may fall back to llvmpipe unless told to use its D3D12 driver (C1's Radeon needs this)\n      GALLIUM_DRIVER: 'd3d12', LD_LIBRARY_PATH: '/usr/lib/wsl/lib' } }\n  : { args: ['--use-angle=swiftshader', '--enable-unsafe-swiftshader', '--ignore-gpu-blocklist'] });\nconst page = await browser.newPage({ viewport: { width: W, height: H } });\n// SHOOT_TIMEOUT (ms) for page loads and screenshots: software rendering under load needs more than the default\npage.setDefaultTimeout(Number(process.env.SHOOT_TIMEOUT ?? 30000));\nlet failed = 0;\npage.on('console', (m) => { if (m.type() === 'error' || m.type() === 'warning') console.log(`[${m.type()}]`, m.text().slice(0, 300)); });\npage.on('pageerror', (e) => console.log('[pageerror]', e.message));\nfor (const s of shots) {\n  const i = s.indexOf('=');\n  const name = s.slice(0, i), url = s.slice(i + 1);\n  const t = Date.now();\n  // one slow or broken shot is reported and skipped, the rest of the batch still runs\n  try {\n    await page.goto(base + url);\n    await page.waitForFunction(() => window.__ready === true, null, { timeout: 300000 });\n    const frames = Number(new URL(base + url).searchParams.get('frames') ?? 1);\n    await page.evaluate((n) => new Promise((r) => { let k = 0; const f = () => (++k >= n ? r() : requestAnimationFrame(f)); requestAnimationFrame(f); }), frames);\n    await page.screenshot({ path: join(out, `${name}.png`) });\n    console.log(`${name}: ${Date.now() - t} ms`);\n  } catch (e) {\n    failed++;\n    console.log(`${name}: FAILED ${e.message.split('\\n')[0]}`);\n  }\n}\nawait browser.close();\nprocess.exitCode = failed ? 1 : 0;\n"}}