sKit  0.0.9
buffers.hpp
Go to the documentation of this file.
1 #pragma once
2 
3 #include <SDL3/SDL_gpu.h>
4 
5 #include <algorithm>
6 #include <span>
7 #include <stdexcept>
8 
9 namespace sKit {
10 namespace sdl {
11 
12 // Creates a GPU buffer and uses a command buffer to queue an upload. The
13 // command buffer is not submitted.
14 template <typename T, SDL_GPUBufferUsageFlags U>
15 inline SDL_GPUBuffer* createBuffer(
16  SDL_GPUDevice* device,
17  SDL_GPUCommandBuffer* commandBuffer,
18  std::span<T> data
19 ) {
20  // create transfer buffer
21  Uint32 size = data.size() * sizeof(T);
22  SDL_GPUTransferBufferCreateInfo info{
23  .usage = SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD, .size = size
24  };
25  auto transfer = SDL_CreateGPUTransferBuffer(device, &info);
26 
27  // create target buffer
28  SDL_GPUBufferCreateInfo vbInfo{.usage = U, .size = size};
29  auto dstBuffer = SDL_CreateGPUBuffer(device, &vbInfo);
30 
31  // copy data to transfer buffer
32  auto mapping = (T*)SDL_MapGPUTransferBuffer(device, transfer, false);
33  std::copy(data.begin(), data.end(), mapping);
34  SDL_UnmapGPUTransferBuffer(device, transfer);
35 
36  // copy data from transfer buffer to GPU buffers
37  SDL_GPUTransferBufferLocation src{.transfer_buffer = transfer};
38  SDL_GPUBufferRegion dst{.buffer = dstBuffer, .size = size};
39  auto pass = SDL_BeginGPUCopyPass(commandBuffer);
40  if (!pass) {
41  throw std::runtime_error(SDL_GetError());
42  }
43  SDL_UploadToGPUBuffer(pass, &src, &dst, false);
44  SDL_EndGPUCopyPass(pass);
45  SDL_ReleaseGPUTransferBuffer(device, transfer);
46  return dstBuffer;
47 }
48 
49 } // namespace sdl
50 } // namespace sKit
sKit::sdl::createBuffer
SDL_GPUBuffer * createBuffer(SDL_GPUDevice *device, SDL_GPUCommandBuffer *commandBuffer, std::span< T > data)
Definition: buffers.hpp:15
sKit
Definition: camera.hpp:8