Benchmark

This commit is contained in:
2026-10-28 11:42:58 -03:00
parent e5221ba681
commit 8fc08ab41e
15 changed files with 1356 additions and 41 deletions
+256
View File
@@ -0,0 +1,256 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// the render benchmark's level, made on the client from a fixed seed so every run draws the same thing whatever world
// the player is in: hills with caves, trees and plants, a lake with glass in it, and flat ground for the scenes with
// entities, visuals and changing blocks. it's made of what the loaded mods' worldgen data makes the ground of, and other
// blocks picked by what they are (a cutout plant, a translucent cube), not by their ids
import { Alea } from "@paulaboks/rng";
import { AIR, CHUNK_AREA, CHUNK_HEIGHT, CHUNK_SIZE } from "$/common/constants.ts";
import { type BlockRegistry, EverythingRegistry } from "$/common/everything_registry.ts";
import { DEFAULT_MODEL } from "$/common/block_models.ts";
import { OctaveNoise2D, OctaveNoise3D, smoothstep } from "$/common/worldgen/noise.ts";
import { can_stand_on, default_block_value } from "$/common/utils.ts";
import type { Biome } from "$/common/worldgen/biomes.ts";
import type { NoiseSettingsJson } from "$/common/worldgen/data.ts";
const SEED = "benchmark";
// chunks go from -LEVEL_RADIUS to LEVEL_RADIUS - 1 each way. the outermost ring is only there so the ones inside it
// can be meshed, see ClientLevel.can_mesh
export const LEVEL_RADIUS = 13;
export const SEA_LEVEL = 62;
// the lake, and flat ground for the scenes. the terrain eases into each over BLEND blocks
export const ZONES = {
lake: { x: -96, z: -96, radius: 44, height: 46 },
arena: { x: 96, z: -96, radius: 26, height: 72 },
visuals: { x: -96, z: 96, radius: 22, height: 72 },
updates: { x: 96, z: 96, radius: 18, height: 72 },
};
const BLEND = 24;
// what the block update scene changes, a wall facing south
export const UPDATE_WALL = {
x: ZONES.updates.x - 8,
y: ZONES.updates.height + 1,
z: ZONES.updates.z,
width: 16,
height: 8,
};
// the field of blocks drawn with code, this many on a side
const VISUALS_SIZE = 20;
// pillars standing in the lake
const GLASS_PILLARS = 6;
// of the ground's top blocks
const PLANT_CHANCE = 0.12;
const LIGHT_CHANCE = 0.003;
// a tree grows in each TREE_CELL square with TREE_CHANCE
const TREE_CELL = 8;
const TREE_CHANCE = 0.5;
// how far leaves reach from the trunk
const LEAVES_REACH = 2;
// caves are where their noise is above this
const CAVE_THRESHOLD = 0.42;
// what the level is made of, as values with their default states. what the loaded mods have no block for is left out
export interface BenchBlocks {
// the level's biome, for its colors
biome: string;
stone: number;
// the ground's cover, see SurfaceJson in common/worldgen/biomes.ts
top: number;
filler: number;
filler_depth: number;
underwater: number;
log: number;
leaves?: number;
plants: number[];
glass?: number;
fluid?: number;
light?: number;
// blocks drawn with code, see client/rendering/visuals.ts
visuals: number[];
}
// visual_blocks are the numeric ids of the blocks drawn with code. the same mods give the same blocks
export function bench_blocks(visual_blocks: ReadonlySet<number>): BenchBlocks {
const all = EverythingRegistry.get_registry<BlockRegistry>("blocks")
.map((block, nid) => ({ block, nid, value: default_block_value(nid, block) }))
.filter(({ block, nid }) => block && nid !== AIR)
.sort((a, b) => a.block.id.localeCompare(b.block.id));
type Entry = typeof all[number];
const layer = ({ block }: Entry) => block.render_layer ?? "solid";
const cube = ({ block }: Entry) => (block.model ?? DEFAULT_MODEL) === DEFAULT_MODEL && !block.parts;
// one look that nothing changes
const plain = ({ block, nid }: Entry) =>
!block.states?.length && !block.variants && !block.fluid && !block.light_emission && !visual_blocks.has(nid);
const tinted = ({ block }: Entry, color: string) => block.tint?.color === color;
const by_id = (id: string | undefined) => all.find((b) => b.block.id === id);
const solid = all.filter((b) => plain(b) && cube(b) && layer(b) === "solid" && b.block.has_collision);
if (solid.length === 0) throw new Error("The benchmark needs a solid block to build its level with");
// what the world generator fills the ground with, and a biome with trees for its cover
const by_key = ([a]: [string, unknown], [b]: [string, unknown]) => a.localeCompare(b);
const settings = EverythingRegistry.entries<NoiseSettingsJson>("noise_settings").sort(by_key)[0]?.[1];
const biomes = EverythingRegistry.entries<Biome>("biomes").sort(by_key).map(([, biome]) => biome);
const biome = biomes.find((biome) => biome.trees) ?? biomes[0];
const stone = by_id(settings?.default_block) ?? solid[0];
const top = by_id(biome?.surface.top) ?? solid.find((b) => tinted(b, "grass")) ?? stone;
const filler = by_id(biome?.surface.filler) ?? stone;
const ground = [stone, top, filler];
const leaves = all.filter((b) => plain(b) && cube(b) && layer(b) === "cutout");
// what says it grows on the ground's top, with its default states
const plants = all.filter((b) =>
b.block.place_on && can_stand_on(b.block, top.block.id) && layer(b) === "cutout" && !cube(b) &&
!b.block.has_collision && !visual_blocks.has(b.nid)
);
// water rather than lava
const fluids = all.filter((b) => b.block.fluid && !b.block.light_emission);
return {
biome: biome?.id ?? "",
stone: stone.value,
top: top.value,
filler: filler.value,
filler_depth: biome?.surface.filler_depth ?? 3,
underwater: (by_id(biome?.surface.underwater_top) ?? filler).value,
log: (solid.find((b) => !ground.includes(b)) ?? stone).value,
leaves: (leaves.find((b) => tinted(b, "foliage")) ?? leaves[0])?.value,
plants: plants.map((b) => b.value),
glass: all.find((b) => plain(b) && cube(b) && layer(b) === "translucent")?.value,
fluid: (by_id(settings?.fluids[0]?.block) ?? fluids.find((b) => layer(b) === "translucent") ?? fluids[0])
?.value,
light: all.find((b) => (b.block.light_emission ?? 0) > 0 && !b.block.fluid)?.value,
visuals: all.filter((b) => visual_blocks.has(b.nid)).map((b) => b.value),
};
}
// the level's terrain, a chunk at a time. a chunk always comes out the same
export class BenchTerrain {
#blocks: BenchBlocks;
#hills = new OctaveNoise2D(SEED, "hills", 160, [1, 0.5, 0.25, 0.125]);
#mountains = new OctaveNoise2D(SEED, "mountains", 320, [1, 0.5, 0.25]);
#caves = new OctaveNoise3D(SEED, "caves", 40, [1, 0.5], 0.75);
constructor(blocks: BenchBlocks) {
this.#blocks = blocks;
}
// the y of the top block
height(x: number, z: number): number {
const mountains = Math.max(0, this.#mountains.sample(x, z));
let height = 68 + this.#hills.sample(x, z) * 16 + mountains * mountains * 140;
for (const zone of Object.values(ZONES)) {
const t = smoothstep(zone.radius, zone.radius + BLEND, Math.hypot(x - zone.x, z - zone.z));
height = zone.height + (height - zone.height) * t;
}
return Math.min(CHUNK_HEIGHT - 32, Math.round(height));
}
chunk(chunk_x: number, chunk_z: number): { blocks: Uint32Array; biomes: string[] } {
const b = this.#blocks;
const blocks = new Uint32Array(CHUNK_AREA * CHUNK_HEIGHT);
const random = new Alea(`${SEED}_${chunk_x}_${chunk_z}`);
const x0 = chunk_x * CHUNK_SIZE;
const z0 = chunk_z * CHUNK_SIZE;
// in world coordinates, only what's in this chunk
const set = (x: number, y: number, z: number, value: number, only_air = false) => {
const lx = x - x0;
const lz = z - z0;
if (lx < 0 || lx >= CHUNK_SIZE || lz < 0 || lz >= CHUNK_SIZE || y < 0 || y >= CHUNK_HEIGHT) return;
const index = y * CHUNK_AREA + lz * CHUNK_SIZE + lx;
if (!only_air || blocks[index] === AIR) blocks[index] = value;
};
for (let lz = 0; lz < CHUNK_SIZE; lz++) {
for (let lx = 0; lx < CHUNK_SIZE; lx++) {
const x = x0 + lx;
const z = z0 + lz;
const height = this.height(x, z);
const shore = height <= SEA_LEVEL + 1;
const cover = height <= SEA_LEVEL ? b.underwater : b.top;
const column = lz * CHUNK_SIZE + lx;
for (let y = 0; y <= height; y++) {
let value = y === height ? cover : y >= height - b.filler_depth ? b.filler : b.stone;
if (y > 4 && y < height - 4 && this.#caves.sample(x, y, z) > CAVE_THRESHOLD) value = AIR;
blocks[y * CHUNK_AREA + column] = value;
}
for (let y = height + 1; b.fluid !== undefined && y <= SEA_LEVEL; y++) {
blocks[y * CHUNK_AREA + column] = b.fluid;
}
if (shore || this.#in_zone(x, z, 4)) continue;
const above = (height + 1) * CHUNK_AREA + column;
const roll = random.next();
if (b.light !== undefined && roll < LIGHT_CHANCE) {
blocks[above] = b.light;
} else if (b.plants.length > 0 && roll < PLANT_CHANCE) {
blocks[above] = b.plants[Math.floor(random.next() * b.plants.length)];
}
}
}
this.#trees(chunk_x, chunk_z, set);
this.#features(set);
return { blocks, biomes: new Array(CHUNK_AREA).fill(b.biome) };
}
#in_zone(x: number, z: number, margin: number) {
return Object.values(ZONES).some((zone) => Math.hypot(x - zone.x, z - zone.z) < zone.radius + margin);
}
// every tree with blocks in this chunk, some grow from the chunks beside it
#trees(chunk_x: number, chunk_z: number, set: (x: number, y: number, z: number, v: number, air?: boolean) => void) {
const b = this.#blocks;
const cells = (chunk: number) => [
Math.floor((chunk * CHUNK_SIZE - LEAVES_REACH) / TREE_CELL),
Math.floor((chunk * CHUNK_SIZE + CHUNK_SIZE - 1 + LEAVES_REACH) / TREE_CELL),
];
const [first_x, last_x] = cells(chunk_x);
const [first_z, last_z] = cells(chunk_z);
for (let cell_z = first_z; cell_z <= last_z; cell_z++) {
for (let cell_x = first_x; cell_x <= last_x; cell_x++) {
const random = new Alea(`${SEED}_tree_${cell_x}_${cell_z}`);
if (random.next() > TREE_CHANCE) continue;
// away from the cell's edges, so leaves don't run into the next cell's tree
const x = cell_x * TREE_CELL + LEAVES_REACH +
Math.floor(random.next() * (TREE_CELL - LEAVES_REACH * 2));
const z = cell_z * TREE_CELL + LEAVES_REACH +
Math.floor(random.next() * (TREE_CELL - LEAVES_REACH * 2));
const trunk = 4 + Math.floor(random.next() * 3);
const ground = this.height(x, z);
if (ground <= SEA_LEVEL + 1 || this.#in_zone(x, z, 6)) continue;
for (let dy = 0; dy < trunk; dy++) set(x, ground + 1 + dy, z, b.log);
if (b.leaves === undefined) continue;
for (let dy = trunk - 2; dy <= trunk + 1; dy++) {
const reach = dy < trunk ? LEAVES_REACH : 1;
for (let dz = -reach; dz <= reach; dz++) {
for (let dx = -reach; dx <= reach; dx++) {
// rounded off at the corners
if (Math.abs(dx) === reach && Math.abs(dz) === reach) continue;
set(x + dx, ground + 1 + dy, z + dz, b.leaves, true);
}
}
}
}
}
}
// glass standing in the lake, and the field of visuals
#features(set: (x: number, y: number, z: number, value: number) => void) {
const b = this.#blocks;
const { lake, visuals } = ZONES;
for (let i = 0; b.glass !== undefined && i < GLASS_PILLARS; i++) {
const angle = (i / GLASS_PILLARS) * Math.PI * 2;
const x = lake.x + Math.round(Math.cos(angle) * lake.radius / 2);
const z = lake.z + Math.round(Math.sin(angle) * lake.radius / 2);
for (let y = lake.height + 1; y <= SEA_LEVEL + 12; y++) {
for (let dz = -1; dz <= 1; dz++) {
for (let dx = -1; dx <= 1; dx++) set(x + dx, y, z + dz, b.glass);
}
}
}
for (let i = 0; b.visuals.length > 0 && i < VISUALS_SIZE * VISUALS_SIZE; i++) {
const x = visuals.x - VISUALS_SIZE / 2 + (i % VISUALS_SIZE);
const z = visuals.z - VISUALS_SIZE / 2 + Math.floor(i / VISUALS_SIZE);
set(x, visuals.height + 1, z, b.visuals[i % b.visuals.length]);
}
}
}
+574
View File
@@ -0,0 +1,574 @@
// 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,
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_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}`,
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++];
const { blocks, biomes } = terrain.chunk(x, z);
this.#level.set_chunk(x, z, blocks, biomes);
}
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),
chunks_in_view: level_renderer.visible_chunks,
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;
}
+153
View File
@@ -0,0 +1,153 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// the render benchmark's results and how they're written out: a table to read, then the same as json, which
// tools/compare_benchmarks.ts reads to put runs side by side
// changes when the scenes or the level change, since runs of different versions don't compare
export const BENCHMARK_VERSION = 1;
// how fast and how smooth frames were, from the time between them. the lows are the fps of the frame that 99% (and
// 99.9%) of the others were faster than
export interface FrameStats {
frames: number;
fps: number;
median_fps: number;
low_1_fps: number;
low_01_fps: number;
p99_ms: number;
max_ms: number;
}
export interface TimeStats {
mean_ms: number;
p99_ms: number;
}
export interface SceneResult {
// frames as the display paces them
paced?: FrameStats;
// frames back to back, see render_debug.uncapped. only how many, the time between them says nothing since they
// come in bursts between the display's refreshes when the gpu is behind
uncapped_fps?: number;
// the main thread's and the gpu's time per frame while paced. the gpu's only with timestamp queries
cpu?: TimeStats;
gpu?: TimeStats;
// what the first paced frame drew, which runs of the same version should about agree on
draw_calls: number;
quads: number;
chunks_in_view: number;
entities_in_view: number;
}
// meshing every chunk of the level that can be
export interface MeshingResult {
chunks: number;
ms: number;
paced?: FrameStats;
}
export interface SystemInfo {
browser: string;
os: string;
user_agent: string;
cpu_threads: number;
// only chromium says, rounded down to a power of two and at most 8
memory_gb?: number;
gpu: string;
gpu_features: string[];
// whether the gpu times are there
timestamps: boolean;
canvas_format: string;
// the median fps where nothing is drawn, which is the display's refresh when the browser holds frames to it
refresh_hz?: number;
device_pixel_ratio: number;
screen: string;
// meshing workers, see ChunkWorkerPool
workers: number;
}
export interface BenchmarkReport {
version: number;
date: string;
system: SystemInfo;
// "id version"
mods: string[];
resolution: string;
level: { chunks: number; build_ms: number };
first_mesh: MeshingResult;
remesh: MeshingResult;
scenes: Record<string, SceneResult>;
}
export function frame_stats(intervals: number[]): FrameStats | undefined {
if (intervals.length === 0) return undefined;
const sorted = [...intervals].sort((a, b) => a - b);
const mean = sorted.reduce((sum, ms) => sum + ms, 0) / sorted.length;
return {
frames: sorted.length,
fps: 1000 / mean,
median_fps: 1000 / percentile(sorted, 0.5),
low_1_fps: 1000 / percentile(sorted, 0.99),
low_01_fps: 1000 / percentile(sorted, 0.999),
p99_ms: percentile(sorted, 0.99),
max_ms: sorted[sorted.length - 1],
};
}
export function time_stats(times: number[]): TimeStats | undefined {
if (times.length === 0) return undefined;
const sorted = [...times].sort((a, b) => a - b);
return { mean_ms: sorted.reduce((sum, ms) => sum + ms, 0) / sorted.length, p99_ms: percentile(sorted, 0.99) };
}
// the smallest value that at least q of them are at or under
function percentile(sorted: number[], q: number) {
return sorted[Math.min(sorted.length - 1, Math.max(0, Math.ceil(q * sorted.length) - 1))];
}
// markdown, to paste where it's read, with the whole report as json at the end
export function format_report(report: BenchmarkReport): string {
const { system, first_mesh, remesh } = report;
const fps = (value?: number) => value === undefined ? "-" : value.toFixed(1);
const ms = (value?: number) => value === undefined ? "-" : value.toFixed(2);
const seconds = (ms: number) => `${(ms / 1000).toFixed(2)} s`;
const meshing = ({ chunks, ms }: MeshingResult) => `${seconds(ms)} (${Math.round(chunks / ms * 1000)} chunks/s)`;
const memory = system.memory_gb ? `, ${system.memory_gb} GB` : "";
const refresh = system.refresh_hz ? `, ${system.refresh_hz} Hz` : "";
const lines = [
`## bworld render benchmark ${report.version}`,
"",
`${system.browser} on ${system.os}, ${system.gpu}`,
`${system.cpu_threads} threads${memory}${refresh}, drawn at ${report.resolution}, ${system.workers} mesh workers` +
(system.timestamps ? "" : ", no gpu timestamps"),
`${report.date}, mods: ${report.mods.join(", ") || "none"}`,
"",
"| scene | fps | 1% low | 0.1% low | uncapped fps | cpu ms | gpu ms | draw calls | quads |",
"|---|---:|---:|---:|---:|---:|---:|---:|---:|",
];
for (const [name, scene] of Object.entries(report.scenes)) {
const { paced } = scene;
lines.push(
`| ${name} | ${fps(paced?.fps)} | ${fps(paced?.low_1_fps)} | ${fps(paced?.low_01_fps)} | ` +
`${fps(scene.uncapped_fps)} | ${ms(scene.cpu?.mean_ms)} | ${ms(scene.gpu?.mean_ms)} | ` +
`${scene.draw_calls} | ${scene.quads.toLocaleString("en")} |`,
);
}
lines.push(
"",
`Meshing the level's ${first_mesh.chunks} chunks took ${meshing(first_mesh)} the first time and ` +
`${meshing(remesh)} again. Building it took ${seconds(report.level.build_ms)} of javascript.`,
"",
"```json",
JSON.stringify(report, (_, value) => typeof value === "number" ? Math.round(value * 100) / 100 : value),
"```",
);
return lines.join("\n");
}
// the report in what format_report wrote, or json on its own
export function parse_report(text: string): BenchmarkReport {
const json = text.match(/```json\n([\s\S]*?)\n```/)?.[1] ?? text;
return JSON.parse(json);
}
+18 -7
View File
@@ -28,6 +28,7 @@ import { PLAYER_MENU } from "$/common/protocol.ts";
import { type BlockRegistry, EverythingRegistry } from "$/common/everything_registry.ts";
import type { EntityJson } from "$/common/mod_data.ts";
import { tick_texture_animations } from "./texture_animations.ts";
import type { RenderBenchmark } from "./benchmark/benchmark.ts";
// holding the use button uses the held item on blocks again this often, like minecraft's 4 ticks
const USE_REPEAT_MS = 200;
@@ -55,6 +56,8 @@ export class Client {
// the entity or other player being looked at, closer than any block. hit_result is undefined then
entity_hit: Entity | undefined;
debugging = false;
// started from the f3 performance window
benchmark: RenderBenchmark | undefined;
// seconds of game time not ticked yet
#pending_time = 0;
@@ -143,21 +146,28 @@ export class Client {
InputManager.set_mouse_grabbed(false);
}
// one frame: input, as many ticks as are due, then drawing between the last tick and the next
// one frame: input, as many ticks as are due, then drawing between the last tick and the next. while the benchmark
// runs, it ticks and draws its own level instead and the world waits, so what's around the player doesn't change
// its numbers
run_frame(delta: number) {
if (this.#stopped) {
return;
}
const screen = this.screen;
this.screen?.on_tick(delta);
// a screen that closed itself just now, like chat on enter, had this frame's keys
this.#handle_keybinds(screen !== undefined && this.screen === undefined);
if (this.benchmark) {
this.benchmark.frame();
} else {
const screen = this.screen;
this.screen?.on_tick(delta);
// a screen that closed itself just now, like chat on enter, had this frame's keys
this.#handle_keybinds(screen !== undefined && this.screen === undefined);
}
this.#pending_time += delta;
let ticks = 0;
const stopped = profiler.section("ticks", () => {
while (this.#pending_time >= TICK_DELTA && ticks < MAX_TICKS_PER_FRAME) {
this.tick();
if (this.benchmark) this.benchmark.tick();
else this.tick();
if (this.#stopped) {
return true;
}
@@ -173,7 +183,8 @@ export class Client {
this.#pending_time = Math.min(this.#pending_time, TICK_DELTA);
}
this.game_renderer.render(this, this.#pending_time / TICK_DELTA);
if (this.benchmark) this.benchmark.render(this.#pending_time / TICK_DELTA);
else this.game_renderer.render(this, this.#pending_time / TICK_DELTA);
}
// one step of the game: what the server sent (chunks included), breaking, then every entity
+48 -1
View File
@@ -8,6 +8,8 @@ import { profiler, type SectionStats } from "$/client/profiler.ts";
import { canvas, gpu_timer, render_debug, render_stats } from "$/client/renderer/mod.ts";
import { RENDER_LAYERS } from "$/common/everything_registry.ts";
import { atlas_png } from "$/client/atlas.ts";
import { RenderBenchmark } from "$/client/benchmark/benchmark.ts";
import { format_report } from "$/client/benchmark/report.ts";
// how often the totals that go through every chunk are worked out again, so the overlay doesn't slow the frames it's
// measuring
@@ -17,6 +19,9 @@ const CHUNK_STATS_MS = 1000;
export class DebugOverlay {
#chunk_stats = { meshed: 0, bytes: 0 };
#chunk_stats_time = -Infinity;
// the last benchmark's, see client/benchmark/
#benchmark_report: string | undefined;
#benchmark_status = "";
render(client: Client) {
this.#render_performance(client);
@@ -54,6 +59,9 @@ export class DebugOverlay {
DebugUI.begin("Performance", 320, 10, 340, 600);
const copy = DebugUI.button("Copy");
if (DebugUI.button("Run the render benchmark")) this.#start_benchmark(client);
if (this.#benchmark_report && DebugUI.button("Copy the benchmark's results")) this.#copy_benchmark();
if (this.#benchmark_status) DebugUI.text(this.#benchmark_status);
// what's shown, for the copy button
const lines: string[] = [];
const text = (line: string) => {
@@ -104,10 +112,36 @@ export class DebugOverlay {
if (copy) {
const switches = { ...render_debug, ...level_renderer.draw };
lines.push(Object.entries(switches).map(([key, on]) => ` ${key}: ${on}`).join("\n"));
navigator.clipboard?.writeText(lines.join("\n")).catch(() => {});
copy_text(lines.join("\n")).catch(() => {});
}
}
#start_benchmark(client: Client) {
try {
client.benchmark = new RenderBenchmark(client.game_renderer, client.connection.mods, (result) => {
client.benchmark = undefined;
if (typeof result === "string") {
this.#benchmark_status = result;
return;
}
this.#benchmark_report = format_report(result);
console.log(this.#benchmark_report);
this.#copy_benchmark();
});
this.#benchmark_status = "";
} catch (e) {
this.#benchmark_status = e instanceof Error ? e.message : String(e);
}
}
// right after the benchmark, firefox and safari only let the page copy from a click
#copy_benchmark() {
copy_text(this.#benchmark_report!).then(
() => this.#benchmark_status = "The benchmark's results are on the clipboard",
() => this.#benchmark_status = "Click above to copy the benchmark's results",
);
}
// meshed chunks and what their meshes take on the gpu, once a second
#count_chunks(client: Client) {
const now = performance.now();
@@ -146,3 +180,16 @@ export class DebugOverlay {
}
}
}
// pages that aren't https or localhost have no clipboard api, like a server on another computer, but the old way
// still copies from a click
function copy_text(text: string): Promise<void> {
if (navigator.clipboard) return navigator.clipboard.writeText(text);
const area = document.createElement("textarea");
area.value = text;
document.body.append(area);
area.select();
const copied = document.execCommand("copy");
area.remove();
return copied ? Promise.resolve() : Promise.reject(new Error("Couldn't copy"));
}
+25
View File
@@ -202,6 +202,11 @@ export class ClientLevel {
if (!this.#in_storage_range(x, z)) {
return;
}
this.set_chunk(x, z, blocks, biomes);
}
// a whole chunk, replacing it if it was already here. blocks are this client's numeric ids with their state bits
set_chunk(x: number, z: number, blocks: Uint32Array, biomes: string[]) {
const biome_colors = new Uint32Array(CHUNK_AREA * 3);
biomes.forEach((biome, column) => {
biome_colors[column] = grass_color(biome);
@@ -590,10 +595,30 @@ export class ClientLevel {
// meshes asked of the workers that haven't come back, for the f3 performance window
meshes_in_flight = 0;
// the rest wait for the next frame. chunks from the server come a few at a time, but the benchmark's level has every
// chunk at once, and each request copies its 3x3 chunks
max_meshes_in_flight = Infinity;
// dirty chunks that can be meshed and the meshes the workers are on, 0 once every chunk that can be is meshed
get meshes_pending() {
let pending = this.meshes_in_flight;
for (const chunk of this.#dirty) {
if (this.can_mesh(chunk)) pending += 1;
}
return pending;
}
// meshes every chunk again, for the benchmark to time
remesh_all() {
for (const chunk of this.chunks.values()) this.#mark_dirty(chunk);
}
// sends every dirty chunk that can be meshed to the workers
request_meshes(camera: Camera) {
for (const chunk of this.#dirty) {
if (this.meshes_in_flight >= this.max_meshes_in_flight) {
break;
}
if (!this.can_mesh(chunk)) {
continue;
}
+42 -1
View File
@@ -21,6 +21,7 @@ import {
init_font,
init_window,
load_texture,
render_debug,
resize_canvas,
} from "./renderer/mod.ts";
import { is_stopped, show_fatal_error } from "./fatal.ts";
@@ -37,6 +38,10 @@ function confirm_leaving(confirm: boolean) {
self.onbeforeunload = confirm ? (event) => event.preventDefault() : null;
}
// with render_debug.uncapped, the most frames between two of the display's refreshes. it's the highest fps that shows,
// 960 on a 60 hz display, and what the gpu can be behind by
const UNCAPPED_FRAMES_PER_REFRESH = 16;
class ClientLoop {
running = false;
last_time = 0;
@@ -53,6 +58,7 @@ class ClientLoop {
}
});
this.#next_task.port1.onmessage = () => this.loop(performance.now());
this.running = true;
const now = performance.now();
this.last_time = now;
@@ -84,6 +90,41 @@ class ClientLoop {
console.log("Game started");
}
// with render_debug.uncapped: frames since the display last refreshed, and whether the next one waits for it
#frames_this_refresh = 0;
#waiting_for_refresh = false;
#refresh_requested = false;
#next_task = new MessageChannel();
// with the display's refresh, or with render_debug.uncapped right away, so frames aren't held to vsync and show what
// they cost. up to UNCAPPED_FRAMES_PER_REFRESH, then it waits for the next refresh, which the browser holds back
// while the gpu is behind, so frames the gpu can't keep up with don't pile up. the browser saying a frame is done
// can't be waited on instead, firefox only says so every 100 ms when nothing else is sent to the gpu
#next_frame() {
if (!render_debug.uncapped) {
requestAnimationFrame((time) => this.loop(time));
return;
}
if (!this.#refresh_requested) {
this.#refresh_requested = true;
requestAnimationFrame(() => {
this.#refresh_requested = false;
this.#frames_this_refresh = 0;
if (this.#waiting_for_refresh) {
this.#waiting_for_refresh = false;
this.loop(performance.now());
}
});
}
this.#frames_this_refresh += 1;
if (this.#frames_this_refresh < UNCAPPED_FRAMES_PER_REFRESH) {
// a task of its own, so input and the workers' messages get handled in between
this.#next_task.port2.postMessage(null);
} else {
this.#waiting_for_refresh = true;
}
}
loop(time: number) {
if (!this.running || is_stopped()) {
return;
@@ -115,7 +156,7 @@ class ClientLoop {
InputManager.update();
this.last_time = time;
requestAnimationFrame((time) => this.loop(time));
this.#next_frame();
}
}
+18 -2
View File
@@ -12,6 +12,14 @@ export interface SectionStats {
max: number;
}
// one frame, in ms
export interface FrameSample {
// since the frame before started
interval: number;
// the javascript part
frame: number;
}
// what the client spends its time on, for the f3 performance window. each section is timed on the cpu, and on the gpu
// too when the renderer can, see gpu_section
class Profiler {
@@ -20,11 +28,14 @@ class Profiler {
frame: SectionStats = { avg: 0, max: 0 };
// the time between frames, which is what the player feels, and the javascript part of it
interval: SectionStats & { fps: number } = { avg: 0, max: 0, fps: 0 };
// every frame, while something reads them, like the benchmark
samples: FrameSample[] | undefined;
#window_start = performance.now();
#frames = 0;
#frame_start = 0;
#last_frame_start = 0;
#interval = 0;
#sums = new Map<string, number>();
#maxes = new Map<string, number>();
// this frame's time per section, added to the sums when it ends
@@ -32,14 +43,19 @@ class Profiler {
begin_frame() {
const now = performance.now();
if (this.#last_frame_start > 0) this.#add("interval", now - this.#last_frame_start);
if (this.#last_frame_start > 0) {
this.#interval = now - this.#last_frame_start;
this.#add("interval", this.#interval);
}
this.#last_frame_start = this.#frame_start = now;
this.#this_frame.clear();
}
end_frame() {
const now = performance.now();
this.#add("frame", now - this.#frame_start);
const frame = now - this.#frame_start;
this.#add("frame", frame);
this.samples?.push({ interval: this.#interval, frame });
for (const [name, ms] of this.#this_frame) this.#add(`cpu:${name}`, ms);
this.#frames += 1;
if (now - this.#window_start >= WINDOW_MS) this.#publish(now);
+26 -6
View File
@@ -99,8 +99,9 @@ let pending_destroy: GPUBuffer[] = [];
// switches for finding out what a frame costs, see the f3 performance window. msaa is changed at the start of the next
// frame. split_passes gives each section (see gpu_section) passes of its own so the gpu times them apart, which costs
// a little since every pass loads and stores the render targets
export const render_debug = { msaa: false, split_passes: false };
// a little since every pass loads and stores the render targets. uncapped starts frames back to back instead of with
// the display's refresh, see the game loop in main.ts
export const render_debug = { msaa: false, split_passes: false, uncapped: false };
// what was drawn, for the last whole frame
export interface RenderStats {
draw_calls: number;
@@ -111,6 +112,11 @@ const empty_stats = (): RenderStats => ({ draw_calls: 0, passes: 0, quads: { sol
export let render_stats = empty_stats();
let frame_stats = empty_stats();
export let gpu_timer: GpuTimer | undefined;
// what the gpu is, for the benchmark's report
export let adapter_info: GPUAdapterInfo | undefined;
// see set_canvas_size
let fixed_canvas_size: { width: number; height: number } | undefined;
let resize_pending = false;
// what the passes starting now are timed as
let gpu_label = "other";
@@ -289,6 +295,7 @@ export async function init_window(canvas_element: HTMLCanvasElement) {
if (!adapter) {
throw new Error("No WebGPU adapter found");
}
adapter_info = adapter.info;
device = await adapter.requestDevice({
requiredFeatures: adapter.features.has("timestamp-query") ? ["timestamp-query"] : [],
});
@@ -365,6 +372,10 @@ export function update_lightmap(daylight = 1) {
}
export function begin_drawing() {
if (resize_pending) {
resize_pending = false;
resize_canvas();
}
const wanted_samples = render_debug.msaa ? SAMPLE_COUNT : 1;
if (wanted_samples !== sample_count) {
sample_count = wanted_samples;
@@ -644,16 +655,25 @@ export function destroy_buffer(buffer: GPUBuffer) {
}
export function resize_canvas() {
const width = self.innerWidth;
const height = self.innerHeight;
const width = fixed_canvas_size?.width ?? self.innerWidth;
const height = fixed_canvas_size?.height ?? self.innerHeight;
// a fixed size is shown as big as it fits in the window
const scale = Math.min(self.innerWidth / width, self.innerHeight / height);
if (canvas.width !== width || canvas.height !== height) {
canvas.width = width;
canvas.height = height;
canvas.style.width = canvas.width + "px";
canvas.style.height = canvas.height + "px";
// render targets get recreated at the start of the next frame
}
canvas.style.width = width * scale + "px";
canvas.style.height = height * scale + "px";
}
// frames are drawn at this size whatever the window's, like the benchmark's, or at the window's again when it's
// undefined. it changes at the start of the next frame, since resizing the canvas takes away the texture being drawn to
export function set_canvas_size(size: { width: number; height: number } | undefined) {
fixed_canvas_size = size;
resize_pending = true;
}
export function get_current_texture(): GPUTexture | null {
+7
View File
@@ -17,6 +17,9 @@ export class GpuTimer {
// ms per frame by label, averaged over the last window
results = new Map<string, number>();
total = 0;
// every timed frame's total, while something reads them, like the benchmark. a frame goes to the array that was
// here when it was submitted, however late its time comes back
samples: number[] | undefined;
#device: GPUDevice;
#query_set: GPUQuerySet | undefined;
@@ -82,16 +85,20 @@ export class GpuTimer {
this.#free.push(buffer);
return;
}
const samples = this.samples;
buffer.mapAsync(GPUMapMode.READ, 0, labels.length * 16).then(() => {
const times = new BigUint64Array(buffer.getMappedRange(0, labels.length * 16));
const frame = new Map<string, number>();
let total = 0;
labels.forEach((label, i) => {
const ms = Math.max(0, Number(times[i * 2 + 1] - times[i * 2])) / 1e6;
frame.set(label, (frame.get(label) ?? 0) + ms);
total += ms;
});
buffer.unmap();
this.#free.push(buffer);
this.#add_frame(frame);
samples?.push(total);
}).catch(() => {
// the device was lost, nothing to time anymore
});
+30 -19
View File
@@ -2,6 +2,8 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import type { Client } from "$/client/client.ts";
import type { Camera } from "$/client/camera.ts";
import type { ClientLevel } from "$/client/level/client_level.ts";
import {
begin_mode_3d,
canvas,
@@ -37,8 +39,8 @@ export class GameRenderer {
#lightmap_daylight = -1;
// sky color and sky light for the time of day
#setup_sky(client: Client, partial_tick: number) {
const light = daylight(client.level.time + partial_tick);
#setup_sky(level: ClientLevel, partial_tick: number) {
const light = daylight(level.time + partial_tick);
const [r, g, b] = DAY_SKY.map((day, i) => NIGHT_SKY[i] + (day - NIGHT_SKY[i]) * light);
clear_background(r, g, b, 1);
@@ -65,23 +67,8 @@ export class GameRenderer {
// partial_tick is how far this frame is between the last tick and the next, entities are drawn in between
render(client: Client, partial_tick: number) {
const camera = client.camera;
camera.setup(client.player, partial_tick);
this.#setup_sky(client, partial_tick);
set_render_time(client.level.ticks + partial_tick);
begin_mode_3d(camera);
const level = this.level_renderer;
level.render_opaque(client.level, camera);
profiler.section("entities", () => {
level.render_destroy_progress(client.level, client.game_mode);
level.render_block_outline(client.level, client.hit_result, camera);
level.render_entities(client.level, camera, client.player, partial_tick);
});
profiler.section("visuals", () => level.render_visuals(client.level, camera, partial_tick));
profiler.section("translucent", () => level.render_translucent(client.level, camera));
profiler.section("nameplates", () => render_nameplates(client.level, camera, client.player, partial_tick));
end_mode_3d();
client.camera.setup(client.player, partial_tick);
this.render_level(client.level, client.camera, partial_tick, client);
profiler.section("hand", () => this.hand.render(client.player, partial_tick));
this.#render_underwater(client);
@@ -93,4 +80,28 @@ export class GameRenderer {
profiler.section("debug overlay", () => this.debug_overlay.render(client));
}
}
// the sky and the level from the camera. with a viewer, the camera is in their player, who isn't drawn, and what
// they're breaking and looking at shows. the benchmark draws its level without one
render_level(
level: ClientLevel,
camera: Camera,
partial_tick: number,
viewer?: Pick<Client, "player" | "game_mode" | "hit_result">,
) {
this.#setup_sky(level, partial_tick);
set_render_time(level.ticks + partial_tick);
begin_mode_3d(camera);
const renderer = this.level_renderer;
renderer.render_opaque(level, camera);
profiler.section("entities", () => {
renderer.render_destroy_progress(level, viewer?.game_mode);
renderer.render_block_outline(level, viewer?.hit_result, camera);
renderer.render_entities(level, camera, viewer?.player, partial_tick);
});
profiler.section("visuals", () => renderer.render_visuals(level, camera, partial_tick));
profiler.section("translucent", () => renderer.render_translucent(level, camera));
profiler.section("nameplates", () => render_nameplates(level, camera, viewer?.player, partial_tick));
end_mode_3d();
}
}
+4 -4
View File
@@ -124,7 +124,7 @@ export class LevelRenderer {
}
// every entity in view but the one the camera is in
render_entities(level: ClientLevel, camera: Camera, camera_entity: Entity, partial_tick: number) {
render_entities(level: ClientLevel, camera: Camera, camera_entity: Entity | undefined, partial_tick: number) {
this.#drawn_entities = 0;
if (!this.draw.entities) return;
flush_batch();
@@ -186,10 +186,10 @@ export class LevelRenderer {
// the cracks on the block being broken, and on the ones machines are breaking, drawn over their models' faces like
// minecraft's crumbling overlay, so a slab or a plant cracks where it is and not on a whole cube around it
render_destroy_progress(level: ClientLevel, game_mode: MultiPlayerGameMode) {
render_destroy_progress(level: ClientLevel, game_mode: MultiPlayerGameMode | undefined) {
for (const { x, y, z, stage } of level.break_progress.values()) this.#draw_cracks(level, x, y, z, stage);
const block = game_mode.destroy_pos;
if (!block) {
const block = game_mode?.destroy_pos;
if (!game_mode || !block) {
return;
}
const progress = Math.max(0, Math.min(1, game_mode.destroy_progress / game_mode.destroy_time));
+6 -1
View File
@@ -24,7 +24,12 @@ const TEXT_LIFT = 0.002;
// names over other players' heads, always facing the camera like minecraft's. drawn after translucent terrain since
// the plate is see through. they're full bright, so they can be read in the dark
export function render_nameplates(level: ClientLevel, camera: Camera, camera_entity: Entity, partial_tick: number) {
export function render_nameplates(
level: ClientLevel,
camera: Camera,
camera_entity: Entity | undefined,
partial_tick: number,
) {
const cos_yaw = Math.cos(camera.yaw);
const sin_yaw = Math.sin(camera.yaw);
const cos_pitch = Math.cos(camera.pitch);
+75
View File
@@ -0,0 +1,75 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// the render benchmark's numbers, its report, and its level, which has to be the same in every run for runs to compare
import { assert, assertEquals } from "@std/assert";
import { type BenchmarkReport, format_report, frame_stats, parse_report } from "$/client/benchmark/report.ts";
import { bench_blocks, BenchTerrain, ZONES } from "$/client/benchmark/bench_level.ts";
import { type BlockRegistry, EverythingRegistry } from "$/common/everything_registry.ts";
import { AIR, CHUNK_SIZE, ID_MASK } from "$/common/constants.ts";
import { test_game } from "./helpers.ts";
Deno.test("the lows are the fps of the slowest frames", () => {
// 2% of the frames take five times as long
const stats = frame_stats([...new Array(980).fill(10), ...new Array(20).fill(50)])!;
assertEquals(stats.frames, 1000);
assertEquals(stats.median_fps, 100);
assertEquals(stats.low_1_fps, 20);
assertEquals(stats.low_01_fps, 20);
assertEquals(stats.max_ms, 50);
assert(stats.fps < 100 && stats.fps > 20, "the average is in between");
assertEquals(frame_stats([]), undefined);
});
Deno.test("a report reads back from what was copied", () => {
const scene = { draw_calls: 10, quads: 1000, chunks_in_view: 4, entities_in_view: 0 };
const report: BenchmarkReport = {
version: 1,
date: "2026-01-01T00:00:00.000Z",
system: {
browser: "Firefox 150.0",
os: "Linux x86_64",
user_agent: "",
cpu_threads: 8,
gpu: "unknown gpu",
gpu_features: [],
timestamps: false,
canvas_format: "bgra8unorm",
device_pixel_ratio: 1,
screen: "1920x1080",
workers: 4,
},
mods: ["bworld 1.0.0"],
resolution: "1920x1080",
level: { chunks: 4, build_ms: 12.5 },
first_mesh: { chunks: 1, ms: 100 },
remesh: { chunks: 1, ms: 50 },
scenes: { sky: { ...scene, paced: frame_stats([16, 16, 18]) }, terrain: scene },
};
const text = format_report(report);
assert(text.includes("| terrain |"), "a table to read");
const read = parse_report(text);
assertEquals(read.scenes.terrain, scene);
assertEquals(read.system, report.system);
assertEquals(read.scenes.sky.paced!.fps.toFixed(2), report.scenes.sky.paced!.fps.toFixed(2));
});
Deno.test("the benchmark's level comes out the same every time, with terrain in every layer", async () => {
await test_game("mods");
const blocks = bench_blocks(new Set());
const chunk = (x: number, z: number) => new BenchTerrain(blocks).chunk(x, z).blocks;
const lake = [Math.floor(ZONES.lake.x / CHUNK_SIZE), Math.floor(ZONES.lake.z / CHUNK_SIZE)] as const;
const near_lake = [lake[0] + 3, lake[1] + 3] as const;
assertEquals(chunk(0, 0), chunk(0, 0));
assertEquals(chunk(...lake), chunk(...lake));
const registry = EverythingRegistry.get_registry<BlockRegistry>("blocks");
const layers = new Set<string>();
for (const [x, z] of [[0, 0], lake, near_lake, [5, 5]] as const) {
for (const value of chunk(x, z)) {
const nid = value & ID_MASK;
if (nid !== AIR) layers.add(registry[nid].render_layer ?? "solid");
}
}
assertEquals([...layers].sort(), ["cutout", "solid", "translucent"]);
});
+74
View File
@@ -0,0 +1,74 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// puts render benchmark runs side by side, from what the benchmark copied (see client/benchmark/benchmark.ts) saved
// to a file per run. a table for each number, with a column per run and how far each is from the first run
// deno run --allow-read tools/compare_benchmarks.ts chrome.md firefox.md ...
import {
type BenchmarkReport,
type MeshingResult,
parse_report,
type SceneResult,
} from "../client/benchmark/report.ts";
const runs = Deno.args.map((path) => ({ path, report: parse_report(Deno.readTextFileSync(path)) }));
if (runs.length === 0) {
console.error("Give it the files the benchmark's results were saved to");
Deno.exit(1);
}
if (new Set(runs.map(({ report }) => report.version)).size > 1) {
console.warn("These are from different versions of the benchmark, their scenes aren't the same\n");
}
const labels = runs.map(({ report }) => `${report.system.browser}, ${report.system.os}`);
// each scene once, in the order they ran
const scenes = [...new Set(runs.flatMap(({ report }) => Object.keys(report.scenes)))];
const SCENE_NUMBERS: { title: string; value: (scene: SceneResult) => number | undefined }[] = [
{ title: "uncapped fps", value: (scene) => scene.uncapped_fps },
{ title: "fps", value: (scene) => scene.paced?.fps },
{ title: "1% low fps", value: (scene) => scene.paced?.low_1_fps },
{ title: "cpu ms per frame", value: (scene) => scene.cpu?.mean_ms },
{ title: "gpu ms per frame", value: (scene) => scene.gpu?.mean_ms },
];
// a value and how far it is from the first run's
function cell(value: number | undefined, first: number | undefined, digits: number) {
if (value === undefined) return "-";
if (first === undefined || first === 0 || value === first) return value.toFixed(digits);
const change = (value / first - 1) * 100;
return `${value.toFixed(digits)} (${change > 0 ? "+" : ""}${change.toFixed(0)}%)`;
}
function table(title: string, rows: [string, (report: BenchmarkReport) => number | undefined][], digits: number) {
console.log(`### ${title}\n`);
console.log(`| | ${labels.join(" | ")} |`);
console.log(`|---|${labels.map(() => "---:").join("|")}|`);
for (const [name, value] of rows) {
const first = value(runs[0].report);
console.log(`| ${name} | ${runs.map(({ report }) => cell(value(report), first, digits)).join(" | ")} |`);
}
console.log();
}
for (const { title, value } of SCENE_NUMBERS) {
const digits = title.includes("ms") ? 2 : 1;
table(title, scenes.map((name) => [name, (report) => report.scenes[name] && value(report.scenes[name])]), digits);
}
const chunks_per_second = ({ chunks, ms }: MeshingResult) => chunks / ms * 1000;
table("meshing, chunks per second", [
["first time", (report) => chunks_per_second(report.first_mesh)],
["again", (report) => chunks_per_second(report.remesh)],
], 0);
// runs of one version draw about the same, a few chunks can be meshed a frame later, unless something like a mod
// differed
for (const name of scenes) {
const quads = runs.map(({ report }) => report.scenes[name]?.quads ?? 0);
if (Math.max(...quads) > Math.min(...quads) * 1.01) {
console.warn(`The runs didn't draw the same in ${name}: ${quads.join(", ")} quads`);
}
}
for (const { path, report } of runs) {
console.log(`${path}: ${report.system.gpu}, ${report.system.cpu_threads} threads, ${report.mods.join(", ")}`);
}