diff --git a/doc/classes/RenderingDevice.xml b/doc/classes/RenderingDevice.xml index b35eb89d196f..cc79eee894d8 100644 --- a/doc/classes/RenderingDevice.xml +++ b/doc/classes/RenderingDevice.xml @@ -796,12 +796,13 @@ Returns the data format used to create this texture. - + Returns the internal graphics handle for this texture object. For use when communicating with third-party APIs mostly with GDExtension. [b]Note:[/b] This function returns a [code]uint64_t[/code] which internally maps to a [code]GLuint[/code] (OpenGL) or [code]VkImage[/code] (Vulkan). + [i]Deprecated.[/i] Use [method get_driver_resource] with [constant DRIVER_RESOURCE_TEXTURE] instead. @@ -928,44 +929,91 @@ Represents the size of the [enum DeviceType] enum. - - Vulkan device driver resource. This is a "global" resource and ignores the RID passed in + + Specific device object based on a physical device. + - Vulkan: Vulkan device driver resource ([code]VkDevice[/code]). ([code]rid[/code] argument doesn't apply.) - - Physical device (graphics card) driver resource. + + Physical device the specific logical device is based on. + - Vulkan: [code]VkDevice[/code]. ([code]rid[/code] argument doesn't apply.) - - Vulkan instance driver resource. + + Top-most graphics API entry object. + - Vulkan: [code]VkInstance[/code]. ([code]rid[/code] argument doesn't apply.) - - Vulkan queue driver resource. + + The main graphics-compute command queue. + - Vulkan: [code]VkQueue[/code]. ([code]rid[/code] argument doesn't apply.) - - Vulkan queue family index driver resource. + + The specific family the main queue belongs to. + - Vulkan: the queue family index, an [code]uint32_t[/code]. ([code]rid[/code] argument doesn't apply.) - - Vulkan image driver resource. + + - Vulkan: [code]VkImage[/code]. - - Vulkan image view driver resource. + + The view of an owned or shared texture. + - Vulkan: [code]VkImageView[/code]. - - Vulkan image native texture format driver resource. + + The native id of the data format of the texture. + - Vulkan: [code]VkFormat[/code]. - - Vulkan sampler driver resource. + + - Vulkan: [code]VkSampler[/code]. - - Vulkan [url=https://vkguide.dev/docs/chapter-4/descriptors/]descriptor set[/url] driver resource. + + - Vulkan: [code]VkDescriptorSet[/code]. - - Vulkan buffer driver resource. + + Buffer of any kind of (storage, vertex, etc.). + - Vulkan: [code]VkBuffer[/code]. - - Vulkan compute pipeline driver resource. + + - Vulkan: [code]VkPipeline[/code]. - - Vulkan render pipeline driver resource. + + - Vulkan: [code]VkPipeline[/code]. + + + [i]Deprecated.[/i] Use [constant DRIVER_RESOURCE_LOGICAL_DEVICE]. + + + [i]Deprecated.[/i] Use [constant DRIVER_RESOURCE_PHYSICAL_DEVICE]. + + + [i]Deprecated.[/i] Use [constant DRIVER_RESOURCE_TOPMOST_OBJECT]. + + + [i]Deprecated.[/i] Use [constant DRIVER_RESOURCE_COMMAND_QUEUE]. + + + [i]Deprecated.[/i] Use [constant DRIVER_RESOURCE_QUEUE_FAMILY]. + + + [i]Deprecated.[/i] Use [constant DRIVER_RESOURCE_TEXTURE]. + + + [i]Deprecated.[/i] Use [constant DRIVER_RESOURCE_TEXTURE_VIEW]. + + + [i]Deprecated.[/i] Use [constant DRIVER_RESOURCE_TEXTURE_DATA_FORMAT]. + + + [i]Deprecated.[/i] Use [constant DRIVER_RESOURCE_SAMPLER]. + + + [i]Deprecated.[/i] Use [constant DRIVER_RESOURCE_UNIFORM_SET]. + + + [i]Deprecated.[/i] Use [constant DRIVER_RESOURCE_BUFFER]. + + + [i]Deprecated.[/i] Use [constant DRIVER_RESOURCE_COMPUTE_PIPELINE]. + + + [i]Deprecated.[/i] Use [constant DRIVER_RESOURCE_RENDER_PIPELINE]. 4-bit-per-channel red/green channel data format, packed into 8 bits. Values are in the [code][0.0, 1.0][/code] range. diff --git a/drivers/vulkan/SCsub b/drivers/vulkan/SCsub index a076c0ac548c..5e4bc986b80a 100644 --- a/drivers/vulkan/SCsub +++ b/drivers/vulkan/SCsub @@ -2,6 +2,8 @@ Import("env") +env.Append(CPPDEFINES=["RD_ENABLED"]) + thirdparty_obj = [] thirdparty_dir = "#thirdparty/vulkan" thirdparty_volk_dir = "#thirdparty/volk" diff --git a/drivers/vulkan/rendering_device_driver_vulkan.cpp b/drivers/vulkan/rendering_device_driver_vulkan.cpp new file mode 100644 index 000000000000..82c888da8a92 --- /dev/null +++ b/drivers/vulkan/rendering_device_driver_vulkan.cpp @@ -0,0 +1,3240 @@ +/**************************************************************************/ +/* rendering_device_driver_vulkan.cpp */ +/**************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/**************************************************************************/ +/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ +/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/**************************************************************************/ + +#include "rendering_device_driver_vulkan.h" + +#include "core/config/project_settings.h" +#include "core/io/marshalls.h" +#include "thirdparty/misc/smolv.h" +#include "vulkan_context.h" + +/*****************/ +/**** GENERIC ****/ +/*****************/ + +static const VkFormat RD_TO_VK_FORMAT[RDD::DATA_FORMAT_MAX] = { + VK_FORMAT_R4G4_UNORM_PACK8, + VK_FORMAT_R4G4B4A4_UNORM_PACK16, + VK_FORMAT_B4G4R4A4_UNORM_PACK16, + VK_FORMAT_R5G6B5_UNORM_PACK16, + VK_FORMAT_B5G6R5_UNORM_PACK16, + VK_FORMAT_R5G5B5A1_UNORM_PACK16, + VK_FORMAT_B5G5R5A1_UNORM_PACK16, + VK_FORMAT_A1R5G5B5_UNORM_PACK16, + VK_FORMAT_R8_UNORM, + VK_FORMAT_R8_SNORM, + VK_FORMAT_R8_USCALED, + VK_FORMAT_R8_SSCALED, + VK_FORMAT_R8_UINT, + VK_FORMAT_R8_SINT, + VK_FORMAT_R8_SRGB, + VK_FORMAT_R8G8_UNORM, + VK_FORMAT_R8G8_SNORM, + VK_FORMAT_R8G8_USCALED, + VK_FORMAT_R8G8_SSCALED, + VK_FORMAT_R8G8_UINT, + VK_FORMAT_R8G8_SINT, + VK_FORMAT_R8G8_SRGB, + VK_FORMAT_R8G8B8_UNORM, + VK_FORMAT_R8G8B8_SNORM, + VK_FORMAT_R8G8B8_USCALED, + VK_FORMAT_R8G8B8_SSCALED, + VK_FORMAT_R8G8B8_UINT, + VK_FORMAT_R8G8B8_SINT, + VK_FORMAT_R8G8B8_SRGB, + VK_FORMAT_B8G8R8_UNORM, + VK_FORMAT_B8G8R8_SNORM, + VK_FORMAT_B8G8R8_USCALED, + VK_FORMAT_B8G8R8_SSCALED, + VK_FORMAT_B8G8R8_UINT, + VK_FORMAT_B8G8R8_SINT, + VK_FORMAT_B8G8R8_SRGB, + VK_FORMAT_R8G8B8A8_UNORM, + VK_FORMAT_R8G8B8A8_SNORM, + VK_FORMAT_R8G8B8A8_USCALED, + VK_FORMAT_R8G8B8A8_SSCALED, + VK_FORMAT_R8G8B8A8_UINT, + VK_FORMAT_R8G8B8A8_SINT, + VK_FORMAT_R8G8B8A8_SRGB, + VK_FORMAT_B8G8R8A8_UNORM, + VK_FORMAT_B8G8R8A8_SNORM, + VK_FORMAT_B8G8R8A8_USCALED, + VK_FORMAT_B8G8R8A8_SSCALED, + VK_FORMAT_B8G8R8A8_UINT, + VK_FORMAT_B8G8R8A8_SINT, + VK_FORMAT_B8G8R8A8_SRGB, + VK_FORMAT_A8B8G8R8_UNORM_PACK32, + VK_FORMAT_A8B8G8R8_SNORM_PACK32, + VK_FORMAT_A8B8G8R8_USCALED_PACK32, + VK_FORMAT_A8B8G8R8_SSCALED_PACK32, + VK_FORMAT_A8B8G8R8_UINT_PACK32, + VK_FORMAT_A8B8G8R8_SINT_PACK32, + VK_FORMAT_A8B8G8R8_SRGB_PACK32, + VK_FORMAT_A2R10G10B10_UNORM_PACK32, + VK_FORMAT_A2R10G10B10_SNORM_PACK32, + VK_FORMAT_A2R10G10B10_USCALED_PACK32, + VK_FORMAT_A2R10G10B10_SSCALED_PACK32, + VK_FORMAT_A2R10G10B10_UINT_PACK32, + VK_FORMAT_A2R10G10B10_SINT_PACK32, + VK_FORMAT_A2B10G10R10_UNORM_PACK32, + VK_FORMAT_A2B10G10R10_SNORM_PACK32, + VK_FORMAT_A2B10G10R10_USCALED_PACK32, + VK_FORMAT_A2B10G10R10_SSCALED_PACK32, + VK_FORMAT_A2B10G10R10_UINT_PACK32, + VK_FORMAT_A2B10G10R10_SINT_PACK32, + VK_FORMAT_R16_UNORM, + VK_FORMAT_R16_SNORM, + VK_FORMAT_R16_USCALED, + VK_FORMAT_R16_SSCALED, + VK_FORMAT_R16_UINT, + VK_FORMAT_R16_SINT, + VK_FORMAT_R16_SFLOAT, + VK_FORMAT_R16G16_UNORM, + VK_FORMAT_R16G16_SNORM, + VK_FORMAT_R16G16_USCALED, + VK_FORMAT_R16G16_SSCALED, + VK_FORMAT_R16G16_UINT, + VK_FORMAT_R16G16_SINT, + VK_FORMAT_R16G16_SFLOAT, + VK_FORMAT_R16G16B16_UNORM, + VK_FORMAT_R16G16B16_SNORM, + VK_FORMAT_R16G16B16_USCALED, + VK_FORMAT_R16G16B16_SSCALED, + VK_FORMAT_R16G16B16_UINT, + VK_FORMAT_R16G16B16_SINT, + VK_FORMAT_R16G16B16_SFLOAT, + VK_FORMAT_R16G16B16A16_UNORM, + VK_FORMAT_R16G16B16A16_SNORM, + VK_FORMAT_R16G16B16A16_USCALED, + VK_FORMAT_R16G16B16A16_SSCALED, + VK_FORMAT_R16G16B16A16_UINT, + VK_FORMAT_R16G16B16A16_SINT, + VK_FORMAT_R16G16B16A16_SFLOAT, + VK_FORMAT_R32_UINT, + VK_FORMAT_R32_SINT, + VK_FORMAT_R32_SFLOAT, + VK_FORMAT_R32G32_UINT, + VK_FORMAT_R32G32_SINT, + VK_FORMAT_R32G32_SFLOAT, + VK_FORMAT_R32G32B32_UINT, + VK_FORMAT_R32G32B32_SINT, + VK_FORMAT_R32G32B32_SFLOAT, + VK_FORMAT_R32G32B32A32_UINT, + VK_FORMAT_R32G32B32A32_SINT, + VK_FORMAT_R32G32B32A32_SFLOAT, + VK_FORMAT_R64_UINT, + VK_FORMAT_R64_SINT, + VK_FORMAT_R64_SFLOAT, + VK_FORMAT_R64G64_UINT, + VK_FORMAT_R64G64_SINT, + VK_FORMAT_R64G64_SFLOAT, + VK_FORMAT_R64G64B64_UINT, + VK_FORMAT_R64G64B64_SINT, + VK_FORMAT_R64G64B64_SFLOAT, + VK_FORMAT_R64G64B64A64_UINT, + VK_FORMAT_R64G64B64A64_SINT, + VK_FORMAT_R64G64B64A64_SFLOAT, + VK_FORMAT_B10G11R11_UFLOAT_PACK32, + VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, + VK_FORMAT_D16_UNORM, + VK_FORMAT_X8_D24_UNORM_PACK32, + VK_FORMAT_D32_SFLOAT, + VK_FORMAT_S8_UINT, + VK_FORMAT_D16_UNORM_S8_UINT, + VK_FORMAT_D24_UNORM_S8_UINT, + VK_FORMAT_D32_SFLOAT_S8_UINT, + VK_FORMAT_BC1_RGB_UNORM_BLOCK, + VK_FORMAT_BC1_RGB_SRGB_BLOCK, + VK_FORMAT_BC1_RGBA_UNORM_BLOCK, + VK_FORMAT_BC1_RGBA_SRGB_BLOCK, + VK_FORMAT_BC2_UNORM_BLOCK, + VK_FORMAT_BC2_SRGB_BLOCK, + VK_FORMAT_BC3_UNORM_BLOCK, + VK_FORMAT_BC3_SRGB_BLOCK, + VK_FORMAT_BC4_UNORM_BLOCK, + VK_FORMAT_BC4_SNORM_BLOCK, + VK_FORMAT_BC5_UNORM_BLOCK, + VK_FORMAT_BC5_SNORM_BLOCK, + VK_FORMAT_BC6H_UFLOAT_BLOCK, + VK_FORMAT_BC6H_SFLOAT_BLOCK, + VK_FORMAT_BC7_UNORM_BLOCK, + VK_FORMAT_BC7_SRGB_BLOCK, + VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK, + VK_FORMAT_ETC2_R8G8B8_SRGB_BLOCK, + VK_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK, + VK_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK, + VK_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK, + VK_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK, + VK_FORMAT_EAC_R11_UNORM_BLOCK, + VK_FORMAT_EAC_R11_SNORM_BLOCK, + VK_FORMAT_EAC_R11G11_UNORM_BLOCK, + VK_FORMAT_EAC_R11G11_SNORM_BLOCK, + VK_FORMAT_ASTC_4x4_UNORM_BLOCK, + VK_FORMAT_ASTC_4x4_SRGB_BLOCK, + VK_FORMAT_ASTC_5x4_UNORM_BLOCK, + VK_FORMAT_ASTC_5x4_SRGB_BLOCK, + VK_FORMAT_ASTC_5x5_UNORM_BLOCK, + VK_FORMAT_ASTC_5x5_SRGB_BLOCK, + VK_FORMAT_ASTC_6x5_UNORM_BLOCK, + VK_FORMAT_ASTC_6x5_SRGB_BLOCK, + VK_FORMAT_ASTC_6x6_UNORM_BLOCK, + VK_FORMAT_ASTC_6x6_SRGB_BLOCK, + VK_FORMAT_ASTC_8x5_UNORM_BLOCK, + VK_FORMAT_ASTC_8x5_SRGB_BLOCK, + VK_FORMAT_ASTC_8x6_UNORM_BLOCK, + VK_FORMAT_ASTC_8x6_SRGB_BLOCK, + VK_FORMAT_ASTC_8x8_UNORM_BLOCK, + VK_FORMAT_ASTC_8x8_SRGB_BLOCK, + VK_FORMAT_ASTC_10x5_UNORM_BLOCK, + VK_FORMAT_ASTC_10x5_SRGB_BLOCK, + VK_FORMAT_ASTC_10x6_UNORM_BLOCK, + VK_FORMAT_ASTC_10x6_SRGB_BLOCK, + VK_FORMAT_ASTC_10x8_UNORM_BLOCK, + VK_FORMAT_ASTC_10x8_SRGB_BLOCK, + VK_FORMAT_ASTC_10x10_UNORM_BLOCK, + VK_FORMAT_ASTC_10x10_SRGB_BLOCK, + VK_FORMAT_ASTC_12x10_UNORM_BLOCK, + VK_FORMAT_ASTC_12x10_SRGB_BLOCK, + VK_FORMAT_ASTC_12x12_UNORM_BLOCK, + VK_FORMAT_ASTC_12x12_SRGB_BLOCK, + VK_FORMAT_G8B8G8R8_422_UNORM, + VK_FORMAT_B8G8R8G8_422_UNORM, + VK_FORMAT_G8_B8_R8_3PLANE_420_UNORM, + VK_FORMAT_G8_B8R8_2PLANE_420_UNORM, + VK_FORMAT_G8_B8_R8_3PLANE_422_UNORM, + VK_FORMAT_G8_B8R8_2PLANE_422_UNORM, + VK_FORMAT_G8_B8_R8_3PLANE_444_UNORM, + VK_FORMAT_R10X6_UNORM_PACK16, + VK_FORMAT_R10X6G10X6_UNORM_2PACK16, + VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16, + VK_FORMAT_G10X6B10X6G10X6R10X6_422_UNORM_4PACK16, + VK_FORMAT_B10X6G10X6R10X6G10X6_422_UNORM_4PACK16, + VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_420_UNORM_3PACK16, + VK_FORMAT_G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16, + VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_422_UNORM_3PACK16, + VK_FORMAT_G10X6_B10X6R10X6_2PLANE_422_UNORM_3PACK16, + VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_444_UNORM_3PACK16, + VK_FORMAT_R12X4_UNORM_PACK16, + VK_FORMAT_R12X4G12X4_UNORM_2PACK16, + VK_FORMAT_R12X4G12X4B12X4A12X4_UNORM_4PACK16, + VK_FORMAT_G12X4B12X4G12X4R12X4_422_UNORM_4PACK16, + VK_FORMAT_B12X4G12X4R12X4G12X4_422_UNORM_4PACK16, + VK_FORMAT_G12X4_B12X4_R12X4_3PLANE_420_UNORM_3PACK16, + VK_FORMAT_G12X4_B12X4R12X4_2PLANE_420_UNORM_3PACK16, + VK_FORMAT_G12X4_B12X4_R12X4_3PLANE_422_UNORM_3PACK16, + VK_FORMAT_G12X4_B12X4R12X4_2PLANE_422_UNORM_3PACK16, + VK_FORMAT_G12X4_B12X4_R12X4_3PLANE_444_UNORM_3PACK16, + VK_FORMAT_G16B16G16R16_422_UNORM, + VK_FORMAT_B16G16R16G16_422_UNORM, + VK_FORMAT_G16_B16_R16_3PLANE_420_UNORM, + VK_FORMAT_G16_B16R16_2PLANE_420_UNORM, + VK_FORMAT_G16_B16_R16_3PLANE_422_UNORM, + VK_FORMAT_G16_B16R16_2PLANE_422_UNORM, + VK_FORMAT_G16_B16_R16_3PLANE_444_UNORM, +}; + +// RDD::CompareOperator == VkCompareOp. +static_assert(ENUM_MEMBERS_EQUAL(RDD::COMPARE_OP_NEVER, VK_COMPARE_OP_NEVER)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::COMPARE_OP_LESS, VK_COMPARE_OP_LESS)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::COMPARE_OP_EQUAL, VK_COMPARE_OP_EQUAL)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::COMPARE_OP_LESS_OR_EQUAL, VK_COMPARE_OP_LESS_OR_EQUAL)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::COMPARE_OP_GREATER, VK_COMPARE_OP_GREATER)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::COMPARE_OP_NOT_EQUAL, VK_COMPARE_OP_NOT_EQUAL)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::COMPARE_OP_GREATER_OR_EQUAL, VK_COMPARE_OP_GREATER_OR_EQUAL)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::COMPARE_OP_ALWAYS, VK_COMPARE_OP_ALWAYS)); + +static_assert(ARRAYS_COMPATIBLE_FIELDWISE(Rect2i, VkRect2D)); + +/****************/ +/**** MEMORY ****/ +/****************/ + +static const uint32_t SMALL_ALLOCATION_MAX_SIZE = 4096; + +VmaPool RenderingDeviceDriverVulkan::_find_or_create_small_allocs_pool(uint32_t p_mem_type_index) { + if (small_allocs_pools.has(p_mem_type_index)) { + return small_allocs_pools[p_mem_type_index]; + } + + print_verbose("Creating VMA small objects pool for memory type index " + itos(p_mem_type_index)); + + VmaPoolCreateInfo pci = {}; + pci.memoryTypeIndex = p_mem_type_index; + pci.flags = 0; + pci.blockSize = 0; + pci.minBlockCount = 0; + pci.maxBlockCount = SIZE_MAX; + pci.priority = 0.5f; + pci.minAllocationAlignment = 0; + pci.pMemoryAllocateNext = nullptr; + VmaPool pool = VK_NULL_HANDLE; + VkResult res = vmaCreatePool(allocator, &pci, &pool); + small_allocs_pools[p_mem_type_index] = pool; // Don't try to create it again if failed the first time. + ERR_FAIL_COND_V_MSG(res, pool, "vmaCreatePool failed with error " + itos(res) + "."); + + return pool; +} + +/*****************/ +/**** BUFFERS ****/ +/*****************/ + +// RDD::BufferUsageBits == VkBufferUsageFlagBits. +static_assert(ENUM_MEMBERS_EQUAL(RDD::BUFFER_USAGE_TRANSFER_FROM_BIT, VK_BUFFER_USAGE_TRANSFER_SRC_BIT)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::BUFFER_USAGE_TRANSFER_TO_BIT, VK_BUFFER_USAGE_TRANSFER_DST_BIT)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::BUFFER_USAGE_TEXEL_BIT, VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::BUFFER_USAGE_UNIFORM_BIT, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::BUFFER_USAGE_STORAGE_BIT, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::BUFFER_USAGE_INDEX_BIT, VK_BUFFER_USAGE_INDEX_BUFFER_BIT)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::BUFFER_USAGE_VERTEX_BIT, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::BUFFER_USAGE_INDIRECT_BIT, VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT)); + +RDD::BufferID RenderingDeviceDriverVulkan::buffer_create(uint64_t p_size, BitField p_usage, MemoryAllocationType p_allocation_type) { + VkBufferCreateInfo create_info = {}; + create_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; + create_info.size = p_size; + create_info.usage = p_usage; + create_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; + + VmaAllocationCreateInfo alloc_create_info = {}; + switch (p_allocation_type) { + case MEMORY_ALLOCATION_TYPE_CPU: { + bool is_src = p_usage.has_flag(BUFFER_USAGE_TRANSFER_FROM_BIT); + bool is_dst = p_usage.has_flag(BUFFER_USAGE_TRANSFER_TO_BIT); + if (is_src && !is_dst) { + // Looks like a staging buffer: CPU maps, writes sequentially, then GPU copies to VRAM. + alloc_create_info.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT; + } + if (is_dst && !is_src) { + // Looks like a readback buffer: GPU copies from VRAM, then CPU maps and reads. + alloc_create_info.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT; + } + alloc_create_info.usage = VMA_MEMORY_USAGE_AUTO_PREFER_HOST; + } break; + case MEMORY_ALLOCATION_TYPE_GPU: { + alloc_create_info.usage = VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE; + if (p_size <= SMALL_ALLOCATION_MAX_SIZE) { + uint32_t mem_type_index = 0; + vmaFindMemoryTypeIndexForBufferInfo(allocator, &create_info, &alloc_create_info, &mem_type_index); + alloc_create_info.pool = _find_or_create_small_allocs_pool(mem_type_index); + } + } break; + } + + VkBuffer vk_buffer = VK_NULL_HANDLE; + VmaAllocation allocation = nullptr; + VmaAllocationInfo alloc_info = {}; + VkResult err = vmaCreateBuffer(allocator, &create_info, &alloc_create_info, &vk_buffer, &allocation, &alloc_info); + ERR_FAIL_COND_V_MSG(err, BufferID(), "Can't create buffer of size: " + itos(p_size) + ", error " + itos(err) + "."); + + // Bookkeep. + + BufferInfo bi; + bi.allocation.handle = allocation; + bi.allocation.size = alloc_info.size; + bi.size = p_size; + + buffers.insert(vk_buffer, bi); + + return BufferID(vk_buffer); +} + +bool RenderingDeviceDriverVulkan::buffer_set_texel_format(BufferID p_buffer, DataFormat p_format) { + VkBuffer vk_buffer = (VkBuffer)p_buffer.id; + BufferInfo &bi = buffers.get(vk_buffer); + + DEV_ASSERT(!bi.vk_view); + + VkBufferViewCreateInfo view_create_info = {}; + view_create_info.sType = VK_STRUCTURE_TYPE_BUFFER_VIEW_CREATE_INFO; + view_create_info.buffer = vk_buffer; + view_create_info.format = RD_TO_VK_FORMAT[p_format]; + view_create_info.range = bi.allocation.size; + + VkResult res = vkCreateBufferView(vk_device, &view_create_info, nullptr, &bi.vk_view); + ERR_FAIL_COND_V_MSG(res, false, "Unable to create buffer view, error " + itos(res) + "."); + + return true; +} + +void RenderingDeviceDriverVulkan::buffer_free(BufferID p_buffer) { + VkBuffer vk_buffer = (VkBuffer)p_buffer.id; + BufferInfo &bi = buffers.get(vk_buffer); + if (bi.vk_view) { + vkDestroyBufferView(vk_device, bi.vk_view, nullptr); + } + vmaDestroyBuffer(allocator, (VkBuffer)p_buffer.id, bi.allocation.handle); + buffers.erase(vk_buffer); +} + +uint64_t RenderingDeviceDriverVulkan::buffer_get_allocation_size(BufferID p_buffer) { + VkBuffer vk_buffer = (VkBuffer)p_buffer.id; + BufferInfo &bi = buffers.get(vk_buffer); + return bi.allocation.size; +} + +uint8_t *RenderingDeviceDriverVulkan::buffer_map(BufferID p_buffer) { + VkBuffer vk_buffer = (VkBuffer)p_buffer.id; + BufferInfo &bi = buffers.get(vk_buffer); + void *data_ptr = nullptr; + VkResult err = vmaMapMemory(allocator, bi.allocation.handle, &data_ptr); + ERR_FAIL_COND_V_MSG(err, nullptr, "vmaMapMemory failed with error " + itos(err) + "."); + return (uint8_t *)data_ptr; +} + +void RenderingDeviceDriverVulkan::buffer_unmap(BufferID p_buffer) { + VkBuffer vk_buffer = (VkBuffer)p_buffer.id; + BufferInfo &bi = buffers.get(vk_buffer); + vmaUnmapMemory(allocator, bi.allocation.handle); +} + +/**********************/ +/**** VERTEX ARRAY ****/ +/**********************/ + +RDD::VertexFormatID RenderingDeviceDriverVulkan::vertex_format_create(VectorView p_vertex_attribs) { + // Pre-bookkeep. + RBSet::Element *E = vertex_formats.insert(VertexFormatInfo()); + + VertexFormatInfo &vfi = E->get(); + + vfi.vk_bindings.resize(p_vertex_attribs.size()); + vfi.vk_attributes.resize(p_vertex_attribs.size()); + for (uint32_t i = 0; i < p_vertex_attribs.size(); i++) { + vfi.vk_bindings[i] = {}; + vfi.vk_bindings[i].binding = i; + vfi.vk_bindings[i].stride = p_vertex_attribs[i].stride; + vfi.vk_bindings[i].inputRate = p_vertex_attribs[i].frequency == VERTEX_FREQUENCY_INSTANCE ? VK_VERTEX_INPUT_RATE_INSTANCE : VK_VERTEX_INPUT_RATE_VERTEX; + vfi.vk_attributes[i] = {}; + vfi.vk_attributes[i].binding = i; + vfi.vk_attributes[i].location = p_vertex_attribs[i].location; + vfi.vk_attributes[i].format = RD_TO_VK_FORMAT[p_vertex_attribs[i].format]; + vfi.vk_attributes[i].offset = p_vertex_attribs[i].offset; + } + + vfi.vk_create_info = {}; + vfi.vk_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; + vfi.vk_create_info.vertexBindingDescriptionCount = vfi.vk_bindings.size(); + vfi.vk_create_info.pVertexBindingDescriptions = vfi.vk_bindings.ptr(); + vfi.vk_create_info.vertexAttributeDescriptionCount = vfi.vk_attributes.size(); + vfi.vk_create_info.pVertexAttributeDescriptions = vfi.vk_attributes.ptr(); + + return VertexFormatID(E); +} + +void RenderingDeviceDriverVulkan::vertex_format_free(VertexFormatID p_vertex_format) { + auto *E = (RBSet::Element *)p_vertex_format.id; + vertex_formats.erase(E); +} + +/*****************/ +/**** TEXTURE ****/ +/*****************/ + +static const VkImageType RD_TEX_TYPE_TO_VK_IMG_TYPE[RDD::TEXTURE_TYPE_MAX] = { + VK_IMAGE_TYPE_1D, + VK_IMAGE_TYPE_2D, + VK_IMAGE_TYPE_3D, + VK_IMAGE_TYPE_2D, + VK_IMAGE_TYPE_1D, + VK_IMAGE_TYPE_2D, + VK_IMAGE_TYPE_2D, +}; + +static const VkSampleCountFlagBits RD_TO_VK_SAMPLE_COUNT[RDD::TEXTURE_SAMPLES_MAX] = { + VK_SAMPLE_COUNT_1_BIT, + VK_SAMPLE_COUNT_2_BIT, + VK_SAMPLE_COUNT_4_BIT, + VK_SAMPLE_COUNT_8_BIT, + VK_SAMPLE_COUNT_16_BIT, + VK_SAMPLE_COUNT_32_BIT, + VK_SAMPLE_COUNT_64_BIT, +}; + +// RDD::TextureType == VkImageViewType. +static_assert(ENUM_MEMBERS_EQUAL(RDD::TEXTURE_TYPE_1D, VK_IMAGE_VIEW_TYPE_1D)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::TEXTURE_TYPE_2D, VK_IMAGE_VIEW_TYPE_2D)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::TEXTURE_TYPE_3D, VK_IMAGE_VIEW_TYPE_3D)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::TEXTURE_TYPE_CUBE, VK_IMAGE_VIEW_TYPE_CUBE)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::TEXTURE_TYPE_1D_ARRAY, VK_IMAGE_VIEW_TYPE_1D_ARRAY)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::TEXTURE_TYPE_2D_ARRAY, VK_IMAGE_VIEW_TYPE_2D_ARRAY)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::TEXTURE_TYPE_CUBE_ARRAY, VK_IMAGE_VIEW_TYPE_CUBE_ARRAY)); + +// RDD::TextureSwizzle == VkComponentSwizzle. +static_assert(ENUM_MEMBERS_EQUAL(RDD::TEXTURE_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::TEXTURE_SWIZZLE_ZERO, VK_COMPONENT_SWIZZLE_ZERO)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::TEXTURE_SWIZZLE_ONE, VK_COMPONENT_SWIZZLE_ONE)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::TEXTURE_SWIZZLE_R, VK_COMPONENT_SWIZZLE_R)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::TEXTURE_SWIZZLE_G, VK_COMPONENT_SWIZZLE_G)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::TEXTURE_SWIZZLE_B, VK_COMPONENT_SWIZZLE_B)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::TEXTURE_SWIZZLE_A, VK_COMPONENT_SWIZZLE_A)); + +// RDD::TextureLayout == VkImageLayout. +static_assert(ENUM_MEMBERS_EQUAL(RDD::TEXTURE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_UNDEFINED)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::TEXTURE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_GENERAL)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::TEXTURE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::TEXTURE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::TEXTURE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL, VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::TEXTURE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::TEXTURE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::TEXTURE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::TEXTURE_LAYOUT_PREINITIALIZED, VK_IMAGE_LAYOUT_PREINITIALIZED)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::TEXTURE_LAYOUT_VRS_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_FRAGMENT_SHADING_RATE_ATTACHMENT_OPTIMAL_KHR)); + +// RDD::TextureAspectBits == VkImageAspectFlagBits. +static_assert(ENUM_MEMBERS_EQUAL(RDD::TEXTURE_ASPECT_COLOR_BIT, VK_IMAGE_ASPECT_COLOR_BIT)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::TEXTURE_ASPECT_DEPTH_BIT, VK_IMAGE_ASPECT_DEPTH_BIT)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::TEXTURE_ASPECT_STENCIL_BIT, VK_IMAGE_ASPECT_STENCIL_BIT)); + +VkSampleCountFlagBits RenderingDeviceDriverVulkan::_ensure_supported_sample_count(TextureSamples p_requested_sample_count) { + VkSampleCountFlags sample_count_flags = (context->get_device_limits().framebufferColorSampleCounts & limits.framebufferDepthSampleCounts); + + if ((sample_count_flags & RD_TO_VK_SAMPLE_COUNT[p_requested_sample_count])) { + // The requested sample count is supported. + return RD_TO_VK_SAMPLE_COUNT[p_requested_sample_count]; + } else { + // Find the closest lower supported sample count. + VkSampleCountFlagBits sample_count = RD_TO_VK_SAMPLE_COUNT[p_requested_sample_count]; + while (sample_count > VK_SAMPLE_COUNT_1_BIT) { + if (sample_count_flags & sample_count) { + return sample_count; + } + sample_count = (VkSampleCountFlagBits)(sample_count >> 1); + } + } + return VK_SAMPLE_COUNT_1_BIT; +} + +RDD::TextureID RenderingDeviceDriverVulkan::texture_create(const TextureFormat &p_format, const TextureView &p_view) { + VkImageCreateInfo create_info = {}; + create_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; + + if (p_format.shareable_formats.size()) { + create_info.flags |= VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT; + + if (context->is_device_extension_enabled(VK_KHR_IMAGE_FORMAT_LIST_EXTENSION_NAME)) { + VkFormat *vk_allowed_formats = ALLOCA_ARRAY(VkFormat, p_format.shareable_formats.size()); + for (int i = 0; i < p_format.shareable_formats.size(); i++) { + vk_allowed_formats[i] = RD_TO_VK_FORMAT[p_format.shareable_formats[i]]; + } + + VkImageFormatListCreateInfoKHR *format_list_create_info = ALLOCA_SINGLE(VkImageFormatListCreateInfoKHR); + *format_list_create_info = {}; + format_list_create_info->sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_LIST_CREATE_INFO_KHR; + format_list_create_info->viewFormatCount = p_format.shareable_formats.size(); + format_list_create_info->pViewFormats = vk_allowed_formats; + + create_info.pNext = format_list_create_info; + } + } + + if (p_format.texture_type == TEXTURE_TYPE_CUBE || p_format.texture_type == TEXTURE_TYPE_CUBE_ARRAY) { + create_info.flags |= VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT; + } + /*if (p_format.texture_type == TEXTURE_TYPE_2D || p_format.texture_type == TEXTURE_TYPE_2D_ARRAY) { + create_info.flags |= VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT; + }*/ + + create_info.imageType = RD_TEX_TYPE_TO_VK_IMG_TYPE[p_format.texture_type]; + + create_info.format = RD_TO_VK_FORMAT[p_format.format]; + + create_info.extent.width = p_format.width; + create_info.extent.height = p_format.height; + create_info.extent.depth = p_format.depth; + + create_info.mipLevels = p_format.mipmaps; + create_info.arrayLayers = p_format.array_layers; + + create_info.samples = _ensure_supported_sample_count(p_format.samples); + create_info.tiling = (p_format.usage_bits & TEXTURE_USAGE_CPU_READ_BIT) ? VK_IMAGE_TILING_LINEAR : VK_IMAGE_TILING_OPTIMAL; + + // Usage. + if ((p_format.usage_bits & TEXTURE_USAGE_SAMPLING_BIT)) { + create_info.usage |= VK_IMAGE_USAGE_SAMPLED_BIT; + } + if ((p_format.usage_bits & TEXTURE_USAGE_STORAGE_BIT)) { + create_info.usage |= VK_IMAGE_USAGE_STORAGE_BIT; + } + if ((p_format.usage_bits & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT)) { + create_info.usage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; + } + if ((p_format.usage_bits & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) { + create_info.usage |= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT; + } + if ((p_format.usage_bits & TEXTURE_USAGE_INPUT_ATTACHMENT_BIT)) { + create_info.usage |= VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT; + } + if ((p_format.usage_bits & TEXTURE_USAGE_VRS_ATTACHMENT_BIT)) { + create_info.usage |= VK_IMAGE_USAGE_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR; + } + if ((p_format.usage_bits & TEXTURE_USAGE_CAN_UPDATE_BIT)) { + create_info.usage |= VK_IMAGE_USAGE_TRANSFER_DST_BIT; + } + if ((p_format.usage_bits & TEXTURE_USAGE_CAN_COPY_FROM_BIT)) { + create_info.usage |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT; + } + if ((p_format.usage_bits & TEXTURE_USAGE_CAN_COPY_TO_BIT)) { + create_info.usage |= VK_IMAGE_USAGE_TRANSFER_DST_BIT; + } + + create_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; + create_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; + + // Allocate memory. + + uint32_t width = 0, height = 0; + uint32_t image_size = get_image_format_required_size(p_format.format, p_format.width, p_format.height, p_format.depth, p_format.mipmaps, &width, &height); + + VmaAllocationCreateInfo alloc_create_info = {}; + alloc_create_info.flags = (p_format.usage_bits & TEXTURE_USAGE_CPU_READ_BIT) ? VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT : 0; + alloc_create_info.usage = VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE; + if (image_size <= SMALL_ALLOCATION_MAX_SIZE) { + uint32_t mem_type_index = 0; + vmaFindMemoryTypeIndexForImageInfo(allocator, &create_info, &alloc_create_info, &mem_type_index); + alloc_create_info.pool = _find_or_create_small_allocs_pool(mem_type_index); + } + + // Create. + + VkImage vk_image = VK_NULL_HANDLE; + VmaAllocation allocation = nullptr; + VmaAllocationInfo alloc_info = {}; + VkResult err = vmaCreateImage(allocator, &create_info, &alloc_create_info, &vk_image, &allocation, &alloc_info); + ERR_FAIL_COND_V_MSG(err, TextureID(), "vmaCreateImage failed with error " + itos(err) + "."); + + // Create view. + + VkImageViewCreateInfo image_view_create_info = {}; + image_view_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; + image_view_create_info.image = vk_image; + image_view_create_info.viewType = (VkImageViewType)p_format.texture_type; + image_view_create_info.format = RD_TO_VK_FORMAT[p_view.format]; + image_view_create_info.components.r = (VkComponentSwizzle)p_view.swizzle_r; + image_view_create_info.components.g = (VkComponentSwizzle)p_view.swizzle_g; + image_view_create_info.components.b = (VkComponentSwizzle)p_view.swizzle_b; + image_view_create_info.components.a = (VkComponentSwizzle)p_view.swizzle_a; + image_view_create_info.subresourceRange.levelCount = create_info.mipLevels; + image_view_create_info.subresourceRange.layerCount = create_info.arrayLayers; + if ((p_format.usage_bits & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) { + image_view_create_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT; + } else { + image_view_create_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + } + + VkImageView vk_image_view = VK_NULL_HANDLE; + err = vkCreateImageView(vk_device, &image_view_create_info, nullptr, &vk_image_view); + if (err) { + vmaDestroyImage(allocator, vk_image, allocation); + ERR_FAIL_COND_V_MSG(err, TextureID(), "vkCreateImageView failed with error " + itos(err) + "."); + } + + // Bookkeep. + + TextureInfo ti; + ti.vk_image = vk_image; + ti.owner_info.allocation.handle = allocation; + ti.owner_info.allocation.size = alloc_info.size; + ti.owner_info.vk_create_info.format = image_view_create_info.format; + ti.owner_info.vk_create_info.level_count = create_info.mipLevels; + ti.owner_info.vk_create_info.layer_count = create_info.arrayLayers; + ti.owner_info.vk_create_info.usage_flags = create_info.usage; + ti.owner_info.vk_create_info.view_type = image_view_create_info.viewType; + ti.owner_info.vk_create_info.aspect_mask = image_view_create_info.subresourceRange.aspectMask; + + textures.insert(vk_image_view, ti); + + return TextureID(vk_image_view); +} + +RDD::TextureID RenderingDeviceDriverVulkan::texture_create_from_extension(uint64_t p_native_texture, TextureType p_type, DataFormat p_format, uint32_t p_array_layers, bool p_depth_stencil) { + VkImage vk_image = (VkImage)p_native_texture; + + // We only need to create a view into the already existing natively-provided texture. + + VkImageViewCreateInfo image_view_create_info = {}; + image_view_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; + image_view_create_info.image = vk_image; + image_view_create_info.viewType = (VkImageViewType)p_type; + image_view_create_info.format = RD_TO_VK_FORMAT[p_format]; + image_view_create_info.components.r = VK_COMPONENT_SWIZZLE_R; + image_view_create_info.components.g = VK_COMPONENT_SWIZZLE_G; + image_view_create_info.components.b = VK_COMPONENT_SWIZZLE_B; + image_view_create_info.components.a = VK_COMPONENT_SWIZZLE_A; + image_view_create_info.subresourceRange.levelCount = 1; + image_view_create_info.subresourceRange.layerCount = p_array_layers; + image_view_create_info.subresourceRange.aspectMask = p_depth_stencil ? VK_IMAGE_ASPECT_DEPTH_BIT : VK_IMAGE_ASPECT_COLOR_BIT; + + VkImageView vk_image_view = VK_NULL_HANDLE; + VkResult err = vkCreateImageView(vk_device, &image_view_create_info, nullptr, &vk_image_view); + if (err) { + ERR_FAIL_COND_V_MSG(err, TextureID(), "vkCreateImageView failed with error " + itos(err) + "."); + } + + // Bookkeep. + + TextureInfo ti; + ti.vk_image = vk_image; + + textures.insert(vk_image_view, ti); + + return TextureID(vk_image); +} + +RDD::TextureID RenderingDeviceDriverVulkan::texture_create_shared(TextureID p_original_texture, const TextureView &p_view) { + VkImageView vk_image_view = (VkImageView)p_original_texture.id; + const TextureInfo &owner_ti = textures.get(vk_image_view); +#ifdef DEBUG_ENABLED + ERR_FAIL_COND_V(!owner_ti.owner_info.allocation.handle, TextureID()); +#endif + + VkImageViewCreateInfo image_view_create_info = {}; + image_view_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; + image_view_create_info.image = owner_ti.vk_image; + image_view_create_info.viewType = owner_ti.owner_info.vk_create_info.view_type; + image_view_create_info.format = RD_TO_VK_FORMAT[p_view.format]; + image_view_create_info.components.r = (VkComponentSwizzle)p_view.swizzle_r; + image_view_create_info.components.g = (VkComponentSwizzle)p_view.swizzle_g; + image_view_create_info.components.b = (VkComponentSwizzle)p_view.swizzle_b; + image_view_create_info.components.a = (VkComponentSwizzle)p_view.swizzle_a; + image_view_create_info.subresourceRange.levelCount = owner_ti.owner_info.vk_create_info.level_count; + image_view_create_info.subresourceRange.layerCount = owner_ti.owner_info.vk_create_info.layer_count; + image_view_create_info.subresourceRange.aspectMask = owner_ti.owner_info.vk_create_info.aspect_mask; + + if (context->is_device_extension_enabled(VK_KHR_MAINTENANCE_2_EXTENSION_NAME)) { + // May need to make VK_KHR_maintenance2 manditory and thus has Vulkan 1.1 be our minimum supported version + // if we require setting this information. Vulkan 1.0 may simply not care. + if (image_view_create_info.format != owner_ti.owner_info.vk_create_info.format) { + VkImageViewUsageCreateInfo *usage_info = ALLOCA_SINGLE(VkImageViewUsageCreateInfo); + *usage_info = {}; + usage_info->sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO; + usage_info->usage = owner_ti.owner_info.vk_create_info.usage_flags; + + // Certain features may not be available for the format of the view. + { + VkFormatProperties properties = {}; + vkGetPhysicalDeviceFormatProperties(context->get_physical_device(), RD_TO_VK_FORMAT[p_view.format], &properties); + VkMemoryPropertyFlags vk_mem_flags = 0; + vmaGetAllocationMemoryProperties(allocator, owner_ti.owner_info.allocation.handle, &vk_mem_flags); + const VkFormatFeatureFlags &supported_flags = (vk_mem_flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) ? properties.linearTilingFeatures : properties.optimalTilingFeatures; + if ((usage_info->usage & VK_IMAGE_USAGE_STORAGE_BIT) && !(supported_flags & VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT)) { + usage_info->usage &= ~VK_IMAGE_USAGE_STORAGE_BIT; + } + if ((usage_info->usage & VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) && !(supported_flags & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT)) { + usage_info->usage &= ~VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; + } + } + + image_view_create_info.pNext = usage_info; + } + } + + VkImageView new_vk_image_view = VK_NULL_HANDLE; + VkResult err = vkCreateImageView(vk_device, &image_view_create_info, nullptr, &new_vk_image_view); + ERR_FAIL_COND_V_MSG(err, TextureID(), "vkCreateImageView failed with error " + itos(err) + "."); + + // Bookkeep. + + TextureInfo ti; + ti.vk_image = owner_ti.vk_image; + + textures.insert(new_vk_image_view, ti); + + return TextureID(new_vk_image_view); +} + +RDD::TextureID RenderingDeviceDriverVulkan::texture_create_shared_from_slice(TextureID p_original_texture, const TextureView &p_view, TextureSliceType p_slice_type, uint32_t p_layer, uint32_t p_layers, uint32_t p_mipmap, uint32_t p_mipmaps) { + VkImageView vk_image_view = (VkImageView)p_original_texture.id; + const TextureInfo &owner_ti = textures.get(vk_image_view); +#ifdef DEBUG_ENABLED + ERR_FAIL_COND_V(!owner_ti.owner_info.allocation.handle, TextureID()); +#endif + + VkImageViewCreateInfo image_view_create_info = {}; + image_view_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; + image_view_create_info.image = owner_ti.vk_image; + switch (p_slice_type) { + case TEXTURE_SLICE_2D: { + image_view_create_info.viewType = VK_IMAGE_VIEW_TYPE_2D; + } break; + case TEXTURE_SLICE_3D: { + image_view_create_info.viewType = VK_IMAGE_VIEW_TYPE_3D; + } break; + case TEXTURE_SLICE_CUBEMAP: { + image_view_create_info.viewType = VK_IMAGE_VIEW_TYPE_CUBE; + } break; + case TEXTURE_SLICE_2D_ARRAY: { + image_view_create_info.viewType = VK_IMAGE_VIEW_TYPE_2D_ARRAY; + } break; + } + image_view_create_info.format = RD_TO_VK_FORMAT[p_view.format]; + image_view_create_info.components.r = (VkComponentSwizzle)p_view.swizzle_r; + image_view_create_info.components.g = (VkComponentSwizzle)p_view.swizzle_g; + image_view_create_info.components.b = (VkComponentSwizzle)p_view.swizzle_b; + image_view_create_info.components.a = (VkComponentSwizzle)p_view.swizzle_a; + image_view_create_info.subresourceRange.aspectMask = owner_ti.owner_info.vk_create_info.aspect_mask; + image_view_create_info.subresourceRange.baseMipLevel = p_mipmap; + image_view_create_info.subresourceRange.levelCount = p_mipmaps; + image_view_create_info.subresourceRange.baseArrayLayer = p_layer; + image_view_create_info.subresourceRange.layerCount = p_layers; + + VkImageView new_vk_image_view = VK_NULL_HANDLE; + VkResult err = vkCreateImageView(vk_device, &image_view_create_info, nullptr, &new_vk_image_view); + ERR_FAIL_COND_V_MSG(err, TextureID(), "vkCreateImageView failed with error " + itos(err) + "."); + + // Bookkeep. + + TextureInfo ti; + ti.vk_image = owner_ti.vk_image; + + textures.insert(new_vk_image_view, ti); + + return TextureID(new_vk_image_view); +} + +void RenderingDeviceDriverVulkan::texture_free(TextureID p_texture) { + VkImageView vk_image_view = (VkImageView)p_texture.id; + TextureInfo &ti = textures.get(vk_image_view); + vkDestroyImageView(vk_device, vk_image_view, nullptr); + if (ti.owner_info.allocation.handle) { + vmaDestroyImage(allocator, ti.vk_image, ti.owner_info.allocation.handle); + } + textures.erase(vk_image_view); +} + +uint64_t RenderingDeviceDriverVulkan::texture_get_allocation_size(TextureID p_texture) { + TextureInfo &ti = textures.get((VkImageView)p_texture.id); + return ti.owner_info.allocation.size; +} + +void RenderingDeviceDriverVulkan::texture_get_subresource_layout(TextureID p_texture, const TextureSubresource &p_subresource, TextureSubresourceLayout *r_layout) { + TextureInfo &ti = textures.get((VkImageView)p_texture.id); + + VkImageSubresource vk_subres = {}; + vk_subres.aspectMask = (VkImageAspectFlags)p_subresource.aspect; + vk_subres.arrayLayer = p_subresource.layer; + vk_subres.mipLevel = p_subresource.mipmap; + + VkSubresourceLayout vk_layout = {}; + vkGetImageSubresourceLayout(vk_device, ti.vk_image, &vk_subres, &vk_layout); + + *r_layout = {}; + r_layout->offset = vk_layout.offset; + r_layout->size = vk_layout.size; + r_layout->row_pitch = vk_layout.rowPitch; + r_layout->array_pitch = vk_layout.arrayPitch; + r_layout->depth_pitch = vk_layout.depthPitch; +} + +uint8_t *RenderingDeviceDriverVulkan::texture_map(TextureID p_texture) { + TextureInfo &ti = textures.get((VkImageView)p_texture.id); + void *data_ptr = nullptr; + VkResult err = vmaMapMemory(allocator, ti.owner_info.allocation.handle, &data_ptr); + ERR_FAIL_COND_V_MSG(err, nullptr, "vmaMapMemory failed with error " + itos(err) + "."); + return (uint8_t *)data_ptr; +} + +void RenderingDeviceDriverVulkan::texture_unmap(TextureID p_texture) { + TextureInfo &ti = textures.get((VkImageView)p_texture.id); + vmaUnmapMemory(allocator, ti.owner_info.allocation.handle); +} + +BitField RenderingDeviceDriverVulkan::texture_get_usages_supported_by_format(DataFormat p_format, bool p_cpu_readable) { + VkFormatProperties properties = {}; + vkGetPhysicalDeviceFormatProperties(context->get_physical_device(), RD_TO_VK_FORMAT[p_format], &properties); + + const VkFormatFeatureFlags &flags = p_cpu_readable ? properties.linearTilingFeatures : properties.optimalTilingFeatures; + + // Everything supported by default makes an all-or-nothing check easier for the caller. + BitField supported = INT64_MAX; + + if (!(flags & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT)) { + supported.clear_flag(TEXTURE_USAGE_SAMPLING_BIT); + } + if (!(flags & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT)) { + supported.clear_flag(TEXTURE_USAGE_COLOR_ATTACHMENT_BIT); + } + if (!(flags & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT)) { + supported.clear_flag(TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT); + } + if (!(flags & VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT)) { + supported.clear_flag(TEXTURE_USAGE_STORAGE_BIT); + } + if (!(flags & VK_FORMAT_FEATURE_STORAGE_IMAGE_ATOMIC_BIT)) { + supported.clear_flag(TEXTURE_USAGE_STORAGE_ATOMIC_BIT); + } + // Validation via VK_FORMAT_FEATURE_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR fails if VRS attachment is not supported. + if (p_format != DATA_FORMAT_R8_UINT) { + supported.clear_flag(TEXTURE_USAGE_VRS_ATTACHMENT_BIT); + } + + return supported; +} + +/*****************/ +/**** SAMPLER ****/ +/*****************/ + +// RDD::SamplerRepeatMode == VkSamplerAddressMode. +static_assert(ENUM_MEMBERS_EQUAL(RDD::SAMPLER_REPEAT_MODE_REPEAT, VK_SAMPLER_ADDRESS_MODE_REPEAT)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::SAMPLER_REPEAT_MODE_MIRRORED_REPEAT, VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::SAMPLER_REPEAT_MODE_CLAMP_TO_EDGE, VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::SAMPLER_REPEAT_MODE_CLAMP_TO_BORDER, VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::SAMPLER_REPEAT_MODE_MIRROR_CLAMP_TO_EDGE, VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE)); + +// RDD::SamplerBorderColor == VkBorderColor. +static_assert(ENUM_MEMBERS_EQUAL(RDD::SAMPLER_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK, VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::SAMPLER_BORDER_COLOR_INT_TRANSPARENT_BLACK, VK_BORDER_COLOR_INT_TRANSPARENT_BLACK)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::SAMPLER_BORDER_COLOR_FLOAT_OPAQUE_BLACK, VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::SAMPLER_BORDER_COLOR_INT_OPAQUE_BLACK, VK_BORDER_COLOR_INT_OPAQUE_BLACK)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::SAMPLER_BORDER_COLOR_FLOAT_OPAQUE_WHITE, VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::SAMPLER_BORDER_COLOR_INT_OPAQUE_WHITE, VK_BORDER_COLOR_INT_OPAQUE_WHITE)); + +RDD::SamplerID RenderingDeviceDriverVulkan::sampler_create(const SamplerState &p_state) { + VkSamplerCreateInfo sampler_create_info = {}; + sampler_create_info.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO; + sampler_create_info.pNext = nullptr; + sampler_create_info.flags = 0; + sampler_create_info.magFilter = p_state.mag_filter == SAMPLER_FILTER_LINEAR ? VK_FILTER_LINEAR : VK_FILTER_NEAREST; + sampler_create_info.minFilter = p_state.min_filter == SAMPLER_FILTER_LINEAR ? VK_FILTER_LINEAR : VK_FILTER_NEAREST; + sampler_create_info.mipmapMode = p_state.mip_filter == SAMPLER_FILTER_LINEAR ? VK_SAMPLER_MIPMAP_MODE_LINEAR : VK_SAMPLER_MIPMAP_MODE_NEAREST; + sampler_create_info.addressModeU = (VkSamplerAddressMode)p_state.repeat_u; + sampler_create_info.addressModeV = (VkSamplerAddressMode)p_state.repeat_v; + sampler_create_info.addressModeW = (VkSamplerAddressMode)p_state.repeat_w; + sampler_create_info.mipLodBias = p_state.lod_bias; + sampler_create_info.anisotropyEnable = p_state.use_anisotropy && context->get_physical_device_features().samplerAnisotropy; + sampler_create_info.maxAnisotropy = p_state.anisotropy_max; + sampler_create_info.compareEnable = p_state.enable_compare; + sampler_create_info.compareOp = (VkCompareOp)p_state.compare_op; + sampler_create_info.minLod = p_state.min_lod; + sampler_create_info.maxLod = p_state.max_lod; + sampler_create_info.borderColor = (VkBorderColor)p_state.border_color; + sampler_create_info.unnormalizedCoordinates = p_state.unnormalized_uvw; + + VkSampler vk_sampler = VK_NULL_HANDLE; + VkResult res = vkCreateSampler(vk_device, &sampler_create_info, nullptr, &vk_sampler); + ERR_FAIL_COND_V_MSG(res, SamplerID(), "vkCreateSampler failed with error " + itos(res) + "."); + + return SamplerID(vk_sampler); +} + +void RenderingDeviceDriverVulkan::sampler_free(SamplerID p_sampler) { + vkDestroySampler(vk_device, (VkSampler)p_sampler.id, nullptr); +} + +bool RenderingDeviceDriverVulkan::sampler_is_format_supported_for_filter(DataFormat p_format, SamplerFilter p_filter) { + switch (p_filter) { + case RD::SAMPLER_FILTER_NEAREST: { + return true; + } + case RD::SAMPLER_FILTER_LINEAR: { + VkFormatProperties properties = {}; + vkGetPhysicalDeviceFormatProperties(context->get_physical_device(), RD_TO_VK_FORMAT[p_format], &properties); + return (properties.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT); + } + } + return false; +} + +/*********************/ +/**** FRAMEBUFFER ****/ +/*********************/ + +RDD::FramebufferID RenderingDeviceDriverVulkan::framebuffer_create(RenderPassID p_render_pass, VectorView p_attachments, uint32_t p_width, uint32_t p_height) { + VkFramebufferCreateInfo framebuffer_create_info = {}; + framebuffer_create_info.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; + framebuffer_create_info.renderPass = (VkRenderPass)p_render_pass.id; + framebuffer_create_info.attachmentCount = p_attachments.size(); + static_assert(ARRAYS_COMPATIBLE(TextureID, VkImageView)); + framebuffer_create_info.pAttachments = (const VkImageView *)p_attachments.ptr(); + framebuffer_create_info.width = p_width; + framebuffer_create_info.height = p_height; + framebuffer_create_info.layers = 1; + + VkFramebuffer vk_framebuffer = VK_NULL_HANDLE; + VkResult err = vkCreateFramebuffer(vk_device, &framebuffer_create_info, nullptr, &vk_framebuffer); + ERR_FAIL_COND_V_MSG(err, FramebufferID(), "vkCreateFramebuffer failed with error " + itos(err) + "."); + + return FramebufferID(vk_framebuffer); +} + +void RenderingDeviceDriverVulkan::framebuffer_free(FramebufferID p_framebuffer) { + vkDestroyFramebuffer(vk_device, (VkFramebuffer)p_framebuffer.id, nullptr); +} + +/****************/ +/**** SHADER ****/ +/****************/ + +static VkShaderStageFlagBits RD_STAGE_TO_VK_SHADER_STAGE_BITS[RDD::SHADER_STAGE_MAX] = { + VK_SHADER_STAGE_VERTEX_BIT, + VK_SHADER_STAGE_FRAGMENT_BIT, + VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT, + VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT, + VK_SHADER_STAGE_COMPUTE_BIT, +}; + +String RenderingDeviceDriverVulkan::shader_get_binary_cache_key() { + return "Vulkan-SV" + uitos(ShaderBinary::VERSION); +} + +Vector RenderingDeviceDriverVulkan::shader_compile_binary_from_spirv(VectorView p_spirv, const String &p_shader_name) { + ShaderReflection shader_refl; + if (_reflect_spirv(p_spirv, shader_refl) != OK) { + return Vector(); + } + + ERR_FAIL_COND_V_MSG((uint32_t)shader_refl.uniform_sets.size() > limits.maxBoundDescriptorSets, Vector(), + "Number of uniform sets is larger than what is supported by the hardware (" + itos(limits.maxBoundDescriptorSets) + ")."); + + // Collect reflection data into binary data. + ShaderBinary::Data binary_data; + Vector> uniforms; // Set bindings. + Vector specialization_constants; + { + binary_data.vertex_input_mask = shader_refl.vertex_input_mask; + binary_data.fragment_output_mask = shader_refl.fragment_output_mask; + binary_data.specialization_constants_count = shader_refl.specialization_constants.size(); + binary_data.is_compute = shader_refl.is_compute; + binary_data.compute_local_size[0] = shader_refl.compute_local_size[0]; + binary_data.compute_local_size[1] = shader_refl.compute_local_size[1]; + binary_data.compute_local_size[2] = shader_refl.compute_local_size[2]; + binary_data.set_count = shader_refl.uniform_sets.size(); + binary_data.push_constant_size = shader_refl.push_constant_size; + for (uint32_t i = 0; i < SHADER_STAGE_MAX; i++) { + if (shader_refl.push_constant_stages.has_flag((ShaderStage)(1 << i))) { + binary_data.vk_push_constant_stages_mask |= RD_STAGE_TO_VK_SHADER_STAGE_BITS[i]; + } + } + + for (const Vector &set_refl : shader_refl.uniform_sets) { + Vector set_bindings; + for (const ShaderUniform &uniform_refl : set_refl) { + ShaderBinary::DataBinding binding; + binding.type = (uint32_t)uniform_refl.type; + binding.binding = uniform_refl.binding; + binding.stages = (uint32_t)uniform_refl.stages; + binding.length = uniform_refl.length; + binding.writable = (uint32_t)uniform_refl.writable; + set_bindings.push_back(binding); + } + uniforms.push_back(set_bindings); + } + + for (const ShaderSpecializationConstant &refl_sc : shader_refl.specialization_constants) { + ShaderBinary::SpecializationConstant spec_constant; + spec_constant.type = (uint32_t)refl_sc.type; + spec_constant.constant_id = refl_sc.constant_id; + spec_constant.int_value = refl_sc.int_value; + spec_constant.stage_flags = (uint32_t)refl_sc.stages; + specialization_constants.push_back(spec_constant); + } + } + + Vector> compressed_stages; + Vector smolv_size; + Vector zstd_size; // If 0, zstd not used. + + uint32_t stages_binary_size = 0; + + bool strip_debug = false; + + for (uint32_t i = 0; i < p_spirv.size(); i++) { + smolv::ByteArray smolv; + if (!smolv::Encode(p_spirv[i].spirv.ptr(), p_spirv[i].spirv.size(), smolv, strip_debug ? smolv::kEncodeFlagStripDebugInfo : 0)) { + ERR_FAIL_V_MSG(Vector(), "Error compressing shader stage :" + String(SHADER_STAGE_NAMES[p_spirv[i].shader_stage])); + } else { + smolv_size.push_back(smolv.size()); + { // zstd. + Vector zstd; + zstd.resize(Compression::get_max_compressed_buffer_size(smolv.size(), Compression::MODE_ZSTD)); + int dst_size = Compression::compress(zstd.ptrw(), &smolv[0], smolv.size(), Compression::MODE_ZSTD); + + if (dst_size > 0 && (uint32_t)dst_size < smolv.size()) { + zstd_size.push_back(dst_size); + zstd.resize(dst_size); + compressed_stages.push_back(zstd); + } else { + Vector smv; + smv.resize(smolv.size()); + memcpy(smv.ptrw(), &smolv[0], smolv.size()); + zstd_size.push_back(0); // Not using zstd. + compressed_stages.push_back(smv); + } + } + } + uint32_t s = compressed_stages[i].size(); + if (s % 4 != 0) { + s += 4 - (s % 4); + } + stages_binary_size += s; + } + + binary_data.specialization_constants_count = specialization_constants.size(); + binary_data.set_count = uniforms.size(); + binary_data.stage_count = p_spirv.size(); + + CharString shader_name_utf = p_shader_name.utf8(); + + binary_data.shader_name_len = shader_name_utf.length(); + + uint32_t total_size = sizeof(uint32_t) * 3; // Header + version + main datasize;. + total_size += sizeof(ShaderBinary::Data); + + total_size += binary_data.shader_name_len; + + if ((binary_data.shader_name_len % 4) != 0) { // Alignment rules are really strange. + total_size += 4 - (binary_data.shader_name_len % 4); + } + + for (int i = 0; i < uniforms.size(); i++) { + total_size += sizeof(uint32_t); + total_size += uniforms[i].size() * sizeof(ShaderBinary::DataBinding); + } + + total_size += sizeof(ShaderBinary::SpecializationConstant) * specialization_constants.size(); + + total_size += compressed_stages.size() * sizeof(uint32_t) * 3; // Sizes. + total_size += stages_binary_size; + + Vector ret; + ret.resize(total_size); + { + uint32_t offset = 0; + uint8_t *binptr = ret.ptrw(); + binptr[0] = 'G'; + binptr[1] = 'S'; + binptr[2] = 'B'; + binptr[3] = 'D'; // Godot Shader Binary Data. + offset += 4; + encode_uint32(ShaderBinary::VERSION, binptr + offset); + offset += sizeof(uint32_t); + encode_uint32(sizeof(ShaderBinary::Data), binptr + offset); + offset += sizeof(uint32_t); + memcpy(binptr + offset, &binary_data, sizeof(ShaderBinary::Data)); + offset += sizeof(ShaderBinary::Data); + + if (binary_data.shader_name_len > 0) { + memcpy(binptr + offset, shader_name_utf.ptr(), binary_data.shader_name_len); + offset += binary_data.shader_name_len; + + if ((binary_data.shader_name_len % 4) != 0) { // Alignment rules are really strange. + offset += 4 - (binary_data.shader_name_len % 4); + } + } + + for (int i = 0; i < uniforms.size(); i++) { + int count = uniforms[i].size(); + encode_uint32(count, binptr + offset); + offset += sizeof(uint32_t); + if (count > 0) { + memcpy(binptr + offset, uniforms[i].ptr(), sizeof(ShaderBinary::DataBinding) * count); + offset += sizeof(ShaderBinary::DataBinding) * count; + } + } + + if (specialization_constants.size()) { + memcpy(binptr + offset, specialization_constants.ptr(), sizeof(ShaderBinary::SpecializationConstant) * specialization_constants.size()); + offset += sizeof(ShaderBinary::SpecializationConstant) * specialization_constants.size(); + } + + for (int i = 0; i < compressed_stages.size(); i++) { + encode_uint32(p_spirv[i].shader_stage, binptr + offset); + offset += sizeof(uint32_t); + encode_uint32(smolv_size[i], binptr + offset); + offset += sizeof(uint32_t); + encode_uint32(zstd_size[i], binptr + offset); + offset += sizeof(uint32_t); + memcpy(binptr + offset, compressed_stages[i].ptr(), compressed_stages[i].size()); + + uint32_t s = compressed_stages[i].size(); + + if (s % 4 != 0) { + s += 4 - (s % 4); + } + + offset += s; + } + + DEV_ASSERT(offset == (uint32_t)ret.size()); + } + + return ret; +} + +RDD::ShaderID RenderingDeviceDriverVulkan::shader_create_from_bytecode(const Vector &p_shader_binary, ShaderDescription &r_shader_desc, String &r_name) { + r_shader_desc = {}; // Driver-agnostic. + ShaderInfo si; // Driver-specific. + + const uint8_t *binptr = p_shader_binary.ptr(); + uint32_t binsize = p_shader_binary.size(); + + uint32_t read_offset = 0; + + // Consistency check. + ERR_FAIL_COND_V(binsize < sizeof(uint32_t) * 3 + sizeof(ShaderBinary::Data), ShaderID()); + ERR_FAIL_COND_V(binptr[0] != 'G' || binptr[1] != 'S' || binptr[2] != 'B' || binptr[3] != 'D', ShaderID()); + + uint32_t bin_version = decode_uint32(binptr + 4); + ERR_FAIL_COND_V(bin_version != ShaderBinary::VERSION, ShaderID()); + + uint32_t bin_data_size = decode_uint32(binptr + 8); + + const ShaderBinary::Data &binary_data = *(reinterpret_cast(binptr + 12)); + + r_shader_desc.push_constant_size = binary_data.push_constant_size; + si.vk_push_constant_stages = binary_data.vk_push_constant_stages_mask; + + r_shader_desc.vertex_input_mask = binary_data.vertex_input_mask; + r_shader_desc.fragment_output_mask = binary_data.fragment_output_mask; + + r_shader_desc.is_compute = binary_data.is_compute; + r_shader_desc.compute_local_size[0] = binary_data.compute_local_size[0]; + r_shader_desc.compute_local_size[1] = binary_data.compute_local_size[1]; + r_shader_desc.compute_local_size[2] = binary_data.compute_local_size[2]; + + read_offset += sizeof(uint32_t) * 3 + bin_data_size; + + if (binary_data.shader_name_len) { + r_name.parse_utf8((const char *)(binptr + read_offset), binary_data.shader_name_len); + read_offset += binary_data.shader_name_len; + if ((binary_data.shader_name_len % 4) != 0) { // Alignment rules are really strange. + read_offset += 4 - (binary_data.shader_name_len % 4); + } + } + + Vector> vk_set_bindings; + + r_shader_desc.uniform_sets.resize(binary_data.set_count); + vk_set_bindings.resize(binary_data.set_count); + + for (uint32_t i = 0; i < binary_data.set_count; i++) { + ERR_FAIL_COND_V(read_offset + sizeof(uint32_t) >= binsize, ShaderID()); + uint32_t set_count = decode_uint32(binptr + read_offset); + read_offset += sizeof(uint32_t); + const ShaderBinary::DataBinding *set_ptr = reinterpret_cast(binptr + read_offset); + uint32_t set_size = set_count * sizeof(ShaderBinary::DataBinding); + ERR_FAIL_COND_V(read_offset + set_size >= binsize, ShaderID()); + + for (uint32_t j = 0; j < set_count; j++) { + ShaderUniform info; + info.type = UniformType(set_ptr[j].type); + info.writable = set_ptr[j].writable; + info.length = set_ptr[j].length; + info.binding = set_ptr[j].binding; + info.stages = set_ptr[j].stages; + + VkDescriptorSetLayoutBinding layout_binding = {}; + layout_binding.binding = set_ptr[j].binding; + layout_binding.descriptorCount = 1; + for (uint32_t k = 0; k < SHADER_STAGE_MAX; k++) { + if ((set_ptr[j].stages & (1 << k))) { + layout_binding.stageFlags |= RD_STAGE_TO_VK_SHADER_STAGE_BITS[k]; + } + } + + switch (info.type) { + case UNIFORM_TYPE_SAMPLER: { + layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_SAMPLER; + layout_binding.descriptorCount = set_ptr[j].length; + } break; + case UNIFORM_TYPE_SAMPLER_WITH_TEXTURE: { + layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; + layout_binding.descriptorCount = set_ptr[j].length; + } break; + case UNIFORM_TYPE_TEXTURE: { + layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; + layout_binding.descriptorCount = set_ptr[j].length; + } break; + case UNIFORM_TYPE_IMAGE: { + layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE; + layout_binding.descriptorCount = set_ptr[j].length; + } break; + case UNIFORM_TYPE_TEXTURE_BUFFER: { + layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER; + layout_binding.descriptorCount = set_ptr[j].length; + } break; + case UNIFORM_TYPE_IMAGE_BUFFER: { + layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER; + } break; + case UNIFORM_TYPE_UNIFORM_BUFFER: { + layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; + } break; + case UNIFORM_TYPE_STORAGE_BUFFER: { + layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + } break; + case UNIFORM_TYPE_INPUT_ATTACHMENT: { + layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT; + } break; + default: { + DEV_ASSERT(false); + } + } + + r_shader_desc.uniform_sets.write[i].push_back(info); + vk_set_bindings.write[i].push_back(layout_binding); + } + + read_offset += set_size; + } + + ERR_FAIL_COND_V(read_offset + binary_data.specialization_constants_count * sizeof(ShaderBinary::SpecializationConstant) >= binsize, ShaderID()); + + r_shader_desc.specialization_constants.resize(binary_data.specialization_constants_count); + for (uint32_t i = 0; i < binary_data.specialization_constants_count; i++) { + const ShaderBinary::SpecializationConstant &src_sc = *(reinterpret_cast(binptr + read_offset)); + ShaderSpecializationConstant sc; + sc.type = PipelineSpecializationConstantType(src_sc.type); + sc.constant_id = src_sc.constant_id; + sc.int_value = src_sc.int_value; + sc.stages = src_sc.stage_flags; + r_shader_desc.specialization_constants.push_back(sc); + + read_offset += sizeof(ShaderBinary::SpecializationConstant); + } + + struct Stage { + ShaderStage type = SHADER_STAGE_MAX; + Vector spirv; + }; + Vector stages; + + for (uint32_t i = 0; i < binary_data.stage_count; i++) { + ERR_FAIL_COND_V(read_offset + sizeof(uint32_t) * 3 >= binsize, ShaderID()); + uint32_t stage = decode_uint32(binptr + read_offset); + read_offset += sizeof(uint32_t); + uint32_t smolv_size = decode_uint32(binptr + read_offset); + read_offset += sizeof(uint32_t); + uint32_t zstd_size = decode_uint32(binptr + read_offset); + read_offset += sizeof(uint32_t); + + uint32_t buf_size = (zstd_size > 0) ? zstd_size : smolv_size; + + Vector smolv; + const uint8_t *src_smolv = nullptr; + + if (zstd_size > 0) { + // Decompress to smolv. + smolv.resize(smolv_size); + int dec_smolv_size = Compression::decompress(smolv.ptrw(), smolv.size(), binptr + read_offset, zstd_size, Compression::MODE_ZSTD); + ERR_FAIL_COND_V(dec_smolv_size != (int32_t)smolv_size, ShaderID()); + src_smolv = smolv.ptr(); + } else { + src_smolv = binptr + read_offset; + } + + Vector spirv; + uint32_t spirv_size = smolv::GetDecodedBufferSize(src_smolv, smolv_size); + spirv.resize(spirv_size); + if (!smolv::Decode(src_smolv, smolv_size, spirv.ptrw(), spirv_size)) { + ERR_FAIL_V_MSG(ShaderID(), "Malformed smolv input uncompressing shader stage:" + String(SHADER_STAGE_NAMES[stage])); + } + + Stage stage_entry; + stage_entry.type = ShaderStage(stage); + stage_entry.spirv = spirv; + stages.push_back(stage_entry); + + if (buf_size % 4 != 0) { + buf_size += 4 - (buf_size % 4); + } + + DEV_ASSERT(read_offset + buf_size <= binsize); + + read_offset += buf_size; + } + + DEV_ASSERT(read_offset == binsize); + + // Modules. + + String error_text; + + for (int i = 0; i < stages.size(); i++) { + VkShaderModuleCreateInfo shader_module_create_info = {}; + shader_module_create_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; + shader_module_create_info.codeSize = stages[i].spirv.size(); + shader_module_create_info.pCode = (const uint32_t *)stages[i].spirv.ptr(); + + VkShaderModule vk_module = VK_NULL_HANDLE; + VkResult res = vkCreateShaderModule(vk_device, &shader_module_create_info, nullptr, &vk_module); + if (res) { + error_text = "Error (" + itos(res) + ") creating shader module for stage: " + String(SHADER_STAGE_NAMES[stages[i].type]); + break; + } + + VkPipelineShaderStageCreateInfo create_info = {}; + create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; + create_info.stage = RD_STAGE_TO_VK_SHADER_STAGE_BITS[stages[i].type]; + create_info.module = vk_module; + create_info.pName = "main"; + + si.vk_stages_create_info.push_back(create_info); + } + + // Descriptor sets. + + if (error_text.is_empty()) { + DEV_ASSERT((uint32_t)vk_set_bindings.size() == binary_data.set_count); + for (uint32_t i = 0; i < binary_data.set_count; i++) { + // Empty ones are fine if they were not used according to spec (binding count will be 0). + VkDescriptorSetLayoutCreateInfo layout_create_info = {}; + layout_create_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; + layout_create_info.bindingCount = vk_set_bindings[i].size(); + layout_create_info.pBindings = vk_set_bindings[i].ptr(); + + VkDescriptorSetLayout layout = VK_NULL_HANDLE; + VkResult res = vkCreateDescriptorSetLayout(vk_device, &layout_create_info, nullptr, &layout); + if (res) { + error_text = "Error (" + itos(res) + ") creating descriptor set layout for set " + itos(i); + break; + } + + si.vk_descriptor_set_layouts.push_back(layout); + } + } + + if (error_text.is_empty()) { + // Pipeline layout. + + VkPipelineLayoutCreateInfo pipeline_layout_create_info = {}; + pipeline_layout_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; + pipeline_layout_create_info.setLayoutCount = binary_data.set_count; + pipeline_layout_create_info.pSetLayouts = si.vk_descriptor_set_layouts.ptr(); + + if (binary_data.push_constant_size) { + VkPushConstantRange *push_constant_range = ALLOCA_SINGLE(VkPushConstantRange); + *push_constant_range = {}; + push_constant_range->stageFlags = binary_data.vk_push_constant_stages_mask; + push_constant_range->size = binary_data.push_constant_size; + pipeline_layout_create_info.pushConstantRangeCount = 1; + pipeline_layout_create_info.pPushConstantRanges = push_constant_range; + } + + VkResult err = vkCreatePipelineLayout(vk_device, &pipeline_layout_create_info, nullptr, &si.vk_pipeline_layout); + if (err) { + error_text = "Error (" + itos(err) + ") creating pipeline layout."; + } + } + + if (!error_text.is_empty()) { + // Clean up if failed. + for (uint32_t i = 0; i < si.vk_stages_create_info.size(); i++) { + vkDestroyShaderModule(vk_device, si.vk_stages_create_info[i].module, nullptr); + } + for (uint32_t i = 0; i < binary_data.set_count; i++) { + vkDestroyDescriptorSetLayout(vk_device, si.vk_descriptor_set_layouts[i], nullptr); + } + + ERR_FAIL_V_MSG(ShaderID(), error_text); + } + + // Bookkeep. + + RBSet::Element *E = shaders.insert(si); + return ShaderID(E); +} + +void RenderingDeviceDriverVulkan::shader_free(ShaderID p_shader) { + auto *E = (RBSet::Element *)p_shader.id; + const ShaderInfo &si = E->get(); + + for (uint32_t i = 0; i < si.vk_descriptor_set_layouts.size(); i++) { + vkDestroyDescriptorSetLayout(vk_device, si.vk_descriptor_set_layouts[i], nullptr); + } + + vkDestroyPipelineLayout(vk_device, si.vk_pipeline_layout, nullptr); + + for (uint32_t i = 0; i < si.vk_stages_create_info.size(); i++) { + vkDestroyShaderModule(vk_device, si.vk_stages_create_info[i].module, nullptr); + } + + shaders.erase(E); +} + +/*********************/ +/**** UNIFORM SET ****/ +/*********************/ + +VkDescriptorPool RenderingDeviceDriverVulkan::_descriptor_set_pool_find_or_create(const DescriptorSetPoolKey &p_key, DescriptorSetPools::Iterator *r_pool_sets_it) { + DescriptorSetPools::Iterator pool_sets_it = descriptor_set_pools.find(p_key); + + if (pool_sets_it) { + for (KeyValue &E : pool_sets_it->value) { + if (E.value < max_descriptor_sets_per_pool) { + *r_pool_sets_it = pool_sets_it; + return E.key; + } + } + } + + // Create a new one. + + // Here comes more vulkan API strangeness. + VkDescriptorPoolSize *vk_sizes = ALLOCA_ARRAY(VkDescriptorPoolSize, UNIFORM_TYPE_MAX); + uint32_t vk_sizes_count = 0; + { + VkDescriptorPoolSize *curr_vk_size = vk_sizes; + if (p_key.uniform_type[UNIFORM_TYPE_SAMPLER]) { + *curr_vk_size = {}; + curr_vk_size->type = VK_DESCRIPTOR_TYPE_SAMPLER; + curr_vk_size->descriptorCount = p_key.uniform_type[UNIFORM_TYPE_SAMPLER] * max_descriptor_sets_per_pool; + curr_vk_size++; + vk_sizes_count++; + } + if (p_key.uniform_type[UNIFORM_TYPE_SAMPLER_WITH_TEXTURE]) { + *curr_vk_size = {}; + curr_vk_size->type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; + curr_vk_size->descriptorCount = p_key.uniform_type[UNIFORM_TYPE_SAMPLER_WITH_TEXTURE] * max_descriptor_sets_per_pool; + curr_vk_size++; + vk_sizes_count++; + } + if (p_key.uniform_type[UNIFORM_TYPE_TEXTURE]) { + *curr_vk_size = {}; + curr_vk_size->type = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; + curr_vk_size->descriptorCount = p_key.uniform_type[UNIFORM_TYPE_TEXTURE] * max_descriptor_sets_per_pool; + curr_vk_size++; + vk_sizes_count++; + } + if (p_key.uniform_type[UNIFORM_TYPE_IMAGE]) { + *curr_vk_size = {}; + curr_vk_size->type = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE; + curr_vk_size->descriptorCount = p_key.uniform_type[UNIFORM_TYPE_IMAGE] * max_descriptor_sets_per_pool; + curr_vk_size++; + vk_sizes_count++; + } + if (p_key.uniform_type[UNIFORM_TYPE_TEXTURE_BUFFER] || p_key.uniform_type[UNIFORM_TYPE_SAMPLER_WITH_TEXTURE_BUFFER]) { + *curr_vk_size = {}; + curr_vk_size->type = VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER; + curr_vk_size->descriptorCount = (p_key.uniform_type[UNIFORM_TYPE_TEXTURE_BUFFER] + p_key.uniform_type[UNIFORM_TYPE_SAMPLER_WITH_TEXTURE_BUFFER]) * max_descriptor_sets_per_pool; + curr_vk_size++; + vk_sizes_count++; + } + if (p_key.uniform_type[UNIFORM_TYPE_IMAGE_BUFFER]) { + *curr_vk_size = {}; + curr_vk_size->type = VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER; + curr_vk_size->descriptorCount = p_key.uniform_type[UNIFORM_TYPE_IMAGE_BUFFER] * max_descriptor_sets_per_pool; + curr_vk_size++; + vk_sizes_count++; + } + if (p_key.uniform_type[UNIFORM_TYPE_UNIFORM_BUFFER]) { + *curr_vk_size = {}; + curr_vk_size->type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; + curr_vk_size->descriptorCount = p_key.uniform_type[UNIFORM_TYPE_UNIFORM_BUFFER] * max_descriptor_sets_per_pool; + curr_vk_size++; + vk_sizes_count++; + } + if (p_key.uniform_type[UNIFORM_TYPE_STORAGE_BUFFER]) { + *curr_vk_size = {}; + curr_vk_size->type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + curr_vk_size->descriptorCount = p_key.uniform_type[UNIFORM_TYPE_STORAGE_BUFFER] * max_descriptor_sets_per_pool; + curr_vk_size++; + vk_sizes_count++; + } + if (p_key.uniform_type[UNIFORM_TYPE_INPUT_ATTACHMENT]) { + *curr_vk_size = {}; + curr_vk_size->type = VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT; + curr_vk_size->descriptorCount = p_key.uniform_type[UNIFORM_TYPE_INPUT_ATTACHMENT] * max_descriptor_sets_per_pool; + curr_vk_size++; + vk_sizes_count++; + } + DEV_ASSERT(vk_sizes_count <= UNIFORM_TYPE_MAX); + } + + VkDescriptorPoolCreateInfo descriptor_set_pool_create_info = {}; + descriptor_set_pool_create_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; + descriptor_set_pool_create_info.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT; // Can't think how somebody may NOT need this flag. + descriptor_set_pool_create_info.maxSets = max_descriptor_sets_per_pool; + descriptor_set_pool_create_info.poolSizeCount = vk_sizes_count; + descriptor_set_pool_create_info.pPoolSizes = vk_sizes; + + VkDescriptorPool vk_pool = VK_NULL_HANDLE; + VkResult res = vkCreateDescriptorPool(vk_device, &descriptor_set_pool_create_info, nullptr, &vk_pool); + if (res) { + ERR_FAIL_COND_V_MSG(res, VK_NULL_HANDLE, "vkCreateDescriptorPool failed with error " + itos(res) + "."); + } + + // Bookkeep. + + if (!pool_sets_it) { + pool_sets_it = descriptor_set_pools.insert(p_key, HashMap()); + } + HashMap &pool_rcs = pool_sets_it->value; + pool_rcs.insert(vk_pool, 0); + *r_pool_sets_it = pool_sets_it; + return vk_pool; +} + +void RenderingDeviceDriverVulkan::_descriptor_set_pool_unreference(DescriptorSetPools::Iterator p_pool_sets_it, VkDescriptorPool p_vk_descriptor_pool) { + HashMap::Iterator pool_rcs_it = p_pool_sets_it->value.find(p_vk_descriptor_pool); + pool_rcs_it->value--; + if (pool_rcs_it->value == 0) { + vkDestroyDescriptorPool(vk_device, p_vk_descriptor_pool, nullptr); + p_pool_sets_it->value.erase(p_vk_descriptor_pool); + if (p_pool_sets_it->value.is_empty()) { + descriptor_set_pools.remove(p_pool_sets_it); + } + } +} + +RDD::UniformSetID RenderingDeviceDriverVulkan::uniform_set_create(VectorView p_uniforms, ShaderID p_shader, uint32_t p_set_index) { + DescriptorSetPoolKey pool_key; + + VkWriteDescriptorSet *vk_writes = ALLOCA_ARRAY(VkWriteDescriptorSet, p_uniforms.size()); + for (uint32_t i = 0; i < p_uniforms.size(); i++) { + const BoundUniform &uniform = p_uniforms[i]; + + vk_writes[i] = {}; + vk_writes[i].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + vk_writes[i].dstBinding = uniform.binding; + vk_writes[i].descriptorType = VK_DESCRIPTOR_TYPE_MAX_ENUM; // Invalid value. + + uint32_t num_descriptors = 1; + + switch (uniform.type) { + case UNIFORM_TYPE_SAMPLER: { + num_descriptors = uniform.ids.size(); + VkDescriptorImageInfo *vk_img_infos = ALLOCA_ARRAY(VkDescriptorImageInfo, num_descriptors); + + for (uint32_t j = 0; j < num_descriptors; j++) { + vk_img_infos[j] = {}; + vk_img_infos[j].sampler = (VkSampler)uniform.ids[j].id; + vk_img_infos[j].imageView = VK_NULL_HANDLE; + vk_img_infos[j].imageLayout = VK_IMAGE_LAYOUT_UNDEFINED; + } + + vk_writes[i].descriptorType = VK_DESCRIPTOR_TYPE_SAMPLER; + vk_writes[i].pImageInfo = vk_img_infos; + } break; + case UNIFORM_TYPE_SAMPLER_WITH_TEXTURE: { + num_descriptors = uniform.ids.size() / 2; + VkDescriptorImageInfo *vk_img_infos = ALLOCA_ARRAY(VkDescriptorImageInfo, num_descriptors); + + for (uint32_t j = 0; j < num_descriptors; j++) { + vk_img_infos[j] = {}; + vk_img_infos[j].sampler = (VkSampler)uniform.ids[j * 2 + 0].id; + vk_img_infos[j].imageView = (VkImageView)uniform.ids[j * 2 + 1].id; + vk_img_infos[j].imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; + } + + vk_writes[i].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; + vk_writes[i].pImageInfo = vk_img_infos; + } break; + case UNIFORM_TYPE_TEXTURE: { + num_descriptors = uniform.ids.size(); + VkDescriptorImageInfo *vk_img_infos = ALLOCA_ARRAY(VkDescriptorImageInfo, num_descriptors); + + for (uint32_t j = 0; j < num_descriptors; j++) { + vk_img_infos[j] = {}; + vk_img_infos[j].imageView = (VkImageView)uniform.ids[j].id; + vk_img_infos[j].imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; + } + + vk_writes[i].descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; + vk_writes[i].pImageInfo = vk_img_infos; + } break; + case UNIFORM_TYPE_IMAGE: { + num_descriptors = uniform.ids.size(); + VkDescriptorImageInfo *vk_img_infos = ALLOCA_ARRAY(VkDescriptorImageInfo, num_descriptors); + + for (uint32_t j = 0; j < num_descriptors; j++) { + vk_img_infos[j] = {}; + vk_img_infos[j].imageView = (VkImageView)uniform.ids[j].id; + vk_img_infos[j].imageLayout = VK_IMAGE_LAYOUT_GENERAL; + } + + vk_writes[i].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE; + vk_writes[i].pImageInfo = vk_img_infos; + } break; + case UNIFORM_TYPE_TEXTURE_BUFFER: { + num_descriptors = uniform.ids.size(); + VkDescriptorBufferInfo *vk_buf_infos = ALLOCA_ARRAY(VkDescriptorBufferInfo, num_descriptors); + VkBufferView *vk_buf_views = ALLOCA_ARRAY(VkBufferView, num_descriptors); + + for (uint32_t j = 0; j < num_descriptors; j++) { + VkBuffer vk_buffer = (VkBuffer)uniform.ids[j].id; + BufferInfo &bi = buffers.get(vk_buffer); + vk_buf_infos[j] = {}; + vk_buf_infos[j].buffer = vk_buffer; + vk_buf_infos[j].range = bi.size; + + vk_buf_views[j] = bi.vk_view; + } + + vk_writes[i].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER; + vk_writes[i].pBufferInfo = vk_buf_infos; + vk_writes[i].pTexelBufferView = vk_buf_views; + } break; + case UNIFORM_TYPE_SAMPLER_WITH_TEXTURE_BUFFER: { + num_descriptors = uniform.ids.size() / 2; + VkDescriptorImageInfo *vk_img_infos = ALLOCA_ARRAY(VkDescriptorImageInfo, num_descriptors); + VkDescriptorBufferInfo *vk_buf_infos = ALLOCA_ARRAY(VkDescriptorBufferInfo, num_descriptors); + VkBufferView *vk_buf_views = ALLOCA_ARRAY(VkBufferView, num_descriptors); + + for (uint32_t j = 0; j < num_descriptors; j++) { + vk_img_infos[j] = {}; + vk_img_infos[j].sampler = (VkSampler)uniform.ids[j * 2 + 0].id; + + VkBuffer vk_buffer = (VkBuffer)uniform.ids[j * 2 + 1].id; + BufferInfo &bi = buffers.get(vk_buffer); + vk_buf_infos[j] = {}; + vk_buf_infos[j].buffer = vk_buffer; + vk_buf_infos[j].range = bi.size; + + vk_buf_views[j] = bi.vk_view; + } + + vk_writes[i].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER; + vk_writes[i].pImageInfo = vk_img_infos; + vk_writes[i].pBufferInfo = vk_buf_infos; + vk_writes[i].pTexelBufferView = vk_buf_views; + } break; + case UNIFORM_TYPE_IMAGE_BUFFER: { + CRASH_NOW_MSG("Unimplemented!"); // TODO. + } break; + case UNIFORM_TYPE_UNIFORM_BUFFER: { + VkBuffer vk_buffer = (VkBuffer)uniform.ids[0].id; + BufferInfo &bi = buffers.get(vk_buffer); + VkDescriptorBufferInfo *buf_info = ALLOCA_SINGLE(VkDescriptorBufferInfo); + *buf_info = {}; + buf_info->buffer = vk_buffer; + buf_info->range = bi.size; + + vk_writes[i].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; + vk_writes[i].pBufferInfo = buf_info; + } break; + case UNIFORM_TYPE_STORAGE_BUFFER: { + VkBuffer vk_buffer = (VkBuffer)uniform.ids[0].id; + BufferInfo &bi = buffers.get(vk_buffer); + VkDescriptorBufferInfo *buf_info = ALLOCA_SINGLE(VkDescriptorBufferInfo); + *buf_info = {}; + buf_info->buffer = vk_buffer; + buf_info->range = bi.size; + + vk_writes[i].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + vk_writes[i].pBufferInfo = buf_info; + } break; + case UNIFORM_TYPE_INPUT_ATTACHMENT: { + num_descriptors = uniform.ids.size(); + VkDescriptorImageInfo *vk_img_infos = ALLOCA_ARRAY(VkDescriptorImageInfo, num_descriptors); + + for (uint32_t j = 0; j < uniform.ids.size(); j++) { + vk_img_infos[j] = {}; + vk_img_infos[j].imageView = (VkImageView)uniform.ids[j].id; + vk_img_infos[j].imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; + } + + vk_writes[i].descriptorType = VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT; + vk_writes[i].pImageInfo = vk_img_infos; + } break; + default: { + DEV_ASSERT(false); + } + } + + vk_writes[i].descriptorCount = num_descriptors; + + ERR_FAIL_COND_V_MSG(pool_key.uniform_type[uniform.type] == MAX_UNIFORM_POOL_ELEMENT, UniformSetID(), + "Uniform set reached the limit of bindings for the same type (" + itos(MAX_UNIFORM_POOL_ELEMENT) + ")."); + pool_key.uniform_type[uniform.type] += num_descriptors; + } + + // Need a descriptor pool. + DescriptorSetPools::Iterator pool_sets_it = {}; + VkDescriptorPool vk_pool = _descriptor_set_pool_find_or_create(pool_key, &pool_sets_it); + DEV_ASSERT(vk_pool); + pool_sets_it->value[vk_pool]++; + + VkDescriptorSetAllocateInfo descriptor_set_allocate_info = {}; + descriptor_set_allocate_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; + descriptor_set_allocate_info.descriptorPool = vk_pool; + descriptor_set_allocate_info.descriptorSetCount = 1; + const ShaderInfo &si = ((RBSet::Element *)p_shader.id)->get(); + descriptor_set_allocate_info.pSetLayouts = &si.vk_descriptor_set_layouts[p_set_index]; + + VkDescriptorSet vk_descriptor_set = VK_NULL_HANDLE; + VkResult res = vkAllocateDescriptorSets(vk_device, &descriptor_set_allocate_info, &vk_descriptor_set); + if (res) { + _descriptor_set_pool_unreference(pool_sets_it, vk_pool); + ERR_FAIL_V_MSG(UniformSetID(), "Cannot allocate descriptor sets, error " + itos(res) + "."); + } + + for (uint32_t i = 0; i < p_uniforms.size(); i++) { + vk_writes[i].dstSet = vk_descriptor_set; + } + vkUpdateDescriptorSets(vk_device, p_uniforms.size(), vk_writes, 0, nullptr); + + // Bookkeep. + + UniformSetInfo usi; + usi.pool_sets_it = pool_sets_it; + usi.vk_descriptor_pool = vk_pool; + usi.vk_descriptor_set = vk_descriptor_set; + + uniform_sets.insert(vk_descriptor_set, usi); + + return UniformSetID(vk_descriptor_set); +} + +void RenderingDeviceDriverVulkan::uniform_set_free(UniformSetID p_uniform_set) { + VkDescriptorSet vk_descriptor_set = (VkDescriptorSet)p_uniform_set.id; + UniformSetInfo &usi = uniform_sets.get(vk_descriptor_set); + vkFreeDescriptorSets(vk_device, usi.vk_descriptor_pool, 1, &usi.vk_descriptor_set); + + _descriptor_set_pool_unreference(usi.pool_sets_it, usi.vk_descriptor_pool); + + uniform_sets.erase(vk_descriptor_set); +} + +/******************/ +/**** BARRIERS ****/ +/******************/ + +// RDD::PipelineStageBits == VkPipelineStageFlagBits. +static_assert(ENUM_MEMBERS_EQUAL(RDD::PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::PIPELINE_STAGE_DRAW_INDIRECT_BIT, VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::PIPELINE_STAGE_VERTEX_INPUT_BIT, VK_PIPELINE_STAGE_VERTEX_INPUT_BIT)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::PIPELINE_STAGE_VERTEX_SHADER_BIT, VK_PIPELINE_STAGE_VERTEX_SHADER_BIT)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT, VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT, VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::PIPELINE_STAGE_GEOMETRY_SHADER_BIT, VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::PIPELINE_STAGE_FRAGMENT_SHADER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT, VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT, VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::PIPELINE_STAGE_ALL_GRAPHICS_BIT, VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT)); + +// RDD::BarrierAccessBits == VkAccessFlagBits. +static_assert(ENUM_MEMBERS_EQUAL(RDD::BARRIER_ACCESS_INDIRECT_COMMAND_READ_BIT, VK_ACCESS_INDIRECT_COMMAND_READ_BIT)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::BARRIER_ACCESS_INDEX_READ_BIT, VK_ACCESS_INDEX_READ_BIT)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::BARRIER_ACCESS_VERTEX_ATTRIBUTE_READ_BIT, VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::BARRIER_ACCESS_UNIFORM_READ_BIT, VK_ACCESS_UNIFORM_READ_BIT)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::BARRIER_ACCESS_INPUT_ATTACHMENT_READ_BIT, VK_ACCESS_INPUT_ATTACHMENT_READ_BIT)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::BARRIER_ACCESS_SHADER_READ_BIT, VK_ACCESS_SHADER_READ_BIT)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::BARRIER_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_SHADER_WRITE_BIT)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::BARRIER_ACCESS_COLOR_ATTACHMENT_READ_BIT, VK_ACCESS_COLOR_ATTACHMENT_READ_BIT)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::BARRIER_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::BARRIER_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT, VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::BARRIER_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::BARRIER_ACCESS_TRANSFER_READ_BIT, VK_ACCESS_TRANSFER_READ_BIT)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::BARRIER_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::BARRIER_ACCESS_HOST_READ_BIT, VK_ACCESS_HOST_READ_BIT)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::BARRIER_ACCESS_HOST_WRITE_BIT, VK_ACCESS_HOST_WRITE_BIT)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::BARRIER_ACCESS_MEMORY_READ_BIT, VK_ACCESS_MEMORY_READ_BIT)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::BARRIER_ACCESS_MEMORY_WRITE_BIT, VK_ACCESS_MEMORY_WRITE_BIT)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::BARRIER_ACCESS_FRAGMENT_SHADING_RATE_ATTACHMENT_READ_BIT, VK_ACCESS_FRAGMENT_SHADING_RATE_ATTACHMENT_READ_BIT_KHR)); + +void RenderingDeviceDriverVulkan::command_pipeline_barrier( + CommandBufferID p_cmd_buffer, + BitField p_src_stages, + BitField p_dst_stages, + VectorView p_memory_barriers, + VectorView p_buffer_barriers, + VectorView p_texture_barriers) { + VkMemoryBarrier *vk_memory_barriers = ALLOCA_ARRAY(VkMemoryBarrier, p_memory_barriers.size()); + for (uint32_t i = 0; i < p_memory_barriers.size(); i++) { + vk_memory_barriers[i] = {}; + vk_memory_barriers[i].sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER; + vk_memory_barriers[i].srcAccessMask = (VkPipelineStageFlags)p_memory_barriers[i].src_access; + vk_memory_barriers[i].dstAccessMask = (VkAccessFlags)p_memory_barriers[i].dst_access; + } + + VkBufferMemoryBarrier *vk_buffer_barriers = ALLOCA_ARRAY(VkBufferMemoryBarrier, p_buffer_barriers.size()); + for (uint32_t i = 0; i < p_buffer_barriers.size(); i++) { + vk_buffer_barriers[i] = {}; + vk_buffer_barriers[i].sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER; + vk_buffer_barriers[i].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + vk_buffer_barriers[i].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + vk_buffer_barriers[i].srcAccessMask = (VkAccessFlags)p_buffer_barriers[i].src_access; + vk_buffer_barriers[i].dstAccessMask = (VkAccessFlags)p_buffer_barriers[i].dst_access; + vk_buffer_barriers[i].buffer = (VkBuffer)p_buffer_barriers[i].buffer.id; + vk_buffer_barriers[i].offset = p_buffer_barriers[i].offset; + vk_buffer_barriers[i].size = p_buffer_barriers[i].size; + } + + VkImageMemoryBarrier *vk_image_barriers = ALLOCA_ARRAY(VkImageMemoryBarrier, p_texture_barriers.size()); + for (uint32_t i = 0; i < p_texture_barriers.size(); i++) { + TextureInfo &ti = textures.get((VkImageView)p_texture_barriers[i].texture.id); + vk_image_barriers[i] = {}; + vk_image_barriers[i].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; + vk_image_barriers[i].srcAccessMask = (VkAccessFlags)p_texture_barriers[i].src_access; + vk_image_barriers[i].dstAccessMask = (VkAccessFlags)p_texture_barriers[i].dst_access; + vk_image_barriers[i].oldLayout = (VkImageLayout)p_texture_barriers[i].prev_layout; + vk_image_barriers[i].newLayout = (VkImageLayout)p_texture_barriers[i].next_layout; + vk_image_barriers[i].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + vk_image_barriers[i].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + vk_image_barriers[i].image = ti.vk_image; + vk_image_barriers[i].subresourceRange.aspectMask = (VkImageAspectFlags)p_texture_barriers[i].subresources.aspect; + vk_image_barriers[i].subresourceRange.baseMipLevel = p_texture_barriers[i].subresources.base_mipmap; + vk_image_barriers[i].subresourceRange.levelCount = p_texture_barriers[i].subresources.mipmap_count; + vk_image_barriers[i].subresourceRange.baseArrayLayer = p_texture_barriers[i].subresources.base_layer; + vk_image_barriers[i].subresourceRange.layerCount = p_texture_barriers[i].subresources.layer_count; + } + + vkCmdPipelineBarrier( + (VkCommandBuffer)p_cmd_buffer.id, + (VkPipelineStageFlags)p_src_stages, + (VkPipelineStageFlags)p_dst_stages, + 0, + p_memory_barriers.size(), vk_memory_barriers, + p_buffer_barriers.size(), vk_buffer_barriers, + p_texture_barriers.size(), vk_image_barriers); +} + +/*************************/ +/**** COMMAND BUFFERS ****/ +/*************************/ + +// ----- POOL ----- + +RDD::CommandPoolID RenderingDeviceDriverVulkan::command_pool_create() { + VkCommandPoolCreateInfo cmd_pool_info = {}; + cmd_pool_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; + cmd_pool_info.queueFamilyIndex = context->get_graphics_queue_family_index(); + cmd_pool_info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; + + VkCommandPool vk_cmd_pool = VK_NULL_HANDLE; + VkResult res = vkCreateCommandPool(vk_device, &cmd_pool_info, nullptr, &vk_cmd_pool); + ERR_FAIL_COND_V_MSG(res, CommandPoolID(), "vkCreateCommandPool failed with error " + itos(res) + "."); + + return CommandPoolID(vk_cmd_pool); +} + +void RenderingDeviceDriverVulkan::command_pool_free(CommandPoolID p_cmd_pool) { + vkDestroyCommandPool(vk_device, (VkCommandPool)p_cmd_pool.id, nullptr); +} + +// ----- BUFFER ----- + +RDD::CommandBufferID RenderingDeviceDriverVulkan::command_buffer_create(CommandBufferType p_cmd_buffer_type, CommandPoolID p_cmd_pool) { + VkCommandBufferAllocateInfo cmd_buf_info = {}; + cmd_buf_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; + cmd_buf_info.commandPool = (VkCommandPool)p_cmd_pool.id; + switch (p_cmd_buffer_type) { + case COMMAND_BUFFER_TYPE_PRIMARY: { + cmd_buf_info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; + } break; + case COMMAND_BUFFER_TYPE_SECONDARY: { + cmd_buf_info.level = VK_COMMAND_BUFFER_LEVEL_SECONDARY; + } break; + } + cmd_buf_info.commandBufferCount = 1; + + VkCommandBuffer vk_cmd_buffer = VK_NULL_HANDLE; + VkResult err = vkAllocateCommandBuffers(vk_device, &cmd_buf_info, &vk_cmd_buffer); + ERR_FAIL_COND_V_MSG(err, CommandBufferID(), "vkAllocateCommandBuffers failed with error " + itos(err) + "."); + + return CommandBufferID(vk_cmd_buffer); +} + +bool RenderingDeviceDriverVulkan::command_buffer_begin(CommandBufferID p_cmd_buffer) { + // Reset is implicit (VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT). + + VkCommandBufferBeginInfo cmd_buf_begin_info = {}; + cmd_buf_begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; + cmd_buf_begin_info.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; + + VkResult err = vkBeginCommandBuffer((VkCommandBuffer)p_cmd_buffer.id, &cmd_buf_begin_info); + ERR_FAIL_COND_V_MSG(err, false, "vkBeginCommandBuffer failed with error " + itos(err) + "."); + + return true; +} + +bool RenderingDeviceDriverVulkan::command_buffer_begin_secondary(CommandBufferID p_cmd_buffer, RenderPassID p_render_pass, uint32_t p_subpass, FramebufferID p_framebuffer) { + // Reset is implicit (VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT). + + VkCommandBufferInheritanceInfo inheritance_info = {}; + inheritance_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_INFO; + inheritance_info.renderPass = (VkRenderPass)p_render_pass.id; + inheritance_info.subpass = p_subpass; + inheritance_info.framebuffer = (VkFramebuffer)p_framebuffer.id; + + VkCommandBufferBeginInfo cmd_buf_begin_info = {}; + cmd_buf_begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; + cmd_buf_begin_info.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT | VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT; + cmd_buf_begin_info.pInheritanceInfo = &inheritance_info; + + VkResult err = vkBeginCommandBuffer((VkCommandBuffer)p_cmd_buffer.id, &cmd_buf_begin_info); + ERR_FAIL_COND_V_MSG(err, false, "vkBeginCommandBuffer failed with error " + itos(err) + "."); + + return true; +} + +void RenderingDeviceDriverVulkan::command_buffer_end(CommandBufferID p_cmd_buffer) { + vkEndCommandBuffer((VkCommandBuffer)p_cmd_buffer.id); +} + +void RenderingDeviceDriverVulkan::command_buffer_execute_secondary(CommandBufferID p_cmd_buffer, VectorView p_secondary_cmd_buffers) { + vkCmdExecuteCommands((VkCommandBuffer)p_cmd_buffer.id, p_secondary_cmd_buffers.size(), (const VkCommandBuffer *)p_secondary_cmd_buffers.ptr()); +} + +/******************/ +/**** TRANSFER ****/ +/******************/ + +static_assert(ARRAYS_COMPATIBLE_FIELDWISE(RDD::BufferCopyRegion, VkBufferCopy)); + +static void _texture_subresource_range_to_vk(const RDD::TextureSubresourceRange &p_subresources, VkImageSubresourceRange *r_vk_subreources) { + *r_vk_subreources = {}; + r_vk_subreources->aspectMask = (VkImageAspectFlags)p_subresources.aspect; + r_vk_subreources->baseMipLevel = p_subresources.base_mipmap; + r_vk_subreources->levelCount = p_subresources.mipmap_count; + r_vk_subreources->baseArrayLayer = p_subresources.base_layer; + r_vk_subreources->layerCount = p_subresources.layer_count; +} + +static void _texture_subresource_layers_to_vk(const RDD::TextureSubresourceLayers &p_subresources, VkImageSubresourceLayers *r_vk_subreources) { + *r_vk_subreources = {}; + r_vk_subreources->aspectMask = (VkImageAspectFlags)p_subresources.aspect; + r_vk_subreources->mipLevel = p_subresources.mipmap; + r_vk_subreources->baseArrayLayer = p_subresources.base_layer; + r_vk_subreources->layerCount = p_subresources.layer_count; +} + +static void _buffer_texture_copy_region_to_vk(const RDD::BufferTextureCopyRegion &p_copy_region, VkBufferImageCopy *r_vk_copy_region) { + *r_vk_copy_region = {}; + r_vk_copy_region->bufferOffset = p_copy_region.buffer_offset; + r_vk_copy_region->bufferRowLength = p_copy_region.buffer_row_length; + r_vk_copy_region->bufferImageHeight = p_copy_region.buffer_texture_height; + _texture_subresource_layers_to_vk(p_copy_region.texture_subresources, &r_vk_copy_region->imageSubresource); + r_vk_copy_region->imageOffset.x = p_copy_region.texture_offset.x; + r_vk_copy_region->imageOffset.y = p_copy_region.texture_offset.y; + r_vk_copy_region->imageOffset.z = p_copy_region.texture_offset.z; + r_vk_copy_region->imageExtent.width = p_copy_region.texture_region_size.x; + r_vk_copy_region->imageExtent.height = p_copy_region.texture_region_size.y; + r_vk_copy_region->imageExtent.depth = p_copy_region.texture_region_size.z; +} + +static void _texture_copy_region_to_vk(const RDD::TextureCopyRegion &p_copy_region, VkImageCopy *r_vk_copy_region) { + *r_vk_copy_region = {}; + _texture_subresource_layers_to_vk(p_copy_region.src_subresources, &r_vk_copy_region->srcSubresource); + r_vk_copy_region->srcOffset.x = p_copy_region.src_offset.x; + r_vk_copy_region->srcOffset.y = p_copy_region.src_offset.y; + r_vk_copy_region->srcOffset.z = p_copy_region.src_offset.z; + _texture_subresource_layers_to_vk(p_copy_region.dst_subresources, &r_vk_copy_region->dstSubresource); + r_vk_copy_region->dstOffset.x = p_copy_region.dst_offset.x; + r_vk_copy_region->dstOffset.y = p_copy_region.dst_offset.y; + r_vk_copy_region->dstOffset.z = p_copy_region.dst_offset.z; + r_vk_copy_region->extent.width = p_copy_region.size.x; + r_vk_copy_region->extent.height = p_copy_region.size.y; + r_vk_copy_region->extent.depth = p_copy_region.size.z; +} + +void RenderingDeviceDriverVulkan::command_clear_buffer(CommandBufferID p_cmd_buffer, BufferID p_buffer, uint64_t p_offset, uint64_t p_size) { + vkCmdFillBuffer((VkCommandBuffer)p_cmd_buffer.id, (VkBuffer)p_buffer.id, p_offset, p_size, 0); +} + +void RenderingDeviceDriverVulkan::command_copy_buffer(CommandBufferID p_cmd_buffer, BufferID p_src_buffer, BufferID p_dst_buffer, VectorView p_regions) { + vkCmdCopyBuffer((VkCommandBuffer)p_cmd_buffer.id, (VkBuffer)p_src_buffer.id, (VkBuffer)p_dst_buffer.id, p_regions.size(), (const VkBufferCopy *)p_regions.ptr()); +} + +void RenderingDeviceDriverVulkan::command_copy_texture(CommandBufferID p_cmd_buffer, TextureID p_src_texture, TextureLayout p_src_texture_layout, TextureID p_dst_texture, TextureLayout p_dst_texture_layout, VectorView p_regions) { + VkImageCopy *vk_copy_regions = ALLOCA_ARRAY(VkImageCopy, p_regions.size()); + for (uint32_t i = 0; i < p_regions.size(); i++) { + _texture_copy_region_to_vk(p_regions[i], &vk_copy_regions[i]); + } + + TextureInfo &src_ti = textures.get((VkImageView)p_src_texture.id); + TextureInfo &dst_ti = textures.get((VkImageView)p_dst_texture.id); + vkCmdCopyImage((VkCommandBuffer)p_cmd_buffer.id, src_ti.vk_image, (VkImageLayout)p_src_texture_layout, dst_ti.vk_image, (VkImageLayout)p_dst_texture_layout, p_regions.size(), vk_copy_regions); +} + +void RenderingDeviceDriverVulkan::command_resolve_texture(CommandBufferID p_cmd_buffer, TextureID p_src_texture, TextureLayout p_src_texture_layout, TextureID p_dst_texture, TextureLayout p_dst_texture_layout, VectorView p_regions) { + VkImageCopy *vk_copy_regions = ALLOCA_ARRAY(VkImageCopy, p_regions.size()); + for (uint32_t i = 0; i < p_regions.size(); i++) { + _texture_copy_region_to_vk(p_regions[i], &vk_copy_regions[i]); + } + + TextureInfo &src_ti = textures.get((VkImageView)p_src_texture.id); + TextureInfo &dst_ti = textures.get((VkImageView)p_dst_texture.id); + ARRAYS_COMPATIBLE_FIELDWISE(VkImageResolve, VkImageCopy); + vkCmdResolveImage((VkCommandBuffer)p_cmd_buffer.id, src_ti.vk_image, (VkImageLayout)p_src_texture_layout, dst_ti.vk_image, (VkImageLayout)p_dst_texture_layout, p_regions.size(), (VkImageResolve *)vk_copy_regions); +} + +void RenderingDeviceDriverVulkan::command_clear_color_texture(CommandBufferID p_cmd_buffer, TextureID p_texture, TextureLayout p_texture_layout, const Color &p_color, const TextureSubresourceRange &p_subresources) { + VkClearColorValue vk_color = {}; + memcpy(&vk_color.float32, p_color.components, sizeof(VkClearColorValue::float32)); + + VkImageSubresourceRange vk_subresources = {}; + _texture_subresource_range_to_vk(p_subresources, &vk_subresources); + + TextureInfo &ti = textures.get((VkImageView)p_texture.id); + vkCmdClearColorImage((VkCommandBuffer)p_cmd_buffer.id, ti.vk_image, (VkImageLayout)p_texture_layout, &vk_color, 1, &vk_subresources); +} + +void RenderingDeviceDriverVulkan::command_copy_buffer_to_texture(CommandBufferID p_cmd_buffer, BufferID p_src_buffer, TextureID p_dst_texture, TextureLayout p_dst_texture_layout, VectorView p_regions) { + VkBufferImageCopy *vk_copy_regions = ALLOCA_ARRAY(VkBufferImageCopy, p_regions.size()); + for (uint32_t i = 0; i < p_regions.size(); i++) { + _buffer_texture_copy_region_to_vk(p_regions[i], &vk_copy_regions[i]); + } + + TextureInfo &ti = textures.get((VkImageView)p_dst_texture.id); + vkCmdCopyBufferToImage((VkCommandBuffer)p_cmd_buffer.id, (VkBuffer)p_src_buffer.id, ti.vk_image, (VkImageLayout)p_dst_texture_layout, p_regions.size(), vk_copy_regions); +} + +void RenderingDeviceDriverVulkan::command_copy_texture_to_buffer(CommandBufferID p_cmd_buffer, TextureID p_src_texture, TextureLayout p_src_texture_layout, BufferID p_dst_buffer, VectorView p_regions) { + VkBufferImageCopy *vk_copy_regions = ALLOCA_ARRAY(VkBufferImageCopy, p_regions.size()); + for (uint32_t i = 0; i < p_regions.size(); i++) { + _buffer_texture_copy_region_to_vk(p_regions[i], &vk_copy_regions[i]); + } + + TextureInfo &ti = textures.get((VkImageView)p_src_texture.id); + vkCmdCopyImageToBuffer((VkCommandBuffer)p_cmd_buffer.id, ti.vk_image, (VkImageLayout)p_src_texture_layout, (VkBuffer)p_dst_buffer.id, p_regions.size(), vk_copy_regions); +} + +/******************/ +/**** PIPELINE ****/ +/******************/ + +void RenderingDeviceDriverVulkan::pipeline_free(PipelineID p_pipeline_id) { + vkDestroyPipeline(vk_device, (VkPipeline)p_pipeline_id.id, nullptr); +} + +// ----- BINDING ----- + +void RenderingDeviceDriverVulkan::command_bind_push_constants(CommandBufferID p_cmd_buffer, ShaderID p_shader, uint32_t p_dst_first_index, VectorView p_data) { + const ShaderInfo &si = ((RBSet::Element *)p_shader.id)->get(); + vkCmdPushConstants((VkCommandBuffer)p_cmd_buffer.id, si.vk_pipeline_layout, si.vk_push_constant_stages, p_dst_first_index * sizeof(uint32_t), p_data.size() * sizeof(uint32_t), p_data.ptr()); +} + +// ----- CACHE ----- + +int RenderingDeviceDriverVulkan::caching_instance_count = 0; + +bool RenderingDeviceDriverVulkan::pipeline_cache_create(const Vector &p_data) { + if (caching_instance_count) { + WARN_PRINT("There's already a RenderingDeviceDriverVulkan instance doing PSO caching. Only one can at the same time. This one won't."); + return false; + } + caching_instance_count++; + + pipelines_cache.current_size = 0; + pipelines_cache.buffer.resize(sizeof(PipelineCacheHeader)); + + // Parse. + { + if (p_data.size() <= (int)sizeof(PipelineCacheHeader)) { + WARN_PRINT("Invalid/corrupt pipelines cache."); + } else { + const PipelineCacheHeader *loaded_header = reinterpret_cast(p_data.ptr()); + if (loaded_header->magic != 868 + VK_PIPELINE_CACHE_HEADER_VERSION_ONE) { + WARN_PRINT("Invalid pipelines cache magic number."); + } + const uint8_t *loaded_buffer_start = p_data.ptr() + sizeof(PipelineCacheHeader); + uint32_t loaded_buffer_size = p_data.size() - sizeof(PipelineCacheHeader); + const PipelineCacheHeader *current_header = (PipelineCacheHeader *)pipelines_cache.buffer.ptr(); + if (loaded_header->data_hash != hash_murmur3_buffer(loaded_buffer_start, loaded_buffer_size) || + loaded_header->data_size != loaded_buffer_size || + loaded_header->vendor_id != current_header->vendor_id || + loaded_header->device_id != current_header->device_id || + loaded_header->driver_version != current_header->driver_version || + memcmp(loaded_header->uuid, current_header->uuid, VK_UUID_SIZE) != 0 || + loaded_header->driver_abi != current_header->driver_abi) { + WARN_PRINT("Invalid pipelines cache header."); + pipelines_cache.current_size = loaded_buffer_size; + pipelines_cache.buffer = p_data; + } + } + } + + // Create. + { + VkPipelineCacheCreateInfo cache_info = {}; + cache_info.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO; + if (context->get_pipeline_cache_control_support()) { + cache_info.flags = VK_PIPELINE_CACHE_CREATE_EXTERNALLY_SYNCHRONIZED_BIT; + } + cache_info.initialDataSize = pipelines_cache.buffer.size() - sizeof(PipelineCacheHeader); + cache_info.pInitialData = pipelines_cache.buffer.ptr() + sizeof(PipelineCacheHeader); + + VkResult err = vkCreatePipelineCache(vk_device, &cache_info, nullptr, &pipelines_cache.vk_cache); + if (err != VK_SUCCESS) { + WARN_PRINT("vkCreatePipelinecache failed with error " + itos(err) + "."); + return false; + } + } + + return true; +} + +void RenderingDeviceDriverVulkan::pipeline_cache_free() { + DEV_ASSERT(pipelines_cache.vk_cache); + + vkDestroyPipelineCache(vk_device, pipelines_cache.vk_cache, nullptr); + + DEV_ASSERT(caching_instance_count > 0); + caching_instance_count--; +} + +size_t RenderingDeviceDriverVulkan::pipeline_cache_query_size() { + DEV_ASSERT(pipelines_cache.vk_cache); + + // FIXME: + // We're letting the cache grow unboundedly. We may want to set at limit and see if implementations use LRU or the like. + // If we do, we won't be able to assume any longer that the cache is dirty if, and only if, it has grown. + VkResult err = vkGetPipelineCacheData(vk_device, pipelines_cache.vk_cache, &pipelines_cache.current_size, nullptr); + ERR_FAIL_COND_V_MSG(err, 0, "vkGetPipelineCacheData failed with error " + itos(err) + "."); + + return pipelines_cache.current_size; +} + +Vector RenderingDeviceDriverVulkan::pipeline_cache_serialize() { + DEV_ASSERT(pipelines_cache.vk_cache); + + pipelines_cache.buffer.resize(pipelines_cache.current_size + sizeof(PipelineCacheHeader)); + + VkResult err = vkGetPipelineCacheData(vk_device, pipelines_cache.vk_cache, &pipelines_cache.current_size, pipelines_cache.buffer.ptrw()); + ERR_FAIL_COND_V(err != VK_SUCCESS && err != VK_INCOMPLETE, Vector()); // Incomplete is OK because the cache may have grown since the size was queried (unless when exiting). + + // The real buffer size may now be bigger than the updated current_size. + // We take into account the new size but keep the buffer resized in a worst-case fashion. + + PipelineCacheHeader *header = (PipelineCacheHeader *)pipelines_cache.buffer.ptrw(); + header->data_size = pipelines_cache.current_size; + header->data_hash = hash_murmur3_buffer(pipelines_cache.buffer.ptr() + sizeof(PipelineCacheHeader), pipelines_cache.current_size); + + return pipelines_cache.buffer; +} + +/*******************/ +/**** RENDERING ****/ +/*******************/ + +// ----- SUBPASS ----- + +// RDD::AttachmentLoadOp == VkAttachmentLoadOp. +static_assert(ENUM_MEMBERS_EQUAL(RDD::ATTACHMENT_LOAD_OP_LOAD, VK_ATTACHMENT_LOAD_OP_LOAD)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::ATTACHMENT_LOAD_OP_CLEAR, VK_ATTACHMENT_LOAD_OP_CLEAR)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::ATTACHMENT_LOAD_OP_DONT_CARE, VK_ATTACHMENT_LOAD_OP_DONT_CARE)); + +// RDD::AttachmentStoreOp == VkAttachmentStoreOp. +static_assert(ENUM_MEMBERS_EQUAL(RDD::ATTACHMENT_STORE_OP_STORE, VK_ATTACHMENT_STORE_OP_STORE)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::ATTACHMENT_STORE_OP_DONT_CARE, VK_ATTACHMENT_STORE_OP_DONT_CARE)); + +// Assuming Vulkan and RDD's are backed by uint32_t in: +// - VkSubpassDescription2::pPreserveAttachments and RDD::Subpass::preserve_attachments. +// - VkRenderPassCreateInfo2KHR::pCorrelatedViewMasks and p_view_correlation_mask. + +static void _attachment_reference_to_vk(const RDD::AttachmentReference &p_attachment_reference, VkAttachmentReference2KHR *r_vk_attachment_reference) { + *r_vk_attachment_reference = {}; + r_vk_attachment_reference->sType = VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2_KHR; + r_vk_attachment_reference->attachment = p_attachment_reference.attachment; + r_vk_attachment_reference->layout = (VkImageLayout)p_attachment_reference.layout; + r_vk_attachment_reference->aspectMask = (VkImageAspectFlags)p_attachment_reference.aspect; +} + +RDD::RenderPassID RenderingDeviceDriverVulkan::render_pass_create(VectorView p_attachments, VectorView p_subpasses, VectorView p_subpass_dependencies, uint32_t p_view_count) { + // These are only used if we use multiview but we need to define them in scope. + const uint32_t view_mask = (1 << p_view_count) - 1; + const uint32_t correlation_mask = (1 << p_view_count) - 1; + + VkAttachmentDescription2KHR *vk_attachments = ALLOCA_ARRAY(VkAttachmentDescription2KHR, p_attachments.size()); + for (uint32_t i = 0; i < p_attachments.size(); i++) { + vk_attachments[i] = {}; + vk_attachments[i].sType = VK_STRUCTURE_TYPE_ATTACHMENT_DESCRIPTION_2_KHR; + vk_attachments[i].format = RD_TO_VK_FORMAT[p_attachments[i].format]; + vk_attachments[i].samples = _ensure_supported_sample_count(p_attachments[i].samples); + vk_attachments[i].loadOp = (VkAttachmentLoadOp)p_attachments[i].load_op; + vk_attachments[i].storeOp = (VkAttachmentStoreOp)p_attachments[i].store_op; + vk_attachments[i].stencilLoadOp = (VkAttachmentLoadOp)p_attachments[i].stencil_load_op; + vk_attachments[i].stencilStoreOp = (VkAttachmentStoreOp)p_attachments[i].stencil_store_op; + vk_attachments[i].initialLayout = (VkImageLayout)p_attachments[i].initial_layout; + vk_attachments[i].finalLayout = (VkImageLayout)p_attachments[i].final_layout; + } + + VkSubpassDescription2KHR *vk_subpasses = ALLOCA_ARRAY(VkSubpassDescription2KHR, p_subpasses.size()); + for (uint32_t i = 0; i < p_subpasses.size(); i++) { + VkAttachmentReference2KHR *vk_subpass_input_attachments = ALLOCA_ARRAY(VkAttachmentReference2KHR, p_subpasses[i].input_references.size()); + for (uint32_t j = 0; j < p_subpasses[i].input_references.size(); j++) { + _attachment_reference_to_vk(p_subpasses[i].input_references[j], &vk_subpass_input_attachments[j]); + } + + VkAttachmentReference2KHR *vk_subpass_color_attachments = ALLOCA_ARRAY(VkAttachmentReference2KHR, p_subpasses[i].color_references.size()); + for (uint32_t j = 0; j < p_subpasses[i].color_references.size(); j++) { + _attachment_reference_to_vk(p_subpasses[i].color_references[j], &vk_subpass_color_attachments[j]); + } + + VkAttachmentReference2KHR *vk_subpass_resolve_attachments = ALLOCA_ARRAY(VkAttachmentReference2KHR, p_subpasses[i].resolve_references.size()); + for (uint32_t j = 0; j < p_subpasses[i].resolve_references.size(); j++) { + _attachment_reference_to_vk(p_subpasses[i].resolve_references[j], &vk_subpass_resolve_attachments[j]); + } + + VkAttachmentReference2KHR *vk_subpass_depth_stencil_attachment = nullptr; + if (p_subpasses[i].depth_stencil_reference.attachment != AttachmentReference::UNUSED) { + vk_subpass_depth_stencil_attachment = ALLOCA_SINGLE(VkAttachmentReference2KHR); + _attachment_reference_to_vk(p_subpasses[i].depth_stencil_reference, vk_subpass_depth_stencil_attachment); + } + + vk_subpasses[i] = {}; + vk_subpasses[i].sType = VK_STRUCTURE_TYPE_SUBPASS_DESCRIPTION_2_KHR; + vk_subpasses[i].pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; + vk_subpasses[i].viewMask = p_view_count == 1 ? 0 : view_mask; + vk_subpasses[i].inputAttachmentCount = p_subpasses[i].input_references.size(); + vk_subpasses[i].pInputAttachments = vk_subpass_input_attachments; + vk_subpasses[i].colorAttachmentCount = p_subpasses[i].color_references.size(); + vk_subpasses[i].pColorAttachments = vk_subpass_color_attachments; + vk_subpasses[i].pResolveAttachments = vk_subpass_resolve_attachments; + vk_subpasses[i].pDepthStencilAttachment = vk_subpass_depth_stencil_attachment; + vk_subpasses[i].preserveAttachmentCount = p_subpasses[i].preserve_attachments.size(); + vk_subpasses[i].pPreserveAttachments = p_subpasses[i].preserve_attachments.ptr(); + + // VRS. + if (context->get_vrs_capabilities().attachment_vrs_supported && p_subpasses[i].vrs_reference.attachment != AttachmentReference::UNUSED) { + VkAttachmentReference2KHR *vk_subpass_vrs_attachment = ALLOCA_SINGLE(VkAttachmentReference2KHR); + *vk_subpass_vrs_attachment = {}; + vk_subpass_vrs_attachment->sType = VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2_KHR; + vk_subpass_vrs_attachment->attachment = p_subpasses[i].vrs_reference.attachment; + vk_subpass_vrs_attachment->layout = VK_IMAGE_LAYOUT_FRAGMENT_SHADING_RATE_ATTACHMENT_OPTIMAL_KHR; + + VkFragmentShadingRateAttachmentInfoKHR *vk_vrs_info = ALLOCA_SINGLE(VkFragmentShadingRateAttachmentInfoKHR); + *vk_vrs_info = {}; + vk_vrs_info->sType = VK_STRUCTURE_TYPE_FRAGMENT_SHADING_RATE_ATTACHMENT_INFO_KHR; + vk_vrs_info->pFragmentShadingRateAttachment = vk_subpass_vrs_attachment; + vk_vrs_info->shadingRateAttachmentTexelSize.width = context->get_vrs_capabilities().texel_size.x; + vk_vrs_info->shadingRateAttachmentTexelSize.height = context->get_vrs_capabilities().texel_size.y; + + vk_subpasses[i].pNext = vk_vrs_info; + } + } + + VkSubpassDependency2KHR *vk_subpass_dependencies = ALLOCA_ARRAY(VkSubpassDependency2KHR, p_subpass_dependencies.size()); + for (uint32_t i = 0; i < p_subpass_dependencies.size(); i++) { + vk_subpass_dependencies[i] = {}; + vk_subpass_dependencies[i].srcSubpass = p_subpass_dependencies[i].src_subpass; + vk_subpass_dependencies[i].dstSubpass = p_subpass_dependencies[i].dst_subpass; + vk_subpass_dependencies[i].srcStageMask = (VkPipelineStageFlags)p_subpass_dependencies[i].src_stages; + vk_subpass_dependencies[i].dstStageMask = (VkPipelineStageFlags)p_subpass_dependencies[i].dst_stages; + vk_subpass_dependencies[i].srcAccessMask = (VkAccessFlags)p_subpass_dependencies[i].src_access; + vk_subpass_dependencies[i].dstAccessMask = (VkAccessFlags)p_subpass_dependencies[i].dst_access; + } + + VkRenderPassCreateInfo2KHR create_info = {}; + create_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO_2_KHR; + create_info.attachmentCount = p_attachments.size(); + create_info.pAttachments = vk_attachments; + create_info.subpassCount = p_subpasses.size(); + create_info.pSubpasses = vk_subpasses; + create_info.dependencyCount = p_subpass_dependencies.size(); + create_info.pDependencies = vk_subpass_dependencies; + create_info.correlatedViewMaskCount = p_view_count == 1 ? 0 : 1; + create_info.pCorrelatedViewMasks = p_view_count == 1 ? nullptr : &correlation_mask; + + // Multiview. + if (p_view_count > 1 && !context->supports_renderpass2()) { + // This is only required when using vkCreateRenderPass. + // We add it if vkCreateRenderPass2KHR is not supported, + // resulting this in being passed to our vkCreateRenderPass fallback. + + uint32_t *vk_view_masks = ALLOCA_ARRAY(uint32_t, p_subpasses.size()); + for (uint32_t i = 0; i < p_subpasses.size(); i++) { + vk_view_masks[i] = view_mask; + } + + VkRenderPassMultiviewCreateInfo *multiview_create_info = ALLOCA_SINGLE(VkRenderPassMultiviewCreateInfo); + *multiview_create_info = {}; + multiview_create_info->sType = VK_STRUCTURE_TYPE_RENDER_PASS_MULTIVIEW_CREATE_INFO; + multiview_create_info->subpassCount = p_subpasses.size(); + multiview_create_info->pViewMasks = vk_view_masks; + multiview_create_info->correlationMaskCount = 1; + multiview_create_info->pCorrelationMasks = &correlation_mask; + + create_info.pNext = multiview_create_info; + } + + VkRenderPass vk_render_pass = VK_NULL_HANDLE; + VkResult res = context->vkCreateRenderPass2KHR(vk_device, &create_info, nullptr, &vk_render_pass); + ERR_FAIL_COND_V_MSG(res, RenderPassID(), "vkCreateRenderPass2KHR failed with error " + itos(res) + "."); + + return RenderPassID(vk_render_pass); +} + +void RenderingDeviceDriverVulkan::render_pass_free(RenderPassID p_render_pass) { + vkDestroyRenderPass(vk_device, (VkRenderPass)p_render_pass.id, nullptr); +} + +// ----- COMMANDS ----- + +static_assert(ARRAYS_COMPATIBLE_FIELDWISE(RDD::RenderPassClearValue, VkClearValue)); +static_assert(ARRAYS_COMPATIBLE_FIELDWISE(RDD::AttachmentClearRect, VkClearRect)); + +void RenderingDeviceDriverVulkan::command_begin_render_pass(CommandBufferID p_cmd_buffer, RenderPassID p_render_pass, FramebufferID p_framebuffer, CommandBufferType p_cmd_buffer_type, const Rect2i &p_rect, VectorView p_clear_values) { + VkRenderPassBeginInfo render_pass_begin = {}; + render_pass_begin.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; + render_pass_begin.renderPass = (VkRenderPass)p_render_pass.id; + render_pass_begin.framebuffer = (VkFramebuffer)p_framebuffer.id; + + render_pass_begin.renderArea.offset.x = p_rect.position.x; + render_pass_begin.renderArea.offset.y = p_rect.position.y; + render_pass_begin.renderArea.extent.width = p_rect.size.x; + render_pass_begin.renderArea.extent.height = p_rect.size.y; + + render_pass_begin.clearValueCount = p_clear_values.size(); + render_pass_begin.pClearValues = (const VkClearValue *)p_clear_values.ptr(); + + VkSubpassContents vk_subpass_contents = p_cmd_buffer_type == COMMAND_BUFFER_TYPE_PRIMARY ? VK_SUBPASS_CONTENTS_INLINE : VK_SUBPASS_CONTENTS_SECONDARY_COMMAND_BUFFERS; + vkCmdBeginRenderPass((VkCommandBuffer)p_cmd_buffer.id, &render_pass_begin, vk_subpass_contents); +} + +void RenderingDeviceDriverVulkan::command_end_render_pass(CommandBufferID p_cmd_buffer) { + vkCmdEndRenderPass((VkCommandBuffer)p_cmd_buffer.id); +} + +void RenderingDeviceDriverVulkan::command_next_render_subpass(CommandBufferID p_cmd_buffer, CommandBufferType p_cmd_buffer_type) { + VkSubpassContents vk_subpass_contents = p_cmd_buffer_type == COMMAND_BUFFER_TYPE_PRIMARY ? VK_SUBPASS_CONTENTS_INLINE : VK_SUBPASS_CONTENTS_SECONDARY_COMMAND_BUFFERS; + vkCmdNextSubpass((VkCommandBuffer)p_cmd_buffer.id, vk_subpass_contents); +} + +void RenderingDeviceDriverVulkan::command_render_set_viewport(CommandBufferID p_cmd_buffer, VectorView p_viewports) { + VkViewport *vk_viewports = ALLOCA_ARRAY(VkViewport, p_viewports.size()); + for (uint32_t i = 0; i < p_viewports.size(); i++) { + vk_viewports[i] = {}; + vk_viewports[i].x = p_viewports[i].position.x; + vk_viewports[i].y = p_viewports[i].position.y; + vk_viewports[i].width = p_viewports[i].size.x; + vk_viewports[i].height = p_viewports[i].size.y; + vk_viewports[i].minDepth = 0.0f; + vk_viewports[i].maxDepth = 1.0f; + } + vkCmdSetViewport((VkCommandBuffer)p_cmd_buffer.id, 0, p_viewports.size(), vk_viewports); +} + +void RenderingDeviceDriverVulkan::command_render_set_scissor(CommandBufferID p_cmd_buffer, VectorView p_scissors) { + vkCmdSetScissor((VkCommandBuffer)p_cmd_buffer.id, 0, p_scissors.size(), (VkRect2D *)p_scissors.ptr()); +} + +void RenderingDeviceDriverVulkan::command_render_clear_attachments(CommandBufferID p_cmd_buffer, VectorView p_attachment_clears, VectorView p_rects) { + VkClearAttachment *vk_clears = ALLOCA_ARRAY(VkClearAttachment, p_attachment_clears.size()); + for (uint32_t i = 0; i < p_attachment_clears.size(); i++) { + vk_clears[i] = {}; + memcpy(&vk_clears[i].clearValue, &p_attachment_clears[i].value, sizeof(VkClearValue)); + vk_clears[i].colorAttachment = p_attachment_clears[i].color_attachment; + vk_clears[i].aspectMask = p_attachment_clears[i].aspect; + } + + vkCmdClearAttachments((VkCommandBuffer)p_cmd_buffer.id, p_attachment_clears.size(), vk_clears, p_rects.size(), (const VkClearRect *)p_rects.ptr()); +} + +void RenderingDeviceDriverVulkan::command_bind_render_pipeline(CommandBufferID p_cmd_buffer, PipelineID p_pipeline) { + vkCmdBindPipeline((VkCommandBuffer)p_cmd_buffer.id, VK_PIPELINE_BIND_POINT_GRAPHICS, (VkPipeline)p_pipeline.id); +} + +void RenderingDeviceDriverVulkan::command_bind_render_uniform_set(CommandBufferID p_cmd_buffer, UniformSetID p_uniform_set, ShaderID p_shader, uint32_t p_set_index) { + const ShaderInfo &si = ((RBSet::Element *)p_shader.id)->get(); + vkCmdBindDescriptorSets((VkCommandBuffer)p_cmd_buffer.id, VK_PIPELINE_BIND_POINT_GRAPHICS, si.vk_pipeline_layout, p_set_index, 1, (VkDescriptorSet *)&p_uniform_set, 0, nullptr); +} + +void RenderingDeviceDriverVulkan::command_render_draw(CommandBufferID p_cmd_buffer, uint32_t p_vertex_count, uint32_t p_instance_count, uint32_t p_base_vertex, uint32_t p_first_instance) { + vkCmdDraw((VkCommandBuffer)p_cmd_buffer.id, p_vertex_count, p_instance_count, p_base_vertex, p_first_instance); +} + +void RenderingDeviceDriverVulkan::command_render_draw_indexed(CommandBufferID p_cmd_buffer, uint32_t p_index_count, uint32_t p_instance_count, uint32_t p_first_index, int32_t p_vertex_offset, uint32_t p_first_instance) { + vkCmdDrawIndexed((VkCommandBuffer)p_cmd_buffer.id, p_index_count, p_instance_count, p_first_index, p_vertex_offset, p_first_instance); +} + +void RenderingDeviceDriverVulkan::command_render_draw_indexed_indirect(CommandBufferID p_cmd_buffer, BufferID p_indirect_buffer, uint64_t p_offset, uint32_t p_draw_count, uint32_t p_stride) { + vkCmdDrawIndexedIndirect((VkCommandBuffer)p_cmd_buffer.id, (VkBuffer)p_indirect_buffer.id, p_offset, p_draw_count, p_stride); +} + +void RenderingDeviceDriverVulkan::command_render_draw_indexed_indirect_count(CommandBufferID p_cmd_buffer, BufferID p_indirect_buffer, uint64_t p_offset, BufferID p_count_buffer, uint64_t p_count_buffer_offset, uint32_t p_max_draw_count, uint32_t p_stride) { + vkCmdDrawIndexedIndirectCount((VkCommandBuffer)p_cmd_buffer.id, (VkBuffer)p_indirect_buffer.id, p_offset, (VkBuffer)p_count_buffer.id, p_count_buffer_offset, p_max_draw_count, p_stride); +} + +void RenderingDeviceDriverVulkan::command_render_draw_indirect(CommandBufferID p_cmd_buffer, BufferID p_indirect_buffer, uint64_t p_offset, uint32_t p_draw_count, uint32_t p_stride) { + vkCmdDrawIndirect((VkCommandBuffer)p_cmd_buffer.id, (VkBuffer)p_indirect_buffer.id, p_offset, p_draw_count, p_stride); +} + +void RenderingDeviceDriverVulkan::command_render_draw_indirect_count(CommandBufferID p_cmd_buffer, BufferID p_indirect_buffer, uint64_t p_offset, BufferID p_count_buffer, uint64_t p_count_buffer_offset, uint32_t p_max_draw_count, uint32_t p_stride) { + vkCmdDrawIndirectCount((VkCommandBuffer)p_cmd_buffer.id, (VkBuffer)p_indirect_buffer.id, p_offset, (VkBuffer)p_count_buffer.id, p_count_buffer_offset, p_max_draw_count, p_stride); +} + +void RenderingDeviceDriverVulkan::command_render_bind_vertex_buffers(CommandBufferID p_cmd_buffer, uint32_t p_binding_count, const BufferID *p_buffers, const uint64_t *p_offsets) { + vkCmdBindVertexBuffers((VkCommandBuffer)p_cmd_buffer.id, 0, p_binding_count, (const VkBuffer *)p_buffers, p_offsets); +} + +void RenderingDeviceDriverVulkan::command_render_bind_index_buffer(CommandBufferID p_cmd_buffer, BufferID p_buffer, IndexBufferFormat p_format, uint64_t p_offset) { + vkCmdBindIndexBuffer((VkCommandBuffer)p_cmd_buffer.id, (VkBuffer)p_buffer.id, p_offset, p_format == INDEX_BUFFER_FORMAT_UINT16 ? VK_INDEX_TYPE_UINT16 : VK_INDEX_TYPE_UINT32); +} + +void RenderingDeviceDriverVulkan::command_render_set_blend_constants(CommandBufferID p_cmd_buffer, const Color &p_constants) { + vkCmdSetBlendConstants((VkCommandBuffer)p_cmd_buffer.id, p_constants.components); +} + +void RenderingDeviceDriverVulkan::command_render_set_line_width(CommandBufferID p_cmd_buffer, float p_width) { + vkCmdSetLineWidth((VkCommandBuffer)p_cmd_buffer.id, p_width); +} + +// ----- PIPELINE ----- + +static const VkPrimitiveTopology RD_TO_VK_PRIMITIVE[RDD::RENDER_PRIMITIVE_MAX] = { + VK_PRIMITIVE_TOPOLOGY_POINT_LIST, + VK_PRIMITIVE_TOPOLOGY_LINE_LIST, + VK_PRIMITIVE_TOPOLOGY_LINE_LIST_WITH_ADJACENCY, + VK_PRIMITIVE_TOPOLOGY_LINE_STRIP, + VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY, + VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, + VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY, + VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP, + VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY, + VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP, + VK_PRIMITIVE_TOPOLOGY_PATCH_LIST, +}; + +// RDD::PolygonCullMode == VkCullModeFlagBits. +static_assert(ENUM_MEMBERS_EQUAL(RDD::POLYGON_CULL_DISABLED, VK_CULL_MODE_NONE)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::POLYGON_CULL_FRONT, VK_CULL_MODE_FRONT_BIT)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::POLYGON_CULL_BACK, VK_CULL_MODE_BACK_BIT)); + +// RDD::StencilOperation == VkStencilOp. +static_assert(ENUM_MEMBERS_EQUAL(RDD::STENCIL_OP_KEEP, VK_STENCIL_OP_KEEP)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::STENCIL_OP_ZERO, VK_STENCIL_OP_ZERO)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::STENCIL_OP_REPLACE, VK_STENCIL_OP_REPLACE)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::STENCIL_OP_INCREMENT_AND_CLAMP, VK_STENCIL_OP_INCREMENT_AND_CLAMP)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::STENCIL_OP_DECREMENT_AND_CLAMP, VK_STENCIL_OP_DECREMENT_AND_CLAMP)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::STENCIL_OP_INVERT, VK_STENCIL_OP_INVERT)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::STENCIL_OP_INCREMENT_AND_WRAP, VK_STENCIL_OP_INCREMENT_AND_WRAP)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::STENCIL_OP_DECREMENT_AND_WRAP, VK_STENCIL_OP_DECREMENT_AND_WRAP)); + +// RDD::LogicOperation == VkLogicOp. +static_assert(ENUM_MEMBERS_EQUAL(RDD::LOGIC_OP_CLEAR, VK_LOGIC_OP_CLEAR)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::LOGIC_OP_AND, VK_LOGIC_OP_AND)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::LOGIC_OP_AND_REVERSE, VK_LOGIC_OP_AND_REVERSE)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::LOGIC_OP_COPY, VK_LOGIC_OP_COPY)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::LOGIC_OP_AND_INVERTED, VK_LOGIC_OP_AND_INVERTED)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::LOGIC_OP_NO_OP, VK_LOGIC_OP_NO_OP)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::LOGIC_OP_XOR, VK_LOGIC_OP_XOR)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::LOGIC_OP_OR, VK_LOGIC_OP_OR)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::LOGIC_OP_NOR, VK_LOGIC_OP_NOR)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::LOGIC_OP_EQUIVALENT, VK_LOGIC_OP_EQUIVALENT)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::LOGIC_OP_INVERT, VK_LOGIC_OP_INVERT)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::LOGIC_OP_OR_REVERSE, VK_LOGIC_OP_OR_REVERSE)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::LOGIC_OP_COPY_INVERTED, VK_LOGIC_OP_COPY_INVERTED)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::LOGIC_OP_OR_INVERTED, VK_LOGIC_OP_OR_INVERTED)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::LOGIC_OP_NAND, VK_LOGIC_OP_NAND)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::LOGIC_OP_SET, VK_LOGIC_OP_SET)); + +// RDD::BlendFactor == VkBlendFactor. +static_assert(ENUM_MEMBERS_EQUAL(RDD::BLEND_FACTOR_ZERO, VK_BLEND_FACTOR_ZERO)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ONE)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::BLEND_FACTOR_SRC_COLOR, VK_BLEND_FACTOR_SRC_COLOR)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::BLEND_FACTOR_ONE_MINUS_SRC_COLOR, VK_BLEND_FACTOR_ONE_MINUS_SRC_COLOR)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::BLEND_FACTOR_DST_COLOR, VK_BLEND_FACTOR_DST_COLOR)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::BLEND_FACTOR_ONE_MINUS_DST_COLOR, VK_BLEND_FACTOR_ONE_MINUS_DST_COLOR)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::BLEND_FACTOR_SRC_ALPHA, VK_BLEND_FACTOR_SRC_ALPHA)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::BLEND_FACTOR_DST_ALPHA, VK_BLEND_FACTOR_DST_ALPHA)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::BLEND_FACTOR_ONE_MINUS_DST_ALPHA, VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::BLEND_FACTOR_CONSTANT_COLOR, VK_BLEND_FACTOR_CONSTANT_COLOR)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::BLEND_FACTOR_ONE_MINUS_CONSTANT_COLOR, VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_COLOR)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::BLEND_FACTOR_CONSTANT_ALPHA, VK_BLEND_FACTOR_CONSTANT_ALPHA)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::BLEND_FACTOR_ONE_MINUS_CONSTANT_ALPHA, VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_ALPHA)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::BLEND_FACTOR_SRC_ALPHA_SATURATE, VK_BLEND_FACTOR_SRC_ALPHA_SATURATE)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::BLEND_FACTOR_SRC1_COLOR, VK_BLEND_FACTOR_SRC1_COLOR)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::BLEND_FACTOR_ONE_MINUS_SRC1_COLOR, VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::BLEND_FACTOR_SRC1_ALPHA, VK_BLEND_FACTOR_SRC1_ALPHA)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA, VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA)); + +// RDD::BlendOperation == VkBlendOp. +static_assert(ENUM_MEMBERS_EQUAL(RDD::BLEND_OP_ADD, VK_BLEND_OP_ADD)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::BLEND_OP_SUBTRACT, VK_BLEND_OP_SUBTRACT)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::BLEND_OP_REVERSE_SUBTRACT, VK_BLEND_OP_REVERSE_SUBTRACT)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::BLEND_OP_MINIMUM, VK_BLEND_OP_MIN)); +static_assert(ENUM_MEMBERS_EQUAL(RDD::BLEND_OP_MAXIMUM, VK_BLEND_OP_MAX)); + +RDD::PipelineID RenderingDeviceDriverVulkan::render_pipeline_create( + ShaderID p_shader, + VertexFormatID p_vertex_format, + RenderPrimitive p_render_primitive, + PipelineRasterizationState p_rasterization_state, + PipelineMultisampleState p_multisample_state, + PipelineDepthStencilState p_depth_stencil_state, + PipelineColorBlendState p_blend_state, + VectorView p_color_attachments, + BitField p_dynamic_state, + RenderPassID p_render_pass, + uint32_t p_render_subpass, + VectorView p_specialization_constants) { + // Vertex. + const VkPipelineVertexInputStateCreateInfo *vertex_input_state_create_info = nullptr; + if (p_vertex_format.id) { + const VertexFormatInfo &vfi = ((RBSet::Element *)p_vertex_format.id)->get(); + vertex_input_state_create_info = &vfi.vk_create_info; + } else { + VkPipelineVertexInputStateCreateInfo *null_vertex_input_state = ALLOCA_SINGLE(VkPipelineVertexInputStateCreateInfo); + *null_vertex_input_state = {}; + null_vertex_input_state->sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; + vertex_input_state_create_info = null_vertex_input_state; + } + + // Input assembly. + VkPipelineInputAssemblyStateCreateInfo input_assembly_create_info = {}; + input_assembly_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; + input_assembly_create_info.topology = RD_TO_VK_PRIMITIVE[p_render_primitive]; + input_assembly_create_info.primitiveRestartEnable = (p_render_primitive == RENDER_PRIMITIVE_TRIANGLE_STRIPS_WITH_RESTART_INDEX); + + // Tessellation. + VkPipelineTessellationStateCreateInfo tessellation_create_info = {}; + tessellation_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_TESSELLATION_STATE_CREATE_INFO; + ERR_FAIL_COND_V(limits.maxTessellationPatchSize > 0 && (p_rasterization_state.patch_control_points < 1 || p_rasterization_state.patch_control_points > limits.maxTessellationPatchSize), PipelineID()); + tessellation_create_info.patchControlPoints = p_rasterization_state.patch_control_points; + + // Viewport. + VkPipelineViewportStateCreateInfo viewport_state_create_info = {}; + viewport_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; + viewport_state_create_info.viewportCount = 1; // If VR extensions are supported at some point, this will have to be customizable in the framebuffer format. + viewport_state_create_info.scissorCount = 1; + + // Rasterization. + VkPipelineRasterizationStateCreateInfo rasterization_state_create_info = {}; + rasterization_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; + rasterization_state_create_info.depthClampEnable = p_rasterization_state.enable_depth_clamp; + rasterization_state_create_info.rasterizerDiscardEnable = p_rasterization_state.discard_primitives; + rasterization_state_create_info.polygonMode = p_rasterization_state.wireframe ? VK_POLYGON_MODE_LINE : VK_POLYGON_MODE_FILL; + rasterization_state_create_info.cullMode = (PolygonCullMode)p_rasterization_state.cull_mode; + rasterization_state_create_info.frontFace = (p_rasterization_state.front_face == POLYGON_FRONT_FACE_CLOCKWISE ? VK_FRONT_FACE_CLOCKWISE : VK_FRONT_FACE_COUNTER_CLOCKWISE); + rasterization_state_create_info.depthBiasEnable = p_rasterization_state.depth_bias_enabled; + rasterization_state_create_info.depthBiasConstantFactor = p_rasterization_state.depth_bias_constant_factor; + rasterization_state_create_info.depthBiasClamp = p_rasterization_state.depth_bias_clamp; + rasterization_state_create_info.depthBiasSlopeFactor = p_rasterization_state.depth_bias_slope_factor; + rasterization_state_create_info.lineWidth = p_rasterization_state.line_width; + + // Multisample. + VkPipelineMultisampleStateCreateInfo multisample_state_create_info = {}; + multisample_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; + multisample_state_create_info.rasterizationSamples = _ensure_supported_sample_count(p_multisample_state.sample_count); + multisample_state_create_info.sampleShadingEnable = p_multisample_state.enable_sample_shading; + multisample_state_create_info.minSampleShading = p_multisample_state.min_sample_shading; + if (p_multisample_state.sample_mask.size()) { + static_assert(ARRAYS_COMPATIBLE(uint32_t, VkSampleMask)); + multisample_state_create_info.pSampleMask = p_multisample_state.sample_mask.ptr(); + } else { + multisample_state_create_info.pSampleMask = nullptr; + } + multisample_state_create_info.alphaToCoverageEnable = p_multisample_state.enable_alpha_to_coverage; + multisample_state_create_info.alphaToOneEnable = p_multisample_state.enable_alpha_to_one; + + // Depth stencil. + + VkPipelineDepthStencilStateCreateInfo depth_stencil_state_create_info = {}; + depth_stencil_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO; + depth_stencil_state_create_info.depthTestEnable = p_depth_stencil_state.enable_depth_test; + depth_stencil_state_create_info.depthWriteEnable = p_depth_stencil_state.enable_depth_write; + depth_stencil_state_create_info.depthCompareOp = (VkCompareOp)p_depth_stencil_state.depth_compare_operator; + depth_stencil_state_create_info.depthBoundsTestEnable = p_depth_stencil_state.enable_depth_range; + depth_stencil_state_create_info.stencilTestEnable = p_depth_stencil_state.enable_stencil; + + depth_stencil_state_create_info.front.failOp = (VkStencilOp)p_depth_stencil_state.front_op.fail; + depth_stencil_state_create_info.front.passOp = (VkStencilOp)p_depth_stencil_state.front_op.pass; + depth_stencil_state_create_info.front.depthFailOp = (VkStencilOp)p_depth_stencil_state.front_op.depth_fail; + depth_stencil_state_create_info.front.compareOp = (VkCompareOp)p_depth_stencil_state.front_op.compare; + depth_stencil_state_create_info.front.compareMask = p_depth_stencil_state.front_op.compare_mask; + depth_stencil_state_create_info.front.writeMask = p_depth_stencil_state.front_op.write_mask; + depth_stencil_state_create_info.front.reference = p_depth_stencil_state.front_op.reference; + + depth_stencil_state_create_info.back.failOp = (VkStencilOp)p_depth_stencil_state.back_op.fail; + depth_stencil_state_create_info.back.passOp = (VkStencilOp)p_depth_stencil_state.back_op.pass; + depth_stencil_state_create_info.back.depthFailOp = (VkStencilOp)p_depth_stencil_state.back_op.depth_fail; + depth_stencil_state_create_info.back.compareOp = (VkCompareOp)p_depth_stencil_state.back_op.compare; + depth_stencil_state_create_info.back.compareMask = p_depth_stencil_state.back_op.compare_mask; + depth_stencil_state_create_info.back.writeMask = p_depth_stencil_state.back_op.write_mask; + depth_stencil_state_create_info.back.reference = p_depth_stencil_state.back_op.reference; + + depth_stencil_state_create_info.minDepthBounds = p_depth_stencil_state.depth_range_min; + depth_stencil_state_create_info.maxDepthBounds = p_depth_stencil_state.depth_range_max; + + // Blend state. + + VkPipelineColorBlendStateCreateInfo color_blend_state_create_info = {}; + color_blend_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; + color_blend_state_create_info.logicOpEnable = p_blend_state.enable_logic_op; + color_blend_state_create_info.logicOp = (VkLogicOp)p_blend_state.logic_op; + + VkPipelineColorBlendAttachmentState *vk_attachment_states = ALLOCA_ARRAY(VkPipelineColorBlendAttachmentState, p_color_attachments.size()); + { + for (uint32_t i = 0; i < p_color_attachments.size(); i++) { + vk_attachment_states[i] = {}; + if (p_color_attachments[i] != ATTACHMENT_UNUSED) { + vk_attachment_states[i].blendEnable = p_blend_state.attachments[i].enable_blend; + + vk_attachment_states[i].srcColorBlendFactor = (VkBlendFactor)p_blend_state.attachments[i].src_color_blend_factor; + vk_attachment_states[i].dstColorBlendFactor = (VkBlendFactor)p_blend_state.attachments[i].dst_color_blend_factor; + vk_attachment_states[i].colorBlendOp = (VkBlendOp)p_blend_state.attachments[i].color_blend_op; + + vk_attachment_states[i].srcAlphaBlendFactor = (VkBlendFactor)p_blend_state.attachments[i].src_alpha_blend_factor; + vk_attachment_states[i].dstAlphaBlendFactor = (VkBlendFactor)p_blend_state.attachments[i].dst_alpha_blend_factor; + vk_attachment_states[i].alphaBlendOp = (VkBlendOp)p_blend_state.attachments[i].alpha_blend_op; + + if (p_blend_state.attachments[i].write_r) { + vk_attachment_states[i].colorWriteMask |= VK_COLOR_COMPONENT_R_BIT; + } + if (p_blend_state.attachments[i].write_g) { + vk_attachment_states[i].colorWriteMask |= VK_COLOR_COMPONENT_G_BIT; + } + if (p_blend_state.attachments[i].write_b) { + vk_attachment_states[i].colorWriteMask |= VK_COLOR_COMPONENT_B_BIT; + } + if (p_blend_state.attachments[i].write_a) { + vk_attachment_states[i].colorWriteMask |= VK_COLOR_COMPONENT_A_BIT; + } + } + } + } + color_blend_state_create_info.attachmentCount = p_color_attachments.size(); + color_blend_state_create_info.pAttachments = vk_attachment_states; + + color_blend_state_create_info.blendConstants[0] = p_blend_state.blend_constant.r; + color_blend_state_create_info.blendConstants[1] = p_blend_state.blend_constant.g; + color_blend_state_create_info.blendConstants[2] = p_blend_state.blend_constant.b; + color_blend_state_create_info.blendConstants[3] = p_blend_state.blend_constant.a; + + // Dynamic state. + + VkPipelineDynamicStateCreateInfo dynamic_state_create_info = {}; + dynamic_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO; + + static const uint32_t MAX_DYN_STATE_COUNT = 9; + VkDynamicState *vk_dynamic_states = ALLOCA_ARRAY(VkDynamicState, MAX_DYN_STATE_COUNT); + uint32_t vk_dynamic_states_count = 0; + + vk_dynamic_states[vk_dynamic_states_count] = VK_DYNAMIC_STATE_VIEWPORT; // Viewport and scissor are always dynamic. + vk_dynamic_states_count++; + vk_dynamic_states[vk_dynamic_states_count] = VK_DYNAMIC_STATE_SCISSOR; + vk_dynamic_states_count++; + if (p_dynamic_state.has_flag(DYNAMIC_STATE_LINE_WIDTH)) { + vk_dynamic_states[vk_dynamic_states_count] = VK_DYNAMIC_STATE_LINE_WIDTH; + vk_dynamic_states_count++; + } + if (p_dynamic_state.has_flag(DYNAMIC_STATE_DEPTH_BIAS)) { + vk_dynamic_states[vk_dynamic_states_count] = VK_DYNAMIC_STATE_DEPTH_BIAS; + vk_dynamic_states_count++; + } + if (p_dynamic_state.has_flag(DYNAMIC_STATE_BLEND_CONSTANTS)) { + vk_dynamic_states[vk_dynamic_states_count] = VK_DYNAMIC_STATE_BLEND_CONSTANTS; + vk_dynamic_states_count++; + } + if (p_dynamic_state.has_flag(DYNAMIC_STATE_DEPTH_BOUNDS)) { + vk_dynamic_states[vk_dynamic_states_count] = VK_DYNAMIC_STATE_DEPTH_BOUNDS; + vk_dynamic_states_count++; + } + if (p_dynamic_state.has_flag(DYNAMIC_STATE_STENCIL_COMPARE_MASK)) { + vk_dynamic_states[vk_dynamic_states_count] = VK_DYNAMIC_STATE_STENCIL_COMPARE_MASK; + vk_dynamic_states_count++; + } + if (p_dynamic_state.has_flag(DYNAMIC_STATE_STENCIL_WRITE_MASK)) { + vk_dynamic_states[vk_dynamic_states_count] = VK_DYNAMIC_STATE_STENCIL_WRITE_MASK; + vk_dynamic_states_count++; + } + if (p_dynamic_state.has_flag(DYNAMIC_STATE_STENCIL_REFERENCE)) { + vk_dynamic_states[vk_dynamic_states_count] = VK_DYNAMIC_STATE_STENCIL_REFERENCE; + vk_dynamic_states_count++; + } + DEV_ASSERT(vk_dynamic_states_count <= MAX_DYN_STATE_COUNT); + + dynamic_state_create_info.dynamicStateCount = vk_dynamic_states_count; + dynamic_state_create_info.pDynamicStates = vk_dynamic_states; + + // VRS. + + void *graphics_pipeline_nextptr = nullptr; + + if (context->get_vrs_capabilities().attachment_vrs_supported) { + // If VRS is used, this defines how the different VRS types are combined. + // combinerOps[0] decides how we use the output of pipeline and primitive (drawcall) VRS. + // combinerOps[1] decides how we use the output of combinerOps[0] and our attachment VRS. + + VkPipelineFragmentShadingRateStateCreateInfoKHR *vrs_create_info = ALLOCA_SINGLE(VkPipelineFragmentShadingRateStateCreateInfoKHR); + *vrs_create_info = {}; + vrs_create_info->sType = VK_STRUCTURE_TYPE_PIPELINE_FRAGMENT_SHADING_RATE_STATE_CREATE_INFO_KHR; + vrs_create_info->fragmentSize = { 4, 4 }; + vrs_create_info->combinerOps[0] = VK_FRAGMENT_SHADING_RATE_COMBINER_OP_KEEP_KHR; // We don't use pipeline/primitive VRS so this really doesn't matter. + vrs_create_info->combinerOps[1] = VK_FRAGMENT_SHADING_RATE_COMBINER_OP_REPLACE_KHR; // Always use the outcome of attachment VRS if enabled. + + graphics_pipeline_nextptr = vrs_create_info; + } + + // Finally, pipeline create info. + + const ShaderInfo &si = ((RBSet::Element *)p_shader.id)->get(); + + VkGraphicsPipelineCreateInfo pipeline_create_info = {}; + + pipeline_create_info.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; + pipeline_create_info.pNext = graphics_pipeline_nextptr; + pipeline_create_info.stageCount = si.vk_stages_create_info.size(); + + VkPipelineShaderStageCreateInfo *vk_pipeline_stages = ALLOCA_ARRAY(VkPipelineShaderStageCreateInfo, si.vk_stages_create_info.size()); + + for (uint32_t i = 0; i < si.vk_stages_create_info.size(); i++) { + vk_pipeline_stages[i] = si.vk_stages_create_info[i]; + + if (p_specialization_constants.size()) { + VkSpecializationMapEntry *specialization_map_entries = ALLOCA_ARRAY(VkSpecializationMapEntry, p_specialization_constants.size()); + for (uint32_t j = 0; j < p_specialization_constants.size(); j++) { + specialization_map_entries[j] = {}; + specialization_map_entries[j].constantID = p_specialization_constants[j].constant_id; + specialization_map_entries[j].offset = (const char *)&p_specialization_constants[j].int_value - (const char *)p_specialization_constants.ptr(); + specialization_map_entries[j].size = sizeof(uint32_t); + } + + VkSpecializationInfo *specialization_info = ALLOCA_SINGLE(VkSpecializationInfo); + *specialization_info = {}; + specialization_info->dataSize = p_specialization_constants.size() * sizeof(PipelineSpecializationConstant); + specialization_info->pData = p_specialization_constants.ptr(); + specialization_info->mapEntryCount = p_specialization_constants.size(); + specialization_info->pMapEntries = specialization_map_entries; + + vk_pipeline_stages[i].pSpecializationInfo = specialization_info; + } + } + + pipeline_create_info.pStages = vk_pipeline_stages; + pipeline_create_info.pVertexInputState = vertex_input_state_create_info; + pipeline_create_info.pInputAssemblyState = &input_assembly_create_info; + pipeline_create_info.pTessellationState = &tessellation_create_info; + pipeline_create_info.pViewportState = &viewport_state_create_info; + pipeline_create_info.pRasterizationState = &rasterization_state_create_info; + pipeline_create_info.pMultisampleState = &multisample_state_create_info; + pipeline_create_info.pDepthStencilState = &depth_stencil_state_create_info; + pipeline_create_info.pColorBlendState = &color_blend_state_create_info; + pipeline_create_info.pDynamicState = &dynamic_state_create_info; + pipeline_create_info.layout = si.vk_pipeline_layout; + pipeline_create_info.renderPass = (VkRenderPass)p_render_pass.id; + pipeline_create_info.subpass = p_render_subpass; + + // --- + + VkPipeline vk_pipeline = VK_NULL_HANDLE; + VkResult err = vkCreateGraphicsPipelines(vk_device, pipelines_cache.vk_cache, 1, &pipeline_create_info, nullptr, &vk_pipeline); + ERR_FAIL_COND_V_MSG(err, PipelineID(), "vkCreateComputePipelines failed with error " + itos(err) + "."); + + return PipelineID(vk_pipeline); +} + +/*****************/ +/**** COMPUTE ****/ +/*****************/ + +// ----- COMMANDS ----- + +void RenderingDeviceDriverVulkan::command_bind_compute_pipeline(CommandBufferID p_cmd_buffer, PipelineID p_pipeline) { + vkCmdBindPipeline((VkCommandBuffer)p_cmd_buffer.id, VK_PIPELINE_BIND_POINT_COMPUTE, (VkPipeline)p_pipeline.id); +} + +void RenderingDeviceDriverVulkan::command_bind_compute_uniform_set(CommandBufferID p_cmd_buffer, UniformSetID p_uniform_set, ShaderID p_shader, uint32_t p_set_index) { + const ShaderInfo &si = ((RBSet::Element *)p_shader.id)->get(); + vkCmdBindDescriptorSets((VkCommandBuffer)p_cmd_buffer.id, VK_PIPELINE_BIND_POINT_COMPUTE, si.vk_pipeline_layout, p_set_index, 1, (VkDescriptorSet *)&p_uniform_set, 0, nullptr); +} + +void RenderingDeviceDriverVulkan::command_compute_dispatch(CommandBufferID p_cmd_buffer, uint32_t p_x_groups, uint32_t p_y_groups, uint32_t p_z_groups) { + vkCmdDispatch((VkCommandBuffer)p_cmd_buffer.id, p_x_groups, p_y_groups, p_z_groups); +} + +void RenderingDeviceDriverVulkan::command_compute_dispatch_indirect(CommandBufferID p_cmd_buffer, BufferID p_indirect_buffer, uint64_t p_offset) { + vkCmdDispatchIndirect((VkCommandBuffer)p_cmd_buffer.id, (VkBuffer)p_indirect_buffer.id, p_offset); +} + +// ----- PIPELINE ----- + +RDD::PipelineID RenderingDeviceDriverVulkan::compute_pipeline_create(ShaderID p_shader, VectorView p_specialization_constants) { + const ShaderInfo &si = ((RBSet::Element *)p_shader.id)->get(); + + VkComputePipelineCreateInfo pipeline_create_info = {}; + pipeline_create_info.sType = VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO; + pipeline_create_info.stage = si.vk_stages_create_info[0]; + pipeline_create_info.layout = si.vk_pipeline_layout; + + if (p_specialization_constants.size()) { + VkSpecializationMapEntry *specialization_map_entries = ALLOCA_ARRAY(VkSpecializationMapEntry, p_specialization_constants.size()); + for (uint32_t i = 0; i < p_specialization_constants.size(); i++) { + specialization_map_entries[i] = {}; + specialization_map_entries[i].constantID = p_specialization_constants[i].constant_id; + specialization_map_entries[i].offset = (const char *)&p_specialization_constants[i].int_value - (const char *)p_specialization_constants.ptr(); + specialization_map_entries[i].size = sizeof(uint32_t); + } + + VkSpecializationInfo *specialization_info = ALLOCA_SINGLE(VkSpecializationInfo); + *specialization_info = {}; + specialization_info->dataSize = p_specialization_constants.size() * sizeof(PipelineSpecializationConstant); + specialization_info->pData = p_specialization_constants.ptr(); + specialization_info->mapEntryCount = p_specialization_constants.size(); + specialization_info->pMapEntries = specialization_map_entries; + + pipeline_create_info.stage.pSpecializationInfo = specialization_info; + } + + VkPipeline vk_pipeline = VK_NULL_HANDLE; + VkResult err = vkCreateComputePipelines(vk_device, pipelines_cache.vk_cache, 1, &pipeline_create_info, nullptr, &vk_pipeline); + ERR_FAIL_COND_V_MSG(err, PipelineID(), "vkCreateComputePipelines failed with error " + itos(err) + "."); + + return PipelineID(vk_pipeline); +} + +/*****************/ +/**** QUERIES ****/ +/*****************/ + +// ----- TIMESTAMP ----- + +RDD::QueryPoolID RenderingDeviceDriverVulkan::timestamp_query_pool_create(uint32_t p_query_count) { + VkQueryPoolCreateInfo query_pool_create_info = {}; + query_pool_create_info.sType = VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO; + query_pool_create_info.queryType = VK_QUERY_TYPE_TIMESTAMP; + query_pool_create_info.queryCount = p_query_count; + + VkQueryPool vk_query_pool = VK_NULL_HANDLE; + vkCreateQueryPool(vk_device, &query_pool_create_info, nullptr, &vk_query_pool); + return RDD::QueryPoolID(vk_query_pool); +} + +void RenderingDeviceDriverVulkan::timestamp_query_pool_free(QueryPoolID p_pool_id) { + vkDestroyQueryPool(vk_device, (VkQueryPool)p_pool_id.id, nullptr); +} + +void RenderingDeviceDriverVulkan::timestamp_query_pool_get_results(QueryPoolID p_pool_id, uint32_t p_query_count, uint64_t *r_results) { + vkGetQueryPoolResults(vk_device, (VkQueryPool)p_pool_id.id, 0, p_query_count, sizeof(uint64_t) * p_query_count, r_results, sizeof(uint64_t), VK_QUERY_RESULT_64_BIT); +} + +uint64_t RenderingDeviceDriverVulkan::timestamp_query_result_to_time(uint64_t p_result) { + // This sucks because timestampPeriod multiplier is a float, while the timestamp is 64 bits nanosecs. + // So, in cases like nvidia which give you enormous numbers and 1 as multiplier, multiplying is next to impossible. + // Need to do 128 bits fixed point multiplication to get the right value. + + auto mult64to128 = [](uint64_t u, uint64_t v, uint64_t &h, uint64_t &l) { + uint64_t u1 = (u & 0xffffffff); + uint64_t v1 = (v & 0xffffffff); + uint64_t t = (u1 * v1); + uint64_t w3 = (t & 0xffffffff); + uint64_t k = (t >> 32); + + u >>= 32; + t = (u * v1) + k; + k = (t & 0xffffffff); + uint64_t w1 = (t >> 32); + + v >>= 32; + t = (u1 * v) + k; + k = (t >> 32); + + h = (u * v) + w1 + k; + l = (t << 32) + w3; + }; + + uint64_t shift_bits = 16; + uint64_t h = 0, l = 0; + mult64to128(p_result, uint64_t(double(context->get_device_limits().timestampPeriod) * double(1 << shift_bits)), h, l); + l >>= shift_bits; + l |= h << (64 - shift_bits); + + return l; +} + +void RenderingDeviceDriverVulkan::command_timestamp_query_pool_reset(CommandBufferID p_cmd_buffer, QueryPoolID p_pool_id, uint32_t p_query_count) { + vkCmdResetQueryPool((VkCommandBuffer)p_cmd_buffer.id, (VkQueryPool)p_pool_id.id, 0, p_query_count); +} + +void RenderingDeviceDriverVulkan::command_timestamp_write(CommandBufferID p_cmd_buffer, QueryPoolID p_pool_id, uint32_t p_index) { + vkCmdWriteTimestamp((VkCommandBuffer)p_cmd_buffer.id, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, (VkQueryPool)p_pool_id.id, p_index); +} + +/****************/ +/**** SCREEN ****/ +/****************/ + +RDD::DataFormat RenderingDeviceDriverVulkan::screen_get_format() { + // Very hacky, but not used often per frame so I guess ok. + VkFormat vk_format = context->get_screen_format(); + DataFormat format = DATA_FORMAT_MAX; + for (int i = 0; i < DATA_FORMAT_MAX; i++) { + if (vk_format == RD_TO_VK_FORMAT[i]) { + format = DataFormat(i); + break; + } + } + return format; +} + +/**************/ +/**** MISC ****/ +/**************/ + +void RenderingDeviceDriverVulkan::set_object_name(ObjectType p_type, ID p_driver_id, const String &p_name) { + switch (p_type) { + case OBJECT_TYPE_TEXTURE: { + TextureInfo &ti = textures.get((VkImageView)p_driver_id.id); + if (ti.owner_info.allocation.handle) { + context->set_object_name(VK_OBJECT_TYPE_IMAGE, (uint64_t)ti.vk_image, p_name); + } + context->set_object_name(VK_OBJECT_TYPE_IMAGE_VIEW, p_driver_id.id, p_name + " View"); + } break; + case OBJECT_TYPE_SAMPLER: { + context->set_object_name(VK_OBJECT_TYPE_SAMPLER, p_driver_id.id, p_name); + } break; + case OBJECT_TYPE_BUFFER: { + BufferInfo &bi = buffers.get((VkBuffer)p_driver_id.id); + context->set_object_name(VK_OBJECT_TYPE_BUFFER, p_driver_id.id, p_name); + if (bi.vk_view) { + context->set_object_name(VK_OBJECT_TYPE_BUFFER_VIEW, (uint64_t)bi.vk_view, p_name + " View"); + } + } break; + case OBJECT_TYPE_SHADER: { + const ShaderInfo &si = ((RBSet::Element *)p_driver_id.id)->get(); + for (uint32_t i = 0; i < si.vk_descriptor_set_layouts.size(); i++) { + context->set_object_name(VK_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT, (uint64_t)si.vk_descriptor_set_layouts[i], p_name); + } + context->set_object_name(VK_OBJECT_TYPE_PIPELINE_LAYOUT, (uint64_t)si.vk_pipeline_layout, p_name + " Pipeline Layout"); + } break; + case OBJECT_TYPE_UNIFORM_SET: { + context->set_object_name(VK_OBJECT_TYPE_DESCRIPTOR_SET, (uint64_t)p_driver_id.id, p_name); + } break; + case OBJECT_TYPE_PIPELINE: { + context->set_object_name(VK_OBJECT_TYPE_PIPELINE, (uint64_t)p_driver_id.id, p_name); + } break; + default: { + DEV_ASSERT(false); + } + } +} + +uint64_t RenderingDeviceDriverVulkan::get_resource_native_handle(DriverResource p_type, ID p_driver_id) { + switch (p_type) { + case DRIVER_RESOURCE_LOGICAL_DEVICE: { + return (uint64_t)vk_device; + } + case DRIVER_RESOURCE_PHYSICAL_DEVICE: { + return (uint64_t)context->get_physical_device(); + } + case DRIVER_RESOURCE_TOPMOST_OBJECT: { + return (uint64_t)context->get_instance(); + } + case DRIVER_RESOURCE_COMMAND_QUEUE: { + return (uint64_t)context->get_graphics_queue(); + } + case DRIVER_RESOURCE_QUEUE_FAMILY: { + return context->get_graphics_queue_family_index(); + } + case DRIVER_RESOURCE_TEXTURE: { + const TextureInfo &ti = textures.get((VkImageView)p_driver_id.id); + return (uint64_t)ti.vk_image; + } + case DRIVER_RESOURCE_TEXTURE_VIEW: { + return p_driver_id.id; + } + case DRIVER_RESOURCE_TEXTURE_DATA_FORMAT: { + const TextureInfo &ti = textures.get((VkImageView)p_driver_id.id); + return (uint64_t)ti.owner_info.vk_create_info.format; + } + case DRIVER_RESOURCE_SAMPLER: + case DRIVER_RESOURCE_UNIFORM_SET: + case DRIVER_RESOURCE_BUFFER: + case DRIVER_RESOURCE_COMPUTE_PIPELINE: + case DRIVER_RESOURCE_RENDER_PIPELINE: { + return p_driver_id.id; + } + default: { + return 0; + } + } +} + +uint64_t RenderingDeviceDriverVulkan::get_total_memory_used() { + VmaTotalStatistics stats = {}; + vmaCalculateStatistics(allocator, &stats); + return stats.total.statistics.allocationBytes; +} + +uint64_t RenderingDeviceDriverVulkan::limit_get(Limit p_limit) { + switch (p_limit) { + case LIMIT_MAX_BOUND_UNIFORM_SETS: + return limits.maxBoundDescriptorSets; + case LIMIT_MAX_FRAMEBUFFER_COLOR_ATTACHMENTS: + return limits.maxColorAttachments; + case LIMIT_MAX_TEXTURES_PER_UNIFORM_SET: + return limits.maxDescriptorSetSampledImages; + case LIMIT_MAX_SAMPLERS_PER_UNIFORM_SET: + return limits.maxDescriptorSetSamplers; + case LIMIT_MAX_STORAGE_BUFFERS_PER_UNIFORM_SET: + return limits.maxDescriptorSetStorageBuffers; + case LIMIT_MAX_STORAGE_IMAGES_PER_UNIFORM_SET: + return limits.maxDescriptorSetStorageImages; + case LIMIT_MAX_UNIFORM_BUFFERS_PER_UNIFORM_SET: + return limits.maxDescriptorSetUniformBuffers; + case LIMIT_MAX_DRAW_INDEXED_INDEX: + return limits.maxDrawIndexedIndexValue; + case LIMIT_MAX_FRAMEBUFFER_HEIGHT: + return limits.maxFramebufferHeight; + case LIMIT_MAX_FRAMEBUFFER_WIDTH: + return limits.maxFramebufferWidth; + case LIMIT_MAX_TEXTURE_ARRAY_LAYERS: + return limits.maxImageArrayLayers; + case LIMIT_MAX_TEXTURE_SIZE_1D: + return limits.maxImageDimension1D; + case LIMIT_MAX_TEXTURE_SIZE_2D: + return limits.maxImageDimension2D; + case LIMIT_MAX_TEXTURE_SIZE_3D: + return limits.maxImageDimension3D; + case LIMIT_MAX_TEXTURE_SIZE_CUBE: + return limits.maxImageDimensionCube; + case LIMIT_MAX_TEXTURES_PER_SHADER_STAGE: + return limits.maxPerStageDescriptorSampledImages; + case LIMIT_MAX_SAMPLERS_PER_SHADER_STAGE: + return limits.maxPerStageDescriptorSamplers; + case LIMIT_MAX_STORAGE_BUFFERS_PER_SHADER_STAGE: + return limits.maxPerStageDescriptorStorageBuffers; + case LIMIT_MAX_STORAGE_IMAGES_PER_SHADER_STAGE: + return limits.maxPerStageDescriptorStorageImages; + case LIMIT_MAX_UNIFORM_BUFFERS_PER_SHADER_STAGE: + return limits.maxPerStageDescriptorUniformBuffers; + case LIMIT_MAX_PUSH_CONSTANT_SIZE: + return limits.maxPushConstantsSize; + case LIMIT_MAX_UNIFORM_BUFFER_SIZE: + return limits.maxUniformBufferRange; + case LIMIT_MAX_VERTEX_INPUT_ATTRIBUTE_OFFSET: + return limits.maxVertexInputAttributeOffset; + case LIMIT_MAX_VERTEX_INPUT_ATTRIBUTES: + return limits.maxVertexInputAttributes; + case LIMIT_MAX_VERTEX_INPUT_BINDINGS: + return limits.maxVertexInputBindings; + case LIMIT_MAX_VERTEX_INPUT_BINDING_STRIDE: + return limits.maxVertexInputBindingStride; + case LIMIT_MIN_UNIFORM_BUFFER_OFFSET_ALIGNMENT: + return limits.minUniformBufferOffsetAlignment; + case LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_X: + return limits.maxComputeWorkGroupCount[0]; + case LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_Y: + return limits.maxComputeWorkGroupCount[1]; + case LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_Z: + return limits.maxComputeWorkGroupCount[2]; + case LIMIT_MAX_COMPUTE_WORKGROUP_INVOCATIONS: + return limits.maxComputeWorkGroupInvocations; + case LIMIT_MAX_COMPUTE_WORKGROUP_SIZE_X: + return limits.maxComputeWorkGroupSize[0]; + case LIMIT_MAX_COMPUTE_WORKGROUP_SIZE_Y: + return limits.maxComputeWorkGroupSize[1]; + case LIMIT_MAX_COMPUTE_WORKGROUP_SIZE_Z: + return limits.maxComputeWorkGroupSize[2]; + case LIMIT_MAX_VIEWPORT_DIMENSIONS_X: + return limits.maxViewportDimensions[0]; + case LIMIT_MAX_VIEWPORT_DIMENSIONS_Y: + return limits.maxViewportDimensions[1]; + case LIMIT_SUBGROUP_SIZE: { + VulkanContext::SubgroupCapabilities subgroup_capabilities = context->get_subgroup_capabilities(); + return subgroup_capabilities.size; + } + case LIMIT_SUBGROUP_MIN_SIZE: { + VulkanContext::SubgroupCapabilities subgroup_capabilities = context->get_subgroup_capabilities(); + return subgroup_capabilities.min_size; + } + case LIMIT_SUBGROUP_MAX_SIZE: { + VulkanContext::SubgroupCapabilities subgroup_capabilities = context->get_subgroup_capabilities(); + return subgroup_capabilities.max_size; + } + case LIMIT_SUBGROUP_IN_SHADERS: { + VulkanContext::SubgroupCapabilities subgroup_capabilities = context->get_subgroup_capabilities(); + return subgroup_capabilities.supported_stages_flags_rd(); + } + case LIMIT_SUBGROUP_OPERATIONS: { + VulkanContext::SubgroupCapabilities subgroup_capabilities = context->get_subgroup_capabilities(); + return subgroup_capabilities.supported_operations_flags_rd(); + } + case LIMIT_VRS_TEXEL_WIDTH: + return context->get_vrs_capabilities().texel_size.x; + case LIMIT_VRS_TEXEL_HEIGHT: + return context->get_vrs_capabilities().texel_size.y; + default: + ERR_FAIL_V(0); + } +} + +bool RenderingDeviceDriverVulkan::has_feature(Features p_feature) { + switch (p_feature) { + case SUPPORTS_MULTIVIEW: { + MultiviewCapabilities multiview_capabilies = context->get_multiview_capabilities(); + return multiview_capabilies.is_supported && multiview_capabilies.max_view_count > 1; + } break; + case SUPPORTS_FSR_HALF_FLOAT: { + return context->get_shader_capabilities().shader_float16_is_supported && context->get_physical_device_features().shaderInt16 && context->get_storage_buffer_capabilities().storage_buffer_16_bit_access_is_supported; + } break; + case SUPPORTS_ATTACHMENT_VRS: { + VulkanContext::VRSCapabilities vrs_capabilities = context->get_vrs_capabilities(); + return vrs_capabilities.attachment_vrs_supported && context->get_physical_device_features().shaderStorageImageExtendedFormats; + } break; + case SUPPORTS_FRAGMENT_SHADER_WITH_ONLY_SIDE_EFFECTS: { + return true; + } break; + default: { + return false; + } + } +} + +const RDD::MultiviewCapabilities &RenderingDeviceDriverVulkan::get_multiview_capabilities() { + return context->get_multiview_capabilities(); +} + +/******************/ + +RenderingDeviceDriverVulkan::RenderingDeviceDriverVulkan(VulkanContext *p_context, VkDevice p_vk_device) : + context(p_context), + vk_device(p_vk_device) { + VmaAllocatorCreateInfo allocator_info = {}; + allocator_info.physicalDevice = context->get_physical_device(); + allocator_info.device = vk_device; + allocator_info.instance = context->get_instance(); + VkResult err = vmaCreateAllocator(&allocator_info, &allocator); + ERR_FAIL_COND_MSG(err, "vmaCreateAllocator failed with error " + itos(err) + "."); + + max_descriptor_sets_per_pool = GLOBAL_GET("rendering/rendering_device/vulkan/max_descriptors_per_pool"); + + VkPhysicalDeviceProperties props = {}; + vkGetPhysicalDeviceProperties(context->get_physical_device(), &props); + pipelines_cache.buffer.resize(sizeof(PipelineCacheHeader)); + PipelineCacheHeader *header = (PipelineCacheHeader *)pipelines_cache.buffer.ptrw(); + *header = {}; + header->magic = 868 + VK_PIPELINE_CACHE_HEADER_VERSION_ONE; + header->device_id = props.deviceID; + header->vendor_id = props.vendorID; + header->driver_version = props.driverVersion; + memcpy(header->uuid, props.pipelineCacheUUID, VK_UUID_SIZE); + header->driver_abi = sizeof(void *); + + limits = context->get_device_limits(); +} + +RenderingDeviceDriverVulkan::~RenderingDeviceDriverVulkan() { + while (small_allocs_pools.size()) { + HashMap::Iterator E = small_allocs_pools.begin(); + vmaDestroyPool(allocator, E->value); + small_allocs_pools.remove(E); + } + vmaDestroyAllocator(allocator); +} diff --git a/drivers/vulkan/rendering_device_driver_vulkan.h b/drivers/vulkan/rendering_device_driver_vulkan.h new file mode 100644 index 000000000000..3430a9a29b0d --- /dev/null +++ b/drivers/vulkan/rendering_device_driver_vulkan.h @@ -0,0 +1,466 @@ +/**************************************************************************/ +/* rendering_device_driver_vulkan.h */ +/**************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/**************************************************************************/ +/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ +/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/**************************************************************************/ + +#ifndef RENDERING_DEVICE_DRIVER_VULKAN_H +#define RENDERING_DEVICE_DRIVER_VULKAN_H + +#include "core/templates/hash_map.h" +#include "servers/rendering/rendering_device_driver.h" + +#ifdef DEBUG_ENABLED +#ifndef _DEBUG +#define _DEBUG +#endif +#endif +#include "vk_mem_alloc.h" + +#ifdef USE_VOLK +#include +#else +#include +#endif + +class VulkanContext; + +// Design principles: +// - Vulkan structs are zero-initialized and fields not requiring a non-zero value are omitted (except in cases where expresivity reasons apply). +class RenderingDeviceDriverVulkan : public RenderingDeviceDriver { + /*****************/ + /**** GENERIC ****/ + /*****************/ + + VulkanContext *context = nullptr; + VkDevice vk_device = VK_NULL_HANDLE; // Owned by the context. + + /****************/ + /**** MEMORY ****/ + /****************/ + + VmaAllocator allocator = nullptr; + HashMap small_allocs_pools; + + VmaPool _find_or_create_small_allocs_pool(uint32_t p_mem_type_index); + + /*****************/ + /**** BUFFERS ****/ + /*****************/ +private: + struct BufferInfo { + struct { + VmaAllocation handle; + uint64_t size; + } allocation = {}; + uint64_t size = 0; + VkBufferView vk_view = VK_NULL_HANDLE; // For texel buffers. + }; + HashMap buffers; + +public: + virtual BufferID buffer_create(uint64_t p_size, BitField p_usage, MemoryAllocationType p_allocation_type) override final; + virtual bool buffer_set_texel_format(BufferID p_buffer, DataFormat p_format) override final; + virtual void buffer_free(BufferID p_buffer) override final; + virtual uint64_t buffer_get_allocation_size(BufferID p_buffer) override final; + virtual uint8_t *buffer_map(BufferID p_buffer) override final; + virtual void buffer_unmap(BufferID p_buffer) override final; + + /*****************/ + /**** TEXTURE ****/ + /*****************/ + + struct TextureInfo { + VkImage vk_image = VK_NULL_HANDLE; // Non-null even if a view. + struct { + struct { + VmaAllocation handle; + uint64_t size; + } allocation; + struct { + VkFormat format; + uint32_t level_count; + uint32_t layer_count; + VkImageUsageFlags usage_flags; + VkImageViewType view_type; + VkImageAspectFlags aspect_mask; + } vk_create_info; + } owner_info = {}; // All 0/null if just a view. + }; + // Using view as the key because that one is unique per RDD texture. + HashMap textures; + + VkSampleCountFlagBits _ensure_supported_sample_count(TextureSamples p_requested_sample_count); + +public: + virtual TextureID texture_create(const TextureFormat &p_format, const TextureView &p_view) override final; + virtual TextureID texture_create_from_extension(uint64_t p_native_texture, TextureType p_type, DataFormat p_format, uint32_t p_array_layers, bool p_depth_stencil) override final; + virtual TextureID texture_create_shared(TextureID p_original_texture, const TextureView &p_view) override final; + virtual TextureID texture_create_shared_from_slice(TextureID p_original_texture, const TextureView &p_view, TextureSliceType p_slice_type, uint32_t p_layer, uint32_t p_layers, uint32_t p_mipmap, uint32_t p_mipmaps) override final; + virtual void texture_free(TextureID p_texture) override final; + virtual uint64_t texture_get_allocation_size(TextureID p_texture) override final; + virtual void texture_get_subresource_layout(TextureID p_texture, const TextureSubresource &p_subresource, TextureSubresourceLayout *r_layout) override final; + virtual uint8_t *texture_map(TextureID p_texture) override final; + virtual void texture_unmap(TextureID p_texture) override final; + virtual BitField texture_get_usages_supported_by_format(DataFormat p_format, bool p_cpu_readable) override final; + + /*****************/ + /**** SAMPLER ****/ + /*****************/ +public: + virtual SamplerID sampler_create(const SamplerState &p_state) final override; + virtual void sampler_free(SamplerID p_sampler) final override; + virtual bool sampler_is_format_supported_for_filter(DataFormat p_format, SamplerFilter p_filter) override final; + + /**********************/ + /**** VERTEX ARRAY ****/ + /**********************/ +private: + struct VertexFormatInfo { + TightLocalVector vk_bindings; + TightLocalVector vk_attributes; + VkPipelineVertexInputStateCreateInfo vk_create_info = {}; + + bool operator<(const VertexFormatInfo &p_other) const { return vk_bindings.ptr() < p_other.vk_bindings.ptr(); } + }; + + RBSet vertex_formats; + +public: + virtual VertexFormatID vertex_format_create(VectorView p_vertex_attribs) override final; + virtual void vertex_format_free(VertexFormatID p_vertex_format) override final; + + /******************/ + /**** BARRIERS ****/ + /******************/ + + virtual void command_pipeline_barrier( + CommandBufferID p_cmd_buffer, + BitField p_src_stages, + BitField p_dst_stages, + VectorView p_memory_barriers, + VectorView p_buffer_barriers, + VectorView p_texture_barriers) override final; + + /*************************/ + /**** COMMAND BUFFERS ****/ + /*************************/ + + // ----- POOL ----- + + virtual CommandPoolID command_pool_create() override final; + virtual void command_pool_free(CommandPoolID p_cmd_pool) override final; + + // ----- BUFFER ----- + + virtual CommandBufferID command_buffer_create(CommandBufferType p_cmd_buffer_type, CommandPoolID p_cmd_pool) override final; + virtual bool command_buffer_begin(CommandBufferID p_cmd_buffer) override final; + virtual bool command_buffer_begin_secondary(CommandBufferID p_cmd_buffer, RenderPassID p_render_pass, uint32_t p_subpass, FramebufferID p_framebuffer) override final; + virtual void command_buffer_end(CommandBufferID p_cmd_buffer) override final; + virtual void command_buffer_execute_secondary(CommandBufferID p_cmd_buffer, VectorView p_secondary_cmd_buffers) override final; + + /*********************/ + /**** FRAMEBUFFER ****/ + /*********************/ + + virtual FramebufferID framebuffer_create(RenderPassID p_render_pass, VectorView p_attachments, uint32_t p_width, uint32_t p_height) override final; + virtual void framebuffer_free(FramebufferID p_framebuffer) override final; + + /****************/ + /**** SHADER ****/ + /****************/ +private: + struct ShaderBinary { + // Version 1: initial. + // Version 2: Added shader name. + // Version 3: Added writable. + // Version 4: 64-bit vertex input mask. + static const uint32_t VERSION = 4; + + struct DataBinding { + uint32_t type = 0; + uint32_t binding = 0; + uint32_t stages = 0; + uint32_t length = 0; // Size of arrays (in total elements), or UBOs (in bytes * total elements). + uint32_t writable = 0; + }; + + struct SpecializationConstant { + uint32_t type = 0; + uint32_t constant_id = 0; + uint32_t int_value = 0; + uint32_t stage_flags = 0; + }; + + struct Data { + uint64_t vertex_input_mask = 0; + uint32_t fragment_output_mask = 0; + uint32_t specialization_constants_count = 0; + uint32_t is_compute = 0; + uint32_t compute_local_size[3] = {}; + uint32_t set_count = 0; + uint32_t push_constant_size = 0; + uint32_t vk_push_constant_stages_mask = 0; + uint32_t stage_count = 0; + uint32_t shader_name_len = 0; + }; + }; + + struct ShaderInfo { + VkShaderStageFlags vk_push_constant_stages = 0; + TightLocalVector vk_stages_create_info; + TightLocalVector vk_descriptor_set_layouts; + VkPipelineLayout vk_pipeline_layout = VK_NULL_HANDLE; + + bool operator<(const ShaderInfo &p_other) const { + return vk_stages_create_info.ptr() < p_other.vk_stages_create_info.ptr(); + } + }; + + RBSet shaders; + +public: + virtual String shader_get_binary_cache_key() override final; + virtual Vector shader_compile_binary_from_spirv(VectorView p_spirv, const String &p_shader_name) override final; + virtual ShaderID shader_create_from_bytecode(const Vector &p_shader_binary, ShaderDescription &r_shader_desc, String &r_name) override final; + virtual void shader_free(ShaderID p_shader) override final; + + /*********************/ + /**** UNIFORM SET ****/ + /*********************/ + + // Descriptor sets require allocation from a pool. + // The documentation on how to use pools properly + // is scarce, and the documentation is strange. + // + // Basically, you can mix and match pools as you + // like, but you'll run into fragmentation issues. + // Because of this, the recommended approach is to + // create a pool for every descriptor set type, as + // this prevents fragmentation. + // + // This is implemented here as a having a list of + // pools (each can contain up to 64 sets) for each + // set layout. The amount of sets for each type + // is used as the key. + +private: + static const uint32_t MAX_UNIFORM_POOL_ELEMENT = 65535; + + struct DescriptorSetPoolKey { + uint16_t uniform_type[UNIFORM_TYPE_MAX] = {}; + + bool operator<(const DescriptorSetPoolKey &p_other) const { + return memcmp(uniform_type, p_other.uniform_type, sizeof(uniform_type)) < 0; + } + }; + + using DescriptorSetPools = RBMap>; + DescriptorSetPools descriptor_set_pools; + uint32_t max_descriptor_sets_per_pool = 0; + + VkDescriptorPool _descriptor_set_pool_find_or_create(const DescriptorSetPoolKey &p_key, DescriptorSetPools::Iterator *r_pool_sets_it); + void _descriptor_set_pool_unreference(DescriptorSetPools::Iterator p_pool_sets_it, VkDescriptorPool p_vk_descriptor_pool); + + struct UniformSetInfo { + DescriptorSetPools::Iterator pool_sets_it = {}; + VkDescriptorPool vk_descriptor_pool = VK_NULL_HANDLE; + VkDescriptorSet vk_descriptor_set = VK_NULL_HANDLE; + }; + HashMap uniform_sets; + +public: + virtual UniformSetID uniform_set_create(VectorView p_uniforms, ShaderID p_shader, uint32_t p_set_index) override final; + virtual void uniform_set_free(UniformSetID p_uniform_set) override final; + + /******************/ + /**** TRANSFER ****/ + /******************/ + + virtual void command_clear_buffer(CommandBufferID p_cmd_buffer, BufferID p_buffer, uint64_t p_offset, uint64_t p_size) override final; + virtual void command_copy_buffer(CommandBufferID p_cmd_buffer, BufferID p_src_buffer, BufferID p_dst_buffer, VectorView p_regions) override final; + virtual void command_copy_texture(CommandBufferID p_cmd_buffer, TextureID p_src_texture, TextureLayout p_src_texture_layout, TextureID p_dst_texture, TextureLayout p_dst_texture_layout, VectorView p_regions) override final; + virtual void command_resolve_texture(CommandBufferID p_cmd_buffer, TextureID p_src_texture, TextureLayout p_src_texture_layout, TextureID p_dst_texture, TextureLayout p_dst_texture_layout, VectorView p_regions) override final; + + virtual void command_clear_color_texture(CommandBufferID p_cmd_buffer, TextureID p_texture, TextureLayout p_texture_layout, const Color &p_color, const TextureSubresourceRange &p_subresources) override final; + + virtual void command_copy_buffer_to_texture(CommandBufferID p_cmd_buffer, BufferID p_src_buffer, TextureID p_dst_texture, TextureLayout p_dst_texture_layout, VectorView p_regions) override final; + virtual void command_copy_texture_to_buffer(CommandBufferID p_cmd_buffer, TextureID p_src_texture, TextureLayout p_src_texture_layout, BufferID p_dst_buffer, VectorView p_regions) override final; + + /******************/ + /**** PIPELINE ****/ + /******************/ +private: + struct PipelineCacheHeader { + uint32_t magic = 0; + uint32_t data_size = 0; + uint64_t data_hash = 0; + uint32_t vendor_id = 0; + uint32_t device_id = 0; + uint32_t driver_version = 0; + uint8_t uuid[VK_UUID_SIZE] = {}; + uint8_t driver_abi = 0; + }; + + struct PipelineCache { + String file_path; + size_t current_size = 0; + Vector buffer; // Header then data. + VkPipelineCache vk_cache = VK_NULL_HANDLE; + }; + + static int caching_instance_count; + PipelineCache pipelines_cache; + +public: + virtual void pipeline_free(PipelineID p_pipeline_id) override final; + + // ----- BINDING ----- + + virtual void command_bind_push_constants(CommandBufferID p_cmd_buffer, ShaderID p_shader, uint32_t p_first_index, VectorView p_data) override final; + + // ----- CACHE ----- + + virtual bool pipeline_cache_create(const Vector &p_data) override final; + virtual void pipeline_cache_free() override final; + virtual size_t pipeline_cache_query_size() override final; + virtual Vector pipeline_cache_serialize() override final; + + /*******************/ + /**** RENDERING ****/ + /*******************/ + + // ----- SUBPASS ----- + + virtual RenderPassID render_pass_create(VectorView p_attachments, VectorView p_subpasses, VectorView p_subpass_dependencies, uint32_t p_view_count) override final; + virtual void render_pass_free(RenderPassID p_render_pass) override final; + + // ----- COMMANDS ----- + + virtual void command_begin_render_pass(CommandBufferID p_cmd_buffer, RenderPassID p_render_pass, FramebufferID p_framebuffer, CommandBufferType p_cmd_buffer_type, const Rect2i &p_rect, VectorView p_clear_values) override final; + virtual void command_end_render_pass(CommandBufferID p_cmd_buffer) override final; + virtual void command_next_render_subpass(CommandBufferID p_cmd_buffer, CommandBufferType p_cmd_buffer_type) override final; + virtual void command_render_set_viewport(CommandBufferID p_cmd_buffer, VectorView p_viewports) override final; + virtual void command_render_set_scissor(CommandBufferID p_cmd_buffer, VectorView p_scissors) override final; + virtual void command_render_clear_attachments(CommandBufferID p_cmd_buffer, VectorView p_attachment_clears, VectorView p_rects) override final; + + // Binding. + virtual void command_bind_render_pipeline(CommandBufferID p_cmd_buffer, PipelineID p_pipeline) override final; + virtual void command_bind_render_uniform_set(CommandBufferID p_cmd_buffer, UniformSetID p_uniform_set, ShaderID p_shader, uint32_t p_set_index) override final; + + // Drawing. + virtual void command_render_draw(CommandBufferID p_cmd_buffer, uint32_t p_vertex_count, uint32_t p_instance_count, uint32_t p_base_vertex, uint32_t p_first_instance) override final; + virtual void command_render_draw_indexed(CommandBufferID p_cmd_buffer, uint32_t p_index_count, uint32_t p_instance_count, uint32_t p_first_index, int32_t p_vertex_offset, uint32_t p_first_instance) override final; + virtual void command_render_draw_indexed_indirect(CommandBufferID p_cmd_buffer, BufferID p_indirect_buffer, uint64_t p_offset, uint32_t p_draw_count, uint32_t p_stride) override final; + virtual void command_render_draw_indexed_indirect_count(CommandBufferID p_cmd_buffer, BufferID p_indirect_buffer, uint64_t p_offset, BufferID p_count_buffer, uint64_t p_count_buffer_offset, uint32_t p_max_draw_count, uint32_t p_stride) override final; + virtual void command_render_draw_indirect(CommandBufferID p_cmd_buffer, BufferID p_indirect_buffer, uint64_t p_offset, uint32_t p_draw_count, uint32_t p_stride) override final; + virtual void command_render_draw_indirect_count(CommandBufferID p_cmd_buffer, BufferID p_indirect_buffer, uint64_t p_offset, BufferID p_count_buffer, uint64_t p_count_buffer_offset, uint32_t p_max_draw_count, uint32_t p_stride) override final; + + // Buffer binding. + virtual void command_render_bind_vertex_buffers(CommandBufferID p_cmd_buffer, uint32_t p_binding_count, const BufferID *p_buffers, const uint64_t *p_offsets) override final; + virtual void command_render_bind_index_buffer(CommandBufferID p_cmd_buffer, BufferID p_buffer, IndexBufferFormat p_format, uint64_t p_offset) override final; + + // Dynamic state. + virtual void command_render_set_blend_constants(CommandBufferID p_cmd_buffer, const Color &p_constants) override final; + virtual void command_render_set_line_width(CommandBufferID p_cmd_buffer, float p_width) override final; + + // ----- PIPELINE ----- + + virtual PipelineID render_pipeline_create( + ShaderID p_shader, + VertexFormatID p_vertex_format, + RenderPrimitive p_render_primitive, + PipelineRasterizationState p_rasterization_state, + PipelineMultisampleState p_multisample_state, + PipelineDepthStencilState p_depth_stencil_state, + PipelineColorBlendState p_blend_state, + VectorView p_color_attachments, + BitField p_dynamic_state, + RenderPassID p_render_pass, + uint32_t p_render_subpass, + VectorView p_specialization_constants) override final; + + /*****************/ + /**** COMPUTE ****/ + /*****************/ + + // ----- COMMANDS ----- + + // Binding. + virtual void command_bind_compute_pipeline(CommandBufferID p_cmd_buffer, PipelineID p_pipeline) override final; + virtual void command_bind_compute_uniform_set(CommandBufferID p_cmd_buffer, UniformSetID p_uniform_set, ShaderID p_shader, uint32_t p_set_index) override final; + + // Dispatching. + virtual void command_compute_dispatch(CommandBufferID p_cmd_buffer, uint32_t p_x_groups, uint32_t p_y_groups, uint32_t p_z_groups) override final; + virtual void command_compute_dispatch_indirect(CommandBufferID p_cmd_buffer, BufferID p_indirect_buffer, uint64_t p_offset) override final; + + // ----- PIPELINE ----- + + virtual PipelineID compute_pipeline_create(ShaderID p_shader, VectorView p_specialization_constants) override final; + + /*****************/ + /**** QUERIES ****/ + /*****************/ + + // ----- TIMESTAMP ----- + + // Basic. + virtual QueryPoolID timestamp_query_pool_create(uint32_t p_query_count) override final; + virtual void timestamp_query_pool_free(QueryPoolID p_pool_id) override final; + virtual void timestamp_query_pool_get_results(QueryPoolID p_pool_id, uint32_t p_query_count, uint64_t *r_results) override final; + virtual uint64_t timestamp_query_result_to_time(uint64_t p_result) override final; + + // Commands. + virtual void command_timestamp_query_pool_reset(CommandBufferID p_cmd_buffer, QueryPoolID p_pool_id, uint32_t p_query_count) override final; + virtual void command_timestamp_write(CommandBufferID p_cmd_buffer, QueryPoolID p_pool_id, uint32_t p_index) override final; + + /****************/ + /**** SCREEN ****/ + /****************/ + + virtual DataFormat screen_get_format() override final; + + /**************/ + /**** MISC ****/ + /**************/ + + VkPhysicalDeviceLimits limits = {}; + + virtual void set_object_name(ObjectType p_type, ID p_driver_id, const String &p_name) override final; + virtual uint64_t get_resource_native_handle(DriverResource p_type, ID p_driver_id) override final; + virtual uint64_t get_total_memory_used() override final; + virtual uint64_t limit_get(Limit p_limit) override final; + virtual bool has_feature(Features p_feature) override final; + virtual const MultiviewCapabilities &get_multiview_capabilities() override final; + + /******************/ + + RenderingDeviceDriverVulkan(VulkanContext *p_context, VkDevice p_vk_device); + virtual ~RenderingDeviceDriverVulkan(); +}; + +#endif // RENDERING_DEVICE_DRIVER_VULKAN_H diff --git a/drivers/vulkan/vulkan_context.cpp b/drivers/vulkan/vulkan_context.cpp index 890fd7277fd4..08acbe76fa7f 100644 --- a/drivers/vulkan/vulkan_context.cpp +++ b/drivers/vulkan/vulkan_context.cpp @@ -412,7 +412,9 @@ Error VulkanContext::_initialize_instance_extensions() { // Make sure our core extensions are here register_requested_instance_extension(VK_KHR_SURFACE_EXTENSION_NAME, true); - register_requested_instance_extension(_get_platform_surface_extension(), true); + if (_get_platform_surface_extension()) { + register_requested_instance_extension(_get_platform_surface_extension(), true); + } if (_use_validation_layers()) { register_requested_instance_extension(VK_EXT_DEBUG_REPORT_EXTENSION_NAME, false); @@ -1232,22 +1234,26 @@ Error VulkanContext::_create_physical_device(VkSurfaceKHR p_surface) { bool present_supported = false; - uint32_t device_queue_family_count = 0; - vkGetPhysicalDeviceQueueFamilyProperties(physical_devices[i], &device_queue_family_count, nullptr); - VkQueueFamilyProperties *device_queue_props = (VkQueueFamilyProperties *)malloc(device_queue_family_count * sizeof(VkQueueFamilyProperties)); - vkGetPhysicalDeviceQueueFamilyProperties(physical_devices[i], &device_queue_family_count, device_queue_props); - for (uint32_t j = 0; j < device_queue_family_count; j++) { - if ((device_queue_props[j].queueFlags & VK_QUEUE_GRAPHICS_BIT) != 0) { - VkBool32 supports; - err = vkGetPhysicalDeviceSurfaceSupportKHR( - physical_devices[i], j, p_surface, &supports); - if (err == VK_SUCCESS && supports) { - present_supported = true; - } else { - continue; + if (p_surface) { + uint32_t device_queue_family_count = 0; + vkGetPhysicalDeviceQueueFamilyProperties(physical_devices[i], &device_queue_family_count, nullptr); + VkQueueFamilyProperties *device_queue_props = (VkQueueFamilyProperties *)malloc(device_queue_family_count * sizeof(VkQueueFamilyProperties)); + vkGetPhysicalDeviceQueueFamilyProperties(physical_devices[i], &device_queue_family_count, device_queue_props); + for (uint32_t j = 0; j < device_queue_family_count; j++) { + if ((device_queue_props[j].queueFlags & VK_QUEUE_GRAPHICS_BIT) != 0) { + VkBool32 supports; + err = vkGetPhysicalDeviceSurfaceSupportKHR( + physical_devices[i], j, p_surface, &supports); + if (err == VK_SUCCESS && supports) { + present_supported = true; + } else { + continue; + } } } + free(device_queue_props); } + String name = props.deviceName; String vendor = "Unknown"; String dev_type; @@ -1276,10 +1282,9 @@ Error VulkanContext::_create_physical_device(VkSurfaceKHR p_surface) { } vendor_idx++; } - free(device_queue_props); print_verbose(" #" + itos(i) + ": " + vendor + " " + name + " - " + (present_supported ? "Supported" : "Unsupported") + ", " + dev_type); - if (present_supported) { // Select first supported device of preferred type: Discrete > Integrated > Virtual > CPU > Other. + if (present_supported || !p_surface) { // Select first supported device of preferred type: Discrete > Integrated > Virtual > CPU > Other. switch (props.deviceType) { case VkPhysicalDeviceType::VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU: { if (type_selected < 4) { @@ -1509,7 +1514,7 @@ Error VulkanContext::_create_physical_device(VkSurfaceKHR p_surface) { return OK; } -Error VulkanContext::_create_device() { +Error VulkanContext::_create_device(VkDevice &r_vk_device) { VkResult err; float queue_priorities[1] = { 0.0 }; VkDeviceQueueCreateInfo queues[2]; @@ -1624,11 +1629,11 @@ Error VulkanContext::_create_device() { } if (vulkan_hooks) { - if (!vulkan_hooks->create_vulkan_device(&sdevice, &device)) { + if (!vulkan_hooks->create_vulkan_device(&sdevice, &r_vk_device)) { return ERR_CANT_CREATE; } } else { - err = vkCreateDevice(gpu, &sdevice, nullptr, &device); + err = vkCreateDevice(gpu, &sdevice, nullptr, &r_vk_device); ERR_FAIL_COND_V(err, ERR_CANT_CREATE); } @@ -1637,9 +1642,13 @@ Error VulkanContext::_create_device() { Error VulkanContext::_initialize_queues(VkSurfaceKHR p_surface) { // Iterate over each queue to learn whether it supports presenting: - VkBool32 *supportsPresent = (VkBool32 *)malloc(queue_family_count * sizeof(VkBool32)); - for (uint32_t i = 0; i < queue_family_count; i++) { - fpGetPhysicalDeviceSurfaceSupportKHR(gpu, i, p_surface, &supportsPresent[i]); + VkBool32 *supportsPresent = nullptr; + + if (p_surface) { + supportsPresent = (VkBool32 *)malloc(queue_family_count * sizeof(VkBool32)); + for (uint32_t i = 0; i < queue_family_count; i++) { + fpGetPhysicalDeviceSurfaceSupportKHR(gpu, i, p_surface, &supportsPresent[i]); + } } // Search for a graphics and a present queue in the array of queue @@ -1652,7 +1661,7 @@ Error VulkanContext::_initialize_queues(VkSurfaceKHR p_surface) { graphicsQueueFamilyIndex = i; } - if (supportsPresent[i] == VK_TRUE) { + if (p_surface && supportsPresent[i] == VK_TRUE) { graphicsQueueFamilyIndex = i; presentQueueFamilyIndex = i; break; @@ -1660,7 +1669,7 @@ Error VulkanContext::_initialize_queues(VkSurfaceKHR p_surface) { } } - if (presentQueueFamilyIndex == UINT32_MAX) { + if (p_surface && presentQueueFamilyIndex == UINT32_MAX) { // If didn't find a queue that supports both graphics and present, then // find a separate present queue. for (uint32_t i = 0; i < queue_family_count; ++i) { @@ -1671,17 +1680,22 @@ Error VulkanContext::_initialize_queues(VkSurfaceKHR p_surface) { } } - free(supportsPresent); + if (p_surface) { + free(supportsPresent); - // Generate error if could not find both a graphics and a present queue. - ERR_FAIL_COND_V_MSG(graphicsQueueFamilyIndex == UINT32_MAX || presentQueueFamilyIndex == UINT32_MAX, ERR_CANT_CREATE, - "Could not find both graphics and present queues\n"); + // Generate error if could not find both a graphics and a present queue. + ERR_FAIL_COND_V_MSG(graphicsQueueFamilyIndex == UINT32_MAX || presentQueueFamilyIndex == UINT32_MAX, ERR_CANT_CREATE, + "Could not find both graphics and present queues\n"); - graphics_queue_family_index = graphicsQueueFamilyIndex; - present_queue_family_index = presentQueueFamilyIndex; - separate_present_queue = (graphics_queue_family_index != present_queue_family_index); + graphics_queue_family_index = graphicsQueueFamilyIndex; + present_queue_family_index = presentQueueFamilyIndex; + separate_present_queue = (graphics_queue_family_index != present_queue_family_index); + } else { + graphics_queue_family_index = graphicsQueueFamilyIndex; + } - _create_device(); + _create_device(device); + driver = memnew(RenderingDeviceDriverVulkan(this, device)); static PFN_vkGetDeviceProcAddr g_gdpa = nullptr; #define GET_DEVICE_PROC_ADDR(dev, entrypoint) \ @@ -1705,60 +1719,62 @@ Error VulkanContext::_initialize_queues(VkSurfaceKHR p_surface) { vkGetDeviceQueue(device, graphics_queue_family_index, 0, &graphics_queue); - if (!separate_present_queue) { - present_queue = graphics_queue; - } else { - vkGetDeviceQueue(device, present_queue_family_index, 0, &present_queue); - } - - // Get the list of VkFormat's that are supported: - uint32_t formatCount; - VkResult err = fpGetPhysicalDeviceSurfaceFormatsKHR(gpu, p_surface, &formatCount, nullptr); - ERR_FAIL_COND_V(err, ERR_CANT_CREATE); - VkSurfaceFormatKHR *surfFormats = (VkSurfaceFormatKHR *)malloc(formatCount * sizeof(VkSurfaceFormatKHR)); - err = fpGetPhysicalDeviceSurfaceFormatsKHR(gpu, p_surface, &formatCount, surfFormats); - if (err) { - free(surfFormats); - ERR_FAIL_V(ERR_CANT_CREATE); - } - // If the format list includes just one entry of VK_FORMAT_UNDEFINED, - // the surface has no preferred format. Otherwise, at least one - // supported format will be returned. - if (formatCount == 1 && surfFormats[0].format == VK_FORMAT_UNDEFINED) { - format = VK_FORMAT_B8G8R8A8_UNORM; - color_space = surfFormats[0].colorSpace; - } else { - // These should be ordered with the ones we want to use on top and fallback modes further down - // we want a 32bit RGBA unsigned normalized buffer or similar. - const VkFormat allowed_formats[] = { - VK_FORMAT_B8G8R8A8_UNORM, - VK_FORMAT_R8G8B8A8_UNORM - }; - uint32_t allowed_formats_count = sizeof(allowed_formats) / sizeof(VkFormat); + if (p_surface) { + if (!separate_present_queue) { + present_queue = graphics_queue; + } else { + vkGetDeviceQueue(device, present_queue_family_index, 0, &present_queue); + } - if (formatCount < 1) { + // Get the list of VkFormat's that are supported: + uint32_t formatCount; + VkResult err = fpGetPhysicalDeviceSurfaceFormatsKHR(gpu, p_surface, &formatCount, nullptr); + ERR_FAIL_COND_V(err, ERR_CANT_CREATE); + VkSurfaceFormatKHR *surfFormats = (VkSurfaceFormatKHR *)malloc(formatCount * sizeof(VkSurfaceFormatKHR)); + err = fpGetPhysicalDeviceSurfaceFormatsKHR(gpu, p_surface, &formatCount, surfFormats); + if (err) { free(surfFormats); - ERR_FAIL_V_MSG(ERR_CANT_CREATE, "formatCount less than 1"); + ERR_FAIL_V(ERR_CANT_CREATE); } + // If the format list includes just one entry of VK_FORMAT_UNDEFINED, + // the surface has no preferred format. Otherwise, at least one + // supported format will be returned. + if (formatCount == 1 && surfFormats[0].format == VK_FORMAT_UNDEFINED) { + format = VK_FORMAT_B8G8R8A8_UNORM; + color_space = surfFormats[0].colorSpace; + } else { + // These should be ordered with the ones we want to use on top and fallback modes further down + // we want a 32bit RGBA unsigned normalized buffer or similar. + const VkFormat allowed_formats[] = { + VK_FORMAT_B8G8R8A8_UNORM, + VK_FORMAT_R8G8B8A8_UNORM + }; + uint32_t allowed_formats_count = sizeof(allowed_formats) / sizeof(VkFormat); - // Find the first format that we support. - format = VK_FORMAT_UNDEFINED; - for (uint32_t af = 0; af < allowed_formats_count && format == VK_FORMAT_UNDEFINED; af++) { - for (uint32_t sf = 0; sf < formatCount && format == VK_FORMAT_UNDEFINED; sf++) { - if (surfFormats[sf].format == allowed_formats[af]) { - format = surfFormats[sf].format; - color_space = surfFormats[sf].colorSpace; + if (formatCount < 1) { + free(surfFormats); + ERR_FAIL_V_MSG(ERR_CANT_CREATE, "formatCount less than 1"); + } + + // Find the first format that we support. + format = VK_FORMAT_UNDEFINED; + for (uint32_t af = 0; af < allowed_formats_count && format == VK_FORMAT_UNDEFINED; af++) { + for (uint32_t sf = 0; sf < formatCount && format == VK_FORMAT_UNDEFINED; sf++) { + if (surfFormats[sf].format == allowed_formats[af]) { + format = surfFormats[sf].format; + color_space = surfFormats[sf].colorSpace; + } } } - } - if (format == VK_FORMAT_UNDEFINED) { - free(surfFormats); - ERR_FAIL_V_MSG(ERR_CANT_CREATE, "No usable surface format found."); + if (format == VK_FORMAT_UNDEFINED) { + free(surfFormats); + ERR_FAIL_V_MSG(ERR_CANT_CREATE, "No usable surface format found."); + } } - } - free(surfFormats); + free(surfFormats); + } Error serr = _create_semaphores(); if (serr) { @@ -1830,6 +1846,8 @@ VkExtent2D VulkanContext::_compute_swapchain_extent(const VkSurfaceCapabilitiesK } Error VulkanContext::_window_create(DisplayServer::WindowID p_window_id, DisplayServer::VSyncMode p_vsync_mode, VkSurfaceKHR p_surface, int p_width, int p_height) { + ERR_FAIL_NULL_V_MSG(_get_platform_surface_extension(), ERR_UNAVAILABLE, "This Vulkan context is headless."); + ERR_FAIL_COND_V(windows.has(p_window_id), ERR_INVALID_PARAMETER); if (!device_initialized) { @@ -1880,22 +1898,20 @@ bool VulkanContext::window_is_valid_swapchain(DisplayServer::WindowID p_window) return w->swapchain_image_resources != VK_NULL_HANDLE; } -VkRenderPass VulkanContext::window_get_render_pass(DisplayServer::WindowID p_window) { - ERR_FAIL_COND_V(!windows.has(p_window), VK_NULL_HANDLE); +RDD::RenderPassID VulkanContext::window_get_render_pass(DisplayServer::WindowID p_window) { + ERR_FAIL_COND_V(!windows.has(p_window), RDD::RenderPassID()); Window *w = &windows[p_window]; - // Vulkan use of currentbuffer. - return w->render_pass; + return (RDD::RenderPassID)w->render_pass; } -VkFramebuffer VulkanContext::window_get_framebuffer(DisplayServer::WindowID p_window) { - ERR_FAIL_COND_V(!windows.has(p_window), VK_NULL_HANDLE); - ERR_FAIL_COND_V(!buffers_prepared, VK_NULL_HANDLE); +RDD::FramebufferID VulkanContext::window_get_framebuffer(DisplayServer::WindowID p_window) { + ERR_FAIL_COND_V(!windows.has(p_window), RDD::FramebufferID()); + ERR_FAIL_COND_V(!buffers_prepared, RDD::FramebufferID()); Window *w = &windows[p_window]; - // Vulkan use of currentbuffer. if (w->swapchain_image_resources != VK_NULL_HANDLE) { - return w->swapchain_image_resources[w->current_buffer].framebuffer; + return (RDD::FramebufferID)w->swapchain_image_resources[w->current_buffer].framebuffer; } else { - return VK_NULL_HANDLE; + return RDD::FramebufferID(); } } @@ -2351,19 +2367,32 @@ Error VulkanContext::initialize() { return err; } + // Headless? Complete setup now. + if (!_get_platform_surface_extension()) { + err = _create_physical_device(VK_NULL_HANDLE); + if (err != OK) { + return err; + } + + err = _initialize_queues(VK_NULL_HANDLE); + if (err != OK) { + return err; + } + } + return OK; } -void VulkanContext::set_setup_buffer(VkCommandBuffer p_command_buffer) { - command_buffer_queue.write[0] = p_command_buffer; +void VulkanContext::set_setup_buffer(RDD::CommandBufferID p_command_buffer) { + command_buffer_queue.write[0] = (VkCommandBuffer)p_command_buffer.id; } -void VulkanContext::append_command_buffer(VkCommandBuffer p_command_buffer) { +void VulkanContext::append_command_buffer(RDD::CommandBufferID p_command_buffer) { if (command_buffer_queue.size() <= command_buffer_count) { command_buffer_queue.resize(command_buffer_count + 1); } - command_buffer_queue.write[command_buffer_count] = p_command_buffer; + command_buffer_queue.write[command_buffer_count] = (VkCommandBuffer)p_command_buffer.id; command_buffer_count++; } @@ -2690,6 +2719,14 @@ Error VulkanContext::swap_buffers() { void VulkanContext::resize_notify() { } +RenderingDevice::Capabilities VulkanContext::get_device_capabilities() const { + RenderingDevice::Capabilities c; + c.device_family = RenderingDevice::DEVICE_VULKAN; + c.version_major = VK_API_VERSION_MAJOR(device_api_version); + c.version_minor = VK_API_VERSION_MINOR(device_api_version); + return c; +} + VkDevice VulkanContext::get_device() { return device; } @@ -2714,61 +2751,27 @@ VkFormat VulkanContext::get_screen_format() const { return format; } -VkPhysicalDeviceLimits VulkanContext::get_device_limits() const { +const VkPhysicalDeviceLimits &VulkanContext::get_device_limits() const { return gpu_props.limits; } RID VulkanContext::local_device_create() { LocalDevice ld; - { // Create device. - VkResult err; - float queue_priorities[1] = { 0.0 }; - VkDeviceQueueCreateInfo queues[2]; - queues[0].sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; - queues[0].pNext = nullptr; - queues[0].queueFamilyIndex = graphics_queue_family_index; - queues[0].queueCount = 1; - queues[0].pQueuePriorities = queue_priorities; - queues[0].flags = 0; - - uint32_t enabled_extension_count = 0; - const char *enabled_extension_names[MAX_EXTENSIONS]; - ERR_FAIL_COND_V(enabled_device_extension_names.size() > MAX_EXTENSIONS, RID()); - for (const CharString &extension_name : enabled_device_extension_names) { - enabled_extension_names[enabled_extension_count++] = extension_name.ptr(); - } - - VkDeviceCreateInfo sdevice = { - /*sType =*/VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, - /*pNext */ nullptr, - /*flags */ 0, - /*queueCreateInfoCount */ 1, - /*pQueueCreateInfos */ queues, - /*enabledLayerCount */ 0, - /*ppEnabledLayerNames */ nullptr, - /*enabledExtensionCount */ enabled_extension_count, - /*ppEnabledExtensionNames */ (const char *const *)enabled_extension_names, - /*pEnabledFeatures */ &physical_device_features, // If specific features are required, pass them in here. - }; - err = vkCreateDevice(gpu, &sdevice, nullptr, &ld.device); - ERR_FAIL_COND_V(err, RID()); - } + Error err = _create_device(ld.device); + ERR_FAIL_COND_V(err, RID()); { // Create graphics queue. vkGetDeviceQueue(ld.device, graphics_queue_family_index, 0, &ld.queue); } - return local_device_owner.make_rid(ld); -} + ld.driver = memnew(RenderingDeviceDriverVulkan(this, ld.device)); -VkDevice VulkanContext::local_device_get_vk_device(RID p_local_device) { - LocalDevice *ld = local_device_owner.get_or_null(p_local_device); - return ld->device; + return local_device_owner.make_rid(ld); } -void VulkanContext::local_device_push_command_buffers(RID p_local_device, const VkCommandBuffer *p_buffers, int p_count) { +void VulkanContext::local_device_push_command_buffers(RID p_local_device, const RDD::CommandBufferID *p_buffers, int p_count) { LocalDevice *ld = local_device_owner.get_or_null(p_local_device); ERR_FAIL_COND(ld->waiting); @@ -2779,7 +2782,7 @@ void VulkanContext::local_device_push_command_buffers(RID p_local_device, const submit_info.waitSemaphoreCount = 0; submit_info.pWaitSemaphores = nullptr; submit_info.commandBufferCount = p_count; - submit_info.pCommandBuffers = p_buffers; + submit_info.pCommandBuffers = (const VkCommandBuffer *)p_buffers; submit_info.signalSemaphoreCount = 0; submit_info.pSignalSemaphores = nullptr; @@ -2808,11 +2811,12 @@ void VulkanContext::local_device_sync(RID p_local_device) { void VulkanContext::local_device_free(RID p_local_device) { LocalDevice *ld = local_device_owner.get_or_null(p_local_device); + memdelete(ld->driver); vkDestroyDevice(ld->device, nullptr); local_device_owner.free(p_local_device); } -void VulkanContext::command_begin_label(VkCommandBuffer p_command_buffer, String p_label_name, const Color p_color) { +void VulkanContext::command_begin_label(RDD::CommandBufferID p_command_buffer, String p_label_name, const Color &p_color) { if (!is_instance_extension_enabled(VK_EXT_DEBUG_UTILS_EXTENSION_NAME)) { return; } @@ -2826,10 +2830,10 @@ void VulkanContext::command_begin_label(VkCommandBuffer p_command_buffer, String label.color[1] = p_color[1]; label.color[2] = p_color[2]; label.color[3] = p_color[3]; - CmdBeginDebugUtilsLabelEXT(p_command_buffer, &label); + CmdBeginDebugUtilsLabelEXT((VkCommandBuffer)p_command_buffer.id, &label); } -void VulkanContext::command_insert_label(VkCommandBuffer p_command_buffer, String p_label_name, const Color p_color) { +void VulkanContext::command_insert_label(RDD::CommandBufferID p_command_buffer, String p_label_name, const Color &p_color) { if (!is_instance_extension_enabled(VK_EXT_DEBUG_UTILS_EXTENSION_NAME)) { return; } @@ -2842,14 +2846,14 @@ void VulkanContext::command_insert_label(VkCommandBuffer p_command_buffer, Strin label.color[1] = p_color[1]; label.color[2] = p_color[2]; label.color[3] = p_color[3]; - CmdInsertDebugUtilsLabelEXT(p_command_buffer, &label); + CmdInsertDebugUtilsLabelEXT((VkCommandBuffer)p_command_buffer.id, &label); } -void VulkanContext::command_end_label(VkCommandBuffer p_command_buffer) { +void VulkanContext::command_end_label(RDD::CommandBufferID p_command_buffer) { if (!is_instance_extension_enabled(VK_EXT_DEBUG_UTILS_EXTENSION_NAME)) { return; } - CmdEndDebugUtilsLabelEXT(p_command_buffer); + CmdEndDebugUtilsLabelEXT((VkCommandBuffer)p_command_buffer.id); } void VulkanContext::set_object_name(VkObjectType p_object_type, uint64_t p_object_handle, String p_object_name) { @@ -2897,12 +2901,25 @@ void VulkanContext::set_vsync_mode(DisplayServer::WindowID p_window, DisplayServ _update_swap_chain(&windows[p_window]); } +RenderingDeviceDriver *VulkanContext::get_driver(RID p_local_device) { + if (p_local_device.is_valid()) { + LocalDevice *ld = local_device_owner.get_or_null(p_local_device); + ERR_FAIL_NULL_V(ld, nullptr); + return ld->driver; + } else { + return driver; + } +} + VulkanContext::VulkanContext() { command_buffer_queue.resize(1); // First one is always the setup command. command_buffer_queue.write[0] = nullptr; } VulkanContext::~VulkanContext() { + if (driver) { + memdelete(driver); + } if (queue_props) { free(queue_props); } diff --git a/drivers/vulkan/vulkan_context.h b/drivers/vulkan/vulkan_context.h index 2ccfd1373905..caad6e3857e1 100644 --- a/drivers/vulkan/vulkan_context.h +++ b/drivers/vulkan/vulkan_context.h @@ -37,8 +37,9 @@ #include "core/templates/hash_map.h" #include "core/templates/rb_map.h" #include "core/templates/rid_owner.h" +#include "rendering_device_driver_vulkan.h" #include "servers/display_server.h" -#include "servers/rendering/rendering_device.h" +#include "servers/rendering/renderer_rd/api_context_rd.h" #ifdef USE_VOLK #include @@ -48,7 +49,7 @@ #include "vulkan_hooks.h" -class VulkanContext { +class VulkanContext : public ApiContextRD { public: struct SubgroupCapabilities { uint32_t size; @@ -65,14 +66,6 @@ class VulkanContext { String supported_operations_desc() const; }; - struct MultiviewCapabilities { - bool is_supported; - bool geometry_shader_is_supported; - bool tessellation_shader_is_supported; - uint32_t max_view_count; - uint32_t max_instance_count; - }; - struct VRSCapabilities { bool pipeline_vrs_supported; // We can specify our fragment rate on a pipeline level. bool primitive_vrs_supported; // We can specify our fragment rate on each drawcall. @@ -115,7 +108,7 @@ class VulkanContext { uint32_t instance_api_version = VK_API_VERSION_1_0; SubgroupCapabilities subgroup_capabilities; - MultiviewCapabilities multiview_capabilities; + RDD::MultiviewCapabilities multiview_capabilities; VRSCapabilities vrs_capabilities; ShaderCapabilities shader_capabilities; StorageBufferCapabilities storage_buffer_capabilities; @@ -171,10 +164,13 @@ class VulkanContext { bool waiting = false; VkDevice device = VK_NULL_HANDLE; VkQueue queue = VK_NULL_HANDLE; + RenderingDeviceDriverVulkan *driver = nullptr; }; RID_Owner local_device_owner; + RenderingDeviceDriverVulkan *driver = nullptr; + HashMap windows; uint32_t swapchainImageCount = 0; @@ -250,7 +246,7 @@ class VulkanContext { Error _initialize_queues(VkSurfaceKHR p_surface); - Error _create_device(); + Error _create_device(VkDevice &r_vk_device); Error _clean_up_swap_chain(Window *window); @@ -262,7 +258,7 @@ class VulkanContext { Vector _convert_VkAttachmentReference2(uint32_t p_count, const VkAttachmentReference2 *p_refs); protected: - virtual const char *_get_platform_surface_extension() const = 0; + virtual const char *_get_platform_surface_extension() const { return nullptr; } virtual Error _window_create(DisplayServer::WindowID p_window_id, DisplayServer::VSyncMode p_vsync_mode, VkSurfaceKHR p_surface, int p_width, int p_height); @@ -277,10 +273,10 @@ class VulkanContext { bool supports_renderpass2() const { return is_device_extension_enabled(VK_KHR_CREATE_RENDERPASS_2_EXTENSION_NAME); } VkResult vkCreateRenderPass2KHR(VkDevice p_device, const VkRenderPassCreateInfo2 *p_create_info, const VkAllocationCallbacks *p_allocator, VkRenderPass *p_render_pass); - uint32_t get_vulkan_major() const { return VK_API_VERSION_MAJOR(device_api_version); }; - uint32_t get_vulkan_minor() const { return VK_API_VERSION_MINOR(device_api_version); }; + virtual const char *get_api_name() const override final { return "Vulkan"; }; + virtual RenderingDevice::Capabilities get_device_capabilities() const override final; const SubgroupCapabilities &get_subgroup_capabilities() const { return subgroup_capabilities; }; - const MultiviewCapabilities &get_multiview_capabilities() const { return multiview_capabilities; }; + virtual const RDD::MultiviewCapabilities &get_multiview_capabilities() const override final { return multiview_capabilities; }; const VRSCapabilities &get_vrs_capabilities() const { return vrs_capabilities; }; const ShaderCapabilities &get_shader_capabilities() const { return shader_capabilities; }; const StorageBufferCapabilities &get_storage_buffer_capabilities() const { return storage_buffer_capabilities; }; @@ -290,7 +286,7 @@ class VulkanContext { VkDevice get_device(); VkPhysicalDevice get_physical_device(); VkInstance get_instance() { return inst; } - int get_swapchain_image_count() const; + virtual int get_swapchain_image_count() const override final; VkQueue get_graphics_queue() const; uint32_t get_graphics_queue_family_index() const; @@ -306,44 +302,45 @@ class VulkanContext { return enabled_device_extension_names.has(extension_name); } - void window_resize(DisplayServer::WindowID p_window_id, int p_width, int p_height); - int window_get_width(DisplayServer::WindowID p_window = 0); - int window_get_height(DisplayServer::WindowID p_window = 0); - bool window_is_valid_swapchain(DisplayServer::WindowID p_window = 0); - void window_destroy(DisplayServer::WindowID p_window_id); - VkFramebuffer window_get_framebuffer(DisplayServer::WindowID p_window = 0); - VkRenderPass window_get_render_pass(DisplayServer::WindowID p_window = 0); + virtual void window_resize(DisplayServer::WindowID p_window_id, int p_width, int p_height) override final; + virtual int window_get_width(DisplayServer::WindowID p_window = 0) override final; + virtual int window_get_height(DisplayServer::WindowID p_window = 0) override final; + virtual bool window_is_valid_swapchain(DisplayServer::WindowID p_window = 0) override final; + virtual void window_destroy(DisplayServer::WindowID p_window_id) override final; + virtual RDD::RenderPassID window_get_render_pass(DisplayServer::WindowID p_window = 0) override final; + virtual RDD::FramebufferID window_get_framebuffer(DisplayServer::WindowID p_window = 0) override final; - RID local_device_create(); - VkDevice local_device_get_vk_device(RID p_local_device); - void local_device_push_command_buffers(RID p_local_device, const VkCommandBuffer *p_buffers, int p_count); - void local_device_sync(RID p_local_device); - void local_device_free(RID p_local_device); + virtual RID local_device_create() override final; + virtual void local_device_push_command_buffers(RID p_local_device, const RDD::CommandBufferID *p_buffers, int p_count) override final; + virtual void local_device_sync(RID p_local_device) override final; + virtual void local_device_free(RID p_local_device) override final; VkFormat get_screen_format() const; - VkPhysicalDeviceLimits get_device_limits() const; + const VkPhysicalDeviceLimits &get_device_limits() const; - void set_setup_buffer(VkCommandBuffer p_command_buffer); - void append_command_buffer(VkCommandBuffer p_command_buffer); + virtual void set_setup_buffer(RDD::CommandBufferID p_command_buffer) override final; + virtual void append_command_buffer(RDD::CommandBufferID p_command_buffer) override final; void resize_notify(); - void flush(bool p_flush_setup = false, bool p_flush_pending = false); - Error prepare_buffers(); - Error swap_buffers(); - Error initialize(); - - void command_begin_label(VkCommandBuffer p_command_buffer, String p_label_name, const Color p_color); - void command_insert_label(VkCommandBuffer p_command_buffer, String p_label_name, const Color p_color); - void command_end_label(VkCommandBuffer p_command_buffer); + virtual void flush(bool p_flush_setup = false, bool p_flush_pending = false) override final; + virtual Error prepare_buffers() override final; + virtual Error swap_buffers() override final; + virtual Error initialize() override final; + + virtual void command_begin_label(RDD::CommandBufferID p_command_buffer, String p_label_name, const Color &p_color) override final; + virtual void command_insert_label(RDD::CommandBufferID p_command_buffer, String p_label_name, const Color &p_color) override final; + virtual void command_end_label(RDD::CommandBufferID p_command_buffer) override final; void set_object_name(VkObjectType p_object_type, uint64_t p_object_handle, String p_object_name); - String get_device_vendor_name() const; - String get_device_name() const; - RenderingDevice::DeviceType get_device_type() const; - String get_device_api_version() const; - String get_device_pipeline_cache_uuid() const; + virtual String get_device_vendor_name() const override final; + virtual String get_device_name() const override final; + virtual RDD::DeviceType get_device_type() const override final; + virtual String get_device_api_version() const override final; + virtual String get_device_pipeline_cache_uuid() const override final; + + virtual void set_vsync_mode(DisplayServer::WindowID p_window, DisplayServer::VSyncMode p_mode) override final; + virtual DisplayServer::VSyncMode get_vsync_mode(DisplayServer::WindowID p_window = 0) const override final; - void set_vsync_mode(DisplayServer::WindowID p_window, DisplayServer::VSyncMode p_mode); - DisplayServer::VSyncMode get_vsync_mode(DisplayServer::WindowID p_window = 0) const; + virtual RenderingDeviceDriver *get_driver(RID p_local_device = RID()) override final; VulkanContext(); virtual ~VulkanContext(); diff --git a/platform/android/display_server_android.cpp b/platform/android/display_server_android.cpp index 445a6ea6ea70..f729db971fa2 100644 --- a/platform/android/display_server_android.cpp +++ b/platform/android/display_server_android.cpp @@ -37,11 +37,13 @@ #include "core/config/project_settings.h" +#if defined(RD_ENABLED) +#include "servers/rendering/renderer_rd/renderer_compositor_rd.h" +#include "servers/rendering/rendering_device.h" + #if defined(VULKAN_ENABLED) #include "vulkan_context_android.h" - -#include "drivers/vulkan/rendering_device_vulkan.h" -#include "servers/rendering/renderer_rd/renderer_compositor_rd.h" +#endif #endif #ifdef GLES3_ENABLED @@ -515,20 +517,31 @@ void DisplayServerAndroid::register_android_driver() { } void DisplayServerAndroid::reset_window() { -#if defined(VULKAN_ENABLED) - if (rendering_driver == "vulkan") { +#if defined(RD_ENABLED) + if (context_rd) { ANativeWindow *native_window = OS_Android::get_singleton()->get_native_window(); ERR_FAIL_NULL(native_window); - ERR_FAIL_NULL(context_vulkan); - VSyncMode last_vsync_mode = context_vulkan->get_vsync_mode(MAIN_WINDOW_ID); - context_vulkan->window_destroy(MAIN_WINDOW_ID); + VSyncMode last_vsync_mode = context_rd->get_vsync_mode(MAIN_WINDOW_ID); + context_rd->window_destroy(MAIN_WINDOW_ID); Size2i display_size = OS_Android::get_singleton()->get_display_size(); - if (context_vulkan->window_create(native_window, last_vsync_mode, display_size.width, display_size.height) != OK) { - memdelete(context_vulkan); - context_vulkan = nullptr; - ERR_FAIL_MSG("Failed to reset Vulkan window."); + + union { +#ifdef VULKAN_ENABLED + VulkanContextAndroid::WindowPlatformData vulkan; +#endif + } wpd; +#ifdef VULKAN_ENABLED + if (rendering_driver == "vulkan") { + wpd.vulkan.window = native_window; + } +#endif + + if (context_rd->window_create(MAIN_WINDOW_ID, last_vsync_mode, display_size.width, display_size.height, &wpd) != OK) { + memdelete(context_rd); + context_rd = nullptr; + ERR_FAIL_MSG(vformat("Failed to reset %s window.", context_rd->get_api_name())); } } #endif @@ -551,30 +564,47 @@ DisplayServerAndroid::DisplayServerAndroid(const String &p_rendering_driver, Dis } #endif -#if defined(VULKAN_ENABLED) - context_vulkan = nullptr; - rendering_device_vulkan = nullptr; +#if defined(RD_ENABLED) + context_rd = nullptr; + rendering_device = nullptr; + + ANativeWindow *native_window = OS_Android::get_singleton()->get_native_window(); + ERR_FAIL_NULL(native_window); +#if defined(VULKAN_ENABLED) if (rendering_driver == "vulkan") { - ANativeWindow *native_window = OS_Android::get_singleton()->get_native_window(); - ERR_FAIL_NULL(native_window); + context_rd = memnew(VulkanContextAndroid); + } +#endif - context_vulkan = memnew(VulkanContextAndroid); - if (context_vulkan->initialize() != OK) { - memdelete(context_vulkan); - context_vulkan = nullptr; - ERR_FAIL_MSG("Failed to initialize Vulkan context"); + if (context_rd) { + if (context_rd->initialize() != OK) { + memdelete(context_rd); + context_rd = nullptr; + ERR_FAIL_MSG(vformat("Failed to initialize %s context", context_rd->get_api_name())); } Size2i display_size = OS_Android::get_singleton()->get_display_size(); - if (context_vulkan->window_create(native_window, p_vsync_mode, display_size.width, display_size.height) != OK) { - memdelete(context_vulkan); - context_vulkan = nullptr; - ERR_FAIL_MSG("Failed to create Vulkan window."); + + union { +#ifdef VULKAN_ENABLED + VulkanContextAndroid::WindowPlatformData vulkan; +#endif + } wpd; +#ifdef VULKAN_ENABLED + if (rendering_driver == "vulkan") { + wpd.vulkan.window = native_window; + } +#endif + + if (context_rd->window_create(MAIN_WINDOW_ID, p_vsync_mode, display_size.width, display_size.height, &wpd) != OK) { + memdelete(context_rd); + context_rd = nullptr; + ERR_FAIL_MSG(vformat("Failed to create %s window.", context_rd->get_api_name())); } - rendering_device_vulkan = memnew(RenderingDeviceVulkan); - rendering_device_vulkan->initialize(context_vulkan); + rendering_device = memnew(RenderingDevice); + rendering_device->initialize(context_rd); RendererCompositorRD::make_current(); } @@ -587,16 +617,13 @@ DisplayServerAndroid::DisplayServerAndroid(const String &p_rendering_driver, Dis } DisplayServerAndroid::~DisplayServerAndroid() { -#if defined(VULKAN_ENABLED) - if (rendering_driver == "vulkan") { - if (rendering_device_vulkan) { - rendering_device_vulkan->finalize(); - memdelete(rendering_device_vulkan); - } - - if (context_vulkan) { - memdelete(context_vulkan); - } +#if defined(RD_ENABLED) + if (rendering_device) { + rendering_device->finalize(); + memdelete(rendering_device); + } + if (context_rd) { + memdelete(context_rd); } #endif } @@ -687,17 +714,17 @@ void DisplayServerAndroid::cursor_set_custom_image(const Ref &p_cursor } void DisplayServerAndroid::window_set_vsync_mode(DisplayServer::VSyncMode p_vsync_mode, WindowID p_window) { -#if defined(VULKAN_ENABLED) - if (context_vulkan) { - context_vulkan->set_vsync_mode(p_window, p_vsync_mode); +#if defined(RD_ENABLED) + if (context_rd) { + context_rd->set_vsync_mode(p_window, p_vsync_mode); } #endif } DisplayServer::VSyncMode DisplayServerAndroid::window_get_vsync_mode(WindowID p_window) const { -#if defined(VULKAN_ENABLED) - if (context_vulkan) { - return context_vulkan->get_vsync_mode(p_window); +#if defined(RD_ENABLED) + if (context_rd) { + return context_rd->get_vsync_mode(p_window); } #endif return DisplayServer::VSYNC_ENABLED; diff --git a/platform/android/display_server_android.h b/platform/android/display_server_android.h index 54912212dc92..80af4f00c188 100644 --- a/platform/android/display_server_android.h +++ b/platform/android/display_server_android.h @@ -33,9 +33,9 @@ #include "servers/display_server.h" -#if defined(VULKAN_ENABLED) -class VulkanContextAndroid; -class RenderingDeviceVulkan; +#if defined(RD_ENABLED) +class ApiContextRD; +class RenderingDevice; #endif class DisplayServerAndroid : public DisplayServer { @@ -72,9 +72,9 @@ class DisplayServerAndroid : public DisplayServer { CursorShape cursor_shape = CursorShape::CURSOR_ARROW; -#if defined(VULKAN_ENABLED) - VulkanContextAndroid *context_vulkan = nullptr; - RenderingDeviceVulkan *rendering_device_vulkan = nullptr; +#if defined(RD_ENABLED) + ApiContextRD *context_rd = nullptr; + RenderingDevice *rendering_device = nullptr; #endif ObjectID window_attached_instance_id; diff --git a/platform/android/vulkan_context_android.cpp b/platform/android/vulkan_context_android.cpp index 01e6d1443818..4f9140bf3ef4 100644 --- a/platform/android/vulkan_context_android.cpp +++ b/platform/android/vulkan_context_android.cpp @@ -42,14 +42,14 @@ const char *VulkanContextAndroid::_get_platform_surface_extension() const { return VK_KHR_ANDROID_SURFACE_EXTENSION_NAME; } -Error VulkanContextAndroid::window_create(ANativeWindow *p_window, DisplayServer::VSyncMode p_vsync_mode, int p_width, int p_height) { - VkAndroidSurfaceCreateInfoKHR createInfo; +Error VulkanContextAndroid::window_create(DisplayServer::WindowID p_window_id, DisplayServer::VSyncMode p_vsync_mode, int p_width, int p_height, const void *p_platform_data) { + const WindowPlatformData *wpd = (const WindowPlatformData *)p_platform_data; + + VkAndroidSurfaceCreateInfoKHR createInfo = {}; createInfo.sType = VK_STRUCTURE_TYPE_ANDROID_SURFACE_CREATE_INFO_KHR; - createInfo.pNext = nullptr; - createInfo.flags = 0; - createInfo.window = p_window; + createInfo.window = wpd->window; - VkSurfaceKHR surface; + VkSurfaceKHR surface = VK_NULL_HANDLE; VkResult err = vkCreateAndroidSurfaceKHR(get_instance(), &createInfo, nullptr, &surface); if (err != VK_SUCCESS) { ERR_FAIL_V_MSG(ERR_CANT_CREATE, "vkCreateAndroidSurfaceKHR failed with error " + itos(err)); diff --git a/platform/android/vulkan_context_android.h b/platform/android/vulkan_context_android.h index f253149ef68a..3cee3feb867b 100644 --- a/platform/android/vulkan_context_android.h +++ b/platform/android/vulkan_context_android.h @@ -38,10 +38,13 @@ struct ANativeWindow; class VulkanContextAndroid : public VulkanContext { - virtual const char *_get_platform_surface_extension() const override; + virtual const char *_get_platform_surface_extension() const override final; public: - Error window_create(ANativeWindow *p_window, DisplayServer::VSyncMode p_vsync_mode, int p_width, int p_height); + struct WindowPlatformData { + ANativeWindow *window; + }; + virtual Error window_create(DisplayServer::WindowID p_window_id, DisplayServer::VSyncMode p_vsync_mode, int p_width, int p_height, const void *p_platform_data) override final; VulkanContextAndroid() = default; ~VulkanContextAndroid() override = default; diff --git a/platform/ios/display_server_ios.h b/platform/ios/display_server_ios.h index be4ea1e6abed..3d19222fa80c 100644 --- a/platform/ios/display_server_ios.h +++ b/platform/ios/display_server_ios.h @@ -34,18 +34,20 @@ #include "core/input/input.h" #include "servers/display_server.h" +#if defined(RD_ENABLED) +#include "servers/rendering/renderer_rd/renderer_compositor_rd.h" +#include "servers/rendering/rendering_device.h" + #if defined(VULKAN_ENABLED) #import "vulkan_context_ios.h" -#include "drivers/vulkan/rendering_device_vulkan.h" -#include "servers/rendering/renderer_rd/renderer_compositor_rd.h" - #ifdef USE_VOLK #include #else #include #endif #endif // VULKAN_ENABLED +#endif // RD_ENABLED #if defined(GLES3_ENABLED) #include "drivers/gles3/rasterizer_gles3.h" @@ -59,9 +61,9 @@ class DisplayServerIOS : public DisplayServer { _THREAD_SAFE_CLASS_ -#if defined(VULKAN_ENABLED) - VulkanContextIOS *context_vulkan = nullptr; - RenderingDeviceVulkan *rendering_device_vulkan = nullptr; +#if defined(RD_ENABLED) + ApiContextRD *context_rd = nullptr; + RenderingDevice *rendering_device = nullptr; #endif id tts = nullptr; diff --git a/platform/ios/display_server_ios.mm b/platform/ios/display_server_ios.mm index 2561c1c09574..1f3282616c17 100644 --- a/platform/ios/display_server_ios.mm +++ b/platform/ios/display_server_ios.mm @@ -62,34 +62,46 @@ tts = [[TTS_IOS alloc] init]; } -#if defined(VULKAN_ENABLED) - context_vulkan = nullptr; - rendering_device_vulkan = nullptr; +#if defined(RD_ENABLED) + context_rd = nullptr; + rendering_device = nullptr; - if (rendering_driver == "vulkan") { - context_vulkan = memnew(VulkanContextIOS); - if (context_vulkan->initialize() != OK) { - memdelete(context_vulkan); - context_vulkan = nullptr; - ERR_FAIL_MSG("Failed to initialize Vulkan context"); - } + CALayer *layer = nullptr; - CALayer *layer = [AppDelegate.viewController.godotView initializeRenderingForDriver:@"vulkan"]; + union { +#ifdef VULKAN_ENABLED + VulkanContextIOS::WindowPlatformData vulkan; +#endif + } wpd; +#if defined(VULKAN_ENABLED) + if (rendering_driver == "vulkan") { + layer = [AppDelegate.viewController.godotView initializeRenderingForDriver:@"vulkan"]; if (!layer) { ERR_FAIL_MSG("Failed to create iOS Vulkan rendering layer."); } + wpd.vulkan.layer_ptr = &layer; + context_rd = memnew(VulkanContextIOS); + } +#endif + + if (context_rd) { + if (context_rd->initialize() != OK) { + memdelete(context_rd); + context_rd = nullptr; + ERR_FAIL_MSG(vformat("Failed to initialize %s context", context_rd->get_api_name())); + } Size2i size = Size2i(layer.bounds.size.width, layer.bounds.size.height) * screen_get_max_scale(); - if (context_vulkan->window_create(MAIN_WINDOW_ID, p_vsync_mode, layer, size.width, size.height) != OK) { - memdelete(context_vulkan); - context_vulkan = nullptr; + if (context_rd->window_create(MAIN_WINDOW_ID, p_vsync_mode, size.width, size.height, &wpd) != OK) { + memdelete(context_rd); + context_rd = nullptr; r_error = ERR_UNAVAILABLE; - ERR_FAIL_MSG("Failed to create Vulkan window."); + ERR_FAIL_MSG(vformat("Failed to create %s window.", context_rd->get_api_name())); } - rendering_device_vulkan = memnew(RenderingDeviceVulkan); - rendering_device_vulkan->initialize(context_vulkan); + rendering_device = memnew(RenderingDevice); + rendering_device->initialize(context_rd); RendererCompositorRD::make_current(); } @@ -116,17 +128,17 @@ } DisplayServerIOS::~DisplayServerIOS() { -#if defined(VULKAN_ENABLED) - if (rendering_device_vulkan) { - rendering_device_vulkan->finalize(); - memdelete(rendering_device_vulkan); - rendering_device_vulkan = nullptr; +#if defined(RD_ENABLED) + if (rendering_device) { + rendering_device->finalize(); + memdelete(rendering_device); + rendering_device = nullptr; } - if (context_vulkan) { - context_vulkan->window_destroy(MAIN_WINDOW_ID); - memdelete(context_vulkan); - context_vulkan = nullptr; + if (context_rd) { + context_rd->window_destroy(MAIN_WINDOW_ID); + memdelete(context_rd); + context_rd = nullptr; } #endif } @@ -693,9 +705,9 @@ _FORCE_INLINE_ int _convert_utf32_offset_to_utf16(const String &p_existing_text, void DisplayServerIOS::resize_window(CGSize viewSize) { Size2i size = Size2i(viewSize.width, viewSize.height) * screen_get_max_scale(); -#if defined(VULKAN_ENABLED) - if (context_vulkan) { - context_vulkan->window_resize(MAIN_WINDOW_ID, size.x, size.y); +#if defined(RD_ENABLED) + if (context_rd) { + context_rd->window_resize(MAIN_WINDOW_ID, size.x, size.y); } #endif @@ -705,18 +717,18 @@ _FORCE_INLINE_ int _convert_utf32_offset_to_utf16(const String &p_existing_text, void DisplayServerIOS::window_set_vsync_mode(DisplayServer::VSyncMode p_vsync_mode, WindowID p_window) { _THREAD_SAFE_METHOD_ -#if defined(VULKAN_ENABLED) - if (context_vulkan) { - context_vulkan->set_vsync_mode(p_window, p_vsync_mode); +#if defined(RD_ENABLED) + if (context_rd) { + context_rd->set_vsync_mode(p_window, p_vsync_mode); } #endif } DisplayServer::VSyncMode DisplayServerIOS::window_get_vsync_mode(WindowID p_window) const { _THREAD_SAFE_METHOD_ -#if defined(VULKAN_ENABLED) - if (context_vulkan) { - return context_vulkan->get_vsync_mode(p_window); +#if defined(RD_ENABLED) + if (context_rd) { + return context_rd->get_vsync_mode(p_window); } #endif return DisplayServer::VSYNC_ENABLED; diff --git a/platform/ios/os_ios.h b/platform/ios/os_ios.h index 9dc5e1149767..06724d763fa4 100644 --- a/platform/ios/os_ios.h +++ b/platform/ios/os_ios.h @@ -41,10 +41,12 @@ #include "servers/audio_server.h" #include "servers/rendering/renderer_compositor.h" +#if defined(RD_ENABLED) +#include "servers/rendering/rendering_device.h" + #if defined(VULKAN_ENABLED) #import "vulkan_context_ios.h" - -#include "drivers/vulkan/rendering_device_vulkan.h" +#endif #endif class OS_IOS : public OS_Unix { diff --git a/platform/ios/os_ios.mm b/platform/ios/os_ios.mm index 68e6d4c934ce..b73489f2d2f3 100644 --- a/platform/ios/os_ios.mm +++ b/platform/ios/os_ios.mm @@ -50,15 +50,17 @@ #import #include -#if defined(VULKAN_ENABLED) +#if defined(RD_ENABLED) #include "servers/rendering/renderer_rd/renderer_compositor_rd.h" - #import + +#if defined(VULKAN_ENABLED) #ifdef USE_VOLK #include #else #include #endif +#endif // VULKAN_ENABLED #endif // Initialization order between compilation units is not guaranteed, diff --git a/platform/ios/vulkan_context_ios.h b/platform/ios/vulkan_context_ios.h index 58dad4aad628..cdc8b618af67 100644 --- a/platform/ios/vulkan_context_ios.h +++ b/platform/ios/vulkan_context_ios.h @@ -38,10 +38,13 @@ #import class VulkanContextIOS : public VulkanContext { - virtual const char *_get_platform_surface_extension() const; + virtual const char *_get_platform_surface_extension() const override final; public: - Error window_create(DisplayServer::WindowID p_window_id, DisplayServer::VSyncMode p_vsync_mode, CALayer *p_metal_layer, int p_width, int p_height); + struct WindowPlatformData { + CALayer *const *layer_ptr; + }; + virtual Error window_create(DisplayServer::WindowID p_window_id, DisplayServer::VSyncMode p_vsync_mode, int p_width, int p_height, const void *p_platform_data) override final; VulkanContextIOS(); ~VulkanContextIOS(); diff --git a/platform/ios/vulkan_context_ios.mm b/platform/ios/vulkan_context_ios.mm index 56f1894e06dd..014e05f2e6ca 100644 --- a/platform/ios/vulkan_context_ios.mm +++ b/platform/ios/vulkan_context_ios.mm @@ -42,16 +42,15 @@ return VK_MVK_IOS_SURFACE_EXTENSION_NAME; } -Error VulkanContextIOS::window_create(DisplayServer::WindowID p_window_id, DisplayServer::VSyncMode p_vsync_mode, CALayer *p_metal_layer, int p_width, int p_height) { - VkIOSSurfaceCreateInfoMVK createInfo; +Error VulkanContextIOS::window_create(DisplayServer::WindowID p_window_id, DisplayServer::VSyncMode p_vsync_mode, int p_width, int p_height, const void *p_platform_data) { + const WindowPlatformData *wpd = (const WindowPlatformData *)p_platform_data; + + VkIOSSurfaceCreateInfoMVK createInfo = {}; createInfo.sType = VK_STRUCTURE_TYPE_IOS_SURFACE_CREATE_INFO_MVK; - createInfo.pNext = nullptr; - createInfo.flags = 0; - createInfo.pView = (__bridge const void *)p_metal_layer; + createInfo.pView = (__bridge const void *)(*wpd->layer_ptr); - VkSurfaceKHR surface; - VkResult err = - vkCreateIOSSurfaceMVK(get_instance(), &createInfo, nullptr, &surface); + VkSurfaceKHR surface = VK_NULL_HANDLE; + VkResult err = vkCreateIOSSurfaceMVK(get_instance(), &createInfo, nullptr, &surface); ERR_FAIL_COND_V(err, ERR_CANT_CREATE); return _window_create(p_window_id, p_vsync_mode, surface, p_width, p_height); diff --git a/platform/linuxbsd/x11/display_server_x11.cpp b/platform/linuxbsd/x11/display_server_x11.cpp index 166010159856..242be30e080f 100644 --- a/platform/linuxbsd/x11/display_server_x11.cpp +++ b/platform/linuxbsd/x11/display_server_x11.cpp @@ -1707,9 +1707,9 @@ void DisplayServerX11::delete_sub_window(WindowID p_id) { window_set_transient(p_id, INVALID_WINDOW_ID); } -#ifdef VULKAN_ENABLED - if (context_vulkan) { - context_vulkan->window_destroy(p_id); +#if defined(RD_ENABLED) + if (context_rd) { + context_rd->window_destroy(p_id); } #endif #ifdef GLES3_ENABLED @@ -2233,9 +2233,9 @@ void DisplayServerX11::window_set_size(const Size2i p_size, WindowID p_window) { } // Keep rendering context window size in sync -#if defined(VULKAN_ENABLED) - if (context_vulkan) { - context_vulkan->window_resize(p_window, xwa.width, xwa.height); +#if defined(RD_ENABLED) + if (context_rd) { + context_rd->window_resize(p_window, xwa.width, xwa.height); } #endif #if defined(GLES3_ENABLED) @@ -3945,9 +3945,9 @@ void DisplayServerX11::_window_changed(XEvent *event) { wd.position = new_rect.position; wd.size = new_rect.size; -#if defined(VULKAN_ENABLED) - if (context_vulkan) { - context_vulkan->window_resize(window_id, wd.size.width, wd.size.height); +#if defined(RD_ENABLED) + if (context_rd) { + context_rd->window_resize(window_id, wd.size.width, wd.size.height); } #endif #if defined(GLES3_ENABLED) @@ -5244,9 +5244,9 @@ void DisplayServerX11::set_icon(const Ref &p_icon) { void DisplayServerX11::window_set_vsync_mode(DisplayServer::VSyncMode p_vsync_mode, WindowID p_window) { _THREAD_SAFE_METHOD_ -#if defined(VULKAN_ENABLED) - if (context_vulkan) { - context_vulkan->set_vsync_mode(p_window, p_vsync_mode); +#if defined(RD_ENABLED) + if (context_rd) { + context_rd->set_vsync_mode(p_window, p_vsync_mode); } #endif @@ -5262,9 +5262,9 @@ void DisplayServerX11::window_set_vsync_mode(DisplayServer::VSyncMode p_vsync_mo DisplayServer::VSyncMode DisplayServerX11::window_get_vsync_mode(WindowID p_window) const { _THREAD_SAFE_METHOD_ -#if defined(VULKAN_ENABLED) - if (context_vulkan) { - return context_vulkan->get_vsync_mode(p_window); +#if defined(RD_ENABLED) + if (context_rd) { + return context_rd->get_vsync_mode(p_window); } #endif #if defined(GLES3_ENABLED) @@ -5606,10 +5606,21 @@ DisplayServerX11::WindowID DisplayServerX11::_create_window(WindowMode p_mode, V _update_size_hints(id); -#if defined(VULKAN_ENABLED) - if (context_vulkan) { - Error err = context_vulkan->window_create(id, p_vsync_mode, wd.x11_window, x11_display, win_rect.size.width, win_rect.size.height); - ERR_FAIL_COND_V_MSG(err != OK, INVALID_WINDOW_ID, "Can't create a Vulkan window"); +#if defined(RD_ENABLED) + if (context_rd) { + union { +#ifdef VULKAN_ENABLED + VulkanContextX11::WindowPlatformData vulkan; +#endif + } wpd; +#ifdef VULKAN_ENABLED + if (rendering_driver == "vulkan") { + wpd.vulkan.window = wd.x11_window; + wpd.vulkan.display = x11_display; + } +#endif + Error err = context_rd->window_create(id, p_vsync_mode, win_rect.size.width, win_rect.size.height, &wpd); + ERR_FAIL_COND_V_MSG(err != OK, INVALID_WINDOW_ID, vformat("Can't create a %s window", context_rd->get_api_name())); } #endif #ifdef GLES3_ENABLED @@ -6008,14 +6019,19 @@ DisplayServerX11::DisplayServerX11(const String &p_rendering_driver, WindowMode rendering_driver = p_rendering_driver; bool driver_found = false; +#if defined(RD_ENABLED) #if defined(VULKAN_ENABLED) if (rendering_driver == "vulkan") { - context_vulkan = memnew(VulkanContextX11); - if (context_vulkan->initialize() != OK) { - memdelete(context_vulkan); - context_vulkan = nullptr; + context_rd = memnew(VulkanContextX11); + } +#endif + + if (context_rd) { + if (context_rd->initialize() != OK) { + memdelete(context_rd); + context_rd = nullptr; r_error = ERR_CANT_CREATE; - ERR_FAIL_MSG("Could not initialize Vulkan"); + ERR_FAIL_MSG(vformat("Could not initialize %s", context_rd->get_api_name())); } driver_found = true; } @@ -6120,11 +6136,10 @@ DisplayServerX11::DisplayServerX11(const String &p_rendering_driver, WindowMode } show_window(main_window); -#if defined(VULKAN_ENABLED) - if (rendering_driver == "vulkan") { - //temporary - rendering_device_vulkan = memnew(RenderingDeviceVulkan); - rendering_device_vulkan->initialize(context_vulkan); +#if defined(RD_ENABLED) + if (context_rd) { + rendering_device = memnew(RenderingDevice); + rendering_device->initialize(context_rd); RendererCompositorRD::make_current(); } @@ -6298,9 +6313,9 @@ DisplayServerX11::~DisplayServerX11() { //destroy all windows for (KeyValue &E : windows) { -#ifdef VULKAN_ENABLED - if (context_vulkan) { - context_vulkan->window_destroy(E.key); +#if defined(RD_ENABLED) + if (context_rd) { + context_rd->window_destroy(E.key); } #endif #ifdef GLES3_ENABLED @@ -6342,16 +6357,16 @@ DisplayServerX11::~DisplayServerX11() { #endif //destroy drivers -#if defined(VULKAN_ENABLED) - if (rendering_device_vulkan) { - rendering_device_vulkan->finalize(); - memdelete(rendering_device_vulkan); - rendering_device_vulkan = nullptr; +#if defined(RD_ENABLED) + if (rendering_device) { + rendering_device->finalize(); + memdelete(rendering_device); + rendering_device = nullptr; } - if (context_vulkan) { - memdelete(context_vulkan); - context_vulkan = nullptr; + if (context_rd) { + memdelete(context_rd); + context_rd = nullptr; } #endif diff --git a/platform/linuxbsd/x11/display_server_x11.h b/platform/linuxbsd/x11/display_server_x11.h index a8d134a6c704..ac2c7843f617 100644 --- a/platform/linuxbsd/x11/display_server_x11.h +++ b/platform/linuxbsd/x11/display_server_x11.h @@ -57,10 +57,12 @@ #include "x11/gl_manager_x11_egl.h" #endif +#if defined(RD_ENABLED) +#include "servers/rendering/rendering_device.h" + #if defined(VULKAN_ENABLED) #include "x11/vulkan_context_x11.h" - -#include "drivers/vulkan/rendering_device_vulkan.h" +#endif #endif #if defined(DBUS_ENABLED) @@ -141,9 +143,9 @@ class DisplayServerX11 : public DisplayServer { GLManager_X11 *gl_manager = nullptr; GLManagerEGL_X11 *gl_manager_egl = nullptr; #endif -#if defined(VULKAN_ENABLED) - VulkanContextX11 *context_vulkan = nullptr; - RenderingDeviceVulkan *rendering_device_vulkan = nullptr; +#if defined(RD_ENABLED) + ApiContextRD *context_rd = nullptr; + RenderingDevice *rendering_device = nullptr; #endif #if defined(DBUS_ENABLED) diff --git a/platform/linuxbsd/x11/vulkan_context_x11.cpp b/platform/linuxbsd/x11/vulkan_context_x11.cpp index d240480f61d5..3eee1706b069 100644 --- a/platform/linuxbsd/x11/vulkan_context_x11.cpp +++ b/platform/linuxbsd/x11/vulkan_context_x11.cpp @@ -42,15 +42,15 @@ const char *VulkanContextX11::_get_platform_surface_extension() const { return VK_KHR_XLIB_SURFACE_EXTENSION_NAME; } -Error VulkanContextX11::window_create(DisplayServer::WindowID p_window_id, DisplayServer::VSyncMode p_vsync_mode, ::Window p_window, Display *p_display, int p_width, int p_height) { - VkXlibSurfaceCreateInfoKHR createInfo; +Error VulkanContextX11::window_create(DisplayServer::WindowID p_window_id, DisplayServer::VSyncMode p_vsync_mode, int p_width, int p_height, const void *p_platform_data) { + const WindowPlatformData *wpd = (const WindowPlatformData *)p_platform_data; + + VkXlibSurfaceCreateInfoKHR createInfo = {}; createInfo.sType = VK_STRUCTURE_TYPE_XLIB_SURFACE_CREATE_INFO_KHR; - createInfo.pNext = nullptr; - createInfo.flags = 0; - createInfo.dpy = p_display; - createInfo.window = p_window; + createInfo.dpy = wpd->display; + createInfo.window = wpd->window; - VkSurfaceKHR surface; + VkSurfaceKHR surface = VK_NULL_HANDLE; VkResult err = vkCreateXlibSurfaceKHR(get_instance(), &createInfo, nullptr, &surface); ERR_FAIL_COND_V(err, ERR_CANT_CREATE); return _window_create(p_window_id, p_vsync_mode, surface, p_width, p_height); diff --git a/platform/linuxbsd/x11/vulkan_context_x11.h b/platform/linuxbsd/x11/vulkan_context_x11.h index 294fdc710e28..2390326b4461 100644 --- a/platform/linuxbsd/x11/vulkan_context_x11.h +++ b/platform/linuxbsd/x11/vulkan_context_x11.h @@ -38,10 +38,14 @@ #include class VulkanContextX11 : public VulkanContext { - virtual const char *_get_platform_surface_extension() const; + virtual const char *_get_platform_surface_extension() const override final; public: - Error window_create(DisplayServer::WindowID p_window_id, DisplayServer::VSyncMode p_vsync_mode, ::Window p_window, Display *p_display, int p_width, int p_height); + struct WindowPlatformData { + ::Window window; + Display *display; + }; + virtual Error window_create(DisplayServer::WindowID p_window_id, DisplayServer::VSyncMode p_vsync_mode, int p_width, int p_height, const void *p_platform_data) override final; VulkanContextX11(); ~VulkanContextX11(); diff --git a/platform/macos/display_server_macos.h b/platform/macos/display_server_macos.h index 66c89d6cc558..0824051339d9 100644 --- a/platform/macos/display_server_macos.h +++ b/platform/macos/display_server_macos.h @@ -39,11 +39,13 @@ #include "gl_manager_macos_legacy.h" #endif // GLES3_ENABLED +#if defined(RD_ENABLED) +#include "servers/rendering/rendering_device.h" + #if defined(VULKAN_ENABLED) #include "vulkan_context_macos.h" - -#include "drivers/vulkan/rendering_device_vulkan.h" #endif // VULKAN_ENABLED +#endif // RD_ENABLED #define BitMap _QDBitMap // Suppress deprecated QuickDraw definition. @@ -132,9 +134,9 @@ class DisplayServerMacOS : public DisplayServer { GLManagerLegacy_MacOS *gl_manager_legacy = nullptr; GLManagerANGLE_MacOS *gl_manager_angle = nullptr; #endif -#if defined(VULKAN_ENABLED) - VulkanContextMacOS *context_vulkan = nullptr; - RenderingDeviceVulkan *rendering_device_vulkan = nullptr; +#if defined(RD_ENABLED) + ApiContextRD *context_rd = nullptr; + RenderingDevice *rendering_device = nullptr; #endif String rendering_driver; diff --git a/platform/macos/display_server_macos.mm b/platform/macos/display_server_macos.mm index 53db9a5abf01..887fcce9eb17 100644 --- a/platform/macos/display_server_macos.mm +++ b/platform/macos/display_server_macos.mm @@ -53,7 +53,7 @@ #include "drivers/gles3/rasterizer_gles3.h" #endif -#if defined(VULKAN_ENABLED) +#if defined(RD_ENABLED) #include "servers/rendering/renderer_rd/renderer_compositor_rd.h" #endif @@ -179,10 +179,20 @@ [layer setBackgroundColor:bg_color.CGColor]; } -#if defined(VULKAN_ENABLED) - if (context_vulkan) { - Error err = context_vulkan->window_create(window_id_counter, p_vsync_mode, wd.window_view, p_rect.size.width, p_rect.size.height); - ERR_FAIL_COND_V_MSG(err != OK, INVALID_WINDOW_ID, "Can't create a Vulkan context"); +#if defined(RD_ENABLED) + if (context_rd) { + union { +#ifdef VULKAN_ENABLED + VulkanContextMacOS::WindowPlatformData vulkan; +#endif + } wpd; +#ifdef VULKAN_ENABLED + if (rendering_driver == "vulkan") { + wpd.vulkan.view_ptr = &wd.window_view; + } +#endif + Error err = context_rd->window_create(window_id_counter, p_vsync_mode, p_rect.size.width, p_rect.size.height, &wpd); + ERR_FAIL_COND_V_MSG(err != OK, INVALID_WINDOW_ID, vformat("Can't create a %s context", context_rd->get_api_name())); } #endif #if defined(GLES3_ENABLED) @@ -232,9 +242,9 @@ gl_manager_angle->window_resize(id, wd.size.width, wd.size.height); } #endif -#if defined(VULKAN_ENABLED) - if (context_vulkan) { - context_vulkan->window_resize(id, wd.size.width, wd.size.height); +#if defined(RD_ENABLED) + if (context_rd) { + context_rd->window_resize(id, wd.size.width, wd.size.height); } #endif @@ -769,9 +779,9 @@ gl_manager_legacy->window_destroy(p_window); } #endif -#ifdef VULKAN_ENABLED - if (context_vulkan) { - context_vulkan->window_destroy(p_window); +#ifdef RD_ENABLED + if (context_rd) { + context_rd->window_destroy(p_window); } #endif windows.erase(p_window); @@ -788,8 +798,8 @@ } #endif #if defined(VULKAN_ENABLED) - if (context_vulkan) { - context_vulkan->window_resize(p_window, p_width, p_height); + if (context_rd) { + context_rd->window_resize(p_window, p_width, p_height); } #endif } @@ -3745,8 +3755,8 @@ - (void)popupAction:(id)sender { } #endif #if defined(VULKAN_ENABLED) - if (context_vulkan) { - context_vulkan->set_vsync_mode(p_window, p_vsync_mode); + if (context_rd) { + context_rd->set_vsync_mode(p_window, p_vsync_mode); } #endif } @@ -3762,8 +3772,8 @@ - (void)popupAction:(id)sender { } #endif #if defined(VULKAN_ENABLED) - if (context_vulkan) { - return context_vulkan->get_vsync_mode(p_window); + if (context_rd) { + return context_rd->get_vsync_mode(p_window); } #endif return DisplayServer::VSYNC_ENABLED; @@ -4519,12 +4529,17 @@ - (void)popupAction:(id)sender { } } #endif +#if defined(RD_ENABLED) #if defined(VULKAN_ENABLED) if (rendering_driver == "vulkan") { - context_vulkan = memnew(VulkanContextMacOS); - if (context_vulkan->initialize() != OK) { - memdelete(context_vulkan); - context_vulkan = nullptr; + context_rd = memnew(VulkanContextMacOS); + } +#endif + + if (context_rd) { + if (context_rd->initialize() != OK) { + memdelete(context_rd); + context_rd = nullptr; r_error = ERR_CANT_CREATE; ERR_FAIL_MSG("Could not initialize Vulkan"); } @@ -4559,10 +4574,10 @@ - (void)popupAction:(id)sender { RasterizerGLES3::make_current(false); } #endif -#if defined(VULKAN_ENABLED) - if (rendering_driver == "vulkan") { - rendering_device_vulkan = memnew(RenderingDeviceVulkan); - rendering_device_vulkan->initialize(context_vulkan); +#if defined(RD_ENABLED) + if (context_rd) { + rendering_device = memnew(RenderingDevice); + rendering_device->initialize(context_rd); RendererCompositorRD::make_current(); } @@ -4596,16 +4611,16 @@ - (void)popupAction:(id)sender { gl_manager_angle = nullptr; } #endif -#if defined(VULKAN_ENABLED) - if (rendering_device_vulkan) { - rendering_device_vulkan->finalize(); - memdelete(rendering_device_vulkan); - rendering_device_vulkan = nullptr; +#if defined(RD_ENABLED) + if (rendering_device) { + rendering_device->finalize(); + memdelete(rendering_device); + rendering_device = nullptr; } - if (context_vulkan) { - memdelete(context_vulkan); - context_vulkan = nullptr; + if (context_rd) { + memdelete(context_rd); + context_rd = nullptr; } #endif diff --git a/platform/macos/vulkan_context_macos.h b/platform/macos/vulkan_context_macos.h index ab019384e2e1..6205877120fb 100644 --- a/platform/macos/vulkan_context_macos.h +++ b/platform/macos/vulkan_context_macos.h @@ -38,10 +38,13 @@ #import class VulkanContextMacOS : public VulkanContext { - virtual const char *_get_platform_surface_extension() const; + virtual const char *_get_platform_surface_extension() const override final; public: - Error window_create(DisplayServer::WindowID p_window_id, DisplayServer::VSyncMode p_vsync_mode, id p_window, int p_width, int p_height); + struct WindowPlatformData { + const id *view_ptr; + }; + virtual Error window_create(DisplayServer::WindowID p_window_id, DisplayServer::VSyncMode p_vsync_mode, int p_width, int p_height, const void *p_platform_data) override final; VulkanContextMacOS(); ~VulkanContextMacOS(); diff --git a/platform/macos/vulkan_context_macos.mm b/platform/macos/vulkan_context_macos.mm index 46a2d9f86ac1..18c3bda39b20 100644 --- a/platform/macos/vulkan_context_macos.mm +++ b/platform/macos/vulkan_context_macos.mm @@ -42,14 +42,14 @@ return VK_MVK_MACOS_SURFACE_EXTENSION_NAME; } -Error VulkanContextMacOS::window_create(DisplayServer::WindowID p_window_id, DisplayServer::VSyncMode p_vsync_mode, id p_window, int p_width, int p_height) { - VkMacOSSurfaceCreateInfoMVK createInfo; +Error VulkanContextMacOS::window_create(DisplayServer::WindowID p_window_id, DisplayServer::VSyncMode p_vsync_mode, int p_width, int p_height, const void *p_platform_data) { + const WindowPlatformData *wpd = (const WindowPlatformData *)p_platform_data; + + VkMacOSSurfaceCreateInfoMVK createInfo = {}; createInfo.sType = VK_STRUCTURE_TYPE_MACOS_SURFACE_CREATE_INFO_MVK; - createInfo.pNext = nullptr; - createInfo.flags = 0; - createInfo.pView = (__bridge const void *)p_window; + createInfo.pView = (__bridge const void *)(*wpd->view_ptr); - VkSurfaceKHR surface; + VkSurfaceKHR surface = VK_NULL_HANDLE; VkResult err = vkCreateMacOSSurfaceMVK(get_instance(), &createInfo, nullptr, &surface); ERR_FAIL_COND_V(err, ERR_CANT_CREATE); return _window_create(p_window_id, p_vsync_mode, surface, p_width, p_height); diff --git a/platform/windows/display_server_windows.cpp b/platform/windows/display_server_windows.cpp index bb0b64ba10d2..8e7288cbe481 100644 --- a/platform/windows/display_server_windows.cpp +++ b/platform/windows/display_server_windows.cpp @@ -1102,9 +1102,9 @@ void DisplayServerWindows::delete_sub_window(WindowID p_window) { window_set_transient(p_window, INVALID_WINDOW_ID); } -#ifdef VULKAN_ENABLED - if (context_vulkan) { - context_vulkan->window_destroy(p_window); +#ifdef RD_ENABLED + if (context_rd) { + context_rd->window_destroy(p_window); } #endif #ifdef GLES3_ENABLED @@ -1534,9 +1534,9 @@ void DisplayServerWindows::window_set_size(const Size2i p_size, WindowID p_windo wd.width = w; wd.height = h; -#if defined(VULKAN_ENABLED) - if (context_vulkan) { - context_vulkan->window_resize(p_window, w, h); +#if defined(RD_ENABLED) + if (context_rd) { + context_rd->window_resize(p_window, w, h); } #endif #if defined(GLES3_ENABLED) @@ -2582,9 +2582,9 @@ void DisplayServerWindows::set_icon(const Ref &p_icon) { void DisplayServerWindows::window_set_vsync_mode(DisplayServer::VSyncMode p_vsync_mode, WindowID p_window) { _THREAD_SAFE_METHOD_ -#if defined(VULKAN_ENABLED) - if (context_vulkan) { - context_vulkan->set_vsync_mode(p_window, p_vsync_mode); +#if defined(RD_ENABLED) + if (context_rd) { + context_rd->set_vsync_mode(p_window, p_vsync_mode); } #endif @@ -2600,9 +2600,9 @@ void DisplayServerWindows::window_set_vsync_mode(DisplayServer::VSyncMode p_vsyn DisplayServer::VSyncMode DisplayServerWindows::window_get_vsync_mode(WindowID p_window) const { _THREAD_SAFE_METHOD_ -#if defined(VULKAN_ENABLED) - if (context_vulkan) { - return context_vulkan->get_vsync_mode(p_window); +#if defined(RD_ENABLED) + if (context_rd) { + return context_rd->get_vsync_mode(p_window); } #endif @@ -3767,10 +3767,10 @@ LRESULT DisplayServerWindows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARA rect_changed = true; } -#if defined(VULKAN_ENABLED) - if (context_vulkan && window.context_created) { +#if defined(RD_ENABLED) + if (context_rd && window.context_created) { // Note: Trigger resize event to update swapchains when window is minimized/restored, even if size is not changed. - context_vulkan->window_resize(window_id, window.width, window.height); + context_rd->window_resize(window_id, window.width, window.height); } #endif } @@ -4324,13 +4324,24 @@ DisplayServer::WindowID DisplayServerWindows::_create_window(WindowMode p_mode, ::DwmSetWindowAttribute(wd.hWnd, DWMWA_USE_IMMERSIVE_DARK_MODE, &value, sizeof(value)); } +#ifdef RD_ENABLED + if (context_rd) { + union { #ifdef VULKAN_ENABLED - if (context_vulkan) { - if (context_vulkan->window_create(id, p_vsync_mode, wd.hWnd, hInstance, WindowRect.right - WindowRect.left, WindowRect.bottom - WindowRect.top) != OK) { - memdelete(context_vulkan); - context_vulkan = nullptr; + VulkanContextWindows::WindowPlatformData vulkan; +#endif + } wpd; +#ifdef VULKAN_ENABLED + if (rendering_driver == "vulkan") { + wpd.vulkan.window = wd.hWnd, + wpd.vulkan.instance = hInstance; + } +#endif + if (context_rd->window_create(id, p_vsync_mode, WindowRect.right - WindowRect.left, WindowRect.bottom - WindowRect.top, &wpd) != OK) { + memdelete(context_rd); + context_rd = nullptr; windows.erase(id); - ERR_FAIL_V_MSG(INVALID_WINDOW_ID, "Failed to create Vulkan Window."); + ERR_FAIL_V_MSG(INVALID_WINDOW_ID, vformat("Failed to create %s Window.", context_rd->get_api_name())); } wd.context_created = true; } @@ -4633,18 +4644,23 @@ DisplayServerWindows::DisplayServerWindows(const String &p_rendering_driver, Win _register_raw_input_devices(INVALID_WINDOW_ID); +#if defined(RD_ENABLED) #if defined(VULKAN_ENABLED) if (rendering_driver == "vulkan") { - context_vulkan = memnew(VulkanContextWindows); - if (context_vulkan->initialize() != OK) { - memdelete(context_vulkan); - context_vulkan = nullptr; + context_rd = memnew(VulkanContextWindows); + } +#endif + + if (context_rd) { + if (context_rd->initialize() != OK) { + memdelete(context_rd); + context_rd = nullptr; r_error = ERR_UNAVAILABLE; return; } } #endif - // Init context and rendering device +// Init context and rendering device #if defined(GLES3_ENABLED) bool fallback = GLOBAL_GET("rendering/gl_compatibility/fallback_to_angle"); @@ -4719,11 +4735,10 @@ DisplayServerWindows::DisplayServerWindows(const String &p_rendering_driver, Win show_window(MAIN_WINDOW_ID); -#if defined(VULKAN_ENABLED) - - if (rendering_driver == "vulkan") { - rendering_device_vulkan = memnew(RenderingDeviceVulkan); - rendering_device_vulkan->initialize(context_vulkan); +#if defined(RD_ENABLED) + if (context_rd) { + rendering_device = memnew(RenderingDevice); + rendering_device->initialize(context_rd); RendererCompositorRD::make_current(); } @@ -4821,9 +4836,9 @@ DisplayServerWindows::~DisplayServerWindows() { #endif if (windows.has(MAIN_WINDOW_ID)) { -#ifdef VULKAN_ENABLED - if (context_vulkan) { - context_vulkan->window_destroy(MAIN_WINDOW_ID); +#ifdef RD_ENABLED + if (context_rd) { + context_rd->window_destroy(MAIN_WINDOW_ID); } #endif if (wintab_available && windows[MAIN_WINDOW_ID].wtctx) { @@ -4833,16 +4848,16 @@ DisplayServerWindows::~DisplayServerWindows() { DestroyWindow(windows[MAIN_WINDOW_ID].hWnd); } -#if defined(VULKAN_ENABLED) - if (rendering_device_vulkan) { - rendering_device_vulkan->finalize(); - memdelete(rendering_device_vulkan); - rendering_device_vulkan = nullptr; +#if defined(RD_ENABLED) + if (rendering_device) { + rendering_device->finalize(); + memdelete(rendering_device); + rendering_device = nullptr; } - if (context_vulkan) { - memdelete(context_vulkan); - context_vulkan = nullptr; + if (context_rd) { + memdelete(context_rd); + context_rd = nullptr; } #endif diff --git a/platform/windows/display_server_windows.h b/platform/windows/display_server_windows.h index 48c8c20280f3..0def90e97db5 100644 --- a/platform/windows/display_server_windows.h +++ b/platform/windows/display_server_windows.h @@ -52,10 +52,12 @@ #include "drivers/xaudio2/audio_driver_xaudio2.h" #endif +#if defined(RD_ENABLED) +#include "servers/rendering/rendering_device.h" + #if defined(VULKAN_ENABLED) #include "vulkan_context_win.h" - -#include "drivers/vulkan/rendering_device_vulkan.h" +#endif #endif #if defined(GLES3_ENABLED) @@ -342,9 +344,9 @@ class DisplayServerWindows : public DisplayServer { GLManagerNative_Windows *gl_manager_native = nullptr; #endif -#if defined(VULKAN_ENABLED) - VulkanContextWindows *context_vulkan = nullptr; - RenderingDeviceVulkan *rendering_device_vulkan = nullptr; +#if defined(RD_ENABLED) + ApiContextRD *context_rd = nullptr; + RenderingDevice *rendering_device = nullptr; #endif RBMap touch_state; diff --git a/platform/windows/os_windows.h b/platform/windows/os_windows.h index e873fb8a1303..60610a166fd2 100644 --- a/platform/windows/os_windows.h +++ b/platform/windows/os_windows.h @@ -46,10 +46,12 @@ #include "drivers/xaudio2/audio_driver_xaudio2.h" #endif +#if defined(RD_ENABLED) +#include "servers/rendering/rendering_device.h" + #if defined(VULKAN_ENABLED) #include "vulkan_context_win.h" - -#include "drivers/vulkan/rendering_device_vulkan.h" +#endif #endif #include diff --git a/platform/windows/vulkan_context_win.cpp b/platform/windows/vulkan_context_win.cpp index a60055dbec5c..69f8dc23fbfb 100644 --- a/platform/windows/vulkan_context_win.cpp +++ b/platform/windows/vulkan_context_win.cpp @@ -42,14 +42,15 @@ const char *VulkanContextWindows::_get_platform_surface_extension() const { return VK_KHR_WIN32_SURFACE_EXTENSION_NAME; } -Error VulkanContextWindows::window_create(DisplayServer::WindowID p_window_id, DisplayServer::VSyncMode p_vsync_mode, HWND p_window, HINSTANCE p_instance, int p_width, int p_height) { - VkWin32SurfaceCreateInfoKHR createInfo; +Error VulkanContextWindows::window_create(DisplayServer::WindowID p_window_id, DisplayServer::VSyncMode p_vsync_mode, int p_width, int p_height, const void *p_platform_data) { + const WindowPlatformData *wpd = (const WindowPlatformData *)p_platform_data; + + VkWin32SurfaceCreateInfoKHR createInfo = {}; createInfo.sType = VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR; - createInfo.pNext = nullptr; - createInfo.flags = 0; - createInfo.hinstance = p_instance; - createInfo.hwnd = p_window; - VkSurfaceKHR surface; + createInfo.hinstance = wpd->instance; + createInfo.hwnd = wpd->window; + + VkSurfaceKHR surface = VK_NULL_HANDLE; VkResult err = vkCreateWin32SurfaceKHR(get_instance(), &createInfo, nullptr, &surface); ERR_FAIL_COND_V(err, ERR_CANT_CREATE); return _window_create(p_window_id, p_vsync_mode, surface, p_width, p_height); diff --git a/platform/windows/vulkan_context_win.h b/platform/windows/vulkan_context_win.h index 01ae2031e7ca..29ab1d45c3d9 100644 --- a/platform/windows/vulkan_context_win.h +++ b/platform/windows/vulkan_context_win.h @@ -42,7 +42,11 @@ class VulkanContextWindows : public VulkanContext { virtual const char *_get_platform_surface_extension() const; public: - Error window_create(DisplayServer::WindowID p_window_id, DisplayServer::VSyncMode p_vsync_mode, HWND p_window, HINSTANCE p_instance, int p_width, int p_height); + struct WindowPlatformData { + HWND window; + HINSTANCE instance; + }; + virtual Error window_create(DisplayServer::WindowID p_window_id, DisplayServer::VSyncMode p_vsync_mode, int p_width, int p_height, const void *p_platform_data) override final; VulkanContextWindows(); ~VulkanContextWindows(); diff --git a/servers/rendering/renderer_rd/api_context_rd.cpp b/servers/rendering/renderer_rd/api_context_rd.cpp new file mode 100644 index 000000000000..b5b3cdd88c40 --- /dev/null +++ b/servers/rendering/renderer_rd/api_context_rd.cpp @@ -0,0 +1,33 @@ +/**************************************************************************/ +/* api_context_rd.cpp */ +/**************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/**************************************************************************/ +/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ +/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/**************************************************************************/ + +#include "api_context_rd.h" + +ApiContextRD::~ApiContextRD() {} diff --git a/servers/rendering/renderer_rd/api_context_rd.h b/servers/rendering/renderer_rd/api_context_rd.h new file mode 100644 index 000000000000..4c19aef3dcad --- /dev/null +++ b/servers/rendering/renderer_rd/api_context_rd.h @@ -0,0 +1,84 @@ +/**************************************************************************/ +/* api_context_rd.h */ +/**************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/**************************************************************************/ +/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ +/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/**************************************************************************/ + +#ifndef API_CONTEXT_RD_H +#define API_CONTEXT_RD_H + +#include "servers/rendering/rendering_device.h" +#include "servers/rendering/rendering_device_driver.h" + +class ApiContextRD { +public: + virtual const char *get_api_name() const = 0; + virtual RenderingDevice::Capabilities get_device_capabilities() const = 0; + virtual const RDD::MultiviewCapabilities &get_multiview_capabilities() const = 0; + + virtual int get_swapchain_image_count() const = 0; + + virtual Error window_create(DisplayServer::WindowID p_window_id, DisplayServer::VSyncMode p_vsync_mode, int p_width, int p_height, const void *p_platform_data) = 0; + virtual void window_resize(DisplayServer::WindowID p_window_id, int p_width, int p_height) = 0; + virtual int window_get_width(DisplayServer::WindowID p_window = 0) = 0; + virtual int window_get_height(DisplayServer::WindowID p_window = 0) = 0; + virtual bool window_is_valid_swapchain(DisplayServer::WindowID p_window = 0) = 0; + virtual void window_destroy(DisplayServer::WindowID p_window_id) = 0; + virtual RDD::RenderPassID window_get_render_pass(DisplayServer::WindowID p_window = 0) = 0; + virtual RDD::FramebufferID window_get_framebuffer(DisplayServer::WindowID p_window = 0) = 0; + + virtual RID local_device_create() = 0; + virtual void local_device_push_command_buffers(RID p_local_device, const RDD::CommandBufferID *p_buffers, int p_count) = 0; + virtual void local_device_sync(RID p_local_device) = 0; + virtual void local_device_free(RID p_local_device) = 0; + + virtual void set_setup_buffer(RDD::CommandBufferID p_command_buffer) = 0; + virtual void append_command_buffer(RDD::CommandBufferID p_command_buffer) = 0; + virtual void flush(bool p_flush_setup = false, bool p_flush_pending = false) = 0; + virtual Error prepare_buffers() = 0; + virtual Error swap_buffers() = 0; + virtual Error initialize() = 0; + + virtual void command_begin_label(RDD::CommandBufferID p_command_buffer, String p_label_name, const Color &p_color) = 0; + virtual void command_insert_label(RDD::CommandBufferID p_command_buffer, String p_label_name, const Color &p_color) = 0; + virtual void command_end_label(RDD::CommandBufferID p_command_buffer) = 0; + + virtual String get_device_vendor_name() const = 0; + virtual String get_device_name() const = 0; + virtual RDD::DeviceType get_device_type() const = 0; + virtual String get_device_api_version() const = 0; + virtual String get_device_pipeline_cache_uuid() const = 0; + + virtual void set_vsync_mode(DisplayServer::WindowID p_window, DisplayServer::VSyncMode p_mode) = 0; + virtual DisplayServer::VSyncMode get_vsync_mode(DisplayServer::WindowID p_window = 0) const = 0; + + virtual RenderingDeviceDriver *get_driver(RID p_local_device = RID()) = 0; + + virtual ~ApiContextRD(); +}; + +#endif // API_CONTEXT_RD_H diff --git a/servers/rendering/renderer_rd/pipeline_cache_rd.h b/servers/rendering/renderer_rd/pipeline_cache_rd.h index 2f1e79b39745..0ebebd054031 100644 --- a/servers/rendering/renderer_rd/pipeline_cache_rd.h +++ b/servers/rendering/renderer_rd/pipeline_cache_rd.h @@ -38,7 +38,7 @@ class PipelineCacheRD { SpinLock spin_lock; RID shader; - uint32_t input_mask; + uint64_t input_mask; RD::RenderPrimitive render_primitive; RD::PipelineRasterizationState rasterization_state; diff --git a/servers/rendering/renderer_rd/shader_rd.cpp b/servers/rendering/renderer_rd/shader_rd.cpp index 242b0301f1f9..28732695862e 100644 --- a/servers/rendering/renderer_rd/shader_rd.cpp +++ b/servers/rendering/renderer_rd/shader_rd.cpp @@ -242,8 +242,8 @@ void ShaderRD::_compile_variant(uint32_t p_variant, const CompileData *p_data) { current_source = builder.as_string(); RD::ShaderStageSPIRVData stage; - stage.spir_v = RD::get_singleton()->shader_compile_spirv_from_source(RD::SHADER_STAGE_VERTEX, current_source, RD::SHADER_LANGUAGE_GLSL, &error); - if (stage.spir_v.size() == 0) { + stage.spirv = RD::get_singleton()->shader_compile_spirv_from_source(RD::SHADER_STAGE_VERTEX, current_source, RD::SHADER_LANGUAGE_GLSL, &error); + if (stage.spirv.size() == 0) { build_ok = false; } else { stage.shader_stage = RD::SHADER_STAGE_VERTEX; @@ -260,8 +260,8 @@ void ShaderRD::_compile_variant(uint32_t p_variant, const CompileData *p_data) { current_source = builder.as_string(); RD::ShaderStageSPIRVData stage; - stage.spir_v = RD::get_singleton()->shader_compile_spirv_from_source(RD::SHADER_STAGE_FRAGMENT, current_source, RD::SHADER_LANGUAGE_GLSL, &error); - if (stage.spir_v.size() == 0) { + stage.spirv = RD::get_singleton()->shader_compile_spirv_from_source(RD::SHADER_STAGE_FRAGMENT, current_source, RD::SHADER_LANGUAGE_GLSL, &error); + if (stage.spirv.size() == 0) { build_ok = false; } else { stage.shader_stage = RD::SHADER_STAGE_FRAGMENT; @@ -279,8 +279,8 @@ void ShaderRD::_compile_variant(uint32_t p_variant, const CompileData *p_data) { current_source = builder.as_string(); RD::ShaderStageSPIRVData stage; - stage.spir_v = RD::get_singleton()->shader_compile_spirv_from_source(RD::SHADER_STAGE_COMPUTE, current_source, RD::SHADER_LANGUAGE_GLSL, &error); - if (stage.spir_v.size() == 0) { + stage.spirv = RD::get_singleton()->shader_compile_spirv_from_source(RD::SHADER_STAGE_COMPUTE, current_source, RD::SHADER_LANGUAGE_GLSL, &error); + if (stage.spirv.size() == 0) { build_ok = false; } else { stage.shader_stage = RD::SHADER_STAGE_COMPUTE; diff --git a/servers/rendering/renderer_rd/storage_rd/texture_storage.cpp b/servers/rendering/renderer_rd/storage_rd/texture_storage.cpp index 474ec897ef28..04f89437b4bb 100644 --- a/servers/rendering/renderer_rd/storage_rd/texture_storage.cpp +++ b/servers/rendering/renderer_rd/storage_rd/texture_storage.cpp @@ -1557,9 +1557,9 @@ uint64_t TextureStorage::texture_get_native_handle(RID p_texture, bool p_srgb) c ERR_FAIL_NULL_V(tex, 0); if (p_srgb && tex->rd_texture_srgb.is_valid()) { - return RD::get_singleton()->texture_get_native_handle(tex->rd_texture_srgb); + return RD::get_singleton()->get_driver_resource(RD::DRIVER_RESOURCE_TEXTURE, tex->rd_texture_srgb); } else { - return RD::get_singleton()->texture_get_native_handle(tex->rd_texture); + return RD::get_singleton()->get_driver_resource(RD::DRIVER_RESOURCE_TEXTURE, tex->rd_texture); } } diff --git a/servers/rendering/rendering_device.cpp b/servers/rendering/rendering_device.cpp index 5c68149a5f4a..ea2396ea8959 100644 --- a/servers/rendering/rendering_device.cpp +++ b/servers/rendering/rendering_device.cpp @@ -1,5 +1,5 @@ /**************************************************************************/ -/* rendering_device_vulkan.cpp */ +/* rendering_device.cpp */ /**************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ @@ -28,124 +28,32 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /**************************************************************************/ -#include "rendering_device_vulkan.h" +#include "rendering_device.h" +#include "rendering_device.compat.inc" + +#include "rendering_device_binds.h" #include "core/config/project_settings.h" -#include "core/io/compression.h" #include "core/io/dir_access.h" -#include "core/io/file_access.h" -#include "core/io/marshalls.h" -#include "core/os/os.h" -#include "core/templates/hashfuncs.h" -#include "drivers/vulkan/vulkan_context.h" - -#include "thirdparty/misc/smolv.h" +#include "servers/rendering/renderer_rd/api_context_rd.h" //#define FORCE_FULL_BARRIER -static const uint32_t SMALL_ALLOCATION_MAX_SIZE = 4096; - -// Get the Vulkan object information and possible stage access types (bitwise OR'd with incoming values). -RenderingDeviceVulkan::Buffer *RenderingDeviceVulkan::_get_buffer_from_owner(RID p_buffer, VkPipelineStageFlags &r_stage_mask, VkAccessFlags &r_access_mask, BitField p_post_barrier) { - Buffer *buffer = nullptr; - if (vertex_buffer_owner.owns(p_buffer)) { - buffer = vertex_buffer_owner.get_or_null(p_buffer); - - r_stage_mask |= VK_PIPELINE_STAGE_VERTEX_INPUT_BIT; - r_access_mask |= VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT; - if (buffer->usage & VK_BUFFER_USAGE_STORAGE_BUFFER_BIT) { - if (p_post_barrier.has_flag(BARRIER_MASK_VERTEX)) { - r_access_mask |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; - r_stage_mask |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT; - } - if (p_post_barrier.has_flag(BARRIER_MASK_FRAGMENT)) { - r_access_mask |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; - r_stage_mask |= VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT; - } - if (p_post_barrier.has_flag(BARRIER_MASK_COMPUTE)) { - r_access_mask |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; - r_stage_mask |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT; - } - } - } else if (index_buffer_owner.owns(p_buffer)) { - r_stage_mask |= VK_PIPELINE_STAGE_VERTEX_INPUT_BIT; - r_access_mask |= VK_ACCESS_INDEX_READ_BIT; - buffer = index_buffer_owner.get_or_null(p_buffer); - } else if (uniform_buffer_owner.owns(p_buffer)) { - if (p_post_barrier.has_flag(BARRIER_MASK_VERTEX)) { - r_stage_mask |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT; - } - if (p_post_barrier.has_flag(BARRIER_MASK_FRAGMENT)) { - r_stage_mask |= VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT; - } - if (p_post_barrier.has_flag(BARRIER_MASK_COMPUTE)) { - r_stage_mask |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT; - } - r_access_mask |= VK_ACCESS_UNIFORM_READ_BIT; - buffer = uniform_buffer_owner.get_or_null(p_buffer); - } else if (texture_buffer_owner.owns(p_buffer)) { - if (p_post_barrier.has_flag(BARRIER_MASK_VERTEX)) { - r_stage_mask |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT; - r_access_mask |= VK_ACCESS_SHADER_READ_BIT; - } - if (p_post_barrier.has_flag(BARRIER_MASK_FRAGMENT)) { - r_stage_mask |= VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT; - r_access_mask |= VK_ACCESS_SHADER_READ_BIT; - } - if (p_post_barrier.has_flag(BARRIER_MASK_COMPUTE)) { - r_stage_mask |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT; - r_access_mask |= VK_ACCESS_SHADER_READ_BIT; - } - - buffer = &texture_buffer_owner.get_or_null(p_buffer)->buffer; - } else if (storage_buffer_owner.owns(p_buffer)) { - buffer = storage_buffer_owner.get_or_null(p_buffer); - if (p_post_barrier.has_flag(BARRIER_MASK_VERTEX)) { - r_stage_mask |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT; - r_access_mask |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; - } - if (p_post_barrier.has_flag(BARRIER_MASK_FRAGMENT)) { - r_stage_mask |= VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT; - r_access_mask |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; - } - if (p_post_barrier.has_flag(BARRIER_MASK_COMPUTE)) { - r_stage_mask |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT; - r_access_mask |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; - } +RenderingDevice *RenderingDevice::singleton = nullptr; - if (buffer->usage & VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT) { - r_stage_mask |= VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT; - r_access_mask |= VK_ACCESS_INDIRECT_COMMAND_READ_BIT; - } - } - return buffer; +RenderingDevice *RenderingDevice::get_singleton() { + return singleton; } -static void update_external_dependency_for_store(VkSubpassDependency2KHR &dependency, bool is_sampled, bool is_storage, bool is_depth) { - // Transitioning from write to read, protect the shaders that may use this next. - // Allow for copies/image layout transitions. - dependency.dstStageMask |= VK_PIPELINE_STAGE_TRANSFER_BIT; - dependency.dstAccessMask |= VK_ACCESS_TRANSFER_READ_BIT; - - if (is_sampled) { - dependency.dstStageMask |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT; - dependency.dstAccessMask |= VK_ACCESS_SHADER_READ_BIT; - } else if (is_storage) { - dependency.dstStageMask |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT; - dependency.dstAccessMask |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; - } else { - dependency.dstStageMask |= VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; - dependency.dstAccessMask |= VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; - } +RenderingDevice::ShaderCompileToSPIRVFunction RenderingDevice::compile_to_spirv_function = nullptr; +RenderingDevice::ShaderCacheFunction RenderingDevice::cache_function = nullptr; +RenderingDevice::ShaderSPIRVGetCacheKeyFunction RenderingDevice::get_spirv_cache_key_function = nullptr; - if (is_depth) { - // Depth resources have additional stages that may be interested in them. - dependency.dstStageMask |= VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT; - dependency.dstAccessMask |= VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; - } -} +/***************************/ +/**** ID INFRASTRUCTURE ****/ +/***************************/ -void RenderingDeviceVulkan::_add_dependency(RID p_id, RID p_depends_on) { +void RenderingDevice::_add_dependency(RID p_id, RID p_depends_on) { if (!dependency_map.has(p_depends_on)) { dependency_map[p_depends_on] = HashSet(); } @@ -159,7 +67,7 @@ void RenderingDeviceVulkan::_add_dependency(RID p_id, RID p_depends_on) { reverse_dependency_map[p_id].insert(p_depends_on); } -void RenderingDeviceVulkan::_free_dependencies(RID p_id) { +void RenderingDevice::_free_dependencies(RID p_id) { // Direct dependencies must be freed. HashMap>::Iterator E = dependency_map.find(p_id); @@ -185,1241 +93,174 @@ void RenderingDeviceVulkan::_free_dependencies(RID p_id) { } } -const VkFormat RenderingDeviceVulkan::vulkan_formats[RenderingDevice::DATA_FORMAT_MAX] = { - VK_FORMAT_R4G4_UNORM_PACK8, - VK_FORMAT_R4G4B4A4_UNORM_PACK16, - VK_FORMAT_B4G4R4A4_UNORM_PACK16, - VK_FORMAT_R5G6B5_UNORM_PACK16, - VK_FORMAT_B5G6R5_UNORM_PACK16, - VK_FORMAT_R5G5B5A1_UNORM_PACK16, - VK_FORMAT_B5G5R5A1_UNORM_PACK16, - VK_FORMAT_A1R5G5B5_UNORM_PACK16, - VK_FORMAT_R8_UNORM, - VK_FORMAT_R8_SNORM, - VK_FORMAT_R8_USCALED, - VK_FORMAT_R8_SSCALED, - VK_FORMAT_R8_UINT, - VK_FORMAT_R8_SINT, - VK_FORMAT_R8_SRGB, - VK_FORMAT_R8G8_UNORM, - VK_FORMAT_R8G8_SNORM, - VK_FORMAT_R8G8_USCALED, - VK_FORMAT_R8G8_SSCALED, - VK_FORMAT_R8G8_UINT, - VK_FORMAT_R8G8_SINT, - VK_FORMAT_R8G8_SRGB, - VK_FORMAT_R8G8B8_UNORM, - VK_FORMAT_R8G8B8_SNORM, - VK_FORMAT_R8G8B8_USCALED, - VK_FORMAT_R8G8B8_SSCALED, - VK_FORMAT_R8G8B8_UINT, - VK_FORMAT_R8G8B8_SINT, - VK_FORMAT_R8G8B8_SRGB, - VK_FORMAT_B8G8R8_UNORM, - VK_FORMAT_B8G8R8_SNORM, - VK_FORMAT_B8G8R8_USCALED, - VK_FORMAT_B8G8R8_SSCALED, - VK_FORMAT_B8G8R8_UINT, - VK_FORMAT_B8G8R8_SINT, - VK_FORMAT_B8G8R8_SRGB, - VK_FORMAT_R8G8B8A8_UNORM, - VK_FORMAT_R8G8B8A8_SNORM, - VK_FORMAT_R8G8B8A8_USCALED, - VK_FORMAT_R8G8B8A8_SSCALED, - VK_FORMAT_R8G8B8A8_UINT, - VK_FORMAT_R8G8B8A8_SINT, - VK_FORMAT_R8G8B8A8_SRGB, - VK_FORMAT_B8G8R8A8_UNORM, - VK_FORMAT_B8G8R8A8_SNORM, - VK_FORMAT_B8G8R8A8_USCALED, - VK_FORMAT_B8G8R8A8_SSCALED, - VK_FORMAT_B8G8R8A8_UINT, - VK_FORMAT_B8G8R8A8_SINT, - VK_FORMAT_B8G8R8A8_SRGB, - VK_FORMAT_A8B8G8R8_UNORM_PACK32, - VK_FORMAT_A8B8G8R8_SNORM_PACK32, - VK_FORMAT_A8B8G8R8_USCALED_PACK32, - VK_FORMAT_A8B8G8R8_SSCALED_PACK32, - VK_FORMAT_A8B8G8R8_UINT_PACK32, - VK_FORMAT_A8B8G8R8_SINT_PACK32, - VK_FORMAT_A8B8G8R8_SRGB_PACK32, - VK_FORMAT_A2R10G10B10_UNORM_PACK32, - VK_FORMAT_A2R10G10B10_SNORM_PACK32, - VK_FORMAT_A2R10G10B10_USCALED_PACK32, - VK_FORMAT_A2R10G10B10_SSCALED_PACK32, - VK_FORMAT_A2R10G10B10_UINT_PACK32, - VK_FORMAT_A2R10G10B10_SINT_PACK32, - VK_FORMAT_A2B10G10R10_UNORM_PACK32, - VK_FORMAT_A2B10G10R10_SNORM_PACK32, - VK_FORMAT_A2B10G10R10_USCALED_PACK32, - VK_FORMAT_A2B10G10R10_SSCALED_PACK32, - VK_FORMAT_A2B10G10R10_UINT_PACK32, - VK_FORMAT_A2B10G10R10_SINT_PACK32, - VK_FORMAT_R16_UNORM, - VK_FORMAT_R16_SNORM, - VK_FORMAT_R16_USCALED, - VK_FORMAT_R16_SSCALED, - VK_FORMAT_R16_UINT, - VK_FORMAT_R16_SINT, - VK_FORMAT_R16_SFLOAT, - VK_FORMAT_R16G16_UNORM, - VK_FORMAT_R16G16_SNORM, - VK_FORMAT_R16G16_USCALED, - VK_FORMAT_R16G16_SSCALED, - VK_FORMAT_R16G16_UINT, - VK_FORMAT_R16G16_SINT, - VK_FORMAT_R16G16_SFLOAT, - VK_FORMAT_R16G16B16_UNORM, - VK_FORMAT_R16G16B16_SNORM, - VK_FORMAT_R16G16B16_USCALED, - VK_FORMAT_R16G16B16_SSCALED, - VK_FORMAT_R16G16B16_UINT, - VK_FORMAT_R16G16B16_SINT, - VK_FORMAT_R16G16B16_SFLOAT, - VK_FORMAT_R16G16B16A16_UNORM, - VK_FORMAT_R16G16B16A16_SNORM, - VK_FORMAT_R16G16B16A16_USCALED, - VK_FORMAT_R16G16B16A16_SSCALED, - VK_FORMAT_R16G16B16A16_UINT, - VK_FORMAT_R16G16B16A16_SINT, - VK_FORMAT_R16G16B16A16_SFLOAT, - VK_FORMAT_R32_UINT, - VK_FORMAT_R32_SINT, - VK_FORMAT_R32_SFLOAT, - VK_FORMAT_R32G32_UINT, - VK_FORMAT_R32G32_SINT, - VK_FORMAT_R32G32_SFLOAT, - VK_FORMAT_R32G32B32_UINT, - VK_FORMAT_R32G32B32_SINT, - VK_FORMAT_R32G32B32_SFLOAT, - VK_FORMAT_R32G32B32A32_UINT, - VK_FORMAT_R32G32B32A32_SINT, - VK_FORMAT_R32G32B32A32_SFLOAT, - VK_FORMAT_R64_UINT, - VK_FORMAT_R64_SINT, - VK_FORMAT_R64_SFLOAT, - VK_FORMAT_R64G64_UINT, - VK_FORMAT_R64G64_SINT, - VK_FORMAT_R64G64_SFLOAT, - VK_FORMAT_R64G64B64_UINT, - VK_FORMAT_R64G64B64_SINT, - VK_FORMAT_R64G64B64_SFLOAT, - VK_FORMAT_R64G64B64A64_UINT, - VK_FORMAT_R64G64B64A64_SINT, - VK_FORMAT_R64G64B64A64_SFLOAT, - VK_FORMAT_B10G11R11_UFLOAT_PACK32, - VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, - VK_FORMAT_D16_UNORM, - VK_FORMAT_X8_D24_UNORM_PACK32, - VK_FORMAT_D32_SFLOAT, - VK_FORMAT_S8_UINT, - VK_FORMAT_D16_UNORM_S8_UINT, - VK_FORMAT_D24_UNORM_S8_UINT, - VK_FORMAT_D32_SFLOAT_S8_UINT, - VK_FORMAT_BC1_RGB_UNORM_BLOCK, - VK_FORMAT_BC1_RGB_SRGB_BLOCK, - VK_FORMAT_BC1_RGBA_UNORM_BLOCK, - VK_FORMAT_BC1_RGBA_SRGB_BLOCK, - VK_FORMAT_BC2_UNORM_BLOCK, - VK_FORMAT_BC2_SRGB_BLOCK, - VK_FORMAT_BC3_UNORM_BLOCK, - VK_FORMAT_BC3_SRGB_BLOCK, - VK_FORMAT_BC4_UNORM_BLOCK, - VK_FORMAT_BC4_SNORM_BLOCK, - VK_FORMAT_BC5_UNORM_BLOCK, - VK_FORMAT_BC5_SNORM_BLOCK, - VK_FORMAT_BC6H_UFLOAT_BLOCK, - VK_FORMAT_BC6H_SFLOAT_BLOCK, - VK_FORMAT_BC7_UNORM_BLOCK, - VK_FORMAT_BC7_SRGB_BLOCK, - VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK, - VK_FORMAT_ETC2_R8G8B8_SRGB_BLOCK, - VK_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK, - VK_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK, - VK_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK, - VK_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK, - VK_FORMAT_EAC_R11_UNORM_BLOCK, - VK_FORMAT_EAC_R11_SNORM_BLOCK, - VK_FORMAT_EAC_R11G11_UNORM_BLOCK, - VK_FORMAT_EAC_R11G11_SNORM_BLOCK, - VK_FORMAT_ASTC_4x4_UNORM_BLOCK, - VK_FORMAT_ASTC_4x4_SRGB_BLOCK, - VK_FORMAT_ASTC_5x4_UNORM_BLOCK, - VK_FORMAT_ASTC_5x4_SRGB_BLOCK, - VK_FORMAT_ASTC_5x5_UNORM_BLOCK, - VK_FORMAT_ASTC_5x5_SRGB_BLOCK, - VK_FORMAT_ASTC_6x5_UNORM_BLOCK, - VK_FORMAT_ASTC_6x5_SRGB_BLOCK, - VK_FORMAT_ASTC_6x6_UNORM_BLOCK, - VK_FORMAT_ASTC_6x6_SRGB_BLOCK, - VK_FORMAT_ASTC_8x5_UNORM_BLOCK, - VK_FORMAT_ASTC_8x5_SRGB_BLOCK, - VK_FORMAT_ASTC_8x6_UNORM_BLOCK, - VK_FORMAT_ASTC_8x6_SRGB_BLOCK, - VK_FORMAT_ASTC_8x8_UNORM_BLOCK, - VK_FORMAT_ASTC_8x8_SRGB_BLOCK, - VK_FORMAT_ASTC_10x5_UNORM_BLOCK, - VK_FORMAT_ASTC_10x5_SRGB_BLOCK, - VK_FORMAT_ASTC_10x6_UNORM_BLOCK, - VK_FORMAT_ASTC_10x6_SRGB_BLOCK, - VK_FORMAT_ASTC_10x8_UNORM_BLOCK, - VK_FORMAT_ASTC_10x8_SRGB_BLOCK, - VK_FORMAT_ASTC_10x10_UNORM_BLOCK, - VK_FORMAT_ASTC_10x10_SRGB_BLOCK, - VK_FORMAT_ASTC_12x10_UNORM_BLOCK, - VK_FORMAT_ASTC_12x10_SRGB_BLOCK, - VK_FORMAT_ASTC_12x12_UNORM_BLOCK, - VK_FORMAT_ASTC_12x12_SRGB_BLOCK, - VK_FORMAT_G8B8G8R8_422_UNORM, - VK_FORMAT_B8G8R8G8_422_UNORM, - VK_FORMAT_G8_B8_R8_3PLANE_420_UNORM, - VK_FORMAT_G8_B8R8_2PLANE_420_UNORM, - VK_FORMAT_G8_B8_R8_3PLANE_422_UNORM, - VK_FORMAT_G8_B8R8_2PLANE_422_UNORM, - VK_FORMAT_G8_B8_R8_3PLANE_444_UNORM, - VK_FORMAT_R10X6_UNORM_PACK16, - VK_FORMAT_R10X6G10X6_UNORM_2PACK16, - VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16, - VK_FORMAT_G10X6B10X6G10X6R10X6_422_UNORM_4PACK16, - VK_FORMAT_B10X6G10X6R10X6G10X6_422_UNORM_4PACK16, - VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_420_UNORM_3PACK16, - VK_FORMAT_G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16, - VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_422_UNORM_3PACK16, - VK_FORMAT_G10X6_B10X6R10X6_2PLANE_422_UNORM_3PACK16, - VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_444_UNORM_3PACK16, - VK_FORMAT_R12X4_UNORM_PACK16, - VK_FORMAT_R12X4G12X4_UNORM_2PACK16, - VK_FORMAT_R12X4G12X4B12X4A12X4_UNORM_4PACK16, - VK_FORMAT_G12X4B12X4G12X4R12X4_422_UNORM_4PACK16, - VK_FORMAT_B12X4G12X4R12X4G12X4_422_UNORM_4PACK16, - VK_FORMAT_G12X4_B12X4_R12X4_3PLANE_420_UNORM_3PACK16, - VK_FORMAT_G12X4_B12X4R12X4_2PLANE_420_UNORM_3PACK16, - VK_FORMAT_G12X4_B12X4_R12X4_3PLANE_422_UNORM_3PACK16, - VK_FORMAT_G12X4_B12X4R12X4_2PLANE_422_UNORM_3PACK16, - VK_FORMAT_G12X4_B12X4_R12X4_3PLANE_444_UNORM_3PACK16, - VK_FORMAT_G16B16G16R16_422_UNORM, - VK_FORMAT_B16G16R16G16_422_UNORM, - VK_FORMAT_G16_B16_R16_3PLANE_420_UNORM, - VK_FORMAT_G16_B16R16_2PLANE_420_UNORM, - VK_FORMAT_G16_B16_R16_3PLANE_422_UNORM, - VK_FORMAT_G16_B16R16_2PLANE_422_UNORM, - VK_FORMAT_G16_B16_R16_3PLANE_444_UNORM, -}; - -const char *RenderingDeviceVulkan::named_formats[RenderingDevice::DATA_FORMAT_MAX] = { - "R4G4_Unorm_Pack8", - "R4G4B4A4_Unorm_Pack16", - "B4G4R4A4_Unorm_Pack16", - "R5G6B5_Unorm_Pack16", - "B5G6R5_Unorm_Pack16", - "R5G5B5A1_Unorm_Pack16", - "B5G5R5A1_Unorm_Pack16", - "A1R5G5B5_Unorm_Pack16", - "R8_Unorm", - "R8_Snorm", - "R8_Uscaled", - "R8_Sscaled", - "R8_Uint", - "R8_Sint", - "R8_Srgb", - "R8G8_Unorm", - "R8G8_Snorm", - "R8G8_Uscaled", - "R8G8_Sscaled", - "R8G8_Uint", - "R8G8_Sint", - "R8G8_Srgb", - "R8G8B8_Unorm", - "R8G8B8_Snorm", - "R8G8B8_Uscaled", - "R8G8B8_Sscaled", - "R8G8B8_Uint", - "R8G8B8_Sint", - "R8G8B8_Srgb", - "B8G8R8_Unorm", - "B8G8R8_Snorm", - "B8G8R8_Uscaled", - "B8G8R8_Sscaled", - "B8G8R8_Uint", - "B8G8R8_Sint", - "B8G8R8_Srgb", - "R8G8B8A8_Unorm", - "R8G8B8A8_Snorm", - "R8G8B8A8_Uscaled", - "R8G8B8A8_Sscaled", - "R8G8B8A8_Uint", - "R8G8B8A8_Sint", - "R8G8B8A8_Srgb", - "B8G8R8A8_Unorm", - "B8G8R8A8_Snorm", - "B8G8R8A8_Uscaled", - "B8G8R8A8_Sscaled", - "B8G8R8A8_Uint", - "B8G8R8A8_Sint", - "B8G8R8A8_Srgb", - "A8B8G8R8_Unorm_Pack32", - "A8B8G8R8_Snorm_Pack32", - "A8B8G8R8_Uscaled_Pack32", - "A8B8G8R8_Sscaled_Pack32", - "A8B8G8R8_Uint_Pack32", - "A8B8G8R8_Sint_Pack32", - "A8B8G8R8_Srgb_Pack32", - "A2R10G10B10_Unorm_Pack32", - "A2R10G10B10_Snorm_Pack32", - "A2R10G10B10_Uscaled_Pack32", - "A2R10G10B10_Sscaled_Pack32", - "A2R10G10B10_Uint_Pack32", - "A2R10G10B10_Sint_Pack32", - "A2B10G10R10_Unorm_Pack32", - "A2B10G10R10_Snorm_Pack32", - "A2B10G10R10_Uscaled_Pack32", - "A2B10G10R10_Sscaled_Pack32", - "A2B10G10R10_Uint_Pack32", - "A2B10G10R10_Sint_Pack32", - "R16_Unorm", - "R16_Snorm", - "R16_Uscaled", - "R16_Sscaled", - "R16_Uint", - "R16_Sint", - "R16_Sfloat", - "R16G16_Unorm", - "R16G16_Snorm", - "R16G16_Uscaled", - "R16G16_Sscaled", - "R16G16_Uint", - "R16G16_Sint", - "R16G16_Sfloat", - "R16G16B16_Unorm", - "R16G16B16_Snorm", - "R16G16B16_Uscaled", - "R16G16B16_Sscaled", - "R16G16B16_Uint", - "R16G16B16_Sint", - "R16G16B16_Sfloat", - "R16G16B16A16_Unorm", - "R16G16B16A16_Snorm", - "R16G16B16A16_Uscaled", - "R16G16B16A16_Sscaled", - "R16G16B16A16_Uint", - "R16G16B16A16_Sint", - "R16G16B16A16_Sfloat", - "R32_Uint", - "R32_Sint", - "R32_Sfloat", - "R32G32_Uint", - "R32G32_Sint", - "R32G32_Sfloat", - "R32G32B32_Uint", - "R32G32B32_Sint", - "R32G32B32_Sfloat", - "R32G32B32A32_Uint", - "R32G32B32A32_Sint", - "R32G32B32A32_Sfloat", - "R64_Uint", - "R64_Sint", - "R64_Sfloat", - "R64G64_Uint", - "R64G64_Sint", - "R64G64_Sfloat", - "R64G64B64_Uint", - "R64G64B64_Sint", - "R64G64B64_Sfloat", - "R64G64B64A64_Uint", - "R64G64B64A64_Sint", - "R64G64B64A64_Sfloat", - "B10G11R11_Ufloat_Pack32", - "E5B9G9R9_Ufloat_Pack32", - "D16_Unorm", - "X8_D24_Unorm_Pack32", - "D32_Sfloat", - "S8_Uint", - "D16_Unorm_S8_Uint", - "D24_Unorm_S8_Uint", - "D32_Sfloat_S8_Uint", - "Bc1_Rgb_Unorm_Block", - "Bc1_Rgb_Srgb_Block", - "Bc1_Rgba_Unorm_Block", - "Bc1_Rgba_Srgb_Block", - "Bc2_Unorm_Block", - "Bc2_Srgb_Block", - "Bc3_Unorm_Block", - "Bc3_Srgb_Block", - "Bc4_Unorm_Block", - "Bc4_Snorm_Block", - "Bc5_Unorm_Block", - "Bc5_Snorm_Block", - "Bc6H_Ufloat_Block", - "Bc6H_Sfloat_Block", - "Bc7_Unorm_Block", - "Bc7_Srgb_Block", - "Etc2_R8G8B8_Unorm_Block", - "Etc2_R8G8B8_Srgb_Block", - "Etc2_R8G8B8A1_Unorm_Block", - "Etc2_R8G8B8A1_Srgb_Block", - "Etc2_R8G8B8A8_Unorm_Block", - "Etc2_R8G8B8A8_Srgb_Block", - "Eac_R11_Unorm_Block", - "Eac_R11_Snorm_Block", - "Eac_R11G11_Unorm_Block", - "Eac_R11G11_Snorm_Block", - "Astc_4X4_Unorm_Block", - "Astc_4X4_Srgb_Block", - "Astc_5X4_Unorm_Block", - "Astc_5X4_Srgb_Block", - "Astc_5X5_Unorm_Block", - "Astc_5X5_Srgb_Block", - "Astc_6X5_Unorm_Block", - "Astc_6X5_Srgb_Block", - "Astc_6X6_Unorm_Block", - "Astc_6X6_Srgb_Block", - "Astc_8X5_Unorm_Block", - "Astc_8X5_Srgb_Block", - "Astc_8X6_Unorm_Block", - "Astc_8X6_Srgb_Block", - "Astc_8X8_Unorm_Block", - "Astc_8X8_Srgb_Block", - "Astc_10X5_Unorm_Block", - "Astc_10X5_Srgb_Block", - "Astc_10X6_Unorm_Block", - "Astc_10X6_Srgb_Block", - "Astc_10X8_Unorm_Block", - "Astc_10X8_Srgb_Block", - "Astc_10X10_Unorm_Block", - "Astc_10X10_Srgb_Block", - "Astc_12X10_Unorm_Block", - "Astc_12X10_Srgb_Block", - "Astc_12X12_Unorm_Block", - "Astc_12X12_Srgb_Block", - "G8B8G8R8_422_Unorm", - "B8G8R8G8_422_Unorm", - "G8_B8_R8_3Plane_420_Unorm", - "G8_B8R8_2Plane_420_Unorm", - "G8_B8_R8_3Plane_422_Unorm", - "G8_B8R8_2Plane_422_Unorm", - "G8_B8_R8_3Plane_444_Unorm", - "R10X6_Unorm_Pack16", - "R10X6G10X6_Unorm_2Pack16", - "R10X6G10X6B10X6A10X6_Unorm_4Pack16", - "G10X6B10X6G10X6R10X6_422_Unorm_4Pack16", - "B10X6G10X6R10X6G10X6_422_Unorm_4Pack16", - "G10X6_B10X6_R10X6_3Plane_420_Unorm_3Pack16", - "G10X6_B10X6R10X6_2Plane_420_Unorm_3Pack16", - "G10X6_B10X6_R10X6_3Plane_422_Unorm_3Pack16", - "G10X6_B10X6R10X6_2Plane_422_Unorm_3Pack16", - "G10X6_B10X6_R10X6_3Plane_444_Unorm_3Pack16", - "R12X4_Unorm_Pack16", - "R12X4G12X4_Unorm_2Pack16", - "R12X4G12X4B12X4A12X4_Unorm_4Pack16", - "G12X4B12X4G12X4R12X4_422_Unorm_4Pack16", - "B12X4G12X4R12X4G12X4_422_Unorm_4Pack16", - "G12X4_B12X4_R12X4_3Plane_420_Unorm_3Pack16", - "G12X4_B12X4R12X4_2Plane_420_Unorm_3Pack16", - "G12X4_B12X4_R12X4_3Plane_422_Unorm_3Pack16", - "G12X4_B12X4R12X4_2Plane_422_Unorm_3Pack16", - "G12X4_B12X4_R12X4_3Plane_444_Unorm_3Pack16", - "G16B16G16R16_422_Unorm", - "B16G16R16G16_422_Unorm", - "G16_B16_R16_3Plane_420_Unorm", - "G16_B16R16_2Plane_420_Unorm", - "G16_B16_R16_3Plane_422_Unorm", - "G16_B16R16_2Plane_422_Unorm", - "G16_B16_R16_3Plane_444_Unorm", -}; - -int RenderingDeviceVulkan::get_format_vertex_size(DataFormat p_format) { - switch (p_format) { - case DATA_FORMAT_R8_UNORM: - case DATA_FORMAT_R8_SNORM: - case DATA_FORMAT_R8_UINT: - case DATA_FORMAT_R8_SINT: - case DATA_FORMAT_R8G8_UNORM: - case DATA_FORMAT_R8G8_SNORM: - case DATA_FORMAT_R8G8_UINT: - case DATA_FORMAT_R8G8_SINT: - case DATA_FORMAT_R8G8B8_UNORM: - case DATA_FORMAT_R8G8B8_SNORM: - case DATA_FORMAT_R8G8B8_UINT: - case DATA_FORMAT_R8G8B8_SINT: - case DATA_FORMAT_B8G8R8_UNORM: - case DATA_FORMAT_B8G8R8_SNORM: - case DATA_FORMAT_B8G8R8_UINT: - case DATA_FORMAT_B8G8R8_SINT: - case DATA_FORMAT_R8G8B8A8_UNORM: - case DATA_FORMAT_R8G8B8A8_SNORM: - case DATA_FORMAT_R8G8B8A8_UINT: - case DATA_FORMAT_R8G8B8A8_SINT: - case DATA_FORMAT_B8G8R8A8_UNORM: - case DATA_FORMAT_B8G8R8A8_SNORM: - case DATA_FORMAT_B8G8R8A8_UINT: - case DATA_FORMAT_B8G8R8A8_SINT: - case DATA_FORMAT_A2B10G10R10_UNORM_PACK32: - return 4; - case DATA_FORMAT_R16_UNORM: - case DATA_FORMAT_R16_SNORM: - case DATA_FORMAT_R16_UINT: - case DATA_FORMAT_R16_SINT: - case DATA_FORMAT_R16_SFLOAT: - return 4; - case DATA_FORMAT_R16G16_UNORM: - case DATA_FORMAT_R16G16_SNORM: - case DATA_FORMAT_R16G16_UINT: - case DATA_FORMAT_R16G16_SINT: - case DATA_FORMAT_R16G16_SFLOAT: - return 4; - case DATA_FORMAT_R16G16B16_UNORM: - case DATA_FORMAT_R16G16B16_SNORM: - case DATA_FORMAT_R16G16B16_UINT: - case DATA_FORMAT_R16G16B16_SINT: - case DATA_FORMAT_R16G16B16_SFLOAT: - return 8; - case DATA_FORMAT_R16G16B16A16_UNORM: - case DATA_FORMAT_R16G16B16A16_SNORM: - case DATA_FORMAT_R16G16B16A16_UINT: - case DATA_FORMAT_R16G16B16A16_SINT: - case DATA_FORMAT_R16G16B16A16_SFLOAT: - return 8; - case DATA_FORMAT_R32_UINT: - case DATA_FORMAT_R32_SINT: - case DATA_FORMAT_R32_SFLOAT: - return 4; - case DATA_FORMAT_R32G32_UINT: - case DATA_FORMAT_R32G32_SINT: - case DATA_FORMAT_R32G32_SFLOAT: - return 8; - case DATA_FORMAT_R32G32B32_UINT: - case DATA_FORMAT_R32G32B32_SINT: - case DATA_FORMAT_R32G32B32_SFLOAT: - return 12; - case DATA_FORMAT_R32G32B32A32_UINT: - case DATA_FORMAT_R32G32B32A32_SINT: - case DATA_FORMAT_R32G32B32A32_SFLOAT: - return 16; - case DATA_FORMAT_R64_UINT: - case DATA_FORMAT_R64_SINT: - case DATA_FORMAT_R64_SFLOAT: - return 8; - case DATA_FORMAT_R64G64_UINT: - case DATA_FORMAT_R64G64_SINT: - case DATA_FORMAT_R64G64_SFLOAT: - return 16; - case DATA_FORMAT_R64G64B64_UINT: - case DATA_FORMAT_R64G64B64_SINT: - case DATA_FORMAT_R64G64B64_SFLOAT: - return 24; - case DATA_FORMAT_R64G64B64A64_UINT: - case DATA_FORMAT_R64G64B64A64_SINT: - case DATA_FORMAT_R64G64B64A64_SFLOAT: - return 32; - default: - return 0; - } +void RenderingDevice::shader_set_compile_to_spirv_function(ShaderCompileToSPIRVFunction p_function) { + compile_to_spirv_function = p_function; } -uint32_t RenderingDeviceVulkan::get_image_format_pixel_size(DataFormat p_format) { - switch (p_format) { - case DATA_FORMAT_R4G4_UNORM_PACK8: - return 1; - case DATA_FORMAT_R4G4B4A4_UNORM_PACK16: - case DATA_FORMAT_B4G4R4A4_UNORM_PACK16: - case DATA_FORMAT_R5G6B5_UNORM_PACK16: - case DATA_FORMAT_B5G6R5_UNORM_PACK16: - case DATA_FORMAT_R5G5B5A1_UNORM_PACK16: - case DATA_FORMAT_B5G5R5A1_UNORM_PACK16: - case DATA_FORMAT_A1R5G5B5_UNORM_PACK16: - return 2; - case DATA_FORMAT_R8_UNORM: - case DATA_FORMAT_R8_SNORM: - case DATA_FORMAT_R8_USCALED: - case DATA_FORMAT_R8_SSCALED: - case DATA_FORMAT_R8_UINT: - case DATA_FORMAT_R8_SINT: - case DATA_FORMAT_R8_SRGB: - return 1; - case DATA_FORMAT_R8G8_UNORM: - case DATA_FORMAT_R8G8_SNORM: - case DATA_FORMAT_R8G8_USCALED: - case DATA_FORMAT_R8G8_SSCALED: - case DATA_FORMAT_R8G8_UINT: - case DATA_FORMAT_R8G8_SINT: - case DATA_FORMAT_R8G8_SRGB: - return 2; - case DATA_FORMAT_R8G8B8_UNORM: - case DATA_FORMAT_R8G8B8_SNORM: - case DATA_FORMAT_R8G8B8_USCALED: - case DATA_FORMAT_R8G8B8_SSCALED: - case DATA_FORMAT_R8G8B8_UINT: - case DATA_FORMAT_R8G8B8_SINT: - case DATA_FORMAT_R8G8B8_SRGB: - case DATA_FORMAT_B8G8R8_UNORM: - case DATA_FORMAT_B8G8R8_SNORM: - case DATA_FORMAT_B8G8R8_USCALED: - case DATA_FORMAT_B8G8R8_SSCALED: - case DATA_FORMAT_B8G8R8_UINT: - case DATA_FORMAT_B8G8R8_SINT: - case DATA_FORMAT_B8G8R8_SRGB: - return 3; - case DATA_FORMAT_R8G8B8A8_UNORM: - case DATA_FORMAT_R8G8B8A8_SNORM: - case DATA_FORMAT_R8G8B8A8_USCALED: - case DATA_FORMAT_R8G8B8A8_SSCALED: - case DATA_FORMAT_R8G8B8A8_UINT: - case DATA_FORMAT_R8G8B8A8_SINT: - case DATA_FORMAT_R8G8B8A8_SRGB: - case DATA_FORMAT_B8G8R8A8_UNORM: - case DATA_FORMAT_B8G8R8A8_SNORM: - case DATA_FORMAT_B8G8R8A8_USCALED: - case DATA_FORMAT_B8G8R8A8_SSCALED: - case DATA_FORMAT_B8G8R8A8_UINT: - case DATA_FORMAT_B8G8R8A8_SINT: - case DATA_FORMAT_B8G8R8A8_SRGB: - return 4; - case DATA_FORMAT_A8B8G8R8_UNORM_PACK32: - case DATA_FORMAT_A8B8G8R8_SNORM_PACK32: - case DATA_FORMAT_A8B8G8R8_USCALED_PACK32: - case DATA_FORMAT_A8B8G8R8_SSCALED_PACK32: - case DATA_FORMAT_A8B8G8R8_UINT_PACK32: - case DATA_FORMAT_A8B8G8R8_SINT_PACK32: - case DATA_FORMAT_A8B8G8R8_SRGB_PACK32: - case DATA_FORMAT_A2R10G10B10_UNORM_PACK32: - case DATA_FORMAT_A2R10G10B10_SNORM_PACK32: - case DATA_FORMAT_A2R10G10B10_USCALED_PACK32: - case DATA_FORMAT_A2R10G10B10_SSCALED_PACK32: - case DATA_FORMAT_A2R10G10B10_UINT_PACK32: - case DATA_FORMAT_A2R10G10B10_SINT_PACK32: - case DATA_FORMAT_A2B10G10R10_UNORM_PACK32: - case DATA_FORMAT_A2B10G10R10_SNORM_PACK32: - case DATA_FORMAT_A2B10G10R10_USCALED_PACK32: - case DATA_FORMAT_A2B10G10R10_SSCALED_PACK32: - case DATA_FORMAT_A2B10G10R10_UINT_PACK32: - case DATA_FORMAT_A2B10G10R10_SINT_PACK32: - return 4; - case DATA_FORMAT_R16_UNORM: - case DATA_FORMAT_R16_SNORM: - case DATA_FORMAT_R16_USCALED: - case DATA_FORMAT_R16_SSCALED: - case DATA_FORMAT_R16_UINT: - case DATA_FORMAT_R16_SINT: - case DATA_FORMAT_R16_SFLOAT: - return 2; - case DATA_FORMAT_R16G16_UNORM: - case DATA_FORMAT_R16G16_SNORM: - case DATA_FORMAT_R16G16_USCALED: - case DATA_FORMAT_R16G16_SSCALED: - case DATA_FORMAT_R16G16_UINT: - case DATA_FORMAT_R16G16_SINT: - case DATA_FORMAT_R16G16_SFLOAT: - return 4; - case DATA_FORMAT_R16G16B16_UNORM: - case DATA_FORMAT_R16G16B16_SNORM: - case DATA_FORMAT_R16G16B16_USCALED: - case DATA_FORMAT_R16G16B16_SSCALED: - case DATA_FORMAT_R16G16B16_UINT: - case DATA_FORMAT_R16G16B16_SINT: - case DATA_FORMAT_R16G16B16_SFLOAT: - return 6; - case DATA_FORMAT_R16G16B16A16_UNORM: - case DATA_FORMAT_R16G16B16A16_SNORM: - case DATA_FORMAT_R16G16B16A16_USCALED: - case DATA_FORMAT_R16G16B16A16_SSCALED: - case DATA_FORMAT_R16G16B16A16_UINT: - case DATA_FORMAT_R16G16B16A16_SINT: - case DATA_FORMAT_R16G16B16A16_SFLOAT: - return 8; - case DATA_FORMAT_R32_UINT: - case DATA_FORMAT_R32_SINT: - case DATA_FORMAT_R32_SFLOAT: - return 4; - case DATA_FORMAT_R32G32_UINT: - case DATA_FORMAT_R32G32_SINT: - case DATA_FORMAT_R32G32_SFLOAT: - return 8; - case DATA_FORMAT_R32G32B32_UINT: - case DATA_FORMAT_R32G32B32_SINT: - case DATA_FORMAT_R32G32B32_SFLOAT: - return 12; - case DATA_FORMAT_R32G32B32A32_UINT: - case DATA_FORMAT_R32G32B32A32_SINT: - case DATA_FORMAT_R32G32B32A32_SFLOAT: - return 16; - case DATA_FORMAT_R64_UINT: - case DATA_FORMAT_R64_SINT: - case DATA_FORMAT_R64_SFLOAT: - return 8; - case DATA_FORMAT_R64G64_UINT: - case DATA_FORMAT_R64G64_SINT: - case DATA_FORMAT_R64G64_SFLOAT: - return 16; - case DATA_FORMAT_R64G64B64_UINT: - case DATA_FORMAT_R64G64B64_SINT: - case DATA_FORMAT_R64G64B64_SFLOAT: - return 24; - case DATA_FORMAT_R64G64B64A64_UINT: - case DATA_FORMAT_R64G64B64A64_SINT: - case DATA_FORMAT_R64G64B64A64_SFLOAT: - return 32; - case DATA_FORMAT_B10G11R11_UFLOAT_PACK32: - case DATA_FORMAT_E5B9G9R9_UFLOAT_PACK32: - return 4; - case DATA_FORMAT_D16_UNORM: - return 2; - case DATA_FORMAT_X8_D24_UNORM_PACK32: - return 4; - case DATA_FORMAT_D32_SFLOAT: - return 4; - case DATA_FORMAT_S8_UINT: - return 1; - case DATA_FORMAT_D16_UNORM_S8_UINT: - return 4; - case DATA_FORMAT_D24_UNORM_S8_UINT: - return 4; - case DATA_FORMAT_D32_SFLOAT_S8_UINT: - return 5; // ? - case DATA_FORMAT_BC1_RGB_UNORM_BLOCK: - case DATA_FORMAT_BC1_RGB_SRGB_BLOCK: - case DATA_FORMAT_BC1_RGBA_UNORM_BLOCK: - case DATA_FORMAT_BC1_RGBA_SRGB_BLOCK: - case DATA_FORMAT_BC2_UNORM_BLOCK: - case DATA_FORMAT_BC2_SRGB_BLOCK: - case DATA_FORMAT_BC3_UNORM_BLOCK: - case DATA_FORMAT_BC3_SRGB_BLOCK: - case DATA_FORMAT_BC4_UNORM_BLOCK: - case DATA_FORMAT_BC4_SNORM_BLOCK: - case DATA_FORMAT_BC5_UNORM_BLOCK: - case DATA_FORMAT_BC5_SNORM_BLOCK: - case DATA_FORMAT_BC6H_UFLOAT_BLOCK: - case DATA_FORMAT_BC6H_SFLOAT_BLOCK: - case DATA_FORMAT_BC7_UNORM_BLOCK: - case DATA_FORMAT_BC7_SRGB_BLOCK: - return 1; - case DATA_FORMAT_ETC2_R8G8B8_UNORM_BLOCK: - case DATA_FORMAT_ETC2_R8G8B8_SRGB_BLOCK: - case DATA_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK: - case DATA_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK: - case DATA_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK: - case DATA_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK: - return 1; - case DATA_FORMAT_EAC_R11_UNORM_BLOCK: - case DATA_FORMAT_EAC_R11_SNORM_BLOCK: - case DATA_FORMAT_EAC_R11G11_UNORM_BLOCK: - case DATA_FORMAT_EAC_R11G11_SNORM_BLOCK: - return 1; - case DATA_FORMAT_ASTC_4x4_UNORM_BLOCK: - case DATA_FORMAT_ASTC_4x4_SRGB_BLOCK: - case DATA_FORMAT_ASTC_5x4_UNORM_BLOCK: - case DATA_FORMAT_ASTC_5x4_SRGB_BLOCK: - case DATA_FORMAT_ASTC_5x5_UNORM_BLOCK: - case DATA_FORMAT_ASTC_5x5_SRGB_BLOCK: - case DATA_FORMAT_ASTC_6x5_UNORM_BLOCK: - case DATA_FORMAT_ASTC_6x5_SRGB_BLOCK: - case DATA_FORMAT_ASTC_6x6_UNORM_BLOCK: - case DATA_FORMAT_ASTC_6x6_SRGB_BLOCK: - case DATA_FORMAT_ASTC_8x5_UNORM_BLOCK: - case DATA_FORMAT_ASTC_8x5_SRGB_BLOCK: - case DATA_FORMAT_ASTC_8x6_UNORM_BLOCK: - case DATA_FORMAT_ASTC_8x6_SRGB_BLOCK: - case DATA_FORMAT_ASTC_8x8_UNORM_BLOCK: - case DATA_FORMAT_ASTC_8x8_SRGB_BLOCK: - case DATA_FORMAT_ASTC_10x5_UNORM_BLOCK: - case DATA_FORMAT_ASTC_10x5_SRGB_BLOCK: - case DATA_FORMAT_ASTC_10x6_UNORM_BLOCK: - case DATA_FORMAT_ASTC_10x6_SRGB_BLOCK: - case DATA_FORMAT_ASTC_10x8_UNORM_BLOCK: - case DATA_FORMAT_ASTC_10x8_SRGB_BLOCK: - case DATA_FORMAT_ASTC_10x10_UNORM_BLOCK: - case DATA_FORMAT_ASTC_10x10_SRGB_BLOCK: - case DATA_FORMAT_ASTC_12x10_UNORM_BLOCK: - case DATA_FORMAT_ASTC_12x10_SRGB_BLOCK: - case DATA_FORMAT_ASTC_12x12_UNORM_BLOCK: - case DATA_FORMAT_ASTC_12x12_SRGB_BLOCK: - return 1; - case DATA_FORMAT_G8B8G8R8_422_UNORM: - case DATA_FORMAT_B8G8R8G8_422_UNORM: - return 4; - case DATA_FORMAT_G8_B8_R8_3PLANE_420_UNORM: - case DATA_FORMAT_G8_B8R8_2PLANE_420_UNORM: - case DATA_FORMAT_G8_B8_R8_3PLANE_422_UNORM: - case DATA_FORMAT_G8_B8R8_2PLANE_422_UNORM: - case DATA_FORMAT_G8_B8_R8_3PLANE_444_UNORM: - return 4; - case DATA_FORMAT_R10X6_UNORM_PACK16: - case DATA_FORMAT_R10X6G10X6_UNORM_2PACK16: - case DATA_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16: - case DATA_FORMAT_G10X6B10X6G10X6R10X6_422_UNORM_4PACK16: - case DATA_FORMAT_B10X6G10X6R10X6G10X6_422_UNORM_4PACK16: - case DATA_FORMAT_G10X6_B10X6_R10X6_3PLANE_420_UNORM_3PACK16: - case DATA_FORMAT_G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16: - case DATA_FORMAT_G10X6_B10X6_R10X6_3PLANE_422_UNORM_3PACK16: - case DATA_FORMAT_G10X6_B10X6R10X6_2PLANE_422_UNORM_3PACK16: - case DATA_FORMAT_G10X6_B10X6_R10X6_3PLANE_444_UNORM_3PACK16: - case DATA_FORMAT_R12X4_UNORM_PACK16: - case DATA_FORMAT_R12X4G12X4_UNORM_2PACK16: - case DATA_FORMAT_R12X4G12X4B12X4A12X4_UNORM_4PACK16: - case DATA_FORMAT_G12X4B12X4G12X4R12X4_422_UNORM_4PACK16: - case DATA_FORMAT_B12X4G12X4R12X4G12X4_422_UNORM_4PACK16: - case DATA_FORMAT_G12X4_B12X4_R12X4_3PLANE_420_UNORM_3PACK16: - case DATA_FORMAT_G12X4_B12X4R12X4_2PLANE_420_UNORM_3PACK16: - case DATA_FORMAT_G12X4_B12X4_R12X4_3PLANE_422_UNORM_3PACK16: - case DATA_FORMAT_G12X4_B12X4R12X4_2PLANE_422_UNORM_3PACK16: - case DATA_FORMAT_G12X4_B12X4_R12X4_3PLANE_444_UNORM_3PACK16: - return 2; - case DATA_FORMAT_G16B16G16R16_422_UNORM: - case DATA_FORMAT_B16G16R16G16_422_UNORM: - case DATA_FORMAT_G16_B16_R16_3PLANE_420_UNORM: - case DATA_FORMAT_G16_B16R16_2PLANE_420_UNORM: - case DATA_FORMAT_G16_B16_R16_3PLANE_422_UNORM: - case DATA_FORMAT_G16_B16R16_2PLANE_422_UNORM: - case DATA_FORMAT_G16_B16_R16_3PLANE_444_UNORM: - return 8; - default: { - ERR_PRINT("Format not handled, bug"); - } - } - - return 1; -} - -// https://www.khronos.org/registry/DataFormat/specs/1.1/dataformat.1.1.pdf - -void RenderingDeviceVulkan::get_compressed_image_format_block_dimensions(DataFormat p_format, uint32_t &r_w, uint32_t &r_h) { - switch (p_format) { - case DATA_FORMAT_BC1_RGB_UNORM_BLOCK: - case DATA_FORMAT_BC1_RGB_SRGB_BLOCK: - case DATA_FORMAT_BC1_RGBA_UNORM_BLOCK: - case DATA_FORMAT_BC1_RGBA_SRGB_BLOCK: - case DATA_FORMAT_BC2_UNORM_BLOCK: - case DATA_FORMAT_BC2_SRGB_BLOCK: - case DATA_FORMAT_BC3_UNORM_BLOCK: - case DATA_FORMAT_BC3_SRGB_BLOCK: - case DATA_FORMAT_BC4_UNORM_BLOCK: - case DATA_FORMAT_BC4_SNORM_BLOCK: - case DATA_FORMAT_BC5_UNORM_BLOCK: - case DATA_FORMAT_BC5_SNORM_BLOCK: - case DATA_FORMAT_BC6H_UFLOAT_BLOCK: - case DATA_FORMAT_BC6H_SFLOAT_BLOCK: - case DATA_FORMAT_BC7_UNORM_BLOCK: - case DATA_FORMAT_BC7_SRGB_BLOCK: - case DATA_FORMAT_ETC2_R8G8B8_UNORM_BLOCK: - case DATA_FORMAT_ETC2_R8G8B8_SRGB_BLOCK: - case DATA_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK: - case DATA_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK: - case DATA_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK: - case DATA_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK: - case DATA_FORMAT_EAC_R11_UNORM_BLOCK: - case DATA_FORMAT_EAC_R11_SNORM_BLOCK: - case DATA_FORMAT_EAC_R11G11_UNORM_BLOCK: - case DATA_FORMAT_EAC_R11G11_SNORM_BLOCK: - case DATA_FORMAT_ASTC_4x4_UNORM_BLOCK: // Again, not sure about astc. - case DATA_FORMAT_ASTC_4x4_SRGB_BLOCK: { - r_w = 4; - r_h = 4; - } break; - case DATA_FORMAT_ASTC_5x4_UNORM_BLOCK: // Unsupported - case DATA_FORMAT_ASTC_5x4_SRGB_BLOCK: - case DATA_FORMAT_ASTC_5x5_UNORM_BLOCK: - case DATA_FORMAT_ASTC_5x5_SRGB_BLOCK: - case DATA_FORMAT_ASTC_6x5_UNORM_BLOCK: - case DATA_FORMAT_ASTC_6x5_SRGB_BLOCK: - case DATA_FORMAT_ASTC_6x6_UNORM_BLOCK: - case DATA_FORMAT_ASTC_6x6_SRGB_BLOCK: - case DATA_FORMAT_ASTC_8x5_UNORM_BLOCK: - case DATA_FORMAT_ASTC_8x5_SRGB_BLOCK: - case DATA_FORMAT_ASTC_8x6_UNORM_BLOCK: - case DATA_FORMAT_ASTC_8x6_SRGB_BLOCK: { - r_w = 4; - r_h = 4; - } break; - case DATA_FORMAT_ASTC_8x8_UNORM_BLOCK: - case DATA_FORMAT_ASTC_8x8_SRGB_BLOCK: { - r_w = 8; - r_h = 8; - } break; - case DATA_FORMAT_ASTC_10x5_UNORM_BLOCK: // Unsupported - case DATA_FORMAT_ASTC_10x5_SRGB_BLOCK: - case DATA_FORMAT_ASTC_10x6_UNORM_BLOCK: - case DATA_FORMAT_ASTC_10x6_SRGB_BLOCK: - case DATA_FORMAT_ASTC_10x8_UNORM_BLOCK: - case DATA_FORMAT_ASTC_10x8_SRGB_BLOCK: - case DATA_FORMAT_ASTC_10x10_UNORM_BLOCK: - case DATA_FORMAT_ASTC_10x10_SRGB_BLOCK: - case DATA_FORMAT_ASTC_12x10_UNORM_BLOCK: - case DATA_FORMAT_ASTC_12x10_SRGB_BLOCK: - case DATA_FORMAT_ASTC_12x12_UNORM_BLOCK: - case DATA_FORMAT_ASTC_12x12_SRGB_BLOCK: - r_w = 4; - r_h = 4; - return; - default: { - r_w = 1; - r_h = 1; - } - } -} - -uint32_t RenderingDeviceVulkan::get_compressed_image_format_block_byte_size(DataFormat p_format) { - switch (p_format) { - case DATA_FORMAT_BC1_RGB_UNORM_BLOCK: - case DATA_FORMAT_BC1_RGB_SRGB_BLOCK: - case DATA_FORMAT_BC1_RGBA_UNORM_BLOCK: - case DATA_FORMAT_BC1_RGBA_SRGB_BLOCK: - return 8; - case DATA_FORMAT_BC2_UNORM_BLOCK: - case DATA_FORMAT_BC2_SRGB_BLOCK: - return 16; - case DATA_FORMAT_BC3_UNORM_BLOCK: - case DATA_FORMAT_BC3_SRGB_BLOCK: - return 16; - case DATA_FORMAT_BC4_UNORM_BLOCK: - case DATA_FORMAT_BC4_SNORM_BLOCK: - return 8; - case DATA_FORMAT_BC5_UNORM_BLOCK: - case DATA_FORMAT_BC5_SNORM_BLOCK: - return 16; - case DATA_FORMAT_BC6H_UFLOAT_BLOCK: - case DATA_FORMAT_BC6H_SFLOAT_BLOCK: - return 16; - case DATA_FORMAT_BC7_UNORM_BLOCK: - case DATA_FORMAT_BC7_SRGB_BLOCK: - return 16; - case DATA_FORMAT_ETC2_R8G8B8_UNORM_BLOCK: - case DATA_FORMAT_ETC2_R8G8B8_SRGB_BLOCK: - return 8; - case DATA_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK: - case DATA_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK: - return 8; - case DATA_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK: - case DATA_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK: - return 16; - case DATA_FORMAT_EAC_R11_UNORM_BLOCK: - case DATA_FORMAT_EAC_R11_SNORM_BLOCK: - return 8; - case DATA_FORMAT_EAC_R11G11_UNORM_BLOCK: - case DATA_FORMAT_EAC_R11G11_SNORM_BLOCK: - return 16; - case DATA_FORMAT_ASTC_4x4_UNORM_BLOCK: // Again, not sure about astc. - case DATA_FORMAT_ASTC_4x4_SRGB_BLOCK: - case DATA_FORMAT_ASTC_5x4_UNORM_BLOCK: - case DATA_FORMAT_ASTC_5x4_SRGB_BLOCK: - case DATA_FORMAT_ASTC_5x5_UNORM_BLOCK: - case DATA_FORMAT_ASTC_5x5_SRGB_BLOCK: - case DATA_FORMAT_ASTC_6x5_UNORM_BLOCK: - case DATA_FORMAT_ASTC_6x5_SRGB_BLOCK: - case DATA_FORMAT_ASTC_6x6_UNORM_BLOCK: - case DATA_FORMAT_ASTC_6x6_SRGB_BLOCK: - case DATA_FORMAT_ASTC_8x5_UNORM_BLOCK: - case DATA_FORMAT_ASTC_8x5_SRGB_BLOCK: - case DATA_FORMAT_ASTC_8x6_UNORM_BLOCK: - case DATA_FORMAT_ASTC_8x6_SRGB_BLOCK: - case DATA_FORMAT_ASTC_8x8_UNORM_BLOCK: - case DATA_FORMAT_ASTC_8x8_SRGB_BLOCK: - case DATA_FORMAT_ASTC_10x5_UNORM_BLOCK: - case DATA_FORMAT_ASTC_10x5_SRGB_BLOCK: - case DATA_FORMAT_ASTC_10x6_UNORM_BLOCK: - case DATA_FORMAT_ASTC_10x6_SRGB_BLOCK: - case DATA_FORMAT_ASTC_10x8_UNORM_BLOCK: - case DATA_FORMAT_ASTC_10x8_SRGB_BLOCK: - case DATA_FORMAT_ASTC_10x10_UNORM_BLOCK: - case DATA_FORMAT_ASTC_10x10_SRGB_BLOCK: - case DATA_FORMAT_ASTC_12x10_UNORM_BLOCK: - case DATA_FORMAT_ASTC_12x10_SRGB_BLOCK: - case DATA_FORMAT_ASTC_12x12_UNORM_BLOCK: - case DATA_FORMAT_ASTC_12x12_SRGB_BLOCK: - return 16; - default: { - } - } - return 1; -} - -uint32_t RenderingDeviceVulkan::get_compressed_image_format_pixel_rshift(DataFormat p_format) { - switch (p_format) { - case DATA_FORMAT_BC1_RGB_UNORM_BLOCK: // These formats are half byte size, so rshift is 1. - case DATA_FORMAT_BC1_RGB_SRGB_BLOCK: - case DATA_FORMAT_BC1_RGBA_UNORM_BLOCK: - case DATA_FORMAT_BC1_RGBA_SRGB_BLOCK: - case DATA_FORMAT_BC4_UNORM_BLOCK: - case DATA_FORMAT_BC4_SNORM_BLOCK: - case DATA_FORMAT_ETC2_R8G8B8_UNORM_BLOCK: - case DATA_FORMAT_ETC2_R8G8B8_SRGB_BLOCK: - case DATA_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK: - case DATA_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK: - case DATA_FORMAT_EAC_R11_UNORM_BLOCK: - case DATA_FORMAT_EAC_R11_SNORM_BLOCK: - return 1; - case DATA_FORMAT_ASTC_8x8_SRGB_BLOCK: - case DATA_FORMAT_ASTC_8x8_UNORM_BLOCK: { - return 2; - } - default: { - } - } - - return 0; +void RenderingDevice::shader_set_spirv_cache_function(ShaderCacheFunction p_function) { + cache_function = p_function; } -bool RenderingDeviceVulkan::format_has_stencil(DataFormat p_format) { - switch (p_format) { - case DATA_FORMAT_S8_UINT: - case DATA_FORMAT_D16_UNORM_S8_UINT: - case DATA_FORMAT_D24_UNORM_S8_UINT: - case DATA_FORMAT_D32_SFLOAT_S8_UINT: { - return true; - } - default: { - } - } - return false; +void RenderingDevice::shader_set_get_cache_key_function(ShaderSPIRVGetCacheKeyFunction p_function) { + get_spirv_cache_key_function = p_function; } -uint32_t RenderingDeviceVulkan::get_image_format_required_size(DataFormat p_format, uint32_t p_width, uint32_t p_height, uint32_t p_depth, uint32_t p_mipmaps, uint32_t *r_blockw, uint32_t *r_blockh, uint32_t *r_depth) { - ERR_FAIL_COND_V(p_mipmaps == 0, 0); - uint32_t w = p_width; - uint32_t h = p_height; - uint32_t d = p_depth; - - uint32_t size = 0; - - uint32_t pixel_size = get_image_format_pixel_size(p_format); - uint32_t pixel_rshift = get_compressed_image_format_pixel_rshift(p_format); - uint32_t blockw, blockh; - get_compressed_image_format_block_dimensions(p_format, blockw, blockh); - - for (uint32_t i = 0; i < p_mipmaps; i++) { - uint32_t bw = w % blockw != 0 ? w + (blockw - w % blockw) : w; - uint32_t bh = h % blockh != 0 ? h + (blockh - h % blockh) : h; - - uint32_t s = bw * bh; - - s *= pixel_size; - s >>= pixel_rshift; - size += s * d; - if (r_blockw) { - *r_blockw = bw; +Vector RenderingDevice::shader_compile_spirv_from_source(ShaderStage p_stage, const String &p_source_code, ShaderLanguage p_language, String *r_error, bool p_allow_cache) { + if (p_allow_cache && cache_function) { + Vector cache = cache_function(p_stage, p_source_code, p_language); + if (cache.size()) { + return cache; } - if (r_blockh) { - *r_blockh = bh; - } - if (r_depth) { - *r_depth = d; - } - w = MAX(blockw, w >> 1); - h = MAX(blockh, h >> 1); - d = MAX(1u, d >> 1); } - return size; -} - -uint32_t RenderingDeviceVulkan::get_image_required_mipmaps(uint32_t p_width, uint32_t p_height, uint32_t p_depth) { - // Formats and block size don't really matter here since they can all go down to 1px (even if block is larger). - uint32_t w = p_width; - uint32_t h = p_height; - uint32_t d = p_depth; - - uint32_t mipmaps = 1; - - while (true) { - if (w == 1 && h == 1 && d == 1) { - break; - } + ERR_FAIL_NULL_V(compile_to_spirv_function, Vector()); - w = MAX(1u, w >> 1); - h = MAX(1u, h >> 1); - d = MAX(1u, d >> 1); + return compile_to_spirv_function(p_stage, p_source_code, p_language, r_error, this); +} - mipmaps++; +String RenderingDevice::shader_get_spirv_cache_key() const { + if (get_spirv_cache_key_function) { + return get_spirv_cache_key_function(this); } - - return mipmaps; + return String(); } -/////////////////////// - -const VkCompareOp RenderingDeviceVulkan::compare_operators[RenderingDevice::COMPARE_OP_MAX] = { - VK_COMPARE_OP_NEVER, - VK_COMPARE_OP_LESS, - VK_COMPARE_OP_EQUAL, - VK_COMPARE_OP_LESS_OR_EQUAL, - VK_COMPARE_OP_GREATER, - VK_COMPARE_OP_NOT_EQUAL, - VK_COMPARE_OP_GREATER_OR_EQUAL, - VK_COMPARE_OP_ALWAYS -}; - -const VkStencilOp RenderingDeviceVulkan::stencil_operations[RenderingDevice::STENCIL_OP_MAX] = { - VK_STENCIL_OP_KEEP, - VK_STENCIL_OP_ZERO, - VK_STENCIL_OP_REPLACE, - VK_STENCIL_OP_INCREMENT_AND_CLAMP, - VK_STENCIL_OP_DECREMENT_AND_CLAMP, - VK_STENCIL_OP_INVERT, - VK_STENCIL_OP_INCREMENT_AND_WRAP, - VK_STENCIL_OP_DECREMENT_AND_WRAP -}; - -const VkSampleCountFlagBits RenderingDeviceVulkan::rasterization_sample_count[RenderingDevice::TEXTURE_SAMPLES_MAX] = { - VK_SAMPLE_COUNT_1_BIT, - VK_SAMPLE_COUNT_2_BIT, - VK_SAMPLE_COUNT_4_BIT, - VK_SAMPLE_COUNT_8_BIT, - VK_SAMPLE_COUNT_16_BIT, - VK_SAMPLE_COUNT_32_BIT, - VK_SAMPLE_COUNT_64_BIT, -}; - -const VkLogicOp RenderingDeviceVulkan::logic_operations[RenderingDevice::LOGIC_OP_MAX] = { - VK_LOGIC_OP_CLEAR, - VK_LOGIC_OP_AND, - VK_LOGIC_OP_AND_REVERSE, - VK_LOGIC_OP_COPY, - VK_LOGIC_OP_AND_INVERTED, - VK_LOGIC_OP_NO_OP, - VK_LOGIC_OP_XOR, - VK_LOGIC_OP_OR, - VK_LOGIC_OP_NOR, - VK_LOGIC_OP_EQUIVALENT, - VK_LOGIC_OP_INVERT, - VK_LOGIC_OP_OR_REVERSE, - VK_LOGIC_OP_COPY_INVERTED, - VK_LOGIC_OP_OR_INVERTED, - VK_LOGIC_OP_NAND, - VK_LOGIC_OP_SET -}; - -const VkBlendFactor RenderingDeviceVulkan::blend_factors[RenderingDevice::BLEND_FACTOR_MAX] = { - VK_BLEND_FACTOR_ZERO, - VK_BLEND_FACTOR_ONE, - VK_BLEND_FACTOR_SRC_COLOR, - VK_BLEND_FACTOR_ONE_MINUS_SRC_COLOR, - VK_BLEND_FACTOR_DST_COLOR, - VK_BLEND_FACTOR_ONE_MINUS_DST_COLOR, - VK_BLEND_FACTOR_SRC_ALPHA, - VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, - VK_BLEND_FACTOR_DST_ALPHA, - VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA, - VK_BLEND_FACTOR_CONSTANT_COLOR, - VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_COLOR, - VK_BLEND_FACTOR_CONSTANT_ALPHA, - VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_ALPHA, - VK_BLEND_FACTOR_SRC_ALPHA_SATURATE, - VK_BLEND_FACTOR_SRC1_COLOR, - VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR, - VK_BLEND_FACTOR_SRC1_ALPHA, - VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA -}; -const VkBlendOp RenderingDeviceVulkan::blend_operations[RenderingDevice::BLEND_OP_MAX] = { - VK_BLEND_OP_ADD, - VK_BLEND_OP_SUBTRACT, - VK_BLEND_OP_REVERSE_SUBTRACT, - VK_BLEND_OP_MIN, - VK_BLEND_OP_MAX -}; +RID RenderingDevice::shader_create_from_spirv(const Vector &p_spirv, const String &p_shader_name) { + Vector bytecode = shader_compile_binary_from_spirv(p_spirv, p_shader_name); + ERR_FAIL_COND_V(bytecode.size() == 0, RID()); + return shader_create_from_bytecode(bytecode); +} -const VkSamplerAddressMode RenderingDeviceVulkan::address_modes[RenderingDevice::SAMPLER_REPEAT_MODE_MAX] = { - VK_SAMPLER_ADDRESS_MODE_REPEAT, - VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT, - VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, - VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER, - VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE -}; +/******************/ +/**** BARRIERS ****/ +/******************/ -const VkBorderColor RenderingDeviceVulkan::sampler_border_colors[RenderingDevice::SAMPLER_BORDER_COLOR_MAX] = { - VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK, - VK_BORDER_COLOR_INT_TRANSPARENT_BLACK, - VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK, - VK_BORDER_COLOR_INT_OPAQUE_BLACK, - VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE, - VK_BORDER_COLOR_INT_OPAQUE_WHITE -}; +void RenderingDevice::_full_barrier(bool p_sync_with_draw) { + // Used for debug. -const VkImageType RenderingDeviceVulkan::vulkan_image_type[RenderingDevice::TEXTURE_TYPE_MAX] = { - VK_IMAGE_TYPE_1D, - VK_IMAGE_TYPE_2D, - VK_IMAGE_TYPE_3D, - VK_IMAGE_TYPE_2D, - VK_IMAGE_TYPE_1D, - VK_IMAGE_TYPE_2D, - VK_IMAGE_TYPE_2D -}; + RDD::MemoryBarrier mb; + mb.src_access = (RDD::BARRIER_ACCESS_INDIRECT_COMMAND_READ_BIT | + RDD::BARRIER_ACCESS_INDEX_READ_BIT | + RDD::BARRIER_ACCESS_VERTEX_ATTRIBUTE_READ_BIT | + RDD::BARRIER_ACCESS_UNIFORM_READ_BIT | + RDD::BARRIER_ACCESS_INPUT_ATTACHMENT_READ_BIT | + RDD::BARRIER_ACCESS_SHADER_READ_BIT | + RDD::BARRIER_ACCESS_SHADER_WRITE_BIT | + RDD::BARRIER_ACCESS_COLOR_ATTACHMENT_READ_BIT | + RDD::BARRIER_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | + RDD::BARRIER_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | + RDD::BARRIER_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT | + RDD::BARRIER_ACCESS_TRANSFER_READ_BIT | + RDD::BARRIER_ACCESS_TRANSFER_WRITE_BIT | + RDD::BARRIER_ACCESS_HOST_READ_BIT | + RDD::BARRIER_ACCESS_HOST_WRITE_BIT); + mb.dst_access = (RDD::BARRIER_ACCESS_INDIRECT_COMMAND_READ_BIT | + RDD::BARRIER_ACCESS_INDEX_READ_BIT | + RDD::BARRIER_ACCESS_VERTEX_ATTRIBUTE_READ_BIT | + RDD::BARRIER_ACCESS_UNIFORM_READ_BIT | + RDD::BARRIER_ACCESS_INPUT_ATTACHMENT_READ_BIT | + RDD::BARRIER_ACCESS_SHADER_READ_BIT | + RDD::BARRIER_ACCESS_SHADER_WRITE_BIT | + RDD::BARRIER_ACCESS_COLOR_ATTACHMENT_READ_BIT | + RDD::BARRIER_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | + RDD::BARRIER_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | + RDD::BARRIER_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT | + RDD::BARRIER_ACCESS_TRANSFER_READ_BIT | + RDD::BARRIER_ACCESS_TRANSFER_WRITE_BIT | + RDD::BARRIER_ACCESS_HOST_READ_BIT | + RDD::BARRIER_ACCESS_HOST_WRITE_BIT); + + RDD::CommandBufferID cmd_buffer = p_sync_with_draw ? frames[frame].draw_command_buffer : frames[frame].setup_command_buffer; + driver->command_pipeline_barrier(cmd_buffer, RDD::PIPELINE_STAGE_ALL_COMMANDS_BIT, RDD::PIPELINE_STAGE_ALL_COMMANDS_BIT, mb, {}, {}); +} /***************************/ /**** BUFFER MANAGEMENT ****/ /***************************/ -Error RenderingDeviceVulkan::_buffer_allocate(Buffer *p_buffer, uint32_t p_size, uint32_t p_usage, VmaMemoryUsage p_mem_usage, VmaAllocationCreateFlags p_mem_flags) { - VkBufferCreateInfo bufferInfo; - bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; - bufferInfo.pNext = nullptr; - bufferInfo.flags = 0; - bufferInfo.size = p_size; - bufferInfo.usage = p_usage; - bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; - bufferInfo.queueFamilyIndexCount = 0; - bufferInfo.pQueueFamilyIndices = nullptr; - - VmaAllocationCreateInfo allocInfo; - allocInfo.flags = p_mem_flags; - allocInfo.usage = p_mem_usage; - allocInfo.requiredFlags = 0; - allocInfo.preferredFlags = 0; - allocInfo.memoryTypeBits = 0; - allocInfo.pool = nullptr; - allocInfo.pUserData = nullptr; - if (p_size <= SMALL_ALLOCATION_MAX_SIZE) { - uint32_t mem_type_index = 0; - vmaFindMemoryTypeIndexForBufferInfo(allocator, &bufferInfo, &allocInfo, &mem_type_index); - allocInfo.pool = _find_or_create_small_allocs_pool(mem_type_index); - } - - VkResult err = vmaCreateBuffer(allocator, &bufferInfo, &allocInfo, &p_buffer->buffer, &p_buffer->allocation, nullptr); - ERR_FAIL_COND_V_MSG(err, ERR_CANT_CREATE, "Can't create buffer of size: " + itos(p_size) + ", error " + itos(err) + "."); - p_buffer->size = p_size; - p_buffer->buffer_info.buffer = p_buffer->buffer; - p_buffer->buffer_info.offset = 0; - p_buffer->buffer_info.range = p_size; - p_buffer->usage = p_usage; - - buffer_memory += p_size; - - return OK; -} +RenderingDevice::Buffer *RenderingDevice::_get_buffer_from_owner(RID p_buffer, BitField &r_stages, BitField &r_access, BitField p_post_barrier) { + Buffer *buffer = nullptr; + r_stages.clear(); + r_access.clear(); + if (vertex_buffer_owner.owns(p_buffer)) { + buffer = vertex_buffer_owner.get_or_null(p_buffer); -Error RenderingDeviceVulkan::_buffer_free(Buffer *p_buffer) { - ERR_FAIL_COND_V(p_buffer->size == 0, ERR_INVALID_PARAMETER); + r_stages.set_flag(RDD::PIPELINE_STAGE_VERTEX_INPUT_BIT); + r_access.set_flag(RDD::BARRIER_ACCESS_VERTEX_ATTRIBUTE_READ_BIT); + if (buffer->usage & RDD::BUFFER_USAGE_STORAGE_BIT) { + if (p_post_barrier.has_flag(BARRIER_MASK_VERTEX)) { + r_access.set_flag(RDD::BARRIER_ACCESS_SHADER_READ_BIT).set_flag(RDD::BARRIER_ACCESS_SHADER_WRITE_BIT); + r_stages.set_flag(RDD::PIPELINE_STAGE_VERTEX_SHADER_BIT); + } + if (p_post_barrier.has_flag(BARRIER_MASK_FRAGMENT)) { + r_access.set_flag(RDD::BARRIER_ACCESS_SHADER_READ_BIT).set_flag(RDD::BARRIER_ACCESS_SHADER_WRITE_BIT); + r_stages.set_flag(RDD::PIPELINE_STAGE_FRAGMENT_SHADER_BIT); + } + if (p_post_barrier.has_flag(BARRIER_MASK_COMPUTE)) { + r_access.set_flag(RDD::BARRIER_ACCESS_SHADER_READ_BIT).set_flag(RDD::BARRIER_ACCESS_SHADER_WRITE_BIT); + r_stages.set_flag(RDD::PIPELINE_STAGE_COMPUTE_SHADER_BIT); + } + } + } else if (index_buffer_owner.owns(p_buffer)) { + r_stages.set_flag(RDD::PIPELINE_STAGE_VERTEX_INPUT_BIT); + r_access.set_flag(RDD::BARRIER_ACCESS_INDEX_READ_BIT); + buffer = index_buffer_owner.get_or_null(p_buffer); + } else if (uniform_buffer_owner.owns(p_buffer)) { + if (p_post_barrier.has_flag(BARRIER_MASK_VERTEX)) { + r_stages.set_flag(RDD::PIPELINE_STAGE_VERTEX_SHADER_BIT); + } + if (p_post_barrier.has_flag(BARRIER_MASK_FRAGMENT)) { + r_stages.set_flag(RDD::PIPELINE_STAGE_FRAGMENT_SHADER_BIT); + } + if (p_post_barrier.has_flag(BARRIER_MASK_COMPUTE)) { + r_stages.set_flag(RDD::PIPELINE_STAGE_COMPUTE_SHADER_BIT); + } + r_access.set_flag(RDD::BARRIER_ACCESS_UNIFORM_READ_BIT); + buffer = uniform_buffer_owner.get_or_null(p_buffer); + } else if (texture_buffer_owner.owns(p_buffer)) { + if (p_post_barrier.has_flag(BARRIER_MASK_VERTEX)) { + r_stages.set_flag(RDD::PIPELINE_STAGE_VERTEX_SHADER_BIT); + r_access.set_flag(RDD::BARRIER_ACCESS_SHADER_READ_BIT); + } + if (p_post_barrier.has_flag(BARRIER_MASK_FRAGMENT)) { + r_stages.set_flag(RDD::PIPELINE_STAGE_FRAGMENT_SHADER_BIT); + r_access.set_flag(RDD::BARRIER_ACCESS_SHADER_READ_BIT); + } + if (p_post_barrier.has_flag(BARRIER_MASK_COMPUTE)) { + r_stages.set_flag(RDD::PIPELINE_STAGE_COMPUTE_SHADER_BIT); + r_access.set_flag(RDD::BARRIER_ACCESS_SHADER_READ_BIT); + } - buffer_memory -= p_buffer->size; - vmaDestroyBuffer(allocator, p_buffer->buffer, p_buffer->allocation); - p_buffer->buffer = VK_NULL_HANDLE; - p_buffer->allocation = nullptr; - p_buffer->size = 0; + // FIXME: Broken. + //buffer = texture_buffer_owner.get_or_null(p_buffer)->buffer; + } else if (storage_buffer_owner.owns(p_buffer)) { + buffer = storage_buffer_owner.get_or_null(p_buffer); + if (p_post_barrier.has_flag(BARRIER_MASK_VERTEX)) { + r_stages.set_flag(RDD::PIPELINE_STAGE_VERTEX_SHADER_BIT); + r_access.set_flag(RDD::BARRIER_ACCESS_SHADER_READ_BIT).set_flag(RDD::BARRIER_ACCESS_SHADER_WRITE_BIT); + } + if (p_post_barrier.has_flag(BARRIER_MASK_FRAGMENT)) { + r_stages.set_flag(RDD::PIPELINE_STAGE_FRAGMENT_SHADER_BIT); + r_access.set_flag(RDD::BARRIER_ACCESS_SHADER_READ_BIT).set_flag(RDD::BARRIER_ACCESS_SHADER_WRITE_BIT); + } + if (p_post_barrier.has_flag(BARRIER_MASK_COMPUTE)) { + r_stages.set_flag(RDD::PIPELINE_STAGE_COMPUTE_SHADER_BIT); + r_access.set_flag(RDD::BARRIER_ACCESS_SHADER_READ_BIT).set_flag(RDD::BARRIER_ACCESS_SHADER_WRITE_BIT); + } - return OK; + if (buffer->usage.has_flag(RDD::BUFFER_USAGE_INDIRECT_BIT)) { + r_stages.set_flag(RDD::PIPELINE_STAGE_DRAW_INDIRECT_BIT); + r_access.set_flag(RDD::BARRIER_ACCESS_INDIRECT_COMMAND_READ_BIT); + } + } + return buffer; } -Error RenderingDeviceVulkan::_insert_staging_block() { - VkBufferCreateInfo bufferInfo; - bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; - bufferInfo.pNext = nullptr; - bufferInfo.flags = 0; - bufferInfo.size = staging_buffer_block_size; - bufferInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT; - bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; - bufferInfo.queueFamilyIndexCount = 0; - bufferInfo.pQueueFamilyIndices = nullptr; - - VmaAllocationCreateInfo allocInfo; - allocInfo.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT; - allocInfo.usage = VMA_MEMORY_USAGE_AUTO_PREFER_HOST; - allocInfo.requiredFlags = 0; - allocInfo.preferredFlags = 0; - allocInfo.memoryTypeBits = 0; - allocInfo.pool = nullptr; - allocInfo.pUserData = nullptr; - +Error RenderingDevice::_insert_staging_block() { StagingBufferBlock block; - VkResult err = vmaCreateBuffer(allocator, &bufferInfo, &allocInfo, &block.buffer, &block.allocation, nullptr); - ERR_FAIL_COND_V_MSG(err, ERR_CANT_CREATE, "vmaCreateBuffer failed with error " + itos(err) + "."); + block.driver_id = driver->buffer_create(staging_buffer_block_size, RDD::BUFFER_USAGE_TRANSFER_FROM_BIT, RDD::MEMORY_ALLOCATION_TYPE_CPU); + ERR_FAIL_COND_V(!block.driver_id, ERR_CANT_CREATE); block.frame_used = 0; block.fill_amount = 0; @@ -1428,7 +269,7 @@ Error RenderingDeviceVulkan::_insert_staging_block() { return OK; } -Error RenderingDeviceVulkan::_staging_buffer_allocate(uint32_t p_amount, uint32_t p_required_align, uint32_t &r_alloc_offset, uint32_t &r_alloc_size, bool p_can_segment) { +Error RenderingDevice::_staging_buffer_allocate(uint32_t p_amount, uint32_t p_required_align, uint32_t &r_alloc_offset, uint32_t &r_alloc_size, bool p_can_segment) { // Determine a block to use. r_alloc_size = p_amount; @@ -1561,7 +402,7 @@ Error RenderingDeviceVulkan::_staging_buffer_allocate(uint32_t p_amount, uint32_ return OK; } -Error RenderingDeviceVulkan::_buffer_update(Buffer *p_buffer, size_t p_offset, const uint8_t *p_data, size_t p_data_size, bool p_use_draw_command_buffer, uint32_t p_required_align) { +Error RenderingDevice::_buffer_update(Buffer *p_buffer, size_t p_offset, const uint8_t *p_data, size_t p_data_size, bool p_use_draw_command_buffer, uint32_t p_required_align) { // Submitting may get chunked for various reasons, so convert this to a task. size_t to_submit = p_data_size; size_t submit_from = 0; @@ -1576,26 +417,22 @@ Error RenderingDeviceVulkan::_buffer_update(Buffer *p_buffer, size_t p_offset, c } // Map staging buffer (It's CPU and coherent). - - void *data_ptr = nullptr; - { - VkResult vkerr = vmaMapMemory(allocator, staging_buffer_blocks[staging_buffer_current].allocation, &data_ptr); - ERR_FAIL_COND_V_MSG(vkerr, ERR_CANT_CREATE, "vmaMapMemory failed with error " + itos(vkerr) + "."); - } + uint8_t *data_ptr = driver->buffer_map(staging_buffer_blocks[staging_buffer_current].driver_id); + ERR_FAIL_NULL_V(data_ptr, ERR_CANT_CREATE); // Copy to staging buffer. - memcpy(((uint8_t *)data_ptr) + block_write_offset, p_data + submit_from, block_write_amount); + memcpy(data_ptr + block_write_offset, p_data + submit_from, block_write_amount); // Unmap. - vmaUnmapMemory(allocator, staging_buffer_blocks[staging_buffer_current].allocation); + driver->buffer_unmap(staging_buffer_blocks[staging_buffer_current].driver_id); + // Insert a command to copy this. - VkBufferCopy region; - region.srcOffset = block_write_offset; - region.dstOffset = submit_from + p_offset; + RDD::BufferCopyRegion region; + region.src_offset = block_write_offset; + region.dst_offset = submit_from + p_offset; region.size = block_write_amount; - - vkCmdCopyBuffer(p_use_draw_command_buffer ? frames[frame].draw_command_buffer : frames[frame].setup_command_buffer, staging_buffer_blocks[staging_buffer_current].buffer, p_buffer->buffer, 1, ®ion); + driver->command_copy_buffer(p_use_draw_command_buffer ? frames[frame].draw_command_buffer : frames[frame].setup_command_buffer, staging_buffer_blocks[staging_buffer_current].driver_id, p_buffer->driver_id, region); staging_buffer_blocks.write[staging_buffer_current].fill_amount = block_write_offset + block_write_amount; @@ -1606,212 +443,351 @@ Error RenderingDeviceVulkan::_buffer_update(Buffer *p_buffer, size_t p_offset, c return OK; } -void RenderingDeviceVulkan::_memory_barrier(VkPipelineStageFlags p_src_stage_mask, VkPipelineStageFlags p_dst_stage_mask, VkAccessFlags p_src_access, VkAccessFlags p_dst_access, bool p_sync_with_draw) { - VkMemoryBarrier mem_barrier; - mem_barrier.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER; - mem_barrier.pNext = nullptr; - mem_barrier.srcAccessMask = p_src_access; - mem_barrier.dstAccessMask = p_dst_access; - - if (p_src_stage_mask == 0 || p_dst_stage_mask == 0) { - return; // No barrier, since this is invalid. - } - vkCmdPipelineBarrier(p_sync_with_draw ? frames[frame].draw_command_buffer : frames[frame].setup_command_buffer, p_src_stage_mask, p_dst_stage_mask, 0, 1, &mem_barrier, 0, nullptr, 0, nullptr); -} - -void RenderingDeviceVulkan::_full_barrier(bool p_sync_with_draw) { - // Used for debug. - _memory_barrier(VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, - VK_ACCESS_INDIRECT_COMMAND_READ_BIT | - VK_ACCESS_INDEX_READ_BIT | - VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT | - VK_ACCESS_UNIFORM_READ_BIT | - VK_ACCESS_INPUT_ATTACHMENT_READ_BIT | - VK_ACCESS_SHADER_READ_BIT | - VK_ACCESS_SHADER_WRITE_BIT | - VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | - VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | - VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | - VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT | - VK_ACCESS_TRANSFER_READ_BIT | - VK_ACCESS_TRANSFER_WRITE_BIT | - VK_ACCESS_HOST_READ_BIT | - VK_ACCESS_HOST_WRITE_BIT, - VK_ACCESS_INDIRECT_COMMAND_READ_BIT | - VK_ACCESS_INDEX_READ_BIT | - VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT | - VK_ACCESS_UNIFORM_READ_BIT | - VK_ACCESS_INPUT_ATTACHMENT_READ_BIT | - VK_ACCESS_SHADER_READ_BIT | - VK_ACCESS_SHADER_WRITE_BIT | - VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | - VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | - VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | - VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT | - VK_ACCESS_TRANSFER_READ_BIT | - VK_ACCESS_TRANSFER_WRITE_BIT | - VK_ACCESS_HOST_READ_BIT | - VK_ACCESS_HOST_WRITE_BIT, - p_sync_with_draw); -} - -void RenderingDeviceVulkan::_buffer_memory_barrier(VkBuffer buffer, uint64_t p_from, uint64_t p_size, VkPipelineStageFlags p_src_stage_mask, VkPipelineStageFlags p_dst_stage_mask, VkAccessFlags p_src_access, VkAccessFlags p_dst_access, bool p_sync_with_draw) { - VkBufferMemoryBarrier buffer_mem_barrier; - buffer_mem_barrier.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER; - buffer_mem_barrier.pNext = nullptr; - buffer_mem_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - buffer_mem_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - buffer_mem_barrier.srcAccessMask = p_src_access; - buffer_mem_barrier.dstAccessMask = p_dst_access; - buffer_mem_barrier.buffer = buffer; - buffer_mem_barrier.offset = p_from; - buffer_mem_barrier.size = p_size; - - vkCmdPipelineBarrier(p_sync_with_draw ? frames[frame].draw_command_buffer : frames[frame].setup_command_buffer, p_src_stage_mask, p_dst_stage_mask, 0, 0, nullptr, 1, &buffer_mem_barrier, 0, nullptr); -} - -/*****************/ -/**** TEXTURE ****/ -/*****************/ - -RID RenderingDeviceVulkan::texture_create(const TextureFormat &p_format, const TextureView &p_view, const Vector> &p_data) { +Error RenderingDevice::buffer_copy(RID p_src_buffer, RID p_dst_buffer, uint32_t p_src_offset, uint32_t p_dst_offset, uint32_t p_size, BitField p_post_barrier) { _THREAD_SAFE_METHOD_ - VkImageCreateInfo image_create_info; - image_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; - image_create_info.pNext = nullptr; - image_create_info.flags = 0; - - VkImageFormatListCreateInfoKHR format_list_create_info; // Keep out of the if, needed for creation. - Vector allowed_formats; // Keep out of the if, needed for creation. - if (p_format.shareable_formats.size()) { - image_create_info.flags |= VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT; - - if (context->is_device_extension_enabled(VK_KHR_IMAGE_FORMAT_LIST_EXTENSION_NAME)) { - for (int i = 0; i < p_format.shareable_formats.size(); i++) { - allowed_formats.push_back(vulkan_formats[p_format.shareable_formats[i]]); - } - - format_list_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_LIST_CREATE_INFO_KHR; - format_list_create_info.pNext = nullptr; - format_list_create_info.viewFormatCount = allowed_formats.size(); - format_list_create_info.pViewFormats = allowed_formats.ptr(); - image_create_info.pNext = &format_list_create_info; + ERR_FAIL_COND_V_MSG(draw_list, ERR_INVALID_PARAMETER, + "Copying buffers is forbidden during creation of a draw list"); + ERR_FAIL_COND_V_MSG(compute_list, ERR_INVALID_PARAMETER, + "Copying buffers is forbidden during creation of a compute list"); - ERR_FAIL_COND_V_MSG(p_format.shareable_formats.find(p_format.format) == -1, RID(), - "If supplied a list of shareable formats, the current format must be present in the list"); - ERR_FAIL_COND_V_MSG(p_view.format_override != DATA_FORMAT_MAX && p_format.shareable_formats.find(p_view.format_override) == -1, RID(), - "If supplied a list of shareable formats, the current view format override must be present in the list"); - } + // This method assumes the barriers have been pushed prior to being called, therefore no barriers are pushed + // for the source or destination buffers before performing the copy. These masks are effectively ignored. + BitField src_stages; + BitField src_access; + Buffer *src_buffer = _get_buffer_from_owner(p_src_buffer, src_stages, src_access, BARRIER_MASK_NO_BARRIER); + if (!src_buffer) { + ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, "Source buffer argument is not a valid buffer of any type."); } - if (p_format.texture_type == TEXTURE_TYPE_CUBE || p_format.texture_type == TEXTURE_TYPE_CUBE_ARRAY) { - image_create_info.flags |= VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT; + BitField dst_stages; + BitField dst_access; + if (p_post_barrier.has_flag(BARRIER_MASK_TRANSFER)) { + // If the post barrier mask defines it, we indicate the destination buffer will require a barrier with these flags set + // after the copy command is queued. + dst_stages.set_flag(RDD::PIPELINE_STAGE_TRANSFER_BIT); + dst_access.set_flag(RDD::BARRIER_ACCESS_TRANSFER_WRITE_BIT); } - /*if (p_format.type == TEXTURE_TYPE_2D || p_format.type == TEXTURE_TYPE_2D_ARRAY) { - image_create_info.flags |= VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT; - }*/ - - ERR_FAIL_INDEX_V(p_format.texture_type, TEXTURE_TYPE_MAX, RID()); - image_create_info.imageType = vulkan_image_type[p_format.texture_type]; + Buffer *dst_buffer = _get_buffer_from_owner(p_dst_buffer, dst_stages, dst_access, p_post_barrier); + if (!dst_buffer) { + ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, "Destination buffer argument is not a valid buffer of any type."); + } - ERR_FAIL_COND_V_MSG(p_format.width < 1, RID(), "Width must be equal or greater than 1 for all textures"); + // Validate the copy's dimensions for both buffers. + ERR_FAIL_COND_V_MSG((p_size + p_src_offset) > src_buffer->size, ERR_INVALID_PARAMETER, "Size is larger than the source buffer."); + ERR_FAIL_COND_V_MSG((p_size + p_dst_offset) > dst_buffer->size, ERR_INVALID_PARAMETER, "Size is larger than the destination buffer."); - image_create_info.format = vulkan_formats[p_format.format]; + // Perform the copy. + RDD::BufferCopyRegion region; + region.src_offset = p_src_offset; + region.dst_offset = p_dst_offset; + region.size = p_size; + driver->command_copy_buffer(frames[frame].draw_command_buffer, src_buffer->driver_id, dst_buffer->driver_id, region); - image_create_info.extent.width = p_format.width; - if (image_create_info.imageType == VK_IMAGE_TYPE_3D || image_create_info.imageType == VK_IMAGE_TYPE_2D) { - ERR_FAIL_COND_V_MSG(p_format.height < 1, RID(), "Height must be equal or greater than 1 for 2D and 3D textures"); - image_create_info.extent.height = p_format.height; - } else { - image_create_info.extent.height = 1; +#ifdef FORCE_FULL_BARRIER + _full_barrier(true); +#else + if (dst_stages.is_empty()) { + dst_stages = RDD::PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; } - if (image_create_info.imageType == VK_IMAGE_TYPE_3D) { - ERR_FAIL_COND_V_MSG(p_format.depth < 1, RID(), "Depth must be equal or greater than 1 for 3D textures"); - image_create_info.extent.depth = p_format.depth; - } else { - image_create_info.extent.depth = 1; + // As indicated by the post barrier mask, push a new barrier. + if (p_post_barrier != RD::BARRIER_MASK_NO_BARRIER) { + RDD::BufferBarrier bb; + bb.buffer = dst_buffer->driver_id; + bb.src_access = RDD::BARRIER_ACCESS_TRANSFER_WRITE_BIT; + bb.dst_access = dst_access; + bb.offset = p_dst_offset; + bb.size = p_size; + driver->command_pipeline_barrier(frames[frame].draw_command_buffer, RDD::PIPELINE_STAGE_TRANSFER_BIT, dst_stages, {}, bb, {}); } +#endif - ERR_FAIL_COND_V(p_format.mipmaps < 1, RID()); - - image_create_info.mipLevels = p_format.mipmaps; + return OK; +} - if (p_format.texture_type == TEXTURE_TYPE_1D_ARRAY || p_format.texture_type == TEXTURE_TYPE_2D_ARRAY || p_format.texture_type == TEXTURE_TYPE_CUBE_ARRAY || p_format.texture_type == TEXTURE_TYPE_CUBE) { - ERR_FAIL_COND_V_MSG(p_format.array_layers < 1, RID(), - "Amount of layers must be equal or greater than 1 for arrays and cubemaps."); - ERR_FAIL_COND_V_MSG((p_format.texture_type == TEXTURE_TYPE_CUBE_ARRAY || p_format.texture_type == TEXTURE_TYPE_CUBE) && (p_format.array_layers % 6) != 0, RID(), - "Cubemap and cubemap array textures must provide a layer number that is multiple of 6"); - image_create_info.arrayLayers = p_format.array_layers; - } else { - image_create_info.arrayLayers = 1; - } +Error RenderingDevice::buffer_update(RID p_buffer, uint32_t p_offset, uint32_t p_size, const void *p_data, BitField p_post_barrier) { + _THREAD_SAFE_METHOD_ - ERR_FAIL_INDEX_V(p_format.samples, TEXTURE_SAMPLES_MAX, RID()); + ERR_FAIL_COND_V_MSG(draw_list, ERR_INVALID_PARAMETER, + "Updating buffers is forbidden during creation of a draw list"); + ERR_FAIL_COND_V_MSG(compute_list, ERR_INVALID_PARAMETER, + "Updating buffers is forbidden during creation of a compute list"); - image_create_info.samples = _ensure_supported_sample_count(p_format.samples); - image_create_info.tiling = (p_format.usage_bits & TEXTURE_USAGE_CPU_READ_BIT) ? VK_IMAGE_TILING_LINEAR : VK_IMAGE_TILING_OPTIMAL; + BitField dst_stages; + BitField dst_access; + if (p_post_barrier.has_flag(BARRIER_MASK_TRANSFER)) { + // Protect subsequent updates. + dst_stages.set_flag(RDD::PIPELINE_STAGE_TRANSFER_BIT); + dst_access.set_flag(RDD::BARRIER_ACCESS_TRANSFER_WRITE_BIT); + } + Buffer *buffer = _get_buffer_from_owner(p_buffer, dst_stages, dst_access, p_post_barrier); + if (!buffer) { + ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, "Buffer argument is not a valid buffer of any type."); + } - // Usage. - image_create_info.usage = 0; + ERR_FAIL_COND_V_MSG(p_offset + p_size > buffer->size, ERR_INVALID_PARAMETER, + "Attempted to write buffer (" + itos((p_offset + p_size) - buffer->size) + " bytes) past the end."); - if (p_format.usage_bits & TEXTURE_USAGE_SAMPLING_BIT) { - image_create_info.usage |= VK_IMAGE_USAGE_SAMPLED_BIT; + Error err = _buffer_update(buffer, p_offset, (uint8_t *)p_data, p_size, p_post_barrier); + if (err) { + return err; } - if (p_format.usage_bits & TEXTURE_USAGE_STORAGE_BIT) { - image_create_info.usage |= VK_IMAGE_USAGE_STORAGE_BIT; +#ifdef FORCE_FULL_BARRIER + _full_barrier(true); +#else + if (dst_stages.is_empty()) { + dst_stages.set_flag(RDD::PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT); } - if (p_format.usage_bits & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) { - image_create_info.usage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; + if (p_post_barrier != RD::BARRIER_MASK_NO_BARRIER) { + RDD::BufferBarrier bb; + bb.buffer = buffer->driver_id; + bb.src_access = RDD::BARRIER_ACCESS_TRANSFER_WRITE_BIT; + bb.dst_access = dst_access; + bb.offset = p_offset; + bb.size = p_size; + driver->command_pipeline_barrier(frames[frame].draw_command_buffer, RDD::PIPELINE_STAGE_TRANSFER_BIT, dst_stages, {}, bb, {}); } - if (p_format.usage_bits & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) { - image_create_info.usage |= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT; - } +#endif + return err; +} - if (p_format.usage_bits & TEXTURE_USAGE_INPUT_ATTACHMENT_BIT) { - image_create_info.usage |= VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT; - } +Error RenderingDevice::buffer_clear(RID p_buffer, uint32_t p_offset, uint32_t p_size, BitField p_post_barrier) { + _THREAD_SAFE_METHOD_ - if (p_format.usage_bits & TEXTURE_USAGE_VRS_ATTACHMENT_BIT) { - image_create_info.usage |= VK_IMAGE_USAGE_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR; - } + ERR_FAIL_COND_V_MSG((p_size % 4) != 0, ERR_INVALID_PARAMETER, + "Size must be a multiple of four"); + ERR_FAIL_COND_V_MSG(draw_list, ERR_INVALID_PARAMETER, + "Updating buffers in is forbidden during creation of a draw list"); + ERR_FAIL_COND_V_MSG(compute_list, ERR_INVALID_PARAMETER, + "Updating buffers is forbidden during creation of a compute list"); - if (p_format.usage_bits & TEXTURE_USAGE_CAN_UPDATE_BIT) { - image_create_info.usage |= VK_IMAGE_USAGE_TRANSFER_DST_BIT; - } - if (p_format.usage_bits & TEXTURE_USAGE_CAN_COPY_FROM_BIT) { - image_create_info.usage |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT; + BitField dst_stages; + BitField dst_access; + if (p_post_barrier.has_flag(BARRIER_MASK_TRANSFER)) { + // Protect subsequent updates. + dst_stages.set_flag(RDD::PIPELINE_STAGE_TRANSFER_BIT); + dst_access.set_flag(RDD::BARRIER_ACCESS_TRANSFER_WRITE_BIT); } - if (p_format.usage_bits & TEXTURE_USAGE_CAN_COPY_TO_BIT) { - image_create_info.usage |= VK_IMAGE_USAGE_TRANSFER_DST_BIT; + Buffer *buffer = _get_buffer_from_owner(p_buffer, dst_stages, dst_access, p_post_barrier); + if (!buffer) { + ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, "Buffer argument is not a valid buffer of any type."); } - image_create_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; - image_create_info.queueFamilyIndexCount = 0; - image_create_info.pQueueFamilyIndices = nullptr; - image_create_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; - - uint32_t required_mipmaps = get_image_required_mipmaps(image_create_info.extent.width, image_create_info.extent.height, image_create_info.extent.depth); + ERR_FAIL_COND_V_MSG(p_offset + p_size > buffer->size, ERR_INVALID_PARAMETER, + "Attempted to write buffer (" + itos((p_offset + p_size) - buffer->size) + " bytes) past the end."); - ERR_FAIL_COND_V_MSG(required_mipmaps < image_create_info.mipLevels, RID(), - "Too many mipmaps requested for texture format and dimensions (" + itos(image_create_info.mipLevels) + "), maximum allowed: (" + itos(required_mipmaps) + ")."); + driver->command_clear_buffer(frames[frame].draw_command_buffer, buffer->driver_id, p_offset, p_size); - if (p_data.size()) { - ERR_FAIL_COND_V_MSG(!(p_format.usage_bits & TEXTURE_USAGE_CAN_UPDATE_BIT), RID(), - "Texture needs the TEXTURE_USAGE_CAN_UPDATE_BIT usage flag in order to be updated at initialization or later"); +#ifdef FORCE_FULL_BARRIER + _full_barrier(true); +#else + if (dst_stages.is_empty()) { + dst_stages.set_flag(RDD::PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT); + } - int expected_images = image_create_info.arrayLayers; - ERR_FAIL_COND_V_MSG(p_data.size() != expected_images, RID(), - "Default supplied data for image format is of invalid length (" + itos(p_data.size()) + "), should be (" + itos(expected_images) + ")."); + RDD::BufferBarrier bb; + bb.buffer = buffer->driver_id; + bb.src_access = RDD::BARRIER_ACCESS_TRANSFER_WRITE_BIT; + bb.dst_access = dst_access; + bb.offset = p_offset; + bb.size = p_size; + driver->command_pipeline_barrier(frames[frame].draw_command_buffer, RDD::PIPELINE_STAGE_TRANSFER_BIT, dst_stages, {}, bb, {}); - for (uint32_t i = 0; i < image_create_info.arrayLayers; i++) { - uint32_t required_size = get_image_format_required_size(p_format.format, image_create_info.extent.width, image_create_info.extent.height, image_create_info.extent.depth, image_create_info.mipLevels); +#endif + return OK; +} + +Vector RenderingDevice::buffer_get_data(RID p_buffer, uint32_t p_offset, uint32_t p_size) { + _THREAD_SAFE_METHOD_ + + // It could be this buffer was just created. + BitField src_stages = RDD::PIPELINE_STAGE_TRANSFER_BIT; + BitField src_access = RDD::BARRIER_ACCESS_TRANSFER_WRITE_BIT; + // Get the vulkan buffer and the potential stage/access possible. + Buffer *buffer = _get_buffer_from_owner(p_buffer, src_stages, src_access, BARRIER_MASK_ALL_BARRIERS); + if (!buffer) { + ERR_FAIL_V_MSG(Vector(), "Buffer is either invalid or this type of buffer can't be retrieved. Only Index and Vertex buffers allow retrieving."); + } + + // Make sure no one is using the buffer -- the "true" gets us to the same command buffer as below. + RDD::BufferBarrier bb; + bb.buffer = buffer->driver_id; + bb.src_access = src_access; + bb.dst_access = RDD::BARRIER_ACCESS_TRANSFER_READ_BIT; + bb.size = buffer->size; + driver->command_pipeline_barrier(frames[frame].draw_command_buffer, src_stages, RDD::PIPELINE_STAGE_TRANSFER_BIT, {}, bb, {}); + + // Size of buffer to retrieve. + if (!p_size) { + p_size = buffer->size; + } else { + ERR_FAIL_COND_V_MSG(p_size + p_offset > buffer->size, Vector(), + "Size is larger than the buffer."); + } + + RDD::BufferID tmp_buffer = driver->buffer_create(buffer->size, RDD::BUFFER_USAGE_TRANSFER_TO_BIT, RDD::MEMORY_ALLOCATION_TYPE_CPU); + ERR_FAIL_COND_V(!tmp_buffer, Vector()); + + RDD::BufferCopyRegion region; + region.src_offset = p_offset; + region.size = p_size; + driver->command_copy_buffer(frames[frame].draw_command_buffer, buffer->driver_id, tmp_buffer, region); + // Flush everything so memory can be safely mapped. + _flush(true); + + uint8_t *buffer_mem = driver->buffer_map(tmp_buffer); + ERR_FAIL_COND_V(!buffer_mem, Vector()); + + Vector buffer_data; + { + buffer_data.resize(p_size); + uint8_t *w = buffer_data.ptrw(); + memcpy(w, buffer_mem, p_size); + } + + driver->buffer_unmap(tmp_buffer); + + driver->buffer_free(tmp_buffer); + + return buffer_data; +} + +RID RenderingDevice::storage_buffer_create(uint32_t p_size_bytes, const Vector &p_data, BitField p_usage) { + _THREAD_SAFE_METHOD_ + + ERR_FAIL_COND_V(p_data.size() && (uint32_t)p_data.size() != p_size_bytes, RID()); + + Buffer buffer; + buffer.size = p_size_bytes; + buffer.usage = (RDD::BUFFER_USAGE_TRANSFER_FROM_BIT | RDD::BUFFER_USAGE_TRANSFER_TO_BIT | RDD::BUFFER_USAGE_STORAGE_BIT); + if (p_usage.has_flag(STORAGE_BUFFER_USAGE_DISPATCH_INDIRECT)) { + buffer.usage.set_flag(RDD::BUFFER_USAGE_INDIRECT_BIT); + } + buffer.driver_id = driver->buffer_create(buffer.size, buffer.usage, RDD::MEMORY_ALLOCATION_TYPE_GPU); + ERR_FAIL_COND_V(!buffer.driver_id, RID()); + + if (p_data.size()) { + uint64_t data_size = p_data.size(); + const uint8_t *r = p_data.ptr(); + _buffer_update(&buffer, 0, r, data_size); + RDD::BufferBarrier bb; + bb.buffer = buffer.driver_id; + bb.src_access = RDD::BARRIER_ACCESS_TRANSFER_WRITE_BIT; + bb.dst_access = (RDD::BARRIER_ACCESS_SHADER_READ_BIT | RDD::BARRIER_ACCESS_SHADER_WRITE_BIT); + bb.size = data_size; + driver->command_pipeline_barrier(frames[frame].setup_command_buffer, RDD::PIPELINE_STAGE_TRANSFER_BIT, RDD::PIPELINE_STAGE_VERTEX_SHADER_BIT | RDD::PIPELINE_STAGE_FRAGMENT_SHADER_BIT | RDD::PIPELINE_STAGE_COMPUTE_SHADER_BIT, {}, bb, {}); + } + + buffer_memory += buffer.size; + + return storage_buffer_owner.make_rid(buffer); +} + +RID RenderingDevice::texture_buffer_create(uint32_t p_size_elements, DataFormat p_format, const Vector &p_data) { + _THREAD_SAFE_METHOD_ + + uint32_t element_size = get_format_vertex_size(p_format); + ERR_FAIL_COND_V_MSG(element_size == 0, RID(), "Format requested is not supported for texture buffers"); + uint64_t size_bytes = uint64_t(element_size) * p_size_elements; + + ERR_FAIL_COND_V(p_data.size() && (uint32_t)p_data.size() != size_bytes, RID()); + + Buffer texture_buffer; + texture_buffer.size = size_bytes; + BitField usage = (RDD::BUFFER_USAGE_TRANSFER_FROM_BIT | RDD::BUFFER_USAGE_TRANSFER_TO_BIT | RDD::BUFFER_USAGE_TEXEL_BIT); + texture_buffer.driver_id = driver->buffer_create(size_bytes, usage, RDD::MEMORY_ALLOCATION_TYPE_GPU); + ERR_FAIL_COND_V(!texture_buffer.driver_id, RID()); + + bool ok = driver->buffer_set_texel_format(texture_buffer.driver_id, p_format); + if (!ok) { + driver->buffer_free(texture_buffer.driver_id); + ERR_FAIL_V(RID()); + } + + if (p_data.size()) { + _buffer_update(&texture_buffer, 0, p_data.ptr(), p_data.size()); + RDD::BufferBarrier bb; + bb.buffer = texture_buffer.driver_id; + bb.src_access = RDD::BARRIER_ACCESS_TRANSFER_WRITE_BIT; + bb.dst_access = RDD::BARRIER_ACCESS_SHADER_READ_BIT; + bb.size = size_bytes; + driver->command_pipeline_barrier(frames[frame].setup_command_buffer, RDD::PIPELINE_STAGE_TRANSFER_BIT, (RDD::PIPELINE_STAGE_VERTEX_SHADER_BIT | RDD::PIPELINE_STAGE_FRAGMENT_SHADER_BIT | RDD::PIPELINE_STAGE_COMPUTE_SHADER_BIT), {}, bb, {}); + } + + buffer_memory += size_bytes; + + RID id = texture_buffer_owner.make_rid(texture_buffer); +#ifdef DEV_ENABLED + set_resource_name(id, "RID:" + itos(id.get_id())); +#endif + return id; +} + +/*****************/ +/**** TEXTURE ****/ +/*****************/ + +RID RenderingDevice::texture_create(const TextureFormat &p_format, const TextureView &p_view, const Vector> &p_data) { + _THREAD_SAFE_METHOD_ + + // Some adjustments will happen. + TextureFormat format = p_format; + + if (format.shareable_formats.size()) { + ERR_FAIL_COND_V_MSG(format.shareable_formats.find(format.format) == -1, RID(), + "If supplied a list of shareable formats, the current format must be present in the list"); + ERR_FAIL_COND_V_MSG(p_view.format_override != DATA_FORMAT_MAX && format.shareable_formats.find(p_view.format_override) == -1, RID(), + "If supplied a list of shareable formats, the current view format override must be present in the list"); + } + + ERR_FAIL_INDEX_V(format.texture_type, RDD::TEXTURE_TYPE_MAX, RID()); + + ERR_FAIL_COND_V_MSG(format.width < 1, RID(), "Width must be equal or greater than 1 for all textures"); + + if (format.texture_type != TEXTURE_TYPE_1D && format.texture_type != TEXTURE_TYPE_1D_ARRAY) { + ERR_FAIL_COND_V_MSG(format.height < 1, RID(), "Height must be equal or greater than 1 for 2D and 3D textures"); + } + + if (format.texture_type == TEXTURE_TYPE_3D) { + ERR_FAIL_COND_V_MSG(format.depth < 1, RID(), "Depth must be equal or greater than 1 for 3D textures"); + } + + ERR_FAIL_COND_V(format.mipmaps < 1, RID()); + + if (format.texture_type == TEXTURE_TYPE_1D_ARRAY || format.texture_type == TEXTURE_TYPE_2D_ARRAY || format.texture_type == TEXTURE_TYPE_CUBE_ARRAY || format.texture_type == TEXTURE_TYPE_CUBE) { + ERR_FAIL_COND_V_MSG(format.array_layers < 1, RID(), + "Amount of layers must be equal or greater than 1 for arrays and cubemaps."); + ERR_FAIL_COND_V_MSG((format.texture_type == TEXTURE_TYPE_CUBE_ARRAY || format.texture_type == TEXTURE_TYPE_CUBE) && (format.array_layers % 6) != 0, RID(), + "Cubemap and cubemap array textures must provide a layer number that is multiple of 6"); + } else { + format.array_layers = 1; + } + + ERR_FAIL_INDEX_V(format.samples, TEXTURE_SAMPLES_MAX, RID()); + + format.height = format.texture_type != TEXTURE_TYPE_1D && format.texture_type != TEXTURE_TYPE_1D_ARRAY ? format.height : 1; + format.depth = format.texture_type == TEXTURE_TYPE_3D ? format.depth : 1; + + uint32_t required_mipmaps = get_image_required_mipmaps(format.width, format.height, format.depth); + + ERR_FAIL_COND_V_MSG(required_mipmaps < format.mipmaps, RID(), + "Too many mipmaps requested for texture format and dimensions (" + itos(format.mipmaps) + "), maximum allowed: (" + itos(required_mipmaps) + ")."); + + if (p_data.size()) { + ERR_FAIL_COND_V_MSG(!(format.usage_bits & TEXTURE_USAGE_CAN_UPDATE_BIT), RID(), + "Texture needs the TEXTURE_USAGE_CAN_UPDATE_BIT usage flag in order to be updated at initialization or later"); + + ERR_FAIL_COND_V_MSG(p_data.size() != (int)format.array_layers, RID(), + "Default supplied data for image format is of invalid length (" + itos(p_data.size()) + "), should be (" + itos(format.array_layers) + ")."); + + for (uint32_t i = 0; i < format.array_layers; i++) { + uint32_t required_size = get_image_format_required_size(format.format, format.width, format.height, format.depth, format.mipmaps); ERR_FAIL_COND_V_MSG((uint32_t)p_data[i].size() != required_size, RID(), "Data for slice index " + itos(i) + " (mapped to layer " + itos(i) + ") differs in size (supplied: " + itos(p_data[i].size()) + ") than what is required by the format (" + itos(required_size) + ")."); } @@ -1819,343 +795,161 @@ RID RenderingDeviceVulkan::texture_create(const TextureFormat &p_format, const T { // Validate that this image is supported for the intended use. - VkFormatProperties properties; - vkGetPhysicalDeviceFormatProperties(context->get_physical_device(), image_create_info.format, &properties); - VkFormatFeatureFlags flags; - - String format_text = "'" + String(named_formats[p_format.format]) + "'"; + bool cpu_readable = (format.usage_bits & RDD::TEXTURE_USAGE_CPU_READ_BIT); + BitField supported_usage = driver->texture_get_usages_supported_by_format(format.format, cpu_readable); - if (p_format.usage_bits & TEXTURE_USAGE_CPU_READ_BIT) { - flags = properties.linearTilingFeatures; - format_text += " (with CPU read bit)"; - } else { - flags = properties.optimalTilingFeatures; - } + String format_text = "'" + String(FORMAT_NAMES[format.format]) + "'"; - if (p_format.usage_bits & TEXTURE_USAGE_SAMPLING_BIT && !(flags & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT)) { + if ((format.usage_bits & TEXTURE_USAGE_SAMPLING_BIT) && !supported_usage.has_flag(TEXTURE_USAGE_SAMPLING_BIT)) { ERR_FAIL_V_MSG(RID(), "Format " + format_text + " does not support usage as sampling texture."); } - - if (p_format.usage_bits & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT && !(flags & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT)) { + if ((format.usage_bits & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) && !supported_usage.has_flag(TEXTURE_USAGE_COLOR_ATTACHMENT_BIT)) { ERR_FAIL_V_MSG(RID(), "Format " + format_text + " does not support usage as color attachment."); } - - if (p_format.usage_bits & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT && !(flags & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT)) { + if ((format.usage_bits & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) && !supported_usage.has_flag(TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) { ERR_FAIL_V_MSG(RID(), "Format " + format_text + " does not support usage as depth-stencil attachment."); } - - if (p_format.usage_bits & TEXTURE_USAGE_STORAGE_BIT && !(flags & VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT)) { + if ((format.usage_bits & TEXTURE_USAGE_STORAGE_BIT) && !supported_usage.has_flag(TEXTURE_USAGE_STORAGE_BIT)) { ERR_FAIL_V_MSG(RID(), "Format " + format_text + " does not support usage as storage image."); } - - if (p_format.usage_bits & TEXTURE_USAGE_STORAGE_ATOMIC_BIT && !(flags & VK_FORMAT_FEATURE_STORAGE_IMAGE_ATOMIC_BIT)) { + if ((format.usage_bits & TEXTURE_USAGE_STORAGE_ATOMIC_BIT) && !supported_usage.has_flag(TEXTURE_USAGE_STORAGE_ATOMIC_BIT)) { ERR_FAIL_V_MSG(RID(), "Format " + format_text + " does not support usage as atomic storage image."); } - - // Validation via VK_FORMAT_FEATURE_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR fails if VRS attachment is not supported. - if (p_format.usage_bits & TEXTURE_USAGE_VRS_ATTACHMENT_BIT && p_format.format != DATA_FORMAT_R8_UINT) { + if ((format.usage_bits & TEXTURE_USAGE_VRS_ATTACHMENT_BIT) && !supported_usage.has_flag(TEXTURE_USAGE_VRS_ATTACHMENT_BIT)) { ERR_FAIL_V_MSG(RID(), "Format " + format_text + " does not support usage as VRS attachment."); } } - // Some view validation. + // Transfer and validate view info. - if (p_view.format_override != DATA_FORMAT_MAX) { + RDD::TextureView tv; + if (p_view.format_override == DATA_FORMAT_MAX) { + tv.format = format.format; + } else { ERR_FAIL_INDEX_V(p_view.format_override, DATA_FORMAT_MAX, RID()); + tv.format = p_view.format_override; } ERR_FAIL_INDEX_V(p_view.swizzle_r, TEXTURE_SWIZZLE_MAX, RID()); ERR_FAIL_INDEX_V(p_view.swizzle_g, TEXTURE_SWIZZLE_MAX, RID()); ERR_FAIL_INDEX_V(p_view.swizzle_b, TEXTURE_SWIZZLE_MAX, RID()); ERR_FAIL_INDEX_V(p_view.swizzle_a, TEXTURE_SWIZZLE_MAX, RID()); + tv.swizzle_r = p_view.swizzle_r; + tv.swizzle_g = p_view.swizzle_g; + tv.swizzle_b = p_view.swizzle_b; + tv.swizzle_a = p_view.swizzle_a; - // Allocate memory. - - uint32_t width, height; - uint32_t image_size = get_image_format_required_size(p_format.format, p_format.width, p_format.height, p_format.depth, p_format.mipmaps, &width, &height); - - VmaAllocationCreateInfo allocInfo; - allocInfo.flags = (p_format.usage_bits & TEXTURE_USAGE_CPU_READ_BIT) ? VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT : 0; - allocInfo.pool = nullptr; - allocInfo.usage = VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE; - allocInfo.requiredFlags = 0; - allocInfo.preferredFlags = 0; - allocInfo.memoryTypeBits = 0; - allocInfo.pUserData = nullptr; - if (image_size <= SMALL_ALLOCATION_MAX_SIZE) { - uint32_t mem_type_index = 0; - vmaFindMemoryTypeIndexForImageInfo(allocator, &image_create_info, &allocInfo, &mem_type_index); - allocInfo.pool = _find_or_create_small_allocs_pool(mem_type_index); - } + // Create. Texture texture; - VkResult err = vmaCreateImage(allocator, &image_create_info, &allocInfo, &texture.image, &texture.allocation, &texture.allocation_info); - ERR_FAIL_COND_V_MSG(err, RID(), "vmaCreateImage failed with error " + itos(err) + "."); - image_memory += texture.allocation_info.size; - texture.type = p_format.texture_type; - texture.format = p_format.format; - texture.width = image_create_info.extent.width; - texture.height = image_create_info.extent.height; - texture.depth = image_create_info.extent.depth; - texture.layers = image_create_info.arrayLayers; - texture.mipmaps = image_create_info.mipLevels; + texture.driver_id = driver->texture_create(format, tv); + ERR_FAIL_COND_V(!texture.driver_id, RID()); + texture.type = format.texture_type; + texture.format = format.format; + texture.width = format.width; + texture.height = format.height; + texture.depth = format.depth; + texture.layers = format.array_layers; + texture.mipmaps = format.mipmaps; texture.base_mipmap = 0; texture.base_layer = 0; - texture.is_resolve_buffer = p_format.is_resolve_buffer; - texture.usage_flags = p_format.usage_bits; - texture.samples = p_format.samples; - texture.allowed_shared_formats = p_format.shareable_formats; + texture.is_resolve_buffer = format.is_resolve_buffer; + texture.usage_flags = format.usage_bits; + texture.samples = format.samples; + texture.allowed_shared_formats = format.shareable_formats; // Set base layout based on usage priority. - if (p_format.usage_bits & TEXTURE_USAGE_SAMPLING_BIT) { + if ((format.usage_bits & TEXTURE_USAGE_SAMPLING_BIT)) { // First priority, readable. - texture.layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; - - } else if (p_format.usage_bits & TEXTURE_USAGE_STORAGE_BIT) { + texture.layout = RDD::TEXTURE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; + } else if ((format.usage_bits & TEXTURE_USAGE_STORAGE_BIT)) { // Second priority, storage. - - texture.layout = VK_IMAGE_LAYOUT_GENERAL; - - } else if (p_format.usage_bits & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) { + texture.layout = RDD::TEXTURE_LAYOUT_GENERAL; + } else if ((format.usage_bits & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT)) { // Third priority, color or depth. - - texture.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; - - } else if (p_format.usage_bits & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) { - texture.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; - + texture.layout = RDD::TEXTURE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; + } else if ((format.usage_bits & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) { + texture.layout = RDD::TEXTURE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; } else { - texture.layout = VK_IMAGE_LAYOUT_GENERAL; + texture.layout = RDD::TEXTURE_LAYOUT_GENERAL; } - if (p_format.usage_bits & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) { - texture.read_aspect_mask = VK_IMAGE_ASPECT_DEPTH_BIT; - texture.barrier_aspect_mask = VK_IMAGE_ASPECT_DEPTH_BIT; - - if (format_has_stencil(p_format.format)) { - texture.barrier_aspect_mask |= VK_IMAGE_ASPECT_STENCIL_BIT; + if ((format.usage_bits & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) { + texture.read_aspect_flags.set_flag(RDD::TEXTURE_ASPECT_DEPTH_BIT); + texture.barrier_aspect_flags.set_flag(RDD::TEXTURE_ASPECT_DEPTH_BIT); + if (format_has_stencil(format.format)) { + texture.barrier_aspect_flags.set_flag(RDD::TEXTURE_ASPECT_STENCIL_BIT); } } else { - texture.read_aspect_mask = VK_IMAGE_ASPECT_COLOR_BIT; - texture.barrier_aspect_mask = VK_IMAGE_ASPECT_COLOR_BIT; + texture.read_aspect_flags.set_flag(RDD::TEXTURE_ASPECT_COLOR_BIT); + texture.barrier_aspect_flags.set_flag(RDD::TEXTURE_ASPECT_COLOR_BIT); } texture.bound = false; - // Create view. - - VkImageViewCreateInfo image_view_create_info; - image_view_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; - image_view_create_info.pNext = nullptr; - image_view_create_info.flags = 0; - image_view_create_info.image = texture.image; - - static const VkImageViewType view_types[TEXTURE_TYPE_MAX] = { - VK_IMAGE_VIEW_TYPE_1D, - VK_IMAGE_VIEW_TYPE_2D, - VK_IMAGE_VIEW_TYPE_3D, - VK_IMAGE_VIEW_TYPE_CUBE, - VK_IMAGE_VIEW_TYPE_1D_ARRAY, - VK_IMAGE_VIEW_TYPE_2D_ARRAY, - VK_IMAGE_VIEW_TYPE_CUBE_ARRAY, - }; - - image_view_create_info.viewType = view_types[p_format.texture_type]; - if (p_view.format_override == DATA_FORMAT_MAX) { - image_view_create_info.format = image_create_info.format; - } else { - image_view_create_info.format = vulkan_formats[p_view.format_override]; - } - - static const VkComponentSwizzle component_swizzles[TEXTURE_SWIZZLE_MAX] = { - VK_COMPONENT_SWIZZLE_IDENTITY, - VK_COMPONENT_SWIZZLE_ZERO, - VK_COMPONENT_SWIZZLE_ONE, - VK_COMPONENT_SWIZZLE_R, - VK_COMPONENT_SWIZZLE_G, - VK_COMPONENT_SWIZZLE_B, - VK_COMPONENT_SWIZZLE_A - }; - - image_view_create_info.components.r = component_swizzles[p_view.swizzle_r]; - image_view_create_info.components.g = component_swizzles[p_view.swizzle_g]; - image_view_create_info.components.b = component_swizzles[p_view.swizzle_b]; - image_view_create_info.components.a = component_swizzles[p_view.swizzle_a]; - - image_view_create_info.subresourceRange.baseMipLevel = 0; - image_view_create_info.subresourceRange.levelCount = image_create_info.mipLevels; - image_view_create_info.subresourceRange.baseArrayLayer = 0; - image_view_create_info.subresourceRange.layerCount = image_create_info.arrayLayers; - if (p_format.usage_bits & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) { - image_view_create_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT; - } else { - image_view_create_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - } - - err = vkCreateImageView(device, &image_view_create_info, nullptr, &texture.view); - - if (err) { - vmaDestroyImage(allocator, texture.image, texture.allocation); - ERR_FAIL_V_MSG(RID(), "vkCreateImageView failed with error " + itos(err) + "."); - } - // Barrier to set layout. { - VkImageMemoryBarrier image_memory_barrier; - image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; - image_memory_barrier.pNext = nullptr; - image_memory_barrier.srcAccessMask = 0; - image_memory_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; - image_memory_barrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; - image_memory_barrier.newLayout = texture.layout; - image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - image_memory_barrier.image = texture.image; - image_memory_barrier.subresourceRange.aspectMask = texture.barrier_aspect_mask; - image_memory_barrier.subresourceRange.baseMipLevel = 0; - image_memory_barrier.subresourceRange.levelCount = image_create_info.mipLevels; - image_memory_barrier.subresourceRange.baseArrayLayer = 0; - image_memory_barrier.subresourceRange.layerCount = image_create_info.arrayLayers; - - vkCmdPipelineBarrier(frames[frame].setup_command_buffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier); + RDD::TextureBarrier tb; + tb.texture = texture.driver_id; + tb.dst_access = RDD::BARRIER_ACCESS_SHADER_READ_BIT; + tb.prev_layout = RDD::TEXTURE_LAYOUT_UNDEFINED; + tb.next_layout = texture.layout; + tb.subresources.aspect = texture.barrier_aspect_flags; + tb.subresources.mipmap_count = format.mipmaps; + tb.subresources.layer_count = format.array_layers; + + driver->command_pipeline_barrier(frames[frame].setup_command_buffer, RDD::PIPELINE_STAGE_TOP_OF_PIPE_BIT, RDD::PIPELINE_STAGE_VERTEX_SHADER_BIT | RDD::PIPELINE_STAGE_FRAGMENT_SHADER_BIT | RDD::PIPELINE_STAGE_COMPUTE_SHADER_BIT, {}, {}, tb); } + texture_memory += driver->texture_get_allocation_size(texture.driver_id); + RID id = texture_owner.make_rid(texture); #ifdef DEV_ENABLED set_resource_name(id, "RID:" + itos(id.get_id())); #endif if (p_data.size()) { - for (uint32_t i = 0; i < image_create_info.arrayLayers; i++) { - _texture_update(id, i, p_data[i], RD::BARRIER_MASK_ALL_BARRIERS, true); + for (uint32_t i = 0; i < p_format.array_layers; i++) { + _texture_update(id, i, p_data[i], BARRIER_MASK_ALL_BARRIERS, true); } } return id; } -RID RenderingDeviceVulkan::texture_create_shared(const TextureView &p_view, RID p_with_texture) { +RID RenderingDevice::texture_create_shared(const TextureView &p_view, RID p_with_texture) { _THREAD_SAFE_METHOD_ Texture *src_texture = texture_owner.get_or_null(p_with_texture); - ERR_FAIL_NULL_V(src_texture, RID()); + ERR_FAIL_COND_V(!src_texture, RID()); - if (src_texture->owner.is_valid()) { // Ahh this is a share. + if (src_texture->owner.is_valid()) { // Ahh this is a share. The RenderingDeviceDriver needs the actual owner. p_with_texture = src_texture->owner; src_texture = texture_owner.get_or_null(src_texture->owner); - ERR_FAIL_NULL_V(src_texture, RID()); // This is a bug. + ERR_FAIL_COND_V(!src_texture, RID()); // This is a bug. } // Create view. Texture texture = *src_texture; - VkImageViewCreateInfo image_view_create_info; - image_view_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; - image_view_create_info.pNext = nullptr; - image_view_create_info.flags = 0; - image_view_create_info.image = texture.image; - - static const VkImageViewType view_types[TEXTURE_TYPE_MAX] = { - VK_IMAGE_VIEW_TYPE_1D, - VK_IMAGE_VIEW_TYPE_2D, - VK_IMAGE_VIEW_TYPE_3D, - VK_IMAGE_VIEW_TYPE_CUBE, - VK_IMAGE_VIEW_TYPE_1D_ARRAY, - VK_IMAGE_VIEW_TYPE_2D_ARRAY, - VK_IMAGE_VIEW_TYPE_CUBE_ARRAY, - }; - - image_view_create_info.viewType = view_types[texture.type]; + RDD::TextureView tv; if (p_view.format_override == DATA_FORMAT_MAX || p_view.format_override == texture.format) { - image_view_create_info.format = vulkan_formats[texture.format]; + tv.format = texture.format; } else { ERR_FAIL_INDEX_V(p_view.format_override, DATA_FORMAT_MAX, RID()); ERR_FAIL_COND_V_MSG(texture.allowed_shared_formats.find(p_view.format_override) == -1, RID(), "Format override is not in the list of allowed shareable formats for original texture."); - image_view_create_info.format = vulkan_formats[p_view.format_override]; - } - - static const VkComponentSwizzle component_swizzles[TEXTURE_SWIZZLE_MAX] = { - VK_COMPONENT_SWIZZLE_IDENTITY, - VK_COMPONENT_SWIZZLE_ZERO, - VK_COMPONENT_SWIZZLE_ONE, - VK_COMPONENT_SWIZZLE_R, - VK_COMPONENT_SWIZZLE_G, - VK_COMPONENT_SWIZZLE_B, - VK_COMPONENT_SWIZZLE_A - }; - - image_view_create_info.components.r = component_swizzles[p_view.swizzle_r]; - image_view_create_info.components.g = component_swizzles[p_view.swizzle_g]; - image_view_create_info.components.b = component_swizzles[p_view.swizzle_b]; - image_view_create_info.components.a = component_swizzles[p_view.swizzle_a]; - - image_view_create_info.subresourceRange.baseMipLevel = 0; - image_view_create_info.subresourceRange.levelCount = texture.mipmaps; - image_view_create_info.subresourceRange.layerCount = texture.layers; - image_view_create_info.subresourceRange.baseArrayLayer = 0; - - if (texture.usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) { - image_view_create_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT; - } else { - image_view_create_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - } - - VkImageViewUsageCreateInfo usage_info; - if (context->is_device_extension_enabled(VK_KHR_MAINTENANCE_2_EXTENSION_NAME)) { - // May need to make VK_KHR_maintenance2 manditory and thus has Vulkan 1.1 be our minimum supported version - // if we require setting this information. Vulkan 1.0 may simply not care.. - - usage_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO; - usage_info.pNext = nullptr; - if (p_view.format_override != DATA_FORMAT_MAX) { - // Need to validate usage with vulkan. - - usage_info.usage = 0; - - if (texture.usage_flags & TEXTURE_USAGE_SAMPLING_BIT) { - usage_info.usage |= VK_IMAGE_USAGE_SAMPLED_BIT; - } - - if (texture.usage_flags & TEXTURE_USAGE_STORAGE_BIT) { - if (texture_is_format_supported_for_usage(p_view.format_override, TEXTURE_USAGE_STORAGE_BIT)) { - usage_info.usage |= VK_IMAGE_USAGE_STORAGE_BIT; - } - } - - if (texture.usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) { - if (texture_is_format_supported_for_usage(p_view.format_override, TEXTURE_USAGE_COLOR_ATTACHMENT_BIT)) { - usage_info.usage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; - } - } - - if (texture.usage_flags & TEXTURE_USAGE_INPUT_ATTACHMENT_BIT) { - usage_info.usage |= VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT; - } - - if (texture.usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) { - usage_info.usage |= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT; - } - - if (texture.usage_flags & TEXTURE_USAGE_CAN_UPDATE_BIT) { - usage_info.usage |= VK_IMAGE_USAGE_TRANSFER_DST_BIT; - } - if (texture.usage_flags & TEXTURE_USAGE_CAN_COPY_FROM_BIT) { - usage_info.usage |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT; - } - - if (texture.usage_flags & TEXTURE_USAGE_CAN_COPY_TO_BIT) { - usage_info.usage |= VK_IMAGE_USAGE_TRANSFER_DST_BIT; - } - - image_view_create_info.pNext = &usage_info; - } + tv.format = p_view.format_override; } + tv.swizzle_r = p_view.swizzle_r; + tv.swizzle_g = p_view.swizzle_g; + tv.swizzle_b = p_view.swizzle_b; + tv.swizzle_a = p_view.swizzle_a; - VkResult err = vkCreateImageView(device, &image_view_create_info, nullptr, &texture.view); - ERR_FAIL_COND_V_MSG(err, RID(), "vkCreateImageView failed with error " + itos(err) + "."); + texture.driver_id = driver->texture_create_shared(texture.driver_id, tv); + ERR_FAIL_COND_V(!texture.driver_id, RID()); texture.owner = p_with_texture; RID id = texture_owner.make_rid(texture); @@ -2167,16 +961,11 @@ RID RenderingDeviceVulkan::texture_create_shared(const TextureView &p_view, RID return id; } -RID RenderingDeviceVulkan::texture_create_from_extension(TextureType p_type, DataFormat p_format, TextureSamples p_samples, BitField p_flags, uint64_t p_image, uint64_t p_width, uint64_t p_height, uint64_t p_depth, uint64_t p_layers) { +RID RenderingDevice::texture_create_from_extension(TextureType p_type, DataFormat p_format, TextureSamples p_samples, BitField p_usage, uint64_t p_image, uint64_t p_width, uint64_t p_height, uint64_t p_depth, uint64_t p_layers) { _THREAD_SAFE_METHOD_ // This method creates a texture object using a VkImage created by an extension, module or other external source (OpenXR uses this). - VkImage image = (VkImage)p_image; Texture texture; - texture.image = image; - // If we leave texture.allocation as a nullptr, would that be enough to detect we don't "own" the image? - // Also leave texture.allocation_info alone. - // We'll set texture.view later on. texture.type = p_type; texture.format = p_format; texture.samples = p_samples; @@ -2185,7 +974,7 @@ RID RenderingDeviceVulkan::texture_create_from_extension(TextureType p_type, Dat texture.depth = p_depth; texture.layers = p_layers; texture.mipmaps = 1; - texture.usage_flags = p_flags; + texture.usage_flags = p_usage; texture.base_mipmap = 0; texture.base_layer = 0; texture.allowed_shared_formats.push_back(RD::DATA_FORMAT_R8G8B8A8_UNORM); @@ -2193,112 +982,47 @@ RID RenderingDeviceVulkan::texture_create_from_extension(TextureType p_type, Dat // Set base layout based on usage priority. - if (texture.usage_flags & TEXTURE_USAGE_SAMPLING_BIT) { + if (p_usage.has_flag(TEXTURE_USAGE_SAMPLING_BIT)) { // First priority, readable. - texture.layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; - - } else if (texture.usage_flags & TEXTURE_USAGE_STORAGE_BIT) { + texture.layout = RDD::TEXTURE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; + } else if (p_usage.has_flag(TEXTURE_USAGE_STORAGE_BIT)) { // Second priority, storage. - - texture.layout = VK_IMAGE_LAYOUT_GENERAL; - - } else if (texture.usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) { + texture.layout = RDD::TEXTURE_LAYOUT_GENERAL; + } else if (p_usage.has_flag(TEXTURE_USAGE_COLOR_ATTACHMENT_BIT)) { // Third priority, color or depth. - - texture.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; - - } else if (texture.usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) { - texture.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; - + texture.layout = RDD::TEXTURE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; + } else if (p_usage.has_flag(TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) { + texture.layout = RDD::TEXTURE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; } else { - texture.layout = VK_IMAGE_LAYOUT_GENERAL; + texture.layout = RDD::TEXTURE_LAYOUT_GENERAL; } - if (texture.usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) { - texture.read_aspect_mask = VK_IMAGE_ASPECT_DEPTH_BIT; - texture.barrier_aspect_mask = VK_IMAGE_ASPECT_DEPTH_BIT; - - // if (format_has_stencil(p_format.format)) { - // texture.barrier_aspect_mask |= VK_IMAGE_ASPECT_STENCIL_BIT; - // } - } else { - texture.read_aspect_mask = VK_IMAGE_ASPECT_COLOR_BIT; - texture.barrier_aspect_mask = VK_IMAGE_ASPECT_COLOR_BIT; - } - - // Create a view for us to use. - - VkImageViewCreateInfo image_view_create_info; - image_view_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; - image_view_create_info.pNext = nullptr; - image_view_create_info.flags = 0; - image_view_create_info.image = texture.image; - - static const VkImageViewType view_types[TEXTURE_TYPE_MAX] = { - VK_IMAGE_VIEW_TYPE_1D, - VK_IMAGE_VIEW_TYPE_2D, - VK_IMAGE_VIEW_TYPE_3D, - VK_IMAGE_VIEW_TYPE_CUBE, - VK_IMAGE_VIEW_TYPE_1D_ARRAY, - VK_IMAGE_VIEW_TYPE_2D_ARRAY, - VK_IMAGE_VIEW_TYPE_CUBE_ARRAY, - }; - - image_view_create_info.viewType = view_types[texture.type]; - image_view_create_info.format = vulkan_formats[texture.format]; - - static const VkComponentSwizzle component_swizzles[TEXTURE_SWIZZLE_MAX] = { - VK_COMPONENT_SWIZZLE_IDENTITY, - VK_COMPONENT_SWIZZLE_ZERO, - VK_COMPONENT_SWIZZLE_ONE, - VK_COMPONENT_SWIZZLE_R, - VK_COMPONENT_SWIZZLE_G, - VK_COMPONENT_SWIZZLE_B, - VK_COMPONENT_SWIZZLE_A - }; - - // Hardcode for now, maybe make this settable from outside. - image_view_create_info.components.r = component_swizzles[TEXTURE_SWIZZLE_R]; - image_view_create_info.components.g = component_swizzles[TEXTURE_SWIZZLE_G]; - image_view_create_info.components.b = component_swizzles[TEXTURE_SWIZZLE_B]; - image_view_create_info.components.a = component_swizzles[TEXTURE_SWIZZLE_A]; - - image_view_create_info.subresourceRange.baseMipLevel = 0; - image_view_create_info.subresourceRange.levelCount = texture.mipmaps; - image_view_create_info.subresourceRange.baseArrayLayer = 0; - image_view_create_info.subresourceRange.layerCount = texture.layers; - if (texture.usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) { - image_view_create_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT; + if (p_usage.has_flag(TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) { + texture.read_aspect_flags.set_flag(RDD::TEXTURE_ASPECT_DEPTH_BIT); + texture.barrier_aspect_flags.set_flag(RDD::TEXTURE_ASPECT_DEPTH_BIT); + /*if (format_has_stencil(p_format.format)) { + texture.barrier_aspect_flags.set_flag(RDD::TEXTURE_ASPECT_STENCIL_BIT); + }*/ } else { - image_view_create_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + texture.read_aspect_flags.set_flag(RDD::TEXTURE_ASPECT_COLOR_BIT); + texture.barrier_aspect_flags.set_flag(RDD::TEXTURE_ASPECT_COLOR_BIT); } - VkResult err = vkCreateImageView(device, &image_view_create_info, nullptr, &texture.view); - - if (err) { - // vmaDestroyImage(allocator, texture.image, texture.allocation); - ERR_FAIL_V_MSG(RID(), "vkCreateImageView failed with error " + itos(err) + "."); - } + texture.driver_id = driver->texture_create_from_extension(p_image, p_type, p_format, p_layers, (texture.usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)); + ERR_FAIL_COND_V(!texture.driver_id, RID()); // Barrier to set layout. { - VkImageMemoryBarrier image_memory_barrier; - image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; - image_memory_barrier.pNext = nullptr; - image_memory_barrier.srcAccessMask = 0; - image_memory_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; - image_memory_barrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; - image_memory_barrier.newLayout = texture.layout; - image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - image_memory_barrier.image = texture.image; - image_memory_barrier.subresourceRange.aspectMask = texture.barrier_aspect_mask; - image_memory_barrier.subresourceRange.baseMipLevel = 0; - image_memory_barrier.subresourceRange.levelCount = texture.mipmaps; - image_memory_barrier.subresourceRange.baseArrayLayer = 0; - image_memory_barrier.subresourceRange.layerCount = texture.layers; - - vkCmdPipelineBarrier(frames[frame].setup_command_buffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier); + RDD::TextureBarrier tb; + tb.texture = texture.driver_id; + tb.dst_access = RDD::BARRIER_ACCESS_SHADER_READ_BIT; + tb.prev_layout = RDD::TEXTURE_LAYOUT_UNDEFINED; + tb.next_layout = texture.layout; + tb.subresources.aspect = texture.barrier_aspect_flags; + tb.subresources.mipmap_count = texture.mipmaps; + tb.subresources.layer_count = texture.layers; + + driver->command_pipeline_barrier(frames[frame].setup_command_buffer, RDD::PIPELINE_STAGE_TOP_OF_PIPE_BIT, RDD::PIPELINE_STAGE_VERTEX_SHADER_BIT, {}, {}, tb); } RID id = texture_owner.make_rid(texture); @@ -2309,16 +1033,16 @@ RID RenderingDeviceVulkan::texture_create_from_extension(TextureType p_type, Dat return id; } -RID RenderingDeviceVulkan::texture_create_shared_from_slice(const TextureView &p_view, RID p_with_texture, uint32_t p_layer, uint32_t p_mipmap, uint32_t p_mipmaps, TextureSliceType p_slice_type, uint32_t p_layers) { +RID RenderingDevice::texture_create_shared_from_slice(const TextureView &p_view, RID p_with_texture, uint32_t p_layer, uint32_t p_mipmap, uint32_t p_mipmaps, TextureSliceType p_slice_type, uint32_t p_layers) { _THREAD_SAFE_METHOD_ Texture *src_texture = texture_owner.get_or_null(p_with_texture); - ERR_FAIL_NULL_V(src_texture, RID()); + ERR_FAIL_COND_V(!src_texture, RID()); - if (src_texture->owner.is_valid()) { // Ahh this is a share. + if (src_texture->owner.is_valid()) { // // Ahh this is a share. The RenderingDeviceDriver needs the actual owner. p_with_texture = src_texture->owner; src_texture = texture_owner.get_or_null(src_texture->owner); - ERR_FAIL_NULL_V(src_texture, RID()); // This is a bug. + ERR_FAIL_COND_V(!src_texture, RID()); // This is a bug. } ERR_FAIL_COND_V_MSG(p_slice_type == TEXTURE_SLICE_CUBEMAP && (src_texture->type != TEXTURE_TYPE_CUBE && src_texture->type != TEXTURE_TYPE_CUBE_ARRAY), RID(), @@ -2355,62 +1079,26 @@ RID RenderingDeviceVulkan::texture_create_shared_from_slice(const TextureView &p texture.base_mipmap = p_mipmap; texture.base_layer = p_layer; - VkImageViewCreateInfo image_view_create_info; - image_view_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; - image_view_create_info.pNext = nullptr; - image_view_create_info.flags = 0; - image_view_create_info.image = texture.image; - - static const VkImageViewType view_types[TEXTURE_TYPE_MAX] = { - VK_IMAGE_VIEW_TYPE_1D, - VK_IMAGE_VIEW_TYPE_2D, - VK_IMAGE_VIEW_TYPE_2D, - VK_IMAGE_VIEW_TYPE_2D, - VK_IMAGE_VIEW_TYPE_1D, - VK_IMAGE_VIEW_TYPE_2D, - VK_IMAGE_VIEW_TYPE_2D, - }; - - image_view_create_info.viewType = view_types[texture.type]; - - if (p_slice_type == TEXTURE_SLICE_CUBEMAP) { - image_view_create_info.viewType = VK_IMAGE_VIEW_TYPE_CUBE; - } else if (p_slice_type == TEXTURE_SLICE_3D) { - image_view_create_info.viewType = VK_IMAGE_VIEW_TYPE_3D; - } else if (p_slice_type == TEXTURE_SLICE_2D_ARRAY) { - image_view_create_info.viewType = VK_IMAGE_VIEW_TYPE_2D_ARRAY; - } - if (p_slice_type == TEXTURE_SLICE_2D) { texture.type = TEXTURE_TYPE_2D; } else if (p_slice_type == TEXTURE_SLICE_3D) { texture.type = TEXTURE_TYPE_3D; } + RDD::TextureView tv; if (p_view.format_override == DATA_FORMAT_MAX || p_view.format_override == texture.format) { - image_view_create_info.format = vulkan_formats[texture.format]; + tv.format = texture.format; } else { ERR_FAIL_INDEX_V(p_view.format_override, DATA_FORMAT_MAX, RID()); ERR_FAIL_COND_V_MSG(texture.allowed_shared_formats.find(p_view.format_override) == -1, RID(), "Format override is not in the list of allowed shareable formats for original texture."); - image_view_create_info.format = vulkan_formats[p_view.format_override]; + tv.format = p_view.format_override; } - - static const VkComponentSwizzle component_swizzles[TEXTURE_SWIZZLE_MAX] = { - VK_COMPONENT_SWIZZLE_IDENTITY, - VK_COMPONENT_SWIZZLE_ZERO, - VK_COMPONENT_SWIZZLE_ONE, - VK_COMPONENT_SWIZZLE_R, - VK_COMPONENT_SWIZZLE_G, - VK_COMPONENT_SWIZZLE_B, - VK_COMPONENT_SWIZZLE_A - }; - - image_view_create_info.components.r = component_swizzles[p_view.swizzle_r]; - image_view_create_info.components.g = component_swizzles[p_view.swizzle_g]; - image_view_create_info.components.b = component_swizzles[p_view.swizzle_b]; - image_view_create_info.components.a = component_swizzles[p_view.swizzle_a]; + tv.swizzle_r = p_view.swizzle_r; + tv.swizzle_g = p_view.swizzle_g; + tv.swizzle_b = p_view.swizzle_b; + tv.swizzle_a = p_view.swizzle_a; if (p_slice_type == TEXTURE_SLICE_CUBEMAP) { ERR_FAIL_COND_V_MSG(p_layer >= src_texture->layers, RID(), @@ -2418,19 +1106,9 @@ RID RenderingDeviceVulkan::texture_create_shared_from_slice(const TextureView &p ERR_FAIL_COND_V_MSG((p_layer % 6) != 0, RID(), "Specified layer must be a multiple of 6."); } - image_view_create_info.subresourceRange.baseMipLevel = p_mipmap; - image_view_create_info.subresourceRange.levelCount = p_mipmaps; - image_view_create_info.subresourceRange.layerCount = slice_layers; - image_view_create_info.subresourceRange.baseArrayLayer = p_layer; - - if (texture.usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) { - image_view_create_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT; - } else { - image_view_create_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - } - VkResult err = vkCreateImageView(device, &image_view_create_info, nullptr, &texture.view); - ERR_FAIL_COND_V_MSG(err, RID(), "vkCreateImageView failed with error " + itos(err) + "."); + texture.driver_id = driver->texture_create_shared_from_slice(src_texture->driver_id, tv, p_slice_type, p_layer, slice_layers, p_mipmap, p_mipmaps); + ERR_FAIL_COND_V(!texture.driver_id, RID()); texture.owner = p_with_texture; RID id = texture_owner.make_rid(texture); @@ -2442,7 +1120,7 @@ RID RenderingDeviceVulkan::texture_create_shared_from_slice(const TextureView &p return id; } -Error RenderingDeviceVulkan::texture_update(RID p_texture, uint32_t p_layer, const Vector &p_data, BitField p_post_barrier) { +Error RenderingDevice::texture_update(RID p_texture, uint32_t p_layer, const Vector &p_data, BitField p_post_barrier) { return _texture_update(p_texture, p_layer, p_data, p_post_barrier, false); } @@ -2462,7 +1140,7 @@ static _ALWAYS_INLINE_ void _copy_region(uint8_t const *__restrict p_src, uint8_ } } -Error RenderingDeviceVulkan::_texture_update(RID p_texture, uint32_t p_layer, const Vector &p_data, BitField p_post_barrier, bool p_use_setup_queue) { +Error RenderingDevice::_texture_update(RID p_texture, uint32_t p_layer, const Vector &p_data, BitField p_post_barrier, bool p_use_setup_queue) { _THREAD_SAFE_METHOD_ ERR_FAIL_COND_V_MSG((draw_list || compute_list) && !p_use_setup_queue, ERR_INVALID_PARAMETER, @@ -2507,28 +1185,21 @@ Error RenderingDeviceVulkan::_texture_update(RID p_texture, uint32_t p_layer, co const uint8_t *r = p_data.ptr(); - VkCommandBuffer command_buffer = p_use_setup_queue ? frames[frame].setup_command_buffer : frames[frame].draw_command_buffer; + RDD::CommandBufferID command_buffer = p_use_setup_queue ? frames[frame].setup_command_buffer : frames[frame].draw_command_buffer; // Barrier to transfer. { - VkImageMemoryBarrier image_memory_barrier; - image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; - image_memory_barrier.pNext = nullptr; - image_memory_barrier.srcAccessMask = 0; - image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - image_memory_barrier.oldLayout = texture->layout; - image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; - - image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - image_memory_barrier.image = texture->image; - image_memory_barrier.subresourceRange.aspectMask = texture->barrier_aspect_mask; - image_memory_barrier.subresourceRange.baseMipLevel = 0; - image_memory_barrier.subresourceRange.levelCount = texture->mipmaps; - image_memory_barrier.subresourceRange.baseArrayLayer = p_layer; - image_memory_barrier.subresourceRange.layerCount = 1; - - vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier); + RDD::TextureBarrier tb; + tb.texture = texture->driver_id; + tb.dst_access = RDD::BARRIER_ACCESS_TRANSFER_WRITE_BIT; + tb.prev_layout = texture->layout; + tb.next_layout = RDD::TEXTURE_LAYOUT_TRANSFER_DST_OPTIMAL; + tb.subresources.aspect = texture->barrier_aspect_flags; + tb.subresources.mipmap_count = texture->mipmaps; + tb.subresources.base_layer = p_layer; + tb.subresources.layer_count = 1; + + driver->command_pipeline_barrier(command_buffer, RDD::PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, RDD::PIPELINE_STAGE_TRANSFER_BIT, {}, {}, tb); } uint32_t mipmap_offset = 0; @@ -2566,10 +1237,9 @@ Error RenderingDeviceVulkan::_texture_update(RID p_texture, uint32_t p_layer, co uint8_t *write_ptr; { // Map. - void *data_ptr = nullptr; - VkResult vkerr = vmaMapMemory(allocator, staging_buffer_blocks[staging_buffer_current].allocation, &data_ptr); - ERR_FAIL_COND_V_MSG(vkerr, ERR_CANT_CREATE, "vmaMapMemory failed with error " + itos(vkerr) + "."); - write_ptr = (uint8_t *)data_ptr; + uint8_t *data_ptr = driver->buffer_map(staging_buffer_blocks[staging_buffer_current].driver_id); + ERR_FAIL_NULL_V(data_ptr, ERR_CANT_CREATE); + write_ptr = data_ptr; write_ptr += alloc_offset; } @@ -2599,28 +1269,19 @@ Error RenderingDeviceVulkan::_texture_update(RID p_texture, uint32_t p_layer, co } { // Unmap. - vmaUnmapMemory(allocator, staging_buffer_blocks[staging_buffer_current].allocation); + driver->buffer_unmap(staging_buffer_blocks[staging_buffer_current].driver_id); } - VkBufferImageCopy buffer_image_copy; - buffer_image_copy.bufferOffset = alloc_offset; - buffer_image_copy.bufferRowLength = 0; // Tightly packed. - buffer_image_copy.bufferImageHeight = 0; // Tightly packed. - - buffer_image_copy.imageSubresource.aspectMask = texture->read_aspect_mask; - buffer_image_copy.imageSubresource.mipLevel = mm_i; - buffer_image_copy.imageSubresource.baseArrayLayer = p_layer; - buffer_image_copy.imageSubresource.layerCount = 1; + RDD::BufferTextureCopyRegion copy_region; + copy_region.buffer_offset = alloc_offset; + copy_region.texture_subresources.aspect = texture->read_aspect_flags; + copy_region.texture_subresources.mipmap = mm_i; + copy_region.texture_subresources.base_layer = p_layer; + copy_region.texture_subresources.layer_count = 1; + copy_region.texture_offset = Vector3i(x, y, z); + copy_region.texture_region_size = Vector3i(region_logic_w, region_logic_h, 1); - buffer_image_copy.imageOffset.x = x; - buffer_image_copy.imageOffset.y = y; - buffer_image_copy.imageOffset.z = z; - - buffer_image_copy.imageExtent.width = region_logic_w; - buffer_image_copy.imageExtent.height = region_logic_h; - buffer_image_copy.imageExtent.depth = 1; - - vkCmdCopyBufferToImage(command_buffer, staging_buffer_blocks[staging_buffer_current].buffer, texture->image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &buffer_image_copy); + driver->command_copy_buffer_to_texture(command_buffer, staging_buffer_blocks[staging_buffer_current].driver_id, texture->driver_id, RDD::TEXTURE_LAYOUT_TRANSFER_DST_OPTIMAL, copy_region); staging_buffer_blocks.write[staging_buffer_current].fill_amount = alloc_offset + alloc_size; } @@ -2634,46 +1295,41 @@ Error RenderingDeviceVulkan::_texture_update(RID p_texture, uint32_t p_layer, co // Barrier to restore layout. { - uint32_t barrier_flags = 0; - uint32_t access_flags = 0; + BitField stages; + BitField access; if (p_post_barrier.has_flag(BARRIER_MASK_COMPUTE)) { - barrier_flags |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT; - access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; + stages.set_flag(RDD::PIPELINE_STAGE_COMPUTE_SHADER_BIT); + access.set_flag(RDD::BARRIER_ACCESS_SHADER_READ_BIT).set_flag(RDD::BARRIER_ACCESS_SHADER_WRITE_BIT); } if (p_post_barrier.has_flag(BARRIER_MASK_VERTEX)) { - barrier_flags |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT; - access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; + stages.set_flag(RDD::PIPELINE_STAGE_VERTEX_SHADER_BIT); + access.set_flag(RDD::BARRIER_ACCESS_SHADER_READ_BIT).set_flag(RDD::BARRIER_ACCESS_SHADER_WRITE_BIT); } if (p_post_barrier.has_flag(BARRIER_MASK_FRAGMENT)) { - barrier_flags |= VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT; - access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; + stages.set_flag(RDD::PIPELINE_STAGE_FRAGMENT_SHADER_BIT); + access.set_flag(RDD::BARRIER_ACCESS_SHADER_READ_BIT).set_flag(RDD::BARRIER_ACCESS_SHADER_WRITE_BIT); } if (p_post_barrier.has_flag(BARRIER_MASK_TRANSFER)) { - barrier_flags |= VK_PIPELINE_STAGE_TRANSFER_BIT; - access_flags |= VK_ACCESS_TRANSFER_WRITE_BIT; + stages.set_flag(RDD::PIPELINE_STAGE_TRANSFER_BIT); + access.set_flag(RDD::BARRIER_ACCESS_TRANSFER_WRITE_BIT); } - if (barrier_flags == 0) { - barrier_flags = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; + if (stages.is_empty()) { + stages.set_flag(RDD::PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT); } - VkImageMemoryBarrier image_memory_barrier; - image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; - image_memory_barrier.pNext = nullptr; - image_memory_barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - image_memory_barrier.dstAccessMask = access_flags; - image_memory_barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; - image_memory_barrier.newLayout = texture->layout; - image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - image_memory_barrier.image = texture->image; - image_memory_barrier.subresourceRange.aspectMask = texture->barrier_aspect_mask; - image_memory_barrier.subresourceRange.baseMipLevel = 0; - image_memory_barrier.subresourceRange.levelCount = texture->mipmaps; - image_memory_barrier.subresourceRange.baseArrayLayer = p_layer; - image_memory_barrier.subresourceRange.layerCount = 1; + RDD::TextureBarrier tb; + tb.texture = texture->driver_id; + tb.src_access = RDD::BARRIER_ACCESS_TRANSFER_WRITE_BIT; + tb.dst_access = access; + tb.prev_layout = RDD::TEXTURE_LAYOUT_TRANSFER_DST_OPTIMAL; + tb.next_layout = texture->layout; + tb.subresources.aspect = texture->barrier_aspect_flags; + tb.subresources.mipmap_count = texture->mipmaps; + tb.subresources.base_layer = p_layer; + tb.subresources.layer_count = 1; - vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, barrier_flags, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier); + driver->command_pipeline_barrier(command_buffer, RDD::PIPELINE_STAGE_TRANSFER_BIT, stages, {}, {}, tb); } if (texture->used_in_frame != frames_drawn) { @@ -2686,15 +1342,15 @@ Error RenderingDeviceVulkan::_texture_update(RID p_texture, uint32_t p_layer, co return OK; } -Vector RenderingDeviceVulkan::_texture_get_data_from_image(Texture *tex, VkImage p_image, VmaAllocation p_allocation, uint32_t p_layer, bool p_2d) { +Vector RenderingDevice::_texture_get_data(Texture *tex, uint32_t p_layer, bool p_2d) { uint32_t width, height, depth; uint32_t image_size = get_image_format_required_size(tex->format, tex->width, tex->height, p_2d ? 1 : tex->depth, tex->mipmaps, &width, &height, &depth); Vector image_data; image_data.resize(image_size); - void *img_mem; - vmaMapMemory(allocator, p_allocation, &img_mem); + uint8_t *img_mem = driver->texture_map(tex->driver_id); + ERR_FAIL_NULL_V(img_mem, Vector()); uint32_t blockw, blockh; get_compressed_image_format_block_dimensions(tex->format, blockw, blockh); @@ -2711,22 +1367,22 @@ Vector RenderingDeviceVulkan::_texture_get_data_from_image(Texture *tex uint8_t *write_ptr_mipmap = w + mipmap_offset; image_size = image_total - mipmap_offset; - VkImageSubresource image_sub_resorce; - image_sub_resorce.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - image_sub_resorce.arrayLayer = p_layer; - image_sub_resorce.mipLevel = mm_i; - VkSubresourceLayout layout; - vkGetImageSubresourceLayout(device, p_image, &image_sub_resorce, &layout); + RDD::TextureSubresource subres; + subres.aspect.set_flag(RDD::TEXTURE_ASPECT_COLOR_BIT); + subres.layer = p_layer; + subres.mipmap = mm_i; + RDD::TextureSubresourceLayout layout; + driver->texture_get_subresource_layout(tex->driver_id, subres, &layout); for (uint32_t z = 0; z < depth; z++) { uint8_t *write_ptr = write_ptr_mipmap + z * image_size / depth; - const uint8_t *slice_read_ptr = ((uint8_t *)img_mem) + layout.offset + z * layout.depthPitch; + const uint8_t *slice_read_ptr = img_mem + layout.offset + z * layout.depth_pitch; if (block_size > 1) { // Compressed. uint32_t line_width = (block_size * (width / blockw)); for (uint32_t y = 0; y < height / blockh; y++) { - const uint8_t *rptr = slice_read_ptr + y * layout.rowPitch; + const uint8_t *rptr = slice_read_ptr + y * layout.row_pitch; uint8_t *wptr = write_ptr + y * line_width; memcpy(wptr, rptr, line_width); @@ -2735,7 +1391,7 @@ Vector RenderingDeviceVulkan::_texture_get_data_from_image(Texture *tex } else { // Uncompressed. for (uint32_t y = 0; y < height; y++) { - const uint8_t *rptr = slice_read_ptr + y * layout.rowPitch; + const uint8_t *rptr = slice_read_ptr + y * layout.row_pitch; uint8_t *wptr = write_ptr + y * pixel_size * width; memcpy(wptr, rptr, (uint64_t)pixel_size * width); } @@ -2746,16 +1402,16 @@ Vector RenderingDeviceVulkan::_texture_get_data_from_image(Texture *tex } } - vmaUnmapMemory(allocator, p_allocation); + driver->texture_unmap(tex->driver_id); return image_data; } -Vector RenderingDeviceVulkan::texture_get_data(RID p_texture, uint32_t p_layer) { +Vector RenderingDevice::texture_get_data(RID p_texture, uint32_t p_layer) { _THREAD_SAFE_METHOD_ Texture *tex = texture_owner.get_or_null(p_texture); - ERR_FAIL_NULL_V(tex, Vector()); + ERR_FAIL_COND_V(!tex, Vector()); ERR_FAIL_COND_V_MSG(tex->bound, Vector(), "Texture can't be retrieved while a draw list that uses it as part of a framebuffer is being created. Ensure the draw list is finalized (and that the color/depth texture using it is not set to `RenderingDevice.FINAL_ACTION_CONTINUE`) to retrieve this texture."); @@ -2770,36 +1426,29 @@ Vector RenderingDeviceVulkan::texture_get_data(RID p_texture, uint32_t if (tex->usage_flags & TEXTURE_USAGE_CPU_READ_BIT) { // Does not need anything fancy, map and read. - return _texture_get_data_from_image(tex, tex->image, tex->allocation, p_layer); + return _texture_get_data(tex, p_layer); } else { // Compute total image size. uint32_t width, height, depth; uint32_t buffer_size = get_image_format_required_size(tex->format, tex->width, tex->height, tex->depth, tex->mipmaps, &width, &height, &depth); // Allocate buffer. - VkCommandBuffer command_buffer = frames[frame].draw_command_buffer; // Makes more sense to retrieve. - Buffer tmp_buffer; - _buffer_allocate(&tmp_buffer, buffer_size, VK_BUFFER_USAGE_TRANSFER_DST_BIT, VMA_MEMORY_USAGE_AUTO_PREFER_HOST, VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT); + RDD::CommandBufferID command_buffer = frames[frame].draw_command_buffer; // Makes more sense to retrieve. + RDD::BufferID tmp_buffer = driver->buffer_create(buffer_size, RDD::BUFFER_USAGE_TRANSFER_TO_BIT, RDD::MEMORY_ALLOCATION_TYPE_CPU); + ERR_FAIL_COND_V(!tmp_buffer, Vector()); { // Source image barrier. - VkImageMemoryBarrier image_memory_barrier; - image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; - image_memory_barrier.pNext = nullptr; - image_memory_barrier.srcAccessMask = 0; - image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; - image_memory_barrier.oldLayout = tex->layout; - image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; - - image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - image_memory_barrier.image = tex->image; - image_memory_barrier.subresourceRange.aspectMask = tex->barrier_aspect_mask; - image_memory_barrier.subresourceRange.baseMipLevel = 0; - image_memory_barrier.subresourceRange.levelCount = tex->mipmaps; - image_memory_barrier.subresourceRange.baseArrayLayer = p_layer; - image_memory_barrier.subresourceRange.layerCount = 1; - - vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier); + RDD::TextureBarrier tb; + tb.texture = tex->driver_id; + tb.dst_access = RDD::BARRIER_ACCESS_TRANSFER_READ_BIT; + tb.prev_layout = tex->layout; + tb.next_layout = RDD::TEXTURE_LAYOUT_TRANSFER_SRC_OPTIMAL; + tb.subresources.aspect = tex->barrier_aspect_flags; + tb.subresources.mipmap_count = tex->mipmaps; + tb.subresources.base_layer = p_layer; + tb.subresources.layer_count = 1; + + driver->command_pipeline_barrier(command_buffer, RDD::PIPELINE_STAGE_TOP_OF_PIPE_BIT, RDD::PIPELINE_STAGE_TRANSFER_BIT, {}, {}, tb); } uint32_t computed_w = tex->width; @@ -2809,27 +1458,20 @@ Vector RenderingDeviceVulkan::texture_get_data(RID p_texture, uint32_t uint32_t prev_size = 0; uint32_t offset = 0; for (uint32_t i = 0; i < tex->mipmaps; i++) { - VkBufferImageCopy buffer_image_copy; - uint32_t image_size = get_image_format_required_size(tex->format, tex->width, tex->height, tex->depth, i + 1); uint32_t size = image_size - prev_size; prev_size = image_size; - buffer_image_copy.bufferOffset = offset; - buffer_image_copy.bufferImageHeight = 0; - buffer_image_copy.bufferRowLength = 0; - buffer_image_copy.imageSubresource.aspectMask = tex->read_aspect_mask; - buffer_image_copy.imageSubresource.baseArrayLayer = p_layer; - buffer_image_copy.imageSubresource.layerCount = 1; - buffer_image_copy.imageSubresource.mipLevel = i; - buffer_image_copy.imageOffset.x = 0; - buffer_image_copy.imageOffset.y = 0; - buffer_image_copy.imageOffset.z = 0; - buffer_image_copy.imageExtent.width = computed_w; - buffer_image_copy.imageExtent.height = computed_h; - buffer_image_copy.imageExtent.depth = computed_d; - - vkCmdCopyImageToBuffer(command_buffer, tex->image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, tmp_buffer.buffer, 1, &buffer_image_copy); + RDD::BufferTextureCopyRegion copy_region; + copy_region.buffer_offset = offset; + copy_region.texture_subresources.aspect = tex->read_aspect_flags; + copy_region.texture_subresources.mipmap = i; + copy_region.texture_subresources.base_layer = p_layer; + copy_region.texture_subresources.layer_count = 1; + copy_region.texture_region_size.x = computed_w; + copy_region.texture_region_size.y = computed_h; + copy_region.texture_region_size.z = computed_d; + driver->command_copy_texture_to_buffer(command_buffer, tex->driver_id, RDD::TEXTURE_LAYOUT_TRANSFER_SRC_OPTIMAL, tmp_buffer, copy_region); computed_w = MAX(1u, computed_w >> 1); computed_h = MAX(1u, computed_h >> 1); @@ -2838,33 +1480,27 @@ Vector RenderingDeviceVulkan::texture_get_data(RID p_texture, uint32_t } { // Restore src. - VkImageMemoryBarrier image_memory_barrier; - image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; - image_memory_barrier.pNext = nullptr; - image_memory_barrier.srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT; - image_memory_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; - if (tex->usage_flags & TEXTURE_USAGE_STORAGE_BIT) { - image_memory_barrier.dstAccessMask |= VK_ACCESS_SHADER_WRITE_BIT; + RDD::TextureBarrier tb; + tb.texture = tex->driver_id; + tb.src_access = RDD::BARRIER_ACCESS_TRANSFER_READ_BIT; + tb.dst_access = RDD::BARRIER_ACCESS_SHADER_READ_BIT; + if ((tex->usage_flags & TEXTURE_USAGE_STORAGE_BIT)) { + tb.dst_access.set_flag(RDD::BARRIER_ACCESS_SHADER_WRITE_BIT); } - image_memory_barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; - image_memory_barrier.newLayout = tex->layout; - image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - image_memory_barrier.image = tex->image; - image_memory_barrier.subresourceRange.aspectMask = tex->barrier_aspect_mask; - image_memory_barrier.subresourceRange.baseMipLevel = 0; - image_memory_barrier.subresourceRange.levelCount = tex->mipmaps; - image_memory_barrier.subresourceRange.baseArrayLayer = p_layer; - image_memory_barrier.subresourceRange.layerCount = 1; + tb.prev_layout = RDD::TEXTURE_LAYOUT_TRANSFER_SRC_OPTIMAL; + tb.next_layout = tex->layout; + tb.subresources.aspect = tex->barrier_aspect_flags; + tb.subresources.mipmap_count = tex->mipmaps; + tb.subresources.base_layer = p_layer; + tb.subresources.layer_count = 1; - vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier); + driver->command_pipeline_barrier(command_buffer, RDD::PIPELINE_STAGE_TRANSFER_BIT, RDD::PIPELINE_STAGE_VERTEX_SHADER_BIT | RDD::PIPELINE_STAGE_FRAGMENT_SHADER_BIT | RDD::PIPELINE_STAGE_COMPUTE_SHADER_BIT, {}, {}, tb); } _flush(true); - void *buffer_mem; - VkResult vkerr = vmaMapMemory(allocator, tmp_buffer.allocation, &buffer_mem); - ERR_FAIL_COND_V_MSG(vkerr, Vector(), "vmaMapMemory failed with error " + itos(vkerr) + "."); + uint8_t *buffer_mem = driver->buffer_map(tmp_buffer); + ERR_FAIL_NULL_V(buffer_mem, Vector()); Vector buffer_data; { @@ -2873,31 +1509,31 @@ Vector RenderingDeviceVulkan::texture_get_data(RID p_texture, uint32_t memcpy(w, buffer_mem, buffer_size); } - vmaUnmapMemory(allocator, tmp_buffer.allocation); + driver->buffer_unmap(tmp_buffer); - _buffer_free(&tmp_buffer); + driver->buffer_free(tmp_buffer); return buffer_data; } } -bool RenderingDeviceVulkan::texture_is_shared(RID p_texture) { +bool RenderingDevice::texture_is_shared(RID p_texture) { _THREAD_SAFE_METHOD_ Texture *tex = texture_owner.get_or_null(p_texture); - ERR_FAIL_NULL_V(tex, false); + ERR_FAIL_COND_V(!tex, false); return tex->owner.is_valid(); } -bool RenderingDeviceVulkan::texture_is_valid(RID p_texture) { +bool RenderingDevice::texture_is_valid(RID p_texture) { return texture_owner.owns(p_texture); } -RD::TextureFormat RenderingDeviceVulkan::texture_get_format(RID p_texture) { +RD::TextureFormat RenderingDevice::texture_get_format(RID p_texture) { _THREAD_SAFE_METHOD_ Texture *tex = texture_owner.get_or_null(p_texture); - ERR_FAIL_NULL_V(tex, TextureFormat()); + ERR_FAIL_COND_V(!tex, TextureFormat()); TextureFormat tf; @@ -2916,24 +1552,21 @@ RD::TextureFormat RenderingDeviceVulkan::texture_get_format(RID p_texture) { return tf; } -Size2i RenderingDeviceVulkan::texture_size(RID p_texture) { +Size2i RenderingDevice::texture_size(RID p_texture) { _THREAD_SAFE_METHOD_ Texture *tex = texture_owner.get_or_null(p_texture); - ERR_FAIL_NULL_V(tex, Size2i()); + ERR_FAIL_COND_V(!tex, Size2i()); return Size2i(tex->width, tex->height); } -uint64_t RenderingDeviceVulkan::texture_get_native_handle(RID p_texture) { - _THREAD_SAFE_METHOD_ - - Texture *tex = texture_owner.get_or_null(p_texture); - ERR_FAIL_NULL_V(tex, 0); - - return (uint64_t)tex->image; +#ifndef DISABLE_DEPRECATED +uint64_t RenderingDevice::texture_get_native_handle(RID p_texture) { + return get_driver_resource(DRIVER_RESOURCE_TEXTURE, p_texture); } +#endif -Error RenderingDeviceVulkan::texture_copy(RID p_from_texture, RID p_to_texture, const Vector3 &p_from, const Vector3 &p_to, const Vector3 &p_size, uint32_t p_src_mipmap, uint32_t p_dst_mipmap, uint32_t p_src_layer, uint32_t p_dst_layer, BitField p_post_barrier) { +Error RenderingDevice::texture_copy(RID p_from_texture, RID p_to_texture, const Vector3 &p_from, const Vector3 &p_to, const Vector3 &p_size, uint32_t p_src_mipmap, uint32_t p_dst_mipmap, uint32_t p_src_layer, uint32_t p_dst_layer, BitField p_post_barrier) { _THREAD_SAFE_METHOD_ Texture *src_tex = texture_owner.get_or_null(p_from_texture); @@ -2978,147 +1611,120 @@ Error RenderingDeviceVulkan::texture_copy(RID p_from_texture, RID p_to_texture, ERR_FAIL_COND_V(p_dst_mipmap >= dst_tex->mipmaps, ERR_INVALID_PARAMETER); ERR_FAIL_COND_V(p_dst_layer >= dst_layer_count, ERR_INVALID_PARAMETER); - ERR_FAIL_COND_V_MSG(src_tex->read_aspect_mask != dst_tex->read_aspect_mask, ERR_INVALID_PARAMETER, + ERR_FAIL_COND_V_MSG(src_tex->read_aspect_flags != dst_tex->read_aspect_flags, ERR_INVALID_PARAMETER, "Source and destination texture must be of the same type (color or depth)."); - VkCommandBuffer command_buffer = frames[frame].draw_command_buffer; + RDD::CommandBufferID command_buffer = frames[frame].draw_command_buffer; { // PRE Copy the image. { // Source. - VkImageMemoryBarrier image_memory_barrier; - image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; - image_memory_barrier.pNext = nullptr; - image_memory_barrier.srcAccessMask = 0; - image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; - image_memory_barrier.oldLayout = src_tex->layout; - image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; - - image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - image_memory_barrier.image = src_tex->image; - image_memory_barrier.subresourceRange.aspectMask = src_tex->barrier_aspect_mask; - image_memory_barrier.subresourceRange.baseMipLevel = p_src_mipmap; - image_memory_barrier.subresourceRange.levelCount = 1; - image_memory_barrier.subresourceRange.baseArrayLayer = p_src_layer; - image_memory_barrier.subresourceRange.layerCount = 1; - - vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier); + RDD::TextureBarrier tb; + tb.texture = src_tex->driver_id; + tb.dst_access = RDD::BARRIER_ACCESS_TRANSFER_READ_BIT; + tb.prev_layout = src_tex->layout; + tb.next_layout = RDD::TEXTURE_LAYOUT_TRANSFER_SRC_OPTIMAL; + tb.subresources.aspect = src_tex->barrier_aspect_flags; + tb.subresources.base_mipmap = p_src_mipmap; + tb.subresources.mipmap_count = 1; + tb.subresources.base_layer = p_src_layer; + tb.subresources.layer_count = 1; + + driver->command_pipeline_barrier(command_buffer, RDD::PIPELINE_STAGE_TOP_OF_PIPE_BIT, RDD::PIPELINE_STAGE_TRANSFER_BIT, {}, {}, tb); } { // Dest. - VkImageMemoryBarrier image_memory_barrier; - image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; - image_memory_barrier.pNext = nullptr; - image_memory_barrier.srcAccessMask = 0; - image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - image_memory_barrier.oldLayout = dst_tex->layout; - image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; - - image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - image_memory_barrier.image = dst_tex->image; - image_memory_barrier.subresourceRange.aspectMask = dst_tex->read_aspect_mask; - image_memory_barrier.subresourceRange.baseMipLevel = p_dst_mipmap; - image_memory_barrier.subresourceRange.levelCount = 1; - image_memory_barrier.subresourceRange.baseArrayLayer = p_dst_layer; - image_memory_barrier.subresourceRange.layerCount = 1; - - vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier); + RDD::TextureBarrier tb; + tb.texture = dst_tex->driver_id; + tb.dst_access = RDD::BARRIER_ACCESS_TRANSFER_WRITE_BIT; + tb.prev_layout = dst_tex->layout; + tb.next_layout = RDD::TEXTURE_LAYOUT_TRANSFER_DST_OPTIMAL; + tb.subresources.aspect = dst_tex->read_aspect_flags; + tb.subresources.base_mipmap = p_dst_mipmap; + tb.subresources.mipmap_count = 1; + tb.subresources.base_layer = p_dst_layer; + tb.subresources.layer_count = 1; + + driver->command_pipeline_barrier(command_buffer, RDD::PIPELINE_STAGE_TOP_OF_PIPE_BIT, RDD::PIPELINE_STAGE_TRANSFER_BIT, {}, {}, tb); } // COPY. { - VkImageCopy image_copy_region; - image_copy_region.srcSubresource.aspectMask = src_tex->read_aspect_mask; - image_copy_region.srcSubresource.baseArrayLayer = p_src_layer; - image_copy_region.srcSubresource.layerCount = 1; - image_copy_region.srcSubresource.mipLevel = p_src_mipmap; - image_copy_region.srcOffset.x = p_from.x; - image_copy_region.srcOffset.y = p_from.y; - image_copy_region.srcOffset.z = p_from.z; - - image_copy_region.dstSubresource.aspectMask = dst_tex->read_aspect_mask; - image_copy_region.dstSubresource.baseArrayLayer = p_dst_layer; - image_copy_region.dstSubresource.layerCount = 1; - image_copy_region.dstSubresource.mipLevel = p_dst_mipmap; - image_copy_region.dstOffset.x = p_to.x; - image_copy_region.dstOffset.y = p_to.y; - image_copy_region.dstOffset.z = p_to.z; - - image_copy_region.extent.width = p_size.x; - image_copy_region.extent.height = p_size.y; - image_copy_region.extent.depth = p_size.z; - - vkCmdCopyImage(command_buffer, src_tex->image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, dst_tex->image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &image_copy_region); + RDD::TextureCopyRegion copy_region; + copy_region.src_subresources.aspect = src_tex->read_aspect_flags; + copy_region.src_subresources.mipmap = p_src_mipmap; + copy_region.src_subresources.base_layer = p_src_layer; + copy_region.src_subresources.layer_count = 1; + copy_region.src_offset = p_from; + + copy_region.dst_subresources.aspect = dst_tex->read_aspect_flags; + copy_region.dst_subresources.mipmap = p_dst_mipmap; + copy_region.dst_subresources.base_layer = p_dst_layer; + copy_region.dst_subresources.layer_count = 1; + copy_region.dst_offset = p_to; + + copy_region.size = p_size; + + driver->command_copy_texture(command_buffer, src_tex->driver_id, RDD::TEXTURE_LAYOUT_TRANSFER_SRC_OPTIMAL, dst_tex->driver_id, RDD::TEXTURE_LAYOUT_TRANSFER_DST_OPTIMAL, copy_region); } // RESTORE LAYOUT for SRC and DST. - uint32_t barrier_flags = 0; - uint32_t access_flags = 0; + BitField stages; + BitField access; if (p_post_barrier.has_flag(BARRIER_MASK_COMPUTE)) { - barrier_flags |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT; - access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; + stages.set_flag(RDD::PIPELINE_STAGE_COMPUTE_SHADER_BIT); + access.set_flag(RDD::BARRIER_ACCESS_SHADER_READ_BIT).set_flag(RDD::BARRIER_ACCESS_SHADER_WRITE_BIT); } if (p_post_barrier.has_flag(BARRIER_MASK_VERTEX)) { - barrier_flags |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT; - access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; + stages.set_flag(RDD::PIPELINE_STAGE_VERTEX_SHADER_BIT); + access.set_flag(RDD::BARRIER_ACCESS_SHADER_READ_BIT).set_flag(RDD::BARRIER_ACCESS_SHADER_WRITE_BIT); } if (p_post_barrier.has_flag(BARRIER_MASK_FRAGMENT)) { - barrier_flags |= VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT; - access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; + stages.set_flag(RDD::PIPELINE_STAGE_FRAGMENT_SHADER_BIT); + access.set_flag(RDD::BARRIER_ACCESS_SHADER_READ_BIT).set_flag(RDD::BARRIER_ACCESS_SHADER_WRITE_BIT); } if (p_post_barrier.has_flag(BARRIER_MASK_TRANSFER)) { - barrier_flags |= VK_PIPELINE_STAGE_TRANSFER_BIT; - access_flags |= VK_ACCESS_TRANSFER_WRITE_BIT; + stages.set_flag(RDD::PIPELINE_STAGE_TRANSFER_BIT); + access.set_flag(RDD::BARRIER_ACCESS_TRANSFER_WRITE_BIT); } - if (barrier_flags == 0) { - barrier_flags = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; + if (stages.is_empty()) { + stages.set_flag(RDD::PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT); } { // Restore src. - VkImageMemoryBarrier image_memory_barrier; - image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; - image_memory_barrier.pNext = nullptr; - image_memory_barrier.srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT; - image_memory_barrier.dstAccessMask = access_flags; - image_memory_barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; - image_memory_barrier.newLayout = src_tex->layout; - image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - image_memory_barrier.image = src_tex->image; - image_memory_barrier.subresourceRange.aspectMask = src_tex->barrier_aspect_mask; - image_memory_barrier.subresourceRange.baseMipLevel = p_src_mipmap; - image_memory_barrier.subresourceRange.levelCount = src_tex->mipmaps; - image_memory_barrier.subresourceRange.baseArrayLayer = p_src_layer; - image_memory_barrier.subresourceRange.layerCount = 1; - - vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, barrier_flags, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier); + RDD::TextureBarrier tb; + tb.texture = src_tex->driver_id; + tb.src_access = RDD::BARRIER_ACCESS_TRANSFER_READ_BIT; + tb.dst_access = access; + tb.prev_layout = RDD::TEXTURE_LAYOUT_TRANSFER_SRC_OPTIMAL; + tb.next_layout = src_tex->layout; + tb.subresources.aspect = src_tex->barrier_aspect_flags; + tb.subresources.base_mipmap = p_src_mipmap; + tb.subresources.mipmap_count = 1; + tb.subresources.base_layer = p_src_layer; + tb.subresources.layer_count = 1; + + driver->command_pipeline_barrier(command_buffer, RDD::PIPELINE_STAGE_TRANSFER_BIT, stages, {}, {}, tb); } { // Make dst readable. - VkImageMemoryBarrier image_memory_barrier; - image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; - image_memory_barrier.pNext = nullptr; - image_memory_barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - image_memory_barrier.dstAccessMask = access_flags; - image_memory_barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; - image_memory_barrier.newLayout = dst_tex->layout; + RDD::TextureBarrier tb; + tb.texture = dst_tex->driver_id; + tb.src_access = RDD::BARRIER_ACCESS_TRANSFER_WRITE_BIT; + tb.dst_access = access; + tb.prev_layout = RDD::TEXTURE_LAYOUT_TRANSFER_DST_OPTIMAL; + tb.next_layout = dst_tex->layout; + tb.subresources.aspect = dst_tex->read_aspect_flags; + tb.subresources.base_mipmap = p_dst_mipmap; + tb.subresources.mipmap_count = 1; + tb.subresources.base_layer = p_dst_layer; + tb.subresources.layer_count = 1; - image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - image_memory_barrier.image = dst_tex->image; - image_memory_barrier.subresourceRange.aspectMask = dst_tex->read_aspect_mask; - image_memory_barrier.subresourceRange.baseMipLevel = p_src_mipmap; - image_memory_barrier.subresourceRange.levelCount = 1; - image_memory_barrier.subresourceRange.baseArrayLayer = p_src_layer; - image_memory_barrier.subresourceRange.layerCount = 1; - - vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, barrier_flags, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier); + driver->command_pipeline_barrier(command_buffer, RDD::PIPELINE_STAGE_TRANSFER_BIT, stages, {}, {}, tb); } } @@ -3132,7 +1738,7 @@ Error RenderingDeviceVulkan::texture_copy(RID p_from_texture, RID p_to_texture, return OK; } -Error RenderingDeviceVulkan::texture_resolve_multisample(RID p_from_texture, RID p_to_texture, BitField p_post_barrier) { +Error RenderingDevice::texture_resolve_multisample(RID p_from_texture, RID p_to_texture, BitField p_post_barrier) { _THREAD_SAFE_METHOD_ Texture *src_tex = texture_owner.get_or_null(p_from_texture); @@ -3160,154 +1766,127 @@ Error RenderingDeviceVulkan::texture_resolve_multisample(RID p_from_texture, RID ERR_FAIL_COND_V_MSG(src_tex->format != dst_tex->format, ERR_INVALID_PARAMETER, "Source and Destination textures must be the same format."); ERR_FAIL_COND_V_MSG(src_tex->width != dst_tex->width && src_tex->height != dst_tex->height && src_tex->depth != dst_tex->depth, ERR_INVALID_PARAMETER, "Source and Destination textures must have the same dimensions."); - ERR_FAIL_COND_V_MSG(src_tex->read_aspect_mask != dst_tex->read_aspect_mask, ERR_INVALID_PARAMETER, + ERR_FAIL_COND_V_MSG(src_tex->read_aspect_flags != dst_tex->read_aspect_flags, ERR_INVALID_PARAMETER, "Source and destination texture must be of the same type (color or depth)."); - VkCommandBuffer command_buffer = frames[frame].draw_command_buffer; + RDD::CommandBufferID command_buffer = frames[frame].draw_command_buffer; { // PRE Copy the image. { // Source. - VkImageMemoryBarrier image_memory_barrier; - image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; - image_memory_barrier.pNext = nullptr; - image_memory_barrier.srcAccessMask = 0; - image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; - image_memory_barrier.oldLayout = src_tex->layout; - image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; - - image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - image_memory_barrier.image = src_tex->image; - image_memory_barrier.subresourceRange.aspectMask = src_tex->barrier_aspect_mask; - image_memory_barrier.subresourceRange.baseMipLevel = src_tex->base_mipmap; - image_memory_barrier.subresourceRange.levelCount = 1; - image_memory_barrier.subresourceRange.baseArrayLayer = src_tex->base_layer; - image_memory_barrier.subresourceRange.layerCount = 1; - - vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier); + RDD::TextureBarrier tb; + tb.texture = src_tex->driver_id; + tb.dst_access = RDD::BARRIER_ACCESS_TRANSFER_READ_BIT; + tb.prev_layout = src_tex->layout; + tb.next_layout = RDD::TEXTURE_LAYOUT_TRANSFER_SRC_OPTIMAL; + tb.subresources.aspect = src_tex->barrier_aspect_flags; + tb.subresources.base_mipmap = src_tex->base_mipmap; + tb.subresources.mipmap_count = 1; + tb.subresources.base_layer = src_tex->base_layer; + tb.subresources.layer_count = 1; + + driver->command_pipeline_barrier(command_buffer, RDD::PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, RDD::PIPELINE_STAGE_TRANSFER_BIT, {}, {}, tb); } { // Dest. - VkImageMemoryBarrier image_memory_barrier; - image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; - image_memory_barrier.pNext = nullptr; - image_memory_barrier.srcAccessMask = 0; - image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - image_memory_barrier.oldLayout = dst_tex->layout; - image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; - - image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - image_memory_barrier.image = dst_tex->image; - image_memory_barrier.subresourceRange.aspectMask = dst_tex->read_aspect_mask; - image_memory_barrier.subresourceRange.baseMipLevel = dst_tex->base_mipmap; - image_memory_barrier.subresourceRange.levelCount = 1; - image_memory_barrier.subresourceRange.baseArrayLayer = dst_tex->base_layer; - image_memory_barrier.subresourceRange.layerCount = 1; - - vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier); + RDD::TextureBarrier tb; + tb.texture = dst_tex->driver_id; + tb.dst_access = RDD::BARRIER_ACCESS_TRANSFER_WRITE_BIT; + tb.prev_layout = dst_tex->layout; + tb.next_layout = RDD::TEXTURE_LAYOUT_TRANSFER_DST_OPTIMAL; + tb.subresources.aspect = dst_tex->barrier_aspect_flags; + tb.subresources.base_mipmap = dst_tex->base_mipmap; + tb.subresources.mipmap_count = 1; + tb.subresources.base_layer = dst_tex->base_layer; + tb.subresources.layer_count = 1; + + driver->command_pipeline_barrier(command_buffer, RDD::PIPELINE_STAGE_TOP_OF_PIPE_BIT, RDD::PIPELINE_STAGE_TRANSFER_BIT, {}, {}, tb); } // COPY. { - VkImageResolve image_copy_region; - image_copy_region.srcSubresource.aspectMask = src_tex->read_aspect_mask; - image_copy_region.srcSubresource.baseArrayLayer = src_tex->base_layer; - image_copy_region.srcSubresource.layerCount = 1; - image_copy_region.srcSubresource.mipLevel = src_tex->base_mipmap; - image_copy_region.srcOffset.x = 0; - image_copy_region.srcOffset.y = 0; - image_copy_region.srcOffset.z = 0; - - image_copy_region.dstSubresource.aspectMask = dst_tex->read_aspect_mask; - image_copy_region.dstSubresource.baseArrayLayer = dst_tex->base_layer; - image_copy_region.dstSubresource.layerCount = 1; - image_copy_region.dstSubresource.mipLevel = dst_tex->base_mipmap; - image_copy_region.dstOffset.x = 0; - image_copy_region.dstOffset.y = 0; - image_copy_region.dstOffset.z = 0; - - image_copy_region.extent.width = src_tex->width; - image_copy_region.extent.height = src_tex->height; - image_copy_region.extent.depth = src_tex->depth; - - vkCmdResolveImage(command_buffer, src_tex->image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, dst_tex->image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &image_copy_region); + RDD::TextureCopyRegion copy_region; + copy_region.src_subresources.aspect = src_tex->read_aspect_flags; + copy_region.src_subresources.mipmap = src_tex->base_mipmap; + copy_region.src_subresources.base_layer = src_tex->base_layer; + copy_region.src_subresources.layer_count = 1; + + copy_region.dst_subresources.aspect = dst_tex->read_aspect_flags; + copy_region.dst_subresources.mipmap = dst_tex->base_mipmap; + copy_region.dst_subresources.base_layer = dst_tex->base_layer; + copy_region.dst_subresources.layer_count = 1; + + copy_region.size.x = src_tex->width; + copy_region.size.y = src_tex->height; + copy_region.size.z = src_tex->depth; + + driver->command_resolve_texture(command_buffer, src_tex->driver_id, RDD::TEXTURE_LAYOUT_TRANSFER_SRC_OPTIMAL, dst_tex->driver_id, RDD::TEXTURE_LAYOUT_TRANSFER_DST_OPTIMAL, copy_region); } // RESTORE LAYOUT for SRC and DST. - uint32_t barrier_flags = 0; - uint32_t access_flags = 0; + BitField stages; + BitField access; if (p_post_barrier.has_flag(BARRIER_MASK_COMPUTE)) { - barrier_flags |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT; - access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; + stages.set_flag(RDD::PIPELINE_STAGE_COMPUTE_SHADER_BIT); + access.set_flag(RDD::BARRIER_ACCESS_SHADER_READ_BIT).set_flag(RDD::BARRIER_ACCESS_SHADER_WRITE_BIT); } if (p_post_barrier.has_flag(BARRIER_MASK_VERTEX)) { - barrier_flags |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT; - access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; + stages.set_flag(RDD::PIPELINE_STAGE_VERTEX_SHADER_BIT); + access.set_flag(RDD::BARRIER_ACCESS_SHADER_READ_BIT).set_flag(RDD::BARRIER_ACCESS_SHADER_WRITE_BIT); } if (p_post_barrier.has_flag(BARRIER_MASK_FRAGMENT)) { - barrier_flags |= VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT; - access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; + stages.set_flag(RDD::PIPELINE_STAGE_FRAGMENT_SHADER_BIT); + access.set_flag(RDD::BARRIER_ACCESS_SHADER_READ_BIT).set_flag(RDD::BARRIER_ACCESS_SHADER_WRITE_BIT); } if (p_post_barrier.has_flag(BARRIER_MASK_TRANSFER)) { - barrier_flags |= VK_PIPELINE_STAGE_TRANSFER_BIT; - access_flags |= VK_ACCESS_TRANSFER_WRITE_BIT; + stages.set_flag(RDD::PIPELINE_STAGE_TRANSFER_BIT); + access.set_flag(RDD::BARRIER_ACCESS_TRANSFER_WRITE_BIT); } - if (barrier_flags == 0) { - barrier_flags = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; + if (stages.is_empty()) { + stages.set_flag(RDD::PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT); } { // Restore src. - VkImageMemoryBarrier image_memory_barrier; - image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; - image_memory_barrier.pNext = nullptr; - image_memory_barrier.srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT; - image_memory_barrier.dstAccessMask = access_flags; - image_memory_barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; - image_memory_barrier.newLayout = src_tex->layout; - image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - image_memory_barrier.image = src_tex->image; - image_memory_barrier.subresourceRange.aspectMask = src_tex->barrier_aspect_mask; - image_memory_barrier.subresourceRange.baseMipLevel = src_tex->base_mipmap; - image_memory_barrier.subresourceRange.levelCount = 1; - image_memory_barrier.subresourceRange.baseArrayLayer = src_tex->base_layer; - image_memory_barrier.subresourceRange.layerCount = 1; - - vkCmdPipelineBarrier(command_buffer, VK_ACCESS_TRANSFER_WRITE_BIT, barrier_flags, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier); + RDD::TextureBarrier tb; + tb.texture = src_tex->driver_id; + tb.src_access = RDD::BARRIER_ACCESS_TRANSFER_READ_BIT; + tb.dst_access = access; + tb.prev_layout = RDD::TEXTURE_LAYOUT_TRANSFER_SRC_OPTIMAL; + tb.next_layout = src_tex->layout; + tb.subresources.aspect = src_tex->barrier_aspect_flags; + tb.subresources.base_mipmap = src_tex->base_mipmap; + tb.subresources.mipmap_count = 1; + tb.subresources.base_layer = src_tex->base_layer; + tb.subresources.layer_count = 1; + + driver->command_pipeline_barrier(command_buffer, RDD::BARRIER_ACCESS_TRANSFER_WRITE_BIT, stages, {}, {}, tb); } { // Make dst readable. - VkImageMemoryBarrier image_memory_barrier; - image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; - image_memory_barrier.pNext = nullptr; - image_memory_barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - image_memory_barrier.dstAccessMask = access_flags; - image_memory_barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; - image_memory_barrier.newLayout = dst_tex->layout; + RDD::TextureBarrier tb; + tb.texture = dst_tex->driver_id; + tb.src_access = RDD::BARRIER_ACCESS_TRANSFER_WRITE_BIT; + tb.dst_access = access; + tb.prev_layout = RDD::TEXTURE_LAYOUT_TRANSFER_DST_OPTIMAL; + tb.next_layout = dst_tex->layout; + tb.subresources.aspect = RDD::TEXTURE_ASPECT_COLOR_BIT; + tb.subresources.base_mipmap = dst_tex->base_mipmap; + tb.subresources.mipmap_count = 1; + tb.subresources.base_layer = dst_tex->base_layer; + tb.subresources.layer_count = 1; - image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - image_memory_barrier.image = dst_tex->image; - image_memory_barrier.subresourceRange.aspectMask = dst_tex->read_aspect_mask; - image_memory_barrier.subresourceRange.baseMipLevel = dst_tex->base_mipmap; - image_memory_barrier.subresourceRange.levelCount = 1; - image_memory_barrier.subresourceRange.baseArrayLayer = dst_tex->base_layer; - image_memory_barrier.subresourceRange.layerCount = 1; - - vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, barrier_flags, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier); + driver->command_pipeline_barrier(command_buffer, RDD::PIPELINE_STAGE_TRANSFER_BIT, stages, {}, {}, tb); } } return OK; } -Error RenderingDeviceVulkan::texture_clear(RID p_texture, const Color &p_color, uint32_t p_base_mipmap, uint32_t p_mipmaps, uint32_t p_base_layer, uint32_t p_layers, BitField p_post_barrier) { +Error RenderingDevice::texture_clear(RID p_texture, const Color &p_color, uint32_t p_base_mipmap, uint32_t p_mipmaps, uint32_t p_base_layer, uint32_t p_layers, BitField p_post_barrier) { _THREAD_SAFE_METHOD_ Texture *src_tex = texture_owner.get_or_null(p_texture); @@ -3330,95 +1909,79 @@ Error RenderingDeviceVulkan::texture_clear(RID p_texture, const Color &p_color, ERR_FAIL_COND_V(p_base_mipmap + p_mipmaps > src_tex->mipmaps, ERR_INVALID_PARAMETER); ERR_FAIL_COND_V(p_base_layer + p_layers > src_layer_count, ERR_INVALID_PARAMETER); - VkCommandBuffer command_buffer = frames[frame].draw_command_buffer; + RDD::CommandBufferID command_buffer = frames[frame].draw_command_buffer; - VkImageLayout clear_layout = (src_tex->layout == VK_IMAGE_LAYOUT_GENERAL) ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; + RDD::TextureLayout clear_layout = (src_tex->layout == RDD::TEXTURE_LAYOUT_GENERAL) ? RDD::TEXTURE_LAYOUT_GENERAL : RDD::TEXTURE_LAYOUT_TRANSFER_DST_OPTIMAL; // NOTE: Perhaps the valid stages/accesses for a given owner should be a property of the owner. (Here and places like _get_buffer_from_owner.) - const VkPipelineStageFlags valid_texture_stages = VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT; - constexpr VkAccessFlags read_access = VK_ACCESS_SHADER_READ_BIT; - constexpr VkAccessFlags read_write_access = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; - const VkAccessFlags valid_texture_access = (src_tex->usage_flags & TEXTURE_USAGE_STORAGE_BIT) ? read_write_access : read_access; + const BitField valid_texture_stages = RDD::PIPELINE_STAGE_VERTEX_SHADER_BIT | RDD::PIPELINE_STAGE_FRAGMENT_SHADER_BIT | RDD::PIPELINE_STAGE_COMPUTE_SHADER_BIT; + constexpr BitField read_access = RDD::BARRIER_ACCESS_SHADER_READ_BIT; + constexpr BitField read_write_access = RDD::BARRIER_ACCESS_SHADER_READ_BIT | RDD::BARRIER_ACCESS_SHADER_WRITE_BIT; + const BitField valid_texture_access = (src_tex->usage_flags & TEXTURE_USAGE_STORAGE_BIT) ? read_write_access : read_access; { // Barrier from previous access with optional layout change (see clear_layout logic above). - VkImageMemoryBarrier image_memory_barrier; - image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; - image_memory_barrier.pNext = nullptr; - image_memory_barrier.srcAccessMask = valid_texture_access; - image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - image_memory_barrier.oldLayout = src_tex->layout; - image_memory_barrier.newLayout = clear_layout; - - image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - image_memory_barrier.image = src_tex->image; - image_memory_barrier.subresourceRange.aspectMask = src_tex->read_aspect_mask; - image_memory_barrier.subresourceRange.baseMipLevel = src_tex->base_mipmap + p_base_mipmap; - image_memory_barrier.subresourceRange.levelCount = p_mipmaps; - image_memory_barrier.subresourceRange.baseArrayLayer = src_tex->base_layer + p_base_layer; - image_memory_barrier.subresourceRange.layerCount = p_layers; - - vkCmdPipelineBarrier(command_buffer, valid_texture_stages, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier); - } - - VkClearColorValue clear_color; - clear_color.float32[0] = p_color.r; - clear_color.float32[1] = p_color.g; - clear_color.float32[2] = p_color.b; - clear_color.float32[3] = p_color.a; - - VkImageSubresourceRange range; - range.aspectMask = src_tex->read_aspect_mask; - range.baseArrayLayer = src_tex->base_layer + p_base_layer; - range.layerCount = p_layers; - range.baseMipLevel = src_tex->base_mipmap + p_base_mipmap; - range.levelCount = p_mipmaps; - - vkCmdClearColorImage(command_buffer, src_tex->image, clear_layout, &clear_color, 1, &range); + RDD::TextureBarrier tb; + tb.texture = src_tex->driver_id; + tb.src_access = valid_texture_access; + tb.dst_access = RDD::BARRIER_ACCESS_TRANSFER_WRITE_BIT; + tb.prev_layout = src_tex->layout; + tb.next_layout = clear_layout; + tb.subresources.aspect = src_tex->read_aspect_flags; + tb.subresources.base_mipmap = src_tex->base_mipmap + p_base_mipmap; + tb.subresources.mipmap_count = p_mipmaps; + tb.subresources.base_layer = src_tex->base_layer + p_base_layer; + tb.subresources.layer_count = p_layers; + + driver->command_pipeline_barrier(command_buffer, valid_texture_stages, RDD::PIPELINE_STAGE_TRANSFER_BIT, {}, {}, tb); + } + + RDD::TextureSubresourceRange range; + range.aspect = src_tex->read_aspect_flags; + range.base_mipmap = src_tex->base_mipmap + p_base_mipmap; + range.mipmap_count = p_mipmaps; + range.base_layer = src_tex->base_layer + p_base_layer; + range.layer_count = p_layers; + + driver->command_clear_color_texture(command_buffer, src_tex->driver_id, clear_layout, p_color, range); { // Barrier to post clear accesses (changing back the layout if needed). - uint32_t barrier_flags = 0; - uint32_t access_flags = 0; + BitField stages; + BitField access; if (p_post_barrier.has_flag(BARRIER_MASK_COMPUTE)) { - barrier_flags |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT; - access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; + stages.set_flag(RDD::PIPELINE_STAGE_COMPUTE_SHADER_BIT); + access.set_flag(RDD::BARRIER_ACCESS_SHADER_READ_BIT).set_flag(RDD::BARRIER_ACCESS_SHADER_WRITE_BIT); } if (p_post_barrier.has_flag(BARRIER_MASK_VERTEX)) { - barrier_flags |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT; - access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; + stages.set_flag(RDD::PIPELINE_STAGE_VERTEX_SHADER_BIT); + access.set_flag(RDD::BARRIER_ACCESS_SHADER_READ_BIT).set_flag(RDD::BARRIER_ACCESS_SHADER_WRITE_BIT); } if (p_post_barrier.has_flag(BARRIER_MASK_FRAGMENT)) { - barrier_flags |= VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT; - access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; + stages.set_flag(RDD::PIPELINE_STAGE_FRAGMENT_SHADER_BIT); + access.set_flag(RDD::BARRIER_ACCESS_SHADER_READ_BIT).set_flag(RDD::BARRIER_ACCESS_SHADER_WRITE_BIT); } if (p_post_barrier.has_flag(BARRIER_MASK_TRANSFER)) { - barrier_flags |= VK_PIPELINE_STAGE_TRANSFER_BIT; - access_flags |= VK_ACCESS_TRANSFER_WRITE_BIT; + stages.set_flag(RDD::PIPELINE_STAGE_TRANSFER_BIT); + access.set_flag(RDD::BARRIER_ACCESS_TRANSFER_WRITE_BIT); } - if (barrier_flags == 0) { - barrier_flags = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; + if (stages.is_empty()) { + stages.set_flag(RDD::PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT); } - VkImageMemoryBarrier image_memory_barrier; - image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; - image_memory_barrier.pNext = nullptr; - image_memory_barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - image_memory_barrier.dstAccessMask = access_flags; - image_memory_barrier.oldLayout = clear_layout; - image_memory_barrier.newLayout = src_tex->layout; - - image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - image_memory_barrier.image = src_tex->image; - image_memory_barrier.subresourceRange.aspectMask = src_tex->read_aspect_mask; - image_memory_barrier.subresourceRange.baseMipLevel = src_tex->base_mipmap + p_base_mipmap; - image_memory_barrier.subresourceRange.levelCount = p_mipmaps; - image_memory_barrier.subresourceRange.baseArrayLayer = src_tex->base_layer + p_base_layer; - image_memory_barrier.subresourceRange.layerCount = p_layers; + RDD::TextureBarrier tb; + tb.texture = src_tex->driver_id; + tb.src_access = RDD::BARRIER_ACCESS_TRANSFER_WRITE_BIT; + tb.dst_access = access; + tb.prev_layout = clear_layout; + tb.next_layout = src_tex->layout; + tb.subresources.aspect = src_tex->read_aspect_flags; + tb.subresources.base_mipmap = src_tex->base_mipmap + p_base_mipmap; + tb.subresources.mipmap_count = p_mipmaps; + tb.subresources.base_layer = src_tex->base_layer + p_base_layer; + tb.subresources.layer_count = p_layers; - vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, barrier_flags, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier); + driver->command_pipeline_barrier(command_buffer, RDD::PIPELINE_STAGE_TRANSFER_BIT, stages, {}, {}, tb); } if (src_tex->used_in_frame != frames_drawn) { @@ -3431,122 +1994,72 @@ Error RenderingDeviceVulkan::texture_clear(RID p_texture, const Color &p_color, return OK; } -bool RenderingDeviceVulkan::texture_is_format_supported_for_usage(DataFormat p_format, BitField p_usage) const { +bool RenderingDevice::texture_is_format_supported_for_usage(DataFormat p_format, BitField p_usage) const { ERR_FAIL_INDEX_V(p_format, DATA_FORMAT_MAX, false); _THREAD_SAFE_METHOD_ - // Validate that this image is supported for the intended use. - VkFormatProperties properties; - vkGetPhysicalDeviceFormatProperties(context->get_physical_device(), vulkan_formats[p_format], &properties); - VkFormatFeatureFlags flags; - - if (p_usage.has_flag(TEXTURE_USAGE_CPU_READ_BIT)) { - flags = properties.linearTilingFeatures; - } else { - flags = properties.optimalTilingFeatures; - } - - if (p_usage.has_flag(TEXTURE_USAGE_SAMPLING_BIT) && !(flags & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT)) { - return false; - } - - if (p_usage.has_flag(TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) && !(flags & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT)) { - return false; - } - - if (p_usage.has_flag(TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) && !(flags & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT)) { - return false; - } - - if (p_usage.has_flag(TEXTURE_USAGE_STORAGE_BIT) && !(flags & VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT)) { - return false; - } - - if (p_usage.has_flag(TEXTURE_USAGE_STORAGE_ATOMIC_BIT) && !(flags & VK_FORMAT_FEATURE_STORAGE_IMAGE_ATOMIC_BIT)) { - return false; - } - - // Validation via VK_FORMAT_FEATURE_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR fails if VRS attachment is not supported. - if (p_usage.has_flag(TEXTURE_USAGE_VRS_ATTACHMENT_BIT) && p_format != DATA_FORMAT_R8_UINT) { - return false; - } - - return true; + bool cpu_readable = (p_usage & RDD::TEXTURE_USAGE_CPU_READ_BIT); + BitField supported = driver->texture_get_usages_supported_by_format(p_format, cpu_readable); + bool any_unsupported = (((int64_t)supported) | ((int64_t)p_usage)) != ((int64_t)supported); + return !any_unsupported; } -/********************/ -/**** ATTACHMENT ****/ -/********************/ +/*********************/ +/**** FRAMEBUFFER ****/ +/*********************/ -VkRenderPass RenderingDeviceVulkan::_render_pass_create(const Vector &p_attachments, const Vector &p_passes, InitialAction p_initial_action, FinalAction p_final_action, InitialAction p_initial_depth_action, FinalAction p_final_depth_action, uint32_t p_view_count, Vector *r_samples) { - // Set up dependencies from/to external equivalent to the default (implicit) one, and then amend them. - const VkPipelineStageFlags default_access_mask = VK_ACCESS_INPUT_ATTACHMENT_READ_BIT | - VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | - VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | - VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | - VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT | // From Section 7.1 of Vulkan API Spec v1.1.148. - VK_ACCESS_FRAGMENT_SHADING_RATE_ATTACHMENT_READ_BIT_KHR; +RDD::RenderPassID RenderingDevice::_render_pass_create(const Vector &p_attachments, const Vector &p_passes, InitialAction p_initial_action, FinalAction p_final_action, InitialAction p_initial_depth_action, FinalAction p_final_depth_action, uint32_t p_view_count, Vector *r_samples) { + // NOTE: + // Before the refactor to RenderingDevice-RenderingDeviceDriver, there was commented out code to + // specify dependencies to external subpasses. Since it had been unused for a long timel it wasn't ported + // to the new architecture. - VkPipelineStageFlags reading_stages = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT | VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_TRANSFER_BIT; - VkSubpassDependency2KHR dependencies[2] = { - { VK_STRUCTURE_TYPE_SUBPASS_DESCRIPTION_2_KHR, nullptr, VK_SUBPASS_EXTERNAL, 0, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, 0, default_access_mask, 0, 0 }, - { VK_STRUCTURE_TYPE_SUBPASS_DESCRIPTION_2_KHR, nullptr, 0, VK_SUBPASS_EXTERNAL, VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, default_access_mask, 0, 0, 0 } - }; - VkSubpassDependency2KHR &dependency_from_external = dependencies[0]; - VkSubpassDependency2KHR &dependency_to_external = dependencies[1]; LocalVector attachment_last_pass; attachment_last_pass.resize(p_attachments.size()); if (p_view_count > 1) { - const VulkanContext::MultiviewCapabilities capabilities = context->get_multiview_capabilities(); + const RDD::MultiviewCapabilities &capabilities = driver->get_multiview_capabilities(); // This only works with multiview! - ERR_FAIL_COND_V_MSG(!capabilities.is_supported, VK_NULL_HANDLE, "Multiview not supported"); + ERR_FAIL_COND_V_MSG(!capabilities.is_supported, RDD::RenderPassID(), "Multiview not supported"); // Make sure we limit this to the number of views we support. - ERR_FAIL_COND_V_MSG(p_view_count > capabilities.max_view_count, VK_NULL_HANDLE, "Hardware does not support requested number of views for Multiview render pass"); + ERR_FAIL_COND_V_MSG(p_view_count > capabilities.max_view_count, RDD::RenderPassID(), "Hardware does not support requested number of views for Multiview render pass"); } - // These are only used if we use multiview but we need to define them in scope. - const uint32_t view_mask = (1 << p_view_count) - 1; - const uint32_t correlation_mask = (1 << p_view_count) - 1; - - Vector attachments; - Vector attachment_remap; + LocalVector attachments; + LocalVector attachment_remap; for (int i = 0; i < p_attachments.size(); i++) { if (p_attachments[i].usage_flags == AttachmentFormat::UNUSED_ATTACHMENT) { - attachment_remap.push_back(VK_ATTACHMENT_UNUSED); + attachment_remap.push_back(RDD::AttachmentReference::UNUSED); continue; } - ERR_FAIL_INDEX_V(p_attachments[i].format, DATA_FORMAT_MAX, VK_NULL_HANDLE); - ERR_FAIL_INDEX_V(p_attachments[i].samples, TEXTURE_SAMPLES_MAX, VK_NULL_HANDLE); + ERR_FAIL_INDEX_V(p_attachments[i].format, DATA_FORMAT_MAX, RDD::RenderPassID()); + ERR_FAIL_INDEX_V(p_attachments[i].samples, TEXTURE_SAMPLES_MAX, RDD::RenderPassID()); ERR_FAIL_COND_V_MSG(!(p_attachments[i].usage_flags & (TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | TEXTURE_USAGE_INPUT_ATTACHMENT_BIT | TEXTURE_USAGE_VRS_ATTACHMENT_BIT)), - VK_NULL_HANDLE, "Texture format for index (" + itos(i) + ") requires an attachment (color, depth-stencil, input or VRS) bit set."); + RDD::RenderPassID(), "Texture format for index (" + itos(i) + ") requires an attachment (color, depth-stencil, input or VRS) bit set."); - VkAttachmentDescription2KHR description = {}; - description.sType = VK_STRUCTURE_TYPE_ATTACHMENT_DESCRIPTION_2_KHR; - description.pNext = nullptr; - description.flags = 0; - description.format = vulkan_formats[p_attachments[i].format]; - description.samples = _ensure_supported_sample_count(p_attachments[i].samples); + RDD::Attachment description; + description.format = p_attachments[i].format; + description.samples = p_attachments[i].samples; - bool is_sampled = p_attachments[i].usage_flags & TEXTURE_USAGE_SAMPLING_BIT; - bool is_storage = p_attachments[i].usage_flags & TEXTURE_USAGE_STORAGE_BIT; - bool is_depth = p_attachments[i].usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT; + bool is_sampled = (p_attachments[i].usage_flags & TEXTURE_USAGE_SAMPLING_BIT); + bool is_storage = (p_attachments[i].usage_flags & TEXTURE_USAGE_STORAGE_BIT); + bool is_depth = (p_attachments[i].usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT); // We can setup a framebuffer where we write to our VRS texture to set it up. // We make the assumption here that if our texture is actually used as our VRS attachment. // It is used as such for each subpass. This is fairly certain seeing the restrictions on subpasses. - bool is_vrs = p_attachments[i].usage_flags & TEXTURE_USAGE_VRS_ATTACHMENT_BIT && i == p_passes[0].vrs_attachment; + bool is_vrs = (p_attachments[i].usage_flags & TEXTURE_USAGE_VRS_ATTACHMENT_BIT) && i == p_passes[0].vrs_attachment; if (is_vrs) { // For VRS we only read, there is no writing to this texture. - description.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD; - description.initialLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; - description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_LOAD; + description.load_op = RDD::ATTACHMENT_LOAD_OP_LOAD; + description.initial_layout = RDD::TEXTURE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; + description.stencil_load_op = RDD::ATTACHMENT_LOAD_OP_LOAD; } else { // For each UNDEFINED, assume the prior use was a *read*, as we'd be discarding the output of a write. // Also, each UNDEFINED will do an immediate layout transition (write), s.t. we must ensure execution synchronization vs @@ -3556,75 +2069,68 @@ VkRenderPass RenderingDeviceVulkan::_render_pass_create(const Vector subpasses; - LocalVector> color_reference_array; - LocalVector> input_reference_array; - LocalVector> resolve_reference_array; - LocalVector> preserve_reference_array; - LocalVector depth_reference_array; - LocalVector vrs_reference_array; - LocalVector vrs_attachment_info_array; - + LocalVector subpasses; subpasses.resize(p_passes.size()); - color_reference_array.resize(p_passes.size()); - input_reference_array.resize(p_passes.size()); - resolve_reference_array.resize(p_passes.size()); - preserve_reference_array.resize(p_passes.size()); - depth_reference_array.resize(p_passes.size()); - vrs_reference_array.resize(p_passes.size()); - vrs_attachment_info_array.resize(p_passes.size()); - - LocalVector subpass_dependencies; + LocalVector subpass_dependencies; for (int i = 0; i < p_passes.size(); i++) { const FramebufferPass *pass = &p_passes[i]; - - LocalVector &color_references = color_reference_array[i]; + RDD::Subpass &subpass = subpasses[i]; TextureSamples texture_samples = TEXTURE_SAMPLES_1; bool is_multisample_first = true; - void *subpass_nextptr = nullptr; for (int j = 0; j < pass->color_attachments.size(); j++) { int32_t attachment = pass->color_attachments[j]; - VkAttachmentReference2KHR reference; - reference.sType = VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2_KHR; - reference.pNext = nullptr; - if (attachment == FramebufferPass::ATTACHMENT_UNUSED) { - reference.attachment = VK_ATTACHMENT_UNUSED; - reference.layout = VK_IMAGE_LAYOUT_UNDEFINED; + RDD::AttachmentReference reference; + if (attachment == ATTACHMENT_UNUSED) { + reference.attachment = RDD::AttachmentReference::UNUSED; + reference.layout = RDD::TEXTURE_LAYOUT_UNDEFINED; } else { - ERR_FAIL_INDEX_V_MSG(attachment, p_attachments.size(), VK_NULL_HANDLE, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), color attachment (" + itos(j) + ")."); - ERR_FAIL_COND_V_MSG(!(p_attachments[attachment].usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT), VK_NULL_HANDLE, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it's marked as depth, but it's not usable as color attachment."); - ERR_FAIL_COND_V_MSG(attachment_last_pass[attachment] == i, VK_NULL_HANDLE, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it already was used for something else before in this pass."); + ERR_FAIL_INDEX_V_MSG(attachment, p_attachments.size(), RDD::RenderPassID(), "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), color attachment (" + itos(j) + ")."); + ERR_FAIL_COND_V_MSG(!(p_attachments[attachment].usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT), RDD::RenderPassID(), "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it's marked as depth, but it's not usable as color attachment."); + ERR_FAIL_COND_V_MSG(attachment_last_pass[attachment] == i, RDD::RenderPassID(), "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it already was used for something else before in this pass."); if (is_multisample_first) { texture_samples = p_attachments[attachment].samples; is_multisample_first = false; } else { - ERR_FAIL_COND_V_MSG(texture_samples != p_attachments[attachment].samples, VK_NULL_HANDLE, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), if an attachment is marked as multisample, all of them should be multisample and use the same number of samples."); + ERR_FAIL_COND_V_MSG(texture_samples != p_attachments[attachment].samples, RDD::RenderPassID(), "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), if an attachment is marked as multisample, all of them should be multisample and use the same number of samples."); } reference.attachment = attachment_remap[attachment]; - reference.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; + reference.layout = RDD::TEXTURE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; attachment_last_pass[attachment] = i; } - reference.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - color_references.push_back(reference); + reference.aspect = RDD::TEXTURE_ASPECT_COLOR_BIT; + subpass.color_references.push_back(reference); } - LocalVector &input_references = input_reference_array[i]; - for (int j = 0; j < pass->input_attachments.size(); j++) { int32_t attachment = pass->input_attachments[j]; - VkAttachmentReference2KHR reference; - reference.sType = VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2_KHR; - reference.pNext = nullptr; - if (attachment == FramebufferPass::ATTACHMENT_UNUSED) { - reference.attachment = VK_ATTACHMENT_UNUSED; - reference.layout = VK_IMAGE_LAYOUT_UNDEFINED; + RDD::AttachmentReference reference; + if (attachment == ATTACHMENT_UNUSED) { + reference.attachment = RDD::AttachmentReference::UNUSED; + reference.layout = RDD::TEXTURE_LAYOUT_UNDEFINED; } else { - ERR_FAIL_INDEX_V_MSG(attachment, p_attachments.size(), VK_NULL_HANDLE, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), input attachment (" + itos(j) + ")."); - ERR_FAIL_COND_V_MSG(!(p_attachments[attachment].usage_flags & TEXTURE_USAGE_INPUT_ATTACHMENT_BIT), VK_NULL_HANDLE, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it isn't marked as an input texture."); - ERR_FAIL_COND_V_MSG(attachment_last_pass[attachment] == i, VK_NULL_HANDLE, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it already was used for something else before in this pass."); + ERR_FAIL_INDEX_V_MSG(attachment, p_attachments.size(), RDD::RenderPassID(), "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), input attachment (" + itos(j) + ")."); + ERR_FAIL_COND_V_MSG(!(p_attachments[attachment].usage_flags & TEXTURE_USAGE_INPUT_ATTACHMENT_BIT), RDD::RenderPassID(), "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it isn't marked as an input texture."); + ERR_FAIL_COND_V_MSG(attachment_last_pass[attachment] == i, RDD::RenderPassID(), "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it already was used for something else before in this pass."); reference.attachment = attachment_remap[attachment]; - reference.layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; + reference.layout = RDD::TEXTURE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; attachment_last_pass[attachment] = i; } - reference.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - input_references.push_back(reference); + reference.aspect = RDD::TEXTURE_ASPECT_COLOR_BIT; + subpass.input_references.push_back(reference); } - LocalVector &resolve_references = resolve_reference_array[i]; - if (pass->resolve_attachments.size() > 0) { - ERR_FAIL_COND_V_MSG(pass->resolve_attachments.size() != pass->color_attachments.size(), VK_NULL_HANDLE, "The amount of resolve attachments (" + itos(pass->resolve_attachments.size()) + ") must match the number of color attachments (" + itos(pass->color_attachments.size()) + ")."); - ERR_FAIL_COND_V_MSG(texture_samples == TEXTURE_SAMPLES_1, VK_NULL_HANDLE, "Resolve attachments specified, but color attachments are not multisample."); + ERR_FAIL_COND_V_MSG(pass->resolve_attachments.size() != pass->color_attachments.size(), RDD::RenderPassID(), "The amount of resolve attachments (" + itos(pass->resolve_attachments.size()) + ") must match the number of color attachments (" + itos(pass->color_attachments.size()) + ")."); + ERR_FAIL_COND_V_MSG(texture_samples == TEXTURE_SAMPLES_1, RDD::RenderPassID(), "Resolve attachments specified, but color attachments are not multisample."); } for (int j = 0; j < pass->resolve_attachments.size(); j++) { int32_t attachment = pass->resolve_attachments[j]; - VkAttachmentReference2KHR reference; - reference.sType = VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2_KHR; - reference.pNext = nullptr; - if (attachment == FramebufferPass::ATTACHMENT_UNUSED) { - reference.attachment = VK_ATTACHMENT_UNUSED; - reference.layout = VK_IMAGE_LAYOUT_UNDEFINED; + RDD::AttachmentReference reference; + if (attachment == ATTACHMENT_UNUSED) { + reference.attachment = RDD::AttachmentReference::UNUSED; + reference.layout = RDD::TEXTURE_LAYOUT_UNDEFINED; } else { - ERR_FAIL_INDEX_V_MSG(attachment, p_attachments.size(), VK_NULL_HANDLE, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), resolve attachment (" + itos(j) + ")."); - ERR_FAIL_COND_V_MSG(pass->color_attachments[j] == FramebufferPass::ATTACHMENT_UNUSED, VK_NULL_HANDLE, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), resolve attachment (" + itos(j) + "), the respective color attachment is marked as unused."); - ERR_FAIL_COND_V_MSG(!(p_attachments[attachment].usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT), VK_NULL_HANDLE, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), resolve attachment, it isn't marked as a color texture."); - ERR_FAIL_COND_V_MSG(attachment_last_pass[attachment] == i, VK_NULL_HANDLE, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it already was used for something else before in this pass."); + ERR_FAIL_INDEX_V_MSG(attachment, p_attachments.size(), RDD::RenderPassID(), "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), resolve attachment (" + itos(j) + ")."); + ERR_FAIL_COND_V_MSG(pass->color_attachments[j] == ATTACHMENT_UNUSED, RDD::RenderPassID(), "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), resolve attachment (" + itos(j) + "), the respective color attachment is marked as unused."); + ERR_FAIL_COND_V_MSG(!(p_attachments[attachment].usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT), RDD::RenderPassID(), "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), resolve attachment, it isn't marked as a color texture."); + ERR_FAIL_COND_V_MSG(attachment_last_pass[attachment] == i, RDD::RenderPassID(), "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it already was used for something else before in this pass."); bool multisample = p_attachments[attachment].samples > TEXTURE_SAMPLES_1; - ERR_FAIL_COND_V_MSG(multisample, VK_NULL_HANDLE, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), resolve attachments can't be multisample."); + ERR_FAIL_COND_V_MSG(multisample, RDD::RenderPassID(), "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), resolve attachments can't be multisample."); reference.attachment = attachment_remap[attachment]; - reference.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; // VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL + reference.layout = RDD::TEXTURE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; // RDD::TEXTURE_LAYOUT_SHADER_READ_ONLY_OPTIMAL attachment_last_pass[attachment] = i; } - reference.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - resolve_references.push_back(reference); + reference.aspect = RDD::TEXTURE_ASPECT_COLOR_BIT; + subpass.resolve_references.push_back(reference); } - VkAttachmentReference2KHR &depth_stencil_reference = depth_reference_array[i]; - depth_stencil_reference.sType = VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2_KHR; - depth_stencil_reference.pNext = nullptr; - - if (pass->depth_attachment != FramebufferPass::ATTACHMENT_UNUSED) { + if (pass->depth_attachment != ATTACHMENT_UNUSED) { int32_t attachment = pass->depth_attachment; - ERR_FAIL_INDEX_V_MSG(attachment, p_attachments.size(), VK_NULL_HANDLE, "Invalid framebuffer depth format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), depth attachment."); - ERR_FAIL_COND_V_MSG(!(p_attachments[attachment].usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT), VK_NULL_HANDLE, "Invalid framebuffer depth format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it's marked as depth, but it's not a depth attachment."); - ERR_FAIL_COND_V_MSG(attachment_last_pass[attachment] == i, VK_NULL_HANDLE, "Invalid framebuffer depth format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it already was used for something else before in this pass."); - depth_stencil_reference.attachment = attachment_remap[attachment]; - depth_stencil_reference.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; - depth_stencil_reference.aspectMask = VK_IMAGE_ASPECT_NONE; + ERR_FAIL_INDEX_V_MSG(attachment, p_attachments.size(), RDD::RenderPassID(), "Invalid framebuffer depth format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), depth attachment."); + ERR_FAIL_COND_V_MSG(!(p_attachments[attachment].usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT), RDD::RenderPassID(), "Invalid framebuffer depth format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it's marked as depth, but it's not a depth attachment."); + ERR_FAIL_COND_V_MSG(attachment_last_pass[attachment] == i, RDD::RenderPassID(), "Invalid framebuffer depth format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it already was used for something else before in this pass."); + subpass.depth_stencil_reference.attachment = attachment_remap[attachment]; + subpass.depth_stencil_reference.layout = RDD::TEXTURE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; attachment_last_pass[attachment] = i; if (is_multisample_first) { texture_samples = p_attachments[attachment].samples; is_multisample_first = false; } else { - ERR_FAIL_COND_V_MSG(texture_samples != p_attachments[attachment].samples, VK_NULL_HANDLE, "Invalid framebuffer depth format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), if an attachment is marked as multisample, all of them should be multisample and use the same number of samples including the depth."); + ERR_FAIL_COND_V_MSG(texture_samples != p_attachments[attachment].samples, RDD::RenderPassID(), "Invalid framebuffer depth format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), if an attachment is marked as multisample, all of them should be multisample and use the same number of samples including the depth."); } } else { - depth_stencil_reference.attachment = VK_ATTACHMENT_UNUSED; - depth_stencil_reference.layout = VK_IMAGE_LAYOUT_UNDEFINED; + subpass.depth_stencil_reference.attachment = RDD::AttachmentReference::UNUSED; + subpass.depth_stencil_reference.layout = RDD::TEXTURE_LAYOUT_UNDEFINED; } - if (context->get_vrs_capabilities().attachment_vrs_supported && pass->vrs_attachment != FramebufferPass::ATTACHMENT_UNUSED) { + if (pass->vrs_attachment != ATTACHMENT_UNUSED) { int32_t attachment = pass->vrs_attachment; - ERR_FAIL_INDEX_V_MSG(attachment, p_attachments.size(), VK_NULL_HANDLE, "Invalid framebuffer VRS format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), VRS attachment."); - ERR_FAIL_COND_V_MSG(!(p_attachments[attachment].usage_flags & TEXTURE_USAGE_VRS_ATTACHMENT_BIT), VK_NULL_HANDLE, "Invalid framebuffer VRS format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it's marked as VRS, but it's not a VRS attachment."); - ERR_FAIL_COND_V_MSG(attachment_last_pass[attachment] == i, VK_NULL_HANDLE, "Invalid framebuffer VRS attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it already was used for something else before in this pass."); - - VkAttachmentReference2KHR &vrs_reference = vrs_reference_array[i]; - vrs_reference.sType = VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2_KHR; - vrs_reference.pNext = nullptr; - vrs_reference.attachment = attachment_remap[attachment]; - vrs_reference.layout = VK_IMAGE_LAYOUT_FRAGMENT_SHADING_RATE_ATTACHMENT_OPTIMAL_KHR; - vrs_reference.aspectMask = VK_IMAGE_ASPECT_NONE; + ERR_FAIL_INDEX_V_MSG(attachment, p_attachments.size(), RDD::RenderPassID(), "Invalid framebuffer VRS format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), VRS attachment."); + ERR_FAIL_COND_V_MSG(!(p_attachments[attachment].usage_flags & TEXTURE_USAGE_VRS_ATTACHMENT_BIT), RDD::RenderPassID(), "Invalid framebuffer VRS format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it's marked as VRS, but it's not a VRS attachment."); + ERR_FAIL_COND_V_MSG(attachment_last_pass[attachment] == i, RDD::RenderPassID(), "Invalid framebuffer VRS attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it already was used for something else before in this pass."); - Size2i texel_size = context->get_vrs_capabilities().texel_size; - - VkFragmentShadingRateAttachmentInfoKHR &vrs_attachment_info = vrs_attachment_info_array[i]; - vrs_attachment_info.sType = VK_STRUCTURE_TYPE_FRAGMENT_SHADING_RATE_ATTACHMENT_INFO_KHR; - vrs_attachment_info.pNext = nullptr; - vrs_attachment_info.pFragmentShadingRateAttachment = &vrs_reference; - vrs_attachment_info.shadingRateAttachmentTexelSize = { uint32_t(texel_size.x), uint32_t(texel_size.y) }; + subpass.vrs_reference.attachment = attachment_remap[attachment]; + subpass.vrs_reference.layout = RDD::TEXTURE_LAYOUT_VRS_ATTACHMENT_OPTIMAL; attachment_last_pass[attachment] = i; - - subpass_nextptr = &vrs_attachment_info; } - LocalVector &preserve_references = preserve_reference_array[i]; - for (int j = 0; j < pass->preserve_attachments.size(); j++) { int32_t attachment = pass->preserve_attachments[j]; - ERR_FAIL_COND_V_MSG(attachment == FramebufferPass::ATTACHMENT_UNUSED, VK_NULL_HANDLE, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), preserve attachment (" + itos(j) + "). Preserve attachments can't be unused."); + ERR_FAIL_COND_V_MSG(attachment == ATTACHMENT_UNUSED, RDD::RenderPassID(), "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), preserve attachment (" + itos(j) + "). Preserve attachments can't be unused."); - ERR_FAIL_INDEX_V_MSG(attachment, p_attachments.size(), VK_NULL_HANDLE, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), preserve attachment (" + itos(j) + ")."); + ERR_FAIL_INDEX_V_MSG(attachment, p_attachments.size(), RDD::RenderPassID(), "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), preserve attachment (" + itos(j) + ")."); if (attachment_last_pass[attachment] != i) { // Preserve can still be used to keep depth or color from being discarded after use. attachment_last_pass[attachment] = i; - preserve_references.push_back(attachment); + subpasses[i].preserve_attachments.push_back(attachment); } } - VkSubpassDescription2KHR &subpass = subpasses[i]; - subpass.sType = VK_STRUCTURE_TYPE_SUBPASS_DESCRIPTION_2_KHR; - subpass.pNext = subpass_nextptr; - subpass.flags = 0; - subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; - if (p_view_count == 1) { - // VUID-VkSubpassDescription2-multiview-06558: If the multiview feature is not enabled, viewMask must be 0. - subpass.viewMask = 0; - } else { - subpass.viewMask = view_mask; - } - subpass.inputAttachmentCount = input_references.size(); - if (input_references.size()) { - subpass.pInputAttachments = input_references.ptr(); - } else { - subpass.pInputAttachments = nullptr; - } - subpass.colorAttachmentCount = color_references.size(); - if (color_references.size()) { - subpass.pColorAttachments = color_references.ptr(); - } else { - subpass.pColorAttachments = nullptr; - } - if (depth_stencil_reference.attachment != VK_ATTACHMENT_UNUSED) { - subpass.pDepthStencilAttachment = &depth_stencil_reference; - } else { - subpass.pDepthStencilAttachment = nullptr; - } - - if (resolve_references.size()) { - subpass.pResolveAttachments = resolve_references.ptr(); - } else { - subpass.pResolveAttachments = nullptr; - } - - subpass.preserveAttachmentCount = preserve_references.size(); - if (preserve_references.size()) { - subpass.pPreserveAttachments = preserve_references.ptr(); - } else { - subpass.pPreserveAttachments = nullptr; - } - if (r_samples) { r_samples->push_back(texture_samples); } if (i > 0) { - VkSubpassDependency2KHR dependency; - dependency.sType = VK_STRUCTURE_TYPE_SUBPASS_DEPENDENCY_2_KHR; - dependency.pNext = nullptr; - dependency.srcSubpass = i - 1; - dependency.dstSubpass = i; - dependency.srcStageMask = 0; - dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT; - dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT; - - dependency.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; - dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_INPUT_ATTACHMENT_READ_BIT; - dependency.dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT; - dependency.viewOffset = 0; + RDD::SubpassDependency dependency; + dependency.src_subpass = i - 1; + dependency.dst_subpass = i; + dependency.src_stages = (RDD::PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | RDD::PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | RDD::PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT); + dependency.dst_stages = (RDD::PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | RDD::PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | RDD::PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT | RDD::PIPELINE_STAGE_FRAGMENT_SHADER_BIT); + dependency.src_access = (RDD::BARRIER_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | RDD::BARRIER_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT); + dependency.dst_access = (RDD::BARRIER_ACCESS_COLOR_ATTACHMENT_READ_BIT | RDD::BARRIER_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | RDD::BARRIER_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | RDD::BARRIER_ACCESS_INPUT_ATTACHMENT_READ_BIT); subpass_dependencies.push_back(dependency); } - /* - // NOTE: Big Mallet Approach -- any layout transition causes a full barrier. - if (reference.layout != description.initialLayout) { - // NOTE: This should be smarter based on the texture's knowledge of its previous role. - dependency_from_external.srcStageMask |= VK_PIPELINE_STAGE_ALL_COMMANDS_BIT; - dependency_from_external.srcAccessMask |= VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT; - } - if (reference.layout != description.finalLayout) { - // NOTE: This should be smarter based on the texture's knowledge of its subsequent role. - dependency_to_external.dstStageMask |= VK_PIPELINE_STAGE_ALL_COMMANDS_BIT; - dependency_to_external.dstAccessMask |= VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT; - } - */ - } - - VkRenderPassCreateInfo2KHR render_pass_create_info; - render_pass_create_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO_2_KHR; - render_pass_create_info.pNext = nullptr; - render_pass_create_info.flags = 0; - - render_pass_create_info.attachmentCount = attachments.size(); - render_pass_create_info.pAttachments = attachments.ptr(); - render_pass_create_info.subpassCount = subpasses.size(); - render_pass_create_info.pSubpasses = subpasses.ptr(); - // Commenting this because it seems it just avoids raster and compute to work at the same time. - // Other barriers seem to be protecting the render pass fine. - // render_pass_create_info.dependencyCount = 2; - // render_pass_create_info.pDependencies = dependencies; - - render_pass_create_info.dependencyCount = subpass_dependencies.size(); - if (subpass_dependencies.size()) { - render_pass_create_info.pDependencies = subpass_dependencies.ptr(); - } else { - render_pass_create_info.pDependencies = nullptr; - } - - if (p_view_count == 1) { - // VUID-VkRenderPassCreateInfo2-viewMask-03057: If the VkSubpassDescription2::viewMask member of all elements of pSubpasses is 0, correlatedViewMaskCount must be 0. - render_pass_create_info.correlatedViewMaskCount = 0; - render_pass_create_info.pCorrelatedViewMasks = nullptr; - } else { - render_pass_create_info.correlatedViewMaskCount = 1; - render_pass_create_info.pCorrelatedViewMasks = &correlation_mask; - } - - Vector view_masks; - VkRenderPassMultiviewCreateInfo render_pass_multiview_create_info; - - if ((p_view_count > 1) && !context->supports_renderpass2()) { - // This is only required when using vkCreateRenderPass, we add it if vkCreateRenderPass2KHR is not supported - // resulting this in being passed to our vkCreateRenderPass fallback. - - // Set view masks for each subpass. - for (uint32_t i = 0; i < subpasses.size(); i++) { - view_masks.push_back(view_mask); - } - - render_pass_multiview_create_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_MULTIVIEW_CREATE_INFO; - render_pass_multiview_create_info.pNext = nullptr; - render_pass_multiview_create_info.subpassCount = subpasses.size(); - render_pass_multiview_create_info.pViewMasks = view_masks.ptr(); - render_pass_multiview_create_info.dependencyCount = 0; - render_pass_multiview_create_info.pViewOffsets = nullptr; - render_pass_multiview_create_info.correlationMaskCount = 1; - render_pass_multiview_create_info.pCorrelationMasks = &correlation_mask; - - render_pass_create_info.pNext = &render_pass_multiview_create_info; } - VkRenderPass render_pass; - VkResult res = context->vkCreateRenderPass2KHR(device, &render_pass_create_info, nullptr, &render_pass); - ERR_FAIL_COND_V_MSG(res, VK_NULL_HANDLE, "vkCreateRenderPass2KHR failed with error " + itos(res) + "."); + RDD::RenderPassID render_pass = driver->render_pass_create(attachments, subpasses, subpass_dependencies, p_view_count); + ERR_FAIL_COND_V(!render_pass, RDD::RenderPassID()); return render_pass; } -RenderingDevice::FramebufferFormatID RenderingDeviceVulkan::framebuffer_format_create(const Vector &p_format, uint32_t p_view_count) { +RenderingDevice::FramebufferFormatID RenderingDevice::framebuffer_format_create(const Vector &p_format, uint32_t p_view_count) { FramebufferPass pass; for (int i = 0; i < p_format.size(); i++) { if (p_format[i].usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) { @@ -4083,7 +2419,7 @@ RenderingDevice::FramebufferFormatID RenderingDeviceVulkan::framebuffer_format_c passes.push_back(pass); return framebuffer_format_create_multipass(p_format, passes, p_view_count); } -RenderingDevice::FramebufferFormatID RenderingDeviceVulkan::framebuffer_format_create_multipass(const Vector &p_attachments, const Vector &p_passes, uint32_t p_view_count) { +RenderingDevice::FramebufferFormatID RenderingDevice::framebuffer_format_create_multipass(const Vector &p_attachments, const Vector &p_passes, uint32_t p_view_count) { _THREAD_SAFE_METHOD_ FramebufferFormatKey key; @@ -4098,9 +2434,9 @@ RenderingDevice::FramebufferFormatID RenderingDeviceVulkan::framebuffer_format_c } Vector samples; - VkRenderPass render_pass = _render_pass_create(p_attachments, p_passes, INITIAL_ACTION_CLEAR, FINAL_ACTION_READ, INITIAL_ACTION_CLEAR, FINAL_ACTION_READ, p_view_count, &samples); // Actions don't matter for this use case. + RDD::RenderPassID render_pass = _render_pass_create(p_attachments, p_passes, INITIAL_ACTION_CLEAR, FINAL_ACTION_READ, INITIAL_ACTION_CLEAR, FINAL_ACTION_READ, p_view_count, &samples); // Actions don't matter for this use case. - if (render_pass == VK_NULL_HANDLE) { // Was likely invalid. + if (!render_pass) { // Was likely invalid. return INVALID_ID; } FramebufferFormatID id = FramebufferFormatID(framebuffer_format_cache.size()) | (FramebufferFormatID(ID_TYPE_FRAMEBUFFER_FORMAT) << FramebufferFormatID(ID_BASE_SHIFT)); @@ -4115,7 +2451,7 @@ RenderingDevice::FramebufferFormatID RenderingDeviceVulkan::framebuffer_format_c return id; } -RenderingDevice::FramebufferFormatID RenderingDeviceVulkan::framebuffer_format_create_empty(TextureSamples p_samples) { +RenderingDevice::FramebufferFormatID RenderingDevice::framebuffer_format_create_empty(TextureSamples p_samples) { FramebufferFormatKey key; key.passes.push_back(FramebufferPass()); @@ -4125,42 +2461,11 @@ RenderingDevice::FramebufferFormatID RenderingDeviceVulkan::framebuffer_format_c return E->get(); } - VkSubpassDescription2KHR subpass; - subpass.sType = VK_STRUCTURE_TYPE_SUBPASS_DESCRIPTION_2_KHR; - subpass.pNext = nullptr; - subpass.flags = 0; - subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; - subpass.viewMask = 0; - subpass.inputAttachmentCount = 0; // Unsupported for now. - subpass.pInputAttachments = nullptr; - subpass.colorAttachmentCount = 0; - subpass.pColorAttachments = nullptr; - subpass.pDepthStencilAttachment = nullptr; - subpass.pResolveAttachments = nullptr; - subpass.preserveAttachmentCount = 0; - subpass.pPreserveAttachments = nullptr; - - VkRenderPassCreateInfo2KHR render_pass_create_info; - render_pass_create_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO_2_KHR; - render_pass_create_info.pNext = nullptr; - render_pass_create_info.flags = 0; - render_pass_create_info.attachmentCount = 0; - render_pass_create_info.pAttachments = nullptr; - render_pass_create_info.subpassCount = 1; - render_pass_create_info.pSubpasses = &subpass; - render_pass_create_info.dependencyCount = 0; - render_pass_create_info.pDependencies = nullptr; - render_pass_create_info.correlatedViewMaskCount = 0; - render_pass_create_info.pCorrelatedViewMasks = nullptr; - - VkRenderPass render_pass; - VkResult res = context->vkCreateRenderPass2KHR(device, &render_pass_create_info, nullptr, &render_pass); - - ERR_FAIL_COND_V_MSG(res, 0, "vkCreateRenderPass2KHR for empty fb failed with error " + itos(res) + "."); - - if (render_pass == VK_NULL_HANDLE) { // Was likely invalid. - return INVALID_ID; - } + LocalVector subpass; + subpass.resize(1); + + RDD::RenderPassID render_pass = driver->render_pass_create({}, subpass, {}, 1); + ERR_FAIL_COND_V(!render_pass, FramebufferFormatID()); FramebufferFormatID id = FramebufferFormatID(framebuffer_format_cache.size()) | (FramebufferFormatID(ID_TYPE_FRAMEBUFFER_FORMAT) << FramebufferFormatID(ID_BASE_SHIFT)); @@ -4174,7 +2479,7 @@ RenderingDevice::FramebufferFormatID RenderingDeviceVulkan::framebuffer_format_c return id; } -RenderingDevice::TextureSamples RenderingDeviceVulkan::framebuffer_format_get_texture_samples(FramebufferFormatID p_format, uint32_t p_pass) { +RenderingDevice::TextureSamples RenderingDevice::framebuffer_format_get_texture_samples(FramebufferFormatID p_format, uint32_t p_pass) { HashMap::Iterator E = framebuffer_formats.find(p_format); ERR_FAIL_COND_V(!E, TEXTURE_SAMPLES_1); ERR_FAIL_COND_V(p_pass >= uint32_t(E->value.pass_samples.size()), TEXTURE_SAMPLES_1); @@ -4182,11 +2487,7 @@ RenderingDevice::TextureSamples RenderingDeviceVulkan::framebuffer_format_get_te return E->value.pass_samples[p_pass]; } -/***********************/ -/**** RENDER TARGET ****/ -/***********************/ - -RID RenderingDeviceVulkan::framebuffer_create_empty(const Size2i &p_size, TextureSamples p_samples, FramebufferFormatID p_format_check) { +RID RenderingDevice::framebuffer_create_empty(const Size2i &p_size, TextureSamples p_samples, FramebufferFormatID p_format_check) { _THREAD_SAFE_METHOD_ Framebuffer framebuffer; framebuffer.format_id = framebuffer_format_create_empty(p_samples); @@ -4201,7 +2502,7 @@ RID RenderingDeviceVulkan::framebuffer_create_empty(const Size2i &p_size, Textur return id; } -RID RenderingDeviceVulkan::framebuffer_create(const Vector &p_texture_attachments, FramebufferFormatID p_format_check, uint32_t p_view_count) { +RID RenderingDevice::framebuffer_create(const Vector &p_texture_attachments, FramebufferFormatID p_format_check, uint32_t p_view_count) { _THREAD_SAFE_METHOD_ FramebufferPass pass; @@ -4219,7 +2520,7 @@ RID RenderingDeviceVulkan::framebuffer_create(const Vector &p_texture_attac if (texture && texture->is_resolve_buffer) { pass.resolve_attachments.push_back(i); } else { - pass.color_attachments.push_back(texture ? i : FramebufferPass::ATTACHMENT_UNUSED); + pass.color_attachments.push_back(texture ? i : ATTACHMENT_UNUSED); } } } @@ -4230,7 +2531,7 @@ RID RenderingDeviceVulkan::framebuffer_create(const Vector &p_texture_attac return framebuffer_create_multipass(p_texture_attachments, passes, p_format_check, p_view_count); } -RID RenderingDeviceVulkan::framebuffer_create_multipass(const Vector &p_texture_attachments, const Vector &p_passes, FramebufferFormatID p_format_check, uint32_t p_view_count) { +RID RenderingDevice::framebuffer_create_multipass(const Vector &p_texture_attachments, const Vector &p_passes, FramebufferFormatID p_format_check, uint32_t p_view_count) { _THREAD_SAFE_METHOD_ Vector attachments; @@ -4295,7 +2596,7 @@ RID RenderingDeviceVulkan::framebuffer_create_multipass(const Vector &p_tex return id; } -RenderingDevice::FramebufferFormatID RenderingDeviceVulkan::framebuffer_get_format(RID p_framebuffer) { +RenderingDevice::FramebufferFormatID RenderingDevice::framebuffer_get_format(RID p_framebuffer) { _THREAD_SAFE_METHOD_ Framebuffer *framebuffer = framebuffer_owner.get_or_null(p_framebuffer); @@ -4304,17 +2605,17 @@ RenderingDevice::FramebufferFormatID RenderingDeviceVulkan::framebuffer_get_form return framebuffer->format_id; } -bool RenderingDeviceVulkan::framebuffer_is_valid(RID p_framebuffer) const { +bool RenderingDevice::framebuffer_is_valid(RID p_framebuffer) const { _THREAD_SAFE_METHOD_ return framebuffer_owner.owns(p_framebuffer); } -void RenderingDeviceVulkan::framebuffer_set_invalidation_callback(RID p_framebuffer, InvalidationCallback p_callback, void *p_userdata) { +void RenderingDevice::framebuffer_set_invalidation_callback(RID p_framebuffer, InvalidationCallback p_callback, void *p_userdata) { _THREAD_SAFE_METHOD_ Framebuffer *framebuffer = framebuffer_owner.get_or_null(p_framebuffer); - ERR_FAIL_NULL(framebuffer); + ERR_FAIL_COND(!framebuffer); framebuffer->invalidated_callback = p_callback; framebuffer->invalidated_callback_userdata = p_userdata; @@ -4324,43 +2625,17 @@ void RenderingDeviceVulkan::framebuffer_set_invalidation_callback(RID p_framebuf /**** SAMPLER ****/ /*****************/ -RID RenderingDeviceVulkan::sampler_create(const SamplerState &p_state) { +RID RenderingDevice::sampler_create(const SamplerState &p_state) { _THREAD_SAFE_METHOD_ - VkSamplerCreateInfo sampler_create_info; - sampler_create_info.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO; - sampler_create_info.pNext = nullptr; - sampler_create_info.flags = 0; - sampler_create_info.magFilter = p_state.mag_filter == SAMPLER_FILTER_LINEAR ? VK_FILTER_LINEAR : VK_FILTER_NEAREST; - sampler_create_info.minFilter = p_state.min_filter == SAMPLER_FILTER_LINEAR ? VK_FILTER_LINEAR : VK_FILTER_NEAREST; - sampler_create_info.mipmapMode = p_state.mip_filter == SAMPLER_FILTER_LINEAR ? VK_SAMPLER_MIPMAP_MODE_LINEAR : VK_SAMPLER_MIPMAP_MODE_NEAREST; - ERR_FAIL_INDEX_V(p_state.repeat_u, SAMPLER_REPEAT_MODE_MAX, RID()); - sampler_create_info.addressModeU = address_modes[p_state.repeat_u]; ERR_FAIL_INDEX_V(p_state.repeat_v, SAMPLER_REPEAT_MODE_MAX, RID()); - sampler_create_info.addressModeV = address_modes[p_state.repeat_v]; ERR_FAIL_INDEX_V(p_state.repeat_w, SAMPLER_REPEAT_MODE_MAX, RID()); - sampler_create_info.addressModeW = address_modes[p_state.repeat_w]; - - sampler_create_info.mipLodBias = p_state.lod_bias; - sampler_create_info.anisotropyEnable = p_state.use_anisotropy && context->get_physical_device_features().samplerAnisotropy; - sampler_create_info.maxAnisotropy = p_state.anisotropy_max; - sampler_create_info.compareEnable = p_state.enable_compare; - ERR_FAIL_INDEX_V(p_state.compare_op, COMPARE_OP_MAX, RID()); - sampler_create_info.compareOp = compare_operators[p_state.compare_op]; - - sampler_create_info.minLod = p_state.min_lod; - sampler_create_info.maxLod = p_state.max_lod; - ERR_FAIL_INDEX_V(p_state.border_color, SAMPLER_BORDER_COLOR_MAX, RID()); - sampler_create_info.borderColor = sampler_border_colors[p_state.border_color]; - sampler_create_info.unnormalizedCoordinates = p_state.unnormalized_uvw; - - VkSampler sampler; - VkResult res = vkCreateSampler(device, &sampler_create_info, nullptr, &sampler); - ERR_FAIL_COND_V_MSG(res, RID(), "vkCreateSampler failed with error " + itos(res) + "."); + RDD::SamplerID sampler = driver->sampler_create(p_state); + ERR_FAIL_COND_V(!sampler, RID()); RID id = sampler_owner.make_rid(sampler); #ifdef DEV_ENABLED @@ -4369,40 +2644,46 @@ RID RenderingDeviceVulkan::sampler_create(const SamplerState &p_state) { return id; } -bool RenderingDeviceVulkan::sampler_is_format_supported_for_filter(DataFormat p_format, SamplerFilter p_sampler_filter) const { +bool RenderingDevice::sampler_is_format_supported_for_filter(DataFormat p_format, SamplerFilter p_sampler_filter) const { ERR_FAIL_INDEX_V(p_format, DATA_FORMAT_MAX, false); _THREAD_SAFE_METHOD_ - // Validate that this image is supported for the intended filtering. - VkFormatProperties properties; - vkGetPhysicalDeviceFormatProperties(context->get_physical_device(), vulkan_formats[p_format], &properties); - - return p_sampler_filter == RD::SAMPLER_FILTER_NEAREST || (p_sampler_filter == RD::SAMPLER_FILTER_LINEAR && (properties.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT)); + return driver->sampler_is_format_supported_for_filter(p_format, p_sampler_filter); } -/**********************/ -/**** VERTEX ARRAY ****/ -/**********************/ +/***********************/ +/**** VERTEX BUFFER ****/ +/***********************/ -RID RenderingDeviceVulkan::vertex_buffer_create(uint32_t p_size_bytes, const Vector &p_data, bool p_use_as_storage) { +RID RenderingDevice::vertex_buffer_create(uint32_t p_size_bytes, const Vector &p_data, bool p_use_as_storage) { _THREAD_SAFE_METHOD_ ERR_FAIL_COND_V(p_data.size() && (uint32_t)p_data.size() != p_size_bytes, RID()); - uint32_t usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT; + Buffer buffer; + buffer.size = p_size_bytes; + buffer.usage = RDD::BUFFER_USAGE_TRANSFER_FROM_BIT | RDD::BUFFER_USAGE_TRANSFER_TO_BIT | RDD::BUFFER_USAGE_VERTEX_BIT; if (p_use_as_storage) { - usage |= VK_BUFFER_USAGE_STORAGE_BUFFER_BIT; + buffer.usage.set_flag(RDD::BUFFER_USAGE_STORAGE_BIT); } - Buffer buffer; - _buffer_allocate(&buffer, p_size_bytes, usage, VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE, 0); + buffer.driver_id = driver->buffer_create(buffer.size, buffer.usage, RDD::MEMORY_ALLOCATION_TYPE_GPU); + ERR_FAIL_COND_V(!buffer.driver_id, RID()); + if (p_data.size()) { uint64_t data_size = p_data.size(); const uint8_t *r = p_data.ptr(); _buffer_update(&buffer, 0, r, data_size); - _buffer_memory_barrier(buffer.buffer, 0, data_size, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_VERTEX_INPUT_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT, false); + RDD::BufferBarrier bb; + bb.buffer = buffer.driver_id; + bb.src_access = RDD::BARRIER_ACCESS_TRANSFER_WRITE_BIT; + bb.dst_access = RDD::BARRIER_ACCESS_VERTEX_ATTRIBUTE_READ_BIT; + bb.size = data_size; + driver->command_pipeline_barrier(frames[frame].setup_command_buffer, RDD::PIPELINE_STAGE_TRANSFER_BIT, RDD::PIPELINE_STAGE_VERTEX_INPUT_BIT, {}, bb, {}); } + buffer_memory += buffer.size; + RID id = vertex_buffer_owner.make_rid(buffer); #ifdef DEV_ENABLED set_resource_name(id, "RID:" + itos(id.get_id())); @@ -4411,58 +2692,39 @@ RID RenderingDeviceVulkan::vertex_buffer_create(uint32_t p_size_bytes, const Vec } // Internally reference counted, this ID is warranted to be unique for the same description, but needs to be freed as many times as it was allocated. -RenderingDevice::VertexFormatID RenderingDeviceVulkan::vertex_format_create(const Vector &p_vertex_formats) { +RenderingDevice::VertexFormatID RenderingDevice::vertex_format_create(const Vector &p_vertex_descriptions) { _THREAD_SAFE_METHOD_ VertexDescriptionKey key; - key.vertex_formats = p_vertex_formats; + key.vertex_formats = p_vertex_descriptions; VertexFormatID *idptr = vertex_format_cache.getptr(key); if (idptr) { return *idptr; } - // Does not exist, create one and cache it. - VertexDescriptionCache vdcache; - vdcache.bindings = memnew_arr(VkVertexInputBindingDescription, p_vertex_formats.size()); - vdcache.attributes = memnew_arr(VkVertexInputAttributeDescription, p_vertex_formats.size()); - HashSet used_locations; - for (int i = 0; i < p_vertex_formats.size(); i++) { - ERR_CONTINUE(p_vertex_formats[i].format >= DATA_FORMAT_MAX); - ERR_FAIL_COND_V(used_locations.has(p_vertex_formats[i].location), INVALID_ID); + for (int i = 0; i < p_vertex_descriptions.size(); i++) { + ERR_CONTINUE(p_vertex_descriptions[i].format >= DATA_FORMAT_MAX); + ERR_FAIL_COND_V(used_locations.has(p_vertex_descriptions[i].location), INVALID_ID); - ERR_FAIL_COND_V_MSG(get_format_vertex_size(p_vertex_formats[i].format) == 0, INVALID_ID, - "Data format for attachment (" + itos(i) + "), '" + named_formats[p_vertex_formats[i].format] + "', is not valid for a vertex array."); + ERR_FAIL_COND_V_MSG(get_format_vertex_size(p_vertex_descriptions[i].format) == 0, INVALID_ID, + "Data format for attachment (" + itos(i) + "), '" + FORMAT_NAMES[p_vertex_descriptions[i].format] + "', is not valid for a vertex array."); - vdcache.bindings[i].binding = i; - vdcache.bindings[i].stride = p_vertex_formats[i].stride; - vdcache.bindings[i].inputRate = p_vertex_formats[i].frequency == VERTEX_FREQUENCY_INSTANCE ? VK_VERTEX_INPUT_RATE_INSTANCE : VK_VERTEX_INPUT_RATE_VERTEX; - vdcache.attributes[i].binding = i; - vdcache.attributes[i].location = p_vertex_formats[i].location; - vdcache.attributes[i].format = vulkan_formats[p_vertex_formats[i].format]; - vdcache.attributes[i].offset = p_vertex_formats[i].offset; - used_locations.insert(p_vertex_formats[i].location); + used_locations.insert(p_vertex_descriptions[i].location); } - vdcache.create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; - vdcache.create_info.pNext = nullptr; - vdcache.create_info.flags = 0; - - vdcache.create_info.vertexAttributeDescriptionCount = p_vertex_formats.size(); - vdcache.create_info.pVertexAttributeDescriptions = vdcache.attributes; - - vdcache.create_info.vertexBindingDescriptionCount = p_vertex_formats.size(); - vdcache.create_info.pVertexBindingDescriptions = vdcache.bindings; - vdcache.vertex_formats = p_vertex_formats; + RDD::VertexFormatID driver_id = driver->vertex_format_create(p_vertex_descriptions); + ERR_FAIL_COND_V(!driver_id, 0); - VertexFormatID id = VertexFormatID(vertex_format_cache.size()) | (VertexFormatID(ID_TYPE_VERTEX_FORMAT) << ID_BASE_SHIFT); + VertexFormatID id = (vertex_format_cache.size() | ((int64_t)ID_TYPE_VERTEX_FORMAT << ID_BASE_SHIFT)); vertex_format_cache[key] = id; - vertex_formats[id] = vdcache; + vertex_formats[id].vertex_formats = p_vertex_descriptions; + vertex_formats[id].driver_id = driver_id; return id; } -RID RenderingDeviceVulkan::vertex_array_create(uint32_t p_vertex_count, VertexFormatID p_vertex_format, const Vector &p_src_buffers, const Vector &p_offsets) { +RID RenderingDevice::vertex_array_create(uint32_t p_vertex_count, VertexFormatID p_vertex_format, const Vector &p_src_buffers, const Vector &p_offsets) { _THREAD_SAFE_METHOD_ ERR_FAIL_COND_V(!vertex_formats.has(p_vertex_format), RID()); @@ -4499,7 +2761,6 @@ RID RenderingDeviceVulkan::vertex_array_create(uint32_t p_vertex_count, VertexFo if (atf.frequency == VERTEX_FREQUENCY_VERTEX) { // Validate size for regular drawing. uint64_t total_size = uint64_t(atf.stride) * (p_vertex_count - 1) + atf.offset + element_size; - ERR_FAIL_COND_V_MSG(total_size > buffer->size, RID(), "Attachment (" + itos(i) + ") will read past the end of the buffer."); @@ -4514,7 +2775,7 @@ RID RenderingDeviceVulkan::vertex_array_create(uint32_t p_vertex_count, VertexFo } } - vertex_array.buffers.push_back(buffer->buffer); + vertex_array.buffers.push_back(buffer->driver_id); } RID id = vertex_array_owner.make_rid(vertex_array); @@ -4525,13 +2786,13 @@ RID RenderingDeviceVulkan::vertex_array_create(uint32_t p_vertex_count, VertexFo return id; } -RID RenderingDeviceVulkan::index_buffer_create(uint32_t p_index_count, IndexBufferFormat p_format, const Vector &p_data, bool p_use_restart_indices) { +RID RenderingDevice::index_buffer_create(uint32_t p_index_count, IndexBufferFormat p_format, const Vector &p_data, bool p_use_restart_indices) { _THREAD_SAFE_METHOD_ ERR_FAIL_COND_V(p_index_count == 0, RID()); IndexBuffer index_buffer; - index_buffer.index_type = (p_format == INDEX_BUFFER_FORMAT_UINT16) ? VK_INDEX_TYPE_UINT16 : VK_INDEX_TYPE_UINT32; + index_buffer.format = p_format; index_buffer.supports_restart_indices = p_use_restart_indices; index_buffer.index_count = p_index_count; uint32_t size_bytes = p_index_count * ((p_format == INDEX_BUFFER_FORMAT_UINT16) ? 2 : 4); @@ -4564,13 +2825,25 @@ RID RenderingDeviceVulkan::index_buffer_create(uint32_t p_index_count, IndexBuff #else index_buffer.max_index = 0xFFFFFFFF; #endif - _buffer_allocate(&index_buffer, size_bytes, VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT, VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE, 0); + index_buffer.size = size_bytes; + index_buffer.usage = (RDD::BUFFER_USAGE_TRANSFER_FROM_BIT | RDD::BUFFER_USAGE_TRANSFER_TO_BIT | RDD::BUFFER_USAGE_INDEX_BIT); + index_buffer.driver_id = driver->buffer_create(index_buffer.size, index_buffer.usage, RDD::MEMORY_ALLOCATION_TYPE_GPU); + ERR_FAIL_COND_V(!index_buffer.driver_id, RID()); + if (p_data.size()) { uint64_t data_size = p_data.size(); const uint8_t *r = p_data.ptr(); _buffer_update(&index_buffer, 0, r, data_size); - _buffer_memory_barrier(index_buffer.buffer, 0, data_size, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_VERTEX_INPUT_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_INDEX_READ_BIT, false); + RDD::BufferBarrier bb; + bb.buffer = index_buffer.driver_id; + bb.src_access = RDD::BARRIER_ACCESS_TRANSFER_WRITE_BIT; + bb.dst_access = RDD::BARRIER_ACCESS_INDEX_READ_BIT; + bb.size = data_size; + driver->command_pipeline_barrier(frames[frame].setup_command_buffer, RDD::PIPELINE_STAGE_TRANSFER_BIT, RDD::PIPELINE_STAGE_VERTEX_INPUT_BIT, {}, bb, {}); } + + buffer_memory += index_buffer.size; + RID id = index_buffer_owner.make_rid(index_buffer); #ifdef DEV_ENABLED set_resource_name(id, "RID:" + itos(id.get_id())); @@ -4578,7 +2851,7 @@ RID RenderingDeviceVulkan::index_buffer_create(uint32_t p_index_count, IndexBuff return id; } -RID RenderingDeviceVulkan::index_array_create(RID p_index_buffer, uint32_t p_index_offset, uint32_t p_index_count) { +RID RenderingDevice::index_array_create(RID p_index_buffer, uint32_t p_index_offset, uint32_t p_index_count) { _THREAD_SAFE_METHOD_ ERR_FAIL_COND_V(!index_buffer_owner.owns(p_index_buffer), RID()); @@ -4590,10 +2863,10 @@ RID RenderingDeviceVulkan::index_array_create(RID p_index_buffer, uint32_t p_ind IndexArray index_array; index_array.max_index = index_buffer->max_index; - index_array.buffer = index_buffer->buffer; + index_array.driver_id = index_buffer->driver_id; index_array.offset = p_index_offset; index_array.indices = p_index_count; - index_array.index_type = index_buffer->index_type; + index_array.format = index_buffer->format; index_array.supports_restart_indices = index_buffer->supports_restart_indices; RID id = index_array_owner.make_rid(index_array); @@ -4605,448 +2878,47 @@ RID RenderingDeviceVulkan::index_array_create(RID p_index_buffer, uint32_t p_ind /**** SHADER ****/ /****************/ -static const char *shader_uniform_names[RenderingDevice::UNIFORM_TYPE_MAX] = { +static const char *SHADER_UNIFORM_NAMES[RenderingDevice::UNIFORM_TYPE_MAX] = { "Sampler", "CombinedSampler", "Texture", "Image", "TextureBuffer", "SamplerTextureBuffer", "ImageBuffer", "UniformBuffer", "StorageBuffer", "InputAttachment" }; -static VkShaderStageFlagBits shader_stage_masks[RenderingDevice::SHADER_STAGE_MAX] = { - VK_SHADER_STAGE_VERTEX_BIT, - VK_SHADER_STAGE_FRAGMENT_BIT, - VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT, - VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT, - VK_SHADER_STAGE_COMPUTE_BIT, -}; - -String RenderingDeviceVulkan::_shader_uniform_debug(RID p_shader, int p_set) { +String RenderingDevice::_shader_uniform_debug(RID p_shader, int p_set) { String ret; const Shader *shader = shader_owner.get_or_null(p_shader); ERR_FAIL_NULL_V(shader, String()); - for (int i = 0; i < shader->sets.size(); i++) { + for (int i = 0; i < shader->uniform_sets.size(); i++) { if (p_set >= 0 && i != p_set) { continue; } - for (int j = 0; j < shader->sets[i].uniform_info.size(); j++) { - const UniformInfo &ui = shader->sets[i].uniform_info[j]; + for (int j = 0; j < shader->uniform_sets[i].size(); j++) { + const ShaderUniform &ui = shader->uniform_sets[i][j]; if (!ret.is_empty()) { ret += "\n"; } - ret += "Set: " + itos(i) + " Binding: " + itos(ui.binding) + " Type: " + shader_uniform_names[ui.type] + " Writable: " + (ui.writable ? "Y" : "N") + " Length: " + itos(ui.length); + ret += "Set: " + itos(i) + " Binding: " + itos(ui.binding) + " Type: " + SHADER_UNIFORM_NAMES[ui.type] + " Writable: " + (ui.writable ? "Y" : "N") + " Length: " + itos(ui.length); } } return ret; } -// Version 1: initial. -// Version 2: Added shader name. -// Version 3: Added writable. - -#define SHADER_BINARY_VERSION 3 - -String RenderingDeviceVulkan::shader_get_binary_cache_key() const { - return "Vulkan-SV" + itos(SHADER_BINARY_VERSION); +String RenderingDevice::shader_get_binary_cache_key() const { + return driver->shader_get_binary_cache_key(); } -struct RenderingDeviceVulkanShaderBinaryDataBinding { - uint32_t type; - uint32_t binding; - uint32_t stages; - uint32_t length; // Size of arrays (in total elements), or ubos (in bytes * total elements). - uint32_t writable; -}; - -struct RenderingDeviceVulkanShaderBinarySpecializationConstant { - uint32_t type; - uint32_t constant_id; - union { - uint32_t int_value; - float float_value; - bool bool_value; - }; - uint32_t stage_flags; -}; - -struct RenderingDeviceVulkanShaderBinaryData { - uint64_t vertex_input_mask; - uint32_t fragment_output_mask; - uint32_t specialization_constants_count; - uint32_t is_compute; - uint32_t compute_local_size[3]; - uint32_t set_count; - uint32_t push_constant_size; - uint32_t push_constant_vk_stages_mask; - uint32_t stage_count; - uint32_t shader_name_len; -}; - -Vector RenderingDeviceVulkan::shader_compile_binary_from_spirv(const Vector &p_spirv, const String &p_shader_name) { - SpirvReflectionData spirv_data; - if (_reflect_spirv(p_spirv, spirv_data) != OK) { - return Vector(); - } - - ERR_FAIL_COND_V_MSG((uint32_t)spirv_data.uniforms.size() > limits.maxBoundDescriptorSets, Vector(), - "Number of uniform sets is larger than what is supported by the hardware (" + itos(limits.maxBoundDescriptorSets) + ")."); - - // Collect reflection data into binary data. - RenderingDeviceVulkanShaderBinaryData binary_data{}; - Vector> uniform_info; // Set bindings. - Vector specialization_constants; - { - binary_data.vertex_input_mask = spirv_data.vertex_input_mask; - binary_data.fragment_output_mask = spirv_data.fragment_output_mask; - binary_data.specialization_constants_count = spirv_data.specialization_constants.size(); - binary_data.is_compute = spirv_data.is_compute; - binary_data.compute_local_size[0] = spirv_data.compute_local_size[0]; - binary_data.compute_local_size[1] = spirv_data.compute_local_size[1]; - binary_data.compute_local_size[2] = spirv_data.compute_local_size[2]; - binary_data.set_count = spirv_data.uniforms.size(); - binary_data.push_constant_size = spirv_data.push_constant_size; - for (uint32_t i = 0; i < SHADER_STAGE_MAX; i++) { - if (spirv_data.push_constant_stages_mask.has_flag((ShaderStage)(1 << i))) { - binary_data.push_constant_vk_stages_mask |= shader_stage_masks[i]; - } - } - - for (const Vector &spirv_set : spirv_data.uniforms) { - Vector set_bindings; - for (const SpirvReflectionData::Uniform &spirv_uniform : spirv_set) { - RenderingDeviceVulkanShaderBinaryDataBinding binding{}; - binding.type = (uint32_t)spirv_uniform.type; - binding.binding = spirv_uniform.binding; - binding.stages = (uint32_t)spirv_uniform.stages_mask; - binding.length = spirv_uniform.length; - binding.writable = (uint32_t)spirv_uniform.writable; - set_bindings.push_back(binding); - } - uniform_info.push_back(set_bindings); - } - - for (const SpirvReflectionData::SpecializationConstant &spirv_sc : spirv_data.specialization_constants) { - RenderingDeviceVulkanShaderBinarySpecializationConstant spec_constant{}; - spec_constant.type = (uint32_t)spirv_sc.type; - spec_constant.constant_id = spirv_sc.constant_id; - spec_constant.int_value = spirv_sc.int_value; - spec_constant.stage_flags = (uint32_t)spirv_sc.stages_mask; - specialization_constants.push_back(spec_constant); - } - } - - Vector> compressed_stages; - Vector smolv_size; - Vector zstd_size; // If 0, zstd not used. - - uint32_t stages_binary_size = 0; - - bool strip_debug = false; - - for (int i = 0; i < p_spirv.size(); i++) { - smolv::ByteArray smolv; - if (!smolv::Encode(p_spirv[i].spir_v.ptr(), p_spirv[i].spir_v.size(), smolv, strip_debug ? smolv::kEncodeFlagStripDebugInfo : 0)) { - ERR_FAIL_V_MSG(Vector(), "Error compressing shader stage :" + String(shader_stage_names[p_spirv[i].shader_stage])); - } else { - smolv_size.push_back(smolv.size()); - { // zstd. - Vector zstd; - zstd.resize(Compression::get_max_compressed_buffer_size(smolv.size(), Compression::MODE_ZSTD)); - int dst_size = Compression::compress(zstd.ptrw(), &smolv[0], smolv.size(), Compression::MODE_ZSTD); - - if (dst_size > 0 && (uint32_t)dst_size < smolv.size()) { - zstd_size.push_back(dst_size); - zstd.resize(dst_size); - compressed_stages.push_back(zstd); - } else { - Vector smv; - smv.resize(smolv.size()); - memcpy(smv.ptrw(), &smolv[0], smolv.size()); - zstd_size.push_back(0); // Not using zstd. - compressed_stages.push_back(smv); - } - } - } - uint32_t s = compressed_stages[i].size(); - if (s % 4 != 0) { - s += 4 - (s % 4); - } - stages_binary_size += s; - } - - binary_data.specialization_constants_count = specialization_constants.size(); - binary_data.set_count = uniform_info.size(); - binary_data.stage_count = p_spirv.size(); - - CharString shader_name_utf = p_shader_name.utf8(); - - binary_data.shader_name_len = shader_name_utf.length(); - - uint32_t total_size = sizeof(uint32_t) * 3; // Header + version + main datasize;. - total_size += sizeof(RenderingDeviceVulkanShaderBinaryData); - - total_size += binary_data.shader_name_len; - - if ((binary_data.shader_name_len % 4) != 0) { // Alignment rules are really strange. - total_size += 4 - (binary_data.shader_name_len % 4); - } - - for (int i = 0; i < uniform_info.size(); i++) { - total_size += sizeof(uint32_t); - total_size += uniform_info[i].size() * sizeof(RenderingDeviceVulkanShaderBinaryDataBinding); - } - - total_size += sizeof(RenderingDeviceVulkanShaderBinarySpecializationConstant) * specialization_constants.size(); - - total_size += compressed_stages.size() * sizeof(uint32_t) * 3; // Sizes. - total_size += stages_binary_size; - - Vector ret; - ret.resize(total_size); - { - uint32_t offset = 0; - uint8_t *binptr = ret.ptrw(); - binptr[0] = 'G'; - binptr[1] = 'S'; - binptr[2] = 'B'; - binptr[3] = 'D'; // Godot Shader Binary Data. - offset += 4; - encode_uint32(SHADER_BINARY_VERSION, binptr + offset); - offset += sizeof(uint32_t); - encode_uint32(sizeof(RenderingDeviceVulkanShaderBinaryData), binptr + offset); - offset += sizeof(uint32_t); - memcpy(binptr + offset, &binary_data, sizeof(RenderingDeviceVulkanShaderBinaryData)); - offset += sizeof(RenderingDeviceVulkanShaderBinaryData); - - if (binary_data.shader_name_len > 0) { - memcpy(binptr + offset, shader_name_utf.ptr(), binary_data.shader_name_len); - offset += binary_data.shader_name_len; - - if ((binary_data.shader_name_len % 4) != 0) { // Alignment rules are really strange. - offset += 4 - (binary_data.shader_name_len % 4); - } - } - - for (int i = 0; i < uniform_info.size(); i++) { - int count = uniform_info[i].size(); - encode_uint32(count, binptr + offset); - offset += sizeof(uint32_t); - if (count > 0) { - memcpy(binptr + offset, uniform_info[i].ptr(), sizeof(RenderingDeviceVulkanShaderBinaryDataBinding) * count); - offset += sizeof(RenderingDeviceVulkanShaderBinaryDataBinding) * count; - } - } - - if (specialization_constants.size()) { - memcpy(binptr + offset, specialization_constants.ptr(), sizeof(RenderingDeviceVulkanShaderBinarySpecializationConstant) * specialization_constants.size()); - offset += sizeof(RenderingDeviceVulkanShaderBinarySpecializationConstant) * specialization_constants.size(); - } - - for (int i = 0; i < compressed_stages.size(); i++) { - encode_uint32(p_spirv[i].shader_stage, binptr + offset); - offset += sizeof(uint32_t); - encode_uint32(smolv_size[i], binptr + offset); - offset += sizeof(uint32_t); - encode_uint32(zstd_size[i], binptr + offset); - offset += sizeof(uint32_t); - memcpy(binptr + offset, compressed_stages[i].ptr(), compressed_stages[i].size()); - - uint32_t s = compressed_stages[i].size(); - - if (s % 4 != 0) { - s += 4 - (s % 4); - } - - offset += s; - } - - ERR_FAIL_COND_V(offset != (uint32_t)ret.size(), Vector()); - } - - return ret; +Vector RenderingDevice::shader_compile_binary_from_spirv(const Vector &p_spirv, const String &p_shader_name) { + return driver->shader_compile_binary_from_spirv(p_spirv, p_shader_name); } -RID RenderingDeviceVulkan::shader_create_from_bytecode(const Vector &p_shader_binary, RID p_placeholder) { - const uint8_t *binptr = p_shader_binary.ptr(); - uint32_t binsize = p_shader_binary.size(); - - uint32_t read_offset = 0; - // Consistency check. - ERR_FAIL_COND_V(binsize < sizeof(uint32_t) * 3 + sizeof(RenderingDeviceVulkanShaderBinaryData), RID()); - ERR_FAIL_COND_V(binptr[0] != 'G' || binptr[1] != 'S' || binptr[2] != 'B' || binptr[3] != 'D', RID()); - - uint32_t bin_version = decode_uint32(binptr + 4); - ERR_FAIL_COND_V(bin_version != SHADER_BINARY_VERSION, RID()); - - uint32_t bin_data_size = decode_uint32(binptr + 8); - - const RenderingDeviceVulkanShaderBinaryData &binary_data = *(reinterpret_cast(binptr + 12)); - - Shader::PushConstant push_constant; - push_constant.size = binary_data.push_constant_size; - push_constant.vk_stages_mask = binary_data.push_constant_vk_stages_mask; - - uint64_t vertex_input_mask = binary_data.vertex_input_mask; - - uint32_t fragment_output_mask = binary_data.fragment_output_mask; - - bool is_compute = binary_data.is_compute; - - const uint32_t compute_local_size[3] = { binary_data.compute_local_size[0], binary_data.compute_local_size[1], binary_data.compute_local_size[2] }; - - read_offset += sizeof(uint32_t) * 3 + bin_data_size; +RID RenderingDevice::shader_create_from_bytecode(const Vector &p_shader_binary, RID p_placeholder) { + _THREAD_SAFE_METHOD_ + ShaderDescription shader_desc; String name; - - if (binary_data.shader_name_len) { - name.parse_utf8((const char *)(binptr + read_offset), binary_data.shader_name_len); - read_offset += binary_data.shader_name_len; - if ((binary_data.shader_name_len % 4) != 0) { // Alignment rules are really strange. - read_offset += 4 - (binary_data.shader_name_len % 4); - } - } - - Vector> set_bindings; - Vector> uniform_info; - - set_bindings.resize(binary_data.set_count); - uniform_info.resize(binary_data.set_count); - - for (uint32_t i = 0; i < binary_data.set_count; i++) { - ERR_FAIL_COND_V(read_offset + sizeof(uint32_t) >= binsize, RID()); - uint32_t set_count = decode_uint32(binptr + read_offset); - read_offset += sizeof(uint32_t); - const RenderingDeviceVulkanShaderBinaryDataBinding *set_ptr = reinterpret_cast(binptr + read_offset); - uint32_t set_size = set_count * sizeof(RenderingDeviceVulkanShaderBinaryDataBinding); - ERR_FAIL_COND_V(read_offset + set_size >= binsize, RID()); - - for (uint32_t j = 0; j < set_count; j++) { - UniformInfo info; - info.type = UniformType(set_ptr[j].type); - info.writable = set_ptr[j].writable; - info.length = set_ptr[j].length; - info.binding = set_ptr[j].binding; - info.stages = set_ptr[j].stages; - - VkDescriptorSetLayoutBinding layout_binding; - layout_binding.pImmutableSamplers = nullptr; - layout_binding.binding = set_ptr[j].binding; - layout_binding.descriptorCount = 1; - layout_binding.stageFlags = 0; - for (uint32_t k = 0; k < SHADER_STAGE_MAX; k++) { - if (set_ptr[j].stages & (1 << k)) { - layout_binding.stageFlags |= shader_stage_masks[k]; - } - } - - switch (info.type) { - case UNIFORM_TYPE_SAMPLER: { - layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_SAMPLER; - layout_binding.descriptorCount = set_ptr[j].length; - } break; - case UNIFORM_TYPE_SAMPLER_WITH_TEXTURE: { - layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; - layout_binding.descriptorCount = set_ptr[j].length; - } break; - case UNIFORM_TYPE_TEXTURE: { - layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; - layout_binding.descriptorCount = set_ptr[j].length; - } break; - case UNIFORM_TYPE_IMAGE: { - layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE; - layout_binding.descriptorCount = set_ptr[j].length; - } break; - case UNIFORM_TYPE_TEXTURE_BUFFER: { - layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER; - layout_binding.descriptorCount = set_ptr[j].length; - } break; - case UNIFORM_TYPE_IMAGE_BUFFER: { - layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER; - } break; - case UNIFORM_TYPE_UNIFORM_BUFFER: { - layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; - } break; - case UNIFORM_TYPE_STORAGE_BUFFER: { - layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; - } break; - case UNIFORM_TYPE_INPUT_ATTACHMENT: { - layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT; - } break; - default: { - ERR_FAIL_V(RID()); - } - } - - set_bindings.write[i].push_back(layout_binding); - uniform_info.write[i].push_back(info); - } - - read_offset += set_size; - } - - ERR_FAIL_COND_V(read_offset + binary_data.specialization_constants_count * sizeof(RenderingDeviceVulkanShaderBinarySpecializationConstant) >= binsize, RID()); - - Vector specialization_constants; - - for (uint32_t i = 0; i < binary_data.specialization_constants_count; i++) { - const RenderingDeviceVulkanShaderBinarySpecializationConstant &src_sc = *(reinterpret_cast(binptr + read_offset)); - Shader::SpecializationConstant sc; - sc.constant.int_value = src_sc.int_value; - sc.constant.type = PipelineSpecializationConstantType(src_sc.type); - sc.constant.constant_id = src_sc.constant_id; - sc.stage_flags = src_sc.stage_flags; - specialization_constants.push_back(sc); - - read_offset += sizeof(RenderingDeviceVulkanShaderBinarySpecializationConstant); - } - - Vector> stage_spirv_data; - Vector stage_type; - - for (uint32_t i = 0; i < binary_data.stage_count; i++) { - ERR_FAIL_COND_V(read_offset + sizeof(uint32_t) * 3 >= binsize, RID()); - uint32_t stage = decode_uint32(binptr + read_offset); - read_offset += sizeof(uint32_t); - uint32_t smolv_size = decode_uint32(binptr + read_offset); - read_offset += sizeof(uint32_t); - uint32_t zstd_size = decode_uint32(binptr + read_offset); - read_offset += sizeof(uint32_t); - - uint32_t buf_size = (zstd_size > 0) ? zstd_size : smolv_size; - - Vector smolv; - const uint8_t *src_smolv = nullptr; - - if (zstd_size > 0) { - // Decompress to smolv. - smolv.resize(smolv_size); - int dec_smolv_size = Compression::decompress(smolv.ptrw(), smolv.size(), binptr + read_offset, zstd_size, Compression::MODE_ZSTD); - ERR_FAIL_COND_V(dec_smolv_size != (int32_t)smolv_size, RID()); - src_smolv = smolv.ptr(); - } else { - src_smolv = binptr + read_offset; - } - - Vector spirv; - uint32_t spirv_size = smolv::GetDecodedBufferSize(src_smolv, smolv_size); - spirv.resize(spirv_size); - if (!smolv::Decode(src_smolv, smolv_size, spirv.ptrw(), spirv_size)) { - ERR_FAIL_V_MSG(RID(), "Malformed smolv input uncompressing shader stage:" + String(shader_stage_names[stage])); - } - stage_spirv_data.push_back(spirv); - stage_type.push_back(ShaderStage(stage)); - - if (buf_size % 4 != 0) { - buf_size += 4 - (buf_size % 4); - } - - ERR_FAIL_COND_V(read_offset + buf_size > binsize, RID()); - - read_offset += buf_size; - } - - ERR_FAIL_COND_V(read_offset != binsize, RID()); + RDD::ShaderID shader_id = driver->shader_create_from_bytecode(p_shader_binary, shader_desc, name); + ERR_FAIL_COND_V(!shader_id, RID()); // All good, let's create modules. - _THREAD_SAFE_METHOD_ - RID id; if (p_placeholder.is_null()) { id = shader_owner.make_rid(); @@ -5057,146 +2929,30 @@ RID RenderingDeviceVulkan::shader_create_from_bytecode(const Vector &p_ Shader *shader = shader_owner.get_or_null(id); ERR_FAIL_NULL_V(shader, RID()); - shader->vertex_input_mask = vertex_input_mask; - shader->fragment_output_mask = fragment_output_mask; - shader->push_constant = push_constant; - shader->is_compute = is_compute; - shader->compute_local_size[0] = compute_local_size[0]; - shader->compute_local_size[1] = compute_local_size[1]; - shader->compute_local_size[2] = compute_local_size[2]; - shader->specialization_constants = specialization_constants; + *((ShaderDescription *)shader) = shader_desc; // ShaderDescription bundle. shader->name = name; + shader->driver_id = shader_id; - String error_text; + for (int i = 0; i < shader->uniform_sets.size(); i++) { + uint32_t format = 0; // No format, default. - bool success = true; - for (int i = 0; i < stage_spirv_data.size(); i++) { - VkShaderModuleCreateInfo shader_module_create_info; - shader_module_create_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; - shader_module_create_info.pNext = nullptr; - shader_module_create_info.flags = 0; - shader_module_create_info.codeSize = stage_spirv_data[i].size(); - const uint8_t *r = stage_spirv_data[i].ptr(); - - shader_module_create_info.pCode = (const uint32_t *)r; - - VkShaderModule module; - VkResult res = vkCreateShaderModule(device, &shader_module_create_info, nullptr, &module); - if (res) { - success = false; - error_text = "Error (" + itos(res) + ") creating shader module for stage: " + String(shader_stage_names[stage_type[i]]); - break; - } - - VkPipelineShaderStageCreateInfo shader_stage; - shader_stage.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; - shader_stage.pNext = nullptr; - shader_stage.flags = 0; - shader_stage.stage = shader_stage_masks[stage_type[i]]; - shader_stage.module = module; - shader_stage.pName = "main"; - shader_stage.pSpecializationInfo = nullptr; - - shader->pipeline_stages.push_back(shader_stage); - } - // Proceed to create descriptor sets. - - if (success) { - for (int i = 0; i < set_bindings.size(); i++) { - // Empty ones are fine if they were not used according to spec (binding count will be 0). - VkDescriptorSetLayoutCreateInfo layout_create_info; - layout_create_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; - layout_create_info.pNext = nullptr; - layout_create_info.flags = 0; - layout_create_info.bindingCount = set_bindings[i].size(); - layout_create_info.pBindings = set_bindings[i].ptr(); - - VkDescriptorSetLayout layout; - VkResult res = vkCreateDescriptorSetLayout(device, &layout_create_info, nullptr, &layout); - if (res) { - error_text = "Error (" + itos(res) + ") creating descriptor set layout for set " + itos(i); - success = false; - break; - } - - Shader::Set set; - set.descriptor_set_layout = layout; - set.uniform_info = uniform_info[i]; + if (shader->uniform_sets[i].size()) { // Sort and hash. - set.uniform_info.sort(); - uint32_t format = 0; // No format, default. + shader->uniform_sets.write[i].sort(); - if (set.uniform_info.size()) { - // Has data, needs an actual format. - UniformSetFormat usformat; - usformat.uniform_info = set.uniform_info; - RBMap::Element *E = uniform_set_format_cache.find(usformat); - if (E) { - format = E->get(); - } else { - format = uniform_set_format_cache.size() + 1; - uniform_set_format_cache.insert(usformat, format); - } + UniformSetFormat usformat; + usformat.uniforms = shader->uniform_sets[i]; + RBMap::Element *E = uniform_set_format_cache.find(usformat); + if (E) { + format = E->get(); + } else { + format = uniform_set_format_cache.size() + 1; + uniform_set_format_cache.insert(usformat, format); } - - shader->sets.push_back(set); - shader->set_formats.push_back(format); - } - } - - if (success) { - // Create pipeline layout. - VkPipelineLayoutCreateInfo pipeline_layout_create_info; - pipeline_layout_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; - pipeline_layout_create_info.pNext = nullptr; - pipeline_layout_create_info.flags = 0; - pipeline_layout_create_info.setLayoutCount = shader->sets.size(); - - Vector layouts; - layouts.resize(shader->sets.size()); - - for (int i = 0; i < layouts.size(); i++) { - layouts.write[i] = shader->sets[i].descriptor_set_layout; - } - - pipeline_layout_create_info.pSetLayouts = layouts.ptr(); - // Needs to be declared in this outer scope, otherwise it may not outlive its assignment - // to pipeline_layout_create_info. - VkPushConstantRange push_constant_range; - if (push_constant.size) { - push_constant_range.stageFlags = push_constant.vk_stages_mask; - push_constant_range.offset = 0; - push_constant_range.size = push_constant.size; - - pipeline_layout_create_info.pushConstantRangeCount = 1; - pipeline_layout_create_info.pPushConstantRanges = &push_constant_range; - } else { - pipeline_layout_create_info.pushConstantRangeCount = 0; - pipeline_layout_create_info.pPushConstantRanges = nullptr; - } - - VkResult err = vkCreatePipelineLayout(device, &pipeline_layout_create_info, nullptr, &shader->pipeline_layout); - - if (err) { - error_text = "Error (" + itos(err) + ") creating pipeline layout."; - success = false; - } - } - - if (!success) { - // Clean up if failed. - for (int i = 0; i < shader->pipeline_stages.size(); i++) { - vkDestroyShaderModule(device, shader->pipeline_stages[i].module, nullptr); - } - - for (int i = 0; i < shader->sets.size(); i++) { - vkDestroyDescriptorSetLayout(device, shader->sets[i].descriptor_set_layout, nullptr); } - shader_owner.free(id); - - ERR_FAIL_V_MSG(RID(), error_text); + shader->set_formats.push_back(format); } #ifdef DEV_ENABLED @@ -5205,12 +2961,12 @@ RID RenderingDeviceVulkan::shader_create_from_bytecode(const Vector &p_ return id; } -RID RenderingDeviceVulkan::shader_create_placeholder() { +RID RenderingDevice::shader_create_placeholder() { Shader shader; return shader_owner.make_rid(shader); } -uint64_t RenderingDeviceVulkan::shader_get_vertex_input_attribute_mask(RID p_shader) { +uint64_t RenderingDevice::shader_get_vertex_input_attribute_mask(RID p_shader) { _THREAD_SAFE_METHOD_ const Shader *shader = shader_owner.get_or_null(p_shader); @@ -5222,210 +2978,39 @@ uint64_t RenderingDeviceVulkan::shader_get_vertex_input_attribute_mask(RID p_sha /**** UNIFORMS ****/ /******************/ -RID RenderingDeviceVulkan::uniform_buffer_create(uint32_t p_size_bytes, const Vector &p_data) { +RID RenderingDevice::uniform_buffer_create(uint32_t p_size_bytes, const Vector &p_data) { _THREAD_SAFE_METHOD_ ERR_FAIL_COND_V(p_data.size() && (uint32_t)p_data.size() != p_size_bytes, RID()); Buffer buffer; - Error err = _buffer_allocate(&buffer, p_size_bytes, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE, 0); - ERR_FAIL_COND_V(err != OK, RID()); - if (p_data.size()) { - uint64_t data_size = p_data.size(); - const uint8_t *r = p_data.ptr(); - _buffer_update(&buffer, 0, r, data_size); - _buffer_memory_barrier(buffer.buffer, 0, data_size, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_UNIFORM_READ_BIT, false); - } - RID id = uniform_buffer_owner.make_rid(buffer); -#ifdef DEV_ENABLED - set_resource_name(id, "RID:" + itos(id.get_id())); -#endif - return id; -} - -RID RenderingDeviceVulkan::storage_buffer_create(uint32_t p_size_bytes, const Vector &p_data, BitField p_usage) { - _THREAD_SAFE_METHOD_ - - ERR_FAIL_COND_V(p_data.size() && (uint32_t)p_data.size() != p_size_bytes, RID()); - - Buffer buffer; - uint32_t flags = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT; - if (p_usage.has_flag(STORAGE_BUFFER_USAGE_DISPATCH_INDIRECT)) { - flags |= VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT; - } - Error err = _buffer_allocate(&buffer, p_size_bytes, flags, VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE, 0); - ERR_FAIL_COND_V(err != OK, RID()); + buffer.size = p_size_bytes; + buffer.usage = (RDD::BUFFER_USAGE_TRANSFER_TO_BIT | RDD::BUFFER_USAGE_UNIFORM_BIT); + buffer.driver_id = driver->buffer_create(buffer.size, buffer.usage, RDD::MEMORY_ALLOCATION_TYPE_GPU); + ERR_FAIL_COND_V(!buffer.driver_id, RID()); if (p_data.size()) { uint64_t data_size = p_data.size(); const uint8_t *r = p_data.ptr(); _buffer_update(&buffer, 0, r, data_size); - _buffer_memory_barrier(buffer.buffer, 0, data_size, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT, false); + RDD::BufferBarrier bb; + bb.buffer = buffer.driver_id; + bb.src_access = RDD::BARRIER_ACCESS_TRANSFER_WRITE_BIT; + bb.dst_access = RDD::BARRIER_ACCESS_UNIFORM_READ_BIT; + bb.size = data_size; + driver->command_pipeline_barrier(frames[frame].setup_command_buffer, RDD::PIPELINE_STAGE_TRANSFER_BIT, RDD::PIPELINE_STAGE_VERTEX_SHADER_BIT | RDD::PIPELINE_STAGE_FRAGMENT_SHADER_BIT | RDD::PIPELINE_STAGE_COMPUTE_SHADER_BIT, {}, bb, {}); } - return storage_buffer_owner.make_rid(buffer); -} - -RID RenderingDeviceVulkan::texture_buffer_create(uint32_t p_size_elements, DataFormat p_format, const Vector &p_data) { - _THREAD_SAFE_METHOD_ - - uint32_t element_size = get_format_vertex_size(p_format); - ERR_FAIL_COND_V_MSG(element_size == 0, RID(), "Format requested is not supported for texture buffers"); - uint64_t size_bytes = uint64_t(element_size) * p_size_elements; - ERR_FAIL_COND_V(p_data.size() && (uint32_t)p_data.size() != size_bytes, RID()); + buffer_memory += buffer.size; - TextureBuffer texture_buffer; - Error err = _buffer_allocate(&texture_buffer.buffer, size_bytes, VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT, VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE, 0); - ERR_FAIL_COND_V(err != OK, RID()); - - if (p_data.size()) { - uint64_t data_size = p_data.size(); - const uint8_t *r = p_data.ptr(); - _buffer_update(&texture_buffer.buffer, 0, r, data_size); - _buffer_memory_barrier(texture_buffer.buffer.buffer, 0, data_size, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT, false); - } - - VkBufferViewCreateInfo view_create_info; - view_create_info.sType = VK_STRUCTURE_TYPE_BUFFER_VIEW_CREATE_INFO; - view_create_info.pNext = nullptr; - view_create_info.flags = 0; - view_create_info.buffer = texture_buffer.buffer.buffer; - view_create_info.format = vulkan_formats[p_format]; - view_create_info.offset = 0; - view_create_info.range = size_bytes; - - texture_buffer.view = VK_NULL_HANDLE; - - VkResult res = vkCreateBufferView(device, &view_create_info, nullptr, &texture_buffer.view); - if (res) { - _buffer_free(&texture_buffer.buffer); - ERR_FAIL_V_MSG(RID(), "Unable to create buffer view, error " + itos(res) + "."); - } - - // Allocate the view. - RID id = texture_buffer_owner.make_rid(texture_buffer); + RID id = uniform_buffer_owner.make_rid(buffer); #ifdef DEV_ENABLED set_resource_name(id, "RID:" + itos(id.get_id())); #endif return id; } -RenderingDeviceVulkan::DescriptorPool *RenderingDeviceVulkan::_descriptor_pool_allocate(const DescriptorPoolKey &p_key) { - if (!descriptor_pools.has(p_key)) { - descriptor_pools[p_key] = HashSet(); - } - - DescriptorPool *pool = nullptr; - - for (DescriptorPool *E : descriptor_pools[p_key]) { - if (E->usage < max_descriptors_per_pool) { - pool = E; - break; - } - } - - if (!pool) { - // Create a new one. - pool = memnew(DescriptorPool); - pool->usage = 0; - - VkDescriptorPoolCreateInfo descriptor_pool_create_info; - descriptor_pool_create_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; - descriptor_pool_create_info.pNext = nullptr; - descriptor_pool_create_info.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT; // Can't think how somebody may NOT need this flag. - descriptor_pool_create_info.maxSets = max_descriptors_per_pool; - Vector sizes; - // Here comes more vulkan API strangeness. - - if (p_key.uniform_type[UNIFORM_TYPE_SAMPLER]) { - VkDescriptorPoolSize s; - s.type = VK_DESCRIPTOR_TYPE_SAMPLER; - s.descriptorCount = p_key.uniform_type[UNIFORM_TYPE_SAMPLER] * max_descriptors_per_pool; - sizes.push_back(s); - } - if (p_key.uniform_type[UNIFORM_TYPE_SAMPLER_WITH_TEXTURE]) { - VkDescriptorPoolSize s; - s.type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; - s.descriptorCount = p_key.uniform_type[UNIFORM_TYPE_SAMPLER_WITH_TEXTURE] * max_descriptors_per_pool; - sizes.push_back(s); - } - if (p_key.uniform_type[UNIFORM_TYPE_TEXTURE]) { - VkDescriptorPoolSize s; - s.type = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; - s.descriptorCount = p_key.uniform_type[UNIFORM_TYPE_TEXTURE] * max_descriptors_per_pool; - sizes.push_back(s); - } - if (p_key.uniform_type[UNIFORM_TYPE_IMAGE]) { - VkDescriptorPoolSize s; - s.type = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE; - s.descriptorCount = p_key.uniform_type[UNIFORM_TYPE_IMAGE] * max_descriptors_per_pool; - sizes.push_back(s); - } - if (p_key.uniform_type[UNIFORM_TYPE_TEXTURE_BUFFER] || p_key.uniform_type[UNIFORM_TYPE_SAMPLER_WITH_TEXTURE_BUFFER]) { - VkDescriptorPoolSize s; - s.type = VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER; - s.descriptorCount = (p_key.uniform_type[UNIFORM_TYPE_TEXTURE_BUFFER] + p_key.uniform_type[UNIFORM_TYPE_SAMPLER_WITH_TEXTURE_BUFFER]) * max_descriptors_per_pool; - sizes.push_back(s); - } - if (p_key.uniform_type[UNIFORM_TYPE_IMAGE_BUFFER]) { - VkDescriptorPoolSize s; - s.type = VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER; - s.descriptorCount = p_key.uniform_type[UNIFORM_TYPE_IMAGE_BUFFER] * max_descriptors_per_pool; - sizes.push_back(s); - } - if (p_key.uniform_type[UNIFORM_TYPE_UNIFORM_BUFFER]) { - VkDescriptorPoolSize s; - s.type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; - s.descriptorCount = p_key.uniform_type[UNIFORM_TYPE_UNIFORM_BUFFER] * max_descriptors_per_pool; - sizes.push_back(s); - } - - if (p_key.uniform_type[UNIFORM_TYPE_STORAGE_BUFFER]) { - VkDescriptorPoolSize s; - s.type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; - s.descriptorCount = p_key.uniform_type[UNIFORM_TYPE_STORAGE_BUFFER] * max_descriptors_per_pool; - sizes.push_back(s); - } - - if (p_key.uniform_type[UNIFORM_TYPE_INPUT_ATTACHMENT]) { - VkDescriptorPoolSize s; - s.type = VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT; - s.descriptorCount = p_key.uniform_type[UNIFORM_TYPE_INPUT_ATTACHMENT] * max_descriptors_per_pool; - sizes.push_back(s); - } - - descriptor_pool_create_info.poolSizeCount = sizes.size(); - descriptor_pool_create_info.pPoolSizes = sizes.ptr(); - VkResult res = vkCreateDescriptorPool(device, &descriptor_pool_create_info, nullptr, &pool->pool); - if (res) { - memdelete(pool); - ERR_FAIL_COND_V_MSG(res, nullptr, "vkCreateDescriptorPool failed with error " + itos(res) + "."); - } - descriptor_pools[p_key].insert(pool); - } - - pool->usage++; - - return pool; -} - -void RenderingDeviceVulkan::_descriptor_pool_free(const DescriptorPoolKey &p_key, DescriptorPool *p_pool) { -#ifdef DEBUG_ENABLED - ERR_FAIL_COND(!descriptor_pools[p_key].has(p_pool)); -#endif - ERR_FAIL_COND(p_pool->usage == 0); - p_pool->usage--; - if (p_pool->usage == 0) { - vkDestroyDescriptorPool(device, p_pool->pool, nullptr); - descriptor_pools[p_key].erase(p_pool); - memdelete(p_pool); - if (descriptor_pools[p_key].is_empty()) { - descriptor_pools.erase(p_key); - } - } -} - -RID RenderingDeviceVulkan::uniform_set_create(const Vector &p_uniforms, RID p_shader, uint32_t p_shader_set) { +RID RenderingDevice::uniform_set_create(const Vector &p_uniforms, RID p_shader, uint32_t p_shader_set) { _THREAD_SAFE_METHOD_ ERR_FAIL_COND_V(p_uniforms.size() == 0, RID()); @@ -5433,32 +3018,28 @@ RID RenderingDeviceVulkan::uniform_set_create(const Vector &p_uniforms, Shader *shader = shader_owner.get_or_null(p_shader); ERR_FAIL_NULL_V(shader, RID()); - ERR_FAIL_COND_V_MSG(p_shader_set >= (uint32_t)shader->sets.size() || shader->sets[p_shader_set].uniform_info.size() == 0, RID(), + ERR_FAIL_COND_V_MSG(p_shader_set >= (uint32_t)shader->uniform_sets.size() || shader->uniform_sets[p_shader_set].size() == 0, RID(), "Desired set (" + itos(p_shader_set) + ") not used by shader."); // See that all sets in shader are satisfied. - const Shader::Set &set = shader->sets[p_shader_set]; + const Vector &set = shader->uniform_sets[p_shader_set]; uint32_t uniform_count = p_uniforms.size(); const Uniform *uniforms = p_uniforms.ptr(); - uint32_t set_uniform_count = set.uniform_info.size(); - const UniformInfo *set_uniforms = set.uniform_info.ptr(); + uint32_t set_uniform_count = set.size(); + const ShaderUniform *set_uniforms = set.ptr(); - Vector writes; - DescriptorPoolKey pool_key; + LocalVector driver_uniforms; + driver_uniforms.resize(set_uniform_count); - // To keep them alive until update call. - List> buffer_infos; - List> buffer_views; - List> image_infos; // Used for verification to make sure a uniform set does not use a framebuffer bound texture. LocalVector attachable_textures; Vector mutable_sampled_textures; Vector mutable_storage_textures; for (uint32_t i = 0; i < set_uniform_count; i++) { - const UniformInfo &set_uniform = set_uniforms[i]; + const ShaderUniform &set_uniform = set_uniforms[i]; int uniform_idx = -1; for (int j = 0; j < (int)uniform_count; j++) { if (uniforms[j].binding == set_uniform.binding) { @@ -5471,20 +3052,11 @@ RID RenderingDeviceVulkan::uniform_set_create(const Vector &p_uniforms, const Uniform &uniform = uniforms[uniform_idx]; ERR_FAIL_COND_V_MSG(uniform.uniform_type != set_uniform.type, RID(), - "Mismatch uniform type for binding (" + itos(set_uniform.binding) + "), set (" + itos(p_shader_set) + "). Expected '" + shader_uniform_names[set_uniform.type] + "', supplied: '" + shader_uniform_names[uniform.uniform_type] + "'."); - - VkWriteDescriptorSet write; // Common header. - write.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; - write.pNext = nullptr; - write.dstSet = VK_NULL_HANDLE; // Will assign afterwards when everything is valid. - write.dstBinding = set_uniform.binding; - write.dstArrayElement = 0; - write.descriptorCount = 0; - write.descriptorType = VK_DESCRIPTOR_TYPE_MAX_ENUM; // Invalid value. - write.pImageInfo = nullptr; - write.pBufferInfo = nullptr; - write.pTexelBufferView = nullptr; - uint32_t type_size = 1; + "Mismatch uniform type for binding (" + itos(set_uniform.binding) + "), set (" + itos(p_shader_set) + "). Expected '" + SHADER_UNIFORM_NAMES[set_uniform.type] + "', supplied: '" + SHADER_UNIFORM_NAMES[uniform.uniform_type] + "'."); + + RDD::BoundUniform &driver_uniform = driver_uniforms[i]; + driver_uniform.type = uniform.uniform_type; + driver_uniform.binding = uniform.binding; switch (uniform.uniform_type) { case UNIFORM_TYPE_SAMPLER: { @@ -5496,29 +3068,12 @@ RID RenderingDeviceVulkan::uniform_set_create(const Vector &p_uniforms, } } - Vector image_info; - for (uint32_t j = 0; j < uniform.get_id_count(); j++) { - VkSampler *sampler = sampler_owner.get_or_null(uniform.get_id(j)); - ERR_FAIL_NULL_V_MSG(sampler, RID(), "Sampler (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") is not a valid sampler."); + RDD::SamplerID *sampler_driver_id = sampler_owner.get_or_null(uniform.get_id(j)); + ERR_FAIL_COND_V_MSG(!sampler_driver_id, RID(), "Sampler (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") is not a valid sampler."); - VkDescriptorImageInfo img_info; - img_info.sampler = *sampler; - img_info.imageView = VK_NULL_HANDLE; - img_info.imageLayout = VK_IMAGE_LAYOUT_UNDEFINED; - - image_info.push_back(img_info); + driver_uniform.ids.push_back(*sampler_driver_id); } - - write.dstArrayElement = 0; - write.descriptorCount = uniform.get_id_count(); - write.descriptorType = VK_DESCRIPTOR_TYPE_SAMPLER; - write.pImageInfo = image_infos.push_back(image_info)->get().ptr(); - write.pBufferInfo = nullptr; - write.pTexelBufferView = nullptr; - - type_size = uniform.get_id_count(); - } break; case UNIFORM_TYPE_SAMPLER_WITH_TEXTURE: { if (uniform.get_id_count() != (uint32_t)set_uniform.length * 2) { @@ -5529,11 +3084,9 @@ RID RenderingDeviceVulkan::uniform_set_create(const Vector &p_uniforms, } } - Vector image_info; - for (uint32_t j = 0; j < uniform.get_id_count(); j += 2) { - VkSampler *sampler = sampler_owner.get_or_null(uniform.get_id(j + 0)); - ERR_FAIL_NULL_V_MSG(sampler, RID(), "SamplerBuffer (binding: " + itos(uniform.binding) + ", index " + itos(j + 1) + ") is not a valid sampler."); + RDD::SamplerID *sampler_driver_id = sampler_owner.get_or_null(uniform.get_id(j + 0)); + ERR_FAIL_COND_V_MSG(!sampler_driver_id, RID(), "SamplerBuffer (binding: " + itos(uniform.binding) + ", index " + itos(j + 1) + ") is not a valid sampler."); Texture *texture = texture_owner.get_or_null(uniform.get_id(j + 1)); ERR_FAIL_NULL_V_MSG(texture, RID(), "Texture (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") is not a valid texture."); @@ -5541,38 +3094,22 @@ RID RenderingDeviceVulkan::uniform_set_create(const Vector &p_uniforms, ERR_FAIL_COND_V_MSG(!(texture->usage_flags & TEXTURE_USAGE_SAMPLING_BIT), RID(), "Texture (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") needs the TEXTURE_USAGE_SAMPLING_BIT usage flag set in order to be used as uniform."); - VkDescriptorImageInfo img_info; - img_info.sampler = *sampler; - img_info.imageView = texture->view; - - if (texture->usage_flags & (TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | TEXTURE_USAGE_INPUT_ATTACHMENT_BIT)) { + if ((texture->usage_flags & (TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | TEXTURE_USAGE_INPUT_ATTACHMENT_BIT))) { UniformSet::AttachableTexture attachable_texture; attachable_texture.bind = set_uniform.binding; attachable_texture.texture = texture->owner.is_valid() ? texture->owner : uniform.get_id(j + 1); attachable_textures.push_back(attachable_texture); } - if (texture->usage_flags & TEXTURE_USAGE_STORAGE_BIT) { - // Can also be used as storage, add to mutable sampled. + if ((texture->usage_flags & TEXTURE_USAGE_STORAGE_BIT)) { mutable_sampled_textures.push_back(texture); } DEV_ASSERT(!texture->owner.is_valid() || texture_owner.get_or_null(texture->owner)); - img_info.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; - - image_info.push_back(img_info); + driver_uniform.ids.push_back(*sampler_driver_id); + driver_uniform.ids.push_back(texture->driver_id); } - - write.dstArrayElement = 0; - write.descriptorCount = uniform.get_id_count() / 2; - write.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; - write.pImageInfo = image_infos.push_back(image_info)->get().ptr(); - write.pBufferInfo = nullptr; - write.pTexelBufferView = nullptr; - - type_size = uniform.get_id_count() / 2; - } break; case UNIFORM_TYPE_TEXTURE: { if (uniform.get_id_count() != (uint32_t)set_uniform.length) { @@ -5583,8 +3120,6 @@ RID RenderingDeviceVulkan::uniform_set_create(const Vector &p_uniforms, } } - Vector image_info; - for (uint32_t j = 0; j < uniform.get_id_count(); j++) { Texture *texture = texture_owner.get_or_null(uniform.get_id(j)); ERR_FAIL_NULL_V_MSG(texture, RID(), "Texture (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") is not a valid texture."); @@ -5592,37 +3127,21 @@ RID RenderingDeviceVulkan::uniform_set_create(const Vector &p_uniforms, ERR_FAIL_COND_V_MSG(!(texture->usage_flags & TEXTURE_USAGE_SAMPLING_BIT), RID(), "Texture (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") needs the TEXTURE_USAGE_SAMPLING_BIT usage flag set in order to be used as uniform."); - VkDescriptorImageInfo img_info; - img_info.sampler = VK_NULL_HANDLE; - img_info.imageView = texture->view; - - if (texture->usage_flags & (TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | TEXTURE_USAGE_INPUT_ATTACHMENT_BIT)) { + if ((texture->usage_flags & (TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | TEXTURE_USAGE_INPUT_ATTACHMENT_BIT))) { UniformSet::AttachableTexture attachable_texture; attachable_texture.bind = set_uniform.binding; attachable_texture.texture = texture->owner.is_valid() ? texture->owner : uniform.get_id(j); attachable_textures.push_back(attachable_texture); } - if (texture->usage_flags & TEXTURE_USAGE_STORAGE_BIT) { - // Can also be used as storage, add to mutable sampled. + if ((texture->usage_flags & TEXTURE_USAGE_STORAGE_BIT)) { mutable_sampled_textures.push_back(texture); } DEV_ASSERT(!texture->owner.is_valid() || texture_owner.get_or_null(texture->owner)); - img_info.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; - - image_info.push_back(img_info); + driver_uniform.ids.push_back(texture->driver_id); } - - write.dstArrayElement = 0; - write.descriptorCount = uniform.get_id_count(); - write.descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; - write.pImageInfo = image_infos.push_back(image_info)->get().ptr(); - write.pBufferInfo = nullptr; - write.pTexelBufferView = nullptr; - - type_size = uniform.get_id_count(); } break; case UNIFORM_TYPE_IMAGE: { if (uniform.get_id_count() != (uint32_t)set_uniform.length) { @@ -5633,8 +3152,6 @@ RID RenderingDeviceVulkan::uniform_set_create(const Vector &p_uniforms, } } - Vector image_info; - for (uint32_t j = 0; j < uniform.get_id_count(); j++) { Texture *texture = texture_owner.get_or_null(uniform.get_id(j)); @@ -5644,31 +3161,14 @@ RID RenderingDeviceVulkan::uniform_set_create(const Vector &p_uniforms, ERR_FAIL_COND_V_MSG(!(texture->usage_flags & TEXTURE_USAGE_STORAGE_BIT), RID(), "Image (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") needs the TEXTURE_USAGE_STORAGE_BIT usage flag set in order to be used as uniform."); - VkDescriptorImageInfo img_info; - img_info.sampler = VK_NULL_HANDLE; - img_info.imageView = texture->view; - - if (texture->usage_flags & TEXTURE_USAGE_SAMPLING_BIT) { - // Can also be used as storage, add to mutable sampled. + if ((texture->usage_flags & TEXTURE_USAGE_SAMPLING_BIT)) { mutable_storage_textures.push_back(texture); } DEV_ASSERT(!texture->owner.is_valid() || texture_owner.get_or_null(texture->owner)); - img_info.imageLayout = VK_IMAGE_LAYOUT_GENERAL; - - image_info.push_back(img_info); + driver_uniform.ids.push_back(texture->driver_id); } - - write.dstArrayElement = 0; - write.descriptorCount = uniform.get_id_count(); - write.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE; - write.pImageInfo = image_infos.push_back(image_info)->get().ptr(); - write.pBufferInfo = nullptr; - write.pTexelBufferView = nullptr; - - type_size = uniform.get_id_count(); - } break; case UNIFORM_TYPE_TEXTURE_BUFFER: { if (uniform.get_id_count() != (uint32_t)set_uniform.length) { @@ -5679,26 +3179,12 @@ RID RenderingDeviceVulkan::uniform_set_create(const Vector &p_uniforms, } } - Vector buffer_info; - Vector buffer_view; - for (uint32_t j = 0; j < uniform.get_id_count(); j++) { - TextureBuffer *buffer = texture_buffer_owner.get_or_null(uniform.get_id(j)); + Buffer *buffer = texture_buffer_owner.get_or_null(uniform.get_id(j)); ERR_FAIL_NULL_V_MSG(buffer, RID(), "Texture Buffer (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") is not a valid texture buffer."); - buffer_info.push_back(buffer->buffer.buffer_info); - buffer_view.push_back(buffer->view); + driver_uniform.ids.push_back(buffer->driver_id); } - - write.dstArrayElement = 0; - write.descriptorCount = uniform.get_id_count(); - write.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER; - write.pImageInfo = nullptr; - write.pBufferInfo = buffer_infos.push_back(buffer_info)->get().ptr(); - write.pTexelBufferView = buffer_views.push_back(buffer_view)->get().ptr(); - - type_size = uniform.get_id_count(); - } break; case UNIFORM_TYPE_SAMPLER_WITH_TEXTURE_BUFFER: { if (uniform.get_id_count() != (uint32_t)set_uniform.length * 2) { @@ -5709,41 +3195,19 @@ RID RenderingDeviceVulkan::uniform_set_create(const Vector &p_uniforms, } } - Vector image_info; - Vector buffer_info; - Vector buffer_view; - for (uint32_t j = 0; j < uniform.get_id_count(); j += 2) { - VkSampler *sampler = sampler_owner.get_or_null(uniform.get_id(j + 0)); - ERR_FAIL_NULL_V_MSG(sampler, RID(), "SamplerBuffer (binding: " + itos(uniform.binding) + ", index " + itos(j + 1) + ") is not a valid sampler."); - - TextureBuffer *buffer = texture_buffer_owner.get_or_null(uniform.get_id(j + 1)); - - VkDescriptorImageInfo img_info; - img_info.sampler = *sampler; - img_info.imageView = VK_NULL_HANDLE; - img_info.imageLayout = VK_IMAGE_LAYOUT_UNDEFINED; - - image_info.push_back(img_info); + RDD::SamplerID *sampler_driver_id = sampler_owner.get_or_null(uniform.get_id(j + 0)); + ERR_FAIL_COND_V_MSG(!sampler_driver_id, RID(), "SamplerBuffer (binding: " + itos(uniform.binding) + ", index " + itos(j + 1) + ") is not a valid sampler."); + Buffer *buffer = texture_buffer_owner.get_or_null(uniform.get_id(j + 1)); ERR_FAIL_NULL_V_MSG(buffer, RID(), "SamplerBuffer (binding: " + itos(uniform.binding) + ", index " + itos(j + 1) + ") is not a valid texture buffer."); - buffer_info.push_back(buffer->buffer.buffer_info); - buffer_view.push_back(buffer->view); + driver_uniform.ids.push_back(*sampler_driver_id); + driver_uniform.ids.push_back(buffer->driver_id); } - - write.dstArrayElement = 0; - write.descriptorCount = uniform.get_id_count() / 2; - write.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER; - write.pImageInfo = image_infos.push_back(image_info)->get().ptr(); - write.pBufferInfo = buffer_infos.push_back(buffer_info)->get().ptr(); - write.pTexelBufferView = buffer_views.push_back(buffer_view)->get().ptr(); - - type_size = uniform.get_id_count() / 2; } break; case UNIFORM_TYPE_IMAGE_BUFFER: { // Todo. - } break; case UNIFORM_TYPE_UNIFORM_BUFFER: { ERR_FAIL_COND_V_MSG(uniform.get_id_count() != 1, RID(), @@ -5753,366 +3217,106 @@ RID RenderingDeviceVulkan::uniform_set_create(const Vector &p_uniforms, ERR_FAIL_NULL_V_MSG(buffer, RID(), "Uniform buffer supplied (binding: " + itos(uniform.binding) + ") is invalid."); ERR_FAIL_COND_V_MSG(buffer->size < (uint32_t)set_uniform.length, RID(), - "Uniform buffer supplied (binding: " + itos(uniform.binding) + ") size (" + itos(buffer->size) + " is smaller than size of shader uniform: (" + itos(set_uniform.length) + ")."); - - write.dstArrayElement = 0; - write.descriptorCount = 1; - write.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; - write.pImageInfo = nullptr; - write.pBufferInfo = &buffer->buffer_info; - write.pTexelBufferView = nullptr; - - } break; - case UNIFORM_TYPE_STORAGE_BUFFER: { - ERR_FAIL_COND_V_MSG(uniform.get_id_count() != 1, RID(), - "Storage buffer supplied (binding: " + itos(uniform.binding) + ") must provide one ID (" + itos(uniform.get_id_count()) + " provided)."); - - Buffer *buffer = nullptr; - - if (storage_buffer_owner.owns(uniform.get_id(0))) { - buffer = storage_buffer_owner.get_or_null(uniform.get_id(0)); - } else if (vertex_buffer_owner.owns(uniform.get_id(0))) { - buffer = vertex_buffer_owner.get_or_null(uniform.get_id(0)); - - ERR_FAIL_COND_V_MSG(!(buffer->usage & VK_BUFFER_USAGE_STORAGE_BUFFER_BIT), RID(), "Vertex buffer supplied (binding: " + itos(uniform.binding) + ") was not created with storage flag."); - } - ERR_FAIL_NULL_V_MSG(buffer, RID(), "Storage buffer supplied (binding: " + itos(uniform.binding) + ") is invalid."); - - // If 0, then it's sized on link time. - ERR_FAIL_COND_V_MSG(set_uniform.length > 0 && buffer->size != (uint32_t)set_uniform.length, RID(), - "Storage buffer supplied (binding: " + itos(uniform.binding) + ") size (" + itos(buffer->size) + " does not match size of shader uniform: (" + itos(set_uniform.length) + ")."); - - write.dstArrayElement = 0; - write.descriptorCount = 1; - write.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; - write.pImageInfo = nullptr; - write.pBufferInfo = &buffer->buffer_info; - write.pTexelBufferView = nullptr; - } break; - case UNIFORM_TYPE_INPUT_ATTACHMENT: { - ERR_FAIL_COND_V_MSG(shader->is_compute, RID(), "InputAttachment (binding: " + itos(uniform.binding) + ") supplied for compute shader (this is not allowed)."); - - if (uniform.get_id_count() != (uint32_t)set_uniform.length) { - if (set_uniform.length > 1) { - ERR_FAIL_V_MSG(RID(), "InputAttachment (binding: " + itos(uniform.binding) + ") is an array of (" + itos(set_uniform.length) + ") textures, so it should be provided equal number of texture IDs to satisfy it (IDs provided: " + itos(uniform.get_id_count()) + ")."); - } else { - ERR_FAIL_V_MSG(RID(), "InputAttachment (binding: " + itos(uniform.binding) + ") should provide one ID referencing a texture (IDs provided: " + itos(uniform.get_id_count()) + ")."); - } - } - - Vector image_info; - - for (uint32_t j = 0; j < uniform.get_id_count(); j++) { - Texture *texture = texture_owner.get_or_null(uniform.get_id(j)); - - ERR_FAIL_NULL_V_MSG(texture, RID(), - "InputAttachment (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") is not a valid texture."); - - ERR_FAIL_COND_V_MSG(!(texture->usage_flags & TEXTURE_USAGE_SAMPLING_BIT), RID(), - "InputAttachment (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") needs the TEXTURE_USAGE_SAMPLING_BIT usage flag set in order to be used as uniform."); - - VkDescriptorImageInfo img_info; - img_info.sampler = VK_NULL_HANDLE; - img_info.imageView = texture->view; - - DEV_ASSERT(!texture->owner.is_valid() || texture_owner.get_or_null(texture->owner)); - - img_info.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; - - image_info.push_back(img_info); - } - - write.dstArrayElement = 0; - write.descriptorCount = uniform.get_id_count(); - write.descriptorType = VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT; - write.pImageInfo = image_infos.push_back(image_info)->get().ptr(); - write.pBufferInfo = nullptr; - write.pTexelBufferView = nullptr; - - type_size = uniform.get_id_count(); - } break; - default: { - } - } - - writes.push_back(write); - - ERR_FAIL_COND_V_MSG(pool_key.uniform_type[set_uniform.type] == MAX_DESCRIPTOR_POOL_ELEMENT, RID(), - "Uniform set reached the limit of bindings for the same type (" + itos(MAX_DESCRIPTOR_POOL_ELEMENT) + ")."); - pool_key.uniform_type[set_uniform.type] += type_size; - } - - // Need a descriptor pool. - DescriptorPool *pool = _descriptor_pool_allocate(pool_key); - - ERR_FAIL_NULL_V(pool, RID()); - - VkDescriptorSetAllocateInfo descriptor_set_allocate_info; - - descriptor_set_allocate_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; - descriptor_set_allocate_info.pNext = nullptr; - descriptor_set_allocate_info.descriptorPool = pool->pool; - descriptor_set_allocate_info.descriptorSetCount = 1; - descriptor_set_allocate_info.pSetLayouts = &shader->sets[p_shader_set].descriptor_set_layout; - - VkDescriptorSet descriptor_set; - - VkResult res = vkAllocateDescriptorSets(device, &descriptor_set_allocate_info, &descriptor_set); - if (res) { - _descriptor_pool_free(pool_key, pool); // Meh. - ERR_FAIL_V_MSG(RID(), "Cannot allocate descriptor sets, error " + itos(res) + "."); - } - - UniformSet uniform_set; - uniform_set.pool = pool; - uniform_set.pool_key = pool_key; - uniform_set.descriptor_set = descriptor_set; - uniform_set.format = shader->set_formats[p_shader_set]; - uniform_set.attachable_textures = attachable_textures; - uniform_set.mutable_sampled_textures = mutable_sampled_textures; - uniform_set.mutable_storage_textures = mutable_storage_textures; - uniform_set.shader_set = p_shader_set; - uniform_set.shader_id = p_shader; - - RID id = uniform_set_owner.make_rid(uniform_set); -#ifdef DEV_ENABLED - set_resource_name(id, "RID:" + itos(id.get_id())); -#endif - // Add dependencies. - _add_dependency(id, p_shader); - for (uint32_t i = 0; i < uniform_count; i++) { - const Uniform &uniform = uniforms[i]; - int id_count = uniform.get_id_count(); - for (int j = 0; j < id_count; j++) { - _add_dependency(id, uniform.get_id(j)); - } - } - - // Write the contents. - if (writes.size()) { - for (int i = 0; i < writes.size(); i++) { - writes.write[i].dstSet = descriptor_set; - } - vkUpdateDescriptorSets(device, writes.size(), writes.ptr(), 0, nullptr); - } - - return id; -} - -bool RenderingDeviceVulkan::uniform_set_is_valid(RID p_uniform_set) { - return uniform_set_owner.owns(p_uniform_set); -} - -void RenderingDeviceVulkan::uniform_set_set_invalidation_callback(RID p_uniform_set, InvalidationCallback p_callback, void *p_userdata) { - UniformSet *us = uniform_set_owner.get_or_null(p_uniform_set); - ERR_FAIL_NULL(us); - us->invalidated_callback = p_callback; - us->invalidated_callback_userdata = p_userdata; -} - -Error RenderingDeviceVulkan::buffer_copy(RID p_src_buffer, RID p_dst_buffer, uint32_t p_src_offset, uint32_t p_dst_offset, uint32_t p_size, BitField p_post_barrier) { - _THREAD_SAFE_METHOD_ - - ERR_FAIL_COND_V_MSG(draw_list, ERR_INVALID_PARAMETER, - "Copying buffers is forbidden during creation of a draw list"); - ERR_FAIL_COND_V_MSG(compute_list, ERR_INVALID_PARAMETER, - "Copying buffers is forbidden during creation of a compute list"); - - // This method assumes the barriers have been pushed prior to being called, therefore no barriers are pushed - // for the source or destination buffers before performing the copy. These masks are effectively ignored. - VkPipelineStageFlags src_stage_mask = 0; - VkAccessFlags src_access_mask = 0; - Buffer *src_buffer = _get_buffer_from_owner(p_src_buffer, src_stage_mask, src_access_mask, BARRIER_MASK_NO_BARRIER); - if (!src_buffer) { - ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, "Source buffer argument is not a valid buffer of any type."); - } - - VkPipelineStageFlags dst_stage_mask = 0; - VkAccessFlags dst_access = 0; - if (p_post_barrier.has_flag(BARRIER_MASK_TRANSFER)) { - // If the post barrier mask defines it, we indicate the destination buffer will require a barrier with these flags set - // after the copy command is queued. - dst_stage_mask = VK_PIPELINE_STAGE_TRANSFER_BIT; - dst_access = VK_ACCESS_TRANSFER_WRITE_BIT; - } - - Buffer *dst_buffer = _get_buffer_from_owner(p_dst_buffer, dst_stage_mask, dst_access, p_post_barrier); - if (!dst_buffer) { - ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, "Destination buffer argument is not a valid buffer of any type."); - } - - // Validate the copy's dimensions for both buffers. - ERR_FAIL_COND_V_MSG((p_size + p_src_offset) > src_buffer->size, ERR_INVALID_PARAMETER, "Size is larger than the source buffer."); - ERR_FAIL_COND_V_MSG((p_size + p_dst_offset) > dst_buffer->size, ERR_INVALID_PARAMETER, "Size is larger than the destination buffer."); - - // Perform the copy. - VkBufferCopy region; - region.srcOffset = p_src_offset; - region.dstOffset = p_dst_offset; - region.size = p_size; - vkCmdCopyBuffer(frames[frame].draw_command_buffer, src_buffer->buffer, dst_buffer->buffer, 1, ®ion); - -#ifdef FORCE_FULL_BARRIER - _full_barrier(true); -#else - if (dst_stage_mask == 0) { - dst_stage_mask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; - } - - // As indicated by the post barrier mask, push a new barrier. - if (p_post_barrier != RD::BARRIER_MASK_NO_BARRIER) { - _buffer_memory_barrier(dst_buffer->buffer, p_dst_offset, p_size, VK_PIPELINE_STAGE_TRANSFER_BIT, dst_stage_mask, VK_ACCESS_TRANSFER_WRITE_BIT, dst_access, true); - } -#endif - - return OK; -} - -Error RenderingDeviceVulkan::buffer_update(RID p_buffer, uint32_t p_offset, uint32_t p_size, const void *p_data, BitField p_post_barrier) { - _THREAD_SAFE_METHOD_ - - ERR_FAIL_COND_V_MSG(draw_list, ERR_INVALID_PARAMETER, - "Updating buffers is forbidden during creation of a draw list"); - ERR_FAIL_COND_V_MSG(compute_list, ERR_INVALID_PARAMETER, - "Updating buffers is forbidden during creation of a compute list"); - - VkPipelineStageFlags dst_stage_mask = 0; - VkAccessFlags dst_access = 0; - if (p_post_barrier.has_flag(BARRIER_MASK_TRANSFER)) { - // Protect subsequent updates. - dst_stage_mask = VK_PIPELINE_STAGE_TRANSFER_BIT; - dst_access = VK_ACCESS_TRANSFER_WRITE_BIT; - } - Buffer *buffer = _get_buffer_from_owner(p_buffer, dst_stage_mask, dst_access, p_post_barrier); - if (!buffer) { - ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, "Buffer argument is not a valid buffer of any type."); - } - - ERR_FAIL_COND_V_MSG(p_offset + p_size > buffer->size, ERR_INVALID_PARAMETER, - "Attempted to write buffer (" + itos((p_offset + p_size) - buffer->size) + " bytes) past the end."); - - // No barrier should be needed here. - // _buffer_memory_barrier(buffer->buffer, p_offset, p_size, dst_stage_mask, VK_PIPELINE_STAGE_TRANSFER_BIT, dst_access, VK_ACCESS_TRANSFER_WRITE_BIT, true); - - Error err = _buffer_update(buffer, p_offset, (uint8_t *)p_data, p_size, p_post_barrier); - if (err) { - return err; - } - -#ifdef FORCE_FULL_BARRIER - _full_barrier(true); -#else - if (dst_stage_mask == 0) { - dst_stage_mask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; - } - - if (p_post_barrier != RD::BARRIER_MASK_NO_BARRIER) { - _buffer_memory_barrier(buffer->buffer, p_offset, p_size, VK_PIPELINE_STAGE_TRANSFER_BIT, dst_stage_mask, VK_ACCESS_TRANSFER_WRITE_BIT, dst_access, true); - } - -#endif - return err; -} - -Error RenderingDeviceVulkan::buffer_clear(RID p_buffer, uint32_t p_offset, uint32_t p_size, BitField p_post_barrier) { - _THREAD_SAFE_METHOD_ - - ERR_FAIL_COND_V_MSG((p_size % 4) != 0, ERR_INVALID_PARAMETER, - "Size must be a multiple of four"); - ERR_FAIL_COND_V_MSG(draw_list, ERR_INVALID_PARAMETER, - "Updating buffers in is forbidden during creation of a draw list"); - ERR_FAIL_COND_V_MSG(compute_list, ERR_INVALID_PARAMETER, - "Updating buffers is forbidden during creation of a compute list"); + "Uniform buffer supplied (binding: " + itos(uniform.binding) + ") size (" + itos(buffer->size) + " is smaller than size of shader uniform: (" + itos(set_uniform.length) + ")."); - VkPipelineStageFlags dst_stage_mask = 0; - VkAccessFlags dst_access = 0; - if (p_post_barrier.has_flag(BARRIER_MASK_TRANSFER)) { - // Protect subsequent updates. - dst_stage_mask = VK_PIPELINE_STAGE_TRANSFER_BIT; - dst_access = VK_ACCESS_TRANSFER_WRITE_BIT; - } + driver_uniform.ids.push_back(buffer->driver_id); + } break; + case UNIFORM_TYPE_STORAGE_BUFFER: { + ERR_FAIL_COND_V_MSG(uniform.get_id_count() != 1, RID(), + "Storage buffer supplied (binding: " + itos(uniform.binding) + ") must provide one ID (" + itos(uniform.get_id_count()) + " provided)."); - Buffer *buffer = _get_buffer_from_owner(p_buffer, dst_stage_mask, dst_access, p_post_barrier); - if (!buffer) { - ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, "Buffer argument is not a valid buffer of any type."); - } + Buffer *buffer = nullptr; - ERR_FAIL_COND_V_MSG(p_offset + p_size > buffer->size, ERR_INVALID_PARAMETER, - "Attempted to write buffer (" + itos((p_offset + p_size) - buffer->size) + " bytes) past the end."); + if (storage_buffer_owner.owns(uniform.get_id(0))) { + buffer = storage_buffer_owner.get_or_null(uniform.get_id(0)); + } else if (vertex_buffer_owner.owns(uniform.get_id(0))) { + buffer = vertex_buffer_owner.get_or_null(uniform.get_id(0)); - vkCmdFillBuffer(frames[frame].draw_command_buffer, buffer->buffer, p_offset, p_size, 0); + ERR_FAIL_COND_V_MSG(!(buffer->usage.has_flag(RDD::BUFFER_USAGE_STORAGE_BIT)), RID(), "Vertex buffer supplied (binding: " + itos(uniform.binding) + ") was not created with storage flag."); + } + ERR_FAIL_NULL_V_MSG(buffer, RID(), "Storage buffer supplied (binding: " + itos(uniform.binding) + ") is invalid."); -#ifdef FORCE_FULL_BARRIER - _full_barrier(true); -#else - if (dst_stage_mask == 0) { - dst_stage_mask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; - } + // If 0, then it's sized on link time. + ERR_FAIL_COND_V_MSG(set_uniform.length > 0 && buffer->size != (uint32_t)set_uniform.length, RID(), + "Storage buffer supplied (binding: " + itos(uniform.binding) + ") size (" + itos(buffer->size) + " does not match size of shader uniform: (" + itos(set_uniform.length) + ")."); - _buffer_memory_barrier(buffer->buffer, p_offset, p_size, VK_PIPELINE_STAGE_TRANSFER_BIT, dst_stage_mask, VK_ACCESS_TRANSFER_WRITE_BIT, dst_access, true); + driver_uniform.ids.push_back(buffer->driver_id); + } break; + case UNIFORM_TYPE_INPUT_ATTACHMENT: { + ERR_FAIL_COND_V_MSG(shader->is_compute, RID(), "InputAttachment (binding: " + itos(uniform.binding) + ") supplied for compute shader (this is not allowed)."); -#endif - return OK; -} + if (uniform.get_id_count() != (uint32_t)set_uniform.length) { + if (set_uniform.length > 1) { + ERR_FAIL_V_MSG(RID(), "InputAttachment (binding: " + itos(uniform.binding) + ") is an array of (" + itos(set_uniform.length) + ") textures, so it should be provided equal number of texture IDs to satisfy it (IDs provided: " + itos(uniform.get_id_count()) + ")."); + } else { + ERR_FAIL_V_MSG(RID(), "InputAttachment (binding: " + itos(uniform.binding) + ") should provide one ID referencing a texture (IDs provided: " + itos(uniform.get_id_count()) + ")."); + } + } -Vector RenderingDeviceVulkan::buffer_get_data(RID p_buffer, uint32_t p_offset, uint32_t p_size) { - _THREAD_SAFE_METHOD_ + for (uint32_t j = 0; j < uniform.get_id_count(); j++) { + Texture *texture = texture_owner.get_or_null(uniform.get_id(j)); - // It could be this buffer was just created. - VkPipelineShaderStageCreateFlags src_stage_mask = VK_PIPELINE_STAGE_TRANSFER_BIT; - VkAccessFlags src_access_mask = VK_ACCESS_TRANSFER_WRITE_BIT; - // Get the vulkan buffer and the potential stage/access possible. - Buffer *buffer = _get_buffer_from_owner(p_buffer, src_stage_mask, src_access_mask, BARRIER_MASK_ALL_BARRIERS); - if (!buffer) { - ERR_FAIL_V_MSG(Vector(), "Buffer is either invalid or this type of buffer can't be retrieved. Only Index and Vertex buffers allow retrieving."); - } + ERR_FAIL_NULL_V_MSG(texture, RID(), + "InputAttachment (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") is not a valid texture."); - // Make sure no one is using the buffer -- the "true" gets us to the same command buffer as below. - _buffer_memory_barrier(buffer->buffer, 0, buffer->size, src_stage_mask, VK_PIPELINE_STAGE_TRANSFER_BIT, src_access_mask, VK_ACCESS_TRANSFER_READ_BIT, true); + ERR_FAIL_COND_V_MSG(!(texture->usage_flags & TEXTURE_USAGE_SAMPLING_BIT), RID(), + "InputAttachment (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") needs the TEXTURE_USAGE_SAMPLING_BIT usage flag set in order to be used as uniform."); - VkCommandBuffer command_buffer = frames[frame].draw_command_buffer; + DEV_ASSERT(!texture->owner.is_valid() || texture_owner.get_or_null(texture->owner)); - // Size of buffer to retrieve. - if (!p_size) { - p_size = buffer->size; - } else { - ERR_FAIL_COND_V_MSG(p_size + p_offset > buffer->size, Vector(), - "Size is larger than the buffer."); + driver_uniform.ids.push_back(texture->driver_id); + } + } break; + default: { + } + } } - Buffer tmp_buffer; - _buffer_allocate(&tmp_buffer, p_size, VK_BUFFER_USAGE_TRANSFER_DST_BIT, VMA_MEMORY_USAGE_AUTO_PREFER_HOST, VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT); - VkBufferCopy region; - region.srcOffset = p_offset; - region.dstOffset = 0; - region.size = p_size; - vkCmdCopyBuffer(command_buffer, buffer->buffer, tmp_buffer.buffer, 1, ®ion); // Dst buffer is in CPU, but I wonder if src buffer needs a barrier for this. - // Flush everything so memory can be safely mapped. - _flush(true); + RDD::UniformSetID driver_uniform_set = driver->uniform_set_create(driver_uniforms, shader->driver_id, p_shader_set); + ERR_FAIL_COND_V(!driver_uniform_set, RID()); - void *buffer_mem; - VkResult vkerr = vmaMapMemory(allocator, tmp_buffer.allocation, &buffer_mem); - ERR_FAIL_COND_V_MSG(vkerr, Vector(), "vmaMapMemory failed with error " + itos(vkerr) + "."); + UniformSet uniform_set; + uniform_set.driver_id = driver_uniform_set; + uniform_set.format = shader->set_formats[p_shader_set]; + uniform_set.attachable_textures = attachable_textures; + uniform_set.mutable_sampled_textures = mutable_sampled_textures; + uniform_set.mutable_storage_textures = mutable_storage_textures; + uniform_set.shader_set = p_shader_set; + uniform_set.shader_id = p_shader; - Vector buffer_data; - { - buffer_data.resize(p_size); - uint8_t *w = buffer_data.ptrw(); - memcpy(w, buffer_mem, p_size); + RID id = uniform_set_owner.make_rid(uniform_set); +#ifdef DEV_ENABLED + set_resource_name(id, "RID:" + itos(id.get_id())); +#endif + // Add dependencies. + _add_dependency(id, p_shader); + for (uint32_t i = 0; i < uniform_count; i++) { + const Uniform &uniform = uniforms[i]; + int id_count = uniform.get_id_count(); + for (int j = 0; j < id_count; j++) { + _add_dependency(id, uniform.get_id(j)); + } } - vmaUnmapMemory(allocator, tmp_buffer.allocation); + return id; +} - _buffer_free(&tmp_buffer); +bool RenderingDevice::uniform_set_is_valid(RID p_uniform_set) { + return uniform_set_owner.owns(p_uniform_set); +} - return buffer_data; +void RenderingDevice::uniform_set_set_invalidation_callback(RID p_uniform_set, InvalidationCallback p_callback, void *p_userdata) { + UniformSet *us = uniform_set_owner.get_or_null(p_uniform_set); + ERR_FAIL_NULL(us); + us->invalidated_callback = p_callback; + us->invalidated_callback_userdata = p_userdata; } -/*************************/ -/**** RENDER PIPELINE ****/ -/*************************/ +/*******************/ +/**** PIPELINES ****/ +/*******************/ -RID RenderingDeviceVulkan::render_pipeline_create(RID p_shader, FramebufferFormatID p_framebuffer_format, VertexFormatID p_vertex_format, RenderPrimitive p_render_primitive, const PipelineRasterizationState &p_rasterization_state, const PipelineMultisampleState &p_multisample_state, const PipelineDepthStencilState &p_depth_stencil_state, const PipelineColorBlendState &p_blend_state, BitField p_dynamic_state_flags, uint32_t p_for_render_pass, const Vector &p_specialization_constants) { +RID RenderingDevice::render_pipeline_create(RID p_shader, FramebufferFormatID p_framebuffer_format, VertexFormatID p_vertex_format, RenderPrimitive p_render_primitive, const PipelineRasterizationState &p_rasterization_state, const PipelineMultisampleState &p_multisample_state, const PipelineDepthStencilState &p_depth_stencil_state, const PipelineColorBlendState &p_blend_state, BitField p_dynamic_state_flags, uint32_t p_for_render_pass, const Vector &p_specialization_constants) { _THREAD_SAFE_METHOD_ // Needs a shader. @@ -6129,32 +3333,30 @@ RID RenderingDeviceVulkan::render_pipeline_create(RID p_shader, FramebufferForma ERR_FAIL_COND_V(!framebuffer_formats.has(p_framebuffer_format), RID()); const FramebufferFormat &fb_format = framebuffer_formats[p_framebuffer_format]; - { // Validate shader vs framebuffer. - + // Validate shader vs. framebuffer. + { ERR_FAIL_COND_V_MSG(p_for_render_pass >= uint32_t(fb_format.E->key().passes.size()), RID(), "Render pass requested for pipeline creation (" + itos(p_for_render_pass) + ") is out of bounds"); const FramebufferPass &pass = fb_format.E->key().passes[p_for_render_pass]; uint32_t output_mask = 0; for (int i = 0; i < pass.color_attachments.size(); i++) { - if (pass.color_attachments[i] != FramebufferPass::ATTACHMENT_UNUSED) { + if (pass.color_attachments[i] != ATTACHMENT_UNUSED) { output_mask |= 1 << i; } } ERR_FAIL_COND_V_MSG(shader->fragment_output_mask != output_mask, RID(), "Mismatch fragment shader output mask (" + itos(shader->fragment_output_mask) + ") and framebuffer color output mask (" + itos(output_mask) + ") when binding both in render pipeline."); } - // Vertex. - VkPipelineVertexInputStateCreateInfo pipeline_vertex_input_state_create_info; + RDD::VertexFormatID driver_vertex_format; if (p_vertex_format != INVALID_ID) { // Uses vertices, else it does not. ERR_FAIL_COND_V(!vertex_formats.has(p_vertex_format), RID()); const VertexDescriptionCache &vd = vertex_formats[p_vertex_format]; - - pipeline_vertex_input_state_create_info = vd.create_info; + driver_vertex_format = vertex_formats[p_vertex_format].driver_id; // Validate with inputs. - for (uint64_t i = 0; i < 64; i++) { - if (!(shader->vertex_input_mask & (1ULL << i))) { + for (uint32_t i = 0; i < 64; i++) { + if (!(shader->vertex_input_mask & ((uint64_t)1) << i)) { continue; } bool found = false; @@ -6169,382 +3371,89 @@ RID RenderingDeviceVulkan::render_pipeline_create(RID p_shader, FramebufferForma } } else { - // Does not use vertices. - pipeline_vertex_input_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; - pipeline_vertex_input_state_create_info.pNext = nullptr; - pipeline_vertex_input_state_create_info.flags = 0; - pipeline_vertex_input_state_create_info.vertexBindingDescriptionCount = 0; - pipeline_vertex_input_state_create_info.pVertexBindingDescriptions = nullptr; - pipeline_vertex_input_state_create_info.vertexAttributeDescriptionCount = 0; - pipeline_vertex_input_state_create_info.pVertexAttributeDescriptions = nullptr; - ERR_FAIL_COND_V_MSG(shader->vertex_input_mask != 0, RID(), "Shader contains vertex inputs, but no vertex input description was provided for pipeline creation."); } - // Input assembly. ERR_FAIL_INDEX_V(p_render_primitive, RENDER_PRIMITIVE_MAX, RID()); - VkPipelineInputAssemblyStateCreateInfo input_assembly_create_info; - input_assembly_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; - input_assembly_create_info.pNext = nullptr; - input_assembly_create_info.flags = 0; - - static const VkPrimitiveTopology topology_list[RENDER_PRIMITIVE_MAX] = { - VK_PRIMITIVE_TOPOLOGY_POINT_LIST, - VK_PRIMITIVE_TOPOLOGY_LINE_LIST, - VK_PRIMITIVE_TOPOLOGY_LINE_LIST_WITH_ADJACENCY, - VK_PRIMITIVE_TOPOLOGY_LINE_STRIP, - VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY, - VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, - VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY, - VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP, - VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY, - VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP, - VK_PRIMITIVE_TOPOLOGY_PATCH_LIST - }; - - input_assembly_create_info.topology = topology_list[p_render_primitive]; - input_assembly_create_info.primitiveRestartEnable = (p_render_primitive == RENDER_PRIMITIVE_TRIANGLE_STRIPS_WITH_RESTART_INDEX); - - // Tessellation. - VkPipelineTessellationStateCreateInfo tessellation_create_info; - tessellation_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_TESSELLATION_STATE_CREATE_INFO; - tessellation_create_info.pNext = nullptr; - tessellation_create_info.flags = 0; - ERR_FAIL_COND_V(limits.maxTessellationPatchSize > 0 && (p_rasterization_state.patch_control_points < 1 || p_rasterization_state.patch_control_points > limits.maxTessellationPatchSize), RID()); - tessellation_create_info.patchControlPoints = p_rasterization_state.patch_control_points; - - VkPipelineViewportStateCreateInfo viewport_state_create_info; - viewport_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; - viewport_state_create_info.pNext = nullptr; - viewport_state_create_info.flags = 0; - viewport_state_create_info.viewportCount = 1; // If VR extensions are supported at some point, this will have to be customizable in the framebuffer format. - viewport_state_create_info.pViewports = nullptr; - viewport_state_create_info.scissorCount = 1; - viewport_state_create_info.pScissors = nullptr; - - // Rasterization. - VkPipelineRasterizationStateCreateInfo rasterization_state_create_info; - rasterization_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; - rasterization_state_create_info.pNext = nullptr; - rasterization_state_create_info.flags = 0; - rasterization_state_create_info.depthClampEnable = p_rasterization_state.enable_depth_clamp; - rasterization_state_create_info.rasterizerDiscardEnable = p_rasterization_state.discard_primitives; - rasterization_state_create_info.polygonMode = (p_rasterization_state.wireframe ? VK_POLYGON_MODE_LINE : VK_POLYGON_MODE_FILL); - static const VkCullModeFlags cull_mode[3] = { - VK_CULL_MODE_NONE, - VK_CULL_MODE_FRONT_BIT, - VK_CULL_MODE_BACK_BIT - }; - ERR_FAIL_INDEX_V(p_rasterization_state.cull_mode, 3, RID()); - rasterization_state_create_info.cullMode = cull_mode[p_rasterization_state.cull_mode]; - rasterization_state_create_info.frontFace = (p_rasterization_state.front_face == POLYGON_FRONT_FACE_CLOCKWISE ? VK_FRONT_FACE_CLOCKWISE : VK_FRONT_FACE_COUNTER_CLOCKWISE); - rasterization_state_create_info.depthBiasEnable = p_rasterization_state.depth_bias_enabled; - rasterization_state_create_info.depthBiasConstantFactor = p_rasterization_state.depth_bias_constant_factor; - rasterization_state_create_info.depthBiasClamp = p_rasterization_state.depth_bias_clamp; - rasterization_state_create_info.depthBiasSlopeFactor = p_rasterization_state.depth_bias_slope_factor; - rasterization_state_create_info.lineWidth = p_rasterization_state.line_width; - - // Multisample. - VkPipelineMultisampleStateCreateInfo multisample_state_create_info; - multisample_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; - multisample_state_create_info.pNext = nullptr; - multisample_state_create_info.flags = 0; - - multisample_state_create_info.rasterizationSamples = _ensure_supported_sample_count(p_multisample_state.sample_count); - multisample_state_create_info.sampleShadingEnable = p_multisample_state.enable_sample_shading; - multisample_state_create_info.minSampleShading = p_multisample_state.min_sample_shading; - Vector sample_mask; + if (p_multisample_state.sample_mask.size()) { // Use sample mask. - const int rasterization_sample_mask_expected_size[TEXTURE_SAMPLES_MAX] = { - 1, 2, 4, 8, 16, 32, 64 - }; - ERR_FAIL_COND_V(rasterization_sample_mask_expected_size[p_multisample_state.sample_count] != p_multisample_state.sample_mask.size(), RID()); - sample_mask.resize(p_multisample_state.sample_mask.size()); - for (int i = 0; i < p_multisample_state.sample_mask.size(); i++) { - VkSampleMask mask = p_multisample_state.sample_mask[i]; - sample_mask.push_back(mask); - } - multisample_state_create_info.pSampleMask = sample_mask.ptr(); - } else { - multisample_state_create_info.pSampleMask = nullptr; + ERR_FAIL_COND_V((int)TEXTURE_SAMPLES_COUNT[p_multisample_state.sample_count] != p_multisample_state.sample_mask.size(), RID()); } - multisample_state_create_info.alphaToCoverageEnable = p_multisample_state.enable_alpha_to_coverage; - multisample_state_create_info.alphaToOneEnable = p_multisample_state.enable_alpha_to_one; - - // Depth stencil. - - VkPipelineDepthStencilStateCreateInfo depth_stencil_state_create_info; - depth_stencil_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO; - depth_stencil_state_create_info.pNext = nullptr; - depth_stencil_state_create_info.flags = 0; - depth_stencil_state_create_info.depthTestEnable = p_depth_stencil_state.enable_depth_test; - depth_stencil_state_create_info.depthWriteEnable = p_depth_stencil_state.enable_depth_write; ERR_FAIL_INDEX_V(p_depth_stencil_state.depth_compare_operator, COMPARE_OP_MAX, RID()); - depth_stencil_state_create_info.depthCompareOp = compare_operators[p_depth_stencil_state.depth_compare_operator]; - depth_stencil_state_create_info.depthBoundsTestEnable = p_depth_stencil_state.enable_depth_range; - depth_stencil_state_create_info.stencilTestEnable = p_depth_stencil_state.enable_stencil; ERR_FAIL_INDEX_V(p_depth_stencil_state.front_op.fail, STENCIL_OP_MAX, RID()); - depth_stencil_state_create_info.front.failOp = stencil_operations[p_depth_stencil_state.front_op.fail]; ERR_FAIL_INDEX_V(p_depth_stencil_state.front_op.pass, STENCIL_OP_MAX, RID()); - depth_stencil_state_create_info.front.passOp = stencil_operations[p_depth_stencil_state.front_op.pass]; ERR_FAIL_INDEX_V(p_depth_stencil_state.front_op.depth_fail, STENCIL_OP_MAX, RID()); - depth_stencil_state_create_info.front.depthFailOp = stencil_operations[p_depth_stencil_state.front_op.depth_fail]; ERR_FAIL_INDEX_V(p_depth_stencil_state.front_op.compare, COMPARE_OP_MAX, RID()); - depth_stencil_state_create_info.front.compareOp = compare_operators[p_depth_stencil_state.front_op.compare]; - depth_stencil_state_create_info.front.compareMask = p_depth_stencil_state.front_op.compare_mask; - depth_stencil_state_create_info.front.writeMask = p_depth_stencil_state.front_op.write_mask; - depth_stencil_state_create_info.front.reference = p_depth_stencil_state.front_op.reference; ERR_FAIL_INDEX_V(p_depth_stencil_state.back_op.fail, STENCIL_OP_MAX, RID()); - depth_stencil_state_create_info.back.failOp = stencil_operations[p_depth_stencil_state.back_op.fail]; ERR_FAIL_INDEX_V(p_depth_stencil_state.back_op.pass, STENCIL_OP_MAX, RID()); - depth_stencil_state_create_info.back.passOp = stencil_operations[p_depth_stencil_state.back_op.pass]; ERR_FAIL_INDEX_V(p_depth_stencil_state.back_op.depth_fail, STENCIL_OP_MAX, RID()); - depth_stencil_state_create_info.back.depthFailOp = stencil_operations[p_depth_stencil_state.back_op.depth_fail]; ERR_FAIL_INDEX_V(p_depth_stencil_state.back_op.compare, COMPARE_OP_MAX, RID()); - depth_stencil_state_create_info.back.compareOp = compare_operators[p_depth_stencil_state.back_op.compare]; - depth_stencil_state_create_info.back.compareMask = p_depth_stencil_state.back_op.compare_mask; - depth_stencil_state_create_info.back.writeMask = p_depth_stencil_state.back_op.write_mask; - depth_stencil_state_create_info.back.reference = p_depth_stencil_state.back_op.reference; - - depth_stencil_state_create_info.minDepthBounds = p_depth_stencil_state.depth_range_min; - depth_stencil_state_create_info.maxDepthBounds = p_depth_stencil_state.depth_range_max; - - // Blend state. - VkPipelineColorBlendStateCreateInfo color_blend_state_create_info; - color_blend_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; - color_blend_state_create_info.pNext = nullptr; - color_blend_state_create_info.flags = 0; - color_blend_state_create_info.logicOpEnable = p_blend_state.enable_logic_op; - ERR_FAIL_INDEX_V(p_blend_state.logic_op, LOGIC_OP_MAX, RID()); - color_blend_state_create_info.logicOp = logic_operations[p_blend_state.logic_op]; - - Vector attachment_states; - { - const FramebufferPass &pass = fb_format.E->key().passes[p_for_render_pass]; - attachment_states.resize(pass.color_attachments.size()); - ERR_FAIL_COND_V(p_blend_state.attachments.size() < pass.color_attachments.size(), RID()); - for (int i = 0; i < pass.color_attachments.size(); i++) { - VkPipelineColorBlendAttachmentState state; - if (pass.color_attachments[i] == FramebufferPass::ATTACHMENT_UNUSED) { - state.blendEnable = false; - state.srcColorBlendFactor = VK_BLEND_FACTOR_ZERO; - state.dstColorBlendFactor = VK_BLEND_FACTOR_ZERO; - state.colorBlendOp = VK_BLEND_OP_ADD; + ERR_FAIL_INDEX_V(p_blend_state.logic_op, LOGIC_OP_MAX, RID()); - state.srcAlphaBlendFactor = VK_BLEND_FACTOR_ZERO; - state.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO; - state.alphaBlendOp = VK_BLEND_OP_ADD; + const FramebufferPass &pass = fb_format.E->key().passes[p_for_render_pass]; + ERR_FAIL_COND_V(p_blend_state.attachments.size() < pass.color_attachments.size(), RID()); + for (int i = 0; i < pass.color_attachments.size(); i++) { + if (pass.color_attachments[i] != ATTACHMENT_UNUSED) { + ERR_FAIL_INDEX_V(p_blend_state.attachments[i].src_color_blend_factor, BLEND_FACTOR_MAX, RID()); + ERR_FAIL_INDEX_V(p_blend_state.attachments[i].dst_color_blend_factor, BLEND_FACTOR_MAX, RID()); + ERR_FAIL_INDEX_V(p_blend_state.attachments[i].color_blend_op, BLEND_OP_MAX, RID()); - state.colorWriteMask = 0; - } else { - state.blendEnable = p_blend_state.attachments[i].enable_blend; - - ERR_FAIL_INDEX_V(p_blend_state.attachments[i].src_color_blend_factor, BLEND_FACTOR_MAX, RID()); - state.srcColorBlendFactor = blend_factors[p_blend_state.attachments[i].src_color_blend_factor]; - ERR_FAIL_INDEX_V(p_blend_state.attachments[i].dst_color_blend_factor, BLEND_FACTOR_MAX, RID()); - state.dstColorBlendFactor = blend_factors[p_blend_state.attachments[i].dst_color_blend_factor]; - ERR_FAIL_INDEX_V(p_blend_state.attachments[i].color_blend_op, BLEND_OP_MAX, RID()); - state.colorBlendOp = blend_operations[p_blend_state.attachments[i].color_blend_op]; - - ERR_FAIL_INDEX_V(p_blend_state.attachments[i].src_alpha_blend_factor, BLEND_FACTOR_MAX, RID()); - state.srcAlphaBlendFactor = blend_factors[p_blend_state.attachments[i].src_alpha_blend_factor]; - ERR_FAIL_INDEX_V(p_blend_state.attachments[i].dst_alpha_blend_factor, BLEND_FACTOR_MAX, RID()); - state.dstAlphaBlendFactor = blend_factors[p_blend_state.attachments[i].dst_alpha_blend_factor]; - ERR_FAIL_INDEX_V(p_blend_state.attachments[i].alpha_blend_op, BLEND_OP_MAX, RID()); - state.alphaBlendOp = blend_operations[p_blend_state.attachments[i].alpha_blend_op]; - - state.colorWriteMask = 0; - if (p_blend_state.attachments[i].write_r) { - state.colorWriteMask |= VK_COLOR_COMPONENT_R_BIT; - } - if (p_blend_state.attachments[i].write_g) { - state.colorWriteMask |= VK_COLOR_COMPONENT_G_BIT; - } - if (p_blend_state.attachments[i].write_b) { - state.colorWriteMask |= VK_COLOR_COMPONENT_B_BIT; - } - if (p_blend_state.attachments[i].write_a) { - state.colorWriteMask |= VK_COLOR_COMPONENT_A_BIT; - } - } - attachment_states.write[i] = state; + ERR_FAIL_INDEX_V(p_blend_state.attachments[i].src_alpha_blend_factor, BLEND_FACTOR_MAX, RID()); + ERR_FAIL_INDEX_V(p_blend_state.attachments[i].dst_alpha_blend_factor, BLEND_FACTOR_MAX, RID()); + ERR_FAIL_INDEX_V(p_blend_state.attachments[i].alpha_blend_op, BLEND_OP_MAX, RID()); } } - color_blend_state_create_info.attachmentCount = attachment_states.size(); - color_blend_state_create_info.pAttachments = attachment_states.ptr(); - - color_blend_state_create_info.blendConstants[0] = p_blend_state.blend_constant.r; - color_blend_state_create_info.blendConstants[1] = p_blend_state.blend_constant.g; - color_blend_state_create_info.blendConstants[2] = p_blend_state.blend_constant.b; - color_blend_state_create_info.blendConstants[3] = p_blend_state.blend_constant.a; - - // Dynamic state. - - VkPipelineDynamicStateCreateInfo dynamic_state_create_info; - dynamic_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO; - dynamic_state_create_info.pNext = nullptr; - dynamic_state_create_info.flags = 0; - Vector dynamic_states; // Vulkan is weird. - - dynamic_states.push_back(VK_DYNAMIC_STATE_VIEWPORT); // Viewport and scissor are always dynamic. - dynamic_states.push_back(VK_DYNAMIC_STATE_SCISSOR); - - if (p_dynamic_state_flags.has_flag(DYNAMIC_STATE_LINE_WIDTH)) { - dynamic_states.push_back(VK_DYNAMIC_STATE_LINE_WIDTH); - } - - if (p_dynamic_state_flags.has_flag(DYNAMIC_STATE_DEPTH_BIAS)) { - dynamic_states.push_back(VK_DYNAMIC_STATE_DEPTH_BIAS); - } - - if (p_dynamic_state_flags.has_flag(DYNAMIC_STATE_BLEND_CONSTANTS)) { - dynamic_states.push_back(VK_DYNAMIC_STATE_BLEND_CONSTANTS); - } - - if (p_dynamic_state_flags.has_flag(DYNAMIC_STATE_DEPTH_BOUNDS)) { - dynamic_states.push_back(VK_DYNAMIC_STATE_DEPTH_BOUNDS); - } - - if (p_dynamic_state_flags.has_flag(DYNAMIC_STATE_STENCIL_COMPARE_MASK)) { - dynamic_states.push_back(VK_DYNAMIC_STATE_STENCIL_COMPARE_MASK); - } - - if (p_dynamic_state_flags.has_flag(DYNAMIC_STATE_STENCIL_WRITE_MASK)) { - dynamic_states.push_back(VK_DYNAMIC_STATE_STENCIL_WRITE_MASK); - } - - if (p_dynamic_state_flags.has_flag(DYNAMIC_STATE_STENCIL_REFERENCE)) { - dynamic_states.push_back(VK_DYNAMIC_STATE_STENCIL_REFERENCE); - } - - dynamic_state_create_info.dynamicStateCount = dynamic_states.size(); - dynamic_state_create_info.pDynamicStates = dynamic_states.ptr(); - - void *graphics_pipeline_nextptr = nullptr; - - VkPipelineFragmentShadingRateStateCreateInfoKHR vrs_create_info; - if (context->get_vrs_capabilities().attachment_vrs_supported) { - // If VRS is used, this defines how the different VRS types are combined. - // combinerOps[0] decides how we use the output of pipeline and primitive (drawcall) VRS. - // combinerOps[1] decides how we use the output of combinerOps[0] and our attachment VRS. - - vrs_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_FRAGMENT_SHADING_RATE_STATE_CREATE_INFO_KHR; - vrs_create_info.pNext = nullptr; - vrs_create_info.fragmentSize = { 4, 4 }; - vrs_create_info.combinerOps[0] = VK_FRAGMENT_SHADING_RATE_COMBINER_OP_KEEP_KHR; // We don't use pipeline/primitive VRS so this really doesn't matter. - vrs_create_info.combinerOps[1] = VK_FRAGMENT_SHADING_RATE_COMBINER_OP_REPLACE_KHR; // Always use the outcome of attachment VRS if enabled. - - graphics_pipeline_nextptr = &vrs_create_info; - } - - // Finally, pipeline create info. - VkGraphicsPipelineCreateInfo graphics_pipeline_create_info; - - graphics_pipeline_create_info.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; - graphics_pipeline_create_info.pNext = graphics_pipeline_nextptr; - graphics_pipeline_create_info.flags = 0; - - Vector pipeline_stages = shader->pipeline_stages; - Vector specialization_info; - Vector> specialization_map_entries; - Vector specialization_constant_data; - - if (shader->specialization_constants.size()) { - specialization_constant_data.resize(shader->specialization_constants.size()); - uint32_t *data_ptr = specialization_constant_data.ptrw(); - specialization_info.resize(pipeline_stages.size()); - specialization_map_entries.resize(pipeline_stages.size()); - for (int i = 0; i < shader->specialization_constants.size(); i++) { - // See if overridden. - const Shader::SpecializationConstant &sc = shader->specialization_constants[i]; - data_ptr[i] = sc.constant.int_value; // Just copy the 32 bits. - - for (int j = 0; j < p_specialization_constants.size(); j++) { - const PipelineSpecializationConstant &psc = p_specialization_constants[j]; - if (psc.constant_id == sc.constant.constant_id) { - ERR_FAIL_COND_V_MSG(psc.type != sc.constant.type, RID(), "Specialization constant provided for id (" + itos(sc.constant.constant_id) + ") is of the wrong type."); - data_ptr[i] = psc.int_value; - break; - } - } - - VkSpecializationMapEntry entry; - - entry.constantID = sc.constant.constant_id; - entry.offset = i * sizeof(uint32_t); - entry.size = sizeof(uint32_t); - - for (int j = 0; j < SHADER_STAGE_MAX; j++) { - if (sc.stage_flags & (1 << j)) { - VkShaderStageFlagBits stage = shader_stage_masks[j]; - for (int k = 0; k < pipeline_stages.size(); k++) { - if (pipeline_stages[k].stage == stage) { - specialization_map_entries.write[k].push_back(entry); - } - } - } - } - } - - for (int i = 0; i < pipeline_stages.size(); i++) { - if (specialization_map_entries[i].size()) { - specialization_info.write[i].dataSize = specialization_constant_data.size() * sizeof(uint32_t); - specialization_info.write[i].pData = data_ptr; - specialization_info.write[i].mapEntryCount = specialization_map_entries[i].size(); - specialization_info.write[i].pMapEntries = specialization_map_entries[i].ptr(); - pipeline_stages.write[i].pSpecializationInfo = specialization_info.ptr() + i; + for (int i = 0; i < shader->specialization_constants.size(); i++) { + const ShaderSpecializationConstant &sc = shader->specialization_constants[i]; + for (int j = 0; j < p_specialization_constants.size(); j++) { + const PipelineSpecializationConstant &psc = p_specialization_constants[j]; + if (psc.constant_id == sc.constant_id) { + ERR_FAIL_COND_V_MSG(psc.type != sc.type, RID(), "Specialization constant provided for id (" + itos(sc.constant_id) + ") is of the wrong type."); + break; } } } - graphics_pipeline_create_info.stageCount = pipeline_stages.size(); - graphics_pipeline_create_info.pStages = pipeline_stages.ptr(); - - graphics_pipeline_create_info.pVertexInputState = &pipeline_vertex_input_state_create_info; - graphics_pipeline_create_info.pInputAssemblyState = &input_assembly_create_info; - graphics_pipeline_create_info.pTessellationState = &tessellation_create_info; - graphics_pipeline_create_info.pViewportState = &viewport_state_create_info; - graphics_pipeline_create_info.pRasterizationState = &rasterization_state_create_info; - graphics_pipeline_create_info.pMultisampleState = &multisample_state_create_info; - graphics_pipeline_create_info.pDepthStencilState = &depth_stencil_state_create_info; - graphics_pipeline_create_info.pColorBlendState = &color_blend_state_create_info; - graphics_pipeline_create_info.pDynamicState = &dynamic_state_create_info; - graphics_pipeline_create_info.layout = shader->pipeline_layout; - graphics_pipeline_create_info.renderPass = fb_format.render_pass; - - graphics_pipeline_create_info.subpass = p_for_render_pass; - graphics_pipeline_create_info.basePipelineHandle = VK_NULL_HANDLE; - graphics_pipeline_create_info.basePipelineIndex = 0; - RenderPipeline pipeline; - VkResult err = vkCreateGraphicsPipelines(device, pipelines_cache.cache_object, 1, &graphics_pipeline_create_info, nullptr, &pipeline.pipeline); - ERR_FAIL_COND_V_MSG(err, RID(), "vkCreateGraphicsPipelines failed with error " + itos(err) + " for shader '" + shader->name + "'."); - - if (pipelines_cache.cache_object != VK_NULL_HANDLE) { + pipeline.driver_id = driver->render_pipeline_create( + shader->driver_id, + driver_vertex_format, + p_render_primitive, + p_rasterization_state, + p_multisample_state, + p_depth_stencil_state, + p_blend_state, + pass.color_attachments, + p_dynamic_state_flags, + fb_format.render_pass, + p_for_render_pass, + p_specialization_constants); + ERR_FAIL_COND_V(!pipeline.driver_id, RID()); + + if (pipelines_cache_enabled) { _update_pipeline_cache(); } - pipeline.set_formats = shader->set_formats; - pipeline.push_constant_stages_mask = shader->push_constant.vk_stages_mask; - pipeline.pipeline_layout = shader->pipeline_layout; pipeline.shader = p_shader; - pipeline.push_constant_size = shader->push_constant.size; + pipeline.shader_driver_id = shader->driver_id; + pipeline.set_formats = shader->set_formats; + pipeline.push_constant_size = shader->push_constant_size; #ifdef DEBUG_ENABLED pipeline.validation.dynamic_state = p_dynamic_state_flags; pipeline.validation.framebuffer_format = p_framebuffer_format; pipeline.validation.render_pass = p_for_render_pass; pipeline.validation.vertex_format = p_vertex_format; - pipeline.validation.uses_restart_indices = input_assembly_create_info.primitiveRestartEnable; + pipeline.validation.uses_restart_indices = p_render_primitive == RENDER_PRIMITIVE_TRIANGLE_STRIPS_WITH_RESTART_INDEX; static const uint32_t primitive_divisor[RENDER_PRIMITIVE_MAX] = { 1, 2, 1, 1, 1, 3, 1, 1, 1, 1, 1 @@ -6575,16 +3484,12 @@ RID RenderingDeviceVulkan::render_pipeline_create(RID p_shader, FramebufferForma return id; } -bool RenderingDeviceVulkan::render_pipeline_is_valid(RID p_pipeline) { +bool RenderingDevice::render_pipeline_is_valid(RID p_pipeline) { _THREAD_SAFE_METHOD_ return render_pipeline_owner.owns(p_pipeline); } -/**************************/ -/**** COMPUTE PIPELINE ****/ -/**************************/ - -RID RenderingDeviceVulkan::compute_pipeline_create(RID p_shader, const Vector &p_specialization_constants) { +RID RenderingDevice::compute_pipeline_create(RID p_shader, const Vector &p_specialization_constants) { _THREAD_SAFE_METHOD_ // Needs a shader. @@ -6594,69 +3499,29 @@ RID RenderingDeviceVulkan::compute_pipeline_create(RID p_shader, const Vectoris_compute, RID(), "Non-compute shaders can't be used in compute pipelines"); - // Finally, pipeline create info. - VkComputePipelineCreateInfo compute_pipeline_create_info; - - compute_pipeline_create_info.sType = VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO; - compute_pipeline_create_info.pNext = nullptr; - compute_pipeline_create_info.flags = 0; - - compute_pipeline_create_info.stage = shader->pipeline_stages[0]; - compute_pipeline_create_info.layout = shader->pipeline_layout; - compute_pipeline_create_info.basePipelineHandle = VK_NULL_HANDLE; - compute_pipeline_create_info.basePipelineIndex = 0; - - VkSpecializationInfo specialization_info; - Vector specialization_map_entries; - Vector specialization_constant_data; - - if (shader->specialization_constants.size()) { - specialization_constant_data.resize(shader->specialization_constants.size()); - uint32_t *data_ptr = specialization_constant_data.ptrw(); - for (int i = 0; i < shader->specialization_constants.size(); i++) { - // See if overridden. - const Shader::SpecializationConstant &sc = shader->specialization_constants[i]; - data_ptr[i] = sc.constant.int_value; // Just copy the 32 bits. - - for (int j = 0; j < p_specialization_constants.size(); j++) { - const PipelineSpecializationConstant &psc = p_specialization_constants[j]; - if (psc.constant_id == sc.constant.constant_id) { - ERR_FAIL_COND_V_MSG(psc.type != sc.constant.type, RID(), "Specialization constant provided for id (" + itos(sc.constant.constant_id) + ") is of the wrong type."); - data_ptr[i] = psc.int_value; - break; - } + for (int i = 0; i < shader->specialization_constants.size(); i++) { + const ShaderSpecializationConstant &sc = shader->specialization_constants[i]; + for (int j = 0; j < p_specialization_constants.size(); j++) { + const PipelineSpecializationConstant &psc = p_specialization_constants[j]; + if (psc.constant_id == sc.constant_id) { + ERR_FAIL_COND_V_MSG(psc.type != sc.type, RID(), "Specialization constant provided for id (" + itos(sc.constant_id) + ") is of the wrong type."); + break; } - - VkSpecializationMapEntry entry; - - entry.constantID = sc.constant.constant_id; - entry.offset = i * sizeof(uint32_t); - entry.size = sizeof(uint32_t); - - specialization_map_entries.push_back(entry); } - - specialization_info.dataSize = specialization_constant_data.size() * sizeof(uint32_t); - specialization_info.pData = data_ptr; - specialization_info.mapEntryCount = specialization_map_entries.size(); - specialization_info.pMapEntries = specialization_map_entries.ptr(); - - compute_pipeline_create_info.stage.pSpecializationInfo = &specialization_info; } ComputePipeline pipeline; - VkResult err = vkCreateComputePipelines(device, pipelines_cache.cache_object, 1, &compute_pipeline_create_info, nullptr, &pipeline.pipeline); - ERR_FAIL_COND_V_MSG(err, RID(), "vkCreateComputePipelines failed with error " + itos(err) + "."); + pipeline.driver_id = driver->compute_pipeline_create(shader->driver_id, p_specialization_constants); + ERR_FAIL_COND_V(!pipeline.driver_id, RID()); - if (pipelines_cache.cache_object != VK_NULL_HANDLE) { + if (pipelines_cache_enabled) { _update_pipeline_cache(); } - pipeline.set_formats = shader->set_formats; - pipeline.push_constant_stages_mask = shader->push_constant.vk_stages_mask; - pipeline.pipeline_layout = shader->pipeline_layout; pipeline.shader = p_shader; - pipeline.push_constant_size = shader->push_constant.size; + pipeline.shader_driver_id = shader->driver_id; + pipeline.set_formats = shader->set_formats; + pipeline.push_constant_size = shader->push_constant_size; pipeline.local_group_size[0] = shader->compute_local_size[0]; pipeline.local_group_size[1] = shader->compute_local_size[1]; pipeline.local_group_size[2] = shader->compute_local_size[2]; @@ -6671,7 +3536,7 @@ RID RenderingDeviceVulkan::compute_pipeline_create(RID p_shader, const Vectorwindow_get_width(p_screen); } -int RenderingDeviceVulkan::screen_get_height(DisplayServer::WindowID p_screen) const { +int RenderingDevice::screen_get_height(DisplayServer::WindowID p_screen) const { _THREAD_SAFE_METHOD_ ERR_FAIL_COND_V_MSG(local_device.is_valid(), -1, "Local devices have no screen"); - return context->window_get_height(p_screen); } -RenderingDevice::FramebufferFormatID RenderingDeviceVulkan::screen_get_framebuffer_format() const { +RenderingDevice::FramebufferFormatID RenderingDevice::screen_get_framebuffer_format() const { _THREAD_SAFE_METHOD_ ERR_FAIL_COND_V_MSG(local_device.is_valid(), INVALID_ID, "Local devices have no screen"); - // Very hacky, but not used often per frame so I guess ok. - VkFormat vkformat = context->get_screen_format(); - DataFormat format = DATA_FORMAT_MAX; - for (int i = 0; i < DATA_FORMAT_MAX; i++) { - if (vkformat == vulkan_formats[i]) { - format = DataFormat(i); - break; - } - } - + DataFormat format = driver->screen_get_format(); ERR_FAIL_COND_V(format == DATA_FORMAT_MAX, INVALID_ID); AttachmentFormat attachment; @@ -6714,21 +3569,21 @@ RenderingDevice::FramebufferFormatID RenderingDeviceVulkan::screen_get_framebuff attachment.usage_flags = TEXTURE_USAGE_COLOR_ATTACHMENT_BIT; Vector screen_attachment; screen_attachment.push_back(attachment); - return const_cast(this)->framebuffer_format_create(screen_attachment); + return const_cast(this)->framebuffer_format_create(screen_attachment); } /*******************/ /**** DRAW LIST ****/ /*******************/ -RenderingDevice::DrawListID RenderingDeviceVulkan::draw_list_begin_for_screen(DisplayServer::WindowID p_screen, const Color &p_clear_color) { +RenderingDevice::DrawListID RenderingDevice::draw_list_begin_for_screen(DisplayServer::WindowID p_screen, const Color &p_clear_color) { _THREAD_SAFE_METHOD_ ERR_FAIL_COND_V_MSG(local_device.is_valid(), INVALID_ID, "Local devices have no screen"); ERR_FAIL_COND_V_MSG(draw_list != nullptr, INVALID_ID, "Only one draw list can be active at the same time."); ERR_FAIL_COND_V_MSG(compute_list != nullptr, INVALID_ID, "Only one draw/compute list can be active at the same time."); - VkCommandBuffer command_buffer = frames[frame].draw_command_buffer; + RDD::CommandBufferID command_buffer = frames[frame].draw_command_buffer; if (!context->window_is_valid_swapchain(p_screen)) { return INVALID_ID; @@ -6742,54 +3597,23 @@ RenderingDevice::DrawListID RenderingDeviceVulkan::draw_list_begin_for_screen(Di #endif draw_list_subpass_count = 1; - VkRenderPassBeginInfo render_pass_begin; - render_pass_begin.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; - render_pass_begin.pNext = nullptr; - render_pass_begin.renderPass = context->window_get_render_pass(p_screen); - render_pass_begin.framebuffer = context->window_get_framebuffer(p_screen); - - render_pass_begin.renderArea.extent.width = size.width; - render_pass_begin.renderArea.extent.height = size.height; - render_pass_begin.renderArea.offset.x = 0; - render_pass_begin.renderArea.offset.y = 0; + RDD::RenderPassClearValue clear_value; + clear_value.color = p_clear_color; + driver->command_begin_render_pass( + command_buffer, + context->window_get_render_pass(p_screen), + context->window_get_framebuffer(p_screen), + RDD::COMMAND_BUFFER_TYPE_PRIMARY, + Rect2i(0, 0, size.width, size.height), + VectorView(&clear_value, 1)); - render_pass_begin.clearValueCount = 1; - - VkClearValue clear_value; - clear_value.color.float32[0] = p_clear_color.r; - clear_value.color.float32[1] = p_clear_color.g; - clear_value.color.float32[2] = p_clear_color.b; - clear_value.color.float32[3] = p_clear_color.a; - - render_pass_begin.pClearValues = &clear_value; - - vkCmdBeginRenderPass(command_buffer, &render_pass_begin, VK_SUBPASS_CONTENTS_INLINE); - - uint32_t size_x = screen_get_width(p_screen); - uint32_t size_y = screen_get_height(p_screen); - - VkViewport viewport; - viewport.x = 0; - viewport.y = 0; - viewport.width = size_x; - viewport.height = size_y; - viewport.minDepth = 0; - viewport.maxDepth = 1.0; - - vkCmdSetViewport(command_buffer, 0, 1, &viewport); - - VkRect2D scissor; - scissor.offset.x = 0; - scissor.offset.y = 0; - scissor.extent.width = size_x; - scissor.extent.height = size_y; - - vkCmdSetScissor(command_buffer, 0, 1, &scissor); + driver->command_render_set_viewport(command_buffer, Rect2i(Point2i(), size)); + driver->command_render_set_scissor(command_buffer, Rect2i(Point2i(), size)); return int64_t(ID_TYPE_DRAW_LIST) << ID_BASE_SHIFT; } -Error RenderingDeviceVulkan::_draw_list_setup_framebuffer(Framebuffer *p_framebuffer, InitialAction p_initial_color_action, FinalAction p_final_color_action, InitialAction p_initial_depth_action, FinalAction p_final_depth_action, VkFramebuffer *r_framebuffer, VkRenderPass *r_render_pass, uint32_t *r_subpass_count) { +Error RenderingDevice::_draw_list_setup_framebuffer(Framebuffer *p_framebuffer, InitialAction p_initial_color_action, FinalAction p_final_color_action, InitialAction p_initial_depth_action, FinalAction p_final_depth_action, RDD::FramebufferID *r_framebuffer, RDD::RenderPassID *r_render_pass, uint32_t *r_subpass_count) { Framebuffer::VersionKey vk; vk.initial_color_action = p_initial_color_action; vk.final_color_action = p_final_color_action; @@ -6803,30 +3627,20 @@ Error RenderingDeviceVulkan::_draw_list_setup_framebuffer(Framebuffer *p_framebu version.render_pass = _render_pass_create(framebuffer_formats[p_framebuffer->format_id].E->key().attachments, framebuffer_formats[p_framebuffer->format_id].E->key().passes, p_initial_color_action, p_final_color_action, p_initial_depth_action, p_final_depth_action, p_framebuffer->view_count); - VkFramebufferCreateInfo framebuffer_create_info; - framebuffer_create_info.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; - framebuffer_create_info.pNext = nullptr; - framebuffer_create_info.flags = 0; - framebuffer_create_info.renderPass = version.render_pass; - Vector attachments; + LocalVector attachments; for (int i = 0; i < p_framebuffer->texture_ids.size(); i++) { Texture *texture = texture_owner.get_or_null(p_framebuffer->texture_ids[i]); if (texture) { - attachments.push_back(texture->view); + attachments.push_back(texture->driver_id); if (!(texture->usage_flags & TEXTURE_USAGE_VRS_ATTACHMENT_BIT)) { // VRS attachment will be a different size. ERR_FAIL_COND_V(texture->width != p_framebuffer->size.width, ERR_BUG); ERR_FAIL_COND_V(texture->height != p_framebuffer->size.height, ERR_BUG); } } } - framebuffer_create_info.attachmentCount = attachments.size(); - framebuffer_create_info.pAttachments = attachments.ptr(); - framebuffer_create_info.width = p_framebuffer->size.width; - framebuffer_create_info.height = p_framebuffer->size.height; - framebuffer_create_info.layers = 1; - VkResult err = vkCreateFramebuffer(device, &framebuffer_create_info, nullptr, &version.framebuffer); - ERR_FAIL_COND_V_MSG(err, ERR_CANT_CREATE, "vkCreateFramebuffer failed with error " + itos(err) + "."); + version.framebuffer = driver->framebuffer_create(version.render_pass, attachments, p_framebuffer->size.width, p_framebuffer->size.height); + ERR_FAIL_COND_V(!version.framebuffer, ERR_CANT_CREATE); version.subpass_count = framebuffer_formats[p_framebuffer->format_id].E->key().passes.size(); @@ -6840,34 +3654,16 @@ Error RenderingDeviceVulkan::_draw_list_setup_framebuffer(Framebuffer *p_framebu return OK; } -Error RenderingDeviceVulkan::_draw_list_render_pass_begin(Framebuffer *framebuffer, InitialAction p_initial_color_action, FinalAction p_final_color_action, InitialAction p_initial_depth_action, FinalAction p_final_depth_action, const Vector &p_clear_colors, float p_clear_depth, uint32_t p_clear_stencil, Point2i viewport_offset, Point2i viewport_size, VkFramebuffer vkframebuffer, VkRenderPass render_pass, VkCommandBuffer command_buffer, VkSubpassContents subpass_contents, const Vector &p_storage_textures) { - VkRenderPassBeginInfo render_pass_begin; - render_pass_begin.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; - render_pass_begin.pNext = nullptr; - render_pass_begin.renderPass = render_pass; - render_pass_begin.framebuffer = vkframebuffer; - /* - * Given how API works, it makes sense to always fully operate on the whole framebuffer. - * This allows better continue operations for operations like shadowmapping. - render_pass_begin.renderArea.extent.width = viewport_size.width; - render_pass_begin.renderArea.extent.height = viewport_size.height; - render_pass_begin.renderArea.offset.x = viewport_offset.x; - render_pass_begin.renderArea.offset.y = viewport_offset.y; - */ - render_pass_begin.renderArea.extent.width = framebuffer->size.width; - render_pass_begin.renderArea.extent.height = framebuffer->size.height; - render_pass_begin.renderArea.offset.x = 0; - render_pass_begin.renderArea.offset.y = 0; - - Vector clear_values; - clear_values.resize(framebuffer->texture_ids.size()); +Error RenderingDevice::_draw_list_render_pass_begin(Framebuffer *p_framebuffer, InitialAction p_initial_color_action, FinalAction p_final_color_action, InitialAction p_initial_depth_action, FinalAction p_final_depth_action, const Vector &p_clear_colors, float p_clear_depth, uint32_t p_clear_stencil, Point2i p_viewport_offset, Point2i p_viewport_size, RDD::FramebufferID p_framebuffer_driver_id, RDD::RenderPassID p_render_pass, RDD::CommandBufferID p_command_buffer, RDD::CommandBufferType p_cmd_buffer_mode, const Vector &p_storage_textures) { + LocalVector clear_values; + clear_values.resize(p_framebuffer->texture_ids.size()); int clear_values_count = 0; { int color_index = 0; - for (int i = 0; i < framebuffer->texture_ids.size(); i++) { - VkClearValue clear_value; + for (int i = 0; i < p_framebuffer->texture_ids.size(); i++) { + RDD::RenderPassClearValue clear_value; - Texture *texture = texture_owner.get_or_null(framebuffer->texture_ids[i]); + Texture *texture = texture_owner.get_or_null(p_framebuffer->texture_ids[i]); if (!texture) { color_index++; continue; @@ -6875,28 +3671,17 @@ Error RenderingDeviceVulkan::_draw_list_render_pass_begin(Framebuffer *framebuff if (color_index < p_clear_colors.size() && texture->usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) { ERR_FAIL_INDEX_V(color_index, p_clear_colors.size(), ERR_BUG); // A bug. - Color clear_color = p_clear_colors[color_index]; - clear_value.color.float32[0] = clear_color.r; - clear_value.color.float32[1] = clear_color.g; - clear_value.color.float32[2] = clear_color.b; - clear_value.color.float32[3] = clear_color.a; + clear_value.color = p_clear_colors[color_index]; color_index++; } else if (texture->usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) { - clear_value.depthStencil.depth = p_clear_depth; - clear_value.depthStencil.stencil = p_clear_stencil; - } else { - clear_value.color.float32[0] = 0; - clear_value.color.float32[1] = 0; - clear_value.color.float32[2] = 0; - clear_value.color.float32[3] = 0; + clear_value.depth = p_clear_depth; + clear_value.stencil = p_clear_stencil; } - clear_values.write[clear_values_count++] = clear_value; + + clear_values[clear_values_count++] = clear_value; } } - render_pass_begin.clearValueCount = clear_values_count; - render_pass_begin.pClearValues = clear_values.ptr(); - for (int i = 0; i < p_storage_textures.size(); i++) { Texture *texture = texture_owner.get_or_null(p_storage_textures[i]); if (!texture) { @@ -6906,52 +3691,58 @@ Error RenderingDeviceVulkan::_draw_list_render_pass_begin(Framebuffer *framebuff if (texture->usage_flags & TEXTURE_USAGE_SAMPLING_BIT) { // Must change layout to general. - VkImageMemoryBarrier image_memory_barrier; - image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; - image_memory_barrier.pNext = nullptr; - image_memory_barrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; - image_memory_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; - image_memory_barrier.oldLayout = texture->layout; - image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_GENERAL; - - image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - image_memory_barrier.image = texture->image; - image_memory_barrier.subresourceRange.aspectMask = texture->read_aspect_mask; - image_memory_barrier.subresourceRange.baseMipLevel = texture->base_mipmap; - image_memory_barrier.subresourceRange.levelCount = texture->mipmaps; - image_memory_barrier.subresourceRange.baseArrayLayer = texture->base_layer; - image_memory_barrier.subresourceRange.layerCount = texture->layers; - - vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, VK_PIPELINE_STAGE_VERTEX_INPUT_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier); - - texture->layout = VK_IMAGE_LAYOUT_GENERAL; + RDD::TextureBarrier tb; + tb.texture = texture->driver_id; + tb.src_access = (RDD::BARRIER_ACCESS_SHADER_READ_BIT | RDD::BARRIER_ACCESS_SHADER_WRITE_BIT); + tb.dst_access = (RDD::BARRIER_ACCESS_SHADER_READ_BIT | RDD::BARRIER_ACCESS_SHADER_WRITE_BIT); + tb.prev_layout = texture->layout; + tb.next_layout = RDD::TEXTURE_LAYOUT_GENERAL; + tb.subresources.aspect = texture->read_aspect_flags; + tb.subresources.base_mipmap = texture->base_mipmap; + tb.subresources.mipmap_count = texture->mipmaps; + tb.subresources.base_layer = texture->base_layer; + tb.subresources.layer_count = texture->layers; + + driver->command_pipeline_barrier(p_command_buffer, RDD::PIPELINE_STAGE_COMPUTE_SHADER_BIT | RDD::PIPELINE_STAGE_FRAGMENT_SHADER_BIT, RDD::PIPELINE_STAGE_VERTEX_INPUT_BIT | RDD::PIPELINE_STAGE_FRAGMENT_SHADER_BIT, {}, {}, tb); + + texture->layout = RDD::TEXTURE_LAYOUT_GENERAL; draw_list_storage_textures.push_back(p_storage_textures[i]); } } - vkCmdBeginRenderPass(command_buffer, &render_pass_begin, subpass_contents); + driver->command_begin_render_pass( + p_command_buffer, + p_render_pass, + p_framebuffer_driver_id, + p_cmd_buffer_mode, + /* + * Given how API works, it makes sense to always fully operate on the whole framebuffer. + * This allows better continue operations for operations like shadowmapping. + * Rect2i(p_viewport_offset.x, p_viewport_offset.y, p_viewport_size.x, p_viewport_size.y) + */ + Rect2i(Point2i(), p_framebuffer->size), + clear_values); // Mark textures as bound. draw_list_bound_textures.clear(); draw_list_unbind_color_textures = p_final_color_action != FINAL_ACTION_CONTINUE; draw_list_unbind_depth_textures = p_final_depth_action != FINAL_ACTION_CONTINUE; - for (int i = 0; i < framebuffer->texture_ids.size(); i++) { - Texture *texture = texture_owner.get_or_null(framebuffer->texture_ids[i]); + for (int i = 0; i < p_framebuffer->texture_ids.size(); i++) { + Texture *texture = texture_owner.get_or_null(p_framebuffer->texture_ids[i]); if (!texture) { continue; } texture->bound = true; - draw_list_bound_textures.push_back(framebuffer->texture_ids[i]); + draw_list_bound_textures.push_back(p_framebuffer->texture_ids[i]); } return OK; } -void RenderingDeviceVulkan::_draw_list_insert_clear_region(DrawList *p_draw_list, Framebuffer *p_framebuffer, Point2i p_viewport_offset, Point2i p_viewport_size, bool p_clear_color, const Vector &p_clear_colors, bool p_clear_depth, float p_depth, uint32_t p_stencil) { - Vector clear_attachments; +void RenderingDevice::_draw_list_insert_clear_region(DrawList *p_draw_list, Framebuffer *p_framebuffer, Point2i p_viewport_offset, Point2i p_viewport_size, bool p_clear_color, const Vector &p_clear_colors, bool p_clear_depth, float p_depth, uint32_t p_stencil) { + LocalVector clear_attachments; int color_index = 0; int texture_index = 0; for (int i = 0; i < p_framebuffer->texture_ids.size(); i++) { @@ -6962,22 +3753,19 @@ void RenderingDeviceVulkan::_draw_list_insert_clear_region(DrawList *p_draw_list continue; } - VkClearAttachment clear_at = {}; - if (p_clear_color && texture->usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) { + RDD::AttachmentClear clear_at; + if (p_clear_color && (texture->usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT)) { Color clear_color = p_clear_colors[texture_index++]; - clear_at.clearValue.color.float32[0] = clear_color.r; - clear_at.clearValue.color.float32[1] = clear_color.g; - clear_at.clearValue.color.float32[2] = clear_color.b; - clear_at.clearValue.color.float32[3] = clear_color.a; - clear_at.colorAttachment = color_index++; - clear_at.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - } else if (p_clear_depth && texture->usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) { - clear_at.clearValue.depthStencil.depth = p_depth; - clear_at.clearValue.depthStencil.stencil = p_stencil; - clear_at.colorAttachment = 0; - clear_at.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT; + clear_at.value.color = clear_color; + clear_at.color_attachment = color_index++; + clear_at.aspect = RDD::TEXTURE_ASPECT_COLOR_BIT; + } else if (p_clear_depth && (texture->usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) { + clear_at.value.depth = p_depth; + clear_at.value.stencil = p_stencil; + clear_at.color_attachment = 0; + clear_at.aspect = RDD::TEXTURE_ASPECT_DEPTH_BIT; if (format_has_stencil(texture->format)) { - clear_at.aspectMask |= VK_IMAGE_ASPECT_STENCIL_BIT; + clear_at.aspect.set_flag(RDD::TEXTURE_ASPECT_STENCIL_BIT); } } else { ERR_CONTINUE(true); @@ -6985,18 +3773,15 @@ void RenderingDeviceVulkan::_draw_list_insert_clear_region(DrawList *p_draw_list clear_attachments.push_back(clear_at); } - VkClearRect cr; - cr.baseArrayLayer = 0; - cr.layerCount = 1; - cr.rect.offset.x = p_viewport_offset.x; - cr.rect.offset.y = p_viewport_offset.y; - cr.rect.extent.width = p_viewport_size.width; - cr.rect.extent.height = p_viewport_size.height; + RDD::AttachmentClearRect cr; + cr.rect = Rect2i(p_viewport_offset, p_viewport_size); + cr.base_layer = 0; + cr.layer_count = 1; - vkCmdClearAttachments(p_draw_list->command_buffer, clear_attachments.size(), clear_attachments.ptr(), 1, &cr); + driver->command_render_clear_attachments(p_draw_list->command_buffer, clear_attachments, cr); } -RenderingDevice::DrawListID RenderingDeviceVulkan::draw_list_begin(RID p_framebuffer, InitialAction p_initial_color_action, FinalAction p_final_color_action, InitialAction p_initial_depth_action, FinalAction p_final_depth_action, const Vector &p_clear_color_values, float p_clear_depth, uint32_t p_clear_stencil, const Rect2 &p_region, const Vector &p_storage_textures) { +RenderingDevice::DrawListID RenderingDevice::draw_list_begin(RID p_framebuffer, InitialAction p_initial_color_action, FinalAction p_final_color_action, InitialAction p_initial_depth_action, FinalAction p_final_depth_action, const Vector &p_clear_color_values, float p_clear_depth, uint32_t p_clear_stencil, const Rect2 &p_region, const Vector &p_storage_textures) { _THREAD_SAFE_METHOD_ ERR_FAIL_COND_V_MSG(draw_list != nullptr, INVALID_ID, "Only one draw list can be active at the same time."); @@ -7055,21 +3840,21 @@ RenderingDevice::DrawListID RenderingDeviceVulkan::draw_list_begin(RID p_framebu ERR_FAIL_COND_V_MSG(p_clear_color_values.size() != color_count, INVALID_ID, "Clear color values supplied (" + itos(p_clear_color_values.size()) + ") differ from the amount required for framebuffer color attachments (" + itos(color_count) + ")."); } - VkFramebuffer vkframebuffer; - VkRenderPass render_pass; + RDD::FramebufferID fb_driver_id; + RDD::RenderPassID render_pass; - Error err = _draw_list_setup_framebuffer(framebuffer, p_initial_color_action, p_final_color_action, p_initial_depth_action, p_final_depth_action, &vkframebuffer, &render_pass, &draw_list_subpass_count); + Error err = _draw_list_setup_framebuffer(framebuffer, p_initial_color_action, p_final_color_action, p_initial_depth_action, p_final_depth_action, &fb_driver_id, &render_pass, &draw_list_subpass_count); ERR_FAIL_COND_V(err != OK, INVALID_ID); - VkCommandBuffer command_buffer = frames[frame].draw_command_buffer; - err = _draw_list_render_pass_begin(framebuffer, p_initial_color_action, p_final_color_action, p_initial_depth_action, p_final_depth_action, p_clear_color_values, p_clear_depth, p_clear_stencil, viewport_offset, viewport_size, vkframebuffer, render_pass, command_buffer, VK_SUBPASS_CONTENTS_INLINE, p_storage_textures); + RDD::CommandBufferID command_buffer = frames[frame].draw_command_buffer; + err = _draw_list_render_pass_begin(framebuffer, p_initial_color_action, p_final_color_action, p_initial_depth_action, p_final_depth_action, p_clear_color_values, p_clear_depth, p_clear_stencil, viewport_offset, viewport_size, fb_driver_id, render_pass, command_buffer, RDD::COMMAND_BUFFER_TYPE_PRIMARY, p_storage_textures); if (err != OK) { return INVALID_ID; } draw_list_render_pass = render_pass; - draw_list_vkframebuffer = vkframebuffer; + draw_list_vkframebuffer = fb_driver_id; _draw_list_allocate(Rect2i(viewport_offset, viewport_size), 0, 0); #ifdef DEBUG_ENABLED @@ -7081,28 +3866,13 @@ RenderingDevice::DrawListID RenderingDeviceVulkan::draw_list_begin(RID p_framebu _draw_list_insert_clear_region(draw_list, framebuffer, viewport_offset, viewport_size, needs_clear_color, p_clear_color_values, needs_clear_depth, p_clear_depth, p_clear_stencil); } - VkViewport viewport; - viewport.x = viewport_offset.x; - viewport.y = viewport_offset.y; - viewport.width = viewport_size.width; - viewport.height = viewport_size.height; - viewport.minDepth = 0; - viewport.maxDepth = 1.0; - - vkCmdSetViewport(command_buffer, 0, 1, &viewport); - - VkRect2D scissor; - scissor.offset.x = viewport_offset.x; - scissor.offset.y = viewport_offset.y; - scissor.extent.width = viewport_size.width; - scissor.extent.height = viewport_size.height; - - vkCmdSetScissor(command_buffer, 0, 1, &scissor); + driver->command_render_set_viewport(command_buffer, Rect2i(viewport_offset, viewport_size)); + driver->command_render_set_scissor(command_buffer, Rect2i(viewport_offset, viewport_size)); return int64_t(ID_TYPE_DRAW_LIST) << ID_BASE_SHIFT; } -Error RenderingDeviceVulkan::draw_list_begin_split(RID p_framebuffer, uint32_t p_splits, DrawListID *r_split_ids, InitialAction p_initial_color_action, FinalAction p_final_color_action, InitialAction p_initial_depth_action, FinalAction p_final_depth_action, const Vector &p_clear_color_values, float p_clear_depth, uint32_t p_clear_stencil, const Rect2 &p_region, const Vector &p_storage_textures) { +Error RenderingDevice::draw_list_begin_split(RID p_framebuffer, uint32_t p_splits, DrawListID *r_split_ids, InitialAction p_initial_color_action, FinalAction p_final_color_action, InitialAction p_initial_depth_action, FinalAction p_final_depth_action, const Vector &p_clear_color_values, float p_clear_depth, uint32_t p_clear_stencil, const Rect2 &p_region, const Vector &p_storage_textures) { _THREAD_SAFE_METHOD_ ERR_FAIL_COND_V_MSG(draw_list != nullptr, ERR_BUSY, "Only one draw list can be active at the same time."); @@ -7156,14 +3926,14 @@ Error RenderingDeviceVulkan::draw_list_begin_split(RID p_framebuffer, uint32_t p "Clear color values supplied (" + itos(p_clear_color_values.size()) + ") differ from the amount required for framebuffer (" + itos(color_count) + ")."); } - VkFramebuffer vkframebuffer; - VkRenderPass render_pass; + RDD::FramebufferID fb_driver_id; + RDD::RenderPassID render_pass; - Error err = _draw_list_setup_framebuffer(framebuffer, p_initial_color_action, p_final_color_action, p_initial_depth_action, p_final_depth_action, &vkframebuffer, &render_pass, &draw_list_subpass_count); + Error err = _draw_list_setup_framebuffer(framebuffer, p_initial_color_action, p_final_color_action, p_initial_depth_action, p_final_depth_action, &fb_driver_id, &render_pass, &draw_list_subpass_count); ERR_FAIL_COND_V(err != OK, ERR_CANT_CREATE); - VkCommandBuffer frame_command_buffer = frames[frame].draw_command_buffer; - err = _draw_list_render_pass_begin(framebuffer, p_initial_color_action, p_final_color_action, p_initial_depth_action, p_final_depth_action, p_clear_color_values, p_clear_depth, p_clear_stencil, viewport_offset, viewport_size, vkframebuffer, render_pass, frame_command_buffer, VK_SUBPASS_CONTENTS_SECONDARY_COMMAND_BUFFERS, p_storage_textures); + RDD::CommandBufferID frame_command_buffer = frames[frame].draw_command_buffer; + err = _draw_list_render_pass_begin(framebuffer, p_initial_color_action, p_final_color_action, p_initial_depth_action, p_final_depth_action, p_clear_color_values, p_clear_depth, p_clear_stencil, viewport_offset, viewport_size, fb_driver_id, render_pass, frame_command_buffer, RDD::COMMAND_BUFFER_TYPE_SECONDARY, p_storage_textures); if (err != OK) { return ERR_CANT_CREATE; @@ -7175,7 +3945,7 @@ Error RenderingDeviceVulkan::draw_list_begin_split(RID p_framebuffer, uint32_t p draw_list_framebuffer_format = framebuffer->format_id; #endif draw_list_render_pass = render_pass; - draw_list_vkframebuffer = vkframebuffer; + draw_list_vkframebuffer = fb_driver_id; err = _draw_list_allocate(Rect2i(viewport_offset, viewport_size), p_splits, 0); if (err != OK) { @@ -7187,30 +3957,15 @@ Error RenderingDeviceVulkan::draw_list_begin_split(RID p_framebuffer, uint32_t p } for (uint32_t i = 0; i < p_splits; i++) { - VkViewport viewport; - viewport.x = viewport_offset.x; - viewport.y = viewport_offset.y; - viewport.width = viewport_size.width; - viewport.height = viewport_size.height; - viewport.minDepth = 0; - viewport.maxDepth = 1.0; - - vkCmdSetViewport(draw_list[i].command_buffer, 0, 1, &viewport); - - VkRect2D scissor; - scissor.offset.x = viewport_offset.x; - scissor.offset.y = viewport_offset.y; - scissor.extent.width = viewport_size.width; - scissor.extent.height = viewport_size.height; - - vkCmdSetScissor(draw_list[i].command_buffer, 0, 1, &scissor); + driver->command_render_set_viewport(draw_list[i].command_buffer, Rect2i(viewport_offset, viewport_size)); + driver->command_render_set_scissor(draw_list[i].command_buffer, Rect2i(viewport_offset, viewport_size)); r_split_ids[i] = (int64_t(ID_TYPE_SPLIT_DRAW_LIST) << ID_BASE_SHIFT) + i; } return OK; } -RenderingDeviceVulkan::DrawList *RenderingDeviceVulkan::_get_draw_list_ptr(DrawListID p_id) { +RenderingDevice::DrawList *RenderingDevice::_get_draw_list_ptr(DrawListID p_id) { if (p_id < 0) { return nullptr; } @@ -7239,17 +3994,17 @@ RenderingDeviceVulkan::DrawList *RenderingDeviceVulkan::_get_draw_list_ptr(DrawL } } -void RenderingDeviceVulkan::draw_list_set_blend_constants(DrawListID p_list, const Color &p_color) { +void RenderingDevice::draw_list_set_blend_constants(DrawListID p_list, const Color &p_color) { DrawList *dl = _get_draw_list_ptr(p_list); ERR_FAIL_NULL(dl); #ifdef DEBUG_ENABLED ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified."); #endif - vkCmdSetBlendConstants(dl->command_buffer, p_color.components); + driver->command_render_set_blend_constants(dl->command_buffer, p_color); } -void RenderingDeviceVulkan::draw_list_bind_render_pipeline(DrawListID p_list, RID p_render_pipeline) { +void RenderingDevice::draw_list_bind_render_pipeline(DrawListID p_list, RID p_render_pipeline) { DrawList *dl = _get_draw_list_ptr(p_list); ERR_FAIL_NULL(dl); #ifdef DEBUG_ENABLED @@ -7267,9 +4022,8 @@ void RenderingDeviceVulkan::draw_list_bind_render_pipeline(DrawListID p_list, RI } dl->state.pipeline = p_render_pipeline; - dl->state.pipeline_layout = pipeline->pipeline_layout; - vkCmdBindPipeline(dl->command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline->pipeline); + driver->command_bind_render_pipeline(dl->command_buffer, pipeline->driver_id); if (dl->state.pipeline_shader != pipeline->shader) { // Shader changed, so descriptor sets may become incompatible. @@ -7298,13 +4052,13 @@ void RenderingDeviceVulkan::draw_list_bind_render_pipeline(DrawListID p_list, RI dl->state.set_count = pcount; // Update set count. if (pipeline->push_constant_size) { - dl->state.pipeline_push_constant_stages = pipeline->push_constant_stages_mask; #ifdef DEBUG_ENABLED dl->validation.pipeline_push_constant_supplied = false; #endif } dl->state.pipeline_shader = pipeline->shader; + dl->state.pipeline_shader_driver_id = pipeline->shader_driver_id; } #ifdef DEBUG_ENABLED @@ -7319,10 +4073,10 @@ void RenderingDeviceVulkan::draw_list_bind_render_pipeline(DrawListID p_list, RI #endif } -void RenderingDeviceVulkan::draw_list_bind_uniform_set(DrawListID p_list, RID p_uniform_set, uint32_t p_index) { +void RenderingDevice::draw_list_bind_uniform_set(DrawListID p_list, RID p_uniform_set, uint32_t p_index) { #ifdef DEBUG_ENABLED - ERR_FAIL_COND_MSG(p_index >= limits.maxBoundDescriptorSets || p_index >= MAX_UNIFORM_SETS, - "Attempting to bind a descriptor set (" + itos(p_index) + ") greater than what the hardware supports (" + itos(limits.maxBoundDescriptorSets) + ")."); + ERR_FAIL_COND_MSG(p_index >= driver->limit_get(LIMIT_MAX_BOUND_UNIFORM_SETS) || p_index >= MAX_UNIFORM_SETS, + "Attempting to bind a descriptor set (" + itos(p_index) + ") greater than what the hardware supports (" + itos(driver->limit_get(LIMIT_MAX_BOUND_UNIFORM_SETS)) + ")."); #endif DrawList *dl = _get_draw_list_ptr(p_list); ERR_FAIL_NULL(dl); @@ -7338,7 +4092,7 @@ void RenderingDeviceVulkan::draw_list_bind_uniform_set(DrawListID p_list, RID p_ dl->state.set_count = p_index; } - dl->state.sets[p_index].descriptor_set = uniform_set->descriptor_set; // Update set pointer. + dl->state.sets[p_index].uniform_set_driver_id = uniform_set->driver_id; // Update set pointer. dl->state.sets[p_index].bound = false; // Needs rebind. dl->state.sets[p_index].uniform_set_format = uniform_set->format; dl->state.sets[p_index].uniform_set = p_uniform_set; @@ -7372,7 +4126,7 @@ void RenderingDeviceVulkan::draw_list_bind_uniform_set(DrawListID p_list, RID p_ #endif } -void RenderingDeviceVulkan::draw_list_bind_vertex_array(DrawListID p_list, RID p_vertex_array) { +void RenderingDevice::draw_list_bind_vertex_array(DrawListID p_list, RID p_vertex_array) { DrawList *dl = _get_draw_list_ptr(p_list); ERR_FAIL_NULL(dl); #ifdef DEBUG_ENABLED @@ -7393,10 +4147,10 @@ void RenderingDeviceVulkan::draw_list_bind_vertex_array(DrawListID p_list, RID p dl->validation.vertex_max_instances_allowed = vertex_array->max_instances_allowed; #endif dl->validation.vertex_array_size = vertex_array->vertex_count; - vkCmdBindVertexBuffers(dl->command_buffer, 0, vertex_array->buffers.size(), vertex_array->buffers.ptr(), vertex_array->offsets.ptr()); + driver->command_render_bind_vertex_buffers(dl->command_buffer, vertex_array->buffers.size(), vertex_array->buffers.ptr(), vertex_array->offsets.ptr()); } -void RenderingDeviceVulkan::draw_list_bind_index_array(DrawListID p_list, RID p_index_array) { +void RenderingDevice::draw_list_bind_index_array(DrawListID p_list, RID p_index_array) { DrawList *dl = _get_draw_list_ptr(p_list); ERR_FAIL_NULL(dl); #ifdef DEBUG_ENABLED @@ -7417,20 +4171,20 @@ void RenderingDeviceVulkan::draw_list_bind_index_array(DrawListID p_list, RID p_ dl->validation.index_array_size = index_array->indices; dl->validation.index_array_offset = index_array->offset; - vkCmdBindIndexBuffer(dl->command_buffer, index_array->buffer, 0, index_array->index_type); + driver->command_render_bind_index_buffer(dl->command_buffer, index_array->driver_id, index_array->format, index_array->offset); } -void RenderingDeviceVulkan::draw_list_set_line_width(DrawListID p_list, float p_width) { +void RenderingDevice::draw_list_set_line_width(DrawListID p_list, float p_width) { DrawList *dl = _get_draw_list_ptr(p_list); ERR_FAIL_NULL(dl); #ifdef DEBUG_ENABLED ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified."); #endif - vkCmdSetLineWidth(dl->command_buffer, p_width); + driver->command_render_set_line_width(dl->command_buffer, p_width); } -void RenderingDeviceVulkan::draw_list_set_push_constant(DrawListID p_list, const void *p_data, uint32_t p_data_size) { +void RenderingDevice::draw_list_set_push_constant(DrawListID p_list, const void *p_data, uint32_t p_data_size) { DrawList *dl = _get_draw_list_ptr(p_list); ERR_FAIL_NULL(dl); @@ -7442,13 +4196,13 @@ void RenderingDeviceVulkan::draw_list_set_push_constant(DrawListID p_list, const ERR_FAIL_COND_MSG(p_data_size != dl->validation.pipeline_push_constant_size, "This render pipeline requires (" + itos(dl->validation.pipeline_push_constant_size) + ") bytes of push constant data, supplied: (" + itos(p_data_size) + ")"); #endif - vkCmdPushConstants(dl->command_buffer, dl->state.pipeline_layout, dl->state.pipeline_push_constant_stages, 0, p_data_size, p_data); + driver->command_bind_push_constants(dl->command_buffer, dl->state.pipeline_shader_driver_id, 0, VectorView((const uint32_t *)p_data, p_data_size / sizeof(uint32_t))); #ifdef DEBUG_ENABLED dl->validation.pipeline_push_constant_supplied = true; #endif } -void RenderingDeviceVulkan::draw_list_draw(DrawListID p_list, bool p_use_indices, uint32_t p_instances, uint32_t p_procedural_vertices) { +void RenderingDevice::draw_list_draw(DrawListID p_list, bool p_use_indices, uint32_t p_instances, uint32_t p_procedural_vertices) { DrawList *dl = _get_draw_list_ptr(p_list); ERR_FAIL_NULL(dl); #ifdef DEBUG_ENABLED @@ -7498,7 +4252,7 @@ void RenderingDeviceVulkan::draw_list_draw(DrawListID p_list, bool p_use_indices #endif if (!dl->state.sets[i].bound) { // All good, see if this requires re-binding. - vkCmdBindDescriptorSets(dl->command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, dl->state.pipeline_layout, i, 1, &dl->state.sets[i].descriptor_set, 0, nullptr); + driver->command_bind_render_uniform_set(dl->command_buffer, dl->state.sets[i].uniform_set_driver_id, dl->state.pipeline_shader_driver_id, i); dl->state.sets[i].bound = true; } } @@ -7523,7 +4277,7 @@ void RenderingDeviceVulkan::draw_list_draw(DrawListID p_list, bool p_use_indices ERR_FAIL_COND_MSG((to_draw % dl->validation.pipeline_primitive_divisor) != 0, "Index amount (" + itos(to_draw) + ") must be a multiple of the amount of indices required by the render primitive (" + itos(dl->validation.pipeline_primitive_divisor) + ")."); #endif - vkCmdDrawIndexed(dl->command_buffer, to_draw, p_instances, dl->validation.index_array_offset, 0, 0); + driver->command_render_draw_indexed(dl->command_buffer, to_draw, p_instances, dl->validation.index_array_offset, 0, 0); } else { uint32_t to_draw; @@ -7549,11 +4303,11 @@ void RenderingDeviceVulkan::draw_list_draw(DrawListID p_list, bool p_use_indices "Vertex amount (" + itos(to_draw) + ") must be a multiple of the amount of vertices required by the render primitive (" + itos(dl->validation.pipeline_primitive_divisor) + ")."); #endif - vkCmdDraw(dl->command_buffer, to_draw, p_instances, 0, 0); + driver->command_render_draw(dl->command_buffer, to_draw, p_instances, 0, 0); } } -void RenderingDeviceVulkan::draw_list_enable_scissor(DrawListID p_list, const Rect2 &p_rect) { +void RenderingDevice::draw_list_enable_scissor(DrawListID p_list, const Rect2 &p_rect) { DrawList *dl = _get_draw_list_ptr(p_list); ERR_FAIL_NULL(dl); @@ -7568,37 +4322,27 @@ void RenderingDeviceVulkan::draw_list_enable_scissor(DrawListID p_list, const Re if (rect.get_area() == 0) { return; } - VkRect2D scissor; - scissor.offset.x = rect.position.x; - scissor.offset.y = rect.position.y; - scissor.extent.width = rect.size.width; - scissor.extent.height = rect.size.height; - vkCmdSetScissor(dl->command_buffer, 0, 1, &scissor); + driver->command_render_set_scissor(dl->command_buffer, rect); } -void RenderingDeviceVulkan::draw_list_disable_scissor(DrawListID p_list) { +void RenderingDevice::draw_list_disable_scissor(DrawListID p_list) { DrawList *dl = _get_draw_list_ptr(p_list); ERR_FAIL_NULL(dl); #ifdef DEBUG_ENABLED ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified."); #endif - VkRect2D scissor; - scissor.offset.x = dl->viewport.position.x; - scissor.offset.y = dl->viewport.position.y; - scissor.extent.width = dl->viewport.size.width; - scissor.extent.height = dl->viewport.size.height; - vkCmdSetScissor(dl->command_buffer, 0, 1, &scissor); + driver->command_render_set_scissor(dl->command_buffer, dl->viewport); } -uint32_t RenderingDeviceVulkan::draw_list_get_current_pass() { +uint32_t RenderingDevice::draw_list_get_current_pass() { return draw_list_current_subpass; } -RenderingDevice::DrawListID RenderingDeviceVulkan::draw_list_switch_to_next_pass() { +RenderingDevice::DrawListID RenderingDevice::draw_list_switch_to_next_pass() { _THREAD_SAFE_METHOD_ - ERR_FAIL_NULL_V(draw_list, INVALID_ID); + ERR_FAIL_COND_V(draw_list == nullptr, INVALID_ID); ERR_FAIL_COND_V(draw_list_current_subpass >= draw_list_subpass_count - 1, INVALID_FORMAT_ID); draw_list_current_subpass++; @@ -7606,15 +4350,15 @@ RenderingDevice::DrawListID RenderingDeviceVulkan::draw_list_switch_to_next_pass Rect2i viewport; _draw_list_free(&viewport); - vkCmdNextSubpass(frames[frame].draw_command_buffer, VK_SUBPASS_CONTENTS_INLINE); + driver->command_next_render_subpass(frames[frame].draw_command_buffer, RDD::COMMAND_BUFFER_TYPE_PRIMARY); _draw_list_allocate(viewport, 0, draw_list_current_subpass); return int64_t(ID_TYPE_DRAW_LIST) << ID_BASE_SHIFT; } -Error RenderingDeviceVulkan::draw_list_switch_to_next_pass_split(uint32_t p_splits, DrawListID *r_split_ids) { +Error RenderingDevice::draw_list_switch_to_next_pass_split(uint32_t p_splits, DrawListID *r_split_ids) { _THREAD_SAFE_METHOD_ - ERR_FAIL_NULL_V(draw_list, ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(draw_list == nullptr, ERR_INVALID_PARAMETER); ERR_FAIL_COND_V(draw_list_current_subpass >= draw_list_subpass_count - 1, ERR_INVALID_PARAMETER); draw_list_current_subpass++; @@ -7622,7 +4366,7 @@ Error RenderingDeviceVulkan::draw_list_switch_to_next_pass_split(uint32_t p_spli Rect2i viewport; _draw_list_free(&viewport); - vkCmdNextSubpass(frames[frame].draw_command_buffer, VK_SUBPASS_CONTENTS_INLINE); + driver->command_next_render_subpass(frames[frame].draw_command_buffer, RDD::COMMAND_BUFFER_TYPE_PRIMARY); _draw_list_allocate(viewport, p_splits, draw_list_current_subpass); @@ -7633,7 +4377,7 @@ Error RenderingDeviceVulkan::draw_list_switch_to_next_pass_split(uint32_t p_spli return OK; } -Error RenderingDeviceVulkan::_draw_list_allocate(const Rect2i &p_viewport, uint32_t p_splits, uint32_t p_subpass) { +Error RenderingDevice::_draw_list_allocate(const Rect2i &p_viewport, uint32_t p_splits, uint32_t p_subpass) { // Lock while draw_list is active. _THREAD_SAFE_LOCK_ @@ -7648,30 +4392,14 @@ Error RenderingDeviceVulkan::_draw_list_allocate(const Rect2i &p_viewport, uint3 uint32_t from = split_draw_list_allocators.size(); split_draw_list_allocators.resize(p_splits); for (uint32_t i = from; i < p_splits; i++) { - VkCommandPoolCreateInfo cmd_pool_info; - cmd_pool_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; - cmd_pool_info.pNext = nullptr; - cmd_pool_info.queueFamilyIndex = context->get_graphics_queue_family_index(); - cmd_pool_info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; - - VkResult res = vkCreateCommandPool(device, &cmd_pool_info, nullptr, &split_draw_list_allocators.write[i].command_pool); - ERR_FAIL_COND_V_MSG(res, ERR_CANT_CREATE, "vkCreateCommandPool failed with error " + itos(res) + "."); + RDD::CommandPoolID cmd_pool = driver->command_pool_create(); + ERR_FAIL_COND_V(!cmd_pool, ERR_CANT_CREATE); + split_draw_list_allocators.write[i].command_pool = cmd_pool; for (int j = 0; j < frame_count; j++) { - VkCommandBuffer command_buffer; - - VkCommandBufferAllocateInfo cmdbuf; - // No command buffer exists, create it. - cmdbuf.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; - cmdbuf.pNext = nullptr; - cmdbuf.commandPool = split_draw_list_allocators[i].command_pool; - cmdbuf.level = VK_COMMAND_BUFFER_LEVEL_SECONDARY; - cmdbuf.commandBufferCount = 1; - - VkResult err = vkAllocateCommandBuffers(device, &cmdbuf, &command_buffer); - ERR_FAIL_COND_V_MSG(err, ERR_CANT_CREATE, "vkAllocateCommandBuffers failed with error " + itos(err) + "."); - - split_draw_list_allocators.write[i].command_buffers.push_back(command_buffer); + RDD::CommandBufferID cmd_buffer = driver->command_buffer_create(RDD::COMMAND_BUFFER_TYPE_SECONDARY, cmd_pool); + ERR_FAIL_COND_V(!cmd_buffer, ERR_CANT_CREATE); + split_draw_list_allocators.write[i].command_buffers.push_back(cmd_buffer); } } } @@ -7681,39 +4409,16 @@ Error RenderingDeviceVulkan::_draw_list_allocate(const Rect2i &p_viewport, uint3 for (uint32_t i = 0; i < p_splits; i++) { // Take a command buffer and initialize it. - VkCommandBuffer command_buffer = split_draw_list_allocators[i].command_buffers[frame]; - - VkCommandBufferInheritanceInfo inheritance_info; - inheritance_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_INFO; - inheritance_info.pNext = nullptr; - inheritance_info.renderPass = draw_list_render_pass; - inheritance_info.subpass = p_subpass; - inheritance_info.framebuffer = draw_list_vkframebuffer; - inheritance_info.occlusionQueryEnable = false; - inheritance_info.queryFlags = 0; // ? - inheritance_info.pipelineStatistics = 0; - - VkCommandBufferBeginInfo cmdbuf_begin; - cmdbuf_begin.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; - cmdbuf_begin.pNext = nullptr; - cmdbuf_begin.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT | VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT; - cmdbuf_begin.pInheritanceInfo = &inheritance_info; - - VkResult res = vkResetCommandBuffer(command_buffer, 0); - if (res) { - memdelete_arr(draw_list); - draw_list = nullptr; - ERR_FAIL_V_MSG(ERR_CANT_CREATE, "vkResetCommandBuffer failed with error " + itos(res) + "."); - } + RDD::CommandBufferID cmd_buffer = split_draw_list_allocators[i].command_buffers[frame]; - res = vkBeginCommandBuffer(command_buffer, &cmdbuf_begin); - if (res) { + bool ok = driver->command_buffer_begin_secondary(cmd_buffer, draw_list_render_pass, p_subpass, draw_list_vkframebuffer); + if (!ok) { memdelete_arr(draw_list); draw_list = nullptr; - ERR_FAIL_V_MSG(ERR_CANT_CREATE, "vkBeginCommandBuffer failed with error " + itos(res) + "."); + ERR_FAIL_V(ERR_CANT_CREATE); } - draw_list[i].command_buffer = command_buffer; + draw_list[i].command_buffer = cmd_buffer; draw_list[i].viewport = p_viewport; } } @@ -7721,12 +4426,12 @@ Error RenderingDeviceVulkan::_draw_list_allocate(const Rect2i &p_viewport, uint3 return OK; } -void RenderingDeviceVulkan::_draw_list_free(Rect2i *r_last_viewport) { +void RenderingDevice::_draw_list_free(Rect2i *r_last_viewport) { if (draw_list_split) { // Send all command buffers. - VkCommandBuffer *command_buffers = (VkCommandBuffer *)alloca(sizeof(VkCommandBuffer) * draw_list_count); + RDD::CommandBufferID *command_buffers = (RDD::CommandBufferID *)alloca(sizeof(RDD::CommandBufferID) * draw_list_count); for (uint32_t i = 0; i < draw_list_count; i++) { - vkEndCommandBuffer(draw_list[i].command_buffer); + driver->command_buffer_end(draw_list[i].command_buffer); command_buffers[i] = draw_list[i].command_buffer; if (r_last_viewport) { if (i == 0 || draw_list[i].viewport_set) { @@ -7735,7 +4440,7 @@ void RenderingDeviceVulkan::_draw_list_free(Rect2i *r_last_viewport) { } } - vkCmdExecuteCommands(frames[frame].draw_command_buffer, draw_list_count, command_buffers); + driver->command_buffer_execute_secondary(frames[frame].draw_command_buffer, VectorView(command_buffers, draw_list_count)); memdelete_arr(draw_list); draw_list = nullptr; @@ -7752,14 +4457,14 @@ void RenderingDeviceVulkan::_draw_list_free(Rect2i *r_last_viewport) { _THREAD_SAFE_UNLOCK_ } -void RenderingDeviceVulkan::draw_list_end(BitField p_post_barrier) { +void RenderingDevice::draw_list_end(BitField p_post_barrier) { _THREAD_SAFE_METHOD_ - ERR_FAIL_NULL_MSG(draw_list, "Immediate draw list is already inactive."); + ERR_FAIL_COND_MSG(!draw_list, "Immediate draw list is already inactive."); _draw_list_free(); - vkCmdEndRenderPass(frames[frame].draw_command_buffer); + driver->command_end_render_pass(frames[frame].draw_command_buffer); for (int i = 0; i < draw_list_bound_textures.size(); i++) { Texture *texture = texture_owner.get_or_null(draw_list_bound_textures[i]); @@ -7772,70 +4477,65 @@ void RenderingDeviceVulkan::draw_list_end(BitField p_post_barrier) } } - uint32_t barrier_flags = 0; - uint32_t access_flags = 0; + BitField dst_stages; + BitField dst_access; if (p_post_barrier.has_flag(BARRIER_MASK_COMPUTE)) { - barrier_flags |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT; - access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; + dst_stages.set_flag(RDD::PIPELINE_STAGE_COMPUTE_SHADER_BIT); + dst_access.set_flag(RDD::BARRIER_ACCESS_SHADER_READ_BIT).set_flag(RDD::BARRIER_ACCESS_SHADER_WRITE_BIT); } if (p_post_barrier.has_flag(BARRIER_MASK_VERTEX)) { - barrier_flags |= VK_PIPELINE_STAGE_VERTEX_INPUT_BIT | VK_PIPELINE_STAGE_VERTEX_SHADER_BIT /*| VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT*/; - access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_INDEX_READ_BIT | VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT /*| VK_ACCESS_INDIRECT_COMMAND_READ_BIT*/; + dst_stages.set_flag(RDD::PIPELINE_STAGE_VERTEX_INPUT_BIT).set_flag(RDD::PIPELINE_STAGE_VERTEX_SHADER_BIT); // RDD::PIPELINE_STAGE_DRAW_INDIRECT_BIT + dst_access.set_flag(RDD::BARRIER_ACCESS_SHADER_READ_BIT).set_flag(RDD::BARRIER_ACCESS_SHADER_WRITE_BIT).set_flag(RDD::BARRIER_ACCESS_INDEX_READ_BIT).set_flag(RDD::BARRIER_ACCESS_VERTEX_ATTRIBUTE_READ_BIT); // RDD::BARRIER_ACCESS_INDIRECT_COMMAND_READ_BIT } if (p_post_barrier.has_flag(BARRIER_MASK_FRAGMENT)) { - barrier_flags |= VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT /*| VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT*/; - access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT /*| VK_ACCESS_INDIRECT_COMMAND_READ_BIT*/; + dst_stages.set_flag(RDD::PIPELINE_STAGE_FRAGMENT_SHADER_BIT); // RDD::PIPELINE_STAGE_DRAW_INDIRECT_BIT + dst_access.set_flag(RDD::BARRIER_ACCESS_SHADER_READ_BIT).set_flag(RDD::BARRIER_ACCESS_SHADER_WRITE_BIT); // RDD::BARRIER_ACCESS_INDIRECT_COMMAND_READ_BIT } if (p_post_barrier.has_flag(BARRIER_MASK_TRANSFER)) { - barrier_flags |= VK_PIPELINE_STAGE_TRANSFER_BIT; - access_flags |= VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT; + dst_stages.set_flag(RDD::PIPELINE_STAGE_TRANSFER_BIT); + dst_access.set_flag(RDD::BARRIER_ACCESS_TRANSFER_WRITE_BIT).set_flag(RDD::BARRIER_ACCESS_TRANSFER_READ_BIT); } - if (barrier_flags == 0) { - barrier_flags = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; + if (dst_stages.is_empty()) { + dst_stages.set_flag(RDD::PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT); } draw_list_bound_textures.clear(); - VkImageMemoryBarrier *image_barriers = nullptr; + RDD::TextureBarrier *texture_barriers = nullptr; - uint32_t image_barrier_count = draw_list_storage_textures.size(); + uint32_t texture_barrier_count = draw_list_storage_textures.size(); - if (image_barrier_count) { - image_barriers = (VkImageMemoryBarrier *)alloca(sizeof(VkImageMemoryBarrier) * draw_list_storage_textures.size()); + if (texture_barrier_count) { + texture_barriers = (RDD::TextureBarrier *)alloca(sizeof(RDD::TextureBarrier) * draw_list_storage_textures.size()); } - uint32_t src_stage = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | - VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT; - uint32_t src_access = - VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; + BitField src_stage(RDD::PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | + RDD::PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | RDD::PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT); + BitField src_access( + RDD::BARRIER_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT | RDD::BARRIER_ACCESS_COLOR_ATTACHMENT_WRITE_BIT); - if (image_barrier_count) { - src_stage |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT; - src_access |= VK_ACCESS_SHADER_WRITE_BIT; + if (texture_barrier_count) { + src_stage.set_flag(RDD::PIPELINE_STAGE_VERTEX_SHADER_BIT).set_flag(RDD::PIPELINE_STAGE_FRAGMENT_SHADER_BIT); + src_access.set_flag(RDD::BARRIER_ACCESS_SHADER_WRITE_BIT); } - for (uint32_t i = 0; i < image_barrier_count; i++) { + for (uint32_t i = 0; i < texture_barrier_count; i++) { Texture *texture = texture_owner.get_or_null(draw_list_storage_textures[i]); - VkImageMemoryBarrier &image_memory_barrier = image_barriers[i]; - image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; - image_memory_barrier.pNext = nullptr; - image_memory_barrier.srcAccessMask = src_access; - image_memory_barrier.dstAccessMask = access_flags; - image_memory_barrier.oldLayout = texture->layout; - image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; - - image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - image_memory_barrier.image = texture->image; - image_memory_barrier.subresourceRange.aspectMask = texture->read_aspect_mask; - image_memory_barrier.subresourceRange.baseMipLevel = texture->base_mipmap; - image_memory_barrier.subresourceRange.levelCount = texture->mipmaps; - image_memory_barrier.subresourceRange.baseArrayLayer = texture->base_layer; - image_memory_barrier.subresourceRange.layerCount = texture->layers; + RDD::TextureBarrier &tb = texture_barriers[i]; + tb.texture = texture->driver_id; + tb.src_access = src_access; + tb.dst_access = dst_access; + tb.prev_layout = texture->layout; + tb.next_layout = RDD::TEXTURE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; + tb.subresources.aspect = texture->read_aspect_flags; + tb.subresources.base_mipmap = texture->base_mipmap; + tb.subresources.mipmap_count = texture->mipmaps; + tb.subresources.base_layer = texture->base_layer; + tb.subresources.layer_count = texture->layers; - texture->layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; + texture->layout = RDD::TEXTURE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; } draw_list_storage_textures.clear(); @@ -7844,14 +4544,12 @@ void RenderingDeviceVulkan::draw_list_end(BitField p_post_barrier) // * Some buffer is copied. // * Another render pass happens (since we may be done). - VkMemoryBarrier mem_barrier; - mem_barrier.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER; - mem_barrier.pNext = nullptr; - mem_barrier.srcAccessMask = src_access; - mem_barrier.dstAccessMask = access_flags; + RDD::MemoryBarrier mb; + mb.src_access = src_access; + mb.dst_access = dst_access; - if (image_barrier_count > 0 || p_post_barrier != BARRIER_MASK_NO_BARRIER) { - vkCmdPipelineBarrier(frames[frame].draw_command_buffer, src_stage, barrier_flags, 0, 1, &mem_barrier, 0, nullptr, image_barrier_count, image_barriers); + if (texture_barrier_count > 0 || p_post_barrier != BARRIER_MASK_NO_BARRIER) { + driver->command_pipeline_barrier(frames[frame].draw_command_buffer, src_stage, dst_stages, mb, {}, VectorView(texture_barriers, texture_barrier_count)); } #ifdef FORCE_FULL_BARRIER @@ -7863,7 +4561,7 @@ void RenderingDeviceVulkan::draw_list_end(BitField p_post_barrier) /**** COMPUTE LISTS ****/ /***********************/ -RenderingDevice::ComputeListID RenderingDeviceVulkan::compute_list_begin(bool p_allow_draw_overlap) { +RenderingDevice::ComputeListID RenderingDevice::compute_list_begin(bool p_allow_draw_overlap) { _THREAD_SAFE_METHOD_ ERR_FAIL_COND_V_MSG(!p_allow_draw_overlap && draw_list != nullptr, INVALID_ID, "Only one draw list can be active at the same time."); @@ -7879,7 +4577,7 @@ RenderingDevice::ComputeListID RenderingDeviceVulkan::compute_list_begin(bool p_ return ID_TYPE_COMPUTE_LIST; } -void RenderingDeviceVulkan::compute_list_bind_compute_pipeline(ComputeListID p_list, RID p_compute_pipeline) { +void RenderingDevice::compute_list_bind_compute_pipeline(ComputeListID p_list, RID p_compute_pipeline) { // Must be called within a compute list, the class mutex is locked during that time ERR_FAIL_COND(p_list != ID_TYPE_COMPUTE_LIST); @@ -7895,9 +4593,8 @@ void RenderingDeviceVulkan::compute_list_bind_compute_pipeline(ComputeListID p_l } cl->state.pipeline = p_compute_pipeline; - cl->state.pipeline_layout = pipeline->pipeline_layout; - vkCmdBindPipeline(cl->command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline->pipeline); + driver->command_bind_compute_pipeline(cl->command_buffer, pipeline->driver_id); if (cl->state.pipeline_shader != pipeline->shader) { // Shader changed, so descriptor sets may become incompatible. @@ -7926,13 +4623,13 @@ void RenderingDeviceVulkan::compute_list_bind_compute_pipeline(ComputeListID p_l cl->state.set_count = pcount; // Update set count. if (pipeline->push_constant_size) { - cl->state.pipeline_push_constant_stages = pipeline->push_constant_stages_mask; #ifdef DEBUG_ENABLED cl->validation.pipeline_push_constant_supplied = false; #endif } cl->state.pipeline_shader = pipeline->shader; + cl->state.pipeline_shader_driver_id = pipeline->shader_driver_id; cl->state.local_group_size[0] = pipeline->local_group_size[0]; cl->state.local_group_size[1] = pipeline->local_group_size[1]; cl->state.local_group_size[2] = pipeline->local_group_size[2]; @@ -7945,7 +4642,7 @@ void RenderingDeviceVulkan::compute_list_bind_compute_pipeline(ComputeListID p_l #endif } -void RenderingDeviceVulkan::compute_list_bind_uniform_set(ComputeListID p_list, RID p_uniform_set, uint32_t p_index) { +void RenderingDevice::compute_list_bind_uniform_set(ComputeListID p_list, RID p_uniform_set, uint32_t p_index) { // Must be called within a compute list, the class mutex is locked during that time ERR_FAIL_COND(p_list != ID_TYPE_COMPUTE_LIST); @@ -7954,8 +4651,8 @@ void RenderingDeviceVulkan::compute_list_bind_uniform_set(ComputeListID p_list, ComputeList *cl = compute_list; #ifdef DEBUG_ENABLED - ERR_FAIL_COND_MSG(p_index >= limits.maxBoundDescriptorSets || p_index >= MAX_UNIFORM_SETS, - "Attempting to bind a descriptor set (" + itos(p_index) + ") greater than what the hardware supports (" + itos(limits.maxBoundDescriptorSets) + ")."); + ERR_FAIL_COND_MSG(p_index >= driver->limit_get(LIMIT_MAX_BOUND_UNIFORM_SETS) || p_index >= MAX_UNIFORM_SETS, + "Attempting to bind a descriptor set (" + itos(p_index) + ") greater than what the hardware supports (" + itos(driver->limit_get(LIMIT_MAX_BOUND_UNIFORM_SETS)) + ")."); #endif #ifdef DEBUG_ENABLED @@ -7969,7 +4666,7 @@ void RenderingDeviceVulkan::compute_list_bind_uniform_set(ComputeListID p_list, cl->state.set_count = p_index; } - cl->state.sets[p_index].descriptor_set = uniform_set->descriptor_set; // Update set pointer. + cl->state.sets[p_index].uniform_set_driver_id = uniform_set->driver_id; // Update set pointer. cl->state.sets[p_index].bound = false; // Needs rebind. cl->state.sets[p_index].uniform_set_format = uniform_set->format; cl->state.sets[p_index].uniform_set = p_uniform_set; @@ -7979,37 +4676,32 @@ void RenderingDeviceVulkan::compute_list_bind_uniform_set(ComputeListID p_list, Texture **textures_to_sampled = uniform_set->mutable_sampled_textures.ptrw(); - VkImageMemoryBarrier *texture_barriers = nullptr; + RDD::TextureBarrier *texture_barriers = nullptr; if (textures_to_sampled_count + textures_to_storage_count) { - texture_barriers = (VkImageMemoryBarrier *)alloca(sizeof(VkImageMemoryBarrier) * (textures_to_sampled_count + textures_to_storage_count)); + texture_barriers = (RDD::TextureBarrier *)alloca(sizeof(RDD::TextureBarrier) * (textures_to_sampled_count + textures_to_storage_count)); } uint32_t texture_barrier_count = 0; - uint32_t src_stage_flags = 0; + BitField src_stages; for (uint32_t i = 0; i < textures_to_sampled_count; i++) { - if (textures_to_sampled[i]->layout != VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) { - src_stage_flags |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT; - - VkImageMemoryBarrier &image_memory_barrier = texture_barriers[texture_barrier_count++]; - image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; - image_memory_barrier.pNext = nullptr; - image_memory_barrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; - image_memory_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; - image_memory_barrier.oldLayout = textures_to_sampled[i]->layout; - image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; - - image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - image_memory_barrier.image = textures_to_sampled[i]->image; - image_memory_barrier.subresourceRange.aspectMask = textures_to_sampled[i]->read_aspect_mask; - image_memory_barrier.subresourceRange.baseMipLevel = textures_to_sampled[i]->base_mipmap; - image_memory_barrier.subresourceRange.levelCount = textures_to_sampled[i]->mipmaps; - image_memory_barrier.subresourceRange.baseArrayLayer = textures_to_sampled[i]->base_layer; - image_memory_barrier.subresourceRange.layerCount = textures_to_sampled[i]->layers; - - textures_to_sampled[i]->layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; + if (textures_to_sampled[i]->layout != RDD::TEXTURE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) { + src_stages.set_flag(RDD::PIPELINE_STAGE_COMPUTE_SHADER_BIT); + + RDD::TextureBarrier &tb = texture_barriers[texture_barrier_count++]; + tb.texture = textures_to_sampled[i]->driver_id; + tb.src_access = (RDD::BARRIER_ACCESS_SHADER_READ_BIT | RDD::BARRIER_ACCESS_SHADER_WRITE_BIT); + tb.dst_access = (RDD::BARRIER_ACCESS_SHADER_READ_BIT | RDD::BARRIER_ACCESS_SHADER_WRITE_BIT); + tb.prev_layout = textures_to_sampled[i]->layout; + tb.next_layout = RDD::TEXTURE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; + tb.subresources.aspect = textures_to_sampled[i]->read_aspect_flags; + tb.subresources.base_mipmap = textures_to_sampled[i]->base_mipmap; + tb.subresources.mipmap_count = textures_to_sampled[i]->mipmaps; + tb.subresources.base_layer = textures_to_sampled[i]->base_layer; + tb.subresources.layer_count = textures_to_sampled[i]->layers; + + textures_to_sampled[i]->layout = RDD::TEXTURE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; cl->state.textures_to_sampled_layout.erase(textures_to_sampled[i]); } @@ -8025,21 +4717,21 @@ void RenderingDeviceVulkan::compute_list_bind_uniform_set(ComputeListID p_list, Texture **textures_to_storage = uniform_set->mutable_storage_textures.ptrw(); for (uint32_t i = 0; i < textures_to_storage_count; i++) { - if (textures_to_storage[i]->layout != VK_IMAGE_LAYOUT_GENERAL) { - uint32_t src_access_flags = 0; + if (textures_to_storage[i]->layout != RDD::TEXTURE_LAYOUT_GENERAL) { + BitField src_access; if (textures_to_storage[i]->used_in_frame == frames_drawn) { if (textures_to_storage[i]->used_in_compute) { - src_stage_flags |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT; - src_access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; + src_stages.set_flag(RDD::PIPELINE_STAGE_COMPUTE_SHADER_BIT); + src_access.set_flag(RDD::BARRIER_ACCESS_SHADER_READ_BIT).set_flag(RDD::BARRIER_ACCESS_SHADER_WRITE_BIT); } if (textures_to_storage[i]->used_in_raster) { - src_stage_flags |= VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_VERTEX_SHADER_BIT; - src_access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; + src_stages.set_flag(RDD::PIPELINE_STAGE_FRAGMENT_SHADER_BIT).set_flag(RDD::PIPELINE_STAGE_VERTEX_SHADER_BIT); + src_access.set_flag(RDD::BARRIER_ACCESS_SHADER_READ_BIT).set_flag(RDD::BARRIER_ACCESS_SHADER_WRITE_BIT); } if (textures_to_storage[i]->used_in_transfer) { - src_stage_flags |= VK_PIPELINE_STAGE_TRANSFER_BIT; - src_access_flags |= VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT; + src_stages.set_flag(RDD::PIPELINE_STAGE_TRANSFER_BIT); + src_access.set_flag(RDD::BARRIER_ACCESS_TRANSFER_WRITE_BIT).set_flag(RDD::BARRIER_ACCESS_TRANSFER_READ_BIT); } textures_to_storage[i]->used_in_compute = false; @@ -8047,42 +4739,37 @@ void RenderingDeviceVulkan::compute_list_bind_uniform_set(ComputeListID p_list, textures_to_storage[i]->used_in_transfer = false; } else { - src_access_flags = 0; + src_access.clear(); textures_to_storage[i]->used_in_compute = false; textures_to_storage[i]->used_in_raster = false; textures_to_storage[i]->used_in_transfer = false; textures_to_storage[i]->used_in_frame = frames_drawn; } - VkImageMemoryBarrier &image_memory_barrier = texture_barriers[texture_barrier_count++]; - image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; - image_memory_barrier.pNext = nullptr; - image_memory_barrier.srcAccessMask = src_access_flags; - image_memory_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; - image_memory_barrier.oldLayout = textures_to_storage[i]->layout; - image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_GENERAL; - - image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - image_memory_barrier.image = textures_to_storage[i]->image; - image_memory_barrier.subresourceRange.aspectMask = textures_to_storage[i]->read_aspect_mask; - image_memory_barrier.subresourceRange.baseMipLevel = textures_to_storage[i]->base_mipmap; - image_memory_barrier.subresourceRange.levelCount = textures_to_storage[i]->mipmaps; - image_memory_barrier.subresourceRange.baseArrayLayer = textures_to_storage[i]->base_layer; - image_memory_barrier.subresourceRange.layerCount = textures_to_storage[i]->layers; - - textures_to_storage[i]->layout = VK_IMAGE_LAYOUT_GENERAL; + RDD::TextureBarrier &tb = texture_barriers[texture_barrier_count++]; + tb.texture = textures_to_storage[i]->driver_id; + tb.src_access = src_access; + tb.dst_access = (RDD::BARRIER_ACCESS_SHADER_READ_BIT | RDD::BARRIER_ACCESS_SHADER_WRITE_BIT); + tb.prev_layout = textures_to_storage[i]->layout; + tb.next_layout = RDD::TEXTURE_LAYOUT_GENERAL; + tb.subresources.aspect = textures_to_storage[i]->read_aspect_flags; + tb.subresources.base_mipmap = textures_to_storage[i]->base_mipmap; + tb.subresources.mipmap_count = textures_to_storage[i]->mipmaps; + tb.subresources.base_layer = textures_to_storage[i]->base_layer; + tb.subresources.layer_count = textures_to_storage[i]->layers; + + textures_to_storage[i]->layout = RDD::TEXTURE_LAYOUT_GENERAL; cl->state.textures_to_sampled_layout.insert(textures_to_storage[i]); // Needs to go back to sampled layout afterwards. } } if (texture_barrier_count) { - if (src_stage_flags == 0) { - src_stage_flags = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; + if (src_stages.is_empty()) { + src_stages.set_flag(RDD::PIPELINE_STAGE_TOP_OF_PIPE_BIT); } - vkCmdPipelineBarrier(cl->command_buffer, src_stage_flags, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 0, nullptr, texture_barrier_count, texture_barriers); + driver->command_pipeline_barrier(cl->command_buffer, src_stages, RDD::PIPELINE_STAGE_COMPUTE_SHADER_BIT, {}, {}, VectorView(texture_barriers, texture_barrier_count)); } #if 0 @@ -8101,7 +4788,7 @@ void RenderingDeviceVulkan::compute_list_bind_uniform_set(ComputeListID p_list, #endif } -void RenderingDeviceVulkan::compute_list_set_push_constant(ComputeListID p_list, const void *p_data, uint32_t p_data_size) { +void RenderingDevice::compute_list_set_push_constant(ComputeListID p_list, const void *p_data, uint32_t p_data_size) { ERR_FAIL_COND(p_list != ID_TYPE_COMPUTE_LIST); ERR_FAIL_NULL(compute_list); @@ -8115,13 +4802,13 @@ void RenderingDeviceVulkan::compute_list_set_push_constant(ComputeListID p_list, ERR_FAIL_COND_MSG(p_data_size != cl->validation.pipeline_push_constant_size, "This compute pipeline requires (" + itos(cl->validation.pipeline_push_constant_size) + ") bytes of push constant data, supplied: (" + itos(p_data_size) + ")"); #endif - vkCmdPushConstants(cl->command_buffer, cl->state.pipeline_layout, cl->state.pipeline_push_constant_stages, 0, p_data_size, p_data); + driver->command_bind_push_constants(cl->command_buffer, cl->state.pipeline_shader_driver_id, 0, VectorView((const uint32_t *)p_data, p_data_size / sizeof(uint32_t))); #ifdef DEBUG_ENABLED cl->validation.pipeline_push_constant_supplied = true; #endif } -void RenderingDeviceVulkan::compute_list_dispatch(ComputeListID p_list, uint32_t p_x_groups, uint32_t p_y_groups, uint32_t p_z_groups) { +void RenderingDevice::compute_list_dispatch(ComputeListID p_list, uint32_t p_x_groups, uint32_t p_y_groups, uint32_t p_z_groups) { // Must be called within a compute list, the class mutex is locked during that time ERR_FAIL_COND(p_list != ID_TYPE_COMPUTE_LIST); @@ -8133,12 +4820,12 @@ void RenderingDeviceVulkan::compute_list_dispatch(ComputeListID p_list, uint32_t ERR_FAIL_COND_MSG(p_x_groups == 0, "Dispatch amount of X compute groups (" + itos(p_x_groups) + ") is zero."); ERR_FAIL_COND_MSG(p_z_groups == 0, "Dispatch amount of Z compute groups (" + itos(p_z_groups) + ") is zero."); ERR_FAIL_COND_MSG(p_y_groups == 0, "Dispatch amount of Y compute groups (" + itos(p_y_groups) + ") is zero."); - ERR_FAIL_COND_MSG(p_x_groups > limits.maxComputeWorkGroupCount[0], - "Dispatch amount of X compute groups (" + itos(p_x_groups) + ") is larger than device limit (" + itos(limits.maxComputeWorkGroupCount[0]) + ")"); - ERR_FAIL_COND_MSG(p_y_groups > limits.maxComputeWorkGroupCount[1], - "Dispatch amount of Y compute groups (" + itos(p_y_groups) + ") is larger than device limit (" + itos(limits.maxComputeWorkGroupCount[1]) + ")"); - ERR_FAIL_COND_MSG(p_z_groups > limits.maxComputeWorkGroupCount[2], - "Dispatch amount of Z compute groups (" + itos(p_z_groups) + ") is larger than device limit (" + itos(limits.maxComputeWorkGroupCount[2]) + ")"); + ERR_FAIL_COND_MSG(p_x_groups > driver->limit_get(LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_X), + "Dispatch amount of X compute groups (" + itos(p_x_groups) + ") is larger than device limit (" + itos(driver->limit_get(LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_X)) + ")"); + ERR_FAIL_COND_MSG(p_y_groups > driver->limit_get(LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_Y), + "Dispatch amount of Y compute groups (" + itos(p_y_groups) + ") is larger than device limit (" + itos(driver->limit_get(LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_Y)) + ")"); + ERR_FAIL_COND_MSG(p_z_groups > driver->limit_get(LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_Z), + "Dispatch amount of Z compute groups (" + itos(p_z_groups) + ") is larger than device limit (" + itos(driver->limit_get(LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_Z)) + ")"); ERR_FAIL_COND_MSG(!cl->validation.active, "Submitted Compute Lists can no longer be modified."); #endif @@ -8175,15 +4862,15 @@ void RenderingDeviceVulkan::compute_list_dispatch(ComputeListID p_list, uint32_t #endif if (!cl->state.sets[i].bound) { // All good, see if this requires re-binding. - vkCmdBindDescriptorSets(cl->command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE, cl->state.pipeline_layout, i, 1, &cl->state.sets[i].descriptor_set, 0, nullptr); + driver->command_bind_compute_uniform_set(cl->command_buffer, cl->state.sets[i].uniform_set_driver_id, cl->state.pipeline_shader_driver_id, i); cl->state.sets[i].bound = true; } } - vkCmdDispatch(cl->command_buffer, p_x_groups, p_y_groups, p_z_groups); + driver->command_compute_dispatch(cl->command_buffer, p_x_groups, p_y_groups, p_z_groups); } -void RenderingDeviceVulkan::compute_list_dispatch_threads(ComputeListID p_list, uint32_t p_x_threads, uint32_t p_y_threads, uint32_t p_z_threads) { +void RenderingDevice::compute_list_dispatch_threads(ComputeListID p_list, uint32_t p_x_threads, uint32_t p_y_threads, uint32_t p_z_threads) { ERR_FAIL_COND(p_list != ID_TYPE_COMPUTE_LIST); ERR_FAIL_NULL(compute_list); @@ -8210,15 +4897,15 @@ void RenderingDeviceVulkan::compute_list_dispatch_threads(ComputeListID p_list, compute_list_dispatch(p_list, (p_x_threads - 1) / cl->state.local_group_size[0] + 1, (p_y_threads - 1) / cl->state.local_group_size[1] + 1, (p_z_threads - 1) / cl->state.local_group_size[2] + 1); } -void RenderingDeviceVulkan::compute_list_dispatch_indirect(ComputeListID p_list, RID p_buffer, uint32_t p_offset) { +void RenderingDevice::compute_list_dispatch_indirect(ComputeListID p_list, RID p_buffer, uint32_t p_offset) { ERR_FAIL_COND(p_list != ID_TYPE_COMPUTE_LIST); ERR_FAIL_NULL(compute_list); ComputeList *cl = compute_list; Buffer *buffer = storage_buffer_owner.get_or_null(p_buffer); - ERR_FAIL_NULL(buffer); + ERR_FAIL_COND(!buffer); - ERR_FAIL_COND_MSG(!(buffer->usage & VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT), "Buffer provided was not created to do indirect dispatch."); + ERR_FAIL_COND_MSG(!buffer->usage.has_flag(RDD::BUFFER_USAGE_INDIRECT_BIT), "Buffer provided was not created to do indirect dispatch."); ERR_FAIL_COND_MSG(p_offset + 12 > buffer->size, "Offset provided (+12) is past the end of buffer."); @@ -8258,55 +4945,50 @@ void RenderingDeviceVulkan::compute_list_dispatch_indirect(ComputeListID p_list, #endif if (!cl->state.sets[i].bound) { // All good, see if this requires re-binding. - vkCmdBindDescriptorSets(cl->command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE, cl->state.pipeline_layout, i, 1, &cl->state.sets[i].descriptor_set, 0, nullptr); + driver->command_bind_compute_uniform_set(cl->command_buffer, cl->state.sets[i].uniform_set_driver_id, cl->state.pipeline_shader_driver_id, i); cl->state.sets[i].bound = true; } } - vkCmdDispatchIndirect(cl->command_buffer, buffer->buffer, p_offset); + driver->command_compute_dispatch_indirect(cl->command_buffer, buffer->driver_id, p_offset); } -void RenderingDeviceVulkan::compute_list_add_barrier(ComputeListID p_list) { +void RenderingDevice::compute_list_add_barrier(ComputeListID p_list) { // Must be called within a compute list, the class mutex is locked during that time - uint32_t barrier_flags = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT; - uint32_t access_flags = VK_ACCESS_SHADER_READ_BIT; - _compute_list_add_barrier(BARRIER_MASK_COMPUTE, barrier_flags, access_flags); + BitField stages(RDD::PIPELINE_STAGE_COMPUTE_SHADER_BIT); + BitField access(RDD::BARRIER_ACCESS_SHADER_READ_BIT); + _compute_list_add_barrier(BARRIER_MASK_COMPUTE, stages, access); } -void RenderingDeviceVulkan::_compute_list_add_barrier(BitField p_post_barrier, uint32_t p_barrier_flags, uint32_t p_access_flags) { +void RenderingDevice::_compute_list_add_barrier(BitField p_post_barrier, BitField p_stages, BitField p_access) { ERR_FAIL_NULL(compute_list); - VkImageMemoryBarrier *image_barriers = nullptr; + RDD::TextureBarrier *texture_barriers = nullptr; - uint32_t image_barrier_count = compute_list->state.textures_to_sampled_layout.size(); + uint32_t texture_barrier_count = compute_list->state.textures_to_sampled_layout.size(); - if (image_barrier_count) { - image_barriers = (VkImageMemoryBarrier *)alloca(sizeof(VkImageMemoryBarrier) * image_barrier_count); + if (texture_barrier_count) { + texture_barriers = (RDD::TextureBarrier *)alloca(sizeof(RDD::TextureBarrier) * texture_barrier_count); } - image_barrier_count = 0; // We'll count how many we end up issuing. + texture_barrier_count = 0; // We'll count how many we end up issuing. for (Texture *E : compute_list->state.textures_to_sampled_layout) { - if (E->layout != VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) { - VkImageMemoryBarrier &image_memory_barrier = image_barriers[image_barrier_count++]; - image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; - image_memory_barrier.pNext = nullptr; - image_memory_barrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; - image_memory_barrier.dstAccessMask = p_access_flags; - image_memory_barrier.oldLayout = E->layout; - image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; - - image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - image_memory_barrier.image = E->image; - image_memory_barrier.subresourceRange.aspectMask = E->read_aspect_mask; - image_memory_barrier.subresourceRange.baseMipLevel = E->base_mipmap; - image_memory_barrier.subresourceRange.levelCount = E->mipmaps; - image_memory_barrier.subresourceRange.baseArrayLayer = E->base_layer; - image_memory_barrier.subresourceRange.layerCount = E->layers; - - E->layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; + if (E->layout != RDD::TEXTURE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) { + RDD::TextureBarrier &tb = texture_barriers[texture_barrier_count++]; + tb.texture = E->driver_id; + tb.src_access = RDD::BARRIER_ACCESS_SHADER_READ_BIT | RDD::BARRIER_ACCESS_SHADER_WRITE_BIT; + tb.dst_access = p_access; + tb.prev_layout = E->layout; + tb.next_layout = RDD::TEXTURE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; + tb.subresources.aspect = E->read_aspect_flags; + tb.subresources.base_mipmap = E->base_mipmap; + tb.subresources.mipmap_count = E->mipmaps; + tb.subresources.base_layer = E->base_layer; + tb.subresources.layer_count = E->layers; + + E->layout = RDD::TEXTURE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; } if (E->used_in_frame != frames_drawn) { @@ -8317,15 +4999,14 @@ void RenderingDeviceVulkan::_compute_list_add_barrier(BitField p_po } } - if (p_barrier_flags) { - VkMemoryBarrier mem_barrier; - mem_barrier.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER; - mem_barrier.pNext = nullptr; - mem_barrier.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; - mem_barrier.dstAccessMask = p_access_flags; - vkCmdPipelineBarrier(compute_list->command_buffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, p_barrier_flags, 0, 1, &mem_barrier, 0, nullptr, image_barrier_count, image_barriers); - } else if (image_barrier_count) { - vkCmdPipelineBarrier(compute_list->command_buffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0, nullptr, 0, nullptr, image_barrier_count, image_barriers); + if (p_stages) { + RDD::MemoryBarrier mb; + mb.src_access = RDD::BARRIER_ACCESS_SHADER_WRITE_BIT; + mb.dst_access = p_access; + driver->command_pipeline_barrier(compute_list->command_buffer, RDD::PIPELINE_STAGE_COMPUTE_SHADER_BIT, p_stages, mb, {}, VectorView(texture_barriers, texture_barrier_count)); + + } else if (texture_barrier_count) { + driver->command_pipeline_barrier(compute_list->command_buffer, RDD::PIPELINE_STAGE_COMPUTE_SHADER_BIT, RDD::PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, {}, {}, VectorView(texture_barriers, texture_barrier_count)); } #ifdef FORCE_FULL_BARRIER @@ -8333,28 +5014,28 @@ void RenderingDeviceVulkan::_compute_list_add_barrier(BitField p_po #endif } -void RenderingDeviceVulkan::compute_list_end(BitField p_post_barrier) { +void RenderingDevice::compute_list_end(BitField p_post_barrier) { ERR_FAIL_NULL(compute_list); - uint32_t barrier_flags = 0; - uint32_t access_flags = 0; + BitField stages; + BitField access; if (p_post_barrier.has_flag(BARRIER_MASK_COMPUTE)) { - barrier_flags |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT; - access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; + stages.set_flag(RDD::PIPELINE_STAGE_COMPUTE_SHADER_BIT); + access.set_flag(RDD::BARRIER_ACCESS_SHADER_READ_BIT).set_flag(RDD::BARRIER_ACCESS_SHADER_WRITE_BIT); } if (p_post_barrier.has_flag(BARRIER_MASK_VERTEX)) { - barrier_flags |= VK_PIPELINE_STAGE_VERTEX_INPUT_BIT | VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT; - access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_INDEX_READ_BIT | VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT | VK_ACCESS_INDIRECT_COMMAND_READ_BIT; + stages.set_flag(RDD::PIPELINE_STAGE_VERTEX_INPUT_BIT).set_flag(RDD::PIPELINE_STAGE_VERTEX_SHADER_BIT).set_flag(RDD::PIPELINE_STAGE_DRAW_INDIRECT_BIT); + access.set_flag(RDD::BARRIER_ACCESS_SHADER_READ_BIT).set_flag(RDD::BARRIER_ACCESS_SHADER_WRITE_BIT).set_flag(RDD::BARRIER_ACCESS_INDEX_READ_BIT).set_flag(RDD::BARRIER_ACCESS_VERTEX_ATTRIBUTE_READ_BIT).set_flag(RDD::BARRIER_ACCESS_INDIRECT_COMMAND_READ_BIT); } if (p_post_barrier.has_flag(BARRIER_MASK_FRAGMENT)) { - barrier_flags |= VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT; - access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_INDIRECT_COMMAND_READ_BIT; + stages.set_flag(RDD::PIPELINE_STAGE_FRAGMENT_SHADER_BIT).set_flag(RDD::PIPELINE_STAGE_DRAW_INDIRECT_BIT); + access.set_flag(RDD::BARRIER_ACCESS_SHADER_READ_BIT).set_flag(RDD::BARRIER_ACCESS_SHADER_WRITE_BIT).set_flag(RDD::BARRIER_ACCESS_INDIRECT_COMMAND_READ_BIT); } if (p_post_barrier.has_flag(BARRIER_MASK_TRANSFER)) { - barrier_flags |= VK_PIPELINE_STAGE_TRANSFER_BIT; - access_flags |= VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT; + stages.set_flag(RDD::PIPELINE_STAGE_TRANSFER_BIT); + access.set_flag(RDD::BARRIER_ACCESS_TRANSFER_WRITE_BIT).set_flag(RDD::BARRIER_ACCESS_TRANSFER_READ_BIT); } - _compute_list_add_barrier(p_post_barrier, barrier_flags, access_flags); + _compute_list_add_barrier(p_post_barrier, stages, access); memdelete(compute_list); compute_list = nullptr; @@ -8363,121 +5044,76 @@ void RenderingDeviceVulkan::compute_list_end(BitField p_post_barrie _THREAD_SAFE_UNLOCK_ } -void RenderingDeviceVulkan::barrier(BitField p_from, BitField p_to) { - uint32_t src_barrier_flags = 0; - uint32_t src_access_flags = 0; +void RenderingDevice::barrier(BitField p_from, BitField p_to) { + BitField src_stages; + BitField src_access; if (p_from == 0) { - src_barrier_flags = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; + src_stages.set_flag(RDD::PIPELINE_STAGE_TOP_OF_PIPE_BIT); } else { if (p_from.has_flag(BARRIER_MASK_COMPUTE)) { - src_barrier_flags |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT; - src_access_flags |= VK_ACCESS_SHADER_WRITE_BIT; + src_stages.set_flag(RDD::PIPELINE_STAGE_COMPUTE_SHADER_BIT); + src_access.set_flag(RDD::BARRIER_ACCESS_SHADER_WRITE_BIT); } if (p_from.has_flag(BARRIER_MASK_FRAGMENT)) { - src_barrier_flags |= VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | - VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | - VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT; - src_access_flags |= - VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; + src_stages.set_flag(RDD::PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT).set_flag(RDD::PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT).set_flag(RDD::PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT); + src_access.set_flag(RDD::BARRIER_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT).set_flag(RDD::BARRIER_ACCESS_COLOR_ATTACHMENT_WRITE_BIT); } if (p_from.has_flag(BARRIER_MASK_TRANSFER)) { - src_barrier_flags |= VK_PIPELINE_STAGE_TRANSFER_BIT; - src_access_flags |= VK_ACCESS_TRANSFER_WRITE_BIT; + src_stages.set_flag(RDD::PIPELINE_STAGE_TRANSFER_BIT); + src_access.set_flag(RDD::BARRIER_ACCESS_TRANSFER_WRITE_BIT); } } - uint32_t dst_barrier_flags = 0; - uint32_t dst_access_flags = 0; + BitField dst_stages; + BitField dst_access; if (p_to == 0) { - dst_barrier_flags = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; + dst_stages.set_flag(RDD::PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT); } else { if (p_to.has_flag(BARRIER_MASK_COMPUTE)) { - dst_barrier_flags |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT; - dst_access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; + dst_stages.set_flag(RDD::PIPELINE_STAGE_COMPUTE_SHADER_BIT); + dst_access.set_flag(RDD::BARRIER_ACCESS_SHADER_READ_BIT).set_flag(RDD::BARRIER_ACCESS_SHADER_WRITE_BIT); } if (p_to.has_flag(BARRIER_MASK_VERTEX)) { - dst_barrier_flags |= VK_PIPELINE_STAGE_VERTEX_INPUT_BIT | VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT; - dst_access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_INDEX_READ_BIT | VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT | VK_ACCESS_INDIRECT_COMMAND_READ_BIT; + dst_stages.set_flag(RDD::PIPELINE_STAGE_VERTEX_INPUT_BIT).set_flag(RDD::PIPELINE_STAGE_VERTEX_SHADER_BIT).set_flag(RDD::PIPELINE_STAGE_DRAW_INDIRECT_BIT); + dst_access.set_flag(RDD::BARRIER_ACCESS_SHADER_READ_BIT).set_flag(RDD::BARRIER_ACCESS_SHADER_WRITE_BIT).set_flag(RDD::BARRIER_ACCESS_INDEX_READ_BIT).set_flag(RDD::BARRIER_ACCESS_VERTEX_ATTRIBUTE_READ_BIT).set_flag(RDD::BARRIER_ACCESS_INDIRECT_COMMAND_READ_BIT); } if (p_to.has_flag(BARRIER_MASK_FRAGMENT)) { - dst_barrier_flags |= VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT; - dst_access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_INDIRECT_COMMAND_READ_BIT; + dst_stages.set_flag(RDD::PIPELINE_STAGE_FRAGMENT_SHADER_BIT).set_flag(RDD::PIPELINE_STAGE_DRAW_INDIRECT_BIT); + dst_access.set_flag(RDD::BARRIER_ACCESS_SHADER_READ_BIT).set_flag(RDD::BARRIER_ACCESS_SHADER_WRITE_BIT).set_flag(RDD::BARRIER_ACCESS_INDIRECT_COMMAND_READ_BIT); } if (p_to.has_flag(BARRIER_MASK_TRANSFER)) { - dst_barrier_flags |= VK_PIPELINE_STAGE_TRANSFER_BIT; - dst_access_flags |= VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT; + dst_stages.set_flag(RDD::PIPELINE_STAGE_TRANSFER_BIT); + dst_access.set_flag(RDD::BARRIER_ACCESS_TRANSFER_WRITE_BIT).set_flag(RDD::BARRIER_ACCESS_TRANSFER_READ_BIT); } } - _memory_barrier(src_barrier_flags, dst_barrier_flags, src_access_flags, dst_access_flags, true); + RDD::MemoryBarrier mb; + mb.src_access = src_access; + mb.dst_access = dst_access; + driver->command_pipeline_barrier(frames[frame].draw_command_buffer, src_stages, dst_stages, mb, {}, {}); } -void RenderingDeviceVulkan::full_barrier() { +void RenderingDevice::full_barrier() { #ifndef DEBUG_ENABLED ERR_PRINT("Full barrier is debug-only, should not be used in production"); #endif _full_barrier(true); } -#if 0 -void RenderingDeviceVulkan::draw_list_render_secondary_to_framebuffer(ID p_framebuffer, ID *p_draw_lists, uint32_t p_draw_list_count, InitialAction p_initial_action, FinalAction p_final_action, const Vector &p_clear_colors) { - VkCommandBuffer frame_cmdbuf = frames[frame].frame_buffer; - ERR_FAIL_NULL(frame_cmdbuf); - - VkRenderPassBeginInfo render_pass_begin; - render_pass_begin.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; - render_pass_begin.pNext = nullptr; - render_pass_begin.renderPass = context->get_render_pass(); - render_pass_begin.framebuffer = context->get_frame_framebuffer(frame); - - render_pass_begin.renderArea.extent.width = context->get_screen_width(p_screen); - render_pass_begin.renderArea.extent.height = context->get_screen_height(p_screen); - render_pass_begin.renderArea.offset.x = 0; - render_pass_begin.renderArea.offset.y = 0; - - render_pass_begin.clearValueCount = 1; - - VkClearValue clear_value; - clear_value.color.float32[0] = p_clear_color.r; - clear_value.color.float32[1] = p_clear_color.g; - clear_value.color.float32[2] = p_clear_color.b; - clear_value.color.float32[3] = p_clear_color.a; - - render_pass_begin.pClearValues = &clear_value; - - vkCmdBeginRenderPass(frame_cmdbuf, &render_pass_begin, VK_SUBPASS_CONTENTS_SECONDARY_COMMAND_BUFFERS); - - ID screen_format = screen_get_framebuffer_format(); - { - VkCommandBuffer *command_buffers = (VkCommandBuffer *)alloca(sizeof(VkCommandBuffer) * p_draw_list_count); - uint32_t command_buffer_count = 0; - - for (uint32_t i = 0; i < p_draw_list_count; i++) { - DrawList *dl = _get_draw_list_ptr(p_draw_lists[i]); - ERR_CONTINUE_MSG(!dl, "Draw list index (" + itos(i) + ") is not a valid draw list ID."); - ERR_CONTINUE_MSG(dl->validation.framebuffer_format != p_format_check, - "Draw list index (" + itos(i) + ") is created with a framebuffer format incompatible with this render pass."); - - if (dl->validation.active) { - // Needs to be closed, so close it. - vkEndCommandBuffer(dl->command_buffer); - dl->validation.active = false; - } - - command_buffers[command_buffer_count++] = dl->command_buffer; - } +/**************************/ +/**** FRAME MANAGEMENT ****/ +/**************************/ - print_line("to draw: " + itos(command_buffer_count)); - vkCmdExecuteCommands(p_primary, command_buffer_count, command_buffers); - } +void RenderingDevice::free(RID p_id) { + _THREAD_SAFE_METHOD_ - vkCmdEndRenderPass(frame_cmdbuf); + _free_dependencies(p_id); // Recursively erase dependencies first, to avoid potential API problems. + _free_internal(p_id); } -#endif -void RenderingDeviceVulkan::_free_internal(RID p_id) { +void RenderingDevice::_free_internal(RID p_id) { #ifdef DEV_ENABLED String resource_name; if (resource_names.has(p_id)) { @@ -8501,8 +5137,8 @@ void RenderingDeviceVulkan::_free_internal(RID p_id) { framebuffer_owner.free(p_id); } else if (sampler_owner.owns(p_id)) { - VkSampler *sampler = sampler_owner.get_or_null(p_id); - frames[frame].samplers_to_dispose_of.push_back(*sampler); + RDD::SamplerID sampler_driver_id = *sampler_owner.get_or_null(p_id); + frames[frame].samplers_to_dispose_of.push_back(sampler_driver_id); sampler_owner.free(p_id); } else if (vertex_buffer_owner.owns(p_id)) { Buffer *vertex_buffer = vertex_buffer_owner.get_or_null(p_id); @@ -8512,27 +5148,23 @@ void RenderingDeviceVulkan::_free_internal(RID p_id) { vertex_array_owner.free(p_id); } else if (index_buffer_owner.owns(p_id)) { IndexBuffer *index_buffer = index_buffer_owner.get_or_null(p_id); - Buffer b; - b.allocation = index_buffer->allocation; - b.buffer = index_buffer->buffer; - b.size = index_buffer->size; - b.buffer_info = {}; - frames[frame].buffers_to_dispose_of.push_back(b); + frames[frame].buffers_to_dispose_of.push_back(*index_buffer); index_buffer_owner.free(p_id); } else if (index_array_owner.owns(p_id)) { index_array_owner.free(p_id); } else if (shader_owner.owns(p_id)) { Shader *shader = shader_owner.get_or_null(p_id); - frames[frame].shaders_to_dispose_of.push_back(*shader); + if (shader->driver_id) { // Not placeholder? + frames[frame].shaders_to_dispose_of.push_back(*shader); + } shader_owner.free(p_id); } else if (uniform_buffer_owner.owns(p_id)) { Buffer *uniform_buffer = uniform_buffer_owner.get_or_null(p_id); frames[frame].buffers_to_dispose_of.push_back(*uniform_buffer); uniform_buffer_owner.free(p_id); } else if (texture_buffer_owner.owns(p_id)) { - TextureBuffer *texture_buffer = texture_buffer_owner.get_or_null(p_id); - frames[frame].buffers_to_dispose_of.push_back(texture_buffer->buffer); - frames[frame].buffer_views_to_dispose_of.push_back(texture_buffer->view); + Buffer *texture_buffer = texture_buffer_owner.get_or_null(p_id); + frames[frame].buffers_to_dispose_of.push_back(*texture_buffer); texture_buffer_owner.free(p_id); } else if (storage_buffer_owner.owns(p_id)) { Buffer *storage_buffer = storage_buffer_owner.get_or_null(p_id); @@ -8563,62 +5195,45 @@ void RenderingDeviceVulkan::_free_internal(RID p_id) { } } -void RenderingDeviceVulkan::free(RID p_id) { - _THREAD_SAFE_METHOD_ - - _free_dependencies(p_id); // Recursively erase dependencies first, to avoid potential API problems. - _free_internal(p_id); -} - // The full list of resources that can be named is in the VkObjectType enum. // We just expose the resources that are owned and can be accessed easily. -void RenderingDeviceVulkan::set_resource_name(RID p_id, const String p_name) { +void RenderingDevice::set_resource_name(RID p_id, const String &p_name) { if (texture_owner.owns(p_id)) { Texture *texture = texture_owner.get_or_null(p_id); - if (texture->owner.is_null()) { - // Don't set the source texture's name when calling on a texture view. - context->set_object_name(VK_OBJECT_TYPE_IMAGE, uint64_t(texture->image), p_name); - } - context->set_object_name(VK_OBJECT_TYPE_IMAGE_VIEW, uint64_t(texture->view), p_name + " View"); + driver->set_object_name(RDD::OBJECT_TYPE_TEXTURE, texture->driver_id, p_name); } else if (framebuffer_owner.owns(p_id)) { //Framebuffer *framebuffer = framebuffer_owner.get_or_null(p_id); // Not implemented for now as the relationship between Framebuffer and RenderPass is very complex. } else if (sampler_owner.owns(p_id)) { - VkSampler *sampler = sampler_owner.get_or_null(p_id); - context->set_object_name(VK_OBJECT_TYPE_SAMPLER, uint64_t(*sampler), p_name); + RDD::SamplerID sampler_driver_id = *sampler_owner.get_or_null(p_id); + driver->set_object_name(RDD::OBJECT_TYPE_SAMPLER, sampler_driver_id, p_name); } else if (vertex_buffer_owner.owns(p_id)) { Buffer *vertex_buffer = vertex_buffer_owner.get_or_null(p_id); - context->set_object_name(VK_OBJECT_TYPE_BUFFER, uint64_t(vertex_buffer->buffer), p_name); + driver->set_object_name(RDD::OBJECT_TYPE_BUFFER, vertex_buffer->driver_id, p_name); } else if (index_buffer_owner.owns(p_id)) { IndexBuffer *index_buffer = index_buffer_owner.get_or_null(p_id); - context->set_object_name(VK_OBJECT_TYPE_BUFFER, uint64_t(index_buffer->buffer), p_name); + driver->set_object_name(RDD::OBJECT_TYPE_BUFFER, index_buffer->driver_id, p_name); } else if (shader_owner.owns(p_id)) { Shader *shader = shader_owner.get_or_null(p_id); - context->set_object_name(VK_OBJECT_TYPE_PIPELINE_LAYOUT, uint64_t(shader->pipeline_layout), p_name + " Pipeline Layout"); - for (int i = 0; i < shader->sets.size(); i++) { - context->set_object_name(VK_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT, uint64_t(shader->sets[i].descriptor_set_layout), p_name); - } + driver->set_object_name(RDD::OBJECT_TYPE_SHADER, shader->driver_id, p_name); } else if (uniform_buffer_owner.owns(p_id)) { Buffer *uniform_buffer = uniform_buffer_owner.get_or_null(p_id); - context->set_object_name(VK_OBJECT_TYPE_BUFFER, uint64_t(uniform_buffer->buffer), p_name); + driver->set_object_name(RDD::OBJECT_TYPE_BUFFER, uniform_buffer->driver_id, p_name); } else if (texture_buffer_owner.owns(p_id)) { - TextureBuffer *texture_buffer = texture_buffer_owner.get_or_null(p_id); - context->set_object_name(VK_OBJECT_TYPE_BUFFER, uint64_t(texture_buffer->buffer.buffer), p_name); - context->set_object_name(VK_OBJECT_TYPE_BUFFER_VIEW, uint64_t(texture_buffer->view), p_name + " View"); + Buffer *texture_buffer = texture_buffer_owner.get_or_null(p_id); + driver->set_object_name(RDD::OBJECT_TYPE_BUFFER, texture_buffer->driver_id, p_name); } else if (storage_buffer_owner.owns(p_id)) { Buffer *storage_buffer = storage_buffer_owner.get_or_null(p_id); - context->set_object_name(VK_OBJECT_TYPE_BUFFER, uint64_t(storage_buffer->buffer), p_name); + driver->set_object_name(RDD::OBJECT_TYPE_BUFFER, storage_buffer->driver_id, p_name); } else if (uniform_set_owner.owns(p_id)) { UniformSet *uniform_set = uniform_set_owner.get_or_null(p_id); - context->set_object_name(VK_OBJECT_TYPE_DESCRIPTOR_SET, uint64_t(uniform_set->descriptor_set), p_name); + driver->set_object_name(RDD::OBJECT_TYPE_UNIFORM_SET, uniform_set->driver_id, p_name); } else if (render_pipeline_owner.owns(p_id)) { RenderPipeline *pipeline = render_pipeline_owner.get_or_null(p_id); - context->set_object_name(VK_OBJECT_TYPE_PIPELINE, uint64_t(pipeline->pipeline), p_name); - context->set_object_name(VK_OBJECT_TYPE_PIPELINE_LAYOUT, uint64_t(pipeline->pipeline_layout), p_name + " Layout"); + driver->set_object_name(RDD::OBJECT_TYPE_PIPELINE, pipeline->driver_id, p_name); } else if (compute_pipeline_owner.owns(p_id)) { ComputePipeline *pipeline = compute_pipeline_owner.get_or_null(p_id); - context->set_object_name(VK_OBJECT_TYPE_PIPELINE, uint64_t(pipeline->pipeline), p_name); - context->set_object_name(VK_OBJECT_TYPE_PIPELINE_LAYOUT, uint64_t(pipeline->pipeline_layout), p_name + " Layout"); + driver->set_object_name(RDD::OBJECT_TYPE_PIPELINE, pipeline->driver_id, p_name); } else { ERR_PRINT("Attempted to name invalid ID: " + itos(p_id.get_id())); return; @@ -8628,42 +5243,42 @@ void RenderingDeviceVulkan::set_resource_name(RID p_id, const String p_name) { #endif } -void RenderingDeviceVulkan::draw_command_begin_label(String p_label_name, const Color p_color) { +void RenderingDevice::draw_command_begin_label(String p_label_name, const Color &p_color) { _THREAD_SAFE_METHOD_ context->command_begin_label(frames[frame].draw_command_buffer, p_label_name, p_color); } -void RenderingDeviceVulkan::draw_command_insert_label(String p_label_name, const Color p_color) { +void RenderingDevice::draw_command_insert_label(String p_label_name, const Color &p_color) { _THREAD_SAFE_METHOD_ context->command_insert_label(frames[frame].draw_command_buffer, p_label_name, p_color); } -void RenderingDeviceVulkan::draw_command_end_label() { +void RenderingDevice::draw_command_end_label() { _THREAD_SAFE_METHOD_ context->command_end_label(frames[frame].draw_command_buffer); } -String RenderingDeviceVulkan::get_device_vendor_name() const { +String RenderingDevice::get_device_vendor_name() const { return context->get_device_vendor_name(); } -String RenderingDeviceVulkan::get_device_name() const { +String RenderingDevice::get_device_name() const { return context->get_device_name(); } -RenderingDevice::DeviceType RenderingDeviceVulkan::get_device_type() const { +RenderingDevice::DeviceType RenderingDevice::get_device_type() const { return context->get_device_type(); } -String RenderingDeviceVulkan::get_device_api_version() const { +String RenderingDevice::get_device_api_version() const { return context->get_device_api_version(); } -String RenderingDeviceVulkan::get_device_pipeline_cache_uuid() const { +String RenderingDevice::get_device_pipeline_cache_uuid() const { return context->get_device_pipeline_cache_uuid(); } -void RenderingDeviceVulkan::_finalize_command_bufers() { +void RenderingDevice::_finalize_command_bufers() { if (draw_list) { ERR_PRINT("Found open draw list at the end of the frame, this should never happen (further drawing will likely not work)."); } @@ -8673,31 +5288,22 @@ void RenderingDeviceVulkan::_finalize_command_bufers() { } { // Complete the setup buffer (that needs to be processed before anything else). - vkEndCommandBuffer(frames[frame].setup_command_buffer); - vkEndCommandBuffer(frames[frame].draw_command_buffer); + driver->command_buffer_end(frames[frame].setup_command_buffer); + driver->command_buffer_end(frames[frame].draw_command_buffer); } } -void RenderingDeviceVulkan::_begin_frame() { +void RenderingDevice::_begin_frame() { // Erase pending resources. _free_pending_resources(frame); // Create setup command buffer and set as the setup buffer. - { - VkCommandBufferBeginInfo cmdbuf_begin; - cmdbuf_begin.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; - cmdbuf_begin.pNext = nullptr; - cmdbuf_begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; - cmdbuf_begin.pInheritanceInfo = nullptr; - - VkResult err = vkResetCommandBuffer(frames[frame].setup_command_buffer, 0); - ERR_FAIL_COND_MSG(err, "vkResetCommandBuffer failed with error " + itos(err) + "."); - - err = vkBeginCommandBuffer(frames[frame].setup_command_buffer, &cmdbuf_begin); - ERR_FAIL_COND_MSG(err, "vkBeginCommandBuffer failed with error " + itos(err) + "."); - err = vkBeginCommandBuffer(frames[frame].draw_command_buffer, &cmdbuf_begin); - ERR_FAIL_COND_MSG(err, "vkBeginCommandBuffer failed with error " + itos(err) + "."); + { + bool ok = driver->command_buffer_begin(frames[frame].setup_command_buffer); + ERR_FAIL_COND(!ok); + ok = driver->command_buffer_begin(frames[frame].draw_command_buffer); + ERR_FAIL_COND(!ok); if (local_device.is_null()) { context->append_command_buffer(frames[frame].draw_command_buffer); @@ -8714,8 +5320,8 @@ void RenderingDeviceVulkan::_begin_frame() { } if (frames[frame].timestamp_count) { - vkGetQueryPoolResults(device, frames[frame].timestamp_pool, 0, frames[frame].timestamp_count, sizeof(uint64_t) * max_timestamp_query_elements, frames[frame].timestamp_result_values.ptr(), sizeof(uint64_t), VK_QUERY_RESULT_64_BIT); - vkCmdResetQueryPool(frames[frame].setup_command_buffer, frames[frame].timestamp_pool, 0, frames[frame].timestamp_count); + driver->timestamp_query_pool_get_results(frames[frame].timestamp_pool, frames[frame].timestamp_count, frames[frame].timestamp_result_values.ptr()); + driver->command_timestamp_query_pool_reset(frames[frame].setup_command_buffer, frames[frame].timestamp_pool, frames[frame].timestamp_count); SWAP(frames[frame].timestamp_names, frames[frame].timestamp_result_names); SWAP(frames[frame].timestamp_cpu_values, frames[frame].timestamp_cpu_result_values); } @@ -8725,26 +5331,7 @@ void RenderingDeviceVulkan::_begin_frame() { frames[frame].index = Engine::get_singleton()->get_frames_drawn(); } -VkSampleCountFlagBits RenderingDeviceVulkan::_ensure_supported_sample_count(TextureSamples p_requested_sample_count) const { - VkSampleCountFlags sample_count_flags = limits.framebufferColorSampleCounts & limits.framebufferDepthSampleCounts; - - if (sample_count_flags & rasterization_sample_count[p_requested_sample_count]) { - // The requested sample count is supported. - return rasterization_sample_count[p_requested_sample_count]; - } else { - // Find the closest lower supported sample count. - VkSampleCountFlagBits sample_count = rasterization_sample_count[p_requested_sample_count]; - while (sample_count > VK_SAMPLE_COUNT_1_BIT) { - if (sample_count_flags & sample_count) { - return sample_count; - } - sample_count = (VkSampleCountFlagBits)(sample_count >> 1); - } - } - return VK_SAMPLE_COUNT_1_BIT; -} - -void RenderingDeviceVulkan::swap_buffers() { +void RenderingDevice::swap_buffers() { ERR_FAIL_COND_MSG(local_device.is_valid(), "Local devices can't swap buffers."); _THREAD_SAFE_METHOD_ @@ -8759,7 +5346,7 @@ void RenderingDeviceVulkan::swap_buffers() { _begin_frame(); } -void RenderingDeviceVulkan::submit() { +void RenderingDevice::submit() { _THREAD_SAFE_METHOD_ ERR_FAIL_COND_MSG(local_device.is_null(), "Only local devices can submit and sync."); @@ -8767,12 +5354,12 @@ void RenderingDeviceVulkan::submit() { _finalize_command_bufers(); - VkCommandBuffer command_buffers[2] = { frames[frame].setup_command_buffer, frames[frame].draw_command_buffer }; + RDD::CommandBufferID command_buffers[2] = { frames[frame].setup_command_buffer, frames[frame].draw_command_buffer }; context->local_device_push_command_buffers(local_device, command_buffers, 2); local_device_processing = true; } -void RenderingDeviceVulkan::sync() { +void RenderingDevice::sync() { _THREAD_SAFE_METHOD_ ERR_FAIL_COND_MSG(local_device.is_null(), "Only local devices can submit and sync."); @@ -8783,37 +5370,13 @@ void RenderingDeviceVulkan::sync() { local_device_processing = false; } -VmaPool RenderingDeviceVulkan::_find_or_create_small_allocs_pool(uint32_t p_mem_type_index) { - if (small_allocs_pools.has(p_mem_type_index)) { - return small_allocs_pools[p_mem_type_index]; - } - - print_verbose("Creating VMA small objects pool for memory type index " + itos(p_mem_type_index)); - - VmaPoolCreateInfo pci; - pci.memoryTypeIndex = p_mem_type_index; - pci.flags = 0; - pci.blockSize = 0; - pci.minBlockCount = 0; - pci.maxBlockCount = SIZE_MAX; - pci.priority = 0.5f; - pci.minAllocationAlignment = 0; - pci.pMemoryAllocateNext = nullptr; - VmaPool pool = VK_NULL_HANDLE; - VkResult res = vmaCreatePool(allocator, &pci, &pool); - small_allocs_pools[p_mem_type_index] = pool; // Don't try to create it again if failed the first time. - ERR_FAIL_COND_V_MSG(res, pool, "vmaCreatePool failed with error " + itos(res) + "."); - - return pool; -} - -void RenderingDeviceVulkan::_free_pending_resources(int p_frame) { +void RenderingDevice::_free_pending_resources(int p_frame) { // Free in dependency usage order, so nothing weird happens. // Pipelines. while (frames[p_frame].render_pipelines_to_dispose_of.front()) { RenderPipeline *pipeline = &frames[p_frame].render_pipelines_to_dispose_of.front()->get(); - vkDestroyPipeline(device, pipeline->pipeline, nullptr); + driver->pipeline_free(pipeline->driver_id); frames[p_frame].render_pipelines_to_dispose_of.pop_front(); } @@ -8821,7 +5384,7 @@ void RenderingDeviceVulkan::_free_pending_resources(int p_frame) { while (frames[p_frame].compute_pipelines_to_dispose_of.front()) { ComputePipeline *pipeline = &frames[p_frame].compute_pipelines_to_dispose_of.front()->get(); - vkDestroyPipeline(device, pipeline->pipeline, nullptr); + driver->pipeline_free(pipeline->driver_id); frames[p_frame].compute_pipelines_to_dispose_of.pop_front(); } @@ -8830,46 +5393,25 @@ void RenderingDeviceVulkan::_free_pending_resources(int p_frame) { while (frames[p_frame].uniform_sets_to_dispose_of.front()) { UniformSet *uniform_set = &frames[p_frame].uniform_sets_to_dispose_of.front()->get(); - vkFreeDescriptorSets(device, uniform_set->pool->pool, 1, &uniform_set->descriptor_set); - _descriptor_pool_free(uniform_set->pool_key, uniform_set->pool); + driver->uniform_set_free(uniform_set->driver_id); frames[p_frame].uniform_sets_to_dispose_of.pop_front(); } - // Buffer views. - while (frames[p_frame].buffer_views_to_dispose_of.front()) { - VkBufferView buffer_view = frames[p_frame].buffer_views_to_dispose_of.front()->get(); - - vkDestroyBufferView(device, buffer_view, nullptr); - - frames[p_frame].buffer_views_to_dispose_of.pop_front(); - } - // Shaders. while (frames[p_frame].shaders_to_dispose_of.front()) { Shader *shader = &frames[p_frame].shaders_to_dispose_of.front()->get(); - // Descriptor set layout for each set. - for (int i = 0; i < shader->sets.size(); i++) { - vkDestroyDescriptorSetLayout(device, shader->sets[i].descriptor_set_layout, nullptr); - } - - // Pipeline layout. - vkDestroyPipelineLayout(device, shader->pipeline_layout, nullptr); - - // Shaders themselves. - for (int i = 0; i < shader->pipeline_stages.size(); i++) { - vkDestroyShaderModule(device, shader->pipeline_stages[i].module, nullptr); - } + driver->shader_free(shader->driver_id); frames[p_frame].shaders_to_dispose_of.pop_front(); } // Samplers. while (frames[p_frame].samplers_to_dispose_of.front()) { - VkSampler sampler = frames[p_frame].samplers_to_dispose_of.front()->get(); + RDD::SamplerID sampler = frames[p_frame].samplers_to_dispose_of.front()->get(); - vkDestroySampler(device, sampler, nullptr); + driver->sampler_free(sampler); frames[p_frame].samplers_to_dispose_of.pop_front(); } @@ -8880,8 +5422,8 @@ void RenderingDeviceVulkan::_free_pending_resources(int p_frame) { for (const KeyValue &E : framebuffer->framebuffers) { // First framebuffer, then render pass because it depends on it. - vkDestroyFramebuffer(device, E.value.framebuffer, nullptr); - vkDestroyRenderPass(device, E.value.render_pass, nullptr); + driver->framebuffer_free(E.value.framebuffer); + driver->render_pass_free(E.value.render_pass); } frames[p_frame].framebuffers_to_dispose_of.pop_front(); @@ -8890,179 +5432,121 @@ void RenderingDeviceVulkan::_free_pending_resources(int p_frame) { // Textures. while (frames[p_frame].textures_to_dispose_of.front()) { Texture *texture = &frames[p_frame].textures_to_dispose_of.front()->get(); - if (texture->bound) { WARN_PRINT("Deleted a texture while it was bound."); } - vkDestroyImageView(device, texture->view, nullptr); - if (texture->owner.is_null()) { - // Actually owns the image and the allocation too. - image_memory -= texture->allocation_info.size; - vmaDestroyImage(allocator, texture->image, texture->allocation); - } + + texture_memory -= driver->texture_get_allocation_size(texture->driver_id); + driver->texture_free(texture->driver_id); + frames[p_frame].textures_to_dispose_of.pop_front(); } // Buffers. while (frames[p_frame].buffers_to_dispose_of.front()) { - _buffer_free(&frames[p_frame].buffers_to_dispose_of.front()->get()); + Buffer &buffer = frames[p_frame].buffers_to_dispose_of.front()->get(); + driver->buffer_free(buffer.driver_id); + buffer_memory -= buffer.size; frames[p_frame].buffers_to_dispose_of.pop_front(); } } -void RenderingDeviceVulkan::prepare_screen_for_drawing() { +void RenderingDevice::prepare_screen_for_drawing() { _THREAD_SAFE_METHOD_ context->prepare_buffers(); screen_prepared = true; } -uint32_t RenderingDeviceVulkan::get_frame_delay() const { +uint32_t RenderingDevice::get_frame_delay() const { return frame_count; } -uint64_t RenderingDeviceVulkan::get_memory_usage(MemoryType p_type) const { - if (p_type == MEMORY_BUFFERS) { - return buffer_memory; - } else if (p_type == MEMORY_TEXTURES) { - return image_memory; - } else { - VmaTotalStatistics stats; - vmaCalculateStatistics(allocator, &stats); - return stats.total.statistics.allocationBytes; +uint64_t RenderingDevice::get_memory_usage(MemoryType p_type) const { + switch (p_type) { + case MEMORY_BUFFERS: { + return buffer_memory; + } + case MEMORY_TEXTURES: { + return texture_memory; + } + case MEMORY_TOTAL: { + return driver->get_total_memory_used(); + } + default: { + DEV_ASSERT(false); + return 0; + } } } -void RenderingDeviceVulkan::_flush(bool p_current_frame) { +void RenderingDevice::_flush(bool p_current_frame) { if (local_device.is_valid() && !p_current_frame) { return; // Flushing previous frames has no effect with local device. } // Not doing this crashes RADV (undefined behavior). if (p_current_frame) { - vkEndCommandBuffer(frames[frame].setup_command_buffer); - vkEndCommandBuffer(frames[frame].draw_command_buffer); + driver->command_buffer_end(frames[frame].setup_command_buffer); + driver->command_buffer_end(frames[frame].draw_command_buffer); } if (local_device.is_valid()) { - VkCommandBuffer command_buffers[2] = { frames[frame].setup_command_buffer, frames[frame].draw_command_buffer }; + RDD::CommandBufferID command_buffers[2] = { frames[frame].setup_command_buffer, frames[frame].draw_command_buffer }; context->local_device_push_command_buffers(local_device, command_buffers, 2); context->local_device_sync(local_device); - VkCommandBufferBeginInfo cmdbuf_begin; - cmdbuf_begin.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; - cmdbuf_begin.pNext = nullptr; - cmdbuf_begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; - cmdbuf_begin.pInheritanceInfo = nullptr; - - VkResult err = vkBeginCommandBuffer(frames[frame].setup_command_buffer, &cmdbuf_begin); - ERR_FAIL_COND_MSG(err, "vkBeginCommandBuffer failed with error " + itos(err) + "."); - err = vkBeginCommandBuffer(frames[frame].draw_command_buffer, &cmdbuf_begin); - ERR_FAIL_COND_MSG(err, "vkBeginCommandBuffer failed with error " + itos(err) + "."); - + bool ok = driver->command_buffer_begin(frames[frame].setup_command_buffer); + ERR_FAIL_COND(!ok); + ok = driver->command_buffer_begin(frames[frame].draw_command_buffer); + ERR_FAIL_COND(!ok); } else { context->flush(p_current_frame, p_current_frame); // Re-create the setup command. if (p_current_frame) { - VkCommandBufferBeginInfo cmdbuf_begin; - cmdbuf_begin.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; - cmdbuf_begin.pNext = nullptr; - cmdbuf_begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; - cmdbuf_begin.pInheritanceInfo = nullptr; - - VkResult err = vkBeginCommandBuffer(frames[frame].setup_command_buffer, &cmdbuf_begin); - ERR_FAIL_COND_MSG(err, "vkBeginCommandBuffer failed with error " + itos(err) + "."); - context->set_setup_buffer(frames[frame].setup_command_buffer); // Append now so it's added before everything else. - } + bool ok = driver->command_buffer_begin(frames[frame].setup_command_buffer); + ERR_FAIL_COND(!ok); - if (p_current_frame) { - VkCommandBufferBeginInfo cmdbuf_begin; - cmdbuf_begin.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; - cmdbuf_begin.pNext = nullptr; - cmdbuf_begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; - cmdbuf_begin.pInheritanceInfo = nullptr; - - VkResult err = vkBeginCommandBuffer(frames[frame].draw_command_buffer, &cmdbuf_begin); - ERR_FAIL_COND_MSG(err, "vkBeginCommandBuffer failed with error " + itos(err) + "."); + context->set_setup_buffer(frames[frame].setup_command_buffer); // Append now so it's added before everything else. + ok = driver->command_buffer_begin(frames[frame].draw_command_buffer); + ERR_FAIL_COND(!ok); context->append_command_buffer(frames[frame].draw_command_buffer); } } } -void RenderingDeviceVulkan::initialize(VulkanContext *p_context, bool p_local_device) { - // Get our device capabilities. - { - device_capabilities.version_major = p_context->get_vulkan_major(); - device_capabilities.version_minor = p_context->get_vulkan_minor(); - } - +void RenderingDevice::initialize(ApiContextRD *p_context, bool p_local_device) { context = p_context; - device = p_context->get_device(); + + device_capabilities = p_context->get_device_capabilities(); + if (p_local_device) { frame_count = 1; - local_device = p_context->local_device_create(); - device = p_context->local_device_get_vk_device(local_device); + local_device = context->local_device_create(); } else { - frame_count = p_context->get_swapchain_image_count() + 1; // Always need one extra to ensure it's unused at any time, without having to use a fence for this. + frame_count = context->get_swapchain_image_count() + 1; // Always need one extra to ensure it's unused at any time, without having to use a fence for this. } - limits = p_context->get_device_limits(); + driver = context->get_driver(local_device); max_timestamp_query_elements = 256; - { // Initialize allocator. - - VmaAllocatorCreateInfo allocatorInfo; - memset(&allocatorInfo, 0, sizeof(VmaAllocatorCreateInfo)); - allocatorInfo.physicalDevice = p_context->get_physical_device(); - allocatorInfo.device = device; - allocatorInfo.instance = p_context->get_instance(); - vmaCreateAllocator(&allocatorInfo, &allocator); - } - frames.resize(frame_count); frame = 0; // Create setup and frame buffers. for (int i = 0; i < frame_count; i++) { frames[i].index = 0; - { // Create command pool, one per frame is recommended. - VkCommandPoolCreateInfo cmd_pool_info; - cmd_pool_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; - cmd_pool_info.pNext = nullptr; - cmd_pool_info.queueFamilyIndex = p_context->get_graphics_queue_family_index(); - cmd_pool_info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; - - VkResult res = vkCreateCommandPool(device, &cmd_pool_info, nullptr, &frames[i].command_pool); - ERR_FAIL_COND_MSG(res, "vkCreateCommandPool failed with error " + itos(res) + "."); - } - - { // Create command buffers. - - VkCommandBufferAllocateInfo cmdbuf; - // No command buffer exists, create it. - cmdbuf.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; - cmdbuf.pNext = nullptr; - cmdbuf.commandPool = frames[i].command_pool; - cmdbuf.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; - cmdbuf.commandBufferCount = 1; - - VkResult err = vkAllocateCommandBuffers(device, &cmdbuf, &frames[i].setup_command_buffer); - ERR_CONTINUE_MSG(err, "vkAllocateCommandBuffers failed with error " + itos(err) + "."); + // Create command pool, one per frame is recommended. + frames[i].command_pool = driver->command_pool_create(); + ERR_FAIL_COND(!frames[i].command_pool); - err = vkAllocateCommandBuffers(device, &cmdbuf, &frames[i].draw_command_buffer); - ERR_CONTINUE_MSG(err, "vkAllocateCommandBuffers failed with error " + itos(err) + "."); - } + // Create command buffers. + frames[i].setup_command_buffer = driver->command_buffer_create(RDD::COMMAND_BUFFER_TYPE_PRIMARY, frames[i].command_pool); + ERR_CONTINUE(!frames[i].setup_command_buffer); + frames[i].draw_command_buffer = driver->command_buffer_create(RDD::COMMAND_BUFFER_TYPE_PRIMARY, frames[i].command_pool); + ERR_CONTINUE(!frames[i].draw_command_buffer); { // Create query pool. - VkQueryPoolCreateInfo query_pool_create_info; - query_pool_create_info.sType = VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO; - query_pool_create_info.flags = 0; - query_pool_create_info.pNext = nullptr; - query_pool_create_info.queryType = VK_QUERY_TYPE_TIMESTAMP; - query_pool_create_info.queryCount = max_timestamp_query_elements; - query_pool_create_info.pipelineStatistics = 0; - - vkCreateQueryPool(device, &query_pool_create_info, nullptr, &frames[i].timestamp_pool); - + frames[i].timestamp_pool = driver->timestamp_query_pool_create(max_timestamp_query_elements); frames[i].timestamp_names.resize(max_timestamp_query_elements); frames[i].timestamp_cpu_values.resize(max_timestamp_query_elements); frames[i].timestamp_count = 0; @@ -9076,17 +5560,11 @@ void RenderingDeviceVulkan::initialize(VulkanContext *p_context, bool p_local_de { // Begin the first command buffer for the first frame, so // setting up things can be done in the meantime until swap_buffers(), which is called before advance. - VkCommandBufferBeginInfo cmdbuf_begin; - cmdbuf_begin.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; - cmdbuf_begin.pNext = nullptr; - cmdbuf_begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; - cmdbuf_begin.pInheritanceInfo = nullptr; - - VkResult err = vkBeginCommandBuffer(frames[0].setup_command_buffer, &cmdbuf_begin); - ERR_FAIL_COND_MSG(err, "vkBeginCommandBuffer failed with error " + itos(err) + "."); + bool ok = driver->command_buffer_begin(frames[0].setup_command_buffer); + ERR_FAIL_COND(!ok); - err = vkBeginCommandBuffer(frames[0].draw_command_buffer, &cmdbuf_begin); - ERR_FAIL_COND_MSG(err, "vkBeginCommandBuffer failed with error " + itos(err) + "."); + ok = driver->command_buffer_begin(frames[0].draw_command_buffer); + ERR_FAIL_COND(!ok); if (local_device.is_null()) { context->set_setup_buffer(frames[0].setup_command_buffer); // Append now so it's added before everything else. context->append_command_buffer(frames[0].draw_command_buffer); @@ -9095,7 +5573,7 @@ void RenderingDeviceVulkan::initialize(VulkanContext *p_context, bool p_local_de for (int i = 0; i < frame_count; i++) { //Reset all queries in a query pool before doing any operations with them. - vkCmdResetQueryPool(frames[0].setup_command_buffer, frames[i].timestamp_pool, 0, max_timestamp_query_elements); + driver->command_timestamp_query_pool_reset(frames[0].setup_command_buffer, frames[i].timestamp_pool, max_timestamp_query_elements); } staging_buffer_block_size = GLOBAL_GET("rendering/rendering_device/staging_buffer/block_size_kb"); @@ -9124,87 +5602,40 @@ void RenderingDeviceVulkan::initialize(VulkanContext *p_context, bool p_local_de ERR_CONTINUE(err != OK); } - max_descriptors_per_pool = GLOBAL_GET("rendering/rendering_device/vulkan/max_descriptors_per_pool"); - - // Check to make sure DescriptorPoolKey is good. - static_assert(sizeof(uint64_t) * 3 >= UNIFORM_TYPE_MAX * sizeof(uint16_t)); - draw_list = nullptr; draw_list_count = 0; draw_list_split = false; compute_list = nullptr; - pipelines_cache.file_path = "user://vulkan/pipelines"; - pipelines_cache.file_path += "." + context->get_device_name().validate_filename().replace(" ", "_").to_lower(); + pipelines_cache_file_path = "user://vulkan/pipelines"; + pipelines_cache_file_path += "." + context->get_device_name().validate_filename().replace(" ", "_").to_lower(); if (Engine::get_singleton()->is_editor_hint()) { - pipelines_cache.file_path += ".editor"; - } - pipelines_cache.file_path += ".cache"; - - // Prepare most fields now. - VkPhysicalDeviceProperties props; - vkGetPhysicalDeviceProperties(context->get_physical_device(), &props); - pipelines_cache.header.magic = 868 + VK_PIPELINE_CACHE_HEADER_VERSION_ONE; - pipelines_cache.header.device_id = props.deviceID; - pipelines_cache.header.vendor_id = props.vendorID; - pipelines_cache.header.driver_version = props.driverVersion; - memcpy(pipelines_cache.header.uuid, props.pipelineCacheUUID, VK_UUID_SIZE); - pipelines_cache.header.driver_abi = sizeof(void *); - - _load_pipeline_cache(); - print_verbose(vformat("Startup PSO cache (%.1f MiB)", pipelines_cache.buffer.size() / (1024.0f * 1024.0f))); - VkPipelineCacheCreateInfo cache_info = {}; - cache_info.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO; - cache_info.pNext = nullptr; - if (context->get_pipeline_cache_control_support()) { - cache_info.flags = VK_PIPELINE_CACHE_CREATE_EXTERNALLY_SYNCHRONIZED_BIT; + pipelines_cache_file_path += ".editor"; } - cache_info.initialDataSize = pipelines_cache.buffer.size(); - cache_info.pInitialData = pipelines_cache.buffer.ptr(); - VkResult err = vkCreatePipelineCache(device, &cache_info, nullptr, &pipelines_cache.cache_object); + pipelines_cache_file_path += ".cache"; - if (err != VK_SUCCESS) { - WARN_PRINT("vkCreatePipelinecache failed with error " + itos(err) + "."); + Vector cache_data = _load_pipeline_cache(); + pipelines_cache_enabled = driver->pipeline_cache_create(cache_data); + if (pipelines_cache_enabled) { + pipelines_cache_size = driver->pipeline_cache_query_size(); + print_verbose(vformat("Startup PSO cache (%.1f MiB)", pipelines_cache_size / (1024.0f * 1024.0f))); } } -void RenderingDeviceVulkan::_load_pipeline_cache() { - DirAccess::make_dir_recursive_absolute(pipelines_cache.file_path.get_base_dir()); +Vector RenderingDevice::_load_pipeline_cache() { + DirAccess::make_dir_recursive_absolute(pipelines_cache_file_path.get_base_dir()); - if (FileAccess::exists(pipelines_cache.file_path)) { + if (FileAccess::exists(pipelines_cache_file_path)) { Error file_error; - Vector file_data = FileAccess::get_file_as_bytes(pipelines_cache.file_path, &file_error); - if (file_error != OK || file_data.size() <= (int)sizeof(PipelineCacheHeader)) { - WARN_PRINT("Invalid/corrupt pipelines cache."); - return; - } - const PipelineCacheHeader *header = reinterpret_cast(file_data.ptr()); - if (header->magic != 868 + VK_PIPELINE_CACHE_HEADER_VERSION_ONE) { - WARN_PRINT("Invalid pipelines cache magic number."); - return; - } - const uint8_t *loaded_buffer_start = file_data.ptr() + sizeof(PipelineCacheHeader); - uint32_t loaded_buffer_size = file_data.size() - sizeof(PipelineCacheHeader); - if (header->data_hash != hash_murmur3_buffer(loaded_buffer_start, loaded_buffer_size) || - header->data_size != loaded_buffer_size || - header->vendor_id != pipelines_cache.header.vendor_id || - header->device_id != pipelines_cache.header.device_id || - header->driver_version != pipelines_cache.header.driver_version || - memcmp(header->uuid, pipelines_cache.header.uuid, VK_UUID_SIZE) != 0 || - header->driver_abi != pipelines_cache.header.driver_abi) { - WARN_PRINT("Invalid pipelines cache header."); - pipelines_cache.current_size = 0; - pipelines_cache.buffer.clear(); - } else { - pipelines_cache.current_size = loaded_buffer_size; - pipelines_cache.buffer.resize(loaded_buffer_size); - memcpy(pipelines_cache.buffer.ptr(), loaded_buffer_start, pipelines_cache.buffer.size()); - } + Vector file_data = FileAccess::get_file_as_bytes(pipelines_cache_file_path, &file_error); + return file_data; + } else { + return Vector(); } } -void RenderingDeviceVulkan::_update_pipeline_cache(bool p_closing) { +void RenderingDevice::_update_pipeline_cache(bool p_closing) { { bool still_saving = pipelines_cache_save_task != WorkerThreadPool::INVALID_TASK_ID && !WorkerThreadPool::get_singleton()->is_task_completed(pipelines_cache_save_task); if (still_saving) { @@ -9219,13 +5650,9 @@ void RenderingDeviceVulkan::_update_pipeline_cache(bool p_closing) { } { - // FIXME: - // We're letting the cache grow unboundedly. We may want to set at limit and see if implementations use LRU or the like. - // If we do, we won't be able to assume any longer that the cache is dirty if, and only if, it has grown. - size_t pso_blob_size = 0; - VkResult vr = vkGetPipelineCacheData(device, pipelines_cache.cache_object, &pso_blob_size, nullptr); - ERR_FAIL_COND(vr); - size_t difference = pso_blob_size - pipelines_cache.current_size; + size_t new_pipelines_cache_size = driver->pipeline_cache_query_size(); + ERR_FAIL_COND(!new_pipelines_cache_size); + size_t difference = new_pipelines_cache_size - pipelines_cache_size; bool must_save = false; @@ -9237,7 +5664,7 @@ void RenderingDeviceVulkan::_update_pipeline_cache(bool p_closing) { } if (must_save) { - pipelines_cache.current_size = pso_blob_size; + pipelines_cache_size = new_pipelines_cache_size; } else { return; } @@ -9250,31 +5677,26 @@ void RenderingDeviceVulkan::_update_pipeline_cache(bool p_closing) { } } -void RenderingDeviceVulkan::_save_pipeline_cache(void *p_data) { - RenderingDeviceVulkan *self = static_cast(p_data); - - self->pipelines_cache.buffer.resize(self->pipelines_cache.current_size); +void RenderingDevice::_save_pipeline_cache(void *p_data) { + RenderingDevice *self = static_cast(p_data); self->_thread_safe_.lock(); - VkResult vr = vkGetPipelineCacheData(self->device, self->pipelines_cache.cache_object, &self->pipelines_cache.current_size, self->pipelines_cache.buffer.ptr()); + Vector cache_blob = self->driver->pipeline_cache_serialize(); self->_thread_safe_.unlock(); - ERR_FAIL_COND(vr != VK_SUCCESS && vr != VK_INCOMPLETE); // Incomplete is OK because the cache may have grown since the size was queried (unless when exiting). - print_verbose(vformat("Updated PSO cache (%.1f MiB)", self->pipelines_cache.current_size / (1024.0f * 1024.0f))); - // The real buffer size may now be bigger than the updated current_size. - // We take into account the new size but keep the buffer resized in a worst-case fashion. + if (cache_blob.size() == 0) { + return; + } + print_verbose(vformat("Updated PSO cache (%.1f MiB)", cache_blob.size() / (1024.0f * 1024.0f))); - self->pipelines_cache.header.data_size = self->pipelines_cache.current_size; - self->pipelines_cache.header.data_hash = hash_murmur3_buffer(self->pipelines_cache.buffer.ptr(), self->pipelines_cache.current_size); - Ref f = FileAccess::open(self->pipelines_cache.file_path, FileAccess::WRITE, nullptr); + Ref f = FileAccess::open(self->pipelines_cache_file_path, FileAccess::WRITE, nullptr); if (f.is_valid()) { - f->store_buffer((const uint8_t *)&self->pipelines_cache.header, sizeof(PipelineCacheHeader)); - f->store_buffer(self->pipelines_cache.buffer.ptr(), self->pipelines_cache.current_size); + f->store_buffer(cache_blob); } } template -void RenderingDeviceVulkan::_free_rids(T &p_owner, const char *p_type) { +void RenderingDevice::_free_rids(T &p_owner, const char *p_type) { List owned; p_owner.get_owned_list(&owned); if (owned.size()) { @@ -9294,106 +5716,85 @@ void RenderingDeviceVulkan::_free_rids(T &p_owner, const char *p_type) { } } -void RenderingDeviceVulkan::capture_timestamp(const String &p_name) { +void RenderingDevice::capture_timestamp(const String &p_name) { ERR_FAIL_COND_MSG(draw_list != nullptr, "Capturing timestamps during draw list creation is not allowed. Offending timestamp was: " + p_name); ERR_FAIL_COND(frames[frame].timestamp_count >= max_timestamp_query_elements); // This should be optional for profiling, else it will slow things down. { - VkMemoryBarrier memoryBarrier; - - memoryBarrier.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER; - memoryBarrier.pNext = nullptr; - memoryBarrier.srcAccessMask = VK_ACCESS_INDIRECT_COMMAND_READ_BIT | - VK_ACCESS_INDEX_READ_BIT | - VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT | - VK_ACCESS_UNIFORM_READ_BIT | - VK_ACCESS_INPUT_ATTACHMENT_READ_BIT | - VK_ACCESS_SHADER_READ_BIT | - VK_ACCESS_SHADER_WRITE_BIT | - VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | - VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | - VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | - VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT | - VK_ACCESS_TRANSFER_READ_BIT | - VK_ACCESS_TRANSFER_WRITE_BIT | - VK_ACCESS_HOST_READ_BIT | - VK_ACCESS_HOST_WRITE_BIT; - memoryBarrier.dstAccessMask = VK_ACCESS_INDIRECT_COMMAND_READ_BIT | - VK_ACCESS_INDEX_READ_BIT | - VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT | - VK_ACCESS_UNIFORM_READ_BIT | - VK_ACCESS_INPUT_ATTACHMENT_READ_BIT | - VK_ACCESS_SHADER_READ_BIT | - VK_ACCESS_SHADER_WRITE_BIT | - VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | - VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | - VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | - VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT | - VK_ACCESS_TRANSFER_READ_BIT | - VK_ACCESS_TRANSFER_WRITE_BIT | - VK_ACCESS_HOST_READ_BIT | - VK_ACCESS_HOST_WRITE_BIT; - - vkCmdPipelineBarrier(frames[frame].draw_command_buffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 1, &memoryBarrier, 0, nullptr, 0, nullptr); - } - - vkCmdWriteTimestamp(frames[frame].draw_command_buffer, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, frames[frame].timestamp_pool, frames[frame].timestamp_count); + RDD::MemoryBarrier mb; + mb.src_access = (RDD::BARRIER_ACCESS_INDIRECT_COMMAND_READ_BIT | + RDD::BARRIER_ACCESS_INDEX_READ_BIT | + RDD::BARRIER_ACCESS_VERTEX_ATTRIBUTE_READ_BIT | + RDD::BARRIER_ACCESS_UNIFORM_READ_BIT | + RDD::BARRIER_ACCESS_INPUT_ATTACHMENT_READ_BIT | + RDD::BARRIER_ACCESS_SHADER_READ_BIT | + RDD::BARRIER_ACCESS_SHADER_WRITE_BIT | + RDD::BARRIER_ACCESS_COLOR_ATTACHMENT_READ_BIT | + RDD::BARRIER_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | + RDD::BARRIER_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | + RDD::BARRIER_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT | + RDD::BARRIER_ACCESS_TRANSFER_READ_BIT | + RDD::BARRIER_ACCESS_TRANSFER_WRITE_BIT | + RDD::BARRIER_ACCESS_HOST_READ_BIT | + RDD::BARRIER_ACCESS_HOST_WRITE_BIT); + mb.dst_access = (RDD::BARRIER_ACCESS_INDIRECT_COMMAND_READ_BIT | + RDD::BARRIER_ACCESS_INDEX_READ_BIT | + RDD::BARRIER_ACCESS_VERTEX_ATTRIBUTE_READ_BIT | + RDD::BARRIER_ACCESS_UNIFORM_READ_BIT | + RDD::BARRIER_ACCESS_INPUT_ATTACHMENT_READ_BIT | + RDD::BARRIER_ACCESS_SHADER_READ_BIT | + RDD::BARRIER_ACCESS_SHADER_WRITE_BIT | + RDD::BARRIER_ACCESS_COLOR_ATTACHMENT_READ_BIT | + RDD::BARRIER_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | + RDD::BARRIER_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | + RDD::BARRIER_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT | + RDD::BARRIER_ACCESS_TRANSFER_READ_BIT | + RDD::BARRIER_ACCESS_TRANSFER_WRITE_BIT | + RDD::BARRIER_ACCESS_HOST_READ_BIT | + RDD::BARRIER_ACCESS_HOST_WRITE_BIT); + + driver->command_pipeline_barrier(frames[frame].draw_command_buffer, RDD::PIPELINE_STAGE_ALL_COMMANDS_BIT, RDD::PIPELINE_STAGE_ALL_COMMANDS_BIT, mb, {}, {}); + } + + driver->command_timestamp_write(frames[frame].draw_command_buffer, frames[frame].timestamp_pool, frames[frame].timestamp_count); frames[frame].timestamp_names[frames[frame].timestamp_count] = p_name; frames[frame].timestamp_cpu_values[frames[frame].timestamp_count] = OS::get_singleton()->get_ticks_usec(); frames[frame].timestamp_count++; } -uint64_t RenderingDeviceVulkan::get_driver_resource(DriverResource p_resource, RID p_rid, uint64_t p_index) { +uint64_t RenderingDevice::get_driver_resource(DriverResource p_resource, RID p_rid, uint64_t p_index) { _THREAD_SAFE_METHOD_ + uint64_t driver_id = 0; switch (p_resource) { - case DRIVER_RESOURCE_VULKAN_DEVICE: { - return (uint64_t)context->get_device(); - } break; - case DRIVER_RESOURCE_VULKAN_PHYSICAL_DEVICE: { - return (uint64_t)context->get_physical_device(); - } break; - case DRIVER_RESOURCE_VULKAN_INSTANCE: { - return (uint64_t)context->get_instance(); - } break; - case DRIVER_RESOURCE_VULKAN_QUEUE: { - return (uint64_t)context->get_graphics_queue(); - } break; - case DRIVER_RESOURCE_VULKAN_QUEUE_FAMILY_INDEX: { - return context->get_graphics_queue_family_index(); - } break; - case DRIVER_RESOURCE_VULKAN_IMAGE: { - Texture *tex = texture_owner.get_or_null(p_rid); - ERR_FAIL_NULL_V(tex, 0); - - return (uint64_t)tex->image; - } break; - case DRIVER_RESOURCE_VULKAN_IMAGE_VIEW: { - Texture *tex = texture_owner.get_or_null(p_rid); - ERR_FAIL_NULL_V(tex, 0); - - return (uint64_t)tex->view; - } break; - case DRIVER_RESOURCE_VULKAN_IMAGE_NATIVE_TEXTURE_FORMAT: { + case DRIVER_RESOURCE_LOGICAL_DEVICE: + case DRIVER_RESOURCE_PHYSICAL_DEVICE: + case DRIVER_RESOURCE_TOPMOST_OBJECT: + case DRIVER_RESOURCE_COMMAND_QUEUE: + case DRIVER_RESOURCE_QUEUE_FAMILY: + break; + case DRIVER_RESOURCE_TEXTURE: + case DRIVER_RESOURCE_TEXTURE_VIEW: + case DRIVER_RESOURCE_TEXTURE_DATA_FORMAT: { Texture *tex = texture_owner.get_or_null(p_rid); ERR_FAIL_NULL_V(tex, 0); - return vulkan_formats[tex->format]; + driver_id = tex->driver_id; } break; - case DRIVER_RESOURCE_VULKAN_SAMPLER: { - VkSampler *sampler = sampler_owner.get_or_null(p_rid); - ERR_FAIL_NULL_V(sampler, 0); + case DRIVER_RESOURCE_SAMPLER: { + RDD::SamplerID *sampler_driver_id = sampler_owner.get_or_null(p_rid); + ERR_FAIL_NULL_V(sampler_driver_id, 0); - return uint64_t(*sampler); + driver_id = *sampler_driver_id; } break; - case DRIVER_RESOURCE_VULKAN_DESCRIPTOR_SET: { + case DRIVER_RESOURCE_UNIFORM_SET: { UniformSet *uniform_set = uniform_set_owner.get_or_null(p_rid); ERR_FAIL_NULL_V(uniform_set, 0); - return uint64_t(uniform_set->descriptor_set); + driver_id = uniform_set->driver_id; } break; - case DRIVER_RESOURCE_VULKAN_BUFFER: { + case DRIVER_RESOURCE_BUFFER: { Buffer *buffer = nullptr; if (vertex_buffer_owner.owns(p_rid)) { buffer = vertex_buffer_owner.get_or_null(p_rid); @@ -9402,198 +5803,62 @@ uint64_t RenderingDeviceVulkan::get_driver_resource(DriverResource p_resource, R } else if (uniform_buffer_owner.owns(p_rid)) { buffer = uniform_buffer_owner.get_or_null(p_rid); } else if (texture_buffer_owner.owns(p_rid)) { - buffer = &texture_buffer_owner.get_or_null(p_rid)->buffer; + buffer = texture_buffer_owner.get_or_null(p_rid); } else if (storage_buffer_owner.owns(p_rid)) { buffer = storage_buffer_owner.get_or_null(p_rid); } - ERR_FAIL_NULL_V(buffer, 0); - return uint64_t(buffer->buffer); + driver_id = buffer->driver_id; } break; - case DRIVER_RESOURCE_VULKAN_COMPUTE_PIPELINE: { + case DRIVER_RESOURCE_COMPUTE_PIPELINE: { ComputePipeline *compute_pipeline = compute_pipeline_owner.get_or_null(p_rid); ERR_FAIL_NULL_V(compute_pipeline, 0); - return uint64_t(compute_pipeline->pipeline); + driver_id = compute_pipeline->driver_id; } break; - case DRIVER_RESOURCE_VULKAN_RENDER_PIPELINE: { + case DRIVER_RESOURCE_RENDER_PIPELINE: { RenderPipeline *render_pipeline = render_pipeline_owner.get_or_null(p_rid); ERR_FAIL_NULL_V(render_pipeline, 0); - return uint64_t(render_pipeline->pipeline); + driver_id = render_pipeline->driver_id; } break; default: { - // Not supported for this driver. - return 0; + ERR_FAIL_V(0); } break; } + + return driver->get_resource_native_handle(p_resource, driver_id); } -uint32_t RenderingDeviceVulkan::get_captured_timestamps_count() const { +uint32_t RenderingDevice::get_captured_timestamps_count() const { return frames[frame].timestamp_result_count; } -uint64_t RenderingDeviceVulkan::get_captured_timestamps_frame() const { +uint64_t RenderingDevice::get_captured_timestamps_frame() const { return frames[frame].index; } -static void mult64to128(uint64_t u, uint64_t v, uint64_t &h, uint64_t &l) { - uint64_t u1 = (u & 0xffffffff); - uint64_t v1 = (v & 0xffffffff); - uint64_t t = (u1 * v1); - uint64_t w3 = (t & 0xffffffff); - uint64_t k = (t >> 32); - - u >>= 32; - t = (u * v1) + k; - k = (t & 0xffffffff); - uint64_t w1 = (t >> 32); - - v >>= 32; - t = (u1 * v) + k; - k = (t >> 32); - - h = (u * v) + w1 + k; - l = (t << 32) + w3; -} - -uint64_t RenderingDeviceVulkan::get_captured_timestamp_gpu_time(uint32_t p_index) const { +uint64_t RenderingDevice::get_captured_timestamp_gpu_time(uint32_t p_index) const { ERR_FAIL_UNSIGNED_INDEX_V(p_index, frames[frame].timestamp_result_count, 0); - - // This sucks because timestampPeriod multiplier is a float, while the timestamp is 64 bits nanosecs. - // So, in cases like nvidia which give you enormous numbers and 1 as multiplier, multiplying is next to impossible. - // Need to do 128 bits fixed point multiplication to get the right value. - - uint64_t shift_bits = 16; - - uint64_t h, l; - - mult64to128(frames[frame].timestamp_result_values[p_index], uint64_t(double(limits.timestampPeriod) * double(1 << shift_bits)), h, l); - l >>= shift_bits; - l |= h << (64 - shift_bits); - - return l; + return driver->timestamp_query_result_to_time(frames[frame].timestamp_result_values[p_index]); } -uint64_t RenderingDeviceVulkan::get_captured_timestamp_cpu_time(uint32_t p_index) const { +uint64_t RenderingDevice::get_captured_timestamp_cpu_time(uint32_t p_index) const { ERR_FAIL_UNSIGNED_INDEX_V(p_index, frames[frame].timestamp_result_count, 0); return frames[frame].timestamp_cpu_result_values[p_index]; } -String RenderingDeviceVulkan::get_captured_timestamp_name(uint32_t p_index) const { +String RenderingDevice::get_captured_timestamp_name(uint32_t p_index) const { ERR_FAIL_UNSIGNED_INDEX_V(p_index, frames[frame].timestamp_result_count, String()); return frames[frame].timestamp_result_names[p_index]; } -uint64_t RenderingDeviceVulkan::limit_get(Limit p_limit) const { - switch (p_limit) { - case LIMIT_MAX_BOUND_UNIFORM_SETS: - return limits.maxBoundDescriptorSets; - case LIMIT_MAX_FRAMEBUFFER_COLOR_ATTACHMENTS: - return limits.maxColorAttachments; - case LIMIT_MAX_TEXTURES_PER_UNIFORM_SET: - return limits.maxDescriptorSetSampledImages; - case LIMIT_MAX_SAMPLERS_PER_UNIFORM_SET: - return limits.maxDescriptorSetSamplers; - case LIMIT_MAX_STORAGE_BUFFERS_PER_UNIFORM_SET: - return limits.maxDescriptorSetStorageBuffers; - case LIMIT_MAX_STORAGE_IMAGES_PER_UNIFORM_SET: - return limits.maxDescriptorSetStorageImages; - case LIMIT_MAX_UNIFORM_BUFFERS_PER_UNIFORM_SET: - return limits.maxDescriptorSetUniformBuffers; - case LIMIT_MAX_DRAW_INDEXED_INDEX: - return limits.maxDrawIndexedIndexValue; - case LIMIT_MAX_FRAMEBUFFER_HEIGHT: - return limits.maxFramebufferHeight; - case LIMIT_MAX_FRAMEBUFFER_WIDTH: - return limits.maxFramebufferWidth; - case LIMIT_MAX_TEXTURE_ARRAY_LAYERS: - return limits.maxImageArrayLayers; - case LIMIT_MAX_TEXTURE_SIZE_1D: - return limits.maxImageDimension1D; - case LIMIT_MAX_TEXTURE_SIZE_2D: - return limits.maxImageDimension2D; - case LIMIT_MAX_TEXTURE_SIZE_3D: - return limits.maxImageDimension3D; - case LIMIT_MAX_TEXTURE_SIZE_CUBE: - return limits.maxImageDimensionCube; - case LIMIT_MAX_TEXTURES_PER_SHADER_STAGE: - return limits.maxPerStageDescriptorSampledImages; - case LIMIT_MAX_SAMPLERS_PER_SHADER_STAGE: - return limits.maxPerStageDescriptorSamplers; - case LIMIT_MAX_STORAGE_BUFFERS_PER_SHADER_STAGE: - return limits.maxPerStageDescriptorStorageBuffers; - case LIMIT_MAX_STORAGE_IMAGES_PER_SHADER_STAGE: - return limits.maxPerStageDescriptorStorageImages; - case LIMIT_MAX_UNIFORM_BUFFERS_PER_SHADER_STAGE: - return limits.maxPerStageDescriptorUniformBuffers; - case LIMIT_MAX_PUSH_CONSTANT_SIZE: - return limits.maxPushConstantsSize; - case LIMIT_MAX_UNIFORM_BUFFER_SIZE: - return limits.maxUniformBufferRange; - case LIMIT_MAX_VERTEX_INPUT_ATTRIBUTE_OFFSET: - return limits.maxVertexInputAttributeOffset; - case LIMIT_MAX_VERTEX_INPUT_ATTRIBUTES: - return limits.maxVertexInputAttributes; - case LIMIT_MAX_VERTEX_INPUT_BINDINGS: - return limits.maxVertexInputBindings; - case LIMIT_MAX_VERTEX_INPUT_BINDING_STRIDE: - return limits.maxVertexInputBindingStride; - case LIMIT_MIN_UNIFORM_BUFFER_OFFSET_ALIGNMENT: - return limits.minUniformBufferOffsetAlignment; - case LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_X: - return limits.maxComputeWorkGroupCount[0]; - case LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_Y: - return limits.maxComputeWorkGroupCount[1]; - case LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_Z: - return limits.maxComputeWorkGroupCount[2]; - case LIMIT_MAX_COMPUTE_WORKGROUP_INVOCATIONS: - return limits.maxComputeWorkGroupInvocations; - case LIMIT_MAX_COMPUTE_WORKGROUP_SIZE_X: - return limits.maxComputeWorkGroupSize[0]; - case LIMIT_MAX_COMPUTE_WORKGROUP_SIZE_Y: - return limits.maxComputeWorkGroupSize[1]; - case LIMIT_MAX_COMPUTE_WORKGROUP_SIZE_Z: - return limits.maxComputeWorkGroupSize[2]; - case LIMIT_MAX_VIEWPORT_DIMENSIONS_X: - return limits.maxViewportDimensions[0]; - case LIMIT_MAX_VIEWPORT_DIMENSIONS_Y: - return limits.maxViewportDimensions[1]; - case LIMIT_SUBGROUP_SIZE: { - VulkanContext::SubgroupCapabilities subgroup_capabilities = context->get_subgroup_capabilities(); - return subgroup_capabilities.size; - } - case LIMIT_SUBGROUP_MIN_SIZE: { - VulkanContext::SubgroupCapabilities subgroup_capabilities = context->get_subgroup_capabilities(); - return subgroup_capabilities.min_size; - } - case LIMIT_SUBGROUP_MAX_SIZE: { - VulkanContext::SubgroupCapabilities subgroup_capabilities = context->get_subgroup_capabilities(); - return subgroup_capabilities.max_size; - } - case LIMIT_SUBGROUP_IN_SHADERS: { - VulkanContext::SubgroupCapabilities subgroup_capabilities = context->get_subgroup_capabilities(); - return subgroup_capabilities.supported_stages_flags_rd(); - } - case LIMIT_SUBGROUP_OPERATIONS: { - VulkanContext::SubgroupCapabilities subgroup_capabilities = context->get_subgroup_capabilities(); - return subgroup_capabilities.supported_operations_flags_rd(); - } - case LIMIT_VRS_TEXEL_WIDTH: { - return context->get_vrs_capabilities().texel_size.x; - } - case LIMIT_VRS_TEXEL_HEIGHT: { - return context->get_vrs_capabilities().texel_size.y; - } - default: - ERR_FAIL_V(0); - } - - return 0; +uint64_t RenderingDevice::limit_get(Limit p_limit) const { + return driver->limit_get(p_limit); } -void RenderingDeviceVulkan::finalize() { +void RenderingDevice::finalize() { // Free all resources. _flush(false); @@ -9648,85 +5913,1024 @@ void RenderingDeviceVulkan::finalize() { } // Free everything pending. - for (int i = 0; i < frame_count; i++) { - int f = (frame + i) % frame_count; + for (uint32_t i = 0; i < frames.size(); i++) { + int f = (frame + i) % frames.size(); _free_pending_resources(f); - vkDestroyCommandPool(device, frames[i].command_pool, nullptr); - vkDestroyQueryPool(device, frames[i].timestamp_pool, nullptr); + driver->command_pool_free(frames[i].command_pool); + driver->timestamp_query_pool_free(frames[i].timestamp_pool); } - _update_pipeline_cache(true); - vkDestroyPipelineCache(device, pipelines_cache.cache_object, nullptr); + if (pipelines_cache_enabled) { + _update_pipeline_cache(true); + driver->pipeline_cache_free(); + } for (int i = 0; i < split_draw_list_allocators.size(); i++) { - vkDestroyCommandPool(device, split_draw_list_allocators[i].command_pool, nullptr); + driver->command_pool_free(split_draw_list_allocators[i].command_pool); } frames.clear(); for (int i = 0; i < staging_buffer_blocks.size(); i++) { - vmaDestroyBuffer(allocator, staging_buffer_blocks[i].buffer, staging_buffer_blocks[i].allocation); - } - while (small_allocs_pools.size()) { - HashMap::Iterator E = small_allocs_pools.begin(); - vmaDestroyPool(allocator, E->value); - small_allocs_pools.remove(E); + driver->buffer_free(staging_buffer_blocks[i].driver_id); } - vmaDestroyAllocator(allocator); while (vertex_formats.size()) { HashMap::Iterator temp = vertex_formats.begin(); - memdelete_arr(temp->value.bindings); - memdelete_arr(temp->value.attributes); + driver->vertex_format_free(temp->value.driver_id); vertex_formats.remove(temp); } for (KeyValue &E : framebuffer_formats) { - vkDestroyRenderPass(device, E.value.render_pass, nullptr); + driver->render_pass_free(E.value.render_pass); } framebuffer_formats.clear(); // All these should be clear at this point. - ERR_FAIL_COND(descriptor_pools.size()); ERR_FAIL_COND(dependency_map.size()); ERR_FAIL_COND(reverse_dependency_map.size()); } -RenderingDevice *RenderingDeviceVulkan::create_local_device() { - RenderingDeviceVulkan *rd = memnew(RenderingDeviceVulkan); +RenderingDevice *RenderingDevice::create_local_device() { + RenderingDevice *rd = memnew(RenderingDevice); rd->initialize(context, true); return rd; } -bool RenderingDeviceVulkan::has_feature(const Features p_feature) const { - switch (p_feature) { - case SUPPORTS_MULTIVIEW: { - VulkanContext::MultiviewCapabilities multiview_capabilies = context->get_multiview_capabilities(); - return multiview_capabilies.is_supported && multiview_capabilies.max_view_count > 1; - } break; - case SUPPORTS_FSR_HALF_FLOAT: { - return context->get_shader_capabilities().shader_float16_is_supported && context->get_physical_device_features().shaderInt16 && context->get_storage_buffer_capabilities().storage_buffer_16_bit_access_is_supported; - } break; - case SUPPORTS_ATTACHMENT_VRS: { - VulkanContext::VRSCapabilities vrs_capabilities = context->get_vrs_capabilities(); - return vrs_capabilities.attachment_vrs_supported && context->get_physical_device_features().shaderStorageImageExtendedFormats; - } break; - case SUPPORTS_FRAGMENT_SHADER_WITH_ONLY_SIDE_EFFECTS: { - return true; - } break; - default: { - return false; - } - } +bool RenderingDevice::has_feature(const Features p_feature) const { + return driver->has_feature(p_feature); } -RenderingDeviceVulkan::RenderingDeviceVulkan() { - device_capabilities.device_family = DEVICE_VULKAN; -} +void RenderingDevice::_bind_methods() { + ClassDB::bind_method(D_METHOD("texture_create", "format", "view", "data"), &RenderingDevice::_texture_create, DEFVAL(Array())); + ClassDB::bind_method(D_METHOD("texture_create_shared", "view", "with_texture"), &RenderingDevice::_texture_create_shared); + ClassDB::bind_method(D_METHOD("texture_create_shared_from_slice", "view", "with_texture", "layer", "mipmap", "mipmaps", "slice_type"), &RenderingDevice::_texture_create_shared_from_slice, DEFVAL(1), DEFVAL(TEXTURE_SLICE_2D)); + ClassDB::bind_method(D_METHOD("texture_create_from_extension", "type", "format", "samples", "usage_flags", "image", "width", "height", "depth", "layers"), &RenderingDevice::texture_create_from_extension); + + ClassDB::bind_method(D_METHOD("texture_update", "texture", "layer", "data", "post_barrier"), &RenderingDevice::texture_update, DEFVAL(BARRIER_MASK_ALL_BARRIERS)); + ClassDB::bind_method(D_METHOD("texture_get_data", "texture", "layer"), &RenderingDevice::texture_get_data); + + ClassDB::bind_method(D_METHOD("texture_is_format_supported_for_usage", "format", "usage_flags"), &RenderingDevice::texture_is_format_supported_for_usage); + + ClassDB::bind_method(D_METHOD("texture_is_shared", "texture"), &RenderingDevice::texture_is_shared); + ClassDB::bind_method(D_METHOD("texture_is_valid", "texture"), &RenderingDevice::texture_is_valid); + + ClassDB::bind_method(D_METHOD("texture_copy", "from_texture", "to_texture", "from_pos", "to_pos", "size", "src_mipmap", "dst_mipmap", "src_layer", "dst_layer", "post_barrier"), &RenderingDevice::texture_copy, DEFVAL(BARRIER_MASK_ALL_BARRIERS)); + ClassDB::bind_method(D_METHOD("texture_clear", "texture", "color", "base_mipmap", "mipmap_count", "base_layer", "layer_count", "post_barrier"), &RenderingDevice::texture_clear, DEFVAL(BARRIER_MASK_ALL_BARRIERS)); + ClassDB::bind_method(D_METHOD("texture_resolve_multisample", "from_texture", "to_texture", "post_barrier"), &RenderingDevice::texture_resolve_multisample, DEFVAL(BARRIER_MASK_ALL_BARRIERS)); + + ClassDB::bind_method(D_METHOD("texture_get_format", "texture"), &RenderingDevice::_texture_get_format); +#ifndef DISABLE_DEPRECATED + ClassDB::bind_method(D_METHOD("texture_get_native_handle", "texture"), &RenderingDevice::texture_get_native_handle); +#endif + + ClassDB::bind_method(D_METHOD("framebuffer_format_create", "attachments", "view_count"), &RenderingDevice::_framebuffer_format_create, DEFVAL(1)); + ClassDB::bind_method(D_METHOD("framebuffer_format_create_multipass", "attachments", "passes", "view_count"), &RenderingDevice::_framebuffer_format_create_multipass, DEFVAL(1)); + ClassDB::bind_method(D_METHOD("framebuffer_format_create_empty", "samples"), &RenderingDevice::framebuffer_format_create_empty, DEFVAL(TEXTURE_SAMPLES_1)); + ClassDB::bind_method(D_METHOD("framebuffer_format_get_texture_samples", "format", "render_pass"), &RenderingDevice::framebuffer_format_get_texture_samples, DEFVAL(0)); + ClassDB::bind_method(D_METHOD("framebuffer_create", "textures", "validate_with_format", "view_count"), &RenderingDevice::_framebuffer_create, DEFVAL(INVALID_FORMAT_ID), DEFVAL(1)); + ClassDB::bind_method(D_METHOD("framebuffer_create_multipass", "textures", "passes", "validate_with_format", "view_count"), &RenderingDevice::_framebuffer_create_multipass, DEFVAL(INVALID_FORMAT_ID), DEFVAL(1)); + ClassDB::bind_method(D_METHOD("framebuffer_create_empty", "size", "samples", "validate_with_format"), &RenderingDevice::framebuffer_create_empty, DEFVAL(TEXTURE_SAMPLES_1), DEFVAL(INVALID_FORMAT_ID)); + ClassDB::bind_method(D_METHOD("framebuffer_get_format", "framebuffer"), &RenderingDevice::framebuffer_get_format); + ClassDB::bind_method(D_METHOD("framebuffer_is_valid", "framebuffer"), &RenderingDevice::framebuffer_is_valid); + + ClassDB::bind_method(D_METHOD("sampler_create", "state"), &RenderingDevice::_sampler_create); + ClassDB::bind_method(D_METHOD("sampler_is_format_supported_for_filter", "format", "sampler_filter"), &RenderingDevice::sampler_is_format_supported_for_filter); + + ClassDB::bind_method(D_METHOD("vertex_buffer_create", "size_bytes", "data", "use_as_storage"), &RenderingDevice::vertex_buffer_create, DEFVAL(Vector()), DEFVAL(false)); + ClassDB::bind_method(D_METHOD("vertex_format_create", "vertex_descriptions"), &RenderingDevice::_vertex_format_create); + ClassDB::bind_method(D_METHOD("vertex_array_create", "vertex_count", "vertex_format", "src_buffers", "offsets"), &RenderingDevice::_vertex_array_create, DEFVAL(Vector())); + + ClassDB::bind_method(D_METHOD("index_buffer_create", "size_indices", "format", "data", "use_restart_indices"), &RenderingDevice::index_buffer_create, DEFVAL(Vector()), DEFVAL(false)); + ClassDB::bind_method(D_METHOD("index_array_create", "index_buffer", "index_offset", "index_count"), &RenderingDevice::index_array_create); + + ClassDB::bind_method(D_METHOD("shader_compile_spirv_from_source", "shader_source", "allow_cache"), &RenderingDevice::_shader_compile_spirv_from_source, DEFVAL(true)); + ClassDB::bind_method(D_METHOD("shader_compile_binary_from_spirv", "spirv_data", "name"), &RenderingDevice::_shader_compile_binary_from_spirv, DEFVAL("")); + ClassDB::bind_method(D_METHOD("shader_create_from_spirv", "spirv_data", "name"), &RenderingDevice::_shader_create_from_spirv, DEFVAL("")); + ClassDB::bind_method(D_METHOD("shader_create_from_bytecode", "binary_data", "placeholder_rid"), &RenderingDevice::shader_create_from_bytecode, DEFVAL(RID())); + ClassDB::bind_method(D_METHOD("shader_create_placeholder"), &RenderingDevice::shader_create_placeholder); + + ClassDB::bind_method(D_METHOD("shader_get_vertex_input_attribute_mask", "shader"), &RenderingDevice::shader_get_vertex_input_attribute_mask); + + ClassDB::bind_method(D_METHOD("uniform_buffer_create", "size_bytes", "data"), &RenderingDevice::uniform_buffer_create, DEFVAL(Vector())); + ClassDB::bind_method(D_METHOD("storage_buffer_create", "size_bytes", "data", "usage"), &RenderingDevice::storage_buffer_create, DEFVAL(Vector()), DEFVAL(0)); + ClassDB::bind_method(D_METHOD("texture_buffer_create", "size_bytes", "format", "data"), &RenderingDevice::texture_buffer_create, DEFVAL(Vector())); + + ClassDB::bind_method(D_METHOD("uniform_set_create", "uniforms", "shader", "shader_set"), &RenderingDevice::_uniform_set_create); + ClassDB::bind_method(D_METHOD("uniform_set_is_valid", "uniform_set"), &RenderingDevice::uniform_set_is_valid); + + ClassDB::bind_method(D_METHOD("buffer_update", "buffer", "offset", "size_bytes", "data", "post_barrier"), &RenderingDevice::_buffer_update_bind, DEFVAL(BARRIER_MASK_ALL_BARRIERS)); + ClassDB::bind_method(D_METHOD("buffer_clear", "buffer", "offset", "size_bytes", "post_barrier"), &RenderingDevice::buffer_clear, DEFVAL(BARRIER_MASK_ALL_BARRIERS)); + ClassDB::bind_method(D_METHOD("buffer_get_data", "buffer", "offset_bytes", "size_bytes"), &RenderingDevice::buffer_get_data, DEFVAL(0), DEFVAL(0)); + + ClassDB::bind_method(D_METHOD("render_pipeline_create", "shader", "framebuffer_format", "vertex_format", "primitive", "rasterization_state", "multisample_state", "stencil_state", "color_blend_state", "dynamic_state_flags", "for_render_pass", "specialization_constants"), &RenderingDevice::_render_pipeline_create, DEFVAL(0), DEFVAL(0), DEFVAL(TypedArray())); + ClassDB::bind_method(D_METHOD("render_pipeline_is_valid", "render_pipeline"), &RenderingDevice::render_pipeline_is_valid); + + ClassDB::bind_method(D_METHOD("compute_pipeline_create", "shader", "specialization_constants"), &RenderingDevice::_compute_pipeline_create, DEFVAL(TypedArray())); + ClassDB::bind_method(D_METHOD("compute_pipeline_is_valid", "compute_pipeline"), &RenderingDevice::compute_pipeline_is_valid); + + ClassDB::bind_method(D_METHOD("screen_get_width", "screen"), &RenderingDevice::screen_get_width, DEFVAL(DisplayServer::MAIN_WINDOW_ID)); + ClassDB::bind_method(D_METHOD("screen_get_height", "screen"), &RenderingDevice::screen_get_height, DEFVAL(DisplayServer::MAIN_WINDOW_ID)); + ClassDB::bind_method(D_METHOD("screen_get_framebuffer_format"), &RenderingDevice::screen_get_framebuffer_format); + + ClassDB::bind_method(D_METHOD("draw_list_begin_for_screen", "screen", "clear_color"), &RenderingDevice::draw_list_begin_for_screen, DEFVAL(DisplayServer::MAIN_WINDOW_ID), DEFVAL(Color())); + + ClassDB::bind_method(D_METHOD("draw_list_begin", "framebuffer", "initial_color_action", "final_color_action", "initial_depth_action", "final_depth_action", "clear_color_values", "clear_depth", "clear_stencil", "region", "storage_textures"), &RenderingDevice::_draw_list_begin, DEFVAL(Vector()), DEFVAL(1.0), DEFVAL(0), DEFVAL(Rect2()), DEFVAL(TypedArray())); + ClassDB::bind_method(D_METHOD("draw_list_begin_split", "framebuffer", "splits", "initial_color_action", "final_color_action", "initial_depth_action", "final_depth_action", "clear_color_values", "clear_depth", "clear_stencil", "region", "storage_textures"), &RenderingDevice::_draw_list_begin_split, DEFVAL(Vector()), DEFVAL(1.0), DEFVAL(0), DEFVAL(Rect2()), DEFVAL(TypedArray())); + + ClassDB::bind_method(D_METHOD("draw_list_set_blend_constants", "draw_list", "color"), &RenderingDevice::draw_list_set_blend_constants); + ClassDB::bind_method(D_METHOD("draw_list_bind_render_pipeline", "draw_list", "render_pipeline"), &RenderingDevice::draw_list_bind_render_pipeline); + ClassDB::bind_method(D_METHOD("draw_list_bind_uniform_set", "draw_list", "uniform_set", "set_index"), &RenderingDevice::draw_list_bind_uniform_set); + ClassDB::bind_method(D_METHOD("draw_list_bind_vertex_array", "draw_list", "vertex_array"), &RenderingDevice::draw_list_bind_vertex_array); + ClassDB::bind_method(D_METHOD("draw_list_bind_index_array", "draw_list", "index_array"), &RenderingDevice::draw_list_bind_index_array); + ClassDB::bind_method(D_METHOD("draw_list_set_push_constant", "draw_list", "buffer", "size_bytes"), &RenderingDevice::_draw_list_set_push_constant); + + ClassDB::bind_method(D_METHOD("draw_list_draw", "draw_list", "use_indices", "instances", "procedural_vertex_count"), &RenderingDevice::draw_list_draw, DEFVAL(0)); + + ClassDB::bind_method(D_METHOD("draw_list_enable_scissor", "draw_list", "rect"), &RenderingDevice::draw_list_enable_scissor, DEFVAL(Rect2())); + ClassDB::bind_method(D_METHOD("draw_list_disable_scissor", "draw_list"), &RenderingDevice::draw_list_disable_scissor); + + ClassDB::bind_method(D_METHOD("draw_list_switch_to_next_pass"), &RenderingDevice::draw_list_switch_to_next_pass); + ClassDB::bind_method(D_METHOD("draw_list_switch_to_next_pass_split", "splits"), &RenderingDevice::_draw_list_switch_to_next_pass_split); + + ClassDB::bind_method(D_METHOD("draw_list_end", "post_barrier"), &RenderingDevice::draw_list_end, DEFVAL(BARRIER_MASK_ALL_BARRIERS)); + + ClassDB::bind_method(D_METHOD("compute_list_begin", "allow_draw_overlap"), &RenderingDevice::compute_list_begin, DEFVAL(false)); + ClassDB::bind_method(D_METHOD("compute_list_bind_compute_pipeline", "compute_list", "compute_pipeline"), &RenderingDevice::compute_list_bind_compute_pipeline); + ClassDB::bind_method(D_METHOD("compute_list_set_push_constant", "compute_list", "buffer", "size_bytes"), &RenderingDevice::_compute_list_set_push_constant); + ClassDB::bind_method(D_METHOD("compute_list_bind_uniform_set", "compute_list", "uniform_set", "set_index"), &RenderingDevice::compute_list_bind_uniform_set); + ClassDB::bind_method(D_METHOD("compute_list_dispatch", "compute_list", "x_groups", "y_groups", "z_groups"), &RenderingDevice::compute_list_dispatch); + ClassDB::bind_method(D_METHOD("compute_list_add_barrier", "compute_list"), &RenderingDevice::compute_list_add_barrier); + ClassDB::bind_method(D_METHOD("compute_list_end", "post_barrier"), &RenderingDevice::compute_list_end, DEFVAL(BARRIER_MASK_ALL_BARRIERS)); + + ClassDB::bind_method(D_METHOD("free_rid", "rid"), &RenderingDevice::free); + + ClassDB::bind_method(D_METHOD("capture_timestamp", "name"), &RenderingDevice::capture_timestamp); + ClassDB::bind_method(D_METHOD("get_captured_timestamps_count"), &RenderingDevice::get_captured_timestamps_count); + ClassDB::bind_method(D_METHOD("get_captured_timestamps_frame"), &RenderingDevice::get_captured_timestamps_frame); + ClassDB::bind_method(D_METHOD("get_captured_timestamp_gpu_time", "index"), &RenderingDevice::get_captured_timestamp_gpu_time); + ClassDB::bind_method(D_METHOD("get_captured_timestamp_cpu_time", "index"), &RenderingDevice::get_captured_timestamp_cpu_time); + ClassDB::bind_method(D_METHOD("get_captured_timestamp_name", "index"), &RenderingDevice::get_captured_timestamp_name); + + ClassDB::bind_method(D_METHOD("limit_get", "limit"), &RenderingDevice::limit_get); + ClassDB::bind_method(D_METHOD("get_frame_delay"), &RenderingDevice::get_frame_delay); + ClassDB::bind_method(D_METHOD("submit"), &RenderingDevice::submit); + ClassDB::bind_method(D_METHOD("sync"), &RenderingDevice::sync); + + ClassDB::bind_method(D_METHOD("barrier", "from", "to"), &RenderingDevice::barrier, DEFVAL(BARRIER_MASK_ALL_BARRIERS), DEFVAL(BARRIER_MASK_ALL_BARRIERS)); + ClassDB::bind_method(D_METHOD("full_barrier"), &RenderingDevice::full_barrier); + + ClassDB::bind_method(D_METHOD("create_local_device"), &RenderingDevice::create_local_device); + + ClassDB::bind_method(D_METHOD("set_resource_name", "id", "name"), &RenderingDevice::set_resource_name); + + ClassDB::bind_method(D_METHOD("draw_command_begin_label", "name", "color"), &RenderingDevice::draw_command_begin_label); + ClassDB::bind_method(D_METHOD("draw_command_insert_label", "name", "color"), &RenderingDevice::draw_command_insert_label); + ClassDB::bind_method(D_METHOD("draw_command_end_label"), &RenderingDevice::draw_command_end_label); + + ClassDB::bind_method(D_METHOD("get_device_vendor_name"), &RenderingDevice::get_device_vendor_name); + ClassDB::bind_method(D_METHOD("get_device_name"), &RenderingDevice::get_device_name); + ClassDB::bind_method(D_METHOD("get_device_pipeline_cache_uuid"), &RenderingDevice::get_device_pipeline_cache_uuid); + + ClassDB::bind_method(D_METHOD("get_memory_usage", "type"), &RenderingDevice::get_memory_usage); + + ClassDB::bind_method(D_METHOD("get_driver_resource", "resource", "rid", "index"), &RenderingDevice::get_driver_resource); + + BIND_ENUM_CONSTANT(DEVICE_TYPE_OTHER); + BIND_ENUM_CONSTANT(DEVICE_TYPE_INTEGRATED_GPU); + BIND_ENUM_CONSTANT(DEVICE_TYPE_DISCRETE_GPU); + BIND_ENUM_CONSTANT(DEVICE_TYPE_VIRTUAL_GPU); + BIND_ENUM_CONSTANT(DEVICE_TYPE_CPU); + BIND_ENUM_CONSTANT(DEVICE_TYPE_MAX); + + BIND_ENUM_CONSTANT(DRIVER_RESOURCE_LOGICAL_DEVICE); + BIND_ENUM_CONSTANT(DRIVER_RESOURCE_PHYSICAL_DEVICE); + BIND_ENUM_CONSTANT(DRIVER_RESOURCE_TOPMOST_OBJECT); + BIND_ENUM_CONSTANT(DRIVER_RESOURCE_COMMAND_QUEUE); + BIND_ENUM_CONSTANT(DRIVER_RESOURCE_QUEUE_FAMILY); + BIND_ENUM_CONSTANT(DRIVER_RESOURCE_TEXTURE); + BIND_ENUM_CONSTANT(DRIVER_RESOURCE_TEXTURE_VIEW); + BIND_ENUM_CONSTANT(DRIVER_RESOURCE_TEXTURE_DATA_FORMAT); + BIND_ENUM_CONSTANT(DRIVER_RESOURCE_SAMPLER); + BIND_ENUM_CONSTANT(DRIVER_RESOURCE_UNIFORM_SET); + BIND_ENUM_CONSTANT(DRIVER_RESOURCE_BUFFER); + BIND_ENUM_CONSTANT(DRIVER_RESOURCE_COMPUTE_PIPELINE); + BIND_ENUM_CONSTANT(DRIVER_RESOURCE_RENDER_PIPELINE); +#ifndef DISABLE_DEPRECATED + BIND_ENUM_CONSTANT(DRIVER_RESOURCE_VULKAN_DEVICE); + BIND_ENUM_CONSTANT(DRIVER_RESOURCE_VULKAN_PHYSICAL_DEVICE); + BIND_ENUM_CONSTANT(DRIVER_RESOURCE_VULKAN_INSTANCE); + BIND_ENUM_CONSTANT(DRIVER_RESOURCE_VULKAN_QUEUE); + BIND_ENUM_CONSTANT(DRIVER_RESOURCE_VULKAN_QUEUE_FAMILY_INDEX); + BIND_ENUM_CONSTANT(DRIVER_RESOURCE_VULKAN_IMAGE); + BIND_ENUM_CONSTANT(DRIVER_RESOURCE_VULKAN_IMAGE_VIEW); + BIND_ENUM_CONSTANT(DRIVER_RESOURCE_VULKAN_IMAGE_NATIVE_TEXTURE_FORMAT); + BIND_ENUM_CONSTANT(DRIVER_RESOURCE_VULKAN_SAMPLER); + BIND_ENUM_CONSTANT(DRIVER_RESOURCE_VULKAN_DESCRIPTOR_SET); + BIND_ENUM_CONSTANT(DRIVER_RESOURCE_VULKAN_BUFFER); + BIND_ENUM_CONSTANT(DRIVER_RESOURCE_VULKAN_COMPUTE_PIPELINE); + BIND_ENUM_CONSTANT(DRIVER_RESOURCE_VULKAN_RENDER_PIPELINE); +#endif -RenderingDeviceVulkan::~RenderingDeviceVulkan() { + BIND_ENUM_CONSTANT(DATA_FORMAT_R4G4_UNORM_PACK8); + BIND_ENUM_CONSTANT(DATA_FORMAT_R4G4B4A4_UNORM_PACK16); + BIND_ENUM_CONSTANT(DATA_FORMAT_B4G4R4A4_UNORM_PACK16); + BIND_ENUM_CONSTANT(DATA_FORMAT_R5G6B5_UNORM_PACK16); + BIND_ENUM_CONSTANT(DATA_FORMAT_B5G6R5_UNORM_PACK16); + BIND_ENUM_CONSTANT(DATA_FORMAT_R5G5B5A1_UNORM_PACK16); + BIND_ENUM_CONSTANT(DATA_FORMAT_B5G5R5A1_UNORM_PACK16); + BIND_ENUM_CONSTANT(DATA_FORMAT_A1R5G5B5_UNORM_PACK16); + BIND_ENUM_CONSTANT(DATA_FORMAT_R8_UNORM); + BIND_ENUM_CONSTANT(DATA_FORMAT_R8_SNORM); + BIND_ENUM_CONSTANT(DATA_FORMAT_R8_USCALED); + BIND_ENUM_CONSTANT(DATA_FORMAT_R8_SSCALED); + BIND_ENUM_CONSTANT(DATA_FORMAT_R8_UINT); + BIND_ENUM_CONSTANT(DATA_FORMAT_R8_SINT); + BIND_ENUM_CONSTANT(DATA_FORMAT_R8_SRGB); + BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8_UNORM); + BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8_SNORM); + BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8_USCALED); + BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8_SSCALED); + BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8_UINT); + BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8_SINT); + BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8_SRGB); + BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8B8_UNORM); + BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8B8_SNORM); + BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8B8_USCALED); + BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8B8_SSCALED); + BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8B8_UINT); + BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8B8_SINT); + BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8B8_SRGB); + BIND_ENUM_CONSTANT(DATA_FORMAT_B8G8R8_UNORM); + BIND_ENUM_CONSTANT(DATA_FORMAT_B8G8R8_SNORM); + BIND_ENUM_CONSTANT(DATA_FORMAT_B8G8R8_USCALED); + BIND_ENUM_CONSTANT(DATA_FORMAT_B8G8R8_SSCALED); + BIND_ENUM_CONSTANT(DATA_FORMAT_B8G8R8_UINT); + BIND_ENUM_CONSTANT(DATA_FORMAT_B8G8R8_SINT); + BIND_ENUM_CONSTANT(DATA_FORMAT_B8G8R8_SRGB); + BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8B8A8_UNORM); + BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8B8A8_SNORM); + BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8B8A8_USCALED); + BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8B8A8_SSCALED); + BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8B8A8_UINT); + BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8B8A8_SINT); + BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8B8A8_SRGB); + BIND_ENUM_CONSTANT(DATA_FORMAT_B8G8R8A8_UNORM); + BIND_ENUM_CONSTANT(DATA_FORMAT_B8G8R8A8_SNORM); + BIND_ENUM_CONSTANT(DATA_FORMAT_B8G8R8A8_USCALED); + BIND_ENUM_CONSTANT(DATA_FORMAT_B8G8R8A8_SSCALED); + BIND_ENUM_CONSTANT(DATA_FORMAT_B8G8R8A8_UINT); + BIND_ENUM_CONSTANT(DATA_FORMAT_B8G8R8A8_SINT); + BIND_ENUM_CONSTANT(DATA_FORMAT_B8G8R8A8_SRGB); + BIND_ENUM_CONSTANT(DATA_FORMAT_A8B8G8R8_UNORM_PACK32); + BIND_ENUM_CONSTANT(DATA_FORMAT_A8B8G8R8_SNORM_PACK32); + BIND_ENUM_CONSTANT(DATA_FORMAT_A8B8G8R8_USCALED_PACK32); + BIND_ENUM_CONSTANT(DATA_FORMAT_A8B8G8R8_SSCALED_PACK32); + BIND_ENUM_CONSTANT(DATA_FORMAT_A8B8G8R8_UINT_PACK32); + BIND_ENUM_CONSTANT(DATA_FORMAT_A8B8G8R8_SINT_PACK32); + BIND_ENUM_CONSTANT(DATA_FORMAT_A8B8G8R8_SRGB_PACK32); + BIND_ENUM_CONSTANT(DATA_FORMAT_A2R10G10B10_UNORM_PACK32); + BIND_ENUM_CONSTANT(DATA_FORMAT_A2R10G10B10_SNORM_PACK32); + BIND_ENUM_CONSTANT(DATA_FORMAT_A2R10G10B10_USCALED_PACK32); + BIND_ENUM_CONSTANT(DATA_FORMAT_A2R10G10B10_SSCALED_PACK32); + BIND_ENUM_CONSTANT(DATA_FORMAT_A2R10G10B10_UINT_PACK32); + BIND_ENUM_CONSTANT(DATA_FORMAT_A2R10G10B10_SINT_PACK32); + BIND_ENUM_CONSTANT(DATA_FORMAT_A2B10G10R10_UNORM_PACK32); + BIND_ENUM_CONSTANT(DATA_FORMAT_A2B10G10R10_SNORM_PACK32); + BIND_ENUM_CONSTANT(DATA_FORMAT_A2B10G10R10_USCALED_PACK32); + BIND_ENUM_CONSTANT(DATA_FORMAT_A2B10G10R10_SSCALED_PACK32); + BIND_ENUM_CONSTANT(DATA_FORMAT_A2B10G10R10_UINT_PACK32); + BIND_ENUM_CONSTANT(DATA_FORMAT_A2B10G10R10_SINT_PACK32); + BIND_ENUM_CONSTANT(DATA_FORMAT_R16_UNORM); + BIND_ENUM_CONSTANT(DATA_FORMAT_R16_SNORM); + BIND_ENUM_CONSTANT(DATA_FORMAT_R16_USCALED); + BIND_ENUM_CONSTANT(DATA_FORMAT_R16_SSCALED); + BIND_ENUM_CONSTANT(DATA_FORMAT_R16_UINT); + BIND_ENUM_CONSTANT(DATA_FORMAT_R16_SINT); + BIND_ENUM_CONSTANT(DATA_FORMAT_R16_SFLOAT); + BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16_UNORM); + BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16_SNORM); + BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16_USCALED); + BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16_SSCALED); + BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16_UINT); + BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16_SINT); + BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16_SFLOAT); + BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16B16_UNORM); + BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16B16_SNORM); + BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16B16_USCALED); + BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16B16_SSCALED); + BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16B16_UINT); + BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16B16_SINT); + BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16B16_SFLOAT); + BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16B16A16_UNORM); + BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16B16A16_SNORM); + BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16B16A16_USCALED); + BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16B16A16_SSCALED); + BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16B16A16_UINT); + BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16B16A16_SINT); + BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16B16A16_SFLOAT); + BIND_ENUM_CONSTANT(DATA_FORMAT_R32_UINT); + BIND_ENUM_CONSTANT(DATA_FORMAT_R32_SINT); + BIND_ENUM_CONSTANT(DATA_FORMAT_R32_SFLOAT); + BIND_ENUM_CONSTANT(DATA_FORMAT_R32G32_UINT); + BIND_ENUM_CONSTANT(DATA_FORMAT_R32G32_SINT); + BIND_ENUM_CONSTANT(DATA_FORMAT_R32G32_SFLOAT); + BIND_ENUM_CONSTANT(DATA_FORMAT_R32G32B32_UINT); + BIND_ENUM_CONSTANT(DATA_FORMAT_R32G32B32_SINT); + BIND_ENUM_CONSTANT(DATA_FORMAT_R32G32B32_SFLOAT); + BIND_ENUM_CONSTANT(DATA_FORMAT_R32G32B32A32_UINT); + BIND_ENUM_CONSTANT(DATA_FORMAT_R32G32B32A32_SINT); + BIND_ENUM_CONSTANT(DATA_FORMAT_R32G32B32A32_SFLOAT); + BIND_ENUM_CONSTANT(DATA_FORMAT_R64_UINT); + BIND_ENUM_CONSTANT(DATA_FORMAT_R64_SINT); + BIND_ENUM_CONSTANT(DATA_FORMAT_R64_SFLOAT); + BIND_ENUM_CONSTANT(DATA_FORMAT_R64G64_UINT); + BIND_ENUM_CONSTANT(DATA_FORMAT_R64G64_SINT); + BIND_ENUM_CONSTANT(DATA_FORMAT_R64G64_SFLOAT); + BIND_ENUM_CONSTANT(DATA_FORMAT_R64G64B64_UINT); + BIND_ENUM_CONSTANT(DATA_FORMAT_R64G64B64_SINT); + BIND_ENUM_CONSTANT(DATA_FORMAT_R64G64B64_SFLOAT); + BIND_ENUM_CONSTANT(DATA_FORMAT_R64G64B64A64_UINT); + BIND_ENUM_CONSTANT(DATA_FORMAT_R64G64B64A64_SINT); + BIND_ENUM_CONSTANT(DATA_FORMAT_R64G64B64A64_SFLOAT); + BIND_ENUM_CONSTANT(DATA_FORMAT_B10G11R11_UFLOAT_PACK32); + BIND_ENUM_CONSTANT(DATA_FORMAT_E5B9G9R9_UFLOAT_PACK32); + BIND_ENUM_CONSTANT(DATA_FORMAT_D16_UNORM); + BIND_ENUM_CONSTANT(DATA_FORMAT_X8_D24_UNORM_PACK32); + BIND_ENUM_CONSTANT(DATA_FORMAT_D32_SFLOAT); + BIND_ENUM_CONSTANT(DATA_FORMAT_S8_UINT); + BIND_ENUM_CONSTANT(DATA_FORMAT_D16_UNORM_S8_UINT); + BIND_ENUM_CONSTANT(DATA_FORMAT_D24_UNORM_S8_UINT); + BIND_ENUM_CONSTANT(DATA_FORMAT_D32_SFLOAT_S8_UINT); + BIND_ENUM_CONSTANT(DATA_FORMAT_BC1_RGB_UNORM_BLOCK); + BIND_ENUM_CONSTANT(DATA_FORMAT_BC1_RGB_SRGB_BLOCK); + BIND_ENUM_CONSTANT(DATA_FORMAT_BC1_RGBA_UNORM_BLOCK); + BIND_ENUM_CONSTANT(DATA_FORMAT_BC1_RGBA_SRGB_BLOCK); + BIND_ENUM_CONSTANT(DATA_FORMAT_BC2_UNORM_BLOCK); + BIND_ENUM_CONSTANT(DATA_FORMAT_BC2_SRGB_BLOCK); + BIND_ENUM_CONSTANT(DATA_FORMAT_BC3_UNORM_BLOCK); + BIND_ENUM_CONSTANT(DATA_FORMAT_BC3_SRGB_BLOCK); + BIND_ENUM_CONSTANT(DATA_FORMAT_BC4_UNORM_BLOCK); + BIND_ENUM_CONSTANT(DATA_FORMAT_BC4_SNORM_BLOCK); + BIND_ENUM_CONSTANT(DATA_FORMAT_BC5_UNORM_BLOCK); + BIND_ENUM_CONSTANT(DATA_FORMAT_BC5_SNORM_BLOCK); + BIND_ENUM_CONSTANT(DATA_FORMAT_BC6H_UFLOAT_BLOCK); + BIND_ENUM_CONSTANT(DATA_FORMAT_BC6H_SFLOAT_BLOCK); + BIND_ENUM_CONSTANT(DATA_FORMAT_BC7_UNORM_BLOCK); + BIND_ENUM_CONSTANT(DATA_FORMAT_BC7_SRGB_BLOCK); + BIND_ENUM_CONSTANT(DATA_FORMAT_ETC2_R8G8B8_UNORM_BLOCK); + BIND_ENUM_CONSTANT(DATA_FORMAT_ETC2_R8G8B8_SRGB_BLOCK); + BIND_ENUM_CONSTANT(DATA_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK); + BIND_ENUM_CONSTANT(DATA_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK); + BIND_ENUM_CONSTANT(DATA_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK); + BIND_ENUM_CONSTANT(DATA_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK); + BIND_ENUM_CONSTANT(DATA_FORMAT_EAC_R11_UNORM_BLOCK); + BIND_ENUM_CONSTANT(DATA_FORMAT_EAC_R11_SNORM_BLOCK); + BIND_ENUM_CONSTANT(DATA_FORMAT_EAC_R11G11_UNORM_BLOCK); + BIND_ENUM_CONSTANT(DATA_FORMAT_EAC_R11G11_SNORM_BLOCK); + BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_4x4_UNORM_BLOCK); + BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_4x4_SRGB_BLOCK); + BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_5x4_UNORM_BLOCK); + BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_5x4_SRGB_BLOCK); + BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_5x5_UNORM_BLOCK); + BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_5x5_SRGB_BLOCK); + BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_6x5_UNORM_BLOCK); + BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_6x5_SRGB_BLOCK); + BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_6x6_UNORM_BLOCK); + BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_6x6_SRGB_BLOCK); + BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_8x5_UNORM_BLOCK); + BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_8x5_SRGB_BLOCK); + BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_8x6_UNORM_BLOCK); + BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_8x6_SRGB_BLOCK); + BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_8x8_UNORM_BLOCK); + BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_8x8_SRGB_BLOCK); + BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_10x5_UNORM_BLOCK); + BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_10x5_SRGB_BLOCK); + BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_10x6_UNORM_BLOCK); + BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_10x6_SRGB_BLOCK); + BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_10x8_UNORM_BLOCK); + BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_10x8_SRGB_BLOCK); + BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_10x10_UNORM_BLOCK); + BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_10x10_SRGB_BLOCK); + BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_12x10_UNORM_BLOCK); + BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_12x10_SRGB_BLOCK); + BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_12x12_UNORM_BLOCK); + BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_12x12_SRGB_BLOCK); + BIND_ENUM_CONSTANT(DATA_FORMAT_G8B8G8R8_422_UNORM); + BIND_ENUM_CONSTANT(DATA_FORMAT_B8G8R8G8_422_UNORM); + BIND_ENUM_CONSTANT(DATA_FORMAT_G8_B8_R8_3PLANE_420_UNORM); + BIND_ENUM_CONSTANT(DATA_FORMAT_G8_B8R8_2PLANE_420_UNORM); + BIND_ENUM_CONSTANT(DATA_FORMAT_G8_B8_R8_3PLANE_422_UNORM); + BIND_ENUM_CONSTANT(DATA_FORMAT_G8_B8R8_2PLANE_422_UNORM); + BIND_ENUM_CONSTANT(DATA_FORMAT_G8_B8_R8_3PLANE_444_UNORM); + BIND_ENUM_CONSTANT(DATA_FORMAT_R10X6_UNORM_PACK16); + BIND_ENUM_CONSTANT(DATA_FORMAT_R10X6G10X6_UNORM_2PACK16); + BIND_ENUM_CONSTANT(DATA_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16); + BIND_ENUM_CONSTANT(DATA_FORMAT_G10X6B10X6G10X6R10X6_422_UNORM_4PACK16); + BIND_ENUM_CONSTANT(DATA_FORMAT_B10X6G10X6R10X6G10X6_422_UNORM_4PACK16); + BIND_ENUM_CONSTANT(DATA_FORMAT_G10X6_B10X6_R10X6_3PLANE_420_UNORM_3PACK16); + BIND_ENUM_CONSTANT(DATA_FORMAT_G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16); + BIND_ENUM_CONSTANT(DATA_FORMAT_G10X6_B10X6_R10X6_3PLANE_422_UNORM_3PACK16); + BIND_ENUM_CONSTANT(DATA_FORMAT_G10X6_B10X6R10X6_2PLANE_422_UNORM_3PACK16); + BIND_ENUM_CONSTANT(DATA_FORMAT_G10X6_B10X6_R10X6_3PLANE_444_UNORM_3PACK16); + BIND_ENUM_CONSTANT(DATA_FORMAT_R12X4_UNORM_PACK16); + BIND_ENUM_CONSTANT(DATA_FORMAT_R12X4G12X4_UNORM_2PACK16); + BIND_ENUM_CONSTANT(DATA_FORMAT_R12X4G12X4B12X4A12X4_UNORM_4PACK16); + BIND_ENUM_CONSTANT(DATA_FORMAT_G12X4B12X4G12X4R12X4_422_UNORM_4PACK16); + BIND_ENUM_CONSTANT(DATA_FORMAT_B12X4G12X4R12X4G12X4_422_UNORM_4PACK16); + BIND_ENUM_CONSTANT(DATA_FORMAT_G12X4_B12X4_R12X4_3PLANE_420_UNORM_3PACK16); + BIND_ENUM_CONSTANT(DATA_FORMAT_G12X4_B12X4R12X4_2PLANE_420_UNORM_3PACK16); + BIND_ENUM_CONSTANT(DATA_FORMAT_G12X4_B12X4_R12X4_3PLANE_422_UNORM_3PACK16); + BIND_ENUM_CONSTANT(DATA_FORMAT_G12X4_B12X4R12X4_2PLANE_422_UNORM_3PACK16); + BIND_ENUM_CONSTANT(DATA_FORMAT_G12X4_B12X4_R12X4_3PLANE_444_UNORM_3PACK16); + BIND_ENUM_CONSTANT(DATA_FORMAT_G16B16G16R16_422_UNORM); + BIND_ENUM_CONSTANT(DATA_FORMAT_B16G16R16G16_422_UNORM); + BIND_ENUM_CONSTANT(DATA_FORMAT_G16_B16_R16_3PLANE_420_UNORM); + BIND_ENUM_CONSTANT(DATA_FORMAT_G16_B16R16_2PLANE_420_UNORM); + BIND_ENUM_CONSTANT(DATA_FORMAT_G16_B16_R16_3PLANE_422_UNORM); + BIND_ENUM_CONSTANT(DATA_FORMAT_G16_B16R16_2PLANE_422_UNORM); + BIND_ENUM_CONSTANT(DATA_FORMAT_G16_B16_R16_3PLANE_444_UNORM); + BIND_ENUM_CONSTANT(DATA_FORMAT_MAX); + + BIND_BITFIELD_FLAG(BARRIER_MASK_VERTEX); + BIND_BITFIELD_FLAG(BARRIER_MASK_FRAGMENT); + BIND_BITFIELD_FLAG(BARRIER_MASK_COMPUTE); + BIND_BITFIELD_FLAG(BARRIER_MASK_TRANSFER); + BIND_BITFIELD_FLAG(BARRIER_MASK_RASTER); + BIND_BITFIELD_FLAG(BARRIER_MASK_ALL_BARRIERS); + BIND_BITFIELD_FLAG(BARRIER_MASK_NO_BARRIER); + + BIND_ENUM_CONSTANT(TEXTURE_TYPE_1D); + BIND_ENUM_CONSTANT(TEXTURE_TYPE_2D); + BIND_ENUM_CONSTANT(TEXTURE_TYPE_3D); + BIND_ENUM_CONSTANT(TEXTURE_TYPE_CUBE); + BIND_ENUM_CONSTANT(TEXTURE_TYPE_1D_ARRAY); + BIND_ENUM_CONSTANT(TEXTURE_TYPE_2D_ARRAY); + BIND_ENUM_CONSTANT(TEXTURE_TYPE_CUBE_ARRAY); + BIND_ENUM_CONSTANT(TEXTURE_TYPE_MAX); + + BIND_ENUM_CONSTANT(TEXTURE_SAMPLES_1); + BIND_ENUM_CONSTANT(TEXTURE_SAMPLES_2); + BIND_ENUM_CONSTANT(TEXTURE_SAMPLES_4); + BIND_ENUM_CONSTANT(TEXTURE_SAMPLES_8); + BIND_ENUM_CONSTANT(TEXTURE_SAMPLES_16); + BIND_ENUM_CONSTANT(TEXTURE_SAMPLES_32); + BIND_ENUM_CONSTANT(TEXTURE_SAMPLES_64); + BIND_ENUM_CONSTANT(TEXTURE_SAMPLES_MAX); + + BIND_BITFIELD_FLAG(TEXTURE_USAGE_SAMPLING_BIT); + BIND_BITFIELD_FLAG(TEXTURE_USAGE_COLOR_ATTACHMENT_BIT); + BIND_BITFIELD_FLAG(TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT); + BIND_BITFIELD_FLAG(TEXTURE_USAGE_STORAGE_BIT); + BIND_BITFIELD_FLAG(TEXTURE_USAGE_STORAGE_ATOMIC_BIT); + BIND_BITFIELD_FLAG(TEXTURE_USAGE_CPU_READ_BIT); + BIND_BITFIELD_FLAG(TEXTURE_USAGE_CAN_UPDATE_BIT); + BIND_BITFIELD_FLAG(TEXTURE_USAGE_CAN_COPY_FROM_BIT); + BIND_BITFIELD_FLAG(TEXTURE_USAGE_CAN_COPY_TO_BIT); + BIND_BITFIELD_FLAG(TEXTURE_USAGE_INPUT_ATTACHMENT_BIT); + + BIND_ENUM_CONSTANT(TEXTURE_SWIZZLE_IDENTITY); + BIND_ENUM_CONSTANT(TEXTURE_SWIZZLE_ZERO); + BIND_ENUM_CONSTANT(TEXTURE_SWIZZLE_ONE); + BIND_ENUM_CONSTANT(TEXTURE_SWIZZLE_R); + BIND_ENUM_CONSTANT(TEXTURE_SWIZZLE_G); + BIND_ENUM_CONSTANT(TEXTURE_SWIZZLE_B); + BIND_ENUM_CONSTANT(TEXTURE_SWIZZLE_A); + BIND_ENUM_CONSTANT(TEXTURE_SWIZZLE_MAX); + + BIND_ENUM_CONSTANT(TEXTURE_SLICE_2D); + BIND_ENUM_CONSTANT(TEXTURE_SLICE_CUBEMAP); + BIND_ENUM_CONSTANT(TEXTURE_SLICE_3D); + + BIND_ENUM_CONSTANT(SAMPLER_FILTER_NEAREST); + BIND_ENUM_CONSTANT(SAMPLER_FILTER_LINEAR); + BIND_ENUM_CONSTANT(SAMPLER_REPEAT_MODE_REPEAT); + BIND_ENUM_CONSTANT(SAMPLER_REPEAT_MODE_MIRRORED_REPEAT); + BIND_ENUM_CONSTANT(SAMPLER_REPEAT_MODE_CLAMP_TO_EDGE); + BIND_ENUM_CONSTANT(SAMPLER_REPEAT_MODE_CLAMP_TO_BORDER); + BIND_ENUM_CONSTANT(SAMPLER_REPEAT_MODE_MIRROR_CLAMP_TO_EDGE); + BIND_ENUM_CONSTANT(SAMPLER_REPEAT_MODE_MAX); + + BIND_ENUM_CONSTANT(SAMPLER_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK); + BIND_ENUM_CONSTANT(SAMPLER_BORDER_COLOR_INT_TRANSPARENT_BLACK); + BIND_ENUM_CONSTANT(SAMPLER_BORDER_COLOR_FLOAT_OPAQUE_BLACK); + BIND_ENUM_CONSTANT(SAMPLER_BORDER_COLOR_INT_OPAQUE_BLACK); + BIND_ENUM_CONSTANT(SAMPLER_BORDER_COLOR_FLOAT_OPAQUE_WHITE); + BIND_ENUM_CONSTANT(SAMPLER_BORDER_COLOR_INT_OPAQUE_WHITE); + BIND_ENUM_CONSTANT(SAMPLER_BORDER_COLOR_MAX); + + BIND_ENUM_CONSTANT(VERTEX_FREQUENCY_VERTEX); + BIND_ENUM_CONSTANT(VERTEX_FREQUENCY_INSTANCE); + + BIND_ENUM_CONSTANT(INDEX_BUFFER_FORMAT_UINT16); + BIND_ENUM_CONSTANT(INDEX_BUFFER_FORMAT_UINT32); + + BIND_BITFIELD_FLAG(STORAGE_BUFFER_USAGE_DISPATCH_INDIRECT); + + BIND_ENUM_CONSTANT(UNIFORM_TYPE_SAMPLER); //for sampling only (sampler GLSL type) + BIND_ENUM_CONSTANT(UNIFORM_TYPE_SAMPLER_WITH_TEXTURE); // for sampling only); but includes a texture); (samplerXX GLSL type)); first a sampler then a texture + BIND_ENUM_CONSTANT(UNIFORM_TYPE_TEXTURE); //only texture); (textureXX GLSL type) + BIND_ENUM_CONSTANT(UNIFORM_TYPE_IMAGE); // storage image (imageXX GLSL type)); for compute mostly + BIND_ENUM_CONSTANT(UNIFORM_TYPE_TEXTURE_BUFFER); // buffer texture (or TBO); textureBuffer type) + BIND_ENUM_CONSTANT(UNIFORM_TYPE_SAMPLER_WITH_TEXTURE_BUFFER); // buffer texture with a sampler(or TBO); samplerBuffer type) + BIND_ENUM_CONSTANT(UNIFORM_TYPE_IMAGE_BUFFER); //texel buffer); (imageBuffer type)); for compute mostly + BIND_ENUM_CONSTANT(UNIFORM_TYPE_UNIFORM_BUFFER); //regular uniform buffer (or UBO). + BIND_ENUM_CONSTANT(UNIFORM_TYPE_STORAGE_BUFFER); //storage buffer ("buffer" qualifier) like UBO); but supports storage); for compute mostly + BIND_ENUM_CONSTANT(UNIFORM_TYPE_INPUT_ATTACHMENT); //used for sub-pass read/write); for mobile mostly + BIND_ENUM_CONSTANT(UNIFORM_TYPE_MAX); + + BIND_ENUM_CONSTANT(RENDER_PRIMITIVE_POINTS); + BIND_ENUM_CONSTANT(RENDER_PRIMITIVE_LINES); + BIND_ENUM_CONSTANT(RENDER_PRIMITIVE_LINES_WITH_ADJACENCY); + BIND_ENUM_CONSTANT(RENDER_PRIMITIVE_LINESTRIPS); + BIND_ENUM_CONSTANT(RENDER_PRIMITIVE_LINESTRIPS_WITH_ADJACENCY); + BIND_ENUM_CONSTANT(RENDER_PRIMITIVE_TRIANGLES); + BIND_ENUM_CONSTANT(RENDER_PRIMITIVE_TRIANGLES_WITH_ADJACENCY); + BIND_ENUM_CONSTANT(RENDER_PRIMITIVE_TRIANGLE_STRIPS); + BIND_ENUM_CONSTANT(RENDER_PRIMITIVE_TRIANGLE_STRIPS_WITH_AJACENCY); + BIND_ENUM_CONSTANT(RENDER_PRIMITIVE_TRIANGLE_STRIPS_WITH_RESTART_INDEX); + BIND_ENUM_CONSTANT(RENDER_PRIMITIVE_TESSELATION_PATCH); + BIND_ENUM_CONSTANT(RENDER_PRIMITIVE_MAX); + + BIND_ENUM_CONSTANT(POLYGON_CULL_DISABLED); + BIND_ENUM_CONSTANT(POLYGON_CULL_FRONT); + BIND_ENUM_CONSTANT(POLYGON_CULL_BACK); + + BIND_ENUM_CONSTANT(POLYGON_FRONT_FACE_CLOCKWISE); + BIND_ENUM_CONSTANT(POLYGON_FRONT_FACE_COUNTER_CLOCKWISE); + + BIND_ENUM_CONSTANT(STENCIL_OP_KEEP); + BIND_ENUM_CONSTANT(STENCIL_OP_ZERO); + BIND_ENUM_CONSTANT(STENCIL_OP_REPLACE); + BIND_ENUM_CONSTANT(STENCIL_OP_INCREMENT_AND_CLAMP); + BIND_ENUM_CONSTANT(STENCIL_OP_DECREMENT_AND_CLAMP); + BIND_ENUM_CONSTANT(STENCIL_OP_INVERT); + BIND_ENUM_CONSTANT(STENCIL_OP_INCREMENT_AND_WRAP); + BIND_ENUM_CONSTANT(STENCIL_OP_DECREMENT_AND_WRAP); + BIND_ENUM_CONSTANT(STENCIL_OP_MAX); //not an actual operator); just the amount of operators :D + + BIND_ENUM_CONSTANT(COMPARE_OP_NEVER); + BIND_ENUM_CONSTANT(COMPARE_OP_LESS); + BIND_ENUM_CONSTANT(COMPARE_OP_EQUAL); + BIND_ENUM_CONSTANT(COMPARE_OP_LESS_OR_EQUAL); + BIND_ENUM_CONSTANT(COMPARE_OP_GREATER); + BIND_ENUM_CONSTANT(COMPARE_OP_NOT_EQUAL); + BIND_ENUM_CONSTANT(COMPARE_OP_GREATER_OR_EQUAL); + BIND_ENUM_CONSTANT(COMPARE_OP_ALWAYS); + BIND_ENUM_CONSTANT(COMPARE_OP_MAX); + + BIND_ENUM_CONSTANT(LOGIC_OP_CLEAR); + BIND_ENUM_CONSTANT(LOGIC_OP_AND); + BIND_ENUM_CONSTANT(LOGIC_OP_AND_REVERSE); + BIND_ENUM_CONSTANT(LOGIC_OP_COPY); + BIND_ENUM_CONSTANT(LOGIC_OP_AND_INVERTED); + BIND_ENUM_CONSTANT(LOGIC_OP_NO_OP); + BIND_ENUM_CONSTANT(LOGIC_OP_XOR); + BIND_ENUM_CONSTANT(LOGIC_OP_OR); + BIND_ENUM_CONSTANT(LOGIC_OP_NOR); + BIND_ENUM_CONSTANT(LOGIC_OP_EQUIVALENT); + BIND_ENUM_CONSTANT(LOGIC_OP_INVERT); + BIND_ENUM_CONSTANT(LOGIC_OP_OR_REVERSE); + BIND_ENUM_CONSTANT(LOGIC_OP_COPY_INVERTED); + BIND_ENUM_CONSTANT(LOGIC_OP_OR_INVERTED); + BIND_ENUM_CONSTANT(LOGIC_OP_NAND); + BIND_ENUM_CONSTANT(LOGIC_OP_SET); + BIND_ENUM_CONSTANT(LOGIC_OP_MAX); //not an actual operator); just the amount of operators :D + + BIND_ENUM_CONSTANT(BLEND_FACTOR_ZERO); + BIND_ENUM_CONSTANT(BLEND_FACTOR_ONE); + BIND_ENUM_CONSTANT(BLEND_FACTOR_SRC_COLOR); + BIND_ENUM_CONSTANT(BLEND_FACTOR_ONE_MINUS_SRC_COLOR); + BIND_ENUM_CONSTANT(BLEND_FACTOR_DST_COLOR); + BIND_ENUM_CONSTANT(BLEND_FACTOR_ONE_MINUS_DST_COLOR); + BIND_ENUM_CONSTANT(BLEND_FACTOR_SRC_ALPHA); + BIND_ENUM_CONSTANT(BLEND_FACTOR_ONE_MINUS_SRC_ALPHA); + BIND_ENUM_CONSTANT(BLEND_FACTOR_DST_ALPHA); + BIND_ENUM_CONSTANT(BLEND_FACTOR_ONE_MINUS_DST_ALPHA); + BIND_ENUM_CONSTANT(BLEND_FACTOR_CONSTANT_COLOR); + BIND_ENUM_CONSTANT(BLEND_FACTOR_ONE_MINUS_CONSTANT_COLOR); + BIND_ENUM_CONSTANT(BLEND_FACTOR_CONSTANT_ALPHA); + BIND_ENUM_CONSTANT(BLEND_FACTOR_ONE_MINUS_CONSTANT_ALPHA); + BIND_ENUM_CONSTANT(BLEND_FACTOR_SRC_ALPHA_SATURATE); + BIND_ENUM_CONSTANT(BLEND_FACTOR_SRC1_COLOR); + BIND_ENUM_CONSTANT(BLEND_FACTOR_ONE_MINUS_SRC1_COLOR); + BIND_ENUM_CONSTANT(BLEND_FACTOR_SRC1_ALPHA); + BIND_ENUM_CONSTANT(BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA); + BIND_ENUM_CONSTANT(BLEND_FACTOR_MAX); + + BIND_ENUM_CONSTANT(BLEND_OP_ADD); + BIND_ENUM_CONSTANT(BLEND_OP_SUBTRACT); + BIND_ENUM_CONSTANT(BLEND_OP_REVERSE_SUBTRACT); + BIND_ENUM_CONSTANT(BLEND_OP_MINIMUM); + BIND_ENUM_CONSTANT(BLEND_OP_MAXIMUM); + BIND_ENUM_CONSTANT(BLEND_OP_MAX); + + BIND_BITFIELD_FLAG(DYNAMIC_STATE_LINE_WIDTH); + BIND_BITFIELD_FLAG(DYNAMIC_STATE_DEPTH_BIAS); + BIND_BITFIELD_FLAG(DYNAMIC_STATE_BLEND_CONSTANTS); + BIND_BITFIELD_FLAG(DYNAMIC_STATE_DEPTH_BOUNDS); + BIND_BITFIELD_FLAG(DYNAMIC_STATE_STENCIL_COMPARE_MASK); + BIND_BITFIELD_FLAG(DYNAMIC_STATE_STENCIL_WRITE_MASK); + BIND_BITFIELD_FLAG(DYNAMIC_STATE_STENCIL_REFERENCE); + + BIND_ENUM_CONSTANT(INITIAL_ACTION_CLEAR); //start rendering and clear the framebuffer (supply params) + BIND_ENUM_CONSTANT(INITIAL_ACTION_CLEAR_REGION); //start rendering and clear the framebuffer (supply params) + BIND_ENUM_CONSTANT(INITIAL_ACTION_CLEAR_REGION_CONTINUE); //continue rendering and clear the framebuffer (supply params) + BIND_ENUM_CONSTANT(INITIAL_ACTION_KEEP); //start rendering); but keep attached color texture contents (depth will be cleared) + BIND_ENUM_CONSTANT(INITIAL_ACTION_DROP); //start rendering); ignore what is there); just write above it + BIND_ENUM_CONSTANT(INITIAL_ACTION_CONTINUE); //continue rendering (framebuffer must have been left in "continue" state as final action previously) + BIND_ENUM_CONSTANT(INITIAL_ACTION_MAX); + + BIND_ENUM_CONSTANT(FINAL_ACTION_READ); //will no longer render to it); allows attached textures to be read again); but depth buffer contents will be dropped (Can't be read from) + BIND_ENUM_CONSTANT(FINAL_ACTION_DISCARD); // discard contents after rendering + BIND_ENUM_CONSTANT(FINAL_ACTION_CONTINUE); //will continue rendering later); attached textures can't be read until re-bound with "finish" + BIND_ENUM_CONSTANT(FINAL_ACTION_MAX); + + BIND_ENUM_CONSTANT(SHADER_STAGE_VERTEX); + BIND_ENUM_CONSTANT(SHADER_STAGE_FRAGMENT); + BIND_ENUM_CONSTANT(SHADER_STAGE_TESSELATION_CONTROL); + BIND_ENUM_CONSTANT(SHADER_STAGE_TESSELATION_EVALUATION); + BIND_ENUM_CONSTANT(SHADER_STAGE_COMPUTE); + BIND_ENUM_CONSTANT(SHADER_STAGE_MAX); + BIND_ENUM_CONSTANT(SHADER_STAGE_VERTEX_BIT); + BIND_ENUM_CONSTANT(SHADER_STAGE_FRAGMENT_BIT); + BIND_ENUM_CONSTANT(SHADER_STAGE_TESSELATION_CONTROL_BIT); + BIND_ENUM_CONSTANT(SHADER_STAGE_TESSELATION_EVALUATION_BIT); + BIND_ENUM_CONSTANT(SHADER_STAGE_COMPUTE_BIT); + + BIND_ENUM_CONSTANT(SHADER_LANGUAGE_GLSL); + BIND_ENUM_CONSTANT(SHADER_LANGUAGE_HLSL); + + BIND_ENUM_CONSTANT(PIPELINE_SPECIALIZATION_CONSTANT_TYPE_BOOL); + BIND_ENUM_CONSTANT(PIPELINE_SPECIALIZATION_CONSTANT_TYPE_INT); + BIND_ENUM_CONSTANT(PIPELINE_SPECIALIZATION_CONSTANT_TYPE_FLOAT); + + BIND_ENUM_CONSTANT(LIMIT_MAX_BOUND_UNIFORM_SETS); + BIND_ENUM_CONSTANT(LIMIT_MAX_FRAMEBUFFER_COLOR_ATTACHMENTS); + BIND_ENUM_CONSTANT(LIMIT_MAX_TEXTURES_PER_UNIFORM_SET); + BIND_ENUM_CONSTANT(LIMIT_MAX_SAMPLERS_PER_UNIFORM_SET); + BIND_ENUM_CONSTANT(LIMIT_MAX_STORAGE_BUFFERS_PER_UNIFORM_SET); + BIND_ENUM_CONSTANT(LIMIT_MAX_STORAGE_IMAGES_PER_UNIFORM_SET); + BIND_ENUM_CONSTANT(LIMIT_MAX_UNIFORM_BUFFERS_PER_UNIFORM_SET); + BIND_ENUM_CONSTANT(LIMIT_MAX_DRAW_INDEXED_INDEX); + BIND_ENUM_CONSTANT(LIMIT_MAX_FRAMEBUFFER_HEIGHT); + BIND_ENUM_CONSTANT(LIMIT_MAX_FRAMEBUFFER_WIDTH); + BIND_ENUM_CONSTANT(LIMIT_MAX_TEXTURE_ARRAY_LAYERS); + BIND_ENUM_CONSTANT(LIMIT_MAX_TEXTURE_SIZE_1D); + BIND_ENUM_CONSTANT(LIMIT_MAX_TEXTURE_SIZE_2D); + BIND_ENUM_CONSTANT(LIMIT_MAX_TEXTURE_SIZE_3D); + BIND_ENUM_CONSTANT(LIMIT_MAX_TEXTURE_SIZE_CUBE); + BIND_ENUM_CONSTANT(LIMIT_MAX_TEXTURES_PER_SHADER_STAGE); + BIND_ENUM_CONSTANT(LIMIT_MAX_SAMPLERS_PER_SHADER_STAGE); + BIND_ENUM_CONSTANT(LIMIT_MAX_STORAGE_BUFFERS_PER_SHADER_STAGE); + BIND_ENUM_CONSTANT(LIMIT_MAX_STORAGE_IMAGES_PER_SHADER_STAGE); + BIND_ENUM_CONSTANT(LIMIT_MAX_UNIFORM_BUFFERS_PER_SHADER_STAGE); + BIND_ENUM_CONSTANT(LIMIT_MAX_PUSH_CONSTANT_SIZE); + BIND_ENUM_CONSTANT(LIMIT_MAX_UNIFORM_BUFFER_SIZE); + BIND_ENUM_CONSTANT(LIMIT_MAX_VERTEX_INPUT_ATTRIBUTE_OFFSET); + BIND_ENUM_CONSTANT(LIMIT_MAX_VERTEX_INPUT_ATTRIBUTES); + BIND_ENUM_CONSTANT(LIMIT_MAX_VERTEX_INPUT_BINDINGS); + BIND_ENUM_CONSTANT(LIMIT_MAX_VERTEX_INPUT_BINDING_STRIDE); + BIND_ENUM_CONSTANT(LIMIT_MIN_UNIFORM_BUFFER_OFFSET_ALIGNMENT); + BIND_ENUM_CONSTANT(LIMIT_MAX_COMPUTE_SHARED_MEMORY_SIZE); + BIND_ENUM_CONSTANT(LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_X); + BIND_ENUM_CONSTANT(LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_Y); + BIND_ENUM_CONSTANT(LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_Z); + BIND_ENUM_CONSTANT(LIMIT_MAX_COMPUTE_WORKGROUP_INVOCATIONS); + BIND_ENUM_CONSTANT(LIMIT_MAX_COMPUTE_WORKGROUP_SIZE_X); + BIND_ENUM_CONSTANT(LIMIT_MAX_COMPUTE_WORKGROUP_SIZE_Y); + BIND_ENUM_CONSTANT(LIMIT_MAX_COMPUTE_WORKGROUP_SIZE_Z); + BIND_ENUM_CONSTANT(LIMIT_MAX_VIEWPORT_DIMENSIONS_X); + BIND_ENUM_CONSTANT(LIMIT_MAX_VIEWPORT_DIMENSIONS_Y); + + BIND_ENUM_CONSTANT(MEMORY_TEXTURES); + BIND_ENUM_CONSTANT(MEMORY_BUFFERS); + BIND_ENUM_CONSTANT(MEMORY_TOTAL); + + BIND_CONSTANT(INVALID_ID); + BIND_CONSTANT(INVALID_FORMAT_ID); +} + +RenderingDevice::~RenderingDevice() { if (local_device.is_valid()) { finalize(); context->local_device_free(local_device); } + if (singleton == this) { + singleton = nullptr; + } +} + +RenderingDevice::RenderingDevice() { + if (singleton == nullptr) { // there may be more rendering devices later + singleton = this; + } +} + +/*****************/ +/**** BINDERS ****/ +/*****************/ + +RID RenderingDevice::_texture_create(const Ref &p_format, const Ref &p_view, const TypedArray &p_data) { + ERR_FAIL_COND_V(p_format.is_null(), RID()); + ERR_FAIL_COND_V(p_view.is_null(), RID()); + Vector> data; + for (int i = 0; i < p_data.size(); i++) { + Vector byte_slice = p_data[i]; + ERR_FAIL_COND_V(byte_slice.is_empty(), RID()); + data.push_back(byte_slice); + } + return texture_create(p_format->base, p_view->base, data); +} + +RID RenderingDevice::_texture_create_shared(const Ref &p_view, RID p_with_texture) { + ERR_FAIL_COND_V(p_view.is_null(), RID()); + + return texture_create_shared(p_view->base, p_with_texture); +} + +RID RenderingDevice::_texture_create_shared_from_slice(const Ref &p_view, RID p_with_texture, uint32_t p_layer, uint32_t p_mipmap, uint32_t p_mipmaps, TextureSliceType p_slice_type) { + ERR_FAIL_COND_V(p_view.is_null(), RID()); + + return texture_create_shared_from_slice(p_view->base, p_with_texture, p_layer, p_mipmap, p_mipmaps, p_slice_type); +} + +Ref RenderingDevice::_texture_get_format(RID p_rd_texture) { + Ref rtf; + rtf.instantiate(); + rtf->base = texture_get_format(p_rd_texture); + + return rtf; +} + +RenderingDevice::FramebufferFormatID RenderingDevice::_framebuffer_format_create(const TypedArray &p_attachments, uint32_t p_view_count) { + Vector attachments; + attachments.resize(p_attachments.size()); + + for (int i = 0; i < p_attachments.size(); i++) { + Ref af = p_attachments[i]; + ERR_FAIL_COND_V(af.is_null(), INVALID_FORMAT_ID); + attachments.write[i] = af->base; + } + return framebuffer_format_create(attachments, p_view_count); +} + +RenderingDevice::FramebufferFormatID RenderingDevice::_framebuffer_format_create_multipass(const TypedArray &p_attachments, const TypedArray &p_passes, uint32_t p_view_count) { + Vector attachments; + attachments.resize(p_attachments.size()); + + for (int i = 0; i < p_attachments.size(); i++) { + Ref af = p_attachments[i]; + ERR_FAIL_COND_V(af.is_null(), INVALID_FORMAT_ID); + attachments.write[i] = af->base; + } + + Vector passes; + for (int i = 0; i < p_passes.size(); i++) { + Ref pass = p_passes[i]; + ERR_CONTINUE(pass.is_null()); + passes.push_back(pass->base); + } + + return framebuffer_format_create_multipass(attachments, passes, p_view_count); +} + +RID RenderingDevice::_framebuffer_create(const TypedArray &p_textures, FramebufferFormatID p_format_check, uint32_t p_view_count) { + Vector textures = Variant(p_textures); + return framebuffer_create(textures, p_format_check, p_view_count); +} + +RID RenderingDevice::_framebuffer_create_multipass(const TypedArray &p_textures, const TypedArray &p_passes, FramebufferFormatID p_format_check, uint32_t p_view_count) { + Vector textures = Variant(p_textures); + Vector passes; + for (int i = 0; i < p_passes.size(); i++) { + Ref pass = p_passes[i]; + ERR_CONTINUE(pass.is_null()); + passes.push_back(pass->base); + } + return framebuffer_create_multipass(textures, passes, p_format_check, p_view_count); +} + +RID RenderingDevice::_sampler_create(const Ref &p_state) { + ERR_FAIL_COND_V(p_state.is_null(), RID()); + + return sampler_create(p_state->base); +} + +RenderingDevice::VertexFormatID RenderingDevice::_vertex_format_create(const TypedArray &p_vertex_formats) { + Vector descriptions; + descriptions.resize(p_vertex_formats.size()); + + for (int i = 0; i < p_vertex_formats.size(); i++) { + Ref af = p_vertex_formats[i]; + ERR_FAIL_COND_V(af.is_null(), INVALID_FORMAT_ID); + descriptions.write[i] = af->base; + } + return vertex_format_create(descriptions); +} + +RID RenderingDevice::_vertex_array_create(uint32_t p_vertex_count, VertexFormatID p_vertex_format, const TypedArray &p_src_buffers, const Vector &p_offsets) { + Vector buffers = Variant(p_src_buffers); + + Vector offsets; + offsets.resize(p_offsets.size()); + for (int i = 0; i < p_offsets.size(); i++) { + offsets.write[i] = p_offsets[i]; + } + + return vertex_array_create(p_vertex_count, p_vertex_format, buffers, offsets); +} + +Ref RenderingDevice::_shader_compile_spirv_from_source(const Ref &p_source, bool p_allow_cache) { + ERR_FAIL_COND_V(p_source.is_null(), Ref()); + + Ref bytecode; + bytecode.instantiate(); + for (int i = 0; i < RD::SHADER_STAGE_MAX; i++) { + String error; + + ShaderStage stage = ShaderStage(i); + String source = p_source->get_stage_source(stage); + + if (!source.is_empty()) { + Vector spirv = shader_compile_spirv_from_source(stage, source, p_source->get_language(), &error, p_allow_cache); + bytecode->set_stage_bytecode(stage, spirv); + bytecode->set_stage_compile_error(stage, error); + } + } + return bytecode; +} + +Vector RenderingDevice::_shader_compile_binary_from_spirv(const Ref &p_spirv, const String &p_shader_name) { + ERR_FAIL_COND_V(p_spirv.is_null(), Vector()); + + Vector stage_data; + for (int i = 0; i < RD::SHADER_STAGE_MAX; i++) { + ShaderStage stage = ShaderStage(i); + ShaderStageSPIRVData sd; + sd.shader_stage = stage; + String error = p_spirv->get_stage_compile_error(stage); + ERR_FAIL_COND_V_MSG(!error.is_empty(), Vector(), "Can't create a shader from an errored bytecode. Check errors in source bytecode."); + sd.spirv = p_spirv->get_stage_bytecode(stage); + if (sd.spirv.is_empty()) { + continue; + } + stage_data.push_back(sd); + } + + return shader_compile_binary_from_spirv(stage_data, p_shader_name); +} + +RID RenderingDevice::_shader_create_from_spirv(const Ref &p_spirv, const String &p_shader_name) { + ERR_FAIL_COND_V(p_spirv.is_null(), RID()); + + Vector stage_data; + for (int i = 0; i < RD::SHADER_STAGE_MAX; i++) { + ShaderStage stage = ShaderStage(i); + ShaderStageSPIRVData sd; + sd.shader_stage = stage; + String error = p_spirv->get_stage_compile_error(stage); + ERR_FAIL_COND_V_MSG(!error.is_empty(), RID(), "Can't create a shader from an errored bytecode. Check errors in source bytecode."); + sd.spirv = p_spirv->get_stage_bytecode(stage); + if (sd.spirv.is_empty()) { + continue; + } + stage_data.push_back(sd); + } + return shader_create_from_spirv(stage_data); +} + +RID RenderingDevice::_uniform_set_create(const TypedArray &p_uniforms, RID p_shader, uint32_t p_shader_set) { + Vector uniforms; + uniforms.resize(p_uniforms.size()); + for (int i = 0; i < p_uniforms.size(); i++) { + Ref uniform = p_uniforms[i]; + ERR_FAIL_COND_V(!uniform.is_valid(), RID()); + uniforms.write[i] = uniform->base; + } + return uniform_set_create(uniforms, p_shader, p_shader_set); +} + +Error RenderingDevice::_buffer_update_bind(RID p_buffer, uint32_t p_offset, uint32_t p_size, const Vector &p_data, BitField p_post_barrier) { + return buffer_update(p_buffer, p_offset, p_size, p_data.ptr(), p_post_barrier); +} + +static Vector _get_spec_constants(const TypedArray &p_constants) { + Vector ret; + ret.resize(p_constants.size()); + for (int i = 0; i < p_constants.size(); i++) { + Ref c = p_constants[i]; + ERR_CONTINUE(c.is_null()); + RenderingDevice::PipelineSpecializationConstant &sc = ret.write[i]; + Variant value = c->get_value(); + switch (value.get_type()) { + case Variant::BOOL: { + sc.type = RD::PIPELINE_SPECIALIZATION_CONSTANT_TYPE_BOOL; + sc.bool_value = value; + } break; + case Variant::INT: { + sc.type = RD::PIPELINE_SPECIALIZATION_CONSTANT_TYPE_INT; + sc.int_value = value; + } break; + case Variant::FLOAT: { + sc.type = RD::PIPELINE_SPECIALIZATION_CONSTANT_TYPE_FLOAT; + sc.float_value = value; + } break; + default: { + } + } + + sc.constant_id = c->get_constant_id(); + } + return ret; +} + +RID RenderingDevice::_render_pipeline_create(RID p_shader, FramebufferFormatID p_framebuffer_format, VertexFormatID p_vertex_format, RenderPrimitive p_render_primitive, const Ref &p_rasterization_state, const Ref &p_multisample_state, const Ref &p_depth_stencil_state, const Ref &p_blend_state, BitField p_dynamic_state_flags, uint32_t p_for_render_pass, const TypedArray &p_specialization_constants) { + PipelineRasterizationState rasterization_state; + if (p_rasterization_state.is_valid()) { + rasterization_state = p_rasterization_state->base; + } + + PipelineMultisampleState multisample_state; + if (p_multisample_state.is_valid()) { + multisample_state = p_multisample_state->base; + for (int i = 0; i < p_multisample_state->sample_masks.size(); i++) { + int64_t mask = p_multisample_state->sample_masks[i]; + multisample_state.sample_mask.push_back(mask); + } + } + + PipelineDepthStencilState depth_stencil_state; + if (p_depth_stencil_state.is_valid()) { + depth_stencil_state = p_depth_stencil_state->base; + } + + PipelineColorBlendState color_blend_state; + if (p_blend_state.is_valid()) { + color_blend_state = p_blend_state->base; + for (int i = 0; i < p_blend_state->attachments.size(); i++) { + Ref attachment = p_blend_state->attachments[i]; + if (attachment.is_valid()) { + color_blend_state.attachments.push_back(attachment->base); + } + } + } + + return render_pipeline_create(p_shader, p_framebuffer_format, p_vertex_format, p_render_primitive, rasterization_state, multisample_state, depth_stencil_state, color_blend_state, p_dynamic_state_flags, p_for_render_pass, _get_spec_constants(p_specialization_constants)); +} + +RID RenderingDevice::_compute_pipeline_create(RID p_shader, const TypedArray &p_specialization_constants = TypedArray()) { + return compute_pipeline_create(p_shader, _get_spec_constants(p_specialization_constants)); +} + +RenderingDevice::DrawListID RenderingDevice::_draw_list_begin(RID p_framebuffer, InitialAction p_initial_color_action, FinalAction p_final_color_action, InitialAction p_initial_depth_action, FinalAction p_final_depth_action, const Vector &p_clear_color_values, float p_clear_depth, uint32_t p_clear_stencil, const Rect2 &p_region, const TypedArray &p_storage_textures) { + Vector stextures; + for (int i = 0; i < p_storage_textures.size(); i++) { + stextures.push_back(p_storage_textures[i]); + } + return draw_list_begin(p_framebuffer, p_initial_color_action, p_final_color_action, p_initial_depth_action, p_final_depth_action, p_clear_color_values, p_clear_depth, p_clear_stencil, p_region, stextures); +} + +Vector RenderingDevice::_draw_list_begin_split(RID p_framebuffer, uint32_t p_splits, InitialAction p_initial_color_action, FinalAction p_final_color_action, InitialAction p_initial_depth_action, FinalAction p_final_depth_action, const Vector &p_clear_color_values, float p_clear_depth, uint32_t p_clear_stencil, const Rect2 &p_region, const TypedArray &p_storage_textures) { + Vector splits; + splits.resize(p_splits); + Vector stextures; + for (int i = 0; i < p_storage_textures.size(); i++) { + stextures.push_back(p_storage_textures[i]); + } + draw_list_begin_split(p_framebuffer, p_splits, splits.ptrw(), p_initial_color_action, p_final_color_action, p_initial_depth_action, p_final_depth_action, p_clear_color_values, p_clear_depth, p_clear_stencil, p_region, stextures); + + Vector split_ids; + split_ids.resize(splits.size()); + for (int i = 0; i < splits.size(); i++) { + split_ids.write[i] = splits[i]; + } + + return split_ids; +} + +Vector RenderingDevice::_draw_list_switch_to_next_pass_split(uint32_t p_splits) { + Vector splits; + splits.resize(p_splits); + + Error err = draw_list_switch_to_next_pass_split(p_splits, splits.ptrw()); + ERR_FAIL_COND_V(err != OK, Vector()); + + Vector split_ids; + split_ids.resize(splits.size()); + for (int i = 0; i < splits.size(); i++) { + split_ids.write[i] = splits[i]; + } + + return split_ids; +} + +void RenderingDevice::_draw_list_set_push_constant(DrawListID p_list, const Vector &p_data, uint32_t p_data_size) { + ERR_FAIL_COND((uint32_t)p_data.size() > p_data_size); + draw_list_set_push_constant(p_list, p_data.ptr(), p_data_size); +} + +void RenderingDevice::_compute_list_set_push_constant(ComputeListID p_list, const Vector &p_data, uint32_t p_data_size) { + ERR_FAIL_COND((uint32_t)p_data.size() > p_data_size); + compute_list_set_push_constant(p_list, p_data.ptr(), p_data_size); } diff --git a/servers/rendering/rendering_device.h b/servers/rendering/rendering_device.h index 7c514c11f873..165d761b5813 100644 --- a/servers/rendering/rendering_device.h +++ b/servers/rendering/rendering_device.h @@ -1,5 +1,5 @@ /**************************************************************************/ -/* rendering_device_vulkan.h */ +/* rendering_device.h */ /**************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ @@ -28,67 +28,104 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /**************************************************************************/ -#ifndef RENDERING_DEVICE_VULKAN_H -#define RENDERING_DEVICE_VULKAN_H +#ifndef RENDERING_DEVICE_H +#define RENDERING_DEVICE_H +#include "core/object/class_db.h" #include "core/object/worker_thread_pool.h" #include "core/os/thread_safe.h" #include "core/templates/local_vector.h" #include "core/templates/oa_hash_map.h" #include "core/templates/rid_owner.h" +#include "core/variant/typed_array.h" +#include "servers/display_server.h" #include "servers/rendering/rendering_device.h" +#include "servers/rendering/rendering_device_commons.h" +#include "servers/rendering/rendering_device_driver.h" + +class RDTextureFormat; +class RDTextureView; +class RDAttachmentFormat; +class RDSamplerState; +class RDVertexAttribute; +class RDShaderSource; +class RDShaderSPIRV; +class RDUniform; +class RDPipelineRasterizationState; +class RDPipelineMultisampleState; +class RDPipelineDepthStencilState; +class RDPipelineColorBlendState; +class RDFramebufferPass; +class RDPipelineSpecializationConstant; + +class RenderingDevice : public RenderingDeviceCommons { + GDCLASS(RenderingDevice, Object) -#ifdef DEBUG_ENABLED -#ifndef _DEBUG -#define _DEBUG -#endif -#endif -#include "vk_mem_alloc.h" + _THREAD_SAFE_CLASS_ +public: + enum DeviceFamily { + DEVICE_UNKNOWN, + DEVICE_OPENGL, + DEVICE_VULKAN, + DEVICE_DIRECTX, + }; -#ifdef USE_VOLK -#include -#else -#include -#endif + enum ShaderLanguage { + SHADER_LANGUAGE_GLSL, + SHADER_LANGUAGE_HLSL + }; -class VulkanContext; + enum SubgroupOperations { + SUBGROUP_BASIC_BIT = 1, + SUBGROUP_VOTE_BIT = 2, + SUBGROUP_ARITHMETIC_BIT = 4, + SUBGROUP_BALLOT_BIT = 8, + SUBGROUP_SHUFFLE_BIT = 16, + SUBGROUP_SHUFFLE_RELATIVE_BIT = 32, + SUBGROUP_CLUSTERED_BIT = 64, + SUBGROUP_QUAD_BIT = 128, + }; -class RenderingDeviceVulkan : public RenderingDevice { - _THREAD_SAFE_CLASS_ + struct Capabilities { + // main device info + DeviceFamily device_family = DEVICE_UNKNOWN; + uint32_t version_major = 1; + uint32_t version_minor = 0; + }; + + typedef String (*ShaderSPIRVGetCacheKeyFunction)(const RenderingDevice *p_render_device); + typedef Vector (*ShaderCompileToSPIRVFunction)(ShaderStage p_stage, const String &p_source_code, ShaderLanguage p_language, String *r_error, const RenderingDevice *p_render_device); + typedef Vector (*ShaderCacheFunction)(ShaderStage p_stage, const String &p_source_code, ShaderLanguage p_language); + + typedef void (*InvalidationCallback)(void *); + +private: + static ShaderCompileToSPIRVFunction compile_to_spirv_function; + static ShaderCacheFunction cache_function; + static ShaderSPIRVGetCacheKeyFunction get_spirv_cache_key_function; + + static RenderingDevice *singleton; - // Miscellaneous tables that map - // our enums to enums used - // by vulkan. - - VkPhysicalDeviceLimits limits; - static const VkFormat vulkan_formats[DATA_FORMAT_MAX]; - static const char *named_formats[DATA_FORMAT_MAX]; - static const VkCompareOp compare_operators[COMPARE_OP_MAX]; - static const VkStencilOp stencil_operations[STENCIL_OP_MAX]; - static const VkSampleCountFlagBits rasterization_sample_count[TEXTURE_SAMPLES_MAX]; - static const VkLogicOp logic_operations[RenderingDevice::LOGIC_OP_MAX]; - static const VkBlendFactor blend_factors[RenderingDevice::BLEND_FACTOR_MAX]; - static const VkBlendOp blend_operations[RenderingDevice::BLEND_OP_MAX]; - static const VkSamplerAddressMode address_modes[SAMPLER_REPEAT_MODE_MAX]; - static const VkBorderColor sampler_border_colors[SAMPLER_BORDER_COLOR_MAX]; - static const VkImageType vulkan_image_type[TEXTURE_TYPE_MAX]; - - // Functions used for format - // validation, and ensures the - // user passes valid data. - - static int get_format_vertex_size(DataFormat p_format); - static uint32_t get_image_format_pixel_size(DataFormat p_format); - static void get_compressed_image_format_block_dimensions(DataFormat p_format, uint32_t &r_w, uint32_t &r_h); - uint32_t get_compressed_image_format_block_byte_size(DataFormat p_format); - static uint32_t get_compressed_image_format_pixel_rshift(DataFormat p_format); - static uint32_t get_image_format_required_size(DataFormat p_format, uint32_t p_width, uint32_t p_height, uint32_t p_depth, uint32_t p_mipmaps, uint32_t *r_blockw = nullptr, uint32_t *r_blockh = nullptr, uint32_t *r_depth = nullptr); - static uint32_t get_image_required_mipmaps(uint32_t p_width, uint32_t p_height, uint32_t p_depth); - static bool format_has_stencil(DataFormat p_format); + Capabilities device_capabilities; + + RenderingDeviceDriver *driver = nullptr; // Owned by the context. + +protected: + static void _bind_methods(); + +#ifndef DISABLE_DEPRECATED + RID _shader_create_from_bytecode_bind_compat_79606(const Vector &p_shader_binary); + static void _bind_compatibility_methods(); +#endif /***************************/ /**** ID INFRASTRUCTURE ****/ /***************************/ +public: + //base numeric ID for all types + enum { + INVALID_FORMAT_ID = -1 + }; enum IDType { ID_TYPE_FRAMEBUFFER_FORMAT, @@ -97,11 +134,11 @@ class RenderingDeviceVulkan : public RenderingDevice { ID_TYPE_SPLIT_DRAW_LIST, ID_TYPE_COMPUTE_LIST, ID_TYPE_MAX, - ID_BASE_SHIFT = 58 // 5 bits for ID types. + ID_BASE_SHIFT = 58, // 5 bits for ID types. + ID_MASK = (ID_BASE_SHIFT - 1), }; - VkDevice device = VK_NULL_HANDLE; - +private: HashMap> dependency_map; // IDs to IDs that depend on it. HashMap> reverse_dependency_map; // Same as above, but in reverse. @@ -109,67 +146,23 @@ class RenderingDeviceVulkan : public RenderingDevice { void _free_dependencies(RID p_id); /*****************/ - /**** TEXTURE ****/ + /**** BARRIER ****/ /*****************/ - // In Vulkan, the concept of textures does not exist, - // instead there is the image (the memory pretty much, - // the view (how the memory is interpreted) and the - // sampler (how it's sampled from the shader). - // - // Texture here includes the first two stages, but - // It's possible to create textures sharing the image - // but with different views. The main use case for this - // is textures that can be read as both SRGB/Linear, - // or slices of a texture (a mipmap, a layer, a 3D slice) - // for a framebuffer to render into it. - - struct Texture { - VkImage image = VK_NULL_HANDLE; - VmaAllocation allocation = nullptr; - VmaAllocationInfo allocation_info; - VkImageView view = VK_NULL_HANDLE; - - TextureType type; - DataFormat format; - TextureSamples samples; - uint32_t width = 0; - uint32_t height = 0; - uint32_t depth = 0; - uint32_t layers = 0; - uint32_t mipmaps = 0; - uint32_t usage_flags = 0; - uint32_t base_mipmap = 0; - uint32_t base_layer = 0; - - Vector allowed_shared_formats; - - VkImageLayout layout; - - uint64_t used_in_frame = 0; - bool used_in_transfer = false; - bool used_in_raster = false; - bool used_in_compute = false; - - bool is_resolve_buffer = false; - - uint32_t read_aspect_mask = 0; - uint32_t barrier_aspect_mask = 0; - bool bound = false; // Bound to framebffer. - RID owner; +public: + enum BarrierMask { + BARRIER_MASK_VERTEX = 1, + BARRIER_MASK_FRAGMENT = 8, + BARRIER_MASK_COMPUTE = 2, + BARRIER_MASK_TRANSFER = 4, + + BARRIER_MASK_RASTER = BARRIER_MASK_VERTEX | BARRIER_MASK_FRAGMENT, // 9, + BARRIER_MASK_ALL_BARRIERS = 0x7FFF, // all flags set + BARRIER_MASK_NO_BARRIER = 0x8000, }; - RID_Owner texture_owner; - uint32_t texture_upload_region_size_px = 0; - - Vector _texture_get_data_from_image(Texture *tex, VkImage p_image, VmaAllocation p_allocation, uint32_t p_layer, bool p_2d = false); - Error _texture_update(RID p_texture, uint32_t p_layer, const Vector &p_data, BitField p_post_barrier, bool p_use_setup_queue); - - /*****************/ - /**** SAMPLER ****/ - /*****************/ - - RID_Owner sampler_owner; +private: + void _full_barrier(bool p_sync_with_draw); /***************************/ /**** BUFFER MANAGEMENT ****/ @@ -197,8 +190,7 @@ class RenderingDeviceVulkan : public RenderingDevice { // See the comments in the code to understand better how it works. struct StagingBufferBlock { - VkBuffer buffer = VK_NULL_HANDLE; - VmaAllocation allocation = nullptr; + RDD::BufferID driver_id; uint64_t frame_used = 0; uint32_t fill_amount = 0; }; @@ -213,33 +205,178 @@ class RenderingDeviceVulkan : public RenderingDevice { Error _insert_staging_block(); struct Buffer { + RDD::BufferID driver_id; uint32_t size = 0; - uint32_t usage = 0; - VkBuffer buffer = VK_NULL_HANDLE; - VmaAllocation allocation = nullptr; - VkDescriptorBufferInfo buffer_info; // Used for binding. - Buffer() { - } + BitField usage; }; - Error _buffer_allocate(Buffer *p_buffer, uint32_t p_size, uint32_t p_usage, VmaMemoryUsage p_mem_usage, VmaAllocationCreateFlags p_mem_flags); - Error _buffer_free(Buffer *p_buffer); + Buffer *_get_buffer_from_owner(RID p_buffer, BitField &r_stages, BitField &r_access, BitField p_post_barrier); Error _buffer_update(Buffer *p_buffer, size_t p_offset, const uint8_t *p_data, size_t p_data_size, bool p_use_draw_command_buffer = false, uint32_t p_required_align = 32); - void _full_barrier(bool p_sync_with_draw); - void _memory_barrier(VkPipelineStageFlags p_src_stage_mask, VkPipelineStageFlags p_dst_stage_mask, VkAccessFlags p_src_access, VkAccessFlags p_dst_access, bool p_sync_with_draw); - void _buffer_memory_barrier(VkBuffer buffer, uint64_t p_from, uint64_t p_size, VkPipelineStageFlags p_src_stage_mask, VkPipelineStageFlags p_dst_stage_mask, VkAccessFlags p_src_access, VkAccessFlags p_dst_access, bool p_sync_with_draw); + RID_Owner uniform_buffer_owner; + RID_Owner storage_buffer_owner; + RID_Owner texture_buffer_owner; + +public: + Error buffer_copy(RID p_src_buffer, RID p_dst_buffer, uint32_t p_src_offset, uint32_t p_dst_offset, uint32_t p_size, BitField p_post_barrier = BARRIER_MASK_ALL_BARRIERS); + Error buffer_update(RID p_buffer, uint32_t p_offset, uint32_t p_size, const void *p_data, BitField p_post_barrier = BARRIER_MASK_ALL_BARRIERS); + Error buffer_clear(RID p_buffer, uint32_t p_offset, uint32_t p_size, BitField p_post_barrier = BARRIER_MASK_ALL_BARRIERS); + Vector buffer_get_data(RID p_buffer, uint32_t p_offset = 0, uint32_t p_size = 0); // This causes stall, only use to retrieve large buffers for saving. + + /*****************/ + /**** TEXTURE ****/ + /*****************/ + + // In modern APIs, the concept of textures may not exist; + // instead there is the image (the memory pretty much, + // the view (how the memory is interpreted) and the + // sampler (how it's sampled from the shader). + // + // Texture here includes the first two stages, but + // It's possible to create textures sharing the image + // but with different views. The main use case for this + // is textures that can be read as both SRGB/Linear, + // or slices of a texture (a mipmap, a layer, a 3D slice) + // for a framebuffer to render into it. + + struct Texture { + RDD::TextureID driver_id; + + TextureType type = TEXTURE_TYPE_MAX; + DataFormat format = DATA_FORMAT_MAX; + TextureSamples samples = TEXTURE_SAMPLES_MAX; + uint32_t width = 0; + uint32_t height = 0; + uint32_t depth = 0; + uint32_t layers = 0; + uint32_t mipmaps = 0; + uint32_t usage_flags = 0; + uint32_t base_mipmap = 0; + uint32_t base_layer = 0; + + Vector allowed_shared_formats; + + RDD::TextureLayout layout = RDD::TEXTURE_LAYOUT_UNDEFINED; + + uint64_t used_in_frame = 0; + bool used_in_transfer = false; + bool used_in_raster = false; + bool used_in_compute = false; + + bool is_resolve_buffer = false; + + BitField read_aspect_flags; + BitField barrier_aspect_flags; + bool bound = false; // Bound to framebffer. + RID owner; + }; + + RID_Owner texture_owner; + uint32_t texture_upload_region_size_px = 0; + + Vector _texture_get_data(Texture *tex, uint32_t p_layer, bool p_2d = false); + Error _texture_update(RID p_texture, uint32_t p_layer, const Vector &p_data, BitField p_post_barrier, bool p_use_setup_queue); + +public: + struct TextureView { + DataFormat format_override = DATA_FORMAT_MAX; // // Means, use same as format. + TextureSwizzle swizzle_r = TEXTURE_SWIZZLE_R; + TextureSwizzle swizzle_g = TEXTURE_SWIZZLE_G; + TextureSwizzle swizzle_b = TEXTURE_SWIZZLE_B; + TextureSwizzle swizzle_a = TEXTURE_SWIZZLE_A; + + bool operator==(const TextureView &p_other) const { + if (format_override != p_other.format_override) { + return false; + } else if (swizzle_r != p_other.swizzle_r) { + return false; + } else if (swizzle_g != p_other.swizzle_g) { + return false; + } else if (swizzle_b != p_other.swizzle_b) { + return false; + } else if (swizzle_a != p_other.swizzle_a) { + return false; + } else { + return true; + } + } + }; + + RID texture_create(const TextureFormat &p_format, const TextureView &p_view, const Vector> &p_data = Vector>()); + RID texture_create_shared(const TextureView &p_view, RID p_with_texture); + RID texture_create_from_extension(TextureType p_type, DataFormat p_format, TextureSamples p_samples, BitField p_usage, uint64_t p_image, uint64_t p_width, uint64_t p_height, uint64_t p_depth, uint64_t p_layers); + RID texture_create_shared_from_slice(const TextureView &p_view, RID p_with_texture, uint32_t p_layer, uint32_t p_mipmap, uint32_t p_mipmaps = 1, TextureSliceType p_slice_type = TEXTURE_SLICE_2D, uint32_t p_layers = 0); + Error texture_update(RID p_texture, uint32_t p_layer, const Vector &p_data, BitField p_post_barrier = BARRIER_MASK_ALL_BARRIERS); + Vector texture_get_data(RID p_texture, uint32_t p_layer); // CPU textures will return immediately, while GPU textures will most likely force a flush + + bool texture_is_format_supported_for_usage(DataFormat p_format, BitField p_usage) const; + bool texture_is_shared(RID p_texture); + bool texture_is_valid(RID p_texture); + TextureFormat texture_get_format(RID p_texture); + Size2i texture_size(RID p_texture); +#ifndef DISABLE_DEPRECATED + uint64_t texture_get_native_handle(RID p_texture); +#endif + + Error texture_copy(RID p_from_texture, RID p_to_texture, const Vector3 &p_from, const Vector3 &p_to, const Vector3 &p_size, uint32_t p_src_mipmap, uint32_t p_dst_mipmap, uint32_t p_src_layer, uint32_t p_dst_layer, BitField p_post_barrier = BARRIER_MASK_ALL_BARRIERS); + Error texture_clear(RID p_texture, const Color &p_color, uint32_t p_base_mipmap, uint32_t p_mipmaps, uint32_t p_base_layer, uint32_t p_layers, BitField p_post_barrier = BARRIER_MASK_ALL_BARRIERS); + Error texture_resolve_multisample(RID p_from_texture, RID p_to_texture, BitField p_post_barrier = BARRIER_MASK_ALL_BARRIERS); + + /************************/ + /**** DRAW LISTS (I) ****/ + /************************/ + + enum InitialAction { + INITIAL_ACTION_CLEAR, // Start rendering and clear the whole framebuffer. + INITIAL_ACTION_CLEAR_REGION, // Start rendering and clear the framebuffer in the specified region. + INITIAL_ACTION_CLEAR_REGION_CONTINUE, // Continue rendering and clear the framebuffer in the specified region. Framebuffer must have been left in `FINAL_ACTION_CONTINUE` state as the final action previously. + INITIAL_ACTION_KEEP, // Start rendering, but keep attached color texture contents. If the framebuffer was previously used to read in a shader, this will automatically insert a layout transition. + INITIAL_ACTION_DROP, // Start rendering, ignore what is there; write above it. In general, this is the fastest option when you will be writing every single pixel and you don't need a clear color. + INITIAL_ACTION_CONTINUE, // Continue rendering. Framebuffer must have been left in `FINAL_ACTION_CONTINUE` state as the final action previously. + INITIAL_ACTION_MAX + }; + + enum FinalAction { + FINAL_ACTION_READ, // Store the texture for reading and make it read-only if it has the `TEXTURE_USAGE_SAMPLING_BIT` bit (only applies to color, depth and stencil attachments). + FINAL_ACTION_DISCARD, // Discard the texture data and make it read-only if it has the `TEXTURE_USAGE_SAMPLING_BIT` bit (only applies to color, depth and stencil attachments). + FINAL_ACTION_CONTINUE, // Store the texture and continue for further processing. Similar to `FINAL_ACTION_READ`, but does not make the texture read-only if it has the `TEXTURE_USAGE_SAMPLING_BIT` bit. + FINAL_ACTION_MAX + }; /*********************/ /**** FRAMEBUFFER ****/ /*********************/ - // In Vulkan, framebuffers work similar to how they + // In modern APIs, generally, framebuffers work similar to how they // do in OpenGL, with the exception that - // the "format" (vkRenderPass) is not dynamic + // the "format" (RDD::RenderPassID) is not dynamic // and must be more or less the same as the one // used for the render pipelines. + struct AttachmentFormat { + enum { UNUSED_ATTACHMENT = 0xFFFFFFFF }; + DataFormat format; + TextureSamples samples; + uint32_t usage_flags; + AttachmentFormat() { + format = DATA_FORMAT_R8G8B8A8_UNORM; + samples = TEXTURE_SAMPLES_1; + usage_flags = 0; + } + }; + + struct FramebufferPass { + Vector color_attachments; + Vector input_attachments; + Vector resolve_attachments; + Vector preserve_attachments; + int32_t depth_attachment = ATTACHMENT_UNUSED; + int32_t vrs_attachment = ATTACHMENT_UNUSED; // density map for VRS, only used if supported + }; + + typedef int64_t FramebufferFormatID; + +private: struct FramebufferFormatKey { Vector attachments; Vector passes; @@ -350,13 +487,14 @@ class RenderingDeviceVulkan : public RenderingDevice { } }; - VkRenderPass _render_pass_create(const Vector &p_attachments, const Vector &p_passes, InitialAction p_initial_action, FinalAction p_final_action, InitialAction p_initial_depth_action, FinalAction p_final_depth_action, uint32_t p_view_count = 1, Vector *r_samples = nullptr); + RDD::RenderPassID _render_pass_create(const Vector &p_attachments, const Vector &p_passes, InitialAction p_initial_action, FinalAction p_final_action, InitialAction p_initial_depth_action, FinalAction p_final_depth_action, uint32_t p_view_count = 1, Vector *r_samples = nullptr); + // This is a cache and it's never freed, it ensures // IDs for a given format are always unique. RBMap framebuffer_format_cache; struct FramebufferFormat { const RBMap::Element *E; - VkRenderPass render_pass = VK_NULL_HANDLE; // Here for constructing shaders, never used, see section (7.2. Render Pass Compatibility from Vulkan spec). + RDD::RenderPassID render_pass; // Here for constructing shaders, never used, see section (7.2. Render Pass Compatibility from Vulkan spec). Vector pass_samples; uint32_t view_count = 1; // Number of views. }; @@ -364,7 +502,7 @@ class RenderingDeviceVulkan : public RenderingDevice { HashMap framebuffer_formats; struct Framebuffer { - FramebufferFormatID format_id = 0; + FramebufferFormatID format_id; struct VersionKey { InitialAction initial_color_action; FinalAction final_color_action; @@ -399,8 +537,8 @@ class RenderingDeviceVulkan : public RenderingDevice { void *invalidated_callback_userdata = nullptr; struct Version { - VkFramebuffer framebuffer = VK_NULL_HANDLE; - VkRenderPass render_pass = VK_NULL_HANDLE; // This one is owned. + RDD::FramebufferID framebuffer; + RDD::RenderPassID render_pass; // This one is owned. uint32_t subpass_count = 1; }; @@ -411,10 +549,38 @@ class RenderingDeviceVulkan : public RenderingDevice { RID_Owner framebuffer_owner; - /***********************/ - /**** VERTEX BUFFER ****/ - /***********************/ +public: + // This ID is warranted to be unique for the same formats, does not need to be freed + FramebufferFormatID framebuffer_format_create(const Vector &p_format, uint32_t p_view_count = 1); + FramebufferFormatID framebuffer_format_create_multipass(const Vector &p_attachments, const Vector &p_passes, uint32_t p_view_count = 1); + FramebufferFormatID framebuffer_format_create_empty(TextureSamples p_samples = TEXTURE_SAMPLES_1); + TextureSamples framebuffer_format_get_texture_samples(FramebufferFormatID p_format, uint32_t p_pass = 0); + + RID framebuffer_create(const Vector &p_texture_attachments, FramebufferFormatID p_format_check = INVALID_ID, uint32_t p_view_count = 1); + RID framebuffer_create_multipass(const Vector &p_texture_attachments, const Vector &p_passes, FramebufferFormatID p_format_check = INVALID_ID, uint32_t p_view_count = 1); + RID framebuffer_create_empty(const Size2i &p_size, TextureSamples p_samples = TEXTURE_SAMPLES_1, FramebufferFormatID p_format_check = INVALID_ID); + bool framebuffer_is_valid(RID p_framebuffer) const; + void framebuffer_set_invalidation_callback(RID p_framebuffer, InvalidationCallback p_callback, void *p_userdata); + + FramebufferFormatID framebuffer_get_format(RID p_framebuffer); + + /*****************/ + /**** SAMPLER ****/ + /*****************/ +private: + RID_Owner sampler_owner; + +public: + RID sampler_create(const SamplerState &p_state); + bool sampler_is_format_supported_for_filter(DataFormat p_format, SamplerFilter p_sampler_filter) const; + + /**********************/ + /**** VERTEX ARRAY ****/ + /**********************/ + typedef int64_t VertexFormatID; + +private: // Vertex buffers in Vulkan are similar to how // they work in OpenGL, except that instead of // an attribute index, there is a buffer binding @@ -428,6 +594,7 @@ class RenderingDeviceVulkan : public RenderingDevice { struct VertexDescriptionKey { Vector vertex_formats; + bool operator==(const VertexDescriptionKey &p_key) const { int vdc = vertex_formats.size(); int vdck = p_key.vertex_formats.size(); @@ -489,21 +656,19 @@ class RenderingDeviceVulkan : public RenderingDevice { struct VertexDescriptionCache { Vector vertex_formats; - VkVertexInputBindingDescription *bindings = nullptr; - VkVertexInputAttributeDescription *attributes = nullptr; - VkPipelineVertexInputStateCreateInfo create_info; + RDD::VertexFormatID driver_id; }; HashMap vertex_formats; struct VertexArray { RID buffer; - VertexFormatID description = 0; + VertexFormatID description; int vertex_count = 0; uint32_t max_instances_allowed = 0; - Vector buffers; // Not owned, just referenced. - Vector offsets; + Vector buffers; // Not owned, just referenced. + Vector offsets; }; RID_Owner vertex_array_owner; @@ -511,7 +676,7 @@ class RenderingDeviceVulkan : public RenderingDevice { struct IndexBuffer : public Buffer { uint32_t max_index = 0; // Used for validation. uint32_t index_count = 0; - VkIndexType index_type = VK_INDEX_TYPE_NONE_NV; + IndexBufferFormat format = INDEX_BUFFER_FORMAT_UINT16; bool supports_restart_indices = false; }; @@ -519,20 +684,30 @@ class RenderingDeviceVulkan : public RenderingDevice { struct IndexArray { uint32_t max_index = 0; // Remember the maximum index here too, for validation. - VkBuffer buffer; // Not owned, inherited from index buffer. + RDD::BufferID driver_id; // Not owned, inherited from index buffer. uint32_t offset = 0; uint32_t indices = 0; - VkIndexType index_type = VK_INDEX_TYPE_NONE_NV; + IndexBufferFormat format = INDEX_BUFFER_FORMAT_UINT16; bool supports_restart_indices = false; }; RID_Owner index_array_owner; +public: + RID vertex_buffer_create(uint32_t p_size_bytes, const Vector &p_data = Vector(), bool p_use_as_storage = false); + + // This ID is warranted to be unique for the same formats, does not need to be freed + VertexFormatID vertex_format_create(const Vector &p_vertex_descriptions); + RID vertex_array_create(uint32_t p_vertex_count, VertexFormatID p_vertex_format, const Vector &p_src_buffers, const Vector &p_offsets = Vector()); + + RID index_buffer_create(uint32_t p_size_indices, IndexBufferFormat p_format, const Vector &p_data = Vector(), bool p_use_restart_indices = false); + RID index_array_create(RID p_index_buffer, uint32_t p_index_offset, uint32_t p_index_count); + /****************/ /**** SHADER ****/ /****************/ - // Vulkan specifies a really complex behavior for the application + // Some APIs (e.g., Vulkan) specifies a really complex behavior for the application // in order to tell when descriptor sets need to be re-bound (or not). // "When binding a descriptor set (see Descriptor Set Binding) to set // number N, if the previously bound descriptor sets for sets zero @@ -544,53 +719,19 @@ class RenderingDeviceVulkan : public RenderingDevice { // As a result, we need to figure out quickly when something is no longer "compatible". // in order to avoid costly rebinds. - struct UniformInfo { - UniformType type = UniformType::UNIFORM_TYPE_MAX; - bool writable = false; - int binding = 0; - uint32_t stages = 0; - int length = 0; // Size of arrays (in total elements), or ubos (in bytes * total elements). - - bool operator!=(const UniformInfo &p_info) const { - return (binding != p_info.binding || type != p_info.type || writable != p_info.writable || stages != p_info.stages || length != p_info.length); - } - - bool operator<(const UniformInfo &p_info) const { - if (binding != p_info.binding) { - return binding < p_info.binding; - } - if (type != p_info.type) { - return type < p_info.type; - } - if (writable != p_info.writable) { - return writable < p_info.writable; - } - if (stages != p_info.stages) { - return stages < p_info.stages; - } - return length < p_info.length; - } - }; - +private: struct UniformSetFormat { - Vector uniform_info; - bool operator<(const UniformSetFormat &p_format) const { - uint32_t size = uniform_info.size(); - uint32_t psize = p_format.uniform_info.size(); + Vector uniforms; - if (size != psize) { - return size < psize; + _FORCE_INLINE_ bool operator<(const UniformSetFormat &p_other) const { + if (uniforms.size() != p_other.uniforms.size()) { + return uniforms.size() < p_other.uniforms.size(); } - - const UniformInfo *infoptr = uniform_info.ptr(); - const UniformInfo *pinfoptr = p_format.uniform_info.ptr(); - - for (uint32_t i = 0; i < size; i++) { - if (infoptr[i] != pinfoptr[i]) { - return infoptr[i] < pinfoptr[i]; + for (int i = 0; i < uniforms.size(); i++) { + if (uniforms[i] < p_other.uniforms[i]) { + return true; } } - return false; } }; @@ -615,115 +756,122 @@ class RenderingDeviceVulkan : public RenderingDevice { // to do quick validation and ensuring the user // does not submit something invalid. - struct Shader { - struct Set { - Vector uniform_info; - VkDescriptorSetLayout descriptor_set_layout = VK_NULL_HANDLE; - }; + struct Shader : public ShaderDescription { + String name; // Used for debug. + RDD::ShaderID driver_id; + Vector set_formats; + }; - uint64_t vertex_input_mask = 0; // Inputs used, this is mostly for validation. - uint32_t fragment_output_mask = 0; + String _shader_uniform_debug(RID p_shader, int p_set = -1); - struct PushConstant { - uint32_t size = 0; - uint32_t vk_stages_mask = 0; - }; + RID_Owner shader_owner; - PushConstant push_constant; +#ifndef DISABLE_DEPRECATED + BitField _convert_barrier_mask_81356(BitField p_old_barrier); + void _draw_list_end_bind_compat_81356(BitField p_post_barrier); + void _compute_list_end_bind_compat_81356(BitField p_post_barrier); + void _barrier_bind_compat_81356(BitField p_from, BitField p_to); +#endif - uint32_t compute_local_size[3] = { 0, 0, 0 }; +public: + ApiContextRD *get_context() const { return context; } - struct SpecializationConstant { - PipelineSpecializationConstant constant; - uint32_t stage_flags = 0; - }; + const Capabilities *get_device_capabilities() const { return &device_capabilities; }; - bool is_compute = false; - Vector sets; - Vector set_formats; - Vector pipeline_stages; - Vector specialization_constants; - VkPipelineLayout pipeline_layout = VK_NULL_HANDLE; - String name; // Used for debug. - }; + bool has_feature(const Features p_feature) const; - String _shader_uniform_debug(RID p_shader, int p_set = -1); + Vector shader_compile_spirv_from_source(ShaderStage p_stage, const String &p_source_code, ShaderLanguage p_language = SHADER_LANGUAGE_GLSL, String *r_error = nullptr, bool p_allow_cache = true); + String shader_get_spirv_cache_key() const; - RID_Owner shader_owner; + static void shader_set_compile_to_spirv_function(ShaderCompileToSPIRVFunction p_function); + static void shader_set_spirv_cache_function(ShaderCacheFunction p_function); + static void shader_set_get_cache_key_function(ShaderSPIRVGetCacheKeyFunction p_function); + + String shader_get_binary_cache_key() const; + Vector shader_compile_binary_from_spirv(const Vector &p_spirv, const String &p_shader_name = ""); + + RID shader_create_from_spirv(const Vector &p_spirv, const String &p_shader_name = ""); + RID shader_create_from_bytecode(const Vector &p_shader_binary, RID p_placeholder = RID()); + RID shader_create_placeholder(); + + uint64_t shader_get_vertex_input_attribute_mask(RID p_shader); /******************/ /**** UNIFORMS ****/ /******************/ - // Descriptor sets require allocation from a pool. - // The documentation on how to use pools properly - // is scarce, and the documentation is strange. - // - // Basically, you can mix and match pools as you - // like, but you'll run into fragmentation issues. - // Because of this, the recommended approach is to - // create a pool for every descriptor set type, as - // this prevents fragmentation. - // - // This is implemented here as a having a list of - // pools (each can contain up to 64 sets) for each - // set layout. The amount of sets for each type - // is used as the key. - - enum { - MAX_DESCRIPTOR_POOL_ELEMENT = 65535 + enum StorageBufferUsage { + STORAGE_BUFFER_USAGE_DISPATCH_INDIRECT = 1, }; - struct DescriptorPoolKey { - union { - struct { - uint16_t uniform_type[UNIFORM_TYPE_MAX]; // Using 16 bits because, for sending arrays, each element is a pool set. - }; - struct { - uint64_t key1; - uint64_t key2; - uint64_t key3; - }; - }; - bool operator<(const DescriptorPoolKey &p_key) const { - if (key1 != p_key.key1) { - return key1 < p_key.key1; - } - if (key2 != p_key.key2) { - return key2 < p_key.key2; - } + RID uniform_buffer_create(uint32_t p_size_bytes, const Vector &p_data = Vector()); + RID storage_buffer_create(uint32_t p_size, const Vector &p_data = Vector(), BitField p_usage = 0); + RID texture_buffer_create(uint32_t p_size_elements, DataFormat p_format, const Vector &p_data = Vector()); - return key3 < p_key.key3; - } - DescriptorPoolKey() { - key1 = 0; - key2 = 0; - key3 = 0; - } - }; + struct Uniform { + UniformType uniform_type = UNIFORM_TYPE_IMAGE; + uint32_t binding = 0; // Binding index as specified in shader. - struct DescriptorPool { - VkDescriptorPool pool; - uint32_t usage; - }; + private: + // In most cases only one ID is provided per binding, so avoid allocating memory unnecessarily for performance. + RID id; // If only one is provided, this is used. + Vector ids; // If multiple ones are provided, this is used instead. - RBMap> descriptor_pools; - uint32_t max_descriptors_per_pool = 0; + public: + _FORCE_INLINE_ uint32_t get_id_count() const { + return (id.is_valid() ? 1 : ids.size()); + } - DescriptorPool *_descriptor_pool_allocate(const DescriptorPoolKey &p_key); - void _descriptor_pool_free(const DescriptorPoolKey &p_key, DescriptorPool *p_pool); + _FORCE_INLINE_ RID get_id(uint32_t p_idx) const { + if (id.is_valid()) { + ERR_FAIL_COND_V(p_idx != 0, RID()); + return id; + } else { + return ids[p_idx]; + } + } + _FORCE_INLINE_ void set_id(uint32_t p_idx, RID p_id) { + if (id.is_valid()) { + ERR_FAIL_COND(p_idx != 0); + id = p_id; + } else { + ids.write[p_idx] = p_id; + } + } - RID_Owner uniform_buffer_owner; - RID_Owner storage_buffer_owner; + _FORCE_INLINE_ void append_id(RID p_id) { + if (ids.is_empty()) { + if (id == RID()) { + id = p_id; + } else { + ids.push_back(id); + ids.push_back(p_id); + id = RID(); + } + } else { + ids.push_back(p_id); + } + } - // Texture buffer needs a view. - struct TextureBuffer { - Buffer buffer; - VkBufferView view = VK_NULL_HANDLE; - }; + _FORCE_INLINE_ void clear_ids() { + id = RID(); + ids.clear(); + } - RID_Owner texture_buffer_owner; + _FORCE_INLINE_ Uniform(UniformType p_type, int p_binding, RID p_id) { + uniform_type = p_type; + binding = p_binding; + id = p_id; + } + _FORCE_INLINE_ Uniform(UniformType p_type, int p_binding, const Vector &p_ids) { + uniform_type = p_type; + binding = p_binding; + ids = p_ids; + } + _FORCE_INLINE_ Uniform() = default; + }; +private: // This structure contains the descriptor set. They _need_ to be allocated // for a shader (and will be erased when this shader is erased), but should // work for other shaders as long as the hash matches. This covers using @@ -736,12 +884,9 @@ class RenderingDeviceVulkan : public RenderingDevice { uint32_t format = 0; RID shader_id; uint32_t shader_set = 0; - DescriptorPool *pool = nullptr; - DescriptorPoolKey pool_key; - VkDescriptorSet descriptor_set = VK_NULL_HANDLE; - //VkPipelineLayout pipeline_layout; // Not owned, inherited from shader. + RDD::UniformSetID driver_id; struct AttachableTexture { - uint32_t bind; + uint32_t bind = 0; RID texture; }; @@ -754,6 +899,11 @@ class RenderingDeviceVulkan : public RenderingDevice { RID_Owner uniform_set_owner; +public: + RID uniform_set_create(const Vector &p_uniforms, RID p_shader, uint32_t p_shader_set); + bool uniform_set_is_valid(RID p_uniform_set); + void uniform_set_set_invalidation_callback(RID p_uniform_set, InvalidationCallback p_callback, void *p_userdata); + /*******************/ /**** PIPELINES ****/ /*******************/ @@ -768,15 +918,15 @@ class RenderingDeviceVulkan : public RenderingDevice { // here to do validation (vulkan does none by // default) and warn the user if something // was not supplied as intended. - +private: struct RenderPipeline { // Cached values for validation. #ifdef DEBUG_ENABLED struct Validation { - FramebufferFormatID framebuffer_format = 0; + FramebufferFormatID framebuffer_format; uint32_t render_pass = 0; uint32_t dynamic_state = 0; - VertexFormatID vertex_format = 0; + VertexFormatID vertex_format; bool uses_restart_indices = false; uint32_t primitive_minimum = 0; uint32_t primitive_divisor = 0; @@ -784,58 +934,56 @@ class RenderingDeviceVulkan : public RenderingDevice { #endif // Actual pipeline. RID shader; + RDD::ShaderID shader_driver_id; Vector set_formats; - VkPipelineLayout pipeline_layout = VK_NULL_HANDLE; // Not owned, needed for push constants. - VkPipeline pipeline = VK_NULL_HANDLE; + RDD::PipelineID driver_id; uint32_t push_constant_size = 0; - uint32_t push_constant_stages_mask = 0; }; RID_Owner render_pipeline_owner; - struct PipelineCacheHeader { - uint32_t magic; - uint32_t data_size; - uint64_t data_hash; - uint32_t vendor_id; - uint32_t device_id; - uint32_t driver_version; - uint8_t uuid[VK_UUID_SIZE]; - uint8_t driver_abi; - }; - - struct PipelineCache { - String file_path; - PipelineCacheHeader header = {}; - size_t current_size = 0; - LocalVector buffer; - VkPipelineCache cache_object = VK_NULL_HANDLE; - }; - - PipelineCache pipelines_cache; - + bool pipelines_cache_enabled = false; + size_t pipelines_cache_size = 0; + String pipelines_cache_file_path; WorkerThreadPool::TaskID pipelines_cache_save_task = WorkerThreadPool::INVALID_TASK_ID; - void _load_pipeline_cache(); + Vector _load_pipeline_cache(); void _update_pipeline_cache(bool p_closing = false); static void _save_pipeline_cache(void *p_data); struct ComputePipeline { RID shader; + RDD::ShaderID shader_driver_id; Vector set_formats; - VkPipelineLayout pipeline_layout = VK_NULL_HANDLE; // Not owned, needed for push constants. - VkPipeline pipeline = VK_NULL_HANDLE; + RDD::PipelineID driver_id; uint32_t push_constant_size = 0; - uint32_t push_constant_stages_mask = 0; uint32_t local_group_size[3] = { 0, 0, 0 }; }; RID_Owner compute_pipeline_owner; - /*******************/ - /**** DRAW LIST ****/ - /*******************/ +public: + RID render_pipeline_create(RID p_shader, FramebufferFormatID p_framebuffer_format, VertexFormatID p_vertex_format, RenderPrimitive p_render_primitive, const PipelineRasterizationState &p_rasterization_state, const PipelineMultisampleState &p_multisample_state, const PipelineDepthStencilState &p_depth_stencil_state, const PipelineColorBlendState &p_blend_state, BitField p_dynamic_state_flags = 0, uint32_t p_for_render_pass = 0, const Vector &p_specialization_constants = Vector()); + bool render_pipeline_is_valid(RID p_pipeline); + + RID compute_pipeline_create(RID p_shader, const Vector &p_specialization_constants = Vector()); + bool compute_pipeline_is_valid(RID p_pipeline); + + /****************/ + /**** SCREEN ****/ + /****************/ + + int screen_get_width(DisplayServer::WindowID p_screen = 0) const; + int screen_get_height(DisplayServer::WindowID p_screen = 0) const; + FramebufferFormatID screen_get_framebuffer_format() const; + + /*************************/ + /**** DRAW LISTS (II) ****/ + /*************************/ + + typedef int64_t DrawListID; +private: // Draw list contains both the command buffer // used for drawing as well as a LOT of // information used for validation. This @@ -848,21 +996,21 @@ class RenderingDeviceVulkan : public RenderingDevice { // each needs its own command pool. struct SplitDrawListAllocator { - VkCommandPool command_pool = VK_NULL_HANDLE; - Vector command_buffers; // One for each frame. + RDD::CommandPoolID command_pool; + Vector command_buffers; // One for each frame. }; Vector split_draw_list_allocators; struct DrawList { - VkCommandBuffer command_buffer = VK_NULL_HANDLE; // If persistent, this is owned, otherwise it's shared with the ringbuffer. + RDD::CommandBufferID command_buffer; // If persistent, this is owned, otherwise it's shared with the ringbuffer. Rect2i viewport; bool viewport_set = false; struct SetState { uint32_t pipeline_expected_format = 0; uint32_t uniform_set_format = 0; - VkDescriptorSet descriptor_set = VK_NULL_HANDLE; + RDD::UniformSetID uniform_set_driver_id; RID uniform_set; bool bound = false; }; @@ -872,10 +1020,9 @@ class RenderingDeviceVulkan : public RenderingDevice { uint32_t set_count = 0; RID pipeline; RID pipeline_shader; - VkPipelineLayout pipeline_layout = VK_NULL_HANDLE; + RDD::ShaderID pipeline_shader_driver_id; RID vertex_array; RID index_array; - uint32_t pipeline_push_constant_stages = 0; } state; #ifdef DEBUG_ENABLED @@ -916,8 +1063,8 @@ class RenderingDeviceVulkan : public RenderingDevice { DrawList *draw_list = nullptr; // One for regular draw lists, multiple for split. uint32_t draw_list_subpass_count = 0; uint32_t draw_list_count = 0; - VkRenderPass draw_list_render_pass = VK_NULL_HANDLE; - VkFramebuffer draw_list_vkframebuffer = VK_NULL_HANDLE; + RDD::RenderPassID draw_list_render_pass; + RDD::FramebufferID draw_list_vkframebuffer; #ifdef DEBUG_ENABLED FramebufferFormatID draw_list_framebuffer_format = INVALID_ID; #endif @@ -930,24 +1077,50 @@ class RenderingDeviceVulkan : public RenderingDevice { bool draw_list_unbind_depth_textures = false; void _draw_list_insert_clear_region(DrawList *p_draw_list, Framebuffer *p_framebuffer, Point2i p_viewport_offset, Point2i p_viewport_size, bool p_clear_color, const Vector &p_clear_colors, bool p_clear_depth, float p_depth, uint32_t p_stencil); - Error _draw_list_setup_framebuffer(Framebuffer *p_framebuffer, InitialAction p_initial_color_action, FinalAction p_final_color_action, InitialAction p_initial_depth_action, FinalAction p_final_depth_action, VkFramebuffer *r_framebuffer, VkRenderPass *r_render_pass, uint32_t *r_subpass_count); - Error _draw_list_render_pass_begin(Framebuffer *framebuffer, InitialAction p_initial_color_action, FinalAction p_final_color_action, InitialAction p_initial_depth_action, FinalAction p_final_depth_action, const Vector &p_clear_colors, float p_clear_depth, uint32_t p_clear_stencil, Point2i viewport_offset, Point2i viewport_size, VkFramebuffer vkframebuffer, VkRenderPass render_pass, VkCommandBuffer command_buffer, VkSubpassContents subpass_contents, const Vector &p_storage_textures); + Error _draw_list_setup_framebuffer(Framebuffer *p_framebuffer, InitialAction p_initial_color_action, FinalAction p_final_color_action, InitialAction p_initial_depth_action, FinalAction p_final_depth_action, RDD::FramebufferID *r_framebuffer, RDD::RenderPassID *r_render_pass, uint32_t *r_subpass_count); + Error _draw_list_render_pass_begin(Framebuffer *p_framebuffer, InitialAction p_initial_color_action, FinalAction p_final_color_action, InitialAction p_initial_depth_action, FinalAction p_final_depth_action, const Vector &p_clear_colors, float p_clear_depth, uint32_t p_clear_stencil, Point2i p_viewport_offset, Point2i p_viewport_size, RDD::FramebufferID p_framebuffer_driver_id, RDD::RenderPassID p_render_pass, RDD::CommandBufferID p_command_buffer, RDD::CommandBufferType p_cmd_buffer_mode, const Vector &p_storage_textures); _FORCE_INLINE_ DrawList *_get_draw_list_ptr(DrawListID p_id); - Buffer *_get_buffer_from_owner(RID p_buffer, VkPipelineStageFlags &dst_stage_mask, VkAccessFlags &dst_access, BitField p_post_barrier); Error _draw_list_allocate(const Rect2i &p_viewport, uint32_t p_splits, uint32_t p_subpass); void _draw_list_free(Rect2i *r_last_viewport = nullptr); - /**********************/ - /**** COMPUTE LIST ****/ - /**********************/ +public: + DrawListID draw_list_begin_for_screen(DisplayServer::WindowID p_screen = 0, const Color &p_clear_color = Color()); + DrawListID draw_list_begin(RID p_framebuffer, InitialAction p_initial_color_action, FinalAction p_final_color_action, InitialAction p_initial_depth_action, FinalAction p_final_depth_action, const Vector &p_clear_color_values = Vector(), float p_clear_depth = 1.0, uint32_t p_clear_stencil = 0, const Rect2 &p_region = Rect2(), const Vector &p_storage_textures = Vector()); + Error draw_list_begin_split(RID p_framebuffer, uint32_t p_splits, DrawListID *r_split_ids, InitialAction p_initial_color_action, FinalAction p_final_color_action, InitialAction p_initial_depth_action, FinalAction p_final_depth_action, const Vector &p_clear_color_values = Vector(), float p_clear_depth = 1.0, uint32_t p_clear_stencil = 0, const Rect2 &p_region = Rect2(), const Vector &p_storage_textures = Vector()); + + void draw_list_set_blend_constants(DrawListID p_list, const Color &p_color); + void draw_list_bind_render_pipeline(DrawListID p_list, RID p_render_pipeline); + void draw_list_bind_uniform_set(DrawListID p_list, RID p_uniform_set, uint32_t p_index); + void draw_list_bind_vertex_array(DrawListID p_list, RID p_vertex_array); + void draw_list_bind_index_array(DrawListID p_list, RID p_index_array); + void draw_list_set_line_width(DrawListID p_list, float p_width); + void draw_list_set_push_constant(DrawListID p_list, const void *p_data, uint32_t p_data_size); + + void draw_list_draw(DrawListID p_list, bool p_use_indices, uint32_t p_instances = 1, uint32_t p_procedural_vertices = 0); + + void draw_list_enable_scissor(DrawListID p_list, const Rect2 &p_rect); + void draw_list_disable_scissor(DrawListID p_list); + + uint32_t draw_list_get_current_pass(); + DrawListID draw_list_switch_to_next_pass(); + Error draw_list_switch_to_next_pass_split(uint32_t p_splits, DrawListID *r_split_ids); + + void draw_list_end(BitField p_post_barrier = BARRIER_MASK_ALL_BARRIERS); + /***********************/ + /**** COMPUTE LISTS ****/ + /***********************/ + + typedef int64_t ComputeListID; + +private: struct ComputeList { - VkCommandBuffer command_buffer = VK_NULL_HANDLE; // If persistent, this is owned, otherwise it's shared with the ringbuffer. + RDD::CommandBufferID command_buffer; // If persistent, this is owned, otherwise it's shared with the ringbuffer. struct SetState { uint32_t pipeline_expected_format = 0; uint32_t uniform_set_format = 0; - VkDescriptorSet descriptor_set = VK_NULL_HANDLE; + RDD::UniformSetID uniform_set_driver_id; RID uniform_set; bool bound = false; }; @@ -958,9 +1131,8 @@ class RenderingDeviceVulkan : public RenderingDevice { uint32_t set_count = 0; RID pipeline; RID pipeline_shader; + RDD::ShaderID pipeline_shader_driver_id; uint32_t local_group_size[3] = { 0, 0, 0 }; - VkPipelineLayout pipeline_layout = VK_NULL_HANDLE; - uint32_t pipeline_push_constant_stages = 0; bool allow_draw_overlap; } state; @@ -982,7 +1154,22 @@ class RenderingDeviceVulkan : public RenderingDevice { ComputeList *compute_list = nullptr; - void _compute_list_add_barrier(BitField p_post_barrier, uint32_t p_barrier_flags, uint32_t p_access_flags); + void _compute_list_add_barrier(BitField p_post_barrier, BitField p_stages, BitField p_access); + +public: + ComputeListID compute_list_begin(bool p_allow_draw_overlap = false); + void compute_list_bind_compute_pipeline(ComputeListID p_list, RID p_compute_pipeline); + void compute_list_bind_uniform_set(ComputeListID p_list, RID p_uniform_set, uint32_t p_index); + void compute_list_set_push_constant(ComputeListID p_list, const void *p_data, uint32_t p_data_size); + void compute_list_dispatch(ComputeListID p_list, uint32_t p_x_groups, uint32_t p_y_groups, uint32_t p_z_groups); + void compute_list_dispatch_threads(ComputeListID p_list, uint32_t p_x_threads, uint32_t p_y_threads, uint32_t p_z_threads); + void compute_list_dispatch_indirect(ComputeListID p_list, RID p_buffer, uint32_t p_offset); + void compute_list_add_barrier(ComputeListID p_list); + + void compute_list_end(BitField p_post_barrier = BARRIER_MASK_ALL_BARRIERS); + + void barrier(BitField p_from = BARRIER_MASK_ALL_BARRIERS, BitField p_to = BARRIER_MASK_ALL_BARRIERS); + void full_barrier(); /**************************/ /**** FRAME MANAGEMENT ****/ @@ -1002,28 +1189,28 @@ class RenderingDeviceVulkan : public RenderingDevice { // nature of the GPU. They will get deleted // when the frame is cycled. +private: struct Frame { // List in usage order, from last to free to first to free. List buffers_to_dispose_of; List textures_to_dispose_of; List framebuffers_to_dispose_of; - List samplers_to_dispose_of; + List samplers_to_dispose_of; List shaders_to_dispose_of; - List buffer_views_to_dispose_of; List uniform_sets_to_dispose_of; List render_pipelines_to_dispose_of; List compute_pipelines_to_dispose_of; - VkCommandPool command_pool = VK_NULL_HANDLE; - VkCommandBuffer setup_command_buffer = VK_NULL_HANDLE; // Used at the beginning of every frame for set-up. - VkCommandBuffer draw_command_buffer = VK_NULL_HANDLE; // Used at the beginning of every frame for set-up. + RDD::CommandPoolID command_pool; + RDD::CommandBufferID setup_command_buffer; // Used at the beginning of every frame for set-up. + RDD::CommandBufferID draw_command_buffer; // Used at the beginning of every frame for set-up. struct Timestamp { String description; uint64_t value = 0; }; - VkQueryPool timestamp_pool; + RDD::QueryPoolID timestamp_pool; TightLocalVector timestamp_names; TightLocalVector timestamp_cpu_values; @@ -1046,13 +1233,9 @@ class RenderingDeviceVulkan : public RenderingDevice { void _free_pending_resources(int p_frame); - VmaAllocator allocator = nullptr; - HashMap small_allocs_pools; - VmaPool _find_or_create_small_allocs_pool(uint32_t p_mem_type_index); - - VulkanContext *context = nullptr; + ApiContextRD *context = nullptr; - uint64_t image_memory = 0; + uint64_t texture_memory = 0; uint64_t buffer_memory = 0; void _free_internal(RID p_id); @@ -1070,219 +1253,140 @@ class RenderingDeviceVulkan : public RenderingDevice { HashMap resource_names; #endif - VkSampleCountFlagBits _ensure_supported_sample_count(TextureSamples p_requested_sample_count) const; - public: - virtual RID texture_create(const TextureFormat &p_format, const TextureView &p_view, const Vector> &p_data = Vector>()); - virtual RID texture_create_shared(const TextureView &p_view, RID p_with_texture); - virtual RID texture_create_from_extension(TextureType p_type, DataFormat p_format, TextureSamples p_samples, BitField p_flags, uint64_t p_image, uint64_t p_width, uint64_t p_height, uint64_t p_depth, uint64_t p_layers); - - virtual RID texture_create_shared_from_slice(const TextureView &p_view, RID p_with_texture, uint32_t p_layer, uint32_t p_mipmap, uint32_t p_mipmaps = 1, TextureSliceType p_slice_type = TEXTURE_SLICE_2D, uint32_t p_layers = 0); - virtual Error texture_update(RID p_texture, uint32_t p_layer, const Vector &p_data, BitField p_post_barrier = BARRIER_MASK_ALL_BARRIERS); - virtual Vector texture_get_data(RID p_texture, uint32_t p_layer); - - virtual bool texture_is_format_supported_for_usage(DataFormat p_format, BitField p_usage) const; - virtual bool texture_is_shared(RID p_texture); - virtual bool texture_is_valid(RID p_texture); - virtual TextureFormat texture_get_format(RID p_texture); - virtual Size2i texture_size(RID p_texture); - virtual uint64_t texture_get_native_handle(RID p_texture); - - virtual Error texture_copy(RID p_from_texture, RID p_to_texture, const Vector3 &p_from, const Vector3 &p_to, const Vector3 &p_size, uint32_t p_src_mipmap, uint32_t p_dst_mipmap, uint32_t p_src_layer, uint32_t p_dst_layer, BitField p_post_barrier = BARRIER_MASK_ALL_BARRIERS); - virtual Error texture_clear(RID p_texture, const Color &p_color, uint32_t p_base_mipmap, uint32_t p_mipmaps, uint32_t p_base_layer, uint32_t p_layers, BitField p_post_barrier = BARRIER_MASK_ALL_BARRIERS); - virtual Error texture_resolve_multisample(RID p_from_texture, RID p_to_texture, BitField p_post_barrier = BARRIER_MASK_ALL_BARRIERS); - - /*********************/ - /**** FRAMEBUFFER ****/ - /*********************/ - - virtual FramebufferFormatID framebuffer_format_create(const Vector &p_format, uint32_t p_view_count = 1); - virtual FramebufferFormatID framebuffer_format_create_multipass(const Vector &p_attachments, const Vector &p_passes, uint32_t p_view_count = 1); - virtual FramebufferFormatID framebuffer_format_create_empty(TextureSamples p_samples = TEXTURE_SAMPLES_1); - virtual TextureSamples framebuffer_format_get_texture_samples(FramebufferFormatID p_format, uint32_t p_pass = 0); - - virtual RID framebuffer_create(const Vector &p_texture_attachments, FramebufferFormatID p_format_check = INVALID_ID, uint32_t p_view_count = 1); - virtual RID framebuffer_create_multipass(const Vector &p_texture_attachments, const Vector &p_passes, FramebufferFormatID p_format_check = INVALID_ID, uint32_t p_view_count = 1); - virtual RID framebuffer_create_empty(const Size2i &p_size, TextureSamples p_samples = TEXTURE_SAMPLES_1, FramebufferFormatID p_format_check = INVALID_ID); - virtual bool framebuffer_is_valid(RID p_framebuffer) const; - virtual void framebuffer_set_invalidation_callback(RID p_framebuffer, InvalidationCallback p_callback, void *p_userdata); - - virtual FramebufferFormatID framebuffer_get_format(RID p_framebuffer); - - /*****************/ - /**** SAMPLER ****/ - /*****************/ - - virtual RID sampler_create(const SamplerState &p_state); - virtual bool sampler_is_format_supported_for_filter(DataFormat p_format, SamplerFilter p_sampler_filter) const; - - /**********************/ - /**** VERTEX ARRAY ****/ - /**********************/ - - virtual RID vertex_buffer_create(uint32_t p_size_bytes, const Vector &p_data = Vector(), bool p_use_as_storage = false); - - // Internally reference counted, this ID is warranted to be unique for the same description, but needs to be freed as many times as it was allocated. - virtual VertexFormatID vertex_format_create(const Vector &p_vertex_formats); - virtual RID vertex_array_create(uint32_t p_vertex_count, VertexFormatID p_vertex_format, const Vector &p_src_buffers, const Vector &p_offsets = Vector()); - - virtual RID index_buffer_create(uint32_t p_size_indices, IndexBufferFormat p_format, const Vector &p_data = Vector(), bool p_use_restart_indices = false); + void initialize(ApiContextRD *p_context, bool p_local_device = false); + void finalize(); - virtual RID index_array_create(RID p_index_buffer, uint32_t p_index_offset, uint32_t p_index_count); + void free(RID p_id); /****************/ - /**** SHADER ****/ + /**** Timing ****/ /****************/ - virtual String shader_get_binary_cache_key() const; - virtual Vector shader_compile_binary_from_spirv(const Vector &p_spirv, const String &p_shader_name = ""); - - virtual RID shader_create_from_bytecode(const Vector &p_shader_binary, RID p_placeholder = RID()); - virtual RID shader_create_placeholder(); - - virtual uint64_t shader_get_vertex_input_attribute_mask(RID p_shader); - - /*****************/ - /**** UNIFORM ****/ - /*****************/ - - virtual RID uniform_buffer_create(uint32_t p_size_bytes, const Vector &p_data = Vector()); - virtual RID storage_buffer_create(uint32_t p_size_bytes, const Vector &p_data = Vector(), BitField p_usage = 0); - virtual RID texture_buffer_create(uint32_t p_size_elements, DataFormat p_format, const Vector &p_data = Vector()); - - virtual RID uniform_set_create(const Vector &p_uniforms, RID p_shader, uint32_t p_shader_set); - virtual bool uniform_set_is_valid(RID p_uniform_set); - virtual void uniform_set_set_invalidation_callback(RID p_uniform_set, InvalidationCallback p_callback, void *p_userdata); - - virtual Error buffer_copy(RID p_src_buffer, RID p_dst_buffer, uint32_t p_src_offset, uint32_t p_dst_offset, uint32_t p_size, BitField p_post_barrier = BARRIER_MASK_ALL_BARRIERS); - virtual Error buffer_update(RID p_buffer, uint32_t p_offset, uint32_t p_size, const void *p_data, BitField p_post_barrier = BARRIER_MASK_ALL_BARRIERS); // Works for any buffer. - virtual Error buffer_clear(RID p_buffer, uint32_t p_offset, uint32_t p_size, BitField p_post_barrier = BARRIER_MASK_ALL_BARRIERS); - virtual Vector buffer_get_data(RID p_buffer, uint32_t p_offset = 0, uint32_t p_size = 0); - - /*************************/ - /**** RENDER PIPELINE ****/ - /*************************/ - - virtual RID render_pipeline_create(RID p_shader, FramebufferFormatID p_framebuffer_format, VertexFormatID p_vertex_format, RenderPrimitive p_render_primitive, const PipelineRasterizationState &p_rasterization_state, const PipelineMultisampleState &p_multisample_state, const PipelineDepthStencilState &p_depth_stencil_state, const PipelineColorBlendState &p_blend_state, BitField p_dynamic_state_flags = 0, uint32_t p_for_render_pass = 0, const Vector &p_specialization_constants = Vector()); - virtual bool render_pipeline_is_valid(RID p_pipeline); - - /**************************/ - /**** COMPUTE PIPELINE ****/ - /**************************/ - - virtual RID compute_pipeline_create(RID p_shader, const Vector &p_specialization_constants = Vector()); - virtual bool compute_pipeline_is_valid(RID p_pipeline); + void capture_timestamp(const String &p_name); + uint32_t get_captured_timestamps_count() const; + uint64_t get_captured_timestamps_frame() const; + uint64_t get_captured_timestamp_gpu_time(uint32_t p_index) const; + uint64_t get_captured_timestamp_cpu_time(uint32_t p_index) const; + String get_captured_timestamp_name(uint32_t p_index) const; /****************/ - /**** SCREEN ****/ + /**** LIMITS ****/ /****************/ - virtual int screen_get_width(DisplayServer::WindowID p_screen = 0) const; - virtual int screen_get_height(DisplayServer::WindowID p_screen = 0) const; - virtual FramebufferFormatID screen_get_framebuffer_format() const; - - /********************/ - /**** DRAW LISTS ****/ - /********************/ - - virtual DrawListID draw_list_begin_for_screen(DisplayServer::WindowID p_screen = 0, const Color &p_clear_color = Color()); - - virtual DrawListID draw_list_begin(RID p_framebuffer, InitialAction p_initial_color_action, FinalAction p_final_color_action, InitialAction p_initial_depth_action, FinalAction p_final_depth_action, const Vector &p_clear_color_values = Vector(), float p_clear_depth = 1.0, uint32_t p_clear_stencil = 0, const Rect2 &p_region = Rect2(), const Vector &p_storage_textures = Vector()); - virtual Error draw_list_begin_split(RID p_framebuffer, uint32_t p_splits, DrawListID *r_split_ids, InitialAction p_initial_color_action, FinalAction p_final_color_action, InitialAction p_initial_depth_action, FinalAction p_final_depth_action, const Vector &p_clear_color_values = Vector(), float p_clear_depth = 1.0, uint32_t p_clear_stencil = 0, const Rect2 &p_region = Rect2(), const Vector &p_storage_textures = Vector()); - - virtual void draw_list_set_blend_constants(DrawListID p_list, const Color &p_color); - virtual void draw_list_bind_render_pipeline(DrawListID p_list, RID p_render_pipeline); - virtual void draw_list_bind_uniform_set(DrawListID p_list, RID p_uniform_set, uint32_t p_index); - virtual void draw_list_bind_vertex_array(DrawListID p_list, RID p_vertex_array); - virtual void draw_list_bind_index_array(DrawListID p_list, RID p_index_array); - virtual void draw_list_set_line_width(DrawListID p_list, float p_width); - virtual void draw_list_set_push_constant(DrawListID p_list, const void *p_data, uint32_t p_data_size); + uint64_t limit_get(Limit p_limit) const; - virtual void draw_list_draw(DrawListID p_list, bool p_use_indices, uint32_t p_instances = 1, uint32_t p_procedural_vertices = 0); + //methods below not exposed, used by RenderingDeviceRD + void prepare_screen_for_drawing(); - virtual void draw_list_enable_scissor(DrawListID p_list, const Rect2 &p_rect); - virtual void draw_list_disable_scissor(DrawListID p_list); - - virtual uint32_t draw_list_get_current_pass(); - virtual DrawListID draw_list_switch_to_next_pass(); - virtual Error draw_list_switch_to_next_pass_split(uint32_t p_splits, DrawListID *r_split_ids); - - virtual void draw_list_end(BitField p_post_barrier = BARRIER_MASK_ALL_BARRIERS); - - /***********************/ - /**** COMPUTE LISTS ****/ - /***********************/ + void swap_buffers(); - virtual ComputeListID compute_list_begin(bool p_allow_draw_overlap = false); - virtual void compute_list_bind_compute_pipeline(ComputeListID p_list, RID p_compute_pipeline); - virtual void compute_list_bind_uniform_set(ComputeListID p_list, RID p_uniform_set, uint32_t p_index); - virtual void compute_list_set_push_constant(ComputeListID p_list, const void *p_data, uint32_t p_data_size); - virtual void compute_list_add_barrier(ComputeListID p_list); + uint32_t get_frame_delay() const; - virtual void compute_list_dispatch(ComputeListID p_list, uint32_t p_x_groups, uint32_t p_y_groups, uint32_t p_z_groups); - virtual void compute_list_dispatch_threads(ComputeListID p_list, uint32_t p_x_threads, uint32_t p_y_threads, uint32_t p_z_threads); - virtual void compute_list_dispatch_indirect(ComputeListID p_list, RID p_buffer, uint32_t p_offset); - virtual void compute_list_end(BitField p_post_barrier = BARRIER_MASK_ALL_BARRIERS); + void submit(); + void sync(); - virtual void barrier(BitField p_from = BARRIER_MASK_ALL_BARRIERS, BitField p_to = BARRIER_MASK_ALL_BARRIERS); - virtual void full_barrier(); + enum MemoryType { + MEMORY_TEXTURES, + MEMORY_BUFFERS, + MEMORY_TOTAL + }; - /**************/ - /**** FREE ****/ - /**************/ + uint64_t get_memory_usage(MemoryType p_type) const; - virtual void free(RID p_id); + RenderingDevice *create_local_device(); - /****************/ - /**** Timing ****/ - /****************/ + void set_resource_name(RID p_id, const String &p_name); - virtual void capture_timestamp(const String &p_name); - virtual uint32_t get_captured_timestamps_count() const; - virtual uint64_t get_captured_timestamps_frame() const; - virtual uint64_t get_captured_timestamp_gpu_time(uint32_t p_index) const; - virtual uint64_t get_captured_timestamp_cpu_time(uint32_t p_index) const; - virtual String get_captured_timestamp_name(uint32_t p_index) const; + void draw_command_begin_label(String p_label_name, const Color &p_color = Color(1, 1, 1, 1)); + void draw_command_insert_label(String p_label_name, const Color &p_color = Color(1, 1, 1, 1)); + void draw_command_end_label(); - /****************/ - /**** Limits ****/ - /****************/ + String get_device_vendor_name() const; + String get_device_name() const; + DeviceType get_device_type() const; + String get_device_api_version() const; + String get_device_pipeline_cache_uuid() const; - virtual uint64_t limit_get(Limit p_limit) const; + uint64_t get_driver_resource(DriverResource p_resource, RID p_rid = RID(), uint64_t p_index = 0); - virtual void prepare_screen_for_drawing(); - void initialize(VulkanContext *p_context, bool p_local_device = false); - void finalize(); + static RenderingDevice *get_singleton(); - virtual void swap_buffers(); // For main device. + RenderingDevice(); + ~RenderingDevice(); - virtual void submit(); // For local device. - virtual void sync(); // For local device. +private: + /*****************/ + /**** BINDERS ****/ + /*****************/ - virtual uint32_t get_frame_delay() const; + RID _texture_create(const Ref &p_format, const Ref &p_view, const TypedArray &p_data = Array()); + RID _texture_create_shared(const Ref &p_view, RID p_with_texture); + RID _texture_create_shared_from_slice(const Ref &p_view, RID p_with_texture, uint32_t p_layer, uint32_t p_mipmap, uint32_t p_mipmaps = 1, TextureSliceType p_slice_type = TEXTURE_SLICE_2D); + Ref _texture_get_format(RID p_rd_texture); - virtual RenderingDevice *create_local_device(); + FramebufferFormatID _framebuffer_format_create(const TypedArray &p_attachments, uint32_t p_view_count); + FramebufferFormatID _framebuffer_format_create_multipass(const TypedArray &p_attachments, const TypedArray &p_passes, uint32_t p_view_count); + RID _framebuffer_create(const TypedArray &p_textures, FramebufferFormatID p_format_check = INVALID_ID, uint32_t p_view_count = 1); + RID _framebuffer_create_multipass(const TypedArray &p_textures, const TypedArray &p_passes, FramebufferFormatID p_format_check = INVALID_ID, uint32_t p_view_count = 1); - virtual uint64_t get_memory_usage(MemoryType p_type) const; + RID _sampler_create(const Ref &p_state); - virtual void set_resource_name(RID p_id, const String p_name); + VertexFormatID _vertex_format_create(const TypedArray &p_vertex_formats); + RID _vertex_array_create(uint32_t p_vertex_count, VertexFormatID p_vertex_format, const TypedArray &p_src_buffers, const Vector &p_offsets = Vector()); - virtual void draw_command_begin_label(String p_label_name, const Color p_color = Color(1, 1, 1, 1)); - virtual void draw_command_insert_label(String p_label_name, const Color p_color = Color(1, 1, 1, 1)); - virtual void draw_command_end_label(); + Ref _shader_compile_spirv_from_source(const Ref &p_source, bool p_allow_cache = true); + Vector _shader_compile_binary_from_spirv(const Ref &p_bytecode, const String &p_shader_name = ""); + RID _shader_create_from_spirv(const Ref &p_spirv, const String &p_shader_name = ""); - virtual String get_device_vendor_name() const; - virtual String get_device_name() const; - virtual RenderingDevice::DeviceType get_device_type() const; - virtual String get_device_api_version() const; - virtual String get_device_pipeline_cache_uuid() const; + RID _uniform_set_create(const TypedArray &p_uniforms, RID p_shader, uint32_t p_shader_set); - virtual uint64_t get_driver_resource(DriverResource p_resource, RID p_rid = RID(), uint64_t p_index = 0); + Error _buffer_update_bind(RID p_buffer, uint32_t p_offset, uint32_t p_size, const Vector &p_data, BitField p_post_barrier = BARRIER_MASK_ALL_BARRIERS); - virtual bool has_feature(const Features p_feature) const; + RID _render_pipeline_create(RID p_shader, FramebufferFormatID p_framebuffer_format, VertexFormatID p_vertex_format, RenderPrimitive p_render_primitive, const Ref &p_rasterization_state, const Ref &p_multisample_state, const Ref &p_depth_stencil_state, const Ref &p_blend_state, BitField p_dynamic_state_flags, uint32_t p_for_render_pass, const TypedArray &p_specialization_constants); + RID _compute_pipeline_create(RID p_shader, const TypedArray &p_specialization_constants); - RenderingDeviceVulkan(); - ~RenderingDeviceVulkan(); + DrawListID _draw_list_begin(RID p_framebuffer, InitialAction p_initial_color_action, FinalAction p_final_color_action, InitialAction p_initial_depth_action, FinalAction p_final_depth_action, const Vector &p_clear_color_values = Vector(), float p_clear_depth = 1.0, uint32_t p_clear_stencil = 0, const Rect2 &p_region = Rect2(), const TypedArray &p_storage_textures = TypedArray()); + Vector _draw_list_begin_split(RID p_framebuffer, uint32_t p_splits, InitialAction p_initial_color_action, FinalAction p_final_color_action, InitialAction p_initial_depth_action, FinalAction p_final_depth_action, const Vector &p_clear_color_values = Vector(), float p_clear_depth = 1.0, uint32_t p_clear_stencil = 0, const Rect2 &p_region = Rect2(), const TypedArray &p_storage_textures = TypedArray()); + void _draw_list_set_push_constant(DrawListID p_list, const Vector &p_data, uint32_t p_data_size); + void _compute_list_set_push_constant(ComputeListID p_list, const Vector &p_data, uint32_t p_data_size); + Vector _draw_list_switch_to_next_pass_split(uint32_t p_splits); }; -#endif // RENDERING_DEVICE_VULKAN_H +VARIANT_ENUM_CAST(RenderingDevice::DeviceType) +VARIANT_ENUM_CAST(RenderingDevice::DriverResource) +VARIANT_ENUM_CAST(RenderingDevice::ShaderStage) +VARIANT_ENUM_CAST(RenderingDevice::ShaderLanguage) +VARIANT_ENUM_CAST(RenderingDevice::CompareOperator) +VARIANT_ENUM_CAST(RenderingDevice::DataFormat) +VARIANT_BITFIELD_CAST(RenderingDevice::BarrierMask); +VARIANT_ENUM_CAST(RenderingDevice::TextureType) +VARIANT_ENUM_CAST(RenderingDevice::TextureSamples) +VARIANT_BITFIELD_CAST(RenderingDevice::TextureUsageBits) +VARIANT_ENUM_CAST(RenderingDevice::TextureSwizzle) +VARIANT_ENUM_CAST(RenderingDevice::TextureSliceType) +VARIANT_ENUM_CAST(RenderingDevice::SamplerFilter) +VARIANT_ENUM_CAST(RenderingDevice::SamplerRepeatMode) +VARIANT_ENUM_CAST(RenderingDevice::SamplerBorderColor) +VARIANT_ENUM_CAST(RenderingDevice::VertexFrequency) +VARIANT_ENUM_CAST(RenderingDevice::IndexBufferFormat) +VARIANT_BITFIELD_CAST(RenderingDevice::StorageBufferUsage) +VARIANT_ENUM_CAST(RenderingDevice::UniformType) +VARIANT_ENUM_CAST(RenderingDevice::RenderPrimitive) +VARIANT_ENUM_CAST(RenderingDevice::PolygonCullMode) +VARIANT_ENUM_CAST(RenderingDevice::PolygonFrontFace) +VARIANT_ENUM_CAST(RenderingDevice::StencilOperation) +VARIANT_ENUM_CAST(RenderingDevice::LogicOperation) +VARIANT_ENUM_CAST(RenderingDevice::BlendFactor) +VARIANT_ENUM_CAST(RenderingDevice::BlendOperation) +VARIANT_BITFIELD_CAST(RenderingDevice::PipelineDynamicStateFlags) +VARIANT_ENUM_CAST(RenderingDevice::PipelineSpecializationConstantType) +VARIANT_ENUM_CAST(RenderingDevice::InitialAction) +VARIANT_ENUM_CAST(RenderingDevice::FinalAction) +VARIANT_ENUM_CAST(RenderingDevice::Limit) +VARIANT_ENUM_CAST(RenderingDevice::MemoryType) +VARIANT_ENUM_CAST(RenderingDevice::Features) + +typedef RenderingDevice RD; + +#endif // RENDERING_DEVICE_H diff --git a/servers/rendering/rendering_device_binds.h b/servers/rendering/rendering_device_binds.h index 737a874abc9b..5f21207579df 100644 --- a/servers/rendering/rendering_device_binds.h +++ b/servers/rendering/rendering_device_binds.h @@ -289,7 +289,7 @@ class RDShaderSPIRV : public Resource { if (bytecode[i].size()) { RD::ShaderStageSPIRVData stage; stage.shader_stage = RD::ShaderStage(i); - stage.spir_v = bytecode[i]; + stage.spirv = bytecode[i]; stages.push_back(stage); } } diff --git a/servers/rendering/rendering_device_commons.cpp b/servers/rendering/rendering_device_commons.cpp index c2fa232eac41..c8b7980633fe 100644 --- a/servers/rendering/rendering_device_commons.cpp +++ b/servers/rendering/rendering_device_commons.cpp @@ -1,5 +1,5 @@ /**************************************************************************/ -/* rendering_device.cpp */ +/* rendering_device_commons.cpp */ /**************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ @@ -28,1325 +28,885 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /**************************************************************************/ -#include "rendering_device.h" -#include "rendering_device.compat.inc" - -#include "rendering_device_binds.h" - -#include "thirdparty/spirv-reflect/spirv_reflect.h" - -RenderingDevice *RenderingDevice::singleton = nullptr; - -const char *RenderingDevice::shader_stage_names[RenderingDevice::SHADER_STAGE_MAX] = { - "Vertex", - "Fragment", - "TesselationControl", - "TesselationEvaluation", - "Compute", +#include "rendering_device_commons.h" + +/*****************/ +/**** GENERIC ****/ +/*****************/ + +const char *const RenderingDeviceCommons::FORMAT_NAMES[DATA_FORMAT_MAX] = { + "R4G4_Unorm_Pack8", + "R4G4B4A4_Unorm_Pack16", + "B4G4R4A4_Unorm_Pack16", + "R5G6B5_Unorm_Pack16", + "B5G6R5_Unorm_Pack16", + "R5G5B5A1_Unorm_Pack16", + "B5G5R5A1_Unorm_Pack16", + "A1R5G5B5_Unorm_Pack16", + "R8_Unorm", + "R8_Snorm", + "R8_Uscaled", + "R8_Sscaled", + "R8_Uint", + "R8_Sint", + "R8_Srgb", + "R8G8_Unorm", + "R8G8_Snorm", + "R8G8_Uscaled", + "R8G8_Sscaled", + "R8G8_Uint", + "R8G8_Sint", + "R8G8_Srgb", + "R8G8B8_Unorm", + "R8G8B8_Snorm", + "R8G8B8_Uscaled", + "R8G8B8_Sscaled", + "R8G8B8_Uint", + "R8G8B8_Sint", + "R8G8B8_Srgb", + "B8G8R8_Unorm", + "B8G8R8_Snorm", + "B8G8R8_Uscaled", + "B8G8R8_Sscaled", + "B8G8R8_Uint", + "B8G8R8_Sint", + "B8G8R8_Srgb", + "R8G8B8A8_Unorm", + "R8G8B8A8_Snorm", + "R8G8B8A8_Uscaled", + "R8G8B8A8_Sscaled", + "R8G8B8A8_Uint", + "R8G8B8A8_Sint", + "R8G8B8A8_Srgb", + "B8G8R8A8_Unorm", + "B8G8R8A8_Snorm", + "B8G8R8A8_Uscaled", + "B8G8R8A8_Sscaled", + "B8G8R8A8_Uint", + "B8G8R8A8_Sint", + "B8G8R8A8_Srgb", + "A8B8G8R8_Unorm_Pack32", + "A8B8G8R8_Snorm_Pack32", + "A8B8G8R8_Uscaled_Pack32", + "A8B8G8R8_Sscaled_Pack32", + "A8B8G8R8_Uint_Pack32", + "A8B8G8R8_Sint_Pack32", + "A8B8G8R8_Srgb_Pack32", + "A2R10G10B10_Unorm_Pack32", + "A2R10G10B10_Snorm_Pack32", + "A2R10G10B10_Uscaled_Pack32", + "A2R10G10B10_Sscaled_Pack32", + "A2R10G10B10_Uint_Pack32", + "A2R10G10B10_Sint_Pack32", + "A2B10G10R10_Unorm_Pack32", + "A2B10G10R10_Snorm_Pack32", + "A2B10G10R10_Uscaled_Pack32", + "A2B10G10R10_Sscaled_Pack32", + "A2B10G10R10_Uint_Pack32", + "A2B10G10R10_Sint_Pack32", + "R16_Unorm", + "R16_Snorm", + "R16_Uscaled", + "R16_Sscaled", + "R16_Uint", + "R16_Sint", + "R16_Sfloat", + "R16G16_Unorm", + "R16G16_Snorm", + "R16G16_Uscaled", + "R16G16_Sscaled", + "R16G16_Uint", + "R16G16_Sint", + "R16G16_Sfloat", + "R16G16B16_Unorm", + "R16G16B16_Snorm", + "R16G16B16_Uscaled", + "R16G16B16_Sscaled", + "R16G16B16_Uint", + "R16G16B16_Sint", + "R16G16B16_Sfloat", + "R16G16B16A16_Unorm", + "R16G16B16A16_Snorm", + "R16G16B16A16_Uscaled", + "R16G16B16A16_Sscaled", + "R16G16B16A16_Uint", + "R16G16B16A16_Sint", + "R16G16B16A16_Sfloat", + "R32_Uint", + "R32_Sint", + "R32_Sfloat", + "R32G32_Uint", + "R32G32_Sint", + "R32G32_Sfloat", + "R32G32B32_Uint", + "R32G32B32_Sint", + "R32G32B32_Sfloat", + "R32G32B32A32_Uint", + "R32G32B32A32_Sint", + "R32G32B32A32_Sfloat", + "R64_Uint", + "R64_Sint", + "R64_Sfloat", + "R64G64_Uint", + "R64G64_Sint", + "R64G64_Sfloat", + "R64G64B64_Uint", + "R64G64B64_Sint", + "R64G64B64_Sfloat", + "R64G64B64A64_Uint", + "R64G64B64A64_Sint", + "R64G64B64A64_Sfloat", + "B10G11R11_Ufloat_Pack32", + "E5B9G9R9_Ufloat_Pack32", + "D16_Unorm", + "X8_D24_Unorm_Pack32", + "D32_Sfloat", + "S8_Uint", + "D16_Unorm_S8_Uint", + "D24_Unorm_S8_Uint", + "D32_Sfloat_S8_Uint", + "Bc1_Rgb_Unorm_Block", + "Bc1_Rgb_Srgb_Block", + "Bc1_Rgba_Unorm_Block", + "Bc1_Rgba_Srgb_Block", + "Bc2_Unorm_Block", + "Bc2_Srgb_Block", + "Bc3_Unorm_Block", + "Bc3_Srgb_Block", + "Bc4_Unorm_Block", + "Bc4_Snorm_Block", + "Bc5_Unorm_Block", + "Bc5_Snorm_Block", + "Bc6H_Ufloat_Block", + "Bc6H_Sfloat_Block", + "Bc7_Unorm_Block", + "Bc7_Srgb_Block", + "Etc2_R8G8B8_Unorm_Block", + "Etc2_R8G8B8_Srgb_Block", + "Etc2_R8G8B8A1_Unorm_Block", + "Etc2_R8G8B8A1_Srgb_Block", + "Etc2_R8G8B8A8_Unorm_Block", + "Etc2_R8G8B8A8_Srgb_Block", + "Eac_R11_Unorm_Block", + "Eac_R11_Snorm_Block", + "Eac_R11G11_Unorm_Block", + "Eac_R11G11_Snorm_Block", + "Astc_4X4_Unorm_Block", + "Astc_4X4_Srgb_Block", + "Astc_5X4_Unorm_Block", + "Astc_5X4_Srgb_Block", + "Astc_5X5_Unorm_Block", + "Astc_5X5_Srgb_Block", + "Astc_6X5_Unorm_Block", + "Astc_6X5_Srgb_Block", + "Astc_6X6_Unorm_Block", + "Astc_6X6_Srgb_Block", + "Astc_8X5_Unorm_Block", + "Astc_8X5_Srgb_Block", + "Astc_8X6_Unorm_Block", + "Astc_8X6_Srgb_Block", + "Astc_8X8_Unorm_Block", + "Astc_8X8_Srgb_Block", + "Astc_10X5_Unorm_Block", + "Astc_10X5_Srgb_Block", + "Astc_10X6_Unorm_Block", + "Astc_10X6_Srgb_Block", + "Astc_10X8_Unorm_Block", + "Astc_10X8_Srgb_Block", + "Astc_10X10_Unorm_Block", + "Astc_10X10_Srgb_Block", + "Astc_12X10_Unorm_Block", + "Astc_12X10_Srgb_Block", + "Astc_12X12_Unorm_Block", + "Astc_12X12_Srgb_Block", + "G8B8G8R8_422_Unorm", + "B8G8R8G8_422_Unorm", + "G8_B8_R8_3Plane_420_Unorm", + "G8_B8R8_2Plane_420_Unorm", + "G8_B8_R8_3Plane_422_Unorm", + "G8_B8R8_2Plane_422_Unorm", + "G8_B8_R8_3Plane_444_Unorm", + "R10X6_Unorm_Pack16", + "R10X6G10X6_Unorm_2Pack16", + "R10X6G10X6B10X6A10X6_Unorm_4Pack16", + "G10X6B10X6G10X6R10X6_422_Unorm_4Pack16", + "B10X6G10X6R10X6G10X6_422_Unorm_4Pack16", + "G10X6_B10X6_R10X6_3Plane_420_Unorm_3Pack16", + "G10X6_B10X6R10X6_2Plane_420_Unorm_3Pack16", + "G10X6_B10X6_R10X6_3Plane_422_Unorm_3Pack16", + "G10X6_B10X6R10X6_2Plane_422_Unorm_3Pack16", + "G10X6_B10X6_R10X6_3Plane_444_Unorm_3Pack16", + "R12X4_Unorm_Pack16", + "R12X4G12X4_Unorm_2Pack16", + "R12X4G12X4B12X4A12X4_Unorm_4Pack16", + "G12X4B12X4G12X4R12X4_422_Unorm_4Pack16", + "B12X4G12X4R12X4G12X4_422_Unorm_4Pack16", + "G12X4_B12X4_R12X4_3Plane_420_Unorm_3Pack16", + "G12X4_B12X4R12X4_2Plane_420_Unorm_3Pack16", + "G12X4_B12X4_R12X4_3Plane_422_Unorm_3Pack16", + "G12X4_B12X4R12X4_2Plane_422_Unorm_3Pack16", + "G12X4_B12X4_R12X4_3Plane_444_Unorm_3Pack16", + "G16B16G16R16_422_Unorm", + "B16G16R16G16_422_Unorm", + "G16_B16_R16_3Plane_420_Unorm", + "G16_B16R16_2Plane_420_Unorm", + "G16_B16_R16_3Plane_422_Unorm", + "G16_B16R16_2Plane_422_Unorm", + "G16_B16_R16_3Plane_444_Unorm", }; -RenderingDevice *RenderingDevice::get_singleton() { - return singleton; -} - -RenderingDevice::ShaderCompileToSPIRVFunction RenderingDevice::compile_to_spirv_function = nullptr; -RenderingDevice::ShaderCacheFunction RenderingDevice::cache_function = nullptr; -RenderingDevice::ShaderSPIRVGetCacheKeyFunction RenderingDevice::get_spirv_cache_key_function = nullptr; - -void RenderingDevice::shader_set_compile_to_spirv_function(ShaderCompileToSPIRVFunction p_function) { - compile_to_spirv_function = p_function; -} - -void RenderingDevice::shader_set_spirv_cache_function(ShaderCacheFunction p_function) { - cache_function = p_function; -} - -void RenderingDevice::shader_set_get_cache_key_function(ShaderSPIRVGetCacheKeyFunction p_function) { - get_spirv_cache_key_function = p_function; -} - -Vector RenderingDevice::shader_compile_spirv_from_source(ShaderStage p_stage, const String &p_source_code, ShaderLanguage p_language, String *r_error, bool p_allow_cache) { - if (p_allow_cache && cache_function) { - Vector cache = cache_function(p_stage, p_source_code, p_language); - if (cache.size()) { - return cache; +/*****************/ +/**** TEXTURE ****/ +/*****************/ + +const uint32_t RenderingDeviceCommons::TEXTURE_SAMPLES_COUNT[TEXTURE_SAMPLES_MAX] = { 1, 2, 4, 8, 16, 32, 64 }; + +uint32_t RenderingDeviceCommons::get_image_format_pixel_size(DataFormat p_format) { + switch (p_format) { + case DATA_FORMAT_R4G4_UNORM_PACK8: + return 1; + case DATA_FORMAT_R4G4B4A4_UNORM_PACK16: + case DATA_FORMAT_B4G4R4A4_UNORM_PACK16: + case DATA_FORMAT_R5G6B5_UNORM_PACK16: + case DATA_FORMAT_B5G6R5_UNORM_PACK16: + case DATA_FORMAT_R5G5B5A1_UNORM_PACK16: + case DATA_FORMAT_B5G5R5A1_UNORM_PACK16: + case DATA_FORMAT_A1R5G5B5_UNORM_PACK16: + return 2; + case DATA_FORMAT_R8_UNORM: + case DATA_FORMAT_R8_SNORM: + case DATA_FORMAT_R8_USCALED: + case DATA_FORMAT_R8_SSCALED: + case DATA_FORMAT_R8_UINT: + case DATA_FORMAT_R8_SINT: + case DATA_FORMAT_R8_SRGB: + return 1; + case DATA_FORMAT_R8G8_UNORM: + case DATA_FORMAT_R8G8_SNORM: + case DATA_FORMAT_R8G8_USCALED: + case DATA_FORMAT_R8G8_SSCALED: + case DATA_FORMAT_R8G8_UINT: + case DATA_FORMAT_R8G8_SINT: + case DATA_FORMAT_R8G8_SRGB: + return 2; + case DATA_FORMAT_R8G8B8_UNORM: + case DATA_FORMAT_R8G8B8_SNORM: + case DATA_FORMAT_R8G8B8_USCALED: + case DATA_FORMAT_R8G8B8_SSCALED: + case DATA_FORMAT_R8G8B8_UINT: + case DATA_FORMAT_R8G8B8_SINT: + case DATA_FORMAT_R8G8B8_SRGB: + case DATA_FORMAT_B8G8R8_UNORM: + case DATA_FORMAT_B8G8R8_SNORM: + case DATA_FORMAT_B8G8R8_USCALED: + case DATA_FORMAT_B8G8R8_SSCALED: + case DATA_FORMAT_B8G8R8_UINT: + case DATA_FORMAT_B8G8R8_SINT: + case DATA_FORMAT_B8G8R8_SRGB: + return 3; + case DATA_FORMAT_R8G8B8A8_UNORM: + case DATA_FORMAT_R8G8B8A8_SNORM: + case DATA_FORMAT_R8G8B8A8_USCALED: + case DATA_FORMAT_R8G8B8A8_SSCALED: + case DATA_FORMAT_R8G8B8A8_UINT: + case DATA_FORMAT_R8G8B8A8_SINT: + case DATA_FORMAT_R8G8B8A8_SRGB: + case DATA_FORMAT_B8G8R8A8_UNORM: + case DATA_FORMAT_B8G8R8A8_SNORM: + case DATA_FORMAT_B8G8R8A8_USCALED: + case DATA_FORMAT_B8G8R8A8_SSCALED: + case DATA_FORMAT_B8G8R8A8_UINT: + case DATA_FORMAT_B8G8R8A8_SINT: + case DATA_FORMAT_B8G8R8A8_SRGB: + return 4; + case DATA_FORMAT_A8B8G8R8_UNORM_PACK32: + case DATA_FORMAT_A8B8G8R8_SNORM_PACK32: + case DATA_FORMAT_A8B8G8R8_USCALED_PACK32: + case DATA_FORMAT_A8B8G8R8_SSCALED_PACK32: + case DATA_FORMAT_A8B8G8R8_UINT_PACK32: + case DATA_FORMAT_A8B8G8R8_SINT_PACK32: + case DATA_FORMAT_A8B8G8R8_SRGB_PACK32: + case DATA_FORMAT_A2R10G10B10_UNORM_PACK32: + case DATA_FORMAT_A2R10G10B10_SNORM_PACK32: + case DATA_FORMAT_A2R10G10B10_USCALED_PACK32: + case DATA_FORMAT_A2R10G10B10_SSCALED_PACK32: + case DATA_FORMAT_A2R10G10B10_UINT_PACK32: + case DATA_FORMAT_A2R10G10B10_SINT_PACK32: + case DATA_FORMAT_A2B10G10R10_UNORM_PACK32: + case DATA_FORMAT_A2B10G10R10_SNORM_PACK32: + case DATA_FORMAT_A2B10G10R10_USCALED_PACK32: + case DATA_FORMAT_A2B10G10R10_SSCALED_PACK32: + case DATA_FORMAT_A2B10G10R10_UINT_PACK32: + case DATA_FORMAT_A2B10G10R10_SINT_PACK32: + return 4; + case DATA_FORMAT_R16_UNORM: + case DATA_FORMAT_R16_SNORM: + case DATA_FORMAT_R16_USCALED: + case DATA_FORMAT_R16_SSCALED: + case DATA_FORMAT_R16_UINT: + case DATA_FORMAT_R16_SINT: + case DATA_FORMAT_R16_SFLOAT: + return 2; + case DATA_FORMAT_R16G16_UNORM: + case DATA_FORMAT_R16G16_SNORM: + case DATA_FORMAT_R16G16_USCALED: + case DATA_FORMAT_R16G16_SSCALED: + case DATA_FORMAT_R16G16_UINT: + case DATA_FORMAT_R16G16_SINT: + case DATA_FORMAT_R16G16_SFLOAT: + return 4; + case DATA_FORMAT_R16G16B16_UNORM: + case DATA_FORMAT_R16G16B16_SNORM: + case DATA_FORMAT_R16G16B16_USCALED: + case DATA_FORMAT_R16G16B16_SSCALED: + case DATA_FORMAT_R16G16B16_UINT: + case DATA_FORMAT_R16G16B16_SINT: + case DATA_FORMAT_R16G16B16_SFLOAT: + return 6; + case DATA_FORMAT_R16G16B16A16_UNORM: + case DATA_FORMAT_R16G16B16A16_SNORM: + case DATA_FORMAT_R16G16B16A16_USCALED: + case DATA_FORMAT_R16G16B16A16_SSCALED: + case DATA_FORMAT_R16G16B16A16_UINT: + case DATA_FORMAT_R16G16B16A16_SINT: + case DATA_FORMAT_R16G16B16A16_SFLOAT: + return 8; + case DATA_FORMAT_R32_UINT: + case DATA_FORMAT_R32_SINT: + case DATA_FORMAT_R32_SFLOAT: + return 4; + case DATA_FORMAT_R32G32_UINT: + case DATA_FORMAT_R32G32_SINT: + case DATA_FORMAT_R32G32_SFLOAT: + return 8; + case DATA_FORMAT_R32G32B32_UINT: + case DATA_FORMAT_R32G32B32_SINT: + case DATA_FORMAT_R32G32B32_SFLOAT: + return 12; + case DATA_FORMAT_R32G32B32A32_UINT: + case DATA_FORMAT_R32G32B32A32_SINT: + case DATA_FORMAT_R32G32B32A32_SFLOAT: + return 16; + case DATA_FORMAT_R64_UINT: + case DATA_FORMAT_R64_SINT: + case DATA_FORMAT_R64_SFLOAT: + return 8; + case DATA_FORMAT_R64G64_UINT: + case DATA_FORMAT_R64G64_SINT: + case DATA_FORMAT_R64G64_SFLOAT: + return 16; + case DATA_FORMAT_R64G64B64_UINT: + case DATA_FORMAT_R64G64B64_SINT: + case DATA_FORMAT_R64G64B64_SFLOAT: + return 24; + case DATA_FORMAT_R64G64B64A64_UINT: + case DATA_FORMAT_R64G64B64A64_SINT: + case DATA_FORMAT_R64G64B64A64_SFLOAT: + return 32; + case DATA_FORMAT_B10G11R11_UFLOAT_PACK32: + case DATA_FORMAT_E5B9G9R9_UFLOAT_PACK32: + return 4; + case DATA_FORMAT_D16_UNORM: + return 2; + case DATA_FORMAT_X8_D24_UNORM_PACK32: + return 4; + case DATA_FORMAT_D32_SFLOAT: + return 4; + case DATA_FORMAT_S8_UINT: + return 1; + case DATA_FORMAT_D16_UNORM_S8_UINT: + return 4; + case DATA_FORMAT_D24_UNORM_S8_UINT: + return 4; + case DATA_FORMAT_D32_SFLOAT_S8_UINT: + return 5; // ? + case DATA_FORMAT_BC1_RGB_UNORM_BLOCK: + case DATA_FORMAT_BC1_RGB_SRGB_BLOCK: + case DATA_FORMAT_BC1_RGBA_UNORM_BLOCK: + case DATA_FORMAT_BC1_RGBA_SRGB_BLOCK: + case DATA_FORMAT_BC2_UNORM_BLOCK: + case DATA_FORMAT_BC2_SRGB_BLOCK: + case DATA_FORMAT_BC3_UNORM_BLOCK: + case DATA_FORMAT_BC3_SRGB_BLOCK: + case DATA_FORMAT_BC4_UNORM_BLOCK: + case DATA_FORMAT_BC4_SNORM_BLOCK: + case DATA_FORMAT_BC5_UNORM_BLOCK: + case DATA_FORMAT_BC5_SNORM_BLOCK: + case DATA_FORMAT_BC6H_UFLOAT_BLOCK: + case DATA_FORMAT_BC6H_SFLOAT_BLOCK: + case DATA_FORMAT_BC7_UNORM_BLOCK: + case DATA_FORMAT_BC7_SRGB_BLOCK: + return 1; + case DATA_FORMAT_ETC2_R8G8B8_UNORM_BLOCK: + case DATA_FORMAT_ETC2_R8G8B8_SRGB_BLOCK: + case DATA_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK: + case DATA_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK: + case DATA_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK: + case DATA_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK: + return 1; + case DATA_FORMAT_EAC_R11_UNORM_BLOCK: + case DATA_FORMAT_EAC_R11_SNORM_BLOCK: + case DATA_FORMAT_EAC_R11G11_UNORM_BLOCK: + case DATA_FORMAT_EAC_R11G11_SNORM_BLOCK: + return 1; + case DATA_FORMAT_ASTC_4x4_UNORM_BLOCK: + case DATA_FORMAT_ASTC_4x4_SRGB_BLOCK: + case DATA_FORMAT_ASTC_5x4_UNORM_BLOCK: + case DATA_FORMAT_ASTC_5x4_SRGB_BLOCK: + case DATA_FORMAT_ASTC_5x5_UNORM_BLOCK: + case DATA_FORMAT_ASTC_5x5_SRGB_BLOCK: + case DATA_FORMAT_ASTC_6x5_UNORM_BLOCK: + case DATA_FORMAT_ASTC_6x5_SRGB_BLOCK: + case DATA_FORMAT_ASTC_6x6_UNORM_BLOCK: + case DATA_FORMAT_ASTC_6x6_SRGB_BLOCK: + case DATA_FORMAT_ASTC_8x5_UNORM_BLOCK: + case DATA_FORMAT_ASTC_8x5_SRGB_BLOCK: + case DATA_FORMAT_ASTC_8x6_UNORM_BLOCK: + case DATA_FORMAT_ASTC_8x6_SRGB_BLOCK: + case DATA_FORMAT_ASTC_8x8_UNORM_BLOCK: + case DATA_FORMAT_ASTC_8x8_SRGB_BLOCK: + case DATA_FORMAT_ASTC_10x5_UNORM_BLOCK: + case DATA_FORMAT_ASTC_10x5_SRGB_BLOCK: + case DATA_FORMAT_ASTC_10x6_UNORM_BLOCK: + case DATA_FORMAT_ASTC_10x6_SRGB_BLOCK: + case DATA_FORMAT_ASTC_10x8_UNORM_BLOCK: + case DATA_FORMAT_ASTC_10x8_SRGB_BLOCK: + case DATA_FORMAT_ASTC_10x10_UNORM_BLOCK: + case DATA_FORMAT_ASTC_10x10_SRGB_BLOCK: + case DATA_FORMAT_ASTC_12x10_UNORM_BLOCK: + case DATA_FORMAT_ASTC_12x10_SRGB_BLOCK: + case DATA_FORMAT_ASTC_12x12_UNORM_BLOCK: + case DATA_FORMAT_ASTC_12x12_SRGB_BLOCK: + return 1; + case DATA_FORMAT_G8B8G8R8_422_UNORM: + case DATA_FORMAT_B8G8R8G8_422_UNORM: + return 4; + case DATA_FORMAT_G8_B8_R8_3PLANE_420_UNORM: + case DATA_FORMAT_G8_B8R8_2PLANE_420_UNORM: + case DATA_FORMAT_G8_B8_R8_3PLANE_422_UNORM: + case DATA_FORMAT_G8_B8R8_2PLANE_422_UNORM: + case DATA_FORMAT_G8_B8_R8_3PLANE_444_UNORM: + return 4; + case DATA_FORMAT_R10X6_UNORM_PACK16: + case DATA_FORMAT_R10X6G10X6_UNORM_2PACK16: + case DATA_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16: + case DATA_FORMAT_G10X6B10X6G10X6R10X6_422_UNORM_4PACK16: + case DATA_FORMAT_B10X6G10X6R10X6G10X6_422_UNORM_4PACK16: + case DATA_FORMAT_G10X6_B10X6_R10X6_3PLANE_420_UNORM_3PACK16: + case DATA_FORMAT_G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16: + case DATA_FORMAT_G10X6_B10X6_R10X6_3PLANE_422_UNORM_3PACK16: + case DATA_FORMAT_G10X6_B10X6R10X6_2PLANE_422_UNORM_3PACK16: + case DATA_FORMAT_G10X6_B10X6_R10X6_3PLANE_444_UNORM_3PACK16: + case DATA_FORMAT_R12X4_UNORM_PACK16: + case DATA_FORMAT_R12X4G12X4_UNORM_2PACK16: + case DATA_FORMAT_R12X4G12X4B12X4A12X4_UNORM_4PACK16: + case DATA_FORMAT_G12X4B12X4G12X4R12X4_422_UNORM_4PACK16: + case DATA_FORMAT_B12X4G12X4R12X4G12X4_422_UNORM_4PACK16: + case DATA_FORMAT_G12X4_B12X4_R12X4_3PLANE_420_UNORM_3PACK16: + case DATA_FORMAT_G12X4_B12X4R12X4_2PLANE_420_UNORM_3PACK16: + case DATA_FORMAT_G12X4_B12X4_R12X4_3PLANE_422_UNORM_3PACK16: + case DATA_FORMAT_G12X4_B12X4R12X4_2PLANE_422_UNORM_3PACK16: + case DATA_FORMAT_G12X4_B12X4_R12X4_3PLANE_444_UNORM_3PACK16: + return 2; + case DATA_FORMAT_G16B16G16R16_422_UNORM: + case DATA_FORMAT_B16G16R16G16_422_UNORM: + case DATA_FORMAT_G16_B16_R16_3PLANE_420_UNORM: + case DATA_FORMAT_G16_B16R16_2PLANE_420_UNORM: + case DATA_FORMAT_G16_B16_R16_3PLANE_422_UNORM: + case DATA_FORMAT_G16_B16R16_2PLANE_422_UNORM: + case DATA_FORMAT_G16_B16_R16_3PLANE_444_UNORM: + return 8; + default: { + ERR_PRINT("Format not handled, bug"); } } - ERR_FAIL_NULL_V(compile_to_spirv_function, Vector()); - - return compile_to_spirv_function(p_stage, p_source_code, p_language, r_error, this); -} - -String RenderingDevice::shader_get_spirv_cache_key() const { - if (get_spirv_cache_key_function) { - return get_spirv_cache_key_function(this); - } - return String(); -} - -RID RenderingDevice::shader_create_from_spirv(const Vector &p_spirv, const String &p_shader_name) { - Vector bytecode = shader_compile_binary_from_spirv(p_spirv, p_shader_name); - ERR_FAIL_COND_V(bytecode.size() == 0, RID()); - return shader_create_from_bytecode(bytecode); -} - -RID RenderingDevice::_texture_create(const Ref &p_format, const Ref &p_view, const TypedArray &p_data) { - ERR_FAIL_COND_V(p_format.is_null(), RID()); - ERR_FAIL_COND_V(p_view.is_null(), RID()); - Vector> data; - for (int i = 0; i < p_data.size(); i++) { - Vector byte_slice = p_data[i]; - ERR_FAIL_COND_V(byte_slice.is_empty(), RID()); - data.push_back(byte_slice); - } - return texture_create(p_format->base, p_view->base, data); -} - -RID RenderingDevice::_texture_create_shared(const Ref &p_view, RID p_with_texture) { - ERR_FAIL_COND_V(p_view.is_null(), RID()); - - return texture_create_shared(p_view->base, p_with_texture); -} - -RID RenderingDevice::_texture_create_shared_from_slice(const Ref &p_view, RID p_with_texture, uint32_t p_layer, uint32_t p_mipmap, uint32_t p_mipmaps, TextureSliceType p_slice_type) { - ERR_FAIL_COND_V(p_view.is_null(), RID()); - - return texture_create_shared_from_slice(p_view->base, p_with_texture, p_layer, p_mipmap, p_mipmaps, p_slice_type); -} - -Ref RenderingDevice::_texture_get_format(RID p_rd_texture) { - Ref rtf; - rtf.instantiate(); - rtf->base = texture_get_format(p_rd_texture); - - return rtf; -} - -RenderingDevice::FramebufferFormatID RenderingDevice::_framebuffer_format_create(const TypedArray &p_attachments, uint32_t p_view_count) { - Vector attachments; - attachments.resize(p_attachments.size()); - - for (int i = 0; i < p_attachments.size(); i++) { - Ref af = p_attachments[i]; - ERR_FAIL_COND_V(af.is_null(), INVALID_FORMAT_ID); - attachments.write[i] = af->base; + return 1; +} + +// https://www.khronos.org/registry/DataFormat/specs/1.1/dataformat.1.1.pdf +void RenderingDeviceCommons::get_compressed_image_format_block_dimensions(DataFormat p_format, uint32_t &r_w, uint32_t &r_h) { + switch (p_format) { + case DATA_FORMAT_BC1_RGB_UNORM_BLOCK: + case DATA_FORMAT_BC1_RGB_SRGB_BLOCK: + case DATA_FORMAT_BC1_RGBA_UNORM_BLOCK: + case DATA_FORMAT_BC1_RGBA_SRGB_BLOCK: + case DATA_FORMAT_BC2_UNORM_BLOCK: + case DATA_FORMAT_BC2_SRGB_BLOCK: + case DATA_FORMAT_BC3_UNORM_BLOCK: + case DATA_FORMAT_BC3_SRGB_BLOCK: + case DATA_FORMAT_BC4_UNORM_BLOCK: + case DATA_FORMAT_BC4_SNORM_BLOCK: + case DATA_FORMAT_BC5_UNORM_BLOCK: + case DATA_FORMAT_BC5_SNORM_BLOCK: + case DATA_FORMAT_BC6H_UFLOAT_BLOCK: + case DATA_FORMAT_BC6H_SFLOAT_BLOCK: + case DATA_FORMAT_BC7_UNORM_BLOCK: + case DATA_FORMAT_BC7_SRGB_BLOCK: + case DATA_FORMAT_ETC2_R8G8B8_UNORM_BLOCK: + case DATA_FORMAT_ETC2_R8G8B8_SRGB_BLOCK: + case DATA_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK: + case DATA_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK: + case DATA_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK: + case DATA_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK: + case DATA_FORMAT_EAC_R11_UNORM_BLOCK: + case DATA_FORMAT_EAC_R11_SNORM_BLOCK: + case DATA_FORMAT_EAC_R11G11_UNORM_BLOCK: + case DATA_FORMAT_EAC_R11G11_SNORM_BLOCK: + case DATA_FORMAT_ASTC_4x4_UNORM_BLOCK: // Again, not sure about astc. + case DATA_FORMAT_ASTC_4x4_SRGB_BLOCK: { + r_w = 4; + r_h = 4; + } break; + case DATA_FORMAT_ASTC_5x4_UNORM_BLOCK: // Unsupported + case DATA_FORMAT_ASTC_5x4_SRGB_BLOCK: + case DATA_FORMAT_ASTC_5x5_UNORM_BLOCK: + case DATA_FORMAT_ASTC_5x5_SRGB_BLOCK: + case DATA_FORMAT_ASTC_6x5_UNORM_BLOCK: + case DATA_FORMAT_ASTC_6x5_SRGB_BLOCK: + case DATA_FORMAT_ASTC_6x6_UNORM_BLOCK: + case DATA_FORMAT_ASTC_6x6_SRGB_BLOCK: + case DATA_FORMAT_ASTC_8x5_UNORM_BLOCK: + case DATA_FORMAT_ASTC_8x5_SRGB_BLOCK: + case DATA_FORMAT_ASTC_8x6_UNORM_BLOCK: + case DATA_FORMAT_ASTC_8x6_SRGB_BLOCK: { + r_w = 4; + r_h = 4; + } break; + case DATA_FORMAT_ASTC_8x8_UNORM_BLOCK: + case DATA_FORMAT_ASTC_8x8_SRGB_BLOCK: { + r_w = 8; + r_h = 8; + } break; + case DATA_FORMAT_ASTC_10x5_UNORM_BLOCK: // Unsupported + case DATA_FORMAT_ASTC_10x5_SRGB_BLOCK: + case DATA_FORMAT_ASTC_10x6_UNORM_BLOCK: + case DATA_FORMAT_ASTC_10x6_SRGB_BLOCK: + case DATA_FORMAT_ASTC_10x8_UNORM_BLOCK: + case DATA_FORMAT_ASTC_10x8_SRGB_BLOCK: + case DATA_FORMAT_ASTC_10x10_UNORM_BLOCK: + case DATA_FORMAT_ASTC_10x10_SRGB_BLOCK: + case DATA_FORMAT_ASTC_12x10_UNORM_BLOCK: + case DATA_FORMAT_ASTC_12x10_SRGB_BLOCK: + case DATA_FORMAT_ASTC_12x12_UNORM_BLOCK: + case DATA_FORMAT_ASTC_12x12_SRGB_BLOCK: + r_w = 4; + r_h = 4; + return; + default: { + r_w = 1; + r_h = 1; + } } - return framebuffer_format_create(attachments, p_view_count); } -RenderingDevice::FramebufferFormatID RenderingDevice::_framebuffer_format_create_multipass(const TypedArray &p_attachments, const TypedArray &p_passes, uint32_t p_view_count) { - Vector attachments; - attachments.resize(p_attachments.size()); - - for (int i = 0; i < p_attachments.size(); i++) { - Ref af = p_attachments[i]; - ERR_FAIL_COND_V(af.is_null(), INVALID_FORMAT_ID); - attachments.write[i] = af->base; +uint32_t RenderingDeviceCommons::get_compressed_image_format_block_byte_size(DataFormat p_format) { + switch (p_format) { + case DATA_FORMAT_BC1_RGB_UNORM_BLOCK: + case DATA_FORMAT_BC1_RGB_SRGB_BLOCK: + case DATA_FORMAT_BC1_RGBA_UNORM_BLOCK: + case DATA_FORMAT_BC1_RGBA_SRGB_BLOCK: + return 8; + case DATA_FORMAT_BC2_UNORM_BLOCK: + case DATA_FORMAT_BC2_SRGB_BLOCK: + return 16; + case DATA_FORMAT_BC3_UNORM_BLOCK: + case DATA_FORMAT_BC3_SRGB_BLOCK: + return 16; + case DATA_FORMAT_BC4_UNORM_BLOCK: + case DATA_FORMAT_BC4_SNORM_BLOCK: + return 8; + case DATA_FORMAT_BC5_UNORM_BLOCK: + case DATA_FORMAT_BC5_SNORM_BLOCK: + return 16; + case DATA_FORMAT_BC6H_UFLOAT_BLOCK: + case DATA_FORMAT_BC6H_SFLOAT_BLOCK: + return 16; + case DATA_FORMAT_BC7_UNORM_BLOCK: + case DATA_FORMAT_BC7_SRGB_BLOCK: + return 16; + case DATA_FORMAT_ETC2_R8G8B8_UNORM_BLOCK: + case DATA_FORMAT_ETC2_R8G8B8_SRGB_BLOCK: + return 8; + case DATA_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK: + case DATA_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK: + return 8; + case DATA_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK: + case DATA_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK: + return 16; + case DATA_FORMAT_EAC_R11_UNORM_BLOCK: + case DATA_FORMAT_EAC_R11_SNORM_BLOCK: + return 8; + case DATA_FORMAT_EAC_R11G11_UNORM_BLOCK: + case DATA_FORMAT_EAC_R11G11_SNORM_BLOCK: + return 16; + case DATA_FORMAT_ASTC_4x4_UNORM_BLOCK: // Again, not sure about astc. + case DATA_FORMAT_ASTC_4x4_SRGB_BLOCK: + case DATA_FORMAT_ASTC_5x4_UNORM_BLOCK: + case DATA_FORMAT_ASTC_5x4_SRGB_BLOCK: + case DATA_FORMAT_ASTC_5x5_UNORM_BLOCK: + case DATA_FORMAT_ASTC_5x5_SRGB_BLOCK: + case DATA_FORMAT_ASTC_6x5_UNORM_BLOCK: + case DATA_FORMAT_ASTC_6x5_SRGB_BLOCK: + case DATA_FORMAT_ASTC_6x6_UNORM_BLOCK: + case DATA_FORMAT_ASTC_6x6_SRGB_BLOCK: + case DATA_FORMAT_ASTC_8x5_UNORM_BLOCK: + case DATA_FORMAT_ASTC_8x5_SRGB_BLOCK: + case DATA_FORMAT_ASTC_8x6_UNORM_BLOCK: + case DATA_FORMAT_ASTC_8x6_SRGB_BLOCK: + case DATA_FORMAT_ASTC_8x8_UNORM_BLOCK: + case DATA_FORMAT_ASTC_8x8_SRGB_BLOCK: + case DATA_FORMAT_ASTC_10x5_UNORM_BLOCK: + case DATA_FORMAT_ASTC_10x5_SRGB_BLOCK: + case DATA_FORMAT_ASTC_10x6_UNORM_BLOCK: + case DATA_FORMAT_ASTC_10x6_SRGB_BLOCK: + case DATA_FORMAT_ASTC_10x8_UNORM_BLOCK: + case DATA_FORMAT_ASTC_10x8_SRGB_BLOCK: + case DATA_FORMAT_ASTC_10x10_UNORM_BLOCK: + case DATA_FORMAT_ASTC_10x10_SRGB_BLOCK: + case DATA_FORMAT_ASTC_12x10_UNORM_BLOCK: + case DATA_FORMAT_ASTC_12x10_SRGB_BLOCK: + case DATA_FORMAT_ASTC_12x12_UNORM_BLOCK: + case DATA_FORMAT_ASTC_12x12_SRGB_BLOCK: + return 16; + default: { + } } - - Vector passes; - for (int i = 0; i < p_passes.size(); i++) { - Ref pass = p_passes[i]; - ERR_CONTINUE(pass.is_null()); - passes.push_back(pass->base); + return 1; +} + +uint32_t RenderingDeviceCommons::get_compressed_image_format_pixel_rshift(DataFormat p_format) { + switch (p_format) { + case DATA_FORMAT_BC1_RGB_UNORM_BLOCK: // These formats are half byte size, so rshift is 1. + case DATA_FORMAT_BC1_RGB_SRGB_BLOCK: + case DATA_FORMAT_BC1_RGBA_UNORM_BLOCK: + case DATA_FORMAT_BC1_RGBA_SRGB_BLOCK: + case DATA_FORMAT_BC4_UNORM_BLOCK: + case DATA_FORMAT_BC4_SNORM_BLOCK: + case DATA_FORMAT_ETC2_R8G8B8_UNORM_BLOCK: + case DATA_FORMAT_ETC2_R8G8B8_SRGB_BLOCK: + case DATA_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK: + case DATA_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK: + case DATA_FORMAT_EAC_R11_UNORM_BLOCK: + case DATA_FORMAT_EAC_R11_SNORM_BLOCK: + return 1; + case DATA_FORMAT_ASTC_8x8_SRGB_BLOCK: + case DATA_FORMAT_ASTC_8x8_UNORM_BLOCK: { + return 2; + } + default: { + } } - return framebuffer_format_create_multipass(attachments, passes, p_view_count); -} - -RID RenderingDevice::_framebuffer_create(const TypedArray &p_textures, FramebufferFormatID p_format_check, uint32_t p_view_count) { - Vector textures = Variant(p_textures); - return framebuffer_create(textures, p_format_check, p_view_count); -} - -RID RenderingDevice::_framebuffer_create_multipass(const TypedArray &p_textures, const TypedArray &p_passes, FramebufferFormatID p_format_check, uint32_t p_view_count) { - Vector textures = Variant(p_textures); - Vector passes; - for (int i = 0; i < p_passes.size(); i++) { - Ref pass = p_passes[i]; - ERR_CONTINUE(pass.is_null()); - passes.push_back(pass->base); - } - return framebuffer_create_multipass(textures, passes, p_format_check, p_view_count); + return 0; } -RID RenderingDevice::_sampler_create(const Ref &p_state) { - ERR_FAIL_COND_V(p_state.is_null(), RID()); +uint32_t RenderingDeviceCommons::get_image_format_required_size(DataFormat p_format, uint32_t p_width, uint32_t p_height, uint32_t p_depth, uint32_t p_mipmaps, uint32_t *r_blockw, uint32_t *r_blockh, uint32_t *r_depth) { + ERR_FAIL_COND_V(p_mipmaps == 0, 0); + uint32_t w = p_width; + uint32_t h = p_height; + uint32_t d = p_depth; - return sampler_create(p_state->base); -} + uint32_t size = 0; -RenderingDevice::VertexFormatID RenderingDevice::_vertex_format_create(const TypedArray &p_vertex_formats) { - Vector descriptions; - descriptions.resize(p_vertex_formats.size()); + uint32_t pixel_size = get_image_format_pixel_size(p_format); + uint32_t pixel_rshift = get_compressed_image_format_pixel_rshift(p_format); + uint32_t blockw, blockh; + get_compressed_image_format_block_dimensions(p_format, blockw, blockh); - for (int i = 0; i < p_vertex_formats.size(); i++) { - Ref af = p_vertex_formats[i]; - ERR_FAIL_COND_V(af.is_null(), INVALID_FORMAT_ID); - descriptions.write[i] = af->base; - } - return vertex_format_create(descriptions); -} + for (uint32_t i = 0; i < p_mipmaps; i++) { + uint32_t bw = w % blockw != 0 ? w + (blockw - w % blockw) : w; + uint32_t bh = h % blockh != 0 ? h + (blockh - h % blockh) : h; -RID RenderingDevice::_vertex_array_create(uint32_t p_vertex_count, VertexFormatID p_vertex_format, const TypedArray &p_src_buffers, const Vector &p_offsets) { - Vector buffers = Variant(p_src_buffers); + uint32_t s = bw * bh; - Vector offsets; - offsets.resize(p_offsets.size()); - for (int i = 0; i < p_offsets.size(); i++) { - offsets.write[i] = p_offsets[i]; + s *= pixel_size; + s >>= pixel_rshift; + size += s * d; + if (r_blockw) { + *r_blockw = bw; + } + if (r_blockh) { + *r_blockh = bh; + } + if (r_depth) { + *r_depth = d; + } + w = MAX(blockw, w >> 1); + h = MAX(blockh, h >> 1); + d = MAX(1u, d >> 1); } - return vertex_array_create(p_vertex_count, p_vertex_format, buffers, offsets); + return size; } -Ref RenderingDevice::_shader_compile_spirv_from_source(const Ref &p_source, bool p_allow_cache) { - ERR_FAIL_COND_V(p_source.is_null(), Ref()); +uint32_t RenderingDeviceCommons::get_image_required_mipmaps(uint32_t p_width, uint32_t p_height, uint32_t p_depth) { + // Formats and block size don't really matter here since they can all go down to 1px (even if block is larger). + uint32_t w = p_width; + uint32_t h = p_height; + uint32_t d = p_depth; - Ref bytecode; - bytecode.instantiate(); - for (int i = 0; i < RD::SHADER_STAGE_MAX; i++) { - String error; + uint32_t mipmaps = 1; - ShaderStage stage = ShaderStage(i); - String source = p_source->get_stage_source(stage); - - if (!source.is_empty()) { - Vector spirv = shader_compile_spirv_from_source(stage, source, p_source->get_language(), &error, p_allow_cache); - bytecode->set_stage_bytecode(stage, spirv); - bytecode->set_stage_compile_error(stage, error); + while (true) { + if (w == 1 && h == 1 && d == 1) { + break; } - } - return bytecode; -} -Vector RenderingDevice::_shader_compile_binary_from_spirv(const Ref &p_spirv, const String &p_shader_name) { - ERR_FAIL_COND_V(p_spirv.is_null(), Vector()); + w = MAX(1u, w >> 1); + h = MAX(1u, h >> 1); + d = MAX(1u, d >> 1); - Vector stage_data; - for (int i = 0; i < RD::SHADER_STAGE_MAX; i++) { - ShaderStage stage = ShaderStage(i); - ShaderStageSPIRVData sd; - sd.shader_stage = stage; - String error = p_spirv->get_stage_compile_error(stage); - ERR_FAIL_COND_V_MSG(!error.is_empty(), Vector(), "Can't create a shader from an errored bytecode. Check errors in source bytecode."); - sd.spir_v = p_spirv->get_stage_bytecode(stage); - if (sd.spir_v.is_empty()) { - continue; - } - stage_data.push_back(sd); + mipmaps++; } - return shader_compile_binary_from_spirv(stage_data, p_shader_name); + return mipmaps; } -RID RenderingDevice::_shader_create_from_spirv(const Ref &p_spirv, const String &p_shader_name) { - ERR_FAIL_COND_V(p_spirv.is_null(), RID()); - - Vector stage_data; - for (int i = 0; i < RD::SHADER_STAGE_MAX; i++) { - ShaderStage stage = ShaderStage(i); - ShaderStageSPIRVData sd; - sd.shader_stage = stage; - String error = p_spirv->get_stage_compile_error(stage); - ERR_FAIL_COND_V_MSG(!error.is_empty(), RID(), "Can't create a shader from an errored bytecode. Check errors in source bytecode."); - sd.spir_v = p_spirv->get_stage_bytecode(stage); - if (sd.spir_v.is_empty()) { - continue; +bool RenderingDeviceCommons::format_has_stencil(DataFormat p_format) { + switch (p_format) { + case DATA_FORMAT_S8_UINT: + case DATA_FORMAT_D16_UNORM_S8_UINT: + case DATA_FORMAT_D24_UNORM_S8_UINT: + case DATA_FORMAT_D32_SFLOAT_S8_UINT: { + return true; } - stage_data.push_back(sd); - } - return shader_create_from_spirv(stage_data); -} - -RID RenderingDevice::_uniform_set_create(const TypedArray &p_uniforms, RID p_shader, uint32_t p_shader_set) { - Vector uniforms; - uniforms.resize(p_uniforms.size()); - for (int i = 0; i < p_uniforms.size(); i++) { - Ref uniform = p_uniforms[i]; - ERR_FAIL_COND_V(!uniform.is_valid(), RID()); - uniforms.write[i] = uniform->base; - } - return uniform_set_create(uniforms, p_shader, p_shader_set); -} - -Error RenderingDevice::_buffer_update(RID p_buffer, uint32_t p_offset, uint32_t p_size, const Vector &p_data, BitField p_post_barrier) { - return buffer_update(p_buffer, p_offset, p_size, p_data.ptr(), p_post_barrier); -} - -static Vector _get_spec_constants(const TypedArray &p_constants) { - Vector ret; - ret.resize(p_constants.size()); - for (int i = 0; i < p_constants.size(); i++) { - Ref c = p_constants[i]; - ERR_CONTINUE(c.is_null()); - RenderingDevice::PipelineSpecializationConstant &sc = ret.write[i]; - Variant value = c->get_value(); - switch (value.get_type()) { - case Variant::BOOL: { - sc.type = RD::PIPELINE_SPECIALIZATION_CONSTANT_TYPE_BOOL; - sc.bool_value = value; - } break; - case Variant::INT: { - sc.type = RD::PIPELINE_SPECIALIZATION_CONSTANT_TYPE_INT; - sc.int_value = value; - } break; - case Variant::FLOAT: { - sc.type = RD::PIPELINE_SPECIALIZATION_CONSTANT_TYPE_FLOAT; - sc.float_value = value; - } break; - default: { - } + default: { } - - sc.constant_id = c->get_constant_id(); } - return ret; + return false; } -RID RenderingDevice::_render_pipeline_create(RID p_shader, FramebufferFormatID p_framebuffer_format, VertexFormatID p_vertex_format, RenderPrimitive p_render_primitive, const Ref &p_rasterization_state, const Ref &p_multisample_state, const Ref &p_depth_stencil_state, const Ref &p_blend_state, BitField p_dynamic_state_flags, uint32_t p_for_render_pass, const TypedArray &p_specialization_constants) { - PipelineRasterizationState rasterization_state; - if (p_rasterization_state.is_valid()) { - rasterization_state = p_rasterization_state->base; - } - - PipelineMultisampleState multisample_state; - if (p_multisample_state.is_valid()) { - multisample_state = p_multisample_state->base; - for (int i = 0; i < p_multisample_state->sample_masks.size(); i++) { - int64_t mask = p_multisample_state->sample_masks[i]; - multisample_state.sample_mask.push_back(mask); +uint32_t RenderingDeviceCommons::format_get_plane_count(DataFormat p_format) { + uint32_t planes = 1; + switch (p_format) { + case DATA_FORMAT_D16_UNORM_S8_UINT: + case DATA_FORMAT_D24_UNORM_S8_UINT: + case DATA_FORMAT_D32_SFLOAT_S8_UINT: { + planes = 2; + break; } - } - - PipelineDepthStencilState depth_stencil_state; - if (p_depth_stencil_state.is_valid()) { - depth_stencil_state = p_depth_stencil_state->base; - } - - PipelineColorBlendState color_blend_state; - if (p_blend_state.is_valid()) { - color_blend_state = p_blend_state->base; - for (int i = 0; i < p_blend_state->attachments.size(); i++) { - Ref attachment = p_blend_state->attachments[i]; - if (attachment.is_valid()) { - color_blend_state.attachments.push_back(attachment->base); - } + default: { } } - - return render_pipeline_create(p_shader, p_framebuffer_format, p_vertex_format, p_render_primitive, rasterization_state, multisample_state, depth_stencil_state, color_blend_state, p_dynamic_state_flags, p_for_render_pass, _get_spec_constants(p_specialization_constants)); -} - -RID RenderingDevice::_compute_pipeline_create(RID p_shader, const TypedArray &p_specialization_constants = TypedArray()) { - return compute_pipeline_create(p_shader, _get_spec_constants(p_specialization_constants)); -} - -RenderingDevice::DrawListID RenderingDevice::_draw_list_begin(RID p_framebuffer, InitialAction p_initial_color_action, FinalAction p_final_color_action, InitialAction p_initial_depth_action, FinalAction p_final_depth_action, const Vector &p_clear_color_values, float p_clear_depth, uint32_t p_clear_stencil, const Rect2 &p_region, const TypedArray &p_storage_textures) { - Vector stextures; - for (int i = 0; i < p_storage_textures.size(); i++) { - stextures.push_back(p_storage_textures[i]); - } - return draw_list_begin(p_framebuffer, p_initial_color_action, p_final_color_action, p_initial_depth_action, p_final_depth_action, p_clear_color_values, p_clear_depth, p_clear_stencil, p_region, stextures); -} - -Vector RenderingDevice::_draw_list_begin_split(RID p_framebuffer, uint32_t p_splits, InitialAction p_initial_color_action, FinalAction p_final_color_action, InitialAction p_initial_depth_action, FinalAction p_final_depth_action, const Vector &p_clear_color_values, float p_clear_depth, uint32_t p_clear_stencil, const Rect2 &p_region, const TypedArray &p_storage_textures) { - Vector splits; - splits.resize(p_splits); - Vector stextures; - for (int i = 0; i < p_storage_textures.size(); i++) { - stextures.push_back(p_storage_textures[i]); - } - draw_list_begin_split(p_framebuffer, p_splits, splits.ptrw(), p_initial_color_action, p_final_color_action, p_initial_depth_action, p_final_depth_action, p_clear_color_values, p_clear_depth, p_clear_stencil, p_region, stextures); - - Vector split_ids; - split_ids.resize(splits.size()); - for (int i = 0; i < splits.size(); i++) { - split_ids.write[i] = splits[i]; - } - - return split_ids; -} - -Vector RenderingDevice::_draw_list_switch_to_next_pass_split(uint32_t p_splits) { - Vector splits; - splits.resize(p_splits); - - Error err = draw_list_switch_to_next_pass_split(p_splits, splits.ptrw()); - ERR_FAIL_COND_V(err != OK, Vector()); - - Vector split_ids; - split_ids.resize(splits.size()); - for (int i = 0; i < splits.size(); i++) { - split_ids.write[i] = splits[i]; - } - - return split_ids; -} - -void RenderingDevice::_draw_list_set_push_constant(DrawListID p_list, const Vector &p_data, uint32_t p_data_size) { - ERR_FAIL_COND((uint32_t)p_data.size() > p_data_size); - draw_list_set_push_constant(p_list, p_data.ptr(), p_data_size); -} - -void RenderingDevice::_compute_list_set_push_constant(ComputeListID p_list, const Vector &p_data, uint32_t p_data_size) { - ERR_FAIL_COND((uint32_t)p_data.size() > p_data_size); - compute_list_set_push_constant(p_list, p_data.ptr(), p_data_size); + DEV_ASSERT(planes <= MAX_IMAGE_FORMAT_PLANES); + return planes; } -Error RenderingDevice::_reflect_spirv(const Vector &p_spirv, SpirvReflectionData &r_reflection_data) { - r_reflection_data = {}; - - for (int i = 0; i < p_spirv.size(); i++) { - ShaderStage stage = p_spirv[i].shader_stage; - ShaderStage stage_flag = (ShaderStage)(1 << p_spirv[i].shader_stage); - - if (p_spirv[i].shader_stage == SHADER_STAGE_COMPUTE) { - r_reflection_data.is_compute = true; - ERR_FAIL_COND_V_MSG(p_spirv.size() != 1, FAILED, - "Compute shaders can only receive one stage, dedicated to compute."); - } - ERR_FAIL_COND_V_MSG(r_reflection_data.stages_mask.has_flag(stage_flag), FAILED, - "Stage " + String(shader_stage_names[p_spirv[i].shader_stage]) + " submitted more than once."); - - { - SpvReflectShaderModule module; - const uint8_t *spirv = p_spirv[i].spir_v.ptr(); - SpvReflectResult result = spvReflectCreateShaderModule(p_spirv[i].spir_v.size(), spirv, &module); - ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, FAILED, - "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_spirv[i].shader_stage]) + "' failed parsing shader."); - - if (r_reflection_data.is_compute) { - r_reflection_data.compute_local_size[0] = module.entry_points->local_size.x; - r_reflection_data.compute_local_size[1] = module.entry_points->local_size.y; - r_reflection_data.compute_local_size[2] = module.entry_points->local_size.z; - } - uint32_t binding_count = 0; - result = spvReflectEnumerateDescriptorBindings(&module, &binding_count, nullptr); - ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, FAILED, - "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_spirv[i].shader_stage]) + "' failed enumerating descriptor bindings."); - - if (binding_count > 0) { - // Parse bindings. - - Vector bindings; - bindings.resize(binding_count); - result = spvReflectEnumerateDescriptorBindings(&module, &binding_count, bindings.ptrw()); - - ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, FAILED, - "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_spirv[i].shader_stage]) + "' failed getting descriptor bindings."); - - for (uint32_t j = 0; j < binding_count; j++) { - const SpvReflectDescriptorBinding &binding = *bindings[j]; - - SpirvReflectionData::Uniform info{}; - - bool need_array_dimensions = false; - bool need_block_size = false; - bool may_be_writable = false; - - switch (binding.descriptor_type) { - case SPV_REFLECT_DESCRIPTOR_TYPE_SAMPLER: { - info.type = UNIFORM_TYPE_SAMPLER; - need_array_dimensions = true; - } break; - case SPV_REFLECT_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER: { - info.type = UNIFORM_TYPE_SAMPLER_WITH_TEXTURE; - need_array_dimensions = true; - } break; - case SPV_REFLECT_DESCRIPTOR_TYPE_SAMPLED_IMAGE: { - info.type = UNIFORM_TYPE_TEXTURE; - need_array_dimensions = true; - } break; - case SPV_REFLECT_DESCRIPTOR_TYPE_STORAGE_IMAGE: { - info.type = UNIFORM_TYPE_IMAGE; - need_array_dimensions = true; - may_be_writable = true; - } break; - case SPV_REFLECT_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER: { - info.type = UNIFORM_TYPE_TEXTURE_BUFFER; - need_array_dimensions = true; - } break; - case SPV_REFLECT_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER: { - info.type = UNIFORM_TYPE_IMAGE_BUFFER; - need_array_dimensions = true; - may_be_writable = true; - } break; - case SPV_REFLECT_DESCRIPTOR_TYPE_UNIFORM_BUFFER: { - info.type = UNIFORM_TYPE_UNIFORM_BUFFER; - need_block_size = true; - } break; - case SPV_REFLECT_DESCRIPTOR_TYPE_STORAGE_BUFFER: { - info.type = UNIFORM_TYPE_STORAGE_BUFFER; - need_block_size = true; - may_be_writable = true; - } break; - case SPV_REFLECT_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC: { - ERR_PRINT("Dynamic uniform buffer not supported."); - continue; - } break; - case SPV_REFLECT_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC: { - ERR_PRINT("Dynamic storage buffer not supported."); - continue; - } break; - case SPV_REFLECT_DESCRIPTOR_TYPE_INPUT_ATTACHMENT: { - info.type = UNIFORM_TYPE_INPUT_ATTACHMENT; - need_array_dimensions = true; - } break; - case SPV_REFLECT_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR: { - ERR_PRINT("Acceleration structure not supported."); - continue; - } break; - } - - if (need_array_dimensions) { - if (binding.array.dims_count == 0) { - info.length = 1; - } else { - for (uint32_t k = 0; k < binding.array.dims_count; k++) { - if (k == 0) { - info.length = binding.array.dims[0]; - } else { - info.length *= binding.array.dims[k]; - } - } - } - - } else if (need_block_size) { - info.length = binding.block.size; - } else { - info.length = 0; - } +/*****************/ +/**** SAMPLER ****/ +/*****************/ - if (may_be_writable) { - info.writable = !(binding.type_description->decoration_flags & SPV_REFLECT_DECORATION_NON_WRITABLE) && !(binding.block.decoration_flags & SPV_REFLECT_DECORATION_NON_WRITABLE); - } else { - info.writable = false; - } - - info.binding = binding.binding; - uint32_t set = binding.set; - - ERR_FAIL_COND_V_MSG(set >= MAX_UNIFORM_SETS, FAILED, - "On shader stage '" + String(shader_stage_names[stage]) + "', uniform '" + binding.name + "' uses a set (" + itos(set) + ") index larger than what is supported (" + itos(MAX_UNIFORM_SETS) + ")."); - - if (set < (uint32_t)r_reflection_data.uniforms.size()) { - // Check if this already exists. - bool exists = false; - for (int k = 0; k < r_reflection_data.uniforms[set].size(); k++) { - if (r_reflection_data.uniforms[set][k].binding == (uint32_t)info.binding) { - // Already exists, verify that it's the same type. - ERR_FAIL_COND_V_MSG(r_reflection_data.uniforms[set][k].type != info.type, FAILED, - "On shader stage '" + String(shader_stage_names[stage]) + "', uniform '" + binding.name + "' trying to reuse location for set=" + itos(set) + ", binding=" + itos(info.binding) + " with different uniform type."); - - // Also, verify that it's the same size. - ERR_FAIL_COND_V_MSG(r_reflection_data.uniforms[set][k].length != info.length, FAILED, - "On shader stage '" + String(shader_stage_names[stage]) + "', uniform '" + binding.name + "' trying to reuse location for set=" + itos(set) + ", binding=" + itos(info.binding) + " with different uniform size."); - - // Also, verify that it has the same writability. - ERR_FAIL_COND_V_MSG(r_reflection_data.uniforms[set][k].writable != info.writable, FAILED, - "On shader stage '" + String(shader_stage_names[stage]) + "', uniform '" + binding.name + "' trying to reuse location for set=" + itos(set) + ", binding=" + itos(info.binding) + " with different writability."); - - // Just append stage mask and return. - r_reflection_data.uniforms.write[set].write[k].stages_mask.set_flag(stage_flag); - exists = true; - break; - } - } - - if (exists) { - continue; // Merged. - } - } - - info.stages_mask.set_flag(stage_flag); - - if (set >= (uint32_t)r_reflection_data.uniforms.size()) { - r_reflection_data.uniforms.resize(set + 1); - } - - r_reflection_data.uniforms.write[set].push_back(info); - } - } - - { - // Specialization constants. - - uint32_t sc_count = 0; - result = spvReflectEnumerateSpecializationConstants(&module, &sc_count, nullptr); - ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, FAILED, - "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_spirv[i].shader_stage]) + "' failed enumerating specialization constants."); - - if (sc_count) { - Vector spec_constants; - spec_constants.resize(sc_count); - - result = spvReflectEnumerateSpecializationConstants(&module, &sc_count, spec_constants.ptrw()); - ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, FAILED, - "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_spirv[i].shader_stage]) + "' failed obtaining specialization constants."); - - for (uint32_t j = 0; j < sc_count; j++) { - int32_t existing = -1; - SpirvReflectionData::SpecializationConstant sconst{}; - SpvReflectSpecializationConstant *spc = spec_constants[j]; - - sconst.constant_id = spc->constant_id; - sconst.int_value = 0; // Clear previous value JIC. - switch (spc->constant_type) { - case SPV_REFLECT_SPECIALIZATION_CONSTANT_BOOL: { - sconst.type = PIPELINE_SPECIALIZATION_CONSTANT_TYPE_BOOL; - sconst.bool_value = spc->default_value.int_bool_value != 0; - } break; - case SPV_REFLECT_SPECIALIZATION_CONSTANT_INT: { - sconst.type = PIPELINE_SPECIALIZATION_CONSTANT_TYPE_INT; - sconst.int_value = spc->default_value.int_bool_value; - } break; - case SPV_REFLECT_SPECIALIZATION_CONSTANT_FLOAT: { - sconst.type = PIPELINE_SPECIALIZATION_CONSTANT_TYPE_FLOAT; - sconst.float_value = spc->default_value.float_value; - } break; - } - sconst.stages_mask.set_flag(stage_flag); - - for (int k = 0; k < r_reflection_data.specialization_constants.size(); k++) { - if (r_reflection_data.specialization_constants[k].constant_id == sconst.constant_id) { - ERR_FAIL_COND_V_MSG(r_reflection_data.specialization_constants[k].type != sconst.type, FAILED, "More than one specialization constant used for id (" + itos(sconst.constant_id) + "), but their types differ."); - ERR_FAIL_COND_V_MSG(r_reflection_data.specialization_constants[k].int_value != sconst.int_value, FAILED, "More than one specialization constant used for id (" + itos(sconst.constant_id) + "), but their default values differ."); - existing = k; - break; - } - } - - if (existing > 0) { - r_reflection_data.specialization_constants.write[existing].stages_mask.set_flag(stage_flag); - } else { - r_reflection_data.specialization_constants.push_back(sconst); - } - } - } - } - - if (stage == SHADER_STAGE_VERTEX) { - uint32_t iv_count = 0; - result = spvReflectEnumerateInputVariables(&module, &iv_count, nullptr); - ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, FAILED, - "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_spirv[i].shader_stage]) + "' failed enumerating input variables."); - - if (iv_count) { - Vector input_vars; - input_vars.resize(iv_count); - - result = spvReflectEnumerateInputVariables(&module, &iv_count, input_vars.ptrw()); - ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, FAILED, - "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_spirv[i].shader_stage]) + "' failed obtaining input variables."); - - for (uint32_t j = 0; j < iv_count; j++) { - if (input_vars[j] && input_vars[j]->decoration_flags == 0) { // Regular input. - r_reflection_data.vertex_input_mask |= (1ULL << uint32_t(input_vars[j]->location)); - } - } - } - } - - if (stage == SHADER_STAGE_FRAGMENT) { - uint32_t ov_count = 0; - result = spvReflectEnumerateOutputVariables(&module, &ov_count, nullptr); - ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, FAILED, - "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_spirv[i].shader_stage]) + "' failed enumerating output variables."); - - if (ov_count) { - Vector output_vars; - output_vars.resize(ov_count); - - result = spvReflectEnumerateOutputVariables(&module, &ov_count, output_vars.ptrw()); - ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, FAILED, - "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_spirv[i].shader_stage]) + "' failed obtaining output variables."); - - for (uint32_t j = 0; j < ov_count; j++) { - const SpvReflectInterfaceVariable *refvar = output_vars[j]; - if (refvar != nullptr && refvar->built_in != SpvBuiltInFragDepth) { - r_reflection_data.fragment_output_mask |= 1 << refvar->location; - } - } - } - } - - uint32_t pc_count = 0; - result = spvReflectEnumeratePushConstantBlocks(&module, &pc_count, nullptr); - ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, FAILED, - "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_spirv[i].shader_stage]) + "' failed enumerating push constants."); - - if (pc_count) { - ERR_FAIL_COND_V_MSG(pc_count > 1, FAILED, - "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_spirv[i].shader_stage]) + "': Only one push constant is supported, which should be the same across shader stages."); - - Vector pconstants; - pconstants.resize(pc_count); - result = spvReflectEnumeratePushConstantBlocks(&module, &pc_count, pconstants.ptrw()); - ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, FAILED, - "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_spirv[i].shader_stage]) + "' failed obtaining push constants."); -#if 0 - if (pconstants[0] == nullptr) { - Ref f = FileAccess::open("res://popo.spv", FileAccess::WRITE); - f->store_buffer((const uint8_t *)&SpirV[0], SpirV.size() * sizeof(uint32_t)); - } -#endif - - ERR_FAIL_COND_V_MSG(r_reflection_data.push_constant_size && r_reflection_data.push_constant_size != pconstants[0]->size, FAILED, - "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_spirv[i].shader_stage]) + "': Push constant block must be the same across shader stages."); - - r_reflection_data.push_constant_size = pconstants[0]->size; - r_reflection_data.push_constant_stages_mask.set_flag(stage_flag); - - //print_line("Stage: " + String(shader_stage_names[stage]) + " push constant of size=" + itos(push_constant.push_constant_size)); - } - - // Destroy the reflection data when no longer required. - spvReflectDestroyShaderModule(&module); - } +const Color RenderingDeviceCommons::SAMPLER_BORDER_COLOR_VALUE[SAMPLER_BORDER_COLOR_MAX] = { + Color(0, 0, 0, 0), + Color(0, 0, 0, 0), + Color(0, 0, 0, 1), + Color(0, 0, 0, 1), + Color(1, 1, 1, 1), + Color(1, 1, 1, 1), +}; - r_reflection_data.stages_mask.set_flag(stage_flag); +/**********************/ +/**** VERTEX ARRAY ****/ +/**********************/ + +uint32_t RenderingDeviceCommons::get_format_vertex_size(DataFormat p_format) { + switch (p_format) { + case DATA_FORMAT_R8_UNORM: + case DATA_FORMAT_R8_SNORM: + case DATA_FORMAT_R8_UINT: + case DATA_FORMAT_R8_SINT: + case DATA_FORMAT_R8G8_UNORM: + case DATA_FORMAT_R8G8_SNORM: + case DATA_FORMAT_R8G8_UINT: + case DATA_FORMAT_R8G8_SINT: + case DATA_FORMAT_R8G8B8_UNORM: + case DATA_FORMAT_R8G8B8_SNORM: + case DATA_FORMAT_R8G8B8_UINT: + case DATA_FORMAT_R8G8B8_SINT: + case DATA_FORMAT_B8G8R8_UNORM: + case DATA_FORMAT_B8G8R8_SNORM: + case DATA_FORMAT_B8G8R8_UINT: + case DATA_FORMAT_B8G8R8_SINT: + case DATA_FORMAT_R8G8B8A8_UNORM: + case DATA_FORMAT_R8G8B8A8_SNORM: + case DATA_FORMAT_R8G8B8A8_UINT: + case DATA_FORMAT_R8G8B8A8_SINT: + case DATA_FORMAT_B8G8R8A8_UNORM: + case DATA_FORMAT_B8G8R8A8_SNORM: + case DATA_FORMAT_B8G8R8A8_UINT: + case DATA_FORMAT_B8G8R8A8_SINT: + case DATA_FORMAT_A2B10G10R10_UNORM_PACK32: + return 4; + case DATA_FORMAT_R16_UNORM: + case DATA_FORMAT_R16_SNORM: + case DATA_FORMAT_R16_UINT: + case DATA_FORMAT_R16_SINT: + case DATA_FORMAT_R16_SFLOAT: + return 4; + case DATA_FORMAT_R16G16_UNORM: + case DATA_FORMAT_R16G16_SNORM: + case DATA_FORMAT_R16G16_UINT: + case DATA_FORMAT_R16G16_SINT: + case DATA_FORMAT_R16G16_SFLOAT: + return 4; + case DATA_FORMAT_R16G16B16_UNORM: + case DATA_FORMAT_R16G16B16_SNORM: + case DATA_FORMAT_R16G16B16_UINT: + case DATA_FORMAT_R16G16B16_SINT: + case DATA_FORMAT_R16G16B16_SFLOAT: + return 8; + case DATA_FORMAT_R16G16B16A16_UNORM: + case DATA_FORMAT_R16G16B16A16_SNORM: + case DATA_FORMAT_R16G16B16A16_UINT: + case DATA_FORMAT_R16G16B16A16_SINT: + case DATA_FORMAT_R16G16B16A16_SFLOAT: + return 8; + case DATA_FORMAT_R32_UINT: + case DATA_FORMAT_R32_SINT: + case DATA_FORMAT_R32_SFLOAT: + return 4; + case DATA_FORMAT_R32G32_UINT: + case DATA_FORMAT_R32G32_SINT: + case DATA_FORMAT_R32G32_SFLOAT: + return 8; + case DATA_FORMAT_R32G32B32_UINT: + case DATA_FORMAT_R32G32B32_SINT: + case DATA_FORMAT_R32G32B32_SFLOAT: + return 12; + case DATA_FORMAT_R32G32B32A32_UINT: + case DATA_FORMAT_R32G32B32A32_SINT: + case DATA_FORMAT_R32G32B32A32_SFLOAT: + return 16; + case DATA_FORMAT_R64_UINT: + case DATA_FORMAT_R64_SINT: + case DATA_FORMAT_R64_SFLOAT: + return 8; + case DATA_FORMAT_R64G64_UINT: + case DATA_FORMAT_R64G64_SINT: + case DATA_FORMAT_R64G64_SFLOAT: + return 16; + case DATA_FORMAT_R64G64B64_UINT: + case DATA_FORMAT_R64G64B64_SINT: + case DATA_FORMAT_R64G64B64_SFLOAT: + return 24; + case DATA_FORMAT_R64G64B64A64_UINT: + case DATA_FORMAT_R64G64B64A64_SINT: + case DATA_FORMAT_R64G64B64A64_SFLOAT: + return 32; + default: + return 0; } - - return OK; } -void RenderingDevice::_bind_methods() { - ClassDB::bind_method(D_METHOD("texture_create", "format", "view", "data"), &RenderingDevice::_texture_create, DEFVAL(Array())); - ClassDB::bind_method(D_METHOD("texture_create_shared", "view", "with_texture"), &RenderingDevice::_texture_create_shared); - ClassDB::bind_method(D_METHOD("texture_create_shared_from_slice", "view", "with_texture", "layer", "mipmap", "mipmaps", "slice_type"), &RenderingDevice::_texture_create_shared_from_slice, DEFVAL(1), DEFVAL(TEXTURE_SLICE_2D)); - ClassDB::bind_method(D_METHOD("texture_create_from_extension", "type", "format", "samples", "usage_flags", "image", "width", "height", "depth", "layers"), &RenderingDevice::texture_create_from_extension); - - ClassDB::bind_method(D_METHOD("texture_update", "texture", "layer", "data", "post_barrier"), &RenderingDevice::texture_update, DEFVAL(BARRIER_MASK_ALL_BARRIERS)); - ClassDB::bind_method(D_METHOD("texture_get_data", "texture", "layer"), &RenderingDevice::texture_get_data); - - ClassDB::bind_method(D_METHOD("texture_is_format_supported_for_usage", "format", "usage_flags"), &RenderingDevice::texture_is_format_supported_for_usage); - - ClassDB::bind_method(D_METHOD("texture_is_shared", "texture"), &RenderingDevice::texture_is_shared); - ClassDB::bind_method(D_METHOD("texture_is_valid", "texture"), &RenderingDevice::texture_is_valid); - - ClassDB::bind_method(D_METHOD("texture_copy", "from_texture", "to_texture", "from_pos", "to_pos", "size", "src_mipmap", "dst_mipmap", "src_layer", "dst_layer", "post_barrier"), &RenderingDevice::texture_copy, DEFVAL(BARRIER_MASK_ALL_BARRIERS)); - ClassDB::bind_method(D_METHOD("texture_clear", "texture", "color", "base_mipmap", "mipmap_count", "base_layer", "layer_count", "post_barrier"), &RenderingDevice::texture_clear, DEFVAL(BARRIER_MASK_ALL_BARRIERS)); - ClassDB::bind_method(D_METHOD("texture_resolve_multisample", "from_texture", "to_texture", "post_barrier"), &RenderingDevice::texture_resolve_multisample, DEFVAL(BARRIER_MASK_ALL_BARRIERS)); - - ClassDB::bind_method(D_METHOD("texture_get_format", "texture"), &RenderingDevice::_texture_get_format); - ClassDB::bind_method(D_METHOD("texture_get_native_handle", "texture"), &RenderingDevice::texture_get_native_handle); - - ClassDB::bind_method(D_METHOD("framebuffer_format_create", "attachments", "view_count"), &RenderingDevice::_framebuffer_format_create, DEFVAL(1)); - ClassDB::bind_method(D_METHOD("framebuffer_format_create_multipass", "attachments", "passes", "view_count"), &RenderingDevice::_framebuffer_format_create_multipass, DEFVAL(1)); - ClassDB::bind_method(D_METHOD("framebuffer_format_create_empty", "samples"), &RenderingDevice::framebuffer_format_create_empty, DEFVAL(TEXTURE_SAMPLES_1)); - ClassDB::bind_method(D_METHOD("framebuffer_format_get_texture_samples", "format", "render_pass"), &RenderingDevice::framebuffer_format_get_texture_samples, DEFVAL(0)); - ClassDB::bind_method(D_METHOD("framebuffer_create", "textures", "validate_with_format", "view_count"), &RenderingDevice::_framebuffer_create, DEFVAL(INVALID_FORMAT_ID), DEFVAL(1)); - ClassDB::bind_method(D_METHOD("framebuffer_create_multipass", "textures", "passes", "validate_with_format", "view_count"), &RenderingDevice::_framebuffer_create_multipass, DEFVAL(INVALID_FORMAT_ID), DEFVAL(1)); - ClassDB::bind_method(D_METHOD("framebuffer_create_empty", "size", "samples", "validate_with_format"), &RenderingDevice::framebuffer_create_empty, DEFVAL(TEXTURE_SAMPLES_1), DEFVAL(INVALID_FORMAT_ID)); - ClassDB::bind_method(D_METHOD("framebuffer_get_format", "framebuffer"), &RenderingDevice::framebuffer_get_format); - ClassDB::bind_method(D_METHOD("framebuffer_is_valid", "framebuffer"), &RenderingDevice::framebuffer_is_valid); - - ClassDB::bind_method(D_METHOD("sampler_create", "state"), &RenderingDevice::_sampler_create); - ClassDB::bind_method(D_METHOD("sampler_is_format_supported_for_filter", "format", "sampler_filter"), &RenderingDevice::sampler_is_format_supported_for_filter); - - ClassDB::bind_method(D_METHOD("vertex_buffer_create", "size_bytes", "data", "use_as_storage"), &RenderingDevice::vertex_buffer_create, DEFVAL(Vector()), DEFVAL(false)); - ClassDB::bind_method(D_METHOD("vertex_format_create", "vertex_descriptions"), &RenderingDevice::_vertex_format_create); - ClassDB::bind_method(D_METHOD("vertex_array_create", "vertex_count", "vertex_format", "src_buffers", "offsets"), &RenderingDevice::_vertex_array_create, DEFVAL(Vector())); - - ClassDB::bind_method(D_METHOD("index_buffer_create", "size_indices", "format", "data", "use_restart_indices"), &RenderingDevice::index_buffer_create, DEFVAL(Vector()), DEFVAL(false)); - ClassDB::bind_method(D_METHOD("index_array_create", "index_buffer", "index_offset", "index_count"), &RenderingDevice::index_array_create); - - ClassDB::bind_method(D_METHOD("shader_compile_spirv_from_source", "shader_source", "allow_cache"), &RenderingDevice::_shader_compile_spirv_from_source, DEFVAL(true)); - ClassDB::bind_method(D_METHOD("shader_compile_binary_from_spirv", "spirv_data", "name"), &RenderingDevice::_shader_compile_binary_from_spirv, DEFVAL("")); - ClassDB::bind_method(D_METHOD("shader_create_from_spirv", "spirv_data", "name"), &RenderingDevice::_shader_create_from_spirv, DEFVAL("")); - ClassDB::bind_method(D_METHOD("shader_create_from_bytecode", "binary_data", "placeholder_rid"), &RenderingDevice::shader_create_from_bytecode, DEFVAL(RID())); - ClassDB::bind_method(D_METHOD("shader_create_placeholder"), &RenderingDevice::shader_create_placeholder); - - ClassDB::bind_method(D_METHOD("shader_get_vertex_input_attribute_mask", "shader"), &RenderingDevice::shader_get_vertex_input_attribute_mask); - - ClassDB::bind_method(D_METHOD("uniform_buffer_create", "size_bytes", "data"), &RenderingDevice::uniform_buffer_create, DEFVAL(Vector())); - ClassDB::bind_method(D_METHOD("storage_buffer_create", "size_bytes", "data", "usage"), &RenderingDevice::storage_buffer_create, DEFVAL(Vector()), DEFVAL(0)); - ClassDB::bind_method(D_METHOD("texture_buffer_create", "size_bytes", "format", "data"), &RenderingDevice::texture_buffer_create, DEFVAL(Vector())); - - ClassDB::bind_method(D_METHOD("uniform_set_create", "uniforms", "shader", "shader_set"), &RenderingDevice::_uniform_set_create); - ClassDB::bind_method(D_METHOD("uniform_set_is_valid", "uniform_set"), &RenderingDevice::uniform_set_is_valid); - - ClassDB::bind_method(D_METHOD("buffer_update", "buffer", "offset", "size_bytes", "data", "post_barrier"), &RenderingDevice::_buffer_update, DEFVAL(BARRIER_MASK_ALL_BARRIERS)); - ClassDB::bind_method(D_METHOD("buffer_clear", "buffer", "offset", "size_bytes", "post_barrier"), &RenderingDevice::buffer_clear, DEFVAL(BARRIER_MASK_ALL_BARRIERS)); - ClassDB::bind_method(D_METHOD("buffer_get_data", "buffer", "offset_bytes", "size_bytes"), &RenderingDevice::buffer_get_data, DEFVAL(0), DEFVAL(0)); - - ClassDB::bind_method(D_METHOD("render_pipeline_create", "shader", "framebuffer_format", "vertex_format", "primitive", "rasterization_state", "multisample_state", "stencil_state", "color_blend_state", "dynamic_state_flags", "for_render_pass", "specialization_constants"), &RenderingDevice::_render_pipeline_create, DEFVAL(0), DEFVAL(0), DEFVAL(TypedArray())); - ClassDB::bind_method(D_METHOD("render_pipeline_is_valid", "render_pipeline"), &RenderingDevice::render_pipeline_is_valid); - - ClassDB::bind_method(D_METHOD("compute_pipeline_create", "shader", "specialization_constants"), &RenderingDevice::_compute_pipeline_create, DEFVAL(TypedArray())); - ClassDB::bind_method(D_METHOD("compute_pipeline_is_valid", "compute_pipeline"), &RenderingDevice::compute_pipeline_is_valid); - - ClassDB::bind_method(D_METHOD("screen_get_width", "screen"), &RenderingDevice::screen_get_width, DEFVAL(DisplayServer::MAIN_WINDOW_ID)); - ClassDB::bind_method(D_METHOD("screen_get_height", "screen"), &RenderingDevice::screen_get_height, DEFVAL(DisplayServer::MAIN_WINDOW_ID)); - ClassDB::bind_method(D_METHOD("screen_get_framebuffer_format"), &RenderingDevice::screen_get_framebuffer_format); - - ClassDB::bind_method(D_METHOD("draw_list_begin_for_screen", "screen", "clear_color"), &RenderingDevice::draw_list_begin_for_screen, DEFVAL(DisplayServer::MAIN_WINDOW_ID), DEFVAL(Color())); - - ClassDB::bind_method(D_METHOD("draw_list_begin", "framebuffer", "initial_color_action", "final_color_action", "initial_depth_action", "final_depth_action", "clear_color_values", "clear_depth", "clear_stencil", "region", "storage_textures"), &RenderingDevice::_draw_list_begin, DEFVAL(Vector()), DEFVAL(1.0), DEFVAL(0), DEFVAL(Rect2()), DEFVAL(TypedArray())); - ClassDB::bind_method(D_METHOD("draw_list_begin_split", "framebuffer", "splits", "initial_color_action", "final_color_action", "initial_depth_action", "final_depth_action", "clear_color_values", "clear_depth", "clear_stencil", "region", "storage_textures"), &RenderingDevice::_draw_list_begin_split, DEFVAL(Vector()), DEFVAL(1.0), DEFVAL(0), DEFVAL(Rect2()), DEFVAL(TypedArray())); - - ClassDB::bind_method(D_METHOD("draw_list_set_blend_constants", "draw_list", "color"), &RenderingDevice::draw_list_set_blend_constants); - ClassDB::bind_method(D_METHOD("draw_list_bind_render_pipeline", "draw_list", "render_pipeline"), &RenderingDevice::draw_list_bind_render_pipeline); - ClassDB::bind_method(D_METHOD("draw_list_bind_uniform_set", "draw_list", "uniform_set", "set_index"), &RenderingDevice::draw_list_bind_uniform_set); - ClassDB::bind_method(D_METHOD("draw_list_bind_vertex_array", "draw_list", "vertex_array"), &RenderingDevice::draw_list_bind_vertex_array); - ClassDB::bind_method(D_METHOD("draw_list_bind_index_array", "draw_list", "index_array"), &RenderingDevice::draw_list_bind_index_array); - ClassDB::bind_method(D_METHOD("draw_list_set_push_constant", "draw_list", "buffer", "size_bytes"), &RenderingDevice::_draw_list_set_push_constant); +/****************/ +/**** SHADER ****/ +/****************/ - ClassDB::bind_method(D_METHOD("draw_list_draw", "draw_list", "use_indices", "instances", "procedural_vertex_count"), &RenderingDevice::draw_list_draw, DEFVAL(0)); - - ClassDB::bind_method(D_METHOD("draw_list_enable_scissor", "draw_list", "rect"), &RenderingDevice::draw_list_enable_scissor, DEFVAL(Rect2())); - ClassDB::bind_method(D_METHOD("draw_list_disable_scissor", "draw_list"), &RenderingDevice::draw_list_disable_scissor); - - ClassDB::bind_method(D_METHOD("draw_list_switch_to_next_pass"), &RenderingDevice::draw_list_switch_to_next_pass); - ClassDB::bind_method(D_METHOD("draw_list_switch_to_next_pass_split", "splits"), &RenderingDevice::_draw_list_switch_to_next_pass_split); - - ClassDB::bind_method(D_METHOD("draw_list_end", "post_barrier"), &RenderingDevice::draw_list_end, DEFVAL(BARRIER_MASK_ALL_BARRIERS)); - - ClassDB::bind_method(D_METHOD("compute_list_begin", "allow_draw_overlap"), &RenderingDevice::compute_list_begin, DEFVAL(false)); - ClassDB::bind_method(D_METHOD("compute_list_bind_compute_pipeline", "compute_list", "compute_pipeline"), &RenderingDevice::compute_list_bind_compute_pipeline); - ClassDB::bind_method(D_METHOD("compute_list_set_push_constant", "compute_list", "buffer", "size_bytes"), &RenderingDevice::_compute_list_set_push_constant); - ClassDB::bind_method(D_METHOD("compute_list_bind_uniform_set", "compute_list", "uniform_set", "set_index"), &RenderingDevice::compute_list_bind_uniform_set); - ClassDB::bind_method(D_METHOD("compute_list_dispatch", "compute_list", "x_groups", "y_groups", "z_groups"), &RenderingDevice::compute_list_dispatch); - ClassDB::bind_method(D_METHOD("compute_list_add_barrier", "compute_list"), &RenderingDevice::compute_list_add_barrier); - ClassDB::bind_method(D_METHOD("compute_list_end", "post_barrier"), &RenderingDevice::compute_list_end, DEFVAL(BARRIER_MASK_ALL_BARRIERS)); - - ClassDB::bind_method(D_METHOD("free_rid", "rid"), &RenderingDevice::free); - - ClassDB::bind_method(D_METHOD("capture_timestamp", "name"), &RenderingDevice::capture_timestamp); - ClassDB::bind_method(D_METHOD("get_captured_timestamps_count"), &RenderingDevice::get_captured_timestamps_count); - ClassDB::bind_method(D_METHOD("get_captured_timestamps_frame"), &RenderingDevice::get_captured_timestamps_frame); - ClassDB::bind_method(D_METHOD("get_captured_timestamp_gpu_time", "index"), &RenderingDevice::get_captured_timestamp_gpu_time); - ClassDB::bind_method(D_METHOD("get_captured_timestamp_cpu_time", "index"), &RenderingDevice::get_captured_timestamp_cpu_time); - ClassDB::bind_method(D_METHOD("get_captured_timestamp_name", "index"), &RenderingDevice::get_captured_timestamp_name); - - ClassDB::bind_method(D_METHOD("limit_get", "limit"), &RenderingDevice::limit_get); - ClassDB::bind_method(D_METHOD("get_frame_delay"), &RenderingDevice::get_frame_delay); - ClassDB::bind_method(D_METHOD("submit"), &RenderingDevice::submit); - ClassDB::bind_method(D_METHOD("sync"), &RenderingDevice::sync); - - ClassDB::bind_method(D_METHOD("barrier", "from", "to"), &RenderingDevice::barrier, DEFVAL(BARRIER_MASK_ALL_BARRIERS), DEFVAL(BARRIER_MASK_ALL_BARRIERS)); - ClassDB::bind_method(D_METHOD("full_barrier"), &RenderingDevice::full_barrier); - - ClassDB::bind_method(D_METHOD("create_local_device"), &RenderingDevice::create_local_device); - - ClassDB::bind_method(D_METHOD("set_resource_name", "id", "name"), &RenderingDevice::set_resource_name); - - ClassDB::bind_method(D_METHOD("draw_command_begin_label", "name", "color"), &RenderingDevice::draw_command_begin_label); - ClassDB::bind_method(D_METHOD("draw_command_insert_label", "name", "color"), &RenderingDevice::draw_command_insert_label); - ClassDB::bind_method(D_METHOD("draw_command_end_label"), &RenderingDevice::draw_command_end_label); - - ClassDB::bind_method(D_METHOD("get_device_vendor_name"), &RenderingDevice::get_device_vendor_name); - ClassDB::bind_method(D_METHOD("get_device_name"), &RenderingDevice::get_device_name); - ClassDB::bind_method(D_METHOD("get_device_pipeline_cache_uuid"), &RenderingDevice::get_device_pipeline_cache_uuid); - - ClassDB::bind_method(D_METHOD("get_memory_usage", "type"), &RenderingDevice::get_memory_usage); - - ClassDB::bind_method(D_METHOD("get_driver_resource", "resource", "rid", "index"), &RenderingDevice::get_driver_resource); - - BIND_ENUM_CONSTANT(DEVICE_TYPE_OTHER); - BIND_ENUM_CONSTANT(DEVICE_TYPE_INTEGRATED_GPU); - BIND_ENUM_CONSTANT(DEVICE_TYPE_DISCRETE_GPU); - BIND_ENUM_CONSTANT(DEVICE_TYPE_VIRTUAL_GPU); - BIND_ENUM_CONSTANT(DEVICE_TYPE_CPU); - BIND_ENUM_CONSTANT(DEVICE_TYPE_MAX); - - BIND_ENUM_CONSTANT(DRIVER_RESOURCE_VULKAN_DEVICE); - BIND_ENUM_CONSTANT(DRIVER_RESOURCE_VULKAN_PHYSICAL_DEVICE); - BIND_ENUM_CONSTANT(DRIVER_RESOURCE_VULKAN_INSTANCE); - BIND_ENUM_CONSTANT(DRIVER_RESOURCE_VULKAN_QUEUE); - BIND_ENUM_CONSTANT(DRIVER_RESOURCE_VULKAN_QUEUE_FAMILY_INDEX); - BIND_ENUM_CONSTANT(DRIVER_RESOURCE_VULKAN_IMAGE); - BIND_ENUM_CONSTANT(DRIVER_RESOURCE_VULKAN_IMAGE_VIEW); - BIND_ENUM_CONSTANT(DRIVER_RESOURCE_VULKAN_IMAGE_NATIVE_TEXTURE_FORMAT); - BIND_ENUM_CONSTANT(DRIVER_RESOURCE_VULKAN_SAMPLER); - BIND_ENUM_CONSTANT(DRIVER_RESOURCE_VULKAN_DESCRIPTOR_SET); - BIND_ENUM_CONSTANT(DRIVER_RESOURCE_VULKAN_BUFFER); - BIND_ENUM_CONSTANT(DRIVER_RESOURCE_VULKAN_COMPUTE_PIPELINE); - BIND_ENUM_CONSTANT(DRIVER_RESOURCE_VULKAN_RENDER_PIPELINE); - - BIND_ENUM_CONSTANT(DATA_FORMAT_R4G4_UNORM_PACK8); - BIND_ENUM_CONSTANT(DATA_FORMAT_R4G4B4A4_UNORM_PACK16); - BIND_ENUM_CONSTANT(DATA_FORMAT_B4G4R4A4_UNORM_PACK16); - BIND_ENUM_CONSTANT(DATA_FORMAT_R5G6B5_UNORM_PACK16); - BIND_ENUM_CONSTANT(DATA_FORMAT_B5G6R5_UNORM_PACK16); - BIND_ENUM_CONSTANT(DATA_FORMAT_R5G5B5A1_UNORM_PACK16); - BIND_ENUM_CONSTANT(DATA_FORMAT_B5G5R5A1_UNORM_PACK16); - BIND_ENUM_CONSTANT(DATA_FORMAT_A1R5G5B5_UNORM_PACK16); - BIND_ENUM_CONSTANT(DATA_FORMAT_R8_UNORM); - BIND_ENUM_CONSTANT(DATA_FORMAT_R8_SNORM); - BIND_ENUM_CONSTANT(DATA_FORMAT_R8_USCALED); - BIND_ENUM_CONSTANT(DATA_FORMAT_R8_SSCALED); - BIND_ENUM_CONSTANT(DATA_FORMAT_R8_UINT); - BIND_ENUM_CONSTANT(DATA_FORMAT_R8_SINT); - BIND_ENUM_CONSTANT(DATA_FORMAT_R8_SRGB); - BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8_UNORM); - BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8_SNORM); - BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8_USCALED); - BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8_SSCALED); - BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8_UINT); - BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8_SINT); - BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8_SRGB); - BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8B8_UNORM); - BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8B8_SNORM); - BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8B8_USCALED); - BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8B8_SSCALED); - BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8B8_UINT); - BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8B8_SINT); - BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8B8_SRGB); - BIND_ENUM_CONSTANT(DATA_FORMAT_B8G8R8_UNORM); - BIND_ENUM_CONSTANT(DATA_FORMAT_B8G8R8_SNORM); - BIND_ENUM_CONSTANT(DATA_FORMAT_B8G8R8_USCALED); - BIND_ENUM_CONSTANT(DATA_FORMAT_B8G8R8_SSCALED); - BIND_ENUM_CONSTANT(DATA_FORMAT_B8G8R8_UINT); - BIND_ENUM_CONSTANT(DATA_FORMAT_B8G8R8_SINT); - BIND_ENUM_CONSTANT(DATA_FORMAT_B8G8R8_SRGB); - BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8B8A8_UNORM); - BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8B8A8_SNORM); - BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8B8A8_USCALED); - BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8B8A8_SSCALED); - BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8B8A8_UINT); - BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8B8A8_SINT); - BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8B8A8_SRGB); - BIND_ENUM_CONSTANT(DATA_FORMAT_B8G8R8A8_UNORM); - BIND_ENUM_CONSTANT(DATA_FORMAT_B8G8R8A8_SNORM); - BIND_ENUM_CONSTANT(DATA_FORMAT_B8G8R8A8_USCALED); - BIND_ENUM_CONSTANT(DATA_FORMAT_B8G8R8A8_SSCALED); - BIND_ENUM_CONSTANT(DATA_FORMAT_B8G8R8A8_UINT); - BIND_ENUM_CONSTANT(DATA_FORMAT_B8G8R8A8_SINT); - BIND_ENUM_CONSTANT(DATA_FORMAT_B8G8R8A8_SRGB); - BIND_ENUM_CONSTANT(DATA_FORMAT_A8B8G8R8_UNORM_PACK32); - BIND_ENUM_CONSTANT(DATA_FORMAT_A8B8G8R8_SNORM_PACK32); - BIND_ENUM_CONSTANT(DATA_FORMAT_A8B8G8R8_USCALED_PACK32); - BIND_ENUM_CONSTANT(DATA_FORMAT_A8B8G8R8_SSCALED_PACK32); - BIND_ENUM_CONSTANT(DATA_FORMAT_A8B8G8R8_UINT_PACK32); - BIND_ENUM_CONSTANT(DATA_FORMAT_A8B8G8R8_SINT_PACK32); - BIND_ENUM_CONSTANT(DATA_FORMAT_A8B8G8R8_SRGB_PACK32); - BIND_ENUM_CONSTANT(DATA_FORMAT_A2R10G10B10_UNORM_PACK32); - BIND_ENUM_CONSTANT(DATA_FORMAT_A2R10G10B10_SNORM_PACK32); - BIND_ENUM_CONSTANT(DATA_FORMAT_A2R10G10B10_USCALED_PACK32); - BIND_ENUM_CONSTANT(DATA_FORMAT_A2R10G10B10_SSCALED_PACK32); - BIND_ENUM_CONSTANT(DATA_FORMAT_A2R10G10B10_UINT_PACK32); - BIND_ENUM_CONSTANT(DATA_FORMAT_A2R10G10B10_SINT_PACK32); - BIND_ENUM_CONSTANT(DATA_FORMAT_A2B10G10R10_UNORM_PACK32); - BIND_ENUM_CONSTANT(DATA_FORMAT_A2B10G10R10_SNORM_PACK32); - BIND_ENUM_CONSTANT(DATA_FORMAT_A2B10G10R10_USCALED_PACK32); - BIND_ENUM_CONSTANT(DATA_FORMAT_A2B10G10R10_SSCALED_PACK32); - BIND_ENUM_CONSTANT(DATA_FORMAT_A2B10G10R10_UINT_PACK32); - BIND_ENUM_CONSTANT(DATA_FORMAT_A2B10G10R10_SINT_PACK32); - BIND_ENUM_CONSTANT(DATA_FORMAT_R16_UNORM); - BIND_ENUM_CONSTANT(DATA_FORMAT_R16_SNORM); - BIND_ENUM_CONSTANT(DATA_FORMAT_R16_USCALED); - BIND_ENUM_CONSTANT(DATA_FORMAT_R16_SSCALED); - BIND_ENUM_CONSTANT(DATA_FORMAT_R16_UINT); - BIND_ENUM_CONSTANT(DATA_FORMAT_R16_SINT); - BIND_ENUM_CONSTANT(DATA_FORMAT_R16_SFLOAT); - BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16_UNORM); - BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16_SNORM); - BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16_USCALED); - BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16_SSCALED); - BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16_UINT); - BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16_SINT); - BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16_SFLOAT); - BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16B16_UNORM); - BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16B16_SNORM); - BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16B16_USCALED); - BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16B16_SSCALED); - BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16B16_UINT); - BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16B16_SINT); - BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16B16_SFLOAT); - BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16B16A16_UNORM); - BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16B16A16_SNORM); - BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16B16A16_USCALED); - BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16B16A16_SSCALED); - BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16B16A16_UINT); - BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16B16A16_SINT); - BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16B16A16_SFLOAT); - BIND_ENUM_CONSTANT(DATA_FORMAT_R32_UINT); - BIND_ENUM_CONSTANT(DATA_FORMAT_R32_SINT); - BIND_ENUM_CONSTANT(DATA_FORMAT_R32_SFLOAT); - BIND_ENUM_CONSTANT(DATA_FORMAT_R32G32_UINT); - BIND_ENUM_CONSTANT(DATA_FORMAT_R32G32_SINT); - BIND_ENUM_CONSTANT(DATA_FORMAT_R32G32_SFLOAT); - BIND_ENUM_CONSTANT(DATA_FORMAT_R32G32B32_UINT); - BIND_ENUM_CONSTANT(DATA_FORMAT_R32G32B32_SINT); - BIND_ENUM_CONSTANT(DATA_FORMAT_R32G32B32_SFLOAT); - BIND_ENUM_CONSTANT(DATA_FORMAT_R32G32B32A32_UINT); - BIND_ENUM_CONSTANT(DATA_FORMAT_R32G32B32A32_SINT); - BIND_ENUM_CONSTANT(DATA_FORMAT_R32G32B32A32_SFLOAT); - BIND_ENUM_CONSTANT(DATA_FORMAT_R64_UINT); - BIND_ENUM_CONSTANT(DATA_FORMAT_R64_SINT); - BIND_ENUM_CONSTANT(DATA_FORMAT_R64_SFLOAT); - BIND_ENUM_CONSTANT(DATA_FORMAT_R64G64_UINT); - BIND_ENUM_CONSTANT(DATA_FORMAT_R64G64_SINT); - BIND_ENUM_CONSTANT(DATA_FORMAT_R64G64_SFLOAT); - BIND_ENUM_CONSTANT(DATA_FORMAT_R64G64B64_UINT); - BIND_ENUM_CONSTANT(DATA_FORMAT_R64G64B64_SINT); - BIND_ENUM_CONSTANT(DATA_FORMAT_R64G64B64_SFLOAT); - BIND_ENUM_CONSTANT(DATA_FORMAT_R64G64B64A64_UINT); - BIND_ENUM_CONSTANT(DATA_FORMAT_R64G64B64A64_SINT); - BIND_ENUM_CONSTANT(DATA_FORMAT_R64G64B64A64_SFLOAT); - BIND_ENUM_CONSTANT(DATA_FORMAT_B10G11R11_UFLOAT_PACK32); - BIND_ENUM_CONSTANT(DATA_FORMAT_E5B9G9R9_UFLOAT_PACK32); - BIND_ENUM_CONSTANT(DATA_FORMAT_D16_UNORM); - BIND_ENUM_CONSTANT(DATA_FORMAT_X8_D24_UNORM_PACK32); - BIND_ENUM_CONSTANT(DATA_FORMAT_D32_SFLOAT); - BIND_ENUM_CONSTANT(DATA_FORMAT_S8_UINT); - BIND_ENUM_CONSTANT(DATA_FORMAT_D16_UNORM_S8_UINT); - BIND_ENUM_CONSTANT(DATA_FORMAT_D24_UNORM_S8_UINT); - BIND_ENUM_CONSTANT(DATA_FORMAT_D32_SFLOAT_S8_UINT); - BIND_ENUM_CONSTANT(DATA_FORMAT_BC1_RGB_UNORM_BLOCK); - BIND_ENUM_CONSTANT(DATA_FORMAT_BC1_RGB_SRGB_BLOCK); - BIND_ENUM_CONSTANT(DATA_FORMAT_BC1_RGBA_UNORM_BLOCK); - BIND_ENUM_CONSTANT(DATA_FORMAT_BC1_RGBA_SRGB_BLOCK); - BIND_ENUM_CONSTANT(DATA_FORMAT_BC2_UNORM_BLOCK); - BIND_ENUM_CONSTANT(DATA_FORMAT_BC2_SRGB_BLOCK); - BIND_ENUM_CONSTANT(DATA_FORMAT_BC3_UNORM_BLOCK); - BIND_ENUM_CONSTANT(DATA_FORMAT_BC3_SRGB_BLOCK); - BIND_ENUM_CONSTANT(DATA_FORMAT_BC4_UNORM_BLOCK); - BIND_ENUM_CONSTANT(DATA_FORMAT_BC4_SNORM_BLOCK); - BIND_ENUM_CONSTANT(DATA_FORMAT_BC5_UNORM_BLOCK); - BIND_ENUM_CONSTANT(DATA_FORMAT_BC5_SNORM_BLOCK); - BIND_ENUM_CONSTANT(DATA_FORMAT_BC6H_UFLOAT_BLOCK); - BIND_ENUM_CONSTANT(DATA_FORMAT_BC6H_SFLOAT_BLOCK); - BIND_ENUM_CONSTANT(DATA_FORMAT_BC7_UNORM_BLOCK); - BIND_ENUM_CONSTANT(DATA_FORMAT_BC7_SRGB_BLOCK); - BIND_ENUM_CONSTANT(DATA_FORMAT_ETC2_R8G8B8_UNORM_BLOCK); - BIND_ENUM_CONSTANT(DATA_FORMAT_ETC2_R8G8B8_SRGB_BLOCK); - BIND_ENUM_CONSTANT(DATA_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK); - BIND_ENUM_CONSTANT(DATA_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK); - BIND_ENUM_CONSTANT(DATA_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK); - BIND_ENUM_CONSTANT(DATA_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK); - BIND_ENUM_CONSTANT(DATA_FORMAT_EAC_R11_UNORM_BLOCK); - BIND_ENUM_CONSTANT(DATA_FORMAT_EAC_R11_SNORM_BLOCK); - BIND_ENUM_CONSTANT(DATA_FORMAT_EAC_R11G11_UNORM_BLOCK); - BIND_ENUM_CONSTANT(DATA_FORMAT_EAC_R11G11_SNORM_BLOCK); - BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_4x4_UNORM_BLOCK); - BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_4x4_SRGB_BLOCK); - BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_5x4_UNORM_BLOCK); - BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_5x4_SRGB_BLOCK); - BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_5x5_UNORM_BLOCK); - BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_5x5_SRGB_BLOCK); - BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_6x5_UNORM_BLOCK); - BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_6x5_SRGB_BLOCK); - BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_6x6_UNORM_BLOCK); - BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_6x6_SRGB_BLOCK); - BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_8x5_UNORM_BLOCK); - BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_8x5_SRGB_BLOCK); - BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_8x6_UNORM_BLOCK); - BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_8x6_SRGB_BLOCK); - BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_8x8_UNORM_BLOCK); - BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_8x8_SRGB_BLOCK); - BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_10x5_UNORM_BLOCK); - BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_10x5_SRGB_BLOCK); - BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_10x6_UNORM_BLOCK); - BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_10x6_SRGB_BLOCK); - BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_10x8_UNORM_BLOCK); - BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_10x8_SRGB_BLOCK); - BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_10x10_UNORM_BLOCK); - BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_10x10_SRGB_BLOCK); - BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_12x10_UNORM_BLOCK); - BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_12x10_SRGB_BLOCK); - BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_12x12_UNORM_BLOCK); - BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_12x12_SRGB_BLOCK); - BIND_ENUM_CONSTANT(DATA_FORMAT_G8B8G8R8_422_UNORM); - BIND_ENUM_CONSTANT(DATA_FORMAT_B8G8R8G8_422_UNORM); - BIND_ENUM_CONSTANT(DATA_FORMAT_G8_B8_R8_3PLANE_420_UNORM); - BIND_ENUM_CONSTANT(DATA_FORMAT_G8_B8R8_2PLANE_420_UNORM); - BIND_ENUM_CONSTANT(DATA_FORMAT_G8_B8_R8_3PLANE_422_UNORM); - BIND_ENUM_CONSTANT(DATA_FORMAT_G8_B8R8_2PLANE_422_UNORM); - BIND_ENUM_CONSTANT(DATA_FORMAT_G8_B8_R8_3PLANE_444_UNORM); - BIND_ENUM_CONSTANT(DATA_FORMAT_R10X6_UNORM_PACK16); - BIND_ENUM_CONSTANT(DATA_FORMAT_R10X6G10X6_UNORM_2PACK16); - BIND_ENUM_CONSTANT(DATA_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16); - BIND_ENUM_CONSTANT(DATA_FORMAT_G10X6B10X6G10X6R10X6_422_UNORM_4PACK16); - BIND_ENUM_CONSTANT(DATA_FORMAT_B10X6G10X6R10X6G10X6_422_UNORM_4PACK16); - BIND_ENUM_CONSTANT(DATA_FORMAT_G10X6_B10X6_R10X6_3PLANE_420_UNORM_3PACK16); - BIND_ENUM_CONSTANT(DATA_FORMAT_G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16); - BIND_ENUM_CONSTANT(DATA_FORMAT_G10X6_B10X6_R10X6_3PLANE_422_UNORM_3PACK16); - BIND_ENUM_CONSTANT(DATA_FORMAT_G10X6_B10X6R10X6_2PLANE_422_UNORM_3PACK16); - BIND_ENUM_CONSTANT(DATA_FORMAT_G10X6_B10X6_R10X6_3PLANE_444_UNORM_3PACK16); - BIND_ENUM_CONSTANT(DATA_FORMAT_R12X4_UNORM_PACK16); - BIND_ENUM_CONSTANT(DATA_FORMAT_R12X4G12X4_UNORM_2PACK16); - BIND_ENUM_CONSTANT(DATA_FORMAT_R12X4G12X4B12X4A12X4_UNORM_4PACK16); - BIND_ENUM_CONSTANT(DATA_FORMAT_G12X4B12X4G12X4R12X4_422_UNORM_4PACK16); - BIND_ENUM_CONSTANT(DATA_FORMAT_B12X4G12X4R12X4G12X4_422_UNORM_4PACK16); - BIND_ENUM_CONSTANT(DATA_FORMAT_G12X4_B12X4_R12X4_3PLANE_420_UNORM_3PACK16); - BIND_ENUM_CONSTANT(DATA_FORMAT_G12X4_B12X4R12X4_2PLANE_420_UNORM_3PACK16); - BIND_ENUM_CONSTANT(DATA_FORMAT_G12X4_B12X4_R12X4_3PLANE_422_UNORM_3PACK16); - BIND_ENUM_CONSTANT(DATA_FORMAT_G12X4_B12X4R12X4_2PLANE_422_UNORM_3PACK16); - BIND_ENUM_CONSTANT(DATA_FORMAT_G12X4_B12X4_R12X4_3PLANE_444_UNORM_3PACK16); - BIND_ENUM_CONSTANT(DATA_FORMAT_G16B16G16R16_422_UNORM); - BIND_ENUM_CONSTANT(DATA_FORMAT_B16G16R16G16_422_UNORM); - BIND_ENUM_CONSTANT(DATA_FORMAT_G16_B16_R16_3PLANE_420_UNORM); - BIND_ENUM_CONSTANT(DATA_FORMAT_G16_B16R16_2PLANE_420_UNORM); - BIND_ENUM_CONSTANT(DATA_FORMAT_G16_B16_R16_3PLANE_422_UNORM); - BIND_ENUM_CONSTANT(DATA_FORMAT_G16_B16R16_2PLANE_422_UNORM); - BIND_ENUM_CONSTANT(DATA_FORMAT_G16_B16_R16_3PLANE_444_UNORM); - BIND_ENUM_CONSTANT(DATA_FORMAT_MAX); - - BIND_BITFIELD_FLAG(BARRIER_MASK_VERTEX); - BIND_BITFIELD_FLAG(BARRIER_MASK_FRAGMENT); - BIND_BITFIELD_FLAG(BARRIER_MASK_COMPUTE); - BIND_BITFIELD_FLAG(BARRIER_MASK_TRANSFER); - BIND_BITFIELD_FLAG(BARRIER_MASK_RASTER); - BIND_BITFIELD_FLAG(BARRIER_MASK_ALL_BARRIERS); - BIND_BITFIELD_FLAG(BARRIER_MASK_NO_BARRIER); - - BIND_ENUM_CONSTANT(TEXTURE_TYPE_1D); - BIND_ENUM_CONSTANT(TEXTURE_TYPE_2D); - BIND_ENUM_CONSTANT(TEXTURE_TYPE_3D); - BIND_ENUM_CONSTANT(TEXTURE_TYPE_CUBE); - BIND_ENUM_CONSTANT(TEXTURE_TYPE_1D_ARRAY); - BIND_ENUM_CONSTANT(TEXTURE_TYPE_2D_ARRAY); - BIND_ENUM_CONSTANT(TEXTURE_TYPE_CUBE_ARRAY); - BIND_ENUM_CONSTANT(TEXTURE_TYPE_MAX); - - BIND_ENUM_CONSTANT(TEXTURE_SAMPLES_1); - BIND_ENUM_CONSTANT(TEXTURE_SAMPLES_2); - BIND_ENUM_CONSTANT(TEXTURE_SAMPLES_4); - BIND_ENUM_CONSTANT(TEXTURE_SAMPLES_8); - BIND_ENUM_CONSTANT(TEXTURE_SAMPLES_16); - BIND_ENUM_CONSTANT(TEXTURE_SAMPLES_32); - BIND_ENUM_CONSTANT(TEXTURE_SAMPLES_64); - BIND_ENUM_CONSTANT(TEXTURE_SAMPLES_MAX); - - BIND_BITFIELD_FLAG(TEXTURE_USAGE_SAMPLING_BIT); - BIND_BITFIELD_FLAG(TEXTURE_USAGE_COLOR_ATTACHMENT_BIT); - BIND_BITFIELD_FLAG(TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT); - BIND_BITFIELD_FLAG(TEXTURE_USAGE_STORAGE_BIT); - BIND_BITFIELD_FLAG(TEXTURE_USAGE_STORAGE_ATOMIC_BIT); - BIND_BITFIELD_FLAG(TEXTURE_USAGE_CPU_READ_BIT); - BIND_BITFIELD_FLAG(TEXTURE_USAGE_CAN_UPDATE_BIT); - BIND_BITFIELD_FLAG(TEXTURE_USAGE_CAN_COPY_FROM_BIT); - BIND_BITFIELD_FLAG(TEXTURE_USAGE_CAN_COPY_TO_BIT); - BIND_BITFIELD_FLAG(TEXTURE_USAGE_INPUT_ATTACHMENT_BIT); - - BIND_ENUM_CONSTANT(TEXTURE_SWIZZLE_IDENTITY); - BIND_ENUM_CONSTANT(TEXTURE_SWIZZLE_ZERO); - BIND_ENUM_CONSTANT(TEXTURE_SWIZZLE_ONE); - BIND_ENUM_CONSTANT(TEXTURE_SWIZZLE_R); - BIND_ENUM_CONSTANT(TEXTURE_SWIZZLE_G); - BIND_ENUM_CONSTANT(TEXTURE_SWIZZLE_B); - BIND_ENUM_CONSTANT(TEXTURE_SWIZZLE_A); - BIND_ENUM_CONSTANT(TEXTURE_SWIZZLE_MAX); - - BIND_ENUM_CONSTANT(TEXTURE_SLICE_2D); - BIND_ENUM_CONSTANT(TEXTURE_SLICE_CUBEMAP); - BIND_ENUM_CONSTANT(TEXTURE_SLICE_3D); - - BIND_ENUM_CONSTANT(SAMPLER_FILTER_NEAREST); - BIND_ENUM_CONSTANT(SAMPLER_FILTER_LINEAR); - BIND_ENUM_CONSTANT(SAMPLER_REPEAT_MODE_REPEAT); - BIND_ENUM_CONSTANT(SAMPLER_REPEAT_MODE_MIRRORED_REPEAT); - BIND_ENUM_CONSTANT(SAMPLER_REPEAT_MODE_CLAMP_TO_EDGE); - BIND_ENUM_CONSTANT(SAMPLER_REPEAT_MODE_CLAMP_TO_BORDER); - BIND_ENUM_CONSTANT(SAMPLER_REPEAT_MODE_MIRROR_CLAMP_TO_EDGE); - BIND_ENUM_CONSTANT(SAMPLER_REPEAT_MODE_MAX); - - BIND_ENUM_CONSTANT(SAMPLER_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK); - BIND_ENUM_CONSTANT(SAMPLER_BORDER_COLOR_INT_TRANSPARENT_BLACK); - BIND_ENUM_CONSTANT(SAMPLER_BORDER_COLOR_FLOAT_OPAQUE_BLACK); - BIND_ENUM_CONSTANT(SAMPLER_BORDER_COLOR_INT_OPAQUE_BLACK); - BIND_ENUM_CONSTANT(SAMPLER_BORDER_COLOR_FLOAT_OPAQUE_WHITE); - BIND_ENUM_CONSTANT(SAMPLER_BORDER_COLOR_INT_OPAQUE_WHITE); - BIND_ENUM_CONSTANT(SAMPLER_BORDER_COLOR_MAX); - - BIND_ENUM_CONSTANT(VERTEX_FREQUENCY_VERTEX); - BIND_ENUM_CONSTANT(VERTEX_FREQUENCY_INSTANCE); - - BIND_ENUM_CONSTANT(INDEX_BUFFER_FORMAT_UINT16); - BIND_ENUM_CONSTANT(INDEX_BUFFER_FORMAT_UINT32); - - BIND_BITFIELD_FLAG(STORAGE_BUFFER_USAGE_DISPATCH_INDIRECT); - - BIND_ENUM_CONSTANT(UNIFORM_TYPE_SAMPLER); //for sampling only (sampler GLSL type) - BIND_ENUM_CONSTANT(UNIFORM_TYPE_SAMPLER_WITH_TEXTURE); // for sampling only); but includes a texture); (samplerXX GLSL type)); first a sampler then a texture - BIND_ENUM_CONSTANT(UNIFORM_TYPE_TEXTURE); //only texture); (textureXX GLSL type) - BIND_ENUM_CONSTANT(UNIFORM_TYPE_IMAGE); // storage image (imageXX GLSL type)); for compute mostly - BIND_ENUM_CONSTANT(UNIFORM_TYPE_TEXTURE_BUFFER); // buffer texture (or TBO); textureBuffer type) - BIND_ENUM_CONSTANT(UNIFORM_TYPE_SAMPLER_WITH_TEXTURE_BUFFER); // buffer texture with a sampler(or TBO); samplerBuffer type) - BIND_ENUM_CONSTANT(UNIFORM_TYPE_IMAGE_BUFFER); //texel buffer); (imageBuffer type)); for compute mostly - BIND_ENUM_CONSTANT(UNIFORM_TYPE_UNIFORM_BUFFER); //regular uniform buffer (or UBO). - BIND_ENUM_CONSTANT(UNIFORM_TYPE_STORAGE_BUFFER); //storage buffer ("buffer" qualifier) like UBO); but supports storage); for compute mostly - BIND_ENUM_CONSTANT(UNIFORM_TYPE_INPUT_ATTACHMENT); //used for sub-pass read/write); for mobile mostly - BIND_ENUM_CONSTANT(UNIFORM_TYPE_MAX); - - BIND_ENUM_CONSTANT(RENDER_PRIMITIVE_POINTS); - BIND_ENUM_CONSTANT(RENDER_PRIMITIVE_LINES); - BIND_ENUM_CONSTANT(RENDER_PRIMITIVE_LINES_WITH_ADJACENCY); - BIND_ENUM_CONSTANT(RENDER_PRIMITIVE_LINESTRIPS); - BIND_ENUM_CONSTANT(RENDER_PRIMITIVE_LINESTRIPS_WITH_ADJACENCY); - BIND_ENUM_CONSTANT(RENDER_PRIMITIVE_TRIANGLES); - BIND_ENUM_CONSTANT(RENDER_PRIMITIVE_TRIANGLES_WITH_ADJACENCY); - BIND_ENUM_CONSTANT(RENDER_PRIMITIVE_TRIANGLE_STRIPS); - BIND_ENUM_CONSTANT(RENDER_PRIMITIVE_TRIANGLE_STRIPS_WITH_AJACENCY); - BIND_ENUM_CONSTANT(RENDER_PRIMITIVE_TRIANGLE_STRIPS_WITH_RESTART_INDEX); - BIND_ENUM_CONSTANT(RENDER_PRIMITIVE_TESSELATION_PATCH); - BIND_ENUM_CONSTANT(RENDER_PRIMITIVE_MAX); - - BIND_ENUM_CONSTANT(POLYGON_CULL_DISABLED); - BIND_ENUM_CONSTANT(POLYGON_CULL_FRONT); - BIND_ENUM_CONSTANT(POLYGON_CULL_BACK); - - BIND_ENUM_CONSTANT(POLYGON_FRONT_FACE_CLOCKWISE); - BIND_ENUM_CONSTANT(POLYGON_FRONT_FACE_COUNTER_CLOCKWISE); - - BIND_ENUM_CONSTANT(STENCIL_OP_KEEP); - BIND_ENUM_CONSTANT(STENCIL_OP_ZERO); - BIND_ENUM_CONSTANT(STENCIL_OP_REPLACE); - BIND_ENUM_CONSTANT(STENCIL_OP_INCREMENT_AND_CLAMP); - BIND_ENUM_CONSTANT(STENCIL_OP_DECREMENT_AND_CLAMP); - BIND_ENUM_CONSTANT(STENCIL_OP_INVERT); - BIND_ENUM_CONSTANT(STENCIL_OP_INCREMENT_AND_WRAP); - BIND_ENUM_CONSTANT(STENCIL_OP_DECREMENT_AND_WRAP); - BIND_ENUM_CONSTANT(STENCIL_OP_MAX); //not an actual operator); just the amount of operators :D - - BIND_ENUM_CONSTANT(COMPARE_OP_NEVER); - BIND_ENUM_CONSTANT(COMPARE_OP_LESS); - BIND_ENUM_CONSTANT(COMPARE_OP_EQUAL); - BIND_ENUM_CONSTANT(COMPARE_OP_LESS_OR_EQUAL); - BIND_ENUM_CONSTANT(COMPARE_OP_GREATER); - BIND_ENUM_CONSTANT(COMPARE_OP_NOT_EQUAL); - BIND_ENUM_CONSTANT(COMPARE_OP_GREATER_OR_EQUAL); - BIND_ENUM_CONSTANT(COMPARE_OP_ALWAYS); - BIND_ENUM_CONSTANT(COMPARE_OP_MAX); - - BIND_ENUM_CONSTANT(LOGIC_OP_CLEAR); - BIND_ENUM_CONSTANT(LOGIC_OP_AND); - BIND_ENUM_CONSTANT(LOGIC_OP_AND_REVERSE); - BIND_ENUM_CONSTANT(LOGIC_OP_COPY); - BIND_ENUM_CONSTANT(LOGIC_OP_AND_INVERTED); - BIND_ENUM_CONSTANT(LOGIC_OP_NO_OP); - BIND_ENUM_CONSTANT(LOGIC_OP_XOR); - BIND_ENUM_CONSTANT(LOGIC_OP_OR); - BIND_ENUM_CONSTANT(LOGIC_OP_NOR); - BIND_ENUM_CONSTANT(LOGIC_OP_EQUIVALENT); - BIND_ENUM_CONSTANT(LOGIC_OP_INVERT); - BIND_ENUM_CONSTANT(LOGIC_OP_OR_REVERSE); - BIND_ENUM_CONSTANT(LOGIC_OP_COPY_INVERTED); - BIND_ENUM_CONSTANT(LOGIC_OP_OR_INVERTED); - BIND_ENUM_CONSTANT(LOGIC_OP_NAND); - BIND_ENUM_CONSTANT(LOGIC_OP_SET); - BIND_ENUM_CONSTANT(LOGIC_OP_MAX); //not an actual operator); just the amount of operators :D - - BIND_ENUM_CONSTANT(BLEND_FACTOR_ZERO); - BIND_ENUM_CONSTANT(BLEND_FACTOR_ONE); - BIND_ENUM_CONSTANT(BLEND_FACTOR_SRC_COLOR); - BIND_ENUM_CONSTANT(BLEND_FACTOR_ONE_MINUS_SRC_COLOR); - BIND_ENUM_CONSTANT(BLEND_FACTOR_DST_COLOR); - BIND_ENUM_CONSTANT(BLEND_FACTOR_ONE_MINUS_DST_COLOR); - BIND_ENUM_CONSTANT(BLEND_FACTOR_SRC_ALPHA); - BIND_ENUM_CONSTANT(BLEND_FACTOR_ONE_MINUS_SRC_ALPHA); - BIND_ENUM_CONSTANT(BLEND_FACTOR_DST_ALPHA); - BIND_ENUM_CONSTANT(BLEND_FACTOR_ONE_MINUS_DST_ALPHA); - BIND_ENUM_CONSTANT(BLEND_FACTOR_CONSTANT_COLOR); - BIND_ENUM_CONSTANT(BLEND_FACTOR_ONE_MINUS_CONSTANT_COLOR); - BIND_ENUM_CONSTANT(BLEND_FACTOR_CONSTANT_ALPHA); - BIND_ENUM_CONSTANT(BLEND_FACTOR_ONE_MINUS_CONSTANT_ALPHA); - BIND_ENUM_CONSTANT(BLEND_FACTOR_SRC_ALPHA_SATURATE); - BIND_ENUM_CONSTANT(BLEND_FACTOR_SRC1_COLOR); - BIND_ENUM_CONSTANT(BLEND_FACTOR_ONE_MINUS_SRC1_COLOR); - BIND_ENUM_CONSTANT(BLEND_FACTOR_SRC1_ALPHA); - BIND_ENUM_CONSTANT(BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA); - BIND_ENUM_CONSTANT(BLEND_FACTOR_MAX); - - BIND_ENUM_CONSTANT(BLEND_OP_ADD); - BIND_ENUM_CONSTANT(BLEND_OP_SUBTRACT); - BIND_ENUM_CONSTANT(BLEND_OP_REVERSE_SUBTRACT); - BIND_ENUM_CONSTANT(BLEND_OP_MINIMUM); - BIND_ENUM_CONSTANT(BLEND_OP_MAXIMUM); - BIND_ENUM_CONSTANT(BLEND_OP_MAX); - - BIND_BITFIELD_FLAG(DYNAMIC_STATE_LINE_WIDTH); - BIND_BITFIELD_FLAG(DYNAMIC_STATE_DEPTH_BIAS); - BIND_BITFIELD_FLAG(DYNAMIC_STATE_BLEND_CONSTANTS); - BIND_BITFIELD_FLAG(DYNAMIC_STATE_DEPTH_BOUNDS); - BIND_BITFIELD_FLAG(DYNAMIC_STATE_STENCIL_COMPARE_MASK); - BIND_BITFIELD_FLAG(DYNAMIC_STATE_STENCIL_WRITE_MASK); - BIND_BITFIELD_FLAG(DYNAMIC_STATE_STENCIL_REFERENCE); - - BIND_ENUM_CONSTANT(INITIAL_ACTION_CLEAR); //start rendering and clear the framebuffer (supply params) - BIND_ENUM_CONSTANT(INITIAL_ACTION_CLEAR_REGION); //start rendering and clear the framebuffer (supply params) - BIND_ENUM_CONSTANT(INITIAL_ACTION_CLEAR_REGION_CONTINUE); //continue rendering and clear the framebuffer (supply params) - BIND_ENUM_CONSTANT(INITIAL_ACTION_KEEP); //start rendering); but keep attached color texture contents (depth will be cleared) - BIND_ENUM_CONSTANT(INITIAL_ACTION_DROP); //start rendering); ignore what is there); just write above it - BIND_ENUM_CONSTANT(INITIAL_ACTION_CONTINUE); //continue rendering (framebuffer must have been left in "continue" state as final action previously) - BIND_ENUM_CONSTANT(INITIAL_ACTION_MAX); - - BIND_ENUM_CONSTANT(FINAL_ACTION_READ); //will no longer render to it); allows attached textures to be read again); but depth buffer contents will be dropped (Can't be read from) - BIND_ENUM_CONSTANT(FINAL_ACTION_DISCARD); // discard contents after rendering - BIND_ENUM_CONSTANT(FINAL_ACTION_CONTINUE); //will continue rendering later); attached textures can't be read until re-bound with "finish" - BIND_ENUM_CONSTANT(FINAL_ACTION_MAX); - - BIND_ENUM_CONSTANT(SHADER_STAGE_VERTEX); - BIND_ENUM_CONSTANT(SHADER_STAGE_FRAGMENT); - BIND_ENUM_CONSTANT(SHADER_STAGE_TESSELATION_CONTROL); - BIND_ENUM_CONSTANT(SHADER_STAGE_TESSELATION_EVALUATION); - BIND_ENUM_CONSTANT(SHADER_STAGE_COMPUTE); - BIND_ENUM_CONSTANT(SHADER_STAGE_MAX); - BIND_ENUM_CONSTANT(SHADER_STAGE_VERTEX_BIT); - BIND_ENUM_CONSTANT(SHADER_STAGE_FRAGMENT_BIT); - BIND_ENUM_CONSTANT(SHADER_STAGE_TESSELATION_CONTROL_BIT); - BIND_ENUM_CONSTANT(SHADER_STAGE_TESSELATION_EVALUATION_BIT); - BIND_ENUM_CONSTANT(SHADER_STAGE_COMPUTE_BIT); - - BIND_ENUM_CONSTANT(SHADER_LANGUAGE_GLSL); - BIND_ENUM_CONSTANT(SHADER_LANGUAGE_HLSL); - - BIND_ENUM_CONSTANT(PIPELINE_SPECIALIZATION_CONSTANT_TYPE_BOOL); - BIND_ENUM_CONSTANT(PIPELINE_SPECIALIZATION_CONSTANT_TYPE_INT); - BIND_ENUM_CONSTANT(PIPELINE_SPECIALIZATION_CONSTANT_TYPE_FLOAT); - - BIND_ENUM_CONSTANT(LIMIT_MAX_BOUND_UNIFORM_SETS); - BIND_ENUM_CONSTANT(LIMIT_MAX_FRAMEBUFFER_COLOR_ATTACHMENTS); - BIND_ENUM_CONSTANT(LIMIT_MAX_TEXTURES_PER_UNIFORM_SET); - BIND_ENUM_CONSTANT(LIMIT_MAX_SAMPLERS_PER_UNIFORM_SET); - BIND_ENUM_CONSTANT(LIMIT_MAX_STORAGE_BUFFERS_PER_UNIFORM_SET); - BIND_ENUM_CONSTANT(LIMIT_MAX_STORAGE_IMAGES_PER_UNIFORM_SET); - BIND_ENUM_CONSTANT(LIMIT_MAX_UNIFORM_BUFFERS_PER_UNIFORM_SET); - BIND_ENUM_CONSTANT(LIMIT_MAX_DRAW_INDEXED_INDEX); - BIND_ENUM_CONSTANT(LIMIT_MAX_FRAMEBUFFER_HEIGHT); - BIND_ENUM_CONSTANT(LIMIT_MAX_FRAMEBUFFER_WIDTH); - BIND_ENUM_CONSTANT(LIMIT_MAX_TEXTURE_ARRAY_LAYERS); - BIND_ENUM_CONSTANT(LIMIT_MAX_TEXTURE_SIZE_1D); - BIND_ENUM_CONSTANT(LIMIT_MAX_TEXTURE_SIZE_2D); - BIND_ENUM_CONSTANT(LIMIT_MAX_TEXTURE_SIZE_3D); - BIND_ENUM_CONSTANT(LIMIT_MAX_TEXTURE_SIZE_CUBE); - BIND_ENUM_CONSTANT(LIMIT_MAX_TEXTURES_PER_SHADER_STAGE); - BIND_ENUM_CONSTANT(LIMIT_MAX_SAMPLERS_PER_SHADER_STAGE); - BIND_ENUM_CONSTANT(LIMIT_MAX_STORAGE_BUFFERS_PER_SHADER_STAGE); - BIND_ENUM_CONSTANT(LIMIT_MAX_STORAGE_IMAGES_PER_SHADER_STAGE); - BIND_ENUM_CONSTANT(LIMIT_MAX_UNIFORM_BUFFERS_PER_SHADER_STAGE); - BIND_ENUM_CONSTANT(LIMIT_MAX_PUSH_CONSTANT_SIZE); - BIND_ENUM_CONSTANT(LIMIT_MAX_UNIFORM_BUFFER_SIZE); - BIND_ENUM_CONSTANT(LIMIT_MAX_VERTEX_INPUT_ATTRIBUTE_OFFSET); - BIND_ENUM_CONSTANT(LIMIT_MAX_VERTEX_INPUT_ATTRIBUTES); - BIND_ENUM_CONSTANT(LIMIT_MAX_VERTEX_INPUT_BINDINGS); - BIND_ENUM_CONSTANT(LIMIT_MAX_VERTEX_INPUT_BINDING_STRIDE); - BIND_ENUM_CONSTANT(LIMIT_MIN_UNIFORM_BUFFER_OFFSET_ALIGNMENT); - BIND_ENUM_CONSTANT(LIMIT_MAX_COMPUTE_SHARED_MEMORY_SIZE); - BIND_ENUM_CONSTANT(LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_X); - BIND_ENUM_CONSTANT(LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_Y); - BIND_ENUM_CONSTANT(LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_Z); - BIND_ENUM_CONSTANT(LIMIT_MAX_COMPUTE_WORKGROUP_INVOCATIONS); - BIND_ENUM_CONSTANT(LIMIT_MAX_COMPUTE_WORKGROUP_SIZE_X); - BIND_ENUM_CONSTANT(LIMIT_MAX_COMPUTE_WORKGROUP_SIZE_Y); - BIND_ENUM_CONSTANT(LIMIT_MAX_COMPUTE_WORKGROUP_SIZE_Z); - BIND_ENUM_CONSTANT(LIMIT_MAX_VIEWPORT_DIMENSIONS_X); - BIND_ENUM_CONSTANT(LIMIT_MAX_VIEWPORT_DIMENSIONS_Y); - - BIND_ENUM_CONSTANT(MEMORY_TEXTURES); - BIND_ENUM_CONSTANT(MEMORY_BUFFERS); - BIND_ENUM_CONSTANT(MEMORY_TOTAL); - - BIND_CONSTANT(INVALID_ID); - BIND_CONSTANT(INVALID_FORMAT_ID); -} - -RenderingDevice::RenderingDevice() { - if (singleton == nullptr) { // there may be more rendering devices later - singleton = this; - } -} +const char *RenderingDeviceCommons::SHADER_STAGE_NAMES[SHADER_STAGE_MAX] = { + "Vertex", + "Fragment", + "TesselationControl", + "TesselationEvaluation", + "Compute", +}; diff --git a/servers/rendering/rendering_device_commons.h b/servers/rendering/rendering_device_commons.h index b95640acc63b..5500a63d8177 100644 --- a/servers/rendering/rendering_device_commons.h +++ b/servers/rendering/rendering_device_commons.h @@ -1,5 +1,5 @@ /**************************************************************************/ -/* rendering_device.h */ +/* rendering_device_commons.h */ /**************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ @@ -28,148 +28,24 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /**************************************************************************/ -#ifndef RENDERING_DEVICE_H -#define RENDERING_DEVICE_H - -#include "core/object/class_db.h" -#include "core/variant/typed_array.h" -#include "servers/display_server.h" - -class RDTextureFormat; -class RDTextureView; -class RDAttachmentFormat; -class RDSamplerState; -class RDVertexAttribute; -class RDShaderSource; -class RDShaderSPIRV; -class RDUniform; -class RDPipelineRasterizationState; -class RDPipelineMultisampleState; -class RDPipelineDepthStencilState; -class RDPipelineColorBlendState; -class RDFramebufferPass; -class RDPipelineSpecializationConstant; - -class RenderingDevice : public Object { - GDCLASS(RenderingDevice, Object) -public: - enum DeviceFamily { - DEVICE_UNKNOWN, - DEVICE_OPENGL, - DEVICE_VULKAN, - DEVICE_DIRECTX - }; - - // This enum matches VkPhysicalDeviceType (except for `DEVICE_TYPE_MAX`). - // Unlike VkPhysicalDeviceType, DeviceType is exposed to the scripting API. - enum DeviceType { - DEVICE_TYPE_OTHER, - DEVICE_TYPE_INTEGRATED_GPU, - DEVICE_TYPE_DISCRETE_GPU, - DEVICE_TYPE_VIRTUAL_GPU, - DEVICE_TYPE_CPU, - DEVICE_TYPE_MAX, - }; - - enum DriverResource { - DRIVER_RESOURCE_VULKAN_DEVICE = 0, - DRIVER_RESOURCE_VULKAN_PHYSICAL_DEVICE, - DRIVER_RESOURCE_VULKAN_INSTANCE, - DRIVER_RESOURCE_VULKAN_QUEUE, - DRIVER_RESOURCE_VULKAN_QUEUE_FAMILY_INDEX, - DRIVER_RESOURCE_VULKAN_IMAGE, - DRIVER_RESOURCE_VULKAN_IMAGE_VIEW, - DRIVER_RESOURCE_VULKAN_IMAGE_NATIVE_TEXTURE_FORMAT, - DRIVER_RESOURCE_VULKAN_SAMPLER, - DRIVER_RESOURCE_VULKAN_DESCRIPTOR_SET, - DRIVER_RESOURCE_VULKAN_BUFFER, - DRIVER_RESOURCE_VULKAN_COMPUTE_PIPELINE, - DRIVER_RESOURCE_VULKAN_RENDER_PIPELINE, - //next driver continue enum from 1000 to keep order - }; - - enum ShaderStage { - SHADER_STAGE_VERTEX, - SHADER_STAGE_FRAGMENT, - SHADER_STAGE_TESSELATION_CONTROL, - SHADER_STAGE_TESSELATION_EVALUATION, - SHADER_STAGE_COMPUTE, - SHADER_STAGE_MAX, - SHADER_STAGE_VERTEX_BIT = (1 << SHADER_STAGE_VERTEX), - SHADER_STAGE_FRAGMENT_BIT = (1 << SHADER_STAGE_FRAGMENT), - SHADER_STAGE_TESSELATION_CONTROL_BIT = (1 << SHADER_STAGE_TESSELATION_CONTROL), - SHADER_STAGE_TESSELATION_EVALUATION_BIT = (1 << SHADER_STAGE_TESSELATION_EVALUATION), - SHADER_STAGE_COMPUTE_BIT = (1 << SHADER_STAGE_COMPUTE), - }; - - enum ShaderLanguage { - SHADER_LANGUAGE_GLSL, - SHADER_LANGUAGE_HLSL - }; - - enum SubgroupOperations { - SUBGROUP_BASIC_BIT = 1, - SUBGROUP_VOTE_BIT = 2, - SUBGROUP_ARITHMETIC_BIT = 4, - SUBGROUP_BALLOT_BIT = 8, - SUBGROUP_SHUFFLE_BIT = 16, - SUBGROUP_SHUFFLE_RELATIVE_BIT = 32, - SUBGROUP_CLUSTERED_BIT = 64, - SUBGROUP_QUAD_BIT = 128, - }; - - struct Capabilities { - // main device info - DeviceFamily device_family = DEVICE_UNKNOWN; - uint32_t version_major = 1.0; - uint32_t version_minor = 0.0; - }; - - typedef String (*ShaderSPIRVGetCacheKeyFunction)(const RenderingDevice *p_render_device); - typedef Vector (*ShaderCompileToSPIRVFunction)(ShaderStage p_stage, const String &p_source_code, ShaderLanguage p_language, String *r_error, const RenderingDevice *p_render_device); - typedef Vector (*ShaderCacheFunction)(ShaderStage p_stage, const String &p_source_code, ShaderLanguage p_language); - - typedef void (*InvalidationCallback)(void *); +#ifndef RENDERING_DEVICE_COMMONS_H +#define RENDERING_DEVICE_COMMONS_H -private: - static ShaderCompileToSPIRVFunction compile_to_spirv_function; - static ShaderCacheFunction cache_function; - static ShaderSPIRVGetCacheKeyFunction get_spirv_cache_key_function; - - static RenderingDevice *singleton; - -protected: - static void _bind_methods(); - -#ifndef DISABLE_DEPRECATED - RID _shader_create_from_bytecode_bind_compat_79606(const Vector &p_shader_binary); - static void _bind_compatibility_methods(); -#endif - - Capabilities device_capabilities; +#include "core/object/object.h" +#include "core/variant/type_info.h" +class RenderingDeviceCommons : public Object { + //////////////////////////////////////////// + // PUBLIC STUFF + // Exposed by RenderingDevice, and shared + // with RenderingDeviceDriver. + //////////////////////////////////////////// public: - //base numeric ID for all types - enum { - INVALID_ID = -1, - INVALID_FORMAT_ID = -1 - }; - /*****************/ /**** GENERIC ****/ /*****************/ - enum CompareOperator { - COMPARE_OP_NEVER, - COMPARE_OP_LESS, - COMPARE_OP_EQUAL, - COMPARE_OP_LESS_OR_EQUAL, - COMPARE_OP_GREATER, - COMPARE_OP_NOT_EQUAL, - COMPARE_OP_GREATER_OR_EQUAL, - COMPARE_OP_ALWAYS, - COMPARE_OP_MAX //not an actual operator, just the amount of operators :D - }; + static const int INVALID_ID = -1; enum DataFormat { DATA_FORMAT_R4G4_UNORM_PACK8, @@ -390,22 +266,19 @@ class RenderingDevice : public Object { DATA_FORMAT_G16_B16_R16_3PLANE_422_UNORM, DATA_FORMAT_G16_B16R16_2PLANE_422_UNORM, DATA_FORMAT_G16_B16_R16_3PLANE_444_UNORM, - DATA_FORMAT_MAX + DATA_FORMAT_MAX, }; - /*****************/ - /**** BARRIER ****/ - /*****************/ - - enum BarrierMask { - BARRIER_MASK_VERTEX = 1, - BARRIER_MASK_FRAGMENT = 8, - BARRIER_MASK_COMPUTE = 2, - BARRIER_MASK_TRANSFER = 4, - - BARRIER_MASK_RASTER = BARRIER_MASK_VERTEX | BARRIER_MASK_FRAGMENT, // 9, - BARRIER_MASK_ALL_BARRIERS = 0x7FFF, // all flags set - BARRIER_MASK_NO_BARRIER = 0x8000, + enum CompareOperator { + COMPARE_OP_NEVER, + COMPARE_OP_LESS, + COMPARE_OP_EQUAL, + COMPARE_OP_LESS_OR_EQUAL, + COMPARE_OP_GREATER, + COMPARE_OP_NOT_EQUAL, + COMPARE_OP_GREATER_OR_EQUAL, + COMPARE_OP_ALWAYS, + COMPARE_OP_MAX }; /*****************/ @@ -420,7 +293,7 @@ class RenderingDevice : public Object { TEXTURE_TYPE_1D_ARRAY, TEXTURE_TYPE_2D_ARRAY, TEXTURE_TYPE_CUBE_ARRAY, - TEXTURE_TYPE_MAX + TEXTURE_TYPE_MAX, }; enum TextureSamples { @@ -431,7 +304,7 @@ class RenderingDevice : public Object { TEXTURE_SAMPLES_16, TEXTURE_SAMPLES_32, TEXTURE_SAMPLES_64, - TEXTURE_SAMPLES_MAX + TEXTURE_SAMPLES_MAX, }; enum TextureUsageBits { @@ -448,27 +321,16 @@ class RenderingDevice : public Object { TEXTURE_USAGE_VRS_ATTACHMENT_BIT = (1 << 10), }; - enum TextureSwizzle { - TEXTURE_SWIZZLE_IDENTITY, - TEXTURE_SWIZZLE_ZERO, - TEXTURE_SWIZZLE_ONE, - TEXTURE_SWIZZLE_R, - TEXTURE_SWIZZLE_G, - TEXTURE_SWIZZLE_B, - TEXTURE_SWIZZLE_A, - TEXTURE_SWIZZLE_MAX - }; - struct TextureFormat { - DataFormat format; - uint32_t width; - uint32_t height; - uint32_t depth; - uint32_t array_layers; - uint32_t mipmaps; - TextureType texture_type; - TextureSamples samples; - uint32_t usage_bits; + DataFormat format = DATA_FORMAT_R8_UNORM; + uint32_t width = 1; + uint32_t height = 1; + uint32_t depth = 1; + uint32_t array_layers = 1; + uint32_t mipmaps = 1; + TextureType texture_type = TEXTURE_TYPE_2D; + TextureSamples samples = TEXTURE_SAMPLES_1; + uint32_t usage_bits = 0; Vector shareable_formats; bool is_resolve_buffer = false; @@ -497,56 +359,19 @@ class RenderingDevice : public Object { return true; } } - - TextureFormat() { - format = DATA_FORMAT_R8_UNORM; - width = 1; - height = 1; - depth = 1; - array_layers = 1; - mipmaps = 1; - texture_type = TEXTURE_TYPE_2D; - samples = TEXTURE_SAMPLES_1; - usage_bits = 0; - } }; - struct TextureView { - DataFormat format_override; - TextureSwizzle swizzle_r; - TextureSwizzle swizzle_g; - TextureSwizzle swizzle_b; - TextureSwizzle swizzle_a; - - bool operator==(const TextureView &p_view) const { - if (format_override != p_view.format_override) { - return false; - } else if (swizzle_r != p_view.swizzle_r) { - return false; - } else if (swizzle_g != p_view.swizzle_g) { - return false; - } else if (swizzle_b != p_view.swizzle_b) { - return false; - } else if (swizzle_a != p_view.swizzle_a) { - return false; - } else { - return true; - } - } - - TextureView() { - format_override = DATA_FORMAT_MAX; //means, use same as format - swizzle_r = TEXTURE_SWIZZLE_R; - swizzle_g = TEXTURE_SWIZZLE_G; - swizzle_b = TEXTURE_SWIZZLE_B; - swizzle_a = TEXTURE_SWIZZLE_A; - } + enum TextureSwizzle { + TEXTURE_SWIZZLE_IDENTITY, + TEXTURE_SWIZZLE_ZERO, + TEXTURE_SWIZZLE_ONE, + TEXTURE_SWIZZLE_R, + TEXTURE_SWIZZLE_G, + TEXTURE_SWIZZLE_B, + TEXTURE_SWIZZLE_A, + TEXTURE_SWIZZLE_MAX }; - virtual RID texture_create(const TextureFormat &p_format, const TextureView &p_view, const Vector> &p_data = Vector>()) = 0; - virtual RID texture_create_shared(const TextureView &p_view, RID p_with_texture) = 0; - virtual RID texture_create_from_extension(TextureType p_type, DataFormat p_format, TextureSamples p_samples, BitField p_flags, uint64_t p_image, uint64_t p_width, uint64_t p_height, uint64_t p_depth, uint64_t p_layers) = 0; - enum TextureSliceType { TEXTURE_SLICE_2D, TEXTURE_SLICE_CUBEMAP, @@ -554,66 +379,6 @@ class RenderingDevice : public Object { TEXTURE_SLICE_2D_ARRAY, }; - virtual RID texture_create_shared_from_slice(const TextureView &p_view, RID p_with_texture, uint32_t p_layer, uint32_t p_mipmap, uint32_t p_mipmaps = 1, TextureSliceType p_slice_type = TEXTURE_SLICE_2D, uint32_t p_layers = 0) = 0; - - virtual Error texture_update(RID p_texture, uint32_t p_layer, const Vector &p_data, BitField p_post_barrier = BARRIER_MASK_ALL_BARRIERS) = 0; - virtual Vector texture_get_data(RID p_texture, uint32_t p_layer) = 0; // CPU textures will return immediately, while GPU textures will most likely force a flush - - virtual bool texture_is_format_supported_for_usage(DataFormat p_format, BitField p_usage) const = 0; - virtual bool texture_is_shared(RID p_texture) = 0; - virtual bool texture_is_valid(RID p_texture) = 0; - virtual TextureFormat texture_get_format(RID p_texture) = 0; - virtual Size2i texture_size(RID p_texture) = 0; - virtual uint64_t texture_get_native_handle(RID p_texture) = 0; - - virtual Error texture_copy(RID p_from_texture, RID p_to_texture, const Vector3 &p_from, const Vector3 &p_to, const Vector3 &p_size, uint32_t p_src_mipmap, uint32_t p_dst_mipmap, uint32_t p_src_layer, uint32_t p_dst_layer, BitField p_post_barrier = BARRIER_MASK_ALL_BARRIERS) = 0; - virtual Error texture_clear(RID p_texture, const Color &p_color, uint32_t p_base_mipmap, uint32_t p_mipmaps, uint32_t p_base_layer, uint32_t p_layers, BitField p_post_barrier = BARRIER_MASK_ALL_BARRIERS) = 0; - virtual Error texture_resolve_multisample(RID p_from_texture, RID p_to_texture, BitField p_post_barrier = BARRIER_MASK_ALL_BARRIERS) = 0; - - /*********************/ - /**** FRAMEBUFFER ****/ - /*********************/ - - struct AttachmentFormat { - enum { UNUSED_ATTACHMENT = 0xFFFFFFFF }; - DataFormat format; - TextureSamples samples; - uint32_t usage_flags; - AttachmentFormat() { - format = DATA_FORMAT_R8G8B8A8_UNORM; - samples = TEXTURE_SAMPLES_1; - usage_flags = 0; - } - }; - - typedef int64_t FramebufferFormatID; - - // This ID is warranted to be unique for the same formats, does not need to be freed - virtual FramebufferFormatID framebuffer_format_create(const Vector &p_format, uint32_t p_view_count = 1) = 0; - struct FramebufferPass { - enum { - ATTACHMENT_UNUSED = -1 - }; - Vector color_attachments; - Vector input_attachments; - Vector resolve_attachments; - Vector preserve_attachments; - int32_t depth_attachment = ATTACHMENT_UNUSED; - int32_t vrs_attachment = ATTACHMENT_UNUSED; // density map for VRS, only used if supported - }; - - virtual FramebufferFormatID framebuffer_format_create_multipass(const Vector &p_attachments, const Vector &p_passes, uint32_t p_view_count = 1) = 0; - virtual FramebufferFormatID framebuffer_format_create_empty(TextureSamples p_samples = TEXTURE_SAMPLES_1) = 0; - virtual TextureSamples framebuffer_format_get_texture_samples(FramebufferFormatID p_format, uint32_t p_pass = 0) = 0; - - virtual RID framebuffer_create(const Vector &p_texture_attachments, FramebufferFormatID p_format_check = INVALID_ID, uint32_t p_view_count = 1) = 0; - virtual RID framebuffer_create_multipass(const Vector &p_texture_attachments, const Vector &p_passes, FramebufferFormatID p_format_check = INVALID_ID, uint32_t p_view_count = 1) = 0; - virtual RID framebuffer_create_empty(const Size2i &p_size, TextureSamples p_samples = TEXTURE_SAMPLES_1, FramebufferFormatID p_format_check = INVALID_ID) = 0; - virtual bool framebuffer_is_valid(RID p_framebuffer) const = 0; - virtual void framebuffer_set_invalidation_callback(RID p_framebuffer, InvalidationCallback p_callback, void *p_userdata) = 0; - - virtual FramebufferFormatID framebuffer_get_format(RID p_framebuffer) = 0; - /*****************/ /**** SAMPLER ****/ /*****************/ @@ -643,227 +408,97 @@ class RenderingDevice : public Object { }; struct SamplerState { - SamplerFilter mag_filter; - SamplerFilter min_filter; - SamplerFilter mip_filter; - SamplerRepeatMode repeat_u; - SamplerRepeatMode repeat_v; - SamplerRepeatMode repeat_w; - float lod_bias; - bool use_anisotropy; - float anisotropy_max; - bool enable_compare; - CompareOperator compare_op; - float min_lod; - float max_lod; - SamplerBorderColor border_color; - bool unnormalized_uvw; - - SamplerState() { - mag_filter = SAMPLER_FILTER_NEAREST; - min_filter = SAMPLER_FILTER_NEAREST; - mip_filter = SAMPLER_FILTER_NEAREST; - repeat_u = SAMPLER_REPEAT_MODE_CLAMP_TO_EDGE; - repeat_v = SAMPLER_REPEAT_MODE_CLAMP_TO_EDGE; - repeat_w = SAMPLER_REPEAT_MODE_CLAMP_TO_EDGE; - lod_bias = 0; - use_anisotropy = false; - anisotropy_max = 1.0; - enable_compare = false; - compare_op = COMPARE_OP_ALWAYS; - min_lod = 0; - max_lod = 1e20; //something very large should do - border_color = SAMPLER_BORDER_COLOR_FLOAT_OPAQUE_BLACK; - unnormalized_uvw = false; - } + SamplerFilter mag_filter = SAMPLER_FILTER_NEAREST; + SamplerFilter min_filter = SAMPLER_FILTER_NEAREST; + SamplerFilter mip_filter = SAMPLER_FILTER_NEAREST; + SamplerRepeatMode repeat_u = SAMPLER_REPEAT_MODE_CLAMP_TO_EDGE; + SamplerRepeatMode repeat_v = SAMPLER_REPEAT_MODE_CLAMP_TO_EDGE; + SamplerRepeatMode repeat_w = SAMPLER_REPEAT_MODE_CLAMP_TO_EDGE; + float lod_bias = 0.0f; + bool use_anisotropy = false; + float anisotropy_max = 1.0f; + bool enable_compare = false; + CompareOperator compare_op = COMPARE_OP_ALWAYS; + float min_lod = 0.0f; + float max_lod = 1e20; // Something very large should do. + SamplerBorderColor border_color = SAMPLER_BORDER_COLOR_FLOAT_OPAQUE_BLACK; + bool unnormalized_uvw = false; }; - virtual RID sampler_create(const SamplerState &p_state) = 0; - virtual bool sampler_is_format_supported_for_filter(DataFormat p_format, SamplerFilter p_sampler_filter) const = 0; - /**********************/ /**** VERTEX ARRAY ****/ /**********************/ + enum IndexBufferFormat { + INDEX_BUFFER_FORMAT_UINT16, + INDEX_BUFFER_FORMAT_UINT32, + }; + enum VertexFrequency { VERTEX_FREQUENCY_VERTEX, VERTEX_FREQUENCY_INSTANCE, }; struct VertexAttribute { - uint32_t location; //shader location - uint32_t offset; - DataFormat format; - uint32_t stride; - VertexFrequency frequency; - VertexAttribute() { - location = 0; - offset = 0; - stride = 0; - format = DATA_FORMAT_MAX; - frequency = VERTEX_FREQUENCY_VERTEX; - } + uint32_t location = 0; // Shader location. + uint32_t offset = 0; + DataFormat format = DATA_FORMAT_MAX; + uint32_t stride = 0; + VertexFrequency frequency = VERTEX_FREQUENCY_VERTEX; }; - virtual RID vertex_buffer_create(uint32_t p_size_bytes, const Vector &p_data = Vector(), bool p_use_as_storage = false) = 0; - - typedef int64_t VertexFormatID; - - // This ID is warranted to be unique for the same formats, does not need to be freed - virtual VertexFormatID vertex_format_create(const Vector &p_vertex_formats) = 0; - virtual RID vertex_array_create(uint32_t p_vertex_count, VertexFormatID p_vertex_format, const Vector &p_src_buffers, const Vector &p_offsets = Vector()) = 0; - enum IndexBufferFormat { - INDEX_BUFFER_FORMAT_UINT16, - INDEX_BUFFER_FORMAT_UINT32, - }; + /*********************/ + /**** FRAMEBUFFER ****/ + /*********************/ - virtual RID index_buffer_create(uint32_t p_size_indices, IndexBufferFormat p_format, const Vector &p_data = Vector(), bool p_use_restart_indices = false) = 0; - virtual RID index_array_create(RID p_index_buffer, uint32_t p_index_offset, uint32_t p_index_count) = 0; + static const int32_t ATTACHMENT_UNUSED = -1; /****************/ /**** SHADER ****/ /****************/ - const Capabilities *get_device_capabilities() const { return &device_capabilities; }; - - enum Features { - SUPPORTS_MULTIVIEW, - SUPPORTS_FSR_HALF_FLOAT, - SUPPORTS_ATTACHMENT_VRS, - // If not supported, a fragment shader with only side effets (i.e., writes to buffers, but doesn't output to attachments), may be optimized down to no-op by the GPU driver. - SUPPORTS_FRAGMENT_SHADER_WITH_ONLY_SIDE_EFFECTS, + enum ShaderStage { + SHADER_STAGE_VERTEX, + SHADER_STAGE_FRAGMENT, + SHADER_STAGE_TESSELATION_CONTROL, + SHADER_STAGE_TESSELATION_EVALUATION, + SHADER_STAGE_COMPUTE, + SHADER_STAGE_MAX, + SHADER_STAGE_VERTEX_BIT = (1 << SHADER_STAGE_VERTEX), + SHADER_STAGE_FRAGMENT_BIT = (1 << SHADER_STAGE_FRAGMENT), + SHADER_STAGE_TESSELATION_CONTROL_BIT = (1 << SHADER_STAGE_TESSELATION_CONTROL), + SHADER_STAGE_TESSELATION_EVALUATION_BIT = (1 << SHADER_STAGE_TESSELATION_EVALUATION), + SHADER_STAGE_COMPUTE_BIT = (1 << SHADER_STAGE_COMPUTE), }; - virtual bool has_feature(const Features p_feature) const = 0; - - virtual Vector shader_compile_spirv_from_source(ShaderStage p_stage, const String &p_source_code, ShaderLanguage p_language = SHADER_LANGUAGE_GLSL, String *r_error = nullptr, bool p_allow_cache = true); - virtual String shader_get_spirv_cache_key() const; - - static void shader_set_compile_to_spirv_function(ShaderCompileToSPIRVFunction p_function); - static void shader_set_spirv_cache_function(ShaderCacheFunction p_function); - static void shader_set_get_cache_key_function(ShaderSPIRVGetCacheKeyFunction p_function); struct ShaderStageSPIRVData { - ShaderStage shader_stage; - Vector spir_v; - - ShaderStageSPIRVData() { - shader_stage = SHADER_STAGE_VERTEX; - } + ShaderStage shader_stage = SHADER_STAGE_MAX; + Vector spirv; }; - virtual String shader_get_binary_cache_key() const = 0; - virtual Vector shader_compile_binary_from_spirv(const Vector &p_spirv, const String &p_shader_name = "") = 0; - - virtual RID shader_create_from_spirv(const Vector &p_spirv, const String &p_shader_name = ""); - virtual RID shader_create_from_bytecode(const Vector &p_shader_binary, RID p_placeholder = RID()) = 0; - virtual RID shader_create_placeholder() = 0; - - virtual uint64_t shader_get_vertex_input_attribute_mask(RID p_shader) = 0; + /*********************/ + /**** UNIFORM SET ****/ + /*********************/ - /******************/ - /**** UNIFORMS ****/ - /******************/ + static const uint32_t MAX_UNIFORM_SETS = 16; enum UniformType { - UNIFORM_TYPE_SAMPLER, //for sampling only (sampler GLSL type) - UNIFORM_TYPE_SAMPLER_WITH_TEXTURE, // for sampling only, but includes a texture, (samplerXX GLSL type), first a sampler then a texture - UNIFORM_TYPE_TEXTURE, //only texture, (textureXX GLSL type) - UNIFORM_TYPE_IMAGE, // storage image (imageXX GLSL type), for compute mostly - UNIFORM_TYPE_TEXTURE_BUFFER, // buffer texture (or TBO, textureBuffer type) - UNIFORM_TYPE_SAMPLER_WITH_TEXTURE_BUFFER, // buffer texture with a sampler(or TBO, samplerBuffer type) - UNIFORM_TYPE_IMAGE_BUFFER, //texel buffer, (imageBuffer type), for compute mostly - UNIFORM_TYPE_UNIFORM_BUFFER, //regular uniform buffer (or UBO). - UNIFORM_TYPE_STORAGE_BUFFER, //storage buffer ("buffer" qualifier) like UBO, but supports storage, for compute mostly - UNIFORM_TYPE_INPUT_ATTACHMENT, //used for sub-pass read/write, for mobile mostly + UNIFORM_TYPE_SAMPLER, // For sampling only (sampler GLSL type). + UNIFORM_TYPE_SAMPLER_WITH_TEXTURE, // For sampling only, but includes a texture, (samplerXX GLSL type), first a sampler then a texture. + UNIFORM_TYPE_TEXTURE, // Only texture, (textureXX GLSL type). + UNIFORM_TYPE_IMAGE, // Storage image (imageXX GLSL type), for compute mostly. + UNIFORM_TYPE_TEXTURE_BUFFER, // Buffer texture (or TBO, textureBuffer type). + UNIFORM_TYPE_SAMPLER_WITH_TEXTURE_BUFFER, // Buffer texture with a sampler(or TBO, samplerBuffer type). + UNIFORM_TYPE_IMAGE_BUFFER, // Texel buffer, (imageBuffer type), for compute mostly. + UNIFORM_TYPE_UNIFORM_BUFFER, // Regular uniform buffer (or UBO). + UNIFORM_TYPE_STORAGE_BUFFER, // Storage buffer ("buffer" qualifier) like UBO, but supports storage, for compute mostly. + UNIFORM_TYPE_INPUT_ATTACHMENT, // Used for sub-pass read/write, for mobile mostly. UNIFORM_TYPE_MAX }; - enum StorageBufferUsage { - STORAGE_BUFFER_USAGE_DISPATCH_INDIRECT = 1, - }; - - virtual RID uniform_buffer_create(uint32_t p_size_bytes, const Vector &p_data = Vector()) = 0; - virtual RID storage_buffer_create(uint32_t p_size, const Vector &p_data = Vector(), BitField p_usage = 0) = 0; - virtual RID texture_buffer_create(uint32_t p_size_elements, DataFormat p_format, const Vector &p_data = Vector()) = 0; - - struct Uniform { - UniformType uniform_type; - int binding; // Binding index as specified in shader. - - private: - // In most cases only one ID is provided per binding, so avoid allocating memory unnecessarily for performance. - RID id; // If only one is provided, this is used. - Vector ids; // If multiple ones are provided, this is used instead. - - public: - _FORCE_INLINE_ uint32_t get_id_count() const { - return (id.is_valid() ? 1 : ids.size()); - } - - _FORCE_INLINE_ RID get_id(uint32_t p_idx) const { - if (id.is_valid()) { - ERR_FAIL_COND_V(p_idx != 0, RID()); - return id; - } else { - return ids[p_idx]; - } - } - _FORCE_INLINE_ void set_id(uint32_t p_idx, RID p_id) { - if (id.is_valid()) { - ERR_FAIL_COND(p_idx != 0); - id = p_id; - } else { - ids.write[p_idx] = p_id; - } - } - - _FORCE_INLINE_ void append_id(RID p_id) { - if (ids.is_empty()) { - if (id == RID()) { - id = p_id; - } else { - ids.push_back(id); - ids.push_back(p_id); - id = RID(); - } - } else { - ids.push_back(p_id); - } - } - - _FORCE_INLINE_ void clear_ids() { - id = RID(); - ids.clear(); - } - - _FORCE_INLINE_ Uniform(UniformType p_type, int p_binding, RID p_id) { - uniform_type = p_type; - binding = p_binding; - id = p_id; - } - _FORCE_INLINE_ Uniform(UniformType p_type, int p_binding, const Vector &p_ids) { - uniform_type = p_type; - binding = p_binding; - ids = p_ids; - } - _FORCE_INLINE_ Uniform() { - uniform_type = UNIFORM_TYPE_IMAGE; - binding = 0; - } - }; - - virtual RID uniform_set_create(const Vector &p_uniforms, RID p_shader, uint32_t p_shader_set) = 0; - virtual bool uniform_set_is_valid(RID p_uniform_set) = 0; - virtual void uniform_set_set_invalidation_callback(RID p_uniform_set, InvalidationCallback p_callback, void *p_userdata) = 0; - - virtual Error buffer_copy(RID p_src_buffer, RID p_dst_buffer, uint32_t p_src_offset, uint32_t p_dst_offset, uint32_t p_size, BitField p_post_barrier = BARRIER_MASK_ALL_BARRIERS) = 0; - virtual Error buffer_update(RID p_buffer, uint32_t p_offset, uint32_t p_size, const void *p_data, BitField p_post_barrier = BARRIER_MASK_ALL_BARRIERS) = 0; - virtual Error buffer_clear(RID p_buffer, uint32_t p_offset, uint32_t p_size, BitField p_post_barrier = BARRIER_MASK_ALL_BARRIERS) = 0; - virtual Vector buffer_get_data(RID p_buffer, uint32_t p_offset = 0, uint32_t p_size = 0) = 0; // This causes stall, only use to retrieve large buffers for saving. - - /******************************************/ - /**** PIPELINE SPECIALIZATION CONSTANT ****/ - /******************************************/ + /******************/ + /**** PIPELINE ****/ + /******************/ enum PipelineSpecializationConstantType { PIPELINE_SPECIALIZATION_CONSTANT_TYPE_BOOL, @@ -872,24 +507,20 @@ class RenderingDevice : public Object { }; struct PipelineSpecializationConstant { - PipelineSpecializationConstantType type; - uint32_t constant_id; + PipelineSpecializationConstantType type = {}; + uint32_t constant_id = 0xffffffff; union { - uint32_t int_value; + uint32_t int_value = 0; float float_value; bool bool_value; }; - - PipelineSpecializationConstant() { - type = PIPELINE_SPECIALIZATION_CONSTANT_TYPE_BOOL; - constant_id = 0; - int_value = 0; - } }; - /*************************/ - /**** RENDER PIPELINE ****/ - /*************************/ + /*******************/ + /**** RENDERING ****/ + /*******************/ + + // ----- PIPELINE ----- enum RenderPrimitive { RENDER_PRIMITIVE_POINTS, @@ -906,8 +537,6 @@ class RenderingDevice : public Object { RENDER_PRIMITIVE_MAX }; - //disable optimization, tessellate control points - enum PolygonCullMode { POLYGON_CULL_DISABLED, POLYGON_CULL_FRONT, @@ -928,7 +557,7 @@ class RenderingDevice : public Object { STENCIL_OP_INVERT, STENCIL_OP_INCREMENT_AND_WRAP, STENCIL_OP_DECREMENT_AND_WRAP, - STENCIL_OP_MAX //not an actual operator, just the amount of operators :D + STENCIL_OP_MAX }; enum LogicOperation { @@ -948,7 +577,7 @@ class RenderingDevice : public Object { LOGIC_OP_OR_INVERTED, LOGIC_OP_NAND, LOGIC_OP_SET, - LOGIC_OP_MAX //not an actual operator, just the amount of operators :D + LOGIC_OP_MAX }; enum BlendFactor { @@ -979,125 +608,72 @@ class RenderingDevice : public Object { BLEND_OP_SUBTRACT, BLEND_OP_REVERSE_SUBTRACT, BLEND_OP_MINIMUM, - BLEND_OP_MAXIMUM, //yes this one is an actual operator - BLEND_OP_MAX //not an actual operator, just the amount of operators :D + BLEND_OP_MAXIMUM, // Yes, this one is an actual operator. + BLEND_OP_MAX }; struct PipelineRasterizationState { - bool enable_depth_clamp; - bool discard_primitives; - bool wireframe; - PolygonCullMode cull_mode; - PolygonFrontFace front_face; - bool depth_bias_enabled; - float depth_bias_constant_factor; - float depth_bias_clamp; - float depth_bias_slope_factor; - float line_width; - uint32_t patch_control_points; - PipelineRasterizationState() { - enable_depth_clamp = false; - discard_primitives = false; - wireframe = false; - cull_mode = POLYGON_CULL_DISABLED; - front_face = POLYGON_FRONT_FACE_CLOCKWISE; - depth_bias_enabled = false; - depth_bias_constant_factor = 0; - depth_bias_clamp = 0; - depth_bias_slope_factor = 0; - line_width = 1.0; - patch_control_points = 1; - } + bool enable_depth_clamp = false; + bool discard_primitives = false; + bool wireframe = false; + PolygonCullMode cull_mode = POLYGON_CULL_DISABLED; + PolygonFrontFace front_face = POLYGON_FRONT_FACE_CLOCKWISE; + bool depth_bias_enabled = false; + float depth_bias_constant_factor = 0.0f; + float depth_bias_clamp = 0.0f; + float depth_bias_slope_factor = 0.0f; + float line_width = 1.0f; + uint32_t patch_control_points = 1; }; struct PipelineMultisampleState { - TextureSamples sample_count; - bool enable_sample_shading; - float min_sample_shading; + TextureSamples sample_count = TEXTURE_SAMPLES_1; + bool enable_sample_shading = false; + float min_sample_shading = 0.0f; Vector sample_mask; - bool enable_alpha_to_coverage; - bool enable_alpha_to_one; - - PipelineMultisampleState() { - sample_count = TEXTURE_SAMPLES_1; - enable_sample_shading = false; - min_sample_shading = 0; - enable_alpha_to_coverage = false; - enable_alpha_to_one = false; - } + bool enable_alpha_to_coverage = false; + bool enable_alpha_to_one = false; }; struct PipelineDepthStencilState { - bool enable_depth_test; - bool enable_depth_write; - CompareOperator depth_compare_operator; - bool enable_depth_range; - float depth_range_min; - float depth_range_max; - bool enable_stencil; + bool enable_depth_test = false; + bool enable_depth_write = false; + CompareOperator depth_compare_operator = COMPARE_OP_ALWAYS; + bool enable_depth_range = false; + float depth_range_min = 0; + float depth_range_max = 0; + bool enable_stencil = false; struct StencilOperationState { - StencilOperation fail; - StencilOperation pass; - StencilOperation depth_fail; - CompareOperator compare; - uint32_t compare_mask; - uint32_t write_mask; - uint32_t reference; - - StencilOperationState() { - fail = STENCIL_OP_ZERO; - pass = STENCIL_OP_ZERO; - depth_fail = STENCIL_OP_ZERO; - compare = COMPARE_OP_ALWAYS; - compare_mask = 0; - write_mask = 0; - reference = 0; - } + StencilOperation fail = STENCIL_OP_ZERO; + StencilOperation pass = STENCIL_OP_ZERO; + StencilOperation depth_fail = STENCIL_OP_ZERO; + CompareOperator compare = COMPARE_OP_ALWAYS; + uint32_t compare_mask = 0; + uint32_t write_mask = 0; + uint32_t reference = 0; }; StencilOperationState front_op; StencilOperationState back_op; - - PipelineDepthStencilState() { - enable_depth_test = false; - enable_depth_write = false; - depth_compare_operator = COMPARE_OP_ALWAYS; - enable_depth_range = false; - depth_range_min = 0; - depth_range_max = 0; - enable_stencil = false; - } }; struct PipelineColorBlendState { - bool enable_logic_op; - LogicOperation logic_op; + bool enable_logic_op = false; + LogicOperation logic_op = LOGIC_OP_CLEAR; + struct Attachment { - bool enable_blend; - BlendFactor src_color_blend_factor; - BlendFactor dst_color_blend_factor; - BlendOperation color_blend_op; - BlendFactor src_alpha_blend_factor; - BlendFactor dst_alpha_blend_factor; - BlendOperation alpha_blend_op; - bool write_r; - bool write_g; - bool write_b; - bool write_a; - Attachment() { - enable_blend = false; - src_color_blend_factor = BLEND_FACTOR_ZERO; - dst_color_blend_factor = BLEND_FACTOR_ZERO; - color_blend_op = BLEND_OP_ADD; - src_alpha_blend_factor = BLEND_FACTOR_ZERO; - dst_alpha_blend_factor = BLEND_FACTOR_ZERO; - alpha_blend_op = BLEND_OP_ADD; - write_r = true; - write_g = true; - write_b = true; - write_a = true; - } + bool enable_blend = false; + BlendFactor src_color_blend_factor = BLEND_FACTOR_ZERO; + BlendFactor dst_color_blend_factor = BLEND_FACTOR_ZERO; + BlendOperation color_blend_op = BLEND_OP_ADD; + BlendFactor src_alpha_blend_factor = BLEND_FACTOR_ZERO; + BlendFactor dst_alpha_blend_factor = BLEND_FACTOR_ZERO; + BlendOperation alpha_blend_op = BLEND_OP_ADD; + bool write_r = true; + bool write_g = true; + bool write_b = true; + bool write_a = true; }; static PipelineColorBlendState create_disabled(int p_attachments = 1) { @@ -1123,13 +699,8 @@ class RenderingDevice : public Object { return bs; } - Vector attachments; //one per render target texture + Vector attachments; // One per render target texture. Color blend_constant; - - PipelineColorBlendState() { - enable_logic_op = false; - logic_op = LOGIC_OP_CLEAR; - } }; enum PipelineDynamicStateFlags { @@ -1142,111 +713,54 @@ class RenderingDevice : public Object { DYNAMIC_STATE_STENCIL_REFERENCE = (1 << 6), }; - virtual bool render_pipeline_is_valid(RID p_pipeline) = 0; - virtual RID render_pipeline_create(RID p_shader, FramebufferFormatID p_framebuffer_format, VertexFormatID p_vertex_format, RenderPrimitive p_render_primitive, const PipelineRasterizationState &p_rasterization_state, const PipelineMultisampleState &p_multisample_state, const PipelineDepthStencilState &p_depth_stencil_state, const PipelineColorBlendState &p_blend_state, BitField p_dynamic_state_flags = 0, uint32_t p_for_render_pass = 0, const Vector &p_specialization_constants = Vector()) = 0; - - /**************************/ - /**** COMPUTE PIPELINE ****/ - /**************************/ + /**************/ + /**** MISC ****/ + /**************/ - virtual RID compute_pipeline_create(RID p_shader, const Vector &p_specialization_constants = Vector()) = 0; - virtual bool compute_pipeline_is_valid(RID p_pipeline) = 0; - - /****************/ - /**** SCREEN ****/ - /****************/ - - virtual int screen_get_width(DisplayServer::WindowID p_screen = 0) const = 0; - virtual int screen_get_height(DisplayServer::WindowID p_screen = 0) const = 0; - virtual FramebufferFormatID screen_get_framebuffer_format() const = 0; - - /********************/ - /**** DRAW LISTS ****/ - /********************/ - - enum InitialAction { - INITIAL_ACTION_CLEAR, // Start rendering and clear the whole framebuffer. - INITIAL_ACTION_CLEAR_REGION, // Start rendering and clear the framebuffer in the specified region. - INITIAL_ACTION_CLEAR_REGION_CONTINUE, // Continue rendering and clear the framebuffer in the specified region. Framebuffer must have been left in `FINAL_ACTION_CONTINUE` state as the final action previously. - INITIAL_ACTION_KEEP, // Start rendering, but keep attached color texture contents. If the framebuffer was previously used to read in a shader, this will automatically insert a layout transition. - INITIAL_ACTION_DROP, // Start rendering, ignore what is there; write above it. In general, this is the fastest option when you will be writing every single pixel and you don't need a clear color. - INITIAL_ACTION_CONTINUE, // Continue rendering. Framebuffer must have been left in `FINAL_ACTION_CONTINUE` state as the final action previously. - INITIAL_ACTION_MAX + // This enum matches VkPhysicalDeviceType (except for `DEVICE_TYPE_MAX`). + // Unlike VkPhysicalDeviceType, DeviceType is exposed to the scripting API. + enum DeviceType { + DEVICE_TYPE_OTHER, + DEVICE_TYPE_INTEGRATED_GPU, + DEVICE_TYPE_DISCRETE_GPU, + DEVICE_TYPE_VIRTUAL_GPU, + DEVICE_TYPE_CPU, + DEVICE_TYPE_MAX }; - enum FinalAction { - FINAL_ACTION_READ, // Store the texture for reading and make it read-only if it has the `TEXTURE_USAGE_SAMPLING_BIT` bit (only applies to color, depth and stencil attachments). - FINAL_ACTION_DISCARD, // Discard the texture data and make it read-only if it has the `TEXTURE_USAGE_SAMPLING_BIT` bit (only applies to color, depth and stencil attachments). - FINAL_ACTION_CONTINUE, // Store the texture and continue for further processing. Similar to `FINAL_ACTION_READ`, but does not make the texture read-only if it has the `TEXTURE_USAGE_SAMPLING_BIT` bit. - FINAL_ACTION_MAX + // Defined in an API-agnostic way. + // Some may not make sense for the underlying API; in that case, 0 is returned. + enum DriverResource { + DRIVER_RESOURCE_LOGICAL_DEVICE, + DRIVER_RESOURCE_PHYSICAL_DEVICE, + DRIVER_RESOURCE_TOPMOST_OBJECT, + DRIVER_RESOURCE_COMMAND_QUEUE, + DRIVER_RESOURCE_QUEUE_FAMILY, + DRIVER_RESOURCE_TEXTURE, + DRIVER_RESOURCE_TEXTURE_VIEW, + DRIVER_RESOURCE_TEXTURE_DATA_FORMAT, + DRIVER_RESOURCE_SAMPLER, + DRIVER_RESOURCE_UNIFORM_SET, + DRIVER_RESOURCE_BUFFER, + DRIVER_RESOURCE_COMPUTE_PIPELINE, + DRIVER_RESOURCE_RENDER_PIPELINE, +#ifndef DISABLE_DEPRECATED + DRIVER_RESOURCE_VULKAN_DEVICE = DRIVER_RESOURCE_LOGICAL_DEVICE, + DRIVER_RESOURCE_VULKAN_PHYSICAL_DEVICE = DRIVER_RESOURCE_PHYSICAL_DEVICE, + DRIVER_RESOURCE_VULKAN_INSTANCE = DRIVER_RESOURCE_TOPMOST_OBJECT, + DRIVER_RESOURCE_VULKAN_QUEUE = DRIVER_RESOURCE_COMMAND_QUEUE, + DRIVER_RESOURCE_VULKAN_QUEUE_FAMILY_INDEX = DRIVER_RESOURCE_QUEUE_FAMILY, + DRIVER_RESOURCE_VULKAN_IMAGE = DRIVER_RESOURCE_TEXTURE, + DRIVER_RESOURCE_VULKAN_IMAGE_VIEW = DRIVER_RESOURCE_TEXTURE_VIEW, + DRIVER_RESOURCE_VULKAN_IMAGE_NATIVE_TEXTURE_FORMAT = DRIVER_RESOURCE_TEXTURE_DATA_FORMAT, + DRIVER_RESOURCE_VULKAN_SAMPLER = DRIVER_RESOURCE_SAMPLER, + DRIVER_RESOURCE_VULKAN_DESCRIPTOR_SET = DRIVER_RESOURCE_UNIFORM_SET, + DRIVER_RESOURCE_VULKAN_BUFFER = DRIVER_RESOURCE_BUFFER, + DRIVER_RESOURCE_VULKAN_COMPUTE_PIPELINE = DRIVER_RESOURCE_COMPUTE_PIPELINE, + DRIVER_RESOURCE_VULKAN_RENDER_PIPELINE = DRIVER_RESOURCE_RENDER_PIPELINE, +#endif }; - typedef int64_t DrawListID; - - virtual DrawListID draw_list_begin_for_screen(DisplayServer::WindowID p_screen = 0, const Color &p_clear_color = Color()) = 0; - virtual DrawListID draw_list_begin(RID p_framebuffer, InitialAction p_initial_color_action, FinalAction p_final_color_action, InitialAction p_initial_depth_action, FinalAction p_final_depth_action, const Vector &p_clear_color_values = Vector(), float p_clear_depth = 1.0, uint32_t p_clear_stencil = 0, const Rect2 &p_region = Rect2(), const Vector &p_storage_textures = Vector()) = 0; - virtual Error draw_list_begin_split(RID p_framebuffer, uint32_t p_splits, DrawListID *r_split_ids, InitialAction p_initial_color_action, FinalAction p_final_color_action, InitialAction p_initial_depth_action, FinalAction p_final_depth_action, const Vector &p_clear_color_values = Vector(), float p_clear_depth = 1.0, uint32_t p_clear_stencil = 0, const Rect2 &p_region = Rect2(), const Vector &p_storage_textures = Vector()) = 0; - - virtual void draw_list_set_blend_constants(DrawListID p_list, const Color &p_color) = 0; - virtual void draw_list_bind_render_pipeline(DrawListID p_list, RID p_render_pipeline) = 0; - virtual void draw_list_bind_uniform_set(DrawListID p_list, RID p_uniform_set, uint32_t p_index) = 0; - virtual void draw_list_bind_vertex_array(DrawListID p_list, RID p_vertex_array) = 0; - virtual void draw_list_bind_index_array(DrawListID p_list, RID p_index_array) = 0; - virtual void draw_list_set_line_width(DrawListID p_list, float p_width) = 0; - virtual void draw_list_set_push_constant(DrawListID p_list, const void *p_data, uint32_t p_data_size) = 0; - - virtual void draw_list_draw(DrawListID p_list, bool p_use_indices, uint32_t p_instances = 1, uint32_t p_procedural_vertices = 0) = 0; - - virtual void draw_list_enable_scissor(DrawListID p_list, const Rect2 &p_rect) = 0; - virtual void draw_list_disable_scissor(DrawListID p_list) = 0; - - virtual uint32_t draw_list_get_current_pass() = 0; - virtual DrawListID draw_list_switch_to_next_pass() = 0; - virtual Error draw_list_switch_to_next_pass_split(uint32_t p_splits, DrawListID *r_split_ids) = 0; - - virtual void draw_list_end(BitField p_post_barrier = BARRIER_MASK_ALL_BARRIERS) = 0; - - /***********************/ - /**** COMPUTE LISTS ****/ - /***********************/ - - typedef int64_t ComputeListID; - - virtual ComputeListID compute_list_begin(bool p_allow_draw_overlap = false) = 0; - virtual void compute_list_bind_compute_pipeline(ComputeListID p_list, RID p_compute_pipeline) = 0; - virtual void compute_list_bind_uniform_set(ComputeListID p_list, RID p_uniform_set, uint32_t p_index) = 0; - virtual void compute_list_set_push_constant(ComputeListID p_list, const void *p_data, uint32_t p_data_size) = 0; - virtual void compute_list_dispatch(ComputeListID p_list, uint32_t p_x_groups, uint32_t p_y_groups, uint32_t p_z_groups) = 0; - virtual void compute_list_dispatch_threads(ComputeListID p_list, uint32_t p_x_threads, uint32_t p_y_threads, uint32_t p_z_threads) = 0; - virtual void compute_list_dispatch_indirect(ComputeListID p_list, RID p_buffer, uint32_t p_offset) = 0; - virtual void compute_list_add_barrier(ComputeListID p_list) = 0; - - virtual void compute_list_end(BitField p_post_barrier = BARRIER_MASK_ALL_BARRIERS) = 0; - - virtual void barrier(BitField p_from = BARRIER_MASK_ALL_BARRIERS, BitField p_to = BARRIER_MASK_ALL_BARRIERS) = 0; - virtual void full_barrier() = 0; - - /***************/ - /**** FREE! ****/ - /***************/ - - virtual void free(RID p_id) = 0; - - /****************/ - /**** Timing ****/ - /****************/ - - virtual void capture_timestamp(const String &p_name) = 0; - virtual uint32_t get_captured_timestamps_count() const = 0; - virtual uint64_t get_captured_timestamps_frame() const = 0; - virtual uint64_t get_captured_timestamp_gpu_time(uint32_t p_index) const = 0; - virtual uint64_t get_captured_timestamp_cpu_time(uint32_t p_index) const = 0; - virtual String get_captured_timestamp_name(uint32_t p_index) const = 0; - - /****************/ - /**** LIMITS ****/ - /****************/ - enum Limit { LIMIT_MAX_BOUND_UNIFORM_SETS, LIMIT_MAX_FRAMEBUFFER_COLOR_ATTACHMENTS, @@ -1294,156 +808,111 @@ class RenderingDevice : public Object { LIMIT_VRS_TEXEL_HEIGHT, }; - virtual uint64_t limit_get(Limit p_limit) const = 0; + enum Features { + SUPPORTS_MULTIVIEW, + SUPPORTS_FSR_HALF_FLOAT, + SUPPORTS_ATTACHMENT_VRS, + // If not supported, a fragment shader with only side effets (i.e., writes to buffers, but doesn't output to attachments), may be optimized down to no-op by the GPU driver. + SUPPORTS_FRAGMENT_SHADER_WITH_ONLY_SIDE_EFFECTS, + }; + + //////////////////////////////////////////// + // PROTECTED STUFF + // Not exposed by RenderingDevice, but shared + // with RenderingDeviceDriver for convenience. + //////////////////////////////////////////// +protected: + /*****************/ + /**** GENERIC ****/ + /*****************/ - //methods below not exposed, used by RenderingDeviceRD - virtual void prepare_screen_for_drawing() = 0; + static const char *const FORMAT_NAMES[DATA_FORMAT_MAX]; - virtual void swap_buffers() = 0; + /*****************/ + /**** TEXTURE ****/ + /*****************/ - virtual uint32_t get_frame_delay() const = 0; + static const uint32_t MAX_IMAGE_FORMAT_PLANES = 2; - virtual void submit() = 0; - virtual void sync() = 0; + static const uint32_t TEXTURE_SAMPLES_COUNT[TEXTURE_SAMPLES_MAX]; - enum MemoryType { - MEMORY_TEXTURES, - MEMORY_BUFFERS, - MEMORY_TOTAL - }; + static uint32_t get_image_format_pixel_size(DataFormat p_format); + static void get_compressed_image_format_block_dimensions(DataFormat p_format, uint32_t &r_w, uint32_t &r_h); + uint32_t get_compressed_image_format_block_byte_size(DataFormat p_format); + static uint32_t get_compressed_image_format_pixel_rshift(DataFormat p_format); + static uint32_t get_image_format_required_size(DataFormat p_format, uint32_t p_width, uint32_t p_height, uint32_t p_depth, uint32_t p_mipmaps, uint32_t *r_blockw = nullptr, uint32_t *r_blockh = nullptr, uint32_t *r_depth = nullptr); + static uint32_t get_image_required_mipmaps(uint32_t p_width, uint32_t p_height, uint32_t p_depth); + static bool format_has_stencil(DataFormat p_format); + static uint32_t format_get_plane_count(DataFormat p_format); - virtual uint64_t get_memory_usage(MemoryType p_type) const = 0; + /*****************/ + /**** SAMPLER ****/ + /*****************/ - virtual RenderingDevice *create_local_device() = 0; + static const Color SAMPLER_BORDER_COLOR_VALUE[SAMPLER_BORDER_COLOR_MAX]; - virtual void set_resource_name(RID p_id, const String p_name) = 0; + /**********************/ + /**** VERTEX ARRAY ****/ + /**********************/ - virtual void draw_command_begin_label(String p_label_name, const Color p_color = Color(1, 1, 1, 1)) = 0; - virtual void draw_command_insert_label(String p_label_name, const Color p_color = Color(1, 1, 1, 1)) = 0; - virtual void draw_command_end_label() = 0; + static uint32_t get_format_vertex_size(DataFormat p_format); - virtual String get_device_vendor_name() const = 0; - virtual String get_device_name() const = 0; - virtual RenderingDevice::DeviceType get_device_type() const = 0; - virtual String get_device_api_version() const = 0; - virtual String get_device_pipeline_cache_uuid() const = 0; + /****************/ + /**** SHADER ****/ + /****************/ - virtual uint64_t get_driver_resource(DriverResource p_resource, RID p_rid = RID(), uint64_t p_index = 0) = 0; + static const char *SHADER_STAGE_NAMES[SHADER_STAGE_MAX]; - static RenderingDevice *get_singleton(); - RenderingDevice(); + struct ShaderUniform { + UniformType type = UniformType::UNIFORM_TYPE_MAX; + bool writable = false; + uint32_t binding = 0; + BitField stages; + uint32_t length = 0; // Size of arrays (in total elements), or ubos (in bytes * total elements). -protected: - static const char *shader_stage_names[RenderingDevice::SHADER_STAGE_MAX]; + bool operator!=(const ShaderUniform &p_other) const { + return binding != p_other.binding || type != p_other.type || writable != p_other.writable || stages != p_other.stages || length != p_other.length; + } - static const uint32_t MAX_UNIFORM_SETS = 16; + bool operator<(const ShaderUniform &p_other) const { + if (binding != p_other.binding) { + return binding < p_other.binding; + } + if (type != p_other.type) { + return type < p_other.type; + } + if (writable != p_other.writable) { + return writable < p_other.writable; + } + if (stages != p_other.stages) { + return stages < p_other.stages; + } + if (length != p_other.length) { + return length < p_other.length; + } + return false; + } + }; - //binders to script API - RID _texture_create(const Ref &p_format, const Ref &p_view, const TypedArray &p_data = Array()); - RID _texture_create_shared(const Ref &p_view, RID p_with_texture); - RID _texture_create_shared_from_slice(const Ref &p_view, RID p_with_texture, uint32_t p_layer, uint32_t p_mipmap, uint32_t p_mipmaps = 1, TextureSliceType p_slice_type = TEXTURE_SLICE_2D); - Ref _texture_get_format(RID p_rd_texture); - - FramebufferFormatID _framebuffer_format_create(const TypedArray &p_attachments, uint32_t p_view_count); - FramebufferFormatID _framebuffer_format_create_multipass(const TypedArray &p_attachments, const TypedArray &p_passes, uint32_t p_view_count); - RID _framebuffer_create(const TypedArray &p_textures, FramebufferFormatID p_format_check = INVALID_ID, uint32_t p_view_count = 1); - RID _framebuffer_create_multipass(const TypedArray &p_textures, const TypedArray &p_passes, FramebufferFormatID p_format_check = INVALID_ID, uint32_t p_view_count = 1); - RID _sampler_create(const Ref &p_state); - VertexFormatID _vertex_format_create(const TypedArray &p_vertex_formats); - RID _vertex_array_create(uint32_t p_vertex_count, VertexFormatID p_vertex_format, const TypedArray &p_src_buffers, const Vector &p_offsets = Vector()); - - Ref _shader_compile_spirv_from_source(const Ref &p_source, bool p_allow_cache = true); - Vector _shader_compile_binary_from_spirv(const Ref &p_bytecode, const String &p_shader_name = ""); - RID _shader_create_from_spirv(const Ref &p_spirv, const String &p_shader_name = ""); - - RID _uniform_set_create(const TypedArray &p_uniforms, RID p_shader, uint32_t p_shader_set); - - Error _buffer_update(RID p_buffer, uint32_t p_offset, uint32_t p_size, const Vector &p_data, BitField p_post_barrier = BARRIER_MASK_ALL_BARRIERS); - - RID _render_pipeline_create(RID p_shader, FramebufferFormatID p_framebuffer_format, VertexFormatID p_vertex_format, RenderPrimitive p_render_primitive, const Ref &p_rasterization_state, const Ref &p_multisample_state, const Ref &p_depth_stencil_state, const Ref &p_blend_state, BitField p_dynamic_state_flags, uint32_t p_for_render_pass, const TypedArray &p_specialization_constants); - RID _compute_pipeline_create(RID p_shader, const TypedArray &p_specialization_constants); - - DrawListID _draw_list_begin(RID p_framebuffer, InitialAction p_initial_color_action, FinalAction p_final_color_action, InitialAction p_initial_depth_action, FinalAction p_final_depth_action, const Vector &p_clear_color_values = Vector(), float p_clear_depth = 1.0, uint32_t p_clear_stencil = 0, const Rect2 &p_region = Rect2(), const TypedArray &p_storage_textures = TypedArray()); - Vector _draw_list_begin_split(RID p_framebuffer, uint32_t p_splits, InitialAction p_initial_color_action, FinalAction p_final_color_action, InitialAction p_initial_depth_action, FinalAction p_final_depth_action, const Vector &p_clear_color_values = Vector(), float p_clear_depth = 1.0, uint32_t p_clear_stencil = 0, const Rect2 &p_region = Rect2(), const TypedArray &p_storage_textures = TypedArray()); - void _draw_list_set_push_constant(DrawListID p_list, const Vector &p_data, uint32_t p_data_size); - void _compute_list_set_push_constant(ComputeListID p_list, const Vector &p_data, uint32_t p_data_size); - Vector _draw_list_switch_to_next_pass_split(uint32_t p_splits); - - struct SpirvReflectionData { - BitField stages_mask; - uint64_t vertex_input_mask; - uint32_t fragment_output_mask; - bool is_compute; - uint32_t compute_local_size[3]; - uint32_t push_constant_size; - BitField push_constant_stages_mask; - - struct Uniform { - UniformType type; - uint32_t binding; - BitField stages_mask; - uint32_t length; // Size of arrays (in total elements), or ubos (in bytes * total elements). - bool writable; - }; - Vector> uniforms; - - struct SpecializationConstant { - PipelineSpecializationConstantType type; - uint32_t constant_id; - union { - uint32_t int_value; - float float_value; - bool bool_value; - }; - BitField stages_mask; - }; - Vector specialization_constants; + struct ShaderSpecializationConstant : public PipelineSpecializationConstant { + BitField stages; }; - Error _reflect_spirv(const Vector &p_spirv, SpirvReflectionData &r_reflection_data); + struct ShaderDescription { + uint64_t vertex_input_mask = 0; + uint32_t fragment_output_mask = 0; + bool is_compute = false; + uint32_t compute_local_size[3] = {}; + uint32_t push_constant_size = 0; -#ifndef DISABLE_DEPRECATED - BitField _convert_barrier_mask_81356(BitField p_old_barrier); - void _draw_list_end_bind_compat_81356(BitField p_post_barrier); - void _compute_list_end_bind_compat_81356(BitField p_post_barrier); - void _barrier_bind_compat_81356(BitField p_from, BitField p_to); -#endif + Vector> uniform_sets; + Vector specialization_constants; + }; + + struct ShaderReflection : public ShaderDescription { + BitField stages; + BitField push_constant_stages; + }; }; -VARIANT_ENUM_CAST(RenderingDevice::DeviceType) -VARIANT_ENUM_CAST(RenderingDevice::DriverResource) -VARIANT_ENUM_CAST(RenderingDevice::ShaderStage) -VARIANT_ENUM_CAST(RenderingDevice::ShaderLanguage) -VARIANT_ENUM_CAST(RenderingDevice::CompareOperator) -VARIANT_ENUM_CAST(RenderingDevice::DataFormat) -VARIANT_BITFIELD_CAST(RenderingDevice::BarrierMask); -VARIANT_ENUM_CAST(RenderingDevice::TextureType) -VARIANT_ENUM_CAST(RenderingDevice::TextureSamples) -VARIANT_BITFIELD_CAST(RenderingDevice::TextureUsageBits) -VARIANT_ENUM_CAST(RenderingDevice::TextureSwizzle) -VARIANT_ENUM_CAST(RenderingDevice::TextureSliceType) -VARIANT_ENUM_CAST(RenderingDevice::SamplerFilter) -VARIANT_ENUM_CAST(RenderingDevice::SamplerRepeatMode) -VARIANT_ENUM_CAST(RenderingDevice::SamplerBorderColor) -VARIANT_ENUM_CAST(RenderingDevice::VertexFrequency) -VARIANT_ENUM_CAST(RenderingDevice::IndexBufferFormat) -VARIANT_BITFIELD_CAST(RenderingDevice::StorageBufferUsage) -VARIANT_ENUM_CAST(RenderingDevice::UniformType) -VARIANT_ENUM_CAST(RenderingDevice::RenderPrimitive) -VARIANT_ENUM_CAST(RenderingDevice::PolygonCullMode) -VARIANT_ENUM_CAST(RenderingDevice::PolygonFrontFace) -VARIANT_ENUM_CAST(RenderingDevice::StencilOperation) -VARIANT_ENUM_CAST(RenderingDevice::LogicOperation) -VARIANT_ENUM_CAST(RenderingDevice::BlendFactor) -VARIANT_ENUM_CAST(RenderingDevice::BlendOperation) -VARIANT_BITFIELD_CAST(RenderingDevice::PipelineDynamicStateFlags) -VARIANT_ENUM_CAST(RenderingDevice::PipelineSpecializationConstantType) -VARIANT_ENUM_CAST(RenderingDevice::InitialAction) -VARIANT_ENUM_CAST(RenderingDevice::FinalAction) -VARIANT_ENUM_CAST(RenderingDevice::Limit) -VARIANT_ENUM_CAST(RenderingDevice::MemoryType) -VARIANT_ENUM_CAST(RenderingDevice::Features) - -typedef RenderingDevice RD; - -#endif // RENDERING_DEVICE_H +#endif // RENDERING_DEVICE_COMMONS_H diff --git a/servers/rendering/rendering_device_driver.cpp b/servers/rendering/rendering_device_driver.cpp new file mode 100644 index 000000000000..ba1730e3a2ff --- /dev/null +++ b/servers/rendering/rendering_device_driver.cpp @@ -0,0 +1,358 @@ +/**************************************************************************/ +/* rendering_device_driver.cpp */ +/**************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/**************************************************************************/ +/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ +/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/**************************************************************************/ + +#include "rendering_device_driver.h" + +#include "thirdparty/spirv-reflect/spirv_reflect.h" + +/****************/ +/**** SHADER ****/ +/****************/ + +Error RenderingDeviceDriver::_reflect_spirv(VectorView p_spirv, ShaderReflection &r_reflection) { + r_reflection = {}; + + for (uint32_t i = 0; i < p_spirv.size(); i++) { + ShaderStage stage = p_spirv[i].shader_stage; + ShaderStage stage_flag = (ShaderStage)(1 << p_spirv[i].shader_stage); + + if (p_spirv[i].shader_stage == SHADER_STAGE_COMPUTE) { + r_reflection.is_compute = true; + ERR_FAIL_COND_V_MSG(p_spirv.size() != 1, FAILED, + "Compute shaders can only receive one stage, dedicated to compute."); + } + ERR_FAIL_COND_V_MSG(r_reflection.stages.has_flag(stage_flag), FAILED, + "Stage " + String(SHADER_STAGE_NAMES[p_spirv[i].shader_stage]) + " submitted more than once."); + + { + SpvReflectShaderModule module; + const uint8_t *spirv = p_spirv[i].spirv.ptr(); + SpvReflectResult result = spvReflectCreateShaderModule(p_spirv[i].spirv.size(), spirv, &module); + ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, FAILED, + "Reflection of SPIR-V shader stage '" + String(SHADER_STAGE_NAMES[p_spirv[i].shader_stage]) + "' failed parsing shader."); + + if (r_reflection.is_compute) { + r_reflection.compute_local_size[0] = module.entry_points->local_size.x; + r_reflection.compute_local_size[1] = module.entry_points->local_size.y; + r_reflection.compute_local_size[2] = module.entry_points->local_size.z; + } + uint32_t binding_count = 0; + result = spvReflectEnumerateDescriptorBindings(&module, &binding_count, nullptr); + ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, FAILED, + "Reflection of SPIR-V shader stage '" + String(SHADER_STAGE_NAMES[p_spirv[i].shader_stage]) + "' failed enumerating descriptor bindings."); + + if (binding_count > 0) { + // Parse bindings. + + Vector bindings; + bindings.resize(binding_count); + result = spvReflectEnumerateDescriptorBindings(&module, &binding_count, bindings.ptrw()); + + ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, FAILED, + "Reflection of SPIR-V shader stage '" + String(SHADER_STAGE_NAMES[p_spirv[i].shader_stage]) + "' failed getting descriptor bindings."); + + for (uint32_t j = 0; j < binding_count; j++) { + const SpvReflectDescriptorBinding &binding = *bindings[j]; + + ShaderUniform uniform; + + bool need_array_dimensions = false; + bool need_block_size = false; + bool may_be_writable = false; + + switch (binding.descriptor_type) { + case SPV_REFLECT_DESCRIPTOR_TYPE_SAMPLER: { + uniform.type = UNIFORM_TYPE_SAMPLER; + need_array_dimensions = true; + } break; + case SPV_REFLECT_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER: { + uniform.type = UNIFORM_TYPE_SAMPLER_WITH_TEXTURE; + need_array_dimensions = true; + } break; + case SPV_REFLECT_DESCRIPTOR_TYPE_SAMPLED_IMAGE: { + uniform.type = UNIFORM_TYPE_TEXTURE; + need_array_dimensions = true; + } break; + case SPV_REFLECT_DESCRIPTOR_TYPE_STORAGE_IMAGE: { + uniform.type = UNIFORM_TYPE_IMAGE; + need_array_dimensions = true; + may_be_writable = true; + } break; + case SPV_REFLECT_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER: { + uniform.type = UNIFORM_TYPE_TEXTURE_BUFFER; + need_array_dimensions = true; + } break; + case SPV_REFLECT_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER: { + uniform.type = UNIFORM_TYPE_IMAGE_BUFFER; + need_array_dimensions = true; + may_be_writable = true; + } break; + case SPV_REFLECT_DESCRIPTOR_TYPE_UNIFORM_BUFFER: { + uniform.type = UNIFORM_TYPE_UNIFORM_BUFFER; + need_block_size = true; + } break; + case SPV_REFLECT_DESCRIPTOR_TYPE_STORAGE_BUFFER: { + uniform.type = UNIFORM_TYPE_STORAGE_BUFFER; + need_block_size = true; + may_be_writable = true; + } break; + case SPV_REFLECT_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC: { + ERR_PRINT("Dynamic uniform buffer not supported."); + continue; + } break; + case SPV_REFLECT_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC: { + ERR_PRINT("Dynamic storage buffer not supported."); + continue; + } break; + case SPV_REFLECT_DESCRIPTOR_TYPE_INPUT_ATTACHMENT: { + uniform.type = UNIFORM_TYPE_INPUT_ATTACHMENT; + need_array_dimensions = true; + } break; + case SPV_REFLECT_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR: { + ERR_PRINT("Acceleration structure not supported."); + continue; + } break; + } + + if (need_array_dimensions) { + if (binding.array.dims_count == 0) { + uniform.length = 1; + } else { + for (uint32_t k = 0; k < binding.array.dims_count; k++) { + if (k == 0) { + uniform.length = binding.array.dims[0]; + } else { + uniform.length *= binding.array.dims[k]; + } + } + } + + } else if (need_block_size) { + uniform.length = binding.block.size; + } else { + uniform.length = 0; + } + + if (may_be_writable) { + uniform.writable = !(binding.type_description->decoration_flags & SPV_REFLECT_DECORATION_NON_WRITABLE) && !(binding.block.decoration_flags & SPV_REFLECT_DECORATION_NON_WRITABLE); + } else { + uniform.writable = false; + } + + uniform.binding = binding.binding; + uint32_t set = binding.set; + + ERR_FAIL_COND_V_MSG(set >= MAX_UNIFORM_SETS, FAILED, + "On shader stage '" + String(SHADER_STAGE_NAMES[stage]) + "', uniform '" + binding.name + "' uses a set (" + itos(set) + ") index larger than what is supported (" + itos(MAX_UNIFORM_SETS) + ")."); + + if (set < (uint32_t)r_reflection.uniform_sets.size()) { + // Check if this already exists. + bool exists = false; + for (int k = 0; k < r_reflection.uniform_sets[set].size(); k++) { + if (r_reflection.uniform_sets[set][k].binding == uniform.binding) { + // Already exists, verify that it's the same type. + ERR_FAIL_COND_V_MSG(r_reflection.uniform_sets[set][k].type != uniform.type, FAILED, + "On shader stage '" + String(SHADER_STAGE_NAMES[stage]) + "', uniform '" + binding.name + "' trying to reuse location for set=" + itos(set) + ", binding=" + itos(uniform.binding) + " with different uniform type."); + + // Also, verify that it's the same size. + ERR_FAIL_COND_V_MSG(r_reflection.uniform_sets[set][k].length != uniform.length, FAILED, + "On shader stage '" + String(SHADER_STAGE_NAMES[stage]) + "', uniform '" + binding.name + "' trying to reuse location for set=" + itos(set) + ", binding=" + itos(uniform.binding) + " with different uniform size."); + + // Also, verify that it has the same writability. + ERR_FAIL_COND_V_MSG(r_reflection.uniform_sets[set][k].writable != uniform.writable, FAILED, + "On shader stage '" + String(SHADER_STAGE_NAMES[stage]) + "', uniform '" + binding.name + "' trying to reuse location for set=" + itos(set) + ", binding=" + itos(uniform.binding) + " with different writability."); + + // Just append stage mask and return. + r_reflection.uniform_sets.write[set].write[k].stages.set_flag(stage_flag); + exists = true; + break; + } + } + + if (exists) { + continue; // Merged. + } + } + + uniform.stages.set_flag(stage_flag); + + if (set >= (uint32_t)r_reflection.uniform_sets.size()) { + r_reflection.uniform_sets.resize(set + 1); + } + + r_reflection.uniform_sets.write[set].push_back(uniform); + } + } + + { + // Specialization constants. + + uint32_t sc_count = 0; + result = spvReflectEnumerateSpecializationConstants(&module, &sc_count, nullptr); + ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, FAILED, + "Reflection of SPIR-V shader stage '" + String(SHADER_STAGE_NAMES[p_spirv[i].shader_stage]) + "' failed enumerating specialization constants."); + + if (sc_count) { + Vector spec_constants; + spec_constants.resize(sc_count); + + result = spvReflectEnumerateSpecializationConstants(&module, &sc_count, spec_constants.ptrw()); + ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, FAILED, + "Reflection of SPIR-V shader stage '" + String(SHADER_STAGE_NAMES[p_spirv[i].shader_stage]) + "' failed obtaining specialization constants."); + + for (uint32_t j = 0; j < sc_count; j++) { + int32_t existing = -1; + ShaderSpecializationConstant sconst; + SpvReflectSpecializationConstant *spc = spec_constants[j]; + + sconst.constant_id = spc->constant_id; + sconst.int_value = 0; // Clear previous value JIC. + switch (spc->constant_type) { + case SPV_REFLECT_SPECIALIZATION_CONSTANT_BOOL: { + sconst.type = PIPELINE_SPECIALIZATION_CONSTANT_TYPE_BOOL; + sconst.bool_value = spc->default_value.int_bool_value != 0; + } break; + case SPV_REFLECT_SPECIALIZATION_CONSTANT_INT: { + sconst.type = PIPELINE_SPECIALIZATION_CONSTANT_TYPE_INT; + sconst.int_value = spc->default_value.int_bool_value; + } break; + case SPV_REFLECT_SPECIALIZATION_CONSTANT_FLOAT: { + sconst.type = PIPELINE_SPECIALIZATION_CONSTANT_TYPE_FLOAT; + sconst.float_value = spc->default_value.float_value; + } break; + } + sconst.stages.set_flag(stage_flag); + + for (int k = 0; k < r_reflection.specialization_constants.size(); k++) { + if (r_reflection.specialization_constants[k].constant_id == sconst.constant_id) { + ERR_FAIL_COND_V_MSG(r_reflection.specialization_constants[k].type != sconst.type, FAILED, "More than one specialization constant used for id (" + itos(sconst.constant_id) + "), but their types differ."); + ERR_FAIL_COND_V_MSG(r_reflection.specialization_constants[k].int_value != sconst.int_value, FAILED, "More than one specialization constant used for id (" + itos(sconst.constant_id) + "), but their default values differ."); + existing = k; + break; + } + } + + if (existing > 0) { + r_reflection.specialization_constants.write[existing].stages.set_flag(stage_flag); + } else { + r_reflection.specialization_constants.push_back(sconst); + } + } + } + } + + if (stage == SHADER_STAGE_VERTEX) { + uint32_t iv_count = 0; + result = spvReflectEnumerateInputVariables(&module, &iv_count, nullptr); + ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, FAILED, + "Reflection of SPIR-V shader stage '" + String(SHADER_STAGE_NAMES[p_spirv[i].shader_stage]) + "' failed enumerating input variables."); + + if (iv_count) { + Vector input_vars; + input_vars.resize(iv_count); + + result = spvReflectEnumerateInputVariables(&module, &iv_count, input_vars.ptrw()); + ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, FAILED, + "Reflection of SPIR-V shader stage '" + String(SHADER_STAGE_NAMES[p_spirv[i].shader_stage]) + "' failed obtaining input variables."); + + for (uint32_t j = 0; j < iv_count; j++) { + if (input_vars[j] && input_vars[j]->decoration_flags == 0) { // Regular input. + r_reflection.vertex_input_mask |= (((uint64_t)1) << input_vars[j]->location); + } + } + } + } + + if (stage == SHADER_STAGE_FRAGMENT) { + uint32_t ov_count = 0; + result = spvReflectEnumerateOutputVariables(&module, &ov_count, nullptr); + ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, FAILED, + "Reflection of SPIR-V shader stage '" + String(SHADER_STAGE_NAMES[p_spirv[i].shader_stage]) + "' failed enumerating output variables."); + + if (ov_count) { + Vector output_vars; + output_vars.resize(ov_count); + + result = spvReflectEnumerateOutputVariables(&module, &ov_count, output_vars.ptrw()); + ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, FAILED, + "Reflection of SPIR-V shader stage '" + String(SHADER_STAGE_NAMES[p_spirv[i].shader_stage]) + "' failed obtaining output variables."); + + for (uint32_t j = 0; j < ov_count; j++) { + const SpvReflectInterfaceVariable *refvar = output_vars[j]; + if (refvar != nullptr && refvar->built_in != SpvBuiltInFragDepth) { + r_reflection.fragment_output_mask |= 1 << refvar->location; + } + } + } + } + + uint32_t pc_count = 0; + result = spvReflectEnumeratePushConstantBlocks(&module, &pc_count, nullptr); + ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, FAILED, + "Reflection of SPIR-V shader stage '" + String(SHADER_STAGE_NAMES[p_spirv[i].shader_stage]) + "' failed enumerating push constants."); + + if (pc_count) { + ERR_FAIL_COND_V_MSG(pc_count > 1, FAILED, + "Reflection of SPIR-V shader stage '" + String(SHADER_STAGE_NAMES[p_spirv[i].shader_stage]) + "': Only one push constant is supported, which should be the same across shader stages."); + + Vector pconstants; + pconstants.resize(pc_count); + result = spvReflectEnumeratePushConstantBlocks(&module, &pc_count, pconstants.ptrw()); + ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, FAILED, + "Reflection of SPIR-V shader stage '" + String(SHADER_STAGE_NAMES[p_spirv[i].shader_stage]) + "' failed obtaining push constants."); +#if 0 + if (pconstants[0] == nullptr) { + Ref f = FileAccess::open("res://popo.spv", FileAccess::WRITE); + f->store_buffer((const uint8_t *)&SpirV[0], SpirV.size() * sizeof(uint32_t)); + } +#endif + + ERR_FAIL_COND_V_MSG(r_reflection.push_constant_size && r_reflection.push_constant_size != pconstants[0]->size, FAILED, + "Reflection of SPIR-V shader stage '" + String(SHADER_STAGE_NAMES[p_spirv[i].shader_stage]) + "': Push constant block must be the same across shader stages."); + + r_reflection.push_constant_size = pconstants[0]->size; + r_reflection.push_constant_stages.set_flag(stage_flag); + + //print_line("Stage: " + String(SHADER_STAGE_NAMES[stage]) + " push constant of size=" + itos(push_constant.push_constant_size)); + } + + // Destroy the reflection data when no longer required. + spvReflectDestroyShaderModule(&module); + } + + r_reflection.stages.set_flag(stage_flag); + } + + return OK; +} + +/******************/ + +RenderingDeviceDriver::~RenderingDeviceDriver() {} diff --git a/servers/rendering/rendering_device_driver.h b/servers/rendering/rendering_device_driver.h new file mode 100644 index 000000000000..41d8069d65fc --- /dev/null +++ b/servers/rendering/rendering_device_driver.h @@ -0,0 +1,626 @@ +/**************************************************************************/ +/* rendering_device_driver.h */ +/**************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/**************************************************************************/ +/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ +/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/**************************************************************************/ + +#ifndef RENDERING_DEVICE_DRIVER_H +#define RENDERING_DEVICE_DRIVER_H + +#include "core/object/object.h" +#include "core/variant/type_info.h" +#include "servers/display_server.h" +#include "servers/rendering/rendering_device_commons.h" + +class ApiContextRD; + +// This may one day be used in Godot for interoperability between C arrays, Vector and LocalVector. +// (See https://github.com/godotengine/godot-proposals/issues/5144.) +template +class VectorView { + const T *_ptr = nullptr; + const uint32_t _size = 0; + +public: + const T &operator[](uint32_t p_index) { + DEV_ASSERT(p_index < _size); + return _ptr[p_index]; + } + + _ALWAYS_INLINE_ const T *ptr() const { return _ptr; } + _ALWAYS_INLINE_ uint32_t size() const { return _size; } + + VectorView() = default; + VectorView(const T &p_ptr) : + // With this one you can pass a single element very conveniently! + _ptr(&p_ptr), + _size(1) {} + VectorView(const T *p_ptr, uint32_t p_size) : + _ptr(p_ptr), _size(p_size) {} + VectorView(const Vector &p_lv) : + _ptr(p_lv.ptr()), _size(p_lv.size()) {} + VectorView(const LocalVector &p_lv) : + _ptr(p_lv.ptr()), _size(p_lv.size()) {} +}; + +// These utilities help drivers avoid allocations. +#define ALLOCA(m_size) ((m_size != 0) ? alloca(m_size) : nullptr) +#define ALLOCA_ARRAY(m_type, m_count) ((m_type *)ALLOCA(sizeof(m_type) * (m_count))) +#define ALLOCA_SINGLE(m_type) ALLOCA_ARRAY(m_type, 1) + +// This helps forwarding certain arrays to the API with confidence. +#define ARRAYS_COMPATIBLE(m_type_a, m_type_b) (sizeof(m_type_a) == sizeof(m_type_b) && alignof(m_type_a) == alignof(m_type_b)) +// This is used when you also need to ensure structured types are compatible field-by-field. +// TODO: The fieldwise check is unimplemented, but still this one is useful, as a strong annotation about the needs. +#define ARRAYS_COMPATIBLE_FIELDWISE(m_type_a, m_type_b) ARRAYS_COMPATIBLE(m_type_a, m_type_b) +// Another utility, to make it easy to compare members of different enums, which is not fine with some compilers. +#define ENUM_MEMBERS_EQUAL(m_a, m_b) ((int64_t)m_a == (int64_t)m_b) + +// Design principles: +// - Very little validation is done, and normally only in dev or debug builds. +// - Error reporting is generally simple: returning an id of 0 or a false boolean. +// - Certain enums/constants/structs follow Vulkan values/layout. That makes things easier for RDDVulkan (it asserts compatibility). +// - We allocate as little as possible in functions expected to be quick (a counterexample is loading/saving shaders) and use alloca() whenever suitable. +// - We try to back our various ids with the native ones. When a bespoke id is needed, if the address of the object is fixed (e.g., a RBSet item), a pointer to it is under the hood. +// - Every struct has default initializers. +// - Using VectorView to take array-like arguments. Vector is an exception (an indiom for "BLOB"). +class RenderingDeviceDriver : public RenderingDeviceCommons { +public: + struct ID { + uint64_t id = 0; + _ALWAYS_INLINE_ ID() = default; + _ALWAYS_INLINE_ ID(uint64_t p_id) : + id(p_id) {} + }; + +#define DEFINE_ID(m_name) \ + struct m_name##ID : public ID { \ + _ALWAYS_INLINE_ operator bool() const { return id != 0; } \ + _ALWAYS_INLINE_ m_name##ID &operator=(m_name##ID p_other) { \ + id = p_other.id; \ + return *this; \ + } \ + _ALWAYS_INLINE_ m_name##ID(const m_name##ID &p_other) : ID(p_other.id) {} \ + _ALWAYS_INLINE_ explicit m_name##ID() = default; \ + _ALWAYS_INLINE_ explicit m_name##ID(uint64_t p_int) : ID(p_int) {} \ + _ALWAYS_INLINE_ explicit m_name##ID(void *p_ptr) : ID((uint64_t)p_ptr) {} \ + }; + + // Id types declared before anything else to prevent cyclic dependencies between the different concerns. + DEFINE_ID(Buffer); + DEFINE_ID(Texture); + DEFINE_ID(Sampler); + DEFINE_ID(VertexFormat); + DEFINE_ID(CommandPool); + DEFINE_ID(CommandBuffer); + DEFINE_ID(Framebuffer); + DEFINE_ID(Shader); + DEFINE_ID(UniformSet); + DEFINE_ID(Pipeline); + DEFINE_ID(RenderPass); + DEFINE_ID(QueryPool); + + /****************/ + /**** MEMORY ****/ + /****************/ + + enum MemoryAllocationType { + MEMORY_ALLOCATION_TYPE_CPU, // For images, CPU allocation also means linear, GPU is tiling optimal. + MEMORY_ALLOCATION_TYPE_GPU, + }; + + /*****************/ + /**** BUFFERS ****/ + /*****************/ + + enum BufferUsageBits { + BUFFER_USAGE_TRANSFER_FROM_BIT = (1 << 0), + BUFFER_USAGE_TRANSFER_TO_BIT = (1 << 1), + BUFFER_USAGE_TEXEL_BIT = (1 << 2), + BUFFER_USAGE_UNIFORM_BIT = (1 << 4), + BUFFER_USAGE_STORAGE_BIT = (1 << 5), + BUFFER_USAGE_INDEX_BIT = (1 << 6), + BUFFER_USAGE_VERTEX_BIT = (1 << 7), + BUFFER_USAGE_INDIRECT_BIT = (1 << 8), + }; + + virtual BufferID buffer_create(uint64_t p_size, BitField p_usage, MemoryAllocationType p_allocation_type) = 0; + // Only for a buffer with BUFFER_USAGE_TEXEL_BIT. + virtual bool buffer_set_texel_format(BufferID p_buffer, DataFormat p_format) = 0; + virtual void buffer_free(BufferID p_buffer) = 0; + virtual uint64_t buffer_get_allocation_size(BufferID p_buffer) = 0; + virtual uint8_t *buffer_map(BufferID p_buffer) = 0; + virtual void buffer_unmap(BufferID p_buffer) = 0; + + /*****************/ + /**** TEXTURE ****/ + /*****************/ + + struct TextureView { + DataFormat format = DATA_FORMAT_MAX; + TextureSwizzle swizzle_r = TEXTURE_SWIZZLE_R; + TextureSwizzle swizzle_g = TEXTURE_SWIZZLE_G; + TextureSwizzle swizzle_b = TEXTURE_SWIZZLE_B; + TextureSwizzle swizzle_a = TEXTURE_SWIZZLE_A; + }; + + enum TextureLayout { + TEXTURE_LAYOUT_UNDEFINED, + TEXTURE_LAYOUT_GENERAL, + TEXTURE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, + TEXTURE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, + TEXTURE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL, + TEXTURE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, + TEXTURE_LAYOUT_TRANSFER_SRC_OPTIMAL, + TEXTURE_LAYOUT_TRANSFER_DST_OPTIMAL, + TEXTURE_LAYOUT_PREINITIALIZED, + TEXTURE_LAYOUT_VRS_ATTACHMENT_OPTIMAL = 1000164003, + }; + + enum TextureAspectBits { + TEXTURE_ASPECT_COLOR_BIT = (1 << 0), + TEXTURE_ASPECT_DEPTH_BIT = (1 << 1), + TEXTURE_ASPECT_STENCIL_BIT = (1 << 2), + }; + + struct TextureSubresource { + BitField aspect; + uint32_t layer = 0; + uint32_t mipmap = 0; + }; + + struct TextureSubresourceLayers { + BitField aspect; + uint32_t mipmap = 0; + uint32_t base_layer = 0; + uint32_t layer_count = 0; + }; + + struct TextureSubresourceRange { + BitField aspect; + uint32_t base_mipmap = 0; + uint32_t mipmap_count = 0; + uint32_t base_layer = 0; + uint32_t layer_count = 0; + }; + + struct TextureSubresourceLayout { + uint64_t offset = 0; + uint64_t size = 0; + uint64_t row_pitch = 0; + uint64_t array_pitch = 0; + uint64_t depth_pitch = 0; + }; + + virtual TextureID texture_create(const TextureFormat &p_format, const TextureView &p_view) = 0; + virtual TextureID texture_create_from_extension(uint64_t p_native_texture, TextureType p_type, DataFormat p_format, uint32_t p_array_layers, bool p_depth_stencil) = 0; + // texture_create_shared_*() can only use original, non-view textures as original. RenderingDevice is responsible for ensuring that. + virtual TextureID texture_create_shared(TextureID p_original_texture, const TextureView &p_view) = 0; + virtual TextureID texture_create_shared_from_slice(TextureID p_original_texture, const TextureView &p_view, TextureSliceType p_slice_type, uint32_t p_layer, uint32_t p_layers, uint32_t p_mipmap, uint32_t p_mipmaps) = 0; + virtual void texture_free(TextureID p_texture) = 0; + virtual uint64_t texture_get_allocation_size(TextureID p_texture) = 0; + virtual void texture_get_subresource_layout(TextureID p_texture, const TextureSubresource &p_subresource, TextureSubresourceLayout *r_layout) = 0; + virtual uint8_t *texture_map(TextureID p_texture) = 0; + virtual void texture_unmap(TextureID p_texture) = 0; + virtual BitField texture_get_usages_supported_by_format(DataFormat p_format, bool p_cpu_readable) = 0; + + /*****************/ + /**** SAMPLER ****/ + /*****************/ + + virtual SamplerID sampler_create(const SamplerState &p_state) = 0; + virtual void sampler_free(SamplerID p_sampler) = 0; + virtual bool sampler_is_format_supported_for_filter(DataFormat p_format, SamplerFilter p_filter) = 0; + + /**********************/ + /**** VERTEX ARRAY ****/ + /**********************/ + + virtual VertexFormatID vertex_format_create(VectorView p_vertex_attribs) = 0; + virtual void vertex_format_free(VertexFormatID p_vertex_format) = 0; + + /******************/ + /**** BARRIERS ****/ + /******************/ + + enum PipelineStageBits { + PIPELINE_STAGE_TOP_OF_PIPE_BIT = (1 << 0), + PIPELINE_STAGE_DRAW_INDIRECT_BIT = (1 << 1), + PIPELINE_STAGE_VERTEX_INPUT_BIT = (1 << 2), + PIPELINE_STAGE_VERTEX_SHADER_BIT = (1 << 3), + PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT = (1 << 4), + PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT = (1 << 5), + PIPELINE_STAGE_GEOMETRY_SHADER_BIT = (1 << 6), + PIPELINE_STAGE_FRAGMENT_SHADER_BIT = (1 << 7), + PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT = (1 << 8), + PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT = (1 << 9), + PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT = (1 << 10), + PIPELINE_STAGE_COMPUTE_SHADER_BIT = (1 << 11), + PIPELINE_STAGE_TRANSFER_BIT = (1 << 12), + PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT = (1 << 13), + PIPELINE_STAGE_ALL_GRAPHICS_BIT = (1 << 15), + PIPELINE_STAGE_ALL_COMMANDS_BIT = (1 << 16), + }; + + enum BarrierAccessBits { + BARRIER_ACCESS_INDIRECT_COMMAND_READ_BIT = (1 << 0), + BARRIER_ACCESS_INDEX_READ_BIT = (1 << 1), + BARRIER_ACCESS_VERTEX_ATTRIBUTE_READ_BIT = (1 << 2), + BARRIER_ACCESS_UNIFORM_READ_BIT = (1 << 3), + BARRIER_ACCESS_INPUT_ATTACHMENT_READ_BIT = (1 << 4), + BARRIER_ACCESS_SHADER_READ_BIT = (1 << 5), + BARRIER_ACCESS_SHADER_WRITE_BIT = (1 << 6), + BARRIER_ACCESS_COLOR_ATTACHMENT_READ_BIT = (1 << 7), + BARRIER_ACCESS_COLOR_ATTACHMENT_WRITE_BIT = (1 << 8), + BARRIER_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT = (1 << 9), + BARRIER_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT = (1 << 10), + BARRIER_ACCESS_TRANSFER_READ_BIT = (1 << 11), + BARRIER_ACCESS_TRANSFER_WRITE_BIT = (1 << 12), + BARRIER_ACCESS_HOST_READ_BIT = (1 << 13), + BARRIER_ACCESS_HOST_WRITE_BIT = (1 << 14), + BARRIER_ACCESS_MEMORY_READ_BIT = (1 << 15), + BARRIER_ACCESS_MEMORY_WRITE_BIT = (1 << 16), + BARRIER_ACCESS_FRAGMENT_SHADING_RATE_ATTACHMENT_READ_BIT = (1 << 23), + }; + + struct MemoryBarrier { + BitField src_access; + BitField dst_access; + }; + + struct BufferBarrier { + BufferID buffer; + BitField src_access; + BitField dst_access; + uint64_t offset = 0; + uint64_t size = 0; + }; + + struct TextureBarrier { + TextureID texture; + BitField src_access; + BitField dst_access; + TextureLayout prev_layout = TEXTURE_LAYOUT_UNDEFINED; + TextureLayout next_layout = TEXTURE_LAYOUT_UNDEFINED; + TextureSubresourceRange subresources; + }; + + virtual void command_pipeline_barrier( + CommandBufferID p_cmd_buffer, + BitField p_src_stages, + BitField p_dst_stages, + VectorView p_memory_barriers, + VectorView p_buffer_barriers, + VectorView p_texture_barriers) = 0; + + /*************************/ + /**** COMMAND BUFFERS ****/ + /*************************/ + + // ----- POOL ----- + + virtual CommandPoolID command_pool_create() = 0; + virtual void command_pool_free(CommandPoolID p_cmd_pool) = 0; + + // ----- BUFFER ----- + + enum CommandBufferType { + COMMAND_BUFFER_TYPE_PRIMARY, + COMMAND_BUFFER_TYPE_SECONDARY, + }; + + virtual CommandBufferID command_buffer_create(CommandBufferType p_cmd_buffer_type, CommandPoolID p_cmd_pool) = 0; + virtual bool command_buffer_begin(CommandBufferID p_cmd_buffer) = 0; + virtual bool command_buffer_begin_secondary(CommandBufferID p_cmd_buffer, RenderPassID p_render_pass, uint32_t p_subpass, FramebufferID p_framebuffer) = 0; + virtual void command_buffer_end(CommandBufferID p_cmd_buffer) = 0; + virtual void command_buffer_execute_secondary(CommandBufferID p_cmd_buffer, VectorView p_secondary_cmd_buffers) = 0; + + /*********************/ + /**** FRAMEBUFFER ****/ + /*********************/ + + virtual FramebufferID framebuffer_create(RenderPassID p_render_pass, VectorView p_attachments, uint32_t p_width, uint32_t p_height) = 0; + virtual void framebuffer_free(FramebufferID p_framebuffer) = 0; + + /****************/ + /**** SHADER ****/ + /****************/ + + virtual String shader_get_binary_cache_key() = 0; + virtual Vector shader_compile_binary_from_spirv(VectorView p_spirv, const String &p_shader_name) = 0; + virtual ShaderID shader_create_from_bytecode(const Vector &p_shader_binary, ShaderDescription &r_shader_desc, String &r_name) = 0; + virtual void shader_free(ShaderID p_shader) = 0; + +protected: + // An optional service to implementations. + Error _reflect_spirv(VectorView p_spirv, ShaderReflection &r_reflection); + +public: + /*********************/ + /**** UNIFORM SET ****/ + /*********************/ + + struct BoundUniform { + UniformType type = UNIFORM_TYPE_MAX; + uint32_t binding = 0xffffffff; // Binding index as specified in shader. + LocalVector ids; + }; + + virtual UniformSetID uniform_set_create(VectorView p_uniforms, ShaderID p_shader, uint32_t p_set_index) = 0; + virtual void uniform_set_free(UniformSetID p_uniform_set) = 0; + + /******************/ + /**** TRANSFER ****/ + /******************/ + + struct BufferCopyRegion { + uint64_t src_offset = 0; + uint64_t dst_offset = 0; + uint64_t size = 0; + }; + + struct TextureCopyRegion { + TextureSubresourceLayers src_subresources; + Vector3i src_offset; + TextureSubresourceLayers dst_subresources; + Vector3i dst_offset; + Vector3i size; + }; + + struct BufferTextureCopyRegion { + uint64_t buffer_offset = 0; + uint32_t buffer_row_length = 0; + uint32_t buffer_texture_height = 0; + TextureSubresourceLayers texture_subresources; + Vector3i texture_offset; + Vector3i texture_region_size; + }; + + virtual void command_clear_buffer(CommandBufferID p_cmd_buffer, BufferID p_buffer, uint64_t p_offset, uint64_t p_size) = 0; + virtual void command_copy_buffer(CommandBufferID p_cmd_buffer, BufferID p_src_buffer, BufferID p_dst_buffer, VectorView p_regions) = 0; + virtual void command_copy_texture(CommandBufferID p_cmd_buffer, TextureID p_src_texture, TextureLayout p_src_texture_layout, TextureID p_dst_texture, TextureLayout p_dst_texture_layout, VectorView p_regions) = 0; + virtual void command_resolve_texture(CommandBufferID p_cmd_buffer, TextureID p_src_texture, TextureLayout p_src_texture_layout, TextureID p_dst_texture, TextureLayout p_dst_texture_layout, VectorView p_regions) = 0; + + virtual void command_clear_color_texture(CommandBufferID p_cmd_buffer, TextureID p_texture, TextureLayout p_texture_layout, const Color &p_color, const TextureSubresourceRange &p_subresources) = 0; + + virtual void command_copy_buffer_to_texture(CommandBufferID p_cmd_buffer, BufferID p_src_buffer, TextureID p_dst_texture, TextureLayout p_dst_texture_layout, VectorView p_regions) = 0; + virtual void command_copy_texture_to_buffer(CommandBufferID p_cmd_buffer, TextureID p_src_texture, TextureLayout p_src_texture_layout, BufferID p_dst_buffer, VectorView p_regions) = 0; + + /******************/ + /**** PIPELINE ****/ + /******************/ + + virtual void pipeline_free(PipelineID p_pipeline_id) = 0; + + // ----- BINDING ----- + + virtual void command_bind_push_constants(CommandBufferID p_cmd_buffer, ShaderID p_shader, uint32_t p_first_index, VectorView p_data) = 0; + + // ----- CACHE ----- + + virtual bool pipeline_cache_create(const Vector &p_data) = 0; + virtual void pipeline_cache_free() = 0; + virtual size_t pipeline_cache_query_size() = 0; + virtual Vector pipeline_cache_serialize() = 0; + + /*******************/ + /**** RENDERING ****/ + /*******************/ + + // ----- SUBPASS ----- + + enum AttachmentLoadOp { + ATTACHMENT_LOAD_OP_LOAD = 0, + ATTACHMENT_LOAD_OP_CLEAR = 1, + ATTACHMENT_LOAD_OP_DONT_CARE = 2, + }; + + enum AttachmentStoreOp { + ATTACHMENT_STORE_OP_STORE = 0, + ATTACHMENT_STORE_OP_DONT_CARE = 1, + }; + + struct Attachment { + DataFormat format = DATA_FORMAT_MAX; + TextureSamples samples = TEXTURE_SAMPLES_MAX; + AttachmentLoadOp load_op = ATTACHMENT_LOAD_OP_LOAD; + AttachmentStoreOp store_op = ATTACHMENT_STORE_OP_STORE; + AttachmentLoadOp stencil_load_op = ATTACHMENT_LOAD_OP_LOAD; + AttachmentStoreOp stencil_store_op = ATTACHMENT_STORE_OP_STORE; + TextureLayout initial_layout = TEXTURE_LAYOUT_UNDEFINED; + TextureLayout final_layout = TEXTURE_LAYOUT_UNDEFINED; + }; + + struct AttachmentReference { + static const uint32_t UNUSED = 0xffffffff; + uint32_t attachment = UNUSED; + TextureLayout layout = TEXTURE_LAYOUT_UNDEFINED; + BitField aspect; + }; + + struct Subpass { + LocalVector input_references; + LocalVector color_references; + AttachmentReference depth_stencil_reference; + LocalVector resolve_references; + LocalVector preserve_attachments; + AttachmentReference vrs_reference; + }; + + struct SubpassDependency { + uint32_t src_subpass = 0xffffffff; + uint32_t dst_subpass = 0xffffffff; + BitField src_stages; + BitField dst_stages; + BitField src_access; + BitField dst_access; + }; + + virtual RenderPassID render_pass_create(VectorView p_attachments, VectorView p_subpasses, VectorView p_subpass_dependencies, uint32_t p_view_count) = 0; + virtual void render_pass_free(RenderPassID p_render_pass) = 0; + + // ----- COMMANDS ----- + + union RenderPassClearValue { + Color color = {}; + struct { + float depth; + uint32_t stencil; + }; + }; + + struct AttachmentClear { + BitField aspect; + uint32_t color_attachment = 0xffffffff; + RenderPassClearValue value; + }; + + struct AttachmentClearRect { + Rect2i rect; + uint32_t base_layer = 0xffffffff; + uint32_t layer_count = 0xffffffff; + }; + + virtual void command_begin_render_pass(CommandBufferID p_cmd_buffer, RenderPassID p_render_pass, FramebufferID p_framebuffer, CommandBufferType p_cmd_buffer_type, const Rect2i &p_rect, VectorView p_clear_values) = 0; + virtual void command_end_render_pass(CommandBufferID p_cmd_buffer) = 0; + virtual void command_next_render_subpass(CommandBufferID p_cmd_buffer, CommandBufferType p_cmd_buffer_type) = 0; + virtual void command_render_set_viewport(CommandBufferID p_cmd_buffer, VectorView p_viewports) = 0; + virtual void command_render_set_scissor(CommandBufferID p_cmd_buffer, VectorView p_scissors) = 0; + virtual void command_render_clear_attachments(CommandBufferID p_cmd_buffer, VectorView p_attachment_clears, VectorView p_rects) = 0; + + // Binding. + virtual void command_bind_render_pipeline(CommandBufferID p_cmd_buffer, PipelineID p_pipeline) = 0; + virtual void command_bind_render_uniform_set(CommandBufferID p_cmd_buffer, UniformSetID p_uniform_set, ShaderID p_shader, uint32_t p_set_index) = 0; + + // Drawing. + virtual void command_render_draw(CommandBufferID p_cmd_buffer, uint32_t p_vertex_count, uint32_t p_instance_count, uint32_t p_base_vertex, uint32_t p_first_instance) = 0; + virtual void command_render_draw_indexed(CommandBufferID p_cmd_buffer, uint32_t p_index_count, uint32_t p_instance_count, uint32_t p_first_index, int32_t p_vertex_offset, uint32_t p_first_instance) = 0; + virtual void command_render_draw_indexed_indirect(CommandBufferID p_cmd_buffer, BufferID p_indirect_buffer, uint64_t p_offset, uint32_t p_draw_count, uint32_t p_stride) = 0; + virtual void command_render_draw_indexed_indirect_count(CommandBufferID p_cmd_buffer, BufferID p_indirect_buffer, uint64_t p_offset, BufferID p_count_buffer, uint64_t p_count_buffer_offset, uint32_t p_max_draw_count, uint32_t p_stride) = 0; + virtual void command_render_draw_indirect(CommandBufferID p_cmd_buffer, BufferID p_indirect_buffer, uint64_t p_offset, uint32_t p_draw_count, uint32_t p_stride) = 0; + virtual void command_render_draw_indirect_count(CommandBufferID p_cmd_buffer, BufferID p_indirect_buffer, uint64_t p_offset, BufferID p_count_buffer, uint64_t p_count_buffer_offset, uint32_t p_max_draw_count, uint32_t p_stride) = 0; + + // Buffer binding. + virtual void command_render_bind_vertex_buffers(CommandBufferID p_cmd_buffer, uint32_t p_binding_count, const BufferID *p_buffers, const uint64_t *p_offsets) = 0; + virtual void command_render_bind_index_buffer(CommandBufferID p_cmd_buffer, BufferID p_buffer, IndexBufferFormat p_format, uint64_t p_offset) = 0; + + // Dynamic state. + virtual void command_render_set_blend_constants(CommandBufferID p_cmd_buffer, const Color &p_constants) = 0; + virtual void command_render_set_line_width(CommandBufferID p_cmd_buffer, float p_width) = 0; + + // ----- PIPELINE ----- + + virtual PipelineID render_pipeline_create( + ShaderID p_shader, + VertexFormatID p_vertex_format, + RenderPrimitive p_render_primitive, + PipelineRasterizationState p_rasterization_state, + PipelineMultisampleState p_multisample_state, + PipelineDepthStencilState p_depth_stencil_state, + PipelineColorBlendState p_blend_state, + VectorView p_color_attachments, + BitField p_dynamic_state, + RenderPassID p_render_pass, + uint32_t p_render_subpass, + VectorView p_specialization_constants) = 0; + + /*****************/ + /**** COMPUTE ****/ + /*****************/ + + // ----- COMMANDS ----- + + // Binding. + virtual void command_bind_compute_pipeline(CommandBufferID p_cmd_buffer, PipelineID p_pipeline) = 0; + virtual void command_bind_compute_uniform_set(CommandBufferID p_cmd_buffer, UniformSetID p_uniform_set, ShaderID p_shader, uint32_t p_set_index) = 0; + + // Dispatching. + virtual void command_compute_dispatch(CommandBufferID p_cmd_buffer, uint32_t p_x_groups, uint32_t p_y_groups, uint32_t p_z_groups) = 0; + virtual void command_compute_dispatch_indirect(CommandBufferID p_cmd_buffer, BufferID p_indirect_buffer, uint64_t p_offset) = 0; + + // ----- PIPELINE ----- + + virtual PipelineID compute_pipeline_create(ShaderID p_shader, VectorView p_specialization_constants) = 0; + + /*****************/ + /**** QUERIES ****/ + /*****************/ + + // ----- TIMESTAMP ----- + + // Basic. + virtual QueryPoolID timestamp_query_pool_create(uint32_t p_query_count) = 0; + virtual void timestamp_query_pool_free(QueryPoolID p_pool_id) = 0; + virtual void timestamp_query_pool_get_results(QueryPoolID p_pool_id, uint32_t p_query_count, uint64_t *r_results) = 0; + virtual uint64_t timestamp_query_result_to_time(uint64_t p_result) = 0; + + // Commands. + virtual void command_timestamp_query_pool_reset(CommandBufferID p_cmd_buffer, QueryPoolID p_pool_id, uint32_t p_query_count) = 0; + virtual void command_timestamp_write(CommandBufferID p_cmd_buffer, QueryPoolID p_pool_id, uint32_t p_index) = 0; + + /****************/ + /**** SCREEN ****/ + /****************/ + + virtual DataFormat screen_get_format() = 0; + + /**************/ + /**** MISC ****/ + /**************/ + + enum ObjectType { + OBJECT_TYPE_TEXTURE, + OBJECT_TYPE_SAMPLER, + OBJECT_TYPE_BUFFER, + OBJECT_TYPE_SHADER, + OBJECT_TYPE_UNIFORM_SET, + OBJECT_TYPE_PIPELINE, + }; + + struct MultiviewCapabilities { + bool is_supported = false; + bool geometry_shader_is_supported = false; + bool tessellation_shader_is_supported = false; + uint32_t max_view_count = 0; + uint32_t max_instance_count = 0; + }; + + virtual void set_object_name(ObjectType p_type, ID p_driver_id, const String &p_name) = 0; + virtual uint64_t get_resource_native_handle(DriverResource p_type, ID p_driver_id) = 0; + virtual uint64_t get_total_memory_used() = 0; + virtual uint64_t limit_get(Limit p_limit) = 0; + virtual bool has_feature(Features p_feature) = 0; + virtual const MultiviewCapabilities &get_multiview_capabilities() = 0; + + /******************/ + + virtual ~RenderingDeviceDriver(); +}; + +using RDD = RenderingDeviceDriver; + +#endif // RENDERING_DEVICE_DRIVER_H