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.

32.4 KB
Raw Blame
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
 * @file    ResourceManager.hpp
 * @brief   Central resource management system
 * @details Provides unified interface for creating, loading, caching, and
 *          releasing GPU resources with automatic deduplication.
 *
 * @author  ESEngine Team
 * @date    2026
 *
 * @copyright Copyright (c) 2026 ESEngine Team
 *            Licensed under the Apache License, Version 2.0.
 */
#pragma once

// =============================================================================
// Includes
// =============================================================================

// Project includes
#include "../core/Types.hpp"
#include "Handle.hpp"
#include "ResourcePool.hpp"
#include "LoaderRegistry.hpp"
#include "TextureMetadata.hpp"
#include "../renderer/rhi/Shader.hpp"
#include "../renderer/rhi/Texture.hpp"
#include "../renderer/rhi/Buffer.hpp"
#include "Mesh.hpp"
#include "MeshArena.hpp"
#include "Environment.hpp"
#include "ProbeVolume.hpp"
#include "../text/BitmapFont.hpp"

// Standard library
#include <string>
#include <unordered_map>

namespace esengine { class GfxDevice; }

namespace esengine::resource {

enum class ShaderTargetLanguage : u8;  // ShaderParser.hpp

/**
 * @brief Who refills a resource's GPU content after a device loss.
 * @details Numbered for the host boundary, where a texture's creator states it:
 *          only the creator knows whether it can make the pixels again.
 */
enum class ResourceContent : u32 {
    Transient = 0,  ///< Rewritten by its owner before every use (a video frame).
    Retained = 1,   ///< The device keeps the bytes (a tile collection composed at load).
    Asset = 2,      ///< The asset layer loads it again from its path.
    Canvas = 3,     ///< Redrawn from the canvas it mirrors.
    Video = 4,      ///< Refilled by the next decoded frame.
    Mesh = 5,       ///< Geometry the asset layer replays (MeshRecovery::SourceReplayable).
    GlyphPage = 6,  ///< Repainted from the glyphs placed on it.
    AtlasPage = 7,  ///< A skeleton's atlas page, decoded again from its image.
    Composed = 8,   ///< Composed again by its creator from its sources (a terrain's layer arrays).
};

/** @brief The device's policy for a content code; unknown codes are Asset, the one that asks. */
GfxContent toGfxContent(ResourceContent content);

// =============================================================================
// Resource Manager Statistics
// =============================================================================

/**
 * @brief Statistics about resource usage
 */
struct ResourceStats {
    usize shaderCount = 0;        ///< Number of active shaders
    usize textureCount = 0;       ///< Number of active textures
    usize vertexBufferCount = 0;  ///< Number of active vertex buffers
    usize indexBufferCount = 0;   ///< Number of active index buffers
    usize cacheHits = 0;          ///< Number of cache hits since reset
    usize cacheMisses = 0;        ///< Number of cache misses since reset
    usize textureBytes = 0;       ///< Resident texture bytes (RGBA8 estimate) — VRAM usage
    usize textureBudget = 0;      ///< Texture pool resident-byte budget (0 = eviction off)
    usize textureEvictableCount = 0;  ///< Cached refCount==0 textures awaiting revive/evict
    usize retainedBytes = 0;      ///< CPU copies the device keeps to restore content after a loss
};

// =============================================================================
// ResourceManager Class
// =============================================================================

/**
 * @brief Central manager for GPU resources
 *
 * @details Manages the lifecycle of shaders, textures, and buffers.
 *          Provides handle-based access with reference counting and
 *          path-based caching for deduplication.
 *
 * @code
 * ResourceManager rm;
 * rm.init();
 *
 * auto shader = rm.createShader(vertSrc, fragSrc);
 * auto texture = rm.loadTexture("assets/player.png");
 *
 * Shader* shaderPtr = rm.getShader(shader);
 * Texture* texturePtr = rm.getTexture(texture);
 *
 * rm.releaseShader(shader);
 * rm.releaseTexture(texture);
 *
 * rm.shutdown();
 * @endcode
 */
class ResourceManager {
public:
    ResourceManager() = default;
    ~ResourceManager() = default;

    // Non-copyable, movable
    ResourceManager(const ResourceManager&) = delete;
    ResourceManager& operator=(const ResourceManager&) = delete;
    ResourceManager(ResourceManager&&) = default;
    ResourceManager& operator=(ResourceManager&&) = default;

