@margoengine/quality 0.1.0 → 1.0.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.
package/README.md CHANGED
@@ -1,300 +1,307 @@
1
- # @margoengine/quality
2
-
3
- Import `margoengine/quality` from the `margoengine` package, or `@margoengine/quality` from this package alone; the two are the same module. Neither is on npm yet: the [Install](../../README.md#install) section lists the two routes that work today (run in a clone, or install local tarballs).
4
-
5
- Measured quality tiers. Desktops start on a light tier (single-sampled, pixel ratio capped, paced to an even rate of at
6
- least 60 FPS) and read the real GPU time of each frame by timestamp queries; a page under the limit gets the full 4× MSAA tier
7
- from its next load. No PC is first shown the 4× tier or reloaded by the probe (the light tier's own frame rate depends on
8
- the GPU), and no rule based on device names is involved.
9
-
10
- ```ts
11
- import {applyQualityTier, paceEngine, watchQuality} from 'margoengine/quality';
12
- import {Engine} from 'margoengine/core';
13
- const canvas = document.querySelector('canvas')!;
14
-
15
- applyQualityTier(); // before creating the engine
16
- const engine = await Engine.create(canvas, {backend: 'webgpu'});
17
- paceEngine(engine); // light tier: an even rate of at least 60 FPS
18
- // ...build the scene and start rendering, then:
19
- watchQuality();
20
- ```
21
-
22
- - `applyQualityTier()` returns `'light'`, `'high'` or `'phone'`. Phones are single-sampled with the pixel ratio capped
23
- at 1 (`globalThis.margoLow = 1`), even with `?quality=high` or `?scale=2`. It sets core's `globalThis.margoLow`, which
24
- core reads when it builds pipelines and sizes the canvas, so it must run before the engine is created.
25
- - `watchQuality()` reads 120 frames on the light tier and, when the 90th percentile of the time a frame's GPU passes cover (passes that run side by side count once) is under
26
- `FAST_GPU_MS` (8 ms), remembers `'high'` for this page in `localStorage['margoQuality:' + location.pathname]`. One key
27
- per page, because the result says what this page's scene costs: a light scene must not mark a weak PC high for a heavy
28
- one. A slow reading remembers nothing, so one bad session cannot hold a browser on the light tier: the next load
29
- measures again. On the full tier, five consecutive seconds under 55 FPS remember that for good (`'held'`) and reload
30
- once (a machine that slowed down, for example on battery).
31
- - Timestamps: `applyQualityTier()` adds `timestamp-query` to the devices this page asks for, only while the page is still
32
- to be measured, until `watchQuality()` starts. The reading is its own small chunk, downloaded only by a page that reads. During the reading (about 4 s at 60 FPS, 10 s at most) `submit` and
33
- `createCommandEncoder` are wrapped and every pass gets timestamp writes; then all of it is put back and its GPU objects
34
- destroyed, so nothing runs after the reading. Without `timestamp-query` the page stays light and stores nothing. A frame
35
- whose passes the page times itself is not counted. Copies between passes, presenting and other work between passes are
36
- not in the number.
37
- - `onReading(milliseconds)` on `watchQuality` reports the reading when it ends, undefined when there is none.
38
- - For testing: `?quality=high` or `?quality=low` forces a tier without remembering it; `?scale=1.5` sets the light
39
- tier's pixel ratio (1 to 2). `localStorage.removeItem('margoQuality:' + location.pathname)` measures again.
40
- - `paceEngine(engine)` sets core's `engine.pace` hook on the light tier so `engine.start()` renders at an even rate of
41
- at least 60 FPS instead of swinging between 120 and 40 FPS on a slow GPU. Each frame spans the most whole refreshes that
42
- still reach 60, so the rate depends on the display:
43
-
44
- | Display | 60 Hz | 75 Hz | 90 Hz | 100 Hz | 120 Hz | 144 Hz | 165 Hz | 200 Hz | 240 Hz |
45
- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
46
- | Frames per second | 60 | 75 | 90 | 100 | 60 | 72 | 83 | 67 | 60 |
47
-
48
- Other tiers stay uncapped. Nothing global is patched: other `requestAnimationFrame` loops on the page run at the display
49
- rate. An app that renders from its own loop (calling `engine.render` itself) can gate it with `frameDue`.
50
- - `capFrameRate(engine, rate = 60)` sets the same pacing on any engine regardless of tier. It reads the display's refresh
51
- from the last 16 callback gaps, so it follows a page moved to another display within 16 frames.
52
- - The light-tier reading skips the first two seconds and gives up after ten, at any refresh rate.
53
-
54
- ## Dynamic resolution
55
-
56
- ```ts
57
- import {applyQualityTier, watchResolution} from 'margoengine/quality';
58
- import {Engine} from 'margoengine/core';
59
- const canvas = document.querySelector('canvas')!;
60
- applyQualityTier(); // light or phone tier
61
- const engine = await Engine.create(canvas, {backend: 'webgpu'});
62
- using resolution = watchResolution({budget: 12, min: 0.6}); // restores full resolution when disposed
63
- console.log(resolution.scale);
64
- ```
65
-
66
- `watchResolution` times each frame's GPU work (submit to finished) and, when the average passes `budget` milliseconds
67
- (default 12), lowers the canvas pixel ratio in 5% steps sized to land under the budget; with room to spare (under 70% of
68
- it) it rises 5% at a time, and backs off after a rise it had to undo. It moves `globalThis.margoLow`, which core reads every
69
- frame, so it works on the light and phone tiers. On the full 4x MSAA tier it does nothing (changing the cap there would
70
- also switch off multisampling); pass your own `apply(scale)` to scale some other way. `ResolutionScaler` is the same
71
- decision logic without timers: `push(frameMs)` returns the new scale when it changes.
72
-
73
- ## Feature scaling
74
-
75
- Resolution is one way down. `@margoengine/quality/features` lowers what the frame actually pays for, in steps it measures.
76
-
77
- ```ts
78
- import {Engine} from 'margoengine/core';
79
- import {SSAO} from 'margoengine/post/ssao';
80
- import {Shadows} from 'margoengine/shadows';
81
- import {featureKnobs, optionKnob, watchFeatures} from 'margoengine/quality/features';
82
- import {TAAUpscale} from 'margoengine/taa/upscale';
83
- const canvas = document.querySelector('canvas')!;
84
- const engine = await Engine.create(canvas, {backend: 'webgpu'});
85
- const shadows = Shadows.attach(engine, {distance: 120});
86
- const ssao = SSAO.attach(engine);
87
- const upscale = TAAUpscale.attach(engine, {scale: 1});
88
-
89
- using features = watchFeatures(
90
- [
91
- ...featureKnobs({ssao, shadows, camera: engine.camera}),
92
- optionKnob('resolution', upscale.options, 'scale', [1, 0.85, 0.7], 2), // anything that reads an option live
93
- ],
94
- {budget: 12, onChange: ({name, level}) => console.log(name, level)},
95
- );
96
- console.log(features.scaler.levels, features.scaler.costs);
97
- ```
98
-
99
- Over `budget` it takes one step, then compares the frame cost before and after. A step that saved under 3% of the frame
100
- is given back at once and rests for 120 decisions, so nothing is lost for no gain. Once a step is measured it is
101
- chosen by its measured saving: of the steps that cover the shortfall the least visible goes first (`weight`), and with
102
- none known to cover it the next untried step is tried, in the knobs' order. Under 70% of the budget the most visible lowered feature
103
- comes back, if its measured cost still leaves the frame under 90%; a rise that had to be undone doubles the wait, as in
104
- `ResolutionScaler`. `dispose()` puts every feature back.
105
-
106
- | `featureKnobs` key | Steps | Weight |
107
- | --- | --- | --- |
108
- | `post` | each effect's `enabled` goes false | 1 |
109
- | `ssao` | `samples` halve twice, then `enabled` false | 1 |
110
- | `ssr` | `steps` halve twice, then `enabled` false | 1 |
111
- | `shadows` | `filter` soft, pcf, hard; a set `distance` to 70% and 50% | 1.5 |
112
- | `shadows` | `resolution` halves twice; `cascades` one at a time to two (not with `bounds` or `frustum`) | 2 |
113
- | `volumetric` | `grid` halves, then `enabled` false | 2 |
114
- | `lod` | `bias` 1.5 and 2 times | 2 |
115
- | `camera` | `far` to 75% and 50%; what lies past it stops drawing, so pair it with fog | 3 |
116
-
117
- Each starts from the value the app set, and a feature already off gets no knob. A knob is `{name, levels, apply(level), weight}`,
118
- so anything can be one. `FeatureScaler` is the same logic without timers: `push(frameMs)` returns the change it made,
119
- `budget` can be set at any time, and `restart()` drops the running measure after a change it did not make, such as a new
120
- scene. Options: `budget` 12, `window` 30, `settle` 8 (samples ignored after a change), `minSaving` 0.03.
121
-
122
- A first change of shadow filter compiles shader variants, and a change of shadow `resolution` or `cascades` or of the fog
123
- `grid` allocates new textures, so that frame hitches once; `settle` keeps it out of the measure.
124
-
125
- ## Battery and heat
126
-
127
- `@margoengine/quality/power` eases off when the machine is on battery or running hot.
128
-
129
- ```ts
130
- import {Engine} from 'margoengine/core';
131
- import {applyQualityTier, paceEngine} from 'margoengine/quality';
132
- import {watchFeatures, featureKnobs} from 'margoengine/quality/features';
133
- import {watchPower} from 'margoengine/quality/power';
134
- const canvas = document.querySelector('canvas')!;
135
- applyQualityTier();
136
- const engine = await Engine.create(canvas, {backend: 'webgpu'});
137
- paceEngine(engine);
138
- using features = watchFeatures(featureKnobs({camera: engine.camera}));
139
- using power = watchPower({
140
- engine, // capped while easing off, its own pace back after
141
- features: features.scaler, // budget cut while easing off
142
- onChange: ({level, charging, battery, pressure, hot}) => console.log(level, charging, battery, pressure, hot),
143
- });
144
- console.log(power.reading.level);
145
- ```
146
-
147
- | Level | When | Frame cap (`rates`) | Budget (`budgets`) |
148
- | --- | --- | --- | --- |
149
- | 0 | On mains, or the browser does not say | The engine's own | Full |
150
- | 1 | On battery | 60 | 75% |
151
- | 2 | Hot, CPU pressure `serious` or `critical`, or battery at `lowBattery` (20%) or under | 30 | 50% |
152
-
153
- - Battery comes from `navigator.getBattery` and CPU pressure from `PressureObserver`, where the browser has them. A
154
- browser that has neither still gets the frame time reading. A source that refuses is left out; the others keep working.
155
- - Heat is read from frame times by `FrameDrift`: a GPU that throttles slows gradually, so the median frame cost creeps
156
- 25% over the coolest reading with no step above 15% between five-second readings, and stays there for six of them. A
157
- new view or level moves the cost in one step and starts the measure over. Once hot it stays hot for 60 readings (five
158
- minutes) or until the cost creeps back, because easing off lowers the cost by itself. Options: `window` 300, `rise`
159
- 1.25, `readings` 6, `jump` 0.15, `hold` 60. `power.restart()` forgets the measure after a change you know of.
160
- - The full tier cannot change while running (4x multisampling is built into the pipelines). On it, leaving level 0 sets
161
- this tab's next load to the light tier, in sessionStorage, keeping what the page measured; back at level 0 the next load
162
- is full again. The page is not reloaded unless you ask: pass `reload: () => location.reload()` to change tier at once.
163
- `?quality=high` still wins. `currentTier()` from the root entry reads the tier.
164
-
165
- ## Tier presets
166
-
167
- The tier also scales optional features. `applyQualityTier()` publishes the tier's `QualityPreset` as
168
- `globalThis.margoPreset`; each feature package below reads its key when an effect is constructed (`X.attach` or
169
- `new X`) and uses a preset value only for an option the app left undefined. **Explicit options always win.** Feature
170
- packages never import this package: the global is the whole contract, so an app that does not use
171
- `@margoengine/quality` gets every package's own defaults, unchanged.
172
-
173
- | Key | Package, class | Option | Full tier (package default) | Light tier | Phone tier |
174
- | --- | --- | --- | --- | --- | --- |
175
- | `shadows` | `@margoengine/shadows` `Shadows` | `resolution`, `filter`, `cascades` | 2048 (two 4-layer maps, 128 MiB), `'soft'` (PCSS), 4 | 1024 (32 MiB), `'pcf'`, 4 | 1024 (16 MiB), `'pcf'`, 2 |
176
- | `ssao` | `@margoengine/post/ssao` `SSAO` | `enabled`, `samples` | on, 32 | on, 16 | off |
177
- | `ssr` | `@margoengine/post/ssr` `SSR` | `enabled`, `steps` | on, 64 | off, 32 | off, 32 |
178
- | `volumetric` | `@margoengine/environment/volumetric` `VolumetricFog` | `enabled`, `grid` | on, [160, 90, 64] | on, [80, 45, 32] | off |
179
- | `localShadows` | `@margoengine/clustered/shadows` `LocalShadows` | `resolution` | 512 | 256 | 256 |
180
- | `vfx` | `@margoengine/vfx` `VFX` | `capacity` | 1,000,000 | 100,000 | 100,000 |
181
- | `scatter` | `@margoengine/scatter` `Scatter` | `lodFade` | 2 | 2 | 0 |
182
-
183
- The phone preset publishes `ssao: { enabled: false }` and `volumetric: { enabled: false }`. Disabled `VolumetricFog`
184
- skips its pass and makes no textures; omitting `enabled` keeps it on. Explicit feature options still win over preset defaults.
185
-
186
- Shadows on the light and phone tiers use `filter: 'pcf'`: four hardware comparison taps per lit pixel instead of PCSS's
187
- 16 blocker reads and 32 taps (a fixed edge about three texels wide instead of contact-hardening penumbrae). Phones also
188
- render two cascades instead of four (half the depth passes) and set scatter's `lodFade: 0`, which compiles its shaders
189
- without `discard`: tile-based phone GPUs then keep early depth rejection under dense grass. Pass `filter: 'soft'`,
190
- `cascades: 4` or `lodFade: 2` to keep those on every tier.
191
-
192
- ```ts
193
- import {applyQualityTier, qualityPreset} from 'margoengine/quality';
194
- import {Shadows} from 'margoengine/shadows';
195
- import {Engine} from 'margoengine/core';
196
- const engine = await Engine.create(document.querySelector('canvas')!);
197
-
198
- applyQualityTier(); // light tier: margoPreset.shadows = {resolution: 1024}
199
- const shadows = Shadows.attach(engine, {distance: 120}); // 1024 on light, 2048 on the full tier
200
- shadows.dispose(); // Release the current owner before trying the explicit resolution.
201
- const crisp = Shadows.attach(engine, {distance: 120, resolution: 2048}); // explicit: 2048 on every tier
202
- const particles = qualityPreset().vfx?.capacity ?? 1_000_000; // read a value for your own UI
203
- ```
204
-
205
- - `QUALITY_PRESETS` holds the table above (`high` is empty: package defaults). `qualityPreset()` returns this page's.
206
- - The preset is read once per effect, at construction; changing tier means a new page load, as before.
207
- - With a preset the effect's `options` is a copy (the app's object is not modified); edit `effect.options`, not the
208
- object you passed, to change a value later. Without a preset `effect.options` is the object you passed.
209
- - `VFX`: an explicit `initialCount` larger than the preset capacity keeps the default capacity (the app asked for that
210
- many particles). `burst(n)` above the preset capacity throws as it always did above `capacity`; pass `capacity`
211
- explicitly if your app bursts more than 100,000 particles on the light tier.
212
- - Bloom, FXAA, Tonemap, TAA and culling have no tier preset: none has an option that trades quality for GPU time.
213
- DOF has none either: `maxRadius` 8 instead of 16 measured no GPU saving on the light tier (its 64 taps are fixed)
214
- and only shrank the blur (`examples/package-benchmarks/results/tier-presets-light-diagnostic.json`).
215
- - Contract tests: `test/quality.test.js` (writer) and `tests/quality-presets.test.js` (every reader). GPU-call proof
216
- (no preset: identical calls to before; preset = passing its values; explicit options win):
217
- `node examples/package-benchmarks/proofs/quality-presets.proof.js`.
218
-
219
- ## Pipeline warm-up and device restoration
220
-
221
- ```ts
222
- import {warmUp} from 'margoengine/quality/warm';
223
- import {redrawAfterRestore} from 'margoengine/quality';
224
- import {Engine} from 'margoengine/core';
225
- const engine = await Engine.create(document.querySelector('canvas')!);
226
-
227
- // ...attach features and build the scene, then, still behind the loading screen:
228
- const report = await warmUp(engine); // {pipelines, fallbacks, rounds, rebooted}
229
- // Options: {frames: 2, maxRounds: 256, signal}; pass an AbortSignal to cancel (rejects with signal.reason).
230
- engine.start();
231
- redrawAfterRestore(engine, () => engine.render({delta: 0})); // only for apps that render on demand
232
- ```
233
-
234
- - `warmUp(engine)` creates the pipelines of every attached feature with `createRenderPipelineAsync` /
235
- `createComputePipelineAsync`, so the first visible frame that draws a feature does not stall on shader compilation.
236
- Features create pipelines lazily inside their passes, so it renders warm frames (delta 0) into an offscreen texture:
237
- a frame that reaches a missing pipeline is stopped there, the work it already encoded is submitted, the pipeline
238
- compiles asynchronously, and the frame is rendered again until two complete. Nothing is presented and frames from the
239
- engine's own loop are untouched. It resolves once the GPU has finished the warm frames, so pipelines a feature made
240
- synchronously at attach (GrassField does) have compiled by then too, during loading but not in parallel. A feature that stores state before creating its pipeline (so the retry skips the
241
- creation) fails on the retry; warmUp then restores the device (`engine.rebootDevice()`, every feature's restore hook)
242
- and finishes with synchronous creation (`report.rebooted`). A feature attached later or switched off is not warmed:
243
- call `warmUp` again after attaching it. Zero cost unless imported: no package reads it.
244
- - `redrawAfterRestore(engine, render)`: core restores a lost GPU device by itself and the engine's loop draws the next
245
- frame, but an app that renders on demand (paused, loop stopped) shows an empty canvas until it renders again. This
246
- runs `render` on the two frames after every restoration (effects that read the previous frame, such as water
247
- refraction and sky reflections, settle on the second). The returned stop function removes the helper from its
248
- registered scene and cancels queued redraws. Removing that plugin, disposing its scene or disposing the engine
249
- also cancels pending redraws; a later plugin with the same name is preserved.
250
- - First-use hitch per feature (`node examples/package-benchmarks/warm-up-gpu.mjs`, results
251
- `examples/package-benchmarks/results/warm-up-gpu.json`): see the table there.
252
-
253
- ## Supersampling: stills and screenshots
254
-
255
- ```ts
256
- import {Engine} from 'margoengine/core';
257
- import {supersample, supersampleBlob} from 'margoengine/quality/ssaa';
258
- const canvas = document.querySelector('canvas')!;
259
- const engine = await Engine.create(canvas, {backend: 'webgpu'});
260
-
261
- const image = await supersample(engine, {samples: 16});
262
- // image.width, image.height, image.data: RGBA bytes, top row first
263
- const pixels = new ImageData(image.data, image.width, image.height);
264
- console.log(pixels.width);
265
-
266
- const poster = await supersampleBlob(engine, {samples: 64, width: 3840, height: 2160});
267
- const link = URL.createObjectURL(poster); // PNG; pass type and quality for another format
268
- console.log(link);
269
- ```
270
-
271
- `supersample` renders `samples` whole frames, each moved by a fraction of a pixel along a Halton (2, 3) sequence, and
272
- averages them in linear light in 32-bit floats. Every edge, thin line, shadow boundary and shader highlight gets that
273
- many samples per pixel, which MSAA alone does not give. It works on every tier and at 4x MSAA it multiplies.
274
-
275
- | Option | Default | Meaning |
276
- | --- | --- | --- |
277
- | `samples` | `16` | Frames averaged, 1 to 1024. Each costs one render; memory does not grow with it |
278
- | `width`, `height` | canvas size | Picture size, up to the device's texture limit. Larger than the canvas works |
279
- | `camera` | `engine.camera` | Camera to shoot through |
280
- | `signal` | none | Rejects with `signal.reason`, checked every 4 frames and after the read |
281
-
282
- Time stands still during a still (delta 0) and the same call gives the same picture. The engine's own loop keeps
283
- running between batches and never sees the moved camera; the canvas ends on an ordinary frame. Effects with history
284
- (`TAA`) run in the still and soften it: remove them first for the sharpest picture. `TAAUpscale` and other effects that
285
- refuse views (`c.view`) throw. Measured on `packages/quality/test/ssaa-browser.mjs`: 64 samples read 45.3 dB against the
286
- same scene drawn 8 times larger and box-filtered, a plain frame 26.1 dB (single-sampled, 160 x 120).
287
-
288
- For live frames rather than stills, `@margoengine/taa/upscale` renders below output size and rebuilds the full frame
289
- with Lanczos and sharpening or from jittered history.
290
-
291
- Apache-2.0. Optional, tree-shakable package; core peer: ^0.1.0 || ^1.0.0.
292
-
293
- Build and unit tests: npm test --workspace @margoengine/quality
294
-
295
- The GPU correctness suite also renders restored redraw callbacks in default and
296
- secondary scenes, checks their pixels and cancels queued work when stopped.
297
- During the build phase it validates real timestamp readings, tier decisions and
298
- wrapper cleanup. The original triangle p90 below 7 ms and submit-to-done
299
- diagnostic remain in the named deferred speed suite; run them only after the
300
- speed phase is enabled.
1
+ # @margoengine/quality
2
+
3
+ Import `margoengine/quality` from the `margoengine` package, or `@margoengine/quality` from this package alone; the two are the same module. Neither is on npm yet: the [Install](../../README.md#install) section lists the two routes that work today (run in a clone, or install local tarballs).
4
+
5
+ Measured quality tiers. Desktops start on a light tier (single-sampled, pixel ratio capped, paced to an even rate of at
6
+ least 60 FPS) and read the real GPU time of each frame by timestamp queries; a page under the limit gets the full 4× MSAA tier
7
+ from its next load. No PC is first shown the 4× tier or reloaded by the probe (the light tier's own frame rate depends on
8
+ the GPU), and no rule based on device names is involved.
9
+
10
+ ```ts
11
+ import {applyQualityTier, paceEngine, watchQuality} from 'margoengine/quality';
12
+ import {Engine} from 'margoengine/core';
13
+ const canvas = document.querySelector('canvas')!;
14
+
15
+ applyQualityTier(); // before creating the engine
16
+ const engine = await Engine.create(canvas, {backend: 'webgpu'});
17
+ paceEngine(engine); // light tier: an even rate of at least 60 FPS
18
+ // ...build the scene and start rendering, then:
19
+ watchQuality();
20
+ ```
21
+
22
+ - `applyQualityTier()` returns `'light'`, `'high'` or `'phone'`. Phones are single-sampled with the pixel ratio capped
23
+ at 1 (`globalThis.margoLow = 1`), even with `?quality=high` or `?scale=2`. It sets core's `globalThis.margoLow`, which
24
+ core reads when it builds pipelines and sizes the canvas, so it must run before the engine is created.
25
+ - `watchQuality()` reads 120 frames on the light tier and, when the 90th percentile of the time a frame's GPU passes cover (passes that run side by side count once) is under
26
+ `FAST_GPU_MS` (8 ms), remembers `'high'` for this page in `localStorage['margoQuality:' + location.pathname]`. One key
27
+ per page, because the result says what this page's scene costs: a light scene must not mark a weak PC high for a heavy
28
+ one. A slow reading remembers nothing, so one bad session cannot hold a browser on the light tier: the next load
29
+ measures again. On the full tier, five consecutive seconds under 55 FPS remember that for good (`'held'`) and reload
30
+ once (a machine that slowed down, for example on battery).
31
+ - Timestamps: `applyQualityTier()` adds `timestamp-query` to the devices this page asks for, only while the page is still
32
+ to be measured, until `watchQuality()` starts. The reading is its own small chunk, downloaded only by a page that reads. During the reading (about 4 s at 60 FPS, 10 s at most) `submit` and
33
+ `createCommandEncoder` are wrapped and every pass gets timestamp writes; then all of it is put back and its GPU objects
34
+ destroyed, so nothing runs after the reading. Without `timestamp-query` the page stays light and stores nothing. A frame
35
+ whose passes the page times itself is not counted. Copies between passes, presenting and other work between passes are
36
+ not in the number.
37
+ - `onReading(milliseconds)` on `watchQuality` reports the reading when it ends, undefined when there is none.
38
+ - For testing: `?quality=high` or `?quality=low` forces a tier without remembering it; `?scale=1.5` sets the light
39
+ tier's pixel ratio (1 to 2). `localStorage.removeItem('margoQuality:' + location.pathname)` measures again.
40
+ - `paceEngine(engine)` sets core's `engine.pace` hook on the light tier so `engine.start()` renders at an even rate of
41
+ at least 60 FPS instead of swinging between 120 and 40 FPS on a slow GPU. Each frame spans the most whole refreshes that
42
+ still reach 60, so the rate depends on the display:
43
+
44
+ | Display | 60 Hz | 75 Hz | 90 Hz | 100 Hz | 120 Hz | 144 Hz | 165 Hz | 200 Hz | 240 Hz |
45
+ | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
46
+ | Frames per second | 60 | 75 | 90 | 100 | 60 | 72 | 83 | 67 | 60 |
47
+
48
+ Other tiers stay uncapped. Nothing global is patched: other `requestAnimationFrame` loops on the page run at the display
49
+ rate. An app that renders from its own loop (calling `engine.render` itself) can gate it with `frameDue`.
50
+ - `capFrameRate(engine, rate = 60)` sets the same pacing on any engine regardless of tier. It reads the display's refresh
51
+ from the last 16 callback gaps, so it follows a page moved to another display within 16 frames.
52
+ - The light-tier reading skips the first two seconds and gives up after ten, at any refresh rate.
53
+
54
+ ## Dynamic resolution
55
+
56
+ ```ts
57
+ import {applyQualityTier, watchResolution} from 'margoengine/quality';
58
+ import {Engine} from 'margoengine/core';
59
+ const canvas = document.querySelector('canvas')!;
60
+ applyQualityTier(); // light or phone tier
61
+ const engine = await Engine.create(canvas, {backend: 'webgpu'});
62
+ using resolution = watchResolution({budget: 12, min: 0.6}); // restores full resolution when disposed
63
+ console.log(resolution.scale);
64
+ ```
65
+
66
+ `watchResolution` times each frame's GPU work (submit to finished) and, when the average passes `budget` milliseconds
67
+ (default 12), lowers the canvas pixel ratio in 5% steps sized to land under the budget; with room to spare (under 70% of
68
+ it) it rises 5% at a time, and backs off after a rise it had to undo. It moves `globalThis.margoLow`, which core reads every
69
+ frame, so it works on the light and phone tiers. On the full 4x MSAA tier it does nothing (changing the cap there would
70
+ also switch off multisampling); pass your own `apply(scale)` to scale some other way. `ResolutionScaler` is the same
71
+ decision logic without timers: `push(frameMs)` returns the new scale when it changes.
72
+
73
+ ## Feature scaling
74
+
75
+ Resolution is one way down. `@margoengine/quality/features` lowers what the frame actually pays for, in steps it measures.
76
+
77
+ ```ts
78
+ import {Engine} from 'margoengine/core';
79
+ import {SSAO} from 'margoengine/post/ssao';
80
+ import {Shadows} from 'margoengine/shadows';
81
+ import {featureKnobs, optionKnob, watchFeatures} from 'margoengine/quality/features';
82
+ import {TAAUpscale} from 'margoengine/taa/upscale';
83
+ const canvas = document.querySelector('canvas')!;
84
+ const engine = await Engine.create(canvas, {backend: 'webgpu'});
85
+ const shadows = Shadows.attach(engine, {distance: 120});
86
+ const ssao = SSAO.attach(engine);
87
+ const upscale = TAAUpscale.attach(engine, {scale: 1});
88
+
89
+ using features = watchFeatures(
90
+ [
91
+ ...featureKnobs({ssao, shadows, camera: engine.camera}),
92
+ optionKnob('resolution', upscale.options, 'scale', [1, 0.85, 0.7], 2), // anything that reads an option live
93
+ ],
94
+ {budget: 12, onChange: ({name, level}) => console.log(name, level)},
95
+ );
96
+ console.log(features.scaler.levels, features.scaler.costs);
97
+ ```
98
+
99
+ Over `budget` it takes one step, then compares the frame cost before and after. A step that saved under 3% of the frame
100
+ is given back at once and rests for 120 decisions, so nothing is lost for no gain. Once a step is measured it is
101
+ chosen by its measured saving: of the steps that cover the shortfall the least visible goes first (`weight`), and with
102
+ none known to cover it the next untried step is tried, in the knobs' order. Under 70% of the budget the most visible lowered feature
103
+ comes back, if its measured cost still leaves the frame under 90%; a rise that had to be undone doubles the wait, as in
104
+ `ResolutionScaler`. `dispose()` puts every feature back.
105
+
106
+ | `featureKnobs` key | Steps | Weight |
107
+ | --- | --- | --- |
108
+ | `post` | each effect's `enabled` goes false | 1 |
109
+ | `ssao` | `samples` halve twice, then `enabled` false | 1 |
110
+ | `ssr` | `steps` halve twice, then `enabled` false | 1 |
111
+ | `shadows` | `filter` soft, pcf, hard; a set `distance` to 70% and 50% | 1.5 |
112
+ | `shadows` | `resolution` halves twice; `cascades` one at a time to two (not with `bounds` or `frustum`) | 2 |
113
+ | `volumetric` | `grid` halves, then `enabled` false | 2 |
114
+ | `lod` | `bias` 1.5 and 2 times | 2 |
115
+ | `camera` | `far` to 75% and 50%; what lies past it stops drawing, so pair it with fog | 3 |
116
+
117
+ Each starts from the value the app set, and a feature already off gets no knob. A knob is `{name, levels, apply(level), weight}`,
118
+ so anything can be one. `FeatureScaler` is the same logic without timers: `push(frameMs)` returns the change it made,
119
+ `budget` can be set at any time, and `restart()` drops the running measure after a change it did not make, such as a new
120
+ scene. Options: `budget` 12, `window` 30, `settle` 8 (samples ignored after a change), `minSaving` 0.03.
121
+
122
+ A first change of shadow filter compiles shader variants, and a change of shadow `resolution` or `cascades` or of the fog
123
+ `grid` allocates new textures, so that frame hitches once; `settle` keeps it out of the measure.
124
+
125
+ ## Battery and heat
126
+
127
+ `@margoengine/quality/power` eases off when the machine is on battery or running hot.
128
+
129
+ ```ts
130
+ import {Engine} from 'margoengine/core';
131
+ import {applyQualityTier, paceEngine} from 'margoengine/quality';
132
+ import {watchFeatures, featureKnobs} from 'margoengine/quality/features';
133
+ import {watchPower} from 'margoengine/quality/power';
134
+ const canvas = document.querySelector('canvas')!;
135
+ applyQualityTier();
136
+ const engine = await Engine.create(canvas, {backend: 'webgpu'});
137
+ paceEngine(engine);
138
+ using features = watchFeatures(featureKnobs({camera: engine.camera}));
139
+ using power = watchPower({
140
+ engine, // capped while easing off, its own pace back after
141
+ features: features.scaler, // budget cut while easing off
142
+ onChange: ({level, charging, battery, pressure, hot}) => console.log(level, charging, battery, pressure, hot),
143
+ });
144
+ console.log(power.reading.level);
145
+ ```
146
+
147
+ | Level | When | Frame cap (`rates`) | Budget (`budgets`) |
148
+ | --- | --- | --- | --- |
149
+ | 0 | On mains, or the browser does not say | The engine's own | Full |
150
+ | 1 | On battery | 60 | 75% |
151
+ | 2 | Hot, CPU pressure `serious` or `critical`, or battery at `lowBattery` (20%) or under | 30 | 50% |
152
+
153
+ - Battery comes from `navigator.getBattery` and CPU pressure from `PressureObserver`, where the browser has them. A
154
+ browser that has neither still gets the frame time reading. A source that refuses is left out; the others keep working.
155
+ - Heat is read from frame times by `FrameDrift`: a GPU that throttles slows gradually, so the median frame cost creeps
156
+ 25% over the coolest reading with no step above 15% between five-second readings, and stays there for six of them. A
157
+ new view or level moves the cost in one step and starts the measure over. Once hot it stays hot for 60 readings (five
158
+ minutes) or until the cost creeps back, because easing off lowers the cost by itself. Options: `window` 300, `rise`
159
+ 1.25, `readings` 6, `jump` 0.15, `hold` 60. `power.restart()` forgets the measure after a change you know of.
160
+ - The full tier cannot change while running (4x multisampling is built into the pipelines). On it, leaving level 0 sets
161
+ this tab's next load to the light tier, in sessionStorage, keeping what the page measured; back at level 0 the next load
162
+ is full again. The page is not reloaded unless you ask: pass `reload: () => location.reload()` to change tier at once.
163
+ `?quality=high` still wins. `currentTier()` from the root entry reads the tier.
164
+
165
+ ## Tier presets
166
+
167
+ The tier also scales optional features. `applyQualityTier()` publishes the tier's `QualityPreset` as
168
+ `globalThis.margoPreset`; each feature package below reads its key when an effect is constructed (`X.attach` or
169
+ `new X`) and uses a preset value only for an option the app left undefined. **Explicit options always win.** Feature
170
+ packages never import this package: the global is the whole contract, so an app that does not use
171
+ `@margoengine/quality` gets every package's own defaults, unchanged.
172
+
173
+ | Key | Package, class | Option | Full tier (package default) | Light tier | Phone tier |
174
+ | --- | --- | --- | --- | --- | --- |
175
+ | `shadows` | `@margoengine/shadows` `Shadows` | `resolution`, `filter`, `cascades` | 2048 (two 4-layer maps, 128 MiB), `'soft'` (PCSS), 4 | 1024 (32 MiB), `'pcf'`, 4 | 1024 (16 MiB), `'pcf'`, 2 |
176
+ | `ssao` | `@margoengine/post/ssao` `SSAO` | `enabled`, `samples` | on, 32 | on, 16 | off |
177
+ | `ssr` | `@margoengine/post/ssr` `SSR` | `enabled`, `steps` | on, 64 | off, 32 | off, 32 |
178
+ | `volumetric` | `@margoengine/environment/volumetric` `VolumetricFog` | `enabled`, `grid` | on, [160, 90, 64] | on, [80, 45, 32] | off |
179
+ | `localShadows` | `@margoengine/clustered/shadows` `LocalShadows` | `resolution` | 512 | 256 | 256 |
180
+ | `vfx` | `@margoengine/vfx` `VFX` | `capacity` | 1,000,000 | 100,000 | 100,000 |
181
+ | `scatter` | `@margoengine/scatter` `Scatter` | `lodFade` | 2 | 2 | 0 |
182
+
183
+ The phone preset publishes `ssao: { enabled: false }` and `volumetric: { enabled: false }`. Disabled `VolumetricFog`
184
+ skips its pass and makes no textures; omitting `enabled` keeps it on. Explicit feature options still win over preset defaults.
185
+
186
+ Shadows on the light and phone tiers use `filter: 'pcf'`: four hardware comparison taps per lit pixel instead of PCSS's
187
+ 16 blocker reads and 32 taps (a fixed edge about three texels wide instead of contact-hardening penumbrae). Phones also
188
+ render two cascades instead of four (half the depth passes) and set scatter's `lodFade: 0`, which compiles its shaders
189
+ without `discard`: tile-based phone GPUs then keep early depth rejection under dense grass. Pass `filter: 'soft'`,
190
+ `cascades: 4` or `lodFade: 2` to keep those on every tier.
191
+
192
+ ```ts
193
+ import {applyQualityTier, qualityPreset} from 'margoengine/quality';
194
+ import {Shadows} from 'margoengine/shadows';
195
+ import {Engine} from 'margoengine/core';
196
+ const engine = await Engine.create(document.querySelector('canvas')!);
197
+
198
+ applyQualityTier(); // light tier: margoPreset.shadows = {resolution: 1024}
199
+ const shadows = Shadows.attach(engine, {distance: 120}); // 1024 on light, 2048 on the full tier
200
+ shadows.dispose(); // Release the current owner before trying the explicit resolution.
201
+ const crisp = Shadows.attach(engine, {distance: 120, resolution: 2048}); // explicit: 2048 on every tier
202
+ const particles = qualityPreset().vfx?.capacity ?? 1_000_000; // read a value for your own UI
203
+ ```
204
+
205
+ - `QUALITY_PRESETS` holds the table above (`high` is empty: package defaults). `qualityPreset()` returns this page's.
206
+ - The preset is read once per effect, at construction; changing tier means a new page load, as before.
207
+ - With a preset the effect's `options` is a copy (the app's object is not modified); edit `effect.options`, not the
208
+ object you passed, to change a value later. Without a preset `effect.options` is the object you passed.
209
+ - `VFX`: an explicit `initialCount` larger than the preset capacity keeps the default capacity (the app asked for that
210
+ many particles). `burst(n)` above the preset capacity throws as it always did above `capacity`; pass `capacity`
211
+ explicitly if your app bursts more than 100,000 particles on the light tier.
212
+ - Bloom, FXAA, Tonemap, TAA and culling have no tier preset: none has an option that trades quality for GPU time.
213
+ DOF has none either: `maxRadius` 8 instead of 16 measured no GPU saving on the light tier (its 64 taps are fixed)
214
+ and only shrank the blur (`examples/package-benchmarks/results/tier-presets-light-diagnostic.json`).
215
+ - Contract tests: `test/quality.test.js` (writer) and `tests/quality-presets.test.js` (every reader). GPU-call proof
216
+ (no preset: identical calls to before; preset = passing its values; explicit options win):
217
+ `node examples/package-benchmarks/proofs/quality-presets.proof.js`.
218
+
219
+ ## Pipeline warm-up and device restoration
220
+
221
+ ```ts
222
+ import {warmUp} from 'margoengine/quality/warm';
223
+ import {redrawAfterRestore} from 'margoengine/quality';
224
+ import {Engine} from 'margoengine/core';
225
+ const engine = await Engine.create(document.querySelector('canvas')!);
226
+
227
+ // ...attach features and build the scene, then, still behind the loading screen:
228
+ const report = await warmUp(engine); // {pipelines, fallbacks, rounds, rebooted}
229
+ // Options: {frames: 2, maxRounds: 256, signal}; pass an AbortSignal to cancel (rejects with signal.reason).
230
+ engine.start();
231
+ redrawAfterRestore(engine, () => engine.render({delta: 0})); // only for apps that render on demand
232
+ ```
233
+
234
+ - `warmUp(engine)` creates the pipelines of every attached feature with `createRenderPipelineAsync` /
235
+ `createComputePipelineAsync`, so the first visible frame that draws a feature does not stall on shader compilation.
236
+ Features create pipelines lazily inside their passes, so it renders warm frames (delta 0) into an offscreen texture:
237
+ a frame that reaches a missing pipeline is stopped there, the work it already encoded is submitted, the pipeline
238
+ compiles asynchronously, and the frame is rendered again until two complete. Nothing is presented and frames from the
239
+ engine's own loop are untouched. It resolves once the GPU has finished the warm frames, so pipelines a feature made
240
+ synchronously at attach (GrassField does) have compiled by then too, during loading but not in parallel. A feature that stores state before creating its pipeline (so the retry skips the
241
+ creation) fails on the retry; warmUp then restores the device (`engine.rebootDevice()`, every feature's restore hook)
242
+ and finishes with synchronous creation (`report.rebooted`). A feature attached later or switched off is not warmed:
243
+ call `warmUp` again after attaching it. Zero cost unless imported: no package reads it.
244
+ - On the WebGL2 compatibility layer with `KHR_parallel_shader_compile` no frame is stopped: each warm frame runs whole
245
+ with the layer's link hold on (`Symbol.for('margoengine.queue.holdsLinks')` on the queue), so the layer keeps the
246
+ frame's submits, and the writes after them in order, until every program the frame made has linked and drawn once,
247
+ then replays them in tasks of about 50 ms. All of a frame's links run side by side, so `report.rounds` is a few
248
+ whole frames (ten-thousand-trees: ready in 17.7 s where the stopped route took 28.2 s, KB-QUALITY-WARMSERIAL1) and
249
+ `report.pipelines` counts the distinct pipelines the warm frames made. Call it before `engine.start()`: frames a
250
+ running loop renders meanwhile wait in the queue behind the held frame.
251
+ - `redrawAfterRestore(engine, render)`: core restores a lost GPU device by itself and the engine's loop draws the next
252
+ frame, but an app that renders on demand (paused, loop stopped) shows an empty canvas until it renders again. This
253
+ runs `render` on the two frames after every restoration (effects that read the previous frame, such as water
254
+ refraction and sky reflections, settle on the second). The returned stop function removes the helper from its
255
+ registered scene and cancels queued redraws. Removing that plugin, disposing its scene or disposing the engine
256
+ also cancels pending redraws; a later plugin with the same name is preserved.
257
+ - First-use hitch per feature (`node examples/package-benchmarks/warm-up-gpu.mjs`, results
258
+ `examples/package-benchmarks/results/warm-up-gpu.json`): see the table there.
259
+
260
+ ## Supersampling: stills and screenshots
261
+
262
+ ```ts
263
+ import {Engine} from 'margoengine/core';
264
+ import {supersample, supersampleBlob} from 'margoengine/quality/ssaa';
265
+ const canvas = document.querySelector('canvas')!;
266
+ const engine = await Engine.create(canvas, {backend: 'webgpu'});
267
+
268
+ const image = await supersample(engine, {samples: 16});
269
+ // image.width, image.height, image.data: RGBA bytes, top row first
270
+ const pixels = new ImageData(image.data, image.width, image.height);
271
+ console.log(pixels.width);
272
+
273
+ const poster = await supersampleBlob(engine, {samples: 64, width: 3840, height: 2160});
274
+ const link = URL.createObjectURL(poster); // PNG; pass type and quality for another format
275
+ console.log(link);
276
+ ```
277
+
278
+ `supersample` renders `samples` whole frames, each moved by a fraction of a pixel along a Halton (2, 3) sequence, and
279
+ averages them in linear light in 32-bit floats. Every edge, thin line, shadow boundary and shader highlight gets that
280
+ many samples per pixel, which MSAA alone does not give. It works on every tier and at 4x MSAA it multiplies.
281
+
282
+ | Option | Default | Meaning |
283
+ | --- | --- | --- |
284
+ | `samples` | `16` | Frames averaged, 1 to 1024. Each costs one render; memory does not grow with it |
285
+ | `width`, `height` | canvas size | Picture size, up to the device's texture limit. Larger than the canvas works |
286
+ | `camera` | `engine.camera` | Camera to shoot through |
287
+ | `signal` | none | Rejects with `signal.reason`, checked every 4 frames and after the read |
288
+
289
+ Time stands still during a still (delta 0) and the same call gives the same picture. The engine's own loop keeps
290
+ running between batches and never sees the moved camera; the canvas ends on an ordinary frame. Effects with history
291
+ (`TAA`) run in the still and soften it: remove them first for the sharpest picture. `TAAUpscale` and other effects that
292
+ refuse views (`c.view`) throw. Measured on `packages/quality/test/ssaa-browser.mjs`: 64 samples read 45.3 dB against the
293
+ same scene drawn 8 times larger and box-filtered, a plain frame 26.1 dB (single-sampled, 160 x 120).
294
+
295
+ For live frames rather than stills, `@margoengine/taa/upscale` renders below output size and rebuilds the full frame
296
+ with Lanczos and sharpening or from jittered history.
297
+
298
+ Apache-2.0. Optional, tree-shakable package; core peer: ^0.1.0 || ^1.0.0.
299
+
300
+ Build and unit tests: npm test --workspace @margoengine/quality
301
+
302
+ The GPU correctness suite also renders restored redraw callbacks in default and
303
+ secondary scenes, checks their pixels and cancels queued work when stopped.
304
+ During the build phase it validates real timestamp readings, tier decisions and
305
+ wrapper cleanup. The original triangle p90 below 7 ms and submit-to-done
306
+ diagnostic remain in the named deferred speed suite; run them only after the
307
+ speed phase is enabled.