Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 68 additions & 0 deletions apps/viewer/web/auto-quality.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
// The page's automatic quality: it starts high and steps down while the frame rate stays below
// target. It never steps back up: oscillating between presets is worse than either one.
//
// Its last step, on a high-density display, is fewer pixels: Low drawn at one canvas pixel per
// CSS pixel. A Retina screen at a device pixel ratio of 2 has four times the pixels, and Low
// there still costs more than High at a ratio of 1 (an integrated GPU: 175 ms against 111).

/// The frame rate below which the page steps down.
export const TARGET_FPS = 28;
/// Below this, a frame rate is far too slow to need three reports in a row to be sure of it.
const VERY_SLOW_FPS = TARGET_FPS / 2;

/// Each step: a quality preset, and the most canvas pixels per CSS pixel it draws.
export function autoSteps(devicePixelRatio) {
const steps = [
{ quality: "high", pixelRatio: 2 },
{ quality: "medium", pixelRatio: 2 },
{ quality: "low", pixelRatio: 2 },
];
if (devicePixelRatio > 1) steps.push({ quality: "low", pixelRatio: 1 });
return steps;
}

export class AutoQuality {
constructor(devicePixelRatio) {
this.steps = autoSteps(devicePixelRatio);
this.level = 0;
this.slowReports = 0;
// The first reports, taken while shaders compile, say nothing about the scene.
this.ignoreReports = 4;
}

get step() {
return this.steps[this.level];
}

/// Takes the frame rate over the last report, and whether the scene was loading through it.
/// Returns the step to take now, or null to stay.
report(fps, loading) {
if (this.level === this.steps.length - 1) return null;
// While geometry pours in, the frame rate says how fast the scene loads, not how fast it
// draws: a lower quality would outlast the loading it was chosen for.
if (loading) {
this.slowReports = 0;
return null;
}
if (this.ignoreReports > 0) {
this.ignoreReports -= 1;
return null;
}
this.slowReports = fps < TARGET_FPS ? this.slowReports + 1 : 0;
// Half the target or less is no passing hitch: two reports in a row settle it.
const needed = fps < VERY_SLOW_FPS ? 2 : 3;
if (this.slowReports < needed) return null;
this.level += 1;
this.slowReports = 0;
// A report for the frames that made the new targets.
this.ignoreReports = 1;
return this.step;
}

/// A name for the step, beside "Automatic" in the quality list.
get label() {
const { quality, pixelRatio } = this.step;
// Only a high-density display has a step at a ratio of 1.
return pixelRatio === 1 ? `${quality}, fewer pixels` : quality;
}
}
31 changes: 29 additions & 2 deletions apps/viewer/web/editor/test.mjs
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
// Tests of the editor's own code that need no browser: the project file writer, the rotation
// maths and the gizmo's drags. Run with `node apps/viewer/web/editor/test.mjs`; CI runs it.
// Tests of the web pages' own code that need no browser: the editor's project file writer,
// rotation maths and gizmo drags, and the viewer's automatic quality. Run with `node apps/viewer/web/editor/test.mjs`; CI runs it.

import { readFileSync } from "node:fs";
import { Commands } from "./commands.js";
import { Gizmo } from "./gizmo.js";
import * as m from "./math.js";
import { writeScene } from "./project.js";
import { AutoQuality } from "../auto-quality.js";

let failures = 0;
function check(what, ok, detail) {
Expand Down Expand Up @@ -128,5 +129,31 @@ function check(what, ok, detail) {
check("help gives JSON Schema", help.arguments.required[0] === "to" && help.arguments.properties.to.type === "number");
}

// ---- Automatic quality steps down while slow, faster when far too slow, never while loading.
{
// Reports until the next step, at a steady frame rate.
const reportsToStep = (auto, fps) => {
for (let n = 1; n <= 100; n++) if (auto.report(fps, false)) return n;
return Infinity;
};
const retina = new AutoQuality(2);
check("a high-density display ends on Low at one pixel per CSS pixel",
JSON.stringify(retina.steps.at(-1)) === '{"quality":"low","pixelRatio":1}', retina.steps);
check("a display of ratio 1 has no step for fewer pixels", new AutoQuality(1).steps.length === 3);
check("a fast frame rate never steps", reportsToStep(new AutoQuality(2), 60) === Infinity);
check("a little slow: three reports after the four at start", reportsToStep(new AutoQuality(2), 25) === 7);
check("far too slow: two after the four at start", reportsToStep(retina, 10) === 6);
check("and then two after the one for new targets", reportsToStep(retina, 10) === 3);
reportsToStep(retina, 10);
check("the last step is fewer pixels", retina.step.pixelRatio === 1 && retina.label === "low, fewer pixels");
check("nothing after the last step", reportsToStep(retina, 1) === Infinity);
const loading = new AutoQuality(2);
for (let n = 0; n < 20; n++) loading.report(5, true);
check("loading never steps down", loading.level === 0);
const hitch = new AutoQuality(1);
for (const fps of [60, 60, 60, 60, 10, 60, 10, 60, 25, 25, 60]) hitch.report(fps, false);
check("a slow report between fast ones is a hitch", hitch.level === 0);
}

console.log(failures ? `${failures} failed` : "all passed");
process.exit(failures ? 1 : 0);
66 changes: 31 additions & 35 deletions apps/viewer/web/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,7 @@ <h2 id="laps-track"></h2>
const { default: init } = wasm;
const { adapterReport, readWithRetries, inflateAtMost, requestAdapter, openScene } =
await import("./loader.js");
const { AutoQuality } = await import("./auto-quality.js");

const sceneName = params.get("scene") ?? "cove";
if (!/^[\w-]+$/.test(sceneName)) throw new Error("invalid scene name");
Expand Down Expand Up @@ -308,8 +309,10 @@ <h2 id="laps-track"></h2>
}