    // =========================================================================
    // Lifecycle
    // =========================================================================

    /**
     * @brief Initializes the resource manager
     * @param device The graphics device used to create all GPU resources
     *        (shaders, textures, buffers). ResourceManager is the GPU-resource
     *        factory, so it owns the single device reference the resource classes
     *        route through.
     */
    void init(GfxDevice& device);

    /** The device resources are created on, or null before {@link init}.
     *  Read by callers that must ASK the backend what it supports. */
    GfxDevice* device() const { return device_; }

    /**
     * @brief Shuts down and releases all resources
     */
    void shutdown();

    /**
     * @brief Checks if the manager is initialized
     * @return True if init() has been called
     */
    bool isInitialized() const { return initialized_; }

    /**
     * @brief Updates resource manager (processes hot reload, call once per frame)
     */
    void update();

    // =========================================================================
    // Shader Resources
    // =========================================================================

    /**
     * @brief The language embedded pipelines must author their sources in.
     * @details GLSL when the backend compiles it (the GL device); otherwise the
     *          backend's own language (WGSL). Embedded shader creation sites
     *          branch on this to pick the .esshader assembly or its WGSL twin —
     *          the one seam that keeps plugins backend-agnostic.
     */
    GfxShaderLanguage preferredShaderLanguage() const;

    /**
     * @brief preferredShaderLanguage() as a ShaderParser assembly target.
     * @details The other half of the seam: creation sites parse one .esshader
     *          (whose WGSL twin rides the same file) and assemble both stages
     *          for this target — no per-backend branches.
     */
    ShaderTargetLanguage preferredShaderTarget() const;

    /**
     * @brief Creates a shader from source strings
     * @param vertSrc Vertex shader GLSL source
     * @param fragSrc Fragment shader GLSL source
     * @param rewriteLoose Lift loose non-sampler uniforms into a std140
     *        DrawParams block (see renderer/DrawParams.hpp). Pass false for
     *        sources whose uniform blocks are already assembled (ShaderParser
     *        material output).
     * @return Handle to the shader, or invalid handle on failure
     */
    /** @brief Whether a shader that is known to compile is made without waiting for it (the device's skip-what-is-not-ready policy is on). */
    bool deferLinks() const;

    ShaderHandle createShader(const std::string& vertSrc, const std::string& fragSrc,
                              bool rewriteLoose = true,
                              GfxShaderLanguage language = GfxShaderLanguage::GLSL_ES300,
                              bool deferLink = false);
    ShaderHandle createShaderWithBindings(const std::string& vertSrc, const std::string& fragSrc,
                                           std::initializer_list<AttribBinding> bindings,
                                           GfxShaderLanguage language = GfxShaderLanguage::GLSL_ES300,
                                           bool deferLink = false);

    /**
     * @brief Loads a shader from file paths (with caching)
     * @param vertPath Path to vertex shader file
     * @param fragPath Path to fragment shader file
     * @return Handle to the shader, or invalid handle on failure
     */
    ShaderHandle loadShader(const std::string& vertPath, const std::string& fragPath);

    /**
     * @brief Gets a shader by handle
     * @param handle The shader handle
     * @return Pointer to the shader, or nullptr if invalid
     */
    Shader* getShader(ShaderHandle handle);

    /**
     * @brief Gets a shader by handle (const)
     * @param handle The shader handle
     * @return Const pointer to the shader, or nullptr if invalid
     */
    const Shader* getShader(ShaderHandle handle) const;

    /**
     * @brief Releases a shader (decrements ref count)
     * @param handle The shader handle
     */
    void releaseShader(ShaderHandle handle);

    /// One renderer owns shader-derived metadata. Notify after final pool retirement.
    using ShaderRetiredCallback = void (*)(void*, ShaderHandle);
    void setShaderRetiredCallback(void* owner, ShaderRetiredCallback callback) {
        shaderRetiredOwner_ = owner; shaderRetiredCallback_ = callback;
    }
    void clearShaderRetiredCallback(void* owner) {
        if (shaderRetiredOwner_ == owner) { shaderRetiredOwner_ = nullptr; shaderRetiredCallback_ = nullptr; }
    }

