upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/runtime/src
diff options
context:
space:
mode:
authorgabrielsteglich <63128571+gabrielsteglich@users.noreply.github.com>2026-11-22 13:13:27 -0300
committergabrielsteglich <63128571+gabrielsteglich@users.noreply.github.com>2026-11-22 13:39:08 -0300
commitf8e89767f66de8f2a375615ca96a10459a87fef7 (patch)
tree14548229b6e2b26c68105d88de104cdf8ae37502 /runtime/src
parent49475796c226c8511b9470bf97a4daf57b8af323 (diff)
Runtime: map sparse reserved RGBA8 texture tiles (D3D-285)
Diffstat (limited to 'runtime/src')
-rw-r--r--runtime/src/command_list.h9
-rw-r--r--runtime/src/vulkan_backend.h200
-rw-r--r--runtime/src/vulkan_replay.h51
3 files changed, 192 insertions, 68 deletions
diff --git a/runtime/src/command_list.h b/runtime/src/command_list.h
index 47a0561b3..7b81ac75d 100644
--- a/runtime/src/command_list.h
+++ b/runtime/src/command_list.h
@@ -324,6 +324,7 @@ struct CopyTexture {
324 CopyLocation src; 324 CopyLocation src;
325 bool has_box; 325 bool has_box;
326 CopyBox box; 326 CopyBox box;
327 bool tile_footprint = false; // RGBA8 CopyTiles: rows in a linear 64 KiB tile, at any byte offset
327}; 328};
328 329
329// CopyResource: every subresource, or the whole buffer. 330// CopyResource: every subresource, or the whole buffer.
@@ -674,7 +675,9 @@ public:
674 } 675 }
675 676
676 bool copy_texture(const CopyTexture& copy) { 677 bool copy_texture(const CopyTexture& copy) {
677 if (!valid(copy.dst) || !valid(copy.src) || (copy.dst.footprint && copy.src.footprint)) return false; 678 const auto alignment = copy.tile_footprint ? 1u : texture_data_placement_alignment;
679 if (!valid(copy.dst, alignment) || !valid(copy.src, alignment) || (copy.dst.footprint && copy.src.footprint))
680 return false;
678 if (copy.has_box && (copy.box.right <= copy.box.left || copy.box.bottom <= copy.box.top || 681 if (copy.has_box && (copy.box.right <= copy.box.left || copy.box.bottom <= copy.box.top ||
679 copy.box.back <= copy.box.front)) 682 copy.box.back <= copy.box.front))
680 return false; 683 return false;
@@ -866,11 +869,11 @@ private:
866 static bool valid(const TargetView& target) { return target.resource && target.layer_count; } 869 static bool valid(const TargetView& target) { return target.resource && target.layer_count; }
867 870
868 // A placed footprint needs aligned offsets and pitches and a non-empty size. 871 // A placed footprint needs aligned offsets and pitches and a non-empty size.
869 static bool valid(const CopyLocation& location) { 872 static bool valid(const CopyLocation& location, std::uint32_t alignment) {
870 if (!location.resource) return false; 873 if (!location.resource) return false;
871 if (!location.footprint) return true; 874 if (!location.footprint) return true;
872 return location.width && location.height && location.depth && location.row_pitch && 875 return location.width && location.height && location.depth && location.row_pitch &&
873 location.offset % texture_data_placement_alignment == 0 && 876 location.offset % alignment == 0 &&
874 location.row_pitch % texture_data_pitch_alignment == 0; 877 location.row_pitch % texture_data_pitch_alignment == 0;
875 } 878 }
876 879
diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h
index 93d7e5259..4990a5953 100644
--- a/runtime/src/vulkan_backend.h
+++ b/runtime/src/vulkan_backend.h
@@ -80,7 +80,7 @@ struct VulkanDeviceFunctions {
80 X(vkCmdBindVertexBuffers2) X(vkCmdBindIndexBuffer) X(vkCmdSetViewport) X(vkCmdSetScissor) \ 80 X(vkCmdBindVertexBuffers2) X(vkCmdBindIndexBuffer) X(vkCmdSetViewport) X(vkCmdSetScissor) \
81 X(vkCmdSetPrimitiveTopology) X(vkCmdSetPrimitiveRestartEnable) X(vkCmdSetStencilReference) \ 81 X(vkCmdSetPrimitiveTopology) X(vkCmdSetPrimitiveRestartEnable) X(vkCmdSetStencilReference) \
82 X(vkCmdSetBlendConstants) X(vkCmdDraw) \ 82 X(vkCmdSetBlendConstants) X(vkCmdDraw) \
83 X(vkCmdDrawIndexed) X(vkCreateGraphicsPipelines) X(vkQueueBindSparse) 83 X(vkCmdDrawIndexed) X(vkCreateGraphicsPipelines) X(vkQueueBindSparse) X(vkGetImageSparseMemoryRequirements)
84#define LEONIDA_VK_MEMBER(name) PFN_##name name = nullptr; 84#define LEONIDA_VK_MEMBER(name) PFN_##name name = nullptr;
85 LEONIDA_VK_DEVICE_FUNCTIONS(LEONIDA_VK_MEMBER) 85 LEONIDA_VK_DEVICE_FUNCTIONS(LEONIDA_VK_MEMBER)
86#undef LEONIDA_VK_MEMBER 86#undef LEONIDA_VK_MEMBER
@@ -345,6 +345,8 @@ private:
345 VkPipeline statistics_pipeline_ = VK_NULL_HANDLE; 345 VkPipeline statistics_pipeline_ = VK_NULL_HANDLE;
346}; 346};
347 347
348struct SparseResource;
349
348// Zero-allocation O(1) Ring Buffer deferred deletion queue tied to the device timeline semaphore. 350// Zero-allocation O(1) Ring Buffer deferred deletion queue tied to the device timeline semaphore.
349class DeferredDeletionQueue { 351class DeferredDeletionQueue {
350public: 352public:
@@ -352,6 +354,7 @@ public:
352 bindless_slot, 354 bindless_slot,
353 image_view, 355 image_view,
354 image, 356 image,
357 sparse_resource,
355 buffer, 358 buffer,
356 device_memory, 359 device_memory,
357 acceleration_structure, 360 acceleration_structure,
@@ -428,6 +431,10 @@ public:
428 case Kind::image: 431 case Kind::image:
429 vk.vkDestroyImage(device, reinterpret_cast<VkImage>(item.handle), nullptr); 432 vk.vkDestroyImage(device, reinterpret_cast<VkImage>(item.handle), nullptr);
430 break; 433 break;
434 case Kind::sparse_resource:
435 // Releases the resource and its page backing together after outstanding submissions.
436 delete reinterpret_cast<std::shared_ptr<SparseResource>*>(item.handle);
437 break;
431 case Kind::buffer: 438 case Kind::buffer:
432 vk.vkDestroyBuffer(device, reinterpret_cast<VkBuffer>(item.handle), nullptr); 439 vk.vkDestroyBuffer(device, reinterpret_cast<VkBuffer>(item.handle), nullptr);
433 break; 440 break;
@@ -721,34 +728,39 @@ struct TileHeapAllocation {
721 std::uint32_t memory_type = 0; 728 std::uint32_t memory_type = 0;
722}; 729};
723 730
724struct BufferTile { 731struct TileMapping {
725 std::shared_ptr<const TileHeapAllocation> heap; 732 std::shared_ptr<const TileHeapAllocation> heap;
726 VkDeviceSize offset = 0; 733 VkDeviceSize offset = 0;
727 bool operator==(const BufferTile&) const = default; 734 bool operator==(const TileMapping&) const = default;
728}; 735};
729 736
730struct SparseBuffer { 737struct SparseResource {
731 SparseBuffer(VkDevice device, PFN_vkDestroyBuffer destroy) : device(device), destroy(destroy) {} 738 SparseResource(VkDevice device, const VulkanDeviceFunctions& vk) : device(device), vk(vk) {}
732 SparseBuffer(const SparseBuffer&) = delete; 739 SparseResource(const SparseResource&) = delete;
733 SparseBuffer& operator=(const SparseBuffer&) = delete; 740 SparseResource& operator=(const SparseResource&) = delete;
734 ~SparseBuffer() { if (buffer) destroy(device, buffer, nullptr); } 741 ~SparseResource() {
742 if (image) vk.vkDestroyImage(device, image, nullptr);
743 if (buffer) vk.vkDestroyBuffer(device, buffer, nullptr);
744 }
735 745
736 VkDevice device; 746 VkDevice device;
737 PFN_vkDestroyBuffer destroy; 747 const VulkanDeviceFunctions& vk;
738 VkBuffer buffer = VK_NULL_HANDLE; 748 VkBuffer buffer = VK_NULL_HANDLE;
749 VkImage image = VK_NULL_HANDLE;
750 VkExtent2D image_extent{};
739 std::uint64_t tile_count = 0; 751 std::uint64_t tile_count = 0;
740 std::uint32_t memory_types = 0; 752 std::uint32_t memory_types = 0;
741 std::map<std::uint64_t, BufferTile> mapped; 753 std::map<std::uint64_t, TileMapping> mapped;
742}; 754};
743 755
744struct BufferTileRegion { 756struct TileRegion {
745 std::uint64_t first = 0; 757 std::uint64_t first = 0;
746 std::uint64_t count = 0; 758 std::uint64_t count = 0;
747}; 759};
748 760
749enum class TileRangeMode { sequential, unmap, skip, reuse }; 761enum class TileRangeMode { sequential, unmap, skip, reuse };
750 762
751struct BufferTileRange { 763struct TileRange {
752 TileRangeMode mode; 764 TileRangeMode mode;
753 std::uint64_t first; 765 std::uint64_t first;
754 std::uint64_t count; 766 std::uint64_t count;
@@ -938,30 +950,36 @@ public:
938 } 950 }
939 } 951 }
940 952
941 // An image that got a storage (unordered-access) view. A shader can write it before any command names it, so the 953 // A shader can access a storage image or an initially unbound sparse image before any command names it.
942 // layer would not know it was used and the first barrier or copy that does would zero-fill it (vulkan_replay.h, 954 // The first shader submission moves it to GENERAL, the descriptor's layout, ahead of its lists.
943 // initialize). The next submission therefore moves each such image to GENERAL, the layout its descriptor names, 955 void note_shader_image(ResourceId id) {
944 // zero-filled, ahead of its lists. An image already tracked beyond UNDEFINED is left as it is.
945 void note_storage_image(ResourceId id) {
946 std::lock_guard lock(storage_mutex_); 956 std::lock_guard lock(storage_mutex_);
947 storage_pending_.insert(id); 957 storage_pending_.insert(id);
948 } 958 }
949 959
950 void add_sparse_buffer(ResourceId id, const ResourceBinding& binding, std::shared_ptr<SparseBuffer> buffer) { 960 void add_sparse_resource(ResourceId id, const ResourceBinding& binding, std::shared_ptr<SparseResource> sparse) {
951 std::unique_lock lock(resource_mutex_); 961 std::unique_lock lock(resource_mutex_);
952 resources_[id] = binding; 962 resources_[id] = binding;
953 sparse_buffers_.emplace(id, std::move(buffer)); 963 sparse_resources_.emplace(id, std::move(sparse));
964 if (binding.image) {
965 std::lock_guard tlock(tracker_mutex_);
966 tracker_.track(id, binding, VK_IMAGE_LAYOUT_UNDEFINED);
967 }
954 } 968 }
955 969
956 void remove_resource(ResourceId id) { 970 void remove_resource(ResourceId id) {
957 VkImage img = VK_NULL_HANDLE; 971 VkImage img = VK_NULL_HANDLE;
972 std::shared_ptr<SparseResource> sparse_resource;
958 { 973 {
959 std::unique_lock rlock(resource_mutex_); 974 std::unique_lock rlock(resource_mutex_);
960 const auto it = resources_.find(id); 975 const auto it = resources_.find(id);
961 if (it == resources_.end()) return; 976 if (it == resources_.end()) return;
962 img = it->second.image; 977 img = it->second.image;
963 resources_.erase(it); 978 resources_.erase(it);
964 sparse_buffers_.erase(id); 979 if (auto sparse = sparse_resources_.find(id); sparse != sparse_resources_.end()) {
980 sparse_resource = std::move(sparse->second);
981 sparse_resources_.erase(sparse);
982 }
965 } 983 }
966 if (img) { 984 if (img) {
967 std::lock_guard vlock(views_mutex_); 985 std::lock_guard vlock(views_mutex_);
@@ -974,6 +992,9 @@ public:
974 } 992 }
975 } 993 }
976 } 994 }
995 if (sparse_resource)
996 defer_destroy(DeferredDeletionQueue::Kind::sparse_resource,
997 new std::shared_ptr<SparseResource>(std::move(sparse_resource)));
977 std::lock_guard tlock(tracker_mutex_); 998 std::lock_guard tlock(tracker_mutex_);
978 tracker_.forget(id); 999 tracker_.forget(id);
979 } 1000 }
@@ -1263,7 +1284,7 @@ private:
1263 DeferredDeletionQueue deletion_queue_; 1284 DeferredDeletionQueue deletion_queue_;
1264 std::unique_ptr<FenceWaitDispatcher> fence_dispatcher_; 1285 std::unique_ptr<FenceWaitDispatcher> fence_dispatcher_;
1265 std::unordered_map<ResourceId, ResourceBinding> resources_; 1286 std::unordered_map<ResourceId, ResourceBinding> resources_;
1266 std::unordered_map<ResourceId, std::shared_ptr<SparseBuffer>> sparse_buffers_; 1287 std::unordered_map<ResourceId, std::shared_ptr<SparseResource>> sparse_resources_;
1267 std::unordered_map<std::uintptr_t, ComputePipeline> pipelines_; 1288 std::unordered_map<std::uintptr_t, ComputePipeline> pipelines_;
1268 std::unordered_map<std::uintptr_t, GraphicsPipeline> graphics_pipelines_; 1289 std::unordered_map<std::uintptr_t, GraphicsPipeline> graphics_pipelines_;
1269 std::unordered_map<std::uint64_t, VkAccelerationStructureKHR> acceleration_structures_; 1290 std::unordered_map<std::uint64_t, VkAccelerationStructureKHR> acceleration_structures_;
@@ -1403,17 +1424,17 @@ public:
1403 bool ok() const { return ok_; } 1424 bool ok() const { return ok_; }
1404 1425
1405 template<typename GetHeap> 1426 template<typename GetHeap>
1406 bool update_tiles(ResourceId id, std::span<const BufferTileRegion> regions, 1427 bool update_tiles(ResourceId id, std::span<const TileRegion> regions,
1407 std::span<const BufferTileRange> ranges, GetHeap&& get_heap) { 1428 std::span<const TileRange> ranges, GetHeap&& get_heap) {
1408 std::unique_lock lock(context_.resource_mutex_); 1429 std::unique_lock lock(context_.resource_mutex_);
1409 const auto it = context_.sparse_buffers_.find(id); 1430 const auto it = context_.sparse_resources_.find(id);
1410 if (it == context_.sparse_buffers_.end()) return false; 1431 if (it == context_.sparse_resources_.end()) return false;
1411 const auto& buffer = it->second; 1432 const auto& sparse = it->second;
1412 for (const auto& region : regions) 1433 for (const auto& region : regions)
1413 if (!valid_tiles(*buffer, region)) return false; 1434 if (!valid_tiles(*sparse, region)) return false;
1414 const auto heap = get_heap(); 1435 const auto heap = get_heap(sparse->image != VK_NULL_HANDLE, sparse->memory_types);
1415 1436
1416 std::map<std::uint64_t, BufferTile> changes; 1437 std::map<std::uint64_t, TileMapping> changes;
1417 std::size_t region_index = 0; 1438 std::size_t region_index = 0;
1418 std::uint64_t consumed = 0; 1439 std::uint64_t consumed = 0;
1419 for (const auto& range : ranges) { 1440 for (const auto& range : ranges) {
@@ -1428,7 +1449,7 @@ public:
1428 const auto first = region.first + consumed; 1449 const auto first = region.first + consumed;
1429 if (range.mode == TileRangeMode::unmap) { 1450 if (range.mode == TileRangeMode::unmap) {
1430 const auto end = first + count; 1451 const auto end = first + count;
1431 for (auto old = buffer->mapped.lower_bound(first); old != buffer->mapped.end() && old->first < end; ++old) 1452 for (auto old = sparse->mapped.lower_bound(first); old != sparse->mapped.end() && old->first < end; ++old)
1432 changes[old->first] = {}; 1453 changes[old->first] = {};
1433 for (auto change = changes.lower_bound(first); change != changes.end() && change->first < end; ++change) 1454 for (auto change = changes.lower_bound(first); change != changes.end() && change->first < end; ++change)
1434 change->second = {}; 1455 change->second = {};
@@ -1446,22 +1467,28 @@ public:
1446 } 1467 }
1447 } 1468 }
1448 } 1469 }
1449 return region_index == regions.size() && bind_tiles(buffer, changes); 1470 return region_index == regions.size() && bind_tiles(id, sparse, changes);
1450 } 1471 }
1451 1472
1452 bool copy_tile_mappings(ResourceId dst, std::uint64_t dst_first, ResourceId src, BufferTileRegion src_region) { 1473 bool copy_tile_mappings(ResourceId dst, std::span<const TileRegion> dst_regions, ResourceId src,
1474 std::span<const TileRegion> src_regions) {
1453 std::unique_lock lock(context_.resource_mutex_); 1475 std::unique_lock lock(context_.resource_mutex_);
1454 const auto source = context_.sparse_buffers_.find(src), target = context_.sparse_buffers_.find(dst); 1476 const auto source = context_.sparse_resources_.find(src), target = context_.sparse_resources_.find(dst);
1455 if (source == context_.sparse_buffers_.end() || target == context_.sparse_buffers_.end() || 1477 if (source == context_.sparse_resources_.end() || target == context_.sparse_resources_.end() ||
1456 !valid_tiles(*source->second, src_region) || 1478 bool(source->second->image) != bool(target->second->image) || src_regions.size() != dst_regions.size())
1457 !valid_tiles(*target->second, {dst_first, src_region.count})) return false; 1479 return false;
1458 // Read the complete source mapping before changing any destination slot, including copies within one buffer. 1480 // Read the complete source mapping before changing any destination slot, including copies within one resource.
1459 std::map<std::uint64_t, BufferTile> changes; 1481 std::map<std::uint64_t, TileMapping> changes;
1460 for (std::uint64_t i = 0; i < src_region.count; ++i) { 1482 for (std::size_t row = 0; row < src_regions.size(); ++row) {
1461 const auto page = source->second->mapped.find(src_region.first + i); 1483 const auto from = src_regions[row], to = dst_regions[row];
1462 changes.emplace(dst_first + i, page == source->second->mapped.end() ? BufferTile{} : page->second); 1484 if (!valid_tiles(*source->second, from) || !valid_tiles(*target->second, to) || from.count != to.count)
1485 return false;
1486 for (std::uint64_t i = 0; i < from.count; ++i) {
1487 const auto page = source->second->mapped.find(from.first + i);
1488 changes.emplace(to.first + i, page == source->second->mapped.end() ? TileMapping{} : page->second);
1489 }
1463 } 1490 }
1464 return bind_tiles(target->second, changes); 1491 return bind_tiles(dst, target->second, changes);
1465 } 1492 }
1466 1493
1467 // ExecuteCommandLists: every list is checked before any is written, so a failure submits nothing and leaves 1494 // ExecuteCommandLists: every list is checked before any is written, so a failure submits nothing and leaves
@@ -1656,8 +1683,8 @@ public:
1656 return ReplayResult::unsupported; 1683 return ReplayResult::unsupported;
1657 } 1684 }
1658 auto next_tracker = context_.tracker_; 1685 auto next_tracker = context_.tracker_;
1659 // Images with a UAV view are moved to GENERAL (zeroed) by the first submission that can use a shader on them: 1686 // Bindless images that may already be visible to shaders are initialized on a submission that runs shaders.
1660 // not a copy queue (its family may not clear images), and one whose lists dispatch or draw. 1687 // initialize() zeroes committed storage images and only transitions sparse images.
1661 bool runs_shaders = false; 1688 bool runs_shaders = false;
1662 for (const CommandList* list : lists) 1689 for (const CommandList* list : lists)
1663 for (const auto& command : list->commands()) 1690 for (const auto& command : list->commands())
@@ -1804,32 +1831,72 @@ private:
1804 1831
1805 struct PendingBindings { 1832 struct PendingBindings {
1806 std::uint64_t ticket = 0; 1833 std::uint64_t ticket = 0;
1807 // Vulkan needs the buffer until the bind completes and the previous allocation until it is unmapped. 1834 // Vulkan needs the resource until the bind completes and the previous allocation until it is unmapped.
1808 std::vector<std::shared_ptr<const TileHeapAllocation>> old_heaps; 1835 std::vector<std::shared_ptr<const TileHeapAllocation>> old_heaps;
1809 std::shared_ptr<SparseBuffer> buffer; 1836 std::shared_ptr<SparseResource> resource;
1810 }; 1837 };
1811 1838
1812 static bool valid_tiles(const SparseBuffer& buffer, BufferTileRegion region) { 1839 static bool valid_tiles(const SparseResource& resource, TileRegion region) {
1813 return region.count && region.first < buffer.tile_count && region.count <= buffer.tile_count - region.first; 1840 return region.count && region.first < resource.tile_count && region.count <= resource.tile_count - region.first;
1841 }
1842
1843 bool initialize_sparse_image_layout(ResourceId id) {
1844 std::lock_guard lock(context_.tracker_mutex_);
1845 if (context_.tracker_.layout(id, 0) != VK_IMAGE_LAYOUT_UNDEFINED) return true;
1846 auto* slot = acquire();
1847 if (!slot) return false;
1848 const VkCommandBuffer command_buffer = slot->buffer;
1849 auto& vk = context_.vk;
1850 VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO};
1851 begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
1852 if (vk.vkBeginCommandBuffer(command_buffer, &begin) != VK_SUCCESS) {
1853 slot->ticket = 0;
1854 return false;
1855 }
1856 // Transition while the image is still unbound. Doing this after binding could discard another image's
1857 // contents in an aliased page. Subsequent uses keep the image in GENERAL.
1858 constexpr VkImageSubresourceRange range{VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
1859 detail::image_barrier(context_.replay_, command_buffer, context_.resources_.at(id), range,
1860 VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL, 0,
1861 VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT,
1862 VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
1863 if (vk.vkEndCommandBuffer(command_buffer) != VK_SUCCESS || !submit(command_buffer, VK_NULL_HANDLE, 0)) {
1864 slot->ticket = 0;
1865 return false;
1866 }
1867 context_.tracker_.set(id, range, VK_IMAGE_LAYOUT_GENERAL);
1868 return true;
1814 } 1869 }
1815 1870
1816 bool bind_tiles(const std::shared_ptr<SparseBuffer>& buffer, 1871 bool bind_tiles(ResourceId id, const std::shared_ptr<SparseResource>& resource,
1817 std::map<std::uint64_t, BufferTile>& changes) { 1872 std::map<std::uint64_t, TileMapping>& changes) {
1818 auto& vk = context_.vk; 1873 auto& vk = context_.vk;
1819 if (!vk.vkQueueBindSparse || context_.is_device_lost()) return false; 1874 if (!vk.vkQueueBindSparse || context_.is_device_lost()) return false;
1820 const auto ticket = submitted_ + 1; 1875 PendingBindings pending{0, {}, resource};
1821 PendingBindings pending{ticket, {}, buffer};
1822 std::vector<VkSparseMemoryBind> binds; 1876 std::vector<VkSparseMemoryBind> binds;
1877 std::vector<VkSparseImageMemoryBind> image_binds;
1823 for (const auto& [index, page] : changes) { 1878 for (const auto& [index, page] : changes) {
1824 const auto old = buffer->mapped.find(index); 1879 const auto old = resource->mapped.find(index);
1825 if (old != buffer->mapped.end()) { 1880 if (old != resource->mapped.end()) {
1826 if (old->second == page) continue; 1881 if (old->second == page) continue;
1827 pending.old_heaps.push_back(old->second.heap); 1882 pending.old_heaps.push_back(old->second.heap);
1828 } else if (!page.heap) { 1883 } else if (!page.heap) {
1829 continue; 1884 continue;
1830 } 1885 }
1831 if (page.heap && !(buffer->memory_types & (1u << page.heap->memory_type))) return false; 1886 if (page.heap && !(resource->memory_types & (1u << page.heap->memory_type))) return false;
1832 const VkDeviceMemory memory = page.heap ? page.heap->memory : VK_NULL_HANDLE; 1887 const VkDeviceMemory memory = page.heap ? page.heap->memory : VK_NULL_HANDLE;
1888 if (resource->image) {
1889 constexpr auto shape = element_tile_shape(false, 4);
1890 const auto extent = resource->image_extent;
1891 const auto columns = 1 + (extent.width - 1) / shape.width;
1892 const auto x = std::uint32_t(index % columns) * shape.width;
1893 const auto y = std::uint32_t(index / columns) * shape.height;
1894 image_binds.push_back({
1895 {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0}, {std::int32_t(x), std::int32_t(y), 0},
1896 {std::min(shape.width, extent.width - x), std::min(shape.height, extent.height - y), 1},
1897 memory, page.offset, 0});
1898 continue;
1899 }
1833 const VkDeviceSize resource_offset = index * tile_size_in_bytes; 1900 const VkDeviceSize resource_offset = index * tile_size_in_bytes;
1834 if (!binds.empty()) { 1901 if (!binds.empty()) {
1835 auto& previous = binds.back(); 1902 auto& previous = binds.back();
@@ -1841,7 +1908,10 @@ private:
1841 } 1908 }
1842 binds.push_back({resource_offset, tile_size_in_bytes, memory, page.offset, 0}); 1909 binds.push_back({resource_offset, tile_size_in_bytes, memory, page.offset, 0});
1843 } 1910 }
1844 if (binds.empty()) return true; 1911 if (binds.empty() && image_binds.empty()) return true;
1912 if (!image_binds.empty() && !initialize_sparse_image_layout(id)) return false;
1913 const auto ticket = submitted_ + 1;
1914 pending.ticket = ticket;
1845 collect_bindings(completed()); 1915 collect_bindings(completed());
1846 auto semaphores = waits_; 1916 auto semaphores = waits_;
1847 auto values = wait_values_; 1917 auto values = wait_values_;
@@ -1855,12 +1925,20 @@ private:
1855 tickets.pWaitSemaphoreValues = values.data(); 1925 tickets.pWaitSemaphoreValues = values.data();
1856 tickets.signalSemaphoreValueCount = 1; 1926 tickets.signalSemaphoreValueCount = 1;
1857 tickets.pSignalSemaphoreValues = &ticket; 1927 tickets.pSignalSemaphoreValues = &ticket;
1858 const VkSparseBufferMemoryBindInfo buffer_bind{buffer->buffer, std::uint32_t(binds.size()), binds.data()}; 1928 const VkSparseBufferMemoryBindInfo buffer_bind{resource->buffer, std::uint32_t(binds.size()), binds.data()};
1929 const VkSparseImageMemoryBindInfo image_bind{
1930 resource->image, std::uint32_t(image_binds.size()), image_binds.data()};
1859 VkBindSparseInfo info{VK_STRUCTURE_TYPE_BIND_SPARSE_INFO, &tickets}; 1931 VkBindSparseInfo info{VK_STRUCTURE_TYPE_BIND_SPARSE_INFO, &tickets};
1860 info.waitSemaphoreCount = std::uint32_t(semaphores.size()); 1932 info.waitSemaphoreCount = std::uint32_t(semaphores.size());
1861 info.pWaitSemaphores = semaphores.data(); 1933 info.pWaitSemaphores = semaphores.data();
1862 info.bufferBindCount = 1; 1934 if (!binds.empty()) {
1863 info.pBufferBinds = &buffer_bind; 1935 info.bufferBindCount = 1;
1936 info.pBufferBinds = &buffer_bind;
1937 }
1938 if (!image_binds.empty()) {
1939 info.imageBindCount = 1;
1940 info.pImageBinds = &image_bind;
1941 }
1864 info.signalSemaphoreCount = 1; 1942 info.signalSemaphoreCount = 1;
1865 info.pSignalSemaphores = &progress_; 1943 info.pSignalSemaphores = &progress_;
1866 pending_bindings_.push_back(std::move(pending)); 1944 pending_bindings_.push_back(std::move(pending));
@@ -1878,11 +1956,11 @@ private:
1878 waits_.clear(); 1956 waits_.clear();
1879 wait_values_.clear(); 1957 wait_values_.clear();
1880 for (auto it = changes.begin(); it != changes.end();) { 1958 for (auto it = changes.begin(); it != changes.end();) {
1881 buffer->mapped.erase(it->first); 1959 resource->mapped.erase(it->first);
1882 if (it->second.heap) ++it; 1960 if (it->second.heap) ++it;
1883 else it = changes.erase(it); 1961 else it = changes.erase(it);
1884 } 1962 }
1885 buffer->mapped.merge(changes); 1963 resource->mapped.merge(changes);
1886 return true; 1964 return true;
1887 } 1965 }
1888 1966
diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h
index 8ece08d1e..26a1e0589 100644
--- a/runtime/src/vulkan_replay.h
+++ b/runtime/src/vulkan_replay.h
@@ -924,6 +924,8 @@ struct Prepared {
924 VkImageSubresourceRange source_range{}; // copies: the source subresources (range: the destination's) 924 VkImageSubresourceRange source_range{}; // copies: the source subresources (range: the destination's)
925 std::vector<VkBufferCopy> buffer_copies; 925 std::vector<VkBufferCopy> buffer_copies;
926 std::vector<VkBufferImageCopy> buffer_image_copies; // one direction, given by which side is an image 926 std::vector<VkBufferImageCopy> buffer_image_copies; // one direction, given by which side is an image
927 VkBuffer tile_scratch = VK_NULL_HANDLE; // CopyTiles with a byte-unaligned linear buffer offset
928 std::vector<VkBufferCopy> tile_rows;
927 std::vector<VkImageCopy> image_copies; 929 std::vector<VkImageCopy> image_copies;
928 VkImageResolve resolve{}; // resolves 930 VkImageResolve resolve{}; // resolves
929 // Depth or stencil resolves: the mode, and the destination view (`view` is the source's). 931 // Depth or stencil resolves: the mode, and the destination view (`view` is the source's).
@@ -1550,7 +1552,7 @@ inline ReplayResult prepare_texture_copy(const CopyTexture& copy, Prepared& p) {
1550 // Vulkan wants a buffer offset that is a multiple of the texel size (VUID-vkCmdCopyBufferToImage-dstImage-07975), 1552 // Vulkan wants a buffer offset that is a multiple of the texel size (VUID-vkCmdCopyBufferToImage-dstImage-07975),
1551 // which D3D12's 512-byte placement does not give a 12-byte texel: one more reason an rgb96 copy is repacked. 1553 // which D3D12's 512-byte placement does not give a 12-byte texel: one more reason an rgb96 copy is repacked.
1552 const std::uint32_t alignment = (range.aspectMask & depth_stencil_aspects) || image.rgb96 ? 4 : format.bytes; 1554 const std::uint32_t alignment = (range.aspectMask & depth_stencil_aspects) || image.rgb96 ? 4 : format.bytes;
1553 if (offset % alignment) return ReplayResult::unsupported; 1555 if (offset % alignment && !copy.tile_footprint) return ReplayResult::unsupported;
1554 const std::uint64_t rows = (std::uint64_t(h) + format.block - 1) / format.block; 1556 const std::uint64_t rows = (std::uint64_t(h) + format.block - 1) / format.block;
1555 const std::uint64_t row_bytes = (std::uint64_t(w) + format.block - 1) / format.block * format.bytes; 1557 const std::uint64_t row_bytes = (std::uint64_t(w) + format.block - 1) / format.block * format.bytes;
1556 if (!rows || !row_bytes || !within(std::uint64_t(placed_x / format.block) * format.bytes, row_bytes, placed.row_pitch) || 1558 if (!rows || !row_bytes || !within(std::uint64_t(placed_x / format.block) * format.bytes, row_bytes, placed.row_pitch) ||
@@ -1559,7 +1561,7 @@ inline ReplayResult prepare_texture_copy(const CopyTexture& copy, Prepared& p) {
1559 return ReplayResult::invalid_copy; 1561 return ReplayResult::invalid_copy;
1560 if (buffer.size > UINT64_MAX - buffer.buffer_offset) return ReplayResult::invalid_copy; 1562 if (buffer.size > UINT64_MAX - buffer.buffer_offset) return ReplayResult::invalid_copy;
1561 const VkDeviceSize backing_offset = buffer.buffer_offset + offset; 1563 const VkDeviceSize backing_offset = buffer.buffer_offset + offset;
1562 if (backing_offset % alignment) return ReplayResult::unsupported; 1564 if (backing_offset % alignment && !copy.tile_footprint) return ReplayResult::unsupported;
1563 VkBufferImageCopy region{}; 1565 VkBufferImageCopy region{};
1564 region.bufferOffset = backing_offset; 1566 region.bufferOffset = backing_offset;
1565 region.bufferRowLength = placed.row_pitch / format.bytes * format.block; 1567 region.bufferRowLength = placed.row_pitch / format.bytes * format.block;
@@ -1579,6 +1581,30 @@ inline ReplayResult prepare_texture_copy(const CopyTexture& copy, Prepared& p) {
1579 return ReplayResult::success; 1581 return ReplayResult::success;
1580} 1582}
1581 1583
1584// RGBA8 CopyTiles accepts arbitrary byte offsets into its linear buffer, while VkBufferImageCopy requires texel
1585// alignment. Stage only the occupied texels through aligned transfer scratch; leave partial-tile padding alone.
1586inline bool stage_unaligned_tile(const ReplayFunctions& vk, Prepared& p, bool upload) {
1587 auto& region = p.buffer_image_copies.front();
1588 const VkDeviceSize row_bytes = VkDeviceSize(region.imageExtent.width) * 4;
1589 const VkDeviceSize pitch = VkDeviceSize(region.bufferRowLength) * 4;
1590 const auto rows = region.imageExtent.height;
1591 VkDeviceSize scratch_offset = 0;
1592 if (!vk.copy_scratch || !vk.copy_scratch(row_bytes * rows, p.tile_scratch, scratch_offset)) return false;
1593 const auto app_offset = region.bufferOffset;
1594 const auto add_copy = [&](VkDeviceSize linear, VkDeviceSize scratch, VkDeviceSize bytes) {
1595 p.tile_rows.push_back(upload ? VkBufferCopy{linear, scratch, bytes} : VkBufferCopy{scratch, linear, bytes});
1596 };
1597 if (row_bytes == pitch) {
1598 add_copy(app_offset, scratch_offset, row_bytes * rows);
1599 } else {
1600 for (std::uint32_t row = 0; row < rows; ++row)
1601 add_copy(app_offset + row * pitch, scratch_offset + row * row_bytes, row_bytes);
1602 }
1603 region.bufferOffset = scratch_offset;
1604 region.bufferRowLength = 0;
1605 return true;
1606}
1607
1582// CopyResource: the whole buffer, or every subresource of two textures of the same shape. 1608// CopyResource: the whole buffer, or every subresource of two textures of the same shape.
1583inline ReplayResult prepare_resource_copy(Prepared& p) { 1609inline ReplayResult prepare_resource_copy(Prepared& p) {
1584 if (p.binding.buffer && p.source.buffer) { 1610 if (p.binding.buffer && p.source.buffer) {
@@ -2286,6 +2312,9 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
2286 // A depth plane footprint of a D24 texture stored as D32: words of 24-bit UNORM, floats in the image. 2312 // A depth plane footprint of a D24 texture stored as D32: words of 24-bit UNORM, floats in the image.
2287 const bool upload = texture_copy->src.footprint; 2313 const bool upload = texture_copy->src.footprint;
2288 const ResourceBinding& image = upload ? p.binding : p.source; 2314 const ResourceBinding& image = upload ? p.binding : p.source;
2315 if (result == ReplayResult::success && texture_copy->tile_footprint && !p.buffer_image_copies.empty() &&
2316 p.buffer_image_copies.front().bufferOffset % 4 && !detail::stage_unaligned_tile(vk, p, upload))
2317 return ReplayResult::unsupported;
2289 const bool depth24_footprint = result == ReplayResult::success && image.depth24_as_float && 2318 const bool depth24_footprint = result == ReplayResult::success && image.depth24_as_float &&
2290 !p.buffer_image_copies.empty() && 2319 !p.buffer_image_copies.empty() &&
2291 p.buffer_image_copies[0].imageSubresource.aspectMask == VK_IMAGE_ASPECT_DEPTH_BIT; 2320 p.buffer_image_copies[0].imageSubresource.aspectMask == VK_IMAGE_ASPECT_DEPTH_BIT;
@@ -3106,7 +3135,13 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
3106 VkBuffer source = p.source.buffer; 3135 VkBuffer source = p.source.buffer;
3107 std::vector<VkBufferImageCopy> converted; 3136 std::vector<VkBufferImageCopy> converted;
3108 const std::vector<VkBufferImageCopy>* regions = &p.buffer_image_copies; 3137 const std::vector<VkBufferImageCopy>* regions = &p.buffer_image_copies;
3109 if (p.has_depth24) { 3138 if (p.tile_scratch) {
3139 vk.copy_buffer(command_buffer, source, p.tile_scratch, std::uint32_t(p.tile_rows.size()),
3140 p.tile_rows.data());
3141 detail::memory_barrier(vk, command_buffer, VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
3142 VK_ACCESS_TRANSFER_READ_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT);
3143 source = p.tile_scratch;
3144 } else if (p.has_depth24) {
3110 // The words become floats in the scratch buffer, which the copy then reads (tightly packed). 3145 // The words become floats in the scratch buffer, which the copy then reads (tightly packed).
3111 detail::memory_barrier(vk, command_buffer, VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 3146 detail::memory_barrier(vk, command_buffer, VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
3112 VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT, 3147 VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT,
@@ -3133,8 +3168,16 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
3133 vk, command_buffer, p.source, src_id, detail::planes_for_layout(p.source, p.source_range, separate), 3168 vk, command_buffer, p.source, src_id, detail::planes_for_layout(p.source, p.source_range, separate),
3134 VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_ACCESS_TRANSFER_READ_BIT, tracker); 3169 VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_ACCESS_TRANSFER_READ_BIT, tracker);
3135 if (!p.has_depth24) { 3170 if (!p.has_depth24) {
3136 vk.copy_image_to_buffer(command_buffer, p.source.image, src_layout, p.binding.buffer, 3171 const auto target = p.tile_scratch ? p.tile_scratch : p.binding.buffer;
3172 vk.copy_image_to_buffer(command_buffer, p.source.image, src_layout, target,
3137 std::uint32_t(p.buffer_image_copies.size()), p.buffer_image_copies.data()); 3173 std::uint32_t(p.buffer_image_copies.size()), p.buffer_image_copies.data());
3174 if (p.tile_scratch) {
3175 detail::memory_barrier(vk, command_buffer, VK_ACCESS_TRANSFER_WRITE_BIT,
3176 VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_READ_BIT,
3177 VK_PIPELINE_STAGE_TRANSFER_BIT);
3178 vk.copy_buffer(command_buffer, p.tile_scratch, p.binding.buffer,
3179 std::uint32_t(p.tile_rows.size()), p.tile_rows.data());
3180 }
3138 } else { 3181 } else {
3139 // The floats land tightly packed in the scratch buffer; the pass turns them into the footprint's words. 3182 // The floats land tightly packed in the scratch buffer; the pass turns them into the footprint's words.
3140 VkBufferImageCopy region = p.buffer_image_copies[0]; 3183 VkBufferImageCopy region = p.buffer_image_copies[0];