@opengamehq/cli 0.0.0-stage → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/AGENTS.md +235 -0
  2. package/CHANGELOG.md +9 -0
  3. package/README.md +128 -2
  4. package/dist/cli.mjs +1415 -0
  5. package/dist/opengame-global.js +3 -0
  6. package/dist/opengame-global.js.LEGAL.txt +1 -0
  7. package/dist/preflight-worker.mjs +13 -0
  8. package/dist/runtime-builder.mjs +800 -0
  9. package/dist/runtime-catalog.json +1 -0
  10. package/dist/runtime-catalog.sha256 +1 -0
  11. package/dist/runtime-shells/runtime-shell.html +4 -0
  12. package/dist/runtime-shells/runtime-shell.js +91 -0
  13. package/dist/safe-fs.py +242 -0
  14. package/dist/skills/manifest.json +512 -0
  15. package/dist/skills/opengame-accessibility/SKILL.md +90 -0
  16. package/dist/skills/opengame-api/SKILL.md +85 -0
  17. package/dist/skills/opengame-assets/SKILL.md +124 -0
  18. package/dist/skills/opengame-assets/references/pipeline.md +97 -0
  19. package/dist/skills/opengame-audio/SKILL.md +154 -0
  20. package/dist/skills/opengame-audio/helpers/audio-chain.js +325 -0
  21. package/dist/skills/opengame-audio/references/mix-notes.md +82 -0
  22. package/dist/skills/opengame-capture/SKILL.md +108 -0
  23. package/dist/skills/opengame-capture/references/pipeline.md +82 -0
  24. package/dist/skills/opengame-capture/references/threejs.md +145 -0
  25. package/dist/skills/opengame-characters/SKILL.md +129 -0
  26. package/dist/skills/opengame-characters/references/integration.md +144 -0
  27. package/dist/skills/opengame-characters/references/player-og.md +160 -0
  28. package/dist/skills/opengame-cli/SKILL.md +118 -0
  29. package/dist/skills/opengame-deploy/SKILL.md +204 -0
  30. package/dist/skills/opengame-deploy/references/json-events.md +62 -0
  31. package/dist/skills/opengame-deploy/references/manifest.md +83 -0
  32. package/dist/skills/opengame-deploy/references/packaging.md +117 -0
  33. package/dist/skills/opengame-depth/SKILL.md +130 -0
  34. package/dist/skills/opengame-enemies/SKILL.md +103 -0
  35. package/dist/skills/opengame-enemies/references/threejs.md +134 -0
  36. package/dist/skills/opengame-front-end/SKILL.md +143 -0
  37. package/dist/skills/opengame-front-end/references/launch.md +50 -0
  38. package/dist/skills/opengame-front-end/references/menus.md +47 -0
  39. package/dist/skills/opengame-game-feel/SKILL.md +137 -0
  40. package/dist/skills/opengame-game-feel/helpers/spring.js +146 -0
  41. package/dist/skills/opengame-game-feel/references/feel-numbers.md +83 -0
  42. package/dist/skills/opengame-jam/SKILL.md +103 -0
  43. package/dist/skills/opengame-lighting/SKILL.md +94 -0
  44. package/dist/skills/opengame-lighting/helpers/light-pool.js +185 -0
  45. package/dist/skills/opengame-loading/SKILL.md +99 -0
  46. package/dist/skills/opengame-loading/references/threejs.md +116 -0
  47. package/dist/skills/opengame-look/SKILL.md +114 -0
  48. package/dist/skills/opengame-look/references/post-and-lens.md +66 -0
  49. package/dist/skills/opengame-mobile/SKILL.md +90 -0
  50. package/dist/skills/opengame-performance/SKILL.md +140 -0
  51. package/dist/skills/opengame-performance/references/measuring.md +72 -0
  52. package/dist/skills/opengame-production/SKILL.md +131 -0
  53. package/dist/skills/opengame-production/references/templates.md +63 -0
  54. package/dist/skills/opengame-quality-bar/SKILL.md +122 -0
  55. package/dist/skills/opengame-quality-bar/references/cheap-tells.md +36 -0
  56. package/dist/skills/opengame-quality-bar/references/review-prompt.md +27 -0
  57. package/dist/skills/opengame-router/SKILL.md +51 -0
  58. package/dist/skills/opengame-router/references/process.md +38 -0
  59. package/dist/skills/opengame-scene-audit/SKILL.md +123 -0
  60. package/dist/skills/opengame-scene-audit/helpers/scene-audit.js +599 -0
  61. package/dist/skills/opengame-sdk/SKILL.md +254 -0
  62. package/dist/skills/opengame-sdk/references/engines.md +93 -0
  63. package/dist/skills/opengame-sdk/references/frame.md +107 -0
  64. package/dist/skills/opengame-sdk/references/identity.md +112 -0
  65. package/dist/skills/opengame-sdk/references/leaderboards.md +83 -0
  66. package/dist/skills/opengame-stability/SKILL.md +84 -0
  67. package/dist/skills/opengame-verification/SKILL.md +136 -0
  68. package/dist/skills/opengame-verification/helpers/browser-evidence.mjs +74 -0
  69. package/dist/skills/opengame-weapons/SKILL.md +109 -0
  70. package/dist/skills/opengame-weapons/references/handling-numbers.md +72 -0
  71. package/dist/skills/opengame-weapons/references/threejs.md +169 -0
  72. package/dist/skills/opengame-world-physics/SKILL.md +114 -0
  73. package/dist/skills/opengame-world-physics/references/measured-failures.md +52 -0
  74. package/package.json +38 -4