    /**
     * @brief Gets the current reference count for a shader
     * @param handle The shader handle
     * @return Reference count, or 0 if invalid
     */
    u32 getShaderRefCount(ShaderHandle handle) const;

    // =========================================================================
    // Texture Resources
    // =========================================================================

    /**
     * @brief Creates a texture from specification
     * @param spec Texture creation parameters
     * @return Handle to the texture, or invalid handle on failure
     */
    TextureHandle createTexture(ResourceContent content, const TextureSpecification& spec);

    /**
     * @brief Creates a texture from pixel data
     * @param width Texture width in pixels
     * @param height Texture height in pixels
     * @param pixels Pixel data
     * @param format Pixel format (default RGBA8)
     * @return Handle to the texture, or invalid handle on failure
     */
    TextureHandle createTexture(ResourceContent content, u32 width, u32 height, ConstSpan<u8> pixels,
                                 TextureFormat format, bool flipY = false);

    /**
     * @brief Creates a 2D texture array from `spec.layers` same-size RGBA8 (or SRGB8A8) layers.
     * @param pixels The layers back to back, layer 0 first; exactly
     *        `spec.width * spec.height * 4 * spec.layers` bytes, or nothing is made.
     * @return Handle to the texture, or invalid handle on failure
     */
    TextureHandle createTextureArray(ResourceContent content, const TextureSpecification& spec,
                                     ConstSpan<u8> pixels);

    /**
     * @brief Creates a block-compressed texture (KTX2 → ETC2/ASTC/BC), uploading
     *        the pre-compressed blocks for mip level 0. Tracked like any texture;
     *        its residency cost is the real (compressed) byte size.
     * @param data All @p mipLevels concatenated (level 0 first, block-aligned).
     * @param mipLevels Mip levels present (1 = base only).
     * @return Handle to the texture, or invalid handle on failure.
     */
    TextureHandle createCompressedTexture(ResourceContent content, u32 width, u32 height,
                                          GfxCompressedFormat format, ConstSpan<u8> data,
                                          u32 mipLevels = 1);

    /**
     * @brief Loads a texture from file (with caching)
     * @param path Path to the image file
     * @return Handle to the texture, or invalid handle on failure
     */
    TextureHandle loadTexture(const std::string& path);

    /**
     * @brief Gets a texture by handle
     * @param handle The texture handle
     * @return Pointer to the texture, or nullptr if invalid
     */
    Texture* getTexture(TextureHandle handle);

    /**
     * @brief Gets a texture by handle (const)
     * @param handle The texture handle
     * @return Const pointer to the texture, or nullptr if invalid
     */
    const Texture* getTexture(TextureHandle handle) const;

    /**
     * @brief Releases a texture (decrements ref count)
     * @param handle The texture handle
     */
    void releaseTexture(TextureHandle handle);

    /**
     * @brief Gets the current reference count for a texture
     * @param handle The texture handle
     * @return Reference count, or 0 if invalid
     */
    u32 getTextureRefCount(TextureHandle handle) const;

    /**
     * @brief Registers an externally-created GL texture
     * @param glTextureId The OpenGL texture ID
     * @param width Texture width in pixels
     * @param height Texture height in pixels
     * @param bytes Actual GPU size for the eviction budget; 0 = estimate as
     *              RGBA8 (width × height × 4). Compressed uploads (KTX2 →
     *              ASTC/ETC2/S3TC) pass their real block size, 4–8× smaller —
     *              billing them as RGBA8 would waste most of the budget.
     * @return Handle to the registered texture
     */
    TextureHandle registerExternalTexture(ResourceContent content, u32 glTextureId, u32 width, u32 height,
                                          usize bytes = 0);

    /**
     * @brief Names a texture the device holds for another owner (a render target's
     *        colour plane) by a resource handle, without taking it over.
     */
    TextureHandle wrapDeviceTexture(::esengine::TextureHandle texture, u32 width, u32 height);

    /**
     * @brief Registers a texture with a path for cache lookup
     * @param handle The texture handle
     * @param path The path to associate (used by loadTexture cache)
     */
    void registerTextureWithPath(TextureHandle handle, const std::string& path);

    // =========================================================================
    // Device Loss
    // =========================================================================

