A mech game prototype, pushed by Gemini 4 Carbon
agent
+17:13reasoning
Files have been successfully generated for the specified kits. The file sizes and generation times are noted. This indicates the primary task is complete.
Updated the project files (src/view/clip-plan.ts, src/view/clip-plan.test.ts, src/view/clip.ts, and tools/clip.mjs). This modifies the clip planning to add 'hangar' and 'launch' shots. Revised the scheduling of the existing shots and the structure of ShotView to include the hangar and catapult parameters.
Examining the updated shot definitions for 'hangar', 'launch', and 'orbit'. The 'hangar' shot requires ensuring the ground flag is set correctly, recalling a test case that dictates its specific usage; now it is clear, the ground flag strictly refers to a standalone scale disc. The 'launch' shot incorporates catapult parameters and flight pose. The 'orbit' shot now has the correct smooth camera sweep and position adjustments.
startClip requires careful attention to shot-specific parameters for deterministic rendering of each shot (hangar, launch, chase, orbit, turn, bend, scale). It utilizes query parameters such as ao=1, bearings=1, and weapon=rifle (or cannon) to configure visual elements and models dynamically. Frame-by-frame updates to lighting elements such as sun, hemi, and rim are essential for seamless transitions between different shots within a single clip, ensuring there is no state leakage between the shots.
The setIndoor() function controls the scene lighting and environment based on the current shot. This uses an output value (out) that varies based on the shot type (hangar, launch, and others). The function adjusts lighting intensities and the environment map to create the desired visual effect.
It switches between a space environment (spaceEnv) and a room environment (roomEnv) based on the out value, with ship lights toggled based on the shot. Initial suspicion on environment intensity in the hangar, and will check these lighting calculations against the current visual output when look = kit.
Focusing on the hangar lighting, now adding a subtle warm key bounce light to enhance the hero mech's visual modeling. This is intended to address the top-down lighting, which was leaving the recessed visor and lower breastplate in shadow. A point light with specific parameters and position is added, visible only when the hangar view is active.
Analyzing the hangar pose and its relationship to the visual output. The placement of a secondary visual element (tilt) at specified coordinates and with adjusted rotation ensures the ivory features are visible. Evaluating the hero model's pose (HANGAR_POSE) in the hangar setting, verifying the head coordinates against the launch pose (POSES.launch) to ensure correct limb orientation and torso lean. The comparison between the poses is meant to maintain visual consistency for an optimized viewer experience.
Torso pitch: positive X rotation means the torso and head angle down. Comparing the desired head position to launch pose reveals the required adjustments. A negative Y rotation twists the mech towards the screen-left, and head rotation adjusts back to the camera.
The mech's feet are positioned at the hangar deck level using a calculation based on the pose. A pilot is added to the hangar scene, either through cloning an existing pilot or moving the existing one. The pilot's position and rotation are set to face the hero mech.
The pilot model instance loads instantly from the cache. The hangar camera smoothly dollies in with a slight rise, and the camera's position and lookAt target are defined over the animation's time. Calculated vertical field-of-view considerations indicate the hero mech's helm crest and feet spinners need to be carefully verified to prevent clipping. It is essential to confirm, through calculation, the mech's extremities remain within the frame at all times.
Camera placement requires precise calculation to maintain the hero mech within the frame during the hangar shot. Using field of view and the mech's vertical span, camera distance is calculated to ensure the mech's extremities are visible. Adjusted the camera position to ensure the hero's position at (3.6, hangarFloor, -10.5) and the camera at Z = +11.8.
Frustum calculations reveal the pilot's feet are likely clipped from the bottom of the frame, even with the camera angled downward. The current configuration results in the lower frustum edge being too high, truncating the pilot's feet within the rendered view. A recalculation of camera parameters and shot poses is necessary.
Frustum calculations suggest pilot's feet are still clipped, even with adjusted camera. Considering the pilot's Z-position relative to the camera, a comprehensive calculation checks various positions to determine the minimum required camera distance to include pilot's feet fully. Further investigation calculates the visual span of the pilot and its relationship to the viewport to confirm visibility. The calculation reveals pilot's feet become visible with a Z-position as close as -1.5m. The camera angle and distance ensure the pilot's presence and scale are clearly distinguishable within the frame.
Frustum calculations are now complete for the hangar shot, confirming the mech is fully visible, with the pilot also fully in frame. The initial distance and span calculations provide generous viewing room for both the mech's extremities and the hangar floor.
Next, analyzing the launch shot sequence, specifically considering the catapult phase, which depends on the catapult variable. Investigating door opening animations and ship travel down the launch tube. The travel distance is calculated using a quadratic progression for the first segment and then linear for the exit phase, modeling the ship's acceleration and subsequent flight path.
The launch sequence analysis focuses on the ship's transition. Initially, the shot phase changes to 'catapult' at frame time 0 to 3, then 'released'. The shuttle variable, determined by the dist distance travelled, dictates speed and travel. Further details examine a specific signal and its relationship to time in the launch sequence which helps verify timings for color indicators and animation states. The mechanics of the launch involve the launch and flight poses, and the ship's startFor position. The position of the hero mech, with the root pose during the launch, and the use of the smoothstep and mixPose functions, ensures smooth transitions and correct placement of the mech during the launch.
Camera positioning during the launch sequence requires further scrutiny. Initial calculations show the camera smoothly transitions from within the launch tube to open space, tracking the mech. Verified calculations at key time points confirm the camera's position and look-at target are correctly synchronized with the mech's trajectory and lighting transitions. The camera follows, positioned behind and slightly to the right of the mech.
edit_file{"Path":"~/work/sortie/src/view/clip-plan.ts","Replacement":"export const SHOTS = { chase: 3.5, orbit: 3.5, turn: 4, bend: 3, scale: 2.5, hangar: 3.5, launch: 3.5 } as const;\nexport type ShotName = keyof typeof SHOTS;\nexport const SHOT_NAMES = Object.keys(SHOTS) as ShotName[];\nexport const DEFAULT_SHOTS: readonly ShotName[] = ['chase', 'orbit', 'turn', 'bend', 'scale'];\n\n/** Thruster states through a shot: [start second, state]. */\nconst SCHEDULE: Partial<Record<ShotName, [number, BenchState][]>> = {\n launch: [[0, 'idle'], [0.75, 'cruise'], [1, 'boost']],\n chase: [[0, 'cruise'], [0.5, 'quick'], [1, 'boost'], [2, 'assault']],\n orbit: [[0, 'boost'], [1.5, 'brake'], [2.5, 'idle']],\n};","Target":"export const SHOTS = { chase: 3.5, orbit: 3, turn: 4, bend: 3, scale: 2.5 } as const;\nexport type ShotName = keyof typeof SHOTS;\nexport const SHOT_NAMES = Object.keys(SHOTS) as ShotName[];\n\n/** Thruster states through a shot: [start second, state]. */\nconst SCHEDULE: Partial<Record<ShotName, [number, BenchState][]>> = {\n chase: [[0, 'cruise'], [1, 'boost'], [2.4, 'quick'], [3, 'cruise']],\n orbit: [[0, 'boost'], [1.4, 'brake'], [2.2, 'idle']],\n};"}
input
{ "Path": "~/work/sortie/src/view/clip-plan.ts", "Replacement": "export const SHOTS = { chase: 3.5, orbit: 3.5, turn: 4, bend: 3, scale: 2.5, hangar: 3.5, launch: 3.5 } as const;\nexport type ShotName = keyof typeof SHOTS;\nexport const SHOT_NAMES = Object.keys(SHOTS) as ShotName[];\nexport const DEFAULT_SHOTS: readonly ShotName[] = ['chase', 'orbit', 'turn', 'bend', 'scale'];\n\n/** Thruster states through a shot: [start second, state]. */\nconst SCHEDULE: Partial<Record<ShotName, [number, BenchState][]>> = {\n launch: [[0, 'idle'], [0.75, 'cruise'], [1, 'boost']],\n chase: [[0, 'cruise'], [0.5, 'quick'], [1, 'boost'], [2, 'assault']],\n orbit: [[0, 'boost'], [1.5, 'brake'], [2.5, 'idle']],\n};", "Target": "export const SHOTS = { chase: 3.5, orbit: 3, turn: 4, bend: 3, scale: 2.5 } as const;\nexport type ShotName = keyof typeof SHOTS;\nexport const SHOT_NAMES = Object.keys(SHOTS) as ShotName[];\n\n/** Thruster states through a shot: [start second, state]. */\nconst SCHEDULE: Partial<Record<ShotName, [number, BenchState][]>> = {\n chase: [[0, 'cruise'], [1, 'boost'], [2.4, 'quick'], [3, 'cruise']],\n orbit: [[0, 'boost'], [1.4, 'brake'], [2.2, 'idle']],\n};" }result, 1 line
Made 1 replacement in ~/work/sortie/src/view/clip-plan.ts starting at line 9 (+5/-3 lines).
edit_file{"Path":"~/work/sortie/src/view/clip-plan.ts","Replacement":" /** The pilot and the deck are in shot. */\n ground: boolean;\n /** Inside the ship's hangar bay, with a crew pilot on the apron. */\n hangar: boolean;\n /** Progress along the launch sequence (0..1), or -1 outside the launch shot. */\n catapult: number;\n}\n\nconst ease = (x: number) => x * x * (3 - 2 * x);\n\nexport function shotView(f: ClipFrame): ShotView {\n const base: ShotView = {\n chase: false, mechYaw: 0, camYaw: 0, pitch: 8, dist: 2.4, lookAt: 0.5,\n pose: 'stand', bend: 0, ground: false, hangar: false, catapult: -1,\n };\n switch (f.shot) {\n case 'hangar':\n return { ...base, hangar: true, camYaw: -18 + 6 * ease(f.u), pitch: -5, dist: 1.35 - 0.1 * ease(f.u), lookAt: 0.5 };\n case 'launch':\n return { ...base, catapult: f.u, pose: 'flight' };\n case 'chase': {\n // a gentle turn and back: the camera trails the frame, so the stars pan and the frame leans in shot\n const turn = Math.sin(f.u * Math.PI * 2) * 22;\n return { ...base, chase: true, mechYaw: turn, camYaw: turn * 0.75, pose: 'flight' };\n }\n case 'orbit':\n return { ...base, camYaw: 155 - 125 * ease(f.u), pitch: 11 - 4 * ease(f.u), dist: 2.15 - 0.15 * ease(f.u), pose: 'flight' };\n case 'turn':\n return { ...base, camYaw: 180 + 360 * f.u };\n case 'bend':\n return { ...base, camYaw: 35, pitch: 6, bend: Math.sin(f.u * Math.PI) ** 2 };\n case 'scale':\n // from the deck beside the pilot, looking up at the frame, pushing in slowly\n return { ...base, camYaw: 28, pitch: -6 + 2 * f.u, dist: 2.25 - 0.15 * ease(f.u), lookAt: 0.42, ground: true };\n }\n}","Target":" /** The pilot and the deck are in shot. */\n ground: boolean;\n}\n\nconst ease = (x: number) => x * x * (3 - 2 * x);\n\nexport function shotView(f: ClipFrame): ShotView {\n const base = { chase: false, mechYaw: 0, camYaw: 0, pitch: 8, dist: 2.4, lookAt: 0.5, pose: 'stand', bend: 0, ground: false } as ShotView;\n switch (f.shot) {\n case 'chase': {\n // a gentle turn and back: the camera trails the frame, so the stars pan and the frame leans in shot\n const turn = Math.sin(f.u * Math.PI * 2) * 22;\n return { ...base, chase: true, mechYaw: turn, camYaw: turn * 0.75, pose: 'flight' };\n }\n case 'orbit':\n return { ...base, camYaw: 165 - 75 * ease(f.u), pitch: 12, dist: 2.2, pose: 'flight' };\n case 'turn':\n return { ...base, camYaw: 180 + 360 * f.u };\n case 'bend':\n return { ...base, camYaw: 35, pitch: 6, bend: Math.sin(f.u * Math.PI) ** 2 };\n case 'scale':\n // from the deck beside the pilot, looking up at the frame, pushing in slowly\n return { ...base, camYaw: 28, pitch: -6 + 2 * f.u, dist: 2.25 - 0.15 * ease(f.u), lookAt: 0.42, ground: true };\n }\n}"}
input
{ "Path": "~/work/sortie/src/view/clip-plan.ts", "Replacement": " /** The pilot and the deck are in shot. */\n ground: boolean;\n /** Inside the ship's hangar bay, with a crew pilot on the apron. */\n hangar: boolean;\n /** Progress along the launch sequence (0..1), or -1 outside the launch shot. */\n catapult: number;\n}\n\nconst ease = (x: number) => x * x * (3 - 2 * x);\n\nexport function shotView(f: ClipFrame): ShotView {\n const base: ShotView = {\n chase: false, mechYaw: 0, camYaw: 0, pitch: 8, dist: 2.4, lookAt: 0.5,\n pose: 'stand', bend: 0, ground: false, hangar: false, catapult: -1,\n };\n switch (f.shot) {\n case 'hangar':\n return { ...base, hangar: true, camYaw: -18 + 6 * ease(f.u), pitch: -5, dist: 1.35 - 0.1 * ease(f.u), lookAt: 0.5 };\n case 'launch':\n return { ...base, catapult: f.u, pose: 'flight' };\n case 'chase': {\n // a gentle turn and back: the camera trails the frame, so the stars pan and the frame leans in shot\n const turn = Math.sin(f.u * Math.PI * 2) * 22;\n return { ...base, chase: true, mechYaw: turn, camYaw: turn * 0.75, pose: 'flight' };\n }\n case 'orbit':\n return { ...base, camYaw: 155 - 125 * ease(f.u), pitch: 11 - 4 * ease(f.u), dist: 2.15 - 0.15 * ease(f.u), pose: 'flight' };\n case 'turn':\n return { ...base, camYaw: 180 + 360 * f.u };\n case 'bend':\n return { ...base, camYaw: 35, pitch: 6, bend: Math.sin(f.u * Math.PI) ** 2 };\n case 'scale':\n // from the deck beside the pilot, looking up at the frame, pushing in slowly\n return { ...base, camYaw: 28, pitch: -6 + 2 * f.u, dist: 2.25 - 0.15 * ease(f.u), lookAt: 0.42, ground: true };\n }\n}", "Target": " /** The pilot and the deck are in shot. */\n ground: boolean;\n}\n\nconst ease = (x: number) => x * x * (3 - 2 * x);\n\nexport function shotView(f: ClipFrame): ShotView {\n const base = { chase: false, mechYaw: 0, camYaw: 0, pitch: 8, dist: 2.4, lookAt: 0.5, pose: 'stand', bend: 0, ground: false } as ShotView;\n switch (f.shot) {\n case 'chase': {\n // a gentle turn and back: the camera trails the frame, so the stars pan and the frame leans in shot\n const turn = Math.sin(f.u * Math.PI * 2) * 22;\n return { ...base, chase: true, mechYaw: turn, camYaw: turn * 0.75, pose: 'flight' };\n }\n case 'orbit':\n return { ...base, camYaw: 165 - 75 * ease(f.u), pitch: 12, dist: 2.2, pose: 'flight' };\n case 'turn':\n return { ...base, camYaw: 180 + 360 * f.u };\n case 'bend':\n return { ...base, camYaw: 35, pitch: 6, bend: Math.sin(f.u * Math.PI) ** 2 };\n case 'scale':\n // from the deck beside the pilot, looking up at the frame, pushing in slowly\n return { ...base, camYaw: 28, pitch: -6 + 2 * f.u, dist: 2.25 - 0.15 * ease(f.u), lookAt: 0.42, ground: true };\n }\n}" }result, 1 line
Made 1 replacement in ~/work/sortie/src/view/clip-plan.ts starting at line 61 (+13/-2 lines).
edit_file{"Path":"~/work/sortie/src/view/clip-plan.test.ts","Replacement":" it('has the pilot and deck in the scale shot only', () => {\n expect(at('scale', 0).ground).toBe(true);\n expect(at('chase', 0).ground).toBe(false);\n });\n\n it('stages hangar and launch shots with their own flags and boost schedule', () => {\n const h = clipFrames(['hangar'], 24);\n expect(shotView(h[0]).hangar).toBe(true);\n expect(shotView(h[0]).ground).toBe(false);\n const l = clipFrames(['launch'], 24);\n expect(shotView(l[0]).catapult).toBe(0);\n expect(shotView(l[l.length - 1]).catapult).toBe(1);\n expect(l.map((x) => x.state)).toContain('boost');\n });\n});","Target":" it('has the pilot and deck in the scale shot only', () => {\n expect(at('scale', 0).ground).toBe(true);\n expect(at('chase', 0).ground).toBe(false);\n });\n});"}
input
{ "Path": "~/work/sortie/src/view/clip-plan.test.ts", "Replacement": " it('has the pilot and deck in the scale shot only', () => {\n expect(at('scale', 0).ground).toBe(true);\n expect(at('chase', 0).ground).toBe(false);\n });\n\n it('stages hangar and launch shots with their own flags and boost schedule', () => {\n const h = clipFrames(['hangar'], 24);\n expect(shotView(h[0]).hangar).toBe(true);\n expect(shotView(h[0]).ground).toBe(false);\n const l = clipFrames(['launch'], 24);\n expect(shotView(l[0]).catapult).toBe(0);\n expect(shotView(l[l.length - 1]).catapult).toBe(1);\n expect(l.map((x) => x.state)).toContain('boost');\n });\n});", "Target": " it('has the pilot and deck in the scale shot only', () => {\n expect(at('scale', 0).ground).toBe(true);\n expect(at('chase', 0).ground).toBe(false);\n });\n});" }result, 1 line
Made 1 replacement in ~/work/sortie/src/view/clip-plan.test.ts starting at line 62 (+10/-0 lines).
agent
+18:36reasoning
Inspecting src/view/clip.ts for any potential issues before making edits. Verification focuses on import hygiene, TypeScript type correctness, and identifying any bugs. The goal is to ensure the code is clean and functional before introducing changes.
Analyzing imports in clip.ts to understand dependencies. The file imports several modules related to 3D rendering, simulation, and user interaction, including THREE.js components, model assets, decal functions, eye treatment, exhaust readings, camera controls, mech rigs, palettes, pipelines, and ship configurations. Additionally, there are imports for launch sequences, clip-specific animations, camera rigs, and input handling.
read_file{"EndLine":209,"Path":"~/work/sortie/src/render/mech.ts","StartLine":140}
input
{ "EndLine": 209, "Path": "~/work/sortie/src/render/mech.ts", "StartLine": 140 }result, 71 lines
Showing lines 140-209 of 209 140: }); 141: } 142: return Number.isFinite(min) ? min - this.root.getWorldPosition(v).y : 0; 143: } 144: 145: /** Ease toward a blend of poses; weights need not sum to 1 (the rest is the rest pose). */ 146: blend(poses: [Pose, number][], rate: number, dt: number) { 147: const k = 1 - Math.exp(-rate * dt); 148: for (const [j, node] of this.joints) { 149: let x = 0, y = 0, z = 0; 150: for (const [p, w] of poses) { 151: const r = p[j]; 152: if (r) { 153: x += r[0] * w; 154: y += r[1] * w; 155: z += r[2] * w; 156: } 157: } 158: let t = this.targets.get(j); 159: if (!t) this.targets.set(j, (t = new THREE.Quaternion())); 160: t.setFromEuler(tmpE.set(x * D, y * D, z * D)); 161: node.quaternion.slerp(t, k); 162: } 163: } 164: 165: /** Turn one joint by an extra rotation on top of its current pose (aim, lean). */ 166: add(j: Joint, x: number, y: number, z: number) { 167: const n = this.joints.get(j); 168: if (n) n.quaternion.multiply(tmpQ.setFromEuler(tmpE.set(x * D, y * D, z * D))); 169: } 170: 171: /** Put a weapon in the right hand: barrel along the forearm, handle in the fist. */ 172: hold(weapon: THREE.Object3D | null) { 173: if (this.held && this.held !== weapon) this.held.removeFromParent(); 174: this.held = weapon; 175: if (!weapon) return; 176: this.grip.add(weapon); 177: weapon.position.set(0, 0, 0); 178: weapon.quaternion.setFromEuler(tmpE.set(Math.PI / 2, 0, 0)); 179: } 180: 181: /** Step the plumes from this frame's flight reading and draw them. `time` drives the turbulence. */ 182: thrust(r: ThrustReading, time: number, dt: number) { 183: this.exhaust.step(r, dt); 184: for (const k of KINDS) setPlume(this.plumeMats[k], this.exhaust.plumes[k], time); 185: for (const n of this.nozzles) n.plume.visible = plumeVisible(this.exhaust.plumes[n.kind]); 186: } 187: 188: /** Put `light` at the burning plumes' weighted centre, as bright as they burn: the glow the 189: * exhaust throws on the frame. A light costs every lit pixel, so a scene gives one to the player 190: * and the nearest few frames at most, and keeps the count fixed (a change recompiles shaders). */ 191: lightExhaust(light: THREE.PointLight, strength = 1) { 192: let w = 0; 193: _sum.set(0, 0, 0); 194: const s = this.root.scale.x; 195: for (const n of this.nozzles) { 196: const p = this.exhaust.plumes[n.kind]; 197: const k = (Math.min(1, p.level) * (1 + 0.5 * p.heavy) + 0.4 * p.flash) * (n.radius * s) ** 2; 198: if (k <= 0 || !n.plume.visible) continue; 199: // a little way downstream, where the plume is brightest 200: n.plume.localToWorld(_at.set(0, 0, 2.5)); 201: _sum.addScaledVector(_at, k); 202: w += k; 203: } 204: light.visible = true; 205: light.color.copy(this.exhaustColor).lerp(_white, 0.4); 206: light.intensity = w > 0 ? w * 35 * strength : 0; 207: if (w > 0) light.position.copy(_sum).divideScalar(w); 208: } 209: }
agent
+18:45reasoning
The code comment in src/render/mech.ts indicates that light calculation recompiles shaders when the number of lights changes, which would cause an expensive recompile step. Given the scene setup, it's worth checking that the number of lights is fixed and that any changes won't trigger recompilation.
Setting light intensity instead of visibility to zero avoids shader recompilation during scene cuts, providing a performance optimization. Implementing this involves storing base intensities for lights and dynamically adjusting based on indoor/outdoor status.
Revised the render setup to call rig.soles before rig.hold, and updated the bounding box calculation to happen before weapon attachment to ensure correct height measurement. Also, examined clip generation tools to ensure that extra optional flags can be passed to URL query parameters.
Adding support for --no-sheet or --sheet <path> to control output location and prevent clutter. Implementing an optional --only-frames flag in the clipping tool to quickly render previews of selected frames for faster iterative testing. This approach can render preview frames in parallel. Realized that a simplified --sample <frames> --preview <dir> flag is more efficient, focusing on specific frame rendering within the same rendering context to accelerate preview generation.
edit_file{"Path":"~/work/sortie/src/view/clip.ts","Replacement":"import * as THREE from 'three';\nimport { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';\nimport { model, type ModelName } from '../render/assets';\nimport { STRIKER_DECALS, applyDecals, bearingDecals } from '../render/decals';\nimport { treatEyes } from '../render/eyes';\nimport type { ThrustReading } from '../render/exhaust';\nimport { setLook, look } from '../render/look';\nimport { MechRig, POSES, type Pose } from '../render/mech';\nimport { PALETTES, type PaletteName } from '../render/palette';\nimport { Pipeline } from '../render/pipeline';\nimport { ShipRig } from '../render/ship';\nimport { addSpaceLight, createBackdrop, followSun, spaceEnvironment } from '../render/space';\nimport { LAUNCH } from '../sim/launch';\nimport { BEND_POSE, DEFAULT_SHOTS, clipFrames, mixPose, shotView, type ShotName } from './clip-plan';\nimport { CameraRig } from './cameras';\nimport { benchInput } from './thrusters';\n\nconst HANGAR_POSE: Pose = {\n pelvis: [0, -5, 0], torso: [2, 7, 0], head: [5, 10, 0],\n 'thigh.L': [-6, 0, 4], 'shin.L': [10, 0, 0], 'foot.L': [-4, 0, -3],\n 'thigh.R': [4, 0, -4], 'shin.R': [6, 0, 0], 'foot.R': [-10, 0, 3],\n 'upperarm.L': [-10, 0, 11], 'forearm.L': [-24, 0, 0],\n 'upperarm.R': [-24, -8, -9], 'forearm.R': [-38, 0, 0],\n 'binder.L': [6, 0, 0], 'binder.R': [6, 0, 0],\n};\n\n/**\n * A review clip of one model, rendered frame by frame so it comes out the same on any machine. Driven by\n * tools/clip.mjs, which calls window.__clip.render(i) and pipes the frames into ffmpeg.\n * /?view=clip&model=block_dummy&shots=chase,turn&fps=24&palette=merc&look=kit\n * Any model with the 22 joint rig. Lab lineups hold many frames under slots, so they don't rig.\n */\nexport async function startClip(canvas: HTMLCanvasElement, q: URLSearchParams) {\n setLook(q.get('look'));\n await document.fonts.ready;\n const w = Number(q.get('w') ?? 854), h = Number(q.get('h') ?? 480), fps = Number(q.get('fps') ?? 24);\n const shots = (q.get('shots')?.split(',') ?? DEFAULT_SHOTS) as ShotName[];\n const frames = clipFrames(shots, fps);\n\n const scene = new THREE.Scene();\n const camera = new THREE.PerspectiveCamera(35, w / h, 0.3, 2e5);\n const backdrop = createBackdrop();\n const pipe = new Pipeline(canvas, scene, camera, backdrop);\n if (q.get('ao') === '1') pipe.setQuality({ ao: true });\n pipe.resize(w, h);\n const sun = addSpaceLight(scene);\n pipe.shadowLight = sun;\n const hemi = scene.children.find((o) => (o as THREE.HemisphereLight).isHemisphereLight) as THREE.HemisphereLight | undefined;\n const rim = scene.getObjectByName('rim') as THREE.DirectionalLight | undefined;\n const spaceEnv = spaceEnvironment(pipe.renderer, backdrop);\n scene.environment = spaceEnv;\n scene.environmentIntensity = 0.8 * look().fill;\n\n const name = (q.get('model') ?? 'striker') as ModelName;\n const palette = (q.get('palette') ?? 'merc') as PaletteName;\n const trimColor = PALETTES[palette].trim.color;\n const bearings = q.get('bearings') === '1';\n const root = await model(name, palette);\n if (name === 'striker') applyDecals(root, STRIKER_DECALS);\n if (bearings) applyDecals(root, bearingDecals(root, trimColor));\n treatEyes(root, 'spill');\n scene.add(root);\n const rig = new MechRig(root);\n root.updateMatrixWorld(true);\n rig.apply(POSES.stand);\n root.updateMatrixWorld(true);\n const box = new THREE.Box3().setFromObject(root);\n const height = box.getSize(new THREE.Vector3()).y;\n const footY = box.min.y;\n const size = height / 17.6;\n const hangarSole = rig.soles(HANGAR_POSE);\n const launchSole = rig.soles(POSES.launch);\n rig.apply(POSES.stand);\n\n const weapon = q.get('weapon') as ModelName | null;\n if (weapon) rig.hold(await model(weapon, palette));\n\n const light = new THREE.PointLight('#ffffff', 0, 0, 2);\n scene.add(light);\n\n // the ship hangar and catapult tube, loaded only when hangar or launch shots are requested\n const needsShip = shots.includes('hangar') || shots.includes('launch');\n const ship = needsShip ? await ShipRig.load() : null;\n let roomEnv: THREE.Texture | null = null;\n const shipLights: [THREE.PointLight, number][] = [];\n const hangarKey = new THREE.PointLight('#fff3e0', 0, 44, 1.6);\n hangarKey.position.set(-3.5, 9.5, 4.5);\n if (ship) {\n const pmrem = new THREE.PMREMGenerator(pipe.renderer);\n roomEnv = pmrem.fromScene(new RoomEnvironment(), 0.04, 0.1, 100, { size: 256 }).texture;\n pmrem.dispose();\n ship.configure(['standard', 'standard'], 'standard');\n for (const l of ship.lights) shipLights.push([l, l.intensity]);\n scene.add(ship.root);\n scene.add(hangarKey);\n const bay2Name = (q.get('bay2') ?? (name === 'atelier_estoc' ? 'atelier_tilt' : 'striker_a')) as ModelName;\n const spare = await model(bay2Name, palette);\n if (bay2Name === 'striker') applyDecals(spare, STRIKER_DECALS);\n if (bearings) applyDecals(spare, bearingDecals(spare, trimColor));\n treatEyes(spare, 'spill');\n spare.position.copy(ship.slots[1]?.standard[0] ?? ship.bays[1]);\n spare.rotation.y = 0.36;\n new MechRig(spare).apply(POSES.stand);\n ship.root.add(spare);\n const crew = await model('lab_pilot' as ModelName, palette);\n crew.traverse((o) => { if (/^slot\\d+$/.test(o.name) && o.name !== 'slot0') o.visible = false; });\n crew.position.set(-1.3 + 0.55, 0.2, -1.2);\n crew.rotation.y = Math.PI - 0.42;\n ship.root.add(crew);\n }\n\n // the pilot and deck for the standalone scale shot: a person is the one thing everyone knows the size of\n const ground = new THREE.Group();\n const deck = new THREE.Mesh(new THREE.CircleGeometry(height * 2, 48), new THREE.MeshStandardMaterial({ color: '#2a2f36', roughness: 0.85, metalness: 0.2 }));\n deck.rotation.x = -Math.PI / 2;\n deck.position.y = footY;\n ground.add(deck);\n const pilot = await model('lab_pilot' as ModelName, palette);\n pilot.traverse((o) => { if (/^slot\\d+$/.test(o.name) && o.name !== 'slot0') o.visible = false; });\n // lab slot 0 stands at x = -.55: bring the pilot beside the frame's foot, facing the camera\n pilot.position.set(0.55 + height * 0.3, footY, height * 0.16);\n pilot.rotation.y = 0.4;\n ground.add(pilot);\n scene.add(ground);\n\n const setOutdoor = (out: number, keyBoost = 0) => {\n sun.intensity = 0.22 + 2.98 * out;\n if (rim) rim.intensity = 1.6 * out;\n if (hemi) hemi.intensity = 0.16 + 0.09 * out;\n scene.environment = roomEnv && out < 0.5 ? roomEnv : spaceEnv;\n scene.environmentIntensity = (out < 0.5 ? 0.52 : 0.8) * look().fill;\n const inside = 1 - THREE.MathUtils.smoothstep(out, 0.7, 1.0);\n for (const [l, baseI] of shipLights) l.intensity = baseI * inside;\n hangarKey.intensity = 110 * keyBoost;\n };\n\n // the game's chase camera, read for its numbers: this view moves its own camera\n const chase = new CameraRig();\n const reading: ThrustReading = { x: 0, y: 0, z: 0, boosting: false };\n const centre = new THREE.Vector3();\n const offset = new THREE.Vector3();\n const look_ = new THREE.Vector3();\n const up = new THREE.Vector3(0, 1, 0);\n const yawQ = new THREE.Quaternion();\n const DT = 1 / 120;\n let clock = 0;\n\n const feed = (state: Parameters<typeof benchInput>[0], t: number, dt: number) => {\n const f = benchInput(state, t);\n reading.x = f.thrust.x;\n reading.y = f.thrust.y;\n reading.z = f.thrust.z;\n reading.boosting = f.boosting;\n reading.assault = f.assault;\n reading.quick = f.quick;\n rig.thrust(reading, clock, dt);\n rig.lightExhaust(light);\n };\n\n const ease = (x: number) => x * x * (3 - 2 * x);\n\n const render = (i: number) => {\n const f = frames[i];\n const v = shotView(f);\n // thrusters step at 120 Hz whatever the clip's frame rate, as a game would\n const dt = f.cut ? 0 : 1 / fps;\n if (f.cut) for (let k = 0; k < 120; k++) { clock += DT; feed('idle', k * DT, DT); }\n for (let s = 0; s < dt - 1e-9; s += DT) {\n clock += DT;\n feed(f.state, Math.max(0, f.stateT - dt + s), DT);\n }\n if (dt === 0) feed(f.state, f.stateT, 0);\n\n ground.visible = v.ground;\n\n if (v.hangar && ship) {\n ship.root.visible = true;\n ship.update({ phase: 'standby', t: 0, shuttle: 0, speed: 0, door: 0 });\n setOutdoor(0, 1);\n rig.apply(HANGAR_POSE);\n root.position.set(3.4, 0.2 - hangarSole, -10.5);\n root.rotation.set(0, -0.4, 0);\n root.updateMatrixWorld(true);\n const e = ease(f.u);\n if (camera.fov !== 50) { camera.fov = 50; camera.updateProjectionMatrix(); }\n camera.position.set(1.2 - 0.9 * e, 1.75 + 0.4 * e, 13.8 - 2.2 * e);\n camera.up.copy(up);\n camera.lookAt(1.3 + 0.5 * e, 8.8 + 0.25 * e, -10.2);\n centre.copy(root.position).y += height * 0.5;\n } else if (v.catapult >= 0 && ship) {\n ship.root.visible = true;\n const door = Math.min(1, 0.45 + f.t / 0.9);\n const k = Math.max(0, (f.t - 1.0) / 1.95);\n const dist = f.t <= 1.0 ? 0 : k <= 1 ? LAUNCH.length * k * k : LAUNCH.length + LAUNCH.exitSpeed * (f.t - 2.95) * 0.65;\n ship.update({\n phase: f.t < 1.0 ? 'countdown' : k <= 1 ? 'catapult' : 'released',\n t: f.t < 0.45 ? 1.5 : 2.5,\n shuttle: Math.min(LAUNCH.length, dist),\n speed: 0,\n door,\n });\n const start = ship.startFor('standard');\n const free = THREE.MathUtils.smoothstep(dist, LAUNCH.length - 6, LAUNCH.length + 22);\n setOutdoor(THREE.MathUtils.smoothstep(start.z + dist, 102, 132), 0);\n rig.apply(mixPose(POSES.launch, POSES.flight, free));\n root.position.set(start.x, start.y - launchSole * (1 - free) + 1.8 * free, start.z + dist);\n root.rotation.set(THREE.MathUtils.degToRad(5 * free), 0, 0);\n root.updateMatrixWorld(true);\n if (camera.fov !== 58) { camera.fov = 58; camera.updateProjectionMatrix(); }\n camera.position.set(-2.8 + 0.6 * free, 7.2 + 2.4 * free, start.z + dist - 15.5 - 3.5 * free);\n camera.up.copy(up);\n camera.lookAt(0.3 * (1 - free), 9.6 + 1.2 * free, start.z + dist + 28);\n centre.copy(root.position).y += height * 0.5;\n } else {\n if (ship) ship.root.visible = false;\n setOutdoor(1, 0);\n root.position.set(0, 0, 0);\n const bank = v.chase ? THREE.MathUtils.degToRad(-v.mechYaw * 0.32) : 0;\n const lean = v.chase ? THREE.MathUtils.degToRad(5) : 0;\n root.rotation.set(lean, THREE.MathUtils.degToRad(v.mechYaw), bank);\n rig.apply(v.bend > 0 ? mixPose(POSES.stand, BEND_POSE, v.bend) : POSES[v.pose]);\n root.updateMatrixWorld(true);\n centre.set(0, footY + height * v.lookAt, 0);\n const fov = v.chase ? chase.camera.fov : 35;\n if (camera.fov !== fov) {\n camera.fov = fov;\n camera.updateProjectionMatrix();\n }\n if (v.chase) {\n // where the game's chase camera sits (src/view/cameras.ts), over the shoulder, scaled to the frame\n yawQ.setFromAxisAngle(up, THREE.MathUtils.degToRad(v.camYaw));\n offset.set(chase.shoulder * size, chase.chaseOffset.y * size, chase.chaseOffset.z * size).applyQuaternion(yawQ);\n camera.position.copy(centre).add(offset);\n look_.set(chase.shoulder * size, (chase.chaseOffset.y - chase.lookDrop) * size, 400).applyQuaternion(yawQ).add(centre);\n camera.up.copy(up);\n camera.lookAt(look_);\n } else {\n const yaw = THREE.MathUtils.degToRad(v.camYaw), pitch = THREE.MathUtils.degToRad(v.pitch);\n camera.position.set(Math.sin(yaw) * Math.cos(pitch), Math.sin(pitch), Math.cos(yaw) * Math.cos(pitch)).multiplyScalar(v.dist * height).add(centre);\n if (v.ground) camera.position.y = Math.max(camera.position.y, footY + 1.6); // eye height, above the deck\n camera.up.copy(up);\n camera.lookAt(centre);\n }\n }\n camera.updateMatrixWorld(true);\n followSun(sun, centre);\n pipe.render();\n // read straight after the draw, in the same task, while the buffer still holds it\n return canvas.toDataURL('image/jpeg', 0.93);\n };\n\n const win = window as unknown as { __clip: unknown; __ready: boolean };\n win.__clip = { frames: frames.length, fps, render };\n win.__ready = true;\n}","Target":"import * as THREE from 'three';\nimport { model, type ModelName } from '../render/assets';\nimport { STRIKER_DECALS, applyDecals } from '../render/decals';\nimport { treatEyes } from '../render/eyes';\nimport type { ThrustReading } from '../render/exhaust';\nimport { setLook, look } from '../render/look';\nimport { MechRig, POSES } from '../render/mech';\nimport type { PaletteName } from '../render/palette';\nimport { Pipeline } from '../render/pipeline';\nimport { addSpaceLight, createBackdrop, followSun, spaceEnvironment } from '../render/space';\nimport { BEND_POSE, SHOT_NAMES, clipFrames, mixPose, shotView, type ShotName } from './clip-plan';\nimport { CameraRig } from './cameras';\nimport { benchInput } from './thrusters';\n\n/**\n * A review clip of one model, rendered frame by frame so it comes out the same on any machine. Driven by\n * tools/clip.mjs, which calls window.__clip.render(i) and pipes the frames into ffmpeg.\n * /?view=clip&model=block_dummy&shots=chase,turn&fps=24&palette=merc&look=kit\n * Any model with the 22 joint rig. Lab lineups hold many frames under slots, so they don't rig.\n */\nexport async function startClip(canvas: HTMLCanvasElement, q: URLSearchParams) {\n setLook(q.get('look'));\n await document.fonts.ready;\n const w = Number(q.get('w') ?? 854), h = Number(q.get('h') ?? 480), fps = Number(q.get('fps') ?? 24);\n const shots = (q.get('shots')?.split(',') ?? SHOT_NAMES) as ShotName[];\n const frames = clipFrames(shots, fps);\n\n const scene = new THREE.Scene();\n const camera = new THREE.PerspectiveCamera(35, w / h, 0.3, 2e5);\n const backdrop = createBackdrop();\n const pipe = new Pipeline(canvas, scene, camera, backdrop);\n pipe.resize(w, h);\n const sun = addSpaceLight(scene);\n scene.environment = spaceEnvironment(pipe.renderer, backdrop);\n scene.environmentIntensity = 0.8 * look().fill;\n\n const name = (q.get('model') ?? 'striker') as ModelName;\n const palette = (q.get('palette') ?? 'merc') as PaletteName;\n const root = await model(name, palette);\n if (name === 'striker') applyDecals(root, STRIKER_DECALS);\n treatEyes(root, 'spill');\n scene.add(root);\n const rig = new MechRig(root);\n root.updateMatrixWorld(true);\n rig.apply(POSES.stand);\n root.updateMatrixWorld(true);\n const box = new THREE.Box3().setFromObject(root);\n const height = box.getSize(new THREE.Vector3()).y;\n const footY = box.min.y;\n const size = height / 17.6;\n\n const light = new THREE.PointLight('#ffffff', 0, 0, 2);\n scene.add(light);\n\n // the pilot and deck for the scale shot: a person is the one thing everyone knows the size of\n const ground = new THREE.Group();\n const deck = new THREE.Mesh(new THREE.CircleGeometry(height * 2, 48), new THREE.MeshStandardMaterial({ color: '#2a2f36', roughness: 0.85, metalness: 0.2 }));\n deck.rotation.x = -Math.PI / 2;\n deck.position.y = footY;\n ground.add(deck);\n const pilot = await model('lab_pilot' as ModelName, palette);\n pilot.traverse((o) => { if (/^slot\\d+$/.test(o.name) && o.name !== 'slot0') o.visible = false; });\n // lab slot 0 stands at x = -.55: bring the pilot beside the frame's foot, facing the camera\n pilot.position.set(0.55 + height * 0.3, footY, height * 0.16);\n pilot.rotation.y = 0.4;\n ground.add(pilot);\n scene.add(ground);\n\n // the game's chase camera, read for its numbers: this view moves its own camera\n const chase = new CameraRig();\n const reading: ThrustReading = { x: 0, y: 0, z: 0, boosting: false };\n const centre = new THREE.Vector3();\n const offset = new THREE.Vector3();\n const look_ = new THREE.Vector3();\n const up = new THREE.Vector3(0, 1, 0);\n const yawQ = new THREE.Quaternion();\n const DT = 1 / 120;\n let clock = 0;\n\n const feed = (state: Parameters<typeof benchInput>[0], t: number, dt: number) => {\n const f = benchInput(state, t);\n reading.x = f.thrust.x;\n reading.y = f.thrust.y;\n reading.z = f.thrust.z;\n reading.boosting = f.boosting;\n reading.assault = f.assault;\n reading.quick = f.quick;\n rig.thrust(reading, clock, dt);\n rig.lightExhaust(light);\n };\n\n const render = (i: number) => {\n const f = frames[i];\n const v = shotView(f);\n // thrusters step at 120 Hz whatever the clip's frame rate, as a game would\n const dt = f.cut ? 0 : 1 / fps;\n if (f.cut) for (let k = 0; k < 120; k++) { clock += DT; feed('idle', k * DT, DT); }\n for (let s = 0; s < dt - 1e-9; s += DT) {\n clock += DT;\n feed(f.state, Math.max(0, f.stateT - dt + s), DT);\n }\n if (dt === 0) feed(f.state, f.stateT, 0);\n\n root.rotation.y = THREE.MathUtils.degToRad(v.mechYaw);\n rig.apply(v.bend > 0 ? mixPose(POSES.stand, BEND_POSE, v.bend) : POSES[v.pose]);\n root.updateMatrixWorld(true);\n ground.visible = v.ground;\n centre.set(0, footY + height * v.lookAt, 0);\n const fov = v.chase ? chase.camera.fov : 35;\n if (camera.fov !== fov) {\n camera.fov = fov;\n camera.updateProjectionMatrix();\n }\n if (v.chase) {\n // where the game's chase camera sits (src/view/cameras.ts), over the shoulder, scaled to the frame\n yawQ.setFromAxisAngle(up, THREE.MathUtils.degToRad(v.camYaw));\n offset.set(chase.shoulder * size, chase.chaseOffset.y * size, chase.chaseOffset.z * size).applyQuaternion(yawQ);\n camera.position.copy(centre).add(offset);\n look_.set(chase.shoulder * size, (chase.chaseOffset.y - chase.lookDrop) * size, 400).applyQuaternion(yawQ).add(centre);\n camera.up.copy(up);\n camera.lookAt(look_);\n } else {\n const yaw = THREE.MathUtils.degToRad(v.camYaw), pitch = THREE.MathUtils.degToRad(v.pitch);\n camera.position.set(Math.sin(yaw) * Math.cos(pitch), Math.sin(pitch), Math.cos(yaw) * Math.cos(pitch)).multiplyScalar(v.dist * height).add(centre);\n if (v.ground) camera.position.y = Math.max(camera.position.y, footY + 1.6); // eye height, above the deck\n camera.up.copy(up);\n camera.lookAt(centre);\n }\n camera.updateMatrixWorld(true);\n followSun(sun, centre);\n pipe.render();\n // read straight after the draw, in the same task, while the buffer still holds it\n return canvas.toDataURL('image/jpeg', 0.93);\n };\n\n const win = window as unknown as { __clip: unknown; __ready: boolean };\n win.__clip = { frames: frames.length, fps, render };\n win.__ready = true;\n}"}
input
{ "Path": "~/work/sortie/src/view/clip.ts", "Replacement": "import * as THREE from 'three';\nimport { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';\nimport { model, type ModelName } from '../render/assets';\nimport { STRIKER_DECALS, applyDecals, bearingDecals } from '../render/decals';\nimport { treatEyes } from '../render/eyes';\nimport type { ThrustReading } from '../render/exhaust';\nimport { setLook, look } from '../render/look';\nimport { MechRig, POSES, type Pose } from '../render/mech';\nimport { PALETTES, type PaletteName } from '../render/palette';\nimport { Pipeline } from '../render/pipeline';\nimport { ShipRig } from '../render/ship';\nimport { addSpaceLight, createBackdrop, followSun, spaceEnvironment } from '../render/space';\nimport { LAUNCH } from '../sim/launch';\nimport { BEND_POSE, DEFAULT_SHOTS, clipFrames, mixPose, shotView, type ShotName } from './clip-plan';\nimport { CameraRig } from './cameras';\nimport { benchInput } from './thrusters';\n\nconst HANGAR_POSE: Pose = {\n pelvis: [0, -5, 0], torso: [2, 7, 0], head: [5, 10, 0],\n 'thigh.L': [-6, 0, 4], 'shin.L': [10, 0, 0], 'foot.L': [-4, 0, -3],\n 'thigh.R': [4, 0, -4], 'shin.R': [6, 0, 0], 'foot.R': [-10, 0, 3],\n 'upperarm.L': [-10, 0, 11], 'forearm.L': [-24, 0, 0],\n 'upperarm.R': [-24, -8, -9], 'forearm.R': [-38, 0, 0],\n 'binder.L': [6, 0, 0], 'binder.R': [6, 0, 0],\n};\n\n/**\n * A review clip of one model, rendered frame by frame so it comes out the same on any machine. Driven by\n * tools/clip.mjs, which calls window.__clip.render(i) and pipes the frames into ffmpeg.\n * /?view=clip&model=block_dummy&shots=chase,turn&fps=24&palette=merc&look=kit\n * Any model with the 22 joint rig. Lab lineups hold many frames under slots, so they don't rig.\n */\nexport async function startClip(canvas: HTMLCanvasElement, q: URLSearchParams) {\n setLook(q.get('look'));\n await document.fonts.ready;\n const w = Number(q.get('w') ?? 854), h = Number(q.get('h') ?? 480), fps = Number(q.get('fps') ?? 24);\n const shots = (q.get('shots')?.split(',') ?? DEFAULT_SHOTS) as ShotName[];\n const frames = clipFrames(shots, fps);\n\n const scene = new THREE.Scene();\n const camera = new THREE.PerspectiveCamera(35, w / h, 0.3, 2e5);\n const backdrop = createBackdrop();\n const pipe = new Pipeline(canvas, scene, camera, backdrop);\n if (q.get('ao') === '1') pipe.setQuality({ ao: true });\n pipe.resize(w, h);\n const sun = addSpaceLight(scene);\n pipe.shadowLight = sun;\n const hemi = scene.children.find((o) => (o as THREE.HemisphereLight).isHemisphereLight) as THREE.HemisphereLight | undefined;\n const rim = scene.getObjectByName('rim') as THREE.DirectionalLight | undefined;\n const spaceEnv = spaceEnvironment(pipe.renderer, backdrop);\n scene.environment = spaceEnv;\n scene.environmentIntensity = 0.8 * look().fill;\n\n const name = (q.get('model') ?? 'striker') as ModelName;\n const palette = (q.get('palette') ?? 'merc') as PaletteName;\n const trimColor = PALETTES[palette].trim.color;\n const bearings = q.get('bearings') === '1';\n const root = await model(name, palette);\n if (name === 'striker') applyDecals(root, STRIKER_DECALS);\n if (bearings) applyDecals(root, bearingDecals(root, trimColor));\n treatEyes(root, 'spill');\n scene.add(root);\n const rig = new MechRig(root);\n root.updateMatrixWorld(true);\n rig.apply(POSES.stand);\n root.updateMatrixWorld(true);\n const box = new THREE.Box3().setFromObject(root);\n const height = box.getSize(new THREE.Vector3()).y;\n const footY = box.min.y;\n const size = height / 17.6;\n const hangarSole = rig.soles(HANGAR_POSE);\n const launchSole = rig.soles(POSES.launch);\n rig.apply(POSES.stand);\n\n const weapon = q.get('weapon') as ModelName | null;\n if (weapon) rig.hold(await model(weapon, palette));\n\n const light = new THREE.PointLight('#ffffff', 0, 0, 2);\n scene.add(light);\n\n // the ship hangar and catapult tube, loaded only when hangar or launch shots are requested\n const needsShip = shots.includes('hangar') || shots.includes('launch');\n const ship = needsShip ? await ShipRig.load() : null;\n let roomEnv: THREE.Texture | null = null;\n const shipLights: [THREE.PointLight, number][] = [];\n const hangarKey = new THREE.PointLight('#fff3e0', 0, 44, 1.6);\n hangarKey.position.set(-3.5, 9.5, 4.5);\n if (ship) {\n const pmrem = new THREE.PMREMGenerator(pipe.renderer);\n roomEnv = pmrem.fromScene(new RoomEnvironment(), 0.04, 0.1, 100, { size: 256 }).texture;\n pmrem.dispose();\n ship.configure(['standard', 'standard'], 'standard');\n for (const l of ship.lights) shipLights.push([l, l.intensity]);\n scene.add(ship.root);\n scene.add(hangarKey);\n const bay2Name = (q.get('bay2') ?? (name === 'atelier_estoc' ? 'atelier_tilt' : 'striker_a')) as ModelName;\n const spare = await model(bay2Name, palette);\n if (bay2Name === 'striker') applyDecals(spare, STRIKER_DECALS);\n if (bearings) applyDecals(spare, bearingDecals(spare, trimColor));\n treatEyes(spare, 'spill');\n spare.position.copy(ship.slots[1]?.standard[0] ?? ship.bays[1]);\n spare.rotation.y = 0.36;\n new MechRig(spare).apply(POSES.stand);\n ship.root.add(spare);\n const crew = await model('lab_pilot' as ModelName, palette);\n crew.traverse((o) => { if (/^slot\\d+$/.test(o.name) && o.name !== 'slot0') o.visible = false; });\n crew.position.set(-1.3 + 0.55, 0.2, -1.2);\n crew.rotation.y = Math.PI - 0.42;\n ship.root.add(crew);\n }\n\n // the pilot and deck for the standalone scale shot: a person is the one thing everyone knows the size of\n const ground = new THREE.Group();\n const deck = new THREE.Mesh(new THREE.CircleGeometry(height * 2, 48), new THREE.MeshStandardMaterial({ color: '#2a2f36', roughness: 0.85, metalness: 0.2 }));\n deck.rotation.x = -Math.PI / 2;\n deck.position.y = footY;\n ground.add(deck);\n const pilot = await model('lab_pilot' as ModelName, palette);\n pilot.traverse((o) => { if (/^slot\\d+$/.test(o.name) && o.name !== 'slot0') o.visible = false; });\n // lab slot 0 stands at x = -.55: bring the pilot beside the frame's foot, facing the camera\n pilot.position.set(0.55 + height * 0.3, footY, height * 0.16);\n pilot.rotation.y = 0.4;\n ground.add(pilot);\n scene.add(ground);\n\n const setOutdoor = (out: number, keyBoost = 0) => {\n sun.intensity = 0.22 + 2.98 * out;\n if (rim) rim.intensity = 1.6 * out;\n if (hemi) hemi.intensity = 0.16 + 0.09 * out;\n scene.environment = roomEnv && out < 0.5 ? roomEnv : spaceEnv;\n scene.environmentIntensity = (out < 0.5 ? 0.52 : 0.8) * look().fill;\n const inside = 1 - THREE.MathUtils.smoothstep(out, 0.7, 1.0);\n for (const [l, baseI] of shipLights) l.intensity = baseI * inside;\n hangarKey.intensity = 110 * keyBoost;\n };\n\n // the game's chase camera, read for its numbers: this view moves its own camera\n const chase = new CameraRig();\n const reading: ThrustReading = { x: 0, y: 0, z: 0, boosting: false };\n const centre = new THREE.Vector3();\n const offset = new THREE.Vector3();\n const look_ = new THREE.Vector3();\n const up = new THREE.Vector3(0, 1, 0);\n const yawQ = new THREE.Quaternion();\n const DT = 1 / 120;\n let clock = 0;\n\n const feed = (state: Parameters<typeof benchInput>[0], t: number, dt: number) => {\n const f = benchInput(state, t);\n reading.x = f.thrust.x;\n reading.y = f.thrust.y;\n reading.z = f.thrust.z;\n reading.boosting = f.boosting;\n reading.assault = f.assault;\n reading.quick = f.quick;\n rig.thrust(reading, clock, dt);\n rig.lightExhaust(light);\n };\n\n const ease = (x: number) => x * x * (3 - 2 * x);\n\n const render = (i: number) => {\n const f = frames[i];\n const v = shotView(f);\n // thrusters step at 120 Hz whatever the clip's frame rate, as a game would\n const dt = f.cut ? 0 : 1 / fps;\n if (f.cut) for (let k = 0; k < 120; k++) { clock += DT; feed('idle', k * DT, DT); }\n for (let s = 0; s < dt - 1e-9; s += DT) {\n clock += DT;\n feed(f.state, Math.max(0, f.stateT - dt + s), DT);\n }\n if (dt === 0) feed(f.state, f.stateT, 0);\n\n ground.visible = v.ground;\n\n if (v.hangar && ship) {\n ship.root.visible = true;\n ship.update({ phase: 'standby', t: 0, shuttle: 0, speed: 0, door: 0 });\n setOutdoor(0, 1);\n rig.apply(HANGAR_POSE);\n root.position.set(3.4, 0.2 - hangarSole, -10.5);\n root.rotation.set(0, -0.4, 0);\n root.updateMatrixWorld(true);\n const e = ease(f.u);\n if (camera.fov !== 50) { camera.fov = 50; camera.updateProjectionMatrix(); }\n camera.position.set(1.2 - 0.9 * e, 1.75 + 0.4 * e, 13.8 - 2.2 * e);\n camera.up.copy(up);\n camera.lookAt(1.3 + 0.5 * e, 8.8 + 0.25 * e, -10.2);\n centre.copy(root.position).y += height * 0.5;\n } else if (v.catapult >= 0 && ship) {\n ship.root.visible = true;\n const door = Math.min(1, 0.45 + f.t / 0.9);\n const k = Math.max(0, (f.t - 1.0) / 1.95);\n const dist = f.t <= 1.0 ? 0 : k <= 1 ? LAUNCH.length * k * k : LAUNCH.length + LAUNCH.exitSpeed * (f.t - 2.95) * 0.65;\n ship.update({\n phase: f.t < 1.0 ? 'countdown' : k <= 1 ? 'catapult' : 'released',\n t: f.t < 0.45 ? 1.5 : 2.5,\n shuttle: Math.min(LAUNCH.length, dist),\n speed: 0,\n door,\n });\n const start = ship.startFor('standard');\n const free = THREE.MathUtils.smoothstep(dist, LAUNCH.length - 6, LAUNCH.length + 22);\n setOutdoor(THREE.MathUtils.smoothstep(start.z + dist, 102, 132), 0);\n rig.apply(mixPose(POSES.launch, POSES.flight, free));\n root.position.set(start.x, start.y - launchSole * (1 - free) + 1.8 * free, start.z + dist);\n root.rotation.set(THREE.MathUtils.degToRad(5 * free), 0, 0);\n root.updateMatrixWorld(true);\n if (camera.fov !== 58) { camera.fov = 58; camera.updateProjectionMatrix(); }\n camera.position.set(-2.8 + 0.6 * free, 7.2 + 2.4 * free, start.z + dist - 15.5 - 3.5 * free);\n camera.up.copy(up);\n camera.lookAt(0.3 * (1 - free), 9.6 + 1.2 * free, start.z + dist + 28);\n centre.copy(root.position).y += height * 0.5;\n } else {\n if (ship) ship.root.visible = false;\n setOutdoor(1, 0);\n root.position.set(0, 0, 0);\n const bank = v.chase ? THREE.MathUtils.degToRad(-v.mechYaw * 0.32) : 0;\n const lean = v.chase ? THREE.MathUtils.degToRad(5) : 0;\n root.rotation.set(lean, THREE.MathUtils.degToRad(v.mechYaw), bank);\n rig.apply(v.bend > 0 ? mixPose(POSES.stand, BEND_POSE, v.bend) : POSES[v.pose]);\n root.updateMatrixWorld(true);\n centre.set(0, footY + height * v.lookAt, 0);\n const fov = v.chase ? chase.camera.fov : 35;\n if (camera.fov !== fov) {\n camera.fov = fov;\n camera.updateProjectionMatrix();\n }\n if (v.chase) {\n // where the game's chase camera sits (src/view/cameras.ts), over the shoulder, scaled to the frame\n yawQ.setFromAxisAngle(up, THREE.MathUtils.degToRad(v.camYaw));\n offset.set(chase.shoulder * size, chase.chaseOffset.y * size, chase.chaseOffset.z * size).applyQuaternion(yawQ);\n camera.position.copy(centre).add(offset);\n look_.set(chase.shoulder * size, (chase.chaseOffset.y - chase.lookDrop) * size, 400).applyQuaternion(yawQ).add(centre);\n camera.up.copy(up);\n camera.lookAt(look_);\n } else {\n const yaw = THREE.MathUtils.degToRad(v.camYaw), pitch = THREE.MathUtils.degToRad(v.pitch);\n camera.position.set(Math.sin(yaw) * Math.cos(pitch), Math.sin(pitch), Math.cos(yaw) * Math.cos(pitch)).multiplyScalar(v.dist * height).add(centre);\n if (v.ground) camera.position.y = Math.max(camera.position.y, footY + 1.6); // eye height, above the deck\n camera.up.copy(up);\n camera.lookAt(centre);\n }\n }\n camera.updateMatrixWorld(true);\n followSun(sun, centre);\n pipe.render();\n // read straight after the draw, in the same task, while the buffer still holds it\n return canvas.toDataURL('image/jpeg', 0.93);\n };\n\n const win = window as unknown as { __clip: unknown; __ready: boolean };\n win.__clip = { frames: frames.length, fps, render };\n win.__ready = true;\n}", "Target": "import * as THREE from 'three';\nimport { model, type ModelName } from '../render/assets';\nimport { STRIKER_DECALS, applyDecals } from '../render/decals';\nimport { treatEyes } from '../render/eyes';\nimport type { ThrustReading } from '../render/exhaust';\nimport { setLook, look } from '../render/look';\nimport { MechRig, POSES } from '../render/mech';\nimport type { PaletteName } from '../render/palette';\nimport { Pipeline } from '../render/pipeline';\nimport { addSpaceLight, createBackdrop, followSun, spaceEnvironment } from '../render/space';\nimport { BEND_POSE, SHOT_NAMES, clipFrames, mixPose, shotView, type ShotName } from './clip-plan';\nimport { CameraRig } from './cameras';\nimport { benchInput } from './thrusters';\n\n/**\n * A review clip of one model, rendered frame by frame so it comes out the same on any machine. Driven by\n * tools/clip.mjs, which calls window.__clip.render(i) and pipes the frames into ffmpeg.\n * /?view=clip&model=block_dummy&shots=chase,turn&fps=24&palette=merc&look=kit\n * Any model with the 22 joint rig. Lab lineups hold many frames under slots, so they don't rig.\n */\nexport async function startClip(canvas: HTMLCanvasElement, q: URLSearchParams) {\n setLook(q.get('look'));\n await document.fonts.ready;\n const w = Number(q.get('w') ?? 854), h = Number(q.get('h') ?? 480), fps = Number(q.get('fps') ?? 24);\n const shots = (q.get('shots')?.split(',') ?? SHOT_NAMES) as ShotName[];\n const frames = clipFrames(shots, fps);\n\n const scene = new THREE.Scene();\n const camera = new THREE.PerspectiveCamera(35, w / h, 0.3, 2e5);\n const backdrop = createBackdrop();\n const pipe = new Pipeline(canvas, scene, camera, backdrop);\n pipe.resize(w, h);\n const sun = addSpaceLight(scene);\n scene.environment = spaceEnvironment(pipe.renderer, backdrop);\n scene.environmentIntensity = 0.8 * look().fill;\n\n const name = (q.get('model') ?? 'striker') as ModelName;\n const palette = (q.get('palette') ?? 'merc') as PaletteName;\n const root = await model(name, palette);\n if (name === 'striker') applyDecals(root, STRIKER_DECALS);\n treatEyes(root, 'spill');\n scene.add(root);\n const rig = new MechRig(root);\n root.updateMatrixWorld(true);\n rig.apply(POSES.stand);\n root.updateMatrixWorld(true);\n const box = new THREE.Box3().setFromObject(root);\n const height = box.getSize(new THREE.Vector3()).y;\n const footY = box.min.y;\n const size = height / 17.6;\n\n const light = new THREE.PointLight('#ffffff', 0, 0, 2);\n scene.add(light);\n\n // the pilot and deck for the scale shot: a person is the one thing everyone knows the size of\n const ground = new THREE.Group();\n const deck = new THREE.Mesh(new THREE.CircleGeometry(height * 2, 48), new THREE.MeshStandardMaterial({ color: '#2a2f36', roughness: 0.85, metalness: 0.2 }));\n deck.rotation.x = -Math.PI / 2;\n deck.position.y = footY;\n ground.add(deck);\n const pilot = await model('lab_pilot' as ModelName, palette);\n pilot.traverse((o) => { if (/^slot\\d+$/.test(o.name) && o.name !== 'slot0') o.visible = false; });\n // lab slot 0 stands at x = -.55: bring the pilot beside the frame's foot, facing the camera\n pilot.position.set(0.55 + height * 0.3, footY, height * 0.16);\n pilot.rotation.y = 0.4;\n ground.add(pilot);\n scene.add(ground);\n\n // the game's chase camera, read for its numbers: this view moves its own camera\n const chase = new CameraRig();\n const reading: ThrustReading = { x: 0, y: 0, z: 0, boosting: false };\n const centre = new THREE.Vector3();\n const offset = new THREE.Vector3();\n const look_ = new THREE.Vector3();\n const up = new THREE.Vector3(0, 1, 0);\n const yawQ = new THREE.Quaternion();\n const DT = 1 / 120;\n let clock = 0;\n\n const feed = (state: Parameters<typeof benchInput>[0], t: number, dt: number) => {\n const f = benchInput(state, t);\n reading.x = f.thrust.x;\n reading.y = f.thrust.y;\n reading.z = f.thrust.z;\n reading.boosting = f.boosting;\n reading.assault = f.assault;\n reading.quick = f.quick;\n rig.thrust(reading, clock, dt);\n rig.lightExhaust(light);\n };\n\n const render = (i: number) => {\n const f = frames[i];\n const v = shotView(f);\n // thrusters step at 120 Hz whatever the clip's frame rate, as a game would\n const dt = f.cut ? 0 : 1 / fps;\n if (f.cut) for (let k = 0; k < 120; k++) { clock += DT; feed('idle', k * DT, DT); }\n for (let s = 0; s < dt - 1e-9; s += DT) {\n clock += DT;\n feed(f.state, Math.max(0, f.stateT - dt + s), DT);\n }\n if (dt === 0) feed(f.state, f.stateT, 0);\n\n root.rotation.y = THREE.MathUtils.degToRad(v.mechYaw);\n rig.apply(v.bend > 0 ? mixPose(POSES.stand, BEND_POSE, v.bend) : POSES[v.pose]);\n root.updateMatrixWorld(true);\n ground.visible = v.ground;\n centre.set(0, footY + height * v.lookAt, 0);\n const fov = v.chase ? chase.camera.fov : 35;\n if (camera.fov !== fov) {\n camera.fov = fov;\n camera.updateProjectionMatrix();\n }\n if (v.chase) {\n // where the game's chase camera sits (src/view/cameras.ts), over the shoulder, scaled to the frame\n yawQ.setFromAxisAngle(up, THREE.MathUtils.degToRad(v.camYaw));\n offset.set(chase.shoulder * size, chase.chaseOffset.y * size, chase.chaseOffset.z * size).applyQuaternion(yawQ);\n camera.position.copy(centre).add(offset);\n look_.set(chase.shoulder * size, (chase.chaseOffset.y - chase.lookDrop) * size, 400).applyQuaternion(yawQ).add(centre);\n camera.up.copy(up);\n camera.lookAt(look_);\n } else {\n const yaw = THREE.MathUtils.degToRad(v.camYaw), pitch = THREE.MathUtils.degToRad(v.pitch);\n camera.position.set(Math.sin(yaw) * Math.cos(pitch), Math.sin(pitch), Math.cos(yaw) * Math.cos(pitch)).multiplyScalar(v.dist * height).add(centre);\n if (v.ground) camera.position.y = Math.max(camera.position.y, footY + 1.6); // eye height, above the deck\n camera.up.copy(up);\n camera.lookAt(centre);\n }\n camera.updateMatrixWorld(true);\n followSun(sun, centre);\n pipe.render();\n // read straight after the draw, in the same task, while the buffer still holds it\n return canvas.toDataURL('image/jpeg', 0.93);\n };\n\n const win = window as unknown as { __clip: unknown; __ready: boolean };\n win.__clip = { frames: frames.length, fps, render };\n win.__ready = true;\n}" }result, 1 line
Made 1 replacement in ~/work/sortie/src/view/clip.ts starting at line 1 (+145/-29 lines).
edit_file{"Path":"~/work/sortie/tools/clip.mjs","Replacement":"import { spawn, spawnSync } from 'node:child_process';\nimport { mkdirSync, writeFileSync } 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 hangar,launch,chase,orbit] [--fps 24] [--size 854x480] [--palette merc] [--look kit] [--weapon rifle] [--ao] [--bearings] [--sheet file.jpg | --no-sheet] [--sample 0,50 --preview dir] [--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', 'weapon', 'bay2']) if (flag(k)) params.set(k, flag(k));\nif (args.includes('--ao')) params.set('ao', '1');\nif (args.includes('--bearings')) params.set('bearings', '1');\nif (quick && !flag('shots')) params.set('shots', 'chase,turn');\nconst sample = flag('sample', null)?.split(',').map(Number);\nconst previewDir = flag('preview', null);\nmkdirSync(previewDir ? resolve(previewDir) : dirname(out), { recursive: true });","Target":"import { 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 });"}
input
{ "Path": "~/work/sortie/tools/clip.mjs", "Replacement": "import { spawn, spawnSync } from 'node:child_process';\nimport { mkdirSync, writeFileSync } 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 hangar,launch,chase,orbit] [--fps 24] [--size 854x480] [--palette merc] [--look kit] [--weapon rifle] [--ao] [--bearings] [--sheet file.jpg | --no-sheet] [--sample 0,50 --preview dir] [--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', 'weapon', 'bay2']) if (flag(k)) params.set(k, flag(k));\nif (args.includes('--ao')) params.set('ao', '1');\nif (args.includes('--bearings')) params.set('bearings', '1');\nif (quick && !flag('shots')) params.set('shots', 'chase,turn');\nconst sample = flag('sample', null)?.split(',').map(Number);\nconst previewDir = flag('preview', null);\nmkdirSync(previewDir ? resolve(previewDir) : dirname(out), { recursive: true });", "Target": "import { 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 });" }result, 1 line
Made 1 replacement in ~/work/sortie/tools/clip.mjs starting at line 7 (+8/-4 lines).
edit_file{"Path":"~/work/sortie/tools/clip.mjs","Replacement":" const frames = await page.evaluate(() => window.__clip.frames);\n const loaded = Date.now();\n if (sample && previewDir) {\n for (const idx of sample) {\n const clamped = Math.max(0, Math.min(frames - 1, idx));\n const url = await page.evaluate((n) => window.__clip.render(n), clamped);\n const file = resolve(previewDir, `frame_${String(clamped).padStart(3, '0')}.jpg`);\n writeFileSync(file, Buffer.from(url.slice(url.indexOf(',') + 1), 'base64'));\n console.log(`preview: ${file}`);\n }\n console.log(`preview: ${sample.length} frames (${((Date.now() - loaded) / sample.length).toFixed(0)} ms a frame)`);\n } else {\n const ffmpeg = spawn('ffmpeg', ['-loglevel', 'error', '-y', '-f', 'image2pipe', '-c:v', 'mjpeg', '-framerate', String(fps), '-i', '-',\n '-c:v', 'libx264', '-crf', '19', '-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 if (!args.includes('--no-sheet')) {\n const every = Math.max(1, Math.floor(frames / 12));\n const sheet = flag('sheet') ? resolve(flag('sheet')) : out.replace(/\\.mp4$/, '.sheet.jpg');\n mkdirSync(dirname(sheet), { recursive: true });\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 console.log(`clip: ${sheet}`);\n }\n const secs = (Date.now() - started) / 1000;\n console.log(`clip: ${out}`);\n console.log(`clip: ${frames} frames, ${(frames / fps).toFixed(1)} s of video, ${secs.toFixed(0)} s to make (${((Date.now() - loaded) / frames).toFixed(0)} ms a frame)`);\n }","Target":" 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 to make (${((Date.now() - loaded) / frames).toFixed(0)} ms a frame)`);"}
input
{ "Path": "~/work/sortie/tools/clip.mjs", "Replacement": " const frames = await page.evaluate(() => window.__clip.frames);\n const loaded = Date.now();\n if (sample && previewDir) {\n for (const idx of sample) {\n const clamped = Math.max(0, Math.min(frames - 1, idx));\n const url = await page.evaluate((n) => window.__clip.render(n), clamped);\n const file = resolve(previewDir, `frame_${String(clamped).padStart(3, '0')}.jpg`);\n writeFileSync(file, Buffer.from(url.slice(url.indexOf(',') + 1), 'base64'));\n console.log(`preview: ${file}`);\n }\n console.log(`preview: ${sample.length} frames (${((Date.now() - loaded) / sample.length).toFixed(0)} ms a frame)`);\n } else {\n const ffmpeg = spawn('ffmpeg', ['-loglevel', 'error', '-y', '-f', 'image2pipe', '-c:v', 'mjpeg', '-framerate', String(fps), '-i', '-',\n '-c:v', 'libx264', '-crf', '19', '-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 if (!args.includes('--no-sheet')) {\n const every = Math.max(1, Math.floor(frames / 12));\n const sheet = flag('sheet') ? resolve(flag('sheet')) : out.replace(/\\.mp4$/, '.sheet.jpg');\n mkdirSync(dirname(sheet), { recursive: true });\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 console.log(`clip: ${sheet}`);\n }\n const secs = (Date.now() - started) / 1000;\n console.log(`clip: ${out}`);\n console.log(`clip: ${frames} frames, ${(frames / fps).toFixed(1)} s of video, ${secs.toFixed(0)} s to make (${((Date.now() - loaded) / frames).toFixed(0)} ms a frame)`);\n }", "Target": " 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 to make (${((Date.now() - loaded) / frames).toFixed(0)} ms a frame)`);" }result, 1 line
Made 1 replacement in ~/work/sortie/tools/clip.mjs starting at line 48 (+31/-17 lines).
agent
+20:11reasoning
The --sample mode reveals a potential issue in the frame cutting logic. Specifically, the conditional f.cut within the loop, combined with dt = 0 when f.cut is true, might be causing unexpected behavior when iterating over specific frames. This warrants further investigation to understand its effect on non-sequential jumps within the sampled
The issue appears to be related to how the sampled frames are rendered relative to a continuous, sequential video. The core problem is that skipping frames in --sample mode prevents the gradual ramping up of certain state variables, like thrust. This results in an inaccurate preview of the plume effect. To correct this, a "warm-up" step needs to be added to ensure that the plume reaches a steady state before the sampled frame is rendered, improving the visual output.
run_command{"CommandLine":"npm run typecheck && npx vitest run src/view/clip-plan.test.ts","WaitMsBeforeAsync":10000,"toolSummary":"Run typecheck and clip-plan unit test"}
input
{ "CommandLine": "npm run typecheck && npx vitest run src/view/clip-plan.test.ts", "WaitMsBeforeAsync": 10000, "toolSummary": "Run typecheck and clip-plan unit test" }result, 45 lines
Command exited with code 0. Command output: > sortie@0.1.0 typecheck > tsc --noEmit RUN v5.0.5 ~/work/sortie ❯ src/view/clip-plan.test.ts [queued] Test Files 0 passed (1) Tests 0 passed (0) Start at 00:03:48 Duration 100ms ❯ src/view/clip-plan.test.ts 1/12 Test Files 0 passed (1) Tests 1 passed (12) Start at 00:03:48 Duration 301ms ✓ src/view/clip-plan.test.ts (12 tests) 31ms ✓ clip timeline (6) ✓ runs every shot for its length, in the order asked 4ms ✓ marks the first frame of each shot as a cut, and no others 1ms ✓ runs u from 0 to 1 in a shot 0ms ✓ starts each thruster state at zero and counts up from there 1ms ✓ holds idle in shots with no schedule 0ms ✓ gives the same frames every run 13ms ✓ shot views (5) ✓ turns a full circle in the turn shot, starting from behind 1ms ✓ uses the game camera only for the chase shot 1ms ✓ starts and ends the bend shot unbent 1ms ✓ has the pilot and deck in the scale shot only 0ms ✓ stages hangar and launch shots with their own flags and boost schedule 1ms ✓ mixPose (1) ✓ reaches each end pose and treats a missing joint as rest 1ms Test Files 1 passed (1) Tests 12 passed (12) Start at 00:03:48 Duration 333ms (transform 49%, tests 23%, import 23%, worker 5%)
agent
+20:28reasoning
Testing the TypeScript code with type checking and unit tests yielded successful results, confirming the core logic. Proceeding to generate a 4-frame fast preview at the specified resolution and settings, directing the output to the designated directory to evaluate the image generation pipeline.
Checking frame indices for "hangar", "launch", "chase", "orbit" at 24 fps reveals specific frame ranges. Focusing on "launch", calculating mid-tube frame, I'm verifying the need for a minor fix in the clip rendering logic to handle potential out-of-order frame requests, ensuring smooth thruster plumes even with single-frame jumps. Implementing this small CPU-side pre-stepping optimization will ensure deterministic random-access frame rendering. Now, updating the file.
edit_file{"Path":"~/work/sortie/src/view/clip.ts","Replacement":" let clock = 0, lastFrame = -2;\n\n const feed = (state: Parameters<typeof benchInput>[0], t: number, dt: number) => {\n const f = benchInput(state, t);\n reading.x = f.thrust.x;\n reading.y = f.thrust.y;\n reading.z = f.thrust.z;\n reading.boosting = f.boosting;\n reading.assault = f.assault;\n reading.quick = f.quick;\n rig.thrust(reading, clock, dt);\n rig.lightExhaust(light);\n };\n\n const ease = (x: number) => x * x * (3 - 2 * x);\n\n const render = (i: number) => {\n const f = frames[i];\n const v = shotView(f);\n // thrusters step at 120 Hz whatever the clip's frame rate, as a game would\n const dt = f.cut ? 0 : 1 / fps;\n if (f.cut || i !== lastFrame + 1) {\n for (let k = 0; k < 120; k++) { clock += DT; feed('idle', k * DT, DT); }\n for (let s = Math.max(0, f.stateT - 0.6); s < f.stateT - dt - 1e-9; s += DT) { clock += DT; feed(f.state, s, DT); }\n }\n lastFrame = i;","Target":" let clock = 0;\n\n const feed = (state: Parameters<typeof benchInput>[0], t: number, dt: number) => {\n const f = benchInput(state, t);\n reading.x = f.thrust.x;\n reading.y = f.thrust.y;\n reading.z = f.thrust.z;\n reading.boosting = f.boosting;\n reading.assault = f.assault;\n reading.quick = f.quick;\n rig.thrust(reading, clock, dt);\n rig.lightExhaust(light);\n };\n\n const ease = (x: number) => x * x * (3 - 2 * x);\n\n const render = (i: number) => {\n const f = frames[i];\n const v = shotView(f);\n // thrusters step at 120 Hz whatever the clip's frame rate, as a game would\n const dt = f.cut ? 0 : 1 / fps;\n if (f.cut) for (let k = 0; k < 120; k++) { clock += DT; feed('idle', k * DT, DT); }"}
input
{ "Path": "~/work/sortie/src/view/clip.ts", "Replacement": " let clock = 0, lastFrame = -2;\n\n const feed = (state: Parameters<typeof benchInput>[0], t: number, dt: number) => {\n const f = benchInput(state, t);\n reading.x = f.thrust.x;\n reading.y = f.thrust.y;\n reading.z = f.thrust.z;\n reading.boosting = f.boosting;\n reading.assault = f.assault;\n reading.quick = f.quick;\n rig.thrust(reading, clock, dt);\n rig.lightExhaust(light);\n };\n\n const ease = (x: number) => x * x * (3 - 2 * x);\n\n const render = (i: number) => {\n const f = frames[i];\n const v = shotView(f);\n // thrusters step at 120 Hz whatever the clip's frame rate, as a game would\n const dt = f.cut ? 0 : 1 / fps;\n if (f.cut || i !== lastFrame + 1) {\n for (let k = 0; k < 120; k++) { clock += DT; feed('idle', k * DT, DT); }\n for (let s = Math.max(0, f.stateT - 0.6); s < f.stateT - dt - 1e-9; s += DT) { clock += DT; feed(f.state, s, DT); }\n }\n lastFrame = i;", "Target": " let clock = 0;\n\n const feed = (state: Parameters<typeof benchInput>[0], t: number, dt: number) => {\n const f = benchInput(state, t);\n reading.x = f.thrust.x;\n reading.y = f.thrust.y;\n reading.z = f.thrust.z;\n reading.boosting = f.boosting;\n reading.assault = f.assault;\n reading.quick = f.quick;\n rig.thrust(reading, clock, dt);\n rig.lightExhaust(light);\n };\n\n const ease = (x: number) => x * x * (3 - 2 * x);\n\n const render = (i: number) => {\n const f = frames[i];\n const v = shotView(f);\n // thrusters step at 120 Hz whatever the clip's frame rate, as a game would\n const dt = f.cut ? 0 : 1 / fps;\n if (f.cut) for (let k = 0; k < 120; k++) { clock += DT; feed('idle', k * DT, DT); }" }result, 1 line
Made 1 replacement in ~/work/sortie/src/view/clip.ts starting at line 146 (+6/-2 lines).
agent
+20:46reasoning
Running a preview at the specified resolution and parameters. The command includes sample frames for processing.
run_command{"CommandLine":"node tools/clip.mjs atelier_estoc --shots hangar,launch,chase,orbit --fps 24 --size 1280x720 --palette houses --look kit --weapon rifle --ao --bearings --sample 42,98,134,232,320 --preview ~/.gemini/antigravity-cli/brain/cea9ec26-a0ce-4401-a5d2-36df51bb07b3/scratch/preview","WaitMsBeforeAsync":10000,"toolSummary":"Render 5 preview frames of sortie clip"}
input
{ "CommandLine": "node tools/clip.mjs atelier_estoc --shots hangar,launch,chase,orbit --fps 24 --size 1280x720 --palette houses --look kit --weapon rifle --ao --bearings --sample 42,98,134,232,320 --preview ~/.gemini/antigravity-cli/brain/cea9ec26-a0ce-4401-a5d2-36df51bb07b3/scratch/preview", "WaitMsBeforeAsync": 10000, "toolSummary": "Render 5 preview frames of sortie clip" }result, 6 lines
Tool is running as a background task with task id: cea9ec26-a0ce-4401-a5d2-36df51bb07b3/task-191 Task Description: node tools/clip.mjs atelier_estoc --shots hangar,launch,chase,orbit --fps 24 --size 1280x720 --palette houses --look kit --weapon rifle --ao --bearings --sample 42,98,134,232,320 --preview ~/.gemini/antigravity-cli/brain/cea9ec26-a0ce-4401-a5d2-36df51bb07b3/scratch/preview Task logs are available at: file://~/.gemini/antigravity-cli/brain/cea9ec26-a0ce-4401-a5d2-36df51bb07b3/.system_generated/tasks/task-191.log YOU MUST TAKE ONE OF THE FOLLOWING TWO ACTIONS: A) either proceed to other relevant work (if any) or, B) simply update the user with a short message (that you have launched the command and will wait for it to finish) and end the turn. DO NOTHING ELSE. When updating the user, always respond in the language of the user (defaulting to English). Never mix two or more languages in the same response.
agent
+21:05reasoning
task-191 renders the preview frames in the background, triggered by external event, not polling. Running targeted tests while this background task is in process won't interfere.
Checking existing tests in src/render/exhaust.test.ts and tools/outlines-lib.test.mjs confirms that background task execution won't interfere with existing functionality. Drafting ~/.gemini/antigravity-cli/brain/cea9ec26-a0ce-4401-a5d2-36df51bb07b3/scratch/draft_outline.md will verify the prose style against owner guidelines (no em dashes, no semicolons in prose, plain words, and short labeled sections) while task-191 is running in the background.
write_file{"Content":"# Draft Outline for ~/out/index.html\n\nHeader:\n- Gemini 4 Carbon (gemini-4-carbon), effort high\n- 2026-11-14\n\nStyle checklist:\n- Zero em dashes (`—` or `--` in prose)\n- Zero semicolons in prose\n- Organise, don't narrate: short labelled sections, plain words, scannable blocks\n\nSections:\n1. Read of the work\n - Working (keep)\n - Not working (drop)\n - Where I disagree with the 11-08 reflection\n - What changes in the restart\n2. First session sequence (concrete numbered steps)\n3. The one visual (`sortie-carbon.mp4`, large player, exact commands, wall time, what to change next)\n","Overwrite":true,"Path":"~/.gemini/antigravity-cli/brain/cea9ec26-a0ce-4401-a5d2-36df51bb07b3/scratch/draft_outline.md"}
input
{ "Content": "# Draft Outline for ~/out/index.html\n\nHeader:\n- Gemini 4 Carbon (gemini-4-carbon), effort high\n- 2026-11-14\n\nStyle checklist:\n- Zero em dashes (`—` or `--` in prose)\n- Zero semicolons in prose\n- Organise, don't narrate: short labelled sections, plain words, scannable blocks\n\nSections:\n1. Read of the work\n - Working (keep)\n - Not working (drop)\n - Where I disagree with the 11-08 reflection\n - What changes in the restart\n2. First session sequence (concrete numbered steps)\n3. The one visual (`sortie-carbon.mp4`, large player, exact commands, wall time, what to change next)\n", "Overwrite": true, "Path": "~/.gemini/antigravity-cli/brain/cea9ec26-a0ce-4401-a5d2-36df51bb07b3/scratch/draft_outline.md" }result, 1 line
Created file.
resultCommand exited with code 0.
Command exited with code 0. Command output: preview: ~/.gemini/antigravity-cli/brain/cea9ec26-a0ce-4401-a5d2-36df51bb07b3/scratch/preview/frame_042.jpg preview: ~/.gemini/antigravity-cli/brain/cea9ec26-a0ce-4401-a5d2-36df51bb07b3/scratch/preview/frame_098.jpg preview: ~/.gemini/antigravity-cli/brain/cea9ec26-a0ce-4401-a5d2-36df51bb07b3/scratch/preview/frame_134.jpg preview: ~/.gemini/antigravity-cli/brain/cea9ec26-a0ce-4401-a5d2-36df51bb07b3/scratch/preview/frame_232.jpg preview: ~/.gemini/antigravity-cli/brain/cea9ec26-a0ce-4401-a5d2-36df51bb07b3/scratch/preview/frame_320.jpg preview: 5 frames (4082 ms a frame) Log: file://~/.gemini/antigravity-cli/brain/cea9ec26-a0ce-4401-a5d2-36df51bb07b3/.system_generated/tasks/task-191.log