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.

13.4 KB
Raw Blame
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
 * @file    Buffer.hpp
 * @brief   GPU buffer abstractions for vertex and index data
 * @details VertexBuffer and IndexBuffer are thin RAII handles over GfxDevice.
 *          They hold no GL state directly — every GPU operation is delegated
 *          to the device, so this layer has zero GL dependency.
 *
 * @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 "./GfxContent.hpp"
#include "./GfxEnums.hpp"

// Standard library
#include <span>
#include <vector>

namespace esengine {

class GfxDevice;

// =============================================================================
// Shader Data Types
// =============================================================================

/**
 * @brief Vertex attribute data types
 *
 * @details Used to describe the data type of each vertex attribute
 *          in the vertex layout. Maps to OpenGL/WebGL types.
 */
enum class ShaderDataType {
    None = 0,
    Float,   ///< Single 32-bit float
    Float2,  ///< vec2 (2 floats)
    Float3,  ///< vec3 (3 floats)
    Float4,  ///< vec4 (4 floats)
    Int,     ///< Single 32-bit integer
    Int2,    ///< ivec2 (2 ints)
    Int3,    ///< ivec3 (3 ints)
    Int4,    ///< ivec4 (4 ints)
    Bool,    ///< Boolean (1 byte)
    UByte4N  ///< 4 unsigned bytes, normalized to [0,1] vec4
};

/**
 * @brief Gets the size in bytes of a shader data type
 * @param type The shader data type
 * @return Size in bytes
 */
u32 shaderDataTypeSize(ShaderDataType type);

/**
 * @brief Gets the component count of a shader data type
 * @param type The shader data type
 * @return Number of components (e.g., 3 for Float3)
 */
u32 shaderDataTypeComponentCount(ShaderDataType type);

// =============================================================================
// Vertex Attribute
// =============================================================================

/**
 * @brief Describes a single vertex attribute
 *
 * @details Contains all information needed to configure a vertex attribute
 *          pointer in OpenGL/WebGL.
 */
struct VertexAttribute {
    /** @brief Attribute name (for debugging) */
    std::string name;
    /** @brief Data type of the attribute */
    ShaderDataType type;
    /** @brief Size in bytes */
    u32 size;
    /** @brief Byte offset within the vertex */
    u32 offset;
    /** @brief Whether to normalize integer data to [0,1] or [-1,1] */
    bool normalized;

    /** @brief Default constructor */
    VertexAttribute() = default;

    /**
     * @brief Constructs a vertex attribute
     * @param type Data type
     * @param name Attribute name
     * @param normalized Whether to normalize integer data
     */
    VertexAttribute(ShaderDataType type, const std::string& name, bool normalized = false)
        : name(name), type(type), size(shaderDataTypeSize(type)), offset(0), normalized(normalized) {}
};

// =============================================================================
// Vertex Layout
// =============================================================================

/**
 * @brief Describes the layout of vertex data in a buffer
 *
 * @details Specifies the attributes that make up each vertex and their
 *          arrangement in memory. Used to configure vertex attribute pointers.
 *
 * @code
 * VertexLayout layout = {
 *     {ShaderDataType::Float3, "a_position"},
 *     {ShaderDataType::Float2, "a_texCoord"},
 *     {ShaderDataType::Float4, "a_color"}
 * };
 * @endcode
 */
class VertexLayout {
public:
    /** @brief Default constructor (empty layout) */
    VertexLayout() = default;

    /**
     * @brief Constructs layout from initializer list
     * @param attributes List of vertex attributes
     */
    VertexLayout(std::initializer_list<VertexAttribute> attributes)
        : attributes_(attributes) {
        calculateOffsetsAndStride();
    }

    VertexLayout(std::vector<VertexAttribute> attributes)
        : attributes_(std::move(attributes)) {
        calculateOffsetsAndStride();
    }

    /**
     * @brief Gets all vertex attributes
     * @return Const reference to attribute vector
     */
    const std::vector<VertexAttribute>& getAttributes() const { return attributes_; }

