Diorama

Made for a big screen.

This site is one 3D scene, built for a computer: a wide window and a mouse. Open dioramajs.dev on a desktop or a laptop to see it.This site is one 3D scene, built for a wide window. Make this one wider, or open dioramajs.dev on a larger screen.

GitHub

DioramaDocs

Quality tiers

How the quality plugin picks a low, medium or high tier for each device and how effects follow it.

View as Markdown
On this page

The quality plugin picks a tier for each device from its GPU, lowers it when the browser misses frames while the page draws, and bounds the pixel ratio for each tier. Effects read the tier and cap their params by it. start() installs it for you: it loads with the engine, about 2 KB, and adds nothing to your main bundle.

What a tier changes

A tier changes two things: how many device pixels the canvas draws, and the most each effect asks of the GPU. Every ready-made effect runs on every tier, so a weak device gets the same page, drawn more cheaply.

TierPixel ratio, at mostParams
low1capped by each effect’s low caps
medium1.5capped by each effect’s medium caps
highthe screen’s own, up to 2as you set them

A cap lowers a value above it and never raises one. Some of the caps:

  • confetti: at most 80 pieces a burst on low, 140 on medium.
  • gradient: at most 15 frames a second and one layer of noise on low, 24 frames on medium.
  • visualizer: at most 20 frames a second and 24 bars on low, 30 frames on medium.
  • text-reveal: no blur on low, and the text rastered at 1 device pixel per CSS pixel instead of 2.

Each effect page lists its own under Cost and quality. Antialiasing does not follow the tier: antialias: 'auto' decides it once, when the renderer starts.

Pin a tier below and fire a burst at it. The effect and its markup stay the same; only the cap on count moves. Leaving the page hands the tier back to detection.

Live preview needs WebGPU or WebGL 2. A confetti cannon that fires 80, 140 or 200 pieces as the tier is pinned to low, medium or high.

This example failed to draw.

Tier

The tier shows once the engine runs.

<div class="q-stage">
<div
class="q-cannon"
data-dio="confetti"
data-dio-trigger="manual"
data-dio-count="200"
></div>
</div>

How the tier is picked

The tier is set once the engine starts, from the GPU name the browser reports and a few facts about the device. Nothing is measured yet, so the first frame already draws at the right cost.

GPUTier
Software renderer, such as SwiftShaderlow
Phone or tablet: Mali, Adreno, PowerVR, Apple GPUmedium, or low with 3 GB of memory or less, or 4 cores or less
Integrated: Intel HD, UHD, Iris, Radeon Graphicsmedium
Apple M serieshigh
Discrete: NVIDIA, Radeon RX, Archigh
Unknown or hiddenhigh with a mouse, medium on a touch device

A screen at pixel ratio 3 or more with over 1.5 million device pixels starts one step lower, at medium instead of high. The tier is kept in sessionStorage for the GPU, so the next page of the visit starts where the last one settled.

Adapting to slow frames

While the page draws, the plugin watches how often the browser paints, not how often Diorama draws: frames run on demand, so their own rate says nothing. When over a quarter of the browser’s frames take longer than one and a half screen refreshes across 2 seconds of drawing, the tier goes one step down.

  • It waits out the moments that are slow anyway: 0.5 s after a new effect compiles, a resize or a page change, and 1 s after the tier changes.
  • It steps down at most twice per page load and never goes back up during the visit, so the page does not flicker between tiers.
  • It stops watching at low, on a pinned tier, and with adapt: false.

Set the tier in start()

Pin a tier for every device, for example on a page whose scene is too heavy for the high tier anywhere.

src/diorama.ts
import {
function start(options?: StartOptions): App

Starts Diorama on the page and returns the app at once. It finishes starting in the background. A second call returns the same app, so a re-run module doesn't make another.

import { start } from '@dioramajs/diorama'
export const app = start()

start
} from '@dioramajs/diorama'
export const
const app: App
app
=
function start(options?: StartOptions): App

Starts Diorama on the page and returns the app at once. It finishes starting in the background. A second call returns the same app, so a re-run module doesn't make another.

import { start } from '@dioramajs/diorama'
export const app = start()

start
({
StartOptions.quality?:
| false
| "auto"
| QualityTier
| Partial<QualityOptions>
| undefined

Quality tiers for weaker GPUs: 'auto' (default) detects and adapts, a tier pins it, false leaves the plugin out. Loads with the engine, never in the main chunk.

quality
: 'medium' })

Keep detection and change how it behaves with an object. This one keeps the detected tier for the whole page and lets the medium tier draw at a pixel ratio of 1.25.

src/diorama.ts
import {
function start(options?: StartOptions): App

Starts Diorama on the page and returns the app at once. It finishes starting in the background. A second call returns the same app, so a re-run module doesn't make another.

import { start } from '@dioramajs/diorama'
export const app = start()

start
} from '@dioramajs/diorama'
export const
const app: App
app
=
function start(options?: StartOptions): App

