roamwright 0.56.0 → 0.58.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 +2 -1
- package/examples/pacing.html +100 -0
- package/examples/pacing.js +305 -0
- package/index.js +13 -1
- package/package.json +1 -1
- package/rendering/perf-box-worker.js +95 -0
- package/rendering/perf-box.js +94 -0
- package/rendering/perf-probe-passes.js +333 -0
- package/rendering/perf-probe.js +406 -0
- package/rendering/sea-shaders.js +30 -0
- package/rendering/water-material.js +32 -33
- package/runtime/device-quality.js +75 -4
- package/runtime/perf-box-text.js +50 -0
- package/runtime/perf-probe.js +145 -0
- package/runtime/perf-watch.js +158 -0
- package/runtime/quality-fit.js +25 -5
- package/runtime/quality-store.js +37 -9
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
const BYTES_IN_MB = 1048576;
|
|
2
|
+
const megabytes = bytes => `${Math.round(bytes / BYTES_IN_MB)} MB`;
|
|
3
|
+
const share = (ms, fps) => Math.min(100, Math.round((ms * fps) / 10));
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Creates the retained state for the on-screen performance box across readout intervals.
|
|
7
|
+
* Memory is estimated less frequently than FPS, so the most recent estimate is carried forward.
|
|
8
|
+
*
|
|
9
|
+
* @returns {{ memory: { script: number, meshes: number, textures: number, targets: number } | null }}
|
|
10
|
+
*/
|
|
11
|
+
export function createPerfBoxState() {
|
|
12
|
+
return { memory: null };
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Formats one readout sample into the text lines shown by the on-screen performance box:
|
|
17
|
+
* FPS, physical pixel dimensions, optional RAM/script/meshes/textures/frame estimates,
|
|
18
|
+
* CPU percentage, optional GPU percentage, and active thread count.
|
|
19
|
+
*
|
|
20
|
+
* Pure arithmetic with no DOM or Three.js dependencies so it runs identically in a worker
|
|
21
|
+
* (drawing onto an `OffscreenCanvas`) or on the main thread as a text fallback.
|
|
22
|
+
*
|
|
23
|
+
* @param {{ memory: { script: number, meshes: number, textures: number, targets: number } | null }} kept Retained state from `createPerfBoxState()`.
|
|
24
|
+
* @param {object} sample Raw measurements collected over the readout interval.
|
|
25
|
+
* @param {number} sample.seconds Duration of the readout interval in seconds.
|
|
26
|
+
* @param {number} sample.frames Number of frames rendered during the interval.
|
|
27
|
+
* @param {number} sample.scriptMs Total main-thread script milliseconds summed over `frames`.
|
|
28
|
+
* @param {number | null} sample.cardMs GPU time of one frame in milliseconds, or `null` when unavailable.
|
|
29
|
+
* @param {number} sample.wide Drawing buffer width in physical pixels.
|
|
30
|
+
* @param {number} sample.high Drawing buffer height in physical pixels.
|
|
31
|
+
* @param {{ script: number, meshes: number, textures: number, targets: number } | null} [sample.memory] Latest memory breakdown in bytes, if refreshed.
|
|
32
|
+
* @param {number} sample.threads Active thread count (main + pool workers + metrics worker + service worker).
|
|
33
|
+
* @returns {string[]}
|
|
34
|
+
*/
|
|
35
|
+
export function formatPerfBoxLines(kept, sample) {
|
|
36
|
+
if (sample.memory) kept.memory = sample.memory;
|
|
37
|
+
const fps = sample.frames / sample.seconds,
|
|
38
|
+
lines = [`${fps.toFixed(0)} fps`, `${sample.wide} x ${sample.high} px`],
|
|
39
|
+
m = kept.memory;
|
|
40
|
+
if (m) {
|
|
41
|
+
// A leading ~ marks estimates reckoned from GPU buffer and texture sizes, which browsers do not report directly.
|
|
42
|
+
lines.push(`RAM ~${megabytes(m.script + m.meshes + m.textures + m.targets)}`);
|
|
43
|
+
if (m.script) lines.push(` script ${megabytes(m.script)}`);
|
|
44
|
+
lines.push(` meshes ~${megabytes(m.meshes)}`, ` textures ~${megabytes(m.textures)}`, ` frame ~${megabytes(m.targets)}`);
|
|
45
|
+
}
|
|
46
|
+
lines.push(`CPU ${share(sample.scriptMs / sample.frames, fps)}%`);
|
|
47
|
+
if (sample.cardMs !== null) lines.push(`GPU ${share(sample.cardMs, fps)}%`);
|
|
48
|
+
lines.push(`threads ${sample.threads}`);
|
|
49
|
+
return lines;
|
|
50
|
+
}
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
/** Default flight legs for the self-measuring route probe: `[label, heightAboveGroundM, speedMetersPerMs, direction, pitchRad]`. */
|
|
2
|
+
export const DEFAULT_PROBE_LEGS = [
|
|
3
|
+
['out at 65 m and 70 m a second', 65, 0.07, 1, -0.35],
|
|
4
|
+
['back the same way', 65, 0.07, -1, -0.35],
|
|
5
|
+
['out at 6 m and 25 m a second', 6, 0.025, 1, -0.08],
|
|
6
|
+
['back the same way', 6, 0.025, -1, -0.08],
|
|
7
|
+
];
|
|
8
|
+
|
|
9
|
+
/** Default preset property groups swapped from Low one at a time during `?probe=lows`. */
|
|
10
|
+
export const DEFAULT_LOW_GROUPS = [
|
|
11
|
+
['shadow'],
|
|
12
|
+
['grass'],
|
|
13
|
+
['treeDist', 'treeDensity', 'treeHi'],
|
|
14
|
+
['lodScale'],
|
|
15
|
+
['clouds'],
|
|
16
|
+
['crowd'],
|
|
17
|
+
['houses'],
|
|
18
|
+
['fx'],
|
|
19
|
+
];
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Returns the upper-middle element of a numeric array without mutating the input.
|
|
23
|
+
*
|
|
24
|
+
* @param {number[]} values
|
|
25
|
+
* @returns {number}
|
|
26
|
+
*/
|
|
27
|
+
export function median(values) {
|
|
28
|
+
const sorted = [...values].sort((a, b) => a - b);
|
|
29
|
+
return sorted[sorted.length >> 1];
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Formats the result of alternating turn-about FPS trials (`changed` vs `own`).
|
|
34
|
+
*
|
|
35
|
+
* @param {number[]} changed Frame-rate counts measured with the change active.
|
|
36
|
+
* @param {number[]} own Frame-rate counts measured in the baseline state.
|
|
37
|
+
* @returns {string}
|
|
38
|
+
*/
|
|
39
|
+
export function formatTurnsResult(changed, own) {
|
|
40
|
+
return `${median(changed)} against ${median(own)} as it is (by turns: ${changed.join(' ')} against ${own.join(' ')})`;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Parses a `?at=x,z,up,yaw,pitch` query value into numeric placement coordinates.
|
|
45
|
+
* Returns `null` when `asked` is empty.
|
|
46
|
+
*
|
|
47
|
+
* @param {string | null | undefined} asked
|
|
48
|
+
* @returns {{ x: number, z: number, up: number, yaw: number, pitch: number } | null}
|
|
49
|
+
*/
|
|
50
|
+
export function parseStandAt(asked) {
|
|
51
|
+
if (!asked) return null;
|
|
52
|
+
const [x, z, up = 2, yaw = 0, pitch = 0] = asked.split(',').map(Number);
|
|
53
|
+
return { x, z, up, yaw, pitch };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Builds the trial list `[keys, values]` for `?probe=lows`. When `setParam` (e.g. `'treeHi:20;grass:18'`)
|
|
58
|
+
* is given, each `key:number` pair becomes a single-key trial; otherwise each group in `defaultGroups`
|
|
59
|
+
* pulls its values from `presets.low`.
|
|
60
|
+
*
|
|
61
|
+
* @param {string | null | undefined} setParam Optional semicolon-separated `key:value` overrides.
|
|
62
|
+
* @param {{ low: Record<string, unknown> }} presets Preset table containing at least `low`.
|
|
63
|
+
* @param {string[][]} [defaultGroups=DEFAULT_LOW_GROUPS] Preset key groups to test when `setParam` is empty.
|
|
64
|
+
* @returns {Array<[string[], unknown[]]>}
|
|
65
|
+
*/
|
|
66
|
+
export function parseLowTrials(setParam, presets, defaultGroups = DEFAULT_LOW_GROUPS) {
|
|
67
|
+
const asked = (setParam || '')
|
|
68
|
+
.split(';')
|
|
69
|
+
.filter(Boolean)
|
|
70
|
+
.map(pair => pair.split(':'));
|
|
71
|
+
return asked.length
|
|
72
|
+
? asked.map(([key, value]) => [[key], [Number(value)]])
|
|
73
|
+
: defaultGroups.map(keys => [keys, keys.map(key => presets.low[key])]);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Summarizes frame-interval gaps collected over one flown route leg.
|
|
78
|
+
*
|
|
79
|
+
* @param {string} name Leg label.
|
|
80
|
+
* @param {number[]} gaps Inter-frame intervals in milliseconds.
|
|
81
|
+
* @param {number} durationMs Total elapsed leg time in milliseconds.
|
|
82
|
+
* @returns {string}
|
|
83
|
+
*/
|
|
84
|
+
export function summarizeRouteLeg(name, gaps, durationMs) {
|
|
85
|
+
const over = ms => gaps.filter(gap => gap > ms).length;
|
|
86
|
+
return (
|
|
87
|
+
`${name}: ${Math.round((gaps.length * 1000) / durationMs)} frames a second, ${over(25)} stood over 25 ms, ${over(50)} over 50, ` +
|
|
88
|
+
`${over(100)} over 100, the longest ${Math.round(Math.max(...gaps))} ms`
|
|
89
|
+
);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Creates a frame-rate sampler for self-measuring probes: counts displayed frames per second over a
|
|
94
|
+
* fixed window (`shown`), measures with a feature temporarily disabled (`shownWithout`), and compares
|
|
95
|
+
* two states by alternating turns (`byTurns`) so background machine load moves both sides equally.
|
|
96
|
+
*
|
|
97
|
+
* @param {object} options
|
|
98
|
+
* @param {() => number} options.getFrame Returns the monotonically increasing rendered frame counter.
|
|
99
|
+
* @param {(ms: number) => Promise<void>} [options.wait] Async sleep helper in milliseconds.
|
|
100
|
+
* @param {() => number} [options.clock] Monotonic clock in milliseconds (defaults to `performance.now`).
|
|
101
|
+
* @param {number} [options.loopMs=3000] Duration of each counted frame-rate window in milliseconds.
|
|
102
|
+
* @param {number} [options.switchSettleMs=300] Delay after toggling a state before counting begins.
|
|
103
|
+
* @param {number} [options.turns=4] Number of alternating pairs run by `byTurns`.
|
|
104
|
+
* @returns {{ shown: () => Promise<number>, shownWithout: (off: () => void, back: () => void) => Promise<number>,
|
|
105
|
+
* byTurns: (change: () => void, back: () => void, settleMs?: number) => Promise<string> }}
|
|
106
|
+
*/
|
|
107
|
+
export function createFrameSampler({
|
|
108
|
+
getFrame,
|
|
109
|
+
wait = ms => new Promise(resolve => setTimeout(resolve, ms)),
|
|
110
|
+
clock = () => performance.now(),
|
|
111
|
+
loopMs = 3000,
|
|
112
|
+
switchSettleMs = 300,
|
|
113
|
+
turns = 4,
|
|
114
|
+
}) {
|
|
115
|
+
async function shown() {
|
|
116
|
+
await wait(switchSettleMs);
|
|
117
|
+
const from = getFrame(),
|
|
118
|
+
began = clock();
|
|
119
|
+
await wait(loopMs);
|
|
120
|
+
return Math.round(((getFrame() - from) * 1000) / (clock() - began));
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
async function shownWithout(off, back) {
|
|
124
|
+
off();
|
|
125
|
+
const frames = await shown();
|
|
126
|
+
back();
|
|
127
|
+
return frames;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
async function byTurns(change, back, settleMs = 0) {
|
|
131
|
+
const changed = [],
|
|
132
|
+
own = [];
|
|
133
|
+
for (let turn = 0; turn < turns; turn++) {
|
|
134
|
+
change();
|
|
135
|
+
await wait(settleMs);
|
|
136
|
+
changed.push(await shown());
|
|
137
|
+
back();
|
|
138
|
+
await wait(settleMs);
|
|
139
|
+
own.push(await shown());
|
|
140
|
+
}
|
|
141
|
+
return formatTurnsResult(changed, own);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
return { shown, shownWithout, byTurns };
|
|
145
|
+
}
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import { createFramePacingMonitor } from './frame-pacing.js';
|
|
2
|
+
|
|
3
|
+
const fileOf = url => (url ? url.slice(url.lastIndexOf('/') + 1).split('?')[0] : '');
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Formats the longest script attributions and style/layout/paint time of a browser
|
|
7
|
+
* `long-animation-frame` entry, counting only time spent at or after `enteredAt`.
|
|
8
|
+
*
|
|
9
|
+
* @param {{ startTime: number, duration: number, styleAndLayoutStart?: number, scripts?: Array<{ startTime: number, duration: number, sourceFunctionName?: string, invoker?: string, sourceURL?: string }> }} entry Long Animation Frame performance entry.
|
|
10
|
+
* @param {number} [enteredAt=0] Timestamp (`performance.now()`, ms) when interactive play began; earlier work is excluded.
|
|
11
|
+
* @param {number} [scriptsNamed=2] Maximum number of scripts to name in the formatted summary.
|
|
12
|
+
* @returns {string}
|
|
13
|
+
*/
|
|
14
|
+
export function formatLongFrameAttribution(entry, enteredAt = 0, scriptsNamed = 2) {
|
|
15
|
+
const elapsed = (start, end) => Math.max(0, end - Math.max(start, enteredAt));
|
|
16
|
+
const scripts = (entry.scripts || [])
|
|
17
|
+
.map(s => ({ s, ms: elapsed(s.startTime, s.startTime + s.duration) }))
|
|
18
|
+
.filter(({ ms }) => ms > 0)
|
|
19
|
+
.sort((a, b) => b.ms - a.ms)
|
|
20
|
+
.slice(0, scriptsNamed);
|
|
21
|
+
const named = scripts.map(
|
|
22
|
+
({ s, ms }) => `${s.sourceFunctionName || s.invoker || 'a script'} in ${fileOf(s.sourceURL) || '?'} ${Math.round(ms)} ms`,
|
|
23
|
+
);
|
|
24
|
+
const drawing = entry.styleAndLayoutStart ? Math.round(elapsed(entry.styleAndLayoutStart, entry.startTime + entry.duration)) : 0;
|
|
25
|
+
if (drawing) named.push(`style, layout and paint ${drawing} ms`);
|
|
26
|
+
return named.join(', ');
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Formats a coalesced long-frame diagnostic message from the worst stall in a reporting window.
|
|
31
|
+
*
|
|
32
|
+
* @param {number} count Number of long frames observed in the window.
|
|
33
|
+
* @param {number} worstMs Duration of the worst frame in milliseconds.
|
|
34
|
+
* @param {string} [what=''] Attribution string (script names or fallback script timing).
|
|
35
|
+
* @param {number} [thresholdMs=100] Long-frame threshold in milliseconds.
|
|
36
|
+
* @returns {string}
|
|
37
|
+
*/
|
|
38
|
+
export function formatLongFrameMessage(count, worstMs, what = '', thresholdMs = 100) {
|
|
39
|
+
const more = count > 1 ? ` (the worst of ${count} over ${thresholdMs} ms)` : '';
|
|
40
|
+
return `long frame of ${Math.round(worstMs)} ms${more}${what ? ': ' + what : ''}`;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Watches a running world loop for visible stalls and sustained slow frame pacing, writing coalesced
|
|
45
|
+
* `'perf'` entries to a diagnostic log. Uses `PerformanceObserver('long-animation-frame')` when the
|
|
46
|
+
* browser supports it for script-level attribution, and falls back to loop frame intervals plus script
|
|
47
|
+
* time elsewhere.
|
|
48
|
+
*
|
|
49
|
+
* @param {object} options
|
|
50
|
+
* @param {(kind: string, text: string) => void} options.noteLog Diagnostic log writer.
|
|
51
|
+
* @param {(flush: () => void) => void} [options.beforeLogRead] Registers a flush callback invoked before reading the log.
|
|
52
|
+
* @param {() => boolean} [options.isActive] Returns true when long frames count as interactive stalls (not loading, hidden, or measuring).
|
|
53
|
+
* @param {() => unknown} [options.subject] Current scene/space identity; a change resets sustained pacing windows.
|
|
54
|
+
* @param {number} [options.minimumFps=55] Sustained FPS floor below which consecutive slow windows log a warning.
|
|
55
|
+
* @param {number} [options.windowMs=1000] Duration of each sustained pacing window in milliseconds.
|
|
56
|
+
* @param {number} [options.windows=3] Consecutive slow windows before logging sustained slow frames.
|
|
57
|
+
* @param {number} [options.longFrameMs=100] Single-frame stall threshold in milliseconds.
|
|
58
|
+
* @param {number} [options.longEveryMs=5000] Minimum interval between coalesced long-frame log entries in milliseconds.
|
|
59
|
+
* @param {number} [options.scriptsNamed=2] Maximum number of script culprits named per long frame.
|
|
60
|
+
* @param {number} [options.hiddenGapMs=5000] Frame interval at or above which the gap is treated as a hidden tab rather than a stall.
|
|
61
|
+
* @param {object} [options.page=globalThis] Host providing `performance`, `setTimeout`, `clearTimeout`, and `PerformanceObserver`.
|
|
62
|
+
* @returns {{ startFrameWatch: () => void, resetPacing: () => void, watchFrame: (ms: number, scriptMs: number) => void, flush: () => void, dispose: () => void }}
|
|
63
|
+
*/
|
|
64
|
+
export function createPerfWatch({
|
|
65
|
+
noteLog,
|
|
66
|
+
beforeLogRead,
|
|
67
|
+
isActive = () => true,
|
|
68
|
+
subject = () => true,
|
|
69
|
+
minimumFps = 55,
|
|
70
|
+
windowMs = 1000,
|
|
71
|
+
windows = 3,
|
|
72
|
+
longFrameMs = 100,
|
|
73
|
+
longEveryMs = 5000,
|
|
74
|
+
scriptsNamed = 2,
|
|
75
|
+
hiddenGapMs = 5000,
|
|
76
|
+
page = globalThis,
|
|
77
|
+
}) {
|
|
78
|
+
const held = { n: 0, worst: 0, what: '', next: 0, timer: 0 };
|
|
79
|
+
const now = () => page.performance.now();
|
|
80
|
+
|
|
81
|
+
function writeLong() {
|
|
82
|
+
page.clearTimeout(held.timer);
|
|
83
|
+
held.timer = 0;
|
|
84
|
+
if (!held.n) return;
|
|
85
|
+
noteLog('perf', formatLongFrameMessage(held.n, held.worst, held.what, longFrameMs));
|
|
86
|
+
held.n = held.worst = 0;
|
|
87
|
+
held.what = '';
|
|
88
|
+
held.next = now() + longEveryMs;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function longFrame(ms, what) {
|
|
92
|
+
if (!isActive()) return;
|
|
93
|
+
held.n++;
|
|
94
|
+
if (ms > held.worst) {
|
|
95
|
+
held.worst = ms;
|
|
96
|
+
held.what = what;
|
|
97
|
+
}
|
|
98
|
+
const current = now();
|
|
99
|
+
if (current >= held.next) writeLong();
|
|
100
|
+
else held.timer ||= page.setTimeout(writeLong, held.next - current);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
beforeLogRead?.(writeLong);
|
|
104
|
+
|
|
105
|
+
// Ignore loading frames delivered after entry until interactive play starts.
|
|
106
|
+
let enteredAt = Infinity;
|
|
107
|
+
function startFrameWatch() {
|
|
108
|
+
enteredAt = now();
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const Observer = page.PerformanceObserver;
|
|
112
|
+
const namesFrames = typeof Observer !== 'undefined' && !!Observer.supportedEntryTypes?.includes('long-animation-frame');
|
|
113
|
+
let observer = null;
|
|
114
|
+
if (namesFrames) {
|
|
115
|
+
observer = new Observer(list => {
|
|
116
|
+
for (const entry of list.getEntries()) {
|
|
117
|
+
const inWorld = entry.startTime + entry.duration - Math.max(entry.startTime, enteredAt);
|
|
118
|
+
if (inWorld >= longFrameMs) longFrame(inWorld, formatLongFrameAttribution(entry, enteredAt, scriptsNamed));
|
|
119
|
+
}
|
|
120
|
+
});
|
|
121
|
+
observer.observe({ type: 'long-animation-frame' });
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const pacing = createFramePacingMonitor({
|
|
125
|
+
minimumFps,
|
|
126
|
+
windowMs,
|
|
127
|
+
windows,
|
|
128
|
+
onSlow(fps, ms) {
|
|
129
|
+
noteLog('perf', `sustained slow frames: ${fps.toFixed(1)} FPS over ${(ms / 1000).toFixed(1)} s (animation loop)`);
|
|
130
|
+
},
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
let watched = null;
|
|
134
|
+
function resetPacing() {
|
|
135
|
+
pacing.reset();
|
|
136
|
+
watched = null;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function watchFrame(ms, scriptMs) {
|
|
140
|
+
const currentSubject = subject();
|
|
141
|
+
if (!namesFrames && currentSubject && ms >= longFrameMs && ms < hiddenGapMs)
|
|
142
|
+
longFrame(ms, `the script's update and draw ${Math.round(scriptMs)} ms`);
|
|
143
|
+
if (currentSubject !== watched || !currentSubject || ms >= hiddenGapMs) {
|
|
144
|
+
resetPacing();
|
|
145
|
+
watched = currentSubject;
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
pacing.sample(ms);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function dispose() {
|
|
152
|
+
writeLong();
|
|
153
|
+
observer?.disconnect?.();
|
|
154
|
+
observer = null;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
return { startFrameWatch, resetPacing, watchFrame, flush: writeLong, dispose };
|
|
158
|
+
}
|
package/runtime/quality-fit.js
CHANGED
|
@@ -99,13 +99,15 @@ export function createQualityFit({
|
|
|
99
99
|
// A picture of another size is another load, and the change itself costs frames (a phone turned on its side): what was
|
|
100
100
|
// timed before it is forgotten.
|
|
101
101
|
|
|
102
|
+
const holders = new Set();
|
|
103
|
+
|
|
102
104
|
// Opens with the preset chosen by hand, else the one that fitted last time, else the guess from the device; or, on a page that
|
|
103
105
|
// loaded itself afresh because the card dropped its picture, with the lower one that page asked for, for this page only.
|
|
104
106
|
function startQuality() {
|
|
105
107
|
const chosen = keptChoice();
|
|
106
108
|
fit.suggested = keptFit() ?? deviceQuality();
|
|
107
109
|
fit.chosen = chosen;
|
|
108
|
-
fit.running =
|
|
110
|
+
fit.running = holders.size === 0;
|
|
109
111
|
const name = keptOnce(true) ?? fit.chosen ?? fit.suggested;
|
|
110
112
|
fit.scaleAt = adaptiveResolution ? Math.max(0, scales.indexOf(keptScale(name))) : 0;
|
|
111
113
|
if (adaptiveResolution) setDrawScale(scales[fit.scaleAt], true);
|
|
@@ -125,11 +127,17 @@ export function createQualityFit({
|
|
|
125
127
|
const cardTime = () => fit.card ?? null;
|
|
126
128
|
// The preset chosen by hand, if one was.
|
|
127
129
|
const chosenQuality = () => fit.chosen;
|
|
128
|
-
// Stops or resumes the fitting
|
|
129
|
-
|
|
130
|
-
|
|
130
|
+
// Stops or resumes the fitting for a named holder (for example `'measure'` or `'pace'`).
|
|
131
|
+
// Fitting resumes only once every active holder has released its hold, so frame pacing cannot
|
|
132
|
+
// accidentally release a preset locked by an active measurement.
|
|
133
|
+
function holdQualityFor(who, held) {
|
|
134
|
+
if (held) holders.add(who);
|
|
135
|
+
else holders.delete(who);
|
|
136
|
+
fit.running = holders.size === 0;
|
|
131
137
|
rest();
|
|
132
138
|
}
|
|
139
|
+
// Stops or resumes the fitting for measurements (`'measure'` holder).
|
|
140
|
+
const holdQuality = held => holdQualityFor('measure', held);
|
|
133
141
|
// The suggestion moves to LEVELS[level]: applied, unless another preset was chosen by hand.
|
|
134
142
|
function suggest(level) {
|
|
135
143
|
const name = LEVELS[level];
|
|
@@ -218,5 +226,17 @@ export function createQualityFit({
|
|
|
218
226
|
suggest(at + 1);
|
|
219
227
|
}
|
|
220
228
|
}
|
|
221
|
-
return {
|
|
229
|
+
return {
|
|
230
|
+
cardTime,
|
|
231
|
+
chooseQuality,
|
|
232
|
+
chosenQuality,
|
|
233
|
+
holdQuality,
|
|
234
|
+
holdQualityFor,
|
|
235
|
+
probeDue,
|
|
236
|
+
probed,
|
|
237
|
+
settleQuality,
|
|
238
|
+
startQuality,
|
|
239
|
+
suggestedQuality,
|
|
240
|
+
rest,
|
|
241
|
+
};
|
|
222
242
|
}
|
package/runtime/quality-store.js
CHANGED
|
@@ -1,6 +1,30 @@
|
|
|
1
|
+
/** Ordered quality preset names from lowest to highest. */
|
|
1
2
|
export const LEVELS = ['low', 'medium', 'high'];
|
|
2
3
|
|
|
3
|
-
|
|
4
|
+
/**
|
|
5
|
+
* Persists a world's manual quality choice, fitted preset, one-visit override, and adaptive scale in
|
|
6
|
+
* browser storage under `<namespace>:quality*` keys.
|
|
7
|
+
*
|
|
8
|
+
* On a performance-aimed device (`device.aim === 'performance'`), `keptFit()` returns `performanceDefault`
|
|
9
|
+
* instead of reading the previously fitted preset from storage so a single heavy view cannot trap later
|
|
10
|
+
* visits on a lower preset. A `?q=<level>` query parameter (when `query` is passed) seeds the one-visit
|
|
11
|
+
* override without overwriting the visitor's saved manual choice.
|
|
12
|
+
*
|
|
13
|
+
* @param {string} namespace Storage key prefix (for example `'myworld'`).
|
|
14
|
+
* @param {object} [options]
|
|
15
|
+
* @param {import('./device.js').Device | null} [options.device=null] Device description from `readDevice` or `describeDevice`.
|
|
16
|
+
* @param {'low' | 'medium' | 'high'} [options.performanceDefault='medium'] Preset `keptFit()` returns on performance-aimed devices.
|
|
17
|
+
* @param {{ get: (name: string) => string | null } | null} [options.query=null] Opening URL query parameters (`URLSearchParams`).
|
|
18
|
+
* @param {string} [options.queryParam='q'] Query parameter name checked for a one-visit preset override.
|
|
19
|
+
* @param {object} [options.storage=globalThis] Host exposing `localStorage` and `sessionStorage`.
|
|
20
|
+
* @returns {{ keepChoice: (name: string | null) => void, keepFit: (name: string | null) => void, keepOnce: (name: string) => void,
|
|
21
|
+
* keepScale: (name: string, scale: number) => void, keptChoice: () => string | null, keptFit: () => string | null,
|
|
22
|
+
* keptOnce: (taken?: boolean) => string | null, keptScale: (name: string) => number }}
|
|
23
|
+
*/
|
|
24
|
+
export function createQualityStore(
|
|
25
|
+
namespace,
|
|
26
|
+
{ device = null, performanceDefault = 'medium', query = null, queryParam = 'q', storage = globalThis } = {},
|
|
27
|
+
) {
|
|
4
28
|
const ONCE = `${namespace}:quality-once`, // in the tab's own storage: the preset its next page opens with, whatever is kept
|
|
5
29
|
CHOSEN = `${namespace}:quality`,
|
|
6
30
|
FITTED = `${namespace}:quality-fit`,
|
|
@@ -8,7 +32,7 @@ export function createQualityStore(namespace) {
|
|
|
8
32
|
|
|
9
33
|
function read(key) {
|
|
10
34
|
try {
|
|
11
|
-
const kept = localStorage.getItem(key);
|
|
35
|
+
const kept = storage.localStorage.getItem(key);
|
|
12
36
|
return LEVELS.includes(kept) ? kept : null;
|
|
13
37
|
} catch {
|
|
14
38
|
return null; // no storage (a private window)
|
|
@@ -16,8 +40,8 @@ export function createQualityStore(namespace) {
|
|
|
16
40
|
}
|
|
17
41
|
function write(key, value) {
|
|
18
42
|
try {
|
|
19
|
-
if (value) localStorage.setItem(key, value);
|
|
20
|
-
else localStorage.removeItem(key);
|
|
43
|
+
if (value) storage.localStorage.setItem(key, value);
|
|
44
|
+
else storage.localStorage.removeItem(key);
|
|
21
45
|
} catch {
|
|
22
46
|
// no storage: it holds for this page
|
|
23
47
|
}
|
|
@@ -25,7 +49,7 @@ export function createQualityStore(namespace) {
|
|
|
25
49
|
// The share of each side the preset `name` was last drawn at, if it was found for that preset.
|
|
26
50
|
function keptScale(name) {
|
|
27
51
|
try {
|
|
28
|
-
const kept = JSON.parse(localStorage.getItem(SCALE));
|
|
52
|
+
const kept = JSON.parse(storage.localStorage.getItem(SCALE));
|
|
29
53
|
return kept?.name === name && kept.scale > 0 && kept.scale <= 1 ? kept.scale : 1;
|
|
30
54
|
} catch {
|
|
31
55
|
return 1;
|
|
@@ -36,23 +60,27 @@ export function createQualityStore(namespace) {
|
|
|
36
60
|
// renderer for its canvas, then by the fit, which lets go of it with `taken`).
|
|
37
61
|
function keepOnce(name) {
|
|
38
62
|
try {
|
|
39
|
-
sessionStorage.setItem(ONCE, name);
|
|
63
|
+
storage.sessionStorage.setItem(ONCE, name);
|
|
40
64
|
} catch {
|
|
41
65
|
// no storage: the next page opens as kept
|
|
42
66
|
}
|
|
43
67
|
}
|
|
44
68
|
function keptOnce(taken = false) {
|
|
45
69
|
try {
|
|
46
|
-
const kept = sessionStorage.getItem(ONCE);
|
|
47
|
-
if (taken) sessionStorage.removeItem(ONCE);
|
|
70
|
+
const kept = storage.sessionStorage.getItem(ONCE);
|
|
71
|
+
if (taken) storage.sessionStorage.removeItem(ONCE);
|
|
48
72
|
return LEVELS.includes(kept) ? kept : null;
|
|
49
73
|
} catch {
|
|
50
74
|
return null;
|
|
51
75
|
}
|
|
52
76
|
}
|
|
53
77
|
const keptChoice = () => read(CHOSEN),
|
|
54
|
-
keptFit = () => read(FITTED),
|
|
78
|
+
keptFit = device?.aim === 'performance' ? () => performanceDefault : () => read(FITTED),
|
|
55
79
|
keepChoice = name => write(CHOSEN, name),
|
|
56
80
|
keepFit = name => write(FITTED, name);
|
|
81
|
+
|
|
82
|
+
const asked = query?.get?.(queryParam);
|
|
83
|
+
if (LEVELS.includes(asked)) keepOnce(asked);
|
|
84
|
+
|
|
57
85
|
return { keepChoice, keepFit, keepOnce, keepScale, keptChoice, keptFit, keptOnce, keptScale };
|
|
58
86
|
}
|