    /**
     * @brief Gets the stride (total size) of one vertex
     * @return Stride in bytes
     */
    u32 getStride() const { return stride_; }

    // Iterator support for range-based for loops
    std::vector<VertexAttribute>::iterator begin() { return attributes_.begin(); }
    std::vector<VertexAttribute>::iterator end() { return attributes_.end(); }
    std::vector<VertexAttribute>::const_iterator begin() const { return attributes_.begin(); }
    std::vector<VertexAttribute>::const_iterator end() const { return attributes_.end(); }

private:
    /**
     * @brief Calculates byte offsets and total stride
     */
    void calculateOffsetsAndStride() {
        u32 offset = 0;
        stride_ = 0;
        for (auto& attr : attributes_) {
            attr.offset = offset;
            offset += attr.size;
            stride_ += attr.size;
        }
    }

    std::vector<VertexAttribute> attributes_;
    u32 stride_ = 0;
};

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

/**
 * @brief GPU buffer for vertex data, static or dynamic; all GPU work goes through the device.
 */
class VertexBuffer {
public:
    VertexBuffer() = default;
    ~VertexBuffer();

    // Non-copyable, movable
    VertexBuffer(const VertexBuffer&) = delete;
    VertexBuffer& operator=(const VertexBuffer&) = delete;
    VertexBuffer(VertexBuffer&& other) noexcept;
    VertexBuffer& operator=(VertexBuffer&& other) noexcept;

    // =========================================================================
    // Type-Safe Creation Methods
    // =========================================================================

    /**
     * @brief Creates a static buffer from a span
     * @tparam T Vertex type
     * @param device Graphics device
     * @param data Span of vertex data
     * @return Unique pointer to the buffer
     */
    template<typename T>
    static Unique<VertexBuffer> create(GfxDevice& device, GfxContent content, std::span<const T> data) {
        return createRaw(device, content, data.data(), static_cast<u32>(data.size_bytes()));
    }

    /**
     * @brief Creates a static buffer from a vector
     */
    template<typename T>
    static Unique<VertexBuffer> create(GfxDevice& device, GfxContent content, const std::vector<T>& data) {
        return create(device, content, std::span<const T>(data));
    }

    /**
     * @brief Creates a static buffer from a C array
     */
    template<typename T, usize N>
    static Unique<VertexBuffer> create(GfxDevice& device, GfxContent content, const T (&data)[N]) {
        return create(device, content, std::span<const T>(data, N));
    }

    /**
     * @brief Creates a dynamic buffer of specified size
     * @param device Graphics device
     * @param sizeBytes Buffer size in bytes
     * @return Unique pointer to the buffer
     *
     * @details Use setData() to upload data later.
     */
    static Unique<VertexBuffer> create(GfxDevice& device, GfxContent content, u32 sizeBytes);

    // =========================================================================
    // Operations
    // =========================================================================

    /**
     * @brief Updates buffer data from a span
     */
    template<typename T>
    void setData(std::span<const T> data) {
        setDataRaw(data.data(), static_cast<u32>(data.size_bytes()));
    }

    /**
     * @brief Updates buffer data from a vector
     */
    template<typename T>
    void setData(const std::vector<T>& data) {
        setData(std::span<const T>(data));
    }

    /**
     * @brief Updates buffer data from a C array
     */
    template<typename T, usize N>
    void setData(const T (&data)[N]) {
        setData(std::span<const T>(data, N));
    }

    // =========================================================================
    // Layout
    // =========================================================================

    /**
     * @brief Sets the vertex layout
     * @param layout The vertex attribute layout
     */
    void setLayout(const VertexLayout& layout) { layout_ = layout; }

    /**
     * @brief Gets the vertex layout
     * @return Const reference to the layout
     */
    const VertexLayout& getLayout() const { return layout_; }

    /** @brief Gets the device buffer handle */
    BufferHandle handle() const { return handle_; }

    // =========================================================================
    // Raw API for internal use only
    // =========================================================================

