VisuTwin Canvas
C++ 3D Engine — Metal Backend
Loading...
Searching...
No Matches
vulkanVertexBuffer.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
9#include "vulkanUtils.h"
10
11#include <cstring>
12#include "spdlog/spdlog.h"
13
14namespace visutwin::canvas
15{
16 VulkanVertexBuffer::VulkanVertexBuffer(GraphicsDevice* device,
17 const std::shared_ptr<VertexFormat>& format, int numVertices,
18 const VertexBufferOptions& options)
19 : VertexBuffer(device, format, numVertices, options)
20 {
21 auto* vkDev = static_cast<VulkanGraphicsDevice*>(device);
22 _allocator = vkDev->vmaAllocator();
23
24 size_t bufferSize = _storage.size();
25 if (bufferSize == 0) return;
26
27 VkBufferCreateInfo bufferInfo{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO};
28 bufferInfo.size = bufferSize;
29 bufferInfo.usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
30
31 VmaAllocationCreateInfo allocInfo{};
32 allocInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY;
33
34 vmaCreateBuffer(_allocator, &bufferInfo, &allocInfo, &_buffer, &_allocation, nullptr);
35
36 if (!options.data.empty()) {
37 unlock();
38 }
39 }
40
41 VulkanVertexBuffer::~VulkanVertexBuffer()
42 {
43 if (_allocator != VK_NULL_HANDLE && _buffer != VK_NULL_HANDLE) {
44 vmaDestroyBuffer(_allocator, _buffer, _allocation);
45 }
46 }
47
48 void VulkanVertexBuffer::unlock()
49 {
50 if (_storage.empty() || !_allocator || !_buffer) return;
51
52 auto* vkDev = static_cast<VulkanGraphicsDevice*>(_device);
53 size_t dataSize = _storage.size();
54
55 // Create staging buffer
56 VkBuffer stagingBuffer;
57 VmaAllocation stagingAlloc;
58
59 VkBufferCreateInfo stagingInfo{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO};
60 stagingInfo.size = dataSize;
61 stagingInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
62
63 VmaAllocationCreateInfo stagingAllocInfo{};
64 stagingAllocInfo.usage = VMA_MEMORY_USAGE_CPU_ONLY;
65
66 vmaCreateBuffer(_allocator, &stagingInfo, &stagingAllocInfo,
67 &stagingBuffer, &stagingAlloc, nullptr);
68
69 void* mapped;
70 vmaMapMemory(_allocator, stagingAlloc, &mapped);
71 memcpy(mapped, _storage.data(), dataSize);
72 vmaUnmapMemory(_allocator, stagingAlloc);
73
74 vulkanImmediateSubmit(vkDev, [&](VkCommandBuffer cmd) {
75 VkBufferCopy copy{};
76 copy.size = dataSize;
77 vkCmdCopyBuffer(cmd, stagingBuffer, _buffer, 1, &copy);
78 });
79
80 vmaDestroyBuffer(_allocator, stagingBuffer, stagingAlloc);
81 }
82}
83
84#endif // VISUTWIN_HAS_VULKAN
Abstract GPU interface for resource creation, state management, and draw submission.