diff --git a/core/kyty/graphics/host_gpu/graphicContext.h b/core/kyty/graphics/host_gpu/graphicContext.h index a59c2ac1ff4..f59a54b7315 100644 --- a/core/kyty/graphics/host_gpu/graphicContext.h +++ b/core/kyty/graphics/host_gpu/graphicContext.h @@ -29,6 +29,7 @@ struct GraphicContext { vk::Device device = nullptr; VmaAllocator allocator = nullptr; bool memory_budget_ext_enabled = false; + bool partial_textures_enabled = false; bool host_import_enabled = false; uint64_t host_import_alignment = 0; bool compute_subgroup_size_control_enabled = false; @@ -131,6 +132,13 @@ struct GraphicContext { [[nodiscard]] uint64_t GetDeviceMemoryUsage() const; [[nodiscard]] uint64_t GetTotalMemoryBudget() const; + struct DeviceLocalBudget { + uint64_t usage = 0; + uint64_t budget = 0; + uint64_t reserve = 0; + }; + [[nodiscard]] DeviceLocalBudget GetDeviceLocalBudget() const; + struct HeapUsage { uint64_t usage = 0; uint64_t budget = 0; @@ -139,6 +147,10 @@ struct GraphicContext { }; [[nodiscard]] uint32_t GetHeapUsage(std::span heaps) const; [[nodiscard]] bool CreateImage(const vk::ImageCreateInfo& info, VulkanImage& image); + [[nodiscard]] bool CreatePartialImage(const vk::ImageCreateInfo& info, uint32_t first_level, VulkanImage& image); + [[nodiscard]] bool BindOmittedLevels(VulkanImage& image); + [[nodiscard]] uint64_t FlushSparseBinds(); + [[nodiscard]] vk::Semaphore SparseBindSemaphore() const noexcept { return m_sparse_semaphore; } void DeleteImage(VulkanImage& image); uint32_t screen_width = 0; @@ -152,6 +164,20 @@ struct GraphicContext { vk::ImageCreateFlags>, std::pair> m_image_format_properties; + + struct SparseBind { + vk::Image image = nullptr; + std::vector levels; + std::vector tails; + }; + [[nodiscard]] bool QueueLevelBinds(VulkanImage& image, uint32_t first_level, uint32_t end_level, + bool bind_tail, bool within_budget, VmaAllocation& allocation); + void WaitSparseBinds(vk::Image image); + + std::mutex m_sparse_mutex; + std::vector m_sparse_pending; + vk::Semaphore m_sparse_semaphore = nullptr; + uint64_t m_sparse_value = 0; }; struct VulkanImageState { @@ -176,7 +202,9 @@ struct VulkanImage { VulkanImageState state; std::vector subresource_states; VmaAllocation allocation = nullptr; + VmaAllocation omitted_allocation = nullptr; bool recyclable = false; + uint32_t first_resident_level = 0; }; diff --git a/core/kyty/graphics/host_gpu/renderer/cache/textureCache.cpp b/core/kyty/graphics/host_gpu/renderer/cache/textureCache.cpp index 3893b555893..aa5c9026a6b 100644 --- a/core/kyty/graphics/host_gpu/renderer/cache/textureCache.cpp +++ b/core/kyty/graphics/host_gpu/renderer/cache/textureCache.cpp @@ -1202,6 +1202,8 @@ void TextureCache::CopyImage(ImageId destination_id, ImageId source_id) { RefreshCopySource(source_id); auto& destination = m_slot_images[destination_id]; auto& source = m_slot_images[source_id]; + MakeResident(source); + MakeResident(destination); TrackImage(destination_id); if (source.backing.samples != destination.backing.samples) { EXIT("TextureCache: cannot issue an unequal-sample image copy\n"); @@ -1245,6 +1247,8 @@ void TextureCache::CopyImageMip(ImageId destination_id, ImageId source_id, uint3 } auto& destination = m_slot_images[destination_id]; auto& source = m_slot_images[source_id]; + MakeResident(source); + MakeResident(destination); TrackImage(destination_id); if (source.IsBufferModified() || source.backing.samples != destination.backing.samples) { EXIT("TextureCache: invalid mip-copy ownership or sample count\n"); @@ -1663,7 +1667,25 @@ bool TextureCache::CanDownload(const Image& image) const { info.LinearSize() != 0; } -void TextureCache::UploadImage(Image& image, Buffer& source, uint64_t source_offset) { +void TextureCache::MakeResident(Image& image) { + if (!image.IsPartiallyResident()) { + return; + } + const auto omitted = image.backing.first_resident_level; + if (!image.MakeResident()) { + EXIT("TextureCache: could not back the omitted levels of image 0x%016" PRIx64 "\n", + image.info.data.address); + } + const auto [source, source_offset] = + m_buffer_cache.ObtainBufferForImage(image.info.data.address, image.info.data.size); + if (source == nullptr) { + EXIT("TextureCache: failed to obtain the upload source of omitted levels\n"); + } + UploadImage(image, *source, source_offset, omitted); +} + +void TextureCache::UploadImage(Image& image, Buffer& source, uint64_t source_offset, + uint32_t level_end) { auto& destination = image.depth_id ? m_slot_images[image.depth_id] : image; const auto& info = image.info; const auto binding = image.depth_id ? BindingType::DepthTarget : UploadBinding(image); @@ -1674,14 +1696,18 @@ void TextureCache::UploadImage(Image& image, Buffer& source, uint64_t source_off EXIT("TextureCache: invalid color-attachment upload\n"); } const auto linear = m_tiler.Detile(source.Handle(), source_offset, info); - const auto copies = info.BufferCopies(linear.offset); + auto copies = info.BufferCopies(linear.offset); + std::erase_if(copies, [level_end](const vk::BufferImageCopy& copy) { + return copy.imageSubresource.mipLevel >= level_end; + }); + EXIT_IF(copies.empty()); destination.Upload(copies, linear.buffer, linear.offset, linear.size); Common::DebugCounters::Add(Common::DebugCounters::Counter::TextureUploadBytes, linear.size); return; } if (destination.backing.samples != 1 || info.resources.layers == 0 || - info.data.size % info.resources.layers != 0 || + info.data.size % info.resources.layers != 0 || level_end != UINT32_MAX || Prospero::NumBytesPerElement(info.guest_format) != info.bytes_per_block) { EXIT("TextureCache: invalid depth upload\n"); } @@ -2761,6 +2787,9 @@ vk::ImageView TextureCache::FindTexture(ImageId id, const ImageDesc& desc) { EXIT("TextureCache: texture requires rediscovery before final acquisition\n"); } RefreshImage(id); + if (desc.type != BindingType::Texture || image.ReachesOmittedLevels(desc.view_info)) { + MakeResident(image); + } if (image.info.HasStencil() && desc.info.data.address >= image.info.stencil.address && desc.info.data.End() <= image.info.stencil.End()) { @@ -2792,6 +2821,7 @@ vk::ImageView TextureCache::FindRenderTarget(ImageId id, const ImageDesc& desc) image.StateChanged(); } RefreshImage(id); + MakeResident(image); CommitGpuWrite(image); TrackImageDownload(id, image); return image.FindView(desc.view_info); @@ -2834,6 +2864,7 @@ vk::ImageView TextureCache::FindDepthTarget(ImageId id, const ImageDesc& desc, I m_meta_epoch.fetch_add(1, std::memory_order_relaxed); } RefreshImage(id); + MakeResident(image); CommitGpuWrite(image); if (desc.info.HasStencil()) { const auto association = AssociateStencil(id, desc.info.stencil); @@ -2974,6 +3005,7 @@ bool TextureCache::ClearImageFromBuffer(CommandBuffer& command, uint64_t address void TextureCache::ClearImage(CommandBuffer& command, ImageId id, vk::Format format, const vk::ImageSubresourceRange& range, const vk::ClearValue& clear) { auto& image = m_slot_images[id]; + MakeResident(image); const auto aspects = image.info.IsDepth() ? ImageViewOps::DepthAspectMask(image.backing.format) : vk::ImageAspectFlagBits::eColor; EXIT_IF(range.baseMipLevel >= image.info.resources.levels); @@ -3037,6 +3069,7 @@ vk::Rect2D TextureCache::BeginColorRendering(Image& image, vk::Format format, ui uint32_t layer, uint32_t layers, const vk::ClearValue* clear, const CommandRecorder& command) { + MakeResident(image); ImageViewInfo view {}; view.format = format; view.type = layers == 1 ? vk::ImageViewType::e2D : vk::ImageViewType::e2DArray; @@ -3068,6 +3101,7 @@ vk::Rect2D TextureCache::BeginColorRendering(Image& image, vk::Format format, ui } void TextureCache::DownloadDepth(Image& image, Buffer& destination, uint64_t destination_offset) { + MakeResident(image); const auto& info = image.info; const auto layers = info.resources.layers; const auto full_slice_size = info.linear_slice_stride != 0 ? info.linear_slice_stride @@ -3139,6 +3173,7 @@ void TextureCache::DownloadDepth(Image& image, Buffer& destination, uint64_t des void TextureCache::DownloadImage(Image& image, Buffer& destination, uint64_t destination_offset, uint64_t destination_size, uint32_t levels) { + MakeResident(image); if (UploadBinding(image) == BindingType::DepthTarget) { EXIT_IF(destination_size != image.info.data.size || levels != image.info.resources.levels); DownloadDepth(image, destination, destination_offset); diff --git a/core/kyty/graphics/host_gpu/renderer/cache/textureCache.h b/core/kyty/graphics/host_gpu/renderer/cache/textureCache.h index 877470354a3..6f096168213 100644 --- a/core/kyty/graphics/host_gpu/renderer/cache/textureCache.h +++ b/core/kyty/graphics/host_gpu/renderer/cache/textureCache.h @@ -386,7 +386,9 @@ class TextureCache { uint32_t metadata_base_layer); void InitializeImage(ImageId id); [[nodiscard]] bool CanDownload(const Image& image) const; - void UploadImage(Image& image, Buffer& source, uint64_t source_offset); + void UploadImage(Image& image, Buffer& source, uint64_t source_offset, + uint32_t level_end = UINT32_MAX); + void MakeResident(Image& image); void DownloadImage(Image& image, Buffer& destination, uint64_t destination_offset, uint64_t destination_size, uint32_t levels); void DownloadDepth(Image& image, Buffer& destination, uint64_t destination_offset); diff --git a/core/kyty/graphics/host_gpu/renderer/commandScheduler.cpp b/core/kyty/graphics/host_gpu/renderer/commandScheduler.cpp index 1f12c6d6002..7d230c63214 100644 --- a/core/kyty/graphics/host_gpu/renderer/commandScheduler.cpp +++ b/core/kyty/graphics/host_gpu/renderer/commandScheduler.cpp @@ -624,6 +624,9 @@ void CommandScheduler::QueueSubmit(vk::CommandBuffer buffer, SubmitInfo& submit, auto& graphics = m_graphics; EXIT_IF(graphics.queue == nullptr); submit.AddSignal(m_master.Handle(), tick); + if (const auto sparse = graphics.FlushSparseBinds(); sparse != 0) { + submit.AddWait(graphics.SparseBindSemaphore(), sparse); + } vk::TimelineSemaphoreSubmitInfo timeline_info {}; timeline_info.waitSemaphoreValueCount = submit.num_wait_semaphores; diff --git a/core/kyty/graphics/host_gpu/renderer/image/image.cpp b/core/kyty/graphics/host_gpu/renderer/image/image.cpp index 7f48a5532be..56746301793 100644 --- a/core/kyty/graphics/host_gpu/renderer/image/image.cpp +++ b/core/kyty/graphics/host_gpu/renderer/image/image.cpp @@ -13,7 +13,10 @@ #include #include #include +#include #include +#include +#include #include #include @@ -52,6 +55,26 @@ ImageCreateFlags(const GraphicContext& graphics, const ImageInfo& info, vk::Imag return static_cast(properties.optimalTilingFeatures & feature); } +[[nodiscard]] static uint32_t PartialFirstLevel(GraphicContext& graphics, const ImageInfo& info, + const vk::ImageCreateInfo& create) { + static const uint64_t threshold_mb = [] { + const char* value = std::getenv("KYTY_PARTIAL_TEXTURE_MB"); + return value != nullptr && value[0] != '\0' ? std::strtoull(value, nullptr, 10) : UINT64_MAX; + }(); + if (threshold_mb == 0 || !graphics.partial_textures_enabled || !graphics.CanReportMemoryUsage() || + !info.IsBlock() || create.imageType != vk::ImageType::e2D || create.samples != vk::SampleCountFlagBits::e1 || + create.mipLevels < 3 || std::max(create.extent.width, create.extent.height) < 512) { + return 0; + } + const auto memory = graphics.GetDeviceLocalBudget(); + const uint64_t start = threshold_mb != UINT64_MAX ? std::min(threshold_mb, UINT64_MAX >> 20u) << 20u + : memory.budget - memory.reserve; + if (memory.budget == 0 || memory.usage < start) { + return 0; + } + return memory.usage >= start + (memory.budget - std::min(memory.budget, start)) / 2u ? 2u : 1u; +} + [[nodiscard]] vk::ImageUsageFlags ImageUsageFlags(GraphicContext& graphics, const ImageInfo& info) { auto usage = vk::ImageUsageFlagBits::eTransferSrc | vk::ImageUsageFlagBits::eTransferDst; if (info.IsBlock()) { @@ -287,6 +310,18 @@ void Image::Transit(vk::ImageLayout destination_layout, vk::AccessFlags2 destina void Image::Upload(std::span copies, vk::Buffer buffer, uint64_t offset, uint64_t size) { EXIT_IF(copies.empty() || buffer == nullptr || size == 0); + std::vector resident; + if (backing.first_resident_level != 0) { + for (const auto& copy: copies) { + if (copy.imageSubresource.mipLevel >= backing.first_resident_level) { + resident.push_back(copy); + } + } + if (resident.empty()) { + return; + } + copies = resident; + } m_scheduler.EndRendering(); vk::BufferMemoryBarrier2 buffer_barrier {}; buffer_barrier.srcStageMask = vk::PipelineStageFlagBits2::eAllCommands; @@ -321,9 +356,33 @@ void Image::Upload(std::span copies, vk::Buffer buffe command.pipelineBarrier2(dependency); } +void Image::RequireResident(const Image& source) const { + if (IsPartiallyResident() || source.IsPartiallyResident()) { + EXIT("Image: a transfer reaches the omitted levels of a partially resident image " + "(guest 0x%016" PRIx64 ", source 0x%016" PRIx64 ")\n", + info.data.address, source.info.data.address); + } +} + +bool Image::MakeResident() { + if (!IsPartiallyResident()) { + return true; + } + if (!m_graphics.BindOmittedLevels(backing)) { + return false; + } + for (const auto& cached: views) { + m_retired_views.push_back(cached.view); + } + views.clear(); + HeapChanged(); + return true; +} + void Image::Download(std::span copies, vk::Buffer buffer, uint64_t offset, uint64_t size) { EXIT_IF(copies.empty() || buffer == nullptr || size == 0); + RequireResident(*this); m_scheduler.EndRendering(); vk::BufferMemoryBarrier2 buffer_barrier {}; buffer_barrier.srcStageMask = vk::PipelineStageFlagBits2::eAllCommands; @@ -383,6 +442,7 @@ std::pair Image::SanitizeCopyLayers(const Image& source, void Image::CopyImage(Image& source) { EXIT_IF(source.backing.samples != backing.samples); + RequireResident(source); m_scheduler.EndRendering(); const uint32_t levels = std::min(source.backing.mip_levels, backing.mip_levels); uint32_t base_depth = source.backing.extent.depth; @@ -440,6 +500,7 @@ void Image::Resolve(Image& source, const ImageSubresourceRange& source_range, destination_range.base_level >= backing.mip_levels || source_range.base_layer >= source.backing.layers || destination_range.base_layer >= backing.layers); + RequireResident(source); const auto layers = std::min({source_range.layer_count, destination_range.layer_count, source.backing.layers - source_range.base_layer, backing.layers - destination_range.base_layer}); @@ -499,6 +560,7 @@ uint32_t Image::CopyRows(uint64_t row_size, uint32_t rows, uint64_t capacity) no void Image::CopyImageWithBuffer(Image& source, Buffer& buffer, TileManager& tiler) { EXIT_IF(buffer.Handle() == nullptr || source.backing.samples != 1 || backing.samples != 1); + RequireResident(source); m_scheduler.EndRendering(); const uint32_t levels = std::min(source.backing.mip_levels, backing.mip_levels); const auto source_aspect = @@ -599,6 +661,7 @@ void Image::CopyImageWithBuffer(Image& source, Buffer& buffer, TileManager& tile void Image::CopyMip(Image& source, uint32_t mip, uint32_t layer) { EXIT_IF(source.backing.samples != backing.samples || mip >= backing.mip_levels || layer >= backing.layers); + RequireResident(source); m_scheduler.EndRendering(); const auto width = std::max(backing.extent.width >> mip, 1u); const auto height = std::max(backing.extent.height >> mip, 1u); @@ -749,7 +812,9 @@ Image::Image(GraphicContext& graphics, CommandScheduler& scheduler, const ImageI static_cast(create.flags), info.samples); } - if (!graphics.CreateImage(create, backing)) { + const auto first_level = PartialFirstLevel(graphics, info, create); + if ((first_level == 0 || !graphics.CreatePartialImage(create, first_level, backing)) && + !graphics.CreateImage(create, backing)) { EXIT("failed to create image: extent=%ux%ux%u format=%d layers=%u levels=%u\n", create.extent.width, create.extent.height, create.extent.depth, static_cast(create.format), create.arrayLayers, create.mipLevels); @@ -786,6 +851,9 @@ Image::~Image() { for (const auto& cached: views) { m_graphics.device.destroyImageView(cached.view, nullptr); } + for (const auto view: m_retired_views) { + m_graphics.device.destroyImageView(view, nullptr); + } if (backing.image != nullptr) { m_graphics.DeleteImage(backing); } diff --git a/core/kyty/graphics/host_gpu/renderer/image/image.h b/core/kyty/graphics/host_gpu/renderer/image/image.h index 881471cd819..5f907685569 100644 --- a/core/kyty/graphics/host_gpu/renderer/image/image.h +++ b/core/kyty/graphics/host_gpu/renderer/image/image.h @@ -71,6 +71,13 @@ class Image final { const ImageSubresourceRange& destination_range); void CopyImageWithBuffer(Image& source, Buffer& buffer, TileManager& tiler); void CopyMip(Image& source, uint32_t mip, uint32_t layer); + [[nodiscard]] bool IsPartiallyResident() const noexcept { return backing.first_resident_level != 0; } + [[nodiscard]] bool ReachesOmittedLevels(const ImageViewInfo& view) const noexcept { + return IsPartiallyResident() && + (static_cast(view.usage & ~vk::ImageUsageFlagBits::eSampled) || + view.base_level + view.level_count <= backing.first_resident_level); + } + [[nodiscard]] bool MakeResident(); [[nodiscard]] static uint64_t CpuDirtyEpoch() noexcept { return s_cpu_dirty_epoch.load(std::memory_order_relaxed); @@ -262,8 +269,11 @@ class Image final { [[nodiscard]] static std::pair SanitizeCopyLayers(const Image& source, const Image& destination, uint32_t depth); + void RequireResident(const Image& source) const; + GraphicContext& m_graphics; CommandScheduler& m_scheduler; + std::vector m_retired_views; uint64_t m_maybe_cpu_hash = 0; bool m_cpu_dirty = false; bool m_maybe_cpu_dirty = false; diff --git a/core/kyty/graphics/host_gpu/renderer/image/imageView.cpp b/core/kyty/graphics/host_gpu/renderer/image/imageView.cpp index 31b2799c0ff..67a529b7457 100644 --- a/core/kyty/graphics/host_gpu/renderer/image/imageView.cpp +++ b/core/kyty/graphics/host_gpu/renderer/image/imageView.cpp @@ -275,6 +275,13 @@ bool FormatsCompatible(vk::Format base, vk::Format view) noexcept { } vk::ImageView Image::FindView(const ImageViewInfo& view_info) { + if (ReachesOmittedLevels(view_info)) { + EXIT("Image: view mip=%u+%u usage=0x%x reaches the omitted levels 0..%u of a partially " + "resident image\n", + view_info.base_level, view_info.level_count, + static_cast(view_info.usage), + backing.first_resident_level - 1u); + } const auto& image = backing; auto normalized = view_info; const bool is_storage = static_cast(normalized.usage & vk::ImageUsageFlagBits::eStorage); @@ -334,6 +341,12 @@ vk::ImageView Image::FindView(const ImageViewInfo& view_info) { static_cast(normalized.min_lod) / 256.0f; usage.pNext = &min_lod; } + if (image.first_resident_level > normalized.base_level) { + const auto last = normalized.base_level + normalized.level_count - 1u; + const auto resident = static_cast(std::min(image.first_resident_level, last)); + min_lod.minLod = std::max(min_lod.minLod, resident); + usage.pNext = &min_lod; + } vk::ImageViewCreateInfo create {}; create.pNext = &usage; create.image = image.image; diff --git a/core/kyty/graphics/host_gpu/renderer/render.h b/core/kyty/graphics/host_gpu/renderer/render.h index 86c54126126..6b2d6d6517a 100644 --- a/core/kyty/graphics/host_gpu/renderer/render.h +++ b/core/kyty/graphics/host_gpu/renderer/render.h @@ -101,7 +101,7 @@ struct StateKeyCache { }; struct SubmitInfo { - static constexpr uint32_t MaxSemaphores = 3; + static constexpr uint32_t MaxSemaphores = 4; std::array wait_semaphores {}; std::array wait_ticks {}; diff --git a/core/kyty/graphics/host_gpu/vma.cpp b/core/kyty/graphics/host_gpu/vma.cpp index 172c9dc5415..0ae78b43f5f 100644 --- a/core/kyty/graphics/host_gpu/vma.cpp +++ b/core/kyty/graphics/host_gpu/vma.cpp @@ -14,6 +14,7 @@ #pragma clang diagnostic pop #endif +#include "common/alignment.h" #include "common/assert.h" #include "common/logging/log.h" #include "common/profiler.h" @@ -179,6 +180,12 @@ void GraphicContext::DestroyAllocator() { DestroyRecycledImages(allocator); vmaDestroyAllocator(allocator); allocator = nullptr; + std::lock_guard lock(m_sparse_mutex); + m_sparse_pending.clear(); + if (m_sparse_semaphore != nullptr) { + device.destroySemaphore(m_sparse_semaphore, nullptr); + m_sparse_semaphore = nullptr; + } } void GraphicContext::LogMemoryBudget() const { @@ -236,6 +243,32 @@ uint32_t GraphicContext::GetHeapUsage(std::span return count; } +static uint64_t AllocatorReserve(uint64_t budget) { + return std::min(budget / 8, 1024ull * 1024 * 1024); +} + +GraphicContext::DeviceLocalBudget GraphicContext::GetDeviceLocalBudget() const { + if (!CanReportMemoryUsage() || allocator == nullptr) { + return {}; + } + VmaBudget budgets[VK_MAX_MEMORY_HEAPS] {}; + vmaGetHeapBudgets(allocator, budgets); + const bool discrete = + physical_device_properties.deviceType == vk::PhysicalDeviceType::eDiscreteGpu; + DeviceLocalBudget result; + for (uint32_t heap = 0; heap < physical_device_memory_properties.memoryHeapCount; heap++) { + const bool device_local = + static_cast(physical_device_memory_properties.memoryHeaps[heap].flags & + vk::MemoryHeapFlagBits::eDeviceLocal); + if (!discrete || device_local) { + result.usage += budgets[heap].usage; + result.budget += budgets[heap].budget; + } + } + result.reserve = AllocatorReserve(result.budget); + return result; +} + uint64_t GraphicContext::GetTotalMemoryBudget() const { if (allocator == nullptr) { return 0; @@ -260,7 +293,7 @@ uint64_t GraphicContext::GetTotalMemoryBudget() const { } } if (discrete) { - return budget - std::min(budget / 8, 1024ull * 1024 * 1024); + return budget - AllocatorReserve(budget); } constexpr uint64_t system_reserve = 8ull * 1024 * 1024 * 1024; const auto available = budget > usage ? budget - usage : uint64_t {0}; @@ -322,9 +355,235 @@ bool GraphicContext::CreateImage(const vk::ImageCreateInfo& image_info, VulkanIm return true; } +bool GraphicContext::QueueLevelBinds(VulkanImage& image, uint32_t first_level, uint32_t end_level, + bool bind_tail, bool within_budget, VmaAllocation& allocation) { + const auto requirements = device.getImageMemoryRequirements(image.image); + const auto sparse = device.getImageSparseMemoryRequirements(image.image); + const vk::SparseImageMemoryRequirements* color = nullptr; + for (const auto& entry: sparse) { + if (entry.formatProperties.aspectMask & vk::ImageAspectFlagBits::eMetadata) { + return false; + } + if (entry.formatProperties.aspectMask & vk::ImageAspectFlagBits::eColor) { + color = &entry; + } + } + if (color == nullptr) { + return false; + } + const auto block = requirements.alignment; + const auto& granularity = color->formatProperties.imageGranularity; + const bool single_tail = static_cast(color->formatProperties.flags & + vk::SparseImageFormatFlagBits::eSingleMiptail); + const auto tail_first = std::min(color->imageMipTailFirstLod, image.mip_levels); + SparseBind request {.image = image.image}; + uint64_t total = 0; + for (uint32_t layer = 0; layer < image.layers; layer++) { + for (uint32_t level = first_level; level < std::min(end_level, tail_first); level++) { + const vk::Extent3D extent {std::max(1u, image.extent.width >> level), + std::max(1u, image.extent.height >> level), 1u}; + const uint64_t blocks = + static_cast((extent.width + granularity.width - 1) / granularity.width) * + ((extent.height + granularity.height - 1) / granularity.height); + vk::SparseImageMemoryBind bind {}; + bind.subresource = {vk::ImageAspectFlagBits::eColor, level, layer}; + bind.extent = extent; + bind.memoryOffset = total; + request.levels.push_back(bind); + total += blocks * block; + } + } + if (bind_tail && tail_first < image.mip_levels) { + const uint32_t tails = single_tail ? 1u : image.layers; + const uint64_t tail_size = Common::AlignUp(color->imageMipTailSize, block); + for (uint32_t tail = 0; tail < tails; tail++) { + vk::SparseMemoryBind bind {}; + bind.resourceOffset = color->imageMipTailOffset + tail * color->imageMipTailStride; + bind.size = color->imageMipTailSize; + bind.memoryOffset = total; + request.tails.push_back(bind); + total += tail_size; + } + } + if (total == 0) { + return false; + } + + VkMemoryRequirements memory {}; + memory.size = total; + memory.alignment = block; + memory.memoryTypeBits = requirements.memoryTypeBits; + VmaAllocationCreateInfo alloc_info {}; + alloc_info.flags = within_budget ? VMA_ALLOCATION_CREATE_WITHIN_BUDGET_BIT : 0; + alloc_info.requiredFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; + VmaAllocationInfo allocated {}; + if (vmaAllocateMemory(allocator, &memory, &alloc_info, &allocation, &allocated) != VK_SUCCESS) { + allocation = nullptr; + return false; + } + for (auto& bind: request.levels) { + bind.memory = allocated.deviceMemory; + bind.memoryOffset += allocated.offset; + } + for (auto& bind: request.tails) { + bind.memory = allocated.deviceMemory; + bind.memoryOffset += allocated.offset; + } + std::lock_guard lock(m_sparse_mutex); + m_sparse_pending.push_back(std::move(request)); + return true; +} + +bool GraphicContext::CreatePartialImage(const vk::ImageCreateInfo& image_info, uint32_t first_level, + VulkanImage& image) { + KYTY_PROFILER_FUNCTION(); + EXIT_IF(allocator == nullptr || image.image != nullptr || image.allocation != nullptr); + if (!partial_textures_enabled || first_level == 0 || first_level >= image_info.mipLevels || + image_info.imageType != vk::ImageType::e2D || image_info.samples != vk::SampleCountFlagBits::e1 || + image_info.tiling != vk::ImageTiling::eOptimal) { + return false; + } + auto create = image_info; + create.flags |= vk::ImageCreateFlagBits::eSparseBinding | vk::ImageCreateFlagBits::eSparseResidency; + const auto sparse_formats = physical_device.getSparseImageFormatProperties( + create.format, create.imageType, create.samples, create.usage, create.tiling); + if (sparse_formats.empty()) { + return false; + } + vk::Image native_image = nullptr; + if (device.createImage(&create, nullptr, &native_image) != vk::Result::eSuccess) { + return false; + } + const auto sparse = device.getImageSparseMemoryRequirements(native_image); + const auto color = std::ranges::find_if(sparse, [](const auto& entry) { + return static_cast(entry.formatProperties.aspectMask & vk::ImageAspectFlagBits::eColor); + }); + if (color == sparse.end() || color->imageMipTailFirstLod <= first_level) { + device.destroyImage(native_image, nullptr); + return false; + } + + image.image = native_image; + image.format = create.format; + image.image_type = create.imageType; + image.extent = create.extent; + image.layers = create.arrayLayers; + image.mip_levels = create.mipLevels; + image.samples = static_cast(create.samples); + image.usage = create.usage; + image.recyclable = false; + image.flags = create.flags; + image.first_resident_level = first_level; + image.state = {.layout = create.initialLayout}; + image.subresource_states.clear(); + if (!QueueLevelBinds(image, first_level, create.mipLevels, true, true, image.allocation)) { + device.destroyImage(native_image, nullptr); + image.image = nullptr; + image.allocation = nullptr; + image.first_resident_level = 0; + return false; + } + return true; +} + +bool GraphicContext::BindOmittedLevels(VulkanImage& image) { + KYTY_PROFILER_FUNCTION(); + if (image.first_resident_level == 0) { + return true; + } + EXIT_IF(image.omitted_allocation != nullptr); + if (!QueueLevelBinds(image, 0, image.first_resident_level, false, false, + image.omitted_allocation)) { + return false; + } + image.first_resident_level = 0; + return true; +} + +uint64_t GraphicContext::FlushSparseBinds() { + std::lock_guard lock(m_sparse_mutex); + if (m_sparse_pending.empty()) { + return m_sparse_value; + } + KYTY_PROFILER_FUNCTION(); + if (m_sparse_semaphore == nullptr) { + vk::SemaphoreTypeCreateInfo type {}; + type.semaphoreType = vk::SemaphoreType::eTimeline; + vk::SemaphoreCreateInfo create {}; + create.pNext = &type; + if (device.createSemaphore(&create, nullptr, &m_sparse_semaphore) != vk::Result::eSuccess) { + EXIT("could not create the sparse bind semaphore\n"); + } + } + std::vector levels; + std::vector tails; + levels.reserve(m_sparse_pending.size()); + tails.reserve(m_sparse_pending.size()); + for (const auto& request: m_sparse_pending) { + if (!request.levels.empty()) { + levels.push_back({request.image, static_cast(request.levels.size()), + request.levels.data()}); + } + if (!request.tails.empty()) { + tails.push_back({request.image, static_cast(request.tails.size()), + request.tails.data()}); + } + } + const uint64_t value = m_sparse_value + 1; + vk::TimelineSemaphoreSubmitInfo timeline {}; + timeline.signalSemaphoreValueCount = 1; + timeline.pSignalSemaphoreValues = &value; + vk::BindSparseInfo info {}; + info.pNext = &timeline; + info.imageBindCount = static_cast(levels.size()); + info.pImageBinds = levels.data(); + info.imageOpaqueBindCount = static_cast(tails.size()); + info.pImageOpaqueBinds = tails.data(); + info.signalSemaphoreCount = 1; + info.pSignalSemaphores = &m_sparse_semaphore; + vk::Result result; + { + Common::LockGuard queue_lock {queue_mutex}; + result = queue.bindSparse(1, &info, nullptr); + } + if (result != vk::Result::eSuccess) { + EXIT("vkQueueBindSparse failed: %s\n", vk::to_string(result).c_str()); + } + m_sparse_value = value; + m_sparse_pending.clear(); + return value; +} + +void GraphicContext::WaitSparseBinds(vk::Image image) { + uint64_t value = 0; + { + std::lock_guard lock(m_sparse_mutex); + std::erase_if(m_sparse_pending, + [image](const SparseBind& request) { return request.image == image; }); + value = m_sparse_value; + } + if (value == 0) { + return; + } + vk::SemaphoreWaitInfo wait {}; + wait.semaphoreCount = 1; + wait.pSemaphores = &m_sparse_semaphore; + wait.pValues = &value; + if (device.waitSemaphores(&wait, UINT64_MAX) != vk::Result::eSuccess) { + EXIT("waiting for the sparse binds failed\n"); + } +} + void GraphicContext::DeleteImage(VulkanImage& image) { KYTY_PROFILER_FUNCTION(); EXIT_IF(allocator == nullptr || image.image == nullptr || image.allocation == nullptr); + if (image.flags & vk::ImageCreateFlagBits::eSparseBinding) { + WaitSparseBinds(image.image); + if (image.omitted_allocation != nullptr) { + Graveyard().Push(allocator, VK_NULL_HANDLE, image.omitted_allocation); + image.omitted_allocation = nullptr; + } + } vk::ImageCreateInfo create {}; create.flags = image.flags; diff --git a/core/kyty/graphics/presentation/window/vulkanWindow.cpp b/core/kyty/graphics/presentation/window/vulkanWindow.cpp index 45d6f1522fa..c4a48f52c86 100644 --- a/core/kyty/graphics/presentation/window/vulkanWindow.cpp +++ b/core/kyty/graphics/presentation/window/vulkanWindow.cpp @@ -707,6 +707,17 @@ static vk::Device VulkanCreateDevice(GraphicContext& graphics, graphics.indirect_draws_enabled = device_features.multiDrawIndirect == VK_TRUE && device_features.drawIndirectFirstInstance == VK_TRUE && features12.drawIndirectCount == VK_TRUE; + { + const auto families = physical_device.getQueueFamilyProperties(); + graphics.partial_textures_enabled = + supported2.features.sparseBinding == VK_TRUE && supported2.features.sparseResidencyImage2D == VK_TRUE && + physical_device.getProperties().sparseProperties.residencyNonResidentStrict == VK_TRUE && + queue_family < families.size() && + static_cast(families[queue_family].queueFlags & vk::QueueFlagBits::eSparseBinding); + device_features.sparseBinding = graphics.partial_textures_enabled ? VK_TRUE : VK_FALSE; + device_features.sparseResidencyImage2D = graphics.partial_textures_enabled ? VK_TRUE : VK_FALSE; + LOGF("Vulkan partially resident textures: %s\n", graphics.partial_textures_enabled ? "true" : "false"); + } device_features.shaderInt64 = VK_TRUE; device_features.shaderFloat64 = supported2.features.shaderFloat64 && float_controls.shaderSignedZeroInfNanPreserveFloat64; diff --git a/core/libs/prx/libSceAgcDriver/KytyShim/src/Settings.cpp b/core/libs/prx/libSceAgcDriver/KytyShim/src/Settings.cpp index 46c13cad49f..3130eb3cab5 100644 --- a/core/libs/prx/libSceAgcDriver/KytyShim/src/Settings.cpp +++ b/core/libs/prx/libSceAgcDriver/KytyShim/src/Settings.cpp @@ -57,6 +57,7 @@ constexpr std::string_view Names[] = { "KYTY_LOCK_STATS_PERIOD", "KYTY_NATIVE_RT", "KYTY_OCCLUSION_QUERIES", + "KYTY_PARTIAL_TEXTURE_MB", "KYTY_PERF_OVERLAY", "KYTY_PGO_DIR", "KYTY_PGO_DUMP_SECONDS", diff --git a/core/libs/prx/libSceAgcDriver/KytyShim/tests/CMakeLists.txt b/core/libs/prx/libSceAgcDriver/KytyShim/tests/CMakeLists.txt index 4d5bdc20d14..5a75b4236e5 100644 --- a/core/libs/prx/libSceAgcDriver/KytyShim/tests/CMakeLists.txt +++ b/core/libs/prx/libSceAgcDriver/KytyShim/tests/CMakeLists.txt @@ -259,6 +259,14 @@ if(NOT ANYPS5_KYTY_DLL AND (WIN32 OR CMAKE_SYSTEM_NAME STREQUAL "Linux")) set_tests_properties(kyty_shim_image_write_back_alias PROPERTIES TIMEOUT 25 SKIP_RETURN_CODE 77 ENVIRONMENT "KYTY_GPU_PIPELINE=0;KYTY_WRITE_BACK_IMAGES=1;KYTY_COMPARE_WRITE_BACK=1" PASS_REGULAR_EXPRESSION "kyty_shim_image_write_back_alias: ok" FAIL_REGULAR_EXPRESSION "FAILED") + target_sources(libSceAgcDriver PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/PartialTextures.cpp) + add_test_executable(kyty_shim_partial_textures_tests ${CMAKE_CURRENT_SOURCE_DIR}/PartialTexturesMain.cpp) + configure_host_test_executable(kyty_shim_partial_textures_tests) + target_link_libraries(kyty_shim_partial_textures_tests PRIVATE libSceAgcDriver libkernel libc) + add_test(NAME kyty_shim_partial_textures COMMAND kyty_shim_partial_textures_tests) + set_tests_properties(kyty_shim_partial_textures PROPERTIES TIMEOUT 25 SKIP_RETURN_CODE 77 + ENVIRONMENT "KYTY_GPU_PIPELINE=0;KYTY_PARTIAL_TEXTURE_MB=1" + PASS_REGULAR_EXPRESSION "kyty_shim_partial_textures: ok" FAIL_REGULAR_EXPRESSION "FAILED") target_sources(libSceAgcDriver PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/BufferCachePages.cpp) add_test_executable(kyty_shim_buffer_cache_pages_tests ${CMAKE_CURRENT_SOURCE_DIR}/BufferCachePagesMain.cpp) configure_host_test_executable(kyty_shim_buffer_cache_pages_tests) diff --git a/core/libs/prx/libSceAgcDriver/KytyShim/tests/ImageWriteBackAlias.cpp b/core/libs/prx/libSceAgcDriver/KytyShim/tests/ImageWriteBackAlias.cpp index 806d9445320..17bb595e7a0 100644 --- a/core/libs/prx/libSceAgcDriver/KytyShim/tests/ImageWriteBackAlias.cpp +++ b/core/libs/prx/libSceAgcDriver/KytyShim/tests/ImageWriteBackAlias.cpp @@ -1,4 +1,5 @@ #include "TestVulkanDevice.h" +#include "TextureCacheTestAccess.h" #include "common/emulatorConfig.h" #include "common/threads.h" #include "graphics/guest_gpu/command_processor/commandProcessor.h" @@ -25,18 +26,6 @@ struct BufferCacheTestAccess { } }; -struct TextureCacheTestAccess { - static ImageId Create(TextureCache& cache, const ImageInfo& info) { - Common::ScopedLock lock {cache.m_lock}; - return cache.InsertImage(info); - } - - static bool QueueDownload(TextureCache& cache, ImageId image) { - Common::ScopedLock lock {cache.m_lock}; - return cache.DownloadImageMemory(image); - } -}; - } namespace { diff --git a/core/libs/prx/libSceAgcDriver/KytyShim/tests/PartialTextures.cpp b/core/libs/prx/libSceAgcDriver/KytyShim/tests/PartialTextures.cpp new file mode 100644 index 00000000000..acc9b1d64cd --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/KytyShim/tests/PartialTextures.cpp @@ -0,0 +1,200 @@ +#include "TestVulkanDevice.h" +#include "TextureCacheTestAccess.h" +#include "common/emulatorConfig.h" +#include "common/threads.h" +#include "graphics/guest_gpu/command_processor/commandProcessor.h" +#include "graphics/host_gpu/renderer/cache/bufferCache.h" +#include "graphics/host_gpu/renderer/cache/textureCache.h" +#include "graphics/host_gpu/graphicContext.h" +#include "kernel/memory.h" +#include "prx/libkernel/DirectMemory/DirectMemory.hpp" +#include "prx/libkernel/include/Api.hpp" + +#include +#include +#include +#include +#include + +namespace { + +using namespace Libs::Graphics; + +constexpr int CpuReadWrite = 0x03; +constexpr uint32_t Size = 2048; +constexpr uint32_t Levels = 12; +constexpr uint64_t Slot = 0x400000; +constexpr uint64_t GuestBytes = 4 * Slot; + +ImageInfo Texture(uint64_t address) { + ImageInfo info; + info.data.address = address; + info.pixel_format = vk::Format::eBc1RgbaUnormBlock; + info.guest_format = Prospero::BufferFormat::kBc1UNorm; + info.extent = vk::Extent3D {Size, Size, 1}; + info.resources.levels = Levels; + info.UpdateSize(); + return info; +} + +void FillGuest(uint64_t address, uint64_t size) { + auto* bytes = reinterpret_cast(address); + for (uint64_t i = 0; i < size; i++) { + bytes[i] = static_cast((i * 2654435761u) >> 13u) | 1u; + } +} + +struct Readback { + const char* failure = nullptr; + std::vector bytes; +}; + +Readback Download(GraphicContext& graphics, CommandScheduler& scheduler, Image& image) { + Readback result; + const auto size = image.info.LinearSize(); + const auto copies = image.info.BufferCopies(0); + Buffer readback(graphics, scheduler, MemoryUsage::Download, 0, + vk::BufferUsageFlagBits::eTransferDst, size); + image.Download(copies, readback.Handle(), 0, size); + const auto tick = scheduler.CurrentTick(); + scheduler.Wait(tick); + scheduler.WaitPriorityOperations(tick); + readback.Invalidate(0, size); + result.bytes.resize(size); + std::memcpy(result.bytes.data(), readback.Mapped().data(), size); + return result; +} + +TextureCache::ImageDesc Sampled(const ImageInfo& info, uint32_t base_level, uint32_t level_count) { + TextureCache::ImageDesc desc {.info = info}; + desc.view_info.format = info.pixel_format; + desc.view_info.base_level = base_level; + desc.view_info.level_count = level_count; + return desc; +} + +const char* CheckOmittedLevelView(GraphicContext& graphics, uint64_t address) { + RenderContext renderer(graphics); + CommandProcessor producer(renderer, 0); + producer.Reset(); + auto& scheduler = renderer.GetCommandScheduler(); + auto& textures = renderer.GetTextureCache(); + scheduler.Begin(producer.GetCtx(), producer.GetUcfg(), producer.GetShCtx()); + + const auto partial_info = Texture(address); + const auto control_info = Texture(address + Slot); + FillGuest(address, partial_info.data.size); + std::memcpy(reinterpret_cast(address + Slot), reinterpret_cast(address), + partial_info.data.size); + + graphics.partial_textures_enabled = true; + const auto partial_id = TextureCacheTestAccess::Create(textures, partial_info); + graphics.partial_textures_enabled = false; + const auto control_id = TextureCacheTestAccess::Create(textures, control_info); + graphics.partial_textures_enabled = true; + auto& partial = textures.GetImage(partial_id); + auto& control = textures.GetImage(control_id); + if (!partial.IsPartiallyResident()) return "the texture was not created partially resident"; + if (control.IsPartiallyResident()) return "the control texture was created partially resident"; + + if (textures.FindTexture(partial_id, Sampled(partial_info, 0, Levels)) == nullptr) { + return "no view of every level"; + } + if (!partial.IsPartiallyResident()) return "a view of every level backed the omitted levels"; + if (textures.FindTexture(partial_id, Sampled(partial_info, 0, 1)) == nullptr) { + return "no view of the omitted top level"; + } + if (partial.IsPartiallyResident()) return "a view of the omitted top level left it unbacked"; + (void)textures.FindTexture(control_id, Sampled(control_info, 0, 1)); + + const auto partial_bytes = Download(graphics, scheduler, partial); + const auto control_bytes = Download(graphics, scheduler, control); + if (partial_bytes.bytes.empty() || partial_bytes.bytes != control_bytes.bytes) { + return "the backed top level differs from the fully backed control"; + } + return nullptr; +} + +const char* CheckCopyFromOmittedLevels(GraphicContext& graphics, uint64_t address) { + RenderContext renderer(graphics); + CommandProcessor producer(renderer, 0); + producer.Reset(); + auto& scheduler = renderer.GetCommandScheduler(); + auto& textures = renderer.GetTextureCache(); + scheduler.Begin(producer.GetCtx(), producer.GetUcfg(), producer.GetShCtx()); + + const auto source_info = Texture(address); + const auto control_info = Texture(address + Slot); + FillGuest(address, source_info.data.size); + std::memcpy(reinterpret_cast(address + Slot), reinterpret_cast(address), + source_info.data.size); + + graphics.partial_textures_enabled = true; + const auto source_id = TextureCacheTestAccess::Create(textures, source_info); + graphics.partial_textures_enabled = false; + const auto control_id = TextureCacheTestAccess::Create(textures, control_info); + const auto copy_id = TextureCacheTestAccess::Create(textures, Texture(address + 2 * Slot)); + const auto control_copy_id = TextureCacheTestAccess::Create(textures, Texture(address + 3 * Slot)); + graphics.partial_textures_enabled = true; + if (!textures.GetImage(source_id).IsPartiallyResident()) { + return "the copy source was not created partially resident"; + } + (void)textures.FindTexture(source_id, Sampled(source_info, 0, Levels)); + (void)textures.FindTexture(control_id, Sampled(control_info, 0, Levels)); + + TextureCacheTestAccess::Copy(textures, copy_id, source_id); + TextureCacheTestAccess::Copy(textures, control_copy_id, control_id); + if (textures.GetImage(source_id).IsPartiallyResident()) { + return "a copy read the omitted levels of its source"; + } + const auto copied = Download(graphics, scheduler, textures.GetImage(copy_id)); + const auto control = Download(graphics, scheduler, textures.GetImage(control_copy_id)); + if (copied.bytes.empty() || copied.bytes != control.bytes) { + return "the copy of a partially resident texture differs from the fully backed control"; + } + return nullptr; +} + +} + +extern "C" int RunKytyPartialTexturesTest() { + Common::InitializeThreads(); + Config::Initialize(); + Config::Load(Config::ConfigOptions {}); + KytyShimTests::TestVulkanDevice gpu; + auto& graphics = gpu.graphics; + if (const auto* unavailable = gpu.Initialize(false, true)) { + const bool required = std::getenv("ANYPS5_REQUIRE_VULKAN") != nullptr; + std::fprintf(stderr, "kyty_shim_partial_textures: skipped, no Vulkan device with sparse residency (%s)%s\n", + unavailable, required ? "; ANYPS5_REQUIRE_VULKAN does not cover optional sparse support" : ""); + return 77; + } + if (!graphics.CreateAllocator()) { + std::fputs("kyty_shim_partial_textures: FAILED: could not create the allocator\n", stderr); + return 1; + } + void* guest = nullptr; + if (sceKernelMapFlexibleMemory(&guest, GuestBytes, CpuReadWrite, 0) != 0 || guest == nullptr) { + std::fputs("kyty_shim_partial_textures: FAILED: could not map guest backing\n", stderr); + return 1; + } + const auto address = reinterpret_cast(guest); + if (Texture(address).data.size > Slot) { + std::fputs("kyty_shim_partial_textures: FAILED: the texture does not fit its slot\n", stderr); + return 1; + } + auto failure = CheckOmittedLevelView(graphics, address); + if (failure == nullptr) { + failure = CheckCopyFromOmittedLevels(graphics, address); + } + if (sceKernelMunmap(address, GuestBytes) != 0) { + std::fputs("kyty_shim_partial_textures: FAILED: could not unmap guest backing\n", stderr); + return 1; + } + if (failure != nullptr) { + std::fprintf(stderr, "kyty_shim_partial_textures: FAILED: %s\n", failure); + return 1; + } + std::puts("kyty_shim_partial_textures: ok"); + return 0; +} diff --git a/core/libs/prx/libSceAgcDriver/KytyShim/tests/PartialTexturesMain.cpp b/core/libs/prx/libSceAgcDriver/KytyShim/tests/PartialTexturesMain.cpp new file mode 100644 index 00000000000..134c7daac66 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/KytyShim/tests/PartialTexturesMain.cpp @@ -0,0 +1,5 @@ +extern "C" int RunKytyPartialTexturesTest(); + +int main() { + return RunKytyPartialTexturesTest(); +} diff --git a/core/libs/prx/libSceAgcDriver/KytyShim/tests/TestVulkanDevice.h b/core/libs/prx/libSceAgcDriver/KytyShim/tests/TestVulkanDevice.h index d7882e154e7..b73c4049777 100644 --- a/core/libs/prx/libSceAgcDriver/KytyShim/tests/TestVulkanDevice.h +++ b/core/libs/prx/libSceAgcDriver/KytyShim/tests/TestVulkanDevice.h @@ -8,6 +8,7 @@ #include #include #include +#include namespace KytyShimTests { @@ -15,7 +16,7 @@ struct TestVulkanDevice { vk::detail::DynamicLoader loader; Libs::Graphics::GraphicContext graphics; - const char* Initialize(bool require_tiling = false) { + const char* Initialize(bool require_tiling = false, bool partial_textures = false) { if (!loader.success()) { return "Vulkan loader unavailable"; } @@ -36,7 +37,7 @@ struct TestVulkanDevice { return "Vulkan device enumeration failed"; } for (const auto device : devices.value) { - if (InitializeDevice(device, require_tiling)) { + if (InitializeDevice(device, require_tiling, partial_textures)) { return nullptr; } } @@ -56,7 +57,7 @@ struct TestVulkanDevice { } private: - bool InitializeDevice(vk::PhysicalDevice physical, bool require_tiling) { + bool InitializeDevice(vk::PhysicalDevice physical, bool require_tiling, bool partial_textures) { vk::PhysicalDeviceVulkan12Properties limits {}; vk::PhysicalDeviceVulkan11Properties properties11 {.pNext = &limits}; vk::PhysicalDeviceProperties2 properties {.pNext = &properties11}; @@ -76,8 +77,12 @@ struct TestVulkanDevice { return false; } const auto extensions = physical.enumerateDeviceExtensionProperties(nullptr); - const std::array required_extensions { + std::vector required_extensions { VK_KHR_PUSH_DESCRIPTOR_EXTENSION_NAME, VK_EXT_ROBUSTNESS_2_EXTENSION_NAME}; + if (partial_textures) { + required_extensions.push_back(VK_EXT_MEMORY_BUDGET_EXTENSION_NAME); + required_extensions.push_back(VK_EXT_IMAGE_VIEW_MIN_LOD_EXTENSION_NAME); + } if (extensions.result != vk::Result::eSuccess || !std::ranges::all_of(required_extensions, [&extensions](const char* extension) { return std::ranges::any_of(extensions.value, [extension](const auto& properties) { @@ -86,7 +91,8 @@ struct TestVulkanDevice { })) { return false; } - vk::PhysicalDeviceRobustness2FeaturesEXT supported_robustness {}; + vk::PhysicalDeviceImageViewMinLodFeaturesEXT supported_min_lod {}; + vk::PhysicalDeviceRobustness2FeaturesEXT supported_robustness {.pNext = partial_textures ? &supported_min_lod : nullptr}; vk::PhysicalDeviceVulkan12Features supported12 {.pNext = &supported_robustness}; vk::PhysicalDeviceVulkan11Features supported11 {.pNext = &supported12}; vk::PhysicalDeviceVulkan13Features supported13 {.pNext = &supported11}; @@ -103,7 +109,16 @@ struct TestVulkanDevice { !supported13.synchronization2 || !supported13.dynamicRendering) { return false; } - vk::PhysicalDeviceRobustness2FeaturesEXT robustness {.nullDescriptor = VK_TRUE}; + if (partial_textures && + (!supported.features.sparseBinding || !supported.features.sparseResidencyImage2D || + !supported_min_lod.minLod || + !properties.properties.sparseProperties.residencyNonResidentStrict || + !(family->queueFlags & vk::QueueFlagBits::eSparseBinding))) { + return false; + } + vk::PhysicalDeviceImageViewMinLodFeaturesEXT min_lod {.minLod = VK_TRUE}; + vk::PhysicalDeviceRobustness2FeaturesEXT robustness {.pNext = partial_textures ? &min_lod : nullptr, + .nullDescriptor = VK_TRUE}; vk::PhysicalDeviceVulkan12Features features12 { .pNext = &robustness, .storageBuffer8BitAccess = require_tiling, @@ -120,7 +135,9 @@ struct TestVulkanDevice { const vk::PhysicalDeviceFeatures core_features { .sampleRateShading = VK_TRUE, .shaderStorageImageMultisample = supported.features.shaderStorageImageMultisample, - .shaderInt64 = VK_TRUE}; + .shaderInt64 = VK_TRUE, + .sparseBinding = partial_textures, + .sparseResidencyImage2D = partial_textures}; const float priority = 1.0f; const vk::DeviceQueueCreateInfo queue_info { .queueFamilyIndex = static_cast(family - families.begin()), @@ -145,6 +162,8 @@ struct TestVulkanDevice { graphics.queue_family = queue_info.queueFamilyIndex; graphics.device.getQueue(graphics.queue_family, 0, &graphics.queue); graphics.occlusion_queries_enabled = true; + graphics.memory_budget_ext_enabled = partial_textures; + graphics.partial_textures_enabled = partial_textures; return true; } }; diff --git a/core/libs/prx/libSceAgcDriver/KytyShim/tests/TextureCacheTestAccess.h b/core/libs/prx/libSceAgcDriver/KytyShim/tests/TextureCacheTestAccess.h new file mode 100644 index 00000000000..c61e473cb9d --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/KytyShim/tests/TextureCacheTestAccess.h @@ -0,0 +1,27 @@ +#ifndef KYTY_SHIM_TESTS_TEXTURE_CACHE_TEST_ACCESS_H_ +#define KYTY_SHIM_TESTS_TEXTURE_CACHE_TEST_ACCESS_H_ + +#include "graphics/host_gpu/renderer/cache/textureCache.h" + +namespace Libs::Graphics { + +struct TextureCacheTestAccess { + static ImageId Create(TextureCache& cache, const ImageInfo& info) { + Common::ScopedLock lock {cache.m_lock}; + return cache.InsertImage(info); + } + + static bool QueueDownload(TextureCache& cache, ImageId image) { + Common::ScopedLock lock {cache.m_lock}; + return cache.DownloadImageMemory(image); + } + + static void Copy(TextureCache& cache, ImageId destination, ImageId source) { + Common::ScopedLock lock {cache.m_lock}; + cache.CopyImage(destination, source); + } +}; + +} + +#endif diff --git a/docs/dev/THIRD_PARTY_KYTY.md b/docs/dev/THIRD_PARTY_KYTY.md index 22b19f7a013..380623615bc 100644 --- a/docs/dev/THIRD_PARTY_KYTY.md +++ b/docs/dev/THIRD_PARTY_KYTY.md @@ -264,6 +264,7 @@ This build does not read KytyPS5's `KYTY_PIPELINE_PRECOMPILE`: stopping the game | Variable | Values | Default | Effect | Category | Platform | Origin | |---|---|---|---|---|---|---| | `KYTY_NATIVE_RT` | `0` or `1`, else stops | unset | Unset: native ray tracing when the device has `VK_KHR_acceleration_structure`, `VK_KHR_ray_query` and `VK_KHR_deferred_host_operations` with their features, emulated otherwise. `1`: native, and a stop when the device cannot. `0`: emulated. KytyPS5's own default is off | perf | all | Kyty option; on by default `8a29429250` | +| `KYTY_PARTIAL_TEXTURE_MB` | MiB, `0` turns it off | the device-local budget from `VK_EXT_memory_budget` minus the reserve the texture and buffer caches keep below it (an eighth of it, at most 1 GiB) | Once the device memory in use passes this, block-compressed 2D textures of 512 px or more with at least 3 mips are created sparse-resident without their top mip (without two past halfway from there to the budget). A texture whose sparse mip tail already starts at a dropped mip is created fully backed. Uploads skip the omitted mips and sampled views that also hold a resident mip clamp `minLod` to it. Every other use binds memory for the omitted mips and uploads them from guest memory first: a sampled view of omitted mips only, a storage or attachment view, a copy, clear, resolve or download to guest memory. An image whose mips are not needed again keeps them unbound for its whole life, even after the pressure is gone. Memory binds are batched and the next queue submit waits on them on the GPU. Needs `sparseBinding`, `sparseResidencyImage2D`, `residencyNonResidentStrict` and a sparse-binding main queue | perf | all | AnyKyty | | `KYTY_RT_STATS` | `0` or `1`, else stops | `0` | With native ray tracing, shaders count their queries and an `[RT]` summary of the last 10 seconds is logged | debug | all | Kyty option | | `KYTY_RT_ORACLE` | `0` to `15`, else stops | `1` | With native ray tracing, bit 1: the BVH intersections of compute walks no form recognizes answer from a host ray query while the guest walk code runs as written; bit 2: the walks a form recognizes are served the same way instead of their rewrite; bit 4: no form is tried; bit 8, with bit 1: the walks of pixel shaders are served too, their draws then build the host TLAS before their rendering pass. Bit 8 is off by default: `KYTY_RT_CHECK` replays dispatches, not draws | perf | all | AnyKyty | | `KYTY_RT_CHECK` | dispatch period, `0` turns it off | `0` | With native ray tracing, one dispatch in N of every program served natively (`ShaderModule::guest_traversal` false, `bvh` and `ray_query`) is played twice: native variant, outputs saved and previous contents restored, then emulated variant, whose outputs stay; a compute pass counts the output dwords that differ and one `[RT] check` line per check is logged; one in 16 N once a program passed 4 checks. Programs that write through device addresses, GDS, self-sized buffers, indirect write tables or image tables are not replayed (one line says why). The emulated variant is translated by the background compile workers: a check waits until it is ready. Decisions go to `_PipelineCache/.rt` and are reused while the check is on and the recompiler stamp, host stamp, effective oracle bits and PPM tolerance all match. A fallback holds for its session only | debug | compute | AnyKyty |