// Canvas pixels per CSS pixel are capped at 2, and at 1 once automatic quality's last step asks.
let pixelRatioCap = 2;
const canvasSize = () => {
const ratio = Math.min(window.devicePixelRatio || 1, 2);
const ratio = Math.min(window.devicePixelRatio || 1, pixelRatioCap);
return [
Math.max(1, Math.round(canvas.clientWidth * ratio)),
Math.max(1, Math.round(canvas.clientHeight * ratio)),
Expand Down Expand Up @@ -505,42 +508,42 @@ <h2 id="laps-track"></h2>
viewer.set_debug_view(params.get("debug"));
}

// Automatic quality starts high and steps down while the frame rate stays below target.
// It never steps back up: oscillating between presets is worse than either one.
// Automatic quality starts high and steps down while the frame rate stays below target:
// see auto-quality.js. Its last step, on a high-density display, draws fewer pixels.
const LEVELS = ["high", "medium", "low"];
const TARGET_FPS = 28;
const LOADING_PAGES_PER_REPORT = 200;
let autoLevel = 0;
let slowReports = 0;
let ignoreReports = 4;
const auto = new AutoQuality(window.devicePixelRatio || 1);
const autoOption = el("quality").querySelector('[value="auto"]');
let pagesAtReport = 0;
const resizeCanvas = () => {
const [width, height] = canvasSize();
if (width !== canvas.width || height !== canvas.height) {
canvas.width = width;
canvas.height = height;
viewer.resize(width, height);
}
};
const usePixelRatio = (cap) => {
if (cap === pixelRatioCap) return;
pixelRatioCap = cap;
resizeCanvas();
};
const adaptQuality = (fps) => {
if (el("quality").value !== "auto" || autoLevel === LEVELS.length - 1) return;
// While geometry pours in, the frame rate says how fast the scene loads, not how fast it
// draws: a lower quality would outlast the loading it was chosen for.
const pages = viewer.pages_installed() + viewer.pages_evicted();
const loading = pages - pagesAtReport > LOADING_PAGES_PER_REPORT;
pagesAtReport = pages;
if (loading) {
slowReports = 0;
return;
}
if (ignoreReports > 0) {
ignoreReports -= 1;
return;
}
slowReports = fps < TARGET_FPS ? slowReports + 1 : 0;
if (slowReports >= 3) {
autoLevel += 1;
slowReports = 0;
ignoreReports = 4;
viewer.set_quality(LEVELS[autoLevel]);
autoOption.textContent = `Automatic (${LEVELS[autoLevel]})`;
}
if (el("quality").value !== "auto") return;
const step = auto.report(fps, loading);
if (!step) return;
viewer.set_quality(step.quality);
usePixelRatio(step.pixelRatio);
autoOption.textContent = `Automatic (${auto.label})`;
};
// A preset chosen by hand is drawn at the display's full density.
el("quality").addEventListener("change", (e) => {
viewer.set_quality(e.target.value === "auto" ? LEVELS[autoLevel] : e.target.value);
const automatic = e.target.value === "auto";
viewer.set_quality(automatic ? auto.step.quality : e.target.value);
usePixelRatio(automatic ? auto.step.pixelRatio : 2);
});
const requestedQuality = params.get("quality");
if (LEVELS.includes(requestedQuality)) {
Expand Down Expand Up @@ -680,14 +683,7 @@ <h2 id="laps-track"></h2>
canvas.addEventListener("touchcancel", endTouch);
}

new ResizeObserver(() => {
const [width, height] = canvasSize();
if (width !== canvas.width || height !== canvas.height) {
canvas.width = width;
canvas.height = height;
viewer.resize(width, height);
}
}).observe(canvas);
new ResizeObserver(resizeCanvas).observe(canvas);

el("overlay").hidden = true;
for (const id of ["hud", "controls", "help", "more"]) el(id).hidden = false;
Expand Down
2 changes: 1 addition & 1 deletion scripts/build-web.sh
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ if [ ! -e assets/content/surface-grass-0-1024.solstice ]; then
fi
mkdir -p dist/content
cp assets/content/*.solstice dist/content/
cp apps/viewer/web/index.html apps/viewer/web/editor.html apps/viewer/web/loader.js dist/
cp apps/viewer/web/index.html apps/viewer/web/editor.html apps/viewer/web/loader.js apps/viewer/web/auto-quality.js dist/
cp -r apps/viewer/web/editor dist/
# Scene files are already compressed where it helps, part by part, so that the page can fetch
# any part alone. Hard links keep big scenes from taking disk space twice.
Expand Down
Loading