    /**
     * @brief Moves a freshly loaded texture's pixels behind an owed handle.
     * @details How the asset layer pays: it loads the texture the ordinary way and
     *          hands the result over, which leaves @p source empty for its release.
     * @return False if either handle names no live texture.
     */
    bool adoptTextureContent(TextureHandle target, TextureHandle source);

    /** @brief Textures the device is waiting for content for, with who refills them. */
    struct OwedTexture {
        TextureHandle handle;
        ResourceContent content = ResourceContent::Asset;
    };
    std::vector<OwedTexture> texturesAwaitingReupload() const;

    /**
     * @brief Gives up on an owed texture's content: it keeps blank storage.
     * @details For content nothing can bring back; the caller says so in the log.
     */
    void forgoTextureContent(TextureHandle handle);

    /**
     * @brief Settles an owed texture whose provider wrote the pixels itself.
     * @details See GfxDevice::restoreContent — for a JS-side upload straight into
     *          the native texture, which the device cannot see.
     */
    void restoreTextureContent(TextureHandle handle);

    /** @brief The backend's own name for a texture's object, for a host that writes
     *         its pixels itself; 0 when there is none. See GfxDevice::nativeTextureName. */
    u32 textureNativeId(TextureHandle handle) const;

    /**
     * @brief Gets the cached path for a texture
     * @param handle The texture handle
     * @return The path used to load the texture, or empty if not found
     */
    const std::string& getTexturePath(TextureHandle handle) const;

    /**
     * @brief Loads a texture by GUID (with caching)
     * @param guid Asset GUID from AssetDatabase
     * @param path File path to load if not cached
     * @return Handle to the texture, or invalid handle on failure
     */
    TextureHandle loadTextureByGUID(const std::string& guid, const std::string& path);

    /**
     * @brief Gets a texture handle by GUID if already loaded
     * @param guid Asset GUID
     * @return Handle to the texture, or invalid handle if not loaded
     */
    TextureHandle getTextureByGUID(const std::string& guid) const;

    /**
     * @brief Releases a texture by GUID
     * @param guid Asset GUID
     */
    void releaseTextureByGUID(const std::string& guid);

    /**
     * @brief Sets the texture pool's resident-byte budget (0 = no eviction).
     *        Over budget, refCount==0 textures are evicted oldest-first.
     */
    void setTextureBudget(usize bytes);

    /** @brief See GfxDevice::setRetainedBudget. */
    void setRetainedBudget(usize bytes);

    /**
     * @brief Reuses a cached texture by its build path: returns its handle with an
     *        added reference (reviving an evictable one), or an invalid handle if
     *        none is cached. Lets the runtime dedupe + reuse textures across loads.
     */
    TextureHandle acquireTextureByPath(const std::string& path);

    /**
     * @brief Severs a path's texture-cache identity (hot reload). The next
     *        acquireTextureByPath for it misses, so stale bytes are never
     *        revived; an evictable entry under that path is freed immediately.
     * @param path The path to invalidate
     * @return True if the path was registered
     */
    bool invalidateTexturePath(const std::string& path);

    /**
     * @brief Frees every evictable cached texture now (memory pressure).
     *        Held textures and the budget are untouched.
     * @return Number of textures freed
     */
    usize trimTextureCache();

    // =========================================================================
    // Texture Metadata
    // =========================================================================

    /**
     * @brief Sets metadata for a texture
     * @param handle The texture handle
     * @param metadata The metadata to associate
     */
    void setTextureMetadata(TextureHandle handle, const TextureMetadata& metadata);

    /**
     * @brief Gets metadata for a texture
     * @param handle The texture handle
     * @return Pointer to metadata, or nullptr if not set
     */
    const TextureMetadata* getTextureMetadata(TextureHandle handle) const;

    /**
     * @brief Checks if a texture has metadata
     * @param handle The texture handle
     * @return True if metadata is set
     */
    bool hasTextureMetadata(TextureHandle handle) const;

    /**
     * @brief Removes metadata for a texture
     * @param handle The texture handle
     */
    void removeTextureMetadata(TextureHandle handle);

    // =========================================================================
    // Vertex Buffer Resources
    // =========================================================================

    /**
     * @brief Creates a vertex buffer from typed data
     * @tparam T Vertex type
     * @param data Span of vertex data
     * @return Handle to the buffer, or invalid handle on failure
     */
    template<typename T>
    VertexBufferHandle createVertexBuffer(GfxContent content, ConstSpan<T> data);