    /**
     * @brief Creates a buffer from raw data pointer for internal use
     * @param device Graphics device
     * @param data Pointer to vertex data
     * @param sizeBytes Size of data in bytes
     * @return Unique pointer to the buffer
     */
    static Unique<VertexBuffer> createRaw(GfxDevice& device, GfxContent content, const void* data, u32 sizeBytes);

    /**
     * @brief Updates buffer data from raw pointer (internal use)
     * @param data Pointer to new data
     * @param sizeBytes Size of data in bytes
     */
    void setDataRaw(const void* data, u32 sizeBytes);

    /**
     * @brief Updates a portion of buffer data with offset (internal use)
     * @param data Pointer to new data
     * @param sizeBytes Size of data in bytes
     * @param offsetBytes Offset in bytes from buffer start
     */
    void setSubDataRaw(const void* data, u32 sizeBytes, u32 offsetBytes);

private:
    GfxDevice* device_ = nullptr;  ///< Set by the create* factories; all GL goes through it.
    BufferHandle handle_ = BufferHandle::Invalid;
    VertexLayout layout_;
};

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

/**
 * @brief GPU buffer for index data
 *
 * @details Wraps a GfxDevice element buffer object. Supports both 16-bit and
 *          32-bit indices.
 *
 * @code
 * std::vector<u32> indices = {0, 1, 2, 2, 3, 0};
 * auto ebo = IndexBuffer::create(device, GfxContent::retained(), std::span(indices));
 * @endcode
 */
class IndexBuffer {
public:
    IndexBuffer() = default;
    ~IndexBuffer();

    // Non-copyable, movable
    IndexBuffer(const IndexBuffer&) = delete;
    IndexBuffer& operator=(const IndexBuffer&) = delete;
    IndexBuffer(IndexBuffer&& other) noexcept;
    IndexBuffer& operator=(IndexBuffer&& other) noexcept;

    // =========================================================================
    // Type-Safe Creation Methods
    // =========================================================================

    /** @brief Creates an index buffer from a span of 32-bit indices */
    static Unique<IndexBuffer> create(GfxDevice& device, GfxContent content, std::span<const u32> indices) {
        return create(device, content, indices.data(), static_cast<u32>(indices.size()));
    }

    /** @brief Creates an index buffer from a span of 16-bit indices */
    static Unique<IndexBuffer> create(GfxDevice& device, GfxContent content, std::span<const u16> indices) {
        return create(device, content, indices.data(), static_cast<u32>(indices.size()));
    }

    /** @brief Creates an index buffer from a vector of 32-bit indices */
    static Unique<IndexBuffer> create(GfxDevice& device, GfxContent content, const std::vector<u32>& indices) {
        return create(device, content, std::span<const u32>(indices));
    }

    /** @brief Creates an index buffer from a vector of 16-bit indices */
    static Unique<IndexBuffer> create(GfxDevice& device, GfxContent content, const std::vector<u16>& indices) {
        return create(device, content, std::span<const u16>(indices));
    }

    /** @brief Creates an index buffer with 32-bit indices from pointer */
    static Unique<IndexBuffer> create(GfxDevice& device, GfxContent content, const u32* indices, u32 count);

    /**
     * @brief Creates an index buffer with 16-bit indices from pointer
     * @details Use 16-bit indices for better performance when vertex
     *          count is under 65536.
     */
    static Unique<IndexBuffer> create(GfxDevice& device, GfxContent content, const u16* indices, u32 count);

    // =========================================================================
    // Operations
    // =========================================================================

    /** @brief Gets the number of indices */
    u32 getCount() const { return count_; }

    /** @brief Gets the device buffer handle */
    BufferHandle handle() const { return handle_; }

    /** @brief Returns true if using 16-bit indices */
    bool is16Bit() const { return is16Bit_; }

private:
    GfxDevice* device_ = nullptr;  ///< Set by the create* factories; all GL goes through it.
    BufferHandle handle_ = BufferHandle::Invalid;
    u32 count_ = 0;
    bool is16Bit_ = false;
};

}  // namespace esengine