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

How a frame is decided

Why a still page draws no frames, who asks for one, and how frame policies, holds and decaying inputs keep frames coming only while needed.

View as Markdown
On this page

Diorama has no animation loop running in the background. The loop sleeps until something asks for a frame, draws it, and checks at the end whether anything still wants the next one. This page explains who asks, how effects decide, and why a page at rest draws nothing.

Paper ridges at dusk

Live preview needs WebGPU or WebGL 2. The built-in ripple on a photo with a tape of the last 120 display refreshes, each marked with the reason Diorama ran a frame or left empty; buttons switch the frame policy, and checkboxes emulate reduced motion and a hidden tab.

This example failed to draw.

Each effect file uses the setup of the built-in ripple with another animate option. The checkboxes act on this whole page.
animate

Frames: 0

no frame invalidate hold timed

<img
src="/media/ridges.jpg"
width="800"
height="450"
data-dio="ripple-hover"
/>
import { effect } from '@dioramajs/diorama'
import { params, setup } from './_ripple.ts'
export default effect(params, { animate: 'hover' }, setup)
import type { EffectContext } from '@dioramajs/diorama'
import { exp, sin, vec2 } from 'three/tsl'
export const params = { strength: 1, frequency: 40, speed: 6 }
// The setup of the built-in ripple, unchanged.
export function setup({
surface,
u,
}: EffectContext<typeof params>): void {
surface.uv((uv) => {
const toPointer = uv.sub(u.pointer)
const d = toPointer.length()
const phase = d.mul(u.frequency).sub(u.hoverTime.mul(u.speed))
const wave = sin(phase).mul(
exp(d.mul(-8)),
u.hover,
u.strength,
0.012,
)
return uv.add(toPointer.add(vec2(1e-5, 0)).normalize().mul(wave))
})
}
import { effect } from '@dioramajs/diorama'
import { params, setup } from './_ripple.ts'
export default effect(params, { animate: 'input' }, setup)
import { effect } from '@dioramajs/diorama'
import { params, setup } from './_ripple.ts'
export default effect(params, { animate: 'visible' }, setup)

A frame is wanted or it is not

Each app has one loop in demand mode. The loop wants a frame when one of these holds:

  • something called invalidate() since the last frame;
  • a hold is active;
  • a keepAwake(seconds) window has not run out;
  • the mode is always, which Diorama never sets itself.

When a frame is wanted and none is pending, the loop requests exactly one from its driver, by default requestAnimationFrame. When nothing is wanted, nothing is requested: no timer, no callback, no GPU work.

Inside a frame the systems run in five stages.

StageWhat happens for effects
inputScroll position and pointer are read.
layoutVisible elements are measured, inputs such as progress, pin and time are computed.
updateUpdate functions of visible instances run, then each instance’s frame policy is checked.
renderthree.js draws the scene.
afterRenderElements whose copy was drawn get data-dio-state="drawn", which hides their DOM.

After the last stage the loop asks again whether a frame is wanted. If it is, the next one is requested at once; if not, the loop goes back to sleep. An invalidate() during a frame gives exactly one more frame.

Who asks for a frame

Most frames come from events Diorama listens to.

  • A scroll event, a pointer move over an element with an effect, a resize.
  • A write to a param, from markup, handle.params or a GSAP tween.
  • A DOM change near an effect element: its box moved, it was added or removed.
  • The motion watcher: while a visible element has a CSS transform, a transition or an animation, it compares boxes once per display frame and invalidates only when something moved. After a second without change it stops.
  • A flight, which holds frames until it lands.

Off screen elements take no part: they are not updated, not drawn, and a param write to them requests nothing.

Frame policy

Events cover effects that change only when something happens. An effect that moves on its own asks for frames through its frame policy, the animate option.

animateAsks for frames while the element is visible
'input'never: it draws on events only
'hover'while the pointer is over it and while hover fades
'visible'every frame
{ fps: 30 }time frames at most 30 times a second
a functionwhile it returns true, checked after each update

Without the option the policy comes from what the effect reads: u.time means 'visible', u.hoverTime means 'hover', neither means 'input'.

The update function can answer for itself. Returning true asks for the next frame and false for none, so an effect draws until state kept in JavaScript settles, such as a damped position or a fade. Without animate the answer decides alone, whatever clocks the update reads; with animate, true adds frames to the policy and false takes none away. An update that returns nothing leaves the decision to the policy.

