VisuTwin Canvas
C++ 3D Engine — Metal Backend
Loading...
Searching...
No Matches
vulkanIndexBuffer.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2025-2026 Arnis Lektauers
3//
4
5#ifdef VISUTWIN_HAS_VULKAN
6
7#include "vulkanIndexBuffer.h"
9#include "vulkanUtils.h"
10
11#include <cstring>
12#include "spdlog/spdlog.h"
13
14namespace visutwin::canvas
15{
16 VulkanIndexBuffer::VulkanIndexBuffer(GraphicsDevice* device, IndexFormat format, int numIndices)
17 : IndexBuffer(device, format, numIndices)
18 {
19 auto* vkDev = static_cast<VulkanGraphicsDevice*>(device);
20 _allocator = vkDev->vmaAllocator();
21
22 int bytesPerIndex = (format == INDEXFORMAT_UINT32) ? 4 : (format == INDEXFORMAT_UINT16) ? 2 : 1;
23 size_t bufferSize = static_cast<size_t>(numIndices) * bytesPerIndex;
24 if (bufferSize == 0) return;
25
26 VkBufferCreateInfo bufferInfo{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO};
27 bufferInfo.size = bufferSize;
28 bufferInfo.usage = VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
29
30 VmaAllocationCreateInfo allocInfo{};
31 allocInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY;
32
33 vmaCreateBuffer(_allocator, &bufferInfo, &allocInfo, &_buffer, &_allocation, nullptr);
34 }
35
36 VulkanIndexBuffer::~VulkanIndexBuffer()
37 {
38 if (_allocator != VK_NULL_HANDLE && _buffer != VK_NULL_HANDLE) {
39 vmaDestroyBuffer(_allocator, _buffer, _allocation);
40 }
41 }
42
43 bool VulkanIndexBuffer::setData(const std::vector<uint8_t>& data)
44 {
45 if (data.empty() || !_allocator || !_buffer) return false;
46 _storage = data;
47 uploadStaging(data.data(), data.size());
48 return true;
49 }
50
51 void VulkanIndexBuffer::uploadStaging(const void* data, size_t size)
52 {
53 auto* vkDev = static_cast<VulkanGraphicsDevice*>(_device);
54
55 VkBuffer stagingBuffer;
56 VmaAllocation stagingAlloc;
57
58 VkBufferCreateInfo stagingInfo{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO};
59 stagingInfo.size = size;
60 stagingInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
61
62 VmaAllocationCreateInfo stagingAllocInfo{};
63 stagingAllocInfo.usage = VMA_MEMORY_USAGE_CPU_ONLY;
64
65 vmaCreateBuffer(_allocator, &stagingInfo, &stagingAllocInfo,
66 &stagingBuffer, &stagingAlloc, nullptr);
67
68 void* mapped;
69 vmaMapMemory(_allocator, stagingAlloc, &mapped);
70 memcpy(mapped, data, size);
71 vmaUnmapMemory(_allocator, stagingAlloc);
72
73 vulkanImmediateSubmit(vkDev, [&](VkCommandBuffer cmd) {
74 VkBufferCopy copy{};
75 copy.size = size;
76 vkCmdCopyBuffer(cmd, stagingBuffer, _buffer, 1, &copy);
77 });
78
79 vmaDestroyBuffer(_allocator, stagingBuffer, stagingAlloc);
80 }
81}
82
83#endif // VISUTWIN_HAS_VULKAN
Abstract GPU interface for resource creation, state management, and draw submission.