15#define VULKAN_HPP_DISPATCH_LOADER_DYNAMIC 1
16#include <vulkan/vulkan.hpp>
17VULKAN_HPP_DEFAULT_DISPATCH_LOADER_DYNAMIC_STORAGE
38 auto tmp_internal_retVal = cmd; \
39 if ((int32_t)tmp_internal_retVal < 0) { \
40 GPUError("VULKAN ERROR: %d: %s (%s: %d)", (int32_t)tmp_internal_retVal, "ERROR", __FILE__, __LINE__); \
41 throw std::runtime_error("Vulkan Failure"); \
54static int32_t checkVulkanLayersSupported(
const std::vector<const char*>& validationLayers)
56 std::vector<vk::LayerProperties> availableLayers = vk::enumerateInstanceLayerProperties();
57 for (
const char* layerName : validationLayers) {
58 bool layerFound =
false;
60 for (
const auto& layerProperties : availableLayers) {
61 if (strcmp(layerName, layerProperties.layerName) == 0) {
74static uint32_t findMemoryType(uint32_t typeFilter, vk::MemoryPropertyFlags properties, vk::PhysicalDevice physDev)
76 vk::PhysicalDeviceMemoryProperties memProperties = physDev.getMemoryProperties();
78 for (uint32_t
i = 0;
i < memProperties.memoryTypeCount;
i++) {
79 if ((typeFilter & (1 <<
i)) && (memProperties.memoryTypes[
i].propertyFlags & properties) == properties) {
84 throw std::runtime_error(
"failed to find suitable memory type!");
87static vk::SurfaceFormatKHR chooseSwapSurfaceFormat(
const std::vector<vk::SurfaceFormatKHR>& availableFormats)
89 for (
const auto& availableFormat : availableFormats) {
90 if (availableFormat.format == vk::Format::eB8G8R8A8Unorm && availableFormat.colorSpace == vk::ColorSpaceKHR::eSrgbNonlinear) {
91 return availableFormat;
94 return availableFormats[0];
97static vk::PresentModeKHR chooseSwapPresentMode(
const std::vector<vk::PresentModeKHR>& availablePresentModes, vk::PresentModeKHR desiredMode = vk::PresentModeKHR::eMailbox)
99 for (
const auto& availablePresentMode : availablePresentModes) {
100 if (availablePresentMode == desiredMode) {
101 return availablePresentMode;
104 static bool errorShown =
false;
107 GPUError(
"VULKAN ERROR: Desired present mode not available, using FIFO mode");
109 return vk::PresentModeKHR::eFifo;
114 if (capabilities.currentExtent.width != std::numeric_limits<uint32_t>::max()) {
115 return capabilities.currentExtent;
119 vk::Extent2D actualExtent = {(uint32_t)
width, (uint32_t)
height};
120 actualExtent.width = std::clamp(actualExtent.width, capabilities.minImageExtent.width, capabilities.maxImageExtent.width);
121 actualExtent.height = std::clamp(actualExtent.height, capabilities.minImageExtent.height, capabilities.maxImageExtent.height);
126static vk::ShaderModule createShaderModule(
const char* code,
size_t size, vk::Device device)
128 vk::ShaderModuleCreateInfo createInfo{};
129 createInfo.codeSize =
size;
130 createInfo.pCode =
reinterpret_cast<const uint32_t*
>(code);
131 return device.createShaderModule(createInfo,
nullptr);
134static void cmdImageMemoryBarrier(vk::CommandBuffer cmdbuffer, vk::Image
image, vk::AccessFlags srcAccessMask, vk::AccessFlags dstAccessMask, vk::ImageLayout oldLayout, vk::ImageLayout newLayout, vk::PipelineStageFlags srcStageMask, vk::PipelineStageFlags dstStageMask)
136 vk::ImageSubresourceRange
range{vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1};
137 vk::ImageMemoryBarrier barrier{};
138 barrier.srcAccessMask = srcAccessMask;
139 barrier.dstAccessMask = dstAccessMask;
140 barrier.oldLayout = oldLayout;
141 barrier.newLayout = newLayout;
142 barrier.image =
image;
143 barrier.subresourceRange =
range;
144 cmdbuffer.pipelineBarrier(srcStageMask, dstStageMask, {}, 0,
nullptr, 0,
nullptr, 1, &barrier);
156 vk::CommandBufferAllocateInfo allocInfo{};
157 allocInfo.level = vk::CommandBufferLevel::ePrimary;
159 allocInfo.commandBufferCount = 1;
160 vk::CommandBuffer commandBuffer =
mDevice.allocateCommandBuffers(allocInfo)[0];
161 vk::CommandBufferBeginInfo beginInfo{};
162 beginInfo.flags = vk::CommandBufferUsageFlagBits::eOneTimeSubmit;
163 commandBuffer.begin(beginInfo);
164 return commandBuffer;
170 vk::SubmitInfo submitInfo{};
171 submitInfo.commandBufferCount = 1;
172 submitInfo.pCommandBuffers = &commandBuffer;
173 static std::mutex fenceMutex;
175 std::lock_guard<std::mutex> guard(fenceMutex);
183static vk::ImageView createImageViewI(vk::Device device, vk::Image
image, vk::Format
format, vk::ImageAspectFlags aspectFlags = vk::ImageAspectFlagBits::eColor, uint32_t mipLevels = 1)
185 vk::ImageViewCreateInfo viewInfo{};
186 viewInfo.image =
image;
187 viewInfo.viewType = vk::ImageViewType::e2D;
189 viewInfo.subresourceRange.aspectMask = aspectFlags;
190 viewInfo.subresourceRange.baseMipLevel = 0;
191 viewInfo.subresourceRange.levelCount = mipLevels;
192 viewInfo.subresourceRange.baseArrayLayer = 0;
193 viewInfo.subresourceRange.layerCount = 1;
194 return device.createImageView(viewInfo,
nullptr);
197static void createImageI(vk::Device device, vk::PhysicalDevice physicalDevice, vk::Image&
image, vk::DeviceMemory& imageMemory, uint32_t
width, uint32_t
height, vk::Format
format, vk::ImageUsageFlags
usage, vk::MemoryPropertyFlags properties, vk::ImageTiling tiling = vk::ImageTiling::eOptimal, vk::SampleCountFlagBits numSamples = vk::SampleCountFlagBits::e1, vk::ImageLayout layout = vk::ImageLayout::eUndefined, uint32_t mipLevels = 1)
199 vk::ImageCreateInfo imageInfo{};
200 imageInfo.imageType = vk::ImageType::e2D;
201 imageInfo.extent.width =
width;
202 imageInfo.extent.height =
height;
203 imageInfo.extent.depth = 1;
204 imageInfo.mipLevels = mipLevels;
205 imageInfo.arrayLayers = 1;
206 imageInfo.format =
format;
207 imageInfo.tiling = tiling;
208 imageInfo.initialLayout = layout;
209 imageInfo.usage =
usage;
210 imageInfo.samples = numSamples;
211 imageInfo.sharingMode = vk::SharingMode::eExclusive;
212 image = device.createImage(imageInfo);
214 vk::MemoryRequirements memRequirements;
215 memRequirements = device.getImageMemoryRequirements(
image);
217 vk::MemoryAllocateInfo allocInfo{};
218 allocInfo.allocationSize = memRequirements.size;
219 allocInfo.memoryTypeIndex = findMemoryType(memRequirements.memoryTypeBits, properties, physicalDevice);
220 imageMemory = device.allocateMemory(allocInfo,
nullptr);
222 device.bindImageMemory(
image, imageMemory, 0);
225static uint32_t getMaxUsableSampleCount(vk::PhysicalDeviceProperties& physicalDeviceProperties)
227 vk::SampleCountFlags counts = physicalDeviceProperties.limits.framebufferColorSampleCounts & physicalDeviceProperties.limits.framebufferDepthSampleCounts;
228 if (counts & vk::SampleCountFlagBits::e64) {
230 }
else if (counts & vk::SampleCountFlagBits::e32) {
232 }
else if (counts & vk::SampleCountFlagBits::e16) {
234 }
else if (counts & vk::SampleCountFlagBits::e8) {
236 }
else if (counts & vk::SampleCountFlagBits::e4) {
238 }
else if (counts & vk::SampleCountFlagBits::e2) {
244static vk::SampleCountFlagBits getMSAASamplesFlag(uint32_t msaa)
247 return vk::SampleCountFlagBits::e2;
248 }
else if (msaa == 4) {
249 return vk::SampleCountFlagBits::e4;
250 }
else if (msaa == 8) {
251 return vk::SampleCountFlagBits::e8;
252 }
else if (msaa == 16) {
253 return vk::SampleCountFlagBits::e16;
254 }
else if (msaa == 32) {
255 return vk::SampleCountFlagBits::e32;
256 }
else if (msaa == 64) {
257 return vk::SampleCountFlagBits::e64;
259 return vk::SampleCountFlagBits::e1;
262template <
class T,
class S>
263static inline void clearVector(T&
v,
S func,
bool downsize =
true)
265 std::for_each(
v.begin(),
v.end(),
func);
276 vk::PhysicalDeviceProperties deviceProperties = device.getProperties();
277 vk::PhysicalDeviceFeatures deviceFeatures = device.getFeatures();
278 vk::PhysicalDeviceMemoryProperties memoryProperties = device.getMemoryProperties();
279 if (!deviceFeatures.geometryShader || !deviceFeatures.wideLines || !deviceFeatures.largePoints) {
283 std::vector<vk::QueueFamilyProperties> queueFamilies = device.getQueueFamilyProperties();
285 for (uint32_t
i = 0;
i < queueFamilies.size();
i++) {
286 if (!(queueFamilies[
i].queueFlags & vk::QueueFlagBits::eGraphics)) {
289 vk::Bool32 presentSupport = device.getSurfaceSupportKHR(
i,
mSurface);
290 if (!presentSupport) {
298 GPUInfo(
"%s ignored due to missing queue properties", &deviceProperties.deviceName[0]);
302 std::vector<vk::ExtensionProperties> availableExtensions = device.enumerateDeviceExtensionProperties(
nullptr);
303 uint32_t extensionsFound = 0;
304 for (uint32_t
i = 0;
i < reqDeviceExtensions.size();
i++) {
305 for (uint32_t
j = 0;
j < availableExtensions.size();
j++) {
306 if (strcmp(reqDeviceExtensions[
i], availableExtensions[
j].extensionName) == 0) {
312 if (extensionsFound < reqDeviceExtensions.size()) {
313 GPUInfo(
"%s ignored due to missing extensions", &deviceProperties.deviceName[0]);
319 GPUInfo(
"%s ignored due to incompatible swap chain", &deviceProperties.deviceName[0]);
324 if (deviceProperties.deviceType == vk::PhysicalDeviceType::eDiscreteGpu) {
326 }
else if (deviceProperties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu) {
330 for (uint32_t
i = 0;
i < memoryProperties.memoryHeapCount;
i++) {
331 if (memoryProperties.memoryHeaps[
i].flags & vk::MemoryHeapFlagBits::eDeviceLocal) {
332 score += memoryProperties.memoryHeaps[
i].size;
341 VULKAN_HPP_DEFAULT_DISPATCHER.init();
342 vk::ApplicationInfo appInfo{};
343 appInfo.pApplicationName =
"GPU CA Standalone display";
344 appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
345 appInfo.pEngineName =
"GPU CI Standalone Engine";
346 appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);
347 appInfo.apiVersion = VK_API_VERSION_1_0;
349 vk::InstanceCreateInfo instanceCreateInfo;
350 instanceCreateInfo.pApplicationInfo = &appInfo;
352 const char** frontendExtensions;
354 std::vector<const char*> reqInstanceExtensions(frontendExtensions, frontendExtensions + frontendExtensionCount);
356 const std::vector<const char*> reqValidationLayers = {
357 "VK_LAYER_KHRONOS_validation"};
358 auto debugCallback = [](vk::DebugUtilsMessageSeverityFlagBitsEXT messageSeverity, vk::DebugUtilsMessageTypeFlagsEXT messageType,
const vk::DebugUtilsMessengerCallbackDataEXT* pCallbackData,
void* pUserData) -> VkBool32 {
359 static int32_t throwOnError = getenv(
"GPUCA_VULKAN_VALIDATION_THROW") ? atoi(getenv(
"GPUCA_VULKAN_VALIDATION_THROW")) : 0;
360 static bool showVulkanValidationInfo = getenv(
"GPUCA_VULKAN_VALIDATION_INFO") && atoi(getenv(
"GPUCA_VULKAN_VALIDATION_INFO"));
361 switch (messageSeverity) {
362 case vk::DebugUtilsMessageSeverityFlagBitsEXT::eVerbose:
363 if (showVulkanValidationInfo) {
364 GPUInfo(
"%s", pCallbackData->pMessage);
367 case vk::DebugUtilsMessageSeverityFlagBitsEXT::eWarning:
368 GPUWarning(
"%s", pCallbackData->pMessage);
369 if (throwOnError > 1) {
370 throw std::logic_error(
"break_on_validation_warning");
373 case vk::DebugUtilsMessageSeverityFlagBitsEXT::eError:
374 GPUError(
"%s", pCallbackData->pMessage);
376 throw std::logic_error(
"break_on_validation_error");
379 case vk::DebugUtilsMessageSeverityFlagBitsEXT::eInfo:
381 GPUInfo(
"%s", pCallbackData->pMessage);
386 vk::DebugUtilsMessengerCreateInfoEXT debugCreateInfo{};
388 if (checkVulkanLayersSupported(reqValidationLayers)) {
389 throw std::runtime_error(
"Requested validation layer support not available");
391 reqInstanceExtensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
392 instanceCreateInfo.enabledLayerCount =
static_cast<uint32_t
>(reqValidationLayers.size());
393 instanceCreateInfo.ppEnabledLayerNames = reqValidationLayers.data();
394 instanceCreateInfo.pNext = (VkDebugUtilsMessengerCreateInfoEXT*)&debugCreateInfo;
396 debugCreateInfo.messageSeverity = vk::DebugUtilsMessageSeverityFlagBitsEXT::eVerbose | vk::DebugUtilsMessageSeverityFlagBitsEXT::eWarning | vk::DebugUtilsMessageSeverityFlagBitsEXT::eError;
397 debugCreateInfo.messageType = vk::DebugUtilsMessageTypeFlagBitsEXT::eGeneral | vk::DebugUtilsMessageTypeFlagBitsEXT::eValidation | vk::DebugUtilsMessageTypeFlagBitsEXT::ePerformance;
398 debugCreateInfo.pfnUserCallback = debugCallback;
399 debugCreateInfo.pUserData =
nullptr;
401 instanceCreateInfo.enabledLayerCount = 0;
404 instanceCreateInfo.enabledExtensionCount =
static_cast<uint32_t
>(reqInstanceExtensions.size());
405 instanceCreateInfo.ppEnabledExtensionNames = reqInstanceExtensions.data();
407 mInstance = vk::createInstance(instanceCreateInfo,
nullptr);
408 VULKAN_HPP_DEFAULT_DISPATCHER.init(
mInstance);
411 GPUInfo(
"Enabling Vulkan Validation Layers");
414 std::vector<vk::ExtensionProperties> extensions = vk::enumerateInstanceExtensionProperties(
nullptr);
416 std::cout <<
"available instance extensions: " << extensions.size() <<
"\n";
417 for (
const auto& extension : extensions) {
418 std::cout <<
'\t' << extension.extensionName <<
'\n';
423 throw std::runtime_error(
"Frontend does not provide Vulkan surface");
426 const std::vector<const char*> reqDeviceExtensions = {
427 VK_KHR_SWAPCHAIN_EXTENSION_NAME};
430 std::vector<vk::PhysicalDevice> devices =
mInstance.enumeratePhysicalDevices();
431 if (devices.size() == 0) {
432 throw std::runtime_error(
"No Vulkan device present!");
434 double bestScore = -1.;
435 for (uint32_t
i = 0;
i < devices.size();
i++) {
436 double score =
checkDevice(devices[
i], reqDeviceExtensions);
438 vk::PhysicalDeviceProperties deviceProperties = devices[
i].getProperties();
439 GPUInfo(
"Available Vulkan device %d: %s - Score %f",
i, &deviceProperties.deviceName[0], score);
441 if (score > bestScore && score > 0) {
447 if (
mDisplay->
cfg().vulkan.forceDevice < 0 ||
mDisplay->
cfg().vulkan.forceDevice >= (int32_t)devices.size()) {
448 throw std::runtime_error(
"Invalid Vulkan device selected");
453 throw std::runtime_error(
"All available Vulkan devices unsuited");
457 vk::PhysicalDeviceProperties deviceProperties =
mPhysicalDevice.getProperties();
458 vk::PhysicalDeviceFeatures deviceFeatures =
mPhysicalDevice.getFeatures();
459 vk::FormatProperties depth32FormatProperties =
mPhysicalDevice.getFormatProperties(vk::Format::eD32Sfloat);
460 vk::FormatProperties depth64FormatProperties =
mPhysicalDevice.getFormatProperties(vk::Format::eD32SfloatS8Uint);
462 GPUInfo(
"Using physical Vulkan device %s", &deviceProperties.deviceName[0]);
464 mZSupported = (bool)(depth32FormatProperties.optimalTilingFeatures & vk::FormatFeatureFlagBits::eDepthStencilAttachment);
465 mStencilSupported = (bool)(depth64FormatProperties.optimalTilingFeatures & vk::FormatFeatureFlagBits::eDepthStencilAttachment);
466 mCubicFilterSupported = (bool)(formatProperties.optimalTilingFeatures & vk::FormatFeatureFlagBits::eSampledImageFilterCubicEXT);
472 vk::DeviceQueueCreateInfo queueCreateInfo{};
474 queueCreateInfo.queueCount = 1;
475 float queuePriority = 1.0f;
476 queueCreateInfo.pQueuePriorities = &queuePriority;
477 vk::DeviceCreateInfo deviceCreateInfo{};
478 deviceCreateInfo.pQueueCreateInfos = &queueCreateInfo;
479 deviceCreateInfo.queueCreateInfoCount = 1;
480 deviceCreateInfo.pEnabledFeatures = &deviceFeatures;
481 deviceCreateInfo.enabledExtensionCount =
static_cast<uint32_t
>(reqDeviceExtensions.size());
482 deviceCreateInfo.ppEnabledExtensionNames = reqDeviceExtensions.data();
483 deviceCreateInfo.enabledLayerCount = instanceCreateInfo.enabledLayerCount;
484 deviceCreateInfo.ppEnabledLayerNames = instanceCreateInfo.ppEnabledLayerNames;
486 VULKAN_HPP_DEFAULT_DISPATCHER.init(
mDevice);
489 vk::CommandPoolCreateInfo poolInfo{};
490 poolInfo.flags = vk::CommandPoolCreateFlagBits::eResetCommandBuffer;
509 vk::CommandBufferAllocateInfo allocInfo{};
511 allocInfo.level = vk::CommandBufferLevel::ePrimary;
534 vk::SemaphoreCreateInfo semaphoreInfo{};
535 vk::FenceCreateInfo fenceInfo{};
536 fenceInfo.flags = vk::FenceCreateFlagBits::eSignaled;
551 fenceInfo.flags = {};
570 for (int32_t
j = 0;
j < 3;
j++) {
579 std::array<vk::DescriptorPoolSize, 2> poolSizes{};
580 poolSizes[0].type = vk::DescriptorType::eUniformBuffer;
582 poolSizes[1].type = vk::DescriptorType::eCombinedImageSampler;
584 vk::DescriptorPoolCreateInfo poolInfo{};
585 poolInfo.poolSizeCount = poolSizes.
size();
586 poolInfo.pPoolSizes = poolSizes.data();
590 vk::DescriptorSetLayoutBinding uboLayoutBindingMat{};
591 uboLayoutBindingMat.binding = 0;
592 uboLayoutBindingMat.descriptorType = vk::DescriptorType::eUniformBuffer;
593 uboLayoutBindingMat.descriptorCount = 1;
594 uboLayoutBindingMat.stageFlags = vk::ShaderStageFlagBits::eVertex;
595 vk::DescriptorSetLayoutBinding uboLayoutBindingCol = uboLayoutBindingMat;
596 uboLayoutBindingCol.binding = 1;
597 uboLayoutBindingCol.stageFlags = vk::ShaderStageFlagBits::eFragment;
598 vk::DescriptorSetLayoutBinding samplerLayoutBinding{};
599 samplerLayoutBinding.binding = 2;
600 samplerLayoutBinding.descriptorCount = 1;
601 samplerLayoutBinding.descriptorType = vk::DescriptorType::eCombinedImageSampler;
602 samplerLayoutBinding.stageFlags = vk::ShaderStageFlagBits::eFragment;
603 vk::DescriptorSetLayoutBinding bindings[3] = {uboLayoutBindingMat, uboLayoutBindingCol, samplerLayoutBinding};
605 vk::DescriptorSetLayoutCreateInfo layoutInfo{};
606 layoutInfo.bindingCount = 2;
607 layoutInfo.pBindings = bindings;
609 layoutInfo.bindingCount = 3;
612 vk::DescriptorSetAllocateInfo allocInfo{};
615 for (int32_t
j = 0;
j < 3;
j++) {
617 allocInfo.pSetLayouts = layouts.data();
620 for (int32_t k = 0; k < 2; k++) {
623 vk::DescriptorBufferInfo bufferInfo{};
624 bufferInfo.buffer = mUniformBuffers[
i].buffer;
625 bufferInfo.offset = 0;
626 bufferInfo.range = mUniformBuffers[
i].size;
628 vk::WriteDescriptorSet descriptorWrite{};
630 descriptorWrite.dstBinding = k;
631 descriptorWrite.dstArrayElement = 0;
632 descriptorWrite.descriptorType = vk::DescriptorType::eUniformBuffer;
633 descriptorWrite.descriptorCount = 1;
634 descriptorWrite.pBufferInfo = &bufferInfo;
635 descriptorWrite.pImageInfo =
nullptr;
636 descriptorWrite.pTexelBufferView =
nullptr;
637 mDevice.updateDescriptorSets(1, &descriptorWrite, 0,
nullptr);
652 for (int32_t
j = 0;
j < 3;
j++) {
660 vk::DescriptorImageInfo imageInfo{};
661 imageInfo.imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
664 vk::WriteDescriptorSet descriptorWrite{};
666 descriptorWrite.dstBinding = 2;
667 descriptorWrite.dstArrayElement = 0;
668 descriptorWrite.descriptorType = vk::DescriptorType::eCombinedImageSampler;
669 descriptorWrite.descriptorCount = 1;
670 descriptorWrite.pImageInfo = &imageInfo;
671 mDevice.updateDescriptorSets(1, &descriptorWrite, 0,
nullptr);
678 vk::SamplerCreateInfo samplerInfo{};
679 samplerInfo.magFilter = vk::Filter::eLinear;
680 samplerInfo.minFilter = vk::Filter::eLinear;
681 samplerInfo.addressModeU = vk::SamplerAddressMode::eRepeat;
682 samplerInfo.addressModeV = vk::SamplerAddressMode::eRepeat;
683 samplerInfo.addressModeW = vk::SamplerAddressMode::eRepeat;
684 samplerInfo.compareEnable =
false;
685 samplerInfo.compareOp = vk::CompareOp::eAlways;
686 samplerInfo.borderColor = vk::BorderColor::eIntOpaqueBlack;
687 samplerInfo.unnormalizedCoordinates =
false;
688 samplerInfo.mipmapMode = vk::SamplerMipmapMode::eLinear;
689 samplerInfo.mipLodBias = 0.0f;
690 samplerInfo.minLod = 0.0f;
691 samplerInfo.maxLod = 0.0f;
723 vk::SwapchainCreateInfoKHR swapCreateInfo{};
725 swapCreateInfo.minImageCount = imageCount;
728 swapCreateInfo.imageExtent = extent;
729 swapCreateInfo.imageArrayLayers = 1;
730 swapCreateInfo.imageUsage = vk::ImageUsageFlagBits::eColorAttachment;
731 swapCreateInfo.imageSharingMode = vk::SharingMode::eExclusive;
732 swapCreateInfo.queueFamilyIndexCount = 0;
733 swapCreateInfo.pQueueFamilyIndices =
nullptr;
735 swapCreateInfo.compositeAlpha = vk::CompositeAlphaFlagBitsKHR::eOpaque;
737 swapCreateInfo.clipped =
true;
738 swapCreateInfo.oldSwapchain = VkSwapchainKHR(VK_NULL_HANDLE);
740 swapCreateInfo.imageUsage |= vk::ImageUsageFlagBits::eTransferSrc;
743 swapCreateInfo.imageUsage |= vk::ImageUsageFlagBits::eTransferDst;
783 if (needUpdateOffscreenBuffers) {
785 if (needUpdateSwapChain) {
803 vk::AttachmentDescription colorAttachment{};
806 colorAttachment.loadOp = vk::AttachmentLoadOp::eClear;
807 colorAttachment.storeOp = vk::AttachmentStoreOp::eStore;
808 colorAttachment.stencilLoadOp = vk::AttachmentLoadOp::eDontCare;
809 colorAttachment.stencilStoreOp = vk::AttachmentStoreOp::eDontCare;
810 colorAttachment.initialLayout = vk::ImageLayout::eUndefined;
811 colorAttachment.finalLayout = (
mMSAASampleCount != vk::SampleCountFlagBits::e1 ||
mDownsampleFSAA) ? vk::ImageLayout::eColorAttachmentOptimal : vk::ImageLayout::ePresentSrcKHR;
812 vk::AttachmentDescription depthAttachment{};
813 depthAttachment.format = vk::Format::eD32Sfloat;
815 depthAttachment.loadOp = vk::AttachmentLoadOp::eClear;
816 depthAttachment.storeOp = vk::AttachmentStoreOp::eDontCare;
817 depthAttachment.stencilLoadOp = vk::AttachmentLoadOp::eDontCare;
818 depthAttachment.stencilStoreOp = vk::AttachmentStoreOp::eDontCare;
819 depthAttachment.initialLayout = vk::ImageLayout::eUndefined;
820 depthAttachment.finalLayout = vk::ImageLayout::eDepthStencilAttachmentOptimal;
821 vk::AttachmentDescription colorAttachmentResolve{};
823 colorAttachmentResolve.samples = vk::SampleCountFlagBits::e1;
824 colorAttachmentResolve.loadOp = vk::AttachmentLoadOp::eDontCare;
825 colorAttachmentResolve.storeOp = vk::AttachmentStoreOp::eStore;
826 colorAttachmentResolve.stencilLoadOp = vk::AttachmentLoadOp::eDontCare;
827 colorAttachmentResolve.stencilStoreOp = vk::AttachmentStoreOp::eDontCare;
828 colorAttachmentResolve.initialLayout = vk::ImageLayout::eUndefined;
829 colorAttachmentResolve.finalLayout =
mDownsampleFSAA ? vk::ImageLayout::eColorAttachmentOptimal : vk::ImageLayout::ePresentSrcKHR;
830 int32_t nAttachments = 0;
831 vk::AttachmentReference colorAttachmentRef{};
832 colorAttachmentRef.attachment = nAttachments++;
833 colorAttachmentRef.layout = vk::ImageLayout::eColorAttachmentOptimal;
834 vk::AttachmentReference depthAttachmentRef{};
836 depthAttachmentRef.layout = vk::ImageLayout::eDepthStencilAttachmentOptimal;
837 vk::AttachmentReference colorAttachmentResolveRef{};
839 colorAttachmentResolveRef.layout = vk::ImageLayout::eColorAttachmentOptimal;
840 vk::SubpassDescription subpass{};
841 subpass.pipelineBindPoint = vk::PipelineBindPoint::eGraphics;
842 subpass.colorAttachmentCount = 1;
843 subpass.pColorAttachments = &colorAttachmentRef;
844 vk::SubpassDependency dependency{};
845 dependency.srcSubpass = VK_SUBPASS_EXTERNAL;
846 dependency.dstSubpass = 0;
847 dependency.srcStageMask = vk::PipelineStageFlagBits::eColorAttachmentOutput | vk::PipelineStageFlagBits::eEarlyFragmentTests;
848 dependency.srcAccessMask = {};
849 dependency.dstStageMask = vk::PipelineStageFlagBits::eColorAttachmentOutput | vk::PipelineStageFlagBits::eEarlyFragmentTests;
850 dependency.dstAccessMask = vk::AccessFlagBits::eColorAttachmentWrite | vk::AccessFlagBits::eDepthStencilAttachmentWrite;
852 std::vector<vk::AttachmentDescription>
attachments = {colorAttachment};
855 depthAttachmentRef.attachment = nAttachments++;
856 subpass.pDepthStencilAttachment = &depthAttachmentRef;
860 colorAttachmentResolveRef.attachment = nAttachments++;
861 subpass.pResolveAttachments = &colorAttachmentResolveRef;
864 vk::RenderPassCreateInfo renderPassInfo{};
865 renderPassInfo.attachmentCount =
attachments.size();
867 renderPassInfo.subpassCount = 1;
868 renderPassInfo.pSubpasses = &subpass;
869 renderPassInfo.dependencyCount = 1;
870 renderPassInfo.pDependencies = &dependency;
883 mZImages.resize(imageCountWithMixImages);
898 renderPassInfo.attachmentCount = 1;
899 renderPassInfo.pAttachments = &colorAttachment;
900 subpass.pDepthStencilAttachment =
nullptr;
901 subpass.pResolveAttachments =
nullptr;
903 dependency.srcStageMask = vk::PipelineStageFlagBits::eColorAttachmentOutput;
904 dependency.dstStageMask = vk::PipelineStageFlagBits::eColorAttachmentOutput;
905 dependency.dstAccessMask = vk::AccessFlagBits::eColorAttachmentWrite;
907 colorAttachment.loadOp = vk::AttachmentLoadOp::eLoad;
908 colorAttachment.initialLayout = vk::ImageLayout::ePresentSrcKHR;
909 colorAttachment.samples = vk::SampleCountFlagBits::e1;
910 colorAttachment.finalLayout = vk::ImageLayout::ePresentSrcKHR;
915 colorAttachment.initialLayout = vk::ImageLayout::eColorAttachmentOptimal;
916 colorAttachment.finalLayout =
mDownsampleFSAA ? vk::ImageLayout::eColorAttachmentOptimal : vk::ImageLayout::ePresentSrcKHR;
919 dependency.srcStageMask = vk::PipelineStageFlagBits::eColorAttachmentOutput;
920 dependency.dstStageMask = vk::PipelineStageFlagBits::eColorAttachmentOutput;
921 dependency.dstAccessMask = vk::AccessFlagBits::eColorAttachmentWrite;
926 for (uint32_t
i = 0;
i < imageCountWithMixImages;
i++) {
933 std::vector<vk::ImageView> att;
935 vk::ImageUsageFlags
usage = vk::ImageUsageFlagBits::eColorAttachment | (
i >=
mImageCount ? vk::ImageUsageFlagBits::eSampled : vk::ImageUsageFlagBits::eTransferSrc);
943 createImageI(
mDevice,
mPhysicalDevice,
mMSAAImages[
i].
image,
mMSAAImages[
i].
memory,
mRenderWidth,
mRenderHeight,
mSurfaceFormat.format, vk::ImageUsageFlagBits::eColorAttachment, vk::MemoryPropertyFlagBits::eDeviceLocal, vk::ImageTiling::eOptimal,
mMSAASampleCount);
950 createImageI(
mDevice,
mPhysicalDevice,
mZImages[
i].
image,
mZImages[
i].
memory,
mRenderWidth,
mRenderHeight, vk::Format::eD32Sfloat, vk::ImageUsageFlagBits::eDepthStencilAttachment, vk::MemoryPropertyFlagBits::eDeviceLocal, vk::ImageTiling::eOptimal,
mMSAASampleCount);
958 vk::FramebufferCreateInfo framebufferInfo{};
960 framebufferInfo.attachmentCount = att.size();
961 framebufferInfo.pAttachments = att.data();
964 framebufferInfo.layers = 1;
968 framebufferInfo.attachmentCount = 1;
977 framebufferInfo.attachmentCount = 1;
987 float vertices[6][4] = {
1027 vk::PipelineShaderStageCreateInfo shaderStages[2] = {vk::PipelineShaderStageCreateInfo{}, vk::PipelineShaderStageCreateInfo{}};
1028 vk::PipelineShaderStageCreateInfo& vertShaderStageInfo = shaderStages[0];
1029 vertShaderStageInfo.stage = vk::ShaderStageFlagBits::eVertex;
1031 vertShaderStageInfo.pName =
"main";
1032 vk::PipelineShaderStageCreateInfo& fragShaderStageInfo = shaderStages[1];
1033 fragShaderStageInfo.stage = vk::ShaderStageFlagBits::eFragment;
1035 fragShaderStageInfo.pName =
"main";
1037 vk::VertexInputBindingDescription bindingDescription{};
1038 bindingDescription.binding = 0;
1040 bindingDescription.inputRate = vk::VertexInputRate::eVertex;
1042 vk::VertexInputAttributeDescription attributeDescriptions{};
1043 attributeDescriptions.binding = 0;
1044 attributeDescriptions.location = 0;
1046 attributeDescriptions.offset = 0;
1048 vk::PipelineVertexInputStateCreateInfo vertexInputInfo{};
1049 vertexInputInfo.vertexBindingDescriptionCount = 1;
1050 vertexInputInfo.pVertexBindingDescriptions = &bindingDescription;
1051 vertexInputInfo.vertexAttributeDescriptionCount = 1;
1052 vertexInputInfo.pVertexAttributeDescriptions = &attributeDescriptions;
1053 vk::PipelineInputAssemblyStateCreateInfo inputAssembly{};
1055 inputAssembly.primitiveRestartEnable =
false;
1057 vk::Viewport viewport{};
1062 viewport.minDepth = 0.0f;
1063 viewport.maxDepth = 1.0f;
1065 vk::Rect2D scissor{};
1066 scissor.offset = vk::Offset2D{0, 0};
1069 vk::PipelineViewportStateCreateInfo viewportState{};
1070 viewportState.viewportCount = 1;
1071 viewportState.pViewports = &viewport;
1072 viewportState.scissorCount = 1;
1073 viewportState.pScissors = &scissor;
1075 vk::PipelineRasterizationStateCreateInfo rasterizer{};
1076 rasterizer.depthClampEnable =
false;
1077 rasterizer.rasterizerDiscardEnable =
false;
1078 rasterizer.polygonMode = vk::PolygonMode::eFill;
1080 rasterizer.cullMode = vk::CullModeFlagBits::eBack;
1081 rasterizer.frontFace = vk::FrontFace::eClockwise;
1082 rasterizer.depthBiasEnable =
false;
1083 rasterizer.depthBiasConstantFactor = 0.0f;
1084 rasterizer.depthBiasClamp = 0.0f;
1085 rasterizer.depthBiasSlopeFactor = 0.0f;
1087 vk::PipelineMultisampleStateCreateInfo multisampling{};
1088 multisampling.sampleShadingEnable =
false;
1090 multisampling.minSampleShading = 1.0f;
1091 multisampling.pSampleMask =
nullptr;
1092 multisampling.alphaToCoverageEnable =
false;
1093 multisampling.alphaToOneEnable =
false;
1095 vk::PipelineColorBlendAttachmentState colorBlendAttachment{};
1096 colorBlendAttachment.colorWriteMask = vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA;
1098 colorBlendAttachment.colorWriteMask = vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA;
1099 colorBlendAttachment.srcColorBlendFactor = vk::BlendFactor::eSrcAlpha;
1100 colorBlendAttachment.dstColorBlendFactor = vk::BlendFactor::eOneMinusSrcAlpha;
1101 colorBlendAttachment.colorBlendOp = vk::BlendOp::eAdd;
1102 colorBlendAttachment.srcAlphaBlendFactor = vk::BlendFactor::eOneMinusSrcAlpha;
1103 colorBlendAttachment.dstAlphaBlendFactor = vk::BlendFactor::eZero;
1104 colorBlendAttachment.alphaBlendOp = vk::BlendOp::eAdd;
1106 vk::PipelineColorBlendStateCreateInfo colorBlending{};
1107 colorBlending.logicOpEnable =
false;
1108 colorBlending.logicOp = vk::LogicOp::eCopy;
1109 colorBlending.attachmentCount = 1;
1110 colorBlending.pAttachments = &colorBlendAttachment;
1111 colorBlending.blendConstants[0] = 0.0f;
1112 colorBlending.blendConstants[1] = 0.0f;
1113 colorBlending.blendConstants[2] = 0.0f;
1114 colorBlending.blendConstants[3] = 0.0f;
1116 vk::PipelineDepthStencilStateCreateInfo depthStencil{};
1117 depthStencil.depthTestEnable =
true;
1118 depthStencil.depthWriteEnable =
true;
1119 depthStencil.depthCompareOp = vk::CompareOp::eLess;
1120 depthStencil.depthBoundsTestEnable =
false;
1121 depthStencil.stencilTestEnable =
false;
1123 vk::DynamicState dynamicStates[] = {vk::DynamicState::eLineWidth};
1124 vk::PipelineDynamicStateCreateInfo dynamicState{};
1125 dynamicState.dynamicStateCount = 1;
1126 dynamicState.pDynamicStates = dynamicStates;
1128 vk::PushConstantRange pushConstantRanges[2] = {vk::PushConstantRange{}, vk::PushConstantRange{}};
1129 pushConstantRanges[0].stageFlags = vk::ShaderStageFlagBits::eFragment;
1130 pushConstantRanges[0].offset = 0;
1131 pushConstantRanges[0].size =
sizeof(float) * 4;
1132 pushConstantRanges[1].stageFlags = vk::ShaderStageFlagBits::eVertex;
1133 pushConstantRanges[1].offset = pushConstantRanges[0].size;
1134 pushConstantRanges[1].size =
sizeof(float);
1135 vk::PipelineLayoutCreateInfo pipelineLayoutInfo{};
1136 pipelineLayoutInfo.setLayoutCount = 1;
1138 pipelineLayoutInfo.pushConstantRangeCount = 2;
1139 pipelineLayoutInfo.pPushConstantRanges = pushConstantRanges;
1141 pipelineLayoutInfo.setLayoutCount = 1;
1145 vk::GraphicsPipelineCreateInfo pipelineInfo{};
1146 pipelineInfo.stageCount = 2;
1147 pipelineInfo.pVertexInputState = &vertexInputInfo;
1148 pipelineInfo.pInputAssemblyState = &inputAssembly;
1149 pipelineInfo.pViewportState = &viewportState;
1150 pipelineInfo.pRasterizationState = &rasterizer;
1151 pipelineInfo.pMultisampleState = &multisampling;
1153 pipelineInfo.pColorBlendState = &colorBlending;
1154 pipelineInfo.pDynamicState = &dynamicState;
1157 pipelineInfo.subpass = 0;
1158 pipelineInfo.pStages = shaderStages;
1159 pipelineInfo.basePipelineHandle = VkPipeline(VK_NULL_HANDLE);
1160 pipelineInfo.basePipelineIndex = -1;
1163 static constexpr vk::PrimitiveTopology
types[3] = {vk::PrimitiveTopology::ePointList, vk::PrimitiveTopology::eLineList, vk::PrimitiveTopology::eLineStrip};
1166 bindingDescription.stride = 4 *
sizeof(float);
1167 attributeDescriptions.format = vk::Format::eR32G32B32A32Sfloat;
1168 inputAssembly.topology = vk::PrimitiveTopology::eTriangleList;
1169 vertShaderStageInfo.module =
mShaders[
"vertexTexture"];
1170 fragShaderStageInfo.module =
mShaders[
"fragmentTexture"];
1173 pipelineInfo.pDepthStencilState =
nullptr;
1174 colorBlendAttachment.blendEnable =
true;
1175 multisampling.rasterizationSamples = vk::SampleCountFlagBits::e1;
1178 }
else if (
i == 3) {
1179 bindingDescription.stride = 4 *
sizeof(float);
1180 attributeDescriptions.format = vk::Format::eR32G32B32A32Sfloat;
1181 inputAssembly.topology = vk::PrimitiveTopology::eTriangleList;
1182 vertShaderStageInfo.module =
mShaders[
"vertexTexture"];
1183 fragShaderStageInfo.module =
mShaders[
"fragmentText"];
1186 pipelineInfo.pDepthStencilState =
nullptr;
1187 colorBlendAttachment.blendEnable =
true;
1188 multisampling.rasterizationSamples = vk::SampleCountFlagBits::e1;
1192 bindingDescription.stride = 3 *
sizeof(float);
1193 attributeDescriptions.format = vk::Format::eR32G32B32Sfloat;
1194 inputAssembly.topology =
types[
i];
1195 vertShaderStageInfo.module =
mShaders[
types[
i] == vk::PrimitiveTopology::ePointList ?
"vertexPoint" :
"vertex"];
1196 fragShaderStageInfo.module =
mShaders[
"fragment"];
1199 pipelineInfo.pDepthStencilState =
mZActive ? &depthStencil :
nullptr;
1200 colorBlendAttachment.blendEnable =
true;
1206 CHKERR(
mDevice.createGraphicsPipelines(VkPipelineCache(VK_NULL_HANDLE), 1, &pipelineInfo,
nullptr, &
mPipelines[
i]));
1212 commandBuffer.reset({});
1214 vk::CommandBufferBeginInfo beginInfo{};
1215 beginInfo.flags = {};
1216 commandBuffer.begin(beginInfo);
1218 vk::ClearValue clearValues[2];
1219 clearValues[0].color =
mDisplay->
cfgL().invertColors ? vk::ClearColorValue{std::array<float, 4>{1.0f, 1.0f, 1.0f, 1.0f}} : vk::ClearColorValue{std::array<float, 4>{0.0f, 0.0f, 0.0f, 1.0f}};
1220 clearValues[1].depthStencil = vk::ClearDepthStencilValue{{1.0f, 0}};
1222 vk::RenderPassBeginInfo renderPassInfo{};
1225 renderPassInfo.renderArea.offset = vk::Offset2D{0, 0};
1227 renderPassInfo.clearValueCount =
mZActive ? 2 : 1;
1228 renderPassInfo.pClearValues = clearValues;
1229 commandBuffer.beginRenderPass(&renderPassInfo, vk::SubpassContents::eInline);
1231 vk::DeviceSize
offsets[] = {0};
1238 commandBuffer.endRenderPass();
1239 commandBuffer.end();
1251#define LOAD_SHADER(file, ext) \
1252 mShaders[#file] = createShaderModule(_binary_shaders_shaders_##file##_##ext##_spv_start, _binary_shaders_shaders_##file##_##ext##_spv_len, mDevice)
1266 clearVector(
mShaders, [&](
auto&
x) {
mDevice.destroyShaderModule(
x.second,
nullptr); });
1273 if (
buffer.deviceMemory != 1) {
1276 memcpy(dstData, srcData,
size);
1279 auto tmp =
createBuffer(
size, srcData, vk::BufferUsageFlagBits::eTransferSrc, 0);
1282 vk::BufferCopy copyRegion{};
1283 copyRegion.size =
size;
1284 commandBuffer.copyBuffer(tmp.buffer,
buffer.buffer, 1, ©Region);
1293 vk::MemoryPropertyFlags properties;
1295 properties |= vk::MemoryPropertyFlagBits::eDeviceLocal;
1297 if (deviceMemory == 0 || deviceMemory == 2) {
1298 properties |= (vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
1300 if (deviceMemory == 1) {
1301 type |= vk::BufferUsageFlagBits::eTransferDst;
1305 vk::BufferCreateInfo bufferInfo{};
1307 bufferInfo.usage =
type;
1308 bufferInfo.sharingMode = vk::SharingMode::eExclusive;
1311 vk::MemoryRequirements memRequirements;
1312 memRequirements =
mDevice.getBufferMemoryRequirements(
buffer.buffer);
1313 vk::MemoryAllocateInfo allocInfo{};
1314 allocInfo.allocationSize = memRequirements.size;
1315 allocInfo.memoryTypeIndex = findMemoryType(memRequirements.memoryTypeBits, properties,
mPhysicalDevice);
1321 buffer.deviceMemory = deviceMemory;
1323 if (srcData !=
nullptr) {
1358 auto tmp =
createBuffer(srcSize, srcData, vk::BufferUsageFlagBits::eTransferSrc, 0);
1361 cmdImageMemoryBarrier(commandBuffer,
image.image, {}, vk::AccessFlagBits::eTransferWrite, vk::ImageLayout::eUndefined, vk::ImageLayout::eTransferDstOptimal, vk::PipelineStageFlagBits::eTopOfPipe, vk::PipelineStageFlagBits::eTransfer);
1362 vk::BufferImageCopy region{};
1363 region.bufferOffset = 0;
1364 region.bufferRowLength = 0;
1365 region.bufferImageHeight = 0;
1366 region.imageSubresource.aspectMask = vk::ImageAspectFlagBits::eColor;
1367 region.imageSubresource.mipLevel = 0;
1368 region.imageSubresource.baseArrayLayer = 0;
1369 region.imageSubresource.layerCount = 1;
1370 region.imageOffset = vk::Offset3D{0, 0, 0};
1371 region.imageExtent = vk::Extent3D{
image.sizex,
image.sizey, 1};
1372 commandBuffer.copyBufferToImage(tmp.buffer,
image.image, vk::ImageLayout::eTransferDstOptimal, 1, ®ion);
1373 cmdImageMemoryBarrier(commandBuffer,
image.image, vk::AccessFlagBits::eTransferWrite, vk::AccessFlagBits::eShaderRead, vk::ImageLayout::eTransferDstOptimal, vk::ImageLayout::eShaderReadOnlyOptimal, vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eFragmentShader);
1382 createImageI(
mDevice,
mPhysicalDevice,
image.image,
image.memory, sizex, sizey,
format, vk::ImageUsageFlagBits::eTransferDst | vk::ImageUsageFlagBits::eSampled, vk::MemoryPropertyFlagBits::eDeviceLocal, vk::ImageTiling::eOptimal, vk::SampleCountFlagBits::e1);
1386 image.sizex = sizex;
1387 image.sizey = sizey;
1470 auto first = std::get<0>(
v);
1471 auto count = std::get<1>(
v);
1472 auto iSector = std::get<2>(
v);
1487 for (uint32_t k = 0; k <
count; k++) {
1501 if (includeMixImage == 0.f) {
1504 auto getImage = [&]() {
1505 vk::Fence fen = VkFence(VK_NULL_HANDLE);
1506 vk::Semaphore sem = VkSemaphore(VK_NULL_HANDLE);
1516 vk::Result
retVal = vk::Result::eSuccess;
1519 mustUpdateRendering =
true;
1524 if (!mustUpdateRendering) {
1525 GPUInfo(
"Pipeline out of data / suboptimal, recreating");
1539 const hmm_mat4 modelViewProj = proj * view;
1563 const vk::Fence noFence = VkFence(VK_NULL_HANDLE);
1565 vk::SubmitInfo submitInfo{};
1566 vk::PipelineStageFlags waitStages[] = {vk::PipelineStageFlagBits::eColorAttachmentOutput};
1568 submitInfo.waitSemaphoreCount = submitInfo.pWaitSemaphores !=
nullptr ? 1 : 0;
1569 submitInfo.pWaitDstStageMask = waitStages;
1570 submitInfo.commandBufferCount = 1;
1572 submitInfo.signalSemaphoreCount = 1;
1573 submitInfo.pSignalSemaphores = stageFinishedSemaphore;
1576 if (includeMixImage > 0.f) {
1578 submitInfo.pWaitSemaphores = stageFinishedSemaphore;
1579 waitStages[0] = {vk::PipelineStageFlagBits::eColorAttachmentOutput};
1580 submitInfo.waitSemaphoreCount = 1;
1583 submitInfo.pSignalSemaphores = stageFinishedSemaphore;
1590 submitInfo.pWaitSemaphores = stageFinishedSemaphore;
1591 waitStages[0] = {vk::PipelineStageFlagBits::eTransfer};
1592 submitInfo.waitSemaphoreCount = 1;
1594 submitInfo.pSignalSemaphores = stageFinishedSemaphore;
1608 submitInfo.pWaitSemaphores = stageFinishedSemaphore;
1609 waitStages[0] = {vk::PipelineStageFlagBits::eColorAttachmentOutput};
1610 submitInfo.waitSemaphoreCount = 1;
1613 submitInfo.pSignalSemaphores = stageFinishedSemaphore;
1618 vk::PresentInfoKHR presentInfo{};
1619 presentInfo.waitSemaphoreCount = 1;
1620 presentInfo.pWaitSemaphores = stageFinishedSemaphore;
1621 presentInfo.swapchainCount = 1;
1624 presentInfo.pResults =
nullptr;
1626 if (
retVal == vk::Result::eErrorOutOfDateKHR) {
1636 commandBuffer.reset({});
1637 vk::CommandBufferBeginInfo beginInfo{};
1638 beginInfo.flags = vk::CommandBufferUsageFlagBits::eOneTimeSubmit;
1639 commandBuffer.begin(beginInfo);
1641 cmdImageMemoryBarrier(commandBuffer,
mSwapChainImages[
mCurrentImageIndex], {}, vk::AccessFlagBits::eTransferWrite, vk::ImageLayout::eUndefined, vk::ImageLayout::eTransferDstOptimal, vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eTransfer);
1642 cmdImageMemoryBarrier(commandBuffer,
mDownsampleImages[
mCurrentImageIndex].
image, vk::AccessFlagBits::eMemoryRead, vk::AccessFlagBits::eTransferRead, vk::ImageLayout::eColorAttachmentOptimal, vk::ImageLayout::eTransferSrcOptimal, vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eTransfer);
1644 vk::Offset3D blitSizeSrc;
1648 vk::Offset3D blitSizeDst;
1652 vk::ImageBlit imageBlitRegion{};
1653 imageBlitRegion.srcSubresource.aspectMask = vk::ImageAspectFlagBits::eColor;
1654 imageBlitRegion.srcSubresource.layerCount = 1;
1655 imageBlitRegion.srcOffsets[1] = blitSizeSrc;
1656 imageBlitRegion.dstSubresource.aspectMask = vk::ImageAspectFlagBits::eColor;
1657 imageBlitRegion.dstSubresource.layerCount = 1;
1658 imageBlitRegion.dstOffsets[1] = blitSizeDst;
1661 cmdImageMemoryBarrier(commandBuffer,
mSwapChainImages[
mCurrentImageIndex], vk::AccessFlagBits::eTransferWrite, vk::AccessFlagBits::eMemoryRead, vk::ImageLayout::eTransferDstOptimal, vk::ImageLayout::ePresentSrcKHR, vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eTransfer);
1662 cmdImageMemoryBarrier(commandBuffer,
mDownsampleImages[
mCurrentImageIndex].
image, vk::AccessFlagBits::eTransferRead, vk::AccessFlagBits::eMemoryRead, vk::ImageLayout::eUndefined, vk::ImageLayout::eColorAttachmentOptimal, vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eTransfer);
1664 commandBuffer.end();
1684 vk::CommandBufferBeginInfo beginInfo{};
1685 beginInfo.flags = vk::CommandBufferUsageFlagBits::eOneTimeSubmit;
1688 vk::RenderPassBeginInfo renderPassInfo{};
1691 renderPassInfo.renderArea.offset = vk::Offset2D{0, 0};
1693 renderPassInfo.clearValueCount = 0;
1703 vk::DeviceSize
offsets[] = {0};
1722 commandBuffer.reset({});
1723 vk::CommandBufferBeginInfo beginInfo{};
1724 beginInfo.flags = vk::CommandBufferUsageFlagBits::eOneTimeSubmit;
1725 commandBuffer.begin(beginInfo);
1728 vk::ImageLayout srcLayout =
mDownsampleFSAA ? vk::ImageLayout::eColorAttachmentOptimal : vk::ImageLayout::ePresentSrcKHR;
1729 cmdImageMemoryBarrier(commandBuffer,
image, {}, vk::AccessFlagBits::eMemoryRead, srcLayout, vk::ImageLayout::eShaderReadOnlyOptimal, vk::PipelineStageFlagBits::eAllCommands, vk::PipelineStageFlagBits::eFragmentShader);
1731 vk::RenderPassBeginInfo renderPassInfo{};
1734 renderPassInfo.renderArea.offset = vk::Offset2D{0, 0};
1736 renderPassInfo.clearValueCount = 0;
1737 commandBuffer.beginRenderPass(renderPassInfo, vk::SubpassContents::eInline);
1739 commandBuffer.bindPipeline(vk::PipelineBindPoint::eGraphics,
mPipelines[4]);
1744 vk::DeviceSize
offsets[] = {0};
1747 commandBuffer.pushConstants(
mPipelineLayoutTexture, vk::ShaderStageFlagBits::eFragment, 0,
sizeof(mixSlaveImage), &mixSlaveImage);
1748 commandBuffer.draw(6, 1, 0, 0);
1750 commandBuffer.endRenderPass();
1751 commandBuffer.end();
1787 throw std::runtime_error(
"Incorrect symbol ID");
1791 if (sizex && sizey) {
1792 buffer.reset(
new char[sizex * sizey]);
1799 int32_t maxSizeX = 0, maxSizeY = 0, maxBigX = 0, maxBigY = 0, maxRowY = 0;
1803 maxSizeX = std::max(maxSizeX, symbol.size[0]);
1804 maxSizeY = std::max(maxSizeY, symbol.size[1]);
1807 int32_t sizex = nn * maxSizeX;
1808 int32_t sizey = nn * maxSizeY;
1809 std::unique_ptr<char[]> bigImage{
new char[sizex * sizey]};
1810 memset(bigImage.get(), 0, sizex * sizey);
1811 int32_t rowy = 0, colx = 0;
1814 if (colx + s.size[0] > sizex) {
1819 for (int32_t k = 0; k < s.size[1]; k++) {
1820 for (int32_t
j = 0;
j < s.size[0];
j++) {
1821 int8_t
val = s.data.get()[
j + k * s.size[0]];
1823 val =
val < 0 ? 0xFF : 0;
1825 bigImage.get()[(colx +
j) + (rowy + k) * sizex] =
val;
1830 s.x1 = colx + s.size[0];
1832 s.y1 = rowy + s.size[1];
1833 maxBigX = std::max(maxBigX, colx + s.size[0]);
1834 maxBigY = std::max(maxBigY, rowy + s.size[1]);
1835 maxRowY = std::max(maxRowY, s.size[1]);
1838 if (maxBigX != sizex) {
1839 for (int32_t
y = 1;
y < maxBigY;
y++) {
1840 memmove(bigImage.get() +
y * maxBigX, bigImage.get() +
y * sizex, maxBigX);
1859 vk::DescriptorImageInfo imageInfo{};
1860 imageInfo.imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
1864 vk::WriteDescriptorSet descriptorWrite{};
1866 descriptorWrite.dstBinding = 2;
1867 descriptorWrite.dstArrayElement = 0;
1868 descriptorWrite.descriptorType = vk::DescriptorType::eCombinedImageSampler;
1869 descriptorWrite.descriptorCount = 1;
1870 descriptorWrite.pImageInfo = &imageInfo;
1871 mDevice.updateDescriptorSets(1, &descriptorWrite, 0,
nullptr);
1886 for (
const char*
c = s; *
c;
c++) {
1888 GPUError(
"Trying to draw unsupported symbol: %d > %d\n", (int32_t)*
c, (int32_t)
mFontSymbols.size());
1894 float xpos =
x + sym.
offset[0] * scale;
1895 float ypos =
y - (sym.
size[1] - sym.
offset[1]) * scale;
1896 float w = sym.
size[0] * scale;
1897 float h = sym.
size[1] * scale;
1898 float vertices[6][4] = {
1916 if (
c.size() &&
c.back().color[0] ==
color[0] &&
c.back().color[1] ==
color[1] &&
c.back().color[2] ==
color[2] &&
c.back().color[3] ==
color[3]) {
1917 c.back().nVertices += nVertices;
1928 static constexpr int32_t bytesPerPixel = 4;
1931 vk::Image dstImage, dstImage2, src2;
1932 vk::DeviceMemory dstImageMemory, dstImageMemory2;
1933 createImageI(
mDevice,
mPhysicalDevice, dstImage, dstImageMemory,
width,
height, vk::Format::eR8G8B8A8Unorm, vk::ImageUsageFlagBits::eTransferDst, vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent, vk::ImageTiling::eLinear);
1935 cmdImageMemoryBarrier(cmdBuffer,
image, vk::AccessFlagBits::eMemoryRead, vk::AccessFlagBits::eTransferRead, layout, vk::ImageLayout::eTransferSrcOptimal, vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eTransfer);
1937 createImageI(
mDevice,
mPhysicalDevice, dstImage2, dstImageMemory2,
width,
height,
mSurfaceFormat.format, vk::ImageUsageFlagBits::eColorAttachment | vk::ImageUsageFlagBits::eTransferSrc | vk::ImageUsageFlagBits::eTransferDst, vk::MemoryPropertyFlagBits::eDeviceLocal, vk::ImageTiling::eOptimal);
1938 cmdImageMemoryBarrier(cmdBuffer, dstImage2, {}, vk::AccessFlagBits::eTransferWrite, vk::ImageLayout::eUndefined, vk::ImageLayout::eTransferDstOptimal, vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eTransfer);
1940 vk::Offset3D blitSizeDst = {(int32_t)
width, (int32_t)
height, 1};
1941 vk::ImageBlit imageBlitRegion{};
1942 imageBlitRegion.srcSubresource.aspectMask = vk::ImageAspectFlagBits::eColor;
1943 imageBlitRegion.srcSubresource.layerCount = 1;
1944 imageBlitRegion.srcOffsets[1] = blitSizeSrc;
1945 imageBlitRegion.dstSubresource.aspectMask = vk::ImageAspectFlagBits::eColor;
1946 imageBlitRegion.dstSubresource.layerCount = 1;
1947 imageBlitRegion.dstOffsets[1] = blitSizeDst;
1948 cmdBuffer.blitImage(
image, vk::ImageLayout::eTransferSrcOptimal, dstImage2, vk::ImageLayout::eTransferDstOptimal, 1, &imageBlitRegion, vk::Filter::eLinear);
1950 cmdImageMemoryBarrier(cmdBuffer, dstImage2, vk::AccessFlagBits::eMemoryRead, vk::AccessFlagBits::eTransferRead, vk::ImageLayout::eTransferDstOptimal, vk::ImageLayout::eTransferSrcOptimal, vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eTransfer);
1955 cmdImageMemoryBarrier(cmdBuffer, dstImage, {}, vk::AccessFlagBits::eTransferWrite, vk::ImageLayout::eUndefined, vk::ImageLayout::eTransferDstOptimal, vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eTransfer);
1956 vk::ImageCopy imageCopyRegion{};
1957 imageCopyRegion.srcSubresource.aspectMask = vk::ImageAspectFlagBits::eColor;
1958 imageCopyRegion.srcSubresource.layerCount = 1;
1959 imageCopyRegion.dstSubresource.aspectMask = vk::ImageAspectFlagBits::eColor;
1960 imageCopyRegion.dstSubresource.layerCount = 1;
1961 imageCopyRegion.extent.width =
width;
1962 imageCopyRegion.extent.height =
height;
1963 imageCopyRegion.extent.depth = 1;
1964 cmdBuffer.copyImage(src2, vk::ImageLayout::eTransferSrcOptimal, dstImage, vk::ImageLayout::eTransferDstOptimal, 1, &imageCopyRegion);
1966 cmdImageMemoryBarrier(cmdBuffer, dstImage, vk::AccessFlagBits::eTransferWrite, vk::AccessFlagBits::eMemoryRead, vk::ImageLayout::eTransferDstOptimal, vk::ImageLayout::eGeneral, vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eTransfer);
1967 cmdImageMemoryBarrier(cmdBuffer,
image, vk::AccessFlagBits::eTransferRead, vk::AccessFlagBits::eMemoryRead, vk::ImageLayout::eTransferSrcOptimal, layout, vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eTransfer);
1970 vk::ImageSubresource subResource{vk::ImageAspectFlagBits::eColor, 0, 0};
1971 vk::SubresourceLayout subResourceLayout =
mDevice.getImageSubresourceLayout(dstImage, subResource);
1974 data += subResourceLayout.offset;
1978 mDevice.unmapMemory(dstImageMemory);
1979 mDevice.freeMemory(dstImageMemory,
nullptr);
1980 mDevice.destroyImage(dstImage,
nullptr);
1982 mDevice.freeMemory(dstImageMemory2,
nullptr);
1983 mDevice.destroyImage(dstImage2,
nullptr);
#define LOAD_SHADER(file, ext)
HMM_INLINE hmm_mat4 HMM_Orthographic(float Left, float Right, float Bottom, float Top, float Near, float Far)
Class for time synchronization of RawReader instances.
void OpenGLPrint(const char *s, float x, float y, float *color, float scale) override
vk::CommandBuffer getSingleTimeCommandBuffer()
std::vector< vk::Fence > mInFlightFence
std::vector< vk::CommandBuffer > mCommandBuffersMix
vk::RenderPass mRenderPassTexture
std::vector< vk::CommandBuffer > mCommandBuffers
void setMixDescriptor(int32_t descriptorIndex, int32_t imageIndex)
std::vector< vk::Semaphore > mRenderFinishedSemaphore
vk::DescriptorPool mDescriptorPool
vk::DescriptorSetLayout mUniformDescriptor
VulkanBuffer mIndirectCommandBuffer
void prepareDraw(const hmm_mat4 &proj, const hmm_mat4 &view, bool requestScreenshot, bool toMixBuffer, float includeMixImage) override
std::vector< vk::Pipeline > mPipelines
vk::CommandBuffer mCurrentCommandBuffer
void createCommandBuffers()
void resizeScene(uint32_t width, uint32_t height) override
vk::Fence mSingleCommitFence
int32_t mCurrentCommandBufferLastPipeline
uint32_t DepthBits() override
void submitSingleTimeCommandBuffer(vk::CommandBuffer commandBuffer)
std::vector< VulkanImage > mDownsampleImages
void clearUniformLayoutsAndBuffers()
void writeToBuffer(VulkanBuffer &buffer, size_t size, const void *srcData)
std::vector< vk::ImageView > mSwapChainImageViews
std::vector< VulkanImage > mMSAAImages
void pointSizeFactor(float factor) override
std::vector< FontSymbolVulkan > mFontSymbols
vk::SwapchainKHR mSwapChain
int32_t InitBackendA() override
void clearImage(VulkanImage &image)
std::vector< vk::ImageView * > mRenderTargetView
std::vector< vk::Framebuffer > mFramebuffersTexture
void finishText() override
void addFontSymbol(int32_t symbol, int32_t sizex, int32_t sizey, int32_t offsetx, int32_t offsety, int32_t advance, void *data) override
bool backendNeedRedraw() override
vk::SampleCountFlagBits mMSAASampleCount
std::vector< vk::Framebuffer > mFramebuffersText
void mixImages(vk::CommandBuffer cmdBuffer, float mixSlaveImage)
void clearVertexBuffers()
void createTextureSampler()
void recreateRendering(bool forScreenshot=false, bool forMixing=false)
std::vector< VulkanBuffer > mFontVertexBuffer
void endFillCommandBuffer(vk::CommandBuffer &commandBuffer)
uint32_t drawVertices(const vboList &v, const drawType t) override
vk::SurfaceFormatKHR mSurfaceFormat
bool mCommandBufferPerImage
std::vector< vk::CommandBuffer > mCommandBuffersDownsample
void ActivateColor(std::array< float, 4 > &color) override
std::vector< vk::Image > mSwapChainImages
void initializeTextDrawing() override
void clearBuffer(VulkanBuffer &buffer)
VulkanBuffer mMixingTextureVertexArray
std::vector< vk::Semaphore > mMixFinishedSemaphore
vk::Sampler mTextureSampler
std::vector< vk::Semaphore > mTextFinishedSemaphore
uint32_t mCurrentImageIndex
void updateFontTextureDescriptor()
void createUniformLayoutsAndBuffers()
void needRecordCommandBuffers()
std::vector< VulkanBuffer > mUniformBuffersMat[3]
double checkDevice(vk::PhysicalDevice device, const std::vector< const char * > &reqDeviceExtensions)
bool mCommandInfrastructureCreated
void updateSwapChainDetails(const vk::PhysicalDevice &device)
std::vector< VulkanImage > mMixImages
vk::CommandPool mCommandPool
void finishDraw(bool doScreenshot, bool toMixBuffer, float includeMixImage) override
bool mCubicFilterSupported
void writeToImage(VulkanImage &image, const void *srcData, size_t srcSize)
vk::RenderPass mRenderPass
void createSemaphoresAndFences()
std::vector< vk::DescriptorSet > mDescriptorSets[3]
vecpod< float > mFontVertexBufferHost
vk::PipelineLayout mPipelineLayout
void clearOffscreenBuffers()
vk::DescriptorSetLayout mUniformDescriptorTexture
bool mSwapchainImageReadable
void downsampleToFramebuffer(vk::CommandBuffer &commandBuffer)
void ExitBackendA() override
vk::Extent2D chooseSwapExtent(const vk::SurfaceCapabilitiesKHR &capabilities)
vk::RenderPass mRenderPassText
void clearSemaphoresAndFences()
~GPUDisplayBackendVulkan() override
std::vector< vk::Framebuffer > mFramebuffers
void readImageToPixels(vk::Image image, vk::ImageLayout layout, std::vector< char > &pixels)
VulkanImage createImage(uint32_t sizex, uint32_t sizey, const void *srcData=nullptr, size_t srcSize=0, vk::Format format=vk::Format::eR8G8B8A8Srgb)
std::vector< vk::Semaphore > mDownsampleFinishedSemaphore
std::vector< TextDrawCommand > mTextDrawCommands
void clearTextureSampler()
vk::PipelineLayout mPipelineLayoutTexture
SwapChainSupportDetails mSwapChainDetails
uint32_t mMaxMSAAsupported
std::unordered_map< std::string, vk::ShaderModule > mShaders
void finishFrame(bool doScreenshot, bool toMixBuffer, float includeMixImage) override
void createSwapChain(bool forScreenshot=false, bool forMixing=false)
std::vector< vk::Semaphore > mImageAvailableSemaphore
int32_t mCurrentBufferSet
void startFillCommandBuffer(vk::CommandBuffer &commandBuffer, uint32_t imageIndex, bool toMixBuffer=false)
std::vector< vk::CommandBuffer > mCommandBuffersTexture
vk::PhysicalDevice mPhysicalDevice
vk::DebugUtilsMessengerEXT mDebugMessenger
GPUDisplayBackendVulkan()
VulkanBuffer createBuffer(size_t size, const void *srcData=nullptr, vk::BufferUsageFlags type=vk::BufferUsageFlagBits::eVertexBuffer, int32_t deviceMemory=1)
std::vector< VulkanImage > mZImages
void createOffscreenBuffers(bool forScreenshot=false, bool forMixing=false)
bool mEnableValidationLayers
std::vector< bool > mCommandBufferUpToDate
void lineWidthFactor(float factor) override
void prepareText() override
void clearCommandBuffers()
std::vector< vk::CommandBuffer > mCommandBuffersText
bool mMustUpdateSwapChain
vk::PresentModeKHR mPresentMode
void loadDataToGPU(size_t totalVertizes) override
std::vector< VulkanBuffer > mUniformBuffersCol[3]
vecpod< DrawArraysIndirectCommand > mCmdBuffer
std::vector< int32_t > mIndirectSectorOffset
void fillIndirectCmdBuffer()
bool mFreetypeInitialized
std::vector< char > mScreenshotPixels
backendTypes mBackendType
const char * mBackendName
float getDownsampleFactor(bool screenshot=false)
int32_t mDownsampleFactor
std::tuple< uint32_t, uint32_t, int32_t > vboList
virtual uint32_t getReqVulkanExtensions(const char **&p)
virtual void getSize(int32_t &width, int32_t &height)
virtual int32_t getVulkanSurface(void *instance, void *surface)
const GPUSettingsDisplayLight & cfgL() const
int32_t updateRenderPipeline() const
const GPUSettingsDisplayRenderer & cfgR() const
vecpod< vtx > * vertexBuffer()
bool drawTextInCompatMode() const
int32_t updateDrawCommands() const
GPUDisplayFrontend * frontend()
const vecpod< uint32_t > * vertexBufferCount() const
const GPUSettingsDisplay & cfg() const
vecpod< int32_t > * vertexBufferStart()
GLuint GLsizei const GLuint const GLintptr * offsets
GLsizei GLenum GLenum * types
GLint GLsizei GLsizei height
GLint GLint GLsizei GLint GLenum GLenum type
GLint GLint GLsizei GLint GLenum GLenum const void * pixels
GLsizei const GLenum * attachments
GLenum GLuint GLenum GLsizei const GLchar * buf
GLubyte GLubyte GLubyte GLubyte w
GLint GLint GLsizei GLint GLenum format
GLsizeiptr const void GLenum usage
#define QGET_LD_BINARY_SYMBOLS(filename)
std::vector< vk::SurfaceFormatKHR > formats
vk::SurfaceCapabilitiesKHR capabilities
std::vector< vk::PresentModeKHR > presentModes