15#define VULKAN_HPP_DISPATCH_LOADER_DYNAMIC 1
16#include <vulkan/vulkan.hpp>
17VULKAN_HPP_DEFAULT_DISPATCH_LOADER_DYNAMIC_STORAGE
40 auto tmp_internal_retVal = cmd; \
41 if ((int32_t)tmp_internal_retVal < 0) { \
42 GPUError("VULKAN ERROR: %d: %s (%s: %d)", (int32_t)tmp_internal_retVal, "ERROR", __FILE__, __LINE__); \
43 throw std::runtime_error("Vulkan Failure"); \
56static int32_t checkVulkanLayersSupported(
const std::vector<const char*>& validationLayers)
58 std::vector<vk::LayerProperties> availableLayers = vk::enumerateInstanceLayerProperties();
59 for (
const char* layerName : validationLayers) {
60 bool layerFound =
false;
62 for (
const auto& layerProperties : availableLayers) {
63 if (strcmp(layerName, layerProperties.layerName) == 0) {
76static uint32_t findMemoryType(uint32_t typeFilter, vk::MemoryPropertyFlags properties, vk::PhysicalDevice physDev)
78 vk::PhysicalDeviceMemoryProperties memProperties = physDev.getMemoryProperties();
80 for (uint32_t
i = 0;
i < memProperties.memoryTypeCount;
i++) {
81 if ((typeFilter & (1 <<
i)) && (memProperties.memoryTypes[
i].propertyFlags & properties) == properties) {
86 throw std::runtime_error(
"failed to find suitable memory type!");
89static vk::SurfaceFormatKHR chooseSwapSurfaceFormat(
const std::vector<vk::SurfaceFormatKHR>& availableFormats)
91 for (
const auto& availableFormat : availableFormats) {
92 if (availableFormat.format == vk::Format::eB8G8R8A8Unorm && availableFormat.colorSpace == vk::ColorSpaceKHR::eSrgbNonlinear) {
93 return availableFormat;
96 return availableFormats[0];
99static vk::PresentModeKHR chooseSwapPresentMode(
const std::vector<vk::PresentModeKHR>& availablePresentModes, vk::PresentModeKHR desiredMode = vk::PresentModeKHR::eMailbox)
101 for (
const auto& availablePresentMode : availablePresentModes) {
102 if (availablePresentMode == desiredMode) {
103 return availablePresentMode;
106 static bool errorShown =
false;
109 GPUError(
"VULKAN ERROR: Desired present mode not available, using FIFO mode");
111 return vk::PresentModeKHR::eFifo;
116 if (capabilities.currentExtent.width != std::numeric_limits<uint32_t>::max()) {
117 return capabilities.currentExtent;
121 vk::Extent2D actualExtent = {(uint32_t)
width, (uint32_t)
height};
122 actualExtent.width = std::clamp(actualExtent.width, capabilities.minImageExtent.width, capabilities.maxImageExtent.width);
123 actualExtent.height = std::clamp(actualExtent.height, capabilities.minImageExtent.height, capabilities.maxImageExtent.height);
128static vk::ShaderModule createShaderModule(
const char* code,
size_t size, vk::Device device)
130 vk::ShaderModuleCreateInfo createInfo{};
131 createInfo.codeSize =
size;
132 createInfo.pCode =
reinterpret_cast<const uint32_t*
>(code);
133 return device.createShaderModule(createInfo,
nullptr);
136static 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)
138 vk::ImageSubresourceRange
range{vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1};
139 vk::ImageMemoryBarrier barrier{};
140 barrier.srcAccessMask = srcAccessMask;
141 barrier.dstAccessMask = dstAccessMask;
142 barrier.oldLayout = oldLayout;
143 barrier.newLayout = newLayout;
144 barrier.image =
image;
145 barrier.subresourceRange =
range;
146 cmdbuffer.pipelineBarrier(srcStageMask, dstStageMask, {}, 0,
nullptr, 0,
nullptr, 1, &barrier);
158 vk::CommandBufferAllocateInfo allocInfo{};
159 allocInfo.level = vk::CommandBufferLevel::ePrimary;
161 allocInfo.commandBufferCount = 1;
162 vk::CommandBuffer commandBuffer =
mDevice.allocateCommandBuffers(allocInfo)[0];
163 vk::CommandBufferBeginInfo beginInfo{};
164 beginInfo.flags = vk::CommandBufferUsageFlagBits::eOneTimeSubmit;
165 commandBuffer.begin(beginInfo);
166 return commandBuffer;
172 vk::SubmitInfo submitInfo{};
173 submitInfo.commandBufferCount = 1;
174 submitInfo.pCommandBuffers = &commandBuffer;
175 static std::mutex fenceMutex;
177 std::lock_guard<std::mutex> guard(fenceMutex);
185static vk::ImageView createImageViewI(vk::Device device, vk::Image
image, vk::Format
format, vk::ImageAspectFlags aspectFlags = vk::ImageAspectFlagBits::eColor, uint32_t mipLevels = 1)
187 vk::ImageViewCreateInfo viewInfo{};
188 viewInfo.image =
image;
189 viewInfo.viewType = vk::ImageViewType::e2D;
191 viewInfo.subresourceRange.aspectMask = aspectFlags;
192 viewInfo.subresourceRange.baseMipLevel = 0;
193 viewInfo.subresourceRange.levelCount = mipLevels;
194 viewInfo.subresourceRange.baseArrayLayer = 0;
195 viewInfo.subresourceRange.layerCount = 1;
196 return device.createImageView(viewInfo,
nullptr);
199static 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)
201 vk::ImageCreateInfo imageInfo{};
202 imageInfo.imageType = vk::ImageType::e2D;
203 imageInfo.extent.width =
width;
204 imageInfo.extent.height =
height;
205 imageInfo.extent.depth = 1;
206 imageInfo.mipLevels = mipLevels;
207 imageInfo.arrayLayers = 1;
208 imageInfo.format =
format;
209 imageInfo.tiling = tiling;
210 imageInfo.initialLayout = layout;
211 imageInfo.usage =
usage;
212 imageInfo.samples = numSamples;
213 imageInfo.sharingMode = vk::SharingMode::eExclusive;
214 image = device.createImage(imageInfo);
216 vk::MemoryRequirements memRequirements;
217 memRequirements = device.getImageMemoryRequirements(
image);
219 vk::MemoryAllocateInfo allocInfo{};
220 allocInfo.allocationSize = memRequirements.size;
221 allocInfo.memoryTypeIndex = findMemoryType(memRequirements.memoryTypeBits, properties, physicalDevice);
222 imageMemory = device.allocateMemory(allocInfo,
nullptr);
224 device.bindImageMemory(
image, imageMemory, 0);
227static uint32_t getMaxUsableSampleCount(vk::PhysicalDeviceProperties& physicalDeviceProperties)
229 vk::SampleCountFlags counts = physicalDeviceProperties.limits.framebufferColorSampleCounts & physicalDeviceProperties.limits.framebufferDepthSampleCounts;
230 if (counts & vk::SampleCountFlagBits::e64) {
232 }
else if (counts & vk::SampleCountFlagBits::e32) {
234 }
else if (counts & vk::SampleCountFlagBits::e16) {
236 }
else if (counts & vk::SampleCountFlagBits::e8) {
238 }
else if (counts & vk::SampleCountFlagBits::e4) {
240 }
else if (counts & vk::SampleCountFlagBits::e2) {
246static vk::SampleCountFlagBits getMSAASamplesFlag(uint32_t msaa)
249 return vk::SampleCountFlagBits::e2;
250 }
else if (msaa == 4) {
251 return vk::SampleCountFlagBits::e4;
252 }
else if (msaa == 8) {
253 return vk::SampleCountFlagBits::e8;
254 }
else if (msaa == 16) {
255 return vk::SampleCountFlagBits::e16;
256 }
else if (msaa == 32) {
257 return vk::SampleCountFlagBits::e32;
258 }
else if (msaa == 64) {
259 return vk::SampleCountFlagBits::e64;
261 return vk::SampleCountFlagBits::e1;
264template <
class T,
class S>
265static inline void clearVector(T&
v,
S func,
bool downsize =
true)
267 std::for_each(
v.begin(),
v.end(),
func);
278 vk::PhysicalDeviceProperties deviceProperties = device.getProperties();
279 vk::PhysicalDeviceFeatures deviceFeatures = device.getFeatures();
280 vk::PhysicalDeviceMemoryProperties memoryProperties = device.getMemoryProperties();
281 if (!deviceFeatures.geometryShader || !deviceFeatures.wideLines || !deviceFeatures.largePoints) {
285 std::vector<vk::QueueFamilyProperties> queueFamilies = device.getQueueFamilyProperties();
287 for (uint32_t
i = 0;
i < queueFamilies.size();
i++) {
288 if (!(queueFamilies[
i].queueFlags & vk::QueueFlagBits::eGraphics)) {
291 vk::Bool32 presentSupport = device.getSurfaceSupportKHR(
i,
mSurface);
292 if (!presentSupport) {
300 GPUInfo(
"%s ignored due to missing queue properties", &deviceProperties.deviceName[0]);
304 std::vector<vk::ExtensionProperties> availableExtensions = device.enumerateDeviceExtensionProperties(
nullptr);
305 uint32_t extensionsFound = 0;
306 for (uint32_t
i = 0;
i < reqDeviceExtensions.size();
i++) {
307 for (uint32_t
j = 0;
j < availableExtensions.size();
j++) {
308 if (strcmp(reqDeviceExtensions[
i], availableExtensions[
j].extensionName) == 0) {
314 if (extensionsFound < reqDeviceExtensions.size()) {
315 GPUInfo(
"%s ignored due to missing extensions", &deviceProperties.deviceName[0]);
321 GPUInfo(
"%s ignored due to incompatible swap chain", &deviceProperties.deviceName[0]);
326 if (deviceProperties.deviceType == vk::PhysicalDeviceType::eDiscreteGpu) {
328 }
else if (deviceProperties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu) {
332 for (uint32_t
i = 0;
i < memoryProperties.memoryHeapCount;
i++) {
333 if (memoryProperties.memoryHeaps[
i].flags & vk::MemoryHeapFlagBits::eDeviceLocal) {
334 score += memoryProperties.memoryHeaps[
i].size;
343 VULKAN_HPP_DEFAULT_DISPATCHER.init(vkGetInstanceProcAddr);
344 vk::ApplicationInfo appInfo{};
345 appInfo.pApplicationName =
"GPU CA Standalone display";
346 appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
347 appInfo.pEngineName =
"GPU CI Standalone Engine";
348 appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);
349 appInfo.apiVersion = VK_API_VERSION_1_0;
351 vk::InstanceCreateInfo instanceCreateInfo;
352 instanceCreateInfo.pApplicationInfo = &appInfo;
354 const char** frontendExtensions;
356 std::vector<const char*> reqInstanceExtensions(frontendExtensions, frontendExtensions + frontendExtensionCount);
358 const std::vector<const char*> reqValidationLayers = {
"VK_LAYER_KHRONOS_validation"};
359 auto debugCallback = [](vk::DebugUtilsMessageSeverityFlagBitsEXT messageSeverity, vk::DebugUtilsMessageTypeFlagsEXT messageType,
const vk::DebugUtilsMessengerCallbackDataEXT* pCallbackData,
void* pUserData) -> VkBool32 {
360 static int32_t throwOnError = getenv(
"GPUCA_VULKAN_VALIDATION_THROW") ? atoi(getenv(
"GPUCA_VULKAN_VALIDATION_THROW")) : 0;
361 static bool showVulkanValidationInfo = getenv(
"GPUCA_VULKAN_VALIDATION_INFO") && atoi(getenv(
"GPUCA_VULKAN_VALIDATION_INFO"));
362 switch (messageSeverity) {
363 case vk::DebugUtilsMessageSeverityFlagBitsEXT::eVerbose:
364 if (showVulkanValidationInfo) {
365 GPUInfo(
"%s", pCallbackData->pMessage);
368 case vk::DebugUtilsMessageSeverityFlagBitsEXT::eWarning:
369 GPUWarning(
"%s", pCallbackData->pMessage);
370 if (throwOnError > 1) {
371 throw std::logic_error(
"break_on_validation_warning");
374 case vk::DebugUtilsMessageSeverityFlagBitsEXT::eError:
375 GPUError(
"%s", pCallbackData->pMessage);
377 throw std::logic_error(
"break_on_validation_error");
380 case vk::DebugUtilsMessageSeverityFlagBitsEXT::eInfo:
382 GPUInfo(
"%s", pCallbackData->pMessage);
387 vk::DebugUtilsMessengerCreateInfoEXT debugCreateInfo{};
389 if (checkVulkanLayersSupported(reqValidationLayers)) {
390 throw std::runtime_error(
"Requested validation layer support not available");
392 reqInstanceExtensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
393 instanceCreateInfo.enabledLayerCount =
static_cast<uint32_t
>(reqValidationLayers.size());
394 instanceCreateInfo.ppEnabledLayerNames = reqValidationLayers.data();
395 instanceCreateInfo.pNext = (VkDebugUtilsMessengerCreateInfoEXT*)&debugCreateInfo;
397 debugCreateInfo.messageSeverity = vk::DebugUtilsMessageSeverityFlagBitsEXT::eVerbose | vk::DebugUtilsMessageSeverityFlagBitsEXT::eWarning | vk::DebugUtilsMessageSeverityFlagBitsEXT::eError;
398 debugCreateInfo.messageType = vk::DebugUtilsMessageTypeFlagBitsEXT::eGeneral | vk::DebugUtilsMessageTypeFlagBitsEXT::eValidation | vk::DebugUtilsMessageTypeFlagBitsEXT::ePerformance;
399 debugCreateInfo.pfnUserCallback = debugCallback;
400 debugCreateInfo.pUserData =
nullptr;
402 instanceCreateInfo.enabledLayerCount = 0;
405 instanceCreateInfo.enabledExtensionCount =
static_cast<uint32_t
>(reqInstanceExtensions.size());
406 instanceCreateInfo.ppEnabledExtensionNames = reqInstanceExtensions.data();
408 mInstance = vk::createInstance(instanceCreateInfo,
nullptr);
409 VULKAN_HPP_DEFAULT_DISPATCHER.init(
mInstance);
412 GPUInfo(
"Enabling Vulkan Validation Layers");
415 std::vector<vk::ExtensionProperties> extensions = vk::enumerateInstanceExtensionProperties(
nullptr);
417 std::cout <<
"available instance extensions: " << extensions.size() <<
"\n";
418 for (
const auto& extension : extensions) {
419 std::cout <<
'\t' << extension.extensionName <<
'\n';
424 throw std::runtime_error(
"Frontend does not provide Vulkan surface");
427 const std::vector<const char*> reqDeviceExtensions = {
428 VK_KHR_SWAPCHAIN_EXTENSION_NAME};
431 std::vector<vk::PhysicalDevice> devices =
mInstance.enumeratePhysicalDevices();
432 if (devices.size() == 0) {
433 throw std::runtime_error(
"No Vulkan device present!");
435 double bestScore = -1.;
436 for (uint32_t
i = 0;
i < devices.size();
i++) {
437 double score =
checkDevice(devices[
i], reqDeviceExtensions);
439 vk::PhysicalDeviceProperties deviceProperties = devices[
i].getProperties();
440 GPUInfo(
"Available Vulkan device %d: %s - Score %f",
i, &deviceProperties.deviceName[0], score);
442 if (score > bestScore && score > 0) {
448 if (
mDisplay->
cfg().vulkan.forceDevice < 0 ||
mDisplay->
cfg().vulkan.forceDevice >= (int32_t)devices.size()) {
449 throw std::runtime_error(
"Invalid Vulkan device selected");
454 throw std::runtime_error(
"All available Vulkan devices unsuited");
458 vk::PhysicalDeviceProperties deviceProperties =
mPhysicalDevice.getProperties();
459 vk::PhysicalDeviceFeatures deviceFeatures =
mPhysicalDevice.getFeatures();
460 vk::FormatProperties depth32FormatProperties =
mPhysicalDevice.getFormatProperties(vk::Format::eD32Sfloat);
461 vk::FormatProperties depth64FormatProperties =
mPhysicalDevice.getFormatProperties(vk::Format::eD32SfloatS8Uint);
463 GPUInfo(
"Using physical Vulkan device %s", &deviceProperties.deviceName[0]);
465 mZSupported = (bool)(depth32FormatProperties.optimalTilingFeatures & vk::FormatFeatureFlagBits::eDepthStencilAttachment);
466 mStencilSupported = (bool)(depth64FormatProperties.optimalTilingFeatures & vk::FormatFeatureFlagBits::eDepthStencilAttachment);
467 mCubicFilterSupported = (bool)(formatProperties.optimalTilingFeatures & vk::FormatFeatureFlagBits::eSampledImageFilterCubicEXT);
473 vk::DeviceQueueCreateInfo queueCreateInfo{};
475 queueCreateInfo.queueCount = 1;
476 float queuePriority = 1.0f;
477 queueCreateInfo.pQueuePriorities = &queuePriority;
478 vk::DeviceCreateInfo deviceCreateInfo{};
479 deviceCreateInfo.pQueueCreateInfos = &queueCreateInfo;
480 deviceCreateInfo.queueCreateInfoCount = 1;
481 deviceCreateInfo.pEnabledFeatures = &deviceFeatures;
482 deviceCreateInfo.enabledExtensionCount =
static_cast<uint32_t
>(reqDeviceExtensions.size());
483 deviceCreateInfo.ppEnabledExtensionNames = reqDeviceExtensions.data();
485 VULKAN_HPP_DEFAULT_DISPATCHER.init(
mDevice);
488 vk::CommandPoolCreateInfo poolInfo{};
489 poolInfo.flags = vk::CommandPoolCreateFlagBits::eResetCommandBuffer;
508 vk::CommandBufferAllocateInfo allocInfo{};
510 allocInfo.level = vk::CommandBufferLevel::ePrimary;
533 vk::SemaphoreCreateInfo semaphoreInfo{};
534 vk::FenceCreateInfo fenceInfo{};
535 fenceInfo.flags = vk::FenceCreateFlagBits::eSignaled;
550 fenceInfo.flags = {};
569 for (int32_t
j = 0;
j < 3;
j++) {
578 std::array<vk::DescriptorPoolSize, 2> poolSizes{};
579 poolSizes[0].type = vk::DescriptorType::eUniformBuffer;
581 poolSizes[1].type = vk::DescriptorType::eCombinedImageSampler;
583 vk::DescriptorPoolCreateInfo poolInfo{};
584 poolInfo.poolSizeCount = poolSizes.
size();
585 poolInfo.pPoolSizes = poolSizes.data();
589 vk::DescriptorSetLayoutBinding uboLayoutBindingMat{};
590 uboLayoutBindingMat.binding = 0;
591 uboLayoutBindingMat.descriptorType = vk::DescriptorType::eUniformBuffer;
592 uboLayoutBindingMat.descriptorCount = 1;
593 uboLayoutBindingMat.stageFlags = vk::ShaderStageFlagBits::eVertex;
594 vk::DescriptorSetLayoutBinding uboLayoutBindingCol = uboLayoutBindingMat;
595 uboLayoutBindingCol.binding = 1;
596 uboLayoutBindingCol.stageFlags = vk::ShaderStageFlagBits::eFragment;
597 vk::DescriptorSetLayoutBinding samplerLayoutBinding{};
598 samplerLayoutBinding.binding = 2;
599 samplerLayoutBinding.descriptorCount = 1;
600 samplerLayoutBinding.descriptorType = vk::DescriptorType::eCombinedImageSampler;
601 samplerLayoutBinding.stageFlags = vk::ShaderStageFlagBits::eFragment;
602 vk::DescriptorSetLayoutBinding bindings[3] = {uboLayoutBindingMat, uboLayoutBindingCol, samplerLayoutBinding};
604 vk::DescriptorSetLayoutCreateInfo layoutInfo{};
605 layoutInfo.bindingCount = 2;
606 layoutInfo.pBindings = bindings;
608 layoutInfo.bindingCount = 3;
611 vk::DescriptorSetAllocateInfo allocInfo{};
614 for (int32_t
j = 0;
j < 3;
j++) {
616 allocInfo.pSetLayouts = layouts.data();
619 for (int32_t k = 0; k < 2; k++) {
622 vk::DescriptorBufferInfo bufferInfo{};
623 bufferInfo.buffer = mUniformBuffers[
i].buffer;
624 bufferInfo.offset = 0;
625 bufferInfo.range = mUniformBuffers[
i].size;
627 vk::WriteDescriptorSet descriptorWrite{};
629 descriptorWrite.dstBinding = k;
630 descriptorWrite.dstArrayElement = 0;
631 descriptorWrite.descriptorType = vk::DescriptorType::eUniformBuffer;
632 descriptorWrite.descriptorCount = 1;
633 descriptorWrite.pBufferInfo = &bufferInfo;
634 descriptorWrite.pImageInfo =
nullptr;
635 descriptorWrite.pTexelBufferView =
nullptr;
636 mDevice.updateDescriptorSets(1, &descriptorWrite, 0,
nullptr);
651 for (int32_t
j = 0;
j < 3;
j++) {
659 vk::DescriptorImageInfo imageInfo{};
660 imageInfo.imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
663 vk::WriteDescriptorSet descriptorWrite{};
665 descriptorWrite.dstBinding = 2;
666 descriptorWrite.dstArrayElement = 0;
667 descriptorWrite.descriptorType = vk::DescriptorType::eCombinedImageSampler;
668 descriptorWrite.descriptorCount = 1;
669 descriptorWrite.pImageInfo = &imageInfo;
670 mDevice.updateDescriptorSets(1, &descriptorWrite, 0,
nullptr);
677 vk::SamplerCreateInfo samplerInfo{};
678 samplerInfo.magFilter = vk::Filter::eLinear;
679 samplerInfo.minFilter = vk::Filter::eLinear;
680 samplerInfo.addressModeU = vk::SamplerAddressMode::eRepeat;
681 samplerInfo.addressModeV = vk::SamplerAddressMode::eRepeat;
682 samplerInfo.addressModeW = vk::SamplerAddressMode::eRepeat;
683 samplerInfo.compareEnable =
false;
684 samplerInfo.compareOp = vk::CompareOp::eAlways;
685 samplerInfo.borderColor = vk::BorderColor::eIntOpaqueBlack;
686 samplerInfo.unnormalizedCoordinates =
false;
687 samplerInfo.mipmapMode = vk::SamplerMipmapMode::eLinear;
688 samplerInfo.mipLodBias = 0.0f;
689 samplerInfo.minLod = 0.0f;
690 samplerInfo.maxLod = 0.0f;
722 vk::SwapchainCreateInfoKHR swapCreateInfo{};
724 swapCreateInfo.minImageCount = imageCount;
727 swapCreateInfo.imageExtent = extent;
728 swapCreateInfo.imageArrayLayers = 1;
729 swapCreateInfo.imageUsage = vk::ImageUsageFlagBits::eColorAttachment;
730 swapCreateInfo.imageSharingMode = vk::SharingMode::eExclusive;
731 swapCreateInfo.queueFamilyIndexCount = 0;
732 swapCreateInfo.pQueueFamilyIndices =
nullptr;
734 swapCreateInfo.compositeAlpha = vk::CompositeAlphaFlagBitsKHR::eOpaque;
736 swapCreateInfo.clipped =
true;
737 swapCreateInfo.oldSwapchain = VkSwapchainKHR(VK_NULL_HANDLE);
739 swapCreateInfo.imageUsage |= vk::ImageUsageFlagBits::eTransferSrc;
742 swapCreateInfo.imageUsage |= vk::ImageUsageFlagBits::eTransferDst;
782 if (needUpdateOffscreenBuffers) {
784 if (needUpdateSwapChain) {
802 vk::AttachmentDescription colorAttachment{};
805 colorAttachment.loadOp = vk::AttachmentLoadOp::eClear;
806 colorAttachment.storeOp = vk::AttachmentStoreOp::eStore;
807 colorAttachment.stencilLoadOp = vk::AttachmentLoadOp::eDontCare;
808 colorAttachment.stencilStoreOp = vk::AttachmentStoreOp::eDontCare;
809 colorAttachment.initialLayout = vk::ImageLayout::eUndefined;
810 colorAttachment.finalLayout = (
mMSAASampleCount != vk::SampleCountFlagBits::e1 ||
mDownsampleFSAA) ? vk::ImageLayout::eColorAttachmentOptimal : vk::ImageLayout::ePresentSrcKHR;
811 vk::AttachmentDescription depthAttachment{};
812 depthAttachment.format = vk::Format::eD32Sfloat;
814 depthAttachment.loadOp = vk::AttachmentLoadOp::eClear;
815 depthAttachment.storeOp = vk::AttachmentStoreOp::eDontCare;
816 depthAttachment.stencilLoadOp = vk::AttachmentLoadOp::eDontCare;
817 depthAttachment.stencilStoreOp = vk::AttachmentStoreOp::eDontCare;
818 depthAttachment.initialLayout = vk::ImageLayout::eUndefined;
819 depthAttachment.finalLayout = vk::ImageLayout::eDepthStencilAttachmentOptimal;
820 vk::AttachmentDescription colorAttachmentResolve{};
822 colorAttachmentResolve.samples = vk::SampleCountFlagBits::e1;
823 colorAttachmentResolve.loadOp = vk::AttachmentLoadOp::eDontCare;
824 colorAttachmentResolve.storeOp = vk::AttachmentStoreOp::eStore;
825 colorAttachmentResolve.stencilLoadOp = vk::AttachmentLoadOp::eDontCare;
826 colorAttachmentResolve.stencilStoreOp = vk::AttachmentStoreOp::eDontCare;
827 colorAttachmentResolve.initialLayout = vk::ImageLayout::eUndefined;
828 colorAttachmentResolve.finalLayout =
mDownsampleFSAA ? vk::ImageLayout::eColorAttachmentOptimal : vk::ImageLayout::ePresentSrcKHR;
829 int32_t nAttachments = 0;
830 vk::AttachmentReference colorAttachmentRef{};
831 colorAttachmentRef.attachment = nAttachments++;
832 colorAttachmentRef.layout = vk::ImageLayout::eColorAttachmentOptimal;
833 vk::AttachmentReference depthAttachmentRef{};
835 depthAttachmentRef.layout = vk::ImageLayout::eDepthStencilAttachmentOptimal;
836 vk::AttachmentReference colorAttachmentResolveRef{};
838 colorAttachmentResolveRef.layout = vk::ImageLayout::eColorAttachmentOptimal;
839 vk::SubpassDescription subpass{};
840 subpass.pipelineBindPoint = vk::PipelineBindPoint::eGraphics;
841 subpass.colorAttachmentCount = 1;
842 subpass.pColorAttachments = &colorAttachmentRef;
843 vk::SubpassDependency dependency{};
844 dependency.srcSubpass = VK_SUBPASS_EXTERNAL;
845 dependency.dstSubpass = 0;
846 dependency.srcStageMask = vk::PipelineStageFlagBits::eColorAttachmentOutput | vk::PipelineStageFlagBits::eEarlyFragmentTests;
847 dependency.srcAccessMask = {};
848 dependency.dstStageMask = vk::PipelineStageFlagBits::eColorAttachmentOutput | vk::PipelineStageFlagBits::eEarlyFragmentTests;
849 dependency.dstAccessMask = vk::AccessFlagBits::eColorAttachmentWrite | vk::AccessFlagBits::eDepthStencilAttachmentWrite;
851 std::vector<vk::AttachmentDescription>
attachments = {colorAttachment};
854 depthAttachmentRef.attachment = nAttachments++;
855 subpass.pDepthStencilAttachment = &depthAttachmentRef;
859 colorAttachmentResolveRef.attachment = nAttachments++;
860 subpass.pResolveAttachments = &colorAttachmentResolveRef;
863 vk::RenderPassCreateInfo renderPassInfo{};
864 renderPassInfo.attachmentCount =
attachments.size();
866 renderPassInfo.subpassCount = 1;
867 renderPassInfo.pSubpasses = &subpass;
868 renderPassInfo.dependencyCount = 1;
869 renderPassInfo.pDependencies = &dependency;
882 mZImages.resize(imageCountWithMixImages);
897 renderPassInfo.attachmentCount = 1;
898 renderPassInfo.pAttachments = &colorAttachment;
899 subpass.pDepthStencilAttachment =
nullptr;
900 subpass.pResolveAttachments =
nullptr;
902 dependency.srcStageMask = vk::PipelineStageFlagBits::eColorAttachmentOutput;
903 dependency.dstStageMask = vk::PipelineStageFlagBits::eColorAttachmentOutput;
904 dependency.dstAccessMask = vk::AccessFlagBits::eColorAttachmentWrite;
906 colorAttachment.loadOp = vk::AttachmentLoadOp::eLoad;
907 colorAttachment.initialLayout = vk::ImageLayout::ePresentSrcKHR;
908 colorAttachment.samples = vk::SampleCountFlagBits::e1;
909 colorAttachment.finalLayout = vk::ImageLayout::ePresentSrcKHR;
914 colorAttachment.initialLayout = vk::ImageLayout::eColorAttachmentOptimal;
915 colorAttachment.finalLayout =
mDownsampleFSAA ? vk::ImageLayout::eColorAttachmentOptimal : vk::ImageLayout::ePresentSrcKHR;
918 dependency.srcStageMask = vk::PipelineStageFlagBits::eColorAttachmentOutput;
919 dependency.dstStageMask = vk::PipelineStageFlagBits::eColorAttachmentOutput;
920 dependency.dstAccessMask = vk::AccessFlagBits::eColorAttachmentWrite;
925 for (uint32_t
i = 0;
i < imageCountWithMixImages;
i++) {
932 std::vector<vk::ImageView> att;
934 vk::ImageUsageFlags
usage = vk::ImageUsageFlagBits::eColorAttachment | (
i >=
mImageCount ? vk::ImageUsageFlagBits::eSampled : vk::ImageUsageFlagBits::eTransferSrc);
942 createImageI(
mDevice,
mPhysicalDevice,
mMSAAImages[
i].
image,
mMSAAImages[
i].
memory,
mRenderWidth,
mRenderHeight,
mSurfaceFormat.format, vk::ImageUsageFlagBits::eColorAttachment, vk::MemoryPropertyFlagBits::eDeviceLocal, vk::ImageTiling::eOptimal,
mMSAASampleCount);
949 createImageI(
mDevice,
mPhysicalDevice,
mZImages[
i].
image,
mZImages[
i].
memory,
mRenderWidth,
mRenderHeight, vk::Format::eD32Sfloat, vk::ImageUsageFlagBits::eDepthStencilAttachment, vk::MemoryPropertyFlagBits::eDeviceLocal, vk::ImageTiling::eOptimal,
mMSAASampleCount);
957 vk::FramebufferCreateInfo framebufferInfo{};
959 framebufferInfo.attachmentCount = att.size();
960 framebufferInfo.pAttachments = att.data();
963 framebufferInfo.layers = 1;
967 framebufferInfo.attachmentCount = 1;
976 framebufferInfo.attachmentCount = 1;
986 float vertices[6][4] = {
1026 vk::PipelineShaderStageCreateInfo shaderStages[2] = {vk::PipelineShaderStageCreateInfo{}, vk::PipelineShaderStageCreateInfo{}};
1027 vk::PipelineShaderStageCreateInfo& vertShaderStageInfo = shaderStages[0];
1028 vertShaderStageInfo.stage = vk::ShaderStageFlagBits::eVertex;
1030 vertShaderStageInfo.pName =
"main";
1031 vk::PipelineShaderStageCreateInfo& fragShaderStageInfo = shaderStages[1];
1032 fragShaderStageInfo.stage = vk::ShaderStageFlagBits::eFragment;
1034 fragShaderStageInfo.pName =
"main";
1036 vk::VertexInputBindingDescription bindingDescription{};
1037 bindingDescription.binding = 0;
1039 bindingDescription.inputRate = vk::VertexInputRate::eVertex;
1041 vk::VertexInputAttributeDescription attributeDescriptions{};
1042 attributeDescriptions.binding = 0;
1043 attributeDescriptions.location = 0;
1045 attributeDescriptions.offset = 0;
1047 vk::PipelineVertexInputStateCreateInfo vertexInputInfo{};
1048 vertexInputInfo.vertexBindingDescriptionCount = 1;
1049 vertexInputInfo.pVertexBindingDescriptions = &bindingDescription;
1050 vertexInputInfo.vertexAttributeDescriptionCount = 1;
1051 vertexInputInfo.pVertexAttributeDescriptions = &attributeDescriptions;
1052 vk::PipelineInputAssemblyStateCreateInfo inputAssembly{};
1054 inputAssembly.primitiveRestartEnable =
false;
1056 vk::Viewport viewport{};
1061 viewport.minDepth = 0.0f;
1062 viewport.maxDepth = 1.0f;
1064 vk::Rect2D scissor{};
1065 scissor.offset = vk::Offset2D{0, 0};
1068 vk::PipelineViewportStateCreateInfo viewportState{};
1069 viewportState.viewportCount = 1;
1070 viewportState.pViewports = &viewport;
1071 viewportState.scissorCount = 1;
1072 viewportState.pScissors = &scissor;
1074 vk::PipelineRasterizationStateCreateInfo rasterizer{};
1075 rasterizer.depthClampEnable =
false;
1076 rasterizer.rasterizerDiscardEnable =
false;
1077 rasterizer.polygonMode = vk::PolygonMode::eFill;
1079 rasterizer.cullMode = vk::CullModeFlagBits::eBack;
1080 rasterizer.frontFace = vk::FrontFace::eClockwise;
1081 rasterizer.depthBiasEnable =
false;
1082 rasterizer.depthBiasConstantFactor = 0.0f;
1083 rasterizer.depthBiasClamp = 0.0f;
1084 rasterizer.depthBiasSlopeFactor = 0.0f;
1086 vk::PipelineMultisampleStateCreateInfo multisampling{};
1087 multisampling.sampleShadingEnable =
false;
1089 multisampling.minSampleShading = 1.0f;
1090 multisampling.pSampleMask =
nullptr;
1091 multisampling.alphaToCoverageEnable =
false;
1092 multisampling.alphaToOneEnable =
false;
1094 vk::PipelineColorBlendAttachmentState colorBlendAttachment{};
1095 colorBlendAttachment.colorWriteMask = vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA;
1097 colorBlendAttachment.colorWriteMask = vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA;
1098 colorBlendAttachment.srcColorBlendFactor = vk::BlendFactor::eSrcAlpha;
1099 colorBlendAttachment.dstColorBlendFactor = vk::BlendFactor::eOneMinusSrcAlpha;
1100 colorBlendAttachment.colorBlendOp = vk::BlendOp::eAdd;
1101 colorBlendAttachment.srcAlphaBlendFactor = vk::BlendFactor::eOneMinusSrcAlpha;
1102 colorBlendAttachment.dstAlphaBlendFactor = vk::BlendFactor::eZero;
1103 colorBlendAttachment.alphaBlendOp = vk::BlendOp::eAdd;
1105 vk::PipelineColorBlendStateCreateInfo colorBlending{};
1106 colorBlending.logicOpEnable =
false;
1107 colorBlending.logicOp = vk::LogicOp::eCopy;
1108 colorBlending.attachmentCount = 1;
1109 colorBlending.pAttachments = &colorBlendAttachment;
1110 colorBlending.blendConstants[0] = 0.0f;
1111 colorBlending.blendConstants[1] = 0.0f;
1112 colorBlending.blendConstants[2] = 0.0f;
1113 colorBlending.blendConstants[3] = 0.0f;
1115 vk::PipelineDepthStencilStateCreateInfo depthStencil{};
1116 depthStencil.depthTestEnable =
true;
1117 depthStencil.depthWriteEnable =
true;
1118 depthStencil.depthCompareOp = vk::CompareOp::eLess;
1119 depthStencil.depthBoundsTestEnable =
false;
1120 depthStencil.stencilTestEnable =
false;
1122 vk::DynamicState dynamicStates[] = {vk::DynamicState::eLineWidth};
1123 vk::PipelineDynamicStateCreateInfo dynamicState{};
1124 dynamicState.dynamicStateCount = 1;
1125 dynamicState.pDynamicStates = dynamicStates;
1127 vk::PushConstantRange pushConstantRanges[2] = {vk::PushConstantRange{}, vk::PushConstantRange{}};
1128 pushConstantRanges[0].stageFlags = vk::ShaderStageFlagBits::eFragment;
1129 pushConstantRanges[0].offset = 0;
1130 pushConstantRanges[0].size =
sizeof(float) * 4;
1131 pushConstantRanges[1].stageFlags = vk::ShaderStageFlagBits::eVertex;
1132 pushConstantRanges[1].offset = pushConstantRanges[0].size;
1133 pushConstantRanges[1].size =
sizeof(float);
1134 vk::PipelineLayoutCreateInfo pipelineLayoutInfo{};
1135 pipelineLayoutInfo.setLayoutCount = 1;
1137 pipelineLayoutInfo.pushConstantRangeCount = 2;
1138 pipelineLayoutInfo.pPushConstantRanges = pushConstantRanges;
1140 pipelineLayoutInfo.setLayoutCount = 1;
1144 vk::GraphicsPipelineCreateInfo pipelineInfo{};
1145 pipelineInfo.stageCount = 2;
1146 pipelineInfo.pVertexInputState = &vertexInputInfo;
1147 pipelineInfo.pInputAssemblyState = &inputAssembly;
1148 pipelineInfo.pViewportState = &viewportState;
1149 pipelineInfo.pRasterizationState = &rasterizer;
1150 pipelineInfo.pMultisampleState = &multisampling;
1152 pipelineInfo.pColorBlendState = &colorBlending;
1153 pipelineInfo.pDynamicState = &dynamicState;
1156 pipelineInfo.subpass = 0;
1157 pipelineInfo.pStages = shaderStages;
1158 pipelineInfo.basePipelineHandle = VkPipeline(VK_NULL_HANDLE);
1159 pipelineInfo.basePipelineIndex = -1;
1162 static constexpr vk::PrimitiveTopology
types[3] = {vk::PrimitiveTopology::ePointList, vk::PrimitiveTopology::eLineList, vk::PrimitiveTopology::eLineStrip};
1165 bindingDescription.stride = 4 *
sizeof(float);
1166 attributeDescriptions.format = vk::Format::eR32G32B32A32Sfloat;
1167 inputAssembly.topology = vk::PrimitiveTopology::eTriangleList;
1168 vertShaderStageInfo.module =
mShaders[
"vertexTexture"];
1169 fragShaderStageInfo.module =
mShaders[
"fragmentTexture"];
1172 pipelineInfo.pDepthStencilState =
nullptr;
1173 colorBlendAttachment.blendEnable =
true;
1174 multisampling.rasterizationSamples = vk::SampleCountFlagBits::e1;
1177 }
else if (
i == 3) {
1178 bindingDescription.stride = 4 *
sizeof(float);
1179 attributeDescriptions.format = vk::Format::eR32G32B32A32Sfloat;
1180 inputAssembly.topology = vk::PrimitiveTopology::eTriangleList;
1181 vertShaderStageInfo.module =
mShaders[
"vertexTexture"];
1182 fragShaderStageInfo.module =
mShaders[
"fragmentText"];
1185 pipelineInfo.pDepthStencilState =
nullptr;
1186 colorBlendAttachment.blendEnable =
true;
1187 multisampling.rasterizationSamples = vk::SampleCountFlagBits::e1;
1191 bindingDescription.stride = 3 *
sizeof(float);
1192 attributeDescriptions.format = vk::Format::eR32G32B32Sfloat;
1193 inputAssembly.topology =
types[
i];
1194 vertShaderStageInfo.module =
mShaders[
types[
i] == vk::PrimitiveTopology::ePointList ?
"vertexPoint" :
"vertex"];
1195 fragShaderStageInfo.module =
mShaders[
"fragment"];
1198 pipelineInfo.pDepthStencilState =
mZActive ? &depthStencil :
nullptr;
1199 colorBlendAttachment.blendEnable =
true;
1205 CHKERR(
mDevice.createGraphicsPipelines(VkPipelineCache(VK_NULL_HANDLE), 1, &pipelineInfo,
nullptr, &
mPipelines[
i]));
1211 commandBuffer.reset({});
1213 vk::CommandBufferBeginInfo beginInfo{};
1214 beginInfo.flags = {};
1215 commandBuffer.begin(beginInfo);
1217 vk::ClearValue clearValues[2];
1218 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}};
1219 clearValues[1].depthStencil = vk::ClearDepthStencilValue{{1.0f, 0}};
1221 vk::RenderPassBeginInfo renderPassInfo{};
1224 renderPassInfo.renderArea.offset = vk::Offset2D{0, 0};
1226 renderPassInfo.clearValueCount =
mZActive ? 2 : 1;
1227 renderPassInfo.pClearValues = clearValues;
1228 commandBuffer.beginRenderPass(&renderPassInfo, vk::SubpassContents::eInline);
1230 vk::DeviceSize
offsets[] = {0};
1237 commandBuffer.endRenderPass();
1238 commandBuffer.end();
1250#define LOAD_SHADER(file, ext) \
1251 mShaders[#file] = createShaderModule(_binary_shaders_shaders_##file##_##ext##_spv_start, _binary_shaders_shaders_##file##_##ext##_spv_len, mDevice)
1265 clearVector(
mShaders, [&](
auto&
x) {
mDevice.destroyShaderModule(
x.second,
nullptr); });
1272 if (
buffer.deviceMemory != 1) {
1275 memcpy(dstData, srcData,
size);
1278 auto tmp =
createBuffer(
size, srcData, vk::BufferUsageFlagBits::eTransferSrc, 0);
1281 vk::BufferCopy copyRegion{};
1282 copyRegion.size =
size;
1283 commandBuffer.copyBuffer(tmp.buffer,
buffer.buffer, 1, ©Region);
1292 vk::MemoryPropertyFlags properties;
1294 properties |= vk::MemoryPropertyFlagBits::eDeviceLocal;
1296 if (deviceMemory == 0 || deviceMemory == 2) {
1297 properties |= (vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
1299 if (deviceMemory == 1) {
1300 type |= vk::BufferUsageFlagBits::eTransferDst;
1304 vk::BufferCreateInfo bufferInfo{};
1306 bufferInfo.usage =
type;
1307 bufferInfo.sharingMode = vk::SharingMode::eExclusive;
1310 vk::MemoryRequirements memRequirements;
1311 memRequirements =
mDevice.getBufferMemoryRequirements(
buffer.buffer);
1312 vk::MemoryAllocateInfo allocInfo{};
1313 allocInfo.allocationSize = memRequirements.size;
1314 allocInfo.memoryTypeIndex = findMemoryType(memRequirements.memoryTypeBits, properties,
mPhysicalDevice);
1320 buffer.deviceMemory = deviceMemory;
1322 if (srcData !=
nullptr) {
1357 auto tmp =
createBuffer(srcSize, srcData, vk::BufferUsageFlagBits::eTransferSrc, 0);
1360 cmdImageMemoryBarrier(commandBuffer,
image.image, {}, vk::AccessFlagBits::eTransferWrite, vk::ImageLayout::eUndefined, vk::ImageLayout::eTransferDstOptimal, vk::PipelineStageFlagBits::eTopOfPipe, vk::PipelineStageFlagBits::eTransfer);
1361 vk::BufferImageCopy region{};
1362 region.bufferOffset = 0;
1363 region.bufferRowLength = 0;
1364 region.bufferImageHeight = 0;
1365 region.imageSubresource.aspectMask = vk::ImageAspectFlagBits::eColor;
1366 region.imageSubresource.mipLevel = 0;
1367 region.imageSubresource.baseArrayLayer = 0;
1368 region.imageSubresource.layerCount = 1;
1369 region.imageOffset = vk::Offset3D{0, 0, 0};
1370 region.imageExtent = vk::Extent3D{
image.sizex,
image.sizey, 1};
1371 commandBuffer.copyBufferToImage(tmp.buffer,
image.image, vk::ImageLayout::eTransferDstOptimal, 1, ®ion);
1372 cmdImageMemoryBarrier(commandBuffer,
image.image, vk::AccessFlagBits::eTransferWrite, vk::AccessFlagBits::eShaderRead, vk::ImageLayout::eTransferDstOptimal, vk::ImageLayout::eShaderReadOnlyOptimal, vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eFragmentShader);
1381 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);
1385 image.sizex = sizex;
1386 image.sizey = sizey;
1469 auto first = std::get<0>(
v);
1470 auto count = std::get<1>(
v);
1471 auto iSector = std::get<2>(
v);
1486 for (uint32_t k = 0; k <
count; k++) {
1500 if (includeMixImage == 0.f) {
1503 auto getImage = [&]() {
1504 vk::Fence fen = VkFence(VK_NULL_HANDLE);
1505 vk::Semaphore sem = VkSemaphore(VK_NULL_HANDLE);
1515 vk::Result
retVal = vk::Result::eSuccess;
1518 mustUpdateRendering =
true;
1523 if (!mustUpdateRendering) {
1524 GPUInfo(
"Pipeline out of data / suboptimal, recreating");
1538 const hmm_mat4 modelViewProj = proj * view;
1562 const vk::Fence noFence = VkFence(VK_NULL_HANDLE);
1564 vk::SubmitInfo submitInfo{};
1565 vk::PipelineStageFlags waitStages[] = {vk::PipelineStageFlagBits::eColorAttachmentOutput};
1567 submitInfo.waitSemaphoreCount = submitInfo.pWaitSemaphores !=
nullptr ? 1 : 0;
1568 submitInfo.pWaitDstStageMask = waitStages;
1569 submitInfo.commandBufferCount = 1;
1571 submitInfo.signalSemaphoreCount = 1;
1572 submitInfo.pSignalSemaphores = stageFinishedSemaphore;
1575 if (includeMixImage > 0.f) {
1577 submitInfo.pWaitSemaphores = stageFinishedSemaphore;
1578 waitStages[0] = {vk::PipelineStageFlagBits::eColorAttachmentOutput};
1579 submitInfo.waitSemaphoreCount = 1;
1582 submitInfo.pSignalSemaphores = stageFinishedSemaphore;
1589 submitInfo.pWaitSemaphores = stageFinishedSemaphore;
1590 waitStages[0] = {vk::PipelineStageFlagBits::eTransfer};
1591 submitInfo.waitSemaphoreCount = 1;
1593 submitInfo.pSignalSemaphores = stageFinishedSemaphore;
1607 submitInfo.pWaitSemaphores = stageFinishedSemaphore;
1608 waitStages[0] = {vk::PipelineStageFlagBits::eColorAttachmentOutput};
1609 submitInfo.waitSemaphoreCount = 1;
1612 submitInfo.pSignalSemaphores = stageFinishedSemaphore;
1617 vk::PresentInfoKHR presentInfo{};
1618 presentInfo.waitSemaphoreCount = 1;
1619 presentInfo.pWaitSemaphores = stageFinishedSemaphore;
1620 presentInfo.swapchainCount = 1;
1623 presentInfo.pResults =
nullptr;
1625 if (
retVal == vk::Result::eErrorOutOfDateKHR) {
1635 commandBuffer.reset({});
1636 vk::CommandBufferBeginInfo beginInfo{};
1637 beginInfo.flags = vk::CommandBufferUsageFlagBits::eOneTimeSubmit;
1638 commandBuffer.begin(beginInfo);
1640 cmdImageMemoryBarrier(commandBuffer,
mSwapChainImages[
mCurrentImageIndex], {}, vk::AccessFlagBits::eTransferWrite, vk::ImageLayout::eUndefined, vk::ImageLayout::eTransferDstOptimal, vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eTransfer);
1641 cmdImageMemoryBarrier(commandBuffer,
mDownsampleImages[
mCurrentImageIndex].
image, vk::AccessFlagBits::eMemoryRead, vk::AccessFlagBits::eTransferRead, vk::ImageLayout::eColorAttachmentOptimal, vk::ImageLayout::eTransferSrcOptimal, vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eTransfer);
1643 vk::Offset3D blitSizeSrc;
1647 vk::Offset3D blitSizeDst;
1651 vk::ImageBlit imageBlitRegion{};
1652 imageBlitRegion.srcSubresource.aspectMask = vk::ImageAspectFlagBits::eColor;
1653 imageBlitRegion.srcSubresource.layerCount = 1;
1654 imageBlitRegion.srcOffsets[1] = blitSizeSrc;
1655 imageBlitRegion.dstSubresource.aspectMask = vk::ImageAspectFlagBits::eColor;
1656 imageBlitRegion.dstSubresource.layerCount = 1;
1657 imageBlitRegion.dstOffsets[1] = blitSizeDst;
1660 cmdImageMemoryBarrier(commandBuffer,
mSwapChainImages[
mCurrentImageIndex], vk::AccessFlagBits::eTransferWrite, vk::AccessFlagBits::eMemoryRead, vk::ImageLayout::eTransferDstOptimal, vk::ImageLayout::ePresentSrcKHR, vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eTransfer);
1661 cmdImageMemoryBarrier(commandBuffer,
mDownsampleImages[
mCurrentImageIndex].
image, vk::AccessFlagBits::eTransferRead, vk::AccessFlagBits::eMemoryRead, vk::ImageLayout::eUndefined, vk::ImageLayout::eColorAttachmentOptimal, vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eTransfer);
1663 commandBuffer.end();
1683 vk::CommandBufferBeginInfo beginInfo{};
1684 beginInfo.flags = vk::CommandBufferUsageFlagBits::eOneTimeSubmit;
1687 vk::RenderPassBeginInfo renderPassInfo{};
1690 renderPassInfo.renderArea.offset = vk::Offset2D{0, 0};
1692 renderPassInfo.clearValueCount = 0;
1702 vk::DeviceSize
offsets[] = {0};
1721 commandBuffer.reset({});
1722 vk::CommandBufferBeginInfo beginInfo{};
1723 beginInfo.flags = vk::CommandBufferUsageFlagBits::eOneTimeSubmit;
1724 commandBuffer.begin(beginInfo);
1727 vk::ImageLayout srcLayout =
mDownsampleFSAA ? vk::ImageLayout::eColorAttachmentOptimal : vk::ImageLayout::ePresentSrcKHR;
1728 cmdImageMemoryBarrier(commandBuffer,
image, {}, vk::AccessFlagBits::eMemoryRead, srcLayout, vk::ImageLayout::eShaderReadOnlyOptimal, vk::PipelineStageFlagBits::eAllCommands, vk::PipelineStageFlagBits::eFragmentShader);
1730 vk::RenderPassBeginInfo renderPassInfo{};
1733 renderPassInfo.renderArea.offset = vk::Offset2D{0, 0};
1735 renderPassInfo.clearValueCount = 0;
1736 commandBuffer.beginRenderPass(renderPassInfo, vk::SubpassContents::eInline);
1738 commandBuffer.bindPipeline(vk::PipelineBindPoint::eGraphics,
mPipelines[4]);
1743 vk::DeviceSize
offsets[] = {0};
1746 commandBuffer.pushConstants(
mPipelineLayoutTexture, vk::ShaderStageFlagBits::eFragment, 0,
sizeof(mixSlaveImage), &mixSlaveImage);
1747 commandBuffer.draw(6, 1, 0, 0);
1749 commandBuffer.endRenderPass();
1750 commandBuffer.end();
1786 throw std::runtime_error(
"Incorrect symbol ID");
1790 if (sizex && sizey) {
1791 buffer.reset(
new char[sizex * sizey]);
1798 int32_t maxSizeX = 0, maxSizeY = 0, maxBigX = 0, maxBigY = 0, maxRowY = 0;
1802 maxSizeX = std::max(maxSizeX, symbol.size[0]);
1803 maxSizeY = std::max(maxSizeY, symbol.size[1]);
1806 int32_t sizex = nn * maxSizeX;
1807 int32_t sizey = nn * maxSizeY;
1808 std::unique_ptr<char[]> bigImage{
new char[sizex * sizey]};
1809 memset(bigImage.get(), 0, sizex * sizey);
1810 int32_t rowy = 0, colx = 0;
1813 if (colx + s.size[0] > sizex) {
1818 for (int32_t k = 0; k < s.size[1]; k++) {
1819 for (int32_t
j = 0;
j < s.size[0];
j++) {
1820 int8_t
val = s.data.get()[
j + k * s.size[0]];
1822 val =
val < 0 ? 0xFF : 0;
1824 bigImage.get()[(colx +
j) + (rowy + k) * sizex] =
val;
1829 s.x1 = colx + s.size[0];
1831 s.y1 = rowy + s.size[1];
1832 maxBigX = std::max(maxBigX, colx + s.size[0]);
1833 maxBigY = std::max(maxBigY, rowy + s.size[1]);
1834 maxRowY = std::max(maxRowY, s.size[1]);
1837 if (maxBigX != sizex) {
1838 for (int32_t
y = 1;
y < maxBigY;
y++) {
1839 memmove(bigImage.get() +
y * maxBigX, bigImage.get() +
y * sizex, maxBigX);
1858 vk::DescriptorImageInfo imageInfo{};
1859 imageInfo.imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
1863 vk::WriteDescriptorSet descriptorWrite{};
1865 descriptorWrite.dstBinding = 2;
1866 descriptorWrite.dstArrayElement = 0;
1867 descriptorWrite.descriptorType = vk::DescriptorType::eCombinedImageSampler;
1868 descriptorWrite.descriptorCount = 1;
1869 descriptorWrite.pImageInfo = &imageInfo;
1870 mDevice.updateDescriptorSets(1, &descriptorWrite, 0,
nullptr);
1885 for (
const char*
c = s; *
c;
c++) {
1887 GPUError(
"Trying to draw unsupported symbol: %d > %d\n", (int32_t)*
c, (int32_t)
mFontSymbols.size());
1893 float xpos =
x + sym.
offset[0] * scale;
1894 float ypos =
y - (sym.
size[1] - sym.
offset[1]) * scale;
1895 float w = sym.
size[0] * scale;
1896 float h = sym.
size[1] * scale;
1897 float vertices[6][4] = {
1915 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]) {
1916 c.back().nVertices += nVertices;
1927 static constexpr int32_t bytesPerPixel = 4;
1930 vk::Image dstImage, dstImage2, src2;
1931 vk::DeviceMemory dstImageMemory, dstImageMemory2;
1932 createImageI(
mDevice,
mPhysicalDevice, dstImage, dstImageMemory,
width,
height, vk::Format::eR8G8B8A8Unorm, vk::ImageUsageFlagBits::eTransferDst, vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent, vk::ImageTiling::eLinear);
1934 cmdImageMemoryBarrier(cmdBuffer,
image, vk::AccessFlagBits::eMemoryRead, vk::AccessFlagBits::eTransferRead, layout, vk::ImageLayout::eTransferSrcOptimal, vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eTransfer);
1936 createImageI(
mDevice,
mPhysicalDevice, dstImage2, dstImageMemory2,
width,
height,
mSurfaceFormat.format, vk::ImageUsageFlagBits::eColorAttachment | vk::ImageUsageFlagBits::eTransferSrc | vk::ImageUsageFlagBits::eTransferDst, vk::MemoryPropertyFlagBits::eDeviceLocal, vk::ImageTiling::eOptimal);
1937 cmdImageMemoryBarrier(cmdBuffer, dstImage2, {}, vk::AccessFlagBits::eTransferWrite, vk::ImageLayout::eUndefined, vk::ImageLayout::eTransferDstOptimal, vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eTransfer);
1939 vk::Offset3D blitSizeDst = {(int32_t)
width, (int32_t)
height, 1};
1940 vk::ImageBlit imageBlitRegion{};
1941 imageBlitRegion.srcSubresource.aspectMask = vk::ImageAspectFlagBits::eColor;
1942 imageBlitRegion.srcSubresource.layerCount = 1;
1943 imageBlitRegion.srcOffsets[1] = blitSizeSrc;
1944 imageBlitRegion.dstSubresource.aspectMask = vk::ImageAspectFlagBits::eColor;
1945 imageBlitRegion.dstSubresource.layerCount = 1;
1946 imageBlitRegion.dstOffsets[1] = blitSizeDst;
1947 cmdBuffer.blitImage(
image, vk::ImageLayout::eTransferSrcOptimal, dstImage2, vk::ImageLayout::eTransferDstOptimal, 1, &imageBlitRegion, vk::Filter::eLinear);
1949 cmdImageMemoryBarrier(cmdBuffer, dstImage2, vk::AccessFlagBits::eMemoryRead, vk::AccessFlagBits::eTransferRead, vk::ImageLayout::eTransferDstOptimal, vk::ImageLayout::eTransferSrcOptimal, vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eTransfer);
1954 cmdImageMemoryBarrier(cmdBuffer, dstImage, {}, vk::AccessFlagBits::eTransferWrite, vk::ImageLayout::eUndefined, vk::ImageLayout::eTransferDstOptimal, vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eTransfer);
1955 vk::ImageCopy imageCopyRegion{};
1956 imageCopyRegion.srcSubresource.aspectMask = vk::ImageAspectFlagBits::eColor;
1957 imageCopyRegion.srcSubresource.layerCount = 1;
1958 imageCopyRegion.dstSubresource.aspectMask = vk::ImageAspectFlagBits::eColor;
1959 imageCopyRegion.dstSubresource.layerCount = 1;
1960 imageCopyRegion.extent.width =
width;
1961 imageCopyRegion.extent.height =
height;
1962 imageCopyRegion.extent.depth = 1;
1963 cmdBuffer.copyImage(src2, vk::ImageLayout::eTransferSrcOptimal, dstImage, vk::ImageLayout::eTransferDstOptimal, 1, &imageCopyRegion);
1965 cmdImageMemoryBarrier(cmdBuffer, dstImage, vk::AccessFlagBits::eTransferWrite, vk::AccessFlagBits::eMemoryRead, vk::ImageLayout::eTransferDstOptimal, vk::ImageLayout::eGeneral, vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eTransfer);
1966 cmdImageMemoryBarrier(cmdBuffer,
image, vk::AccessFlagBits::eTransferRead, vk::AccessFlagBits::eMemoryRead, vk::ImageLayout::eTransferSrcOptimal, layout, vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eTransfer);
1969 vk::ImageSubresource subResource{vk::ImageAspectFlagBits::eColor, 0, 0};
1970 vk::SubresourceLayout subResourceLayout =
mDevice.getImageSubresourceLayout(dstImage, subResource);
1973 data += subResourceLayout.offset;
1977 mDevice.unmapMemory(dstImageMemory);
1978 mDevice.freeMemory(dstImageMemory,
nullptr);
1979 mDevice.destroyImage(dstImage,
nullptr);
1981 mDevice.freeMemory(dstImageMemory2,
nullptr);
1982 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()
const GPUSettingsProcessing & GetProcessingSettings() const
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