Rendering performace on F3

This commit is contained in:
2026-10-02 21:21:19 -03:00
parent 1511338a23
commit dcaf878254
9 changed files with 426 additions and 53 deletions
+13 -6
View File
@@ -9,6 +9,7 @@ import { Camera } from "./camera.ts";
import { Options } from "./options.ts";
import { MultiPlayerGameMode } from "./game_mode.ts";
import { ClientPacketListener } from "./packet_listener.ts";
import { profiler } from "./profiler.ts";
import { GameRenderer } from "./rendering/game_renderer.ts";
import { ChatComponent } from "./gui/chat_component.ts";
import { GuiMenuScreen, GuiScreen } from "./gui/gui_screen.ts";
@@ -148,13 +149,19 @@ export class Client {
this.#pending_time += delta;
let ticks = 0;
while (this.#pending_time >= TICK_DELTA && ticks < MAX_TICKS_PER_FRAME) {
this.tick();
if (this.#stopped) {
return;
const stopped = profiler.section("ticks", () => {
while (this.#pending_time >= TICK_DELTA && ticks < MAX_TICKS_PER_FRAME) {
this.tick();
if (this.#stopped) {
return true;
}
this.#pending_time -= TICK_DELTA;
ticks += 1;
}
this.#pending_time -= TICK_DELTA;
ticks += 1;
return false;
});
if (stopped) {
return;
}
if (ticks === MAX_TICKS_PER_FRAME) {
this.#pending_time = Math.min(this.#pending_time, TICK_DELTA);
+76 -1
View File
@@ -1,10 +1,15 @@
import type { Client } from "$/client/client.ts";
import { DebugUI } from "$/client/debug_ui.ts";
import { format_clock } from "$/common/time.ts";
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";
// f3: every entity's fields, editable
// f3: every entity's fields, editable, and what frames cost
export class DebugOverlay {
render(client: Client) {
this.#render_performance(client);
DebugUI.begin("Entities", 10, 10, 300);
DebugUI.text(`${format_clock(client.level.time)} (tick ${client.level.time})`);
DebugUI.separator();
@@ -24,6 +29,76 @@ export class DebugOverlay {
DebugUI.end();
}
// where a frame's time goes. if the time between frames is much more than the javascript takes, the frame is
// waiting on the gpu (or vsync), and the gpu times say what it's doing
#render_performance(client: Client) {
const ms = (value: number) => value.toFixed(2);
const stats = (name: string, { avg, max }: SectionStats) => `${name}: ${ms(avg)} ms (max ${ms(max)})`;
const { interval, frame } = profiler;
DebugUI.begin("Performance", 320, 10, 340, 600);
const copy = DebugUI.button("Copy");
// what's shown, for the copy button
const lines: string[] = [];
const text = (line: string) => {
lines.push(line);
DebugUI.text(line);
};
const separator = () => {
lines.push("");
DebugUI.separator();
};
const msaa = render_debug.msaa ? "4x" : "off";
text(`${interval.fps.toFixed(0)} fps, ${canvas.width}x${canvas.height}, msaa ${msaa}`);
text(stats("between frames", interval));
text(stats("javascript", frame));
text(`waiting: ${ms(Math.max(0, interval.avg - frame.avg))} ms`);
separator();
text("cpu per frame");
for (const [name, section] of profiler.cpu) text(stats(` ${name}`, section));
separator();
if (!gpu_timer?.supported) {
text("gpu: no timestamp-query on this device");
} else {
text(`gpu per frame: ${ms(gpu_timer.total)} ms`);
if (!render_debug.split_passes) text(" (split_passes times each section)");
for (const [label, time] of gpu_timer.results) text(` ${label}: ${ms(time)} ms`);
}
separator();
const { draw_calls, passes, quads } = render_stats;
text(`draw calls: ${draw_calls}, passes: ${passes}`);
for (const layer of RENDER_LAYERS) text(` ${layer}: ${quads[layer].toLocaleString()} quads`);
const level = client.level;
const level_renderer = client.game_renderer.level_renderer;
let meshed = 0;
let waiting = 0;
let bytes = 0;
for (const chunk of level.chunks.values()) {
const meshes = Object.values(chunk.meshes);
if (meshes.length > 0) meshed += 1;
if (chunk.dirty) waiting += 1;
for (const mesh of meshes) bytes += mesh.vertex_buffer.size + (mesh.index_buffer?.size ?? 0);
}
text(`chunks: ${level.chunks.size} loaded, ${meshed} meshed, ${level_renderer.visible_chunks} in view`);
text(` ${waiting} waiting to mesh, ${level.meshes_in_flight} meshing`);
text(` meshes: ${(bytes / 1024 / 1024).toFixed(1)} MB`);
separator();
text("switches");
this.#render_fields(render_debug);
this.#render_fields(level_renderer.draw);
DebugUI.end();
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(() => {});
}
}
// deno-lint-ignore no-explicit-any
#render_fields(object: any) {
for (const key in object) {
+5
View File
@@ -450,6 +450,9 @@ export class ClientLevel {
return true;
}
// meshes asked of the workers that haven't come back, for the f3 performance window
meshes_in_flight = 0;
// sends every dirty chunk that can be meshed to the workers
request_meshes(camera: Camera) {
for (const chunk of this.chunks.values()) {
@@ -468,6 +471,7 @@ export class ClientLevel {
biome_colors.push(neighbor?.biome_colors ?? null);
}
}
this.meshes_in_flight += 1;
this.workers.post({
type: "mesh",
chunk_x: chunk.x,
@@ -512,6 +516,7 @@ export class ClientLevel {
}
#on_meshed(message: Extract<FromChunkWorker, { type: "meshed" }>) {
this.meshes_in_flight -= 1;
const chunk = this.get_chunk(message.chunk_x, message.chunk_z);
// unloaded, or remeshed again since this was requested
if (!chunk || chunk.mesh_version !== message.version) {
+5 -2
View File
@@ -22,6 +22,7 @@ import { download_mods, load_client_mods, set_mods_client } from "./mods.ts";
import type { GuiScreen } from "./gui/gui_screen.ts";
import { TitleScreen } from "./gui/title_screen.ts";
import { DisconnectedScreen } from "./gui/disconnected_screen.ts";
import { profiler } from "./profiler.ts";
// runs whatever is showing every frame: a menu screen before joining (and after leaving), or the game
export // while playing, the browser asks before leaving the page. sprinting is ctrl and walking is w, and ctrl+w closes the
@@ -84,7 +85,8 @@ class ClientLoop {
const delta = (time - this.last_time) / 1000;
begin_drawing();
profiler.begin_frame();
profiler.section("begin frame", begin_drawing);
clear_background(0.69, 0.8, 1, 1.0);
if (this.client) {
this.client.run_frame(delta);
@@ -92,7 +94,8 @@ class ClientLoop {
this.screen.on_tick(delta);
this.screen.on_render();
}
end_drawing();
profiler.section("submit", end_drawing);
profiler.end_frame();
this.frame_count += 1;
const now = performance.now();
+76
View File
@@ -0,0 +1,76 @@
import { gpu_section } from "./renderer/mod.ts";
// how long the numbers are averaged over, so they hold still long enough to read
const WINDOW_MS = 1000;
export interface SectionStats {
// per frame, over the last window
avg: number;
max: 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 {
// what the last window came to, in ms
cpu = new Map<string, SectionStats>();
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 };
#window_start = performance.now();
#frames = 0;
#frame_start = 0;
#last_frame_start = 0;
#sums = new Map<string, number>();
#maxes = new Map<string, number>();
// this frame's time per section, added to the sums when it ends
#this_frame = new Map<string, number>();
begin_frame() {
const now = performance.now();
if (this.#last_frame_start > 0) this.#add("interval", now - this.#last_frame_start);
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);
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);
}
// runs fn as a named part of the frame. the gpu work it records is timed under the same name
section<T>(name: string, fn: () => T): T {
gpu_section(name);
const start = performance.now();
try {
return fn();
} finally {
this.#this_frame.set(name, (this.#this_frame.get(name) ?? 0) + performance.now() - start);
}
}
#add(key: string, ms: number) {
this.#sums.set(key, (this.#sums.get(key) ?? 0) + ms);
this.#maxes.set(key, Math.max(this.#maxes.get(key) ?? 0, ms));
}
#publish(now: number) {
const frames = Math.max(1, this.#frames);
const stats = (key: string) => ({ avg: (this.#sums.get(key) ?? 0) / frames, max: this.#maxes.get(key) ?? 0 });
this.frame = stats("frame");
this.interval = { ...stats("interval"), fps: this.#frames * 1000 / (now - this.#window_start) };
this.cpu = new Map(
[...this.#sums.keys()].filter((key) => key.startsWith("cpu:")).map((key) => [key.slice(4), stats(key)]),
);
this.#sums.clear();
this.#maxes.clear();
this.#frames = 0;
this.#window_start = now;
}
}
export const profiler = new Profiler();
+103 -25
View File
@@ -2,6 +2,7 @@ import type { Camera } from "../camera.ts";
import { mat4 } from "gl-matrix";
import type { RenderLayer } from "$/common/everything_registry.ts";
import { TERRAIN_VERTEX_BYTES } from "../workers/chunk_messages.ts";
import { GpuTimer } from "./gpu_timing.ts";
export let device: GPUDevice;
export let canvas: HTMLCanvasElement;
@@ -11,7 +12,11 @@ const VERTS_PER_SPRITE = 6;
const FLOATS_PER_VERT = 9;
const VERTEX_STRIDE = FLOATS_PER_VERT * 4;
// msaa when it's turned on in the f3 performance window. off by default like minecraft and sodium, it's costly at
// large window sizes
const SAMPLE_COUNT = 4;
// what the pipelines and render targets were made for
let sample_count = 1;
const DEPTH_FORMAT: GPUTextureFormat = "depth24plus";
// dynamic uniform offsets have to be 256 aligned
@@ -73,6 +78,23 @@ let pending_depth_clear = false;
let scissor: { x: number; y: number; width: number; height: number } | undefined;
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 };
// what was drawn, for the last whole frame
export interface RenderStats {
draw_calls: number;
passes: number;
quads: Record<RenderLayer, number>;
}
const empty_stats = (): RenderStats => ({ draw_calls: 0, passes: 0, quads: { solid: 0, cutout: 0, translucent: 0 } });
export let render_stats = empty_stats();
let frame_stats = empty_stats();
export let gpu_timer: GpuTimer | undefined;
// what the passes starting now are timed as
let gpu_label = "other";
const shader_src = /* wgsl */ `
struct Uniforms {
mvp: mat4x4<f32>,
@@ -151,8 +173,12 @@ fn vs_terrain(
fn lit(in: VertexOut) -> vec4<f32> {
let texel = textureSample(texture0, sampler0, in.tex_coord);
let light = textureSample(lightmap, lightmap_sampler, in.light).rgb;
return vec4<f32>(texel.rgb * in.color.rgb * light, texel.a * in.color.a);
return vec4<f32>(texel.rgb * in.color.rgb * light_at(in), texel.a * in.color.a);
}
// the lightmap has no mipmaps, so a level is the same as textureSample, and it can be read after a branch
fn light_at(in: VertexOut) -> vec3<f32> {
return textureSampleLevel(lightmap, lightmap_sampler, in.light, 0.0).rgb;
}
// no discard, so the gpu can reject hidden fragments before running the shader
@@ -161,14 +187,26 @@ fn fs_solid(in: VertexOut) -> @location(0) vec4<f32> {
return vec4<f32>(lit(in).rgb, 1.0);
}
// alpha tested instead of blended, so it doesn't need sorting
// alpha tested instead of blended, so it doesn't need sorting. with msaa on, alpha to coverage instead of discard:
// alpha is 0 or 1, so a texel covers none or all of a pixel's samples, the same as discarding below 0.1, but the gpu
// can still reject hidden fragments before running the shader. clear texels skip the lightmap
@fragment
fn fs_cutout(in: VertexOut) -> @location(0) vec4<f32> {
let color = lit(in);
if (color.a < 0.1) {
let texel = textureSample(texture0, sampler0, in.tex_coord);
if (texel.a < 0.1) {
return vec4<f32>(0.0);
}
return vec4<f32>(texel.rgb * in.color.rgb * light_at(in), 1.0);
}
// without msaa, the default, there's no alpha to coverage, so clear texels are discarded like minecraft and sodium
@fragment
fn fs_cutout_discard(in: VertexOut) -> @location(0) vec4<f32> {
let texel = textureSample(texture0, sampler0, in.tex_coord);
if (texel.a < 0.1) {
discard;
}
return vec4<f32>(color.rgb, 1.0);
return vec4<f32>(texel.rgb * in.color.rgb * light_at(in), 1.0);
}
@fragment
@@ -193,7 +231,10 @@ export async function init_window(canvas_element: HTMLCanvasElement) {
if (!adapter) {
throw new Error("No WebGPU adapter found");
}
device = await adapter.requestDevice();
device = await adapter.requestDevice({
requiredFeatures: adapter.features.has("timestamp-query") ? ["timestamp-query"] : [],
});
gpu_timer = new GpuTimer(device);
device.addEventListener("uncapturederror", (event) => {
console.error("WebGPU error:", (event as GPUUncapturedErrorEvent).error.message);
});
@@ -266,6 +307,15 @@ export function update_lightmap(daylight = 1) {
}
export function begin_drawing() {
const wanted_samples = render_debug.msaa ? SAMPLE_COUNT : 1;
if (wanted_samples !== sample_count) {
sample_count = wanted_samples;
create_pipelines();
}
render_stats = frame_stats;
frame_stats = empty_stats();
gpu_label = "other";
gpu_timer?.begin_frame();
encoder = device.createCommandEncoder();
frame_view = context.getCurrentTexture().createView();
ensure_render_targets();
@@ -287,8 +337,10 @@ export function end_drawing() {
pass!.end();
pass = undefined;
gpu_timer?.resolve(encoder!);
device.queue.submit([encoder!.finish()]);
encoder = undefined;
gpu_timer?.read();
for (const buffer of pending_destroy) {
buffer.destroy();
@@ -310,6 +362,16 @@ function update_2d_mvp() {
mat4.orthoZO(ortho, l, r, b, t, n, f);
}
// what the gpu work recorded from now on is timed as. with render_debug.split_passes the current pass ends here, so
// the next one is timed apart
export function gpu_section(label: string) {
gpu_label = label;
if (!render_debug.split_passes || !pass) return;
flush_batch();
pass.end();
pass = undefined;
}
export function begin_clip(x: number, y: number, width: number, height: number) {
flush_batch();
scissor = { x, y, width, height };
@@ -445,6 +507,8 @@ export function draw_terrain(
render_pass.setVertexBuffer(0, vertex_buffer);
render_pass.drawIndexed(quad_count * 6, 1, first * 6);
frame_stats.draw_calls += 1;
frame_stats.quads[layer] += quad_count;
}
// the camera's view and projection, for frustum culling. only meaningful in 3d mode
@@ -620,6 +684,7 @@ function draw(buffer: GPUBuffer, offset: number, vertex_count: number) {
render_pass.setBindGroup(1, get_texture_bind_group(current_texture));
render_pass.setVertexBuffer(0, buffer, offset);
render_pass.draw(vertex_count);
frame_stats.draw_calls += 1;
}
function ensure_pass(): GPURenderPassEncoder {
@@ -627,10 +692,11 @@ function ensure_pass(): GPURenderPassEncoder {
return pass;
}
const multisampled = sample_count > 1;
pass = encoder!.beginRenderPass({
colorAttachments: [{
view: msaa_texture!.createView(),
resolveTarget: frame_view,
view: multisampled ? msaa_texture!.createView() : frame_view,
resolveTarget: multisampled ? frame_view : undefined,
clearValue: clear_color,
loadOp: pending_color_clear ? "clear" : "load",
storeOp: "store",
@@ -641,7 +707,9 @@ function ensure_pass(): GPURenderPassEncoder {
depthLoadOp: pending_depth_clear ? "clear" : "load",
depthStoreOp: "store",
},
timestampWrites: gpu_timer?.pass_writes(gpu_label),
});
frame_stats.passes += 1;
pending_color_clear = false;
pending_depth_clear = false;
current_pipeline = undefined;
@@ -652,8 +720,8 @@ function ensure_pass(): GPURenderPassEncoder {
}
function apply_scissor(render_pass: GPURenderPassEncoder) {
const target_width = msaa_texture!.width;
const target_height = msaa_texture!.height;
const target_width = depth_texture!.width;
const target_height = depth_texture!.height;
if (!scissor) {
render_pass.setScissorRect(0, 0, target_width, target_height);
@@ -673,23 +741,29 @@ function ensure_render_targets() {
const width = canvas.width;
const height = canvas.height;
if (msaa_texture && msaa_texture.width === width && msaa_texture.height === height) {
if (
depth_texture && depth_texture.width === width && depth_texture.height === height &&
depth_texture.sampleCount === sample_count
) {
return;
}
msaa_texture?.destroy();
depth_texture?.destroy();
msaa_texture = device.createTexture({
size: [width, height],
format: canvas_format,
sampleCount: SAMPLE_COUNT,
usage: GPUTextureUsage.RENDER_ATTACHMENT,
});
// without msaa the frame is drawn straight into the canvas
msaa_texture = sample_count > 1
? device.createTexture({
size: [width, height],
format: canvas_format,
sampleCount: sample_count,
usage: GPUTextureUsage.RENDER_ATTACHMENT,
})
: undefined;
depth_texture = device.createTexture({
size: [width, height],
format: DEPTH_FORMAT,
sampleCount: SAMPLE_COUNT,
sampleCount: sample_count,
usage: GPUTextureUsage.RENDER_ATTACHMENT,
});
}
@@ -734,14 +808,15 @@ function update_camera() {
function create_pipelines() {
const module = device.createShaderModule({ code: shader_src });
uniform_layout = device.createBindGroupLayout({
// made once, the bind groups made with them outlive pipelines made again for a new sample count
uniform_layout ??= device.createBindGroupLayout({
entries: [{
binding: 0,
visibility: GPUShaderStage.VERTEX,
buffer: { type: "uniform", hasDynamicOffset: true, minBindingSize: 64 },
}],
});
texture_layout = device.createBindGroupLayout({
texture_layout ??= device.createBindGroupLayout({
entries: [
{ binding: 0, visibility: GPUShaderStage.FRAGMENT, texture: {} },
{ binding: 1, visibility: GPUShaderStage.FRAGMENT, sampler: {} },
@@ -772,7 +847,7 @@ function create_pipelines() {
},
}],
};
const multisample: GPUMultisampleState = { count: SAMPLE_COUNT };
const multisample: GPUMultisampleState = { count: sample_count };
pipeline_2d = device.createRenderPipeline({
layout,
@@ -821,18 +896,21 @@ function create_pipelines() {
};
// like sodium and vanilla: solid and cutout don't blend, translucent blends and still writes depth
// since it's drawn sorted back to front
const terrain_pipeline = (entryPoint: string, blend?: GPUBlendState) =>
const terrain_pipeline = (entryPoint: string, blend?: GPUBlendState, alphaToCoverageEnabled = false) =>
device.createRenderPipeline({
layout: terrain_layout,
vertex: terrain_vertex,
fragment: { module: terrain_module, entryPoint, targets: [{ format: canvas_format, blend }] },
multisample,
multisample: { ...multisample, alphaToCoverageEnabled },
primitive: primitive_3d,
depthStencil: depth_3d,
});
terrain_pipelines = {
solid: terrain_pipeline("fs_solid"),
cutout: terrain_pipeline("fs_cutout"),
// alpha to coverage needs msaa
cutout: sample_count > 1
? terrain_pipeline("fs_cutout", undefined, true)
: terrain_pipeline("fs_cutout_discard"),
translucent: terrain_pipeline("fs_translucent", {
color: { srcFactor: "src-alpha", dstFactor: "one-minus-src-alpha", operation: "add" },
alpha: { srcFactor: "src-alpha", dstFactor: "one-minus-src-alpha", operation: "add" },
+108
View File
@@ -0,0 +1,108 @@
// how long the gpu spends on each render pass, with timestamp queries, for the f3 performance window. passes are
// labeled with the section they started in (see gpu_section in core.ts), and the results come back a few frames
// later, when the gpu is done. chrome rounds timestamps to 0.1 ms unless it's started with
// --enable-webgpu-developer-features
// passes timed per frame, the rest of a frame's aren't
const MAX_PASSES = 32;
// frames whose results can be on their way back at once. when they all are, the next frame isn't timed
const READBACK_BUFFERS = 3;
const WINDOW_MS = 1000;
export class GpuTimer {
readonly supported: boolean;
// ms per frame by label, averaged over the last window
results = new Map<string, number>();
total = 0;
#device: GPUDevice;
#query_set: GPUQuerySet | undefined;
#resolve_buffer: GPUBuffer | undefined;
#free: GPUBuffer[] = [];
#created = 0;
// this frame's
#labels: string[] = [];
#readback: GPUBuffer | undefined;
#sums = new Map<string, number>();
#frames = 0;
#window_start = performance.now();
constructor(device: GPUDevice) {
this.#device = device;
this.supported = device.features.has("timestamp-query");
if (this.supported) {
this.#query_set = device.createQuerySet({ type: "timestamp", count: MAX_PASSES * 2 });
this.#resolve_buffer = device.createBuffer({
size: MAX_PASSES * 16,
usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC,
});
}
}
begin_frame() {
this.#labels = [];
this.#readback = undefined;
if (!this.supported) return;
this.#readback = this.#free.pop();
if (!this.#readback && this.#created < READBACK_BUFFERS) {
this.#created += 1;
this.#readback = this.#device.createBuffer({
size: MAX_PASSES * 16,
usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST,
});
}
}
// for a pass about to begin
pass_writes(label: string): GPURenderPassTimestampWrites | undefined {
if (!this.#readback || this.#labels.length >= MAX_PASSES) return undefined;
const i = this.#labels.length;
this.#labels.push(label);
return { querySet: this.#query_set!, beginningOfPassWriteIndex: i * 2, endOfPassWriteIndex: i * 2 + 1 };
}
// after the last pass ends, before the encoder finishes
resolve(encoder: GPUCommandEncoder) {
if (!this.#readback || this.#labels.length === 0) return;
const count = this.#labels.length * 2;
encoder.resolveQuerySet(this.#query_set!, 0, count, this.#resolve_buffer!, 0);
encoder.copyBufferToBuffer(this.#resolve_buffer!, 0, this.#readback, 0, count * 8);
}
// after the submit
read() {
const buffer = this.#readback;
if (!buffer) return;
const labels = this.#labels;
if (labels.length === 0) {
this.#free.push(buffer);
return;
}
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>();
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);
});
buffer.unmap();
this.#free.push(buffer);
this.#add_frame(frame);
}).catch(() => {
// the device was lost, nothing to time anymore
});
}
#add_frame(frame: Map<string, number>) {
for (const [label, ms] of frame) this.#sums.set(label, (this.#sums.get(label) ?? 0) + ms);
this.#frames += 1;
const now = performance.now();
if (now - this.#window_start < WINDOW_MS) return;
this.results = new Map([...this.#sums].map(([label, ms]) => [label, ms / this.#frames]));
this.total = [...this.results.values()].reduce((sum, ms) => sum + ms, 0);
this.#sums.clear();
this.#frames = 0;
this.#window_start = now;
}
}
+14 -8
View File
@@ -5,6 +5,7 @@ import { Hud } from "$/client/gui/hud.ts";
import { DebugOverlay } from "$/client/gui/debug_overlay.ts";
import { LevelRenderer } from "./level_renderer.ts";
import { HandRenderer } from "./hand_renderer.ts";
import { profiler } from "$/client/profiler.ts";
// the sky at noon and in the middle of the night
const DAY_SKY = [0.69, 0.8, 1];
@@ -40,17 +41,22 @@ export class GameRenderer {
this.#setup_sky(client, partial_tick);
begin_mode_3d(camera);
this.level_renderer.render_opaque(client.level, camera);
this.level_renderer.render_destroy_progress(client.game_mode);
this.level_renderer.render_entities(client.level, camera, client.player, partial_tick);
this.level_renderer.render_translucent(client.level, camera);
const level = this.level_renderer;
level.render_opaque(client.level, camera);
profiler.section("entities", () => {
level.render_destroy_progress(client.game_mode);
level.render_entities(client.level, camera, client.player, partial_tick);
});
profiler.section("translucent", () => level.render_translucent(client.level, camera));
end_mode_3d();
this.hand.render(client.player, partial_tick);
profiler.section("hand", () => this.hand.render(client.player, partial_tick));
this.hud.render(client);
client.screen?.on_render();
profiler.section("hud", () => {
this.hud.render(client);
client.screen?.on_render();
});
if (client.debugging) {
this.debug_overlay.render(client);
profiler.section("debug overlay", () => this.debug_overlay.render(client));
}
}
}
+26 -11
View File
@@ -1,4 +1,5 @@
import { type Chunk, CHUNK_SIZE, type ChunkMesh, ClientLevel } from "$/client/level/client_level.ts";
import { profiler } from "$/client/profiler.ts";
import { Camera } from "$/client/camera.ts";
import { AssetManager } from "$/client/assets.ts";
import { get_sprite_region } from "$/client/sprites.ts";
@@ -47,9 +48,32 @@ export class LevelRenderer {
frustum = new Frustum();
// chunks in view this frame, worked out once for all the layers
#visible: Chunk[] = [];
// what to draw, switched off in the f3 performance window to see what each costs
draw = { solid: true, cutout: true, translucent: true, entities: true };
get visible_chunks() {
return this.#visible.length;
}
// solid and cutout terrain, drawn before entities
render_opaque(level: ClientLevel, camera: Camera) {
profiler.section("chunk upkeep", () => this.#find_visible(level, camera));
set_current_texture(level.image.tex);
for (const layer of ["solid", "cutout"] as const) {
if (!this.draw[layer]) continue;
profiler.section(layer, () => {
for (const chunk of this.#visible) {
const mesh = chunk.meshes[layer];
if (mesh) {
draw_facing_camera(layer, mesh, camera);
}
}
});
}
}
// asks for meshes and sorting, then works out which chunks are in view, near to far
#find_visible(level: ClientLevel, camera: Camera) {
level.request_meshes(camera);
level.update_translucent_sorting(camera);
@@ -68,22 +92,12 @@ export class LevelRenderer {
return dx * dx + dz * dz;
};
this.#visible.sort((a, b) => distance_sq(a) - distance_sq(b));
set_current_texture(level.image.tex);
for (const layer of ["solid", "cutout"] as const) {
for (const chunk of this.#visible) {
const mesh = chunk.meshes[layer];
if (mesh) {
draw_facing_camera(layer, mesh, camera);
}
}
}
}
// translucent terrain, drawn after entities so they show through water and glass.
// chunks go back to front, and each chunk's quads are already sorted back to front
render_translucent(_level: ClientLevel, camera: Camera) {
if (!this.draw.translucent) return;
const distance_sq = (x: number, z: number) => {
const dx = (x + 0.5) * CHUNK_SIZE - camera.x;
const dz = (z + 0.5) * CHUNK_SIZE - camera.z;
@@ -107,6 +121,7 @@ export class LevelRenderer {
// every entity but the one the camera is in
render_entities(level: ClientLevel, camera: Camera, camera_entity: Entity, partial_tick: number) {
if (!this.draw.entities) return;
flush_batch();
const default_skin = AssetManager.instance.get<Texture>("bworld:skin");
// what they wear is drawn with the atlas, after every skin