@margoengine/quality 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Scott Campbell
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,4 @@
1
+ Margo Engine
2
+ Copyright 2026 Scott Campbell
3
+
4
+ This product includes Margo Engine (https://margoengine.com) by Scott Campbell.
package/README.md CHANGED
@@ -1,3 +1,300 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
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.
@@ -0,0 +1,45 @@
1
+ import type { EngineKernel } from '@margoengine/core';
2
+ /** A change source, including controls and DOM EventTargets. */
3
+ export interface DemandSource {
4
+ /** Subscribe to a change, start, end or load event. */
5
+ addEventListener(type: string, listener: () => void): void;
6
+ /** Remove the subscription. */
7
+ removeEventListener(type: string, listener: () => void): void;
8
+ }
9
+ /** Options for the demand frame loop. */
10
+ export interface DemandOptions {
11
+ /** Controls or loaders emitting change/start/end/load. Default none. */
12
+ sources?: readonly DemandSource[];
13
+ /** Update before rendering; return true while an animation needs another frame. Default none. */
14
+ update?: (delta: number, time: number) => boolean | void;
15
+ /** Request an initial frame. Default true. */
16
+ initial?: boolean;
17
+ /** Maximum animation step in seconds after a delayed frame. Default 0.1. */
18
+ maxDelta?: number;
19
+ /** Abort cancels queued work and subscriptions. Default none. */
20
+ signal?: AbortSignal;
21
+ /** Frame scheduler. Default requestAnimationFrame. */
22
+ request?: (callback: (time: number) => void) => number;
23
+ /** Cancels a scheduled frame. Default cancelAnimationFrame. */
24
+ cancel?: (id: number) => void;
25
+ }
26
+ /** An idle loop has no scheduled frame or polling timer. */
27
+ export interface DemandLoop {
28
+ /** Request at least this many frames, coalescing requests. Default 1. */
29
+ invalidate(frames?: number): void;
30
+ /** Keep drawing until the returned release function runs; independent callers nest. */
31
+ animate(): () => void;
32
+ /** Invalidate when a successful load finishes, preserving its result or rejection. */
33
+ loaded<T>(promise: PromiseLike<T>): Promise<T>;
34
+ /** Whether a frame is queued. */
35
+ readonly pending: boolean;
36
+ /** Stop and unsubscribe; the engine remains stopped. */
37
+ dispose(): void;
38
+ [Symbol.dispose](): void;
39
+ }
40
+ /**
41
+ * Stop the engine's continuous loop and render only dirty frames. Attached controls and plugins update during
42
+ * engine.render; app engine.onFrame callbacks belong in options.update instead. No import-time side effects.
43
+ * @throws RangeError for an invalid frame count; use a positive integer.
44
+ */
45
+ export declare function renderOnDemand(engine: EngineKernel, options?: DemandOptions): DemandLoop;
package/dist/demand.js ADDED
@@ -0,0 +1,74 @@
1
+ // @margo/core-built 0.1.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+
4
+ import { r as e } from "./errors-XvcwUnU4.js";
5
+ //#region src/demand.ts
6
+ var t = 0;
7
+ function n(n, r = {}) {
8
+ let { sources: i = [], update: a, initial: o = !0, signal: s, maxDelta: c = .1, request: l = globalThis.requestAnimationFrame.bind(globalThis), cancel: u = globalThis.cancelAnimationFrame.bind(globalThis) } = r;
9
+ if (!Number.isFinite(c) || c <= 0) throw e("Invalid demand delta; use a finite value above zero", "arguments");
10
+ let d = !1, f, p = 0, m = 0, h, g = () => {
11
+ !d && f === void 0 && (p || m) && (f = l(v));
12
+ }, _ = (t = 1) => {
13
+ if (!Number.isSafeInteger(t) || t < 1) throw e("Invalid demand count; use a positive safe integer", "arguments");
14
+ d || (p = Math.max(p, t), g());
15
+ }, v = (e) => {
16
+ if (f = void 0, d) return;
17
+ p = Math.max(0, p - 1);
18
+ let t = h === void 0, r = t ? 0 : Math.min(c, Math.max(0, (e - h) / 1e3));
19
+ h = e;
20
+ try {
21
+ a?.(r, e) && (p = Math.max(p, 1)), d || n.render({
22
+ delta: t ? Math.min(c, 1 / 60) : r,
23
+ views: n.views
24
+ });
25
+ } catch (e) {
26
+ throw x(), e;
27
+ }
28
+ g(), f === void 0 && (h = void 0);
29
+ }, y = () => _(), b = [
30
+ "start",
31
+ "change",
32
+ "end",
33
+ "load"
34
+ ], x = () => {
35
+ if (!d) {
36
+ d = !0, f !== void 0 && u(f), f = void 0;
37
+ for (let e of i) for (let t of b) e.removeEventListener(t, y);
38
+ s?.removeEventListener("abort", x), n.sceneOf(S)?.removePlugin(S.name);
39
+ }
40
+ }, S = {coreRequirement:/*@__PURE__*/__margoCoreRequirement("0.1.0",import.meta.url),
41
+ name: `quality-demand-${++t}`,
42
+ setup() {},
43
+ onDeviceRestored: () => _(2),
44
+ dispose: x
45
+ };
46
+ if (n.stop(), s?.aborted) d = !0;
47
+ else {
48
+ n.use(S);
49
+ for (let e of i) for (let t of b) e.addEventListener(t, y);
50
+ s?.addEventListener("abort", x, { once: !0 }), o && _();
51
+ }
52
+ return {
53
+ invalidate: _,
54
+ animate() {
55
+ if (d) return () => {};
56
+ m++, _();
57
+ let e = !1;
58
+ return () => {
59
+ e || (e = !0, m--, _());
60
+ };
61
+ },
62
+ async loaded(e) {
63
+ let t = await e;
64
+ return _(), t;
65
+ },
66
+ get pending() {
67
+ return f !== void 0;
68
+ },
69
+ dispose: x,
70
+ [Symbol.dispose]: x
71
+ };
72
+ }
73
+ //#endregion
74
+ export { n as renderOnDemand };
@@ -0,0 +1,7 @@
1
+ //#region ../shared/errors.js
2
+ var e = (e, t) => Object.assign(Error(t), {
3
+ name: "MargoError",
4
+ code: e
5
+ }), t = (e, t) => `${e}; see https://margoengine.com/errors#${t}`, n = (n, r, i = n) => e(n, t(r, i)), r = (e, n) => RangeError(t(e, n));
6
+ //#endregion
7
+ export { e as n, r, n as t };