Files
bworld/client/benchmark/benchmark.ts
T

576 lines
20 KiB
TypeScript

// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// the render benchmark, run from the f3 performance window, for comparing browsers and systems. it draws a level of
// its own that's the same every time (see bench_level.ts) through scenes that each load a part of the renderer: the
// terrain from above, the lake, a crowd of entities, blocks changing every tick and so on. the world waits meanwhile,
// so what's around the player doesn't change the numbers. each scene is timed with frames paced by the display, then
// with frames back to back (see render_debug.uncapped), after a warmup. meshing the whole level is timed too, the
// first time and again. the report says what the computer and the browser are, see report.ts
import { Camera } from "@/client/camera.ts";
import { ClientLevel } from "@/client/level/client_level.ts";
import type { GameRenderer } from "@/client/rendering/game_renderer.ts";
import { block_visuals } from "@/client/rendering/visuals.ts";
import { draw_item } from "@/client/rendering/render_utils.ts";
import { InputManager } from "@/client/input_manager.ts";
import { type FrameSample, profiler } from "@/client/profiler.ts";
import { RemotePlayer } from "@/client/entity/remote_player.ts";
import { RemoteEntity } from "@/client/entity/remote_entity.ts";
import { ItemEntity } from "@/client/entity/item_entity.ts";
import { tick_texture_animations } from "@/client/texture_animations.ts";
import {
adapter_info,
device,
draw_text,
gpu_timer,
render_debug,
render_stats,
set_canvas_size,
} from "@/client/renderer/mod.ts";
import { ID_MASK, SLOT_SIZE, STATE_SHIFT } from "@/common/constants.ts";
import { AIR_ID } from "@/common/protocol.ts";
import { TIMES_OF_DAY } from "@/common/time.ts";
import { type BlockRegistry, EverythingRegistry, RENDER_LAYERS } from "@/common/everything_registry.ts";
import type { EntityJson } from "@/common/mod_data.ts";
import type { ModListing } from "@/common/mod_loader.ts";
import { ItemStack } from "@/common/inventory.ts";
import { display_name } from "@/common/utils.ts";
import {
bench_blocks,
type BenchBlocks,
BenchTerrain,
LEVEL_RADIUS,
LEVEL_SHAPE,
SEA_LEVEL,
UPDATE_WALL,
ZONES,
} from "./bench_level.ts";
import {
BENCHMARK_VERSION,
type BenchmarkReport,
frame_stats,
type MeshingResult,
type SceneResult,
type SystemInfo,
time_stats,
} from "./report.ts";
// each scene's parts. warmup and settle aren't counted, settle is for the switch to uncapped frames
const PHASES = [
{ phase: "warmup", ms: 1500 },
{ phase: "paced", ms: 5000 },
{ phase: "settle", ms: 500 },
{ phase: "uncapped", ms: 4000 },
] as const;
// every run draws at this size, scaled to fit the window, so runs in different windows compare
const RESOLUTION = { width: 1920, height: 1080 };
// how long a frame spends building the level, it's built over many so the page keeps responding
const BUILD_MS_PER_FRAME = 30;
// meshing the level gives up after this
const MESHING_TIMEOUT_MS = 120_000;
// meshes each worker is given at once, see ClientLevel.max_meshes_in_flight
const MESHES_PER_WORKER = 8;
// walking round the arena
const PLAYERS = 40;
const MOBS = 80;
// in blocks per tick
const WALK_SPEED = 0.2;
// lying in the middle of it
const ITEMS = 160;
const ITEM_ROW = 16;
const ITEM_SPACING = 0.6;
// the gui scene's lines of item names, about as long as the screen is wide
const GUI_LINE_LENGTH = 160;
interface Scene {
name: string;
// where the camera is t of the way through each part of the scene, from 0 to 1
camera: (camera: Camera, t: number) => void;
msaa?: boolean;
// before and after it, for what only it has
start?: () => void;
end?: () => void;
// every tick
tick?: (ticks: number) => void;
// over the level, like a screen
draw?: () => void;
}
// an entity going round the arena
interface Walker {
entity: RemotePlayer | RemoteEntity;
radius: number;
angle: number;
// radians per tick, negative is clockwise
speed: number;
}
export class RenderBenchmark {
// what it's doing, shown while it runs
status = "Building the level";
#renderer: GameRenderer;
#mods: ModListing[];
// with the report, or why it stopped
#on_end: (result: BenchmarkReport | string) => void;
#ended = false;
#level: ClientLevel;
#blocks: BenchBlocks;
#camera = new Camera();
// what's drawn, nothing while the level is built
#scene: Scene | undefined;
// how far through the scene's part it is
#t = 0;
#flow: Generator<void, void>;
#build_ms = 0;
#walkers: Walker[] = [];
// every item, for the gui scene and the ones lying in the arena
#items: ItemStack[];
// a line of names for each row of the gui scene's slots
#gui_lines: string[];
#system: SystemInfo;
// the page was hidden, which stops frames
#hidden = false;
#saved_debug = { ...render_debug };
#saved_draw: Record<string, boolean>;
constructor(renderer: GameRenderer, mods: ModListing[], on_end: (result: BenchmarkReport | string) => void) {
this.#blocks = bench_blocks(new Set(block_visuals.keys()));
this.#renderer = renderer;
this.#mods = mods;
this.#on_end = on_end;
this.#items = EverythingRegistry.entries("items").map(([id]) => id).sort().map((id) => new ItemStack(id));
const names = this.#items.map((item) => display_name(item.type_id)).join(" ");
this.#gui_lines = Array.from(
{ length: Math.floor(RESOLUTION.height / SLOT_SIZE) },
(_, row) => names.slice(row * GUI_LINE_LENGTH, (row + 1) * GUI_LINE_LENGTH),
);
this.#level = new ClientLevel([], LEVEL_SHAPE, LEVEL_RADIUS);
this.#level.time = TIMES_OF_DAY.noon;
this.#level.max_meshes_in_flight = this.#level.workers.size * MESHES_PER_WORKER;
this.#system = system_info(this.#level.workers.size);
// what the f3 window switched is put back after
const draw = renderer.level_renderer.draw;
this.#saved_draw = { ...draw };
for (const key of Object.keys(draw) as (keyof typeof draw)[]) draw[key] = true;
Object.assign(render_debug, { msaa: false, split_passes: false, uncapped: false });
set_canvas_size(RESOLUTION);
document.addEventListener("visibilitychange", this.#on_visibility);
this.#flow = this.#run();
}
// at the start of the client's frame, before its ticks
frame() {
this.#guard(() => {
if (InputManager.is_key_pressed("Escape")) {
this.#end("The benchmark was stopped");
} else if (this.#hidden) {
this.#end("The benchmark stopped since the page was hidden, which holds frames back");
} else {
this.#flow.next();
}
});
}
// instead of the client's tick, which waits
tick() {
this.#guard(() => {
this.#scene?.tick?.(this.#level.ticks);
this.#level.tick();
this.#level.time = TIMES_OF_DAY.noon;
tick_texture_animations();
});
}
// instead of the client's drawing
render(partial_tick: number) {
this.#guard(() => {
const scene = this.#scene;
if (scene) {
scene.camera(this.#camera, Math.min(this.#t, 1));
this.#renderer.render_level(this.#level, this.#camera, partial_tick);
scene.draw?.();
}
draw_text(`Benchmark: ${this.status}. Escape stops it`, 8, 8);
});
}
// a benchmark that throws stops, so the game goes on
#guard(fn: () => void) {
if (this.#ended) return;
try {
fn();
} catch (e) {
console.error(e);
this.#end(`The benchmark failed: ${e instanceof Error ? e.message : e}`);
}
}
#end(result: BenchmarkReport | string) {
this.#ended = true;
this.#level.dispose();
Object.assign(render_debug, this.#saved_debug);
Object.assign(this.#renderer.level_renderer.draw, this.#saved_draw);
set_canvas_size(undefined);
profiler.samples = undefined;
if (gpu_timer) gpu_timer.samples = undefined;
document.removeEventListener("visibilitychange", this.#on_visibility);
this.#on_end(result);
}
#on_visibility = () => {
if (document.hidden) this.#hidden = true;
};
// the whole benchmark, a frame at each yield
*#run(): Generator<void, void> {
yield* this.#build();
const first_mesh = yield* this.#mesh(false);
const remesh = yield* this.#mesh(true);
const scenes: Record<string, SceneResult> = {};
const list = this.#scenes();
for (const [i, scene] of list.entries()) {
scenes[scene.name] = yield* this.#measure(scene, `${i + 1} of ${list.length}`);
}
// the mean, firefox's timer only counts whole ms
const sky = scenes.sky?.paced;
if (sky) this.#system.refresh_hz = Math.round(sky.fps);
this.#end({
version: BENCHMARK_VERSION,
date: new Date().toISOString(),
system: this.#system,
mods: this.#mods.map((mod) => `${mod.id} ${mod.version}`),
resolution: `${RESOLUTION.width}x${RESOLUTION.height}`,
render_regions: render_debug.render_regions,
level: { chunks: this.#level.chunks.size, build_ms: this.#build_ms },
first_mesh,
remesh,
scenes,
});
}
*#build(): Generator<void, void> {
const terrain = new BenchTerrain(this.#blocks);
const chunks: [number, number][] = [];
for (let z = -LEVEL_RADIUS; z < LEVEL_RADIUS; z++) {
for (let x = -LEVEL_RADIUS; x < LEVEL_RADIUS; x++) chunks.push([x, z]);
}
let built = 0;
while (built < chunks.length) {
const start = performance.now();
while (built < chunks.length && performance.now() - start < BUILD_MS_PER_FRAME) {
const [x, z] = chunks[built++];
this.#level.set_chunk(terrain.chunk(x, z));
}
this.#build_ms += performance.now() - start;
this.status = `building the level, ${Math.floor(built / chunks.length * 100)}%`;
yield;
}
}
// meshing every chunk that can be, the first time and again once the workers have warmed up
*#mesh(again: boolean): Generator<void, MeshingResult> {
const level = this.#level;
this.#scene = { name: "meshing", camera: overlook };
this.status = again ? "meshing the level again" : "meshing the level";
if (again) level.remesh_all();
const frames: FrameSample[] = [];
profiler.samples = frames;
const start = performance.now();
// this frame asks for the first meshes
do {
yield;
if (performance.now() - start > MESHING_TIMEOUT_MS) throw new Error("meshing the level took too long");
} while (level.meshes_pending > 0);
profiler.samples = undefined;
return {
chunks: [...level.chunks.values()].filter((chunk) => level.can_mesh(chunk)).length,
ms: performance.now() - start,
paced: frame_stats(frames.map((frame) => frame.interval)),
};
}
*#measure(scene: Scene, progress: string): Generator<void, SceneResult> {
this.#scene = scene;
scene.start?.();
render_debug.msaa = scene.msaa ?? false;
const timed: Partial<Record<"paced" | "uncapped", { frames: FrameSample[]; gpu: number[] }>> = {};
let drawn = this.#drawn();
for (const { phase, ms } of PHASES) {
this.status = `${scene.name}, ${progress}`;
render_debug.uncapped = phase === "settle" || phase === "uncapped";
const frames: FrameSample[] = [];
const gpu: number[] = [];
profiler.samples = frames;
if (gpu_timer) gpu_timer.samples = gpu;
const start = performance.now();
for (let frame = 0; (this.#t = (performance.now() - start) / ms) < 1; frame++) {
// the first frame's, where the camera always is in the same place
if (phase === "paced" && frame === 1) drawn = this.#drawn();
yield;
}
if (phase === "paced" || phase === "uncapped") timed[phase] = { frames, gpu };
}
render_debug.msaa = false;
render_debug.uncapped = false;
scene.end?.();
// the paced frames' gpu times have all come back by now
const { paced, uncapped } = timed;
return {
paced: frame_stats(paced?.frames.map((frame) => frame.interval) ?? []),
uncapped_fps: uncapped && uncapped.frames.length * 1000 /
uncapped.frames.reduce((sum, frame) => sum + frame.interval, 0),
cpu: time_stats(paced?.frames.map((frame) => frame.frame) ?? []),
gpu: time_stats(paced?.gpu ?? []),
...drawn,
};
}
// what the last frame drew
#drawn() {
const { draw_calls, quads } = render_stats;
const level_renderer = this.#renderer.level_renderer;
return {
draw_calls,
quads: RENDER_LAYERS.reduce((sum, layer) => sum + quads[layer], 0),
sections_in_view: level_renderer.visible_sections,
entities_in_view: level_renderer.drawn_entities,
};
}
#scenes(): Scene[] {
const sky = (camera: Camera) => place(camera, 0, 200, 0, 0, 1.5);
const { lake, arena, visuals } = ZONES;
const wall = UPDATE_WALL;
return [
// nothing in view: what every frame costs anyway, and the display's refresh
{ name: "sky", camera: sky },
// the whole level from above
{ name: "terrain", camera: overlook },
{ name: "msaa", camera: overlook, msaa: true },
// round the level, low and looking ahead, so what's in view keeps changing
{ name: "flyover", camera: flyover },
// across the lake, moving so its water is sorted again
{
name: "water",
camera: (camera, t) =>
place(
camera,
lake.x + 40 + sway(t, 6),
SEA_LEVEL + 6,
lake.z + 40 - sway(t, 6),
Math.PI / 4 + sway(t, 0.3),
-0.12,
),
},
// only here, so the other scenes don't draw them
{
name: "entities",
camera: (camera, t) => place(camera, arena.x, arena.height + 8, arena.z + 30, sway(t, 0.3), -0.3),
start: () => this.#spawn_entities(),
end: () => this.#remove_entities(),
tick: () => this.#walk(),
},
{
name: "visuals",
camera: (camera, t) =>
place(camera, visuals.x, visuals.height + 10, visuals.z + 18, sway(t, 0.2), -0.5),
},
// a screen full of items over the sky
{ name: "gui", camera: sky, draw: () => this.#draw_gui() },
{
name: "block_updates",
camera: (camera, t) =>
place(camera, wall.x + wall.width / 2, wall.y + 4, wall.z + 16, sway(t, 0.15), -0.1),
tick: (ticks) => this.#change_wall(ticks),
},
];
}
#spawn_entities() {
const level = this.#level;
const { x, z, height } = ZONES.arena;
const y = height + 1;
// four rings each way round, every other one the other way
const walk = (entity: RemotePlayer | RemoteEntity, i: number, count: number, radius: number) => {
const ring = i % 4;
const ring_radius = radius + ring * 4;
const speed = (ring % 2 === 0 ? 1 : -1) * WALK_SPEED / ring_radius;
this.#walkers.push({ entity, radius: ring_radius, angle: (i / count) * Math.PI * 2, speed });
level.add_entity(entity);
};
for (let i = 0; i < PLAYERS; i++) {
const info = { id: `benchmark_player_${i}`, name: `Player ${i + 1}`, x, y, z, yaw: 0, pitch: 0 };
walk(new RemotePlayer(level, info), i, PLAYERS, 6);
}
const types = EverythingRegistry.entries<EntityJson>("entities").map(([id]) => id).sort();
for (let i = 0; types.length > 0 && i < MOBS; i++) {
const type = types[i % types.length];
const info = {
kind: "entity" as const,
type,
id: `benchmark_mob_${i}`,
x,
y,
z,
yaw: 0,
pitch: 0,
data: {},
};
walk(new RemoteEntity(level, info), i, MOBS, 8);
}
for (let i = 0; this.#items.length > 0 && i < ITEMS; i++) {
level.add_entity(
new ItemEntity(level, {
kind: "item",
id: `benchmark_item_${i}`,
x: x + ((i % ITEM_ROW) - ITEM_ROW / 2) * ITEM_SPACING,
y,
z: z + (Math.floor(i / ITEM_ROW) - ITEMS / ITEM_ROW / 2) * ITEM_SPACING,
item: { id: this.#items[i % this.#items.length].type_id, count: 1 },
}),
);
}
}
#remove_entities() {
for (const id of [...this.#level.entities.keys()]) this.#level.remove_entity(id);
this.#walkers = [];
}
#walk() {
const { x, z, height } = ZONES.arena;
for (const walker of this.#walkers) {
walker.angle += walker.speed;
const cos = Math.cos(walker.angle);
const sin = Math.sin(walker.angle);
// facing the way it goes, yaw 0 is north (-z)
const yaw = Math.atan2(sin * Math.sign(walker.speed), -cos * Math.sign(walker.speed));
walker.entity.lerp_to(x + cos * walker.radius, height + 1, z + sin * walker.radius, yaw, 0);
}
}
// every block of the wall changes every tick, between a light and stone, so the light around it changes too, the
// way the server's block changes come in
#change_wall(ticks: number) {
const { light, stone } = this.#blocks;
const [on, off] = light === undefined
? [block_id(stone), [AIR_ID, 0] as const]
: [block_id(light), block_id(stone)];
const wall = UPDATE_WALL;
for (let dy = 0; dy < wall.height; dy++) {
for (let dx = 0; dx < wall.width; dx++) {
const [id, state] = (dx + dy + ticks) % 2 === 0 ? on : off;
this.#level.apply_change(wall.x + dx, wall.y + dy, wall.z, id, state);
}
}
}
// every item in slots filling the screen, with their names over them
#draw_gui() {
const items = this.#items;
if (items.length === 0) return;
const columns = Math.floor(RESOLUTION.width / SLOT_SIZE);
const rows = this.#gui_lines.length;
for (let i = 0; i < columns * rows; i++) {
const x = (i % columns) * SLOT_SIZE;
const y = Math.floor(i / columns) * SLOT_SIZE;
draw_item(items[i % items.length], x, y, false);
}
this.#gui_lines.forEach((line, row) => draw_text(line, 4, row * SLOT_SIZE + 4));
}
}
// the camera at x y z, turned yaw from facing north (-z) and pitch up
function place(camera: Camera, x: number, y: number, z: number, yaw: number, pitch: number) {
camera.x = x;
camera.y = y;
camera.z = z;
camera.yaw = yaw;
camera.pitch = pitch;
}
// there and back once, from 0
function sway(t: number, amount: number) {
return Math.sin(t * Math.PI * 2) * amount;
}
// the whole level from its south edge, looking a little to each side
function overlook(camera: Camera, t: number) {
place(camera, 0, 150, LEVEL_RADIUS * 16 - 8, sway(t, 0.25), -0.45);
}
// once round the level, looking ahead and a little in. yaw 0 faces north (-z)
function flyover(camera: Camera, t: number) {
const angle = t * Math.PI * 2;
const radius = LEVEL_RADIUS * 16 * 0.6;
place(camera, Math.cos(angle) * radius, 120, Math.sin(angle) * radius, Math.PI - angle - 0.3, -0.35);
}
// what apply_change takes for a block value
function block_id(value: number): readonly [string, number] {
return [EverythingRegistry.get_by_id<BlockRegistry>("blocks", value & ID_MASK)!.id, value >>> STATE_SHIFT];
}
// navigator.userAgentData, chromium's client hints, which the dom typings don't have
interface UserAgentData {
getHighEntropyValues(hints: string[]): Promise<{
platform?: string;
platformVersion?: string;
architecture?: string;
fullVersionList?: { brand: string; version: string }[];
}>;
}
// the first that matches
const BROWSERS: [RegExp, string][] = [
[/Firefox\/([\d.]+)/, "Firefox"],
[/Edg\/([\d.]+)/, "Edge"],
[/OPR\/([\d.]+)/, "Opera"],
[/Chrome\/([\d.]+)/, "Chrome"],
[/Version\/([\d.]+).*Safari/, "Safari"],
];
const SYSTEMS: [RegExp, string][] = [
[/Windows/, "Windows"],
[/iPhone|iPad/, "iOS"],
[/Mac OS X/, "macOS"],
[/Android/, "Android"],
[/CrOS/, "ChromeOS"],
[/Linux/, "Linux"],
];
// what's running the benchmark. the browser and the system come from the user agent, then from the client hints in
// browsers that have them, which say more and come a moment later
function system_info(workers: number): SystemInfo {
const agent = navigator.userAgent;
const browser = BROWSERS.find(([pattern]) => pattern.test(agent));
const architecture = /x86_64|x64|Win64/.test(agent) ? " x86_64" : /aarch64|arm64/i.test(agent) ? " arm64" : "";
const { vendor = "", architecture: gpu_architecture = "", description = "" } = adapter_info ?? {};
const gpu = [vendor, gpu_architecture].filter(Boolean).join(" ") || "unknown gpu";
const info: SystemInfo = {
browser: browser ? `${browser[1]} ${agent.match(browser[0])![1]}` : "unknown browser",
os: (SYSTEMS.find(([pattern]) => pattern.test(agent))?.[1] ?? "unknown system") + architecture,
user_agent: agent,
cpu_threads: navigator.hardwareConcurrency,
memory_gb: (navigator as { deviceMemory?: number }).deviceMemory,
gpu: description ? `${gpu} (${description})` : gpu,
gpu_features: [...device.features].sort(),
timestamps: gpu_timer?.supported ?? false,
canvas_format: navigator.gpu.getPreferredCanvasFormat(),
device_pixel_ratio: devicePixelRatio,
screen: `${screen.width}x${screen.height}`,
workers,
};
const hints = (navigator as { userAgentData?: UserAgentData }).userAgentData;
hints?.getHighEntropyValues(["architecture", "platformVersion", "fullVersionList"]).then((values) => {
const brands = values.fullVersionList ?? [];
const brand = brands.find(({ brand }) => !/Not.A.Brand|Chromium/i.test(brand)) ??
brands.find(({ brand }) => brand === "Chromium");
if (brand) info.browser = `${brand.brand} ${brand.version}`;
info.os = [values.platform, values.platformVersion, values.architecture].filter(Boolean).join(" ");
}).catch(() => {});
return info;
}