Program Listing for File ASManager.ixx

Program Listing for File ASManager.ixx#

↰ Return to documentation for file (Src/GraphicsEngineVulkan/renderer/accelerationStructures/ASManager.ixx)

module;
#include <cstddef>
#include <cstdint>
#include <memory>
#include <utility>
#include <vector>
#include <vulkan/vulkan.hpp>

#include "renderer/accelerationStructures/BottomLevelAccelerationStructure.hpp"
#include "renderer/accelerationStructures/TopLevelAccelerationStructure.hpp"

export module kataglyphis.vulkan.as_manager;

import kataglyphis.vulkan.device;
import kataglyphis.vulkan.buffer_manager;
import kataglyphis.vulkan.scene;
import kataglyphis.vulkan.mesh;
import kataglyphis.vulkan.model;
import kataglyphis.vulkan.buffer;

export namespace Kataglyphis::VulkanRendererInternals {
struct BuildAccelerationStructure
{
    vk::AccelerationStructureBuildGeometryInfoKHR build_info;
    vk::AccelerationStructureBuildSizesInfoKHR size_info;
    const vk::AccelerationStructureBuildRangeInfoKHR *range_info;
    BottomLevelAccelerationStructure single_blas;
};

struct BlasInput
{
    std::vector<vk::AccelerationStructureGeometryKHR> as_geometry;
    std::vector<vk::AccelerationStructureBuildRangeInfoKHR> as_build_offset_info;
};

class ASManager
{
  public:
    class Retired
    {
      public:
        void add(vk::AccelerationStructureKHR handle, VulkanBuffer &&buffer)
        {
            if (handle) { handles.push_back(handle); }
            addBuffer(std::move(buffer));
        }
        void addBuffer(VulkanBuffer &&buffer)
        {
            if (buffer.getBuffer()) { buffers.push_back(std::move(buffer)); }
        }
        [[nodiscard]] bool empty() const { return handles.empty() && buffers.empty(); }
        void release(vk::Device device)
        {
            for (vk::AccelerationStructureKHR handle : handles) { device.destroyAccelerationStructureKHR(handle); }
            handles.clear();
            buffers.clear();
        }

      private:
        std::vector<vk::AccelerationStructureKHR> handles;
        std::vector<VulkanBuffer> buffers;
    };

    ASManager();

    vk::AccelerationStructureKHR &getTLAS() { return tlas.vulkanAS; };
    [[nodiscard]] bool hasTLAS() const { return static_cast<bool>(tlas.vulkanAS); }

    // Keeps the BLAS of the leading models the scene still holds and builds the rest, then the TLAS.
    void createASForScene(const std::shared_ptr<VulkanDevice> &device,
      vk::CommandPool commandPool,
      Kataglyphis::Scene *scene);

    void
      createTLAS(const std::shared_ptr<VulkanDevice> &device, vk::CommandPool commandPool, Kataglyphis::Scene *scene);

    // True when the TLAS holds the scene's models with their current BLAS, so new transforms are an update, not a build.
    [[nodiscard]] bool canUpdateTLAS(const Kataglyphis::Scene *scene) const;
    // Records the instances' new transforms and an in-place TLAS update into a frame's command buffer; false, recording
    // nothing, when canUpdateTLAS is not.
    bool recordTLASUpdate(vk::CommandBuffer commandBuffer, Kataglyphis::Scene *scene);

    // What the builds since the last call replaced, for the caller to release once no frame in flight reads it.
    [[nodiscard]] Retired takeRetired() { return std::exchange(retired, {}); }

    // Test instrumentation: a transform change must update the TLAS, not build it again.
    [[nodiscard]] std::uint64_t getTlasBuildCount() const { return tlasBuildCount; }
    [[nodiscard]] std::uint64_t getTlasUpdateCount() const { return tlasUpdateCount; }
    // Test seam, called only by the renderer's: drops the TLAS the way a failed createTLAS leaves it.
    void simulateMissingTlasForTesting()
    {
        if (vulkanDevice) { releaseTLAS(); }
    }

    // Every BLAS built so far, compaction copies not counted; the incremental-append golden reads it.
    [[nodiscard]] std::uint64_t getBlasBuildCount() const { return blasBuildCount; }
    [[nodiscard]] std::vector<vk::AccelerationStructureKHR> getBlasHandles() const;

    void cleanUp();

    ~ASManager();

  private:
    std::shared_ptr<VulkanDevice> vulkanDevice{ nullptr };
    Kataglyphis::VulkanBufferManager vulkanBufferManager;

    std::vector<BottomLevelAccelerationStructure> blas;
    // blas[i] was built from blasModels[i]; a model the scene no longer holds at index i invalidates it and the rest.
    std::vector<std::weak_ptr<Model>> blasModels;
    std::uint64_t blasBuildCount = 0;
    TopLevelAccelerationStructure tlas;
    // The models and BLAS the TLAS's instances name, in instance order.
    std::vector<std::weak_ptr<Model>> tlasModels;
    std::vector<vk::AccelerationStructureKHR> tlasBlas;
    std::uint64_t tlasBuildCount = 0;
    std::uint64_t tlasUpdateCount = 0;
    // Replaced BLAS and TLAS, kept until takeRetired; cleanUp releases them on an idle device.
    Retired retired;

    // One instance per model: its BLAS, its transform and its first mesh's flat index.
    [[nodiscard]] std::vector<vk::AccelerationStructureInstanceKHR> tlasInstances(const VulkanDevice &device,
      const Kataglyphis::Scene &scene,
      const std::vector<uint32_t> &meshBaseOffsets) const;
    void releaseTLAS();

    // Builds one BLAS per model from blas.size() on, in one batch through one scratch buffer.
    bool
      createBLAS(const std::shared_ptr<VulkanDevice> &device, vk::CommandPool commandPool, Kataglyphis::Scene *scene);

    void destroyBLASFrom(std::size_t first);

    // Replaces every BLAS from `first` on with a compacted copy. Compaction
    // typically reclaims a large fraction of BLAS memory at no trace-time
    // cost; it is legal because the builds carry eAllowCompaction and the
    // build submission is fully synchronous before this runs. TLAS is built
    // AFTER, so it picks up the compacted device addresses naturally.
    void compactBLAS(const std::shared_ptr<VulkanDevice> &device, vk::CommandPool commandPool, std::size_t first);

    static void createSingleBlas(const std::shared_ptr<VulkanDevice> &device,
      vk::CommandBuffer command_buffer,
      BuildAccelerationStructure &build_as_structure,
      vk::DeviceAddress scratch_device_or_host_address,
      std::size_t index);

    static void createAccelerationStructureInfosBLAS(const std::shared_ptr<VulkanDevice> &device,
      BuildAccelerationStructure &build_as_structure,
      BlasInput &blas_input,
      vk::DeviceSize &current_scratch_size,
      vk::DeviceSize &current_size);

    static void objectToVkGeometryKHR(const std::shared_ptr<VulkanDevice> &device,
      Kataglyphis::Mesh *mesh,
      vk::AccelerationStructureGeometryKHR &acceleration_structure_geometry,
      vk::AccelerationStructureBuildRangeInfoKHR &acceleration_structure_build_range_info);
};
}// namespace Kataglyphis::VulkanRendererInternals