    /**
     * @brief Creates a dynamic vertex buffer
     * @param sizeBytes Buffer size in bytes
     * @return Handle to the buffer, or invalid handle on failure
     */
    VertexBufferHandle createVertexBuffer(GfxContent content, u32 sizeBytes);

    /**
     * @brief Uploads geometry that stays on the GPU, drawn from its own buffers.
     * @details The frame's transient pool, which every renderable uses today, is
     *          rewritten by the CPU each frame — a per-frame re-upload of anything
     *          that does not change. The layout travels with the buffers: one whose
     *          attribute description lives elsewhere is a rename from garbage.
     *          Every caller is a mesh PRODUCER and owes a row in
     *          tools/meshProducers.mjs saying how the handles it mints come back
     *          after a device generation ends; check-mesh-provenance keeps that
     *          census closed in both directions.
     * @param vertexBytes Raw vertex data, laid out as @p layout describes.
     * @param indices Triangle-list indices into it.
     * @return Handle to the mesh, or invalid on failure.
     */
    MeshHandle createMesh(ConstSpan<u8> vertexBytes, ConstSpan<u32> indices,
                          ConstSpan<GfxVertexAttribute> channels, u32 vertexStride,
                          const glm::vec3& localMin, const glm::vec3& localMax,
                          MeshRecovery recovery, ConstSpan<f32> inverseBind = {},
                          const MeshMorphSource& morph = {});

    /**
     * @brief Puts new geometry behind an EXISTING mesh handle.
     *
     * @details Same identity, a fresh realization. Re-uploading through createMesh
     *          would mint a SECOND handle and leave every component on the dead
     *          one. Refuses a host-only mesh; clears the debt only on success.
     * @return False if the handle names no live mesh, is not replayable, or the
     *         geometry could not be rebuilt.
     */
    bool rematerializeMesh(MeshHandle target, ConstSpan<u8> vertexBytes, ConstSpan<u32> indices,
                           ConstSpan<GfxVertexAttribute> channels, u32 vertexStride,
                           const glm::vec3& localMin, const glm::vec3& localMax,
                           ConstSpan<f32> inverseBind = {}, const MeshMorphSource& morph = {});

    /**
     * @brief Whether meshes realized FROM NOW ON also get an edge buffer.
     * @details Diagnostic geometry for a wireframe view, off by default because it is a
     *          second index buffer per mesh. Set before the assets load: a mesh realized
     *          earlier has no edges, and a view that wants them draws it filled.
     */
    void setMeshEdgeBuffers(bool enabled) { meshEdges_ = enabled; }
    bool meshEdgeBuffers() const { return meshEdges_; }

    /** @brief The mesh a handle names, or null. */
    Mesh* getMesh(MeshHandle handle);
    const Mesh* getMesh(MeshHandle handle) const;

    /** @brief Releases a mesh and the buffers it owns. */
    void releaseMesh(MeshHandle handle);

    /**
     * @brief Changes whenever any mesh is realized (each takes a new Mesh::revision) or released: while it holds, every mesh a
     *        reader looked at is the one it was.
     */
    u64 meshesRevision() const { return meshes_revision_; }

    /**
     * @brief Replayable meshes whose geometry the device is still waiting for.
     * @details Read off the device's ledger, so the list empties exactly when a
     *          rematerialization has put the geometry back.
     */
    std::vector<MeshHandle> meshesAwaitingRematerialization() const;

    /** @brief One live mesh and whether its geometry is on the device. */
    struct MeshRealization {
        u32 handle = 0;
        bool realized = false;
    };

    /** @brief Every live mesh, for a recovery criterion to read. */
    std::vector<MeshRealization> meshRealizations();

    // =========================================================================
    // Environment Resources
    // =========================================================================

    /**
     * @brief Registers a baked environment.
     * @param irradiance Nine RGB spherical-harmonic coefficients.
     * @param specular The prefiltered octahedral atlas; may be invalid, leaving
     *        the environment diffuse-only.
     * @return Handle to the environment, or invalid when the coefficients are not nine.
     */
    EnvironmentHandle createEnvironment(ConstSpan<f32> irradiance, TextureHandle specular,
                                        f32 faceSize, u32 mipCount, f32 maxRange,
                                        u32 columns = 1);

