14#include <vulkan/vulkan.h>
15#include <vk_mem_alloc.h>
22#include <unordered_map>
23#include <unordered_set>
27#include <source_location>
49 ::std::deque<::std::function<void()>>
deletors;
54 deletors.push_back(::std::move(function));
76 void Add(VkSemaphore semaphore, uint64_t value, VkPipelineStageFlags2 stageMask)
78 if (semaphore == VK_NULL_HANDLE)
80 for (
size_t i = 0; i < waits.size(); ++i)
81 if (waits[i].semaphore == semaphore)
83 waits[i].value = std::max(waits[i].value, value);
84 waits[i].stageMask |= stageMask;
87 std::swap(waits[i], waits[--submitted]);
90 waits.push_back({ .sType = VK_STRUCTURE_TYPE_SEMAPHORE_SUBMIT_INFO, .semaphore = semaphore,
91 .value = value, .stageMask = stageMask });
94 std::span<const VkSemaphoreSubmitInfo>
Waits()
const {
return waits; }
100 waits.erase(waits.begin(), waits.begin() + std::ptrdiff_t(submitted));
104 void Clear() { waits.clear(); submitted = 0; }
107 std::vector<VkSemaphoreSubmitInfo> waits;
108 size_t submitted = 0;
126 const VkAllocationCallbacks*
AllocationCallbacks()
const {
return m_hooks.IsSet() ? &m_allocationCallbacks :
nullptr; }
133 PFN_vkDebugUtilsMessengerCallbackEXT
callback =
nullptr;
195 [[nodiscard]] std::unique_lock<std::mutex>
LockQueue()
const {
return std::unique_lock<std::mutex>(*m_queueMutex); }
216 std::span<tachyon::DeviceAddress> addresses);
245 const std::source_location& loc =
246 std::source_location::current());
255 const std::source_location& loc =
256 std::source_location::current());
265 const std::source_location& loc =
266 std::source_location::current());
305 const std::source_location*
WasDropped(VkImageView view)
const;
390 bool InitializeSharedResources();
391 bool AdoptExternalDevice();
395 VkAllocationCallbacks m_allocationCallbacks{};
396 InstanceDebugConfig m_instanceDebugConfig;
397 std::optional<ExternalDevice> m_externalDevice;
398 bool m_ownsInstance =
true;
399 bool m_ownsDevice =
true;
400 bool m_ownsAllocator =
true;
404 struct PendingUpload {
Buffer staging; VkImage image; VkExtent3D extent;
bool mipmapped; uint32_t firstRow = 0;
bool partial =
false; };
406 mutable std::mutex m_imagesMutex;
407 std::vector<PendingUpload> m_pendingUploads;
409 mutable UploadWorker m_uploads;
412 struct ResidentBuffer {
Buffer buffer;
Buffer staging;
size_t size = 0;
bool ready =
false; };
413 std::unordered_map<tachyon::RHI::ResidentBufferId, ResidentBuffer> m_residentBuffers;
415 mutable std::unordered_set<VulkanImage*> m_liveImages;
416 std::vector<VulkanImage*> m_handedOver;
418 std::mutex m_ownedQueueMutex;
419 std::mutex* m_queueMutex = &m_ownedQueueMutex;
424 struct DroppedAfter { uint64_t after = 0; DeletionQueue queue; };
425 mutable std::mutex m_deletionMutex;
428 std::unordered_map<VkImageView, std::source_location> m_droppedViews;
429 void NoteDropped(VkImageView view,
const std::source_location& where);
430 void NoteDestroyed(VkImageView view);
431 DeletionQueue m_dropped;
432 std::deque<DroppedAfter> m_droppedAfter;
434 std::atomic<uint64_t> m_submitValue{ 0 };
436 void DestroyAllDropped();
455 VulkanImage CreateImage(VkExtent3D size, VkFormat format, VkImageUsageFlags usage, VkSampler sampler,
bool mipmapped =
false)
const;
Definition gui_buffer.h:9
An image made by GraphicsContext::CreateImage; the backend defines its contents.
Definition gui_image.h:102
GPU form of a ColorStyle, uploaded as is: the gradient is baked into an atlas slot that colorUV / gra...
Definition gui_style.h:591
Library internal: copies into mapped GPU memory on a thread of its own, so the main thread goes on re...
Definition vk_upload_worker.h:20
The Vulkan device the GUI renders with: its own, or a host's (SetExternalDevice).
Definition vk_device_context.h:114
VulkanImage CreateImage(VkExtent3D size, VkFormat format, VkImageUsageFlags usage, VkSampler sampler, bool mipmapped=false) const
Library internal: a VMA image with its view.
uint32_t imageSlots
The image slots there are: the ones asked for, or fewer when the device holds fewer sampled images pe...
Definition vk_device_context.h:344
tachyon::RHI::ResidentState GetResidentBufferState(tachyon::RHI::ResidentBufferId id) const
Library internal: whether the buffer exists and has been copied to the GPU.
void Defer(tachyon::DeviceScope scope, std::function< void()> destroy)
For DeviceScope::Frame, DestroyAfterGpu; for Application, at Destroy.
void DestroyVisualBoxStylesAtEnd(tachyon::Buffer *buffer, tachyon::DeviceScope scope, const std::source_location &loc=std::source_location::current())
Library internal: destroys and deletes the buffer when the scope's queue flushes.
std::string deviceName
chosenGPU's name, as its driver reports it.
Definition vk_device_context.h:321
void DestroyBuffer(const Buffer &buffer) const
Library internal: destroys a CreateBuffer buffer now.
void DestroyHandedOverImages()
At shutdown, the GPU idle: destroys the images handed over with an Application-scope DestroyImageAtEn...
void DestroyVisualColorStylesAtEnd(tachyon::Buffer *buffer, tachyon::DeviceScope scope, const std::source_location &loc=std::source_location::current())
Library internal: destroys and deletes the buffer when the scope's queue flushes.
void SetAllocationHooks(const tachyon::AllocationHooks &hooks)
Host memory functions for every Vulkan object, vk-bootstrap and VMA.
std::string shaderDirectory
Where to load the compiled shaders from; empty uses the built-in ones.
Definition vk_device_context.h:308
tachyon::Error initError
why the bring-up failed, when it did
Definition vk_device_context.h:375
void DestroyShader(const VkShaderModule &shader) const
Library internal.
void Destroy()
Waits for the GPU, flushes every deletion queue and destroys what the GUI made.
void DestroyImage(const VulkanImage &img)
Library internal: destroys the image and its view now; as DestroyBuffer, only when no submitted frame...
void ReleaseLiveImages()
After a device loss: frees the live images' Vulkan objects; the image objects stay.
bool Initialize()
Library internal: finishes the bring-up that the first CreateSurface does; false when that failed (se...
bool UpdateImageRows(tachyon::Image *image, uint32_t firstRow, uint32_t rowCount, const void *data)
GraphicsContext::UpdateImageRows: the rows go up with the next frame's uploads, and into the pixels k...
uint32_t requestedImageSlots
Image slots asked for (VulkanGraphicsContext::SetImageSlotCount); set before Initialize.
Definition vk_device_context.h:339
Buffer CreateMappedStorageBuffer(const void *data, size_t size, VkDeviceAddress &outAddress) const
Library internal: a host-visible, persistently mapped storage buffer with a device address,...
VkSemaphore submitTimeline
A timeline every frame submission signals, one value further each.
Definition vk_device_context.h:360
void WaitIdle() const
Waits until the device is idle, holding the queue lock (vkDeviceWaitIdle needs every queue externally...
tachyon::RHI::ResidentBufferId CreateResidentBuffer(std::span< const tachyon::RHI::UploadRequest > requests, std::span< tachyon::DeviceAddress > addresses)
Library internal: GPU-only storage for the packed requests, copied in from a staging buffer by the ne...
VkFence immFence
Library internal: the immediate-submit fence.
Definition vk_device_context.h:324
VkCommandPoolCreateInfo commandPoolInfo
Library internal: reused for the window contexts' command pools.
Definition vk_device_context.h:369
VkDebugUtilsMessengerEXT debug_messenger
The default debug messenger, when the GUI made the instance with one.
Definition vk_device_context.h:367
GUIRenderContext renderContext
Library internal: the GUI's pipelines.
Definition vk_device_context.h:310
uint32_t graphicsQueueFamily
graphicsQueue's family.
Definition vk_device_context.h:333
bool initialized
Whether the device is up (made or adopted).
Definition vk_device_context.h:374
DeletionQueue shutdownQueue
Flushed only when the context shuts down (Cleanup), not when a lost device is remade: for objects tha...
Definition vk_device_context.h:358
VkQueue graphicsQueue
The queue every GUI submit and present goes to; the host's with SetExternalDevice.
Definition vk_device_context.h:331
DeletionQueue & GetDeletionQueue(tachyon::DeviceScope scope)
Library internal: the deletion queue flushed at Destroy (DeviceScope::Application).
Definition vk_device_context.h:273
void SetSurfaceFactory(SurfaceFactory factory)
How surfaces are made; set before initialization. SDLWindowBackend installs its own.
Definition vk_device_context.h:120
void DestroyMesh(const VisualColorStyleBuffers &mesh) const
Library internal: destroys the style buffers now.
void DestroyImageAtEnd(tachyon::Image *img, tachyon::DeviceScope scope, const std::source_location &loc=std::source_location::current())
Destroys the image and deletes the object: a Frame-scope image once the frames that may use it are do...
VkCommandPool immCommandPool
Library internal.
Definition vk_device_context.h:328
void SetExternalDevice(const ExternalDevice &external)
Renders on the host's device instead of making one; call before initialization.
Definition vk_device_context.h:171
void DestroyMesh(const VisualBoxStyleBuffers &mesh) const
Library internal: destroys the style buffers now.
VkCommandBuffer immCommandBuffer
Library internal.
Definition vk_device_context.h:326
void Flush()
Waits for the GPU and flushes the frame deletion queues.
std::string gpuPreference
The GPU asked for (GraphicsContext::SetGpuPreference); set before Initialize.
Definition vk_device_context.h:341
VkShaderModule CreateShader(::std::span< uint32_t > spirvBuffer) const
Library internal: a shader module from SPIR-V words.
VmaAllocator allocator
The allocator; the host's when it passed one.
Definition vk_device_context.h:317
void DestroyUnsubmittedBuffer(const Buffer &buffer) const
Library internal: destroys a buffer no command buffer was recorded with, now.
void RecordPendingUploads(VkCommandBuffer cmd)
Records the queued uploads into cmd, outside any rendering scope.
void AdvanceFrameAndFlushDeletions()
Library internal, once a frame before it's built (all of the last frame's windows submitted): what wa...
VisualBoxStyleBuffers UploadMesh(::std::span< const tachyon::VisualBoxStyle > visualBoxStyles) const
Library internal: the box styles in GPU buffers. Per-primitive uploads go through the RHI.
VkSampler defaultSamplerLinearClampToEdge
For Sampler::LinearClampToEdge.
Definition vk_device_context.h:351
void DestroyImage(tachyon::Image *img)
Destroys the image's Vulkan objects now; doesn't delete the object.
std::function< VkSurfaceKHR(VkInstance, const VkAllocationCallbacks *, tachyon::OSWindowHandle)> SurfaceFactory
Makes a VkSurfaceKHR for one of the window backend's windows with the given instance and allocation c...
Definition vk_device_context.h:118
std::unique_lock< std::mutex > LockQueue() const
Locks the queue for the duration of a submit or present.
Definition vk_device_context.h:195
UploadWorker & Uploads() const
Library internal: copies into mapped memory, off the main thread.
Definition vk_device_context.h:227
VkDevice device
The device; the host's with SetExternalDevice.
Definition vk_device_context.h:315
tachyon::Image * CreateImage(const void *data, tachyon::uint2 size, tachyon::ImageFormat format, tachyon::Sampler sampler, bool mipmapped=false)
An image from data pixels (null: cleared).
VisualColorStyleBuffers UploadMesh(::std::span< const tachyon::VisualColorStyle > colorStyles) const
Library internal: the color styles in GPU buffers.
void DestroyAfterGpu(std::function< void()> destroy)
The one way to free, while frames run, anything a frame may use (a buffer, an image,...
static DeviceRequirements GetDeviceRequirements()
What a host's device must enable for the GUI.
tachyon::Buffer * UploadVisualBoxStyles(::std::span< const tachyon::VisualBoxStyle > styles) const
Library internal: the box styles in a GPU buffer for the shaders.
VkDescriptorSetLayout singleImageDescriptorLayout
Library internal: the layout of the descriptor set the shaders sample images from.
Definition vk_device_context.h:336
DeletionQueue mainDeletionQueue
Flushed at Destroy (DeviceScope::Application).
Definition vk_device_context.h:354
void RebuildLiveImages()
Makes the released images again on the new device, uploading the pixels they were made from.
void DestroyVisualBoxStyles(tachyon::Buffer *buffer)
Library internal: destroys the buffer's GPU objects now, when no submitted frame can use it.
VkSampler defaultSamplerLinear
For Sampler::LinearRepeat.
Definition vk_device_context.h:347
void DestroyVisualColorStyles(tachyon::Buffer *buffer)
Library internal: destroys the buffer's GPU objects now, when no submitted frame can use it.
VkSemaphoreSubmitInfo NextSubmitSignal()
Library internal: the signal every frame submission adds, the submit timeline at its next value.
uint64_t frameNumber
Frames advanced so far.
Definition vk_device_context.h:362
FrameWaits frameWaits
Library internal: the timeline semaphores the frame's submissions wait on.
Definition vk_device_context.h:269
tachyon::Buffer * UploadVisualColorStyles(::std::span< const tachyon::VisualColorStyle > colorStyles) const
Library internal: the color styles in a GPU buffer for the shaders.
void SetInstanceDebugConfig(const InstanceDebugConfig &cfg)
Sets the instance debug config; call before initialization (no effect after).
Definition vk_device_context.h:138
VkSampler defaultSamplerNearest
For Sampler::NearestRepeat.
Definition vk_device_context.h:349
const std::source_location * WasDropped(VkImageView view) const
Debug builds: where an image dropped (DestroyImageAtEnd) and not destroyed yet was dropped,...
VkFenceCreateInfo fenceCreateInfo
Library internal: reused for the window contexts' fences.
Definition vk_device_context.h:371
VkInstance instance
The instance; the host's with SetExternalDevice.
Definition vk_device_context.h:313
size_t ResidentBufferCount() const
Library internal: the resident buffers not released.
Definition vk_device_context.h:223
static bool CheckPhysicalDeviceSupport(VkPhysicalDevice physicalDevice, std::string *problems)
Checks that a physical device can support GetDeviceRequirements().
const VkAllocationCallbacks * AllocationCallbacks() const
What the vkCreate*/vkDestroy* calls pass; null when no hooks are set.
Definition vk_device_context.h:126
void ReleaseResidentBuffer(tachyon::RHI::ResidentBufferId id)
Library internal: frees the buffer now if its copy was never recorded, else when the frame deletion q...
Buffer CreateBuffer(size_t allocSize, VkBufferUsageFlags usage, VmaMemoryUsage memoryUsage) const
Library internal: a VMA buffer.
VkSurfaceKHR CreateSurface(tachyon::OSWindowHandle windowHandle)
A surface for the window, through the surface factory.
bool FramesDone() const
True when the GPU has finished every frame submitted: a resource can go now.
void WaitForUploads() const
Definition vk_device_context.h:228
tachyon::Image * CreateImage(tachyon::uint2 size, tachyon::ImageFormat format, tachyon::Sampler sampler, bool mipmapped=false) const
An image nothing is uploaded to (undefined contents), for sampling only.
bool UsesExternalDevice() const noexcept
Whether SetExternalDevice was called; a lost host device isn't recreated.
Definition vk_device_context.h:173
VkPhysicalDevice chosenGPU
The GPU the device runs on.
Definition vk_device_context.h:319
uint64_t ResidentBufferId
GPU storage kept across frames (UploadResidentBuffers); 0 is none.
Definition gui_rhi.h:36
Sampler
How an image is filtered and addressed when sampled.
Definition gui_image.h:89
ImageFormat
Pixel formats for GraphicsContext::CreateImage, 8 bits per channel.
Definition gui_image.h:75
DeviceScope
When a deferred GPU resource destruction runs: Frame once the GPU has finished the frames that may us...
Definition gui_graphics_context.h:44
ResidentState
Where a resident buffer is.
Definition gui_rhi.h:40
@ Application
Definition gui_graphics_context.h:46
void * OSWindowHandle
An OS window, opaque; what it points to is up to the window backend.
Definition gui_window_backend.h:37
Definition vk_defaults.h:6
Definition gui_logging.h:24
Memory functions a host gives the library, for the allocations that can be routed: Vulkan objects,...
Definition gui_allocation_hooks.h:17
A failure: its category and a human-readable message.
Definition gui_result.h:26
The box part of one state of a registered Style, in pixels; uploaded to the GPU as is (32 bytes).
Definition gui_style.h:923
Definition gui_base_types.h:74
Definition vk_meshes.h:14
Library internal: destroy functions that run later, newest first.
Definition vk_device_context.h:47
void push_function(::std::function< void()> &&function)
Queues a function for the next flush.
Definition vk_device_context.h:52
::std::deque<::std::function< void()> > deletors
The queued functions, oldest first.
Definition vk_device_context.h:49
void flush()
Runs and clears the queued functions.
Definition vk_device_context.h:58
Timeline semaphores the GUI's frame submissions wait on (VulkanGraphicsContext::AddFrameWait).
Definition vk_device_context.h:73
void NextFrame()
A new frame: those submitted go, those added since stay.
Definition vk_device_context.h:98
void Add(VkSemaphore semaphore, uint64_t value, VkPipelineStageFlags2 stageMask)
Waits for semaphore to reach value before stageMask.
Definition vk_device_context.h:76
void Clear()
All of them go (the device they were made on is going).
Definition vk_device_context.h:104
std::span< const VkSemaphoreSubmitInfo > Waits() const
What a submission waits on now.
Definition vk_device_context.h:94
void Submitted()
A submission waited on all of them.
Definition vk_device_context.h:96
The Vulkan-side GUI pipeline set, built once at device init from kPrimitiveSpecs.
Definition vk_rhi.h:24
Definition vk_meshes.h:20
Definition vk_meshes.h:21
What a device must provide for the GUI to run on it.
Definition vk_device_context.h:177
VkPhysicalDeviceVulkan12Features features12
Vulkan 1.2 features to enable.
Definition vk_device_context.h:181
std::vector< const char * > deviceExtensions
Device extensions to enable.
Definition vk_device_context.h:183
uint32_t apiVersion
The lowest Vulkan version.
Definition vk_device_context.h:178
VkPhysicalDeviceVulkan13Features features13
Vulkan 1.3 features to enable.
Definition vk_device_context.h:182
VkPhysicalDeviceVulkan11Features features11
Vulkan 1.1 features to enable.
Definition vk_device_context.h:180
VkPhysicalDeviceFeatures features
Vulkan 1.0 features to enable.
Definition vk_device_context.h:179
A host's Vulkan handles for SetExternalDevice, so the GUI renders on the host's device (an engine hos...
Definition vk_device_context.h:148
VkDevice device
Made with GetDeviceRequirements() enabled.
Definition vk_device_context.h:154
VkInstance instance
Must enable the window backend's surface extensions.
Definition vk_device_context.h:150
VkPhysicalDevice physicalDevice
The GPU device was made on.
Definition vk_device_context.h:152
VkQueue graphicsQueue
Every GUI submit and present goes here; it supports graphics and presenting to the GUI's windows.
Definition vk_device_context.h:157
std::mutex * queueMutex
Optional.
Definition vk_device_context.h:168
uint32_t graphicsQueueFamily
graphicsQueue's family.
Definition vk_device_context.h:159
VmaAllocator allocator
Optional.
Definition vk_device_context.h:162
Diagnostic hook for the GPU test harness: the instance is built with this debug callback instead of t...
Definition vk_device_context.h:132
PFN_vkDebugUtilsMessengerCallbackEXT callback
Gets the validation messages.
Definition vk_device_context.h:133
bool enableSyncValidation
adds sync validation
Definition vk_device_context.h:135
void * userData
Passed to callback.
Definition vk_device_context.h:134