Starts Diorama on the page and returns the app at once. It finishes starting in the background. A second call returns the same app, so a re-run module doesn't make another.

import { start } from '@dioramajs/diorama'
export const app = start()

start
({
StartOptions.quality?:
| false
| "auto"
| QualityTier
| Partial<QualityOptions>
| undefined

Quality tiers for weaker GPUs: 'auto' (default) detects and adapts, a tier pins it, false leaves the plugin out. Loads with the engine, never in the main chunk.

quality
: {
adapt?: boolean | undefined

Lower the tier when the browser misses frames while the site draws. Default true.

adapt
: false,
pixelRatio?:
| Readonly<Record<QualityTier, number>>
| undefined

Pixel ratio bound per tier. Default { low: 1, medium: 1.5, high: Infinity }.

pixelRatio
: {
low: number
low
: 1,
medium: number
medium
: 1.25,
high: number
high
: 2 },
},
})

quality: false leaves the plugin out: every effect draws as at the high tier, with no caps and no step down.

Change it while the page runs

app.quality exists once the engine runs, so wait for app.effects.load(), which resolves false when 3D is unavailable. This battery saver switch in a site’s settings pins the low tier and hands the choice back to detection when it is turned off.

const
const saver: HTMLInputElement | null
saver
=
var document: Document

window.document returns a reference to the document contained in the window.

MDN Reference

document
.
ParentNode.querySelector<HTMLInputElement>(selectors: string): HTMLInputElement
| null (+4 overloads)

Returns the first element that is a descendant of node that matches selectors.

MDN Reference

querySelector
<
interface HTMLInputElement

The HTMLInputElement interface provides special properties and methods for manipulating the options, layout, and presentation of elements.

MDN Reference

HTMLInputElement
>('#battery-saver')
if (
const saver: HTMLInputElement | null
saver
)
const saver: HTMLInputElement
saver
.
HTMLInputElement.addEventListener<"change">(
type: "change",
listener: (this: HTMLInputElement, ev: Event) => any,
options?: boolean | AddEventListenerOptions
): void (+1 overload)

The addEventListener() method of the EventTarget interface sets up a function that will be called whenever the specified event is delivered to the target.

MDN Reference

addEventListener
('change', async () => {
if (!(await
const app: App
app
.
Services.effects: EffectsApi
effects
.
EffectsApi.load(): Promise<boolean>

Boots the engine now. Resolves false when 3D is unavailable.

load
())) return
const app: App
app
.
Services.quality: QualityApi

The quality tier, see QualityApi.

quality
.
QualityApi.set(tier: QualityTier | "auto"): void

Pins a tier, or 'auto' to detect and adapt again.

set
(
const saver: HTMLInputElement
saver
.
HTMLInputElement.checked: boolean

The checked property of the HTMLInputElement interface specifies the current checkedness of the element; that is, whether the form control is checked or not.

MDN Reference

checked
? 'low' : 'auto')
})

app.quality.tier and app.quality.reason are signals: the tier now, and why it is what it is, 'detected', 'pinned', 'slow' or 'remembered'. The quality:tier event fires when the tier changes, which lets your CSS follow it too.

const app: App
app
.
AppCore<Services & Empty, string>.on<"quality:tier">(
event: "quality:tier",
listener: Listener<"quality:tier">
): Off

Listens to an event. Returns Off.

on
('quality:tier', ({
tier: QualityTier
tier
}) => {
var document: Document

window.document returns a reference to the document contained in the window.

MDN Reference

document
.
Document.documentElement: HTMLElement

The documentElement read-only property of the Document interface returns the Element that is the root element of the document (for example, the element for HTML documents).

MDN Reference

documentElement
.
HTMLOrSVGElement.dataset: DOMStringMap
dataset
.
DOMStringMap[string]: string | undefined
quality
=
tier: QualityTier
tier
})
/* Frosted panels cost as much as an effect: drop them on the low tier. */
html[data-quality='low'] .panel {
backdrop-filter: none;
background: rgb(18 18 28 / 0.92);
}

Caps in your own effects

Give your own effect a quality option with caps per tier, and min for the lowest tier it should run at. Below min the instance is off and the element stays plain HTML. A param that setup reads, such as a mesh’s detail, belongs in rebuild, so the effect is set up again when its cap changes.

src/effects/lift.ts
import {
function effect(
setup: EffectSetup<Empty>
): Effect<Empty> (+2 overloads)

Short form of defineEffect: defaults, optional options, setup. An unnamed effect takes its registry key (the file name when a build plugin finds it).

export default effect({ strength: 1 }, ({ surface, u }) => { ... })

effect
} from '@dioramajs/diorama'
import {
const vec3: Vec3Function
vec3
} from 'three/tsl'
export default
effect<P>(
params: P & CheckSpec<P>,
options: EffectOptions<ColorsIn<P>>,
setup: EffectSetup<ColorsIn<P>>
): Effect<WidenSpec<P>> (+2 overloads)
type P = {
readonly height: 40;
readonly detail: 64;
}