    /** @brief The environment a handle names, or null. */
    Environment* getEnvironment(EnvironmentHandle handle);
    const Environment* getEnvironment(EnvironmentHandle handle) const;

    /** @brief Releases an environment. The atlas is an ordinary texture asset with
     *         its own lifetime, so it is NOT released here. */
    void releaseEnvironment(EnvironmentHandle handle);

    /**
     * @brief Registers a grid of baked irradiance.
     * @param resolution Probes along x, y and z.
     * @param irradiance Nine RGB coefficients per probe, x fastest then y then z.
     */
    ProbeVolumeHandle createProbeVolume(const glm::ivec3& resolution, ConstSpan<f32> irradiance);

    /** @brief The probe volume a handle names, or null. */
    ProbeVolume* getProbeVolume(ProbeVolumeHandle handle);
    const ProbeVolume* getProbeVolume(ProbeVolumeHandle handle) const;

    /** @brief Releases a probe volume. */
    void releaseProbeVolume(ProbeVolumeHandle handle);

    /**
     * @brief Gets a vertex buffer by handle
     * @param handle The buffer handle
     * @return Pointer to the buffer, or nullptr if invalid
     */
    VertexBuffer* getVertexBuffer(VertexBufferHandle handle);

    /**
     * @brief Gets a vertex buffer by handle (const)
     * @param handle The buffer handle
     * @return Const pointer to the buffer, or nullptr if invalid
     */
    const VertexBuffer* getVertexBuffer(VertexBufferHandle handle) const;

    /**
     * @brief Releases a vertex buffer (decrements ref count)
     * @param handle The buffer handle
     */
    void releaseVertexBuffer(VertexBufferHandle handle);

    // =========================================================================
    // Index Buffer Resources
    // =========================================================================

    /**
     * @brief Creates an index buffer from 32-bit indices
     * @param indices Span of index data
     * @return Handle to the buffer, or invalid handle on failure
     */
    IndexBufferHandle createIndexBuffer(GfxContent content, ConstSpan<u32> indices);

    /**
     * @brief Creates an index buffer from 16-bit indices
     * @param indices Span of index data
     * @return Handle to the buffer, or invalid handle on failure
     */
    IndexBufferHandle createIndexBuffer(GfxContent content, ConstSpan<u16> indices);

    /**
     * @brief Gets an index buffer by handle
     * @param handle The buffer handle
     * @return Pointer to the buffer, or nullptr if invalid
     */
    IndexBuffer* getIndexBuffer(IndexBufferHandle handle);

    /**
     * @brief Gets an index buffer by handle (const)
     * @param handle The buffer handle
     * @return Const pointer to the buffer, or nullptr if invalid
     */
    const IndexBuffer* getIndexBuffer(IndexBufferHandle handle) const;

    /**
     * @brief Releases an index buffer (decrements ref count)
     * @param handle The buffer handle
     */
    void releaseIndexBuffer(IndexBufferHandle handle);

    // =========================================================================
    // Bitmap Font Resources
    // =========================================================================

    BitmapFontHandle loadBitmapFont(const std::string& fntPath);

    BitmapFontHandle createBitmapFont(const std::string& fntContent,
                                       TextureHandle texture,
                                       u32 texWidth, u32 texHeight);

    BitmapFontHandle createLabelAtlasFont(TextureHandle texture,
                                           u32 texWidth, u32 texHeight,
                                           const std::string& chars,
                                           u32 charWidth, u32 charHeight);

    text::BitmapFont* getBitmapFont(BitmapFontHandle handle);
    const text::BitmapFont* getBitmapFont(BitmapFontHandle handle) const;
    void releaseBitmapFont(BitmapFontHandle handle);

    /**
     * @brief Gets the current reference count for a bitmap font
     * @param handle The font handle
     * @return Reference count, or 0 if invalid
     */
    u32 getBitmapFontRefCount(BitmapFontHandle handle) const;

    // =========================================================================
    // Statistics
    // =========================================================================

    /**
     * @brief Gets current resource statistics
     * @return Resource counts and cache statistics
     */
    ResourceStats getStats() const;

    /**
     * @brief Resets cache hit/miss counters
     */
    void resetCacheStats();

