Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

7.3 KB
Raw Blame
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
import { Renderer } from './render/renderer';
import { defineResource, Res, Time } from './ecs/resource';
import { defineSystem, GetWorld, Schedule } from './ecs/system';
import type { App, Plugin } from './app/app';
import { StatsOverlay, type StatsPosition } from './stats-overlay';
import { Quality } from './render/qualityRuntime';

export interface FrameStats {
    fps: number;
    frameTimeMs: number;
    entityCount: number;
    systemTimings: Map<string, number>;
    phaseTimings: Map<string, number>;
    drawCalls: number;
    /** Every draw the GPU was asked for, every pass included (see `RenderStats.gpuDraws`). */
    gpuDraws: number;
    /** The draw call budget of the quality level in force; 0 when the app has no quality controller. */
    drawCallBudget: number;
    triangles: number;
    sprites: number;
    text: number;
    skeletal: number;
    meshes: number;
    culled: number;
}

export function defaultFrameStats(): FrameStats {
    return {
        fps: 0,
        frameTimeMs: 0,
        entityCount: 0,
        systemTimings: new Map(),
        phaseTimings: new Map(),
        drawCalls: 0,
        gpuDraws: 0,
        drawCallBudget: 0,
        triangles: 0,
        sprites: 0,
        text: 0,
        skeletal: 0,
        meshes: 0,
        culled: 0,
    };
}

export const Stats = defineResource<FrameStats>(defaultFrameStats(), 'Stats');

// =============================================================================
// Frame History
// =============================================================================

const DEFAULT_HISTORY_CAPACITY = 300;

export interface FrameSnapshot {
    frameTimeMs: number;
    phaseTimings: Map<string, number>;
    systemTimings: Map<string, number>;
}

export class FrameHistory {
    private readonly capacity_: number;
    private buffer_: FrameSnapshot[] = [];
    private cursor_ = 0;
    private count_ = 0;

    constructor(capacity = DEFAULT_HISTORY_CAPACITY) {
        this.capacity_ = capacity;
    }

    get count(): number {
        return this.count_;
    }

    push(frameTimeMs: number, phaseTimings: Map<string, number>, systemTimings?: Map<string, number>): void {
        const snapshot: FrameSnapshot = {
            frameTimeMs,
            phaseTimings: new Map(phaseTimings),
            systemTimings: systemTimings ? new Map(systemTimings) : new Map(),
        };

        if (this.count_ < this.capacity_) {
            this.buffer_.push(snapshot);
            this.count_++;
        } else {
            this.buffer_[this.cursor_] = snapshot;
        }
        this.cursor_ = (this.cursor_ + 1) % this.capacity_;
    }

    getLatest(): FrameSnapshot | null {
        if (this.count_ === 0) return null;
        const idx = (this.cursor_ - 1 + this.capacity_) % this.capacity_;
        return this.buffer_[idx];
    }

    getAll(): FrameSnapshot[] {
        if (this.count_ === 0) return [];
        if (this.count_ < this.capacity_) {
            return this.buffer_.slice();
        }
        return [
            ...this.buffer_.slice(this.cursor_),
            ...this.buffer_.slice(0, this.cursor_),
        ];
    }

    reset(): void {
        this.buffer_.length = 0;
        this.cursor_ = 0;
        this.count_ = 0;
    }
}

const SLIDING_WINDOW_SIZE = 60;
const STATS_COLLECT_SYSTEM_NAME = 'StatsCollect';

export class StatsCollector {
    private deltas_: number[] = [];
    private cursor_ = 0;
    private count_ = 0;
    private sum_ = 0;

    pushFrame(deltaSeconds: number): void {
        if (!Number.isFinite(deltaSeconds) || deltaSeconds < 0) return;

        if (this.count_ < SLIDING_WINDOW_SIZE) {
            this.deltas_.push(deltaSeconds);
            this.sum_ += deltaSeconds;
            this.count_++;
        } else {
            this.sum_ -= this.deltas_[this.cursor_];
            this.deltas_[this.cursor_] = deltaSeconds;
            this.sum_ += deltaSeconds;
            this.cursor_ = (this.cursor_ + 1) % SLIDING_WINDOW_SIZE;
        }
    }

    getFps(): number {
        if (this.count_ === 0 || this.sum_ <= 0) return 0;
        return this.count_ / this.sum_;
    }

    getFrameTimeMs(): number {
        if (this.count_ === 0 || this.sum_ <= 0) return 0;
        return (this.sum_ / this.count_) * 1000;
    }

    reset(): void {
        this.deltas_.length = 0;
        this.cursor_ = 0;
        this.count_ = 0;
        this.sum_ = 0;
    }
}

export interface StatsPluginOptions {
    overlay?: boolean;
    position?: StatsPosition;
    container?: HTMLElement;
}

export class StatsPlugin implements Plugin {
    readonly name = 'stats';
    private collector_ = new StatsCollector();
    private overlay_: StatsOverlay | null = null;
    private options_: StatsPluginOptions;

    constructor(options?: StatsPluginOptions) {
        this.options_ = options ?? {};
    }

    build(app: App): void {
        this.collector_.reset();

        app.enableStats();
        app.insertResource(Stats, defaultFrameStats());

        const showOverlay = this.options_.overlay !== false;
        if (showOverlay && typeof document !== 'undefined') {
            const container = this.options_.container ?? document.body;
            this.overlay_ = new StatsOverlay(container, this.options_.position);
        }

        const collector = this.collector_;
        const overlay = this.overlay_;

        const statsCollectSystem = defineSystem(
            [Res(Time), GetWorld()],
            (time, world) => {
                collector.pushFrame(time.delta);

                const stats = app.getResource(Stats);
                stats.fps = collector.getFps();
                stats.frameTimeMs = collector.getFrameTimeMs();
                stats.entityCount = world.entityCount();

                const timings = app.getSystemTimings();
                if (timings) {
                    const copy = new Map(timings);
                    copy.delete(STATS_COLLECT_SYSTEM_NAME);
                    stats.systemTimings = copy;
                } else {
                    stats.systemTimings = new Map();
                }

                const pt = app.getPhaseTimings();
                stats.phaseTimings = pt ? new Map(pt) : new Map();

                const renderStats = Renderer.getStats();
                stats.drawCalls = renderStats.drawCalls;
                stats.gpuDraws = renderStats.gpuDraws;
                stats.drawCallBudget = app.hasResource(Quality) ? app.getResource(Quality)?.profile.drawCallBudget ?? 0 : 0;
                stats.triangles = renderStats.triangles;
                stats.sprites = renderStats.sprites;
                stats.text = renderStats.text;
                stats.skeletal = renderStats.skeletal;
                stats.meshes = renderStats.meshes;
                stats.culled = renderStats.culled;

                overlay?.update(stats);
            },
            // It holds the World to count entities, which is not component access
            // at all: an empty claim is the honest one, and it keeps the overlay
            // out of every other system's conflict set.
            { name: STATS_COLLECT_SYSTEM_NAME, touches: {} }
        );

        app.addSystemToSchedule(Schedule.Last, statsCollectSystem);
    }

    cleanup(): void {
        this.overlay_?.dispose();
        this.overlay_ = null;
    }
}

export const statsPlugin = new StatsPlugin();