Files
b26b9cf743 Add Vulkan rendering backend, with HDR10 output and raytraced shadows (#7554)
* Shadow overhaul round 2: PCSS, dynamic cascades, cockpit/instanced shadows

Squashed snapshot of lafiel/shadow_overhaul_2's continuation work
(d3922aa87..010f9d2d9), which has no separate upstream PR of its own.

* Add Vulkan rendering backend

Squashed snapshot of the Vulkan backend as vendored into this branch
(ce2d1e85f..6ce539463, authored by Mara van der Laan with build/CI
fixes by Taylor Richards). This work has its own upstream PR #7553
(notimaginative:vulkan-pr-new) and is not otherwise original to true-hdr.

* Add true HDR output, RT shadows, and PCSS shadows for Vulkan

Squashed snapshot of true-hdr's own integration work: true HDR
framebuffer output, wiring the shadow overhaul into the Vulkan
backend (raytraced + cascaded shadow maps), logging refactors, log
filter UI, and CI/build fixes.

* refactor: update Vulkan logging calls to use `nprintf` for scoped logging

* fix: correct shadow cascade count in Vulkan logging calls

* fix: fall back to PATH-resolved ccache when CCACHE_PATH is stale

CI hardcodes /usr/local/bin/ccache, but macOS runners on Apple Silicon
hosts install Homebrew (and ccache) under /opt/homebrew instead,
causing all four Mac configs to fail with "No such file or directory".

* Fix vulkan texture readback to correctly handle transparent pipelines

* Put the pixel swizzles into a util file

* OOB safety check

* Fix fog handling

* Fix MSAA in Vulkan

* fix: enable SMAA for vulkan

* adapt the post-processing AA shaders to hdr

* fix clang-tidy warnings: concatenate nested namespaces, static methods

pixel_swizzle.{h,cpp}: collapse `namespace graphics { namespace util {`
into `namespace graphics::util {` (modernize-concat-nested-namespaces).

VulkanState.h/VulkanDraw.h: getClearColor()/setClearColor() only touch
gr_screen and other globals, no instance state, so make them static
(readability-convert-member-functions-to-static) and drop the
top-level const on getClearColor()'s return type
(readability-const-return-type).

* fix clang-tidy warning

* Extend raytraced shadows to all directional lights

RT shadows previously only shadowed the first directional light in the
scene, even though multi-sun missions push more than one directional
light into the engine. The TLAS raytraced shadows query against is
already light-agnostic, so this extends both the deferred lighting
pass and the forward MODEL shader to shadow every directional light
(capped by a new Max Raytraced Shadow Lights option, configurable via
the in-game Options menu or the Lab's Scene rendering options).

Cascaded shadow maps are untouched: they're built for a single light
only, so the deferred pass still limits itself to one shadowed
directional light whenever CSM (not raytracing) is the active method.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_016DA6JHJ3twz2oHGQcZ1Udc

* refactor: improve shader flag handling and render target finalization in Vulkan backend

- Consolidate shader flag setup logic in VulkanPostProcessingLighting to simplify configuration.
- Fix dead field usage in VulkanDraw by ensuring correct image view selection for environment maps.
- Add mip chain regeneration in VulkanRenderer::endRenderTarget to ensure correct mip levels for cubemaps.

* fix: ensure correct mip chain initialization in cubemap rendering

- Add mip chain generation to VulkanDraw for cubemaps with multiple mip levels.
- Fix potential issue with uninitialized mip levels above level 0 in deferred-f.sdr sampling paths.

* fix: don't crash on startup when environment locale is unavailable

std::locale("") pulls in the process's environment locale categories
(LC_CTYPE, LC_MONETARY, LC_PAPER, etc.), and throws std::runtime_error
if any of them names a locale not installed on the host (e.g.
mismatched regional-format overrides). Since SCP_default_locale is
constructed during static initialization, before main() and before any
of our own exception handling exists, an uncaught throw here aborted
the whole process before the game even started. Fall back to the
classic "C" locale instead, which is sufficient since this locale is
only ever used for ASCII case-folding (SCP_toupper/tolower/isdigit).

Co-Authored-By: Claude Sonnet 5 <[email protected]>

* `feat: add raytraced shadows for local lights and optimize TLAS management`

* Make the Commandline authoritative for -res and -vulkan / -opengl

* address BMagnu's comments on the original PR

* update prebuilt version hash to 62c89ef6

* refactor: standardize graphics API handling and document Vulkan limitations in qtFRED

- Updated `AboutDialogModel.cpp` to use `GraphicsAPI` enum for better clarity.
- Ensured qtFRED falls back to OpenGL when Vulkan is requested.
- Added detailed documentation in `qtfred/README.md` regarding Vulkan backend limitations and requirements.

* chore: include cmdline library in main and mission management modules

* docs: add known issue for blank render viewport under Wayland in README.md

* fix CI issues

* chore: add `GR_DEBUG_SCOPE` markers across Vulkan post-processing and rendering paths for improved debugging

* feat: improve Vulkan HDR pipeline with separate encode paths for SDR and HDR10

- Added an HDR10-specific output encode pass in `VulkanRenderer` and `VulkanPostProcessor` that applies PQ/BT.2020 transfer.
- Introduced an optimized SDR fallback path with direct blit support for devices that can skip shader draws.
- Updated `m_sceneLdrCompressed` to provide [0,1]-clamped proxies for HDR edge detection.
- Refactored `copyImageToImage` and added `blitImageToImage` to allow format conversions and optimized transfers.
- Replaced `hdr_mode` with explicit HDR10 flags and data structures for clearer state handling.

* refactor: encapsulate SMAA processing and refactor VulkanPostProcessor

- Moved SMAA-specific logic into `VulkanSMAA` class for better separation of concerns.
- Simplified `initSMAA`, `shutdownSMAA`, and `executeSMAA` logic by leveraging `VulkanLDR` and `PostProcessContext` abstractions.
- Improved initialization and cleanup code with clearer resource lifecycle management.
- Updated debug markers and messages to reference `VulkanSMAA`.
- Enhanced flexibility of fullscreen triangle rendering API with additional parameters (`sampleCount`, `bindGlobalSet`).

* Update Vulkan porting credits in AboutDialogModel

* fix CI issues again

* fix: correct Y-flip in viewport setup for Vulkan light volumes

- Adjusted viewport height to negative value to account for G-buffer render pass's negative Y-axis convention.
- Ensured proper alignment of point and tube light volumes with actual light positions.

* feat: add user-adjustable gamma correction to SDR and HDR10 output paths

- Added gamma correction to HDR10 path, applying user settings before PQ/BT.2020 encode.
- Replaced the SDR blit-only path with an encode pass that applies gamma correction, ensuring consistent behavior across devices.
- Refactored VulkanPostProcessor and associated shaders to support gamma slider adjustments for both SDR and HDR output.

* fix: ensure proper uniform and cull mode setup for Vulkan sphere rendering

- Added uniform buffer setup and default material uniforms in `vulkan_draw_sphere`.
- Disabled face culling in material definition for sphere rendering to align behavior with OpenGL.

* Ensure memory flushes after UBO updates and add explicit pipeline barrier for MoltenVK compatibility.

* fix: add clear pass for SMAA edge detection to prevent persistent artifacts

* feat: add Vulkan debug-utils messenger, opt-in sync validation, frame diagnostics

Groundwork for the renderer-review fix series (.agents/plans/
vulkan-renderer-review-fixes.md, Phase 0):

- Register a VK_EXT_debug_utils messenger (preferred) instead of only the
  deprecated VK_EXT_debug_report callback, which is kept as a fallback for
  loaders without debug-utils. The messenger config is also chained into
  instance creation so vkCreateInstance-time messages are captured.
  Validation errors/warnings now go to the main log via mprintf.
- New -gr_sync_validation cmdline flag (implies -gr_debug): chains
  VkValidationFeaturesEXT with synchronization validation into instance
  creation when VK_LAYER_KHRONOS_validation is available. This is the
  regression net for the synchronization fixes in the following commits.
- Frame stats now report descriptor sets/writes allocated per frame and the
  total pipeline count (descriptor-manager counters; DescriptorWriter::flush
  moved out-of-line to report into the manager).

Co-Authored-By: Claude Fable 5 <[email protected]>

* refactor: unify Vulkan render-pass begins, clamp in-pass clears, add per-frame UBO ring

Phase 1 of the renderer-review fix series: shared helpers that the
correctness fixes build on.

- New VulkanRenderer::beginTrackedRenderPass(PassBeginDesc): every render-pass
  begin on the frame command buffer now records vkCmdBeginRenderPass and
  updates the state tracker (pass, color attachment count, sample count,
  render area, viewport) in one place. Converted: setupFrame,
  beginSceneRendering (both branches), resumeSceneRendering,
  endSceneRendering, beginRenderTarget (viewport kept for gr_set_viewport),
  resumeSwapChainPass, plus new resumeScenePassAfterCopy() shared by
  copyEffectTexture/copySceneDepthForParticles and
  rebeginSwapChainPassAfterReadback() shared by both readbackFramebuffer
  exits (~200 lines of duplicated begin/clear/viewport blocks removed).
- The state tracker records the active render area; all four
  vkCmdClearAttachments sites clamp their rects against it and skip empty
  results. Previously gr_screen-sized clear rects could exceed a smaller
  off-screen render target's render area, which is invalid API usage.
- New PerFrameUboRing utility (VulkanPerFrameUbo.h/.cpp): a persistently
  mapped uniform buffer with one slot region per frame in flight and a
  self-flushing alloc(). Used by the next commit to fix the cross-frame
  UBO races.

Deliberate behavior deltas (all safe-direction): the helper always sets
colorAttachmentCount/sampleCount (some sites previously inherited stale
values), and resumeSwapChainPass/resumeSceneRendering now also reset the
standard flipped viewport instead of leaving the previous one.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix: eliminate Vulkan cross-frame UBO/buffer races, make gr_sync honest

Phase 2 of the renderer-review fix series: with two frames in flight, several
host-visible resources were rewritten by the CPU while the previous frame's
GPU work could still be reading them.

- The post-processing scratch UBO is now a PerFrameUboRing (per-frame-in-
  flight slot regions, persistently mapped, self-flushing alloc). All the
  per-pass map/unmap/cursor bookkeeping in bloom/LDR/fog/SMAA is deleted;
  the cursor resets exactly once per frame via the new
  VulkanPostProcessor::beginFrame() hook in setupFrame.
  This also fixes two latent bugs: (a) fog consumed scratch slots mid-scene
  and bloom's later same-frame cursor reset overwrote them before submission
  whenever fog+bloom were both active; (b) volumetric_fog_data (288 bytes)
  overflowed the 256-byte slots - the memcpy spilled into the neighboring
  slot and the shader's bound range ended before the aspect/fov/noise
  fields. Slots are now 512 bytes (static_assert at the fog call site) and
  the per-frame budget is 32 slots.
- The dedicated tonemap, output-encode, and MSAA-resolve UBOs (each a single
  instance rewritten per frame, i.e. racy; the MSAA one also never flushed)
  are deleted entirely - those passes build their structs on the stack and
  allocate from the scratch ring.
- Static-buffer rewrites orphan instead of racing: getVkBuffer() stamps a
  last-used frame number, and a full-content updateBufferData() on a Static
  buffer used within the last MAX_FRAMES_IN_FLIGHT frames defers the old
  VkBuffer to the deletion queue and writes a fresh one. Offset writes
  (GPU-heap appends to fresh regions) and PersistentMapping buffers (the
  engine holds their mapped pointer and syncs via gr_sync) are exempt.
- gr_sync_wait now honors its contract: VulkanRenderFrame::waitForFinish
  takes a timeout and reports expiry without consuming the fence;
  VulkanRenderer::waitForFrame returns false for fences taken during the
  still-recording frame (previously it waited on a stale or idle slot and
  reported success) and resolves the frame->slot mapping correctly. This
  makes UniformBufferManager's segment-fence throttling actually protective
  on Vulkan for the first time.

Co-Authored-By: Claude Fable 5 <[email protected]>

* Refactor framebuffer and target lifecycle: centralized creation/resizing logic, improved resource management across Vulkan post-processing subsystems.

* Improve Vulkan cross-frame sync with explicit access masks and validation updates

- Unified Vulkan validation flag handling in setup, separating engine debug output from synchronization validation.
- Specified access masks and stage flags to address cross-frame WRITE_AFTER_WRITE vulnerabilities, notably in G-buffer, post-processing, and MSAA resolve paths.
- Adjusted subpass dependencies and image layout transitions to prevent read-after-write and write-after-write hazards, detected using `-gr_sync_validation`.
- Fixed uniform buffer and barrier transitions to ensure proper ordering in render passes across frames.

* Refactor Vulkan render-pass dependencies and sync stages for clarity and future testing

- Clarified dependency logic for cross-pass and cross-frame synchronization, ensuring explicit stage and access flag comments match observed behavior.
- Adjusted subpass dependencies to decouple render-pass compatibility definitions from dependency assumptions.
- Highlighted MoltenVK-specific issues and retained workarounds with notes for re-testing on macOS hardware.
- Updated synchronization barriers and validation notes to address historical inconsistencies across platforms.

* Remove transfer queue support; consolidate all operations into the graphics queue

- Removed transfer queue handling, simplifying buffer and queue logic to use the graphics queue for all transfer operations.
- Updated buffer sharing modes and removed related code paths and parameters for transfer queue families.
- Introduced exclusive buffer access, noting async transfer and queue ownership transfers are future work.
- Limited enabled device features to only those actively used by the renderer, reducing unnecessary feature requests (e.g., robustBufferAccess).

* Refactor frame advancement and descriptor management in VulkanRenderer

- Removed `endFrame()` from `VulkanDescriptorManager`, replacing it with `setCurrentFrame(frameIndex)` for explicit frame synchronization.
- Centralized frame index advancement within `VulkanRenderer` to ensure consistency across components.
- Invalidated cached descriptor set bindings at render-pass boundaries to handle raw recorder staleness correctly.
- Optimized pipeline descriptor rebind logic by removing redundant clears during pipeline changes.

* Refactor `PipelineConfig::hash` and Global descriptor set management for improved hashing and memoization efficiency

- Replaced inefficient shift-based hashing in `PipelineConfig::hash` with a robust `hashCombine` strategy to minimize bucket collisions.
- Introduced `maskBits` helper to streamline bitmask creation for boolean fields.
- Implemented memoization for Global (Set 0) descriptor sets, reducing redundant rebuilds across frames and improving performance.
- Added dirty state tracking (`m_globalSetDirty`) and invalidation logic for Global set updates following relevant input changes (e.g., TLAS or UBO modifications).

* Refactor Vulkan post-processing output logic: extracted shared `encodeToSwapChainPass` method to streamline HDR and SDR output paths.

* Optimize Vulkan descriptor set management with per-frame memoization

- Added memoization for Material (Set 1) and PerDraw (Set 2) descriptor sets to reuse cached sets across frames if inputs remain unchanged.
- Implemented precise input tracking for Material and PerDraw descriptor sets to detect and rebuild only when necessary.
- Reduced redundant Vulkan descriptor allocations and writes, improving performance on repeated or batched draw calls.

* Fix Vulkan access masks for G-buffer and scene pass transitions

- Added `eColorAttachmentRead` to access masks in multiple barriers to ensure proper synchronization for load operations (e.g., `loadOp=eLoad`) across render passes.
- Prevented `READ_AFTER_WRITE` synchronization validation issues in deferred and multi-pass rendering scenarios.
- Updated comments to clarify the reasoning behind the access mask changes and load dependencies.

* Refactor Vulkan resource management and indexed draw logic

- Consolidated destruction queue methods in `VulkanDeletionQueue` using a shared `queueHandle` template to reduce redundancy.
- Introduced `ModelDrawParams` structure and `computeModelDrawParams` function to unify indexed draw parameters for models and shadows.
- Simplified draw logic by eliminating repeated calculation of indexed draw parameters and improving code reuse.

* Add `releaseAnimationSlotRef` for ref-count handling of shared animation texture arrays

- Introduced `releaseAnimationSlotRef` to manage reference counting for shared animation texture-array slots, preventing premature destruction of shared resources.
- Updated `flushTextures` and related methods to integrate `releaseAnimationSlotRef` for shared slot cleanup.
- Refactored staging buffer creation into `createStagingBuffer` for 3D texture uploads and shared path consistency.
- Enhanced texture upload logic with improved tracking and logging for re-upload cases, aiding preloading gap analysis.
- Added instrumentation for on-demand mid-frame texture uploads in `FrameStats`.

* Refactor Vulkan resource and texture management, extend debug logging

- Updated smart pointer usage for consistency across Vulkan resource managers (`std::make_unique`).
- Removed redundant `cubeImageView` member and related cleanup logic; unified sampling view management.
- Added per-instance debug log counters (avoiding static state) for Vulkan texture uploads and bindings, improving visibility during initialization and run-time.
- Optimized `VulkanRenderer` property/feature getters by caching physical device properties and features during device creation.
- Improved memory region flushing logic for out-of-date offsets, aligning with Vulkan Memory Allocator behavior.
- Refactored render pass state tracking to reapply dynamic state reliably after mid-frame render passes.
- Enhanced validation and error handling for mismatched update texture formats.

* fix CI build warning

* Fix on-demand YUV texture locking and set alpha uniform for movie rendering in Vulkan

- Corrected bitmap lock type from `BMP_TEX_OTHER` to `BMP_AABITMAP` for YUV textures during on-demand loading.
- Updated movie rendering to bind alpha from the `MovieData` UBO (set 2, binding 4) for Vulkan, aligning behavior with OpenGL implementation.

* revert inadvertent changes introduced by a squash commit

* address ci issues

* remove wip stuff from code comments that make no sense to people who aren't me

* Remove unused LD_LIBRARY_PATH export and fix shader shadow map sampling.

* Refactor batched rendering uniform setup in Vulkan

- Removed unused fields from `genericData` uniform block, simplifying shader definitions.
- Updated Vulkan material uniform handling to align with OpenGL's batched rendering logic.
- Introduced `batched_data` struct for streamlined UBO updates, improving maintainability and clarity.

* Add `-hdr` command-line option for HDR nits configuration

- Introduced `-hdr` parameter to set paper white and peak luminance in nits, overriding in-game HDR settings.
- Added input validation with error feedback for incorrect format.

* Remove unused `MODEL_SDR_FLAG_SHADOW_MAP` macro from shader flags

* clean up unrelated changes

* Invalidate Vulkan state tracker bindings after external command buffer modifications

- Added `invalidateExternalBindings()` to `VulkanStateTracker` to handle stale pipelines, descriptors, and dynamic states caused by external Vulkan commands (e.g., ImGui renders mid-pass).
- Updated ImGui rendering flow to call `invalidateExternalBindings()` post-draw, ensuring consistent pipeline state for subsequent engine renders.
- Adjusted image usage flags to account for `eTransferSrc` in texture readbacks.
- Fixed barrier `dstAccessMask` and pipeline stage flags to ensure proper synchronization for image transitions.

* Add a few more generically useful lines to the log

* Simplify Qt deployment logic and improve handling for system-installed Qt on Linux

* add cmdline headers to make qtFred compile

* use VK_KHR_synchronization2 for sync and barrier purposes

* Simplify and clean up Qt deployment logic in CMake for qtfred

* update get_bitmap_from_texture to match the new API

* Enhance `-hdr` command-line option to force HDR output and support optional nits configuration with improved input validation and overrides.

* Improve Vulkan robustness, add device feature checks, and refine memory/logging.

- Added depth clamping support gated by device feature checks, with fallback where unsupported.
- Improved deferred lighting UBO overflow handling with user-accessible warnings and buffer size adjustments.
- Enhanced Vulkan logging for validation, allocation, and debugging:
  - Automatic logging for descriptor pool exhaustion/fragmentation.
  - Vertex format and resource destruction checks.
  - Notifications for generic layout transitions and volumetric texture uploads.
- Consolidated shader logic to ensure Vulkan and OpenGL parity.

* Remove HDR10 encode shader and consolidate gamma correction logic for SDR and HDR10. Replace `Verify` assertions with `Assert`

* Add braces to conditional in object lighting logic for clarity

* Refine Vulkan memory allocation checks with `Verification` for improved error handling and messaging.

* Refine VulkanBuffer resize logic to preserve contents with CPU-side copy and add safeguards for non-coherent memory scenarios.

* Add detailed comments explaining descriptor array capacity constants in VulkanDescriptorManager

* Gate shadow support on depth clamp feature availability and clarify its necessity with improved comments.

---------

Co-authored-by: BMagnu <[email protected]>
Co-authored-by: Mara van der Laan <[email protected]>
Co-authored-by: Claude <[email protected]>
2026-07-21 16:58:21 +00:00

856 lines
27 KiB
C++

#include "VulkanBuffer.h"
#include "VulkanDeletionQueue.h"
#include "VulkanDraw.h"
#include "globalincs/pstypes.h"
namespace graphics::vulkan {
namespace {
VulkanBufferManager* g_bufferManager = nullptr;
}
VulkanBufferManager* getBufferManager()
{
Assertion(g_bufferManager != nullptr, "Vulkan BufferManager not initialized!");
return g_bufferManager;
}
void setBufferManager(VulkanBufferManager* manager)
{
g_bufferManager = manager;
}
VulkanBufferManager::VulkanBufferManager() = default;
VulkanBufferManager::~VulkanBufferManager()
{
if (m_initialized) {
shutdown();
}
}
bool VulkanBufferManager::createOneShotBuffer(vk::Flags<vk::BufferUsageFlagBits> usage, const void* data, size_t size, vk::Buffer& buf, VulkanAllocation& alloc) const
{
vk::BufferCreateInfo bufferInfo;
bufferInfo.size = size;
bufferInfo.usage = usage;
bufferInfo.sharingMode = vk::SharingMode::eExclusive;
try {
buf = m_device.createBuffer(bufferInfo);
} catch (const vk::SystemError& e) {
nprintf(("vulkan", "Failed to create buffer: %s\n", e.what()));
return false;
}
if (!m_memoryManager->allocateBufferMemory(buf, MemoryUsage::CpuToGpu, alloc)) {
m_device.destroyBuffer(buf);
buf = nullptr;
nprintf(("vulkan", "Failed to allocate buffer memory!\n"));
return false;
}
void* mapped = m_memoryManager->mapMemory(alloc);
if (mapped) {
memcpy(mapped, data, size);
m_memoryManager->flushMemory(alloc, 0, size);
m_memoryManager->unmapMemory(alloc);
} else {
m_memoryManager->freeAllocation(alloc);
m_device.destroyBuffer(buf);
buf = nullptr;
nprintf(("vulkan", "Failed to map buffer memory!\n"));
return false;
}
return true;
}
// ========== Frame bump allocator ==========
bool VulkanBufferManager::createFrameAllocBuffer(FrameBumpAllocator& alloc, size_t size)
{
vk::BufferCreateInfo bufferInfo;
bufferInfo.size = size;
bufferInfo.usage = vk::BufferUsageFlagBits::eVertexBuffer
| vk::BufferUsageFlagBits::eIndexBuffer
| vk::BufferUsageFlagBits::eUniformBuffer
| vk::BufferUsageFlagBits::eStorageBuffer
| vk::BufferUsageFlagBits::eTransferDst;
bufferInfo.sharingMode = vk::SharingMode::eExclusive;
try {
alloc.buffer = m_device.createBuffer(bufferInfo);
} catch (const vk::SystemError& e) {
nprintf(("vulkan", "Failed to create frame allocator buffer: %s\n", e.what()));
return false;
}
if (!m_memoryManager->allocateBufferMemory(alloc.buffer, MemoryUsage::CpuToGpu, alloc.allocation)) {
m_device.destroyBuffer(alloc.buffer);
alloc.buffer = nullptr;
nprintf(("vulkan", "Failed to allocate frame allocator buffer memory!\n"));
return false;
}
alloc.mappedPtr = m_memoryManager->mapMemory(alloc.allocation);
if (!alloc.mappedPtr) {
m_memoryManager->freeAllocation(alloc.allocation);
m_device.destroyBuffer(alloc.buffer);
alloc.buffer = nullptr;
alloc.allocation = {};
nprintf(("vulkan", "Failed to map frame allocator buffer!\n"));
return false;
}
alloc.capacity = size;
alloc.cursor = 0;
return true;
}
void VulkanBufferManager::initFrameAllocators()
{
for (auto & m_frameAlloc : m_frameAllocs) {
Verification(createFrameAllocBuffer(m_frameAlloc, FRAME_ALLOC_INITIAL_SIZE),
"Failed to create Vulkan frame-allocator buffer during initialization");
}
nprintf(("vulkan", "Frame bump allocators initialized: %u x %zuKB\n",
MAX_FRAMES_IN_FLIGHT, FRAME_ALLOC_INITIAL_SIZE / 1024));
}
void VulkanBufferManager::shutdownFrameAllocators()
{
for (auto & alloc : m_frameAllocs) {
if (alloc.mappedPtr) {
m_memoryManager->unmapMemory(alloc.allocation);
alloc.mappedPtr = nullptr;
}
if (alloc.buffer) {
m_device.destroyBuffer(alloc.buffer);
alloc.buffer = nullptr;
}
if (alloc.allocation.isValid()) {
m_memoryManager->freeAllocation(alloc.allocation);
alloc.allocation = {};
}
alloc.capacity = 0;
alloc.cursor = 0;
}
}
size_t VulkanBufferManager::bumpAllocate(size_t size)
{
auto& alloc = m_frameAllocs[m_currentFrame];
// Align cursor up to UBO alignment (satisfies UBO/SSBO/vertex alignment)
size_t alignedOffset = (alloc.cursor + m_uboAlignment - 1) & ~(static_cast<size_t>(m_uboAlignment) - 1);
if (alignedOffset + size > alloc.capacity) {
growFrameAllocator();
// After growth, cursor is 0 so alignedOffset is 0
alignedOffset = 0;
Assertion(size <= alloc.capacity, "Frame allocator growth failed to provide enough capacity");
}
alloc.cursor = alignedOffset + size;
return alignedOffset;
}
void VulkanBufferManager::growFrameAllocator()
{
auto& alloc = m_frameAllocs[m_currentFrame];
// Double capacity until sufficient
size_t newCapacity = alloc.capacity > 0 ? alloc.capacity * 2 : FRAME_ALLOC_INITIAL_SIZE;
// Ensure at least the current cursor position can fit (handles pathological single-alloc case)
while (newCapacity < alloc.cursor) {
newCapacity *= 2;
}
nprintf(("vulkan", "Growing frame allocator %u: %zuKB -> %zuKB\n",
m_currentFrame, alloc.capacity / 1024, newCapacity / 1024));
// Queue old buffer for deferred destruction - the deletion queue's FRAMES_TO_WAIT=2
// ensures the old buffer survives through current frame's GPU execution.
// Existing handles with frameAllocBuffer pointing to the old buffer remain valid.
auto* deletionQueue = getDeletionQueue();
if (alloc.mappedPtr) {
m_memoryManager->unmapMemory(alloc.allocation);
}
deletionQueue->queueBuffer(alloc.buffer, alloc.allocation);
// Create new buffer
alloc = {};
Verification(createFrameAllocBuffer(alloc, newCapacity), "Failed to grow Vulkan frame-allocator buffer");
}
// ========== Init / Shutdown ==========
bool VulkanBufferManager::init(vk::Device device,
VulkanMemoryManager* memoryManager,
uint32_t graphicsQueueFamily,
uint32_t minUboAlignment)
{
if (m_initialized) {
nprintf(("vulkan", "VulkanBufferManager::init called when already initialized!\n"));
return false;
}
if (!device || !memoryManager) {
nprintf(("vulkan", "VulkanBufferManager::init called with null device or memory manager!\n"));
return false;
}
m_device = device;
m_memoryManager = memoryManager;
m_graphicsQueueFamily = graphicsQueueFamily;
m_currentFrame = 0;
m_uboAlignment = minUboAlignment > 0 ? minUboAlignment : 256;
// Create fallback color buffer with white (1,1,1,1) for shaders expecting vertColor
std::array<float, 4> whiteColor = { 1.0f, 1.0f, 1.0f, 1.0f };
if (!createOneShotBuffer(vk::BufferUsageFlagBits::eVertexBuffer | vk::BufferUsageFlagBits::eTransferDst, whiteColor.data(), sizeof(whiteColor), m_fallbackColorBuffer, m_fallbackColorAllocation)) {
nprintf(("vulkan", "VulkanBufferManager::init could not create fallback color buffer\n"));
return false;
}
std::array<float, 4> zeroTexCoord = { 0.0f, 0.0f, 0.0f, 0.0f };
if (!createOneShotBuffer(vk::BufferUsageFlagBits::eVertexBuffer | vk::BufferUsageFlagBits::eTransferDst, zeroTexCoord.data(), sizeof(zeroTexCoord), m_fallbackTexCoordBuffer, m_fallbackTexCoordAllocation)) {
nprintf(("vulkan", "VulkanBufferManager::init could not create fallback texcoord buffer\n"));
return false;
}
// Create fallback uniform buffer (zeros) for uninitialized descriptor set bindings
// Without this, descriptor set UBO bindings left unwritten after pool reset
// contain undefined data, causing intermittent rendering failures
std::array<float, FALLBACK_UNIFORM_BUFFER_SIZE> dummy_ubo = {};
if (!createOneShotBuffer(vk::BufferUsageFlagBits::eUniformBuffer | vk::BufferUsageFlagBits::eStorageBuffer, dummy_ubo.data(), sizeof(dummy_ubo), m_fallbackUniformBuffer, m_fallbackUniformAllocation)) {
nprintf(("vulkan", "VulkanBufferManager::init could not create fallback uniform buffer\n"));
return false;
}
initFrameAllocators();
m_initialized = true;
nprintf(("vulkan", "Vulkan Buffer Manager initialized (frame bump allocator, UBO alignment=%u, %u frames)\n",
m_uboAlignment, MAX_FRAMES_IN_FLIGHT));
return true;
}
void VulkanBufferManager::shutdown()
{
if (!m_initialized) {
return;
}
// Destroy fallback color buffer
if (m_fallbackColorBuffer) {
m_device.destroyBuffer(m_fallbackColorBuffer);
m_fallbackColorBuffer = nullptr;
}
if (m_fallbackColorAllocation.isValid()) {
m_memoryManager->freeAllocation(m_fallbackColorAllocation);
m_fallbackColorAllocation = {};
}
// Destroy fallback texcoord buffer
if (m_fallbackTexCoordBuffer) {
m_device.destroyBuffer(m_fallbackTexCoordBuffer);
m_fallbackTexCoordBuffer = nullptr;
}
if (m_fallbackTexCoordAllocation.isValid()) {
m_memoryManager->freeAllocation(m_fallbackTexCoordAllocation);
m_fallbackTexCoordAllocation = {};
}
// Destroy fallback uniform buffer
if (m_fallbackUniformBuffer) {
m_device.destroyBuffer(m_fallbackUniformBuffer);
m_fallbackUniformBuffer = nullptr;
}
if (m_fallbackUniformAllocation.isValid()) {
m_memoryManager->freeAllocation(m_fallbackUniformAllocation);
m_fallbackUniformAllocation = {};
}
// Free all remaining static buffers
for (auto& bufferObj : m_buffers) {
if (bufferObj.valid) {
if (!bufferObj.isStreaming() && bufferObj.buffer) {
m_device.destroyBuffer(bufferObj.buffer);
}
if (!bufferObj.isStreaming() && bufferObj.allocation.isValid()) {
m_memoryManager->freeAllocation(bufferObj.allocation);
}
bufferObj.valid = false;
}
}
shutdownFrameAllocators();
m_buffers.clear();
m_freeIndices.clear();
m_activeBufferCount = 0;
m_totalBufferMemory = 0;
m_initialized = false;
nprintf(("vulkan", "Vulkan Buffer Manager shutdown\n"));
}
void VulkanBufferManager::setCurrentFrame(uint32_t frameIndex, uint64_t frameNumber)
{
m_currentFrame = frameIndex % MAX_FRAMES_IN_FLIGHT;
m_currentFrameNumber = frameNumber;
// Reset bump cursor — safe because the GPU fence for this frame-in-flight
// was already waited on before setCurrentFrame is called.
m_frameAllocs[m_currentFrame].cursor = 0;
}
// ========== Buffer usage / memory helpers ==========
vk::BufferUsageFlags VulkanBufferManager::getVkUsageFlags(BufferType type, bool rtCapable)
{
vk::BufferUsageFlags flags = vk::BufferUsageFlagBits::eTransferDst;
switch (type) {
case BufferType::Vertex:
flags |= vk::BufferUsageFlagBits::eVertexBuffer;
break;
case BufferType::Index:
flags |= vk::BufferUsageFlagBits::eIndexBuffer;
break;
case BufferType::Uniform:
flags |= vk::BufferUsageFlagBits::eUniformBuffer;
break;
}
if (rtCapable) {
// Required to use this buffer as acceleration structure geometry input
// and to query its device address. Only valid if the VMA allocator was
// created with VMA_ALLOCATOR_CREATE_BUFFER_DEVICE_ADDRESS_BIT (see
// VulkanMemoryManager::init), which is only true when
// CAPABILITY_RAYTRACED_SHADOWS was negotiated as supported.
flags |= vk::BufferUsageFlagBits::eShaderDeviceAddress |
vk::BufferUsageFlagBits::eAccelerationStructureBuildInputReadOnlyKHR;
}
return flags;
}
MemoryUsage VulkanBufferManager::getMemoryUsage(BufferUsageHint hint)
{
switch (hint) {
case BufferUsageHint::Static:
// Static data goes to device-local memory for best GPU performance
// For simplicity, we use CpuToGpu which allows host writes
// A more optimized path would use staging buffers for truly static data
return MemoryUsage::CpuToGpu;
case BufferUsageHint::Dynamic:
case BufferUsageHint::Streaming:
// Frequently updated data needs to be host visible
return MemoryUsage::CpuToGpu;
case BufferUsageHint::PersistentMapping:
// Persistent mapping requires host visible memory
return MemoryUsage::CpuOnly;
default:
return MemoryUsage::CpuToGpu;
}
}
// ========== Buffer create / delete ==========
gr_buffer_handle VulkanBufferManager::createBuffer(BufferType type, BufferUsageHint usage, bool rtCapable)
{
Assert(m_initialized);
VulkanBufferObject bufferObj;
bufferObj.type = type;
bufferObj.usage = usage;
bufferObj.rtCapable = rtCapable;
bufferObj.valid = true;
// Note: actual buffer creation is deferred until data is uploaded
int index;
if (!m_freeIndices.empty()) {
// Reuse a freed slot
index = m_freeIndices.back();
m_freeIndices.pop_back();
m_buffers[index] = bufferObj;
} else {
// Add new slot
index = static_cast<int>(m_buffers.size());
m_buffers.push_back(bufferObj);
}
++m_activeBufferCount;
return gr_buffer_handle(index);
}
void VulkanBufferManager::deleteBuffer(gr_buffer_handle handle)
{
Assert(m_initialized && isValidHandle(handle));
VulkanBufferObject& bufferObj = m_buffers[handle.value()];
Assert(bufferObj.valid);
if (!bufferObj.isStreaming()) {
// Queue static buffer for deferred destruction
auto* deletionQueue = getDeletionQueue();
if (bufferObj.buffer) {
deletionQueue->queueBuffer(bufferObj.buffer, bufferObj.allocation);
m_totalBufferMemory -= bufferObj.dataSize;
}
bufferObj.buffer = nullptr;
bufferObj.allocation = {};
bufferObj.dataSize = 0;
} else {
// Streaming buffers have no per-buffer resources — just mark invalid
}
--m_activeBufferCount;
bufferObj.valid = false;
// Add to free list for reuse
m_freeIndices.push_back(handle.value());
}
// ========== createOrResizeBuffer (static only) ==========
bool VulkanBufferManager::createOrResizeBuffer(VulkanBufferObject& bufferObj, size_t size)
{
Assertion(!bufferObj.isStreaming(), "createOrResizeBuffer called on streaming buffer!");
// If buffer exists and is large enough, no-op
if (bufferObj.buffer && bufferObj.dataSize >= size) {
return true;
}
// Save old buffer info for data copy
vk::Buffer oldBuffer = bufferObj.buffer;
VulkanAllocation oldAllocation = bufferObj.allocation;
size_t oldDataSize = bufferObj.dataSize;
// Create new buffer
vk::BufferCreateInfo bufferInfo;
bufferInfo.size = size;
bufferInfo.usage = getVkUsageFlags(bufferObj.type, bufferObj.rtCapable);
// Exclusive sharing: all buffer access happens on the graphics queue (there
// is no separate transfer queue). Reintroducing async transfer would require
// eConcurrent here (or explicit queue-family ownership transfers).
bufferInfo.sharingMode = vk::SharingMode::eExclusive;
try {
bufferObj.buffer = m_device.createBuffer(bufferInfo);
} catch (const vk::SystemError& e) {
nprintf(("vulkan", "Failed to create Vulkan buffer: %s\n", e.what()));
bufferObj.buffer = oldBuffer;
return false;
}
// Allocate memory
MemoryUsage memUsage = getMemoryUsage(bufferObj.usage);
if (!m_memoryManager->allocateBufferMemory(bufferObj.buffer, memUsage, bufferObj.allocation)) {
m_device.destroyBuffer(bufferObj.buffer);
bufferObj.buffer = oldBuffer;
bufferObj.allocation = oldAllocation;
return false;
}
// Preserve existing contents across the grow.
//
// This is intentionally a CPU-side copy across two host mappings, not a
// GPU-side vkCmdCopyBuffer. It is correct here because everything reaching
// createOrResizeBuffer is a static buffer, and getMemoryUsage() maps static
// usage to CpuToGpu (host-visible) memory — so both allocations are always
// mappable (the Asserts below cannot trip on this path) and their contents
// are CPU-authored, meaning the CPU already holds the authoritative bytes.
// Resize is grow-only (see the size check above), so this one-time copy is
// amortized. A device-local-only (GpuOnly) buffer could not be mapped and
// would require a vkCmdCopyBuffer with command-buffer synchronization; if
// such a usage is ever routed here, the Assert(oldMapped) will fire loudly
// rather than silently corrupting.
if (oldBuffer && oldDataSize > 0) {
void* oldMapped = m_memoryManager->mapMemory(oldAllocation);
void* newMapped = m_memoryManager->mapMemory(bufferObj.allocation);
Assert(oldMapped);
Assert(newMapped);
size_t copySize = std::min(oldDataSize, size);
// Mirror the post-write flush below: on non-coherent memory the source
// must be invalidated before the CPU reads it. This is a no-op on the
// coherent, CPU-authored buffers this path handles today, kept for
// correctness-by-construction if a non-coherent usage is ever added.
m_memoryManager->invalidateMemory(oldAllocation, 0, copySize);
memcpy(newMapped, oldMapped, copySize);
m_memoryManager->flushMemory(bufferObj.allocation, 0, copySize);
m_memoryManager->unmapMemory(oldAllocation);
m_memoryManager->unmapMemory(bufferObj.allocation);
}
// Queue old buffer for deferred destruction
if (oldBuffer) {
auto* deletionQueue = getDeletionQueue();
deletionQueue->queueBuffer(oldBuffer, oldAllocation);
m_totalBufferMemory -= oldDataSize;
}
bufferObj.dataSize = size;
m_totalBufferMemory += size;
// A new VkBuffer was created above (and thus a new device address, if
// rtCapable) -- bump the generation so cached-address consumers can
// detect staleness.
++bufferObj.generation;
return true;
}
// ========== Buffer data updates ==========
void VulkanBufferManager::updateBufferData(gr_buffer_handle handle, size_t size, const void* data)
{
Assert(m_initialized && isValidHandle(handle));
if (size == 0) {
nprintf(("vulkan", "WARNING: updateBufferData called with size 0\n"));
return;
}
VulkanBufferObject& bufferObj = m_buffers[handle.value()];
Assert(bufferObj.valid);
if (bufferObj.isStreaming()) {
auto& alloc = m_frameAllocs[m_currentFrame];
if (data) {
// Pattern A: full replacement — allocate and copy
size_t offset = bumpAllocate(size);
memcpy(static_cast<uint8_t*>(alloc.mappedPtr) + offset, data, size);
m_memoryManager->flushMemory(alloc.allocation, offset, size);
bufferObj.frameAllocBuffer = alloc.buffer;
bufferObj.frameAllocOffset = offset;
bufferObj.dataSize = size;
bufferObj.frameAllocFrame = m_currentFrame;
} else {
// Pattern B: pre-alloc for offset writes (null data)
if (bufferObj.frameAllocFrame != m_currentFrame || size > bufferObj.dataSize) {
// First allocation this frame, or need more space
size_t offset = bumpAllocate(size);
bufferObj.frameAllocBuffer = alloc.buffer;
bufferObj.frameAllocOffset = offset;
bufferObj.dataSize = size;
bufferObj.frameAllocFrame = m_currentFrame;
}
// Otherwise: same frame and size fits — keep current allocation
}
} else {
// Static / PersistentMapping path.
//
// A full-content rewrite of a buffer the GPU may still be reading from an
// in-flight frame must not write the host-visible memory in place -- host
// writes are not synchronized against already-queued GPU reads. Orphan
// instead: defer the old VkBuffer to the deletion queue and write into a
// fresh one. Draws recorded afterwards pick up the new handle via
// getVkBuffer(); frames already using the old handle keep reading intact
// data until the deletion queue retires it.
//
// Offset writes (updateBufferDataOffset) intentionally do NOT orphan:
// their dominant caller is the GPU heap appending freshly-allocated,
// never-yet-drawn regions at model page-in, which is safe in place.
//
// PersistentMapping buffers are also exempt: the engine holds their
// mapped pointer long-term (mapBuffer) and synchronizes reuse itself
// via gr_sync fences, so swapping the VkBuffer underneath would leave
// the caller writing into the orphaned allocation.
if (data != nullptr && bufferObj.buffer && bufferObj.usage == BufferUsageHint::Static &&
m_currentFrameNumber < bufferObj.lastUsedFrameNumber + MAX_FRAMES_IN_FLIGHT) {
auto* deletionQueue = getDeletionQueue();
deletionQueue->queueBuffer(bufferObj.buffer, bufferObj.allocation);
m_totalBufferMemory -= bufferObj.dataSize;
bufferObj.buffer = nullptr;
bufferObj.allocation = {};
bufferObj.dataSize = 0;
}
Verification(createOrResizeBuffer(bufferObj, size), "Failed to create or resize Vulkan buffer");
// A null data pointer just allocates/resizes the buffer without writing
if (data) {
void* mapped = m_memoryManager->mapMemory(bufferObj.allocation);
Assert(mapped);
memcpy(mapped, data, size);
m_memoryManager->flushMemory(bufferObj.allocation, 0, size);
m_memoryManager->unmapMemory(bufferObj.allocation);
}
}
}
void VulkanBufferManager::updateBufferDataOffset(gr_buffer_handle handle, size_t offset, size_t size, const void* data)
{
Assert(m_initialized && isValidHandle(handle));
VulkanBufferObject& bufferObj = m_buffers[handle.value()];
Assert(bufferObj.valid);
if (bufferObj.isStreaming()) {
// Auto-allocate if not yet allocated this frame. This happens when
// the caller skips updateBufferData (e.g. gr_add_to_immediate_buffer
// when the data fits the existing buffer size).
if (bufferObj.frameAllocFrame != m_currentFrame) {
size_t allocSize = std::max(bufferObj.dataSize, offset + size);
Assert(allocSize > 0);
auto& fa = m_frameAllocs[m_currentFrame];
size_t allocOffset = bumpAllocate(allocSize);
bufferObj.frameAllocBuffer = fa.buffer;
bufferObj.frameAllocOffset = allocOffset;
bufferObj.dataSize = allocSize;
bufferObj.frameAllocFrame = m_currentFrame;
}
Assert(offset + size <= bufferObj.dataSize);
auto& alloc = m_frameAllocs[m_currentFrame];
size_t totalOffset = bufferObj.frameAllocOffset + offset;
memcpy(static_cast<uint8_t*>(alloc.mappedPtr) + totalOffset, data, size);
m_memoryManager->flushMemory(alloc.allocation, totalOffset, size);
} else {
// Static path
Assert(bufferObj.buffer);
Assert(offset + size <= bufferObj.dataSize);
// Map, update region, and unmap
void* mapped = m_memoryManager->mapMemory(bufferObj.allocation);
Assert(mapped);
memcpy(static_cast<uint8_t*>(mapped) + offset, data, size);
m_memoryManager->flushMemory(bufferObj.allocation, offset, size);
m_memoryManager->unmapMemory(bufferObj.allocation);
}
}
// ========== Map / Flush ==========
void* VulkanBufferManager::mapBuffer(gr_buffer_handle handle)
{
if (!m_initialized || !isValidHandle(handle)) {
return nullptr;
}
VulkanBufferObject& bufferObj = m_buffers[handle.value()];
if (!bufferObj.valid) {
return nullptr;
}
if (bufferObj.isStreaming()) {
Assert(bufferObj.frameAllocFrame == m_currentFrame);
auto& alloc = m_frameAllocs[m_currentFrame];
return static_cast<uint8_t*>(alloc.mappedPtr) + bufferObj.frameAllocOffset;
}
// Static / PersistentMapping
if (!bufferObj.buffer) {
return nullptr;
}
// Only persistent mapping buffers should stay mapped
if (bufferObj.usage != BufferUsageHint::PersistentMapping) {
nprintf(("vulkan", "WARNING: mapBuffer called on non-persistent buffer\n"));
}
// Map the entire buffer
void* mapped = m_memoryManager->mapMemory(bufferObj.allocation);
return mapped;
}
void VulkanBufferManager::flushMappedBuffer(gr_buffer_handle handle, size_t offset, size_t size)
{
Assert(m_initialized && isValidHandle(handle));
VulkanBufferObject const& bufferObj = m_buffers[handle.value()];
Assert(bufferObj.valid);
if (bufferObj.isStreaming()) {
// Adjust offset for current frame's allocation
Assert(bufferObj.frameAllocFrame == m_currentFrame);
auto& alloc = m_frameAllocs[m_currentFrame];
m_memoryManager->flushMemory(alloc.allocation, bufferObj.frameAllocOffset + offset, size);
} else {
m_memoryManager->flushMemory(bufferObj.allocation, offset, size);
}
}
// ========== Uniform buffer binding ==========
void VulkanBufferManager::bindUniformBuffer(uniform_block_type blockType, size_t offset, size_t size, gr_buffer_handle buffer) const
{
// Resolve the full offset NOW (frame base + caller offset) so the binding
// captures the correct allocation. The vk::Buffer is still looked up at
// draw time (via handle) to survive buffer recreation.
size_t resolvedOffset = getFrameBaseOffset(buffer) + offset;
auto* drawManager = getDrawManager();
drawManager->setPendingUniformBinding(blockType, buffer,
static_cast<vk::DeviceSize>(resolvedOffset),
static_cast<vk::DeviceSize>(size));
}
// ========== Buffer queries ==========
vk::Buffer VulkanBufferManager::getVkBuffer(gr_buffer_handle handle) const
{
if (!isValidHandle(handle)) {
return nullptr;
}
const VulkanBufferObject& bufferObj = m_buffers[handle.value()];
if (!bufferObj.valid) {
return nullptr;
}
if (bufferObj.isStreaming()) {
// Streaming buffers return the frame allocator buffer they were uploaded to
Assert(bufferObj.frameAllocFrame == m_currentFrame);
return bufferObj.frameAllocBuffer;
} else {
// Record that this frame (potentially) references the buffer -- consulted
// by updateBufferData() to decide whether a rewrite must orphan.
bufferObj.lastUsedFrameNumber = m_currentFrameNumber;
return bufferObj.buffer;
}
}
size_t VulkanBufferManager::getBufferSize(gr_buffer_handle handle) const
{
if (!isValidHandle(handle)) {
return 0;
}
const VulkanBufferObject& bufferObj = m_buffers[handle.value()];
if (!bufferObj.valid) {
return 0;
}
return bufferObj.dataSize;
}
uint64_t VulkanBufferManager::getBufferGeneration(gr_buffer_handle handle) const
{
if (!isValidHandle(handle)) {
return 0;
}
const VulkanBufferObject& bufferObj = m_buffers[handle.value()];
if (!bufferObj.valid) {
return 0;
}
return bufferObj.generation;
}
size_t VulkanBufferManager::getFrameBaseOffset(gr_buffer_handle handle) const
{
if (!isValidHandle(handle)) {
return 0;
}
const VulkanBufferObject& bufferObj = m_buffers[handle.value()];
if (!bufferObj.valid) {
return 0;
}
if (bufferObj.isStreaming()) {
// Return the bump allocator offset for the most recent upload this frame.
// Stale handle detection: if frameAllocFrame != m_currentFrame, this buffer
// was not uploaded this frame and the offset would be meaningless (the bump
// allocator has been reset). This indicates a buffer marked Streaming/Dynamic
// is being bound for rendering without being uploaded first.
Assert(bufferObj.frameAllocFrame == m_currentFrame);
return bufferObj.frameAllocOffset;
} else {
return 0;
}
}
bool VulkanBufferManager::isValidHandle(gr_buffer_handle handle) const
{
if (!handle.isValid()) {
return false;
}
if (static_cast<size_t>(handle.value()) >= m_buffers.size()) {
return false;
}
return m_buffers[handle.value()].valid;
}
VulkanBufferObject* VulkanBufferManager::getBufferObject(gr_buffer_handle handle)
{
if (!isValidHandle(handle)) {
return nullptr;
}
return &m_buffers[handle.value()];
}
const VulkanBufferObject* VulkanBufferManager::getBufferObject(gr_buffer_handle handle) const
{
if (!isValidHandle(handle)) {
return nullptr;
}
return &m_buffers[handle.value()];
}
// ========== gr_screen function pointer implementations ==========
gr_buffer_handle vulkan_create_buffer(BufferType type, BufferUsageHint usage, bool rt_capable)
{
auto* bufferManager = getBufferManager();
return bufferManager->createBuffer(type, usage, rt_capable);
}
void vulkan_delete_buffer(gr_buffer_handle handle)
{
auto* bufferManager = getBufferManager();
bufferManager->deleteBuffer(handle);
}
void vulkan_update_buffer_data(gr_buffer_handle handle, size_t size, const void* data)
{
auto* bufferManager = getBufferManager();
bufferManager->updateBufferData(handle, size, data);
}
void vulkan_update_buffer_data_offset(gr_buffer_handle handle, size_t offset, size_t size, const void* data)
{
auto* bufferManager = getBufferManager();
bufferManager->updateBufferDataOffset(handle, offset, size, data);
}
void* vulkan_map_buffer(gr_buffer_handle handle)
{
auto* bufferManager = getBufferManager();
void* result = bufferManager->mapBuffer(handle);
Assert(result);
return result;
}
void vulkan_flush_mapped_buffer(gr_buffer_handle handle, size_t offset, size_t size)
{
auto* bufferManager = getBufferManager();
bufferManager->flushMappedBuffer(handle, offset, size);
}
void vulkan_bind_uniform_buffer(uniform_block_type blockType, size_t offset, size_t size, gr_buffer_handle buffer)
{
auto* bufferManager = getBufferManager();
bufferManager->bindUniformBuffer(blockType, offset, size, buffer);
}
} // namespace graphics::vulkan