src/effects/shimmer.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 sin: UnaryFloatVecFunction
sin
} from 'three/tsl'
// Reads u.hoverTime: draws while hovered and while hover fades.
export default
effect<P>(
params: P & CheckSpec<P>,
setup: EffectSetup<ColorsIn<P>>
): Effect<WidenSpec<P>> (+2 overloads)
type P = {
readonly strength: 0.1;
}

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
({
strength: 0.1
strength
: 0.1 }, ({
surface: Surface

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

surface
,
u: Uniforms<ColorsIn<{
readonly strength: 0.1;
}>>

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

u
}) => {
const
const wave: Node<"float">
wave
=
function sin(x: FloatOrNumber): Node<"float"> (+3 overloads)
sin
(
u: Uniforms<ColorsIn<{
readonly strength: 0.1;
}>>

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

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

Seconds that run while hovered or while hover decays, frozen at rest and under reduced motion. Reading it implies animate: 'hover'.

hoverTime
.
mul: (
b: NumberParameterForNumType<"float">,
...params: NumberParameterForNumType<"float">[]
) => Node<"float"> (+7 overloads)
mul
(6)).
mul: (
b: NumberParameterForNumType<"float">,
...params: NumberParameterForNumType<"float">[]
) => Node<"float"> (+7 overloads)
mul
(
u: Uniforms<ColorsIn<{
readonly strength: 0.1;
}>>

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

u
.
strength: UniformNode<"float">
strength
)
surface: Surface

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

surface
.
Surface.color(
transform: (color: Node<"vec4">, input: SurfaceInput) => Node
): Off

Changes the colour. sample(uv) reads the element's media with crop and masks applied.

color
((
color: Node<"vec4">
color
) =>
color: Node<"vec4">
color
.
mul: (
b: Vec4OrLessOrNumberParameterForNumType<"float">,
...params: Vec4OrLessOrNumberParameterForNumType<"float">[]
) => Node<"vec4"> (+4 overloads)
mul
(
const wave: Node<"float">
wave
.
NumExtensions<"float">.add: AddSubMulDivNumberVecNumExtensions
(
b: NumberParameterForNumType<"float">,
...params: NumberParameterForNumType<"float">[]
) => Node<"float"> (+3 overloads)
add
(1)))
})

The decision is made at the end of the update stage of the same frame. An effect that asks for frames for the first time gets the next one, and an effect that stops asking gets one closing frame that shows its final state. All instances share one hold, taken while any of them asks and released when none does.

Inputs that fade

Some inputs keep changing after their cause has stopped. They hold frames themselves, so an effect with the 'input' policy never freezes halfway through a fade.

  • hover eases towards 1 or 0 and requests frames until it arrives, but only if some instance on the element reads it.
  • velocity decays after a scroll. Reading it requests the next frame while it is still above zero; nobody reading it means one frame per scroll event and no tail.
  • opacity requests frames while the CSS opacity of the element or its ancestors keeps changing.

Time

u.time counts seconds the element has been visible. It stands still while the element is off screen, while the tab is hidden and under reduced motion, so a loop picks up where it stopped instead of jumping.

Frame time is protected against long gaps. The first frame after the loop slept gets at most one display frame of time, and a slow frame in the middle of an animation gets at most 0.1 seconds. The loop measures the display rate as it runs, from 30 to 240 frames a second, so a phone in power saving mode at 30 Hz advances time correctly.

Why a still page draws nothing

Put together, the rules leave nothing running at rest.

ScenarioFrames
Page at rest, pointer not over effects0
Pointer over ripple, policy 'hover'every frame; after it leaves, until hover fades, then one more
A 'visible' effect on screenevery frame; once it scrolls away, 0
Scrollingone per scroll event, plus the fade of velocity if read
Tweening a param of a visible effectone per write
Tweening a param of an off screen effect0
Hidden tab0

With GSAP the frames come from gsap.ticker instead of requestAnimationFrame, after the tweens of the same tick, and the ticker subscription ends when no frame is wanted. With Lenis the frame runs right after Lenis moves the page. Both keep the same rule: no frame unless one is wanted.

Ask for frames yourself

Code outside effects uses the app’s loop controls.

// One frame after a change Diorama cannot see.
const app: App
app
.
AppCore<Services & Empty, string>.invalidate(): void

Requests one frame.

invalidate
()
// Frames for a fixed time.
const app: App
app
.
AppCore<
Services & Empty,
string
>.keepAwake(seconds: number): void

Keeps frames coming for seconds. Extends, never shortens.

keepAwake
(0.5)
// Frames until released, labelled for app.loop.stats.
const
const release: Off
release
=
const app: App
app
.
AppCore<
Services & Empty,
string
>.hold(reason?: string): Off

Keeps frames coming until released, e.g. while an animation runs. reason is a note for readers of the call and is not used.

hold
('intro')
await
function playIntro(): Promise<void>
playIntro
()
const release: () => void
release
()

Inside an effect prefer the frame policy or the update’s answer. A hold keeps frames coming even while the element is off screen, and both stop on their own. Both are checked only in frames: when something changes without one, such as an event that starts a motion, call ctx.invalidate() for the first frame and let the update or the function ask for the rest.

To see what the loop is doing, read app.loop.stats: frames counts frames so far and reason says why the last one ran, one of invalidate, hold, timed, always or step.