    // =========================================================================
    // Loader Registration
    // =========================================================================

    /**
     * @brief Registers a custom resource loader
     * @tparam T Resource type the loader produces
     * @param loader The loader instance
     */
    template<typename T>
    void registerLoader(Unique<ResourceLoader<T>> loader);

    /**
     * @brief Gets a registered loader for a resource type
     * @tparam T Resource type
     * @return Pointer to the loader, or nullptr if not registered
     */
    template<typename T>
    ResourceLoader<T>* getLoader();

    /**
     * @brief Checks if a loader is registered for a type
     * @tparam T Resource type
     * @return True if a loader is registered
     */
    template<typename T>
    bool hasLoader() const;

    /**
     * @brief Gets the loader registry for advanced usage
     * @return Reference to the loader registry
     */
    LoaderRegistry& getLoaderRegistry() { return loaderRegistry_; }

private:
    void* shaderRetiredOwner_ = nullptr;
    ShaderRetiredCallback shaderRetiredCallback_ = nullptr;
    ResourcePool<Shader> shaders_;
    ResourcePool<Texture> textures_;
    ResourcePool<VertexBuffer> vertexBuffers_;
    ResourcePool<IndexBuffer> indexBuffers_;
    bool meshEdges_ = false;
    ResourcePool<Mesh> meshes_;
    /// The pages meshes of one vertex shape share (see MeshArena).
    MeshArena meshArena_;
    /// See meshesRevision().
    u64 meshes_revision_ = 0;
    /** Gives back what a mesh's geometry holds, its own buffers and layout or its place in a page; the edges are apart. */
    void releaseMeshGeometry(VertexBufferHandle vertices, IndexBufferHandle indices, VertexLayoutHandle layout,
                             u32 arenaPage, u32 arenaFirstVertex, u32 vertexCount, u32 firstIndex, u32 indexCount);

public:
    /** The shared mesh pages standing and the bytes they hold, for a profiler. */
    u32 meshPageCount() const { return meshArena_.pageCount(); }
    u64 meshPageBytes() const { return meshArena_.pageBytes(); }

private:
    ResourcePool<Environment> environments_;
    ResourcePool<ProbeVolume> probeVolumes_;
    ResourcePool<text::BitmapFont> fonts_;
    /** Builds the buffers and layout one mesh is drawn from, replacing whatever
     *  it had. Shared by the mint and the rebuild so the two cannot describe the
     *  same geometry differently. Leaves the mesh untouched when it fails. */
    bool realizeMesh(Mesh& mesh, ConstSpan<u8> vertexBytes, ConstSpan<u32> indices,
                     ConstSpan<GfxVertexAttribute> channels, u32 vertexStride,
                     const glm::vec3& localMin, const glm::vec3& localMax,
                     ConstSpan<f32> inverseBind, const MeshMorphSource& morph);
    /** The deltas as a texture the vertex stage fetches from, or an invalid
     *  handle where they do not fit one — see realizeMesh for what that means. */
    esengine::TextureHandle createMorphTexture(GfxContent content, const MeshMorphSource& morph,
                                               u32 vertexCount);

    std::unordered_map<std::string, TextureHandle> guidToTexture_;
    std::unordered_map<TextureHandle::IdType, TextureMetadata> textureMetadata_;
    LoaderRegistry loaderRegistry_;
    mutable ResourceStats stats_;
    GfxDevice* device_ = nullptr;  ///< GPU device for resource creation (set in init)
    bool initialized_ = false;
};

// =============================================================================
// Template Implementations
// =============================================================================

template<typename T>
VertexBufferHandle ResourceManager::createVertexBuffer(GfxContent content, ConstSpan<T> data) {
    auto buffer = VertexBuffer::create(*device_, content, data);
    if (!buffer) return VertexBufferHandle();
    return vertexBuffers_.add(std::move(buffer));
}

template<typename T>
void ResourceManager::registerLoader(Unique<ResourceLoader<T>> loader) {
    loaderRegistry_.registerLoader<T>(std::move(loader));
}

template<typename T>
ResourceLoader<T>* ResourceManager::getLoader() {
    return loaderRegistry_.getLoader<T>();
}

template<typename T>
bool ResourceManager::hasLoader() const {
    return loaderRegistry_.hasLoader<T>();
}

}  // namespace esengine::resource