Short form of defineEffect: defaults, optional options, setup. An unnamed effect takes its registry key (the file name when a build plugin finds it).

export default effect({ strength: 1 }, ({ surface, u }) => { ... })

effect
(
{
height: 40
height
: 40,
detail: 64
detail
: 64 },
{
rebuild?:
| readonly ("height" | "detail")[]
| undefined

Params whose change re-runs setup. String and choice params always do.

rebuild
: ['detail'],
quality?:
| QualitySpec<
ColorsIn<{ readonly height: 40; readonly detail: 64; }>
>
| undefined

How the effect gets cheaper on weaker GPUs. Read by the runtime and by the docs.

quality
: {
QualitySpec<
ColorsIn<{ readonly height: 40; readonly detail: 64; }>
>.low?: QualityCaps<
ColorsIn<{ readonly height: 40; readonly detail: 64; }>
>
| undefined

Caps at the 'low' tier.

low
: {
detail?: number | undefined
detail
: 16 },
QualitySpec<
ColorsIn<{ readonly height: 40; readonly detail: 64; }>
>.medium?: QualityCaps<
ColorsIn<{ readonly height: 40; readonly detail: 64; }>
>
| undefined

Caps at the 'medium' tier.

medium
: {
detail?: number | undefined
detail
: 32 } },
},
({
surface: Surface

The shared GL copy of the element, created on first access.

surface
,
params: Readonly<
ParamsOf<
ColorsIn<{ readonly height: 40; readonly detail: 64; }>
>
>

Live resolved values. Read them in update, a read in setup is a snapshot.

params
,
u: Uniforms<
ColorsIn<{ readonly height: 40; readonly detail: 64; }>
>

Input uniforms and one uniform per live param, for TSL graphs.

u
}) => {
surface: Surface

The shared GL copy of the element, created on first access.

surface
.
Surface.segments(count: number): void

Requests plane subdivisions. The largest request wins, default 1.

segments
(
params: Readonly<
ParamsOf<
ColorsIn<{ readonly height: 40; readonly detail: 64; }>
>
>

Live resolved values. Read them in update, a read in setup is a snapshot.

params
.
detail: number
detail
)
surface: Surface

The shared GL copy of the element, created on first access.

surface
.
Surface.position(
transform: (position: Node<"vec3">, uv: Node<"vec2">) => Node
): Off

Moves vertices in the plane's local 1x1 space.

position
((
position: Node<"vec3">
position
,
uv: Node<"vec2">
uv
) => {
const
const near: Node<"float">
near
=
uv: Node<"vec2">
uv
.
NumVec2Extensions<"float">.sub: AddSubMulDivNumberVecVec2Extensions
(
b: Vec2OrLessOrNumberParameterForNumType<"float">,
...params: Vec2OrLessOrNumberParameterForNumType<"float">[]
) => Node<"vec2"> (+2 overloads)
sub
(
u: Uniforms<
ColorsIn<{ readonly height: 40; readonly detail: 64; }>
>

Input uniforms and one uniform per live param, for TSL graphs.

u
.
InputUniforms.pointer: UniformNode<"vec2">

Pointer in element UV, y up like uv(). 0..1 inside the box, not clamped outside.

pointer
).
FloatOrVecExtensions<"vec2">.length: () => Node<"float">
length
().
FloatOrVecExtensions<"float">.oneMinus: () => Node<"float">
oneMinus
().
FloatExtensions.max: MinMaxFloatExtension
(
y: FloatOrNumber,
...params: FloatOrNumber[]
) => Node<"float"> (+3 overloads)
max
(0)
return
position: Node<"vec3">
position
.
add: (
b: Vec3OrLessOrNumberParameterForNumType<"float">,
...params: Vec3OrLessOrNumberParameterForNumType<"float">[]
) => Node<"vec3"> (+2 overloads)
add
(
function vec3(
x: Scalar,
y: Scalar,
z: Scalar
): JoinNode<"vec3"> (+6 overloads)
vec3
(0, 0,
const near: Node<"float">
near
.
mul: (
b: NumberParameterForNumType<"float">,
...params: NumberParameterForNumType<"float">[]
) => Node<"float"> (+7 overloads)
mul
(
u: Uniforms<
ColorsIn<{ readonly height: 40; readonly detail: 64; }>
>

Input uniforms and one uniform per live param, for TSL graphs.

u
.
InputUniforms.hover: UniformNode<"float">

Damped 0..1 while the pointer is over the box. 0 under reduced motion.

hover
,
u: Uniforms<
ColorsIn<{ readonly height: 40; readonly detail: 64; }>
>

Input uniforms and one uniform per live param, for TSL graphs.

u
.
height: UniformNode<"float">
height
)))
})
},
)

Inside setup, quality holds the tier for a cost that is not a param, such as the size of an offscreen buffer. Reading it there sets the effect up again when the tier changes.