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.

8.4 KB
Raw Blame
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
 * @file    Handle.hpp
 * @brief   Type-safe resource handle system
 * @details Provides lightweight, type-safe handles for referencing GPU
 *          resources without exposing raw pointers or ownership semantics.
 *
 * @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"

// Standard library
#include <functional>

namespace esengine::resource {

// =============================================================================
// Handle Template
// =============================================================================

/**
 * @brief Type-safe resource handle
 *
 * @details Lightweight identifier for resources stored in ResourcePool.
 *          Handles are copyable and comparable, but do not manage resource
 *          lifetime - use ResourceManager for acquire/release.
 *
 * @tparam T The resource type this handle references
 *
 * @code
 * ShaderHandle shader = resourceManager.loadShader("vert.glsl", "frag.glsl");
 * if (shader.isValid()) {
 *     Shader* ptr = resourceManager.getShader(shader);
 * }
 * @endcode
 */
template<typename T>
class Handle {
public:
    using IdType = u32;

    // Bit-packing math is shared with Entity via PackedId (single source). The
    // resource handle split stays 20+12 (independent of the ECS entity split).
    using Layout = PackedId<20, 12>;
    static constexpr u32 INDEX_BITS = Layout::INDEX_BITS;
    static constexpr u32 GEN_BITS = Layout::GEN_BITS;
    static constexpr u32 INDEX_MASK = Layout::INDEX_MASK;
    static constexpr u32 GEN_MASK = Layout::GEN_MASK;
    static constexpr IdType INVALID = 0;

    /** @brief Creates an invalid handle */
    Handle() = default;

    /**
     * @brief Creates a handle from a packed ID (index + generation)
     * @param id The packed resource identifier
     */
    explicit Handle(IdType id) : id_(id) {}

    /**
     * @brief Creates a handle from separate index and generation
     * @param index Slot index in the resource pool (max ~1M)
     * @param generation Reuse counter for the slot (max 4095)
     */
    static Handle fromParts(u32 index, u32 generation) {
        return Handle(Layout::pack(index, generation));
    }

    /** @brief Checks if the handle references a valid resource */
    bool isValid() const { return id_ != INVALID; }

    /** @brief Gets the packed identifier (index + generation) */
    IdType id() const { return id_; }

    /** @brief Extracts the slot index from the packed handle */
    u32 index() const { return Layout::indexOf(id_); }

    /** @brief Extracts the generation from the packed handle */
    u32 generation() const { return Layout::generationOf(id_); }

    /** @brief Extracts index from a raw packed ID */
    static u32 extractIndex(IdType packed) { return Layout::indexOf(packed); }

    /** @brief Extracts generation from a raw packed ID */
    static u32 extractGeneration(IdType packed) { return Layout::generationOf(packed); }

    /** @brief Equality comparison */
    bool operator==(const Handle& other) const { return id_ == other.id_; }

    /** @brief Inequality comparison */
    bool operator!=(const Handle& other) const { return id_ != other.id_; }

    /** @brief Explicit bool conversion (true if valid) */
    explicit operator bool() const { return isValid(); }

private:
    IdType id_ = INVALID;
};

// =============================================================================
// SharedHandle (RAII wrapper)
// =============================================================================

/**
 * @brief RAII wrapper around Handle that auto-releases on destruction
 *
 * @details Calls a release function when the last SharedHandle copy is
 *          destroyed. Use for scoped resource ownership. The underlying
 *          Handle can be extracted with get() for hot-path access.
 *
 * @tparam T The resource type
 *
 * @code
 * {
 *     auto tex = SharedHandle<Texture>::make(
 *         rm.loadTexture("player.png"),
 *         [&rm](TextureHandle h) { rm.releaseTexture(h); });
 *     // Use tex.get() ...
 * } // auto-released here
 * @endcode
 */
template<typename T>
class SharedHandle {
public:
    using ReleaseFunc = std::function<void(Handle<T>)>;

    SharedHandle() = default;

    /** @brief Creates a SharedHandle that will auto-release */
    static SharedHandle make(Handle<T> handle, ReleaseFunc release) {
        SharedHandle sh;
        if (handle.isValid()) {
            sh.state_ = std::make_shared<State>(handle, std::move(release));
        }
        return sh;
    }

    /** @brief Gets the underlying raw handle (no ownership transfer) */
    Handle<T> get() const { return state_ ? state_->handle : Handle<T>{}; }

    /** @brief Checks if valid */
    bool isValid() const { return state_ && state_->handle.isValid(); }
    explicit operator bool() const { return isValid(); }

    /** @brief Manually release (all copies become invalid) */
    void reset() { state_.reset(); }

private:
    struct State {
        Handle<T> handle;
        ReleaseFunc release;

        State(Handle<T> h, ReleaseFunc r) : handle(h), release(std::move(r)) {}
        ~State() {
            if (handle.isValid() && release) {
                release(handle);
            }
        }

        State(const State&) = delete;
        State& operator=(const State&) = delete;
    };

    Shared<State> state_;
};

}  // namespace esengine::resource

// =============================================================================
// Forward Declarations
// =============================================================================

namespace esengine {
    class Shader;
    class Texture;
    class VertexBuffer;
    class IndexBuffer;
    class Mesh;
    class Environment;
    class ProbeVolume;
}

// Forward-declared only — the native spine runtime was removed (spine is fully
// side-module now), but SpineAnimation keeps its (vestigial) skeleton-data handle
// field so the component layout/hash is unchanged. Handle<T> stores just an id,
// so T never needs a definition here.
namespace esengine::spine {
    struct SpineSkeletonData;
}

namespace esengine::text {
    class BitmapFont;
}

// =============================================================================
// Handle Type Aliases
// =============================================================================

namespace esengine::resource {

/** @brief Handle to a shader resource */
using ShaderHandle = Handle<esengine::Shader>;

/** @brief Handle to a texture resource */
using TextureHandle = Handle<esengine::Texture>;

/** @brief Handle to a vertex buffer resource */
using VertexBufferHandle = Handle<esengine::VertexBuffer>;

/** @brief Handle to an index buffer resource */
using IndexBufferHandle = Handle<esengine::IndexBuffer>;

/** @brief Handle to GPU-resident geometry */
using MeshHandle = Handle<esengine::Mesh>;

/** @brief Handle to a baked environment (irradiance + prefiltered reflection) */
using EnvironmentHandle = Handle<esengine::Environment>;

/** @brief Handle to a grid of baked irradiance */
using ProbeVolumeHandle = Handle<esengine::ProbeVolume>;

/** @brief Handle to a Spine skeleton data resource (vestigial — see fwd decl) */
using SpineDataHandle = Handle<esengine::spine::SpineSkeletonData>;

/** @brief Handle to a bitmap font resource */
using BitmapFontHandle = Handle<esengine::text::BitmapFont>;

/** @brief RAII handle to a shader resource */
using SharedShaderHandle = SharedHandle<esengine::Shader>;

/** @brief RAII handle to a texture resource */
using SharedTextureHandle = SharedHandle<esengine::Texture>;

/** @brief RAII handle to a bitmap font resource */
using SharedBitmapFontHandle = SharedHandle<esengine::text::BitmapFont>;

}  // namespace esengine::resource

// =============================================================================
// Std Hash Support
// =============================================================================

namespace std {

template<typename T>
struct hash<esengine::resource::Handle<T>> {
    size_t operator()(const esengine::resource::Handle<T>& handle) const noexcept {
        return hash<esengine::u32>{}(handle.id());
    }
};

}  // namespace std