# benchKit: repeatable performance benchmarks for any Zero world
benchKit measures how fast a world really runs, the same way every time, on a desktop, in a
browser and on phones and tablets (the app and the browser), and keeps the results so any
device can list and compare them later. A benchmark is data: the scene, a seed, the world's
knob values, the graphics settings, the budget it is judged against, and segments (camera
paths or still views). One call applies the settings, builds the seeded content, waits until
the world has truly settled, measures each segment in a quiet window with repeats, and reads
the engine's own measurements of that window. Results come as a readable card and a
versioned machine-readable report, saved for the player who ran them.
You choose how much a run keeps, from the summary numbers alone (`light`) up to every single
frame (`comprehensive`): each frame's time, CPU and GPU time, the time of each GPU pass, CPU by
engine system and by script, hitches with what ran inside them, the loading and shader-compile
timeline with the camera path's segments marked on it, memory over the run (the app, each script
VM, GPU memory by kind, caches, garbage collection, allocation rate), peaks, growth and a leak
check. A viewer opens any saved run on any device with graphs of all of it and a compare view;
every series exports as JSON, CSV, a trace for Perfetto / chrome://tracing and flame graphs. The
charts are **chartKit**, a separate package any game can use.
Plain frames per second and milliseconds; no invented score.
## Quick start (an empty world, about 3 minutes)
1. Install **benchKit** from ZeroMind (search "benchmark my world"). It brings Graphics Presets
(`graphicsPresets`, formerly graphicsSettingsKit: quality ladders and card palettes) and filmRig
(camera moves) along. The install may list a "problem" or two about a Graphics Presets test
suite or guide "not placed": those files are left out of that kit's install and nothing
benchKit uses is missing.
2. In the engine's shell (the editor's terminal, or an agent's `bash`), run the sample benchmark
that ships with the kit: a seeded field of 1,500 props, an orbit and three still views,
3 repeats each. Keep hands off for about 1 to 2 minutes while it settles and measures:
```
zero benchKit run benchKit.sample
```
It prints the report: fps, median / 95th / 99th percentile / worst frame, 1% and 0.1% lows,
hitches, engine CPU and GPU time, the three biggest costs, budget pass or fail, and
benchKit's own cost. **UNSETTLED** on the first line means the machine never held steady for
2 seconds before measuring (other programs busy, for instance); the numbers are measured
anyway, but treat them with care.
3. See the results card over the editor: `zero benchKit card` (`zero benchKit card hide` to
close it; `zero benchKit card last phone pixel` for another layout and look). In the editor
the memory budgets read "not judged": the process holds the whole editor, so memory is
judged only in player mode (the play page or the app).
4. Run it a second time, then `zero benchKit compare`: with no ids it compares your previous
run with your last one (`zero benchKit list` shows every report, newest first, and
`compare <baseline id> <new id>` takes any two). Two settled runs of the same thing read
"no change". When either run is UNSETTLED the compare says so first, and any "worse" it
reports may be the machine rather than the world: run again to confirm.
The same from Luau: `local Bench = require("benchKit.bench")`,
`local r = Bench.run(require("benchKit.sample"))` inside a task, `print(Bench.show(r))`.
## Your own benchmark
Copy `benchKit.sample` (`sample.module` in the package) into your world and change `build`,
`knobs` and `segments`, or write the definition from scratch:
```lua
local Bench = require("benchKit.bench")
Bench.define {
name = "harbour",
seed = 42,
knobs = { boats = 400 },
graphics = { quality = "high", renderScale = 1.0 },
budget = "desktop60",
build = function(ctx) Harbour.build(ctx.rng("boats"), ctx.knobs.boats) end,
toggles = { boats = function(on) Harbour.setVisible(on) end },
segments = {
{ name = "flyover", duration = 12, path = { kind = "flythrough", points = { {0,30,-80}, {40,12,0}, {0,20,80} } } },
{ name = "docks", duration = 8, views = { { pos = {5,2,5}, look = {0,1,0} }, { pos = {30,8,-10}, look = {0,0,0} } } },
{ name = "no boats", duration = 12, control = true, set = { boats = false },
path = { kind = "flythrough", points = { {0,30,-80}, {40,12,0}, {0,20,80} } } },
},
}
task.spawn(function()
local report = Bench.run("harbour") -- blocks this task for the run
print(Bench.show(report))
require("benchKit.cards").show("full", report, { look = "scifi" })
end)
```
From the engine's command line (or any agent, through the `benchKit` toolbox):
```
zero benchKit run harbour zero benchKit list
zero benchKit sweep harbour zero benchKit show <id>
zero benchKit sustain harbour --minutes 10
zero benchKit compare <baseline id> <new id>
```
`run`, `sweep` and `sustain` all take how much to keep as their last argument, the same choice the
Frame Lab showcase's **Keep** button makes: `zero benchKit run harbour 3 "label" comprehensive`,
`zero benchKit sweep harbour 2 "0.5,1" frames` (every step keeps every frame),
`zero benchKit sustain harbour 10 memory` (memory over the whole sustained run, with each kind's
growth per minute).
A module that returns a definition can be named directly (`zero benchKit run frameLab.frameLabShowcase`).
## Variants
**Camera path kinds** (every kind is a pure function of benchmark time, swapped by changing `kind`):
`orbit`, `dolly`, `walk` (eye height, 1.4 m/s), `drive` (car height, 13.9 m/s), `flythrough`
(smooth curve at even speed), `views` (still views with cuts), `crane`, `spiral`, `pan`,
`keys` (poses recorded by flying the camera), `film` (any filmRig move: craneRise, pushIn,
reveal, topDown, spiralClimb, arc, whipPan, ...).
**Card looks** (one setting, `Looks.setDefault`): minimal, scifi, fantasy, cartoon, pixel, cozy,
realistic, horror, military.
**Card layouts**: `full` (the results card), `badge` (small corner badge), `phone` (portrait
card for 390x844), `sweep` (the sweep table), `minutes` (per-minute chart of a sustained run).
**Budgets**: `desktop60`, `desktop144`, `web60` (30 fps floor), `laptopWeb` (integrated GPU),
`tablet60` (0.75 render scale, 30 fps sustained floor), `phone30`, `batterySaver`; each with
memory and GPU memory ceilings. `Budgets.define` adds your own.
**Modes**: `Bench.run` (one run), `Bench.sweep` (every quality level x render scale 0.5 / 0.75 /
1.0, plus each step of the world's own Graphics Presets ladder when it has one; content built
once, each segment cut to `segmentSeconds` (6 by default), 2 repeats; nine steps took 423 to
436 s on a busy desktop, so about 7 minutes; one table), `Bench.sustain` (loop the first
segment for N minutes, 10 by default; per-minute median and 95th percentile, and the last
minute against the first).
**Workflow**: `benchKit.benchmark-a-change`, a runnable workflow that compares performance
between two builds or before and after a change, stage by stage: conditions, a baseline run
twice (must read "no change"), the change, the run after, the compare, the verdict.
`zero workflow start --name benchKit.benchmark-a-change --args '{"benchmark":"benchKit.sample"}'`.
## Reference
### A benchmark definition
| Field | Meaning |
|---|---|
| `name` | Required. Names the benchmark in reports and the shell. |
| `version` | Your own version of the definition (default 1); part of the fingerprint. |
| `scene` | The scene it is meant for (a warning names a mismatch). |
| `seed` | Seed for `ctx.rng(stream)`, the engine's `Random` (same numbers native and web). |
| `knobs` | The world's knob values; `ctx.knobs` in `build`; a segment's `set` may change one. |
| `build(ctx)` | Builds the content. `ctx.spawn(opts)` spawns local, temporary entities removed after the run. A table with a `build` field works too. |
| `ready(ctx)` | Optional: polled until true (content streamed in, say). |
| `toggles` | `{ name = function(on, ctx) }` switches a segment can flip (`set = { name = false }`); put back to `defaults[name]` or true after the segment. |
| `graphics` | `{ quality, renderScale, frameCap, presentMode, anisotropy, shadows, overrides }`. `quality` is a step of the world's Graphics Presets (`graphicsPresets`) ladder when it has one, else an engine tier (low, medium, high). |
| `budget` | The budget the card's headline is judged against (default `desktop60`); every budget is judged too. |
| `settle` | `{ spread = 0.15, holdSeconds = 2, timeout = 60, minSeconds = 1 }`: frame times must hold (p90 - p10) / p50 under `spread` for `holdSeconds`. |
| `warmupSeconds` | Before each segment's repeats, play its whole path once, unmeasured, compressed into this many seconds (default 4; 0 turns it off), so every view the repeats see is already loaded. |
| `repeats` | Repeats per segment (default 3). |
| `segments` | `{ name, path or views, duration, set?, control? }`. A `control` segment is reported but left out of the totals. A `views` path takes `settleEach` (default 0.5 s): frames right after each cut are counted apart. |
### What a run does
1. Applies the graphics settings and builds the content from the seed (all local to the
player who started the run; nothing replicates).
2. Takes this player's camera with a local, temporary camera, and tells the renderer to draw
every frame for the run.
3. Settles: the renderer owes nothing (`renderer.pendingWork`: no shader compiles, pipeline
builds, uploads or streaming, and no new work arrived) and frame times stay inside
`spread` for `holdSeconds`. After `timeout` the report says **unsettled** with the reason.
Each section waits again, up to the same `timeout`, before it is measured; work still
outstanding then, or arriving during a measured repeat, marks that section **unsettled**
(`segments[].unsettled` names what was outstanding) and the whole report with it. A section
is never handed back as a normal row while the renderer was still working.
4. Calls every `onQuiet(true)` hook: benchKit's cards and the showcase panel hide.
5. Plays each segment `repeats` times while `profiler.frameCost` measures the same seconds;
samples the sun shadow page counters 8 times per window; after the repeats, stands the camera at 16
exact path times (outside every window) to read draw, cull and triangle counts, so they are the
same every run; reads GPU passes, CPU by
system and memory after each window closes.
6. Puts the camera, graphics, draw policy and switches back, removes built content, saves.
### Measured per segment and in total
Frame time median, p95, p99 and worst; 1% and 0.1% low fps; hitches over 33 / 50 / 100 ms;
engine CPU per frame and time waiting for a core; the engine's own GPU time and the biggest
GPU passes; the frame rate with the machine to itself; CPU time by engine system; draws,
instances, cluster triangles, clusters, pixels shaded, culled and visible counts; sun shadow
pages redrawn per frame; process memory and peak, GPU memory by kind and the driver's figure;
load times (build, first frame, settled). Each number is folded across repeats as the median,
with its relative spread.
### The report (`format = "benchKit.report"`, `formatVersion = 2`)
`id, kind ("run" | "sustained"), createdAt, owner, label, sweepStep, benchmark { name, version,
fingerprint, seed, knobs, graphics, budget, repeats, segments }, conditions, settled, settle,
load, segments[] { name, control, kind, duration, pathFingerprint, settled, unsettled,
framesLeftOut, result, spread, repeats, gpuPasses, systems }, totals, totalsSpread, topCosts,
budgets, budget, kitCost, sustained, sinceLast, references, unavailable, warnings, notes, saved,
capture, data`. Version 2 adds `capture` (level, frames recorded, recording cost against its
limit, memory peaks and growth, GC, allocation rate, the leak check, a small preview the card
draws, figures unavailable with reasons) and `data` (whether every frame was kept, where, and
how big). `settle.by` says whether the world settled on its frame times or on the engine's own
cost while the machine was busy (`machineBusy`, with the share of each frame spent waiting for a
core). Reports of version 1 still open, list and compare.
`segments[].framesLeftOut` counts, per section, the frames measured but left out of its
numbers and why: `capture` (a screenshot was being taken), `outsideWork` (work from outside the
benchmark ran in the frame), `afterViewCut` (the brief settle after each still-view cut), with
`total` and `perRepeat`. Zero is written as zero, so a clean section shows it was clean.
`conditions` records the engine build type, Luau codegen, platform, editor or player, GPU, its
family and kind, handheld, GPU memory, device kind, display, quality level, render scale and
the size actually drawn, present mode, frame rate mode and cap, how busy the machine was
(share of each frame spent waiting for a core), temperature and battery, world and kit
versions and the benchmark fingerprint. Anything a platform does not state is
`{ available = false, reason }`; never a guess, never a silent zero. Today no platform gives
scripts the device temperature or battery level (native, browser or Android), so those two
always read unavailable with that reason; a browser that withholds its GPU adapter's name
gives "GPU name unavailable" with the reason.
### Saved reports
Every run is saved for the player who ran it, on their account (`runtime_data` player store),
so the same person's runs on desktop, browser and tablet list together anywhere. Any signed-in
player saves, visitors of a public world included (the platform lets every signed-in player
write their own store). Every player in the world can read every other player's saved runs:
a world roster (`benchKit/players/<id>`) lists who has runs, and the viewer's run picker shows
yours, other players' and the reference runs. Signed-out sessions keep runs on the machine
(`/source/local/benchKit/reports`). The world's author promotes runs into **reference results**
(`zero benchKit promote <id> "<device>"`, edit mode; files under `/source/benchReports/reference`,
published with the world). Visitors read them and can never overwrite them. `Bench.list`,
`Bench.open`, `Bench.show`.
A run's per-frame data (capture level `frames` and up) is packed (about 2.4 bytes per value),
cut into pieces under 180 KB and saved beside its report on the same shelf; a two-minute
comprehensive run of the sample keeps about 0.8 to 1 MB. Each player keeps the data of their
newest 8 runs (`Dataset.KEEP`); older runs keep their report and summary and say their frames
were let go.
### Comparing
`Bench.compare(a, b)` refuses, naming each difference, unless both reports share the benchmark
fingerprint, drawn size, quality level, render scale and build type (`{ force = true }`
compares anyway). Each number gets a noise threshold from both reports' repeat spread (with a
floor per number), so a rerun of the same thing reads "no change" and a real change is
"better" or "worse". Draw calls, triangles and pixels shaded are read at 16 fixed camera poses
outside the measured windows, from a frame the GPU rendered after each pose (its counts arrive
a few frames late); that count pass is walked twice and the difference between the walks is
those rows' noise. Memory rows have a 5% floor, since GPU pools and caches keep their high-water
mark from one run to the next.
### Its own cost
The runner's per-frame work (pose evaluation, bookkeeping, samplers) is timed and reported as
`kitCost.msPerFrame` (typically 0.01 to 0.03 ms). Moving the camera entity costs the engine
about 0.02 to 0.1 ms per frame and is reported apart as `kitCost.cameraMsPerFrame`; any moving
game camera pays it too. Reading CPU by system costs ~2 ms and is done outside windows.
### Recording every frame
`Bench.run(def, { capture = level })`, `capture = level` in the definition, or
`zero benchKit run <name> <repeats> <label> <level>`. Each level keeps everything the one before
does:
| Level | Keeps |
|---|---|
| `light` (default) | The summary numbers above. No engine recording. |
| `frames` | Every frame: wall time, engine CPU (the thread's own clock), wait for a core, GPU time, CPU by engine schedule and by its 16 heaviest systems (the rest summed), script time per frame (component updates, tasks and coroutines, the Luau GC step, fixed updates, UI callbacks, every named `profiler.begin` block), entity / draw / instance counts, and every hitch (twice the median and 8 ms above it) with the four systems that took the most of it. |
| `memory` | + a sample every 100 ms: process private and resident memory, the allocator's live heap, every engine memory source (GPU textures, meshes, geometry, instances, shadow pool, culling, compute, the driver's figure; the file store, images, fonts), each Luau VM's live and allocated bytes; peaks, growth over the run, **growth per minute** of each kind of memory, GC pauses, the game VM's allocation rate, and the **leak check**. |
| `comprehensive` | + every GPU frame with the time of its 16 heaviest passes, every worker job (asset decodes and imports, shader compiles, module loads: start, length, worker), and the game VM's sampled call stacks plus the engine's timed scopes for flame graphs. |
The recording is the engine's own (`profiler.startCapture`), taken in native code as each frame
closes; benchKit adds only the marks of its phases (build, settle, warm-up, count pass,
teardown), each measured repeat as a camera-path segment, and each cut between still views. One
recording spans the whole run, so the loading and shader-compile timeline, the measured
segments and the teardown share one time axis.
**Growth per minute** is each kind of memory's trend (a straight line fitted to its samples) over
the measured part of the run: the measured segments, or the whole loop of a sustained run, so the
memory that building and settling took is not counted. The report prints it on every memory line
("grows +0.40 MB per minute") with the stretch it was read over, and the viewer's Memory tab shows
it beside peak and growth. It means most on long sustained runs; over a minute or two on a busy
machine, other programs freeing or taking memory move the process figures.
**Stopping a run halfway** lets its recording go. Leaving play, the world unloading, or the run
being stopped or dying any other way releases the engine's recording slot within about two
seconds (a watchdog checks the run every 2 s; leaving play releases it at once). A recording a
stopped run left behind is reclaimed by the next run you start, so the detailed levels never
quietly fall back to `light` because of it. And every benchKit recording is bounded: it is started
with a time limit of twice the run's longest plausible length plus five minutes, past which the
engine stops it on its own whatever happened, so a recording can never stay held forever. A
recording that someone else's session is making is never stopped; a run that finds the slot held
by one still falls back to `light` and says who holds it.
**The leak check** reads memory before anything is built and again after the content is torn
down and the renderer has settled, and fails when the game's script VM (4 MB; 16 MB in the
editor, where tools share that VM), GPU memory held by content (textures, meshes, geometry,
instances: 8 MB) or the entity count grew past its limit. GPU pools (shadow pages, culling,
compute), render targets and process memory are shown but never fail it: pools keep their
high-water mark on purpose (a first run grows the shadow pool by tens of MB and keeps it).
**The viewer** (`zero benchKit view`, `Bench.view()`, or `require("benchKit.viewer").open()`
from a button) opens any saved run on any device: Overview (headline numbers, frame-time graph
over the whole run with the segments, budget line and hitches, histogram, recording cost, leak
verdict), Frames, GPU, CPU, Flame graphs (upright or icicle), Memory, Loading, Export (each file
with a Save button: a download in a browser, a save dialog on desktop, the picker on Android)
and Compare (two runs side by side: what got slower or bigger). Below 760 points wide it lays out
in one column for a phone or a tablet held upright. Every player's viewer is their own screen.
The results cards draw a frame-time graph, a histogram and memory from the report alone.
**Exports** (`zero benchKit export <id>`, the viewer's Export tab, `Export.files(report, data)`):
`report.json`, `data.json`, `frames.csv`, `cpu_by_system.csv`, `cpu_by_schedule.csv`,
`cpu_by_script.csv`, `memory.csv`, `gpu_passes.csv`, `jobs.csv`, `hitches.csv`, `marks.csv`,
`trace.json` (Perfetto and chrome://tracing: segments, phases, frames, hitches, CPU by system,
GPU passes, memory and each worker's jobs on one timeline), `scripts.folded` / `engine.folded`
(speedscope, inferno, flamegraph.pl) and `scripts_flame.svg` / `engine_flame.svg`, plus the
engine's own export files while the machine still holds the recording.
### What measuring costs, and the limit it is held to
Recording must not change what it measures. Every run states the engine's own measure of what
the recording took on the engine thread inside each frame (`capture.cost.engineMsPerFrame`)
against benchKit's limit: **1.5% of the budget's frame: 0.25 ms at 60 fps, 0.5 ms at 30 fps**.
A run over the limit says so on its card and report. `zero benchKit overhead <name>` measures it
directly on a device: alternating rounds of the same camera path with and without the recording.
| Device | Comprehensive recording cost per frame | Limit | Measured |
|---|---|---|---|
| Desktop app, Linux, Intel Arc (BMG G31), dev build, shared machine | 0.109 ms median of 4 rounds (0.098 to 0.163 ms; the costliest single frame 3.3 ms); full runs 0.096 and 0.141 ms | 0.25 ms | 2026-11-21, `benchKit.overhead` and two runs |
| Android tablet, Chrome (1506x2060, held upright) | **0.268 ms** over a settled comprehensive run of the sample (2,891 frames, median frame 31.8 ms, 95th percentile 37.5 ms): **over** the sample's 0.25 ms limit, 0.84% of that run's median frame. Luau call stacks unavailable (#27601). The tablet started cool and stayed cool; battery 92% then 94% (read by hand: #27792) | 0.25 ms (the sample's desktop 60 budget); 0.5 ms against a 30 fps budget | 2026-11-21, one run by the world's owner; a second run is still to be taken |
| Desktop Chrome | not measured yet: no desktop browser engine could be reached from the editor that made this release | 0.25 ms (60 fps budgets) | |
| Android tablet, app | not measured yet: the tablet app could not be reached from the editor that made this release | 0.5 ms (30 fps budgets) | |
To fill a row, open the world on that device and run `zero benchKit overhead benchKitSample` (or
press Run benchmark with Keep set to comprehensive) twice; each report states its recording cost,
its limit and its share of the run's median frame.
**What an over-limit cost means.** The recording added about 0.27 ms to each tablet frame of about
32 ms, under 1% of the frame. That run's frame times are therefore up to that much slower than a
light run on the same tablet would show. That is far smaller than how much two tablet runs differ
from each other, so the run's verdicts stand, but its absolute frame times should be compared
only with other comprehensive runs on that device. For headline numbers to quote, or to compare
against light runs, use `light` (no recording) or `frames` (no memory sampling or GPU pass
recording, the cheaper levels) on the tablet. The limit is checked against the benchmark's own
budget: the sample is judged against desktop 60 (16.7 ms frames), so on a 30 fps tablet budget the
same 0.268 ms is within its 0.5 ms limit.
On the desktop the A/B difference in engine CPU between rounds with and without recording was
smaller than the machine's own noise (rounds without recording spread 32% on a shared editor
machine), so the engine's direct measure is the number to quote. benchKit's own per-frame work
stays apart in `kitCost` (below). Each memory sample takes 9 to 21 ms on a thread of its own on
native, never inside a frame.
### Known limits
Each is a gap in what the engine gives scripts, filed on the platform's issue tracker; benchKit
reports the figure as unavailable with the reason instead of estimating it.
- **Script CPU time and memory per individual script** (#27789): the engine's frame records carry
Luau time as totals (component updates, tasks, GC) and named `profiler.begin` blocks, and its
memory samples give each script VM's heap, not each script's. Script time by module over the
whole run comes from the sampled call stacks instead.
- **Render-target and pipeline memory over time** (#27788): not in the engine's memory samples;
read at the leak check's two moments instead.
- **A forced full garbage collection** for the leak check (#27791): not available to scripts, so
the check waits until the script heap stops shrinking.
- **Entity count** (#27769): benchKit reads the number of entities from the engine's per-frame
recording, so the leak check's entity row needs a capture level of `frames` or above.
- **Script call stacks in a browser** (#27601): a browser engine runs no Luau stack sampler, so
the scripts flame graph and script time by module are unavailable there (the run states the
reason); the engine flame graph still shows where frames went.
- **Battery and device temperature** (#27792): no platform exposes them to scripts, so a report
states them as unavailable.
- **Very large charts** (#27787): the UI's `svg` widget draws nothing past about 64 KB of markup;
chartKit keeps every chart under 60 KB.
- **Card text inside a scaled thumbnail** (#26273): in the card gallery at phone size, text inside
a scaled-down box that sits partly off screen can be dropped (the engine culls it by its
unscaled box), so a label near a quarter-size thumbnail's corner may be missing from the picture.
### Modules
`bench` (the entry point), `spec`, `paths`, `recorder`, `runner`, `probe`, `metrics`, `report`,
`store`, `compare`, `budgets`, `graphics`, `cards`, `looks`, `capture` (capture levels, memory
snapshots, the leak check, reading a recording into a dataset), `codec` (packing long columns),
`dataset` (per-frame data on the player's shelf, the world roster), `export` (JSON, CSV, trace,
flame graphs, saving to the device), `viewer` (the run viewer and compare view), `sample` (the
sample benchmark), the `benchKit` toolbox (run, sweep, sustain, list, show, compare, card,
budgets, paths, record, promote, view, export, overhead), the `benchKitTests` test suite, the
runnable `benchmark-a-change` workflow, and six guides: how to benchmark my world's frame rate on
every device; how to record every frame, memory and flame graphs of my world's performance; how
to compare two benchmark runs and find what got slower; how to export benchmark data to a
spreadsheet or a trace viewer; an example from an empty world to a benchmark world; and the
benchmark-a-change steps for reading by hand. The charts come from **chartKit** (a dependency).
### Comparing across a render-scale change
The render scale is the one setting a comparison accepts as the change under test: two reports of
the same benchmark content (`contentFingerprint`) at the same quality level, build type and
window size that differ only in render scale (and so in the size drawn) are compared, and the
summary names the change ("render scale changed 1 -> 0.5 (drawn 1920x1080 -> 960x540): ...").
Any other difference refuses. When the machine was clearly busier in one run (the share of each
frame spent waiting for a core differs by more than a quarter), engine CPU and "fps with the
machine to itself" read "machine load differed" instead of better or worse.
### Sweep timing
The content is built and settled once; each step settles its new settings for at most
`settleTimeout` (15 s), warms each segment for `warmupSeconds` (2 s), and plays each segment for
`segmentSeconds` (6 s) twice. Nine steps took 423 to 436 s on a busy desktop, so about 7 minutes.
### One setting swaps each variant
| What | The one setting | Where |
|---|---|---|
| Camera path kind | `path = Paths.preset(kind, { center, size, height })`: every kind laid out over the same area, so changing `kind` is the whole change (the benchmark fingerprint follows) | `benchKit.paths` |
| Card look | `Looks.setDefault(name)` (or `opts.look` per card) | `benchKit.looks` |
| Card layout | the first argument of `Cards.show(layout, data, opts)` | `benchKit.cards` |
| Budget | `budget = name` in the definition; every budget is judged regardless | `benchKit.budgets` |
| Run, sweep or sustained | `Bench.run`, `Bench.sweep`, `Bench.sustain` | `benchKit.bench` |
`Bench.preview(path, seconds?)` plays any path through this player's camera without measuring,
so a path can be checked before it is benchmarked. `Recorder.draw(path, duration, n, { group,
material, size })` draws a path as markers; each `group` stays until it is drawn again or
cleared, so several paths stand side by side (`Recorder.clear(group?)`).
`Cards.gallery(layout, data, opts)` / `Cards.showGallery(...)` put every look side by side for a
layout, with the layouts as tabs; `Cards.handleGallery(id)` turns its clicks into a look or
layout change for the caller to apply.
### The Frame Lab showcase
The world's `FrameLabShowcase` component exposes each variant as one field and one button:
`pathKind` (the moving segment flies any of the 11 kinds over the city), `look`, `layout`,
`budget`, `mode` (run, sweep or sustain) and `gallery` (`paths`: every path kind drawn in its
own labelled lane south of the city; `cards`: every look for the chosen layout; `budgets`:
every budget with what it asks and this device's pass or fail). Galleries hide for every
measured window.
# chartKit: game-quality charts for your world's UI
chartKit draws charts and graphs for any screen in a Zero world: a stats screen after a match,
a benchmark results page, a HUD strip that shows frame time live, a loading timeline, a
before-and-after comparison. Every chart is drawn as SVG in one of eleven art styles, and
**one call switches the style of every chart in the world**. Fourteen chart kinds, four sizes
(down to a 390-point-wide phone and a thin HUD strip), and long series of 50,000+ points that
build in a few milliseconds without ever hiding a spike. Point at (or tap) any part of a chart
to read its exact value, and put a chart on a panel standing in the 3D world.
No dependencies. When Graphics Presets is installed, chartKit reads its looks so charts match
those pickers; otherwise built-in copies of the same palettes stand in.
## Quick start
```lua
local Charts = require("chartKit.charts")
local frameTimes = { 8.1, 8.4, 9.0, 31.5, 8.2, 8.6 } -- any list of numbers, 50k is fine
ui.registerScreen("myStats", { type = "vertical", style = { padding = 16, gap = 12 }, children = {
Charts.line {
title = "Frame time", subtitle = "Last run", unit = "ms",
series = { { name = "Frame", values = frameTimes } },
refLines = { { y = 16.7, label = "60 fps", kind = "budget" } },
},
} })
ui.showScreen("myStats")
Charts.setStyle("pixel") -- every chart built from now on is pixel art
```
To see everything at once: `require("chartKit.charts").gallery.show()` puts up a scrolling
gallery of every kind, with buttons to switch style and size. `gallery.hide()` takes it down.
## Two forms of every chart
- `Charts.<kind>(spec)` returns a **UI node**: a styled card with the title, subtitle, an
optional big `headline` value at the right, the chart, and a legend. Put it anywhere in a
screen tree. `spec.id` becomes the card's id (and `id/svg`, `id/plot`, `id/title`, `id/legend`
inside; `id/plot` holds the svg and the readout's hit boxes).
- `Charts.svg.<kind>(spec)` returns `(markup, width, height)`: the bare SVG, for your own
`{ type = "svg", props = { svg = markup }, style = { width = width, height = height } }`.
Note an `svg` widget must not be the direct child of an `anchor`; wrap it in a vertical.
## Options every chart takes
| field | meaning |
|---|---|
| `size` | `"panel"` (about 720 wide, the default), `"tile"` (about 240), `"phone"` (about 358, readable on a 390-wide portrait phone), `"hud"` (a 320x36 strip, no axes) |
| `width`, `height` | override the chart's own size in points |
| `title`, `subtitle`, `headline` | card text (node form) |
| `unit` | "ms", "MB", "%", ... added to axis and value labels |
| `style` | draw this one chart in another style than the world's |
| `legend` | `true` / `false` to force the legend on or off |
| `id` | the card's widget id (one is made up when left out) |
| `readout` | `false` turns off the hover and tap readout for this chart |
## The chart kinds
**line**: one or more series over x, with reference lines, segment marks, shaded bands and hitch dots.
```lua
Charts.line {
title = "Frame time", unit = "ms",
series = { { name = "Frame", values = ft }, { name = "GPU", values = gpu, color = "#ff3e9a" } },
x = { label = "frame" }, -- or x = { values = { ... } } for numeric x or text categories
refLines = { { y = 16.7, label = "60 fps", kind = "budget" }, { y = 9.4, kind = "median" } },
marks = { { x = 1, label = "Orbit" }, { x = 900, label = "Fly-through" } },
bands = { { from = 900, to = 1400, label = "Heavy area" } },
highlights = { { x = 512, label = "31 ms hitch" } }, -- value is looked up when left out
}
```
A series can also be `points = { { x, y }, ... }`. `yMin`, `yMax` fix the axis.
**area**: the same spec as line, filled. Larger areas are drawn first so a smaller one is never hidden.
**stacked**: stacked areas over x, e.g. GPU passes per frame; `bars = true` draws stacked columns.
```lua
Charts.stacked { title = "GPU passes", unit = "ms", series = {
{ name = "Opaque", values = opaque }, { name = "Shadows", values = shadows }, { name = "Post", values = post } } }
```
**histogram**: raw samples (`values`) or ready `bins = { { from, to, count } }`. Bins past a budget line turn the style's "bad" colour; a lone huge hitch goes into an overflow bin marked "+".
```lua
Charts.histogram { title = "Distribution", unit = "ms", values = ft, refLines = { { x = 16.7, kind = "budget" } } }
```
**bar**: labelled values, horizontal by default; `horizontal = false` for columns, `sort = true` biggest first, `colorful = true` one colour per bar.
```lua
Charts.bar { title = "Top costs", unit = "ms", sort = true, items = {
{ label = "Shadows", value = 3.4, note = "4 cascades" }, { label = "Physics", value = 1.7 } } }
```
**ring**: a donut with a centre value and, at panel and phone size, a list with values and percentages.
```lua
Charts.ring { title = "Memory", unit = "MB", center = { value = 1840, label = "MB total" },
items = { { label = "Textures", value = 820 }, { label = "Meshes", value = 410 } } }
```
**flame**: a flame graph from a tree or folded stacks. `inverted = true` draws an icicle (root on top).
```lua
Charts.flame { title = "Where a frame goes", folded = "frame;render;shadows 420\nframe;update;physics 330" }
Charts.flame { root = { name = "frame", value = 16, children = { { name = "render", value = 10 } } }, inverted = true }
```
`minFraction` hides boxes narrower than that share; `maxDepth` limits rows.
**sparkline**: a small line with no axes.
```lua
Charts.sparkline { values = ft, refLine = 16.7 }
```
**overlay**: two runs on one axis; `a` is drawn dashed (the baseline), `b` solid.
```lua
Charts.overlay { title = "Before vs after", unit = "ms", a = { name = "Baseline", values = old }, b = { name = "This build", values = new } }
```
**diffBars**: change from `a` to `b` per row, coloured good or bad with the percent.
```lua
Charts.diffBars { aName = "Baseline", bName = "This build", items = {
{ label = "Median", a = 10.4, b = 9.6, unit = "ms" }, -- lower is better by default
{ label = "1% low fps", a = 58, b = 66, lowerIsBetter = false } } }
```
**heatStrip**: one row of coloured cells (e.g. every frame's time; a long row keeps each cell's worst value), or a heat map with `rows`.
```lua
Charts.heatStrip { values = ft, thresholds = { good = 11, warn = 16.7 } }
Charts.heatStrip { rows = { { label = "Orbit", values = a }, { label = "Fly", values = b } } }
```
**gantt**: lanes of timed items, e.g. loading and shader compiles.
```lua
Charts.gantt { unit = "s", lanes = {
{ name = "Textures", items = { { start = 0.3, finish = 3.1, label = "stream" } } },
{ name = "Shaders", items = { { start = 0.5, finish = 1.6, label = "compile" } } } },
marks = { { x = 3.1, label = "playable" } } }
```
**statTile**: a big number with an optional change and sparkline.
```lua
Charts.statTile { label = "Median frame", value = 9.6, unit = "ms", delta = -7.7, lowerIsBetter = true, spark = ft }
```
**treemap**: shares of a whole as nested rectangles (squarified, so cells stay close to square). Labels sit in the cells that fit them, with the value and share underneath when there is room. An item with `children` is drawn as a group with its children inside. `sort` defaults to biggest first (`"asc"`, or `false` to keep your order). At hud size it draws a one-row share strip led by the biggest item.
```lua
Charts.treemap { title = "Memory", unit = "MB", items = {
{ label = "Textures", children = { { label = "Terrain", value = 380 }, { label = "UI", value = 60 } } },
{ label = "Meshes", value = 410 }, { label = "Audio", value = 230, color = "#ff9f1c" } } }
```
## Hover and tap readout
Every chart card tells the player the exact value under their pointer, on by default:
- **Mouse**: hovering shows the engine's tooltip with the label, value and unit. On `line`, `area`,
`stacked` and `overlay` it names the x position ("frame 512", or "frames 500-528" on a long run)
and every series' value there, with the column's max when a spike sits inside it.
- **Touch**: a tap pins a small readout bubble beside the finger, drawn in the chart's style; a
tap anywhere else (or on the same spot) dismisses it. A mouse click pins it too.
It covers `line`, `area`, `stacked` (areas and columns), `overlay`, `histogram` (range, count and
share), `bar`, `ring` (slices and list rows), `treemap`, `flame`, `heatStrip`, `gantt` (start, end,
duration), `diffBars` and `sparkline`. The card holds transparent hit boxes over the svg; the svg is
never rebuilt on hover or tap, only the small `chartKit.readout` screen changes, and nothing runs
per frame. `readout = false` turns it off for one chart. A chart without an `id` gets one
(`ck.auto.<n>`); give your own to drive it from code: `Charts.readout.show(id, box)`,
`Charts.readout.hide()`, `Charts.readout.current()`.
A screen your **component** registers sends its callbacks to that component, so forward them:
```lua
local Charts = require("chartKit.charts")
function onCallback(id, data)
if Charts.onCallback(id, data) then return end -- a chart readout tap
if id == "stats.close" then closeStats() end
end
```
Screens registered from a module, a scene script or `execute` need nothing: chartKit owns a
callback env for them.
## Charts on a panel in the 3D world
A scoreboard on a wall, a lobby stats board, a sign that charts progress:
```lua
local board = Charts.worldPanel { kind = "bar", position = { 0, 2, -6 }, yaw = 180, width = 3,
spec = { title = "Top scores", unit = "pts", sort = true, items = { { label = "Ann", value = 120 } } } }
board.set({ title = "Top scores", unit = "pts", sort = true, items = newItems }) -- redraws once
board.destroy()
```
Or put the **`ChartPanel`** component on an entity in your scene: `kind`, `spec` (exactly what
`Charts.<kind>` takes), `size`, `style` (empty follows the world style), `width` in metres and
`height` above the entity.
```lua
entity(boardId).component.add("ChartPanel", { kind = "treemap", width = 3, height = 2,
spec = { title = "Memory", unit = "MB", items = items } })
entity(boardId).component.get("ChartPanel").spec = { title = "Memory", unit = "MB", items = newItems }
```
The card is laid out on a hidden screen and rasterised into a texture (up to twice its size, so
text stays crisp up close) that an unlit quad shows; the quad faces the entity's +Z and respects
depth like any mesh. It is drawn again only when the spec, kind, size or style changes or the
world chart style changes, never per frame. The ChartPanel fields are synced: the peer that owns
the entity writes `spec` and every player's engine draws the same chart. `Charts.worldPanel`
makes a panel on the peer that calls it (a temporary entity, never saved into the scene), so
call it from code every player runs. World panels have no readout (nobody points at a texture).
## Helpers
- `Charts.legend(items, opts)`: a legend node, `items = { { name, color, dash?, fill? } }`.
- `Charts.folded(text)`: parse folded stacks into `{ name, value, children }`.
- `Charts.decimate(values, buckets)`: `(ys, idx)` keeping each bucket's min and max in order.
- `Charts.binValues(values, binCount?, binWidth?)`: histogram bins.
- `Charts.format(v, unit)`: "16.7 ms", "12.3k".
- `Charts.build(kind, spec)`: any kind by name.
## Styles
`Charts.setStyle(name)` sets the style for every chart in the world; `Charts.style()` reads it,
`Charts.styles()` lists them, `Charts.theme(name?)` returns the colours and fonts (to style the
rest of your screen to match), and `Charts.onStyleChanged(fn)` tells you when to rebuild screens
already on show. `Charts.defineStyle(name, { base = "scifi", accent = "#39ff14" })` adds your own.
| style | look |
|---|---|
| minimal | white cards, hairline grid, ink black and one red accent |
| scifi | dark navy, glowing cyan lines, corner brackets, upper-case mono labels |
| fantasy | parchment gradient, serif type, inked double strokes, hatched fills, double-rule frame |
| cartoon | yellow page, white cards, thick black outlines, bright flat fills, chunky shadow |
| pixel | stepped lines, square markers, dithered fills, block bars, crisp edges, mono type |
| cozy | warm cream, rounded, soft pastel colours and thick round lines |
| realistic | graphite instrument cluster, white type, one amber accent |
| horror | near-black, blood-red glow, vignette, serif type |
| military | olive drab, stencil titles, amber, corner brackets, hatched fills |
| colorblind | Okabe-Ito palette, and every series also gets its own dash and hatch angle |
| highContrast | black, white and yellow, thick strokes, text 25% larger |
## Sizes and phones
`panel` suits desktop screens; `phone` fits a 390-point-wide portrait phone (358 wide with its
padding, fewer ticks, labels kept apart); `tile` is for grids of small charts; `hud` is a thin
strip with a caption on the left and the latest value on the right, for in-game overlays.
## Performance
Series of any length are reduced to about two points per horizontal pixel, keeping each
pixel column's minimum and maximum, so a single-frame spike always shows. Strings are built with
`table.concat` and paths are written compactly. Measured in this engine: a 50,000-point line
chart builds in **2.6 ms on an idle engine and 5 to 7 ms with a benchmark running beside it** (svg and node form alike, every style); the test suite fails if
it ever takes 50 ms. The engine's svg widget draws nothing for markup much past 64 KB, so any
chart that would exceed 60 KB is rebuilt at lower detail automatically.
**A chart on screen costs nothing per frame (1.0.2).** The engine rasterises an svg widget's
markup once, on the main thread, and keeps the picture for as long as the markup string is the
same. 1.0.1 was reported making the worst frame of a 4 s profiler capture 83.7 ms with a chart
open against 48.4 ms closed. Measured with `profiler.startCapture(label, { level = "frames" })`
and the per-frame `prepare_ui_rendering.svg.render` time, the causes were:
- **Blur filters.** The glow of scifi and horror (and the glow under bars) was an SVG
`feGaussianBlur`. Rasterising a 2,400-point scifi line chart took **130 ms (min of 3; median
145 ms) with the filter and 21 ms (median 31 ms) without it**. Glows are now two wide
translucent strokes (or a soft rect), no filter anywhere; a test fails if one comes back.
- **New markup on every build.** Every chart carried a fresh numeric id in its gradient and
pattern ids, so rebuilding a chart with the same data (a style listener, a canvas event, the
gallery, a game refreshing its stats) produced different markup and a full re-raster (11.4 ms
for one minimal line chart, all 16 gallery charts at once on each gallery rebuild). Ids are
now fixed per document, so the same data gives byte-identical markup and **re-showing or
rebuilding a chart re-rasterises nothing (measured 0 ms)**; a test checks two builds match.
- **The gallery** keeps its built charts per style, size and width (a canvas event that changes
none of them rebuilds nothing) and comes up two charts per frame, so first-show rasters are
spread over frames.
After, alternating open and closed 4 s captures on this shared, busy machine (each window started
0.5 s after opening, so it shows the steady state):
| capture | median frame open / closed | worst frame open / closed | svg raster while open |
|---|---|---|---|
| gallery, 3 pairs | 19.6, 24.9, 24.0 ms / 20.5, 24.4, 22.6 ms | 39.8, 49.9, 47.5 ms / 47.7, 47.6, 49.2 ms | 0 ms |
| one scifi line chart, 3 pairs | 27.6, 22.4, 31.4 ms / 28.9, 22.4, 28.2 ms | 50.4, 102.5, 178.6 ms / 37.2, 73.1, 49.9 ms | 0 ms |
The open and closed medians match. The worst single frames swing with the machine's other load
in both columns: the open windows' worst frames were all render-thread waits
(`render_frame.tail_finish`, `tail_submit`, `deferred_oit` as their top keys) with zero svg or UI
work in them. What a chart still costs is the one raster when new markup is first shown, about
10 to 30 ms for a full panel chart on this machine (pixel style is the cheapest); show charts
before the moment that matters (a results screen as the round ends) and update live charts a few
times a second, not every frame.
## Multiplayer
Charts are local UI: each player builds the screens they see from the data they have, and
`setStyle` changes the style on the peer that calls it. To show every player the same numbers,
replicate the numbers (the engine's multiplayer state), not the chart.
## What else is in the package
- `chartKit.gallery`: the gallery screen (`show`, `hide`, `node`, `sampleData`).
- `chartKit.readout`: the hover and tap readout behind every card.
- `chartKit.panel` and the `ChartPanel` component: charts on panels in the 3D world.
- `chartKit.example`: "Star Catcher", a small playable game with a stats screen
(`require("chartKit.example").start()`); its guide walks through building it.
- Guides: *how to draw graphs and charts in my game's UI* and *example: a small game with a stats
screen using charts*.
- `chartKitTests`: `zero tests run --suite chartKitTests`.