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.

4.1 KB
Raw Blame
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
 * @file    QueryCache.ts
 * @brief   Component-aware query result cache with fine-grained invalidation
 */

import { Entity } from '../types';

interface CacheEntry {
    componentVersions: Map<symbol, number>;
    result: Entity[];
}

/** Cumulative counters for query-cache activity (observability only). */
export interface QueryCacheStats {
    /** Lookups that returned a still-valid cached result. */
    readonly hits: number;
    /** Lookups that recomputed — either no entry or stale. */
    readonly misses: number;
    /** Times an entry was rejected because one of its dep components changed. */
    readonly componentInvalidations: number;
    /** Current number of entries held. */
    readonly size: number;
}

export class QueryCache {
    private structuralVersion_ = 0;
    private componentVersions_ = new Map<symbol, number>();
    private cache_ = new Map<string, CacheEntry>();

    private hits_ = 0;
    private misses_ = 0;
    private componentInvalidations_ = 0;

    get structuralVersion(): number {
        return this.structuralVersion_;
    }

    // A monotonic "something structural happened" counter exposed as the world
    // version for coarse external gates (e.g. physics reconcile). It deliberately
    // does NOT invalidate cached queries — invalidation is per-component below, so
    // churn of unrelated entities never drops an unrelated query's result.
    markStructuralChange(): void {
        this.structuralVersion_++;
    }

    /** A component's current version — for a derived set that has to recompute
     *  when it moves, without standing up a second invalidation scheme. */
    componentVersion(componentId: symbol): number {
        return this.componentVersions_.get(componentId) ?? 0;
    }

    markComponentDirty(componentId: symbol): void {
        const cur = this.componentVersions_.get(componentId) ?? 0;
        this.componentVersions_.set(componentId, cur + 1);
    }

    /**
     * Drop every cached result. For changes no per-component version describes —
     * a reorder (see World.applyEntityOrder) moves entities within results that are
     * otherwise still correct, so nothing else would recompute them.
     */
    invalidateAll(): void {
        this.cache_.clear();
        this.structuralVersion_++;
    }

    getOrCompute(
        cacheKey: string,
        dependentComponentIds: symbol[],
        computeFn: () => Entity[],
    ): Entity[] {
        const cached = this.cache_.get(cacheKey);
        if (cached) {
            if (this.checkValidity_(cached, dependentComponentIds)) {
                this.hits_++;
                return cached.result;
            }
            this.componentInvalidations_++;
        }
        this.misses_++;

        const result = computeFn();

        const compVersions = new Map<symbol, number>();
        for (const id of dependentComponentIds) {
            compVersions.set(id, this.componentVersions_.get(id) ?? 0);
        }
        this.cache_.set(cacheKey, {
            componentVersions: compVersions,
            result,
        });

        return result;
    }

    /** Snapshot of counters. Read-only; callers can diff across frames. */
    getStats(): QueryCacheStats {
        return {
            hits: this.hits_,
            misses: this.misses_,
            componentInvalidations: this.componentInvalidations_,
            size: this.cache_.size,
        };
    }

    /** Reset counters without dropping cached entries. */
    resetStats(): void {
        this.hits_ = 0;
        this.misses_ = 0;
        this.componentInvalidations_ = 0;
    }

    /** True when every dependent component is unchanged since the entry was cached. */
    private checkValidity_(entry: CacheEntry, dependentComponentIds: symbol[]): boolean {
        for (const id of dependentComponentIds) {
            const current = this.componentVersions_.get(id) ?? 0;
            const cached = entry.componentVersions.get(id) ?? 0;
            if (current !== cached) return false;
        }
        return true;
    }
}