@@ -0,0 +1,185 @@
1
+ /**
2
+ * A fixed pool of real lights standing in for any number of authored ones.
3
+ *
4
+ * Three.js compiles the light count into every lit shader. Add a point light, remove
5
+ * one, or toggle `visible`, and every material recompiles on the next frame: a stall in
6
+ * the middle of play. So the game creates `size` real lights once, never changes how
7
+ * many exist, and lets this pool decide each frame which authored sources they show.
8
+ *
9
+ * import { createLightPool, selfTest } from "./light-pool.js";
10
+ * const pool = createLightPool({ size: 6 });
11
+ * const real = Array.from({ length: pool.size }, () => { const l = new THREE.PointLight(0xffffff, 0); scene.add(l); return l; });
12
+ * // each frame, with sources = [{ id, x, y, z, intensity, range, color }]
13
+ * pool.update(dt, sources, camera.position).forEach((slot, i) => {
14
+ * real[i].position.set(slot.x, slot.y, slot.z);
15
+ * real[i].intensity = slot.intensity; // 0 when empty: never toggle visible
16
+ * real[i].distance = slot.range;
17
+ * if (slot.color !== undefined) real[i].color.set(slot.color);
18
+ * });
19
+ *
20
+ * Two behaviours make a pool watchable rather than a flicker machine:
21
+ * - hysteresis: a waiting source replaces a shown one only when it scores clearly
22
+ * higher, so two lamps of similar strength do not trade places every frame;
23
+ * - handover at zero: a replaced slot fades out, moves on the frame its intensity is
24
+ * exactly zero, then fades in at the new source. A lit light never teleports.
25
+ *
26
+ * Defaults are Der Koloss's reference configuration (about 68 authored lamps shown
27
+ * through a handful of real lights). Run `selfTest()` after editing; it plants a pool
28
+ * without each behaviour and fails unless the planted defect is measured.
29
+ */
30
+
31
+ export const POOL_DEFAULTS = Object.freeze({ size: 6, hysteresis: 1.7, fadeSeconds: 0.25 });
32
+
33
+ /** How much one source matters at the viewer: intensity over distance, windowed to its range. */
34
+ export function contribution(source, viewer) {
35
+ const dx = source.x - viewer.x, dy = source.y - viewer.y, dz = source.z - viewer.z;
36
+ const d2 = dx * dx + dy * dy + dz * dz;
37
+ const range = source.range > 0 ? source.range : Infinity;
38
+ const ratio = range === Infinity ? 0 : d2 / (range * range);
39
+ const window = Math.max(0, 1 - ratio * ratio) ** 2;
40
+ return (source.intensity * window) / Math.max(d2, 1);
41
+ }
42
+
43
+ export function createLightPool(options = {}) {
44
+ const { size, hysteresis, fadeSeconds } = { ...POOL_DEFAULTS, ...options };
45
+ if (!Number.isInteger(size) || size < 1) throw new Error("size must be a positive integer");
46
+ const slots = Array.from({ length: size }, () => ({ id: null, next: null, fade: 0, x: 0, y: 0, z: 0, range: 0, color: undefined, base: 0 }));
47
+ const out = Array.from({ length: size }, () => ({ sourceId: null, x: 0, y: 0, z: 0, intensity: 0, range: 0, color: undefined }));
48
+ const rate = fadeSeconds > 0 ? 1 / fadeSeconds : Infinity;
49
+
50
+ function place(slot, source) {
51
+ slot.x = source.x; slot.y = source.y; slot.z = source.z;
52
+ slot.range = source.range ?? 0; slot.color = source.color; slot.base = source.intensity;
53
+ }
54
+
55
+ return {
56
+ size,
57
+ /** Advances fades and assignments. Returns `size` slots every call, empty ones at intensity 0. */
58
+ update(dt, sources, viewer) {
59
+ const byId = new Map();
60
+ const scored = [];
61
+ for (const source of sources) {
62
+ if (source.enabled === false || !(source.intensity > 0)) continue;
63
+ byId.set(source.id, source);
64
+ scored.push({ source, score: contribution(source, viewer) });
65
+ }
66
+ scored.sort((a, b) => b.score - a.score);
67
+ const shown = new Set(slots.map((slot) => slot.next ?? slot.id).filter((id) => id !== null));
68
+ const scoreOf = new Map(scored.map((entry) => [entry.source.id, entry.score]));
69
+
70
+ // Fill empty slots, then let clearly stronger waiting sources displace the weakest.
71
+ for (const { source, score } of scored) {
72
+ if (shown.has(source.id) || score <= 0) continue;
73
+ const empty = slots.find((slot) => slot.id === null && slot.next === null);
74
+ if (empty) { empty.next = source.id; shown.add(source.id); continue; }
75
+ let weakest = null, weakestScore = Infinity;
76
+ for (const slot of slots) {
77
+ if (slot.next !== null) continue; // already handing over
78
+ const s = scoreOf.get(slot.id) ?? 0;
79
+ if (s < weakestScore) { weakest = slot; weakestScore = s; }
80
+ }
81
+ if (weakest && score > weakestScore * hysteresis) { weakest.next = source.id; shown.add(source.id); }
82
+ }
83
+
84
+ slots.forEach((slot, i) => {
85
+ const current = slot.id !== null ? byId.get(slot.id) : undefined;
86
+ // A source that vanished or fell to nothing fades out where it stands.
87
+ const leaving = slot.next !== null || (slot.id !== null && !current);
88
+ if (leaving) {
89
+ slot.fade = Math.max(0, slot.fade - dt * rate);
90
+ if (slot.fade === 0) {
91
+ // The handover frame: intensity is exactly zero, so moving now cannot be seen.
92
+ const incoming = slot.next !== null ? byId.get(slot.next) : undefined;
93
+ slot.id = incoming ? incoming.id : null;
94
+ slot.next = null;
95
+ if (incoming) place(slot, incoming); else slot.base = 0;
96
+ }
97
+ } else if (current) {
98
+ place(slot, current); // a source that genuinely moves is followed
99
+ slot.fade = Math.min(1, slot.fade + dt * rate);
100
+ }
101
+ const o = out[i];
102
+ o.sourceId = slot.id; o.x = slot.x; o.y = slot.y; o.z = slot.z; o.range = slot.range; o.color = slot.color;
103
+ o.intensity = slot.id === null ? 0 : slot.base * slot.fade;
104
+ });
105
+ return out;
106
+ },
107
+ };
108
+ }
109
+
110
+ /**
111
+ * Drives `makePool` along a walk past a row of lamps, then parks the viewer inside a
112
+ * ring of near-equal lamps whose strengths wobble, and measures what a player would see:
113
+ * - countChanges: frames where the number of real lights changed (a shader recompile);
114
+ * - litTeleports: a lit real light jumping more than 0.25 m to a different source;
115
+ * - pops: a real light's intensity changing by more than half its source in one frame;
116
+ * - reassignments: how often a real light changed which source it shows.
117
+ */
118
+ export function measurePool(makePool, { frames = 600, dt = 1 / 60 } = {}) {
119
+ const lamps = Array.from({ length: 24 }, (_, i) => ({ id: `lamp${i}`, x: i * 4, y: 3, z: (i % 2) * 6 - 3, intensity: 40, range: 12 }));
120
+ const ring = Array.from({ length: 8 }, (_, k) => ({ id: `ring${k}`, x: -30 + 5 * Math.cos(k * Math.PI / 4), y: 3, z: 5 * Math.sin(k * Math.PI / 4), intensity: 40, range: 30 }));
121
+ const pool = makePool();
122
+ let previous = null, countChanges = 0, litTeleports = 0, pops = 0, reassignments = 0;
123
+ for (let f = 0; f < frames; f++) {
124
+ const walking = f < frames / 2;
125
+ const viewer = walking ? { x: (f / (frames / 2)) * 92, y: 1.7, z: 0 } : { x: -30, y: 1.7, z: 0 };
126
+ ring.forEach((lamp, k) => { lamp.intensity = 40 * (1 + 0.1 * Math.sin(f * 0.9 + k * 1.7)); });
127
+ const slots = pool.update(dt, walking ? lamps : ring, viewer).map((slot) => ({ ...slot }));
128
+ if (previous) {
129
+ if (slots.length !== previous.length) countChanges++;
130
+ slots.forEach((slot, i) => {
131
+ const before = previous[i];
132
+ if (!before) return;
133
+ if (slot.sourceId !== before.sourceId && slot.sourceId !== null) reassignments++;
134
+ const moved = Math.hypot(slot.x - before.x, slot.y - before.y, slot.z - before.z);
135
+ if (moved > 0.25 && slot.intensity > 0 && slot.sourceId !== before.sourceId) litTeleports++;
136
+ if (Math.abs(slot.intensity - before.intensity) > 20) pops++;
137
+ });
138
+ }
139
+ previous = slots;
140
+ }
141
+ return { countChanges, litTeleports, pops, reassignments };
142
+ }
143
+
144
+ /** A pool that returns only the lights it is using: the shader-recompile defect. */
145
+ function plantedShrinkingPool() {
146
+ const inner = createLightPool();
147
+ return { size: inner.size, update: (dt, sources, viewer) => inner.update(dt, sources, viewer).filter((slot) => slot.intensity > 0) };
148
+ }
149
+
150
+ /** The obvious pool: slot i shows the i-th strongest source, at full strength. */
151
+ function plantedRankedPool() {
152
+ const size = POOL_DEFAULTS.size;
153
+ return {
154
+ size,
155
+ update(dt, sources, viewer) {
156
+ const ranked = sources.map((source) => ({ source, score: contribution(source, viewer) })).sort((a, b) => b.score - a.score);
157
+ return Array.from({ length: size }, (_, i) => {
158
+ const s = ranked[i]?.source;
159
+ return s ? { sourceId: s.id, x: s.x, y: s.y, z: s.z, intensity: s.intensity, range: s.range, color: s.color } : { sourceId: null, x: 0, y: 0, z: 0, intensity: 0, range: 0 };
160
+ });
161
+ },
162
+ };
163
+ }
164
+
165
+ /**
166
+ * Plants each defect and requires the measurement to catch it, then measures the real
167
+ * pool. Returns `{ ok, examined, failures }`.
168
+ */
169
+ export function selfTest() {
170
+ const failures = [];
171
+ const real = measurePool(() => createLightPool());
172
+ const shrinking = measurePool(plantedShrinkingPool);
173
+ const ranked = measurePool(plantedRankedPool);
174
+ const instant = measurePool(() => createLightPool({ fadeSeconds: 0 }));
175
+ const twitchy = measurePool(() => createLightPool({ hysteresis: 1 }));
176
+ if (!(shrinking.countChanges > 0)) failures.push("planted shrinking pool was not caught by the count check");
177
+ if (!(ranked.litTeleports > 0)) failures.push("planted ranked pool was not caught by the teleport check");
178
+ if (!(instant.pops > 0)) failures.push("planted pool without fades was not caught by the pop check");
179
+ if (!(twitchy.reassignments > real.reassignments * 2)) failures.push(`planted pool without hysteresis reassigned ${twitchy.reassignments} times against ${real.reassignments}; the flicker check is not discriminating`);
180
+ if (real.countChanges) failures.push(`light count changed ${real.countChanges} times; shaders would recompile`);
181
+ if (real.litTeleports) failures.push(`${real.litTeleports} lit lights jumped to another source`);
182
+ if (real.pops) failures.push(`${real.pops} lights popped by more than half their strength in one frame`);
183
+ if (!(real.reassignments > 0)) failures.push("the walk never reassigned a light, so the handover was not exercised");
184
+ return { ok: failures.length === 0, examined: 5, failures, measured: { real, shrinking, ranked, instant, twitchy } };
185
+ }
@@ -0,0 +1,99 @@
1
+ ---
2
+ name: opengame-loading
3
+ description: Get a browser game from link to playable fast, and make the second visit almost instant. Covers a title-first boot over key art, a manifest of what the game really requests, a byte budget at a stated bandwidth, precompression and content types, hashed caching, fetch retries and stall deadlines, a progress bar by bytes, priority loads and quality changes without a reload. Use when the person says loading is slow, the bar sticks, the first load is huge, assets pop in or a return visit is slow.
4
+ metadata:
5
+ version: "1.0.0"
6
+ ---
7
+
8
+ # Loading
9
+
10
+ A player decides whether to stay before the game has finished downloading. They need a
11
+ working title screen with sound in a second or two, an honest bar while the world
12
+ streams behind it, and nothing on screen that is a stand-in for the real thing. A
13
+ returning player should download nothing. OC (OG Clash) asked for load speed about 12
14
+ times and reached its 15 s target only for returning players, so the first rule here is
15
+ the one that moves a first load most.
16
+
17
+ Rules carry five tags; `opengame-quality-bar` explains them and the game codes. Three.js
18
+ loaders, compression, Vite and service-worker detail is in
19
+ [references/threejs.md](references/threejs.md). Frame-time cost of loading belongs to
20
+ `opengame-performance`; phone memory and texture caps to `opengame-mobile`.
21
+
22
+ ## Rules
23
+
24
+ ### The title comes first and the world streams behind it
25
+ - **Invariant:** The first screen a player sees is interactive over key art before the world has downloaded, and the world loads behind the title and menus, so Play is ready by the time the player presses it.
26
+ - **Technique:** Split the download into tiers. The boot tier holds the shell, the key art, the title UI, its music and the input that unlocks audio. The next tier holds what the player will use first (their character, the equipped loadout, the spawn area). The rest loads by need. Draw the title from a still or a light scene, and swap in the live scene only once it is fully ready. Compile shaders behind the menus, not after Play.
27
+ - **Reference configuration:** OC's targets: key art on frame one, press-start under 1 s, title under 2 s on a first visit and under 1 s after. OC's 3D title needed the arena (135 MB) and the boss (15 MB) before it could show, and a key-art title estimated at "15x faster first load" was deferred as a 1-2 day build. Loading the arena behind the menus made Play take 0.12-0.15 s.
28
+ - **Applies when:** Every game whose world is larger than a few megabytes.
29
+ - **Verify:** On a cold cache at the stated bandwidth, record time and bytes to an interactive title, then press Play as soon as it is allowed and record the wait.
30
+
31
+ ### Ship what the runtime requests, listed in a manifest
32
+ - **Invariant:** The deployed build contains only files the game requests, and a manifest generated from real runs lists each one with its size and the tier that needs it.
33
+ - **Technique:** Log every request during scripted runs through every screen, mode, weapon and device class. Diff the log against the build folder, move unrequested files out, and fail the build when a large file has no entry. Keep a tier and a device class on each manifest entry, and gate the size of each tier.
34
+ - **Reference configuration:** OC's build folder grew to about 6.3 GB in 25,600 files, "mostly files the game never loads"; its deploy worker logged real requests to prune it, and the CDN set came to 3.07 GB. Boot loads grew from 225 MB in 590 files to 833 MB in 6,124 files over a few days, and models from 222 to 490 MB over R74-R77, with no gate to stop them.
35
+ - **Applies when:** Every game with a build step or an asset pipeline. It matters most when an exporter writes every asset in the project.
36
+ - **Verify:** A full scripted run requests every manifest entry, and the build folder holds nothing outside the manifest.
37
+
38
+ ### Bytes before the title have a budget at a stated bandwidth
39
+ - **Invariant:** The bytes needed before the title and the time they take on a named connection are written budgets, measured on every build with a cold cache and a throttled network.
40
+ - **Technique:** State the target as time at a bandwidth, convert it to bytes, and gate each build on the bytes the title tier actually transfers. Measure with network throttling in a real browser rather than on localhost at full speed, and record the transfer size the browser reports.
41
+ - **Reference configuration:** OC's target was 15 s or less at 25 Mbps, which is about 47 MB at roughly 3.1 MB/s. Before the title it sent 309 MB in 1,788 files; 291-304 MB took 119.6-123.2 s at 25 Mbps. Compression took that to 181 MB (R164), still about 58 s.
42
+ - **Applies when:** Every web game. Pick the bandwidth with the owner; a phone on mobile data is slower than a desk.
43
+ - **Verify:** A cold-cache run under the stated throttle prints bytes transferred and seconds to an interactive title, and fails above budget.
44
+
45
+ ### Every file is precompressed and typed
46
+ - **Invariant:** Every compressible file is served precompressed with the right `Content-Type` and `Content-Encoding`, the server picks the encoding from `Accept-Encoding`, and nothing is compressed twice.
47
+ - **Technique:** Write Brotli and gzip siblings at build time and have the host serve them; set types for `.wasm` (`application/wasm`, which streaming compilation needs), `.glb` (`model/gltf-binary`), `.ktx2` (`image/ktx2`) and every custom format. GPU-compressed textures shrink little, so measure each class before spending build time on it.
48
+ - **Reference configuration:** OC served its packed model files, asset index and audio with no `Content-Type` and no compression, and its shell ignored a Brotli copy of the wasm (12.6 MB raw against 2.56 MB). Earlier the game binary downloaded uncompressed (10.6 MB instead of 2.1 MB). Measured deflate ratios: GPU textures 1.28x, model files 2.27x, the asset catalog 7.2x. A claim that gzip "saves 20 s" failed audit.
49
+ - **Applies when:** Every game served over HTTP. The static host may do this for you; check rather than assume.
50
+ - **Verify:** For one file of each type, request it with `Accept-Encoding: br, gzip` and read the response headers; in the network log, the transfer size of each text, wasm and model file is well under its resource size.
51
+
52
+ ### Hashed names and long-lived caching
53
+ - **Invariant:** A returning player on an unchanged build downloads only the small entry document, and after a deploy downloads only the files that changed.
54
+ - **Technique:** Put a content hash in every asset's file name. Serve hashed files as `Cache-Control: public, max-age=31536000, immutable`, and the entry document as `no-cache` with an ETag. Avoid per-build path prefixes, which change every URL on every deploy. A service worker that keeps hashed files in Cache Storage helps where the HTTP cache is evicted.
55
+ - **Reference configuration:** OC's content-hash cache (R193) took a returning player from 150 s to 14.7 s. Before it, per-build paths made every deploy a full download. An earlier server rewrite took repeat visits from 714 MB to 5.1 MB.
56
+ - **Applies when:** Every game that is played more than once or deployed more than once.
57
+ - **Verify:** Load, close, load again: the second load transfers only the entry document. Change one asset, deploy, reload: only that file and the entry document transfer.
58
+
59
+ ### Fetches retry, and a stalled load is caught by a byte deadline
60
+ - **Invariant:** Every fetch can time out and retry, a load that stops receiving bytes is detected and reported, a slow load that is still receiving bytes continues, and a failed load ends on a retry button rather than an automatic page reload.
61
+ - **Technique:** Wrap every fetch with an idle timeout reset on each chunk received, retries with backoff and jitter, and a size or hash check on the result. Tell slow from stalled by bytes over time. Show a "slow connection" notice after a stretch with no bytes, keep retrying, and give up only after a long deadline with a button to try again. Cap concurrent requests. Check that a wrapper keeps the platform's own checks, such as range-response handling.
62
+ - **Reference configuration:** OC's runtime never retried a failed file, so a load waited on it forever, stuck at 97% (fixed R185). An earlier loader sat at 2% for 74 s after 244 failed requests with no timeout or error path. The page-side guard took 5 revisions over about 2 h, because a first wrapper bypassed range-response checks, and a later version's give-up turned into an "arena stalled" crash. The settings that shipped: the notice only after 20 s with zero bytes, retry with backoff while bytes arrive, and phone requests capped from 128 at a time to 24.
63
+ - **Applies when:** Every game that fetches assets after the first document.
64
+ - **Verify:** Fail one asset's first three requests (Playwright `page.route` aborting them): the load completes. Fail it every time: the notice appears, the page does not reload, and the error names the file. Throttle to a slow but steady link: no notice.
65
+
66
+ ### Progress counts bytes and only reaches 100% when the next screen works
67
+ - **Invariant:** The bar follows bytes received plus weighted non-network steps, climbs in small even steps, never goes backward or holds a number for long, and reaches the end only when the next screen is interactive.
68
+ - **Technique:** Take each file's size from the manifest, count bytes as response chunks arrive, and give shader compiles, environment maps and scene builds their own weights. Advance the shown number toward the true one at a capped rate so it moves in small steps. Hide the bar on loads short enough to finish before it would be read.
69
+ - **Reference configuration:** OC's bar stuck at 60% and jumped to 100% ("Baking light" was hard-coded at 60% for about 8 s of work), and stuck at 97% for 20 s before a reload. Fixed, it climbs 1% at a time, holds no number for more than about 0.75 s (0.68-0.73 s measured) and shows only after 0.6 s. A shader warm-up curtain had added 2.5 s of blank screen. The owner asked 3 times.
70
+ - **Applies when:** Every load the player waits through, first boot and match entry alike.
71
+ - **Verify:** Under the stated throttle with a load of 8 s or more, sample the shown value every frame: it only rises, holds no value past the cap, and reaches 100% within a frame of the next screen accepting input.
72
+
73
+ ### What the player sees first is loaded first, and never as a stand-in
74
+ - **Invariant:** The equipped weapon, the player's own character and their sounds load at top priority and are resident before the screen that shows them; a lower-detail stand-in never appears, and anything late shows the previous complete asset or a designed loading state.
75
+ - **Technique:** Run fetches through a priority queue and order requests by need. Gate screens, purchases and pickups on the asset being ready. Load the equipped weapon's sounds with its model. Keep the old complete model on screen until the new one is fully ready.
76
+ - **Reference configuration:** OC's runtime had no priority control, so request order was the only control it had. Weapons the player was given arrived 2.5-7 s late (about 40 s for the heaviest) as mitten hands or black shapes, which spoiled captures in 3 streams and caused a false regression. One lazy-load change put low-poly guns in 6 places; the owner: "dont show the low poly versions anywhere anytime for any weapon anywhere in the game". Gun sounds were silent for 11-16 s, queued behind 35 MB of audio banks.
77
+ - **Applies when:** Every game with a loadout, a character select or items that appear mid-game.
78
+ - **Verify:** On a cold cache under throttle, go straight to play and fire: the first frame of the weapon is the full model and the first shot is heard. Capture every path that hands over an item.
79
+
80
+ ### Changing quality never reloads the page
81
+ - **Invariant:** Tier and pixel ratio change at runtime without navigation, and a capability probe's result is stored for the next visit instead of applied by reloading.
82
+ - **Technique:** Read the stored tier or run a quick probe before creating the renderer (choosing tier and pixel ratio before the first frame is in `opengame-mobile`). Switch passes, resolution and texture sets at runtime. Prewarm only the active tier, and warm another tier when the player picks it.
83
+ - **Reference configuration:** An OC probe stored a higher tier 12 s after the title and reloaded the page, which matched the owner's report: "once it got near 100% it just restarted the game". Warming 4 tiers made the last 3-5% of phone loading take 1-3 min.
84
+ - **Applies when:** Every game with quality tiers.
85
+ - **Verify:** Change the tier in settings during a run: the page fires no `beforeunload`, the run continues, and the log shows one tier prewarmed at boot.
86
+
87
+ ### Loading keeps going in a background tab
88
+ - **Invariant:** A player who switches away during the download comes back to a load that kept going.
89
+ - **Technique:** Drive loading from fetch promises and message events, not from animation frames. Slice long CPU work with `MessageChannel` or `scheduler.postTask`. Count stall timeouts in visible time only.
90
+ - **Reference configuration:** OC's runtime drove loading from its animation-frame loop, so loading halted in hidden tabs. Browsers stop `requestAnimationFrame` in a hidden tab and slow `setTimeout` to about once a second, then once a minute.
91
+ - **Applies when:** Every load long enough that a player might switch tabs.
92
+ - **Verify:** Start a cold load, switch to another tab for 60 s, return: the progress advanced while hidden, and no stall notice fired.
93
+
94
+ ### A self-hosted build keeps code off the asset path
95
+ - **Invariant:** When the game is hosted outside a game platform, heavy assets come from a static host or CDN with no per-request code, with the headers the runtime needs and range requests where the runtime uses them.
96
+ - **Technique:** Put the page shell and the heavy assets on separate hosts if one host's limits are smaller than the game. Serve assets as plain static files. If the game uses threads (`SharedArrayBuffer`), send `Cross-Origin-Opener-Policy: same-origin` and `Cross-Origin-Embedder-Policy: require-corp` on the page and `Cross-Origin-Resource-Policy` on the asset host. Check the served build after each deploy (see `opengame-stability`).
97
+ - **Reference configuration:** OC split a 106 MB page shell from 3.07 GB of assets on a CDN under per-build paths. A worker function on every asset request billed about 5,000 requests per load.
98
+ - **Applies when:** Games deployed to your own hosting. On OpenGame, `opengame-deploy` covers packaging and the platform serves the files.
99
+ - **Verify:** One cold load's request log shows no function invocations for asset files, the isolation headers on the page and the asset responses, and `206` responses where the runtime sends `Range`.
@@ -0,0 +1,116 @@
1
+ # Loading in three.js
2
+
3
+ How the rules in `SKILL.md` map onto three.js and a Vite build. Class names are from
4
+ three.js addons (`three/addons/...`). Check them against the three.js version in your
5
+ `package.json`, since loader options move between releases.
6
+
7
+ ## Compressed textures: KTX2 and Basis
8
+
9
+ Encode textures as KTX2 with Basis Universal supercompression, and load them with
10
+ `KTX2Loader`. The loader transcodes to whatever the GPU supports (BC on desktop, ASTC or
11
+ ETC on phones), so one file serves every device class.
12
+
13
+ ```js
14
+ import { KTX2Loader } from 'three/addons/loaders/KTX2Loader.js';
15
+
16
+ const ktx2 = new KTX2Loader()
17
+ .setTranscoderPath('/basis/') // copy node_modules/three/examples/jsm/libs/basis/ here
18
+ .detectSupport(renderer); // for WebGPURenderer, after `await renderer.init()`
19
+ ```
20
+
21
+ - ETC1S is small and soft; UASTC is larger and sharp. AW measured ETC1S good enough for
22
+ its normals at a sixth of UASTC's bytes (see `opengame-performance`). Measure per class.
23
+ - Phones need lower top mips as well as a different transcode target. Ship a mip-trimmed
24
+ file per device class and pick it from the manifest, so a phone does not download mips
25
+ it will throw away (see `opengame-mobile`).
26
+ - Encode with `gltf-transform` (`--texture-compress ktx2`) or KTX-Software's `toktx`.
27
+
28
+ ## Geometry: meshopt or Draco
29
+
30
+ Both shrink glTF geometry. Meshopt decodes faster and also compresses animation and
31
+ morph targets; Draco often makes smaller static meshes. Pick by measuring your models.
32
+
33
+ ```js
34
+ import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
35
+ import { DRACOLoader } from 'three/addons/loaders/DRACOLoader.js';
36
+ import { MeshoptDecoder } from 'three/addons/libs/meshopt_decoder.module.js';
37
+
38
+ const draco = new DRACOLoader().setDecoderPath('/draco/');
39
+ const gltf = new GLTFLoader()
40
+ .setKTX2Loader(ktx2)
41
+ .setDRACOLoader(draco)
42
+ .setMeshoptDecoder(MeshoptDecoder);
43
+ ```
44
+
45
+ `gltf-transform optimize in.glb out.glb --compress meshopt --texture-compress ktx2` does
46
+ both passes in one command. Compare the result side by side with the source under the
47
+ same light before shipping it; quantisation can move vertices on thin parts.
48
+
49
+ ## LoadingManager, staged
50
+
51
+ `LoadingManager.onProgress(url, itemsLoaded, itemsTotal)` counts files, not bytes. One
52
+ large model and fifty icons then weigh the same, which is how a bar stops at 60% and jumps
53
+ to 100%. Use one manager per tier (boot, first use, rest) so each tier has its own
54
+ `onLoad`, and drive the bar from bytes:
55
+
56
+ - Take each file's size from your manifest. The per-file `onProgress` event from
57
+ `GLTFLoader.load` reports `loaded` and `total`, but with Brotli or gzip on the wire
58
+ `total` is the compressed `Content-Length` while `loaded` counts decoded bytes, and
59
+ `total` is 0 when the header is missing. Recent `FileLoader` versions read an
60
+ `X-File-Size` header first when the server sends one. Manifest sizes avoid all of it.
61
+ - Add fixed weights for work that is not a download: `renderer.compileAsync(scene,
62
+ camera)` for shaders, PMREM environment maps, building instanced scenes.
63
+ - `manager.setURLModifier` maps logical names to hashed URLs from the manifest.
64
+ - `manager.onError` fires per failed URL. Retry from there (or from your own fetch
65
+ wrapper) instead of letting the tier wait forever.
66
+
67
+ Three.js loaders do not retry. For retries, timeouts and a priority order, fetch the
68
+ bytes yourself and hand them to `GLTFLoader.parse(arrayBuffer, path, onLoad, onError)`.
69
+
70
+ ## Vite: hashed assets
71
+
72
+ Vite puts a content hash in the name of every asset it processes: files imported from
73
+ JavaScript, referenced from CSS or HTML, or imported with `?url`.
74
+
75
+ ```js
76
+ import gunUrl from './assets/guns/rifle.glb?url'; // -> /assets/rifle-3f9a1c2b.glb
77
+ gltf.load(gunUrl, onLoad);
78
+ ```
79
+
80
+ - Files in `public/` are copied as they are, with no hash. Move cacheable assets out of
81
+ `public/`, or hash them in your own build step, or the long cache rule cannot apply.
82
+ - `build.manifest: true` writes `.vite/manifest.json`, which maps source paths to hashed
83
+ output. Join it with your request log to build the runtime manifest.
84
+ - Vite inlines small assets as data URLs below `build.assetsInlineLimit`. Set it to 0 for
85
+ game assets so each one is cached on its own.
86
+ - Vite does not write Brotli or gzip siblings. A post-build script with Node's
87
+ `zlib.brotliCompressSync` and `zlib.gzipSync` over `dist/` does; skip files that are
88
+ already compressed (KTX2, images, audio) unless measuring shows a gain.
89
+ - Vite adds `<link rel="modulepreload">` for the entry's imports. Add `<link
90
+ rel="preload">` by hand for the boot-tier key art and title music.
91
+
92
+ ## Service worker
93
+
94
+ The HTTP cache can be evicted. A service worker that keeps hashed files in Cache Storage
95
+ makes a return visit nearly free:
96
+
97
+ - Cache first for hashed URLs, since a hashed file never changes.
98
+ - Network first for the entry document, so a deploy is picked up on the next visit.
99
+ - On `activate`, delete caches from older builds.
100
+ - `vite-plugin-pwa` (Workbox) generates the precache list from the build; a short
101
+ worker of your own works as well.
102
+
103
+ Watch memory when writing to the cache from the page, which matters on a phone. One
104
+ common way to double it: `response.clone()` splits the body into two streams, and if the game reads its
105
+ copy into an `ArrayBuffer` while the cache copy is still being written, both copies sit
106
+ in memory. Let the service worker do the caching from its own fetch handler, and measure
107
+ tab memory with the cache on and off.
108
+
109
+ ## Upload and memory
110
+
111
+ - `ImageBitmapLoader` decodes images off the main thread. After the GPU upload, close
112
+ the bitmap so its CPU copy is freed (see `opengame-mobile` for when that is safe).
113
+ - Call `dispose()` on geometries, materials and textures you unload, and watch
114
+ `renderer.info.memory` fall.
115
+ - `renderer.compileAsync` before the menu lifts keeps shader links out of play (see
116
+ `opengame-performance`).
@@ -0,0 +1,114 @@
1
+ ---
2
+ name: opengame-look
3
+ description: Make a three.js browser game's image hold up. Covers linear HDR rendering with one tone curve, a sky inside the exposure, fog that leaves the sky alone, the concept's lens, bloom that keeps small glows small, an authored grade, honest materials, detail that does not tile or shimmer, and a look bible. Use when the person says it looks flat, washed out, plastic, like a prototype, too dark, too bright, the sky looks pale, the colours are off, or wants a cinematic or AAA look.
4
+ metadata:
5
+ version: "1.0.0"
6
+ ---
7
+
8
+ # The look
9
+
10
+ The image is decided by a handful of choices made once: where the tone curve lives, what
11
+ the grade is, which surfaces may bloom, and what materials are allowed to be. Make them
12
+ on purpose and write them down; most "it looks like a prototype" reports are one of
13
+ these left at a default.
14
+
15
+ Rules carry five tags; `opengame-quality-bar` explains them and the game codes (DK, MC,
16
+ AW, SR, ST, OC).
17
+
18
+ ## Rules
19
+
20
+ ### Render linear, tone map once
21
+ - **Invariant:** The world renders in linear light with values above display white, and exactly one tone curve maps it to the screen.
22
+ - **Technique:** Render into a half-float target with the renderer's own tone mapping off, then apply exposure, the tone curve and the grade in one composite pass. Or keep three's tone mapping and add no post. Never both. Then trace the frame from the tone curve to the screen and remove any later pass with a shoulder of its own (a grade, vignette or "filmic" pass), because a second highlight roll-off strips colour from every bright area. In three.js, `renderer.toneMapping` applies when drawing to the canvas or in `OutputPass`; a custom pass after either may not compress highlights.
23
+ - **Reference configuration:** DK, MC and AW render into half-float targets with `NoToneMapping` and run AgX, exposure and the grade in one composite (AgX rolls highlights toward white instead of clipping to a hue). SR uses ACES at exposure 1.1 with no post. The ST starter uses ACES at about 0.8 for punch. OC applied a second strong highlight roll-off after ACES that also removed blue, and the concept's colour did not come back until it was taken out.
24
+ - **Applies when:** Any lit 3D look. Pixel art, 2D and unlit retro looks use no tone mapping at all, so their colours stay exact.
25
+ - **Verify:** Search the code for every place a tone curve is applied; there is one. Render a strip of grey and saturated patches from black to well above white through the full chain: each patch keeps its hue until it reaches white, and the strip shows one shoulder. A bright emissive rolls off smoothly in a capture instead of turning a flat hue.
26
+
27
+ ### Write the look bible first
28
+ - **Invariant:** Before building the scene there is one short written spec of the look: palette, tone curve, grade per level, light rig, material rules and what may bloom.
29
+ - **Technique:** A page in the repository the build reads from, with one table of values per level or map. Every later change to the look edits the table, not scattered constants.
30
+ - **Reference configuration:** DK and MC keep the grade as one table per map; ST writes a look target from the selected concept views before production.
31
+ - **Applies when:** Every game with a rendered world.
32
+ - **Verify:** The values in the running game (read them from the renderer and post passes at runtime) match the spec.
33
+
34
+ ### The sky is inside the exposure range
35
+ - **Invariant:** The sky's brightness falls inside the range the tone curve can show, so any change to the sky shows on screen.
36
+ - **Technique:** Read the sky's linear value before the tone curve at the horizon and overhead, and set its intensity against the key light and the exposure, not by eye on the final frame. Keep a false-colour exposure view in the debug build. Before anyone tunes sky variants, swap two very different ones and confirm the capture changes. In three.js scale a sky texture with `scene.backgroundIntensity` or the sky shader's output, and read a half-float target before `OutputPass`.
37
+ - **Reference configuration:** OC's sky was 5 to 10 times too bright for the exposure. It clipped into the top of the display curve, so every sky variant came out the same pale grey, and agents tuned variants that could not change through rounds r04 to r06. Measured on fixed crops later, OC's sky band read 56 to 67 against a target of 72 to 78.
38
+ - **Applies when:** Any game with a visible sky, skybox or painted backdrop.
39
+ - **Verify:** Capture one view with two different sky variants: the sky pixels differ. The false-colour view shows no clipped sky away from the sun or moon.
40
+
41
+ ### Fog stops at the sky
42
+ - **Invariant:** Fog thickens geometry with distance; the sky dome and the far backdrop look as authored.
43
+ - **Technique:** Exempt sky and backdrop materials from fog, fog only the world geometry, and build atmosphere into the sky shader itself. Use height fog with gaps and banks rather than one flat veil. In three.js set `material.fog = false` on backdrop meshes; `scene.background` and a `ShaderMaterial` sky (such as the `Sky` addon) are not fogged unless they opt in.
44
+ - **Reference configuration:** OC's world fog covered its sky dome for about 3 hours before anyone exempted the sky. OC capped its fog sheets at 22% opacity so they never hid the subject.
45
+ - **Applies when:** Fogged scenes with a sky dome, skybox or backdrop geometry.
46
+ - **Verify:** Toggle fog in a debug build while looking at the horizon: the geometry changes and the sky does not.
47
+
48
+ ### The lens matches the concept
49
+ - **Invariant:** The player camera's field of view matches the concept art and the genre's reference, recorded as a vertical angle, and every capture tool reads the value the game uses.
50
+ - **Technique:** Solve the camera from the concept (horizon height, subject size, camera height) and write its vertical field of view into the look bible. Convert a horizontal slider value with vertical = 2 atan(tan(horizontal / 2) / aspect). Capture scripts read the live camera, not a saved settings copy. In three.js `PerspectiveCamera.fov` is vertical, in degrees; call `updateProjectionMatrix()` after setting it. A first-person view model keeps its own lens (`opengame-weapons`).
51
+ - **Reference configuration:** OC's concepts show a first-person lens of 50 to 55 degrees vertical, and the build ran at 66. Later a capture read a stale settings copy and stayed at 66.5 degrees. OC's view model used its own 75 degree lens.
52
+ - **Applies when:** First- and third-person 3D games, and any game captured against concept art.
53
+ - **Verify:** Write the camera's vertical field of view into each capture's metadata and compare it with the look bible. Overlay a capture on its concept: the horizon and the subject's size line up.
54
+
55
+ ### Small glows stay small
56
+ - **Invariant:** Thin or tiny emissive geometry (reticles, filaments, eyes, runes, cores) glows at its own size with no bloom rings, flowers or white suns.
57
+ - **Technique:** Cap emissive intensity per material class and clamp before bloom. Draw reticles and holographic sights in a shader or sprite that bloom does not see, and give tiny glows a minimum size on screen instead of more intensity. In three.js put them on a layer excluded from `UnrealBloomPass` (three's selective bloom example does this with `Layers`), or draw them after the bloom pass.
58
+ - **Reference configuration:** An OC holographic reticle was a 0.8 mm glowing torus, and bloom turned it into a 7-ring flower. Clipped emissive halos read as "four giant white suns". OC capped emissives near HDR 3 to 4, kept eye glows at 1.5 to 2 px or more, and cut its flat-white pixel share from 10.47% to 0.58%.
59
+ - **Applies when:** Lit looks with bloom and any small emissive detail.
60
+ - **Verify:** Capture each optic, eye and glowing detail at the nearest and farthest play distance, and count pixels above 0.95: the bright area is close to the detail's footprint.
61
+
62
+ ### Find the broken channel before tuning colour
63
+ - **Invariant:** A surface that looks wrong is traced to its channel (normals, albedo, material flags, light or post) before anyone changes a colour or a light.
64
+ - **Technique:** Render the asset with normals only, then unlit albedo only, then lit with post off, and see which view shows the fault. In three.js swap in `MeshNormalMaterial`, then a `MeshBasicMaterial` with the albedo map.
65
+ - **Reference configuration:** OC tuned albedo, fill and fire tint on a "black horde" for 10 rounds before finding that 7.7 to 25.8% of zombie vertices had normals opposed to their faces. Titan faceting blamed on decimation came from shader derivative curvature. The importer's metalness default of 1.0 turned surfaces into mirror slabs.
66
+ - **Applies when:** Any asset that reads too dark, faceted, plastic or like foil.
67
+ - **Verify:** The channel view that showed the fault changes after the fix, and the lit capture follows.
68
+
69
+ ### An authored grade per level
70
+ - **Invariant:** Each level has a grade chosen for it: exposure, contrast, saturation, lift and gain, with shadows and highlights pulled apart in temperature.
71
+ - **Technique:** Lift-gamma-gain in the composite, contrast on luma, values from the look bible's table. Warm highlights over cool shadows is the common thread; break it on purpose.
72
+ - **Reference configuration:** DK: exposure 2.45, saturation 1.10, contrast 1.075, lift (0.030, 0.040, 0.062), gain (1.045, 1.0, 0.955). MC Rust: contrast 1.18, lift (0.010, 0.018, 0.034), gain (1.10, 1.00, 0.84) as a highlight-only tilt, contrast on luma with a 0.055 toe.
73
+ - **Applies when:** Any game with more than flat colour. An ungraded style says so in its bible.
74
+ - **Verify:** Capture the same view with the grade off and on. Keep whichever reads play more clearly, and check threats, UI and team colours stay distinct.
75
+
76
+ ### Bloom only where light is
77
+ - **Invariant:** Only emissive sources, specular glints and effects bloom. A lit wall never glows.
78
+ - **Technique:** Threshold bloom above display white in linear, with a soft knee and a clamp for fireflies, and author emissive and effect colours above one so they cross it.
79
+ - **Reference configuration:** Threshold about 1.0 to 1.15 linear (AW sets 95% of display white), soft knee 0.7, firefly clamp 24, strength 0.3 to 0.6. Authored emissive: sparks (3.2, 2.1, 0.9), muzzle core (5.0, 3.6, 1.9), fireball (6.0, 3.0, 0.9) (DK, MC).
80
+ - **Applies when:** Lit 3D looks with post. Stylised looks may skip bloom entirely.
81
+ - **Verify:** A capture of the brightest lit surface in the level shows no halo; a capture of a muzzle flash or lamp does.
82
+
83
+ ### Fog is the horizon
84
+ - **Invariant:** Fog takes the sky's horizon colour, so distant geometry dissolves into the sky rather than into a grey or white haze.
85
+ - **Technique:** Derive the fog colour from the sky shader's horizon term in code, not as a second constant.
86
+ - **Reference configuration:** DK locks fog and horizon to one value. Fog density 0.003 to 0.03 by mood across our games; a white horizon is one of the cheap tells.
87
+ - **Applies when:** Any outdoor or large interior scene with fog.
88
+ - **Verify:** Capture a long sightline. The farthest geometry's colour converges on the sky behind it.
89
+
90
+ ### Materials are honest
91
+ - **Invariant:** Metalness is fully metal or fully not, roughness never reaches the maximum, and every surface has some variation across it.
92
+ - **Technique:** Anything between metal and dielectric comes from a map. Pick roughness by material family. Base colour and emissive maps in sRGB, normal, roughness, metalness and occlusion maps linear.
93
+ - **Reference configuration:** Concrete 0.90 to 0.97, painted steel 0.35 to 0.55, gun steel 0.45 to 0.60, chrome trim 0.05 to 0.15. SR's plain props default to 0.78 instead of three's 1.0, and keep normal scale 0.35 to 0.6 with occlusion at 0.25 to 0.55.
94
+ - **Applies when:** PBR looks. Toon and flat styles follow their own banding rules.
95
+ - **Verify:** List every material at runtime with its metalness and roughness; none is at roughness one without a map, none has a fractional metalness without a map.
96
+
97
+ ### Break the tiling
98
+ - **Invariant:** No texture repeat is visible at play distance.
99
+ - **Technique:** A world-space triplanar detail normal that fades with distance, plus very low frequency mottling of albedo and roughness. Normalise a detail texture by its mean luminance so it adds grain without darkening.
100
+ - **Reference configuration:** DK: detail normal at 2.6 tiles per metre, strength 0.55, faded from 3.5 to 13 m; macro mottling at about 18 m, albedo plus or minus 16%, roughness plus or minus 12%. Anisotropy 8 to 16 on ground and repeated detail.
101
+ - **Applies when:** Large textured surfaces: ground, walls, terrain.
102
+ - **Verify:** A wide capture of the largest surface from standing height shows no grid of repeats.
103
+
104
+ ### Detail does not shimmer
105
+ - **Invariant:** Surfaces do not crawl with bright dashes or sparkle as the camera moves.
106
+ - **Technique:** Band-limit generated height fields (blur before deriving normals) so the mip chain has something to average, then fade normal detail where a pixel covers more relief than it can show, and widen roughness by a local average of normal variance.
107
+ - **Reference configuration:** DK: blurring prop height fields before the Sobel pass was the largest single win at a bridge doorway (32% off the oscillation). Raising specular antialiasing strength instead made it monotonically worse (3.43 to 5.24 at above 8/255), because the derivative of an aliasing normal is itself aliasing.
108
+ - **Applies when:** Any normal-mapped surface, generated textures above all.
109
+ - **Verify:** Record a slow pan at a grazing angle and difference consecutive frames; the flicker is measurable and should fall after the fix.
110
+
111
+ ## Further reading
112
+
113
+ Post that reacts to sprint and damage, lens finish values, and the starter look's
114
+ defaults are in [references/post-and-lens.md](references/post-and-lens.md).
@@ -0,0 +1,66 @@
1
+ # Post that reacts, and the lens finish
2
+
3
+ All values here are reference configurations from our games. Start from them, then tune
4
+ by eye against the look bible, at play distance, while moving.
5
+
6
+ ## Lens finish
7
+
8
+ A restrained lens pass on the graded frame, in display space, after the tone curve:
9
+
10
+ - **Chromatic aberration** that grows toward the edge and is nearly zero at the centre:
11
+ offset `k * (0.35 + 2.6 r^2)`.
12
+ - **Vignette** `smoothstep(0.05, 0.75, r^2)`.
13
+ - **Grain** weighted to the shadows, highlights clean, with a new pattern 24 times a
14
+ second. A new pattern every frame reads as noise; 24 Hz reads as film.
15
+
16
+ | Game | Vignette | Aberration | Grain |
17
+ | --- | --- | --- | --- |
18
+ | AW | 0.22 | 0.02 | 0.01 |
19
+ | DK | 0.34 | 0.11 | 0.014 |
20
+
21
+ AW is the restrained end, DK the hotter one. Pick one for the game and keep it.
22
+
23
+ ## Post that responds to play
24
+
25
+ - **Sprint:** vignette +0.12 and aberration +0.05, eased in and out.
26
+ - **Missing health:** up to vignette +0.3, aberration +0.16, and saturation down 35%.
27
+ - **Damage:** tint the frame edge by (1.25, 0.22, 0.18), decaying at 3.2 per second.
28
+ - **Exposure flash:** each shot adds 0.07 of exposure (a heavy shot 0.16), decaying at 7
29
+ per second.
30
+
31
+ These are DK and AW's numbers. Every one of them must stay inside the flash limits in
32
+ `opengame-accessibility`: a full-screen change is bounded per frame however it is driven.
33
+
34
+ ## The ST starter's look
35
+
36
+ Studio games start from a `createLook` with ACES at exposure 0.8, sRGB output, a warm
37
+ shadow-casting key that follows the player, a cool hemisphere fill plus a PMREM of the
38
+ sky (shadowed ground about a sixth of lit), a grade (an S-curve, saturation x1.25, cool
39
+ shadows, warm highlights), bloom above linear 1, and ambient occlusion on the top
40
+ quality tier. Lower tiers drop occlusion, then bloom and multisampling. Stylised art
41
+ drops the grade; pixel and flat art drop tone mapping, lights and post so colours stay
42
+ exact.
43
+
44
+ A hand-written `ShaderMaterial` does not apply the output transforms for you.
45
+ For direct rendering, write linear color, then include `tonemapping_fragment` and
46
+ `colorspace_fragment` at the end of the fragment shader when that material needs
47
+ the renderer's output transforms. The `toneMapped` flag controls tone mapping; it
48
+ does not insert either chunk. `RawShaderMaterial` also needs its own declarations.
49
+
50
+ For a post pipeline, keep intermediate render targets linear and apply the output
51
+ transforms in the final pass. Inspect the game's actual shader and render path
52
+ before changing either; applying a transform twice changes the color again.
53
+
54
+ ## The look pass
55
+
56
+ At play distance, on the real route:
57
+
58
+ 1. No white or grey haze; fog matches the sky's horizon.
59
+ 2. Shadowed surfaces sit well below lit ones (see `opengame-lighting`).
60
+ 3. One warm key casts shadows over a cool fill.
61
+ 4. Every grounded object shows a contact shadow.
62
+ 5. The brightest diffuse surface stays below white; highlights roll off.
63
+ 6. The grade adds contrast without hiding threats, UI or team colours.
64
+ 7. Only emissive and specular sources bloom.
65
+ 8. A capture with the grade off is compared, and the clearer one kept.
66
+ 9. The lowest quality tier still reads.