#include "../src/shader_directory.h" // A Vulkan-backed ID3D12Device (PC ABI) for the Xbox-ABI device proxy (d3d12_xs_device.cpp) to forward to. // Implemented: queues, allocators, command lists, fences, descriptor heaps, render-target and depth-stencil views, // committed buffers and textures (1D, 1D arrays, 2D, multisampled 2D, 3D) and their 1/2/3 variants, allocation // info, CPU texture copies (WriteToSubresource/ReadFromSubresource), query heaps, a few feature queries. Everything else is a // generated stub that reports itself once. See docs/d3d12_vulkan.md section 4.1/4.2 for what each answer means and // what is still open. #ifndef VK_USE_PLATFORM_WIN32_KHR #define VK_USE_PLATFORM_WIN32_KHR #endif #include "../src/vulkan_graphics_shader_modules.h" #include "d3d12_com.h" #include "d3d12_compile_exit.h" #include "d3d12_pipeline_compile.h" #include "d3d12_pipeline_checkpoint.h" #include "d3d12_feature_compat.h" #include "d3d12_stubs.h" // generated #include "d3d12_com_object.h" #include "d3d12_trace.h" #include "d3d12_xs_device.h" #include "d3d12_xs_pso_stream.h" #include "xg_xs_layout.h" #include "d3d12_title_image_upload.h" #include "d3d12_title_buffer_windows.h" #include "d3d12_geometry_views.h" #include "placed_image_map_note.h" #include "d3d12_title_image_census.h" #include "d3d12_xs_native_pso.h" #include "dxgi_com.h" #include "../src/arena_size.h" #include "../src/value_write_sink.h" #include "../src/arena_blocks.h" #include "../src/gfx10_descriptors.h" #include "../src/depth24_fragment.h" #include "../src/rgba4_fragment.h" #include "../src/dual_source_fragment.h" #include "../src/rect_list_geometry.h" #include "../src/uav_clear.h" #include "../src/vulkan_bindless.h" #include "../src/vulkan_memory.h" #include "../src/vulkan_mesh_limits.h" #include "../src/resource_tiling.h" #include "../src/cached_pso.h" #include "../src/pipeline_cache_file.h" #include "../src/pipeline_profile.h" #include "../src/submit_phases.h" #include "../src/pipeline_cache_store.h" #include "../src/large_module_gate.h" #include "../src/conservative_raster.h" #include "../src/resource_detile.h" #include "../src/console_texture_layout.h" #include "../src/shader_library.h" #include "../src/dstorage_trace.h" #include "../src/title_page_watch.h" #include "../src/guarded_copy.h" #include "../src/title_geometry_watch.h" #include "../src/title_texture_memory.h" #include "../src/title_texture_refresh.h" #include "title_gpu_placements.h" #include "../src/spirv_f16_halves.h" #include "../src/spirv_stores.h" #include "../src/title_va_alias.h" #include "../src/console_heap_vsharp_slots.h" #include "../src/title_window_plan.h" #include "../src/vulkan_present.h" #include "../src/vulkan_device_filter.h" #include "../src/vulkan13_features.h" #include "../src/vulkan_index_view.h" #include "d3d12_compute_input_probe.h" #include "../src/fsdraw_probe.h" // LOCAL DIAGNOSTIC #include "../src/local_diagnostics.h" #include "../src/mem_probe.h" // LOCAL DIAGNOSTIC #include "../src/vulkan_aftermath.h" #include #ifdef _MSC_VER #pragma comment(lib, "advapi32.lib") #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace rt::d3d12 { namespace { // Every descriptor slot is this many bytes; an RTV or DSV slot holds a leonida::TargetView. The console's own // increments are open question 4 in docs/d3d12_vulkan.md; the application reads them from the device, as it must. constexpr UINT kDescriptorSize = descriptor_size; // The first 64 KiB of the GPU address arena are never handed out: VA 0 stays invalid, and the page is kept zero // for unbound vertex and index buffers to read (D3D12 reads zeros there). constexpr VkDeviceSize kZeroPage = 64 * 1024; // zeroed: what unbound vertex and index buffers read constexpr auto kQuadIndicesPerQuad = std::uint32_t(leonida::quad_triangle_indices.size()); constexpr std::uint32_t kQuadIndexCount = 16 * 1024 * kQuadIndicesPerQuad; constexpr VkDeviceSize kArenaReserved = kZeroPage + VkDeviceSize(kQuadIndexCount) * sizeof(std::uint32_t); static_assert(sizeof(leonida::TargetView) <= kDescriptorSize); // pipeline_cache_store.h reads this layout without vulkan.h (D3D-704); remember the two. static_assert(sizeof(VkPipelineCacheHeaderVersionOne) == leonida::pipeline_cache_store::header_bytes); // Saturates at the last multiple of `to` instead of wrapping, as the PC runtime's totals do. UINT64 align_up(UINT64 value, UINT64 to) { return value > UINT64_MAX - (to - 1) ? UINT64_MAX / to * to : (value + to - 1) / to * to; } // The shader model and root signature version this layer can honour. Nothing in the runtime compiles DXIL: the // game's shaders arrive as SPIR-V from the offline translator, and the only DXIL path (the BVH builder) is lowered // to standard DXIL, whose baseline is 6.0. Answering the driver's own maximum would tell the game it can hand this // layer shaders it has no front end for, which section 4.1 of docs/d3d12_vulkan.md calls worse than a false // "unsupported" at boot. Raise these when a front end for the higher version lands. constexpr D3D_SHADER_MODEL kHighestShaderModel = D3D_SHADER_MODEL_6_0; constexpr D3D_ROOT_SIGNATURE_VERSION kHighestRootSignatureVersion = D3D_ROOT_SIGNATURE_VERSION_1_1; std::atomic g_global_realtime_privilege_override{-1}; bool first_diagnostic(const char* what, int value) { static std::mutex mutex; static std::set> seen; std::lock_guard lock(mutex); return seen.insert({what, value}).second; } enum class TitleImageOrigin { ordinary, placed, streamed, pending_stream }; void log_once(const char* what, int value) { if (first_diagnostic(what, value)) std::fprintf(stderr, "[rt] d3d12: %s %d\n", what, value); } // Matches the offset interpretation of the selected shader pack. bool signed_vsharp_offsets() { static const bool on = [] { wchar_t value[2]{}; return GetEnvironmentVariableW(L"LEONIDA_IMPORT_BELOW_ARENA", value, 2) == 1 && value[0] == L'1'; }(); return on; } // The CBV/SRV/UAV slots a descriptor table declares: the end of its furthest range (D3D12 appends a range at // D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND), an unbounded range limited by the registered heap. 0 for a sampler table or no table. std::uint32_t table_view_descriptors(const rt::rootsig::RootParameter& param) { if (param.type != rt::rootsig::ParamType::Table) return 0; constexpr std::uint32_t kUnbounded = UINT_MAX; std::uint64_t next = 0, end = 0; for (const auto& range : param.ranges) { const std::uint64_t start = range.offset_in_table == D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND ? next : range.offset_in_table; next = start + range.num_descriptors; if (range.range_type != D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER) end = std::max(end, next); } return std::uint32_t(std::min(end, kUnbounded)); } // The streaming copy of copy_guarded, in a frame of its own so that a fault in it reaches copy_guarded's __except // (src/guarded_copy.h: not in the CRT, which Wine's unwinding does not get out of, and not inline, which clang-cl does // not cover without /EHa). MOVNTDQA, for write-combined pages: ordinary loads from them are not cached, and memcpy // read 64 MiB of them in 253 ms on a Core i9-13900K (253 MiB/s), MOVNTDQA in 13 to 17 ms (4 to 5 GiB/s). #if defined(__clang__) && defined(_M_X64) __attribute__((target("sse4.1"))) #endif __declspec(noinline) LEONIDA_GUARDED_NO_BUILTIN void copy_streaming(std::uint8_t* to, const std::uint8_t* from, std::size_t bytes) { const std::size_t head = std::min(bytes, (0 - reinterpret_cast(from)) & 63); __movsb(to, from, head); to += head, from += head, bytes -= head; for (; bytes >= 64; to += 64, from += 64, bytes -= 64) { const auto* in = reinterpret_cast(from); const __m128i a = _mm_stream_load_si128(in), b = _mm_stream_load_si128(in + 1); const __m128i c = _mm_stream_load_si128(in + 2), d = _mm_stream_load_si128(in + 3); auto* out = reinterpret_cast<__m128i*>(to); _mm_storeu_si128(out, a), _mm_storeu_si128(out + 1, b); _mm_storeu_si128(out + 2, c), _mm_storeu_si128(out + 3, d); } __movsb(to, from, bytes); } // A copy that a page fault ends instead of killing the process: the title may decommit or remap a page between the // VirtualQuery that saw it committed and the read. No C++ objects here: it is a __try frame. `streaming`: for // write-combined pages (copy_streaming). Paid at every submission. bool copy_guarded(std::uint8_t* to, const std::uint8_t* from, std::size_t bytes, bool streaming) { __try { if (streaming) copy_streaming(to, from, bytes); else leonida::guarded::copy(to, from, bytes); return true; } __except (EXCEPTION_EXECUTE_HANDLER) { return false; } } // A 64-bit digest of the bytes of a texture the title keeps in its own memory, to tell whether they changed since its // image was filled (TitleTextures). Up to 256 KiB every byte; above, 64 bytes at the start and 64 at the middle of // every 4 KiB page plus the last 64 bytes, about 3% of them: the title's writes into texture memory are whole tiles // (streaming, file reads, XG copies) or whole planes (video), never a few bytes inside a page. The same sampling as // OpenScarlett's texture hash before submission (src/gpu/d3d12_xs/device_x.cpp, f8e24d4, MIT), with more samples. // False when a page faults (the title unmapped it). No C++ objects here: it is a __try frame. inline std::uint64_t mix_words(std::uint64_t h, const std::uint8_t* at, std::size_t n) { for (std::size_t i = 0; i + 8 <= n; i += 8) { std::uint64_t w; std::memcpy(&w, at + i, 8); h = (h ^ w) * 0x100000001b3ull; h ^= h >> 29; } return h; } // The reads of hash_guarded, in a frame of its own: an inline load inside the __try is not covered by clang-cl // without /EHa (src/guarded_copy.h). __declspec(noinline) std::uint64_t hash_bytes(const std::uint8_t* p, std::size_t bytes, bool every_byte) { std::uint64_t h = 0x9e3779b97f4a7c15ull ^ bytes; if (bytes <= (256u << 10) || every_byte) { h = mix_words(h, p, bytes & ~std::size_t(7)); for (std::size_t i = bytes & ~std::size_t(7); i < bytes; ++i) h = (h ^ p[i]) * 0x100000001b3ull; } else { for (std::size_t page = 0; page + 4096 <= bytes; page += 4096) { h = mix_words(h, p + page, 64); h = mix_words(h, p + page + 2048, 64); } h = mix_words(h, p + bytes - 64, 64); } return h; } bool hash_guarded(const std::uint8_t* p, std::size_t bytes, std::uint64_t& out, bool every_byte = false) { __try { out = hash_bytes(p, bytes, every_byte); return true; } __except (EXCEPTION_EXECUTE_HANDLER) { return false; } } inline std::uint64_t hashed_bytes(std::uint64_t bytes, bool every_byte = false) { return bytes <= (256u << 10) || every_byte ? bytes : bytes / 32 + 64; } // Set while this thread is inside the title-texture registry (it holds title_texture_mutex): a staged copy it makes // submits through a queue, whose before-submission refresh must then not take the registry again. thread_local bool t_in_title_textures = false; struct InTitleTextures { bool was = std::exchange(t_in_title_textures, true); ~InTitleTextures() { t_in_title_textures = was; } }; // Copies a run of the title's pages that VirtualQuery saw committed and readable. A page decommitted since then reads // as zeros, and only that page: the run is redone page by page, so the rest of it keeps its bytes. void copy_run(std::uint8_t* to, const std::uint8_t* from, std::size_t bytes, bool streaming) { if (copy_guarded(to, from, bytes, streaming)) return; for (std::size_t off = 0; off < bytes;) { const std::size_t in_page = reinterpret_cast(from + off) & 4095; const std::size_t n = std::min(bytes - off, 4096 - in_page); if (!copy_guarded(to + off, from + off, n, streaming)) std::memset(to + off, 0, n); off += n; } } // The title's pages behind slot-133 shadow buffers and title windows, and which of them the title wrote since the // copies were last brought up to date. Nothing says which pages a title writes, so the pages say it themselves: once // copied, a read-write page is made read-only (its cache attribute kept: PAGE_READONLY | PAGE_WRITECOMBINE for a // write-combined one), and the title's next write to it faults. The fault handler (shadow_write_fault) makes the // 64 KiB around it writable again and the write goes on; reopening the page clears its watched state. Each refresh() // walks the range with VirtualQuery, passing over pages still known clean when the title memory map hasn't changed: // - read-write pages were written (or newly committed, or newly mapped by xmem): made read-only, then copied. A // write landing between the two faults again, so it reaches the next refresh at the latest; // - pages this tracker made read-only weren't written: skipped; // - other readable pages (read-only or copy-on-write pages of the title's own, pages another tracker protected) // can't be watched: copied every time, as before; // - pages not committed, or not readable, are zero in the copies (written once); // - pages xmem reports mapped at another address too (title_page_watch.h) are copied every time: a write // through the other address doesn't fault here; // - pages a file shim pinned for a kernel write (ReadFile into title memory, which fails with ERROR_NOACCESS on a // read-only page instead of faulting) are left writable and copied every time until the pin ends. // If the protection can't be changed (VirtualProtect refuses, or the fault handler couldn't be installed), those // pages stay read-write and are copied at every submission: the whole-range copy this replaces. // // One tracker serves every copy of the pages it covers (its targets). A page has one owner that may make it // read-only, so copies of the same 4 KiB page must share a tracker: the title places many slot-133 buffers of a few // KiB back to back, off page boundaries (measured on Windows 11: 3,172 of 3,267 placements shared a page with // another), and with a tracker each every buffer but one found its shared pages read-only, not its own, and queried // and copied them again at every submission (3,045 VirtualQuery calls, 57 of 62 ms per refresh). DeviceState:: // add_shadow keeps one tracker per run of pages that overlap or touch, and a written page reaches every target over // it. A page no target covers any more (its buffer went) is left writable and passed over. // // Pages xmem reserved with MEM_WRITE_WATCH (leonida::title_write_watch: the title's ordinary memory, not its // physical-page views) start guarded like the rest. A write fault on one makes its 64 KiB block hot: never made // read-only again, it is asked about instead. Each refresh first asks the kernel which hot pages were written since // the last asking (GetWriteWatch, which clears its bits), through the journal that keeps the answer for every other // tracker over the same pages; then those, and pages not known yet, are copied, and the rest passed over. A write // after the asking is in the next one. No fault, no VirtualProtect, and a kernel write needs no opening: hot pages // stay writable. A block not found written for kCool refreshes is guarded again. Asking costs about 3 ns per page per // refresh and a fault about three orders more, so the pages written often are asked about and the rest wait for their // write (measured natively: asking about all 242 MiB of write-watched pages at every submission cost 2.4 ms per // refresh, against 0.14 ms for the guards with their faults). A file shim's pin still marks a hot page written // (reopen_range) and keeps it copied until the pin ends: a device's write into locked pages need not set the kernel's // bit. // // The fault handler waits for g_shadow_pages_lock and a tracker's lock_, and the faulting thread may hold the process // heap's lock (the title's XMemAlloc memory is _aligned_malloc's, whose headers HeapAlloc and HeapFree write on pages a // tracker may guard). So nothing that holds either lock, or a lock taken under them (title_page_aliases, // kernel_writes' pins, title_write_watch's record and journal), touches the process heap: their containers allocate // from leonida::host_heap, a heap of the runtime's own, and logging waits until the lock is released. class ShadowPages { template using Vector = leonida::host_heap::vector; public: static constexpr std::uintptr_t kPage = 0x1000; static constexpr std::uintptr_t kBlock = 0x10000; // what one write fault makes writable again ShadowPages(const std::uint8_t* pages, std::uint8_t* shadow, std::size_t size, bool watch) : watch_(watch) { begin_ = reinterpret_cast(pages); end_ = begin_ + size; first_ = begin_ & ~(kPage - 1); last_ = (end_ + kPage - 1) & ~(kPage - 1); state_.assign((last_ - first_) / kPage, 0); idle_.assign(state_.size(), 0); cover_.assign(state_.size(), 1); targets_.push_back({begin_, end_, shadow}); index_targets(); } ~ShadowPages() { if (reader_) leonida::title_write_watch::close_reader(reader_); } // Every page made read-only here is read-write again: the title's pages outlive the buffer. void reopen_all() { AcquireSRWLockExclusive(&lock_); if (std::any_of(state_.begin(), state_.end(), [](std::uint8_t s) { return s & kProtected; })) reopen_locked(first_, last_); ReleaseSRWLockExclusive(&lock_); } ShadowPages(const ShadowPages&) = delete; ShadowPages& operator=(const ShadowPages&) = delete; // The bytes of all targets, and how many there are. std::size_t size() const { return target_bytes_; } std::size_t targets() const { return targets_.size(); } // The pages covered: [first(), last()), 4 KiB aligned. std::uintptr_t first() const { return first_; } std::uintptr_t last() const { return last_; } bool contains(std::uintptr_t address) const { return address >= first_ && address < last_; } std::uint64_t faults() const { return faults_.load(std::memory_order_relaxed); } std::uint64_t refresh_queries() const { return refresh_queries_; } std::uint64_t refresh_protects() const { return refresh_protects_; } bool refresh_walked_all() const { return refresh_walked_all_; } // GetWriteWatch calls of the last refresh(), the write-watched pages it found written, and the bytes of the // covered pages that are write-watched, and of those asked about (hot). std::uint64_t refresh_asks() const { return refresh_asks_; } std::uint64_t refresh_written() const { return refresh_written_; } std::size_t watched_bytes() const { return watched_pages_ * kPage; } std::size_t hot_bytes() const { return hot_pages_ * kPage; } // The ranges the last refresh() copied from the pages, as (offset from the first target's start, bytes). Pages it // zeroed are not among them. Only between refreshes, under the lock that serializes them. For a tracker with one // target (a console descriptor heap's), whose offsets are the buffer's. template void for_each_copied(F&& f) const { for (const Job& job : jobs_) f(job.offset, job.bytes); } // The ranges the last refresh() zeroed in the copies (pages no longer committed or readable), likewise. template void for_each_zeroed(F&& f) const { for (const Job& job : zeroed_) f(job.offset, job.bytes); } // Brings every target up to date with the pages. Returns the bytes copied into them. With copy_aliased false, pages // xmem maps at another address too are left as they are this time (DeviceState::refresh_shadows throttles them). std::size_t refresh(bool copy_aliased = true) { copy_aliased_ = copy_aliased; jobs_.clear(); zeroed_.clear(); copy_bytes_ = {}; std::uint64_t queries = 0; const std::uint64_t generation = leonida::title_page_aliases::generation(); // LEONIDA_SHADOW_FULL_WALK=1 queries every page at every refresh, as before the generation skip. static const bool always_full_walk = [] { char value[8] = {}; std::size_t length = 0; return getenv_s(&length, value, sizeof(value), "LEONIDA_SHADOW_FULL_WALK") == 0 && length > 1 && value[0] != '0'; }(); AcquireSRWLockExclusive(&lock_); // Pages whose mapping, commitment or protection changed since the last walk are queried again (kRequery); the // rest keep what is known of them. A tracker that never walked, or whose changes the journal no longer holds, // walks everything. std::uint64_t map_generation = leonida::title_memory_map::generation(); bool full_walk = always_full_walk || map_generation_ == ~std::uint64_t(0); if (!full_walk && map_generation != map_generation_ && !leonida::title_memory_map::changes_since( map_generation_, map_generation, first_, last_, [&](std::uintptr_t from, std::uintptr_t to) { for (std::size_t i = (from - first_) / kPage, i1 = (to - first_ + kPage - 1) / kPage; i < i1 && i < state_.size(); ++i) state_[i] |= kRequery; })) full_walk = true; refresh_walked_all_ = full_walk; refresh_protects_ = 0; if (generation != alias_generation_) { alias_generation_ = generation; for (std::uint8_t& s : state_) s &= ~kAliased; leonida::title_page_aliases::for_each_in(first_, last_, [&](std::uintptr_t va) { const std::uintptr_t from = std::max(va, first_), to = std::min(va + kBlock, last_); for (std::uintptr_t p = from; p < to; p += kPage) state_[(p - first_) / kPage] |= kAliased; }); } if (pinned_) { for (std::uint8_t& s : state_) s &= ~kPinned; pinned_ = false; } leonida::kernel_writes::for_each_pin(first_, last_, [&](std::uintptr_t from, std::uintptr_t to) { for (std::uintptr_t p = from & ~(kPage - 1); p < to; p += kPage) state_[(p - first_) / kPage] |= kPinned; pinned_ = true; }); // The write-watched pages written since the last asking are no longer clean: asked before the walk, so a write // after this is in the next asking. const std::uint64_t watch_generation = leonida::title_write_watch::generation(); if (watch_generation != watch_generation_) { watch_generation_ = watch_generation; update_watched(); } if (runs_stale_) rebuild_watch_runs(); refresh_asks_ = refresh_written_ = 0; if (!watch_runs_.empty()) { if (!reader_) { reader_ = leonida::title_write_watch::open_reader(); forget_clean(); } refresh_asks_ = watch_runs_.size(); leonida::title_write_watch::ask( reader_, watch_runs_, [&](std::uintptr_t from, std::uintptr_t to) { for (std::uintptr_t p = from; p < to; p += kPage) { std::uint8_t& s = state_[(p - first_) / kPage]; if (!(s & kHot)) continue; // asked over a gap between hot pages: guarded refresh_written_ += (s & kClean) != 0; s &= ~kClean; warm(p); } }, [&](std::uintptr_t from, std::uintptr_t to) { // Not write-watched after all (released and reserved again): guarded from now on. for (std::uintptr_t p = from; p < to; p += kPage) state_[(p - first_) / kPage] &= ~(kWatched | kClean | kHot); runs_stale_ = true; }); cool(); // a block it guards again leaves the runs at the next refresh } for (std::uintptr_t at = first_; at < last_;) { const std::size_t i0 = (at - first_) / kPage; if (!cover_[i0]) { // no copy reads it: left as the title set it std::size_t i = i0 + 1; while (i < state_.size() && !cover_[i]) ++i; at = first_ + i * kPage; continue; } // Between the refreshes that copy aliased pages (copy_aliased_, LEONIDA_SHADOW_ALIAS_MS), pages that are // only aliased, and pages that were not mapped or committed when last looked at (zero in the copies), are // passed over like unchanged ones and queried at the next such refresh: a mapping change over them is in // the journal (kRequery) anyway. speed-16/17/18: 730-820 VirtualQuery calls a refresh, ~19 us each under // Wine (NtQueryVirtualMemory waits for Wine's virtual-memory lock, which the mapping threads hold), a // fifth of the submitting thread's time. const auto skip = [&](std::uint8_t s) { return unchanged(s) || (!copy_aliased_ && (s == kAliased || s == kZero || s == (kZero | kAliased))); }; if (!full_walk && skip(state_[i0])) { std::size_t i = i0 + 1; while (i < state_.size() && skip(state_[i])) ++i; at = first_ + i * kPage; continue; } MEMORY_BASIC_INFORMATION region{}; std::uintptr_t next = at + kPage; Kind kind = Kind::zero; ++queries; if (VirtualQuery(reinterpret_cast(at), ®ion, sizeof(region))) { next = std::min(last_, reinterpret_cast(region.BaseAddress) + region.RegionSize); kind = classify(region); } std::size_t i1 = (next - first_) / kPage; for (std::size_t i = i0 + 1; i < i1; ++i) if (!cover_[i]) { // the region goes on past the pages copies read: the rest is passed over above i1 = i; next = first_ + i * kPage; break; } const bool streaming = (region.Protect & PAGE_WRITECOMBINE) != 0; switch (kind) { case Kind::zero: for (std::size_t i = i0; i < i1; ++i) { if (state_[i] & kZero) continue; const auto [offset, bytes] = span_of(i, i + 1); zero_targets(offset, bytes); if (!zeroed_.empty() && zeroed_.back().offset + zeroed_.back().bytes == offset) zeroed_.back().bytes += bytes; else zeroed_.push_back({offset, bytes, false}); state_[i] = std::uint8_t(kZero | (state_[i] & (kAliased | kPinned | kWatched))); } break; case Kind::writable: case Kind::read_only: for (std::size_t i = i0; i < i1;) { const Watch how = watch_of(state_[i]); std::size_t j = i + 1; while (j < i1 && watch_of(state_[j]) == how) ++j; switch (how) { case Watch::clean: break; // write-watched, not written since it was copied case Watch::written: // write-watched: written since, or not known yet for (std::size_t k = i; k < j; ++k) state_[k] = std::uint8_t((state_[k] & ~(kZero | kProtected)) | kClean); add_job(i, j, streaming, Copy::write_watched); break; case Watch::open: // write-watched, but pinned for a kernel write: copied until the pin ends for (std::size_t k = i; k < j; ++k) state_[k] &= ~(kZero | kProtected | kClean); add_job(i, j, streaming, Copy::write_watched); break; case Watch::guard: if (kind == Kind::writable) guard_writable(i, j, region.Protect, streaming); else guard_read_only(i, j, streaming); break; } i = j; } break; case Kind::unwatched: for (std::size_t i = i0; i < i1; ++i) state_[i] &= kAliased | kPinned | kWatched; add_job(i0, i1, streaming, Copy::copy_on_write); break; } for (std::size_t i = i0; i < i1; ++i) state_[i] &= std::uint8_t(~kRequery); // queried now at = next; } // Remember the generation from before the walk, so a change during the walk triggers another one. map_generation_ = map_generation; const DWORD protect_error = std::exchange(protect_error_, 0); ReleaseSRWLockExclusive(&lock_); if (protect_error) log_once("slot-133 shadow: VirtualProtect refused to watch the title's pages for writes, so they are " "copied at every submission; error", int(protect_error)); // The copies run without the lock: a write that faults meanwhile is let through and copied next time. std::size_t copied = 0; for (const Job& job : jobs_) for_each_target(begin_ + job.offset, begin_ + job.offset + job.bytes, [&](const Target& t, std::uintptr_t from, std::uintptr_t to) { copy_run(t.shadow + (from - t.begin), reinterpret_cast(from), to - from, job.streaming); copied += to - from; }); refresh_queries_ = queries; return copied; } // DeviceState::add_shadow, with every other tracker of its device held still (shadow_mutex) and the fault // handler kept out (g_shadow_pages_lock exclusive). The pages [first, last) (4 KiB aligned) are covered from // now on; the ones new here are unknown, so the next refresh queries them. void extend(std::uintptr_t first, std::uintptr_t last) { AcquireSRWLockExclusive(&lock_); if (first < first_) { const std::size_t n = (first_ - first) / kPage; state_.insert(state_.begin(), n, std::uint8_t(0)); idle_.insert(idle_.begin(), n, std::uint8_t(0)); cover_.insert(cover_.begin(), n, 0u); first_ = first; } if (last > last_) { state_.resize((last - first_) / kPage, 0); idle_.resize(state_.size(), 0); cover_.resize(state_.size(), 0); last_ = last; } alias_generation_ = ~std::uint64_t(0); // the new pages' alias marks watch_generation_ = ~std::uint64_t(0); // and whether they are write-watched ReleaseSRWLockExclusive(&lock_); } // Likewise: takes over `other`'s targets, pages and what is known of them (inside this tracker's range, which // never shares a page with it before). `other` is left with nothing to reopen: the caller unregisters and // deletes it, and the pages it made read-only are this tracker's now. void absorb(ShadowPages& other) { AcquireSRWLockExclusive(&lock_); AcquireSRWLockExclusive(&other.lock_); const std::size_t at = (other.first_ - first_) / kPage; for (std::size_t i = 0; i < other.state_.size(); ++i) { state_[at + i] |= other.state_[i]; cover_[at + i] += other.cover_[i]; idle_[at + i] = other.idle_[i]; } targets_.insert(targets_.end(), other.targets_.begin(), other.targets_.end()); if (other.map_generation_ != map_generation_) map_generation_ = ~std::uint64_t(0); // Its clean write-watched pages are clean as of its last asking: this tracker asks from the older of the two. if (other.reader_) { if (!reader_) { reader_ = leonida::title_write_watch::open_reader(); forget_clean(); } leonida::title_write_watch::merge_reader(reader_, other.reader_); } watch_generation_ = ~std::uint64_t(0); pinned_ |= other.pinned_; watch_ = watch_ && other.watch_; faults_.fetch_add(other.faults(), std::memory_order_relaxed); std::fill(other.state_.begin(), other.state_.end(), std::uint8_t(0)); other.targets_.clear(); ReleaseSRWLockExclusive(&other.lock_); index_targets(); ReleaseSRWLockExclusive(&lock_); } // Likewise: [begin, end), inside the covered pages, is copied to `shadow` from now on. fill() it next. void add_target(std::uintptr_t begin, std::uintptr_t end, std::uint8_t* shadow) { AcquireSRWLockExclusive(&lock_); targets_.push_back({begin, end, shadow}); for (std::uintptr_t p = begin & ~(kPage - 1); p < end; p += kPage) ++cover_[(p - first_) / kPage]; index_targets(); ReleaseSRWLockExclusive(&lock_); } // A new target's first copy, of the pages as they are now; their watched state is not touched. A page this // tracker keeps read-only is as the other targets have it; one written meanwhile is copied again at the next // refresh, like any page that isn't read-only here. Under shadow_mutex, so no refresh runs meanwhile. void fill(std::uintptr_t begin, std::uintptr_t end, std::uint8_t* shadow) { for (std::uintptr_t at = begin & ~(kPage - 1); at < end;) { MEMORY_BASIC_INFORMATION region{}; std::uintptr_t next = at + kPage; Kind kind = Kind::zero; if (VirtualQuery(reinterpret_cast(at), ®ion, sizeof(region))) { next = reinterpret_cast(region.BaseAddress) + region.RegionSize; kind = classify(region); } const std::uintptr_t from = std::max(at, begin), to = std::min(next, end); if (kind == Kind::zero) std::memset(shadow + (from - begin), 0, to - from); else copy_run(shadow + (from - begin), reinterpret_cast(from), to - from, (region.Protect & PAGE_WRITECOMBINE) != 0); at = next; } } // Under shadow_mutex: `shadow` is no longer a target. Pages no other target covers are made writable again and // passed over from now on. False when it isn't one of this tracker's. bool remove_target(const std::uint8_t* shadow) { const auto it = std::find_if(targets_.begin(), targets_.end(), [shadow](const Target& t) { return t.shadow == shadow; }); if (it == targets_.end()) return false; AcquireSRWLockExclusive(&lock_); const std::size_t i_end = (((it->end + kPage - 1) & ~(kPage - 1)) - first_) / kPage; for (std::size_t i = ((it->begin & ~(kPage - 1)) - first_) / kPage; i < i_end;) { if (--cover_[i]) { ++i; continue; } std::size_t j = i + 1; // [i, j): pages nothing covers now for (; j < i_end && cover_[j] == 1; ++j) cover_[j] = 0; reopen_locked(first_ + i * kPage, first_ + j * kPage); for (std::size_t k = i; k < j; ++k) state_[k] &= kAliased | kPinned | kWatched; i = j; } targets_.erase(it); index_targets(); watch_generation_ = ~std::uint64_t(0); // recounts the write-watched pages covered ReleaseSRWLockExclusive(&lock_); return true; } // From a file shim, before the kernel writes [from, to): the pages there this tracker protected are writable again, // and the write-watched ones count as written (a device writing into locked pages need not set the kernel's bit). void reopen_range(std::uintptr_t from, std::uintptr_t to) { from = std::max(from & ~(kPage - 1), first_); to = std::min((to + kPage - 1) & ~(kPage - 1), last_); if (from >= to) return; AcquireSRWLockExclusive(&lock_); bool guarded = false; for (std::size_t i = (from - first_) / kPage, i1 = (to - first_) / kPage; i < i1; ++i) { state_[i] &= ~kClean; guarded |= (state_[i] & kProtected) != 0; } if (guarded) reopen_locked(from, to); ReleaseSRWLockExclusive(&lock_); } // From the fault handler: a write to `address`, inside this range, faulted. True when the write can be retried: // the page is one this tracker made read-only, and the 64 KiB around it that it protected are read-write again; // or the page is writable already, because another thread's fault reopened it after this write faulted. The // second is asked here, under the lock, not by the handler afterwards: refresh() protects pages under the same // lock, so by a later look the page can be read-only again (and this tracker's again), and the handler refused a // write it should have retried, which ended the process (seen natively on Windows 11: threads writing one page // across a submission). bool reopen(std::uintptr_t address) { AcquireSRWLockExclusive(&lock_); const std::size_t index = (address - first_) / kPage; bool retry = (state_[index] & kProtected) != 0; if (retry) { const std::uintptr_t block = address & ~(kBlock - 1); const std::uintptr_t from = std::max(block, first_), to = std::min(block + kBlock, last_); // A write-watched block written again: asked about from now on, not guarded (what reopen_locked left // read-only stays guarded). No allocation in here: the faulting thread may hold the heap's lock. bool watched[kBlock / kPage] = {}; const std::size_t i0 = (from - first_) / kPage, i1 = (to - first_) / kPage; for (std::size_t i = i0; i < i1; ++i) watched[i - i0] = (state_[i] & (kWatched | kHot | kProtected)) == (kWatched | kProtected); reopen_locked(from, to); retry = !(state_[index] & kProtected); faults_.fetch_add(1, std::memory_order_relaxed); for (std::size_t i = i0; i < i1; ++i) { if (!watched[i - i0] || (state_[i] & kProtected)) continue; state_[i] = std::uint8_t((state_[i] | kHot) & ~kClean); idle_[i] = 0; runs_stale_ = true; } } else { MEMORY_BASIC_INFORMATION region{}; retry = VirtualQuery(reinterpret_cast(address), ®ion, sizeof(region)) && classify(region) == Kind::writable; } ReleaseSRWLockExclusive(&lock_); return retry; } private: enum : std::uint8_t { kProtected = 1, // made read-only here: unchanged since it was copied kZero = 2, // zero in the copies (not committed when last looked at) kAliased = 4, // xmem maps its physical page at another address too kPinned = 8, // a kernel write into it may be in flight (leonida::kernel_writes) kWatched = 16, // in a write-watched reservation (leonida::title_write_watch) kClean = 32, // hot, and not written since it was copied after an asking kHot = 64, // write-watched and asked about at every refresh, never guarded kRequery = 128, // its mapping, commitment or protection changed (title_memory_map): queried at the next walk }; // Refreshes a hot block may go without a write before it is guarded again. static constexpr std::uint8_t kCool = 64; // Hot runs this close in one reservation are asked about as one (a call costs about as much as 300 pages). static constexpr std::uintptr_t kMergeGap = 0x40000; enum class Kind { zero, writable, read_only, unwatched }; public: // Why the last refresh() copied the bytes it did (copy_bytes): pages guarded now (written since, or new), pages left // writable (no guard possible), pages xmem maps at another address too, pages pinned for a kernel write, // read-only pages that are not this tracker's, copy-on-write pages, write-watched pages found written. enum class Copy { guarded, unguarded, aliased, pinned, read_only, copy_on_write, write_watched, count }; const std::array& copy_bytes() const { return copy_bytes_; } private: // How a committed, readable page is watched: by the kernel (clean, written or, pinned or aliased, open) or by // a guard. enum class Watch { clean, written, open, guard }; static Watch watch_of(std::uint8_t s) { if ((s & (kWatched | kHot)) != (kWatched | kHot)) return Watch::guard; if (s & (kAliased | kPinned)) return Watch::open; return s & kClean ? Watch::clean : Watch::written; } // A page known unchanged since the last refresh, which one that doesn't walk everything passes over. static bool unchanged(std::uint8_t s) { return s == kProtected || s == (kWatched | kProtected) || s == (kWatched | kHot | kClean); } // A hot page `p` was found written: its block is not idle. void warm(std::uintptr_t p) { const std::uintptr_t block = p & ~(kBlock - 1); const std::size_t i0 = (std::max(block, first_) - first_) / kPage; const std::size_t i1 = (std::min(block + kBlock, last_) - first_) / kPage; for (std::size_t i = i0; i < i1; ++i) idle_[i] = 0; } // After an asking: the hot pages not found written are one refresh idler, and those idle for kCool refreshes are // guarded from now on (not clean: the walk copies them as it makes them read-only). void cool() { for (const auto& [from, to] : watch_runs_) for (std::size_t i = (from - first_) / kPage, i1 = (to - first_) / kPage; i < i1; ++i) { if (!(state_[i] & kHot)) continue; if (idle_[i] < kCool) { ++idle_[i]; continue; } state_[i] &= ~(kHot | kClean); idle_[i] = 0; runs_stale_ = true; } } // Guarded pages [i, j) of a read-write region (protection `current`): written since the last refresh, or newly // committed or mapped. Watched from now on, then copied. void guard_writable(std::size_t i0, std::size_t i1, DWORD current, bool streaming) { for (std::size_t i = i0; i < i1;) { const bool unwatched = state_[i] & (kAliased | kPinned); std::size_t j = i + 1; while (j < i1 && bool(state_[j] & (kAliased | kPinned)) == unwatched) ++j; for (std::size_t k = i; k < j; ++k) state_[k] &= ~(kZero | kProtected); if (!unwatched && watch_) protect(i, j, current); if (unwatched && !copy_aliased_ && (state_[i] & kAliased)) { i = j; continue; } add_job(i, j, streaming, !unwatched ? (watch_ && (state_[i] & kProtected) ? Copy::guarded : Copy::unguarded) : (state_[i] & kAliased) ? Copy::aliased : Copy::pinned); i = j; } } // Guarded pages [i, j) of a read-only region: pages this tracker protected are as the last refresh left them; // any other is copied again. void guard_read_only(std::size_t i0, std::size_t i1, bool streaming) { for (std::size_t i = i0; i < i1;) { const bool clean = (state_[i] & (kProtected | kAliased | kPinned)) == kProtected; std::size_t j = i + 1; while (j < i1 && ((state_[j] & (kProtected | kAliased | kPinned)) == kProtected) == clean) ++j; if (!clean && !(!copy_aliased_ && (state_[i] & kAliased))) { for (std::size_t k = i; k < j; ++k) state_[k] &= ~kZero; add_job(i, j, streaming, state_[i] & kAliased ? Copy::aliased : state_[i] & kPinned ? Copy::pinned : Copy::read_only); } i = j; } } // With the lock held, when this tracker opens a new write-watch reader: no page is clean until that reader has // asked and the walk has copied it. The runs may have closed (their reservation released) and come back over a // reservation made at the same address since, which a page's watched mark alone doesn't tell (re-review of #61). void forget_clean() { for (std::uint8_t& page : state_) page &= std::uint8_t(~kClean); } // With the lock held, after the write-watched reservations changed: which pages are write-watched now. A page // that changes sides starts guarded: one this tracker keeps read-only stays so, and a hot one is not known any // more (the next walk queries, guards and copies it). void update_watched() { // Pages [i, upto) are write-watched now, or not. Either way a page that changes sides is guarded now (a guard // it has stays): only a hot one changes, to not known. std::size_t i = 0; const auto side = [&](std::size_t upto, bool watched) { for (; i < upto; ++i) if (bool(state_[i] & kWatched) != watched) state_[i] = std::uint8_t((state_[i] & ~(kWatched | kClean | kHot | kZero)) | (watched ? kWatched : 0)); }; leonida::title_write_watch::for_each_in(first_, last_, [&](std::uintptr_t from, std::uintptr_t to) { side((from - first_) / kPage, false); side((to - first_) / kPage, true); }); side(state_.size(), false); rebuild_watch_runs(); } // The runs of hot pages to ask about, each inside one reservation, from the pages' marks; runs less than kMergeGap // apart are asked about as one. void rebuild_watch_runs() { runs_stale_ = false; Vector>& runs = watch_runs_; runs.clear(); const auto hot = [&](std::uintptr_t p) { return (state_[(p - first_) / kPage] & (kWatched | kHot)) == (kWatched | kHot); }; leonida::title_write_watch::for_each_in(first_, last_, [&](std::uintptr_t from, std::uintptr_t to) { const std::size_t first_run = runs.size(); for (std::uintptr_t p = from; p < to;) { if (!hot(p)) { p += kPage; continue; } std::uintptr_t q = p + kPage; while (q < to && hot(q)) q += kPage; if (runs.size() > first_run && p - runs.back().second < kMergeGap) runs.back().second = q; else runs.emplace_back(p, q); p = q; } }); watched_pages_ = hot_pages_ = 0; for (std::size_t i = 0; i < state_.size(); ++i) { watched_pages_ += (state_[i] & kWatched) && cover_[i]; hot_pages_ += (state_[i] & kHot) && cover_[i]; } if (watch_runs_.empty() && reader_) { leonida::title_write_watch::close_reader(reader_); reader_ = 0; } } struct Job { std::size_t offset, bytes; // from begin_ bool streaming; }; struct Target { std::uintptr_t begin, end; // the title's bytes std::uint8_t* shadow; // where begin's byte goes }; static Kind classify(const MEMORY_BASIC_INFORMATION& region) { if (region.State != MEM_COMMIT || (region.Protect & PAGE_GUARD)) return Kind::zero; switch (region.Protect & 0xff) { case PAGE_READWRITE: case PAGE_EXECUTE_READWRITE: return Kind::writable; case PAGE_READONLY: case PAGE_EXECUTE_READ: return Kind::read_only; case PAGE_WRITECOPY: case PAGE_EXECUTE_WRITECOPY: return Kind::unwatched; default: return Kind::zero; // PAGE_NOACCESS, PAGE_EXECUTE: not readable } } // Offset from begin_ and size of pages [i, j): the first and last pages may stick out of the targets. std::pair span_of(std::size_t i, std::size_t j) const { const std::uintptr_t from = std::max(first_ + i * kPage, begin_), to = std::min(first_ + j * kPage, end_); return {from - begin_, to - from}; } void add_job(std::size_t i, std::size_t j, bool streaming, Copy why) { const auto [offset, bytes] = span_of(i, j); copy_bytes_[unsigned(why)] += bytes; if (!jobs_.empty() && jobs_.back().streaming == streaming && jobs_.back().offset + jobs_.back().bytes == offset) { jobs_.back().bytes += bytes; return; } jobs_.push_back({offset, bytes, streaming}); } // The targets sorted by start, the bytes they hold, and reach_[k], the furthest end among targets_[0..k]: the // targets over [from, to) are found from the first whose reach passes `from`. void index_targets() { std::sort(targets_.begin(), targets_.end(), [](const Target& a, const Target& b) { return a.begin < b.begin; }); reach_.resize(targets_.size()); target_bytes_ = 0; std::uintptr_t reach = 0; for (std::size_t k = 0; k < targets_.size(); ++k) { reach = std::max(reach, targets_[k].end); reach_[k] = reach; target_bytes_ += targets_[k].end - targets_[k].begin; } if (!targets_.empty()) { begin_ = targets_.front().begin; end_ = reach; } } // f(target, from, to) for each target's part of the title's bytes [from, to). template void for_each_target(std::uintptr_t from, std::uintptr_t to, F&& f) const { auto k = std::size_t(std::upper_bound(reach_.begin(), reach_.end(), from) - reach_.begin()); for (; k < targets_.size() && targets_[k].begin < to; ++k) { const Target& t = targets_[k]; const std::uintptr_t a = std::max(from, t.begin), b = std::min(to, t.end); if (a < b) f(t, a, b); } } void zero_targets(std::size_t offset, std::size_t bytes) { for_each_target(begin_ + offset, begin_ + offset + bytes, [](const Target& t, std::uintptr_t a, std::uintptr_t b) { std::memset(t.shadow + (a - t.begin), 0, b - a); }); } // Pages [i, j) of one region, read-write with protection `current`: read-only from now on, same cache attribute. void protect(std::size_t i, std::size_t j, DWORD current) { const DWORD base = current & 0xff; const DWORD read_only = (current & ~DWORD(0xff)) | (base == PAGE_READWRITE ? PAGE_READONLY : PAGE_EXECUTE_READ); DWORD old = 0; if (!VirtualProtect(reinterpret_cast(first_ + i * kPage), (j - i) * kPage, read_only, &old)) { protect_error_ = GetLastError(); // logged once the lock is released return; } for (std::size_t k = i; k < j; ++k) state_[k] |= kProtected; ++refresh_protects_; } // With the lock held: the pages in [from, to) this tracker made read-only are read-write again. void reopen_locked(std::uintptr_t from, std::uintptr_t to) { for (std::uintptr_t at = from; at < to;) { MEMORY_BASIC_INFORMATION region{}; std::uintptr_t next = at + kPage; DWORD base = 0; if (VirtualQuery(reinterpret_cast(at), ®ion, sizeof(region))) { next = std::min(to, reinterpret_cast(region.BaseAddress) + region.RegionSize); if (region.State == MEM_COMMIT) base = region.Protect & 0xff; } const std::size_t i0 = (at - first_) / kPage, i1 = (next - first_) / kPage; if (base != PAGE_READONLY && base != PAGE_EXECUTE_READ) { // Not read-only any more (remapped, decommitted, opened by another thread): nothing to undo. for (std::size_t i = i0; i < i1; ++i) state_[i] &= ~kProtected; } else { const DWORD writable = (region.Protect & ~DWORD(0xff)) | (base == PAGE_READONLY ? PAGE_READWRITE : PAGE_EXECUTE_READWRITE); for (std::size_t i = i0; i < i1;) { const bool ours = state_[i] & kProtected; std::size_t j = i + 1; while (j < i1 && bool(state_[j] & kProtected) == ours) ++j; DWORD old = 0; if (ours && VirtualProtect(reinterpret_cast(first_ + i * kPage), (j - i) * kPage, writable, &old)) { for (std::size_t k = i; k < j; ++k) state_[k] &= ~kProtected; leonida::geometry_writes::notify(first_ + i * kPage, first_ + j * kPage, leonida::geometry_writes::Event::write); } i = j; } } at = next; } } bool watch_; std::uintptr_t begin_ = 0, end_ = 0; // the targets' bytes: the first start and the furthest end std::uintptr_t first_ = 0, last_ = 0; // the pages covered SRWLOCK lock_ = SRWLOCK_INIT; // state_, cover_, the targets, and the protection of the pages Vector state_; // per 4 KiB page Vector cover_; // per 4 KiB page: the targets that read it Vector targets_; // by start Vector reach_; // see index_targets std::size_t target_bytes_ = 0; std::uint64_t alias_generation_ = ~std::uint64_t(0); std::uint64_t map_generation_ = ~std::uint64_t(0); bool pinned_ = false; // some page has kPinned Vector jobs_; // refresh() only, which DeviceState::shadow_mutex serializes Vector zeroed_; // likewise DWORD protect_error_ = 0; // a VirtualProtect refusal of this refresh(), logged after it std::array copy_bytes_{}; // refresh() only, likewise bool copy_aliased_ = true; // likewise std::uint64_t refresh_queries_ = 0; std::uint64_t refresh_protects_ = 0; // VirtualProtect calls of the last refresh() bool refresh_walked_all_ = false; // the last refresh() queried every page (the title memory map changed) std::atomic faults_{0}; // Write watching (leonida::title_write_watch): the reservations' generation the kWatched marks are from, the runs // of hot pages, this tracker's reader of the journal (0: none yet) and what the last refresh() asked. std::uint64_t watch_generation_ = ~std::uint64_t(0); Vector> watch_runs_; std::uint64_t reader_ = 0; std::size_t watched_pages_ = 0, hot_pages_ = 0; // covered pages write-watched, and hot Vector idle_; // per 4 KiB page: refreshes a hot page went without a write (kCool) bool runs_stale_ = false; // a page became hot or cold: watch_runs_ is rebuilt at the next refresh std::uint64_t refresh_asks_ = 0; std::uint64_t refresh_written_ = 0; }; // The live ShadowPages of every device, for the fault handler. Never freed: a fault can come at any time. In host_heap, // like everything changed under g_shadow_pages_lock (see ShadowPages). SRWLOCK g_shadow_pages_lock = SRWLOCK_INIT; leonida::host_heap::vector& shadow_pages_list() { static auto* list = new leonida::host_heap::vector; return *list; } // A write to a page a shadow made read-only: the page is made writable again and the write retried. First in the // handler chain, so a startup trace doesn't log these as exceptions; any other access violation goes on down it. // Whatever thread wrote: the title's, or a host thread of the runtime's (a DirectStorage queue's copy). // // A physical page xmem maps at two addresses (a stream pool's CPU view and its GPU-only twin) has a protection per // address: a guard on one view never faults a write through the other, which the shadows see by copying aliased // pages at every submission (title_page_aliases), so the guard to look for is the faulting address's own. When none // answers for it (each guard reopens only what it protected), xmem makes the page writable again if its window is // (kernel_writes' unguarder): a read-only page nobody reopens would fault that write, and every later one, for good. LONG CALLBACK shadow_write_fault(EXCEPTION_POINTERS* info) { const EXCEPTION_RECORD* record = info ? info->ExceptionRecord : nullptr; if (!record || record->ExceptionCode != EXCEPTION_ACCESS_VIOLATION || record->NumberParameters < 2 || record->ExceptionInformation[0] != 1) return EXCEPTION_CONTINUE_SEARCH; const auto address = static_cast(record->ExceptionInformation[1]); bool tile_reopened = false; bool retry = leonida::geometry_writes::notify(address, address + 1, leonida::geometry_writes::Event::fault, &tile_reopened); // The geometry watch reopened the whole 64 KiB tile around the address: the shadows over it reopen it too, so a // page both guarded is not left writable while its shadow takes it for unchanged. constexpr std::uintptr_t kTile = leonida::geometry_writes::tile_size; const std::uintptr_t tile = address & ~(kTile - 1); AcquireSRWLockShared(&g_shadow_pages_lock); for (ShadowPages* pages : shadow_pages_list()) { if (pages->contains(address)) retry |= pages->reopen(address); // reopened, or another thread's fault did if (tile_reopened && pages->first() < tile + kTile && tile < pages->last()) pages->reopen_range(tile, tile + kTile); } ReleaseSRWLockShared(&g_shadow_pages_lock); if (!retry) if (const auto unguard = leonida::kernel_writes::state().unguarder.load(std::memory_order_acquire)) retry = unguard(address, address + 1); return retry ? EXCEPTION_CONTINUE_EXECUTION : EXCEPTION_CONTINUE_SEARCH; } // leonida::kernel_writes' opener: a file shim is about to let the kernel write [from, to). void open_shadow_pages(std::uintptr_t from, std::uintptr_t to) { bool tiles_reopened = false; leonida::geometry_writes::notify(from, to, leonida::geometry_writes::Event::open, &tiles_reopened); if (tiles_reopened) { // whole tiles were reopened: so are the shadows' pages there (see shadow_write_fault) constexpr std::uintptr_t kTile = leonida::geometry_writes::tile_size; from &= ~(kTile - 1); to = (to + kTile - 1) & ~(kTile - 1); } AcquireSRWLockShared(&g_shadow_pages_lock); for (ShadowPages* pages : shadow_pages_list()) pages->reopen_range(from, to); ReleaseSRWLockShared(&g_shadow_pages_lock); } // Installs the handler once. false: it couldn't be, and shadows copy every page at every submission. bool watch_shadow_writes() { static const bool installed = [] { if (!AddVectoredExceptionHandler(1, &shadow_write_fault)) return false; leonida::kernel_writes::set_opener(&open_shadow_pages); return true; }(); return installed; } // A ShadowPages the fault handler knows of for its whole life: registered before it protects anything, removed once // its destructor has made every page writable again. struct ShadowPagesDeleter { void operator()(ShadowPages* pages) const { pages->reopen_all(); AcquireSRWLockExclusive(&g_shadow_pages_lock); std::erase(shadow_pages_list(), pages); ReleaseSRWLockExclusive(&g_shadow_pages_lock); delete pages; } }; using ShadowPagesPtr = std::unique_ptr; ShadowPagesPtr make_shadow_pages(const std::uint8_t* pages, std::uint8_t* shadow, std::size_t size) { const bool watch = watch_shadow_writes(); auto* tracker = new ShadowPages(pages, shadow, size, watch); if (watch) { shadow_pages_list(); // made (on the process heap) before the lock the fault handler waits for AcquireSRWLockExclusive(&g_shadow_pages_lock); shadow_pages_list().push_back(tracker); ReleaseSRWLockExclusive(&g_shadow_pages_lock); } return ShadowPagesPtr(tracker); } // The furthest range end is the span to refresh at submission. Sampler ranges use their full hardware // heap limit. Buffer-view translation retains its existing per-table budget. // The refresh of title-backed sampler tables (this count, the sampler entries of DeviceState::visible_heaps and the // sampler-heap case of scan_title_table) is adapted from the patch sampler-table-refresh of // Sigtryggur-Mani-Gudmundsson/graphics-runtime-patches at d9a0bc1b (author smg, as "Codex"), GPL-3.0; the // descriptor mapping provider registered in set_device_outer is from its patch descriptor-write-through. constexpr std::uint32_t kViewScanLimit = 1024; std::uint32_t table_descriptor_count(const rt::rootsig::RootParameter& param) { if (param.type != rt::rootsig::ParamType::Table || param.ranges.empty()) return 0; const std::uint32_t limit = param.ranges.front().range_type == D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER ? D3D12_MAX_SHADER_VISIBLE_SAMPLER_HEAP_SIZE : UINT_MAX; std::uint64_t next = 0, end = 0; for (const auto& range : param.ranges) { const std::uint64_t start = range.offset_in_table == D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND ? next : range.offset_in_table; const std::uint64_t count = range.num_descriptors == UINT_MAX ? limit : range.num_descriptors; next = start + count; end = std::max(end, next); } return std::uint32_t(std::min(end, limit)); } // Two test settings that make the standalone device look like a GPU with fewer Vulkan queues, so the path where D3D12 // queues share a VkQueue runs on any GPU; both together give the Intel UHD 770 on Windows and lavapipe (one family, // one queue). LEONIDA_VK_MAX_QUEUES_PER_FAMILY=N (1 to 16): at most N VkQueues per queue family (unset, or not a // number from 1 to 16: 16). LEONIDA_VK_GRAPHICS_FAMILY_ONLY=1: COMPUTE and COPY queues use the graphics family, as on // a GPU without async compute or transfer families. The game's device ignores both (QueueTestSettings::ignore). // The setting's value, or false when it is unset; set but ignored, it says so. bool queue_test_setting(const char* name, char* text, size_t size, rt::d3d12::QueueTestSettings settings) { size_t length = 0; if (getenv_s(&length, text, size, name) != 0 || length <= 1) return false; if (settings == rt::d3d12::QueueTestSettings::apply) return true; std::fprintf(stderr, "[rt] d3d12: %s is a test setting; the game's device ignores it (all its Vulkan queues)\n", name); return false; } bool graphics_family_only(rt::d3d12::QueueTestSettings settings) { char text[8] = {}; const bool on = queue_test_setting("LEONIDA_VK_GRAPHICS_FAMILY_ONLY", text, sizeof(text), settings) && text[0] != '0'; if (on) std::fprintf(stderr, "[rt] d3d12: LEONIDA_VK_GRAPHICS_FAMILY_ONLY: every D3D12 queue in the graphics family\n"); return on; } std::uint32_t max_queues_per_family(rt::d3d12::QueueTestSettings settings) { constexpr std::uint32_t most = 16; char text[16] = {}; if (!queue_test_setting("LEONIDA_VK_MAX_QUEUES_PER_FAMILY", text, sizeof(text), settings)) return most; char* end = nullptr; const unsigned long value = std::strtoul(text, &end, 10); if (end == text || *end || value < 1 || value > most) { std::fprintf(stderr, "[rt] d3d12: LEONIDA_VK_MAX_QUEUES_PER_FAMILY=%s is not a number from 1 to %u: ignored\n", text, most); return most; } std::fprintf(stderr, "[rt] d3d12: LEONIDA_VK_MAX_QUEUES_PER_FAMILY: at most %lu Vulkan queue(s) per family\n", value); return std::uint32_t(value); } // The pipelines build stage writes its cache beside gta6rt.exe, independently of the working directory. // LEONIDA_PIPELINE_CACHE_DIR= keeps it there instead, so several builds of gta6rt share one warmed cache. std::filesystem::path pipeline_cache_path() { { std::wstring dir(32768, L'\0'); const DWORD n = GetEnvironmentVariableW(L"LEONIDA_PIPELINE_CACHE_DIR", dir.data(), static_cast(dir.size())); if (n > 0 && n < dir.size()) { dir.resize(n); std::error_code ec; std::filesystem::create_directories(dir, ec); return std::filesystem::path(dir) / L"pipeline_cache.bin"; } } std::wstring path(32768, L'\0'); const DWORD length = GetModuleFileNameW(nullptr, path.data(), static_cast(path.size())); if (!length || length >= path.size()) return {}; path.resize(length); return std::filesystem::path(path).parent_path() / L"pipeline_cache.bin"; } // What the runtime itself compiled, kept next to the offline seed and never written over it (D3D-704). std::filesystem::path pipeline_cache_session_path() { std::filesystem::path path = pipeline_cache_path(); if (!path.empty()) path.replace_filename(L"pipeline_cache.session.bin"); return path; } // LEONIDA_PIPELINE_CACHE_BYTES, in bytes; 0 turns the session file off. One line for a value that is not a number. std::size_t pipeline_cache_save_limit() { char text[32] = {}; size_t length = 0; const bool present = getenv_s(&length, text, "LEONIDA_PIPELINE_CACHE_BYTES") == 0 && length > 1; const auto limit = leonida::pipeline_cache_store::parse_save_limit(present ? text : ""); if (!limit.valid) std::fprintf(stderr, "[rt] d3d12: LEONIDA_PIPELINE_CACHE_BYTES=%s is not a byte count; using %zu\n", text, limit.bytes); return limit.bytes; } // A corpus cache may be several GiB. Keep the read-only view alive through vkCreatePipelineCache // and deny writers while the view is in use. class PipelineCacheSeed { public: explicit PipelineCacheSeed(const std::filesystem::path& path) { if (path.empty()) return; file_ = CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); if (file_ == INVALID_HANDLE_VALUE) return; LARGE_INTEGER length{}; constexpr auto header_size = static_cast(sizeof(VkPipelineCacheHeaderVersionOne)); if (!GetFileSizeEx(file_, &length) || length.QuadPart < header_size) return; const HANDLE mapping = CreateFileMappingW(file_, nullptr, PAGE_READONLY, 0, 0, nullptr); if (!mapping) return; data_ = MapViewOfFile(mapping, FILE_MAP_READ, 0, 0, 0); CloseHandle(mapping); if (data_) size_ = static_cast(length.QuadPart); } ~PipelineCacheSeed() { if (data_) UnmapViewOfFile(data_); if (file_ != INVALID_HANDLE_VALUE) CloseHandle(file_); } PipelineCacheSeed(const PipelineCacheSeed&) = delete; PipelineCacheSeed& operator=(const PipelineCacheSeed&) = delete; const void* data() const { return data_; } std::size_t size() const { return size_; } bool compatible(const leonida::cached_pso::Identity& identity) const { return leonida::pipeline_cache_store::header_matches(data_, size_, identity); } private: HANDLE file_ = INVALID_HANDLE_VALUE; const void* data_ = nullptr; std::size_t size_ = 0; }; VkPipelineCache create_seeded_pipeline_cache(PFN_vkCreatePipelineCache create_cache, VkDevice device, const leonida::cached_pso::Identity& identity, bool session = false) { auto start = compile_us(); const auto name = session ? "pipeline_cache.session.bin" : "pipeline_cache.bin"; const PipelineCacheSeed seed(session ? pipeline_cache_session_path() : pipeline_cache_path()); if (!seed.data()) return VK_NULL_HANDLE; if (!seed.compatible(identity)) { std::fprintf(stderr, "[rt] d3d12: %s does not match this Vulkan device\n", name); return VK_NULL_HANDLE; } const VkPipelineCacheCreateInfo create{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO, nullptr, 0, seed.size(), seed.data()}; VkPipelineCache cache = VK_NULL_HANDLE; const auto mapped = compile_us(); if (create_cache(device, &create, nullptr, &cache) != VK_SUCCESS) { std::fprintf(stderr, "[rt] d3d12: Vulkan declined the pipeline cache seed\n"); return VK_NULL_HANDLE; } std::fprintf(stderr, "[rt] d3d12: loaded %zu bytes from %s\n", seed.size(), name); if (trace_pipeline_compile()) std::fprintf(stderr, "[rt] pipeline-cache op=load bytes=%zu map_us=%lld driver_us=%lld file=%s\n", seed.size(), mapped-start, compile_us()-mapped, name); return cache; } // D3D-704: merges what earlier launches compiled into the cache the pipelines are created against. The offline seed // and the session file cannot be handed over as one VkPipelineCacheCreateInfo -- Vulkan reads a single blob -- so the // session cache is created on its own and merged in. A missing, foreign or corrupt session file leaves the cache as // it was, and so does a driver that does not expose vkMergePipelineCaches. void merge_session_pipeline_cache(const leonida::VulkanDeviceFunctions& vk, VkDevice device, VkPipelineCache cache, const leonida::cached_pso::Identity& identity) { if (!cache || !vk.vkCreatePipelineCache || !vk.vkDestroyPipelineCache || !vk.vkMergePipelineCaches) return; if (!pipeline_cache_save_limit()) return; // LEONIDA_PIPELINE_CACHE_BYTES=0 turns the session file off const auto start = compile_us(); const PipelineCacheSeed seed(pipeline_cache_session_path()); if (!seed.data()) return; if (!seed.compatible(identity)) { std::fprintf(stderr, "[rt] d3d12: pipeline_cache.session.bin does not match this Vulkan device\n"); return; } const VkPipelineCacheCreateInfo create{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO, nullptr, 0, seed.size(), seed.data()}; const auto mapped = compile_us(); VkPipelineCache session = VK_NULL_HANDLE; if (vk.vkCreatePipelineCache(device, &create, nullptr, &session) != VK_SUCCESS) { std::fprintf(stderr, "[rt] d3d12: Vulkan declined pipeline_cache.session.bin\n"); return; } const auto created = compile_us(); const VkResult result = vk.vkMergePipelineCaches(device, cache, 1, &session); const auto merged = compile_us(); vk.vkDestroyPipelineCache(device, session, nullptr); if (trace_pipeline_compile()) std::fprintf(stderr, "[rt] pipeline-cache op=merge bytes=%zu map_us=%lld driver_us=%lld merge_us=%lld release_us=%lld result=%d\n", seed.size(), mapped-start, created-mapped, merged-created, compile_us()-merged, int(result)); if (result == VK_SUCCESS) std::fprintf(stderr, "[rt] d3d12: merged %zu bytes from pipeline_cache.session.bin\n", seed.size()); else std::fprintf(stderr, "[rt] d3d12: vkMergePipelineCaches on pipeline_cache.session.bin returned %d; ignored\n", static_cast(result)); } // LEONIDA_SKIP_COMPUTE=[,...]: compute programs whose library name contains one of the parts are // never built and every dispatch of theirs is dropped ("all" or "*": every compute program). For getting past a // program that hangs the GPU, such as a translated loop that never ends on the input it is given here, while the // program or its input is being fixed. What the program would have written keeps its previous contents. bool skip_compute(const std::string& name) { static const std::vector parts = [] { std::vector out; const DWORD need = GetEnvironmentVariableA("LEONIDA_SKIP_COMPUTE", nullptr, 0); // with the terminator if (need == 0) return out; std::string text(need, '\0'); const DWORD n = GetEnvironmentVariableA("LEONIDA_SKIP_COMPUTE", text.data(), need); if (n == 0 || n >= need) return out; text.resize(n); for (std::size_t at = 0; at <= text.size();) { const std::size_t end = std::min(text.find(',', at), text.size()); if (end > at) out.push_back(text.substr(at, end - at)); at = end + 1; } return out; }(); for (const std::string& part : parts) if (part == "all" || part == "*" || name.find(part) != std::string::npos) return true; return false; } // Graphics pipelines are built at their first draw, not at CreatePipelineState (LEONIDA_LAZY_PIPELINES=0: at // creation, as before). The title creates ~50,000 graphics PSOs at startup and draws a small part of them; each live // VkPipeline and its shader modules cost the driver ~90 KiB of host memory, ~4.5 GiB for the whole set. bool lazy_graphics_pipelines() { static const bool lazy = [] { wchar_t value[2]{}; return !(GetEnvironmentVariableW(L"LEONIDA_LAZY_PIPELINES", value, 2) == 1 && value[0] == L'0'); }(); return lazy; } // Texture descriptions the console accepts and a PC GPU may not: an R9G9B9E5 render target (RDNA2 renders and // stores to it; NVIDIA only samples it) and an sRGB RGBA8 or BGRA8 texture with unordered access. The title asks // GetResourceAllocationInfo for them at boot and asserts when the answer is "invalid", so the device gives them a // host format that can do the job (DeviceState::r9g9b9e5_target_stand_in, srgb_uav_emulated). // LEONIDA_CONSOLE_FORMATS=0 refuses them, as a PC D3D12 runtime does. bool console_format_stand_ins() { static const bool on = [] { wchar_t value[2]{}; return !(GetEnvironmentVariableW(L"LEONIDA_CONSOLE_FORMATS", value, 2) == 1 && value[0] == L'0'); }(); return on; } // A driver's compiler needs hundreds of MiB for a very large module; several at once exhausted host memory. Large are // compute modules over 128 KiB and graphics pipelines of PipelineCompiles::large_spirv_bytes or more. They compile side by // side while their estimates fit the memory that is free (big_compile_gate). LEONIDA_SERIAL_BIG_COMPILES=1: one at a time, // as before there was a budget (graphics: one after another in each submission). 0: as many as are asked for. enum class BigCompiles { budget, serial, unlimited }; BigCompiles big_compiles() { static const BigCompiles mode = [] { wchar_t v[2]{}; const DWORD n = GetEnvironmentVariableW(L"LEONIDA_SERIAL_BIG_COMPILES", v, 2); if (n == 0) return BigCompiles::budget; return n == 1 && v[0] == L'0' ? BigCompiles::unlimited : BigCompiles::serial; }(); return mode; } bool big_compute(std::size_t spirv_bytes) { return spirv_bytes > 128 * 1024; } // Where large compiles wait for memory: one for the process, as the memory is the machine's. Never destroyed: static // destruction must not race the compile worker. leonida::LargeModuleGate& big_compile_gate() { static auto* const gate = [] { char text[32]{}; std::size_t length = 0; const bool present = getenv_s(&length, text, "LEONIDA_BIG_COMPILE_BUDGET_MB") == 0 && length > 1; const auto setting = leonida::large_compile_budget(present ? text : ""); if (!setting.valid) std::fprintf(stderr, "[rt] d3d12: LEONIDA_BIG_COMPILE_BUDGET_MB=%s is not a number; not used\n", text); auto budget = [fixed = setting.fixed] { return fixed ? *fixed : leonida::large_compile_budget_bytes(); }; std::fprintf(stderr, "[rt] d3d12: large pipelines compile side by side within %llu MiB (%s)\n", static_cast(budget() >> 20), setting.fixed ? "LEONIDA_BIG_COMPILE_BUDGET_MB" : "3/4 of the memory free now"); return new leonida::LargeModuleGate(std::move(budget)); }(); return *gate; } bool startup_cache_checkpoints_enabled() { static const bool enabled = [] { wchar_t value[2]{}; return GetEnvironmentVariableW(L"LEONIDA_STARTUP_CACHE_CHECKPOINTS", value, 2) == 1 && value[0] == L'1'; }(); return enabled; } // Writes the session cache at a startup checkpoint or during device teardown. The size cap applies to either write. void save_session_pipeline_cache(const leonida::VulkanDeviceFunctions& vk, VkDevice device, VkPipelineCache cache, bool checkpoint = false, const char* op = nullptr) { if (!cache || !vk.vkGetPipelineCacheData) return; auto limit = pipeline_cache_save_limit(); // The output is an opaque Vulkan blob. A prefix is not an incremental cache. if (checkpoint) limit = (std::min)(limit, std::size_t{512} << 20); if (!limit) return; const auto start = compile_us(); std::size_t size = 0; if (vk.vkGetPipelineCacheData(device, cache, &size, nullptr) != VK_SUCCESS || size <= sizeof(VkPipelineCacheHeaderVersionOne)) return; if (size > limit) { std::fprintf(stderr, "[rt] d3d12: pipeline cache is %zu bytes, over the %zu-byte write limit\n", size, limit); return; } const auto queried = compile_us(); // A size query can itself serialize the driver cache. Let newly queued work run first. if (checkpoint && PipelineCompiler::instance().has_compile_waiter()) return; const auto path = pipeline_cache_session_path(); if (path.empty()) return; CacheStagingFile staging(path, size); if (!staging.data) { std::fprintf(stderr, "[rt] d3d12: could not map staging file for %zu pipeline cache bytes\n", size); return; } auto written = size; const auto result = vk.vkGetPipelineCacheData(device, cache, &written, staging.data); const auto filled = compile_us(); const bool ok = result == VK_SUCCESS && written >= sizeof(VkPipelineCacheHeaderVersionOne) && written <= size && staging.publish(path, written); if (trace_pipeline_compile()) std::fprintf(stderr, "[rt] pipeline-cache op=%s bytes=%zu query_us=%lld fill_us=%lld publish_us=%lld ok=%d result=%d\n", op ? op : checkpoint ? "checkpoint" : "teardown", written, queried-start, filled-queried, compile_us()-filled, int(ok), int(result)); if (ok) std::fprintf(stderr, "[rt] d3d12: wrote %zu bytes to pipeline_cache.session.bin\n", written); else std::fprintf(stderr, "[rt] d3d12: pipeline cache snapshot incomplete (%d); previous session retained\n", int(result)); } // A shader whose subgroup size cannot be had runs at the device's: inexact if it crosses the halves of a wave64 (or, // for a wave32 shader on a 64-wide default, reads lanes that are not its own), unless the translator's // partition-invariance tier says otherwise. Logged once per stage with the first shader's name, then again at 10, 100, // 1000... of that stage so a whole corpus stays readable. void report_subgroup_unavailable(const leonida::ShaderEntry& entry, const leonida::SubgroupRequest& request, const leonida::SubgroupSizeCaps& caps) { static std::mutex mutex; static std::map, unsigned>> seen; // stage -> names, next report std::lock_guard lock(mutex); auto& [names, next_report] = seen[entry.stage]; if (!names.insert(entry.name).second) return; if (names.size() == 1) next_report = 10; else if (names.size() != next_report) return; else next_report *= 10; const bool emulable = entry.stage == "cs" || entry.stage == "ms"; const std::string so_far = names.size() > 1 ? " (shaders of this stage so far: " + std::to_string(names.size()) + ")" : ""; if (leonida::graphics_partition_invariant(entry)) { // The translator proved this shader's results do not change when its wave is cut into two 32-lane halves // (docs/design.md, "Wave64 graphics"), so neither a 64-wide subgroup nor emulation is needed. std::fprintf(stderr, "[rt] d3d12: %s (%s) is a 64-wide shader but this device cannot require that subgroup size for " "the stage (device sizes %u..%u, default %u, subgroupSizeControl %s); it runs at the device's " "size, which is exact for it: the translator's partition-invariance analysis puts it in tier " "%s%s\n", entry.name.c_str(), entry.stage.c_str(), caps.min_size, caps.max_size, caps.default_size, caps.subgroup_size_control ? "on" : "off", entry.wave64_graphics.c_str(), so_far.c_str()); return; } std::fprintf(stderr, "[rt] d3d12: %s (%s) is a %u-wide shader but this device cannot require that subgroup size for the " "stage (device sizes %u..%u, default %u, subgroupSizeControl %s); it runs at the device's size and " "is inexact where lanes of the other half matter%s\n", entry.name.c_str(), entry.stage.c_str(), request.wanted, caps.min_size, caps.max_size, caps.default_size, caps.subgroup_size_control ? "on" : "off", so_far.c_str()); if (emulable && request.wanted == 64) std::fprintf(stderr, "[rt] d3d12: translate wave64 %s shaders with --wave64-emulate for this GPU " "(make_game.py --wave64-emulate auto does)\n", entry.stage.c_str()); else if (request.wanted == 64) std::fprintf(stderr, "[rt] d3d12: no emulation exists for wave64 %s shaders yet (docs/d3d12_vulkan.md, " "subgroup size)\n", entry.stage.c_str()); } // VK_FORMAT_A8_UNORM_KHR where the Vulkan headers have VK_KHR_maintenance5. Older headers have no A8 render targets: // VulkanDeviceInfo::a8_render_target is then never set, so this is never used as UNDEFINED. #ifdef VK_KHR_MAINTENANCE_5_EXTENSION_NAME constexpr VkFormat kA8UnormFormat = VK_FORMAT_A8_UNORM_KHR; #else constexpr VkFormat kA8UnormFormat = VK_FORMAT_UNDEFINED; #endif // Xbox DXGI values published by Microsoft's DirectXTex (DirectXTexP.h). constexpr auto xbox_d16s8=static_cast(118); constexpr auto xbox_d16_plane=static_cast(119); constexpr auto xbox_s8_plane=static_cast(120); struct Format { VkFormat format = VK_FORMAT_UNDEFINED; VkImageAspectFlags aspects = 0; bool typeless = false; // created with MUTABLE_FORMAT so typed views can reinterpret it bool d24_as_float = false; // D24_UNORM_S8_UINT stored as D32_SFLOAT_S8_UINT (no D24 on the GPU) bool d24 = false; // a D24_UNORM_S8_UINT family format, native or stored as D32 // An A8_UNORM render target stored as VK_FORMAT_A8_UNORM_KHR (VulkanDeviceInfo::a8_render_target): its RTVs render // to the alpha channel and its SRVs view it in that format, whose one channel the T# names as X (gfx10's // channels_a). Other A8_UNORM textures are R8_UNORM images. Vulkan puts A8 in a compatibility class of its own, // so one image cannot be viewed both ways. bool a8_as_alpha = false; // A UAV texture whose format has no storage support, stored as the mutable unsigned image `format` names (R32_UINT // for R9G9B9E5_SHAREDEXP, R16_UINT for B5G5R5A1_UNORM): the format its SRVs, RTVs and T#s use. Its storage view is // `format`, in the uint class; shaders write the packed bits. UNDEFINED for every other texture. VkFormat uint_backed = VK_FORMAT_UNDEFINED; // A 96-bit R32G32B32 format, held in the R32G32B32A32 image `format` names (ResourceBinding::rgb96). bool rgb96 = false; bool xbox_depth16_stencil8 = false; bool rgba4_render_fallback = false; }; // 96-bit textures are always RGBA32 images, even where the GPU has an RGB32 one (most have none with optimal // tiling): D3D12 places subresources at multiples of 512 bytes, Vulkan wants a copy's buffer offset to be a // multiple of the 12-byte texel (VUID-vkCmdCopyBufferToImage-dstImage-07975), so copies need the repack either // way (docs section 4.2). constexpr Format rgb96_format(VkFormat wide, bool typeless = false) { Format format{wide, VK_IMAGE_ASPECT_COLOR_BIT, typeless}; format.rgb96 = true; return format; } // DXGI -> Vulkan for the formats render targets, depth buffers and common textures use. R32 and R16 typeless become // depth formats when the resource allows depth-stencil; R32G8X24 and R24G8 always do, as Vulkan has no colour format // with their layout. // The console's own depth-stencil family, DXGI values past the PC list: D16_UNORM_S8_UINT (118) and its plane views // R16_UNORM_X8_TYPELESS (119) and X16_TYPELESS_G8_UINT (120). The title sizes and creates its depth targets in it // (and asserts when GetResourceAllocationInfo calls the description invalid). No D16S8 on the PC GPUs in reach, and // the PC has no such DXGI format: they are the D24_UNORM_S8_UINT family here, whose planes are viewed the same way // (depth as UNORM in X, stencil as UINT). Every entry point that takes a format from the title goes through this. // // That holds where the GPU has D24_UNORM_S8_UINT as a depth-stencil attachment. Where it has none (AMD), the D24S8 // family would itself be stored as D32_SFLOAT_S8_UINT, a third precision the title did not ask for; there the // family is kept as it is and takes the D16/S8 path (Format::xbox_depth16_stencil8: D16_UNORM_S8_UINT where the GPU // has it, else the first usable of D32_SFLOAT_S8_UINT and D24_UNORM_S8_UINT, with clears and stores quantised to // 16 bits), which is the path an AMD card was measured on past the title's first frames. The device decides when it // is created; LEONIDA_CONSOLE_D16S8=native or =d24 chooses for every GPU. Process-wide, like the title's one device. std::atomic g_console_d16s8_native{false}; inline bool console_d16s8_native() { return g_console_d16s8_native.load(std::memory_order_relaxed); } inline DXGI_FORMAT pc_format(DXGI_FORMAT format) { if (console_d16s8_native()) return format; switch (static_cast(format)) { case 118: return DXGI_FORMAT_D24_UNORM_S8_UINT; case 119: return DXGI_FORMAT_R24_UNORM_X8_TYPELESS; case 120: return DXGI_FORMAT_X24_TYPELESS_G8_UINT; default: return format; } } Format vulkan_format(DXGI_FORMAT format, bool depth) { constexpr VkImageAspectFlags color = VK_IMAGE_ASPECT_COLOR_BIT, d = VK_IMAGE_ASPECT_DEPTH_BIT, ds = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT; format = pc_format(format); switch (format) { case DXGI_FORMAT_R32G32B32A32_TYPELESS: return {VK_FORMAT_R32G32B32A32_SFLOAT, color, true}; case DXGI_FORMAT_R32G32B32A32_FLOAT: return {VK_FORMAT_R32G32B32A32_SFLOAT, color}; case DXGI_FORMAT_R32G32B32A32_UINT: return {VK_FORMAT_R32G32B32A32_UINT, color}; case DXGI_FORMAT_R32G32B32A32_SINT: return {VK_FORMAT_R32G32B32A32_SINT, color}; case DXGI_FORMAT_R32G32B32_TYPELESS: return rgb96_format(VK_FORMAT_R32G32B32A32_SFLOAT, true); case DXGI_FORMAT_R32G32B32_FLOAT: return rgb96_format(VK_FORMAT_R32G32B32A32_SFLOAT); case DXGI_FORMAT_R32G32B32_UINT: return rgb96_format(VK_FORMAT_R32G32B32A32_UINT); case DXGI_FORMAT_R32G32B32_SINT: return rgb96_format(VK_FORMAT_R32G32B32A32_SINT); case DXGI_FORMAT_R16G16B16A16_TYPELESS: return {VK_FORMAT_R16G16B16A16_SFLOAT, color, true}; case DXGI_FORMAT_R16G16B16A16_FLOAT: return {VK_FORMAT_R16G16B16A16_SFLOAT, color}; case DXGI_FORMAT_R16G16B16A16_UNORM: return {VK_FORMAT_R16G16B16A16_UNORM, color}; case DXGI_FORMAT_R16G16B16A16_SNORM: return {VK_FORMAT_R16G16B16A16_SNORM, color}; case DXGI_FORMAT_R16G16B16A16_UINT: return {VK_FORMAT_R16G16B16A16_UINT, color}; case DXGI_FORMAT_R16G16B16A16_SINT: return {VK_FORMAT_R16G16B16A16_SINT, color}; case DXGI_FORMAT_R32G32_TYPELESS: return {VK_FORMAT_R32G32_SFLOAT, color, true}; case DXGI_FORMAT_R32G32_FLOAT: return {VK_FORMAT_R32G32_SFLOAT, color}; case DXGI_FORMAT_R32G32_UINT: return {VK_FORMAT_R32G32_UINT, color}; case DXGI_FORMAT_R32G32_SINT: return {VK_FORMAT_R32G32_SINT, color}; case DXGI_FORMAT_R10G10B10A2_TYPELESS: return {VK_FORMAT_A2B10G10R10_UNORM_PACK32, color, true}; case DXGI_FORMAT_R10G10B10A2_UNORM: return {VK_FORMAT_A2B10G10R10_UNORM_PACK32, color}; case DXGI_FORMAT_R10G10B10A2_UINT: return {VK_FORMAT_A2B10G10R10_UINT_PACK32, color}; // XR_BIAS is the same packed 10:10:10:2 bit layout as R10G10B10A2_UNORM. Vulkan has no XR_BIAS format: // the application biases and scales the channels in its shader, so the resource itself is an ordinary UNORM. case DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM: return {VK_FORMAT_A2B10G10R10_UNORM_PACK32, color}; case DXGI_FORMAT_R9G9B9E5_SHAREDEXP: return {VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, color}; case DXGI_FORMAT_R11G11B10_FLOAT: return {VK_FORMAT_B10G11R11_UFLOAT_PACK32, color}; case DXGI_FORMAT_R8G8B8A8_TYPELESS: return {VK_FORMAT_R8G8B8A8_UNORM, color, true}; case DXGI_FORMAT_R8G8B8A8_UNORM: return {VK_FORMAT_R8G8B8A8_UNORM, color}; case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: return {VK_FORMAT_R8G8B8A8_SRGB, color}; case DXGI_FORMAT_R8G8B8A8_SNORM: return {VK_FORMAT_R8G8B8A8_SNORM, color}; case DXGI_FORMAT_R8G8B8A8_UINT: return {VK_FORMAT_R8G8B8A8_UINT, color}; case DXGI_FORMAT_R8G8B8A8_SINT: return {VK_FORMAT_R8G8B8A8_SINT, color}; case DXGI_FORMAT_B8G8R8A8_TYPELESS: return {VK_FORMAT_B8G8R8A8_UNORM, color, true}; case DXGI_FORMAT_B8G8R8A8_UNORM: return {VK_FORMAT_B8G8R8A8_UNORM, color}; // DXGI names channels from the low bits up, Vulkan from the high bits down: B in bits 0-3, A in 12-15 in both. // Vulkan 1.3 requires sampling it (formerly VK_EXT_4444_formats). case DXGI_FORMAT_B4G4R4A4_UNORM: return {VK_FORMAT_A4R4G4B4_UNORM_PACK16, color}; // A in bits 0-3 and R in 12-15 (cleared and read back on native D3D12, AMD and WARP): Vulkan's R4G4B4A4_PACK16. case DXGI_FORMAT_A4B4G4R4_UNORM: return {VK_FORMAT_R4G4B4A4_UNORM_PACK16, color}; case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: return {VK_FORMAT_B8G8R8A8_SRGB, color}; // The X byte has no channel of its own: the BGRA8 images hold it, and shader views read alpha as 1. case DXGI_FORMAT_B8G8R8X8_TYPELESS: return {VK_FORMAT_B8G8R8A8_UNORM, color, true}; case DXGI_FORMAT_B8G8R8X8_UNORM: return {VK_FORMAT_B8G8R8A8_UNORM, color}; case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB: return {VK_FORMAT_B8G8R8A8_SRGB, color}; case DXGI_FORMAT_R16G16_TYPELESS: return {VK_FORMAT_R16G16_SFLOAT, color, true}; case DXGI_FORMAT_R16G16_FLOAT: return {VK_FORMAT_R16G16_SFLOAT, color}; case DXGI_FORMAT_R16G16_UNORM: return {VK_FORMAT_R16G16_UNORM, color}; case DXGI_FORMAT_R16G16_SNORM: return {VK_FORMAT_R16G16_SNORM, color}; case DXGI_FORMAT_R16G16_UINT: return {VK_FORMAT_R16G16_UINT, color}; case DXGI_FORMAT_R16G16_SINT: return {VK_FORMAT_R16G16_SINT, color}; case DXGI_FORMAT_R8G8_TYPELESS: return {VK_FORMAT_R8G8_UNORM, color, true}; case DXGI_FORMAT_R8G8_UNORM: return {VK_FORMAT_R8G8_UNORM, color}; case DXGI_FORMAT_R8G8_SNORM: return {VK_FORMAT_R8G8_SNORM, color}; case DXGI_FORMAT_R16_UNORM: return {VK_FORMAT_R16_UNORM, color}; case DXGI_FORMAT_R16_SNORM: return {VK_FORMAT_R16_SNORM, color}; case DXGI_FORMAT_R16_UINT: return {VK_FORMAT_R16_UINT, color}; case DXGI_FORMAT_R16_SINT: return {VK_FORMAT_R16_SINT, color}; // DXGI names packed channels from the high bits down, Vulkan's PACK formats the same way but spelled the other // way round: B5G6R5 (blue in bits 0-4) is R5G6B5_PACK16 and B5G5R5A1 (alpha in bit 15) is A1R5G5B5_PACK16. case DXGI_FORMAT_B5G6R5_UNORM: return {VK_FORMAT_R5G6B5_UNORM_PACK16, color}; case DXGI_FORMAT_B5G5R5A1_UNORM: return {VK_FORMAT_A1R5G5B5_UNORM_PACK16, color}; case DXGI_FORMAT_R8G8_UINT: return {VK_FORMAT_R8G8_UINT, color}; case DXGI_FORMAT_R8G8_SINT: return {VK_FORMAT_R8G8_SINT, color}; case DXGI_FORMAT_R16_FLOAT: return {VK_FORMAT_R16_SFLOAT, color}; case DXGI_FORMAT_R8_UNORM: return {VK_FORMAT_R8_UNORM, color}; case DXGI_FORMAT_R8_TYPELESS: return {VK_FORMAT_R8_UNORM, color, true}; case DXGI_FORMAT_R8_SNORM: return {VK_FORMAT_R8_SNORM, color}; case DXGI_FORMAT_R8_UINT: return {VK_FORMAT_R8_UINT, color}; case DXGI_FORMAT_R8_SINT: return {VK_FORMAT_R8_SINT, color}; case DXGI_FORMAT_R32_FLOAT: return {VK_FORMAT_R32_SFLOAT, color}; case DXGI_FORMAT_R32_UINT: return {VK_FORMAT_R32_UINT, color}; case DXGI_FORMAT_R32_SINT: return {VK_FORMAT_R32_SINT, color}; case DXGI_FORMAT_BC1_TYPELESS: return {VK_FORMAT_BC1_RGBA_UNORM_BLOCK, color, true}; case DXGI_FORMAT_BC1_UNORM: return {VK_FORMAT_BC1_RGBA_UNORM_BLOCK, color}; case DXGI_FORMAT_BC1_UNORM_SRGB: return {VK_FORMAT_BC1_RGBA_SRGB_BLOCK, color}; case DXGI_FORMAT_BC2_TYPELESS: return {VK_FORMAT_BC2_UNORM_BLOCK, color, true}; case DXGI_FORMAT_BC2_UNORM: return {VK_FORMAT_BC2_UNORM_BLOCK, color}; case DXGI_FORMAT_BC2_UNORM_SRGB: return {VK_FORMAT_BC2_SRGB_BLOCK, color}; case DXGI_FORMAT_BC3_TYPELESS: return {VK_FORMAT_BC3_UNORM_BLOCK, color, true}; case DXGI_FORMAT_BC3_UNORM: return {VK_FORMAT_BC3_UNORM_BLOCK, color}; case DXGI_FORMAT_BC3_UNORM_SRGB: return {VK_FORMAT_BC3_SRGB_BLOCK, color}; case DXGI_FORMAT_BC4_TYPELESS: return {VK_FORMAT_BC4_UNORM_BLOCK, color, true}; case DXGI_FORMAT_BC4_UNORM: return {VK_FORMAT_BC4_UNORM_BLOCK, color}; case DXGI_FORMAT_BC4_SNORM: return {VK_FORMAT_BC4_SNORM_BLOCK, color}; case DXGI_FORMAT_BC5_TYPELESS: return {VK_FORMAT_BC5_UNORM_BLOCK, color, true}; case DXGI_FORMAT_BC5_UNORM: return {VK_FORMAT_BC5_UNORM_BLOCK, color}; case DXGI_FORMAT_BC5_SNORM: return {VK_FORMAT_BC5_SNORM_BLOCK, color}; case DXGI_FORMAT_BC6H_TYPELESS: return {VK_FORMAT_BC6H_UFLOAT_BLOCK, color, true}; case DXGI_FORMAT_BC6H_UF16: return {VK_FORMAT_BC6H_UFLOAT_BLOCK, color}; case DXGI_FORMAT_BC6H_SF16: return {VK_FORMAT_BC6H_SFLOAT_BLOCK, color}; case DXGI_FORMAT_BC7_TYPELESS: return {VK_FORMAT_BC7_UNORM_BLOCK, color, true}; case DXGI_FORMAT_BC7_UNORM: return {VK_FORMAT_BC7_UNORM_BLOCK, color}; case DXGI_FORMAT_BC7_UNORM_SRGB: return {VK_FORMAT_BC7_SRGB_BLOCK, color}; case DXGI_FORMAT_D32_FLOAT: return {VK_FORMAT_D32_SFLOAT, d}; case DXGI_FORMAT_D16_UNORM: return {VK_FORMAT_D16_UNORM, d}; case xbox_d16s8: return {VK_FORMAT_D16_UNORM_S8_UINT, ds}; case xbox_d16_plane: return {VK_FORMAT_D16_UNORM_S8_UINT, d}; case xbox_s8_plane: return {VK_FORMAT_D16_UNORM_S8_UINT, VK_IMAGE_ASPECT_STENCIL_BIT}; case DXGI_FORMAT_D32_FLOAT_S8X24_UINT: return {VK_FORMAT_D32_SFLOAT_S8_UINT, ds}; case DXGI_FORMAT_D24_UNORM_S8_UINT: return {VK_FORMAT_D24_UNORM_S8_UINT, ds}; case DXGI_FORMAT_R32_TYPELESS: return depth ? Format{VK_FORMAT_D32_SFLOAT, d, true} : Format{VK_FORMAT_R32_SFLOAT, color, true}; case DXGI_FORMAT_R16_TYPELESS: return depth ? Format{VK_FORMAT_D16_UNORM, d, true} : Format{VK_FORMAT_R16_UNORM, color, true}; case DXGI_FORMAT_R32G8X24_TYPELESS: return {VK_FORMAT_D32_SFLOAT_S8_UINT, ds, true}; case DXGI_FORMAT_R24G8_TYPELESS: return {VK_FORMAT_D24_UNORM_S8_UINT, ds, true}; default: return {}; } } Format texture_storage_format(DXGI_FORMAT format, bool depth) { return vulkan_format(format == DXGI_FORMAT_A8_UNORM ? DXGI_FORMAT_R8_UNORM : format, depth); } // The three-channel format a view of a 96-bit texture names in its T# (GFX10_FORMAT_32_32_32_*): the format // whose channels the view's swizzle is taken from, so alpha reads as one whatever the image's fourth channel holds. VkFormat rgb96_named_format(VkFormat image_view_format) { switch (image_view_format) { case VK_FORMAT_R32G32B32A32_SFLOAT: return VK_FORMAT_R32G32B32_SFLOAT; case VK_FORMAT_R32G32B32A32_UINT: return VK_FORMAT_R32G32B32_UINT; case VK_FORMAT_R32G32B32A32_SINT: return VK_FORMAT_R32G32B32_SINT; default: return VK_FORMAT_UNDEFINED; } } // And back: the format of the view of the RGBA32 image that shows such a T#. VkFormat rgb96_view_format(VkFormat image_format, std::uint32_t gfx10_format) { for (const VkFormat wide : {VK_FORMAT_R32G32B32A32_SFLOAT, VK_FORMAT_R32G32B32A32_UINT, VK_FORMAT_R32G32B32A32_SINT}) if (leonida::gfx10::format_from_vulkan(rgb96_named_format(wide)) == gfx10_format) return rgb96_named_format(image_format) != VK_FORMAT_UNDEFINED ? wide : VK_FORMAT_UNDEFINED; return VK_FORMAT_UNDEFINED; } // Bytes per texel or block as D3D12 lays the format out in a footprint. leonida::BlockFormat footprint_block(const Format& format, VkImageAspectFlags aspect) { leonida::BlockFormat block = leonida::block_format(format.format, aspect); if (format.rgb96 && block.bytes) block.bytes = leonida::rgb96_bytes; return block; } // 96-bit textures are sampled and copied, nothing else yet: the flags creation refuses, and // GetResourceAllocationInfo with it. The PC runtime (WARP) refuses unordered access and depth too; it does make // 96-bit render targets (d3d12_rgb96_test prints both devices' answers). bool rgb96_refused(const D3D12_RESOURCE_DESC& desc) { return vulkan_format(desc.Format, false).rgb96 && (desc.Flags & (D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS | D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)); } // B8G8R8X8: the BGRA8 Vulkan formats with the alpha byte unused. Its typeless family is a family of its own, so // only a castable-format list lets a view cross between it and B8G8R8A8, although both land on the same VkFormat. bool alpha_unused(DXGI_FORMAT format) { return format == DXGI_FORMAT_B8G8R8X8_TYPELESS || format == DXGI_FORMAT_B8G8R8X8_UNORM || format == DXGI_FORMAT_B8G8R8X8_UNORM_SRGB; } // The 8-bit four-channel UNORM and SRGB formats in either channel order, B8G8R8X8 included. A texture in one of them // takes an RTV in another when its castable-format list names it: WARP and AMD's D3D12 driver store the clear or the // draw in the view's channel order and encoding. bool rgba8_any_order(DXGI_FORMAT format) { switch (format) { case DXGI_FORMAT_R8G8B8A8_UNORM: case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: case DXGI_FORMAT_B8G8R8A8_UNORM: case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: case DXGI_FORMAT_B8G8R8X8_UNORM: case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB: return true; default: return false; } } // The full mip chain's length for a texture this size. UINT16 full_mips(UINT64 width, UINT height, UINT depth) { UINT16 mips = 0; for (UINT64 size = std::max({width, height, depth}); size; size >>= 1) ++mips; return mips; } // XR_BIAS is a display format: the PC runtime accepts it only as a single-mip, single-sample 2D texture, and // refuses 3D, extra mips and multisampling in creation, allocation and footprints alike. bool xr_bias_compatible(const D3D12_RESOURCE_DESC& desc) { if (desc.Format != DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM) return true; if (desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || desc.SampleDesc.Count != 1) return false; const UINT mips = desc.MipLevels ? desc.MipLevels : full_mips(desc.Width, desc.Height, 1); return mips == 1; } // The Xbox tiled layout word (slot 76, docs/d3d12_vulkan.md section 4.2) is outside D3D12_TEXTURE_LAYOUT's // enumerators, so compare as an integer. constexpr UINT kXboxTiledLayout = 0x101; bool is_tiled_layout(D3D12_TEXTURE_LAYOUT layout) { return layout == D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE || static_cast(layout) == kXboxTiledLayout; } // A volume RTV covers W slices of one mip. UINT_MAX extends through the last slice of that mip. leonida::TargetView volume_rtv(leonida::ResourceId id, const D3D12_RESOURCE_DESC& resource, const D3D12_RENDER_TARGET_VIEW_DESC* view) { if (!(resource.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) || vulkan_format(resource.Format, false).typeless) return {}; if (view && (view->ViewDimension != D3D12_RTV_DIMENSION_TEXTURE3D || (view->Format != DXGI_FORMAT_UNKNOWN && view->Format != resource.Format))) return {}; const D3D12_TEX3D_RTV slices = view ? view->Texture3D : D3D12_TEX3D_RTV{0, 0, UINT_MAX}; if (slices.MipSlice >= resource.MipLevels) return {}; const UINT depth = std::max(1u, UINT(resource.DepthOrArraySize) >> slices.MipSlice); if (slices.FirstWSlice >= depth) return {}; const UINT remaining = depth - slices.FirstWSlice; const UINT count = slices.WSize == UINT_MAX ? remaining : slices.WSize; if (!count || count > remaining) return {}; return {id, slices.MipSlice, slices.FirstWSlice, count}; } leonida::TargetView line_target_view(leonida::ResourceId id, const D3D12_RESOURCE_DESC& resource, UINT mip, UINT first_layer, UINT layer_count) { if (resource.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE1D || mip >= resource.MipLevels || first_layer >= resource.DepthOrArraySize) return {}; const UINT remaining = UINT(resource.DepthOrArraySize) - first_layer; const UINT count = layer_count == UINT_MAX ? remaining : layer_count; if (!count || count > remaining) return {}; return {id, mip, first_layer, count}; } // ArraySize of a 2D-array RTV or DSV: UINT_MAX is every slice from the first on, as on the host. Any other count // is kept, and UINT_MAX with a first slice past the array too, so an out-of-range view is refused as before. UINT view_slices(const D3D12_RESOURCE_DESC& resource, UINT first_layer, UINT layer_count) { const bool remaining = layer_count == UINT_MAX && first_layer < resource.DepthOrArraySize; return remaining ? resource.DepthOrArraySize - first_layer : layer_count; } // The VkImage a texture description becomes, with its mip count already resolved (MipLevels != 0). Shared by // texture creation and GetResourceAllocationInfo, so the sizes reported are the sizes later allocated. // Keeps the optional VkImageFormatListCreateInfo alongside VkImageCreateInfo so info.pNext stays valid. // attachment_usable: the GPU can render to `format`. A UAV texture then also gets COLOR_ATTACHMENT usage, because // ClearUnorderedAccessView* with rectangles clears through an attachment (vkCmdClearAttachments). struct TextureCreateInfo { VkImageCreateInfo info{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; VkImageFormatListCreateInfo format_list{VK_STRUCTURE_TYPE_IMAGE_FORMAT_LIST_CREATE_INFO}; std::array view_formats{}; TextureCreateInfo(const D3D12_RESOURCE_DESC& desc, const Format& format, bool attachment_usable) { const bool volume = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D; const bool one_d = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D; info.flags = format.typeless ? VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT : 0; if (volume && (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET)) info.flags |= VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT; info.imageType = volume ? VK_IMAGE_TYPE_3D : one_d ? VK_IMAGE_TYPE_1D : VK_IMAGE_TYPE_2D; info.format = format.format; info.extent = {std::uint32_t(desc.Width), one_d ? 1u : desc.Height, volume ? UINT(desc.DepthOrArraySize) : 1u}; info.mipLevels = desc.MipLevels; info.arrayLayers = volume ? 1 : desc.DepthOrArraySize; info.samples = VkSampleCountFlagBits(std::max(1u, desc.SampleDesc.Count)); info.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; if (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) info.usage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; if (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) info.usage |= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT; // No B8G8R8X8 view is ever a UAV, so its typeless family needs no storage usage (not every GPU has it for BGRA8). if ((desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) && !alpha_unused(desc.Format)) { info.usage |= VK_IMAGE_USAGE_STORAGE_BIT; if (!volume && info.samples == VK_SAMPLE_COUNT_1_BIT && attachment_usable) info.usage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; } if (!(desc.Flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE)) info.usage |= VK_IMAGE_USAGE_SAMPLED_BIT; if (format.uint_backed) { // The unsigned format owns the storage usage; views in the logical format restrict their usage (SAMPLED_BIT // for SRVs, COLOR_ATTACHMENT_BIT for RTVs). info.flags |= VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT | VK_IMAGE_CREATE_EXTENDED_USAGE_BIT; view_formats = {format.format, format.uint_backed}; format_list.viewFormatCount = 2; format_list.pViewFormats = view_formats.data(); info.pNext = &format_list; } } TextureCreateInfo(const TextureCreateInfo&) = delete; TextureCreateInfo& operator=(const TextureCreateInfo&) = delete; }; // The console descriptor heaps' ranges (Xbox slot 14): a descriptor table the title binds at a console VA inside one // is read by shaders at the console VA of its copy in the GPU address arena (DeviceState::add_console_heap). Process // wide, like the title's addresses; read by every SetGraphicsRootDescriptorTable / SetComputeRootDescriptorTable. class ConsoleHeapRanges { public: void add(std::uint64_t console_va, std::uint64_t bytes, std::uint64_t shader_va) { std::unique_lock lock(mutex_); ranges_.push_back({console_va, bytes, shader_va}); count_.store(ranges_.size(), std::memory_order_release); } void remove(std::uint64_t console_va) { std::unique_lock lock(mutex_); std::erase_if(ranges_, [console_va](const Range& r) { return r.console_va == console_va; }); count_.store(ranges_.size(), std::memory_order_release); } std::uint64_t shader_va(std::uint64_t va) const { if (!count_.load(std::memory_order_acquire)) return va; std::shared_lock lock(mutex_); for (const Range& r : ranges_) if (va >= r.console_va && va - r.console_va < r.bytes) return r.shader_va + (va - r.console_va); return va; } private: struct Range { std::uint64_t console_va, bytes, shader_va; }; mutable std::shared_mutex mutex_; std::vector ranges_; std::atomic count_{0}; }; ConsoleHeapRanges& console_heap_ranges() { static ConsoleHeapRanges ranges; return ranges; } // LEONIDA_CONSOLE_HEAP_SHADOW=0 keeps a console descriptor heap as it was before its arena copy existed: its bytes in // the title's memory only, where no shader reads them (the comparison for a run that misbehaves with the copy). bool console_heap_shadow_enabled() { static const bool enabled = [] { char text[4] = {}; size_t length = 0; return !(getenv_s(&length, text, "LEONIDA_CONSOLE_HEAP_SHADOW") == 0 && length > 1 && text[0] == '0'); }(); return enabled; } // What a T# the title wrote itself into a console descriptor heap came to (bind_title_image, after Resource). // not_tsharp: words with an image TYPE that do not decode as a T#: data, not a descriptor (the retail heap's last // 27 MiB are also the slot-133 pool, whose buffers sit there; T14 in ref/GAP-ANALYSIS-2.md). // TitleImage is defined in d3d12_com.h. class Resource; struct DeviceState; // `why`, when given, says what refused a T#: the first refusals are logged with their words (scan_console_slots). TitleImage bind_title_image(DeviceState& device, const leonida::gfx10::ImageWords& words, const char** why = nullptr); struct TitleTexture; // a texture the title keeps in its own memory (TitleTexture, after Resource) // The first refused T#s of each reason, with where they sit in the heap and their words, and counts of the // distinct slots refused overall and per reason (a slot is scanned again every pass over the heap). struct UnboundTsharpTracker { std::mutex mutex; std::set total_slots; std::map> slots_by_reason; std::map counts_by_reason; std::map logged; std::uint64_t total_refusals = 0; void note(std::uint64_t heap_va, std::size_t offset, const leonida::gfx10::ImageWords& words, const char* why) { std::lock_guard lock(mutex); const std::string reason = why ? why : "?"; ++total_refusals; ++counts_by_reason[reason]; if (total_slots.size() >= 262144) return; // enough to say how many const bool fresh_overall = total_slots.insert(offset).second; const bool fresh_reason = slots_by_reason[reason].insert(offset).second; unsigned& n = logged[reason]; if ((!fresh_overall && !fresh_reason) || n >= 6) return; ++n; std::fprintf(stderr, "[rt] d3d12: unbound T# in console heap 0x%llx at +0x%zx (%zu distinct slots so far, %zu for '%s'): %s: " "%08x %08x %08x %08x %08x %08x %08x %08x\n", static_cast(heap_va), offset, total_slots.size(), slots_by_reason[reason].size(), reason.c_str(), reason.c_str(), words[0], words[1], words[2], words[3], words[4], words[5], words[6], words[7]); } UnboundTsharpStats stats() { std::lock_guard lock(mutex); UnboundTsharpStats s; s.total_distinct_slots = total_slots.size(); s.total_refusals = total_refusals; for (const auto& [reason, slots] : slots_by_reason) { s.by_reason[reason].distinct_slots = slots.size(); s.by_reason[reason].total_refusals = counts_by_reason[reason]; } return s; } void reset() { std::lock_guard lock(mutex); total_slots.clear(); slots_by_reason.clear(); counts_by_reason.clear(); logged.clear(); total_refusals = 0; } }; UnboundTsharpTracker& unbound_tsharp_tracker() { static UnboundTsharpTracker tracker; return tracker; } // What a device's children need from it, kept apart from the COM class so children can hold a plain pointer. class Resource; struct DeviceState { std::mutex mapped_texture_mutex; std::set mapped_textures; std::atomic map_count{}; bool publish_mapped_textures(); std::mutex title_image_mutex; std::multimap title_images; VulkanDeviceInfo info; std::vector families; template void share(CreateInfo& create) const { leonida::share_across_queue_families(create, families); } std::unique_ptr context; // The blocks textures share (allocate_image). Freed after the context, whose deferred queue holds ranges of them. std::unique_ptr image_memory; VkPhysicalDeviceMemoryProperties memory{}; leonida::TitleImagePool title_image_pool; PFN_vkGetImageMemoryRequirements2 bound_image_requirements = nullptr; // D3D-96: upload-heap buffers prefer DEVICE_LOCAL | HOST_VISIBLE memory, so the GPU reads them from VRAM. Only // with Resizable BAR (leonida::resizable_bar); LEONIDA_UPLOAD_SYSMEM=1 keeps them in system memory to compare. bool upload_in_vram = false; // D3D-299: the first texture or default-heap buffer that lands outside device-local memory is logged, once. mutable std::once_flag spill_logged; // What D3D12_OPTIONS1 answers with: the physical device's own subgroup facts, read on first use. struct SubgroupFacts { UINT lane_min = 0; UINT lane_max = 0; bool wave_ops = false; }; SubgroupFacts subgroups; std::once_flag subgroups_once; // VkPhysicalDeviceMeshShaderPropertiesEXT, read on first use by a mesh PSO; zeros when it cannot be asked. VkPhysicalDeviceMeshShaderPropertiesEXT mesh_properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_PROPERTIES_EXT}; bool mesh_properties_read = false; std::mutex mesh_properties_mutex; PFN_vkGetPhysicalDeviceFormatProperties format_properties = nullptr; PFN_vkGetPhysicalDeviceImageFormatProperties image_format_properties = nullptr; PFN_vkGetPhysicalDeviceImageFormatProperties2 image_format_properties2 = nullptr; PFN_vkGetDeviceImageMemoryRequirements image_requirements = nullptr; // Vulkan 1.3 or VK_KHR_maintenance4 LUID luid{}; // VkPhysicalDeviceIDProperties::deviceLUID; zero when the driver reports none // An integrated GPU (VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU): D3D12_FEATURE_ARCHITECTURE answers UMA, the custom // heap equivalents are in MEMORY_POOL_L0 and custom heaps in L1 are refused, as the host runtime does there. bool uma = false; leonida::cached_pso::Identity pso_identity; // what GetCachedBlob records and CachedPSO is checked against std::once_flag pipeline_cache_once; VkPipelineCache pipeline_cache_handle = VK_NULL_HANDLE; std::atomic next_checkpoint{GetTickCount64() + 120000}; std::atomic active_compiles{0}; VkPipelineCache pipeline_cache() { std::call_once(pipeline_cache_once, [this] { const auto& vk = context->vk; if (!vk.vkCreatePipelineCache || !vk.vkDestroyPipelineCache) return; if (pipeline_cache_save_limit()) clean_stale_cache_files(pipeline_cache_session_path()); pipeline_cache_handle = create_seeded_pipeline_cache(vk.vkCreatePipelineCache, info.device, pso_identity); if (pipeline_cache_handle) { merge_session_pipeline_cache(vk, info.device, pipeline_cache_handle, pso_identity); } else if (pipeline_cache_save_limit() && direct_session_cache()) { // With no offline seed the session file can initialize the actual cache directly. pipeline_cache_handle = create_seeded_pipeline_cache(vk.vkCreatePipelineCache, info.device, pso_identity, true); } if (!pipeline_cache_handle) { const VkPipelineCacheCreateInfo create{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO}; if (vk.vkCreatePipelineCache(info.device, &create, nullptr, &pipeline_cache_handle) != VK_SUCCESS) pipeline_cache_handle = VK_NULL_HANDLE; else if (!direct_session_cache()) merge_session_pipeline_cache(vk, info.device, pipeline_cache_handle, pso_identity); } }); // Without EXTERNALLY_SYNCHRONIZED_BIT the driver synchronizes concurrent pipeline creation using this cache. return pipeline_cache_handle; } QueueClock clock; // device-wide calibration entry points std::vector timestamp_bits; QueueClock clock_for(std::uint32_t family) const { QueueClock result = clock; result.timestamp_valid_bits = leonida::queue_family_timestamp_bits(timestamp_bits, family); return result; } bool copy_timestamps_supported() const { // Copy queues can fall back to a graphics queue when their own pool is busy. const bool has_copy_pool = !info.command_queues.empty() && !info.copy_queues.empty(); const auto dedicated_copy = has_copy_pool ? std::optional{info.copy_family} : std::nullopt; return context->timestamp_period() > 0 && leonida::copy_queue_timestamp_families_supported( timestamp_bits, info.queue_family, dedicated_copy); } PFN_vkGetPhysicalDeviceFormatProperties2 format_properties2 = nullptr; // True when VK_FORMAT_E5B9G9R9_UFLOAT_PACK32 lacks native STORAGE_IMAGE but mutable R32_UINT+{R32_UINT,E5B9G9R9} // is supported, so R9G9B9E5_SHAREDEXP UAV textures are backed by R32_UINT with separate storage/sampled views. bool r9g9b9e5_uav_emulated = false; // The same for B5G5R5A1_UNORM: VK_FORMAT_A1R5G5B5_UNORM_PACK16 without STORAGE_IMAGE, backed by mutable R16_UINT. bool b5g5r5a1_uav_emulated = false; // True when the GPU cannot render to VK_FORMAT_E5B9G9R9_UFLOAT_PACK32 but can render and store to // VK_FORMAT_B10G11R11_UFLOAT_PACK32: an R9G9B9E5_SHAREDEXP texture that allows render targets is then an // R11G11B10F image of the same texel size, viewed in that format by every RTV, SRV, UAV and T#, and pipelines // that name R9G9B9E5 as a target format render in it (console_format_stand_ins). Its contents were rendered or // stored, never uploaded, so the different bit layout is not visible to the title's shaders. bool r9g9b9e5_target_stand_in = false; // True when VK_FORMAT_R8G8B8A8_SRGB (B8G8R8A8_SRGB) has no STORAGE_IMAGE support but its UNORM twin does: an sRGB // texture that allows unordered access is a mutable UNORM image (Format::uint_backed names the sRGB format its // SRVs and RTVs use), and its storage views write the UNORM bits unconverted, as the console does. bool rgba8_srgb_uav_emulated = false; bool bgra8_srgb_uav_emulated = false; // Cached physical-device no-attachment sample counts for D3D12_OPTIONS19. UINT no_output_sample_counts = 0; std::uint32_t f16_half_top_location = 29; float max_sampler_lod_bias = 0; D3D12_CONSERVATIVE_RASTERIZATION_TIER conservative_raster_tier = D3D12_CONSERVATIVE_RASTERIZATION_TIER_NOT_SUPPORTED; bool conservative_post_depth_coverage = false; // VkPhysicalDeviceDepthStencilResolveProperties: the modes a depth or stencil ResolveSubresourceRegion can use. VkResolveModeFlags depth_resolve_modes = 0; VkResolveModeFlags stencil_resolve_modes = 0; // VK_EXT_host_image_copy; null unless the device enabled it and its copies accept GENERAL. PFN_vkCopyMemoryToImageEXT copy_memory_to_image = nullptr; PFN_vkCopyImageToMemoryEXT copy_image_to_memory = nullptr; PFN_vkTransitionImageLayoutEXT transition_image_layout = nullptr; // VK_EXT_external_memory_host; null unless info.host_pointer_alignment is set and the entry point loaded. PFN_vkGetMemoryHostPointerPropertiesEXT get_host_pointer_properties = nullptr; // Slot-133 imports whose memory is allocated (create_host_buffer), for title_host_imports. std::atomic host_imports{0}; // The live shadow buffers of Xbox device slot 133 (Resource::create_shadow_buffer): title-placed buffers whose // pages the driver would not import. Each is brought up to date from the title's pages before every submission // of command lists (VulkanContext::set_before_execute), copying only what the title wrote since the last one // (ShadowPages). The title windows below are refreshed with them. The first refresh is logged with what it cost, // then the refreshes of every 5 seconds. mutable std::mutex shadow_mutex; // nothing else is taken under it but the ShadowPages' own locks std::vector shadows; std::uint64_t shadow_submissions = 0; std::uint64_t shadow_logged = 0; // shadow_submissions at the last log line std::chrono::steady_clock::time_point shadow_log_time{}; std::uint64_t shadow_bytes = 0; // copied since the last log line std::uint64_t shadow_queries = 0; // VirtualQuery calls since the last log line std::uint64_t shadow_protects = 0; // VirtualProtect calls since the last log line std::uint64_t shadow_walks = 0; // trackers that queried every page (the title memory map changed), likewise std::uint64_t shadow_asks = 0; // GetWriteWatch calls, likewise std::uint64_t shadow_written = 0; // write-watched pages they found written, likewise std::array shadow_copy_bytes{}; // by cause, likewise std::chrono::steady_clock::time_point shadow_alias_time{}; // the last refresh that copied aliased pages double shadow_ms = 0; // spent since the last log line double shadow_max_ms = 0; // the longest refresh since the last log line double heap_ms = 0; // spent in refresh_console_heaps since the last log line std::uint64_t shadow_faults = 0; // the write faults counted at the last log line // A copy of the title's bytes [pages, pages + size) at `shadow`: filled now, then brought up to date before every // submission. Copies whose pages overlap or touch share one tracker (ShadowPages: a page has one owner that may // watch it), so a copy that reaches one or more trackers joins them into one. void add_shadow(const std::uint8_t* pages, std::uint8_t* shadow, std::size_t size) { constexpr std::uintptr_t kPage = ShadowPages::kPage; const auto begin = reinterpret_cast(pages), end = begin + size; const std::uintptr_t first = begin & ~(kPage - 1), last = (end + kPage - 1) & ~(kPage - 1); std::lock_guard lock(shadow_mutex); std::vector hits; // ascending std::uintptr_t lo = first, hi = last; for (std::size_t i = 0; i < shadows.size(); ++i) if (shadows[i]->first() <= last && first <= shadows[i]->last()) { hits.push_back(i); lo = std::min(lo, shadows[i]->first()); hi = std::max(hi, shadows[i]->last()); } if (hits.empty()) { ShadowPagesPtr tracker = make_shadow_pages(pages, shadow, size); tracker->refresh(); shadows.push_back(std::move(tracker)); return; } ShadowPages& keep = *shadows[hits.front()]; // The fault handler is kept out while the pages change hands: it finds them in `keep` from then on, with // what the others knew of them (the pages they made read-only stay so, now `keep`'s). AcquireSRWLockExclusive(&g_shadow_pages_lock); keep.extend(lo, hi); for (std::size_t k = 1; k < hits.size(); ++k) { ShadowPages* other = shadows[hits[k]].get(); keep.absorb(*other); std::erase(shadow_pages_list(), other); } keep.add_target(begin, end, shadow); ReleaseSRWLockExclusive(&g_shadow_pages_lock); for (std::size_t k = hits.size(); k-- > 1;) shadows.erase(shadows.begin() + std::ptrdiff_t(hits[k])); keep.fill(begin, end, shadow); } void remove_shadow(const std::uint8_t* mapped) { std::lock_guard lock(shadow_mutex); for (auto it = shadows.begin(); it != shadows.end(); ++it) if ((*it)->remove_target(mapped)) { if (!(*it)->targets()) shadows.erase(it); return; } } // heaps / pages: whether this submission refreshes the console heaps and the slot-133 shadows and title windows // (LEONIDA_REFRESH_PER_FRAME leaves some submissions without them). void refresh_shadows(bool heaps = true, bool pages = true) { using clock = std::chrono::steady_clock; // First, and without shadow_mutex: fixing a console heap's slots can make a title window (add_shadow). const auto heaps_start = clock::now(); if (heaps) { const leonida::submit_phases::Scope timed(leonida::submit_phases::heaps); refresh_console_heaps(); } heap_ms += std::chrono::duration(clock::now() - heaps_start).count(); probe_census(); // LOCAL DIAGNOSTIC if (!pages) return; const leonida::submit_phases::Scope timed(leonida::submit_phases::shadows); std::lock_guard lock(shadow_mutex); if (shadows.empty()) return; const auto start = clock::now(); // LEONIDA_SHADOW_ALIAS_MS (0 by default: every submission): pages xmem maps at two addresses, which no guard // can watch, are copied at most this often. After the story load they were 59 MiB a submission (speed-6); a // GPU read of them is at most this many milliseconds behind the title's writes. static const auto alias_period = std::chrono::milliseconds([] { char text[16] = {}; const DWORD n = GetEnvironmentVariableA("LEONIDA_SHADOW_ALIAS_MS", text, sizeof(text)); return n > 0 && n < sizeof(text) ? std::strtoull(text, nullptr, 10) : 0ull; }()); const bool copy_aliased = alias_period.count() == 0 || start - shadow_alias_time >= alias_period; if (copy_aliased) shadow_alias_time = start; std::uint64_t copied = 0; for (const ShadowPagesPtr& s : shadows) { copied += s->refresh(copy_aliased); shadow_queries += s->refresh_queries(); shadow_protects += s->refresh_protects(); shadow_walks += s->refresh_walked_all(); shadow_asks += s->refresh_asks(); shadow_written += s->refresh_written(); for (unsigned k = 0; k < shadow_copy_bytes.size(); ++k) shadow_copy_bytes[k] += s->copy_bytes()[k]; } const auto now = clock::now(); const double ms = std::chrono::duration(now - start).count(); shadow_ms += ms; shadow_max_ms = std::max(shadow_max_ms, ms); shadow_bytes += copied; ++shadow_submissions; if (shadow_submissions != 1 && now - shadow_log_time < std::chrono::seconds(5)) return; std::uint64_t size = 0, faults = 0, copies = 0, watched = 0, hot = 0; for (const ShadowPagesPtr& s : shadows) size += s->size(), faults += s->faults(), copies += s->targets(), watched += s->watched_bytes(), hot += s->hot_bytes(); const double count = double(shadow_submissions - shadow_logged); std::fprintf(stderr, "[rt] d3d12: slot-133 shadow buffers and title windows (%llu KiB in %llu copies, %zu trackers, " "%zu title windows; %llu KiB of pages write-watched, %llu KiB hot): submissions %llu-%llu copied %.1f KiB each " "from the title's pages in %.3f ms on average (%.3f max; console heaps %.3f ms), %.1f VirtualQuery, " "%.1f VirtualProtect and %.1f GetWriteWatch calls (%.1f pages found written) and %.1f trackers " "walked in full per refresh, %llu write faults\n", static_cast(size / 1024), static_cast(copies), shadows.size(), title_window_count.load(std::memory_order_relaxed), static_cast(watched / 1024), static_cast(hot / 1024), static_cast(shadow_logged + 1), static_cast(shadow_submissions), double(shadow_bytes) / 1024.0 / count, shadow_ms / count, shadow_max_ms, heap_ms / count, double(shadow_queries) / count, double(shadow_protects) / count, double(shadow_asks) / count, double(shadow_written) / count, double(shadow_walks) / count, static_cast(faults >= shadow_faults ? faults - shadow_faults : faults)); const auto kib = [&](ShadowPages::Copy c) { return double(shadow_copy_bytes[unsigned(c)]) / 1024.0 / count; }; std::fprintf(stderr, "[rt] d3d12: slot-133 shadow copies by cause, KiB a submission: guarded now %.1f, unguarded %.1f, " "aliased %.1f, pinned %.1f, read-only (not ours) %.1f, copy-on-write %.1f, write-watched %.1f\n", kib(ShadowPages::Copy::guarded), kib(ShadowPages::Copy::unguarded), kib(ShadowPages::Copy::aliased), kib(ShadowPages::Copy::pinned), kib(ShadowPages::Copy::read_only), kib(ShadowPages::Copy::copy_on_write), kib(ShadowPages::Copy::write_watched)); shadow_copy_bytes = {}; shadow_logged = shadow_submissions; shadow_log_time = now; shadow_bytes = shadow_queries = shadow_protects = shadow_walks = shadow_asks = shadow_written = 0; shadow_ms = shadow_max_ms = heap_ms = 0; shadow_faults = faults; } // Textures the title keeps in its own memory, by the GPU address it names them by (Device:: // write_placed_texture_view, register_title_texture, refresh_title_textures): the slot-133 textures and the // images made for slot-70 views of memory no resource covers. title_texture_mutex is taken before // descriptor_mutex. A slot-133 texture tells the registry when the title maps it and when it goes; both are // defined after TitleTexture. std::mutex title_texture_mutex; std::map> title_textures; void title_texture_mapped(const void* resource, std::uint64_t address); void title_texture_unmapped(const void* resource, std::uint64_t address); // the title wrote texels void title_texture_gone(const void* resource, std::uint64_t address); // Textures destroyed while their thread held title_texture_mutex (inside the registry, t_in_title_textures): a // descriptor it overwrote held the last reference. Their GPU placement is removed at once; title_texture_gone // cannot take the registry mutex again there (MSVC's // std::mutex throws resource_deadlock_would_occur, which Wine's msvcp140 aborts on), so their entries only stop // naming the resource and are removed by drain_titles_gone once the mutex is free. Under title_texture_mutex. std::vector> titles_gone; std::atomic titles_gone_pending{false}; void drain_titles_gone(); // Windows of the title's own memory in the GPU address arena (src/title_va_alias.h, docs/d3d12_vulkan.md // section 3.3 "Title-chosen addresses"): a root view or buffer V# that names the title's memory outside any // slot-133 buffer (a per-frame constant ring, #8862 section 3.5) gets a copy of the 64 KiB-aligned pages it // covers, refreshed before every submission like a slot-133 shadow, and the address of that copy. Windows are // kept until the device goes (the ring comes round to the same pages), up to LEONIDA_TITLE_WINDOWS_MB (64 MiB // by default). A window that does not fit is not made: the range is backed by a geometry copy instead, or the // view written with a zero-size range (src/title_window_plan.h). struct TitleWindow { std::uint64_t start; std::uint64_t shader_va; }; static constexpr std::uint64_t kTitleWindowAlign = 65536; static constexpr std::uint64_t kTitleWindowMax = 16ull << 20; // the most one address pulls in // One mapping serves this much of a stream pool: the readable run of a 16-24 GiB reservation, whose frames the // title remaps per request, so a whole-pool allocation is not possible. static constexpr std::uint64_t kPoolExtentMax = 1ull << 20; std::mutex title_window_mutex; // taken before shadow_mutex, never under it rt::d3d12::TitleBufferWindows external_windows; std::vector title_windows; std::atomic title_window_count{0}; // title_windows.size(), read without the mutex std::uint64_t title_window_bytes = 0; std::uint64_t title_window_cap = 64ull << 20; // The stream pools' mappings (title_gpu_views): one per readable run of a pool, kept for the device's life. struct PoolSpan { std::uint64_t source; // the readable side of the pair the copy is made from std::uint64_t twin; // the extent's address in the pair's other view (0 when there is none) std::uint64_t shader_va; std::uint64_t size; bool geometry; // a geometry copy, not charged to the title-window budget }; std::vector pool_spans; std::atomic pool_span_count{0}; std::uint64_t pool_span_bytes = 0; std::uint64_t title_window_refusals = 0; // windows neither the budget nor the arena allowed std::uint64_t unbacked_requests = 0; // title addresses no backing could be made for (zero-size views) rt::d3d12::GeometryViews geometry; static rt::d3d12::GeometryCopy copy_geometry(std::uint8_t* to, const std::uint8_t* from, std::size_t size) { using Result = rt::d3d12::GeometryCopy; if (!leonida::texture_memory_readable(reinterpret_cast(from), size)) return Result::unreadable; return copy_guarded(to, from, size, false) ? Result::copied : Result::interrupted; } std::uint64_t geometry_va(std::uint64_t guest, std::uint64_t span, bool read_only) { if (!geometry.cap() || !span || !guest || !watch_shadow_writes()) return 0; const auto cpu = leonida::title_gpu_views::to_cpu(guest, span); auto& aliases = leonida::title_va_aliases(); const auto alias = aliases.shader_va(cpu, span); if (alias != cpu) return alias; if (cpu == guest) { std::uint64_t lo{}, hi{}; if (!aliases.title_memory(guest, lo, hi) || span > hi - guest || context->knows_buffer_va(guest)) return 0; if (!read_only && !leonida::title_gpu_views::other_view(cpu)) { MEMORY_BASIC_INFORMATION region{}; if (!VirtualQuery(reinterpret_cast(cpu), ®ion, sizeof region) || region.Type != MEM_MAPPED) return geometry.find(cpu, span); } } return geometry.resolve(*this, cpu, span, copy_geometry); } // LEONIDA_STREAM_BUFFER_WINDOWS=0: a window may not come from a block outside the arena. static bool stream_windows() { static const bool enabled = [] { const char* flag = std::getenv("LEONIDA_STREAM_BUFFER_WINDOWS"); return !flag || std::string_view(flag) != "0"; }(); return enabled; } // A committed page the host may read: the title's reservations start uncommitted. static bool readable_page(std::uint64_t address) { MEMORY_BASIC_INFORMATION region{}; return VirtualQuery(reinterpret_cast(static_cast(address)), ®ion, sizeof(region)) && region.State == MEM_COMMIT && region.Protect && !(region.Protect & (PAGE_NOACCESS | PAGE_GUARD)); } // The end of the readable run that starts at the page `address`, at most `end` (a pool's frames are mapped per // request, so its range is read until the first page the title has not committed). static std::uint64_t readable_run_end(std::uint64_t address, std::uint64_t end) { std::uint64_t at = address; while (at < end) { MEMORY_BASIC_INFORMATION region{}; if (!VirtualQuery(reinterpret_cast(static_cast(at)), ®ion, sizeof(region)) || region.State != MEM_COMMIT || !region.Protect || (region.Protect & (PAGE_NOACCESS | PAGE_GUARD))) break; const auto region_end = reinterpret_cast(region.BaseAddress) + region.RegionSize; if (region_end <= at) break; at = region_end; } return std::min(at, end); } // One line per call site (and then at 2, 4, 8... of it): a view the layer had to write with no backing, and how // many so far. It is written with a zero-size range, so a shader never adds heap_base to a raw title address. void note_unbacked(const char* site, std::uint64_t va, std::uint64_t bytes) { static std::mutex mutex; static std::map counts; std::lock_guard lock(mutex); std::uint64_t& seen = counts[site]; ++seen; if (seen != 1 && (seen & (seen - 1))) return; std::fprintf(stderr, "[rt] d3d12: %s: title address 0x%llx (%llu bytes) got no GPU copy: the view is written with no " "records (loads 0, stores dropped); %llu so far\n", site, static_cast(va), static_cast(bytes), static_cast(seen)); } // A window for [start, start + size): an arena range or a block outside the arena, charged to // LEONIDA_TITLE_WINDOWS_MB and refreshed before every submission by the tracker of its pages. 0 when neither the // budget nor the arena has room. title_window_mutex held. std::uint64_t make_title_window(std::uint64_t start, std::uint64_t size) { if (!leonida::title_window_fits(title_window_cap, title_window_bytes, size)) { ++title_window_refusals; log_once("title memory named by a shader address is past LEONIDA_TITLE_WINDOWS_MB, no window; MiB copied " "so far:", int(title_window_bytes >> 20)); return 0; } VkDeviceSize offset = 0; std::uint8_t* mapped{}; if (arena_allocate(size, kTitleWindowAlign, offset, arena_buffer)) { mapped = arena.mapped + offset; } else if (!stream_windows() || !external_windows.allocate(*this, size, offset, mapped)) { ++title_window_refusals; log_once("GPU address arena full (raise LEONIDA_ARENA_MB): title memory has no window; window KiB:", int(std::min(size >> 10, INT_MAX))); return 0; } if (offset >= arena.size) backing(arena.address + offset, size, start, true); const auto* pages = reinterpret_cast(static_cast(start)); add_shadow(pages, mapped, std::size_t(size)); title_windows.push_back({start, offset}); title_window_count.store(title_windows.size(), std::memory_order_relaxed); title_window_bytes += size; if (title_windows.size() <= 4 || !(title_windows.size() & (title_windows.size() - 1))) std::fprintf(stderr, "[rt] d3d12: a %llu KiB window of the title's memory, named by a shader address, is " "mirrored before every submission (%zu windows, %llu KiB)\n", static_cast(size >> 10), title_windows.size(), static_cast(title_window_bytes >> 10)); return offset; } // A stream pool's address (a CPU view paired with a GPU-only alias). Rule B // first: the CPU view is where the host reads the frames, so that is what the copy is made from; the GPU-only // pages are the same frames through the title's queue slot 31 and are read only when the CPU view is not // committed. One mapping serves a page-aligned readable run (kPoolExtentMax at most), not one 128 KiB window per // vertex buffer, and both of the pair's addresses are entered in the table, so a V# naming either view reaches // the same bytes instead of asking for a second mapping. // True when `va` is in a pool (out = its shader VA, or 0 when nothing could back the run). title_window_mutex // held. bool resolve_pool_memory(std::uint64_t va, std::uint64_t bytes, std::uint64_t& out) { leonida::title_gpu_views::Range view{}; if (!leonida::title_gpu_views::view_at(static_cast(va), static_cast(std::max(bytes, 1)), view)) return false; const std::uint64_t offset = va >= view.gpu && va - view.gpu < view.size ? va - view.gpu : va - view.cpu; // Rule B: the CPU view where the host reads the frames, the GPU-only pages only when that view has none. const std::uint64_t source = leonida::title_gpu_views::to_host_view(static_cast(va), static_cast( std::max(bytes, 1))); const std::uint64_t twin = leonida::title_gpu_views::other_view(static_cast(source)); const std::uint64_t twin_view = twin ? twin : source; // the pair always has two addresses if (!readable_page(source)) { out = 0; ++unbacked_requests; note_unbacked("stream pool", va, bytes); return true; } const std::uint64_t pool_end = (source >= view.gpu && source - view.gpu < view.size ? view.gpu : view.cpu) + view.size; const std::uint64_t run_end = readable_run_end(source & ~(kTitleWindowAlign - 1), std::min(pool_end, source + kPoolExtentMax)); leonida::TitleWindowRange extent{}; if (!leonida::title_pool_extent(source - offset, pool_end, source, run_end, kTitleWindowAlign, kPoolExtentMax, extent)) { out = 0; ++unbacked_requests; note_unbacked("stream pool", va, bytes); return true; } const std::uint64_t twin_start = twin_view - (source - extent.start); // the same pages in the other view auto& aliases = leonida::title_va_aliases(); // A mapping that already holds the extent's start (a buffer made over these pages, or a window from another // request) serves the request only as far as it reaches: claim that much, never bytes it does not cover. std::uint64_t shader = 0, available = 0; if (aliases.range_of(extent.start, shader, available) || aliases.range_of(twin_start, shader, available)) { if (available < extent.size) { if (available <= source - extent.start) shader = 0; else extent.size = available; } } if (shader) { // Both addresses must reach it. The address the mapping was found at keeps its own (possibly wider) // range: adding a shorter one over it would drop bytes another view still uses. if (aliases.shader_va(twin_start) == twin_start) aliases.add(twin_start, extent.size, shader); if (aliases.shader_va(extent.start) == extent.start) aliases.add(extent.start, extent.size, shader); } else { bool geometry_copy = false; if (geometry.cap() && watch_shadow_writes() && !context->knows_buffer_va(extent.start, extent.size)) shader = geometry.resolve(*this, extent.start, extent.size, copy_geometry), geometry_copy = shader != 0; if (!shader) shader = make_title_window(extent.start, extent.size); if (!shader) { out = 0; ++unbacked_requests; note_unbacked("stream pool", va, bytes); return true; } aliases.add_twin(extent.start, twin_start, extent.size, shader); pool_spans.push_back({extent.start, twin_start, shader, extent.size, geometry_copy}); pool_span_count.store(pool_spans.size(), std::memory_order_relaxed); pool_span_bytes += extent.size; if (pool_spans.size() <= 4 || !(pool_spans.size() & (pool_spans.size() - 1))) std::fprintf(stderr, "[rt] d3d12: a %llu KiB stream-pool extent is one %s mapping (alias 0x%llx and CPU view " "0x%llx share shader VA 0x%llx; %zu extents, %llu KiB)\n", static_cast(extent.size >> 10), geometry_copy ? "geometry-copy" : "window", static_cast(twin_view), static_cast(source), static_cast(shader), pool_spans.size(), static_cast(pool_span_bytes >> 10)); } out = shader + (source - extent.start); return true; } // Called through title_va_aliases().resolve for an address with no copy yet. False: not the title's memory. // True: it is, and `out` is its shader VA, 0 when no backing could be made (never the raw address). bool resolve_title_memory(std::uint64_t va, std::uint64_t bytes, std::uint64_t& out) { out = va; if (!arena.mapped || !context) return false; if (context->knows_buffer_va(va)) return false; // an upload or readback buffer's biased VA, say if (va < arena.size) { // Below the arena's size an address is an arena address unless the title's own memory is there (its // heap is: arena_allocate keeps out of those ranges). std::uint64_t lo = 0, hi = 0; if (!leonida::title_va_aliases().title_memory(va, lo, hi)) return false; } auto& aliases = leonida::title_va_aliases(); // Only title memory can request a new copy. Elsewhere, require existing GPU backing. std::uint64_t title_lo = 0, title_hi = 0; if (!aliases.title_memory(va, title_lo, title_hi)) { // Root descriptors carry a pointer without a declared length. Validate the base. out = vsharp_address(va, 1, leonida::TitleVaAliases::root_view, false); return true; } const std::uint64_t want = std::max(bytes, 1); std::lock_guard lock(title_window_mutex); if (const std::uint64_t made = aliases.shader_va(va); made != va) { // another thread made it meanwhile out = made; return true; } // A stream pool's address: one mapping for its readable run, shared by both of its views. if (resolve_pool_memory(va, bytes, out)) return true; if (readable_page(va)) { std::uint64_t lo = 0, hi = UINT64_MAX; aliases.gap(va, lo, hi); // never over a slot-133 buffer's range or another window lo = std::max(lo, title_lo); // nor past the title's range hi = std::min(hi, title_hi); leonida::TitleWindowRange range{}; if (leonida::title_window_range(va, want, lo, hi, kTitleWindowAlign, kTitleWindowMax, title_window_cap, title_window_bytes, range)) { if (const std::uint64_t offset = make_title_window(range.start, range.size)) { aliases.add(range.start, range.size, offset); out = offset + (va - range.start); return true; } } } // No window (the budget or the arena is full, or the page is not committed yet): the persistent geometry // copy backs the range instead, refreshed when its source pages change. A raw address never comes out of // this; when neither backing is available the view is written with no records. if (const std::uint64_t copy = geometry_va(va, want, false)) { aliases.add(va, want, copy); out = copy; return true; } out = 0; ++unbacked_requests; note_unbacked("title memory", va, bytes); return true; } // ---- Acceleration-structure addresses (XDXR builds, docs/d3d12_vulkan.md 4.8) ---- // A BuildRaytracingAccelerationStructure, CopyRaytracingAccelerationStructure or postbuild names its memory by the // title's GPU VAs, and the builder reaches each at heap_base + VA. A VA in the title's own memory (a slot-133 // buffer, or pages no resource covers: the retail title builds into its own heap) is past the arena, so heap_base // + VA is no allocation, and the first write of a build there lost the device (measured natively with Nsight // Aftermath: xdxr_build.comp MODE_INIT, an MMU write fault at heap_base + a title address). So every address goes // through the same resolver as the root views and V#s (src/title_va_alias.h): it becomes the VA of the memory's // GPU copy, and the copy must hold every byte the builder touches from it. An address that has no such copy is // refused, and the command is not recorded: nothing is written through it, and the destination keeps what it had. enum BvhField : unsigned { bvh_dst, bvh_scratch, bvh_source, bvh_instances, bvh_vertices, bvh_indices, bvh_transform, bvh_copy_dst, bvh_copy_src, bvh_postbuild_dst, bvh_postbuild_src, bvh_layout, bvh_field_count }; static constexpr const char* kBvhFieldNames[bvh_field_count] = { "destination", "scratch", "update source", "instance descs", "vertices", "indices", "transform", "copy destination", "copy source", "postbuild destination", "postbuild source", "instance pointer array"}; std::array, bvh_field_count> bvh_refused{}; std::atomic bvh_refused_total{0}, bvh_resolved_builds{0}, bvh_translated{0}; // Each structure's layout size by the title VA it was built at, so a copy of it knows how much to pull in. std::mutex bvh_size_mutex; std::map bvh_sizes; // The VA shaders reach [va, va + bytes) by, in `out`; `room` (when given) gets the bytes the copy has from `va` // on when it is one of the title's ranges, and 0 for an arena VA (the replay sizes it by its buffer). `gpu`: the // builder writes the bytes, or they are a structure it wrote (a destination, scratch, an update or copy source): // only the title-memory copies the GPU's writes stay in (a slot-133 import or shadow, a title window). Otherwise // they are inputs the title wrote (vertices, indices, a transform, instance descs), which a geometry copy can also // answer, as for a placed buffer view. False: no copy holds all of the bytes. // A persistent copy of exactly [va, va + bytes) from the title's pages, entered in the alias table, so a shader // or a build reaches the whole range by one address. A GPU-written structure (a BVH destination or its scratch) // keeps the GPU's writes in the copy: that is the only place the structure is read from afterwards, so the copy // is the structure. It is made even when a shorter range already maps the start: spreading a window's address over // bytes it does not cover would be a lie. 0 when geometry copies are off (LEONIDA_GEOMETRY_MB), their cap refuses // it, or the range is not the title's memory. std::uint64_t copy_title_range(std::uint64_t va, std::uint64_t bytes) { const std::uint64_t span = std::max(bytes, 1); auto& aliases = leonida::title_va_aliases(); std::uint64_t lo = 0, hi = 0; if (!geometry.cap() || !watch_shadow_writes() || !aliases.title_memory(va, lo, hi) || span > hi - va) return 0; const auto cpu = leonida::title_gpu_views::to_host_view(static_cast(va), static_cast(span)); if (context->knows_buffer_va(cpu, span)) return 0; const std::uint64_t copy = geometry.resolve(*this, cpu, span, copy_geometry); if (!copy) return 0; std::lock_guard lock(title_window_mutex); aliases.add(va, span, copy); return copy; } bool bvh_va(std::uint64_t va, std::uint64_t bytes, bool gpu, std::uint64_t& out, std::uint64_t* room = nullptr) { out = va; if (room) *room = 0; if (!va) return true; bytes = std::max(bytes, 1); if (va > UINT64_MAX - bytes) return false; auto& aliases = leonida::title_va_aliases(); if (!gpu) { if (const std::uint64_t copy = geometry_va(va, bytes, true)) { out = copy; if (room) *room = bytes; if (copy != va) bvh_translated.fetch_add(1, std::memory_order_relaxed); return true; } } const std::uint64_t to = aliases.resolve(va, bytes, leonida::TitleVaAliases::bvh_address); std::uint64_t shader = 0, available = 0; if (aliases.range_of(va, shader, available)) { // The range the address is in must be the one it was translated by, and reach past the last byte: a // window is at most kTitleWindowMax and stops at the next range, so a large structure can outrun it. if (shader == to && available >= bytes) { out = shader; if (room) *room = available; bvh_translated.fetch_add(1, std::memory_order_relaxed); return true; } } // No range holds all of it (no window at all after the budget ran out, or one that ends early): a copy of // the whole structure backs it, so the command is recorded and its destination or scratch is reachable. if (const std::uint64_t copy = copy_title_range(va, bytes)) { out = copy; if (room) *room = bytes; bvh_translated.fetch_add(1, std::memory_order_relaxed); return true; } if (to != va) return false; // Not in a range: an arena VA, or one of the layer's buffers outside the arena (an upload or readback heap, // whose VA is its device address minus heap_base). The title's own memory without a copy is neither. std::uint64_t lo = 0, hi = 0; if (aliases.title_memory(va, lo, hi)) return false; if (va + bytes <= arena.size) return true; return context && context->knows_buffer_va(va, bytes); } void bvh_refuse(BvhField field, std::uint64_t va, std::uint64_t bytes) { const std::uint64_t first = bvh_refused[field].fetch_add(1, std::memory_order_relaxed); const std::uint64_t total = bvh_refused_total.fetch_add(1, std::memory_order_relaxed) + 1; if (!first) std::fprintf(stderr, "[rt] d3d12: an acceleration-structure command was not recorded: its %s at 0x%llx (%llu " "bytes) has no GPU copy that holds all of it (title memory without a window, past " "LEONIDA_TITLE_WINDOWS_MB, a window that ends early, or no allocation); nothing is written " "through it\n", kBvhFieldNames[field], static_cast(va), static_cast(bytes)); if (total & (total - 1)) return; char counts[512]; int at = 0; for (unsigned f = 0; f < bvh_field_count && at < int(sizeof counts) - 64; ++f) if (const std::uint64_t n = bvh_refused[f].load(std::memory_order_relaxed)) at += std::snprintf(counts + at, sizeof counts - std::size_t(at), "%s%s %llu", at ? ", " : "", kBvhFieldNames[f], static_cast(n)); std::fprintf(stderr, "[rt] d3d12: %llu acceleration-structure commands not recorded for an unresolved address (%s); " "%llu builds resolved, %llu addresses translated to GPU copies\n", static_cast(total), counts, static_cast(bvh_resolved_builds.load(std::memory_order_relaxed)), static_cast(bvh_translated.load(std::memory_order_relaxed))); } void bvh_note_size(std::uint64_t title_va, std::uint64_t bytes) { if (!title_va || !bytes) return; std::lock_guard lock(bvh_size_mutex); if (bvh_sizes.size() >= (1u << 16)) bvh_sizes.clear(); // a guess only: it sizes a copy's window bvh_sizes[title_va] = bytes; } std::uint64_t bvh_known_size(std::uint64_t title_va) { std::lock_guard lock(bvh_size_mutex); const auto it = bvh_sizes.find(title_va); return it == bvh_sizes.end() ? 0 : it->second; } // BuildRaytracingAccelerationStructure: every address of `b` in place, or false (logged) when one has no copy. // Unchanged on a device that builds KHR structures (they are named by their resources' VAs) or none. bool resolve_xdxr_build(leonida::BuildAccelerationStructure& b) { if (!context || !context->xdxr_acceleration_structures()) return true; leonida::XdxrLayout layout; // A count the format cannot hold: left as it was, and refused when the list is prepared (xdxr_check). if (!layout.compute(leonida::VulkanContext::xdxr_elements(b), b.is_tlas, leonida::VulkanContext::xdxr_box16(b))) return true; const std::uint64_t title_dst = b.dst_va; std::uint64_t out = 0; // The destination holds the records the traversal shaders find by a 256-byte-unit address (an INSTANCE // record's BLAS, a BVH descriptor's base), so its copy must keep that alignment. if (!bvh_va(b.dst_va, layout.size, true, out) || (out & 255)) return bvh_refuse(bvh_dst, b.dst_va, layout.size), false; b.dst_va = out; // The other addresses keep the alignment D3D12 gives them too (CommandList checks it again). if (!bvh_va(b.scratch_va, layout.scratch, true, out) || (out & 255)) return bvh_refuse(bvh_scratch, b.scratch_va, layout.scratch), false; b.scratch_va = out; if (b.update && b.src_va) { if (b.src_va == title_dst) { b.src_va = b.dst_va; } else { if (!bvh_va(b.src_va, layout.size, true, out) || (out & 255)) return bvh_refuse(bvh_source, b.src_va, layout.size), false; b.src_va = out; } } if (b.is_tlas) { // The builder reads 64-byte descs one after another (xdxr_build.comp MODE_INSTANCES); a pointer array // would be read as descs, past its end. if (b.instance_count && b.instance_pointers) return bvh_refuse(bvh_layout, b.instances_va, 8ull * b.instance_count), false; if (b.instance_count) { if (!bvh_va(b.instances_va, 64ull * b.instance_count, false, out)) return bvh_refuse(bvh_instances, b.instances_va, 64ull * b.instance_count), false; b.instances_va = out; } } else { for (auto& t : b.triangles) { const std::uint64_t triangles = (t.index_type ? t.index_count : t.vertex_count) / 3; if (!triangles) continue; // Unindexed: three vertices a triangle. Indexed: the VertexCount the title declared (indices past // it read past the buffer, as on the console). const std::uint64_t vertices = t.index_type ? t.vertex_count : 3 * triangles; const std::uint64_t element = t.vertex_format == VK_FORMAT_R32G32_SFLOAT ? 8 : 12; const std::uint64_t vertex_bytes = vertices ? (vertices - 1) * t.vertex_stride + element : 0; if (vertex_bytes && !bvh_va(t.vertex_va, vertex_bytes, false, out)) return bvh_refuse(bvh_vertices, t.vertex_va, vertex_bytes), false; t.vertex_va = out; if (t.index_type && t.index_va) { const std::uint64_t index_bytes = 3 * triangles * (t.index_type == 1 ? 2 : 4); if (!bvh_va(t.index_va, index_bytes, false, out)) return bvh_refuse(bvh_indices, t.index_va, index_bytes), false; t.index_va = out; } if (t.transform_va) { if (!bvh_va(t.transform_va, 48, false, out)) return bvh_refuse(bvh_transform, t.transform_va, 48), false; t.transform_va = out; } } } bvh_note_size(title_dst, layout.size); bvh_resolved_builds.fetch_add(1, std::memory_order_relaxed); return true; } // CopyRaytracingAccelerationStructure: both addresses, with the room their copies have (the replay bounds the // copy by it). The source's size comes from its build when the layer saw it, else from its header only. bool resolve_xdxr_copy(leonida::CopyAccelerationStructure& c) { if (!context || !context->xdxr_acceleration_structures()) return true; const std::uint64_t known = bvh_known_size(c.src_va); const std::uint64_t want = known ? known : leonida::XdxrLayout::header_size; const std::uint64_t title_dst = c.dst_va; std::uint64_t out = 0, room = 0; if (!bvh_va(c.src_va, want, true, out, &room) || (out & 255)) return bvh_refuse(bvh_copy_src, c.src_va, want), false; c.src_va = out; c.src_room = room; if (!bvh_va(c.dst_va, want, true, out, &room) || (out & 255)) return bvh_refuse(bvh_copy_dst, c.dst_va, want), false; c.dst_va = out; c.dst_room = room; if (known) bvh_note_size(title_dst, known); return true; } // A postbuild: its destination (8 bytes a source) and each source structure's header, which it reads. bool resolve_xdxr_postbuild(leonida::AccelerationStructurePostbuild& info) { if (!context || !context->xdxr_acceleration_structures()) return true; std::uint64_t out = 0, room = 0; const std::uint64_t bytes = 8ull * info.sources.size(); if (!bvh_va(info.dest_va, bytes, true, out, &room) || (out & 7)) return bvh_refuse(bvh_postbuild_dst, info.dest_va, bytes), false; info.dest_va = out; info.dest_room = room; for (auto& source : info.sources) { if (!bvh_va(source, leonida::XdxrLayout::header_size, true, out) || (out & 255)) return bvh_refuse(bvh_postbuild_src, source, leonida::XdxrLayout::header_size), false; source = out; } return true; } // The console's value writes (list slots 71 and 72) whose address is an arena offset: a default-heap buffer. // The arena is host-visible, so its host mapping holds the bytes the GPU reads. As in resolve_title_memory, an // address below the arena's size is an arena address unless the title's own memory is there (arena_allocate // keeps out of those ranges); an arena address is never stored to as a host address, so it is the arena's // whether or not it can be written here (src/value_write_sink.h). Below the first offset the arena hands out are // the null region, the zero page and the quad indices, which shaders read: a value there is refused, as is one // past the end. leonida::value_sink::Landing write_arena_value(std::uint64_t va, const void* bytes, unsigned size) { using leonida::value_sink::Landing; if (!arena.mapped || va >= arena.size) return Landing::elsewhere; std::uint64_t title_lo = 0, title_hi = 0; if (leonida::title_va_aliases().title_memory(va, title_lo, title_hi)) return Landing::elsewhere; if (!bytes || !size || va < arena.first || size > arena.size - va) return Landing::refused; // A sparse resource's memory is bound by the sparse pass, not by the arena's mapping. if (context && context->is_sparse_va(va)) return Landing::refused; // An aligned value in one store, so a reader never sees half of it. if (size == 4 && !(va & 3)) std::atomic_ref(*reinterpret_cast(arena.mapped + va)) .store(*static_cast(bytes), std::memory_order_relaxed); else if (size == 8 && !(va & 7)) std::atomic_ref(*reinterpret_cast(arena.mapped + va)) .store(*static_cast(bytes), std::memory_order_relaxed); else std::memcpy(arena.mapped + va, bytes, size); return Landing::landed; } struct ShaderVisibleHeap { VkDeviceSize end; D3D12_DESCRIPTOR_HEAP_TYPE type; }; std::mutex visible_heap_mutex; std::map visible_heaps; std::map cpu_view_heaps; bool known_view_heap(std::uintptr_t addr) { std::lock_guard lock(visible_heap_mutex); const auto mapped = reinterpret_cast(arena.mapped); if (mapped && addr >= mapped && addr - mapped < arena.size) { const auto off = addr-mapped; auto visible = visible_heaps.upper_bound(off); if (visible != visible_heaps.begin()) { --visible; if (visible->second.type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV && off < visible->second.end && (off-visible->first)%kDescriptorSize==0) return true; } } auto it = cpu_view_heaps.upper_bound(addr); if (it == cpu_view_heaps.begin()) return false; --it; return addr < it->second && (addr-it->first) % kDescriptorSize == 0; } // The shader-visible CBV/SRV/UAV heaps (arena offset -> end), for the scan of bound tables before a submission. std::mutex cbv_heap_mutex; std::map cbv_heaps; // The buffer V#s of the table at `table_va` whose base is in the title's own memory get the address of a copy, // written in place: the title wrote them itself (or copied them), so no Create*View saw them. Images (T#s) and // null slots are skipped; so is a V# already in the arena, so a rewritten one is left alone next time. void scan_title_table(std::uint64_t table_va, std::uint32_t descriptors) { probe_table(table_va, descriptors); // LOCAL DIAGNOSTIC VkDeviceSize end = 0; bool sampler = false; { std::lock_guard lock(visible_heap_mutex); auto it = visible_heaps.upper_bound(table_va); if (it == visible_heaps.begin()) return; --it; const auto& heap = it->second; if (table_va >= heap.end || (table_va - it->first) % kDescriptorSize != 0) return; sampler = heap.type == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER; const auto slots = sampler ? descriptors : std::min(descriptors, kViewScanLimit); end = table_va + std::min(heap.end - table_va, VkDeviceSize(slots) * kDescriptorSize); } auto& aliases = leonida::title_va_aliases(); // Slots the title wrote in its own backing of this heap, if it gave the heap one. aliases.pull_descriptors(arena.mapped + table_va, std::size_t(end - table_va)); if (sampler) return; // S# words describe sampling state. They have no buffer address to translate. // Each slot's V# and the counter V# in its second half, as a console heap's GPU copy (fix_vsharp): a base in // the title's memory is rebased, one nothing backs becomes zero-size instead of a GPU fault at heap_base plus // that address. for (VkDeviceSize at = table_va; at + kDescriptorSize <= end; at += kDescriptorSize) { auto* const w = reinterpret_cast(arena.mapped + at); fix_vsharp(w, VsharpPath::table); fix_vsharp(w + 4, VsharpPath::table); } } // A buffer V# (its first four dwords at `w`) whose base is in the title's own memory gets the console VA of a GPU // copy of that memory, in place. False for anything else: a null slot, an image, a V# already in the arena, or // memory no copy could be made of. bool rebase_title_vsharp(std::uint32_t* w, leonida::TitleVaAliases& aliases, bool make_window = true) { const std::uint32_t w0 = w[0], w1 = w[1], w2 = w[2], w3 = w[3]; if (!(w0 | w1 | w2 | w3) || (w3 >> 30)) return false; // null, or not a buffer V# (TYPE, dword 3 bits 30-31) const std::uint64_t base = std::uint64_t(w0) | (std::uint64_t(w1 & 0xFFFFu) << 32); std::uint64_t host{}, remaining{}; if (base < arena.size || (geometry.cap() && geometry.lookup(arena.address + base, host, remaining))) return false; const std::uint32_t stride = (w1 >> 16) & 0x3FFFu; const std::uint64_t span = std::uint64_t(w2) * (stride ? stride : 1); std::uint64_t to{}; if (geometry.cap()) { const leonida::gfx10::BufferWords words{w0, w1, w2, w3}; leonida::gfx10::Buffer desc{}; if (leonida::gfx10::decode(words, desc)) { // Untyped heap slots can contain ordinary pointers or other data. Large extents with // no format or fields outside our buffer encoding need independent evidence of a view. // An explicit table or a placed SRV can still establish the backing for those words. if (!make_window && span > kTitleWindowMax && (!desc.format || leonida::gfx10::encode(desc) != words)) { to = geometry.find(leonida::title_gpu_views::to_cpu(base, span), span); if (!to) return false; } else { to = geometry_va(base, span, false); } } } // A heap scan sees free-list links, raw data and inactive slots. Only explicit bindings may // request general-purpose windows. The heap can reuse an existing one or make a geometry mirror. if (!to) to = make_window ? aliases.resolve(base, span, leonida::TitleVaAliases::table_view) : aliases.shader_va(base, span); if (to == base || (to >> 48)) return false; w[0] = std::uint32_t(to); w[1] = (w1 & 0xFFFF0000u) | std::uint32_t((to >> 32) & 0xFFFFu); return true; } // Indexed by actual Vulkan address, never by a placed buffer's CPU address. std::atomic released_backings{}; std::mutex backing_mutex; leonida::BufferVaIndex gpu_backings; void backing(VkDeviceAddress address, uint64_t bytes, uint64_t id, bool add) { std::lock_guard lock(backing_mutex); if (add) gpu_backings.insert(address, bytes, id); else { gpu_backings.erase(address, id); released_backings.fetch_add(1, std::memory_order_release); } } enum class VsharpPath { table, shadow, scratch }; enum class VsharpResult { unchanged, rebased, empty }; uint64_t vsharp_address(uint64_t base, uint64_t bytes, leonida::TitleVaAliases::Kind kind = leonida::TitleVaAliases::created_view, bool make_window = true, bool try_geometry = false) { if (!base || !bytes) return 0; auto& aliases = leonida::title_va_aliases(); constexpr uint64_t mask = (1ull << 48) - 1; // A negative offset (a buffer of the layer's that the driver put below the arena) fits the 48 bits as the // translated shaders read them, sign-extended (docs/design.md, "Heap-relative buffer device addresses"); only // a buffer registered in gpu_backings or the geometry copies is ever accepted, so LEONIDA_IMPORT_BELOW_ARENA // still decides alone whether title memory is imported there. const auto encodable = [&](uint64_t offset) { const uint64_t limit = signed_vsharp_offsets() ? mask / 2 : mask; if (offset <= limit) return bytes - 1 <= limit - offset; return offset >= UINT64_MAX - mask / 2 && bytes - 1 <= mask / 2 - offset; // unsigned distance across zero }; const auto backed = [&](uint64_t offset) { if (!encodable(offset)) return false; const auto bda = arena.address + offset; { std::lock_guard lock(backing_mutex); if (gpu_backings.covers(bda, bytes)) return true; } uint64_t host{}, room{}; return geometry.cap() && geometry.lookup(bda, host, room) && room >= bytes; }; uint64_t to{}, room{}; if (aliases.range_of(base, to, room)) { if (!to || room < bytes || !backed(to)) return 0; aliases.note_translation(kind); return to; } // An already rewritten descriptor carries only the low 48 bits. uint64_t offset = base; if (signed_vsharp_offsets() && base <= mask && (base & (1ull << 47))) offset |= ~mask; if (backed(offset)) return offset; // Read the other way: bit 47 as a sign, for a below-arena buffer's V# the layer wrote itself. if (offset == base && base <= mask && (base & (1ull << 47)) && backed(base | ~mask)) return base | ~mask; if (try_geometry) { to = geometry_va(base, bytes, false); if (to && encodable(to)) return to; } uint64_t lo{}, hi{}; if (make_window && aliases.title_memory(base, lo, hi) && bytes <= hi - base) { to = aliases.resolve(base, bytes, kind); uint64_t mapped{}; if (to && aliases.range_of(base, mapped, room) && mapped == to && room >= bytes && backed(to)) return to; } return 0; } VsharpResult fix_vsharp(uint32_t* w, VsharpPath path) { if ((w[3] >> 30) || !w[2]) return VsharpResult::unchanged; // image, empty slot or raw pointer const uint64_t base = uint64_t(w[0]) | (uint64_t(w[1] & 0xffff) << 32); const uint32_t stride = (w[1] >> 16) & 0x3fffu; const uint64_t span = uint64_t(w[2]) * (stride ? stride : 1); const leonida::gfx10::BufferWords words{w[0], w[1], w[2], w[3]}; leonida::gfx10::Buffer desc{}; const bool copy_geometry = leonida::gfx10::decode(words, desc) && (path != VsharpPath::scratch || span <= kTitleWindowMax || (desc.format && leonida::gfx10::encode(desc) == words)); const auto to = vsharp_address(base, span, leonida::TitleVaAliases::table_view, path != VsharpPath::scratch, copy_geometry); if (!to) { static std::atomic_flag noted[3]{}; if (!noted[unsigned(path)].test_and_set(std::memory_order_relaxed)) { const char* where = path == VsharpPath::table ? "inline table" : path == VsharpPath::shadow ? "console shadow" : "console scratch"; std::fprintf(stderr, "[rt] d3d12: %s V# at 0x%llx (%llu bytes) has no GPU backing; zero records\n", where, (unsigned long long)base, (unsigned long long)span); } w[0] = w[1] = w[2] = 0; return VsharpResult::empty; } if ((to & ((1ull << 48) - 1)) == base) return VsharpResult::unchanged; w[0] = uint32_t(to); w[1] = (w[1] & 0xffff0000u) | uint32_t((to >> 32) & 0xffff); return VsharpResult::rebased; } // WriteToSubresource/ReadFromSubresource without host image copy: one staging copy at a time, submitted to // the device's VkQueue and waited for. Created on first use. rt::d3d12::TitleImageUpload title_upload; // accessed with title_upload_mutex held std::mutex title_upload_mutex; // after title_texture_mutex when both are taken (the fill worker takes it alone) std::mutex staging_mutex; std::unique_ptr staging_queue; // The GPU address arena (docs/d3d12_vulkan.md section 3.3): one host-visible, device-addressable VkBuffer that // stands in for the console's GPU address space. A console VA is an offset in it, and heap_base (push-constant // dwords 32-33) is its device address. It is at most 4 GiB, so every VA fits the 32-bit descriptor-table // pointers some shaders use, and no larger than the device's maxBufferSize and maxMemoryAllocationSize // (src/arena_size.h). The first 64 KiB are never handed out, so no resource has VA 0. struct Arena { VkBuffer buffer = VK_NULL_HANDLE; bool indirect_arguments = false; VkDeviceMemory memory = VK_NULL_HANDLE; std::uint8_t* mapped = nullptr; VkDeviceAddress address = 0; VkDeviceSize size = 0; VkDeviceSize first = 0; // the first offset handed out: below it are the null region and kArenaReserved std::uint32_t memory_type = 0; std::mutex mutex; leonida::ArenaBlocks blocks; // offset -> size, guarded by mutex (src/arena_blocks.h) // Diagnostics: a fault line is rate-limited, and the full block walk runs only on a fault or LEONIDA_ARENA_CHECK=1. ULONGLONG fault_report_ms = 0; std::uint64_t faults_suppressed = 0; bool check_all = false; // The high-water mark (D3D-55, open question 5): the arena's size is a guess until a run measures it. // `peak_end` is the highest end offset ever handed out, the size the arena must have; `peak_in_use` is the // most bytes live at once, which differs from it by fragmentation. bool log = false; // LEONIDA_ARENA_LOG=1: one line per VA handed out VkDeviceSize in_use = 0, peak_in_use = 0, peak_end = 0; VkDeviceSize use_in_use[4] = {}, use_peak[4] = {}; std::uint64_t allocations = 0, failures = 0; } arena; std::uint32_t sparse_buffer_memory_types = 0; bool sparse_image_tiles = false; bool tiles_share_arena() const { return (sparse_buffer_memory_types & (1u << arena.memory_type)) != 0; } VkBufferCreateInfo sparse_buffer_info(VkDeviceSize bytes) const { VkBufferCreateInfo result{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; result.size = bytes; result.flags = VK_BUFFER_CREATE_SPARSE_BINDING_BIT | VK_BUFFER_CREATE_SPARSE_RESIDENCY_BIT | VK_BUFFER_CREATE_SPARSE_ALIASED_BIT; result.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; if (info.conditional_rendering) result.usage |= VK_BUFFER_USAGE_CONDITIONAL_RENDERING_BIT_EXT; // D3D12 reserved buffers are visible to DIRECT, COPY and COMPUTE queues without exposing Vulkan // queue-family ownership. Their tile bindings and accesses may use distinct families, so match the // CONCURRENT sharing policy used for ordinary buffers and the GPU address arena. share(result); return result; } // What an arena range holds, for the high-water report (D3D-55). enum ArenaUse { arena_buffer, arena_descriptor_heap, arena_shader, arena_heap }; static constexpr const char* kArenaUseNames[4] = {"buffer", "descriptor heap", "shader", "heap"}; // A fault line about the arena is rate-limited to this interval: the walk behind it costs a pass over every // free block, and a persistent fault would otherwise print on every allocation of a streaming frame. static constexpr ULONGLONG kArenaReportMs = 5000; // One arena line per interval, so a fault that persists does not flood the log and a second, different fault // still gets its own line later (a one-shot flag would have hidden it). The count of suppressed lines is // printed with the next one. bool arena_report_due() { const ULONGLONG now = GetTickCount64(); if (arena.fault_report_ms && now - arena.fault_report_ms < kArenaReportMs) { ++arena.faults_suppressed; return false; } arena.fault_report_ms = now; return true; } void arena_report_suppressed(const char* what) { if (!arena.faults_suppressed) return; std::fprintf(stderr, "[rt] d3d12: GPU address arena: %llu earlier line(s) about %s were rate-limited\n", static_cast(arena.faults_suppressed), what); arena.faults_suppressed = 0; } // The free bytes and the live bytes must add up to the arena: a range released twice, or released without ever // having been allocated, breaks it. That check is O(1) and runs on every call; the whole block map is walked // only when it fails or LEONIDA_ARENA_CHECK=1 asks for it, since a walk costs a pass over every free block. void check_arena(const char* what) { const bool consistent = arena.blocks.consistent(arena.in_use); if (consistent && !arena.check_all) return; const auto fault = arena.blocks.check(); if (fault == leonida::ArenaBlocks::Fault::none && consistent) return; if (!arena_report_due()) return; const char* why = fault != leonida::ArenaBlocks::Fault::none ? leonida::ArenaBlocks::kFaultNames[static_cast(fault)] : "free + live does not add up to the arena"; std::fprintf(stderr, "[rt] d3d12: GPU address arena: %s left %llu KiB free and %llu KiB live of %llu the arena has " "minus %llu reserved (%s; %zu free blocks, %llu faults so far)\n", what, static_cast(arena.blocks.free_bytes() >> 10), static_cast(arena.in_use >> 10), static_cast(arena.size >> 10), static_cast(arena.blocks.reserved() >> 10), why, arena.blocks.count(), static_cast(arena.blocks.faults())); arena_report_suppressed(what); } // A zero-size range is refused: it would share its offset with the next range, and its release would collide // with that range's free entry. The fit test cannot wrap: free blocks lie inside the arena (below 4 GiB). bool arena_allocate(VkDeviceSize bytes, VkDeviceSize alignment, VkDeviceSize& out, ArenaUse use) { if (!bytes || bytes > arena.size) return false; std::lock_guard lock(arena.mutex); // Not over a range of the title's own memory: the title's heap can lie below the arena's size, and a view // that names an address there must mean the title's bytes (TitleVaAliases::want_buffer). The walk holds no // iterator across this call, so a cut made under it cannot invalidate it (src/arena_blocks.h). const bool found = arena.blocks.allocate( bytes, alignment, [](std::uint64_t lo, std::uint64_t hi) { return leonida::title_va_aliases().title_overlap_end(lo, hi); }, out); if (!found) { ++arena.failures; if (arena.log) std::fprintf(stderr, "[rt] d3d12: arena %s: no room for 0x%llx bytes\n", kArenaUseNames[use], (unsigned long long)bytes); // The search restarted to its limit: say so, since the request may have been refusable anyway. if (arena.blocks.interrupted() && arena_report_due()) std::fprintf(stderr, "[rt] d3d12: GPU address arena: the block map was cut under a search %d times; " "a %llu KiB request was refused (live %llu KiB, free %llu KiB)\n", leonida::ArenaBlocks::kAttempts, static_cast(bytes >> 10), static_cast(arena.in_use >> 10), static_cast(arena.blocks.free_bytes() >> 10)); return false; } backing(arena.address + out, bytes, out, true); ++arena.allocations; arena.in_use += bytes; arena.peak_in_use = std::max(arena.peak_in_use, arena.in_use); arena.peak_end = std::max(arena.peak_end, out + bytes); arena.use_in_use[use] += bytes; arena.use_peak[use] = std::max(arena.use_peak[use], arena.use_in_use[use]); if (arena.log) std::fprintf(stderr, "[rt] d3d12: arena %s VA 0x%llx + 0x%llx\n", kArenaUseNames[use], (unsigned long long)out, (unsigned long long)bytes); check_arena("an allocation"); return true; } // A console VA outside the arena (an upload or readback buffer: its device address minus heap_base). void log_va(const char* what, std::uint64_t va, VkDeviceSize bytes) { if (arena.log) std::fprintf(stderr, "[rt] d3d12: %s VA 0x%llx + 0x%llx (outside the arena)\n", what, (unsigned long long)va, (unsigned long long)bytes); } // Printed once at device release, so a run reports the size the arena needs. void report_arena() { std::lock_guard lock(arena.mutex); if (!arena.size) return; const double mib = 1.0 / (1 << 20); std::fprintf(stderr, "[rt] d3d12: GPU address arena: peak end %.1f of %.1f MiB (%.1f%%), peak live %.1f MiB " "(buffers %.1f, descriptor heaps %.1f, shaders %.1f, heaps %.1f), %llu allocations, %llu refused; " "%zu free blocks (largest %.1f MiB, %.1f MiB free)\n", arena.peak_end * mib, arena.size * mib, 100.0 * double(arena.peak_end) / double(arena.size), arena.peak_in_use * mib, arena.use_peak[arena_buffer] * mib, arena.use_peak[arena_descriptor_heap] * mib, arena.use_peak[arena_shader] * mib, arena.use_peak[arena_heap] * mib, (unsigned long long)arena.allocations, (unsigned long long)arena.failures, arena.blocks.count(), arena.blocks.largest().size * mib, arena.blocks.free_bytes() * mib); { std::lock_guard windows(title_window_mutex); const auto geometry_spans = std::count_if(pool_spans.begin(), pool_spans.end(), [](const PoolSpan& span) { return span.geometry; }); std::fprintf(stderr, "[rt] d3d12: title memory: %zu windows (%llu KiB of a %llu MiB budget, %llu refused), %zu " "stream-pool extents (one mapping each, %llu KiB; %lld by geometry copy), %llu addresses " "given a zero-size view\n", title_windows.size(), static_cast(title_window_bytes >> 10), static_cast(title_window_cap >> 20), static_cast(title_window_refusals), pool_spans.size(), static_cast(pool_span_bytes >> 10), static_cast(geometry_spans), static_cast(unbacked_requests)); } } void arena_release(VkDeviceSize offset, VkDeviceSize bytes, ArenaUse use) { if (!bytes) return; std::lock_guard lock(arena.mutex); // The range is validated and merged before the live-byte counters move: a release of a range the arena never // had must not change them, and a double free must not count the bytes twice. const auto fault = arena.blocks.release(offset, bytes); if (fault != leonida::ArenaBlocks::Fault::outside_arena) { backing(arena.address + offset, bytes, offset, false); arena.in_use -= bytes; arena.use_in_use[use] -= bytes; } if (fault != leonida::ArenaBlocks::Fault::none && arena_report_due()) { std::fprintf(stderr, "[rt] d3d12: GPU address arena: %s at VA 0x%llx + 0x%llx (live %llu KiB, free %llu KiB, " "%llu faults so far)\n", leonida::ArenaBlocks::kFaultNames[static_cast(fault)], static_cast(offset), static_cast(bytes), static_cast(arena.in_use >> 10), static_cast(arena.blocks.free_bytes() >> 10), static_cast(arena.blocks.faults())); arena_report_suppressed("arena releases"); } check_arena("a release"); } // Console descriptor heaps (Xbox slot 14, docs/d3d12_vulkan.md section 3.4). The title gives the heap's address // itself: memory of its own, at a console VA the shaders would reach as heap_base + VA, past the arena. It fills // the heap through Create*View and CopyDescriptors, and also by writing 32-byte descriptor records into that // memory itself and copying them with its own memcpy, which no API call sees. So shaders must read the title's // pages, not a copy the API keeps. Two ways, in this order: // - import: the heap's pages are imported as host memory (VK_EXT_external_memory_host, as a slot-133 buffer // on the title's pages is), so the GPU reads them as they are, with no copy. Shaders reach them at the // import's device address minus heap_base, which must stay below 4 GiB: most shaders keep only 32 bits of a // descriptor-table pointer (section 3.3). The title's own records are then read as written; T#s among them // that no Create*View registered are found by a scan that walks a part of the heap before every submission; // - copy: an arena range of the heap's size (at the console VA itself when the arena reaches that far), brought // up to date before every submission from the pages the title wrote since the last one (ShadowPages, the // slot-133 shadow's tracker); each slot copied is fixed up: a buffer V# whose base is the title's memory gets // the console VA of a GPU copy (rebase_title_vsharp), and an unregistered T# is bound (bind_title_image). // The tracker copies into a host mirror of the title's bytes, and only the slots whose bytes differ from what // their arena slot was made from (a second host copy) are fixed and written there again; a T# that found no // texture and a V# into title memory with no copy yet are tried at every submission until they do. Pages xmem // maps at two addresses are copied at every submission, and fixing all their slots each time, reading the // arena (uncached device memory) to do it, cost more than a frame (295 ms a submission for the 4 MiB of the // retail heap in use, RTX 4070 Ti). // A copy must not watch pages another import pins (a slot-133 buffer placed over the heap, as the retail // title does): it is only the fallback. // Descriptor tables bound at a console VA inside the heap, and the heap's base for SetDescriptorHeaps, are moved // to where shaders read it (console_heap_ranges). The copy is one way, as for slot 133. struct FreeConsoleScratch { void operator()(std::uint8_t* p) const { VirtualFree(p, 0, MEM_RELEASE); } }; struct ConsoleHeap { std::uint64_t console_va = 0; VkDeviceSize bytes = 0; std::uint64_t shader_va = 0; // where shaders read it VkDeviceSize guard = 0; bool resource_heap = false; bool imported = false; std::uint8_t* copy = nullptr; // writable GPU mirror of the console heap // Keep large scratch allocations out of the low addresses the title can use for its heap. std::unique_ptr scratch; std::uint8_t* input{}; std::uint8_t* previous{}; // import VkBuffer buffer = VK_NULL_HANDLE; VkDeviceMemory memory = VK_NULL_HANDLE; std::uint64_t pin = 0; // the imported pages' leonida::kernel_writes pin while `memory` lives std::size_t scan_at = 0; // the next slot the T# scan reads uint64_t checked_generation{}, alias_generation{}; // copy bool identity = false; ShadowPagesPtr pages; std::vector mirror; // the title's bytes as the tracker last copied them std::vector made; // the title's bytes each arena slot was last made from std::vector retry; // per slot: not settled yet (fix_console_slot), in `retries` leonida::ConsoleHeapVsharpSlots live_vsharps; // slots whose GPU copy holds a live buffer V# std::vector retries; std::set empty_slots; std::uint32_t next_empty = 0; std::size_t retry_at = 0; // where retry_console_slots goes on // fix_console_slots' budget, for the current refresh, and the slots it nulled since the last log line std::chrono::steady_clock::time_point fix_start{}; bool fix_over = false; std::uint32_t fix_count = 0; std::uint64_t deferred_fixes = 0; std::uint64_t refreshes = 0, logged = 0; std::chrono::steady_clock::time_point log_time{}; // Since the last log line. std::uint64_t copied = 0, vsharps = 0, unbacked = 0, retried = 0; std::uint64_t images[5] = {}; // by TitleImage std::map refused_reasons; double ms = 0, pages_ms = 0, fix_ms = 0, retry_ms = 0; // ms: all; the others its parts }; std::mutex console_heap_mutex; // taken before title_window_mutex, shadow_mutex and descriptor_mutex std::vector> console_heaps; static constexpr VkDeviceSize kHeapIndexReach = VkDeviceSize(1) << 26; // 2^21 slots of 32 bytes static VkDeviceSize heap_guard_bytes() { static const VkDeviceSize bytes = [] { char text[16] = {}; const DWORD n = GetEnvironmentVariableA("LEONIDA_HEAP_GUARD_MB", text, sizeof(text)); if (n == 0 || n >= sizeof(text)) return kHeapIndexReach; return VkDeviceSize(std::min(std::strtoull(text, nullptr, 10), 1024)) << 20; }(); return bytes; } // [start, start + bytes) of the arena, exactly. False when any of it is taken or past the arena. bool arena_allocate_at(VkDeviceSize start, VkDeviceSize bytes, ArenaUse use) { if (!bytes || start > arena.size || bytes > arena.size - start) return false; std::lock_guard lock(arena.mutex); if (!arena.blocks.allocate_at(start, bytes)) return false; backing(arena.address + start, bytes, start, true); ++arena.allocations; arena.in_use += bytes; arena.peak_in_use = std::max(arena.peak_in_use, arena.in_use); arena.peak_end = std::max(arena.peak_end, start + bytes); arena.use_in_use[use] += bytes; arena.use_peak[use] = std::max(arena.use_peak[use], arena.use_in_use[use]); return true; } // Slot `slot` of a heap copy, as the title wrote it, fixed up as described above. True when it is settled: not a // T# whose texture is still to come, nor a V# into the title's memory that got no copy. bool fix_console_slot(ConsoleHeap& heap, std::size_t slot) { std::uint32_t w[kDescriptorSize / 4]; std::memcpy(w, heap.previous + slot * kDescriptorSize, kDescriptorSize); bool settled = true, empty = false; if (!(w[3] >> 30)) { const auto path = heap.scratch ? VsharpPath::scratch : VsharpPath::shadow; const auto result = fix_vsharp(w, path); const auto counter = fix_vsharp(w + 4, path); if (result == VsharpResult::rebased) ++heap.vsharps; if (result == VsharpResult::empty || counter == VsharpResult::empty) { ++heap.unbacked; empty = true; } } else { leonida::gfx10::ImageWords words; std::memcpy(words.data(), w, sizeof(words)); if (leonida::gfx10::is_image(words)) { const char* why = nullptr; const TitleImage result = bind_title_image(*this, words, &why); if (result == TitleImage::unknown || result == TitleImage::refused) { note_refused_tsharp(heap, slot * kDescriptorSize, words, why); if (result == TitleImage::refused) ++heap.refused_reasons[why ? why : "?"]; } ++heap.images[unsigned(result)]; settled = result != TitleImage::unknown && result != TitleImage::refused; if (result == TitleImage::not_tsharp) std::memset(w, 0, 16); } else { ++heap.images[unsigned(TitleImage::not_tsharp)]; std::memset(w, 0, 16); } } if (empty) heap.empty_slots.insert(std::uint32_t(slot)); else if (!heap.empty_slots.empty()) heap.empty_slots.erase(std::uint32_t(slot)); std::memcpy(heap.copy + slot * kDescriptorSize, w, kDescriptorSize); heap.live_vsharps.set(slot, leonida::ConsoleHeapVsharpSlots::is_live_vsharp(w)); return settled; } // The slots on [offset, offset + bytes) of a heap copy's mirror, just brought up to date: each that differs from // what its arena slot was made from is written there and fixed up. // LEONIDA_CONSOLE_FIX_US limits the fixing in one submission (0, the default: no limit). Past it a changed slot is // written as a null descriptor and left to retry_console_slots: after the story load the title rewrote up to // 3.7 MiB of its heap at once and one submission spent 28 s fixing it (speed-8). A shader reads such a slot as // empty until its turn comes, so a limit changes results: at the first world frame lib_cs_01144 read the size it // divides by from a nulled buffer slot and its loops never ended, which lost the device. void fix_console_slots(ConsoleHeap& heap, std::size_t offset, std::size_t bytes) { static const std::uint64_t budget_us = [] { char text[16] = {}; const DWORD n = GetEnvironmentVariableA("LEONIDA_CONSOLE_FIX_US", text, sizeof(text)); return n > 0 && n < sizeof(text) ? std::strtoull(text, nullptr, 10) : 0ull; }(); const std::size_t end = std::min(offset + bytes, std::size_t(heap.bytes)); if (!heap.resource_heap) { std::memcpy(heap.copy + offset, heap.input + offset, end - offset); return; } for (std::size_t at = offset & ~std::size_t(kDescriptorSize - 1); at + kDescriptorSize <= end; at += kDescriptorSize) { const std::size_t slot = at / kDescriptorSize; if (!std::memcmp(heap.previous + at, heap.input + at, kDescriptorSize)) continue; std::memcpy(heap.previous + at, heap.input + at, kDescriptorSize); if (budget_us && !heap.fix_over && !(++heap.fix_count & 15) && std::chrono::steady_clock::now() - heap.fix_start >= std::chrono::microseconds(budget_us)) heap.fix_over = true; if (heap.fix_over) { std::memset(heap.copy + at, 0, kDescriptorSize); heap.live_vsharps.clear(slot); ++heap.deferred_fixes; if (!heap.retry[slot]) { heap.retry[slot] = 1; heap.retries.push_back(std::uint32_t(slot)); } continue; } if (fix_console_slot(heap, slot)) { heap.retry[slot] = 0; } else if (!heap.retry[slot]) { heap.retry[slot] = 1; heap.retries.push_back(std::uint32_t(slot)); } } } // The slots of a heap copy not settled yet: fixed again, and kept while they are still not. Round robin, for at // most LEONIDA_CONSOLE_RETRY_US a submission (500 by default, 0: all of them every time): during the story load // thousands of T#s name textures that come much later, and trying them all at every submission cost hundreds of // milliseconds each. One not reached waits a few submissions more for its texture. void retry_console_slots(ConsoleHeap& heap) { static const std::uint64_t budget_us = [] { char text[16] = {}; const DWORD n = GetEnvironmentVariableA("LEONIDA_CONSOLE_RETRY_US", text, sizeof(text)); return n > 0 && n < sizeof(text) ? std::strtoull(text, nullptr, 10) : 500ull; }(); const auto start = std::chrono::steady_clock::now(); std::size_t i = heap.retry_at, visited = 0; const std::size_t total = heap.retries.size(); while (visited < total && !heap.retries.empty()) { if (i >= heap.retries.size()) i = 0; const std::uint32_t slot = heap.retries[i]; ++visited; // Rewritten or zeroed since, or settled now: out of the list (the last one takes its place, seen later). const bool settled = !heap.retry[slot] || fix_console_slot(heap, slot); if (settled) { heap.retry[slot] = 0; heap.retries[i] = heap.retries.back(); heap.retries.pop_back(); } else { ++i; } if (budget_us && !(visited & 31) && std::chrono::steady_clock::now() - start >= std::chrono::microseconds(budget_us)) break; } heap.retry_at = i; heap.retried += visited; } void note_refused_tsharp(ConsoleHeap& heap, std::size_t offset, const leonida::gfx10::ImageWords& words, const char* why) { unbound_tsharp_tracker().note(heap.console_va, offset, words, why); } void refresh_console_heap(ConsoleHeap& heap) { // console_heap_mutex held if (heap.imported) return; // directly imported sampler heap using clock = std::chrono::steady_clock; const auto ms = [](clock::time_point a, clock::time_point b) { return std::chrono::duration(b - a).count(); }; const auto t0 = clock::now(); heap.copied += heap.pages->refresh(); heap.pages->for_each_zeroed([&](std::size_t offset, std::size_t bytes) { std::memset(heap.copy + offset, 0, bytes); std::memset(heap.previous + offset, 0, bytes); const auto first = std::uint32_t(offset / kDescriptorSize); const auto end = std::uint32_t((offset + bytes) / kDescriptorSize); heap.empty_slots.erase(heap.empty_slots.lower_bound(first), heap.empty_slots.lower_bound(end)); for (auto slot = first; slot < end; ++slot) heap.retry[slot] = 0; heap.live_vsharps.clear_range(first, end); }); const auto t1 = clock::now(); heap.fix_start = t1; heap.fix_over = false; heap.fix_count = 0; heap.pages->for_each_copied([&](std::size_t offset, std::size_t bytes) { fix_console_slots(heap, offset, bytes); }); const auto generation = released_backings.load(std::memory_order_acquire); const auto alias_generation = leonida::title_va_aliases().invalidations(); if (heap.resource_heap && (generation != heap.checked_generation || alias_generation != heap.alias_generation)) { heap.alias_generation = alias_generation; heap.checked_generation = generation; // Even an unchanged title slot may name a buffer released since the last submission. // Walk the host-RAM V# bitset instead of reading every slot of `heap.copy` (which may be uncached WC VRAM). heap.live_vsharps.for_each([&](std::size_t slot) { if (!fix_console_slot(heap, slot) && !heap.retry[slot]) { heap.retry[slot] = 1; heap.retries.push_back(uint32_t(slot)); } }); } const auto t2 = clock::now(); // A settled zero can acquire GPU backing without a CPU map event. Probe at most eight in // round-robin order every 32 submissions. Keep texture and copy-budget retries independent. if ((heap.refreshes & 31) == 31 && !heap.empty_slots.empty()) { auto it = heap.empty_slots.lower_bound(heap.next_empty); const auto count = (std::min)(std::size_t{8}, heap.empty_slots.size()); for (std::size_t n = 0; n < count && !heap.empty_slots.empty(); ++n) { if (it == heap.empty_slots.end()) it = heap.empty_slots.begin(); const auto slot = *it++; heap.next_empty = slot + 1; if (!heap.retry[slot]) { fix_console_slot(heap, slot); ++heap.retried; } } } if (!heap.retries.empty()) retry_console_slots(heap); const auto t3 = clock::now(); heap.pages_ms += ms(t0, t1); heap.fix_ms += ms(t1, t2); heap.retry_ms += ms(t2, t3); } // Before every submission, ahead of the slot-133 shadows. void refresh_console_heaps() { std::lock_guard lock(console_heap_mutex); for (const auto& heap : console_heaps) { const auto start = std::chrono::steady_clock::now(); refresh_console_heap(*heap); heap->ms += std::chrono::duration(std::chrono::steady_clock::now() - start).count(); ++heap->refreshes; // A line at the first and 64th submission, then every 10 s (a crawl logs as often as a fast run). const bool logged = heap->refreshes == 1 || heap->refreshes == 64 || (heap->refreshes > 64 && start - heap->log_time >= std::chrono::seconds(10)); if (!logged) continue; const double count = double(std::max(1, heap->refreshes - heap->logged)); heap->logged = heap->refreshes; heap->log_time = start; std::fprintf(stderr, "[rt] d3d12: console descriptor heap 0x%llx (%s): submissions up to %llu %s %.1f KiB each " "in %.3f ms on average (pages %.3f, fixing copied slots %.3f, %llu left to retries past the " "budget, retrying %.3f: %.1f slots a " "submission, %zu waiting), %llu write faults; %llu title V#s rebased, %llu with no copy given " "no records, T#s %llu known, %llu bound, %llu naming no texture, %llu refused, %llu words " "that are no T# (data)\n", static_cast(heap->console_va), heap->imported ? "imported" : "copy", static_cast(heap->refreshes), "copied", double(heap->copied) / 1024.0 / count, heap->ms / count, heap->pages_ms / count, heap->fix_ms / count, static_cast(heap->deferred_fixes), heap->retry_ms / count, double(heap->retried) / count, heap->retries.size(), static_cast(heap->pages ? heap->pages->faults() : 0), static_cast(heap->vsharps), static_cast(heap->unbacked), static_cast(heap->images[unsigned(TitleImage::known)]), static_cast(heap->images[unsigned(TitleImage::bound)]), static_cast(heap->images[unsigned(TitleImage::unknown)]), static_cast(heap->images[unsigned(TitleImage::refused)]), static_cast(heap->images[unsigned(TitleImage::not_tsharp)])); std::string refused_breakdown; for (const auto& [reason, count] : heap->refused_reasons) refused_breakdown += (refused_breakdown.empty() ? "" : "; ") + reason + " " + std::to_string(count); if (!refused_breakdown.empty()) std::fprintf(stderr, "[rt] d3d12: console descriptor heap 0x%llx unbound T#s by reason: %s\n", static_cast(heap->console_va), refused_breakdown.c_str()); heap->refused_reasons.clear(); heap->copied = heap->vsharps = heap->unbacked = heap->retried = heap->deferred_fixes = 0; for (auto& n : heap->images) n = 0; heap->ms = heap->pages_ms = heap->fix_ms = heap->retry_ms = 0; } } // The heap's pages imported as host memory (see above): true with `heap` filled in, false when they cannot be // (no VK_EXT_external_memory_host, a page not committed or write-combined, a driver refusal, or a device address // shaders could not reach with 32 bits). // `span`: the bytes to import from host_va (0: the heap's), its copy and null guard for a scratch backing. bool import_console_heap(ConsoleHeap& heap, std::uintptr_t host_va, VkDeviceSize span = 0) { auto& vk = context->vk; const VkDeviceSize alignment = info.host_pointer_alignment; if (!span) span = heap.bytes; if (!get_host_pointer_properties || !alignment || !arena.address || (host_va % alignment) || (span % alignment)) return false; const auto* pages = reinterpret_cast(static_cast(host_va)); for (VkDeviceSize at = 0; at < span;) { MEMORY_BASIC_INFORMATION region{}; if (!VirtualQuery(pages + at, ®ion, sizeof(region)) || region.State != MEM_COMMIT || (region.Protect & (PAGE_WRITECOMBINE | PAGE_NOCACHE | PAGE_GUARD))) return false; at = reinterpret_cast(region.BaseAddress) + region.RegionSize - host_va; } VkExternalMemoryBufferCreateInfo external{VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO}; external.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT; VkBufferCreateInfo create{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, &external}; create.size = span; create.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; share(create); if (vk.vkCreateBuffer(info.device, &create, nullptr, &heap.buffer) != VK_SUCCESS) return false; const auto fail = [&] { if (heap.buffer) vk.vkDestroyBuffer(info.device, heap.buffer, nullptr); if (heap.memory) vk.vkFreeMemory(info.device, heap.memory, nullptr); leonida::kernel_writes::release(std::exchange(heap.pin, 0)); heap.buffer = VK_NULL_HANDLE; heap.memory = VK_NULL_HANDLE; return false; }; VkMemoryRequirements requirements{}; vk.vkGetBufferMemoryRequirements(info.device, heap.buffer, &requirements); VkMemoryHostPointerPropertiesEXT host{VK_STRUCTURE_TYPE_MEMORY_HOST_POINTER_PROPERTIES_EXT}; if (get_host_pointer_properties(info.device, VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT, const_cast(pages), &host) != VK_SUCCESS) return fail(); const std::uint32_t types = host.memoryTypeBits & requirements.memoryTypeBits; if (!types || span < requirements.size) return fail(); VkImportMemoryHostPointerInfoEXT import{VK_STRUCTURE_TYPE_IMPORT_MEMORY_HOST_POINTER_INFO_EXT}; import.handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT; import.pHostPointer = const_cast(pages); VkMemoryAllocateFlagsInfo flags{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO, &import}; flags.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT; heap.pin = leonida::kernel_writes::hold(pages, std::size_t(heap.bytes)); // as create_host_buffer's for (const VkMemoryPropertyFlags want : {VkMemoryPropertyFlags(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT), VkMemoryPropertyFlags(0)}) { for (std::uint32_t i = 0; i < memory.memoryTypeCount && !heap.memory; ++i) { if (!(types & (1u << i)) || (memory.memoryTypes[i].propertyFlags & want) != want) continue; VkMemoryAllocateInfo allocate{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, &flags}; allocate.allocationSize = span; allocate.memoryTypeIndex = i; if (vk.vkAllocateMemory(info.device, &allocate, nullptr, &heap.memory) != VK_SUCCESS) heap.memory = VK_NULL_HANDLE; } if (heap.memory) break; } if (!heap.memory || vk.vkBindBufferMemory(info.device, heap.buffer, heap.memory, 0) != VK_SUCCESS) return fail(); VkBufferDeviceAddressInfo bda{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; bda.buffer = heap.buffer; const VkDeviceAddress address = vk.vkGetBufferDeviceAddress(info.device, &bda); const std::uint64_t shader_va = address - arena.address; // mod 2^64, as for an imported slot-133 buffer if (!address || shader_va > (std::uint64_t(1) << 32) - span) { std::fprintf(stderr, "[rt] d3d12: console descriptor heap 0x%llx: its import lies at heap_base + 0x%llx, which " "32-bit descriptor-table pointers cannot reach; copied instead\n", static_cast(heap.console_va), static_cast(shader_va)); return fail(); } heap.shader_va = shader_va; heap.imported = true; return true; } // Gives the console heap at `console_va` a GPU view: `shader_va` is where shaders read it. False when there is // none (the heap then stays where only the CPU sees it, as without this). bool add_console_heap(std::uint64_t console_va, VkDeviceSize bytes, std::uint64_t& shader_va, bool resource_heap) { if (!arena.mapped || !context || !bytes || console_va > UINTPTR_MAX - bytes) return false; auto heap = std::make_unique(); heap->console_va = console_va; heap->bytes = bytes; // Self-written V#s must be rebased without changing the title's descriptor bytes. // A directly indexed heap can lie outside the main arena and still fit in a 32-bit shader offset. heap->resource_heap = resource_heap; // Round the guarded import up to Wine's allocation granularity. if (bytes > (1ull << 32)) return false; const VkDeviceSize requested = resource_heap ? heap_guard_bytes() : 0; const VkDeviceSize guard = requested && bytes + requested <= (1ull << 32) ? ((bytes + requested + 65535) & ~VkDeviceSize(65535)) - bytes : 0; if (resource_heap && geometry.cap()) { if (bytes > (SIZE_MAX - guard) / 3) return false; // [copy | guard | input | previous]: the import covers the copy and its guard. heap->scratch.reset(static_cast(VirtualAlloc(nullptr, bytes * 3 + guard, MEM_TOP_DOWN | MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE))); if (heap->scratch) { auto* backing = heap->scratch.get(); if (import_console_heap(*heap, reinterpret_cast(backing), bytes + guard)) { heap->copy = backing; heap->guard = guard; } heap->input = backing + bytes + guard; heap->previous = backing + 2 * bytes + guard; } heap->imported = false; // the imported storage holds the rewritten descriptors } else if (!resource_heap) { import_console_heap(*heap, console_va); } if (!heap->imported) { if (!heap->copy) { VkDeviceSize offset = 0; // At the console VA itself when the arena reaches that far, else anywhere: with the guard first. bool placed = false; for (int attempt = 0; attempt < (guard ? 2 : 1) && !placed; ++attempt) { const VkDeviceSize size = attempt ? bytes : bytes + guard; heap->identity = arena_allocate_at(console_va, size, arena_descriptor_heap); if (heap->identity) { offset = console_va; } else if (!arena_allocate(size, 65536, offset, arena_descriptor_heap)) { continue; } heap->guard = size - bytes; placed = true; } if (!placed) { log_once("GPU address arena full (raise LEONIDA_ARENA_MB): console descriptor heap left in title " "memory only; KiB", int(std::min(bytes >> 10, INT_MAX))); return false; } if (guard && !heap->guard) log_once("GPU address arena has no room for a console heap's null guard (raise LEONIDA_ARENA_MB): " "a heap index past it reads the arena's next bytes; guard MiB", int(guard >> 20)); heap->shader_va = offset; heap->copy = arena.mapped + offset; } std::memset(heap->copy, 0, std::size_t(bytes + heap->guard)); if (!heap->input) { heap->mirror.assign(std::size_t(bytes), 0); heap->made.assign(std::size_t(bytes), 0); heap->input = heap->mirror.data(); heap->previous = heap->made.data(); } heap->retry.assign(std::size_t(bytes / kDescriptorSize), 0); heap->live_vsharps.reset(std::size_t(bytes / kDescriptorSize)); heap->pages = make_shadow_pages(reinterpret_cast(static_cast(console_va)), heap->input, std::size_t(bytes)); } shader_va = heap->shader_va; if (shader_va != console_va) console_heap_ranges().add(console_va, bytes, shader_va); const bool imported = heap->imported; const VkDeviceSize guarded = heap->guard; { std::lock_guard lock(console_heap_mutex); if (!imported) refresh_console_heap(*heap); if (heap->copy) { std::unique_lock ranges(console_copy_ranges_mutex); console_copy_ranges.emplace_back(heap->console_va, heap->bytes); } console_heaps.push_back(std::move(heap)); } std::fprintf(stderr, "[rt] d3d12: console descriptor heap 0x%llx (%llu KiB): shaders read it at heap_base + 0x%llx, %s; " "%llu KiB of null slots after it\n", static_cast(console_va), static_cast(bytes >> 10), static_cast(shader_va), imported ? "the title's pages imported as host memory" : "a descriptor copy brought up to date before every submission", static_cast(guarded >> 10)); return true; } // Called by the title's threads as they write buffer views (the Subrender workers among them). Not under // console_heap_mutex, which the submit thread holds for every refresh of the heaps (3-7 ms a submission after the // load, speed-27): the heaps with a copy, as ranges, under a lock of their own. std::shared_mutex console_copy_ranges_mutex; std::vector> console_copy_ranges; // console VA, bytes bool has_console_descriptor_copy(std::uintptr_t destination) { std::shared_lock lock(console_copy_ranges_mutex); for (const auto& [va, bytes] : console_copy_ranges) if (destination - va < bytes) return true; return false; } void remove_console_heap(std::uint64_t console_va) { std::unique_ptr heap; { std::lock_guard lock(console_heap_mutex); const auto it = std::find_if(console_heaps.begin(), console_heaps.end(), [console_va](const auto& h) { return h->console_va == console_va; }); if (it == console_heaps.end()) return; heap = std::move(*it); console_heaps.erase(it); std::unique_lock ranges(console_copy_ranges_mutex); std::erase_if(console_copy_ranges, [console_va](const auto& r) { return r.first == console_va; }); } console_heap_ranges().remove(console_va); heap->pages.reset(); if (heap->buffer) { // As for an imported slot-133 buffer: the title may free its pages right after, so the memory goes once // what was submitted retires, not through the deferred queue. context->wait_retire_ticket(context->submitted_retire_ticket()); context->vk.vkDestroyBuffer(info.device, heap->buffer, nullptr); context->vk.vkFreeMemory(info.device, heap->memory, nullptr); leonida::kernel_writes::release(std::exchange(heap->pin, 0)); } else { arena_release(heap->shader_va, heap->bytes + heap->guard, arena_descriptor_heap); } } // LOCAL DIAGNOSTIC (desc-probe): which console-heap slots our API wrote and which the title wrote itself, what // the title's own records decode to, and whether the GPU can see them. Title data: the log stays local. struct HeapProbe { std::uint64_t console_va = 0, shader_va = 0; std::size_t slots = 0; bool shadowed = false; std::vector api; // hash of what our API last wrote to the slot; 0: never std::vector writer; // optional input-probe API origin by slot std::vector seen; // hash at the last census std::uint64_t api_writes = 0, censuses = 0; int table_dumps = 0, census_dumps = 0; bool told_table = false; // bound tables, since the last census std::uint64_t tables = 0, t_slots = 0, t_zero = 0, t_api = 0, t_title = 0, t_kind[8] = {}; int table_logs = 0; std::size_t recent[8] = {}; // the last bound slots, read again at each census unsigned recent_count = 0; }; std::mutex probe_mutex; // never under console_heap_mutex' callees; takes descriptor_mutex inside std::vector> probes; std::uint64_t probe_submissions = 0; static constexpr const char* kProbeKinds[8] = {"V# in arena", "V# title memory", "V# other", "T# key known", "T# texture by address", "T# no texture", "other", "free-list link (dword 0 only)"}; std::atomic probe_view_logs{0}; // Where a Create*View / CopyDescriptors* write landed, for the first ones. void probe_view(const char* what, SIZE_T ptr, UINT count) { if (!leonida::local_diagnostics() || probe_view_logs.fetch_add(1) >= 48) return; std::lock_guard lock(probe_mutex); for (const auto& p : probes) if (ptr >= p->console_va && ptr < p->console_va + p->slots * kDescriptorSize) { char text[512]; probe_kind(reinterpret_cast(ptr), text, sizeof(text)); std::fprintf(stderr, "[rt] desc-probe: %s x%u -> console heap slot %llu: %s\n", what, count, static_cast((ptr - p->console_va) / kDescriptorSize), text); return; } std::fprintf(stderr, "[rt] desc-probe: %s x%u -> 0x%llx, outside the console heaps\n", what, count, static_cast(ptr)); } static std::uint64_t probe_hash(const std::uint8_t* p) { std::uint64_t h = 1469598103934665603ull; for (unsigned i = 0; i < kDescriptorSize; ++i) h = (h ^ p[i]) * 1099511628211ull; return h ? h : 1; } static bool probe_zero(const std::uint8_t* p) { std::uint64_t q[4]; std::memcpy(q, p, sizeof(q)); return !(q[0] | q[1] | q[2] | q[3]); } void probe_add(std::uint64_t console_va, std::uint64_t shader_va, std::size_t slots, bool shadowed) { // Nothing reads a probe unless one of the two diagnostics is on; without probes the other probe_* are no-ops. if (!leonida::local_diagnostics() && !rt::compute_probe::enabled()) return; auto probe = std::make_unique(); probe->console_va = console_va; probe->shader_va = shader_va; probe->slots = slots; probe->shadowed = shadowed; probe->api.assign(slots, 0); if (rt::compute_probe::enabled()) probe->writer.resize(slots); probe->seen.assign(slots, 0); std::lock_guard lock(probe_mutex); probes.push_back(std::move(probe)); std::fprintf(stderr, "[rt] desc-probe: console heap 0x%llx, %zu slots, shaders read it at VA 0x%llx (%s); arena size " "0x%llx: heap_base + VA is %s the arena\n", static_cast(console_va), slots, static_cast(shader_va), !shadowed ? "no GPU view" : shader_va + slots * kDescriptorSize <= arena.size ? "arena copy" : "import", static_cast(arena.size), shader_va + slots * kDescriptorSize <= arena.size ? "inside" : "PAST"); } void probe_remove(std::uint64_t console_va) { std::lock_guard lock(probe_mutex); std::erase_if(probes, [console_va](const std::unique_ptr& p) { return p->console_va == console_va; }); } void probe_api(SIZE_T ptr, UINT count, const char* what = "CopyDescriptors") { if (!ptr || !count) return; std::lock_guard lock(probe_mutex); for (const auto& p : probes) { if (ptr < p->console_va || ptr >= p->console_va + p->slots * kDescriptorSize) continue; const std::size_t first = std::size_t((ptr - p->console_va) / kDescriptorSize); for (std::size_t i = first; i < first + count && i < p->slots; ++i) { p->api[i] = probe_hash(reinterpret_cast( static_cast(p->console_va + i * kDescriptorSize))); if (!p->writer.empty()) p->writer[i] = rt::compute_probe::writer_code(what); ++p->api_writes; } } } // What a slot the title wrote holds (an index into kProbeKinds) and a line saying so. int probe_kind(const std::uint8_t* bytes, char* text, std::size_t size) { namespace g = leonida::gfx10; std::uint32_t w[8]; std::memcpy(w, bytes, sizeof(w)); int n = std::snprintf(text, size, "%08x %08x %08x %08x %08x %08x %08x %08x |", w[0], w[1], w[2], w[3], w[4], w[5], w[6], w[7]); if (!(w[1] | w[2] | w[3] | w[4] | w[5] | w[6] | w[7]) && w[0] < 0x200000u) { if (n > 0 && std::size_t(n) < size) std::snprintf(text + n, size - n, " free-list link to slot %u?", w[0]); return 7; } if (n < 0) n = 0; char* rest = text + std::min(std::size_t(n), size); const std::size_t left = size - std::min(std::size_t(n), size); if (!(w[3] >> 30)) { g::BufferWords words{w[0], w[1], w[2], w[3]}; g::Buffer b{}; const bool ok = g::decode(words, b); std::uint64_t lo = 0, hi = 0; const bool title = leonida::title_va_aliases().title_memory(b.address, lo, hi); const std::uint64_t to = leonida::title_va_aliases().shader_va(b.address); const int kind = b.address < arena.size ? 0 : title ? 1 : 2; std::snprintf(rest, left, " V#%s base 0x%llx stride %u records %u fmt %u dst %u%u%u%u oob %u -> %s%s (upper 16 B %s)", ok ? "" : "(bad dst)", static_cast(b.address), b.stride, b.num_records, b.format, b.swizzle[0], b.swizzle[1], b.swizzle[2], b.swizzle[3], unsigned(b.oob_select), kProbeKinds[kind], to != b.address ? " (has a GPU copy)" : "", (w[4] | w[5] | w[6] | w[7]) ? "set" : "zero"); return kind; } g::ImageWords words{w[0], w[1], w[2], w[3], w[4], w[5], w[6], w[7]}; g::Image image{}; if (!g::is_image(words) || !g::decode(words, image)) { std::snprintf(rest, left, " neither V# nor valid T# (type %u)", w[3] >> 28); return 6; } int kind = 5; char what[96] = "no texture at that address"; { std::lock_guard lock(descriptor_mutex); if (image_entries.count(words)) { kind = 3; std::snprintf(what, sizeof(what), "key registered"); } else if (const auto it = images_by_address.find(image.address); it != images_by_address.end()) { kind = 4; std::snprintf(what, sizeof(what), "texture known, this key not registered"); } } std::snprintf(rest, left, " T# base 0x%llx fmt %u type %u %ux%u depth %u mips %u+%u of %u layers %u+%u samples %u dst " "%u%u%u%u minlod %.2f -> %s", static_cast(image.address), image.format, unsigned(image.type), image.width, image.height, image.depth, image.first_mip, image.mip_count, image.resource_mips, image.first_layer, image.layer_count, image.samples, image.swizzle[0], image.swizzle[1], image.swizzle[2], image.swizzle[3], double(image.min_lod), what); return kind; } // At a descriptor-table scan (ExecuteCommandLists): the slots a bound table in a console heap declares. void probe_table(std::uint64_t table_va, std::uint32_t descriptors) { std::lock_guard lock(probe_mutex); for (const auto& p : probes) { const std::uint64_t span = p->slots * kDescriptorSize; std::uint64_t at = 0; if (table_va >= p->shader_va && table_va - p->shader_va < span) at = table_va - p->shader_va; else if (table_va >= p->console_va && table_va - p->console_va < span) at = table_va - p->console_va; else continue; const std::size_t first = std::size_t(at / kDescriptorSize); const std::size_t count = std::min(std::min(descriptors, 1024), p->slots - first); if (!p->told_table) { p->told_table = true; std::fprintf(stderr, "[rt] desc-probe: first bound table in console heap 0x%llx: VA 0x%llx = slot %zu, %zu " "slots declared; shaders load it at heap_base + 0x%llx, %s the arena (size 0x%llx)\n", static_cast(p->console_va), static_cast(table_va), first, count, static_cast(table_va), table_va + count * kDescriptorSize <= arena.size ? "inside" : "PAST", static_cast(arena.size)); } ++p->tables; p->recent[p->recent_count++ % 8] = first; if (p->table_logs < 40) { ++p->table_logs; char text[512] = ""; probe_kind(reinterpret_cast( static_cast(p->console_va + first * kDescriptorSize)), text, sizeof(text)); std::fprintf(stderr, "[rt] desc-probe: table %llu VA 0x%llx slot %zu (%zu declared) at execute: %s\n", static_cast(p->tables), static_cast(table_va), first, count, text); } for (std::size_t i = first; i < first + count; ++i) { const auto* bytes = reinterpret_cast(static_cast(p->console_va + i * kDescriptorSize)); ++p->t_slots; if (probe_zero(bytes)) { ++p->t_zero; continue; } if (p->api[i] && p->api[i] == probe_hash(bytes)) { ++p->t_api; continue; } ++p->t_title; char text[512]; const int kind = probe_kind(bytes, text, sizeof(text)); ++p->t_kind[kind]; if (p->table_dumps < 24) { ++p->table_dumps; std::fprintf(stderr, "[rt] desc-probe: table slot %zu (table VA 0x%llx +%zu) %s-written: %s\n", i, static_cast(table_va), i - first, p->api[i] ? "API-then-title" : "title", text); } } } } // Before a submission, after the console heaps' copies are refreshed: the whole heap, now and then. void probe_census() { if (!leonida::local_diagnostics()) return; const std::uint64_t n = ++probe_submissions; if (n != 1 && n != 64 && n != 512 && n != 2048 && n % 4096) return; std::lock_guard lock(probe_mutex); for (const auto& p : probes) { ++p->censuses; std::uint64_t zero = 0, api = 0, title_new = 0, title_over = 0, changed_no_api = 0, kinds[8] = {}; std::uint64_t copy_differs = 0, copy_differs_unrebased = 0; // A copy lies in the arena; an import never does (its device address is outside the arena's). const std::uint8_t* copy = p->shadowed && p->shader_va + p->slots * kDescriptorSize <= arena.size ? arena.mapped + p->shader_va : nullptr; for (std::size_t i = 0; i < p->slots; ++i) { const auto* bytes = reinterpret_cast(static_cast(p->console_va + i * kDescriptorSize)); if (copy && std::memcmp(copy + i * kDescriptorSize, bytes, kDescriptorSize)) { ++copy_differs; // A rebased V# differs in its base only (dwords 0 and 1 low half). std::uint32_t a[8], b[8]; std::memcpy(a, bytes, 32); std::memcpy(b, copy + i * kDescriptorSize, 32); const bool rebased = !(a[3] >> 30) && a[2] == b[2] && a[3] == b[3] && (a[1] & 0xFFFF0000u) == (b[1] & 0xFFFF0000u) && !std::memcmp(a + 4, b + 4, 16); copy_differs_unrebased += !rebased; } const bool is_zero = probe_zero(bytes); const std::uint64_t h = is_zero ? 0 : probe_hash(bytes); if (p->seen[i] != h && p->censuses > 1 && h != p->api[i]) ++changed_no_api; p->seen[i] = h; if (is_zero) { ++zero; continue; } if (p->api[i] == h) { ++api; continue; } ++(p->api[i] ? title_over : title_new); char text[512]; const int kind = probe_kind(bytes, text, sizeof(text)); ++kinds[kind]; if (p->census_dumps < 40 && kind != 7 && kind != 0) { ++p->census_dumps; std::fprintf(stderr, "[rt] desc-probe: census %llu slot %zu %s-written: %s\n", static_cast(p->censuses), i, p->api[i] ? "API-then-title" : "title", text); } } std::fprintf(stderr, "[rt] desc-probe: census %llu at submission %llu, heap 0x%llx (%zu slots, %llu API writes so " "far): zero %llu, as our API wrote them %llu, title-written %llu (never API %llu, over an API " "write %llu), changed since the last census with no API write %llu; title kinds: %s %llu, %s " "%llu, %s %llu, %s %llu, %s %llu, %s %llu, %s %llu, %s %llu; arena copy differs %llu (not a rebased V# " "%llu)\n", static_cast(p->censuses), static_cast(n), static_cast(p->console_va), p->slots, static_cast(p->api_writes), static_cast(zero), static_cast(api), static_cast(title_new + title_over), static_cast(title_new), static_cast(title_over), static_cast(changed_no_api), kProbeKinds[0], static_cast(kinds[0]), kProbeKinds[1], static_cast(kinds[1]), kProbeKinds[2], static_cast(kinds[2]), kProbeKinds[3], static_cast(kinds[3]), kProbeKinds[4], static_cast(kinds[4]), kProbeKinds[5], static_cast(kinds[5]), kProbeKinds[6], static_cast(kinds[6]), kProbeKinds[7], static_cast(kinds[7]), static_cast(copy_differs), static_cast(copy_differs_unrebased)); std::fprintf(stderr, "[rt] desc-probe: bound tables since the last census: %llu tables, %llu slots: zero %llu, API " "%llu, title-written %llu (%s %llu, %s %llu, %s %llu, %s %llu, %s %llu, %s %llu, %s %llu, %s %llu)\n", static_cast(p->tables), static_cast(p->t_slots), static_cast(p->t_zero), static_cast(p->t_api), static_cast(p->t_title), kProbeKinds[0], static_cast(p->t_kind[0]), kProbeKinds[1], static_cast(p->t_kind[1]), kProbeKinds[2], static_cast(p->t_kind[2]), kProbeKinds[3], static_cast(p->t_kind[3]), kProbeKinds[4], static_cast(p->t_kind[4]), kProbeKinds[5], static_cast(p->t_kind[5]), kProbeKinds[6], static_cast(p->t_kind[6]), kProbeKinds[7], static_cast(p->t_kind[7])); for (unsigned r = 0; r < std::min(p->recent_count, 8u); ++r) { char text[512] = ""; const std::size_t slot = p->recent[r]; probe_kind(reinterpret_cast( static_cast(p->console_va + slot * kDescriptorSize)), text, sizeof(text)); std::fprintf(stderr, "[rt] desc-probe: census %llu: recently bound slot %zu now: %s\n", static_cast(p->censuses), slot, text); } p->tables = p->t_slots = p->t_zero = p->t_api = p->t_title = 0; for (auto& k : p->t_kind) k = 0; } } // The translator's output, loaded on first use. std::mutex library_mutex; bool library_tried = false; leonida::ShaderLibrary shader_library; leonida::GraphicsShaderModules graphics_modules; rt::d3d12_xs::NativeGraphicsPipelines native_graphics; const leonida::ShaderLibrary* library() { std::lock_guard lock(library_mutex); if (!library_tried) { library_tried = true; // Nothing may leave here into Create*PipelineState: a path the STL cannot convert throws std::system_error // under MSVC, which is not a filesystem_error, so every std::exception gives the message. try { std::string error; const std::filesystem::path dir = info.shader_dir.empty() ? configured_shader_directory(&error) : std::filesystem::path(info.shader_dir); if (!error.empty()) std::fprintf(stderr, "[rt] d3d12: invalid translated shader path: %s\n", error.c_str()); else if (dir.empty()) std::fprintf(stderr, "[rt] d3d12: no translated shaders: set LEONIDA_SHADERS to /shaders/spirv\n"); else if (!shader_library.load(dir, &error)) std::fprintf(stderr, "[rt] d3d12: %s\n", error.c_str()); else { const auto path = shader_library.directory().u8string(); // fspx counts library/ too (shader_library.h, load()). std::fprintf(stderr, "[rt] d3d12: %zu translated shaders (%zu fspx, %zu fspx_compute, " "%zu fspx_gfx, %zu bvh, %zu exe) from %s\n", shader_library.size(), shader_library.fspx_size(), shader_library.fspx_compute_size(), shader_library.fspx_gfx_size(), shader_library.bvh_size(), shader_library.exe_size(), reinterpret_cast(path.c_str())); } } catch (const std::exception& e) { std::fprintf(stderr, "[rt] d3d12: invalid translated shader path: %s\n", e.what()); } } return shader_library.loaded() ? &shader_library : nullptr; } VkFormat depth_backing(VkFormat logical) const { if(logical!=VK_FORMAT_D16_UNORM_S8_UINT)return logical; for(const auto candidate : {VK_FORMAT_D16_UNORM_S8_UINT,VK_FORMAT_D32_SFLOAT_S8_UINT,VK_FORMAT_D24_UNORM_S8_UINT}) if(depth_usable(candidate))return candidate; return VK_FORMAT_UNDEFINED; } bool depth_usable(VkFormat format) const { VkFormatProperties properties{}; format_properties(info.physical, format, &properties); return properties.optimalTilingFeatures & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT; } bool color_attachment_usable(VkFormat format) const { VkFormatProperties properties{}; format_properties(info.physical, format, &properties); return (properties.optimalTilingFeatures & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT) != 0; } bool storage_usable(VkFormat format) const { VkFormatProperties properties{}; format_properties(info.physical, format, &properties); return (properties.optimalTilingFeatures & VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT) != 0; } bool sampled_usable(VkFormat format) const { VkFormatProperties properties{}; format_properties(info.physical, format, &properties); return (properties.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) != 0; } // Whether the GPU needs and supports backing UAV textures of `logical` (no storage support) with a mutable image of // the unsigned format `backing` of the same size. bool probe_uint_backed_uav(VkFormat logical, VkFormat backing) const { if (storage_usable(logical)) return false; if (!image_format_properties2 || !storage_usable(backing) || !sampled_usable(logical)) return false; const VkFormat view_formats[2] = {backing, logical}; VkImageFormatListCreateInfo list{VK_STRUCTURE_TYPE_IMAGE_FORMAT_LIST_CREATE_INFO}; list.viewFormatCount = 2; list.pViewFormats = view_formats; VkPhysicalDeviceImageFormatInfo2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2, &list}; query.format = backing; query.type = VK_IMAGE_TYPE_2D; query.tiling = VK_IMAGE_TILING_OPTIMAL; query.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT; query.flags = VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT | VK_IMAGE_CREATE_EXTENDED_USAGE_BIT; VkImageFormatProperties2 props{VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2}; return image_format_properties2(info.physical, &query, &props) == VK_SUCCESS; } // The limits apply to this exact combination of format, type, tiling, usage, create flags and pNext format list. HRESULT check_image_support(const VkImageCreateInfo& create) const { VkImageFormatProperties limits{}; VkResult result = VK_ERROR_FORMAT_NOT_SUPPORTED; if (image_format_properties2) { VkPhysicalDeviceImageFormatInfo2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2}; query.pNext = create.pNext; query.format = create.format; query.type = create.imageType; query.tiling = create.tiling; query.usage = create.usage; query.flags = create.flags; VkImageFormatProperties2 props{VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2}; result = image_format_properties2(info.physical, &query, &props); limits = props.imageFormatProperties; } else { result = image_format_properties(info.physical, create.format, create.imageType, create.tiling, create.usage, create.flags, &limits); } if (result == VK_ERROR_FORMAT_NOT_SUPPORTED) return E_INVALIDARG; if (result == VK_ERROR_OUT_OF_HOST_MEMORY || result == VK_ERROR_OUT_OF_DEVICE_MEMORY) return E_OUTOFMEMORY; if (result != VK_SUCCESS) return E_FAIL; if (create.extent.width > limits.maxExtent.width || create.extent.height > limits.maxExtent.height || create.extent.depth > limits.maxExtent.depth || create.mipLevels > limits.maxMipLevels || create.arrayLayers > limits.maxArrayLayers || !(limits.sampleCounts & create.samples)) return E_INVALIDARG; return S_OK; } VkFormatFeatureFlags2 optimal_features(VkFormat format) const { if (!format_properties2) return 0; VkFormatProperties3 features{VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_3}; VkFormatProperties2 properties{VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_2, &features}; format_properties2(info.physical, format, &properties); return features.optimalTilingFeatures; } // D3D12_OPTIONS1's wave facts, from the physical device: which subgroup operations exist and what wave sizes it // can run. Zeros and false when the device cannot be asked, which the query then reports as unsupported. // Read once: std::call_once makes a concurrent first caller wait until the facts are complete. const SubgroupFacts& subgroup_facts() { std::call_once(subgroups_once, [this] { read_subgroup_facts(); }); return subgroups; } void read_subgroup_facts() { const auto properties2 = reinterpret_cast( info.get_instance_proc ? info.get_instance_proc(info.instance, "vkGetPhysicalDeviceProperties2") : nullptr); if (!properties2 || !info.physical) return; VkPhysicalDeviceSubgroupSizeControlProperties size_control{ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_SIZE_CONTROL_PROPERTIES}; VkPhysicalDeviceSubgroupProperties subgroup{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_PROPERTIES, &size_control}; VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &subgroup}; properties2(info.physical, &properties); // Every group the wave intrinsics map to, because D3D12 promises them all behind the one bool. constexpr VkSubgroupFeatureFlags kD3D12WaveOps = VK_SUBGROUP_FEATURE_BASIC_BIT | VK_SUBGROUP_FEATURE_VOTE_BIT | VK_SUBGROUP_FEATURE_BALLOT_BIT | VK_SUBGROUP_FEATURE_SHUFFLE_BIT | VK_SUBGROUP_FEATURE_ARITHMETIC_BIT; subgroups.wave_ops = (subgroup.supportedOperations & kD3D12WaveOps) == kD3D12WaveOps; subgroups.lane_min = size_control.minSubgroupSize ? size_control.minSubgroupSize : subgroup.subgroupSize; subgroups.lane_max = size_control.maxSubgroupSize ? size_control.maxSubgroupSize : subgroups.lane_min; if (subgroups.lane_max < subgroups.lane_min) subgroups.lane_max = subgroups.lane_min; // D3D-121: Intel's D3D12 driver answers a fixed 16..16 on its older integrated GPUs, where Vulkan reports // the compiler's whole 8..32 choice. Measured on Xe-LP: UHD 770 (32.0.101.6129), Raptor Lake-S Mobile // (101.7092) and Tiger Lake 0x9a78 (101.7088). Discrete Arc is not measured yet (TEST-57), so it keeps the // Vulkan range. D3D-280: from Xe-LPG on the driver answers what Vulkan reports (Meteor Lake 0x7d55, // 32.0.101.6127: 8..32 on both sides), so there is no fixed answer to mirror and those lines keep the // Vulkan range too. constexpr uint32_t kIntelVendorId = 0x8086; constexpr UINT kIntelD3D12Lanes = 16; const uint32_t intel_device_id = properties.properties.deviceID; // The Xe-core integrated lines from Xe-LPG on. Device IDs are not generation-ordered (Tiger Lake's 0x9a78 // sorts above Meteor Lake's), so the ranges are listed out, not compared as a cutoff. const bool intel_xe_lpg_or_later = (intel_device_id >= 0x7d40 && intel_device_id <= 0x7dc5) || // Meteor Lake, Arrow Lake (intel_device_id >= 0x64a0 && intel_device_id <= 0x64b6); // Lunar Lake if (properties.properties.vendorID == kIntelVendorId && properties.properties.deviceType == VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU && !intel_xe_lpg_or_later && subgroups.lane_min <= kIntelD3D12Lanes && kIntelD3D12Lanes <= subgroups.lane_max) subgroups.lane_min = subgroups.lane_max = kIntelD3D12Lanes; } // The device's mesh-shader limits (output vertices and primitives, workgroup size), for mesh PSO creation. const VkPhysicalDeviceMeshShaderPropertiesEXT& mesh_limits() { std::lock_guard lock(mesh_properties_mutex); if (mesh_properties_read) return mesh_properties; mesh_properties_read = true; const auto properties2 = reinterpret_cast( info.get_instance_proc ? info.get_instance_proc(info.instance, "vkGetPhysicalDeviceProperties2") : nullptr); if (!properties2 || !info.physical || !info.mesh_shader) return mesh_properties; VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &mesh_properties}; properties2(info.physical, &properties); mesh_properties.pNext = nullptr; return mesh_properties; } // Integer sampled images need not support multisampling. Pick a supported count for the // zero image in the corresponding set-0 bindings; one means that class is unavailable. VkSampleCountFlagBits ms_fallback_samples(VkFormat format) const { VkImageFormatProperties props{}; constexpr VkImageUsageFlags usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; if (image_format_properties(info.physical, format, VK_IMAGE_TYPE_2D, VK_IMAGE_TILING_OPTIMAL, usage, 0, &props) == VK_SUCCESS) { for (UINT count = D3D12_MAX_MULTISAMPLE_SAMPLE_COUNT; count > 1; count >>= 1) if (props.sampleCounts & count) return VkSampleCountFlagBits(count); } return VK_SAMPLE_COUNT_1_BIT; } // The format a texture description is created with, D24S8 and R9G9B9E5 UAV fallbacks included. Format texture_format(const D3D12_RESOURCE_DESC& desc) const { if (!xr_bias_compatible(desc)) return {}; if (desc.Format == DXGI_FORMAT_A8_UNORM) { // Sampled A8: an R8 image read through the alpha swizzle, in 1D, 2D or 3D as the host runtime makes // them (d3d12_a8_dimensions_test); A8 render targets stay 2D. if ((desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE1D && desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D && desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE3D) || ((desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) && desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) || desc.SampleDesc.Count != 1 || (desc.Flags & (D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS))) return {}; if (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) { if (!info.a8_render_target) { log_once("A8_UNORM render targets need VK_FORMAT_A8_UNORM_KHR (VK_KHR_maintenance5); format", desc.Format); return {}; } Format alpha{kA8UnormFormat, VK_IMAGE_ASPECT_COLOR_BIT}; alpha.a8_as_alpha = true; return alpha; } } if (desc.Format == DXGI_FORMAT_R9G9B9E5_SHAREDEXP) { if ((desc.SampleDesc.Count != 1 && (!(desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) || (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS))) || (desc.Flags & (D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE))) return {}; if ((desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) && r9g9b9e5_target_stand_in) { log_once("R9G9B9E5_SHAREDEXP render target unavailable natively, using B10G11R11_UFLOAT; format", desc.Format); return Format{VK_FORMAT_B10G11R11_UFLOAT_PACK32, VK_IMAGE_ASPECT_COLOR_BIT}; } if ((desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) && (!color_attachment_usable(VK_FORMAT_E5B9G9R9_UFLOAT_PACK32) || ((desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) && !storage_usable(VK_FORMAT_E5B9G9R9_UFLOAT_PACK32)))) return {}; if ((desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) && r9g9b9e5_uav_emulated) { log_once("R9G9B9E5_SHAREDEXP UAV unavailable natively, using mutable R32_UINT; format", desc.Format); Format backed{VK_FORMAT_R32_UINT, VK_IMAGE_ASPECT_COLOR_BIT}; backed.uint_backed = VK_FORMAT_E5B9G9R9_UFLOAT_PACK32; return backed; } } if (rgb96_refused(desc)) { if (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) log_once("96-bit (R32G32B32) render targets not supported; format", desc.Format); return {}; } // The host runtime refuses typed B8G8R8X8 with unordered access (its typeless family is accepted): the // BGRA8 image could take storage writes, but D3D12 has no typed UAV for these formats. if (alpha_unused(desc.Format) && desc.Format != DXGI_FORMAT_B8G8R8X8_TYPELESS && (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) { log_once("B8G8R8X8 textures cannot allow unordered access; format", desc.Format); return {}; } // A B5G5R5A1 UAV texture where VK_FORMAT_A1R5G5B5_UNORM_PACK16 has no storage support: a mutable R16_UINT image // (Format::uint_backed). Its RTVs and SRVs view it as A1R5G5B5; shaders store the packed 16 bits. if (desc.Format == DXGI_FORMAT_B5G5R5A1_UNORM && (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) && !storage_usable(VK_FORMAT_A1R5G5B5_UNORM_PACK16)) { if (!b5g5r5a1_uav_emulated || desc.SampleDesc.Count > 1 || ((desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) && !color_attachment_usable(VK_FORMAT_A1R5G5B5_UNORM_PACK16))) return {}; log_once("B5G5R5A1_UNORM UAV unavailable natively, using mutable R16_UINT; format", desc.Format); Format backed{VK_FORMAT_R16_UINT, VK_IMAGE_ASPECT_COLOR_BIT}; backed.uint_backed = VK_FORMAT_A1R5G5B5_UNORM_PACK16; return backed; } // A B4G4R4A4 render target where no 4444 format is a colour attachment (NVIDIA has none, sampled only): an // RGBA8 image, which holds every 4-bit value exactly. RTVs and PSOs follow the image's format; the 4_4_4_4 T#s // read it with the 4444 view's channels (bind_image). Not covered: a copy between it and a buffer footprint // moves 4-byte RGBA8 texels, not packed 16-bit ones (replay's footprint bounds checks still hold). if (desc.Format == DXGI_FORMAT_B4G4R4A4_UNORM && (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) && !color_attachment_usable(VK_FORMAT_A4R4G4B4_UNORM_PACK16) && color_attachment_usable(VK_FORMAT_R8G8B8A8_UNORM)) { log_once("B4G4R4A4_UNORM render targets unavailable natively, using RGBA8; format", desc.Format); Format backed{VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_ASPECT_COLOR_BIT}; backed.rgba4_render_fallback = true; // clears are quantised to 4 bits a channel, as its draws are return backed; } // An 8-bit sRGB UAV texture where the sRGB format has no storage support: the host runtime makes it (RTX 4090 // and WARP; a retail title sizes a 2048x2048 R8G8B8A8_UNORM_SRGB render target with unordered access), but no // typed UAV is sRGB in D3D12, so shaders write the raw bytes. A mutable image of the UNORM format of the same // channel order (Format::uint_backed): its storage view is UNORM, its SRVs and RTVs are sRGB, so sampling // decodes and rendering encodes as on the host. if ((desc.Format == DXGI_FORMAT_R8G8B8A8_UNORM_SRGB || desc.Format == DXGI_FORMAT_B8G8R8A8_UNORM_SRGB) && (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) { const bool rgba = desc.Format == DXGI_FORMAT_R8G8B8A8_UNORM_SRGB; const VkFormat srgb = rgba ? VK_FORMAT_R8G8B8A8_SRGB : VK_FORMAT_B8G8R8A8_SRGB; if (!storage_usable(srgb)) { if (!(rgba ? rgba8_srgb_uav_emulated : bgra8_srgb_uav_emulated) || desc.SampleDesc.Count > 1 || ((desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) && !color_attachment_usable(srgb))) return {}; log_once("8-bit sRGB UAV unavailable natively, using a mutable UNORM image; format", desc.Format); Format backed{rgba ? VK_FORMAT_R8G8B8A8_UNORM : VK_FORMAT_B8G8R8A8_UNORM, VK_IMAGE_ASPECT_COLOR_BIT}; backed.uint_backed = srgb; return backed; } } Format format = texture_storage_format(desc.Format, desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL); if (desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D && (format.aspects & VK_IMAGE_ASPECT_DEPTH_BIT)) return {}; if(desc.Format==DXGI_FORMAT_B4G4R4A4_UNORM && (desc.Flags&D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) && !color_attachment_usable(format.format)) { if(!color_attachment_usable(VK_FORMAT_R8G8B8A8_UNORM))return {}; format.format=VK_FORMAT_R8G8B8A8_UNORM;format.rgba4_render_fallback=true; return format; } if(format.format==VK_FORMAT_D16_UNORM_S8_UINT) { format.xbox_depth16_stencil8=true;format.format=depth_backing(format.format); return format; } format.d24 = format.format == VK_FORMAT_D24_UNORM_S8_UINT; // native or not: clears are quantised if (format.format == VK_FORMAT_D24_UNORM_S8_UINT && !depth_usable(format.format)) { log_once("D24_UNORM_S8_UINT unavailable, using D32_SFLOAT_S8_UINT; format", desc.Format); format.format = VK_FORMAT_D32_SFLOAT_S8_UINT; format.d24_as_float = true; } return format; } // The memory an image made from `create` needs, or false if the device can't make that image. bool memory_requirements(const VkImageCreateInfo& create, VkMemoryRequirements& out) const { if (FAILED(check_image_support(create))) return false; if (image_requirements) { VkDeviceImageMemoryRequirements query{VK_STRUCTURE_TYPE_DEVICE_IMAGE_MEMORY_REQUIREMENTS}; query.pCreateInfo = &create; VkMemoryRequirements2 result{VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2}; image_requirements(info.device, &query, &result); out = result.memoryRequirements; return true; } auto& vk = context->vk; // without the query, a throwaway image VkImage image = VK_NULL_HANDLE; VkImageCreateInfo shared = create; share(shared); if (vk.vkCreateImage(info.device, &shared, nullptr, &image) != VK_SUCCESS) return false; vk.vkGetImageMemoryRequirements(info.device, image, &out); vk.vkDestroyImage(info.device, image, nullptr); return true; } // Set 0 of the translated shaders (vulkan_bindless.h, docs section 3.4) and what has been put in it. A shader // finds a T# or S# by its bytes (the descriptor hash table), so one entry serves every heap slot that holds // those bytes: a copied descriptor needs nothing more. An image's entries live until its texture is // destroyed, samplers until the device is. struct ImageEntry { leonida::ImageDimension dimension; std::uint32_t index; VkImageView sampled; VkImageView storage; // the same range without a component mapping, for the storage bindings; or null std::uint64_t address; }; std::unique_ptr bindless; std::mutex descriptor_mutex; // the set and the containers below // vkDeviceWaitIdle calls made for the bindless set (none, unless LEONIDA_BINDLESS_IDLE_WAIT restores the old wait). std::atomic bindless_idle_waits{0}; bool bindless_legacy_idle = false; std::atomic bindless_cap_logged{false}; std::size_t bindless_logged_table_bytes = 0; // descriptor_mutex: the table size last logged bool bindless_host_logged = false; // descriptor_mutex std::map image_entries; // A pending stream has a console descriptor immediately. Keep its keys (including aliases) // until the first complete upload. A shader hash miss selects the existing fallback image. struct PendingImage { VkImage zero = VK_NULL_HANDLE; std::map keys; }; std::unordered_map pending_image_keys; using ZeroShape = std::tuple; std::mutex zero_image_mutex; std::map zero_images; std::atomic zero_image_bytes{0}; VkImage zero_sampled_image(const D3D12_RESOURCE_DESC&, const Format&, VkDeviceSize); std::multimap image_keys; // by the texture's address std::vector replaced_images; // kept until their texture goes: work in flight may still use them std::map sampler_entries; struct CustomBorderColor { bool is_int = false; VkClearColorValue value{}; bool operator==(const CustomBorderColor& o) const { return is_int == o.is_int && std::memcmp(&value, &o.value, sizeof(value)) == 0; } }; std::vector border_color_table; std::uint32_t register_border_color(bool is_int, const void* components) { std::lock_guard lock(descriptor_mutex); CustomBorderColor entry{}; entry.is_int = is_int; std::memcpy(&entry.value, components, sizeof(entry.value)); for (std::size_t i = 0; i < border_color_table.size(); ++i) { if (border_color_table[i] == entry) return std::uint32_t(i); } if (border_color_table.size() >= 4000) { log_once("custom sampler border colour table is full (4000 entries); clamping index", int(border_color_table.size())); return 3999; } const std::uint32_t idx = std::uint32_t(border_color_table.size()); border_color_table.push_back(entry); return idx; } // A T# names a texture by an address of its own: above 4 GiB, which the GPU address arena for buffers (docs // section 3.3) stays below, and 256 bytes apart (the T# keeps addresses in 256-byte units). Nothing // dereferences it. std::atomic next_image_address{std::uint64_t(1) << 32}; // 0 float, 1 unsigned integer, 2 signed integer: which of the three storage-image arrays a view belongs in. static int numeric_class(VkFormat format) { switch (format) { case VK_FORMAT_R8_UINT: case VK_FORMAT_R8G8_UINT: case VK_FORMAT_R8G8B8A8_UINT: case VK_FORMAT_R16_UINT: case VK_FORMAT_R16G16_UINT: case VK_FORMAT_R16G16B16A16_UINT: case VK_FORMAT_R32_UINT: case VK_FORMAT_R32G32_UINT: case VK_FORMAT_R32G32B32A32_UINT: case VK_FORMAT_A2B10G10R10_UINT_PACK32: return 1; case VK_FORMAT_R8_SINT: case VK_FORMAT_R8G8_SINT: case VK_FORMAT_R8G8B8A8_SINT: case VK_FORMAT_R16_SINT: case VK_FORMAT_R16G16_SINT: case VK_FORMAT_R16G16B16A16_SINT: case VK_FORMAT_R32_SINT: case VK_FORMAT_R32G32_SINT: case VK_FORMAT_R32G32B32A32_SINT: return 2; default: return 0; } } void release(const ImageEntry& entry) { // descriptor_mutex held const std::uint64_t slot_handle = (static_cast(entry.dimension) << 32) | static_cast(entry.index); context->defer_destroy(leonida::DeferredDeletionQueue::Kind::bindless_slot, slot_handle); if (entry.sampled) context->defer_destroy(leonida::DeferredDeletionQueue::Kind::image_view, entry.sampled); if (entry.storage) context->defer_destroy(leonida::DeferredDeletionQueue::Kind::image_view, entry.storage); } struct PendingSample { Resource* owner = nullptr; leonida::gfx10::Image image{}; VkFormat view_format{}, channels_format{}; }; std::mutex pending_view_mutex; std::map pending_samples; std::atomic pending_sample_count{}; bool materialize_sample(const leonida::DescriptorKey& key); bool materialize_table(std::uint64_t address,std::uint32_t slots); void remember_sample(const leonida::DescriptorKey& key, const PendingSample& sample) { std::lock_guard lock(pending_view_mutex); if (pending_samples.try_emplace(key,sample).second) { ++pending_sample_count; } } void retire_samples(Resource* owner) { std::lock_guard lock(pending_view_mutex); const auto removed=std::erase_if(pending_samples,[&](const auto& p){return p.second.owner==owner;}); pending_sample_count -= static_cast(removed); } struct VolumeSlices { UINT first = 0; UINT count = 0; // 0: no restriction (ordinary view of the whole mip) }; // Gives the T# `words` a view in set 0 and an entry in the hash table, unless it has them. `storage`: shaders // write through it too (an unordered-access view), so it also goes into the storage arrays, which are // shorter. False when set 0 cannot show the image; the descriptor then finds the fallback at index 0. bool bind_image(const leonida::gfx10::ImageWords& words, const leonida::gfx10::Image& image, VkImage vk_image, VkFormat image_format, VkImageAspectFlags aspects, bool storage, bool allow_channel_cast = false, VkFormat uint_backed = VK_FORMAT_UNDEFINED) { std::lock_guard lock(descriptor_mutex); return bind_image_locked(words, image, vk_image, image_format, aspects, storage, allow_channel_cast, uint_backed); } bool bind_image_locked(const leonida::gfx10::ImageWords& words, const leonida::gfx10::Image& image, VkImage vk_image, VkFormat image_format, VkImageAspectFlags aspects, bool storage, bool allow_channel_cast = false, VkFormat uint_backed = VK_FORMAT_UNDEFINED) { namespace g = leonida::gfx10; if (!bindless) return false; auto pending = pending_image_keys.find(vk_image); if (pending != pending_image_keys.end()) { pending->second.keys.try_emplace(words, image); if (!pending->second.zero) return true; vk_image = pending->second.zero; } const bool depth_or_stencil = (aspects & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) != 0; // A T# of 8_UINT on a depth-stencil image is a view of its stencil plane (image_descriptor, D3D-75). Vulkan // views it in the image's own format with the stencil aspect, and returns the value in R, as a T# whose // format is 8_UINT reads it from X. const bool stencil = (aspects & VK_IMAGE_ASPECT_STENCIL_BIT) && image.format == g::stencil_format; const VkFormat logical_format = uint_backed ? uint_backed : image_format; VkFormat view_format = stencil ? image_format : g::vulkan_view_format(logical_format, image.format, allow_channel_cast); VkFormat channels_format = view_format; // whose channels the T#'s swizzle selects from // A B4G4R4A4 render target stored as RGBA8 (no 4444 format renders on this device): a 16-bit view of the // 32-bit image is not allowed, so its 4_4_4_4 T# reads the RGBA8 image (which holds the logical R, G, B, A) // with the channels of A4R4G4B4, the format the texture has (DXGI_FORMAT_B4G4R4A4_UNORM). if (!stencil && image_format == VK_FORMAT_R8G8B8A8_UNORM && (view_format == VK_FORMAT_A4B4G4R4_UNORM_PACK16 || view_format == VK_FORMAT_A4R4G4B4_UNORM_PACK16)) { view_format = VK_FORMAT_R8G8B8A8_UNORM; channels_format = VK_FORMAT_A4R4G4B4_UNORM_PACK16; } if (view_format == VK_FORMAT_UNDEFINED) { // a 96-bit texture's T# names RGB32; its image is RGBA32 view_format = rgb96_view_format(image_format, image.format); channels_format = rgb96_named_format(view_format); } // A depth image can only be viewed in its own format, so a T# that names another format on it (the title's // T# of a console D16S8 target says 16-bit UNORM; the image is D24S8 or D32S8) is its depth plane, read as a // normalised value in X either way. if (depth_or_stencil && !stencil && (aspects & VK_IMAGE_ASPECT_DEPTH_BIT) && (view_format == VK_FORMAT_UNDEFINED || !g::is_depth_stencil_format(view_format))) { log_once("a T# names another format on a depth image; viewed as its depth plane, GFX10 format", int(image.format)); view_format = image_format; channels_format = image_format; } // A sampled view only samples: a view in a cast format the image's storage usage does not support (an R32 // target viewed as E5B9G9R9) stays valid (VUID-VkImageViewCreateInfo-usage-02274). const bool sampled_only = uint_backed || (view_format != image_format && view_format != VK_FORMAT_UNDEFINED); return bind_image_views_locked(words, image, vk_image, view_format, channels_format, uint_backed ? image_format : view_format, aspects, true, storage, {}, sampled_only); } // The same for a view whose formats the caller has worked out: `view_format` of the sampled view (made when // `sampled`), `channels_format` whose channels the T#'s swizzle selects from, `storage_format` of the storage view. bool bind_image(const leonida::gfx10::ImageWords& words, const leonida::gfx10::Image& image, VkImage vk_image, VkFormat view_format, VkFormat channels_format, VkFormat storage_format, VkImageAspectFlags aspects, bool sampled, bool storage, VolumeSlices slices) { std::lock_guard lock(descriptor_mutex); return bind_image_views_locked(words, image, vk_image, view_format, channels_format, storage_format, aspects, sampled, storage, slices, true); } bool bind_image_views_locked(const leonida::gfx10::ImageWords& words, const leonida::gfx10::Image& image, VkImage vk_image, VkFormat view_format, VkFormat channels_format, VkFormat storage_format, VkImageAspectFlags aspects, bool sampled, bool storage, VolumeSlices slices, bool sampled_only) { namespace g = leonida::gfx10; if (!bindless) { if (storage) log_once("unordered-access view needs the Vulkan bindless set; type", int(image.type)); return false; } if (const auto pending = pending_image_keys.find(vk_image); pending != pending_image_keys.end()) { pending->second.keys.try_emplace(words, image); if (!pending->second.zero) return true; vk_image = pending->second.zero; } const auto existing = image_entries.find(words); if (existing != image_entries.end() && (existing->second.storage || !storage)) return true; leonida::ImageDimension dimension; switch (image.type) { case g::ImageType::image_2d: dimension = leonida::ImageDimension::dim_2d; break; case g::ImageType::image_2d_array: case g::ImageType::cube: dimension = leonida::ImageDimension::dim_2d_array; break; case g::ImageType::image_3d: dimension = leonida::ImageDimension::dim_3d; break; case g::ImageType::image_1d: dimension = leonida::ImageDimension::dim_1d; break; case g::ImageType::image_1d_array: dimension = leonida::ImageDimension::dim_1d_array; break; case g::ImageType::image_2d_msaa: dimension = leonida::ImageDimension::dim_2d_ms; break; case g::ImageType::image_2d_msaa_array: dimension = leonida::ImageDimension::dim_2d_ms_array; break; default: log_once("set 0 has no array for this image type:", int(image.type)); return false; } const bool depth_or_stencil = (aspects & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) != 0; if (storage && depth_or_stencil) { log_once("storage view not supported for depth-stencil image format:", int(view_format)); return false; } if (view_format == VK_FORMAT_UNDEFINED || (depth_or_stencil && !g::is_depth_stencil_format(view_format))) { log_once("no Vulkan view format for the GFX10 format of a view:", int(image.format)); return false; } // A T# of 8_UINT on a depth-stencil image is a view of its stencil plane (image_descriptor, D3D-75). Vulkan // views it in the image's own format with the stencil aspect, and returns the value in R, as a T# whose // format is 8_UINT reads it from X. const bool stencil = (aspects & VK_IMAGE_ASPECT_STENCIL_BIT) && image.format == g::stencil_format; const unsigned sampled_class = g::multisampled(image.type) ? numeric_class(view_format) : 0; if (g::multisampled(image.type) && !bindless->supports_ms_class(sampled_class)) { log_once("set 0 has no multisample binding for this numeric class:", int(sampled_class)); return false; } auto& vk = context->vk; VkImageViewUsageCreateInfo view_usage{VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO}; view_usage.usage = VK_IMAGE_USAGE_SAMPLED_BIT; VkImageViewCreateInfo view_info{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; if (sampled_only) view_info.pNext = &view_usage; view_info.image = vk_image; view_info.viewType = g::vulkan_view_type(image.type); view_info.format = view_format; auto swizzle = image.swizzle; VkImageViewMinLodCreateInfoEXT clamp{VK_STRUCTURE_TYPE_IMAGE_VIEW_MIN_LOD_CREATE_INFO_EXT}; const bool supports_lod_clamp = image.type == g::ImageType::image_1d || image.type == g::ImageType::image_2d || image.type == g::ImageType::image_2d_array || image.type == g::ImageType::cube || image.type == g::ImageType::image_3d; if (!storage && supports_lod_clamp && (aspects & VK_IMAGE_ASPECT_COLOR_BIT)) { // Use the clamp in the T# itself: views with identical keys must sample identically. clamp.minLod = g::image_min_lod(words); if (clamp.minLod > float(image.first_mip + image.mip_count - 1)) { // The accessible mip set is empty. Keep the dimensions and constant/missing channels. for (auto& channel : swizzle) if (channel != g::select_one) channel = g::select_zero; } else if (clamp.minLod > float(image.first_mip)) { if (!info.image_view_min_lod) { log_once("SRV requires VK_EXT_image_view_min_lod; first mip", int(image.first_mip)); return false; } clamp.pNext = view_info.pNext; view_info.pNext = &clamp; } } view_info.components = g::vulkan_swizzle(swizzle, channels_format); view_info.subresourceRange = g::vulkan_subresource_range( image, stencil ? VK_IMAGE_ASPECT_STENCIL_BIT : (aspects & VK_IMAGE_ASPECT_DEPTH_BIT) ? VK_IMAGE_ASPECT_DEPTH_BIT : VK_IMAGE_ASPECT_COLOR_BIT); ImageEntry entry{dimension, 0, VK_NULL_HANDLE, VK_NULL_HANDLE, image.address}; if (sampled) { const VkResult result = vk.vkCreateImageView(info.device, &view_info, nullptr, &entry.sampled); if (result != VK_SUCCESS) { log_once("sampled image view creation failed:", result); return false; } } leonida::StorageViews views{}; if (storage) { VkImageViewCreateInfo storage_info = view_info; storage_info.components = {}; storage_info.format = storage_format; VkImageViewUsageCreateInfo storage_usage{VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO}; storage_usage.usage = VK_IMAGE_USAGE_STORAGE_BIT; VkImageViewSlicedCreateInfoEXT sliced{VK_STRUCTURE_TYPE_IMAGE_VIEW_SLICED_CREATE_INFO_EXT}; if (slices.count) { sliced.sliceOffset = slices.first; sliced.sliceCount = slices.count; storage_usage.pNext = &sliced; } storage_info.pNext = &storage_usage; const VkResult result = vk.vkCreateImageView(info.device, &storage_info, nullptr, &entry.storage); if (result != VK_SUCCESS) { log_once("storage image view creation failed:", result); if (entry.sampled) vk.vkDestroyImageView(info.device, entry.sampled, nullptr); return false; } const int numeric = numeric_class(storage_format); (numeric == 1 ? views.as_uint : numeric == 2 ? views.as_sint : views.as_float) = entry.storage; if (storage_format == VK_FORMAT_R32_UINT) views.r32ui = entry.storage; } // Every state a shader can read or write the texture in is GENERAL (ResourceBinding::sampled_in_general). entry.index = bindless->add_image(dimension, entry.sampled, VK_IMAGE_LAYOUT_GENERAL, views, sampled_class); if (!entry.index) { if (first_diagnostic("a bindless image array is full; dimension", int(dimension))) { // Whether the array holds live textures or stale views: the T#s it holds, the textures they name, // and the most T#s of one texture (a texture whose T#s keep changing, a streamed mip clamp say, // keeps an index for each until it goes). std::size_t entries = 0, replaced = 0, most = 0; std::map per_texture; for (const auto& [key, held] : image_entries) if (held.dimension == dimension) { ++entries; most = std::max(most, ++per_texture[held.address]); } for (const auto& held : replaced_images) replaced += held.dimension == dimension; std::fprintf(stderr, "[rt] d3d12: a bindless image array is full; dimension %d: %u indices, %zu T#s of %zu " "textures (at most %zu T#s of one), %zu replaced views kept; further T#s of this " "dimension read the fallback\n", int(dimension), bindless->image_capacity(dimension), entries, per_texture.size(), most, replaced); } if (entry.sampled) vk.vkDestroyImageView(info.device, entry.sampled, nullptr); if (entry.storage) vk.vkDestroyImageView(info.device, entry.storage, nullptr); return false; } if (existing != image_entries.end()) { replaced_images.push_back(existing->second); // the read-only entry of the same bytes existing->second = entry; } else { image_entries.emplace(words, entry); image_keys.emplace(image.address, words); } bindless->insert_key(words, entry.index); leonida::fsdraw::note_tsharp(words.data()); // LOCAL DIAGNOSTIC return true; } // Textures by the address their T#s name them by (Resource::image_address), for the T#s a title writes into a // console descriptor heap itself (bind_title_image). Under descriptor_mutex: a texture leaves it in forget_image, // before its image goes. TitleGpuPlacements gpu_placements; // descriptor_mutex std::map images_by_address; // a Resource void note_image_address(std::uint64_t address, const void* resource) { std::lock_guard lock(descriptor_mutex); images_by_address[address] = resource; } // The texture registered at `address` (a title-placed texture's address can be taken over by a later one). const void* image_owner(std::uint64_t address) { std::lock_guard lock(descriptor_mutex); const auto it = images_by_address.find(address); return it == images_by_address.end() ? nullptr : it->second; } // The texture at `address` is gone: its views leave set 0 and its T#s the hash table. void forget_image(std::uint64_t address) { std::lock_guard lock(descriptor_mutex); images_by_address.erase(address); forget_image_views_locked(address); } void forget_image_views_locked(std::uint64_t address) { if (!bindless) return; const auto [first, last] = image_keys.equal_range(address); for (auto it = first; it != last; ++it) { const auto entry = image_entries.find(it->second); bindless->erase_key(it->second); release(entry->second); image_entries.erase(entry); } image_keys.erase(first, last); std::erase_if(replaced_images, [&](const ImageEntry& entry) { if (entry.address != address) return false; release(entry); return true; }); } // Gives the S# `words` a sampler in set 0 and an entry in the hash table, unless it has them. bool bind_sampler(const leonida::gfx10::SamplerWords& words) { namespace g = leonida::gfx10; std::lock_guard lock(descriptor_mutex); if (!bindless) return false; const leonida::DescriptorKey key = leonida::make_ssharp_key(words.data()); if (sampler_entries.count(key)) return true; const g::Sampler sampler = g::decode(words); VkSamplerCreateInfo sampler_info = g::vulkan_sampler(sampler, max_sampler_lod_bias); // What vulkan_sampler leaves to its caller, and features this device may not have enabled. if (sampler_info.anisotropyEnable && !info.sampler_anisotropy) { log_once("anisotropic sampler without samplerAnisotropy; anisotropy", int(sampler.max_anisotropy)); sampler_info.anisotropyEnable = VK_FALSE; } for (VkSamplerAddressMode* mode : {&sampler_info.addressModeU, &sampler_info.addressModeV, &sampler_info.addressModeW}) { if (*mode != VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE || info.sampler_mirror_clamp_to_edge) continue; log_once("mirror-once sampler without samplerMirrorClampToEdge; clamped instead, mode", int(*mode)); *mode = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; } VkSamplerReductionModeCreateInfo reduction{VK_STRUCTURE_TYPE_SAMPLER_REDUCTION_MODE_CREATE_INFO}; if (sampler.filter_mode != g::FilterMode::blend) { if (info.sampler_filter_minmax && !sampler_info.compareEnable) { reduction.reductionMode = g::vulkan_reduction_mode(sampler.filter_mode); reduction.pNext = sampler_info.pNext; sampler_info.pNext = &reduction; } else { log_once("minimum/maximum filter sampler without samplerFilterMinmax; blended instead, mode", int(sampler.filter_mode)); } } VkSamplerCustomBorderColorCreateInfoEXT custom_border{ VK_STRUCTURE_TYPE_SAMPLER_CUSTOM_BORDER_COLOR_CREATE_INFO_EXT}; if (sampler.border_color == g::BorderColor::table) { const bool is_int = sampler.border_color_index < border_color_table.size() && border_color_table[sampler.border_color_index].is_int; if (info.custom_border_color && info.custom_border_color_without_format && sampler.border_color_index < border_color_table.size()) { const auto& entry = border_color_table[sampler.border_color_index]; custom_border.customBorderColor = entry.value; custom_border.format = VK_FORMAT_UNDEFINED; sampler_info.borderColor = entry.is_int ? VK_BORDER_COLOR_INT_CUSTOM_EXT : VK_BORDER_COLOR_FLOAT_CUSTOM_EXT; custom_border.pNext = sampler_info.pNext; sampler_info.pNext = &custom_border; } else { sampler_info.borderColor = is_int ? VK_BORDER_COLOR_INT_TRANSPARENT_BLACK : VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK; log_once("custom sampler border colours without VK_EXT_custom_border_color; transparent black instead, index", int(sampler.border_color_index)); } } VkSampler vk_sampler = VK_NULL_HANDLE; if (!context->vk.vkCreateSampler || context->vk.vkCreateSampler(info.device, &sampler_info, nullptr, &vk_sampler) != VK_SUCCESS) return false; const std::uint32_t index = bindless->add_sampler(vk_sampler); if (!index) { log_once("the bindless sampler array is full; samplers", int(sampler_entries.size())); context->vk.vkDestroySampler(info.device, vk_sampler, nullptr); return false; } sampler_entries.emplace(key, vk_sampler); bindless->insert_key(key, index); return true; } // An optimal-tiling image of this format can take VK_IMAGE_USAGE_HOST_TRANSFER_BIT_EXT. bool host_transfer_format(VkFormat format) const { if (!copy_memory_to_image || !format_properties2) return false; VkFormatProperties3 properties3{VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_3}; VkFormatProperties2 properties{VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_2, &properties3}; format_properties2(info.physical, format, &properties); return properties3.optimalTilingFeatures & VK_FORMAT_FEATURE_2_HOST_IMAGE_TRANSFER_BIT_EXT; } // A memory type with `required`, preferring one that also has `preferred`, in a heap large enough for the // allocation (leonida::memory_type_order). `chosen`, when given, receives the property flags of the type the // memory came from. // Held around every vkAllocateMemory of this device, host-pointer imports included (see allocate). static std::mutex& memory_mutex() { static std::mutex mutex; return mutex; } VkDeviceMemory allocate(const VkMemoryRequirements& requirements, VkMemoryPropertyFlags required, VkMemoryPropertyFlags preferred, VkMemoryPropertyFlags* chosen = nullptr, bool device_address = false, std::uint32_t* chosen_type = nullptr, VkImage dedicated_image = VK_NULL_HANDLE) const { VkMemoryAllocateFlagsInfo flags_info{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO}; flags_info.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT; for (const std::uint32_t i : leonida::memory_type_order(memory, requirements.memoryTypeBits, required, preferred, requirements.size)) { VkMemoryAllocateInfo allocate{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; if (device_address) allocate.pNext = &flags_info; VkMemoryDedicatedAllocateInfo dedicated{VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO}; if (dedicated_image) { dedicated.image = dedicated_image; dedicated.pNext = allocate.pNext; allocate.pNext = &dedicated; } allocate.allocationSize = requirements.size; allocate.memoryTypeIndex = i; VkDeviceMemory out = VK_NULL_HANDLE; // The NVIDIA driver (620.73 under Wine) answers VK_ERROR_OUT_OF_HOST_MEMORY for a few-KiB allocation now // and then while other threads import host pointers that the kernel module cannot pin (journal: "Cannot // map memory with base addr ..."), with gigabytes free. The title asserts on the texture it loses. So // allocations and imports take turns (memory_mutex), and that answer is retried before it is believed. // // The retries are only worth their sleeps while some of them succeed: after the load a title placement // that fails this way failed every retry (speed-25/26: none recovered), and each failing memory type cost // the caller 15 ms of Sleep (the title's Subrender workers, slot 133), before the next type succeeded. So // while fewer than one in 16 of the recent retried allocations recovered (both counts are halved every 64 // retried allocations, so one recovery at boot does not keep them on), one attempt per type is made; one // failure in 64 still retries, to notice when they help again. static std::atomic retried{0}, recovered_total{0}, failures{0}; const std::uint32_t recent = retried.load(std::memory_order_relaxed); const bool retry = recent < 32 || recovered_total.load(std::memory_order_relaxed) * 16 >= recent || failures.load(std::memory_order_relaxed) % 64 == 0; VkResult allocated = VK_ERROR_OUT_OF_HOST_MEMORY; for (int attempt = 0; attempt < (retry ? 6 : 1) && allocated == VK_ERROR_OUT_OF_HOST_MEMORY; ++attempt) { if (attempt) Sleep(attempt); std::lock_guard serial(memory_mutex()); allocated = context->vk.vkAllocateMemory(info.device, &allocate, nullptr, &out); if (attempt == 1 && retried.fetch_add(1, std::memory_order_relaxed) + 1 >= 64) { retried.store(32, std::memory_order_relaxed); // halve both (racy, approximate is enough) recovered_total.store(recovered_total.load(std::memory_order_relaxed) / 2, std::memory_order_relaxed); } if (attempt && allocated == VK_SUCCESS) { recovered_total.fetch_add(1, std::memory_order_relaxed); static std::atomic recovered{0}; if (recovered.fetch_add(1, std::memory_order_relaxed) < 8) std::fprintf(stderr, "[rt] d3d12: vkAllocateMemory succeeded on retry %d after out-of-host-memory (%llu " "bytes, type %u)\n", attempt, static_cast(requirements.size), i); } } if (allocated == VK_ERROR_OUT_OF_HOST_MEMORY) failures.fetch_add(1, std::memory_order_relaxed); if (allocated != VK_SUCCESS) { static std::atomic logged{0}; if (logged.fetch_add(1, std::memory_order_relaxed) < 16) std::fprintf(stderr, "[rt] d3d12: vkAllocateMemory failed (%d): %llu bytes, memory type %u (flags 0x%x, heap " "%u of %llu MiB), device address %d\n", int(allocated), static_cast(requirements.size), i, unsigned(memory.memoryTypes[i].propertyFlags), memory.memoryTypes[i].heapIndex, static_cast(memory.memoryHeaps[memory.memoryTypes[i].heapIndex].size >> 20), int(device_address)); } if (allocated == VK_SUCCESS) { if (chosen) *chosen = memory.memoryTypes[i].propertyFlags; if (chosen_type) *chosen_type = i; if (leonida::spilled_to_host(required, preferred, memory.memoryTypes[i].propertyFlags)) std::call_once(spill_logged, [&] { const std::uint32_t heap = memory.memoryTypes[i].heapIndex; std::fprintf(stderr, "[rt] d3d12: a %llu-byte allocation did not fit in device-local memory and went " "to memory type %u (heap %u, %llu MiB); later ones are not logged\n", static_cast(requirements.size), i, heap, static_cast(memory.memoryHeaps[heap].size >> 20)); }); return out; } } return VK_NULL_HANDLE; } // A range of a device-local block for a texture, or null: the texture is too large to share one, or device-local // memory has no room for another block, and the caller makes its own allocation as it would without the blocks. std::unique_ptr allocate_image(const VkMemoryRequirements& requirements, VkMemoryPropertyFlags& chosen) { for (const std::uint32_t i : leonida::memory_type_order(memory, requirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, 0, requirements.size)) { const VkDeviceSize block = leonida::image_block_bytes(memory.memoryHeaps[memory.memoryTypes[i].heapIndex].size); if (requirements.size > block / 8) continue; if (auto range = image_memory->allocate(i, requirements.size, requirements.alignment, block)) { chosen = memory.memoryTypes[i].propertyFlags; return range; } } return nullptr; } }; // The Vulkan format for a texture this layer can create, with the D24 fallback; VK_FORMAT_UNDEFINED, after a log // line, when it cannot. Committed and placed textures share it so both refuse the same formats for the same reason. Format texture_format(const DeviceState& device, const D3D12_RESOURCE_DESC& desc) { Format format = vulkan_format(desc.Format, desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL); if(format.format==VK_FORMAT_D16_UNORM_S8_UINT) {format.xbox_depth16_stencil8=true;format.format=device.depth_backing(format.format);return format;} if(desc.Format==DXGI_FORMAT_B4G4R4A4_UNORM && (desc.Flags&D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) && !device.color_attachment_usable(format.format)) { if(!device.color_attachment_usable(VK_FORMAT_R8G8B8A8_UNORM))return {}; format.format=VK_FORMAT_R8G8B8A8_UNORM;format.rgba4_render_fallback=true; } if (format.format == VK_FORMAT_D24_UNORM_S8_UINT && !device.depth_usable(format.format)) { log_once("D24_UNORM_S8_UINT unavailable, using D32_SFLOAT_S8_UINT; format", desc.Format); format.format = VK_FORMAT_D32_SFLOAT_S8_UINT; } if (format.format == VK_FORMAT_UNDEFINED) log_once("texture format not supported yet:", desc.Format); return format; } // The castable-format list a committed or placed texture was created with, mapped to Vulkan (D3D-85's committed // path, D3D-90's placed one). Each format must map and be the same texel size as the resource's: the host PC // runtime refuses other sizes, and a size-mismatched VkImageFormatListCreateInfo is a Vulkan validation error // (VUID-VkImageCreateInfo-pNext-06722). A nonzero count with a null list is no list. E_INVALIDARG on a bad format. // An A8_UNORM texture's own format is always viewable (create_texture adds the image's format), so naming it is a // no-op. An A8 render target's VK_FORMAT_A8_UNORM_KHR image (Format::a8_as_alpha) is in a class of its own: no // other format can be a view format of it, so any other castable format is refused here, before Vulkan. HRESULT castable_view_formats(const Format& format, DXGI_FORMAT resource_format, UINT32 count, const DXGI_FORMAT* castable, std::vector& out, bool depth_uav_planes = false) { if (!count || !castable) return S_OK; const bool depth = (format.aspects & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) != 0; const leonida::BlockFormat own = leonida::block_format(format.format, format.aspects); for (UINT32 i = 0; i < count; ++i) { if (resource_format == DXGI_FORMAT_A8_UNORM && castable[i] == DXGI_FORMAT_A8_UNORM) continue; if (format.a8_as_alpha) { log_once("castable format of an A8_UNORM render target not supported (only A8_UNORM is):", castable[i]); return E_INVALIDARG; } if (depth_uav_planes) { // Attachment and sampled views use the original depth image's VkFormat. Each typed UAV // already has its own image; putting its colour format on the depth image is invalid. const DXGI_FORMAT view = castable[i]; const bool valid = format.format == VK_FORMAT_D16_UNORM ? view == DXGI_FORMAT_R16_TYPELESS || view == DXGI_FORMAT_D16_UNORM || view == DXGI_FORMAT_R16_UNORM || view == DXGI_FORMAT_R16_UINT : view == DXGI_FORMAT_R32G8X24_TYPELESS || view == DXGI_FORMAT_D32_FLOAT_S8X24_UINT || view == DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS || view == DXGI_FORMAT_X32_TYPELESS_G8X24_UINT || view == DXGI_FORMAT_R32_FLOAT || view == DXGI_FORMAT_R8_UINT; if (!valid) return E_INVALIDARG; continue; } const Format cast = vulkan_format(castable[i], depth); if (cast.format == VK_FORMAT_UNDEFINED) { log_once("castable format not supported yet:", castable[i]); return E_INVALIDARG; } const leonida::BlockFormat block = leonida::block_format(cast.format, cast.aspects); if (own.bytes && block.bytes && (block.bytes != own.bytes || block.block != own.block)) { log_once("castable format is a different texel size than the resource:", castable[i]); return E_INVALIDARG; } if (std::find(out.begin(), out.end(), cast.format) == out.end()) out.push_back(cast.format); } return S_OK; } // Argument checks the host PC runtime makes (without the debug layer) before it creates anything, so the layer // returns the same HRESULTs. Each rule was measured against the host runtime by d3d12_vulkan_device_test // (compare_invalid_arguments, D3D-49); the texture size, mip, sample-count and alignment rules are in // GetResourceAllocationInfo's allocation(), which CreateCommittedResource also applies. // The typeless format a DXGI format can be cast within, or the format itself when it has no such family. DXGI_FORMAT format_family(DXGI_FORMAT format) { if (format==xbox_d16s8 || format==xbox_d16_plane || format==xbox_s8_plane) return xbox_d16s8; const int f = int(format); const auto in = [f](int first, int last) { return f >= first && f <= last; }; if (in(1, 4)) return DXGI_FORMAT_R32G32B32A32_TYPELESS; if (in(5, 8)) return DXGI_FORMAT_R32G32B32_TYPELESS; if (in(9, 14)) return DXGI_FORMAT_R16G16B16A16_TYPELESS; if (in(15, 18)) return DXGI_FORMAT_R32G32_TYPELESS; if (in(19, 22)) return DXGI_FORMAT_R32G8X24_TYPELESS; if (in(23, 25)) return DXGI_FORMAT_R10G10B10A2_TYPELESS; if (in(27, 32)) return DXGI_FORMAT_R8G8B8A8_TYPELESS; if (in(33, 38)) return DXGI_FORMAT_R16G16_TYPELESS; if (in(39, 43)) return DXGI_FORMAT_R32_TYPELESS; if (in(44, 47)) return DXGI_FORMAT_R24G8_TYPELESS; if (in(48, 52)) return DXGI_FORMAT_R8G8_TYPELESS; if (in(53, 59)) return DXGI_FORMAT_R16_TYPELESS; if (in(60, 64)) return DXGI_FORMAT_R8_TYPELESS; if (in(70, 72)) return DXGI_FORMAT_BC1_TYPELESS; if (in(73, 75)) return DXGI_FORMAT_BC2_TYPELESS; if (in(76, 78)) return DXGI_FORMAT_BC3_TYPELESS; if (in(79, 81)) return DXGI_FORMAT_BC4_TYPELESS; if (in(82, 84)) return DXGI_FORMAT_BC5_TYPELESS; if (f == 87 || in(90, 91)) return DXGI_FORMAT_B8G8R8A8_TYPELESS; if (f == 88 || in(92, 93)) return DXGI_FORMAT_B8G8R8X8_TYPELESS; if (in(94, 96)) return DXGI_FORMAT_BC6H_TYPELESS; if (in(97, 99)) return DXGI_FORMAT_BC7_TYPELESS; return format; } // ALLOW_DEPTH_STENCIL: the host accepts every format of a family with a depth member (R32_FLOAT and R16_FLOAT // included) and nothing else. bool depth_stencil_family(DXGI_FORMAT format) { // The console's own D16S8 family (DXGI 118-120) counts as the D24S8 family it is made of here (pc_format). if (format_family(format) == xbox_d16s8) return true; const DXGI_FORMAT family = format_family(pc_format(format)); return family == DXGI_FORMAT_R32_TYPELESS || family == DXGI_FORMAT_R16_TYPELESS || family == DXGI_FORMAT_R24G8_TYPELESS || family == DXGI_FORMAT_R32G8X24_TYPELESS; } // ALLOW_RENDER_TARGET: the host refuses the families below and accepts the rest, D32_FLOAT, D16_UNORM, // R9G9B9E5_SHAREDEXP and NV12 among them. R32G32B32 is the driver's answer (refused by both AMD drivers measured, // accepted by WARP); it is refused here, since Vulkan drivers rarely render to it. bool render_target_family(DXGI_FORMAT format) { switch (format_family(format)) { case DXGI_FORMAT_R32G32B32_TYPELESS: case DXGI_FORMAT_R32G8X24_TYPELESS: case DXGI_FORMAT_R24G8_TYPELESS: case DXGI_FORMAT_R1_UNORM: case DXGI_FORMAT_R8G8_B8G8_UNORM: case DXGI_FORMAT_G8R8_G8B8_UNORM: case DXGI_FORMAT_BC1_TYPELESS: case DXGI_FORMAT_BC2_TYPELESS: case DXGI_FORMAT_BC3_TYPELESS: case DXGI_FORMAT_BC4_TYPELESS: case DXGI_FORMAT_BC5_TYPELESS: case DXGI_FORMAT_BC6H_TYPELESS: case DXGI_FORMAT_BC7_TYPELESS: return false; default: return true; } } // Why the host would refuse these heap properties, or null if it accepts them. `uma` is the device's // D3D12_FEATURE_ARCHITECTURE answer: a UMA adapter has no MEMORY_POOL_L1, and the host refuses a custom heap in it // (measured on a Radeon 780M, AMD 32.0.13030.13001, and on WARP: E_INVALIDARG from CreateHeap and // CreateCommittedResource for every CPU page property). const char* heap_properties_refusal(const D3D12_HEAP_PROPERTIES& heap, bool uma) { if (heap.Type < D3D12_HEAP_TYPE_DEFAULT || heap.Type > D3D12_HEAP_TYPE_GPU_UPLOAD) return "heap type"; // CheckFeatureSupport reports OPTIONS16.GPUUploadHeapSupported FALSE, and a host runtime without GPU upload heaps // (Resizable BAR off) refuses the type. if (heap.Type == D3D12_HEAP_TYPE_GPU_UPLOAD) return "GPU upload heap, which OPTIONS16 reports unsupported"; const bool custom = heap.Type == D3D12_HEAP_TYPE_CUSTOM; const bool page_given = heap.CPUPageProperty != D3D12_CPU_PAGE_PROPERTY_UNKNOWN; const bool pool_given = heap.MemoryPoolPreference != D3D12_MEMORY_POOL_UNKNOWN; if (custom ? !(page_given && pool_given) : (page_given || pool_given)) return "CPU page property or memory pool (given only, and both, on custom heaps)"; if (heap.CreationNodeMask > 1 || heap.VisibleNodeMask > 1) return "node mask (one node)"; if (uma && custom && heap.MemoryPoolPreference == D3D12_MEMORY_POOL_L1) return "MEMORY_POOL_L1 on a UMA adapter"; return nullptr; } // Why the host would refuse this CreateHeap description, or null if these checks pass (D3D-238). A probe on an // RX 5700 and WARP refuses an alignment other than 0, 64 KiB and 4 MiB, the heap properties above (a type of 0, a // custom heap without a CPU page property), and a heap that denies buffers and both kinds of texture. ALLOW_DISPLAY // (CreateCommittedResource on a default heap only, per the D3D12_HEAP_FLAGS documentation) is refused too, confirmed // on an RTX 4070 SUPER and a UHD 770 host by @CowBoYdu76. Those hosts accept HARDWARE_PROTECTED, so it is not refused. const char* heap_desc_refusal(const D3D12_HEAP_DESC& desc, bool uma) { if (!desc.SizeInBytes) return "zero size"; if (desc.Alignment && desc.Alignment != D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT && desc.Alignment != D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT) return "alignment (0, 64 KiB or 4 MiB)"; if (const char* why = heap_properties_refusal(desc.Properties, uma)) return why; constexpr UINT deny_all = D3D12_HEAP_FLAG_DENY_BUFFERS | D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES | D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES; if ((UINT(desc.Flags) & deny_all) == deny_all) return "heap flags denying every resource kind"; if (UINT(desc.Flags) & D3D12_HEAP_FLAG_ALLOW_DISPLAY) return "ALLOW_DISPLAY (committed resources only)"; return nullptr; } // Why the host would refuse this committed resource, or null if these checks pass. The flag and format tables were // measured on an RX 9070 XT, an integrated Radeon and WARP, which agree on all of them. Cross-adapter resources // (valid there only as a row-major texture on a SHARED | SHARED_CROSS_ADAPTER heap) are refused: this layer has no // cross-adapter sharing. // The initial state a committed, placed or reserved resource may start in, as the host runtime answers it // (d3d12_vulkan_device_test's compare_placed_reserved and its "committed: ... state" cases, RTX 3060 / 610.88). // A buffer takes any bits, unknown ones too, except RAYTRACING_ACCELERATION_STRUCTURE without UAV access, or at all // on a device without acceleration structures (the host refuses it where OPTIONS5 reports no ray tracing: an // integrated Radeon, measured by @aguedou-34 on #2462; here, a device with neither the KHR acceleration structures // nor the XDXR builds). A texture // takes exactly GENERIC_READ, or one write state alone (RENDER_TARGET, UNORDERED_ACCESS and DEPTH_WRITE need the // matching resource flag), or any mix of read states (DEPTH_READ needs ALLOW_DEPTH_STENCIL; the shader-resource // states are refused with DENY_SHADER_RESOURCE). The buffer-only bits (vertex/constant, index, indirect, stream // output, acceleration structure) and undefined bits are refused on a texture, also inside a mix. const char* initial_state_refusal(bool buffer, UINT flags, D3D12_RESOURCE_STATES state, bool acceleration_structures) { const UINT s = UINT(state); if (buffer) { if ((s & D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE) && !acceleration_structures) return "acceleration-structure state on a device without acceleration structures"; if ((s & D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE) && !(flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) return "acceleration-structure state on a buffer without UAV access"; return nullptr; } if (s == D3D12_RESOURCE_STATE_GENERIC_READ) return nullptr; constexpr UINT writes = D3D12_RESOURCE_STATE_RENDER_TARGET | D3D12_RESOURCE_STATE_UNORDERED_ACCESS | D3D12_RESOURCE_STATE_DEPTH_WRITE | D3D12_RESOURCE_STATE_COPY_DEST | D3D12_RESOURCE_STATE_RESOLVE_DEST | D3D12_RESOURCE_STATE_VIDEO_DECODE_WRITE | D3D12_RESOURCE_STATE_VIDEO_PROCESS_WRITE | D3D12_RESOURCE_STATE_VIDEO_ENCODE_WRITE; constexpr UINT shader_reads = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; constexpr UINT reads = D3D12_RESOURCE_STATE_DEPTH_READ | shader_reads | D3D12_RESOURCE_STATE_COPY_SOURCE | D3D12_RESOURCE_STATE_RESOLVE_SOURCE | D3D12_RESOURCE_STATE_SHADING_RATE_SOURCE | D3D12_RESOURCE_STATE_VIDEO_DECODE_READ | D3D12_RESOURCE_STATE_VIDEO_PROCESS_READ | D3D12_RESOURCE_STATE_VIDEO_ENCODE_READ; if (s & ~(writes | reads)) return "initial state of a texture (buffer-only or undefined bits)"; if (s & writes) { if (s & (s - 1)) return "initial state of a texture (a write state with another state)"; if (s == D3D12_RESOURCE_STATE_RENDER_TARGET && !(flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET)) return "RENDER_TARGET state without ALLOW_RENDER_TARGET"; if (s == D3D12_RESOURCE_STATE_UNORDERED_ACCESS && !(flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) return "UNORDERED_ACCESS state without ALLOW_UNORDERED_ACCESS"; if (s == D3D12_RESOURCE_STATE_DEPTH_WRITE && !(flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) return "DEPTH_WRITE state without ALLOW_DEPTH_STENCIL"; return nullptr; } if ((s & D3D12_RESOURCE_STATE_DEPTH_READ) && !(flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) return "DEPTH_READ state without ALLOW_DEPTH_STENCIL"; if ((s & shader_reads) && (flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE)) return "shader-resource state with DENY_SHADER_RESOURCE"; return nullptr; } const char* committed_resource_refusal(const D3D12_HEAP_PROPERTIES& heap, D3D12_HEAP_FLAGS heap_flags, const D3D12_RESOURCE_DESC& desc, D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear, bool acceleration_structures, bool uma) { if (const char* why = heap_properties_refusal(heap, uma)) return why; // The DENY flags of a committed resource's heap are the runtime's to choose; most other bits are refused too. constexpr UINT committed_heap_flags = D3D12_HEAP_FLAG_SHARED | D3D12_HEAP_FLAG_ALLOW_DISPLAY | D3D12_HEAP_FLAG_HARDWARE_PROTECTED | D3D12_HEAP_FLAG_CREATE_NOT_RESIDENT | D3D12_HEAP_FLAG_CREATE_NOT_ZEROED | D3D12_HEAP_FLAG_ALLOW_SHADER_ATOMICS; if (UINT(heap_flags) & ~committed_heap_flags) return "heap flags of a committed resource"; const bool buffer = desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER; // 0x400 is not in this SDK's d3d12.h (10.0.26100), but the host accepts it on buffers and textures; 0x200 and // 0x800 it refuses. RAYTRACING_ACCELERATION_STRUCTURE is accepted on a texture too. constexpr UINT buffer_flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS | D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE | D3D12_RESOURCE_FLAG_RAYTRACING_ACCELERATION_STRUCTURE | 0x400; constexpr UINT texture_flags = buffer_flags | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS; const UINT flags = UINT(desc.Flags); if (flags & ~(buffer ? buffer_flags : texture_flags)) return "resource flags"; const bool rt = flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; const bool ds = flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; const bool uav = flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; // ALLOW_SHADER_ATOMICS is for a resource shaders can write: RTX 4070 Laptop (621.24) and WARP refuse it without // ALLOW_UNORDERED_ACCESS, on buffers and textures alike. It changes nothing on one adapter; GetHeapProperties keeps it. if ((UINT(heap_flags) & D3D12_HEAP_FLAG_ALLOW_SHADER_ATOMICS) && !uav) return "ALLOW_SHADER_ATOMICS without ALLOW_UNORDERED_ACCESS"; // Upload heaps start in (a part of) GENERIC_READ, readback heaps in COPY_DEST; COMMON on both; no UAVs. if (heap.Type == D3D12_HEAP_TYPE_UPLOAD && (uav || (UINT(state) & ~UINT(D3D12_RESOURCE_STATE_GENERIC_READ)))) return "upload heap state or UAV"; if (heap.Type == D3D12_HEAP_TYPE_READBACK && (uav || (UINT(state) & ~UINT(D3D12_RESOURCE_STATE_COPY_DEST)))) return "readback heap state or UAV"; if (const char* why = initial_state_refusal(buffer, flags, state, acceleration_structures)) return why; if (buffer) { if (!desc.Width || desc.Height != 1 || desc.DepthOrArraySize != 1 || desc.MipLevels != 1 || desc.Format != DXGI_FORMAT_UNKNOWN || desc.SampleDesc.Count != 1 || desc.SampleDesc.Quality != 0 || desc.Layout != D3D12_TEXTURE_LAYOUT_ROW_MAJOR) return "buffer description"; if (desc.Alignment && desc.Alignment != D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT) return "buffer alignment"; if (clear) return "clear value on a buffer"; if (heap_flags & D3D12_HEAP_FLAG_ALLOW_DISPLAY) return "display heap for a buffer"; return nullptr; } if (desc.Dimension < D3D12_RESOURCE_DIMENSION_TEXTURE1D || desc.Dimension > D3D12_RESOURCE_DIMENSION_TEXTURE3D) return "resource dimension"; if ((rt && ds) || (ds && uav) || ((flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) && !ds)) { return "resource flag combination"; } if (ds && !depth_stencil_family(desc.Format)) return "depth-stencil format"; if (rt && !render_target_family(desc.Format)) return "render-target format"; const UINT samples = desc.SampleDesc.Count; if (samples > 1 && !rt && !ds) return "multisampled texture that is not a render target or depth buffer"; // Every adapter measured reports one quality level; the two standard patterns are accepted too. They are spelled // with the DXGI names: D3D12_STANDARD/CENTER_MULTISAMPLE_PATTERN, the same values, are only in d3d12.h from // DirectX-Headers 1.613 on, and older Windows SDK 10.0.26100 headers lack them. if (samples > 1 && desc.SampleDesc.Quality && desc.SampleDesc.Quality != DXGI_STANDARD_MULTISAMPLE_QUALITY_PATTERN && desc.SampleDesc.Quality != DXGI_CENTER_MULTISAMPLE_QUALITY_PATTERN) return "sample quality"; // A clear value is only for render targets and depth buffers, in the resource's format family. if (clear && (!(rt || ds) || clear->Format == DXGI_FORMAT_UNKNOWN || format_family(clear->Format) != format_family(desc.Format))) return "clear value"; return nullptr; } // Why the host refuses this enhanced-barrier initial layout for `desc`, or null when valid (measured on Windows D3D12). const char* barrier_layout_refusal(const D3D12_RESOURCE_DESC& desc, D3D12_BARRIER_LAYOUT layout) { if (desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) return layout == D3D12_BARRIER_LAYOUT_UNDEFINED ? nullptr : "buffer barrier layout"; const UINT flags = UINT(desc.Flags); switch (layout) { case D3D12_BARRIER_LAYOUT_RENDER_TARGET: return (flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) ? nullptr : "RENDER_TARGET barrier layout"; case D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS: case D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_UNORDERED_ACCESS: case D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_UNORDERED_ACCESS: return (flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) ? nullptr : "UNORDERED_ACCESS barrier layout"; case D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_WRITE: case D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_READ: return (flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) ? nullptr : "DEPTH_STENCIL barrier layout"; case D3D12_BARRIER_LAYOUT_SHADER_RESOURCE: case D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_SHADER_RESOURCE: case D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_SHADER_RESOURCE: return (flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) ? "SHADER_RESOURCE barrier layout" : nullptr; default: return nullptr; } } // Console Xbox D3D12 CreateDescriptorHeap (device slot 14) passes the PC description followed by the heap address // and size, as measured in the retail boot (issue #313 comment 7107265058): a 16-byte PC D3D12_DESCRIPTOR_HEAP_DESC, // then address at +0x10 and size at +0x18. The title asserts GetCPUDescriptorHandleForHeapStart() == address. // Backing this range with title memory / section 3.3 aliasing is tracked separately; this path only satisfies the // observed ABI contract and must not be inferred from normal PC 16-byte CreateDescriptorHeap calls. // LOCAL DIAGNOSTIC (desc-probe): records what a descriptor write through our API left in a console-heap slot. struct ProbeApiWrite { DeviceState& state; SIZE_T ptr; UINT count; const char* what; ~ProbeApiWrite() { state.probe_api(ptr, count, what); state.probe_view(what, ptr, count); } }; struct ConsoleDescriptorHeapDesc { D3D12_DESCRIPTOR_HEAP_DESC desc{}; std::uint64_t address = 0; std::uint64_t size = 0; }; class DescriptorHeap final : public Child { public: // {4a7d2c90-5e1b-4f63-8c0a-91d3b6e2f417} static constexpr GUID kTag{0x4a7d2c90, 0x5e1b, 0x4f63, {0x8c, 0x0a, 0x91, 0xd3, 0xb6, 0xe2, 0xf4, 0x17}}; // A shader-visible heap lives in the GPU address arena: its CPU handles point at the arena's host mapping and // its GPU handle is the console VA, so the bytes the game or Create*View writes are what shaders load. Other // heaps (RTV, DSV, non-visible staging heaps) stay in host memory. // A shader-visible heap that the arena cannot hold is not created (ok() is false, E_OUTOFMEMORY), as a // default-heap buffer is not: in host memory its GPU handle would be 0, and every table would read VA 0. DescriptorHeap(DeviceState& device, const D3D12_DESCRIPTOR_HEAP_DESC& desc, std::uint64_t console_address = 0, std::uint64_t console_size = 0) : device_(device), desc_(desc), console_address_(console_address), console_size_(console_size), console_addressed_(console_address != 0) { const VkDeviceSize bytes = VkDeviceSize(desc_.NumDescriptors) * kDescriptorSize; if (console_addressed_) { // The retail boot checks GetCPUDescriptorHandleForHeapStart() == address, so the CPU handles are the // title's memory and the GPU handles its console VA. A shader-visible heap there is read by shaders from // an arena copy the device keeps up to date (DeviceState::add_console_heap). cpu_ = reinterpret_cast(static_cast(console_address_)); in_arena_ = false; if ((desc_.Flags & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE) && console_heap_shadow_enabled()) shadowed_ = device.add_console_heap(console_address_, bytes, console_shader_va_, desc_.Type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); if (!shadowed_ && (desc_.Flags & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE)) log_once("descriptor heap uses console address/size, which no shader reads (no GPU view); type", int(desc_.Type)); if (desc_.Type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV && // LOCAL DIAGNOSTIC (desc_.Flags & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE)) device.probe_add(console_address_, shadowed_ ? console_shader_va_ : console_address_, desc_.NumDescriptors, shadowed_); return; } if ((desc_.Flags & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE) && device.arena.mapped) { // A bindless-sized resource heap (64Ki slots or more: what a shader indexes directly) is followed by null // slots, as a console heap's copy is (DeviceState::heap_guard_bytes); a smaller one, or one the arena has // no room for with them, is not. const VkDeviceSize guard = desc_.Type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV && desc_.NumDescriptors >= 65536 ? DeviceState::heap_guard_bytes() : 0; if (guard && device.arena_allocate(bytes + guard, 256, arena_offset_, DeviceState::arena_descriptor_heap)) guard_ = guard; else if (!device.arena_allocate(bytes, 256, arena_offset_, DeviceState::arena_descriptor_heap)) { log_once("GPU address arena full (raise LEONIDA_ARENA_MB); shader-visible heap size in KiB:", int(std::min(bytes / 1024, INT_MAX))); return; } in_arena_ = true; cpu_ = device.arena.mapped + arena_offset_; std::memset(cpu_, 0, std::size_t(bytes + guard_)); if (desc.Type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV || desc.Type == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER) { std::lock_guard lock(device.visible_heap_mutex); device.visible_heaps[arena_offset_] = {arena_offset_ + bytes, desc.Type}; } if (desc.Type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) { std::lock_guard lock(device.cbv_heap_mutex); device.cbv_heaps[arena_offset_] = arena_offset_ + bytes; } } else { storage_.reset(new std::byte[std::size_t(bytes)]()); cpu_ = reinterpret_cast(storage_.get()); } if (cpu_ && !(desc_.Flags & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE) && desc_.Type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) { std::lock_guard lock(device_.visible_heap_mutex); const auto begin = reinterpret_cast(cpu_); device_.cpu_view_heaps[begin] = begin + bytes; registered_cpu_views_ = true; } } ~DescriptorHeap() override { if (console_addressed_) device_.probe_remove(console_address_); // LOCAL DIAGNOSTIC if (shadowed_) device_.remove_console_heap(console_address_); if (registered_cpu_views_) { std::lock_guard lock(device_.visible_heap_mutex); device_.cpu_view_heaps.erase(reinterpret_cast(cpu_)); } if (in_arena_) { std::lock_guard lock(device_.visible_heap_mutex); device_.visible_heaps.erase(arena_offset_); } if (in_arena_) device_.arena_release(arena_offset_, VkDeviceSize(desc_.NumDescriptors) * kDescriptorSize + guard_, DeviceState::arena_descriptor_heap); } bool ok() const { return cpu_ != nullptr; } // A node mask of 0 reads back as the one node of a single adapter, as on the PC runtime (d3d12_node_mask_test). D3D12_DESCRIPTOR_HEAP_DESC STDMETHODCALLTYPE GetDesc() override { D3D12_DESCRIPTOR_HEAP_DESC desc = desc_; if (!desc.NodeMask) desc.NodeMask = 1; return desc; } D3D12_CPU_DESCRIPTOR_HANDLE STDMETHODCALLTYPE GetCPUDescriptorHandleForHeapStart() override { return {reinterpret_cast(cpu_)}; } D3D12_GPU_DESCRIPTOR_HANDLE STDMETHODCALLTYPE GetGPUDescriptorHandleForHeapStart() override { if (!(desc_.Flags & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE)) return {0}; if (console_addressed_) return {static_cast(console_address_)}; if (!in_arena_) log_once("shader-visible heap without a GPU address arena; flags", int(desc_.Flags)); return {in_arena_ ? UINT64(arena_offset_) : 0}; } bool owns_mapped_span(SIZE_T start, SIZE_T bytes) const { return in_arena_ && start == reinterpret_cast(cpu_) && bytes == SIZE_T(desc_.NumDescriptors) * kDescriptorSize; } const D3D12_DESCRIPTOR_HEAP_DESC& raw_desc() const { return desc_; } // Where shaders read the heap: its arena copy for a console heap that has one (SetDescriptorHeaps' base). D3D12_GPU_VIRTUAL_ADDRESS gpu_base() const { if (shadowed_) return UINT64(console_shader_va_); if (console_addressed_) return static_cast(console_address_); return in_arena_ ? UINT64(arena_offset_) : 0; } private: DeviceState& device_; D3D12_DESCRIPTOR_HEAP_DESC desc_; bool registered_cpu_views_ = false; std::unique_ptr storage_; std::uint8_t* cpu_ = nullptr; VkDeviceSize arena_offset_ = 0; VkDeviceSize guard_ = 0; // null bytes after the heap in its arena range bool in_arena_ = false; std::uint64_t console_address_ = 0; std::uint64_t console_size_ = 0; bool console_addressed_ = false; bool shadowed_ = false; // a console heap shaders read at console_shader_va_ (DeviceState::add_console_heap) std::uint64_t console_shader_va_ = 0; }; // Only Xbox depth resources have an alternate storage image. Barriers for other COM objects // can look it up without dereferencing the pointer or calling into another implementation. std::mutex depth_storage_mutex; std::map depth_storage_images; std::atomic depth_storage_count{0}; constexpr bool xbox_depth_storage_desc(const D3D12_RESOURCE_DESC& desc) { const unsigned usages = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; return (unsigned(desc.Flags) & ~unsigned(D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE)) == usages && (desc.Format == DXGI_FORMAT_R16_TYPELESS || desc.Format == DXGI_FORMAT_R32_TYPELESS) && desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && desc.SampleDesc.Count == 1 && desc.Layout == D3D12_TEXTURE_LAYOUT_UNKNOWN; } D3D12_RESOURCE_DESC depth_storage_part(D3D12_RESOURCE_DESC desc, bool colour) { desc.Flags = colour ? D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS : D3D12_RESOURCE_FLAGS(unsigned(desc.Flags) & ~unsigned(D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)); return desc; } class Resource final : public Child { public: static constexpr GUID kTag = rt::d3d12_xs::kVulkanResourceTag; Resource(DeviceState& device, const D3D12_RESOURCE_DESC& desc, const D3D12_HEAP_PROPERTIES& heap, D3D12_HEAP_FLAGS heap_flags) : device_(device), desc_(desc), heap_(heap), heap_flags_(heap_flags) {} // A placed resource lives inside a heap's arena range: the heap owns the range, so only the console VA is kept // here and nothing goes back to the arena when this object dies. Resource(DeviceState& device, const D3D12_RESOURCE_DESC& desc, const D3D12_HEAP_PROPERTIES& heap, D3D12_HEAP_FLAGS heap_flags, VkDeviceSize placed_va) : device_(device), desc_(desc), heap_(heap), heap_flags_(heap_flags), placed_(true), va_(placed_va) {} void adopt_depth_storage(Resource* colour) { storage_ = colour; std::lock_guard lock(depth_storage_mutex); depth_storage_images.emplace(this, XboxDepthStorage{colour->id(), desc_.MipLevels, desc_.DepthOrArraySize}); ++depth_storage_count; } const Resource* storage_image() const { return storage_; } ~Resource() override { { std::lock_guard guard(device_.mapped_texture_mutex); if (device_.mapped_textures.erase(this)) --device_.map_count; } if (deferred_attachment_) device_.retire_samples(this); if (title_image_registered_) { std::lock_guard lock(device_.title_image_mutex); auto [begin,end] = device_.title_images.equal_range(va_); for (auto it = begin; it != end; ++it) if (it->second == this) { device_.title_images.erase(it); break; } } if (storage_) { { std::lock_guard lock(depth_storage_mutex); depth_storage_images.erase(this); --depth_storage_count; } storage_->Release(); } if (title_texture_) device_.title_texture_gone(this, reinterpret_cast(title_address_)); if (indexed_bda_) device_.backing(indexed_bda_, desc_.Width, id(), false); if (aliased_) leonida::title_va_aliases().remove(va_, title_alias_); if (accel_) { device_.context->unregister_acceleration_structure(gpu_va_); if (buffer_va_ && buffer_va_ != gpu_va_) device_.context->unregister_acceleration_structure(buffer_va_); device_.context->defer_destroy(leonida::DeferredDeletionQueue::Kind::acceleration_structure, accel_); } if (deferred_stream_) { std::lock_guard lock(device_.descriptor_mutex); device_.pending_image_keys.erase(image_); } if (image_address_ && device_.image_owner(image_address_) == this) device_.forget_image(image_address_); device_.context->remove_resource(id()); // Before the memory goes to the deferred queue: no submission copies into it after this. if (shadow_) device_.remove_shadow(shadow_); if (host_import_) { // VK_EXT_external_memory_host needs the caller's pages to stay valid for the imported memory's whole // lifetime, and a title may free them right after releasing the resource. So the memory is not left to // the deferred queue (freed after the *next* submission retires): wait for what was submitted, then // free it now (found in review). device_.context->wait_retire_ticket(device_.context->submitted_retire_ticket()); auto& vk = device_.context->vk; if (buffer_) vk.vkDestroyBuffer(device_.info.device, buffer_, nullptr); if (memory_) { vk.vkFreeMemory(device_.info.device, memory_, nullptr); device_.host_imports.fetch_sub(1, std::memory_order_relaxed); } leonida::kernel_writes::release(std::exchange(host_pin_, 0)); buffer_ = VK_NULL_HANDLE; memory_ = VK_NULL_HANDLE; } if (in_arena_) device_.arena_release(arena_offset_, desc_.Width, DeviceState::arena_buffer); if (pooled_image_) device_.context->defer_destroy(leonida::DeferredDeletionQueue::Kind::pooled_title_image, pooled_image_.release()); else if (image_ && !sparse_image_) device_.context->defer_destroy(leonida::DeferredDeletionQueue::Kind::image, image_); if (buffer_) device_.context->defer_destroy(leonida::DeferredDeletionQueue::Kind::buffer, buffer_); if (memory_) device_.context->defer_destroy(leonida::DeferredDeletionQueue::Kind::device_memory, memory_); if (image_range_) device_.context->defer_destroy(leonida::DeferredDeletionQueue::Kind::image_memory, image_range_.release()); } VkDeviceAddress indexed_bda_{}; void index_shader_backing(VkDeviceAddress address) { if (address) { device_.backing(address, desc_.Width, id(), true); indexed_bda_ = address; } } leonida::ResourceId id() const { return resource_id(this); } VkImage image() const { return deferred_attachment_ && !deferred_attachment_->ensure() ? VK_NULL_HANDLE : image_; } // A sampled placement can publish views of its shared, correctly sized zero image while its own image is unbound. VkImage descriptor_image() const { return shared_zero_ ? image_ : image(); } bool host_initialized_image() const { return host_transfer_; } bool unbound_attachment() const { return deferred_attachment_ && !deferred_attachment_->bound(); } VkDeviceSize image_backing_bytes() const { return unbound_attachment() ? 0 : image_backing_bytes_; } // A placed image whose memory waits for its first use (create_texture) gets it here. bool ensure_texture_bound() const { return !deferred_attachment_ || deferred_attachment_->ensure(); } VkImage bound_image() const { return descriptor_image(); } // A deferred placed image with no memory yet, other than one that shows the shared zero image meanwhile. bool deferrable_sample() const { return !shared_zero_ && unbound_attachment(); } bool sparse_image() const { return sparse_image_; } VkBuffer buffer() const { return buffer_; } const D3D12_RESOURCE_DESC& desc() const { return desc_; } bool rgba4_render_backing() const {return desc_.Format==DXGI_FORMAT_B4G4R4A4_UNORM && format_==VK_FORMAT_R8G8B8A8_UNORM;} VkFormat format() const { return format_; } // of the image bool has_view_format_list() const { return !view_formats_.empty(); } bool allows_view_format(VkFormat format) const { return view_formats_.empty() || format == format_ || std::find(view_formats_.begin(), view_formats_.end(), format) != view_formats_.end(); } // The castable-format list in DXGI formats, which the Vulkan list can't tell apart where two families share a // VkFormat: B8G8R8X8 and B8G8R8A8 are both BGRA8 images. void keep_castable_formats(UINT32 count, const DXGI_FORMAT* formats) { if (count && formats) castable_formats_.assign(formats, formats + count); } bool lists_castable_format(DXGI_FORMAT format) const { return std::find(castable_formats_.begin(), castable_formats_.end(), format) != castable_formats_.end(); } bool has_castable_formats() const { return !castable_formats_.empty(); } VkFormat uint_backed() const { return uint_backed_; } // Format::uint_backed bool a8_as_alpha() const { return a8_as_alpha_; } VkImageAspectFlags aspects() const { return aspects_; } bool rgb96() const { return rgb96_; } // a 96-bit texture in an RGBA32 image std::uint64_t image_address() const { return image_address_; } // what a T# names the texture by const Resource* depth_stencil_uav(UINT plane) const { return plane < storage_planes_.size() ? storage_planes_[plane].get() : nullptr; } VkMemoryPropertyFlags memory_flags() const { return unbound_attachment() ? 0 : memory_flags_; } // of its backing bool is_shadow() const { return shadow_ != nullptr; } // create_shadow_buffer: a copy of title pages const DeviceState& device_state() const { return device_; } void* title_address() const { return title_address_; } // place_at_title_address, or null HRESULT upload_title_subresource(UINT subresource, void* data, UINT row, UINT slice, bool allow_staging) { static const bool ordered = [] { const char* value = std::getenv("LEONIDA_ORDER_TEXTURE_UPLOADS"); return !value || std::strcmp(value, "0"); }(); if (ordered && host_transfer_) { Region r{}; if (!region(subresource, nullptr, r) || row != r.row_bytes || slice != row * r.rows) return E_INVALIDARG; const auto result = device_.context->write_host_texture(id(), subresource, [&] { return host_copy(true, r, data); }); if (result == VK_SUCCESS) return S_OK; if (result != VK_NOT_READY) return E_FAIL; // Layout changed after the pass checked the subresources. Never submit recursively. if (!allow_staging) return DXGI_ERROR_WAS_STILL_DRAWING; return cpu_copy(true, subresource, nullptr, data, row, slice, false); } return WriteToSubresource(subresource, nullptr, data, row, slice); } bool replay_seen() const { return replay_seen_.load(std::memory_order_relaxed); } bool staged_title() const { return staged_title_; } bool upload_staged_title(const rt::xg_xs::Texture& layout, const std::uint8_t* tiled, std::vector& columns, bool inspect, bool& nonzero) { std::lock_guard lock(device_.title_upload_mutex); return device_.title_upload.write(device_, id(), binding_, layout, tiled, columns, inspect, nonzero); } // Map and the destructor notify the registry for a slot-133 placement. void mark_title_texture() { title_texture_ = true; } void note_shader_view() const { shader_views_.fetch_add(1, std::memory_order_relaxed); } std::uint32_t shader_views() const { return shader_views_.load(std::memory_order_relaxed); } // The element a CPU copy moves (a 4x4 block for block-compressed formats), as WriteToSubresource takes it. leonida::BlockFormat copy_element() const { return leonida::copy_block_format(binding_, VK_IMAGE_ASPECT_COLOR_BIT); } // WriteToSubresource of this subresource is a host copy now (VK_EXT_host_image_copy, image in GENERAL), not a // staged copy through a queue: the only kind a refresh before a submission may do. bool host_copy_now(UINT subresource) const { return host_transfer_ && device_.context->layout(id(), subresource) == VK_IMAGE_LAYOUT_GENERAL; } // Default-heap buffers are ranges of the GPU address arena: console VA = offset, zeroed through the arena's host // mapping. Upload and readback buffers keep their own host memory; with buffer device addresses their console // VA is their device address minus heap_base, so a shader's heap_base + VA still lands on them (section 3.3). HRESULT create_buffer(D3D12_RESOURCE_STATES initial_state = D3D12_RESOURCE_STATE_COMMON) { auto& vk = device_.context->vk; // A buffer has at least one byte, and its size must survive alignment to 64 KiB without wrapping. if (!desc_.Width || desc_.Width > ~UINT64(0) - D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT) return E_INVALIDARG; const bool host = cpu_visible(); leonida::ResourceBinding binding{}; // a buffer: no image binding.size = desc_.Width; if (!host && device_.arena.mapped) { if (!device_.arena_allocate(desc_.Width, D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT, arena_offset_, DeviceState::arena_buffer)) { log_once("GPU address arena full (raise LEONIDA_ARENA_MB); buffer size in KiB:", int(desc_.Width / 1024)); return E_OUTOFMEMORY; } in_arena_ = true; std::memset(device_.arena.mapped + arena_offset_, 0, std::size_t(desc_.Width)); va_ = arena_offset_; binding.va = va_; binding.buffer = device_.arena.buffer; binding.indirect_arguments = device_.arena.indirect_arguments; binding.buffer_offset = arena_offset_; // No host pointer: this is DEFAULT-heap arena memory the GPU may write, so its mapped bytes can be // stale. host_at() must not treat it as a CPU-written instance pointer list. // A default-heap AS resource is one of these ranges: a GENERIC acceleration structure covers it where // it sits. It is named by its device address (heap base + offset, as the driver reports it), as instance // descriptors and BuildRaytracingAccelerationStructure hand that address to the driver, not a console VA. if (device_.info.ray_tracing && initial_state == D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE && vk.vkCreateAccelerationStructureKHR) { VkAccelerationStructureCreateInfoKHR asci{VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_CREATE_INFO_KHR}; asci.buffer = device_.arena.buffer; asci.offset = arena_offset_; asci.size = desc_.Width; asci.type = VK_ACCELERATION_STRUCTURE_TYPE_GENERIC_KHR; if (vk.vkCreateAccelerationStructureKHR(device_.info.device, &asci, nullptr, &accel_) == VK_SUCCESS) { gpu_va_ = device_.arena.address + va_; // An instance names its BLAS by a value obtained from vkGetAccelerationStructureDeviceAddressKHR // (VUID-vkCmdBuildAccelerationStructuresKHR-pInfos-12281), so ask for it, as the committed path // below does. For GENERIC the spec only promises that these addresses keep the offsets between // the structures of one buffer; drivers return buffer address + offset (vkd3d-proton checks the // same). If one ever does not, the driver's address is the one instances must hold. if (vk.vkGetAccelerationStructureDeviceAddressKHR) { VkAccelerationStructureDeviceAddressInfoKHR dai{ VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_DEVICE_ADDRESS_INFO_KHR}; dai.accelerationStructure = accel_; const std::uint64_t as_va = vk.vkGetAccelerationStructureDeviceAddressKHR(device_.info.device, &dai); if (as_va && as_va != gpu_va_) { log_once("GENERIC acceleration structure address is not its buffer address + offset; " "arena offset in KiB:", int(arena_offset_ / 1024)); buffer_va_ = gpu_va_; gpu_va_ = as_va; } } device_.context->register_acceleration_structure(gpu_va_, accel_); if (buffer_va_ && buffer_va_ != gpu_va_) device_.context->register_acceleration_structure(buffer_va_, accel_); } } device_.context->add_resource(id(), binding); return S_OK; } const bool addressable = device_.arena.buffer != VK_NULL_HANDLE; const bool need_bda = device_.info.buffer_device_address || device_.info.ray_tracing; VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; // The indexed quad pass loads 16-bit indices from aligned 32-bit words. Keep the final word inside the // Vulkan buffer while the D3D resource and views still use desc_.Width. info.size = addressable || need_bda ? align_up(desc_.Width, sizeof(std::uint32_t)) : desc_.Width; info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT; if (device_.info.conditional_rendering) info.usage |= VK_BUFFER_USAGE_CONDITIONAL_RENDERING_BIT_EXT; if (addressable || need_bda) info.usage |= VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; if (device_.info.ray_tracing) { info.usage |= VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_STORAGE_BIT_KHR | VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR; } device_.share(info); if (vk.vkCreateBuffer(device_.info.device, &info, nullptr, &buffer_) != VK_SUCCESS) return E_OUTOFMEMORY; VkMemoryRequirements requirements{}; vk.vkGetBufferMemoryRequirements(device_.info.device, buffer_, &requirements); // Readback buffers prefer cached memory, which the CPU reads quickly. Upload buffers prefer VRAM the CPU // writes through Resizable BAR, where the GPU reads them quickly (D3D-96); without it, system memory. VkMemoryPropertyFlags host_preferred = 0; if (heap_.Type == D3D12_HEAP_TYPE_READBACK) host_preferred = VK_MEMORY_PROPERTY_HOST_CACHED_BIT; if (heap_.Type == D3D12_HEAP_TYPE_UPLOAD && device_.upload_in_vram) host_preferred = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; memory_ = host ? device_.allocate(requirements, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, host_preferred, &memory_flags_, addressable || need_bda) : device_.allocate(requirements, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, &memory_flags_, addressable || need_bda); if (!memory_ || vk.vkBindBufferMemory(device_.info.device, buffer_, memory_, 0) != VK_SUCCESS) return E_OUTOFMEMORY; if (addressable) { VkBufferDeviceAddressInfo address{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; address.buffer = buffer_; va_ = vk.vkGetBufferDeviceAddress(device_.info.device, &address) - device_.arena.address; device_.log_va(heap_.Type == D3D12_HEAP_TYPE_READBACK ? "readback buffer" : "upload buffer", va_, desc_.Width); } if (host) { if (vk.vkMapMemory(device_.info.device, memory_, 0, VK_WHOLE_SIZE, 0, &mapped_) != VK_SUCCESS) return E_OUTOFMEMORY; std::memset(mapped_, 0, std::size_t(info.size)); // committed resources and private padding start zeroed } if (need_bda && vk.vkGetBufferDeviceAddress) { VkBufferDeviceAddressInfo bda{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; bda.buffer = buffer_; buffer_va_ = vk.vkGetBufferDeviceAddress(device_.info.device, &bda); gpu_va_ = buffer_va_; } if (device_.info.ray_tracing && initial_state == D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE && vk.vkCreateAccelerationStructureKHR && vk.vkGetAccelerationStructureDeviceAddressKHR) { VkAccelerationStructureCreateInfoKHR asci{VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_CREATE_INFO_KHR}; asci.buffer = buffer_; asci.offset = 0; asci.size = desc_.Width; asci.type = VK_ACCELERATION_STRUCTURE_TYPE_GENERIC_KHR; if (vk.vkCreateAccelerationStructureKHR(device_.info.device, &asci, nullptr, &accel_) == VK_SUCCESS) { VkAccelerationStructureDeviceAddressInfoKHR dai{ VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_DEVICE_ADDRESS_INFO_KHR}; dai.accelerationStructure = accel_; const std::uint64_t as_va = vk.vkGetAccelerationStructureDeviceAddressKHR(device_.info.device, &dai); if (as_va) gpu_va_ = as_va; device_.context->register_acceleration_structure(gpu_va_, accel_); if (buffer_va_ && buffer_va_ != gpu_va_) device_.context->register_acceleration_structure(buffer_va_, accel_); } } binding.buffer = buffer_; binding.indirect_arguments = (info.usage & VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT) != 0; binding.size = desc_.Width; binding.host = cpu_writable() ? static_cast(mapped_) : nullptr; binding.host_readable = (heap_.Type == D3D12_HEAP_TYPE_READBACK || (heap_.Type == D3D12_HEAP_TYPE_CUSTOM && heap_.CPUPageProperty == D3D12_CPU_PAGE_PROPERTY_WRITE_BACK)); binding.va = va_; index_shader_backing(addressable ? device_.arena.address + va_ : buffer_va_); device_.context->add_resource(id(), binding); // Committed resources start zeroed unless the heap says otherwise; the host cannot reach device-local memory, // so the next submission fills it (D3D-71). if (!host && !(heap_flags_ & D3D12_HEAP_FLAG_CREATE_NOT_ZEROED)) device_.context->zero_on_next_submit(id(), buffer_); return S_OK; } // A buffer on the caller's own pages (Xbox device slot 133, create_buffer_at_host_address): `address` is imported // with VK_EXT_external_memory_host and the buffer bound to it at offset 0, so the CPU's writes there are the GPU's // reads with no copy. Its console VA is `address` itself, the VA the title chose, so vertex, index and immediate // writes the title names by that VA find this buffer (VulkanContext::buffer_at). A shader that adds heap_base to // that VA would not reach it, so the root views and V#s the layer writes for it name its device address minus // heap_base instead (alias_title_va, docs/d3d12_vulkan.md section 3.3 "Title-placed buffers"); V#s the title // writes into memory itself keep its VA. The pages stay the caller's: nothing is zeroed. HRESULT create_host_buffer(void* address) { // LEONIDA_SLOT133_IMPORT=0 (diagnostic): no title-placed buffer is imported; each takes the shadow fallback, // so no GPU store can reach title memory through an import. static const bool no_import = [] { const char* v = std::getenv("LEONIDA_SLOT133_IMPORT"); return v && std::strcmp(v, "0") == 0; }(); if (no_import) return E_NOTIMPL; auto& vk = device_.context->vk; const VkDeviceSize alignment = device_.info.host_pointer_alignment; if (!device_.get_host_pointer_properties || !alignment) return E_NOTIMPL; const auto start = reinterpret_cast(address); if (start & 3) return E_NOTIMPL; // byte-unaligned copies keep the ordinary-buffer fallback if (!address || !desc_.Width || alignment > UINT64_MAX / 2 || (alignment & (alignment - 1)) || desc_.Width > UINT64_MAX - 2 * alignment) return E_INVALIDARG; const bool need_bda = device_.info.buffer_device_address || device_.arena.buffer != VK_NULL_HANDLE; // Keep the device-address word padding, and include the host page prefix in the backing buffer. const VkDeviceSize backing_size = need_bda ? align_up(desc_.Width, sizeof(std::uint32_t)) : desc_.Width; // Bind at zero; replay and device addresses carry the logical buffer's prefix instead. const std::uintptr_t base = start & ~static_cast(alignment - 1); void* const base_address = reinterpret_cast(base); const VkDeviceSize offset = start - base; const VkDeviceSize bytes = align_up(offset + backing_size, alignment); // An imported buffer's VA is its host address, and it joins the same BufferVaIndex as default-heap buffers, // whose VAs are offsets in [0, arena size). A host range that reaches into that window (low host addresses, // as under Wine) would shadow arena buffers in the index's nearest-start lookup, so it takes the fallback // (found in review). if (start < device_.arena.size) { log_once("a title-placed buffer's host address overlaps the arena's VA window; not imported, size", int(desc_.Width > INT_MAX ? INT_MAX : desc_.Width)); return E_NOTIMPL; } // A GPU-only range with pages of its own (title_gpu_views::independently_mapped): queue slot 31 remaps them // there, and an import would keep the GPU on the old physical pages. The shadow, copied from the pages before // every submission, follows the remap. Declined before anything is made, so nothing is left behind. if (leonida::title_gpu_views::independently_mapped(start, desc_.Width)) { log_once("a title-placed buffer over a GPU-only range slot 31 maps by itself is not imported, size", int(desc_.Width > INT_MAX ? INT_MAX : desc_.Width)); return E_NOTIMPL; } // The whole imported range must be committed, possibly across several allocations (the retail buffer spans // three mapped windows); a page not committed yet (xmem commits on first touch) or a write-combined one (on // an RTX 5090 such an import succeeded but GPU reads returned wrong bytes, found in review) is not imported, // and the ordinary-buffer fallback answers instead. bool importable = true; for (VkDeviceSize at = 0; at < bytes;) { MEMORY_BASIC_INFORMATION region{}; // A page that is not writable right now (a shadow buffer's write watch on the same page, say) cannot be // pinned for the GPU: the kernel module refuses it, loudly, and the shadow answers anyway. if (!VirtualQuery(static_cast(base_address) + at, ®ion, sizeof(region)) || region.State != MEM_COMMIT || (region.Protect & (PAGE_WRITECOMBINE | PAGE_NOCACHE | PAGE_GUARD)) || !(region.Protect & (PAGE_READWRITE | PAGE_EXECUTE_READWRITE))) { importable = false; break; } const auto region_end = reinterpret_cast(region.BaseAddress) + region.RegionSize; at = region_end - base; } if (!importable) return E_NOTIMPL; VkExternalMemoryBufferCreateInfo external{VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO}; external.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT; VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, &external}; info.size = offset + backing_size; info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT; if (device_.info.conditional_rendering) info.usage |= VK_BUFFER_USAGE_CONDITIONAL_RENDERING_BIT_EXT; if (need_bda) info.usage |= VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; device_.share(info); if (vk.vkCreateBuffer(device_.info.device, &info, nullptr, &buffer_) != VK_SUCCESS) return E_OUTOFMEMORY; // An import not used is destroyed here, not left to the destructor's deferred queue: there it outlived the // next submission while the shadow the caller makes instead over the same pages guarded them, and RADV // rejects every submission once a page under a live import is read-only (the CS is rejected, then // VK_ERROR_DEVICE_LOST: found and measured by NateWeav, #14). Nothing was submitted with it: the resource is // registered only on success. const auto decline = [&](HRESULT hr) { if (buffer_) vk.vkDestroyBuffer(device_.info.device, buffer_, nullptr); if (memory_) { vk.vkFreeMemory(device_.info.device, memory_, nullptr); device_.host_imports.fetch_sub(1, std::memory_order_relaxed); } leonida::kernel_writes::release(std::exchange(host_pin_, 0)); buffer_ = VK_NULL_HANDLE; memory_ = VK_NULL_HANDLE; buffer_va_ = gpu_va_ = 0; return hr; }; VkMemoryRequirements requirements{}; vk.vkGetBufferMemoryRequirements(device_.info.device, buffer_, &requirements); VkMemoryHostPointerPropertiesEXT host{VK_STRUCTURE_TYPE_MEMORY_HOST_POINTER_PROPERTIES_EXT}; if (device_.get_host_pointer_properties(device_.info.device, VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT, base_address, &host) != VK_SUCCESS) return decline(E_NOTIMPL); const std::uint32_t types = host.memoryTypeBits & requirements.memoryTypeBits; // The binding is at zero; requirements cover the prefix as part of the buffer. if (!types || requirements.size > bytes) return decline(E_NOTIMPL); VkImportMemoryHostPointerInfoEXT import{VK_STRUCTURE_TYPE_IMPORT_MEMORY_HOST_POINTER_INFO_EXT}; import.handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT; import.pHostPointer = base_address; VkMemoryAllocateFlagsInfo flags{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO, &import}; flags.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT; // The imported pages are pinned before the import and until its memory is freed, so the shadow trackers // and the geometry watch never make them read-only meanwhile (leonida::kernel_writes::hold). Taken first, // so no guard lands between the writability check above and the import. host_pin_ = leonida::kernel_writes::hold(base_address, std::size_t(bytes)); // Host-visible and coherent first, as the caller's pages are; then any type both the import and the // buffer take. for (const VkMemoryPropertyFlags want : {VkMemoryPropertyFlags(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT), VkMemoryPropertyFlags(0)}) { for (std::uint32_t i = 0; i < device_.memory.memoryTypeCount && !memory_; ++i) { if (!(types & (1u << i)) || (device_.memory.memoryTypes[i].propertyFlags & want) != want) continue; VkMemoryAllocateInfo allocate{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, need_bda ? static_cast(&flags) : &import}; allocate.allocationSize = bytes; allocate.memoryTypeIndex = i; std::lock_guard serial(DeviceState::memory_mutex()); if (vk.vkAllocateMemory(device_.info.device, &allocate, nullptr, &memory_) == VK_SUCCESS) { memory_flags_ = device_.memory.memoryTypes[i].propertyFlags; device_.host_imports.fetch_add(1, std::memory_order_relaxed); } else { memory_ = VK_NULL_HANDLE; } } if (memory_) break; } if (!memory_) return decline(E_OUTOFMEMORY); if (vk.vkBindBufferMemory(device_.info.device, buffer_, memory_, 0) != VK_SUCCESS) return decline(E_OUTOFMEMORY); if (need_bda && vk.vkGetBufferDeviceAddress) { VkBufferDeviceAddressInfo bda{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; bda.buffer = buffer_; buffer_va_ = vk.vkGetBufferDeviceAddress(device_.info.device, &bda); if (buffer_va_) buffer_va_ += offset; gpu_va_ = buffer_va_; } // An import the driver put below the arena cannot be named by a V#: the V# keeps 48 bits of (device address // - heap_base), which is negative there, and the translated shaders zero-extend it, so they read 2^48 above // the buffer (found natively by plaaasma-agent: garbage constants, or VK_ERROR_DEVICE_LOST; this machine // logs the same wrap). Such an import is not used: the shadow buffer in the arena answers, as when the // import is refused. LEONIDA_IMPORT_BELOW_ARENA=1 keeps the import (for a shader library whose programs // sign-extend the address). if (buffer_va_ && buffer_va_ < device_.arena.address && !signed_vsharp_offsets()) { static std::atomic logged{0}; if (logged.fetch_add(1, std::memory_order_relaxed) < 8) std::fprintf(stderr, "[rt] d3d12: an import of title memory at %p (%llu bytes) landed below the arena (device " "address 0x%llx, arena 0x%llx): a shadow in the arena is used instead\n", address, static_cast(desc_.Width), static_cast(buffer_va_), static_cast(device_.arena.address)); return decline(E_NOTIMPL); } mapped_ = address; host_import_ = true; va_ = start; device_.log_va("title-placed buffer", va_, desc_.Width); { // Which title ranges a GPU store can reach through an import (the first 256, then every 256th). static std::atomic imports{0}; const std::uint64_t n = imports.fetch_add(1, std::memory_order_relaxed) + 1; if (n <= 256 || n % 256 == 0) std::fprintf(stderr, "[rt] d3d12: slot-133 import #%llu: title 0x%llx-0x%llx (%llu bytes), device " "address 0x%llx, flags 0x%x\n", static_cast(n), static_cast(start), static_cast(start + desc_.Width), static_cast(desc_.Width), static_cast(buffer_va_), unsigned(desc_.Flags)); } leonida::ResourceBinding binding{}; binding.buffer = buffer_; binding.indirect_arguments = (info.usage & VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT) != 0; binding.buffer_offset = offset; binding.size = desc_.Width; binding.host = static_cast(address); binding.host_readable = true; binding.va = va_; index_shader_backing(buffer_va_); device_.context->add_resource(id(), binding); // Shaders reach the imported pages by their device address (src/title_va_alias.h). if (buffer_va_) alias_title_va(buffer_va_ - device_.arena.address); return S_OK; } // Registers [va_, va_ + width) as reached by shaders at `shader_va` (src/title_va_alias.h): the root views and // buffer V#s the layer writes for an address in it get the matching address of the buffer's GPU copy. void alias_title_va(std::uint64_t shader_va) { if (!leonida::title_va_aliases().add(va_, desc_.Width, shader_va)) return; title_alias_ = shader_va; aliased_ = true; } // The fallback of create_host_buffer, for pages the driver will not import: write-combined or uncached ones (in // retail 74 MiB of the title's 182 MiB range), pages not committed yet, a device without // VK_EXT_external_memory_host, or a driver past its import budget (an RTX 3070 Ti answers // VK_ERROR_OUT_OF_DEVICE_MEMORY after about 64 MiB of imports). The buffer has its own host-visible memory, a // shadow of the title's pages, but keeps the title's VA as its console VA, so the descriptors and views the title // builds from that VA still find it (an ordinary buffer here had another VA and none of the data: slot 70 wrote // a null SRV and the UI draws sampled nothing). It is filled from the pages now, and before every submission // of command lists the pages the title wrote since are copied again (ShadowPages, DeviceState::refresh_shadows). // One way only: what the GPU writes to the shadow is NOT copied back to the title's pages, and the next copy of // a page overwrites it. A title that reads GPU output at `address` needs the import. HRESULT create_shadow_buffer(void* address) { auto& vk = device_.context->vk; if (!address || !desc_.Width || desc_.Width > ~UINT64(0) - D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT) return E_INVALIDARG; const auto* pages = static_cast(address); // The shadow is a range of the GPU address arena when it fits there (docs/d3d12_vulkan.md section 3.3). // The title's VA is a user-mode Windows address far above 4 GiB, past the arena, so a shader's heap_base + VA would miss // any buffer of the layer's; the root views and V#s the layer writes for that VA name the arena offset // instead (src/title_va_alias.h), a VA below 4 GiB that a root view and a V#'s 48 bits both hold. The arena // is host-visible, so the per-submission copy writes it in place. if (device_.arena.mapped && device_.arena_allocate(desc_.Width, D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT, arena_offset_, DeviceState::arena_buffer)) { in_arena_ = true; shadow_ = device_.arena.mapped + arena_offset_; device_.add_shadow(pages, shadow_, std::size_t(desc_.Width)); mapped_ = address; va_ = reinterpret_cast(address); buffer_va_ = gpu_va_ = device_.arena.address + arena_offset_; device_.log_va("title-placed buffer (arena shadow)", va_, desc_.Width); leonida::ResourceBinding binding{}; binding.buffer = device_.arena.buffer; binding.indirect_arguments = device_.arena.indirect_arguments; binding.buffer_offset = arena_offset_; binding.size = desc_.Width; binding.host = shadow_; binding.va = va_; device_.context->add_resource(id(), binding); alias_title_va(arena_offset_); return S_OK; } log_once("a title-placed shadow buffer does not fit the GPU address arena (raise LEONIDA_ARENA_MB), so it " "has its own memory; size in KiB:", int(desc_.Width / 1024)); const bool need_bda = device_.info.buffer_device_address || device_.arena.buffer != VK_NULL_HANDLE; VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; info.size = desc_.Width; info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT; if (device_.info.conditional_rendering) info.usage |= VK_BUFFER_USAGE_CONDITIONAL_RENDERING_BIT_EXT; if (need_bda) info.usage |= VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; device_.share(info); if (vk.vkCreateBuffer(device_.info.device, &info, nullptr, &buffer_) != VK_SUCCESS) return E_OUTOFMEMORY; VkMemoryRequirements requirements{}; vk.vkGetBufferMemoryRequirements(device_.info.device, buffer_, &requirements); // As an upload buffer (D3D-96): the CPU writes it at every submission and the GPU reads it, so VRAM through // Resizable BAR where there is one, system memory otherwise. memory_ = device_.allocate(requirements, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, device_.upload_in_vram ? VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT : 0, &memory_flags_, need_bda); void* shadow = nullptr; if (!memory_ || vk.vkBindBufferMemory(device_.info.device, buffer_, memory_, 0) != VK_SUCCESS || vk.vkMapMemory(device_.info.device, memory_, 0, VK_WHOLE_SIZE, 0, &shadow) != VK_SUCCESS) return E_OUTOFMEMORY; shadow_ = static_cast(shadow); device_.add_shadow(pages, shadow_, std::size_t(desc_.Width)); // Map() answers the title's own pages, as the imported buffer does: a write to the shadow's memory would be // overwritten by the next copy. mapped_ = address; va_ = reinterpret_cast(address); if (need_bda && vk.vkGetBufferDeviceAddress) { VkBufferDeviceAddressInfo bda{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; bda.buffer = buffer_; buffer_va_ = vk.vkGetBufferDeviceAddress(device_.info.device, &bda); gpu_va_ = buffer_va_; } device_.log_va("title-placed buffer (shadow)", va_, desc_.Width); leonida::ResourceBinding binding{}; binding.buffer = buffer_; binding.indirect_arguments = (info.usage & VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT) != 0; binding.size = desc_.Width; // CPU-side reads take the shadow, not the title's pages: it is as fresh as what the GPU reads and every byte // of it can be read, which the pages do not promise. Not host_readable: GPU writes are not handed back. binding.host = shadow_; binding.va = va_; index_shader_backing(buffer_va_); device_.context->add_resource(id(), binding); if (buffer_va_) alias_title_va(buffer_va_ - device_.arena.address); return S_OK; } HRESULT create_sparse_buffer() { constexpr std::uint64_t tile_bytes = leonida::tile_size_in_bytes; if (!desc_.Width || desc_.Width > UINT64_MAX - tile_bytes || desc_.SampleDesc.Count != 1 || desc_.SampleDesc.Quality != 0) return E_INVALIDARG; auto& vk = device_.context->vk; auto sparse = std::make_shared(device_.info.device, vk); sparse->tile_count = (desc_.Width + tile_bytes - 1) / tile_bytes; const auto info = device_.sparse_buffer_info(sparse->tile_count * tile_bytes); if (vk.vkCreateBuffer(device_.info.device, &info, nullptr, &sparse->buffer) != VK_SUCCESS) return E_OUTOFMEMORY; VkMemoryRequirements requirements{}; vk.vkGetBufferMemoryRequirements(device_.info.device, sparse->buffer, &requirements); sparse->memory_types = requirements.memoryTypeBits; if (tile_bytes % requirements.alignment || !(sparse->memory_types & device_.sparse_buffer_memory_types)) return E_NOTIMPL; VkBufferDeviceAddressInfo address{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; address.buffer = sparse->buffer; va_ = vk.vkGetBufferDeviceAddress(device_.info.device, &address) - device_.arena.address; leonida::ResourceBinding binding{}; binding.buffer = sparse->buffer; binding.indirect_arguments = (info.usage & VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT) != 0; binding.size = desc_.Width; binding.va = va_; index_shader_backing(va_ + device_.arena.address); binding.sparse_buffer = true; device_.context->add_sparse_resource(id(), binding, std::move(sparse)); return S_OK; } HRESULT create_sparse_image() { auto& vk = device_.context->vk; const auto format = device_.texture_format(desc_); TextureCreateInfo create(desc_, format, false); create.info.flags |= VK_IMAGE_CREATE_SPARSE_BINDING_BIT | VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT | VK_IMAGE_CREATE_SPARSE_ALIASED_BIT; HRESULT support = device_.check_image_support(create.info); if (FAILED(support)) return support == E_INVALIDARG ? E_NOTIMPL : support; device_.share(create.info); auto sparse = std::make_shared(device_.info.device, vk); const auto result = vk.vkCreateImage(device_.info.device, &create.info, nullptr, &sparse->image); if (result == VK_ERROR_FORMAT_NOT_SUPPORTED) return E_NOTIMPL; if (result != VK_SUCCESS) return E_OUTOFMEMORY; VkMemoryRequirements requirements{}; vk.vkGetImageMemoryRequirements(device_.info.device, sparse->image, &requirements); if (requirements.alignment != leonida::tile_size_in_bytes || leonida::memory_type_order(device_.memory, requirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, 0, leonida::tile_size_in_bytes).empty()) return E_NOTIMPL; std::uint32_t count = 0; vk.vkGetImageSparseMemoryRequirements(device_.info.device, sparse->image, &count, nullptr); if (count != 1) return E_NOTIMPL; // exactly one color aspect, with no separately bound metadata VkSparseImageMemoryRequirements image_requirements{}; vk.vkGetImageSparseMemoryRequirements(device_.info.device, sparse->image, &count, &image_requirements); constexpr auto shape = leonida::element_tile_shape(false, 4); const auto& properties = image_requirements.formatProperties; const auto granularity = properties.imageGranularity; if (properties.aspectMask != VK_IMAGE_ASPECT_COLOR_BIT || granularity.width != shape.width || granularity.height != shape.height || granularity.depth != 1 || !image_requirements.imageMipTailFirstLod || image_requirements.imageMipTailSize) return E_NOTIMPL; sparse->image_extent = {create.info.extent.width, create.info.extent.height}; sparse->tile_count = (1 + (sparse->image_extent.width - 1) / shape.width) * std::uint64_t(1 + (sparse->image_extent.height - 1) / shape.height); sparse->memory_types = requirements.memoryTypeBits; image_ = sparse->image; sparse_image_ = true; format_ = format.format; aspects_ = format.aspects; image_address_ = device_.next_image_address.fetch_add(256); device_.note_image_address(image_address_, this); binding_.image = image_; binding_.format = format_; binding_.aspects = aspects_; binding_.width = sparse->image_extent.width; binding_.height = sparse->image_extent.height; // An unbound tile reads as zero. Keep the layout stable once the image can share memory with an alias. binding_.not_zeroed = true; binding_.simultaneous_access = true; binding_.sampled_in_general = true; device_.context->add_sparse_resource(id(), binding_, std::move(sparse)); return S_OK; } // A placed buffer is a range of the heap's arena memory: it has no VkBuffer of its own and its console VA is // where it sits in the arena. The arena is host-visible, so an upload or readback place maps that same range. HRESULT create_placed_buffer(std::shared_ptr heap_range) { if (!device_.arena.mapped) return E_OUTOFMEMORY; heap_range_ = std::move(heap_range); if (cpu_visible()) mapped_ = device_.arena.mapped + va_; std::memset(device_.arena.mapped + va_, 0, std::size_t(desc_.Width)); // a fresh place reads as zeroed leonida::ResourceBinding binding{}; binding.size = desc_.Width; binding.buffer = device_.arena.buffer; binding.indirect_arguments = device_.arena.indirect_arguments; binding.buffer_offset = va_; binding.va = va_; binding.host = cpu_writable() ? device_.arena.mapped + va_ : nullptr; binding.host_readable = (heap_.Type == D3D12_HEAP_TYPE_READBACK || (heap_.Type == D3D12_HEAP_TYPE_CUSTOM && heap_.CPUPageProperty == D3D12_CPU_PAGE_PROPERTY_WRITE_BACK)); device_.context->add_resource(id(), binding); return S_OK; } HRESULT create_texture(const Format& format, const std::vector& asked_castable = {}, TitleImageOrigin origin = TitleImageOrigin::ordinary, bool allow_staged_title = true) { auto& vk = device_.context->vk; // The console lets a typed RGBA8 or BGRA8 render target take a view in its UNORM/sRGB twin without a castable // list: the title renders its movie frames through an R8G8B8A8_UNORM view of an R8G8B8A8_UNORM_SRGB target, // and every such draw lost its target (9 of 9 sampled). Such a texture is created as if its list named the // twin, so the view is legal in Vulkan (console_format_stand_ins). std::vector castable = asked_castable; if (castable.empty() && !format.uint_backed && !format.typeless && console_format_stand_ins() && (desc_.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET)) { const VkFormat twin = format.format == VK_FORMAT_R8G8B8A8_UNORM ? VK_FORMAT_R8G8B8A8_SRGB : format.format == VK_FORMAT_R8G8B8A8_SRGB ? VK_FORMAT_R8G8B8A8_UNORM : format.format == VK_FORMAT_B8G8R8A8_UNORM ? VK_FORMAT_B8G8R8A8_SRGB : format.format == VK_FORMAT_B8G8R8A8_SRGB ? VK_FORMAT_B8G8R8A8_UNORM : VK_FORMAT_UNDEFINED; if (twin != VK_FORMAT_UNDEFINED && desc_.Format != DXGI_FORMAT_B8G8R8X8_UNORM && desc_.Format != DXGI_FORMAT_B8G8R8X8_UNORM_SRGB) castable = {format.format, twin}; } const bool volume = desc_.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D; const UINT depth = volume ? desc_.DepthOrArraySize : 1; const bool one_d = desc_.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D; const UINT16 mips = full_mips(desc_.Width, desc_.Height, depth); if (desc_.MipLevels == 0) desc_.MipLevels = mips; if ((volume || one_d) && (desc_.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) { const UINT extent_limit = volume ? D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION : D3D12_REQ_TEXTURE1D_U_DIMENSION; const UINT slice_limit = volume ? extent_limit : D3D12_REQ_TEXTURE1D_ARRAY_AXIS_DIMENSION; if (!desc_.Width || desc_.Width > extent_limit || !desc_.Height || desc_.Height > extent_limit || !desc_.DepthOrArraySize || desc_.DepthOrArraySize > slice_limit || desc_.MipLevels > mips) return E_INVALIDARG; } TextureCreateInfo create(desc_, format, device_.color_attachment_usable(format.format)); VkImageCreateInfo& info = create.info; if (!castable.empty()) { // D3D12 always allows a view in the resource's own format, whether or not the castable list names // it. Vulkan requires every view format to be in the image's format list, so add it when missing. view_formats_ = castable; if (std::find(view_formats_.begin(), view_formats_.end(), format.format) == view_formats_.end()) view_formats_.push_back(format.format); if (format.uint_backed) { // An unsigned-backed UAV texture needs both its formats whatever the list names (TextureCreateInfo). for (VkFormat pair : {format.format, format.uint_backed}) if (std::find(view_formats_.begin(), view_formats_.end(), pair) == view_formats_.end()) view_formats_.push_back(pair); } info.flags |= VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT; create.format_list.viewFormatCount = std::uint32_t(view_formats_.size()); create.format_list.pViewFormats = view_formats_.data(); // A uint-backed format already chained format_list in TextureCreateInfo: chaining it to itself would // make the pNext chain cyclic (found in review). if (info.pNext != &create.format_list) { create.format_list.pNext = info.pNext; info.pNext = &create.format_list; } } const std::uint32_t samples = info.samples; // Textures the CPU reads and writes (WriteToSubresource/ReadFromSubresource) copy on the host when they can. // (A D24 texture stored as D32 goes through the staged copy: the host copy would not convert. Nor would it // repack a 96-bit texture's 12-byte texels.) host_transfer_ = cpu_visible() && samples == 1 && !format.d24_as_float && !format.rgb96 && device_.host_transfer_format(format.format); rgb96_ = format.rgb96; if (host_transfer_) info.usage |= VK_IMAGE_USAGE_HOST_TRANSFER_BIT_EXT; HRESULT support = device_.check_image_support(info); if (support == E_INVALIDARG && host_transfer_) { host_transfer_ = false; // staging copies do not require host-transfer usage info.usage &= ~VK_IMAGE_USAGE_HOST_TRANSFER_BIT_EXT; support = device_.check_image_support(info); } if (FAILED(support)) { std::fprintf(stderr, "[rt] d3d12: texture refused by the GPU's image support query (hr 0x%08x): vk format %d " "type %d %ux%ux%u mips %u layers %u samples %d usage 0x%x flags 0x%x (DXGI %d, D3D12 flags " "0x%x)\n", unsigned(support), int(info.format), int(info.imageType), info.extent.width, info.extent.height, info.extent.depth, info.mipLevels, info.arrayLayers, int(info.samples), unsigned(info.usage), unsigned(info.flags), int(desc_.Format), unsigned(desc_.Flags)); return support; } device_.share(info); // A host-copyable sampled image can exclude the GPU's unmapped device-local memory. // Compare identical creation parameters before dropping HOST_TRANSFER. Keep the fast // host path on UMA and on devices where host copies allow the same device-local type. static const bool stage_title = [] { const char* value = std::getenv("LEONIDA_TITLE_IMAGE_STAGING"); return !value || std::strcmp(value, "0"); }(); // Keep placed movie planes with a known linear CPU layout on the host-copy path, where there is one. // Map on a staged placement still returns the title's pages and participates in the refresh. std::uint32_t xg_layout = 0; const bool linear_placement = origin == TitleImageOrigin::placed && (desc_.Layout == D3D12_TEXTURE_LAYOUT_ROW_MAJOR || (leonida::title_xg_layouts::find({std::uint32_t(desc_.Dimension), std::uint32_t(desc_.Format), desc_.Height, desc_.DepthOrArraySize, desc_.MipLevels, desc_.Width}, xg_layout) && xg_layout == 1)); static const bool defer_placed = [] { const char* value = std::getenv("LEONIDA_PLACED_IMAGE_DEFER"); return !value || std::strcmp(value, "0"); }(); // Private BC copies start with the exact same zero blocks as the shared image. The host // transition and clear complete before a private view is published, including during command prepare. if (defer_placed && origin == TitleImageOrigin::placed && host_transfer_ && device_.bindless && desc_.Flags == D3D12_RESOURCE_FLAG_NONE && desc_.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && desc_.SampleDesc.Count == 1 && asked_castable.empty() && !format.typeless && leonida::block_format(format.format, format.aspects).block > 1) { VkMemoryRequirements footprint{}; if (device_.memory_requirements(info, footprint)) shared_zero_ = device_.zero_sampled_image(desc_, format, footprint.size); } std::uint32_t plain_bits = 0; // A device without host copies has no other way to fill a title image: a refresh before a submission may not // use a staged copy through the queue (host_copy_now). Its linear movie planes are staged too. const bool no_host_copy = !device_.copy_memory_to_image && cpu_visible() && samples == 1 && !format.d24_as_float && !format.rgb96; if (stage_title && !shared_zero_ && allow_staged_title && origin != TitleImageOrigin::ordinary && (no_host_copy || (!linear_placement && host_transfer_)) && format.aspects == VK_IMAGE_ASPECT_COLOR_BIT && device_.image_requirements) { for (std::uint32_t i = 0; i < device_.memory.memoryTypeCount; ++i) { const auto flags = device_.memory.memoryTypes[i].propertyFlags; if ((flags & (VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT)) == VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) plain_bits |= 1u << i; } if (no_host_copy) plain_bits = UINT32_MAX; // nothing to compare with: any memory type will do VkMemoryRequirements with{}, without{}; auto staged = info; staged.usage &= ~VK_IMAGE_USAGE_HOST_TRANSFER_BIT_EXT; if (plain_bits && (no_host_copy || (device_.memory_requirements(info, with) && !(with.memoryTypeBits & plain_bits))) && device_.memory_requirements(staged, without) && (without.memoryTypeBits & plain_bits)) { staged_title_ = true; host_transfer_ = false; info.usage = staged.usage; } } auto retry_host = [&] { if (image_) vk.vkDestroyImage(device_.info.device, image_, nullptr); if (memory_) vk.vkFreeMemory(device_.info.device, memory_, nullptr); image_ = VK_NULL_HANDLE; memory_ = VK_NULL_HANDLE; staged_title_ = false; log_once("no room for a staged title image; retrying host-copyable backing, format", int(info.format)); return create_texture(format, asked_castable, origin, false); }; const auto create_image = [&]() -> HRESULT { const VkResult created = vk.vkCreateImage(device_.info.device, &info, nullptr, &image_); if (created == VK_SUCCESS) return S_OK; image_ = VK_NULL_HANDLE; // undefined after a failed create; ~Resource destroys any non-null image_ std::fprintf(stderr, "[rt] d3d12: vkCreateImage failed (%d): vk format %d %ux%u usage 0x%x flags 0x%x\n", int(created), int(info.format), info.extent.width, info.extent.height, unsigned(info.usage), unsigned(info.flags)); if (created == VK_ERROR_OUT_OF_HOST_MEMORY || created == VK_ERROR_OUT_OF_DEVICE_MEMORY) return E_OUTOFMEMORY; if (!view_formats_.empty()) { log_once("castable format list refused by Vulkan; count", int(view_formats_.size())); return E_INVALIDARG; } return E_OUTOFMEMORY; }; if (HRESULT hr = create_image(); FAILED(hr)) return staged_title_ ? retry_host() : hr; VkMemoryRequirements requirements{}; std::uint32_t type = UINT32_MAX; const bool stream = origin == TitleImageOrigin::streamed || origin == TitleImageOrigin::pending_stream; const auto allowed = staged_title_ ? plain_bits : UINT32_MAX; const bool deferrable = desc_.Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); // With pipelines and views prepared at bind time, a placed 2D texture that takes no host copies waits for // its memory too, until a command or a sampled view first uses it. const bool defer_sampled = device_.info.prepare_on_bind && origin == TitleImageOrigin::placed && desc_.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && !(desc_.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) && !host_transfer_; if (shared_zero_ || defer_sampled || (defer_placed && origin == TitleImageOrigin::placed && deferrable && !cpu_visible())) { vk.vkGetImageMemoryRequirements(device_.info.device, image_, &requirements); deferred_bytes_ = requirements.size; deferred_types_ = allowed; if (shared_zero_) { deferred_stream_ = true; std::lock_guard lock(device_.descriptor_mutex); device_.pending_image_keys[image_].zero = shared_zero_; } deferred_attachment_ = std::make_unique(this, [](void* owner) { return static_cast(owner)->bind_placed_memory(); }); } else if (origin == TitleImageOrigin::pending_stream && (host_transfer_ || staged_title_)) { vk.vkGetImageMemoryRequirements(device_.info.device, image_, &requirements); deferred_bytes_ = requirements.size; deferred_types_ = allowed; deferred_stream_ = true; std::lock_guard lock(device_.descriptor_mutex); device_.pending_image_keys.try_emplace(image_); } else if (origin != TitleImageOrigin::ordinary) { // A title image (placed or streamed) takes the title image pool or an allocation of its own, of the memory // types its placement allows; the shared texture blocks below are for the layer's ordinary textures. if (!bind_texture_memory(stream, allowed, requirements, type)) { if (staged_title_) return retry_host(); std::fprintf(stderr, "[rt] d3d12: texture memory unavailable: %llu bytes, alignment %llu, type bits 0x%x (vk " "format %d %ux%u)\n", static_cast(requirements.size), static_cast(requirements.alignment), unsigned(requirements.memoryTypeBits), int(info.format), info.extent.width, info.extent.height); return E_OUTOFMEMORY; } } else { // Some drivers advertise VK_EXT_host_image_copy yet allow no memory type for a HOST_TRANSFER image // (NVIDIA Pascal / 582.78: memoryTypeBits == 0), or fail to allocate one. Staging copies do not need // that usage, so recreate the image without it and continue on that path, as for a refused format above. // Render targets and depth buffers keep their own allocations: there are few of them, and a driver may // give one a better place. constexpr D3D12_RESOURCE_FLAGS attachment = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; for (;;) { vk.vkGetImageMemoryRequirements(device_.info.device, image_, &requirements); // NVIDIA's Pascal driver (582.78 on a GTX 1050 Ti) reports HOST_IMAGE_TRANSFER for the format and // creates the image, but then allows it no memory type at all. The image has not been bound or used, // so it is made again without host-transfer usage and the CPU copies take the staging path. The test // forces this branch on any GPU with force_host_transfer_retry. bool retry = host_transfer_ && (requirements.memoryTypeBits == 0 || device_.info.force_host_transfer_retry); if (!(desc_.Flags & attachment) && !host_transfer_) image_range_ = device_.allocate_image(requirements, memory_flags_); if (image_range_) { if (vk.vkBindImageMemory(device_.info.device, image_, image_range_->memory(), image_range_->offset()) == VK_SUCCESS) break; return E_OUTOFMEMORY; } if (!retry) { memory_ = device_.allocate(requirements, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, &memory_flags_); if (memory_ && vk.vkBindImageMemory(device_.info.device, image_, memory_, 0) == VK_SUCCESS) break; if (memory_) { vk.vkFreeMemory(device_.info.device, memory_, nullptr); memory_ = VK_NULL_HANDLE; } retry = host_transfer_; // a failed allocation/bind retries on the staging path too } if (!retry) return E_OUTOFMEMORY; log_once(requirements.memoryTypeBits == 0 || device_.info.force_host_transfer_retry ? "host-transfer image has no memory type; using staging copies, format" : "host-transfer image could not be bound; using staging copies, format", int(info.format)); vk.vkDestroyImage(device_.info.device, image_, nullptr); image_ = VK_NULL_HANDLE; host_transfer_ = false; info.usage &= ~VK_IMAGE_USAGE_HOST_TRANSFER_BIT_EXT; if (HRESULT hr = device_.check_image_support(info); FAILED(hr)) return hr; if (HRESULT hr = create_image(); FAILED(hr)) { log_once("image refused after dropping host-transfer usage; format", int(info.format)); return hr; } vk.vkGetImageMemoryRequirements(device_.info.device, image_, &requirements); if (requirements.memoryTypeBits == 0) log_once("image has no memory type even without host-transfer usage; format", int(info.format)); } image_backing_bytes_ = requirements.size; } if (!deferred_stream_ && !deferred_attachment_ && origin != TitleImageOrigin::ordinary && leonida::mem_probe::interval_seconds()) { char key[160]; std::snprintf(key, sizeof(key), "image-class slot=%u format=%u dim=%u samples=%u flags=0x%x usage=0x%x bits=0x%x", stream ? 70u : 133u, unsigned(info.format), unsigned(info.imageType), unsigned(info.samples), unsigned(info.flags), unsigned(info.usage), requirements.memoryTypeBits); if (first_diagnostic(key, int(type))) { VkImageCreateInfo staged = info; staged.usage &= ~VK_IMAGE_USAGE_HOST_TRANSFER_BIT_EXT; VkMemoryRequirements without = requirements; if (staged.usage != info.usage && !device_.memory_requirements(staged, without)) without.memoryTypeBits = 0; std::fprintf(stderr, "[rt] mem-probe: %s no-host-bits=0x%x type=%u\n", key, without.memoryTypeBits, type); } } leonida::ResourceBinding binding{}; if (deferred_attachment_) { binding.residency_owner = this; binding.ensure_residency = [](void* object) { auto* r=static_cast(object); const bool ready=r->ensure_texture_bound(); if (ready) r->gpu_referenced_.store(true,std::memory_order_release); return ready; }; } binding.image = image_; binding.typeless = format.typeless && format.aspects == VK_IMAGE_ASPECT_COLOR_BIT; // views name their format binding.castable_view_formats = !view_formats_.empty(); // a castable list made the image mutable binding.uint_backed = format.uint_backed; binding.rgb96 = format.rgb96; binding.depth24_as_float = format.d24_as_float; binding.depth24 = format.d24; binding.xbox_depth16_stencil8=format.xbox_depth16_stencil8; binding.rgba4_render_fallback=format.rgba4_render_fallback; binding.format = format.format; binding.aspects = format.aspects; binding.width = std::uint32_t(desc_.Width); binding.height = one_d ? 1u : desc_.Height; binding.mip_levels = desc_.MipLevels; binding.array_layers = info.arrayLayers; binding.depth = depth; binding.volume = volume; binding.line = one_d; binding.samples = samples; binding.color_attachment = (info.usage & VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) != 0; binding.sampled = (info.usage & VK_IMAGE_USAGE_SAMPLED_BIT) != 0; binding.simultaneous_access = (desc_.Flags & D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS) != 0; binding.not_zeroed = (heap_flags_ & D3D12_HEAP_FLAG_CREATE_NOT_ZEROED) != 0; // With the bindless set, a view's descriptor has one layout for as long as it lives (bind_image). binding.sampled_in_general = device_.bindless != nullptr; format_ = format.format; uint_backed_ = format.uint_backed; a8_as_alpha_ = format.a8_as_alpha; aspects_ = format.aspects; image_address_ = device_.next_image_address.fetch_add(256); device_.note_image_address(image_address_, this); binding.deferred_memory = deferred_attachment_.get(); if (origin == TitleImageOrigin::placed && leonida::mem_probe::interval_seconds()) binding.replay_seen = &replay_seen_; binding_ = binding; if (shared_zero_) { // All direct GPU commands resolve this binding in prepare(), before the descriptor table flush. device_.context->add_resource(id(), binding_, host_transfer_ ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_UNDEFINED); return S_OK; } return deferred_stream_ ? S_OK : register_bound_texture(); } // Called with title_texture_mutex held, after a guarded read of the complete console texture. bool back_streamed_texture() { if (!deferred_bytes_) return true; if (!image_backing_bytes_) { VkMemoryRequirements requirements{}; std::uint32_t type = UINT32_MAX; if (!bind_texture_memory(true, deferred_types_, requirements, type) && (deferred_types_ == UINT32_MAX || !(requirements.memoryTypeBits & ~deferred_types_) || !bind_texture_memory(true, ~deferred_types_, requirements, type))) return false; } if (FAILED(register_bound_texture())) return false; deferred_bytes_ = 0; return true; } void publish_streamed_texture() { if (!deferred_stream_) return; std::lock_guard lock(device_.descriptor_mutex); auto pending = device_.pending_image_keys.extract(image_); const auto owner = device_.images_by_address.find(image_address_); if (!pending.empty() && owner != device_.images_by_address.end() && owner->second == this) { if (pending.mapped().zero) device_.forget_image_views_locked(image_address_); for (const auto& [words, image] : pending.mapped().keys) device_.bind_image_locked(words, image, image_, format_, aspects_, false, has_view_format_list(), uint_backed_); } deferred_stream_ = false; } VkDeviceSize unbound_bytes() const { return image_backing_bytes() ? 0 : deferred_bytes_; } private: bool bind_placed_memory() { VkMemoryRequirements requirements{}; std::uint32_t type = UINT32_MAX; if (!image_backing_bytes_ && !bind_texture_memory(false, deferred_types_, requirements, type)) { if (!(requirements.memoryTypeBits & ~deferred_types_) || !bind_texture_memory(false, ~deferred_types_, requirements, type)) return false; } if (shared_zero_) { if (host_transfer_ && !host_initialize()) return false; publish_streamed_texture(); } return true; } bool bind_texture_memory(bool stream, std::uint32_t allowed_types, VkMemoryRequirements& requirements, std::uint32_t& type) { auto& vk = device_.context->vk; static const bool pool_images = [] { wchar_t value[2]{}; return !(GetEnvironmentVariableW(L"LEONIDA_TITLE_IMAGE_POOL", value, 2) == 1 && value[0] == L'0'); }(); VkMemoryDedicatedRequirements dedicated{VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS}; if (stream && pool_images && device_.bound_image_requirements) { VkImageMemoryRequirementsInfo2 query{VK_STRUCTURE_TYPE_IMAGE_MEMORY_REQUIREMENTS_INFO_2}; query.image = image_; VkMemoryRequirements2 result{VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2}; result.pNext = &dedicated; device_.bound_image_requirements(device_.info.device, &query, &result); requirements = result.memoryRequirements; if (!dedicated.requiresDedicatedAllocation) { auto pool_requirements = requirements; pool_requirements.memoryTypeBits &= allowed_types; pooled_image_ = device_.title_image_pool.bind(device_.info.device, image_, pool_requirements, vk.vkBindImageMemory, vk.vkDestroyImage, vk.vkFreeMemory, [&](VkDeviceSize size, std::uint32_t& type) { auto page = pool_requirements; page.size = size; return device_.allocate(page, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, nullptr, false, &type); }); if (pooled_image_) memory_flags_ = device_.memory.memoryTypes[pooled_image_->page->type].propertyFlags; } } else { vk.vkGetImageMemoryRequirements(device_.info.device, image_, &requirements); } type = pooled_image_ ? pooled_image_->page->type : UINT32_MAX; if (!pooled_image_) { auto selected = requirements; selected.memoryTypeBits &= allowed_types; memory_ = device_.allocate(selected, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, &memory_flags_, false, &type, dedicated.requiresDedicatedAllocation ? image_ : VK_NULL_HANDLE); } if (!pooled_image_ && (!memory_ || vk.vkBindImageMemory(device_.info.device, image_, memory_, 0) != VK_SUCCESS)) { if (memory_) vk.vkFreeMemory(device_.info.device, memory_, nullptr); memory_ = VK_NULL_HANDLE; return false; } image_backing_bytes_ = requirements.size; return true; } HRESULT register_bound_texture() { if (host_transfer_) { // Moved to GENERAL and zero-filled on the host now, so the CPU can copy into it before any command // list has touched it (a first GPU use would otherwise zero-fill over what the CPU wrote). if (!host_initialize()) return E_OUTOFMEMORY; device_.context->add_resource(id(), binding_, VK_IMAGE_LAYOUT_GENERAL); return S_OK; } // Never used yet: the first command that touches a part zero-fills it and moves it to the layout of the // state that command expects (vulkan_replay.h, initialize), so no submission is needed here. device_.context->add_resource(id(), binding_, VK_IMAGE_LAYOUT_UNDEFINED); // A shader may read it before any command names it: D3D12 gives zeros, and a reused range holds an older texture. if (image_range_ && image_range_->reused() && !binding_.not_zeroed) device_.context->note_shader_image(id()); return S_OK; } public: // The Xbox proxy calls this before publishing an allocated depth texture. Each storage plane owns a // regular color image with its own GFX10 address, so a UAV cannot replace the original SRV in set 0. HRESULT enable_depth_stencil_uav(D3D12_HEAP_FLAGS storage_heap_flags) { const bool narrow_stencil = desc_.Format == xbox_d16s8; const bool depth16 = desc_.Format == DXGI_FORMAT_R16_TYPELESS || narrow_stencil; if (!image_ || (!depth16 && desc_.Format != DXGI_FORMAT_R32G8X24_TYPELESS) || !(desc_.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) || desc_.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || desc_.MipLevels != 1 || !desc_.DepthOrArraySize || desc_.SampleDesc.Count != 1) return E_INVALIDARG; if (storage_planes_[0]) return S_OK; try { decltype(storage_planes_) planes; D3D12_RESOURCE_DESC plane_desc = desc_; plane_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; // D16 copies through a buffer as raw UNORM bits. R16_UINT lets an Xbox UAV read/write those bits. const bool widened = narrow_stencil && format_ != VK_FORMAT_D16_UNORM_S8_UINT; std::unique_ptr conversion; if (widened) { const auto blit = VK_FORMAT_FEATURE_2_BLIT_SRC_BIT | VK_FORMAT_FEATURE_2_BLIT_DST_BIT; if (format_ != VK_FORMAT_D32_SFLOAT_S8_UINT || (device_.optimal_features(VK_FORMAT_R16_UNORM) & blit) != blit || (device_.optimal_features(VK_FORMAT_R32_SFLOAT) & blit) != blit) return E_NOTIMPL; auto intermediate = plane_desc; intermediate.Format = DXGI_FORMAT_R32_FLOAT; intermediate.Flags = D3D12_RESOURCE_FLAG_NONE; conversion = std::make_unique(device_, intermediate, heap_, D3D12_HEAP_FLAG_NONE); const HRESULT hr = conversion->create_texture(device_.texture_format(intermediate)); if (FAILED(hr)) return hr; } const auto depth_format = widened ? DXGI_FORMAT_R16_TYPELESS : depth16 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_FLOAT; const DXGI_FORMAT formats[] = {depth_format, DXGI_FORMAT_R8_UINT}; const UINT plane_count = depth16 && !narrow_stencil ? 1 : 2; for (UINT plane = 0; plane < plane_count; ++plane) { plane_desc.Format = formats[plane]; planes[plane] = std::make_unique(device_, plane_desc, heap_, storage_heap_flags); const HRESULT hr = planes[plane]->create_texture(device_.texture_format(plane_desc)); if (FAILED(hr)) return hr; } // Replacing the binding preserves the tracked layout of the original depth/stencil image. auto binding = binding_; binding.depth_uav = planes[0]->id(); binding.depth_conversion = conversion ? conversion->id() : 0; binding.stencil_uav = planes[1] ? planes[1]->id() : 0; device_.context->add_resource(id(), binding); binding_ = binding; storage_planes_ = std::move(planes); depth_conversion_ = std::move(conversion); heap_flags_ |= storage_heap_flags; // GetHeapProperties describes the caller's entire logical texture. } catch (const std::bad_alloc&) { return E_OUTOFMEMORY; } return S_OK; } // D3D12 reports the placement alignment of a description that left it 0: 64 KiB, or 4 MiB for a multisampled // texture. One the description asked for is kept. Measured on the PC runtime and WARP (d3d12_resource_desc_test). D3D12_RESOURCE_DESC STDMETHODCALLTYPE GetDesc() override { D3D12_RESOURCE_DESC desc = desc_; if (storage_ || storage_planes_[0]) desc.Flags |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; if (!desc.Alignment) { desc.Alignment = (desc.SampleDesc.Count > 1 && !is_tiled_layout(desc.Layout)) ? D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT : D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT; } return desc; } bool belongs_to(const DeviceState& device) const { return &device_ == &device; } // Both sparse resources and the committed fallback report the reserved layout and have no heap of their own. void make_reserved(D3D12_TEXTURE_LAYOUT layout) { reserved_ = true; desc_.Layout = layout; } bool reserved() const { return reserved_; } // A committed resource: neither placed in a heap nor reserved. It owns its memory, like a heap does. bool committed() const { return !placed_ && !reserved_; } // D3D12 answers only for committed and placed resources (E_INVALIDARG for reserved ones, measured on the PC // runtime). // Buffers report their console VA into the GPU address arena; an acceleration structure reports its real device // address (instance descriptors and builds hand it to the driver). A texture the title placed at its own address // through Xbox slot 133 reports that title address, as the console does (place_at_title_address; docs/d3d12_vulkan.md // 3.3). Any other texture answers 0, as on D3D12. D3D12_GPU_VIRTUAL_ADDRESS STDMETHODCALLTYPE GetGPUVirtualAddress() override { if (image_ && title_address_) return reinterpret_cast(title_address_); return accel_ ? gpu_va_ : va_; } // A texture the title placed on its own memory (Xbox device slot 133, create_at_host_address). The console's // texture IS that memory: Map and GetGPUVirtualAddress answer with the address (the title memsets and fills // textures through the pointer Map gives it, and writes to address 0 when it gets none), and its T#s, the ones // the title writes itself into a console descriptor heap included, name it by that address. The image is still // ordinary GPU memory, filled from the title's bytes at the address by the title-texture registry // (TitleTexture) unless the GPU writes it. void place_at_title_address(void* address, bool separate_image_key = false) { title_address_ = address; const auto va = reinterpret_cast(address); if (!image_ || !image_address_ || (va & 0xff)) return; // a T# keeps the address without its low 8 bits if (separate_image_key) return; device_.forget_image(image_address_); device_.forget_image(va); // an earlier texture placed at this address, still alive: its views are stale image_address_ = va; device_.note_image_address(image_address_, this); } // The title's own address for a texture Xbox slot 133 placed. The image is still the committed fallback, so its // pixels do not alias the title's pages yet; the address is what GetGPUVirtualAddress answers (XCL PR #168's // behavior, measured on a retail title). void set_title_address(D3D12_GPU_VIRTUAL_ADDRESS address) { if (!image_ || !address || title_image_registered_) return; std::lock_guard lock(device_.title_image_mutex); va_ = address; device_.title_images.emplace(va_, this); title_image_registered_ = true; } // No descriptors have been built for a newly materialized raw surface. void set_raw_image_address(std::uint64_t address) { image_address_ = address; } void use_texture_lease(void* data, std::size_t size, UINT layout) { if (!image_ || !data) return; const auto addr = reinterpret_cast(data); if (va_ && va_ != addr) return; if ((layout == 1 || layout == 0x100) && desc_.Dimension==D3D12_RESOURCE_DIMENSION_TEXTURE2D) { // Placement callbacks get a title VA; pin_mapped_data checks its live XMem section on Map. title_linear_ = true; title_linear_limit_ = size ? size : SIZE_MAX; } if (!size || va_) return; std::uint64_t lo = 0, hi = 0; const bool tracked = leonida::title_va_aliases().title_memory(addr, lo, hi) && size <= hi - addr; MEMORY_BASIC_INFORMATION page{}; const bool writable = VirtualQuery(data, &page, sizeof(page)) && page.State == MEM_COMMIT && !(page.Protect & (PAGE_NOACCESS | PAGE_GUARD)) && ((page.Protect & 0xffu) == PAGE_READWRITE || (page.Protect & 0xffu) == PAGE_WRITECOPY); if (tracked && writable) { set_title_address(addr); } } // // The node masks read back as the one node of a single adapter (0 becomes 1), and the heap flags as the runtime // resolves them: the caller's, without the two creation-only bits (CREATE_NOT_RESIDENT, CREATE_NOT_ZEROED), plus // the DENY bits of the resource classes this resource is not (buffers 0xC0, textures without render-target or // depth use 0x44, the others 0x84). Measured on the PC runtime and WARP (d3d12_node_mask_test). HRESULT STDMETHODCALLTYPE GetHeapProperties(D3D12_HEAP_PROPERTIES* properties, D3D12_HEAP_FLAGS* flags) override { if (reserved_) return E_INVALIDARG; if (properties) { *properties = heap_; if (!properties->CreationNodeMask) properties->CreationNodeMask = 1; if (!properties->VisibleNodeMask) properties->VisibleNodeMask = 1; } if (flags) *flags = resolved_heap_flags(); return S_OK; } D3D12_HEAP_FLAGS resolved_heap_flags() const { const UINT deny_buffers = D3D12_HEAP_FLAG_DENY_BUFFERS, deny_rt_ds = D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES, deny_non_rt_ds = D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES; UINT deny = deny_buffers | deny_rt_ds; // a texture without render-target or depth use if (desc_.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) deny = deny_rt_ds | deny_non_rt_ds; else if (desc_.Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) deny = deny_buffers | deny_non_rt_ds; const UINT creation_only = D3D12_HEAP_FLAG_CREATE_NOT_RESIDENT | D3D12_HEAP_FLAG_CREATE_NOT_ZEROED; // A placed resource reports its heap's flags as they are (an ALLOW_ALL heap reads back 0): the DENY bits // are the runtime's choice only for the implicit heap of a committed resource (d3d12_heap_properties_test). if (placed_) return D3D12_HEAP_FLAGS(UINT(heap_flags_) & ~creation_only); return D3D12_HEAP_FLAGS((UINT(heap_flags_) & ~creation_only) | deny); } // Buffers on upload and readback heaps are mapped persistently; the ranges are hints, as on D3D12, except that // the host runtime refuses a non-empty read range that ends past the buffer. A texture in a CPU-visible heap has // no pointer to give (its layout is the driver's), so D3D12 only lets it be mapped with a null pointer, before // WriteToSubresource/ReadFromSubresource. HRESULT STDMETHODCALLTYPE Map(UINT subresource, const D3D12_RANGE* read, void** data) override { // A texture whose lease says its title memory is linear (title_linear_) and that also has a placement // address (slot 133; the video planes among them) has two answers. The placement address, with the title // texture registry filling the image, is the one the retail boot ran through the intro movie and the story // load on, so it is asked first. LEONIDA_LINEAR_MAP_FIRST=1 gives such a texture the linear mapping instead // (pinned pages, with a GPU-written texture read back into them), and its refusal when the pages are gone. static const bool linear_first = [] { const char* v = std::getenv("LEONIDA_LINEAR_MAP_FIRST"); return v && *v == '1'; }(); if (linear_first && title_linear_ && data && image_) { *data = nullptr; return map_title_texture(subresource, read, data); } if (image_ && title_address_) { // place_at_title_address: the console answers with the texture's memory if (data) { *data = title_address_; rt::placed_image_map_note::note(title_address_, subresource, read, desc_.Width == 1 && desc_.Height == 1 && desc_.Format == DXGI_FORMAT_R32G32B32A32_FLOAT); read_back_on_map(subresource); } // From now on the CPU may write its texels whenever it likes (video planes are mapped once): the // registry checks this texture's bytes before submissions (Device::refresh_title_textures). if (title_texture_ && !title_mapped_.exchange(true, std::memory_order_relaxed)) device_.title_texture_mapped(this, reinterpret_cast(title_address_)); return S_OK; } if (title_linear_ && data && image_) { // a leased linear texture with no placement address *data = nullptr; return map_title_texture(subresource, read, data); } if (image_) { VkImageSubresourceRange range{}; return !data && cpu_visible() && subresource != leonida::all_subresources && leonida::image_range(binding_, subresource, range) ? S_OK : E_INVALIDARG; } if (!mapped_ || subresource != 0) return E_INVALIDARG; if (read && read->Begin < read->End && read->End > desc_.Width) return E_INVALIDARG; if (data) *data = mapped_; return S_OK; } // LEONIDA_MAP_READBACK=1: the GPU's texels of a small render target the title placed are written into the title's // pages when it maps the target. The title reads its exposure statistics that way every frame (a 1x1 and a 5x1 // RGBA32F target, Map at 0x5121690 from 0xb96aa0: team/exposure-readback.md); the GPU renders into our image, // never into those pages, so the CPU read zeros and the exposure went to ~0 (a frame crushed to black, peak // 0.008). Only a single-row, single-mip, single-layer 2D target of at most 4 KiB: the console's linear layout // puts that row at offset 0 (xg-rt-layout), so the row pitch does not matter. The copy waits for the GPU // (ReadFromSubresource's staging copy, behind the work already submitted), and lands through a guarded copy: a // page that is not writable now is left as it is. void read_back_on_map(UINT subresource) { static const bool on = [] { const char* v = std::getenv("LEONIDA_MAP_READBACK"); return v && std::strcmp(v, "1") == 0; }(); if (!on || subresource != 0) return; if (!(desc_.Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS))) return; if (desc_.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || desc_.Height != 1 || desc_.DepthOrArraySize != 1 || desc_.MipLevels > 1 || binding_.samples > 1) return; const auto block = leonida::copy_block_format(binding_, VK_IMAGE_ASPECT_COLOR_BIT); if (!block.bytes || block.block != 1) return; const std::uint64_t row = desc_.Width * block.bytes; if (!row || row > 4096) return; std::uint8_t texels[4096]; const HRESULT hr = cpu_copy(false, 0, nullptr, texels, UINT(row), UINT(row)); static std::atomic done{0}, failed{0}; if (FAILED(hr) || !copy_guarded(static_cast(title_address_), texels, std::size_t(row), false)) { const std::uint64_t n = failed.fetch_add(1, std::memory_order_relaxed) + 1; if (n <= 4 || !(n & (n - 1))) std::fprintf(stderr, "[rt] d3d12: map read-back of a %llux1 target at %p failed (hr 0x%08lx; %llu so far)\n", static_cast(desc_.Width), title_address_, static_cast(hr), static_cast(n)); return; } const std::uint64_t n = done.fetch_add(1, std::memory_order_relaxed) + 1; if (n <= 8 || !(n & (n - 1))) { float f[4] = {}; std::memcpy(f, texels, (std::min)(sizeof(f), std::size_t(row))); std::fprintf(stderr, "[rt] d3d12: map read-back #%llu: %llux1 format %d target at %p, first texel %g %g %g " "%g\n", static_cast(n), static_cast(desc_.Width), int(desc_.Format), title_address_, f[0], f[1], f[2], f[3]); } } // A texture the title placed: Unmap ends its CPU writes (the title's lock passes the range it wrote), so its // image is filled again before the next submission (TitleTexture). void STDMETHODCALLTYPE Unmap(UINT sub, const D3D12_RANGE* written) override { if (image_ && title_address_ && title_texture_ && (!written || written->End > written->Begin)) device_.title_texture_unmapped(this, reinterpret_cast(title_address_)); if (!title_linear_) return; std::lock_guard lock(title_map_mutex_); const auto it=title_maps_.find(sub); if(it==title_maps_.end()) return; if ((!written || written->End>written->Begin) && (!written || written->End<=it->second.bytes)) if(!upload_title_map(sub,it->second)) std::fprintf(stderr,"[rt] d3d12: texture upload on Unmap failed, format %u\n",unsigned(desc_.Format)); if (!--it->second.refs) title_maps_.erase(it); if (title_maps_.empty()) { std::lock_guard guard(device_.mapped_texture_mutex); if(device_.mapped_textures.erase(this)) --device_.map_count; } } bool publish_cpu_writes() { std::lock_guard lock(title_map_mutex_); for(auto& [sub,map]:title_maps_) if(!upload_title_map(sub,map)) return false; return true; } // CPU copies into and out of a texture subresource. D3D12 completes them before returning and leaves it to // the application to keep the GPU off the subresource meanwhile, so a blocking copy is the whole contract. HRESULT STDMETHODCALLTYPE WriteToSubresource(UINT subresource, const D3D12_BOX* box, const void* data, UINT row_pitch, UINT depth_pitch) override { return cpu_copy(true, subresource, box, const_cast(data), row_pitch, depth_pitch); } HRESULT STDMETHODCALLTYPE ReadFromSubresource(void* data, UINT row_pitch, UINT depth_pitch, UINT subresource, const D3D12_BOX* box) override { return cpu_copy(false, subresource, box, data, row_pitch, depth_pitch); } private: struct TitleMap { std::shared_ptr data; std::uintptr_t address{}; UINT row{},bytes{},refs{}; std::string fingerprint; bool shared_pages = false; }; static std::string fingerprint(const TitleMap& map) { std::string out; for(std::size_t at=0;at(1u<<20,map.bytes-at)}); return out; } bool upload_title_map(UINT sub, TitleMap& map) { if (map.shared_pages) { auto current=rt::d3d12_xs::pin_texture_pages(reinterpret_cast(map.address),map.bytes); if (!current || current.get()!=map.data.get()) return false; } auto hash=fingerprint(map); if(hash==map.fingerprint) return true; if(FAILED(cpu_copy(true,sub,nullptr,map.data.get(),map.row,map.bytes))) return false; map.fingerprint=std::move(hash); return true; } HRESULT map_title_texture(UINT sub, const D3D12_RANGE* read, void** out) { if (!va_ || desc_.SampleDesc.Count!=1 || aspects_!=VK_IMAGE_ASPECT_COLOR_BIT || binding_.rgba4_render_fallback || binding_.rgb96 || sub>=UINT(desc_.MipLevels)*desc_.DepthOrArraySize) return E_INVALIDARG; std::lock_guard lock(title_map_mutex_); if (auto it=title_maps_.find(sub);it!=title_maps_.end()) { if(read && read->End>read->Begin && read->End>it->second.bytes) return E_INVALIDARG; ++it->second.refs;*out=reinterpret_cast(it->second.address);return S_OK; } namespace ct=leonida::console_texture; ct::TextureDesc d{};d.format=unsigned(desc_.Format);d.width=UINT(desc_.Width);d.height=desc_.Height; d.depth_or_array=desc_.DepthOrArraySize;d.mips=desc_.MipLevels;d.swizzle=ct::kLinear; const auto shape=ct::Texture::make(d); if(!shape || shape->planes.size()!=1) return E_INVALIDARG; const auto& layout=shape->planes[0].layout; const UINT mip=sub%desc_.MipLevels,slice=sub/desc_.MipLevels; const auto& level=layout.mips[mip]; const std::uint64_t row=std::uint64_t(level.pitch)*layout.desc.element_bytes, size=row*level.height; std::uint64_t offset{}; if(layout.offset(mip,0,0,slice,offset)!=ct::Error::ok || !size || size>UINT_MAX || offset>title_linear_limit_ || size>title_linear_limit_-offset || offset>UINTPTR_MAX-va_ || size>UINTPTR_MAX-va_-offset || (read && read->End>read->Begin && read->End>size)) return E_INVALIDARG; const auto title_address=std::uintptr_t(va_+offset); auto pinned=rt::d3d12_xs::pin_texture_pages(reinterpret_cast(title_address),std::size_t(size)); const bool shared=bool(pinned); if (shared) previously_pinned_ = true; else if (previously_pinned_) return E_INVALIDARG; else { // A console GPU VA need not name CPU memory on the PC. Map the live Vulkan image by // staging it through our own allocation. The supplied VA is never dereferenced here. try { pinned = std::shared_ptr(new std::uint8_t[std::size_t(size)]{},std::default_delete()); } catch(const std::bad_alloc&) { return E_OUTOFMEMORY; } } const auto address=shared ? title_address : reinterpret_cast(pinned.get()); TitleMap map{std::move(pinned),address,UINT(row),UINT(size),1,{},shared}; if ((!read || read->End>read->Begin) && (!shared || gpu_referenced_.load(std::memory_order_acquire))) { const HRESULT hr=cpu_copy(false,sub,nullptr,map.data.get(),map.row,map.bytes); if(FAILED(hr)) return hr; map.fingerprint=fingerprint(map); } title_maps_.emplace(sub,std::move(map)); { std::lock_guard guard(device_.mapped_texture_mutex); if(device_.mapped_textures.insert(this).second) ++device_.map_count; } *out=reinterpret_cast(address); return S_OK; } bool title_linear_ = false; bool previously_pinned_ = false; std::uint64_t title_linear_limit_ = 0; std::atomic gpu_referenced_{false}; std::mutex title_map_mutex_; std::map title_maps_; // One subresource region in copy units: rows of texels, or of 4x4 blocks for block-compressed formats. struct Region { VkImageSubresourceLayers layers; D3D12_BOX box; leonida::BlockFormat block; std::uint32_t rows; std::uint64_t row_bytes; std::uint32_t slices; }; // The region a copy names, or false when D3D12 would reject it: an unknown subresource, a box whose right, // bottom or back edge lies past the mip's, or one that cuts a compressed block anywhere but at the mip edge. // An empty or inverted box that passes those checks is no copy at all: `rows` and `slices` are 0, and the host // runtime answers S_OK without touching a byte (d3d12_subresource_copy_test, RTX 3060 / 610.88). bool region(UINT subresource, const D3D12_BOX* box, Region& out) const { VkImageSubresourceRange range{}; if (subresource == leonida::all_subresources || !leonida::image_range(binding_, subresource, range)) return false; if (binding_.samples > 1) return false; // D3D12 has no CPU copies of multisampled textures; Vulkan neither const std::uint32_t mip = range.baseMipLevel; const std::uint32_t width = std::max(1u, binding_.width >> mip), height = std::max(1u, binding_.height >> mip); const std::uint32_t depth = binding_.volume ? std::max(1u, binding_.depth >> mip) : 1; out.box = box ? *box : D3D12_BOX{0, 0, 0, width, height, depth}; const D3D12_BOX& b = out.box; if (b.right > width || b.bottom > height || b.back > depth) return false; out.block = leonida::copy_block_format(binding_, range.aspectMask); if (!out.block.bytes) return false; const std::uint32_t k = out.block.block; if (b.left % k || b.top % k || (b.right % k && b.right != width) || (b.bottom % k && b.bottom != height)) return false; out.layers = {range.aspectMask, mip, range.baseArrayLayer, 1}; if (b.left >= b.right || b.top >= b.bottom || b.front >= b.back) { out.rows = 0; out.row_bytes = 0; out.slices = 0; return true; } out.rows = (b.bottom - b.top + k - 1) / k; out.row_bytes = std::uint64_t((b.right - b.left + k - 1) / k) * out.block.bytes; out.slices = b.back - b.front; return true; } HRESULT cpu_copy(bool write, UINT subresource, const D3D12_BOX* box, void* data, UINT row_pitch, UINT depth_pitch, bool allow_host = true) { if (!image_ || !data) return E_INVALIDARG; Region r{}; if (!region(subresource, box, r)) return E_INVALIDARG; if (!r.rows || !r.slices) return S_OK; // an empty box: nothing to copy if (deferred_attachment_ && !deferred_attachment_->ensure()) return E_OUTOFMEMORY; // The pitches are not checked, as on the host runtime: rows or slices that overlap (a pitch smaller than a // row, or 0) are copied in order, row by row and slice by slice, so on a read the last one wins. if (!cpu_visible()) log_once(write ? "WriteToSubresource on a texture outside a CPU-visible heap; heap type" : "ReadFromSubresource on a texture outside a CPU-visible heap; heap type", heap_.Type); auto* bytes = static_cast(data); // Between the application's pitches and `pitch`, the one a copy reads or writes. const auto pack = [&](std::byte* to, std::uint64_t pitch) { for (std::uint32_t z = 0; z < r.slices; ++z) for (std::uint32_t y = 0; y < r.rows; ++y) std::memcpy(to + (std::uint64_t(z) * r.rows + y) * pitch, bytes + std::uint64_t(z) * depth_pitch + std::uint64_t(y) * row_pitch, r.row_bytes); }; const auto unpack = [&](const std::byte* from, std::uint64_t pitch) { for (std::uint32_t z = 0; z < r.slices; ++z) for (std::uint32_t y = 0; y < r.rows; ++y) std::memcpy(bytes + std::uint64_t(z) * depth_pitch + std::uint64_t(y) * row_pitch, from + (std::uint64_t(z) * r.rows + y) * pitch, r.row_bytes); }; // On the host only while the subresource is in GENERAL: it is from creation, and stays there until a // barrier moves it (D3D12's COMMON is GENERAL). Any other layout goes through the staging copy, which // moves it as a CopyTextureRegion would. if (allow_host && host_transfer_ && device_.context->layout(id(), subresource) == VK_IMAGE_LAYOUT_GENERAL) { std::vector packed(r.row_bytes * r.rows * r.slices); if (write) pack(packed.data(), r.row_bytes); if (!host_copy(write, r, packed.data())) return E_FAIL; if (!write) unpack(packed.data(), r.row_bytes); return S_OK; } return staged_copy(write, subresource, r, pack, unpack); } // Tightly packed `memory` to or from the region, with VK_EXT_host_image_copy. bool host_copy(bool write, const Region& r, void* memory) { const VkOffset3D offset{std::int32_t(r.box.left), std::int32_t(r.box.top), std::int32_t(r.box.front)}; const VkExtent3D extent{r.box.right - r.box.left, r.box.bottom - r.box.top, r.slices}; const VkDevice dev = device_.info.device; if (write) { VkMemoryToImageCopyEXT copy{VK_STRUCTURE_TYPE_MEMORY_TO_IMAGE_COPY_EXT}; copy.pHostPointer = memory; copy.imageSubresource = r.layers; copy.imageOffset = offset; copy.imageExtent = extent; VkCopyMemoryToImageInfoEXT info{VK_STRUCTURE_TYPE_COPY_MEMORY_TO_IMAGE_INFO_EXT}; info.dstImage = image_; info.dstImageLayout = VK_IMAGE_LAYOUT_GENERAL; info.regionCount = 1; info.pRegions = © return device_.copy_memory_to_image(dev, &info) == VK_SUCCESS; } VkImageToMemoryCopyEXT copy{VK_STRUCTURE_TYPE_IMAGE_TO_MEMORY_COPY_EXT}; copy.pHostPointer = memory; copy.imageSubresource = r.layers; copy.imageOffset = offset; copy.imageExtent = extent; VkCopyImageToMemoryInfoEXT info{VK_STRUCTURE_TYPE_COPY_IMAGE_TO_MEMORY_INFO_EXT}; info.srcImage = image_; info.srcImageLayout = VK_IMAGE_LAYOUT_GENERAL; info.regionCount = 1; info.pRegions = © return device_.copy_image_to_memory(dev, &info) == VK_SUCCESS; } // Every subresource of a new host-transfer image to GENERAL, zero-filled unless the heap said not to. bool host_initialize() { const VkDevice dev = device_.info.device; VkHostImageLayoutTransitionInfoEXT transition{VK_STRUCTURE_TYPE_HOST_IMAGE_LAYOUT_TRANSITION_INFO_EXT}; transition.image = image_; transition.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; transition.newLayout = VK_IMAGE_LAYOUT_GENERAL; transition.subresourceRange = {binding_.aspects, 0, binding_.mip_levels, 0, binding_.volume ? VK_REMAINING_ARRAY_LAYERS : binding_.array_layers}; if (device_.transition_image_layout(dev, 1, &transition) != VK_SUCCESS) return false; if (binding_.not_zeroed) return true; const std::uint32_t planes = leonida::two_planes(binding_) ? 2 : 1; const std::uint32_t per_plane = binding_.mip_levels * binding_.array_layers; std::vector zero; for (UINT subresource = 0; subresource < planes * per_plane; ++subresource) { Region r{}; if (!region(subresource, nullptr, r)) return false; zero.assign(r.row_bytes * r.rows * r.slices, std::byte{0}); if (!host_copy(true, r, zero.data())) return false; } return true; } // A host-visible buffer at D3D12's footprint pitch, copied to or from the subresource by a CopyTextureRegion // replayed on the device's queue, then waited for. The replay handles the layout (and a first use's zero fill) // exactly as it does for the application's own copies. template HRESULT staged_copy(bool write, UINT subresource, const Region& r, const Pack& pack, const Unpack& unpack) { auto& vk = device_.context->vk; const VkDevice dev = device_.info.device; const std::uint64_t pitch = (r.row_bytes + D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1) / D3D12_TEXTURE_DATA_PITCH_ALIGNMENT * D3D12_TEXTURE_DATA_PITCH_ALIGNMENT; leonida::ResourceBinding staging{}; staging.size = pitch * r.rows * r.slices; VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; info.size = staging.size; info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT; // storage: D24 depth conversion device_.share(info); if (vk.vkCreateBuffer(dev, &info, nullptr, &staging.buffer) != VK_SUCCESS) return E_OUTOFMEMORY; VkDeviceMemory memory = VK_NULL_HANDLE; void* mapped = nullptr; const auto release = [&](HRESULT hr) { if (memory) vk.vkFreeMemory(dev, memory, nullptr); // unmaps it vk.vkDestroyBuffer(dev, staging.buffer, nullptr); return hr; }; VkMemoryRequirements requirements{}; vk.vkGetBufferMemoryRequirements(dev, staging.buffer, &requirements); memory = device_.allocate(requirements, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, write ? 0 : VK_MEMORY_PROPERTY_HOST_CACHED_BIT); if (!memory || vk.vkBindBufferMemory(dev, staging.buffer, memory, 0) != VK_SUCCESS || vk.vkMapMemory(dev, memory, 0, VK_WHOLE_SIZE, 0, &mapped) != VK_SUCCESS) return release(E_OUTOFMEMORY); if (write) pack(static_cast(mapped), pitch); // The staging buffer is a resource only for the length of this call; its ID is its binding's address, // which no COM resource can share. const auto staging_id = reinterpret_cast(&staging); const std::uint32_t k = r.block.block; const leonida::CopyLocation texture{id(), false, subresource, 0, 0, 0, 0, 0}; const leonida::CopyLocation placed{staging_id, true, 0, 0, std::uint32_t(r.row_bytes / r.block.bytes) * k, r.rows * k, r.slices, std::uint32_t(pitch)}; leonida::CopyTexture copy{}; if (write) { copy = {texture, r.box.left, r.box.top, r.box.front, placed, false, {}}; } else { copy = {placed, 0, 0, 0, texture, true, {r.box.left, r.box.top, r.box.front, r.box.right, r.box.bottom, r.box.back}}; } leonida::CommandList list; if (!list.copy_texture(copy) || !list.close()) return release(E_INVALIDARG); device_.context->add_resource(staging_id, staging); leonida::ReplayResult result = leonida::ReplayResult::unsupported; { std::lock_guard lock(device_.staging_mutex); if (!device_.staging_queue) { device_.staging_queue = std::make_unique(*device_.context, device_.info.queue, device_.info.queue_family); } if (device_.staging_queue->ok()) { const leonida::CommandList* lists[] = {&list}; result = device_.staging_queue->execute(lists); if (result == leonida::ReplayResult::success && !device_.staging_queue->idle()) result = leonida::ReplayResult::unsupported; } } device_.context->remove_resource(staging_id); if (result != leonida::ReplayResult::success) { log_once("WriteToSubresource/ReadFromSubresource staging copy failed; replay result", int(result)); return release(E_FAIL); } if (!write) unpack(static_cast(mapped), pitch); return release(S_OK); } bool cpu_visible() const { if (heap_.Type == D3D12_HEAP_TYPE_UPLOAD || heap_.Type == D3D12_HEAP_TYPE_READBACK) return true; return heap_.Type == D3D12_HEAP_TYPE_CUSTOM && heap_.CPUPageProperty != D3D12_CPU_PAGE_PROPERTY_NOT_AVAILABLE && heap_.CPUPageProperty != D3D12_CPU_PAGE_PROPERTY_UNKNOWN; } // Only these heaps hold bytes the CPU writes. READBACK is CPU-visible but GPU-written, and DEFAULT arena memory // is also GPU-written; both can hold stale bytes at replay time, so host_at() must not read them as inputs. bool cpu_writable() const { if (heap_.Type == D3D12_HEAP_TYPE_UPLOAD) return true; return heap_.Type == D3D12_HEAP_TYPE_CUSTOM && (heap_.CPUPageProperty == D3D12_CPU_PAGE_PROPERTY_WRITE_BACK || heap_.CPUPageProperty == D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE); } DeviceState& device_; D3D12_RESOURCE_DESC desc_; Resource* storage_ = nullptr; bool title_image_registered_ = false; D3D12_HEAP_PROPERTIES heap_; D3D12_HEAP_FLAGS heap_flags_; VkImage image_ = VK_NULL_HANDLE; VkBuffer buffer_ = VK_NULL_HANDLE; VkDeviceMemory memory_ = VK_NULL_HANDLE; std::unique_ptr image_range_; // a texture's, instead of memory_ VkMemoryPropertyFlags memory_flags_ = 0; VkDeviceSize image_backing_bytes_ = 0; // Vulkan image memory requirement; excludes pool alignment/padding. std::unique_ptr pooled_image_; VkAccelerationStructureKHR accel_ = VK_NULL_HANDLE; void* mapped_ = nullptr; VkFormat format_ = VK_FORMAT_UNDEFINED; std::vector view_formats_; // creation-time castable list; empty means no restriction std::vector castable_formats_; // the same list as the application gave it VkFormat uint_backed_ = VK_FORMAT_UNDEFINED; bool a8_as_alpha_ = false; std::uint64_t image_address_ = 0; // what a T# names the texture by void* title_address_ = nullptr; // where the title placed this texture (place_at_title_address), or null bool title_texture_ = false; // mark_title_texture mutable std::atomic shader_views_{0}; // T#s written for it (write_image_descriptor), for the census std::atomic title_mapped_{false}; // Map told the registry bool rgb96_ = false; VkImageAspectFlags aspects_ = 0; std::uint64_t buffer_va_ = 0; std::uint64_t gpu_va_ = 0; bool host_import_ = false; // memory_ is the caller's pages (create_host_buffer): freed at once, not deferred std::uint64_t host_pin_ = 0; // create_host_buffer: the pages' leonida::kernel_writes pin while memory_ lives std::uint8_t* shadow_ = nullptr; // create_shadow_buffer: memory_ mapped, in DeviceState::shadows bool aliased_ = false; // va_ is in leonida::title_va_aliases(), reached at title_alias_ std::uint64_t title_alias_ = 0; bool reserved_ = false; bool sparse_image_ = false; bool placed_ = false; leonida::ResourceBinding binding_{}; // a texture's, as registered with the context std::unique_ptr depth_conversion_; std::array, 2> storage_planes_; // Xbox depth/stencil UAV, by plane VkImage shared_zero_ = VK_NULL_HANDLE; // owned by the device std::unique_ptr deferred_attachment_; std::atomic replay_seen_{false}; bool staged_title_ = false; std::atomic deferred_stream_{false}; // keys stay unpublished until the whole first upload succeeds VkDeviceSize deferred_bytes_ = 0; std::uint32_t deferred_types_ = 0; bool host_transfer_ = false; // created with VK_IMAGE_USAGE_HOST_TRANSFER_BIT_EXT D3D12_GPU_VIRTUAL_ADDRESS va_ = 0; // a buffer's console VA, or a slot-133 texture's title address VkDeviceSize arena_offset_ = 0; bool in_arena_ = false; // A placed buffer's heap range, held as a D3D12 placed resource holds its heap: the app may release the heap // first, and the range must not go to another allocation while this buffer lives. std::shared_ptr heap_range_; }; // One immutable, host-zeroed BC image per exact view shape. It has the right sampled format, extent, // mip count and zero-block decoding even before the title first supplies data or copies into the placement. VkImage DeviceState::zero_sampled_image(const D3D12_RESOURCE_DESC& d, const Format& format, VkDeviceSize bytes) { if (!host_transfer_format(format.format)) return VK_NULL_HANDLE; const ZeroShape key{d.Format, d.Width, d.Height, d.DepthOrArraySize, d.MipLevels}; std::lock_guard lock(zero_image_mutex); if (auto it = zero_images.find(key); it != zero_images.end()) return it->second ? it->second->image() : VK_NULL_HANDLE; constexpr VkDeviceSize limit = 256ull << 20; const auto used = zero_image_bytes.load(std::memory_order_relaxed); if (used >= limit || bytes > limit - used) return VK_NULL_HANDLE; const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_CUSTOM, D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, D3D12_MEMORY_POOL_L0, 1, 1}; auto* zero = new Resource(*this, d, heap, D3D12_HEAP_FLAG_NONE); if (FAILED(zero->create_texture(format)) || !zero->host_initialized_image() || zero->image_backing_bytes() > limit - used) { zero->Release(); zero_images.emplace(key, nullptr); return VK_NULL_HANDLE; } zero_images.emplace(key, zero); zero_image_bytes.fetch_add(zero->image_backing_bytes(), std::memory_order_relaxed); return zero->image(); } // DXGI -> Vulkan for vertex attributes, with each element's size for D3D12_APPEND_ALIGNED_ELEMENT. bool vertex_format(DXGI_FORMAT format, VkFormat& out, UINT& bytes) { struct Row { DXGI_FORMAT dxgi; VkFormat vk; UINT bytes; }; static constexpr Row rows[] = { {DXGI_FORMAT_R32G32B32A32_FLOAT, VK_FORMAT_R32G32B32A32_SFLOAT, 16}, {DXGI_FORMAT_R32G32B32A32_UINT, VK_FORMAT_R32G32B32A32_UINT, 16}, {DXGI_FORMAT_R32G32B32A32_SINT, VK_FORMAT_R32G32B32A32_SINT, 16}, {DXGI_FORMAT_R32G32B32_FLOAT, VK_FORMAT_R32G32B32_SFLOAT, 12}, {DXGI_FORMAT_R32G32B32_UINT, VK_FORMAT_R32G32B32_UINT, 12}, {DXGI_FORMAT_R32G32B32_SINT, VK_FORMAT_R32G32B32_SINT, 12}, {DXGI_FORMAT_R32G32_FLOAT, VK_FORMAT_R32G32_SFLOAT, 8}, {DXGI_FORMAT_R32G32_UINT, VK_FORMAT_R32G32_UINT, 8}, {DXGI_FORMAT_R32G32_SINT, VK_FORMAT_R32G32_SINT, 8}, {DXGI_FORMAT_R32_FLOAT, VK_FORMAT_R32_SFLOAT, 4}, {DXGI_FORMAT_R32_UINT, VK_FORMAT_R32_UINT, 4}, {DXGI_FORMAT_R32_SINT, VK_FORMAT_R32_SINT, 4}, {DXGI_FORMAT_R16G16B16A16_FLOAT, VK_FORMAT_R16G16B16A16_SFLOAT, 8}, {DXGI_FORMAT_R16G16B16A16_UNORM, VK_FORMAT_R16G16B16A16_UNORM, 8}, {DXGI_FORMAT_R16G16B16A16_SNORM, VK_FORMAT_R16G16B16A16_SNORM, 8}, {DXGI_FORMAT_R16G16B16A16_UINT, VK_FORMAT_R16G16B16A16_UINT, 8}, {DXGI_FORMAT_R16G16B16A16_SINT, VK_FORMAT_R16G16B16A16_SINT, 8}, {DXGI_FORMAT_R16G16_FLOAT, VK_FORMAT_R16G16_SFLOAT, 4}, {DXGI_FORMAT_R16G16_UNORM, VK_FORMAT_R16G16_UNORM, 4}, {DXGI_FORMAT_R16G16_SNORM, VK_FORMAT_R16G16_SNORM, 4}, {DXGI_FORMAT_R16G16_UINT, VK_FORMAT_R16G16_UINT, 4}, {DXGI_FORMAT_R16G16_SINT, VK_FORMAT_R16G16_SINT, 4}, {DXGI_FORMAT_R16_FLOAT, VK_FORMAT_R16_SFLOAT, 2}, {DXGI_FORMAT_R16_UNORM, VK_FORMAT_R16_UNORM, 2}, {DXGI_FORMAT_R16_SNORM, VK_FORMAT_R16_SNORM, 2}, {DXGI_FORMAT_R16_UINT, VK_FORMAT_R16_UINT, 2}, {DXGI_FORMAT_R16_SINT, VK_FORMAT_R16_SINT, 2}, {DXGI_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_R8G8B8A8_UNORM, 4}, {DXGI_FORMAT_R8G8B8A8_SNORM, VK_FORMAT_R8G8B8A8_SNORM, 4}, {DXGI_FORMAT_R8G8B8A8_UINT, VK_FORMAT_R8G8B8A8_UINT, 4}, {DXGI_FORMAT_R8G8B8A8_SINT, VK_FORMAT_R8G8B8A8_SINT, 4}, {DXGI_FORMAT_B8G8R8A8_UNORM, VK_FORMAT_B8G8R8A8_UNORM, 4}, {DXGI_FORMAT_R8G8_UNORM, VK_FORMAT_R8G8_UNORM, 2}, {DXGI_FORMAT_R8G8_SNORM, VK_FORMAT_R8G8_SNORM, 2}, {DXGI_FORMAT_R8G8_UINT, VK_FORMAT_R8G8_UINT, 2}, {DXGI_FORMAT_R8G8_SINT, VK_FORMAT_R8G8_SINT, 2}, {DXGI_FORMAT_R8_UNORM, VK_FORMAT_R8_UNORM, 1}, {DXGI_FORMAT_R8_SNORM, VK_FORMAT_R8_SNORM, 1}, {DXGI_FORMAT_R8_UINT, VK_FORMAT_R8_UINT, 1}, {DXGI_FORMAT_R8_SINT, VK_FORMAT_R8_SINT, 1}, {DXGI_FORMAT_R10G10B10A2_UNORM, VK_FORMAT_A2B10G10R10_UNORM_PACK32, 4}, {DXGI_FORMAT_R10G10B10A2_UINT, VK_FORMAT_A2B10G10R10_UINT_PACK32, 4}, {DXGI_FORMAT_R11G11B10_FLOAT, VK_FORMAT_B10G11R11_UFLOAT_PACK32, 4}, }; for (const Row& row : rows) if (row.dxgi == format) { out = row.vk; bytes = row.bytes; return true; } return false; } VkBlendFactor blend_factor(D3D12_BLEND blend) { switch (blend) { case D3D12_BLEND_ZERO: return VK_BLEND_FACTOR_ZERO; case D3D12_BLEND_ONE: return VK_BLEND_FACTOR_ONE; case D3D12_BLEND_SRC_COLOR: return VK_BLEND_FACTOR_SRC_COLOR; case D3D12_BLEND_INV_SRC_COLOR: return VK_BLEND_FACTOR_ONE_MINUS_SRC_COLOR; case D3D12_BLEND_SRC_ALPHA: return VK_BLEND_FACTOR_SRC_ALPHA; case D3D12_BLEND_INV_SRC_ALPHA: return VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA; case D3D12_BLEND_DEST_ALPHA: return VK_BLEND_FACTOR_DST_ALPHA; case D3D12_BLEND_INV_DEST_ALPHA: return VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA; case D3D12_BLEND_DEST_COLOR: return VK_BLEND_FACTOR_DST_COLOR; case D3D12_BLEND_INV_DEST_COLOR: return VK_BLEND_FACTOR_ONE_MINUS_DST_COLOR; case D3D12_BLEND_SRC_ALPHA_SAT: return VK_BLEND_FACTOR_SRC_ALPHA_SATURATE; case D3D12_BLEND_BLEND_FACTOR: return VK_BLEND_FACTOR_CONSTANT_COLOR; case D3D12_BLEND_INV_BLEND_FACTOR: return VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_COLOR; case D3D12_BLEND_SRC1_COLOR: return VK_BLEND_FACTOR_SRC1_COLOR; case D3D12_BLEND_INV_SRC1_COLOR: return VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR; case D3D12_BLEND_SRC1_ALPHA: return VK_BLEND_FACTOR_SRC1_ALPHA; case D3D12_BLEND_INV_SRC1_ALPHA: return VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA; case D3D12_BLEND_ALPHA_FACTOR: return VK_BLEND_FACTOR_CONSTANT_ALPHA; case D3D12_BLEND_INV_ALPHA_FACTOR: return VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_ALPHA; default: return VK_BLEND_FACTOR_ONE; } } VkBlendOp blend_op(D3D12_BLEND_OP op) { switch (op) { case D3D12_BLEND_OP_SUBTRACT: return VK_BLEND_OP_SUBTRACT; case D3D12_BLEND_OP_REV_SUBTRACT: return VK_BLEND_OP_REVERSE_SUBTRACT; case D3D12_BLEND_OP_MIN: return VK_BLEND_OP_MIN; case D3D12_BLEND_OP_MAX: return VK_BLEND_OP_MAX; default: return VK_BLEND_OP_ADD; } } // D3D12 and Vulkan list the logic ops in different orders, so each is named. VkLogicOp logic_op(D3D12_LOGIC_OP op) { switch (op) { case D3D12_LOGIC_OP_CLEAR: return VK_LOGIC_OP_CLEAR; case D3D12_LOGIC_OP_SET: return VK_LOGIC_OP_SET; case D3D12_LOGIC_OP_COPY: return VK_LOGIC_OP_COPY; case D3D12_LOGIC_OP_COPY_INVERTED: return VK_LOGIC_OP_COPY_INVERTED; case D3D12_LOGIC_OP_NOOP: return VK_LOGIC_OP_NO_OP; case D3D12_LOGIC_OP_INVERT: return VK_LOGIC_OP_INVERT; case D3D12_LOGIC_OP_AND: return VK_LOGIC_OP_AND; case D3D12_LOGIC_OP_NAND: return VK_LOGIC_OP_NAND; case D3D12_LOGIC_OP_OR: return VK_LOGIC_OP_OR; case D3D12_LOGIC_OP_NOR: return VK_LOGIC_OP_NOR; case D3D12_LOGIC_OP_XOR: return VK_LOGIC_OP_XOR; case D3D12_LOGIC_OP_EQUIV: return VK_LOGIC_OP_EQUIVALENT; case D3D12_LOGIC_OP_AND_REVERSE: return VK_LOGIC_OP_AND_REVERSE; case D3D12_LOGIC_OP_AND_INVERTED: return VK_LOGIC_OP_AND_INVERTED; case D3D12_LOGIC_OP_OR_REVERSE: return VK_LOGIC_OP_OR_REVERSE; case D3D12_LOGIC_OP_OR_INVERTED: return VK_LOGIC_OP_OR_INVERTED; default: return VK_LOGIC_OP_COPY; } } // D3D12_COMPARISON_FUNC (NEVER = 1 .. ALWAYS = 8) and D3D12_STENCIL_OP (KEEP = 1 .. DECR = 8) list their values // in Vulkan's order, starting at 1 instead of 0. VkCompareOp compare_op(D3D12_COMPARISON_FUNC func) { const int value = int(func); return value >= 1 && value <= 8 ? VkCompareOp(value - 1) : VK_COMPARE_OP_ALWAYS; } VkStencilOp stencil_op(D3D12_STENCIL_OP op) { const int value = int(op); return value >= 1 && value <= 8 ? VkStencilOp(value - 1) : VK_STENCIL_OP_KEEP; } VkStencilOpState stencil_face(const D3D12_DEPTH_STENCILOP_DESC& face, UINT8 read_mask, UINT8 write_mask) { VkStencilOpState state{}; state.failOp = stencil_op(face.StencilFailOp); state.passOp = stencil_op(face.StencilPassOp); state.depthFailOp = stencil_op(face.StencilDepthFailOp); state.compareOp = compare_op(face.StencilFunc); state.compareMask = read_mask; state.writeMask = write_mask; return state; } bool equal_semantic(const std::string& a, const char* b) { if (!b || a.size() != std::strlen(b)) return false; for (std::size_t i = 0; i < a.size(); ++i) if (std::tolower(static_cast(a[i])) != std::tolower(static_cast(b[i]))) return false; return true; } // A heap (section 3.3): a range of the GPU address arena, as large as the game asked for, so a placed buffer can // name any 64 KiB-aligned offset in it. Textures placed in it still get their own VkDeviceMemory; the offset is only // their key, which keeps optimal-tiling images out of the arena's memory type. bool DeviceState::publish_mapped_textures() { if(!map_count.load(std::memory_order_acquire)) return true; std::vector pending; { std::lock_guard lock(mapped_texture_mutex); for(auto* r:mapped_textures) if(r->try_add_ref()) pending.push_back(r); } bool ok=true; for(auto* r:pending) { if(!r->publish_cpu_writes()) ok=false; r->Release(); } return ok; } bool DeviceState::materialize_sample(const leonida::DescriptorKey& key) { if (!pending_sample_count.load(std::memory_order_acquire)) return true; PendingSample sample{}; { std::lock_guard lock(pending_view_mutex); const auto it = pending_samples.find(key); if (it == pending_samples.end()) return true; sample = it->second; if (!sample.owner->try_add_ref()) return false; } const auto image = sample.owner->bound_image(); const bool ok = image && bind_image(key, sample.image, image, sample.view_format, sample.channels_format, sample.view_format, sample.owner->aspects(), true, false, {}); if (ok) { context->note_shader_image(sample.owner->id()); std::lock_guard lock(pending_view_mutex); const auto it=pending_samples.find(key); if (it!=pending_samples.end() && it->second.owner==sample.owner) { pending_samples.erase(it); --pending_sample_count; } } sample.owner->Release(); return ok; } bool DeviceState::materialize_table(std::uint64_t address, std::uint32_t slots) { if (!pending_sample_count.load(std::memory_order_acquire)) return true; if (!slots && address) { std::vector keys; { std::lock_guard lock(pending_view_mutex); for (const auto& [key,view]:pending_samples) if (view.owner->id() == address) keys.push_back(key); } for (const auto& key:keys) if (!materialize_sample(key)) return false; return true; } std::uint64_t end = 0; if (slots) { std::lock_guard lock(visible_heap_mutex); auto it = visible_heaps.upper_bound(address); if (it != visible_heaps.begin()) { --it; if (address < it->second.end && (address-it->first)%kDescriptorSize==0) { if(it->second.type==D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER) return true; end = address + std::min(it->second.end-address, std::uint64_t(slots)*kDescriptorSize); } } } if (!end) { // Directly indexed and unrecognized heaps have no trustworthy table extent. std::vector all; {std::lock_guard lock(pending_view_mutex);for(const auto& [key,v]:pending_samples) all.push_back(key);} for(const auto& key:all) if(!materialize_sample(key)) return false; return true; } const auto refreshed = std::min(end-address, std::uint64_t(kViewScanLimit)*kDescriptorSize); if (end-address>refreshed) leonida::title_va_aliases().pull_descriptors(arena.mapped+address+refreshed,std::size_t(end-address-refreshed)); for (auto at=address; at { public: // {5d20c7a4-8e13-4b6d-9f27-3a1c94e0b7d8} static constexpr GUID kTag{0x5d20c7a4, 0x8e13, 0x4b6d, {0x9f, 0x27, 0x3a, 0x1c, 0x94, 0xe0, 0xb7, 0xd8}}; Heap(DeviceState& device, const D3D12_HEAP_DESC& desc) : device_(device), desc_(desc) { VkDeviceSize offset = 0; if (device_.arena.mapped && device_.arena_allocate(desc_.SizeInBytes, D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT, offset, DeviceState::arena_heap)) { allocation_ = std::shared_ptr( new leonida::TileHeapAllocation{device_.arena.memory, offset, desc_.SizeInBytes, device_.arena.memory_type}, [&device](const leonida::TileHeapAllocation* allocation) { device.arena_release(allocation->offset, allocation->size, DeviceState::arena_heap); delete allocation; }); } } // An existing heap (OpenExistingHeapFromAddress): `memory` is the caller's committed range imported with // VK_EXT_external_memory_host, and the heap owns that VkDeviceMemory, not the range. Not in the arena. Heap(DeviceState& device, const D3D12_HEAP_DESC& desc, VkDeviceMemory memory, std::uint32_t memory_type, const void* address) : device_(device), desc_(desc), host_address_(address) { allocation_ = std::shared_ptr( new leonida::TileHeapAllocation{memory, 0, desc_.SizeInBytes, memory_type}, [device = device_.info.device, free = device_.context->vk.vkFreeMemory] (const leonida::TileHeapAllocation* allocation) { free(device, allocation->memory, nullptr); delete allocation; }); } // As the host reports it (measured against the PC runtime, d3d12_vulkan_device_test compare_heap_descs): the // alignment the heap was placed with (64 KiB for an Alignment of 0) and the one node for a node mask of 0, as the // layer's resources, descriptor heaps and queues already answer. D3D12_HEAP_DESC STDMETHODCALLTYPE GetDesc() override { D3D12_HEAP_DESC desc = desc_; desc.Alignment = alignment(); desc.Properties.CreationNodeMask = 1; desc.Properties.VisibleNodeMask = 1; return desc; } bool reserved() const { return bool(allocation_); } // An existing heap: the caller's memory, not an arena range, so offset() is not a place in the arena. const void* host_address() const { return host_address_; } const std::shared_ptr& arena_range() const { return allocation_; } VkDeviceSize offset() const { return allocation_->offset; } UINT64 bytes() const { return desc_.SizeInBytes; } UINT64 alignment() const { return desc_.Alignment ? desc_.Alignment : D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT; } const D3D12_HEAP_PROPERTIES& properties() const { return desc_.Properties; } D3D12_HEAP_FLAGS flags() const { return desc_.Flags; } std::shared_ptr tiles(const leonida::VulkanContext& context, bool image, std::uint32_t memory_types) { const auto denied = image ? D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES : D3D12_HEAP_FLAG_DENY_BUFFERS; if (device_.context.get() != &context || desc_.Properties.Type != D3D12_HEAP_TYPE_DEFAULT || (desc_.Flags & denied) || host_address_) return {}; std::lock_guard lock(backing_mutex_); if (!image && device_.tiles_share_arena()) { if (tile_allocation_) return {}; arena_tiles_ = true; return allocation_; } // Vulkan only guarantees sparse aliasing between compatible images. A texture tile heap has its own // backing, so a heap already used for buffer tiles or placed buffers cannot also map texture tiles. if (arena_tiles_ || (tile_allocation_ && image_tiles_ != image)) return {}; if (placed_buffer_ || (image && placed_image_)) return {}; if (!tile_allocation_) { std::uint32_t memory_type = 0; if (!image) memory_types = device_.sparse_buffer_memory_types; const VkMemoryRequirements requirements{desc_.SizeInBytes, leonida::tile_size_in_bytes, memory_types}; const auto memory = device_.allocate(requirements, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, 0, nullptr, !image, &memory_type); if (!memory) return {}; image_tiles_ = image; tile_allocation_ = std::shared_ptr( new leonida::TileHeapAllocation{memory, 0, desc_.SizeInBytes, memory_type}, [device = device_.info.device, free = device_.context->vk.vkFreeMemory] (const leonida::TileHeapAllocation* allocation) { free(device, allocation->memory, nullptr); delete allocation; }); } return tile_allocation_; } bool use_as_placed_resource(bool buffer) { std::lock_guard lock(backing_mutex_); // A placed resource cannot alias the separate sparse memory allocation. if (tile_allocation_ && (buffer || image_tiles_)) return false; (buffer ? placed_buffer_ : placed_image_) = true; return true; } private: DeviceState& device_; D3D12_HEAP_DESC desc_; const void* host_address_ = nullptr; std::shared_ptr allocation_; std::mutex backing_mutex_; std::shared_ptr tile_allocation_; bool placed_buffer_ = false; bool placed_image_ = false; bool arena_tiles_ = false; bool image_tiles_ = false; }; // The S#s a shader builds from immediates (literal_samplers in its index entry) are named by no heap slot, so // nothing else gives them a sampler and a hash-table key: without this their lookup finds the fallback sampler // (index 0) and the shader samples with the wrong filter and address modes (docs/design.md, Literal samplers). // Registering is idempotent and also runs when the pipeline is created again. void register_literal_samplers(DeviceState& device, const leonida::ShaderEntry& entry) { for (const leonida::gfx10::SamplerWords& words : entry.literal_samplers) if (!device.bind_sampler(words)) log_once("a shader's literal S# got no sampler (no bindless set, or its sampler array is full); " "literal S#s in that shader:", int(entry.literal_samplers.size())); } // Among index entries for one program (containers with the same FSSM program; 789 groups in the 26,503-shader // corpus), the one to build: the first that `fits` and declares no set-0 bindings (the cheaper pipeline); else the // first that fits; else the first without bindings; else the first. Null when there is none. template const leonida::ShaderEntry* pick_entry(const std::vector& candidates, Fits&& fits) { const leonida::ShaderEntry* fitting = nullptr; const leonida::ShaderEntry* unbound = nullptr; for (const leonida::ShaderEntry* e : candidates) { const bool fit = fits(*e); if (fit && !e->binding_count) return e; if (fit && !fitting) fitting = e; if (!e->binding_count && !unbound) unbound = e; } if (fitting) return fitting; if (unbound) return unbound; return candidates.empty() ? nullptr : candidates.front(); } // Whether the input layout has an element for every ordinary (non-system-value) input of the vertex shader. bool layout_feeds(const leonida::ShaderEntry& vs, const D3D12_INPUT_LAYOUT_DESC& layout) { const UINT count = layout.pInputElementDescs ? layout.NumElements : 0; for (const auto& input : vs.input_signature) { if (input.system_value) continue; bool fed = false; for (UINT i = 0; i < count && !fed; ++i) fed = layout.pInputElementDescs[i].SemanticIndex == input.semantic_index && equal_semantic(input.semantic, layout.pInputElementDescs[i].SemanticName); if (!fed) return false; } return true; } // Known D3D12_PIPELINE_STATE_FLAGS bits: TOOL_DEBUG (0x1, kept for cached-PSO parity), bit 0x2, // DYNAMIC_DEPTH_BIAS (0x4), and DYNAMIC_INDEX_BUFFER_STRIP_CUT (0x8). Higher bits fail with E_INVALIDARG // on both Windows hardware D3D12 and WARP. constexpr UINT kKnownPipelineStateFlags = 0xFu; class RootSignature final : public Child { public: // {3e9b4a61-2d7c-4f18-b5a0-c71e8d92f036} static constexpr GUID kTag{0x3e9b4a61, 0x2d7c, 0x4f18, {0xb5, 0xa0, 0xc7, 0x1e, 0x8d, 0x92, 0xf0, 0x36}}; RootSignature(RootArgumentLayout layout, std::string content) : layout_(std::move(layout)), content_(std::move(content)) {} const RootArgumentLayout& layout() const { return layout_; } // SHA-256 of the serialized root signature: a cached PSO matches root signatures with the same content. const std::string& content() const { return content_; } private: RootArgumentLayout layout_; std::string content_; }; // The ID3DBlob GetCachedBlob returns. class CachedBlob final : public ID3DBlob { public: explicit CachedBlob(std::vector bytes) : bytes_(std::move(bytes)) {} HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** out) override { if (!out) return E_POINTER; if (riid == __uuidof(IUnknown) || riid == __uuidof(ID3D10Blob)) { AddRef(); *out = static_cast(this); return S_OK; } *out = nullptr; return E_NOINTERFACE; } ULONG STDMETHODCALLTYPE AddRef() override { return ++refs_; } ULONG STDMETHODCALLTYPE Release() override { const ULONG left = --refs_; if (!left) delete this; return left; } LPVOID STDMETHODCALLTYPE GetBufferPointer() override { return bytes_.data(); } SIZE_T STDMETHODCALLTYPE GetBufferSize() override { return bytes_.size(); } private: std::vector bytes_; std::atomic refs_{1}; }; // A shader as the key sees it, without reading the whole program on every PSO: a DXBC container already carries a // checksum of its contents (bytes 4..19), so that and the size stand for it. A container without one (all zero, as // hand-built test containers have) or other bytecode is hashed with FNV-1a. void key_shader(leonida::cached_pso::KeyBuilder& key, const char* stage, const D3D12_SHADER_BYTECODE& code) { const auto* bytes = static_cast(code.pShaderBytecode); const std::size_t size = bytes ? code.BytecodeLength : 0; key.tag(stage).u32(std::uint32_t(size)).u32(std::uint32_t(std::uint64_t(size) >> 32)); if (size >= 20 && std::memcmp(bytes, "DXBC", 4) == 0 && std::any_of(bytes + 4, bytes + 20, [](std::uint8_t b) { return b != 0; })) { key.bytes(bytes + 4, 16); return; } std::uint64_t h = 0xcbf29ce484222325ull; for (std::size_t i = 0; i < size; ++i) h = (h ^ bytes[i]) * 0x100000001b3ull; key.u32(std::uint32_t(h)).u32(std::uint32_t(h >> 32)); } void key_root_signature(leonida::cached_pso::KeyBuilder& key, ID3D12RootSignature* signature); // The parts of a compute description the PC runtime matches a cached PSO against (not Flags, measured). leonida::cached_pso::Key pipeline_key(const D3D12_COMPUTE_PIPELINE_STATE_DESC& desc) { leonida::cached_pso::KeyBuilder key; key.tag("compute"); key_root_signature(key, desc.pRootSignature); key_shader(key, "cs", desc.CS); key.u32(desc.NodeMask); return leonida::sha256_hex(key.data()); } leonida::cached_pso::Key pipeline_key(const D3D12_GRAPHICS_PIPELINE_STATE_DESC& desc) { leonida::cached_pso::KeyBuilder key; key.tag("graphics"); key_root_signature(key, desc.pRootSignature); key_shader(key, "vs", desc.VS); key_shader(key, "ps", desc.PS); key_shader(key, "ds", desc.DS); key_shader(key, "hs", desc.HS); key_shader(key, "gs", desc.GS); const D3D12_STREAM_OUTPUT_DESC& so = desc.StreamOutput; key.u32(so.pSODeclaration ? so.NumEntries : 0); for (UINT i = 0; so.pSODeclaration && i < so.NumEntries; ++i) { const D3D12_SO_DECLARATION_ENTRY& e = so.pSODeclaration[i]; key.u32(e.Stream).text(e.SemanticName).u32(e.SemanticIndex).u32(e.StartComponent).u32(e.ComponentCount); key.u32(e.OutputSlot); } key.u32(so.pBufferStrides ? so.NumStrides : 0); for (UINT i = 0; so.pBufferStrides && i < so.NumStrides; ++i) key.u32(so.pBufferStrides[i]); key.u32(so.RasterizedStream); const D3D12_BLEND_DESC& blend = desc.BlendState; key.u32(blend.AlphaToCoverageEnable).u32(blend.IndependentBlendEnable); for (const D3D12_RENDER_TARGET_BLEND_DESC& t : blend.RenderTarget) key.u32(t.BlendEnable).u32(t.LogicOpEnable).u32(t.SrcBlend).u32(t.DestBlend).u32(t.BlendOp).u32(t.SrcBlendAlpha) .u32(t.DestBlendAlpha).u32(t.BlendOpAlpha).u32(t.LogicOp).u32(t.RenderTargetWriteMask); key.u32(desc.SampleMask); const D3D12_RASTERIZER_DESC& r = desc.RasterizerState; std::uint32_t bias_clamp = 0, slope = 0; std::memcpy(&bias_clamp, &r.DepthBiasClamp, 4); std::memcpy(&slope, &r.SlopeScaledDepthBias, 4); key.u32(r.FillMode).u32(r.CullMode).u32(r.FrontCounterClockwise).u32(std::uint32_t(r.DepthBias)).u32(bias_clamp); key.u32(slope).u32(r.DepthClipEnable).u32(r.MultisampleEnable).u32(r.AntialiasedLineEnable); key.u32(r.ForcedSampleCount).u32(r.ConservativeRaster); const D3D12_DEPTH_STENCIL_DESC& d = desc.DepthStencilState; key.u32(d.DepthEnable).u32(d.DepthWriteMask).u32(d.DepthFunc).u32(d.StencilEnable).u32(d.StencilReadMask); key.u32(d.StencilWriteMask); for (const D3D12_DEPTH_STENCILOP_DESC& face : {d.FrontFace, d.BackFace}) key.u32(face.StencilFailOp).u32(face.StencilDepthFailOp).u32(face.StencilPassOp).u32(face.StencilFunc); const D3D12_INPUT_LAYOUT_DESC& input = desc.InputLayout; const UINT input_count = input.pInputElementDescs ? std::min(input.NumElements, D3D12_IA_VERTEX_INPUT_STRUCTURE_ELEMENT_COUNT) : 0; key.u32(input_count); for (UINT i = 0; i < input_count; ++i) { const D3D12_INPUT_ELEMENT_DESC& e = input.pInputElementDescs[i]; key.text(e.SemanticName).u32(e.SemanticIndex).u32(e.Format).u32(e.InputSlot).u32(e.AlignedByteOffset); key.u32(e.InputSlotClass).u32(e.InstanceDataStepRate); } key.u32(desc.IBStripCutValue).u32(std::bit_cast(desc.PrimitiveTopologyType)) .u32(desc.NumRenderTargets); for (const DXGI_FORMAT format : desc.RTVFormats) key.u32(format); key.u32(desc.DSVFormat).u32(desc.SampleDesc.Count).u32(desc.SampleDesc.Quality).u32(desc.NodeMask); return leonida::sha256_hex(key.data()); } // CachedPSO as the PC runtime checks it before creating the PSO (src/cached_pso.h has the measured answers). HRESULT check_cached_pso(const leonida::cached_pso::Identity& identity, const leonida::cached_pso::Key& key, const D3D12_CACHED_PIPELINE_STATE& cached) { if (!cached.pCachedBlob) return S_OK; if (!cached.CachedBlobSizeInBytes) return E_INVALIDARG; using leonida::cached_pso::Check; switch (leonida::cached_pso::check(identity, key, {static_cast(cached.pCachedBlob), cached.CachedBlobSizeInBytes})) { case Check::accepted: return S_OK; case Check::other_adapter: return D3D12_ERROR_ADAPTER_NOT_FOUND; case Check::other_driver: return D3D12_ERROR_DRIVER_VERSION_MISMATCH; default: return E_INVALIDARG; } } // The console's ID3D12PipelineState goes past the public interface, which ends at slot 8 (GetCachedBlob). The // FidelityFX DLL calls slot 11 on every compute pipeline it creates (docs/d3d12_command_objects.md, "Pipeline slot 11 // sizes the compute scratch"). These three are declared here, ahead of Object's virtual destructor, so they are vtable // slots 9, 10 and 11 under MSVC and GCC alike; declared in PipelineState itself they would come after the destructor, // which takes one slot under MSVC and two under GCC. d3d12_fspx_compute_test calls slot 11 through the vtable. class XboxPipelineStateStubs : public ID3D12PipelineStateStubs { public: virtual HRESULT STDMETHODCALLTYPE xbox_slot9(UINT64, UINT64, UINT64) = 0; virtual HRESULT STDMETHODCALLTYPE xbox_slot10(UINT64, UINT64, UINT64) = 0; virtual HRESULT STDMETHODCALLTYPE xbox_slot11(UINT64, UINT64, void** out) = 0; }; // A D3D12_PIPELINE_STATE_STREAM_DESC (ID3D12Device2::CreatePipelineState) as the descriptions the PSO creators take. // The stream is a run of subobjects, each a D3D12_PIPELINE_STATE_SUBOBJECT_TYPE followed by its description at that // description's alignment, each subobject starting at pointer alignment (the d3dx12.h layout, `alignas(void*)`). A // subobject that is absent takes the runtime's default (the CD3DX12 defaults: depth test on with LESS, back-face // culling, no blending, sample mask 0xFFFFFFFF, one sample). A type given twice, a truncated stream or an unknown // type is E_INVALIDARG, as on the PC runtime; state this layer cannot honour yet is E_NOTIMPL with a log. // The back face's stencil masks of a DEPTH_STENCIL2 subobject. D3D12_DEPTH_STENCIL_DESC has one read and one write // mask for both faces, so the face masks travel beside the description. struct StencilFaceMasks { UINT8 read = D3D12_DEFAULT_STENCIL_READ_MASK; UINT8 write = D3D12_DEFAULT_STENCIL_WRITE_MASK; }; struct PipelineStream { D3D12_GRAPHICS_PIPELINE_STATE_DESC graphics{}; bool back_masks = false; // DEPTH_STENCIL2: back_stencil holds the back face's masks StencilFaceMasks back_stencil; D3D12_COMPUTE_PIPELINE_STATE_DESC compute{}; D3D12_SHADER_BYTECODE ms{}; D3D12_SHADER_BYTECODE as{}; bool has_cs = false; bool has_graphics_stage = false; // VS, PS, DS, HS, GS, AS or MS }; // Console stream retry adapted from Kokonotcu, ubiquitarianism/leonida #496 (GPL-3.0). bool console_stream_enum_enabled() { static const bool enabled = [] { char value[8] = {}; const DWORD n = GetEnvironmentVariableA("LEONIDA_XS_STREAM_ENUM", value, sizeof(value)); return !(n == 1 && value[0] == '0') && !(n == 2 && (value[0] == 'p' || value[0] == 'P') && (value[1] == 'c' || value[1] == 'C')); }(); return enabled; } // The first DWORD in a DXIL program header holds the shader kind in its high 16 bits. // Require a mesh program (kind 13) before changing the meaning of a stream that failed the PC parse. bool is_mesh_container(const D3D12_SHADER_BYTECODE& code) { if (!code.pShaderBytecode) return false; const auto dxil = leonida::dxbc_part({static_cast(code.pShaderBytecode), code.BytecodeLength}, "DXIL"); return dxil.size() >= 4 && dxil[2] == 13 && dxil[3] == 0; } HRESULT stream_unsupported(const char* reason, int type = 0) { d3d12_trace::stream_refusal = reason; log_once(reason, type); return E_NOTIMPL; } // The console numbering lacks the gap at 23 in the PC enumeration. HRESULT parse_pipeline_stream(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, PipelineStream& out, bool console_enum = false) { if (!desc.pPipelineStateSubobjectStream || !desc.SizeInBytes) return E_INVALIDARG; D3D12_GRAPHICS_PIPELINE_STATE_DESC& g = out.graphics; for (auto& target : g.BlendState.RenderTarget) { target.SrcBlend = target.SrcBlendAlpha = D3D12_BLEND_ONE; target.DestBlend = target.DestBlendAlpha = D3D12_BLEND_ZERO; target.BlendOp = target.BlendOpAlpha = D3D12_BLEND_OP_ADD; target.LogicOp = D3D12_LOGIC_OP_NOOP; target.RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; } g.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; g.RasterizerState.CullMode = D3D12_CULL_MODE_BACK; g.RasterizerState.DepthClipEnable = TRUE; g.DepthStencilState.DepthEnable = TRUE; g.DepthStencilState.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL; g.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_LESS; g.DepthStencilState.StencilReadMask = D3D12_DEFAULT_STENCIL_READ_MASK; g.DepthStencilState.StencilWriteMask = D3D12_DEFAULT_STENCIL_WRITE_MASK; g.DepthStencilState.FrontFace = g.DepthStencilState.BackFace = { D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_KEEP, D3D12_COMPARISON_FUNC_ALWAYS}; g.SampleMask = UINT_MAX; g.SampleDesc = {1, 0}; const auto* base = static_cast(desc.pPipelineStateSubobjectStream); const std::size_t size = desc.SizeInBytes; const auto round_up = [](std::size_t v, std::size_t a) { return (v + a - 1) / a * a; }; std::uint64_t seen = 0; std::size_t at = 0; while (at < size) { D3D12_PIPELINE_STATE_SUBOBJECT_TYPE type; if (size - at < sizeof(type)) return E_INVALIDARG; std::memcpy(&type, base + at, sizeof(type)); type = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE(d3d12_xs::pc_stream_type(unsigned(type), console_enum)); // The versioned depth-stencil and rasterizer subobjects describe the same state as their base type, so the // stream contract counts any two of one family as duplicates; the payload below still follows `type`. D3D12_PIPELINE_STATE_SUBOBJECT_TYPE family = type; if (type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1 || type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL2) family = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL; else if (type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER1 || type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER2) family = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER; if (unsigned(type) >= 64 || (seen >> unsigned(family) & 1)) return E_INVALIDARG; seen |= std::uint64_t(1) << unsigned(family); bool ok = true; const auto take = [&](auto& value) { using T = std::remove_reference_t; const std::size_t payload = round_up(at + sizeof(type), alignof(T)); if (payload > size || size - payload < sizeof(T)) { ok = false; return; } std::memcpy(&value, base + payload, sizeof(T)); at = round_up(payload + sizeof(T), sizeof(void*)); }; const auto stage = [&](D3D12_SHADER_BYTECODE& code) { take(code); out.has_graphics_stage = true; }; switch (type) { case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE: take(g.pRootSignature); out.compute.pRootSignature = g.pRootSignature; break; case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS: stage(g.VS); break; case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS: stage(g.PS); break; case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DS: stage(g.DS); break; case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_HS: stage(g.HS); break; case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_GS: stage(g.GS); break; case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS: stage(out.as); break; case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS: stage(out.ms); break; case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CS: take(out.compute.CS); out.has_cs = true; break; case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_STREAM_OUTPUT: take(g.StreamOutput); break; case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND: take(g.BlendState); break; case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK: take(g.SampleMask); break; case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER: take(g.RasterizerState); break; case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL: take(g.DepthStencilState); break; case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT: take(g.InputLayout); break; case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_IB_STRIP_CUT_VALUE: take(g.IBStripCutValue); break; case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY: take(g.PrimitiveTopologyType); break; case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS: { D3D12_RT_FORMAT_ARRAY formats{}; take(formats); if (formats.NumRenderTargets > D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT) return E_INVALIDARG; g.NumRenderTargets = formats.NumRenderTargets; std::copy(std::begin(formats.RTFormats), std::end(formats.RTFormats), std::begin(g.RTVFormats)); break; } case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT: take(g.DSVFormat); break; case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC: take(g.SampleDesc); break; case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_NODE_MASK: take(g.NodeMask); out.compute.NodeMask = g.NodeMask; break; case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CACHED_PSO: take(g.CachedPSO); out.compute.CachedPSO = g.CachedPSO; break; case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_FLAGS: take(g.Flags); out.compute.Flags = g.Flags; break; case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1: { D3D12_DEPTH_STENCIL_DESC1 d{}; take(d); if (ok && d.DepthBoundsTestEnable) { return stream_unsupported("depth-bounds tests are not supported yet; stream subobject", int(type)); } g.DepthStencilState = {d.DepthEnable, d.DepthWriteMask, d.DepthFunc, d.StencilEnable, d.StencilReadMask, d.StencilWriteMask, d.FrontFace, d.BackFace}; break; } case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL2: { D3D12_DEPTH_STENCIL_DESC2 d{}; take(d); if (!ok) break; if (d.DepthBoundsTestEnable) { return stream_unsupported("depth-bounds tests are not supported yet; stream subobject", int(type)); } // Each face has its own read and write mask (OPTIONS14.IndependentFrontAndBackStencilRefMaskSupported): // the description takes the front face's, back_stencil the back face's. out.back_masks = true; out.back_stencil = {UINT8(d.BackFace.StencilReadMask), UINT8(d.BackFace.StencilWriteMask)}; const auto face = [](const D3D12_DEPTH_STENCILOP_DESC1& f) { return D3D12_DEPTH_STENCILOP_DESC{f.StencilFailOp, f.StencilDepthFailOp, f.StencilPassOp, f.StencilFunc}; }; g.DepthStencilState = {d.DepthEnable, d.DepthWriteMask, d.DepthFunc, d.StencilEnable, UINT8(d.FrontFace.StencilReadMask), UINT8(d.FrontFace.StencilWriteMask), face(d.FrontFace), face(d.BackFace)}; break; } case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER1: case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER2: { // Their DepthBias is a float; the PSO path takes D3D12_RASTERIZER_DESC's integer one. FLOAT bias = 0; D3D12_RASTERIZER_DESC& r = g.RasterizerState; if (type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER1) { D3D12_RASTERIZER_DESC1 d{}; take(d); r = {d.FillMode, d.CullMode, d.FrontCounterClockwise, 0, d.DepthBiasClamp, d.SlopeScaledDepthBias, d.DepthClipEnable, d.MultisampleEnable, d.AntialiasedLineEnable, d.ForcedSampleCount, d.ConservativeRaster}; bias = d.DepthBias; } else { D3D12_RASTERIZER_DESC2 d{}; take(d); r = {d.FillMode, d.CullMode, d.FrontCounterClockwise, 0, d.DepthBiasClamp, d.SlopeScaledDepthBias, d.DepthClipEnable, FALSE, FALSE, d.ForcedSampleCount, d.ConservativeRaster}; bias = d.DepthBias; } r.DepthBias = INT(bias); if (ok && FLOAT(r.DepthBias) != bias) log_once("a fractional depth bias is truncated; bias x1000", int(bias * 1000)); break; } case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VIEW_INSTANCING: { D3D12_VIEW_INSTANCING_DESC d{}; take(d); if (ok && d.ViewInstanceCount) { return stream_unsupported("view instancing is not supported yet; stream subobject", int(type)); } break; } default: log_once("unknown pipeline state stream subobject type:", int(type)); return E_INVALIDARG; } if (!ok) return E_INVALIDARG; } if (out.has_cs && out.has_graphics_stage) return E_INVALIDARG; // a compute stage with graphics stages if (!out.has_cs && !out.has_graphics_stage) return E_INVALIDARG; return S_OK; } // A pipeline state, compute (create_compute) or graphics (create_graphics): each shader is found by the SHA-256 of // its FSSM program in the translator's index, and the FSSM blob is copied into the arena as the shader's code base. std::atomic live_pipeline_state_count{0}; // live_pipeline_states() class PipelineState final : public Child { public: // {8d2f6c14-b0e7-4a93-9c58-1f4a7e3b6d20} static constexpr GUID kTag{0x8d2f6c14, 0xb0e7, 0x4a93, {0x9c, 0x58, 0x1f, 0x4a, 0x7e, 0x3b, 0x6d, 0x20}}; explicit PipelineState(DeviceState& device) : device_(device) { ++live_pipeline_state_count; } // Object::Release at zero references. Background builds hold no reference to the PSO: its queued ones are dropped // here. One already running (a vkCreate*Pipelines in the driver, minutes for some modules) is not waited for: the // PSO is deleted on the worker when that build returns, so the title's Release returns now. The device reference // goes now, so a device released with its last PSO is torn down here, and ~Device waits for the build and the // deletion (PipelineCompiler::cancel). Released on the worker inside its own build, both wait for its return. void last_release() { // The registry's build callback reaches this PSO by a raw pointer: unregistered first, so nothing queues a // build for it after the queued ones are dropped. unregister(); IUnknown* const device = detach_device(); auto& compiler = PipelineCompiler::instance(); const bool own_build = compiler.running_here(compile_owner()); IUnknown* const release_after = own_build ? device : nullptr; if (compiler.after_running(compile_owner(), [this, release_after] { delete this; if (release_after) release_after->Release(); })) { if (device && !own_build) device->Release(); return; } delete this; if (device) device->Release(); } ~PipelineState() override { unregister(); PipelineCompiler::instance().cancel(compile_owner()); // nothing left in practice (last_release) auto& vk = device_.context->vk; const VkDevice dev = device_.info.device; if (pipeline_.pipeline) vk.vkDestroyPipeline(dev, pipeline_.pipeline, nullptr); if (pipeline_.layout) vk.vkDestroyPipelineLayout(dev, pipeline_.layout, nullptr); if (module_) vk.vkDestroyShaderModule(dev, module_, nullptr); if (graphics_.pipeline) vk.vkDestroyPipeline(dev, graphics_.pipeline, nullptr); for (const auto& [unbound, built] : variants_) vk.vkDestroyPipeline(dev, built, nullptr); if (graphics_.layout) vk.vkDestroyPipelineLayout(dev, graphics_.layout, nullptr); modules_.clear(); if (code_bytes_) device_.arena_release(code_base_, code_bytes_, DeviceState::arena_shader); --live_pipeline_state_count; } // Pipeline layouts declare the whole 144-byte block as one push-constant range. A device whose // maxPushConstantsSize is smaller (128 bytes is the Vulkan minimum, which some Intel and mobile drivers // report) needs the uniform-buffer tail #224 flags with push_constants_need_fallback, which is not built yet, // so pipelines are refused there with the limit named instead of breaking VUID-VkPushConstantRange-size-00298. bool push_constants_fit() const { const std::uint32_t limit = device_.info.max_push_constants_size; if (limit == 0 || limit >= sizeof(leonida::ShaderUserData)) return true; // 0: not queried log_once("pipelines need 144 bytes of push constants (uniform-buffer fallback not built yet); " "maxPushConstantsSize", int(limit)); return false; } // Asks for the subgroup size the shader was translated for, where the device allows (src/subgroup_size.h): the // stage gets VkPipelineShaderStageRequiredSubgroupSizeCreateInfo in `storage` (which must outlive pipeline // creation) and, for compute, REQUIRE_FULL_SUBGROUPS. A size the device cannot give is reported, not hidden. void subgroup_size_for(const leonida::ShaderEntry& entry, VkPipelineShaderStageRequiredSubgroupSizeCreateInfo& storage, VkPipelineShaderStageCreateInfo& stage) { const leonida::SubgroupRequest request = leonida::decide_subgroup_size(entry, device_.info.subgroup); if (request.outcome == leonida::SubgroupOutcome::unavailable) report_subgroup_unavailable(entry, request, device_.info.subgroup); leonida::apply_subgroup_request(request, storage, stage); subgroup_requests_.push_back(request); } std::uintptr_t id() const { return native_owner_ ? native_owner_->id() : reinterpret_cast(static_cast(this)); } void share_native_graphics(std::shared_ptr owner) { native_owner_ = std::move(owner); } bool ensure_native_source(const D3D12_GRAPHICS_PIPELINE_STATE_DESC& pc, D3D12_SHADER_BYTECODE mesh, std::span containers) { std::call_once(native_source_once_,[&]{ if(rt::d3d12_xs::find_pso_record(this)){native_source_ready_=true;return;} rt::d3d12_xs::native_pipeline_detail::Stream source; rt::d3d12_xs::native_pipeline_detail::build_stream(pc,mesh,source); auto record=rt::d3d12_xs::PsoStreamRecord::capture(source.desc(),containers); native_source_ready_=record && rt::d3d12_xs::attach_pso_record(this,std::move(record)); }); return native_source_ready_; } // What its PipelineCompiler jobs are filed under: the interface pointer the title holds. const void* compile_owner() const { return static_cast(this); } // Out of the context's pipeline registry (and its build callback), once. void unregister() { if (!registered_ || unregistered_) return; device_.context->remove_pipeline(id()); unregistered_ = true; } void set_cache_key(leonida::cached_pso::Key key) { cache_key_ = std::move(key); } // A null pointer is accepted with S_OK, as by the PC runtime (measured on an RTX 3060 and WARP). HRESULT STDMETHODCALLTYPE GetCachedBlob(ID3DBlob** blob) override { if (native_owner_) return native_owner_->GetCachedBlob(blob); if (!blob) return S_OK; *blob = new CachedBlob(leonida::cached_pso::encode(device_.pso_identity, cache_key_)); return S_OK; } // Slots 9 and 10: console methods no caller is known to use; refused, and named once in the log. HRESULT STDMETHODCALLTYPE xbox_slot9(UINT64, UINT64, UINT64) override { log_once("console pipeline slot called (not implemented); slot", 9); return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE xbox_slot10(UINT64, UINT64, UINT64) override { log_once("console pipeline slot called (not implemented); slot", 10); return E_NOTIMPL; } // Slot 11, called by the FidelityFX DLL as (0, 0, &obj) after it creates a pipeline. It reads one dword through // obj's slot 3 (the shape of ID3DBlob::GetBufferPointer), multiplies it by 1024, releases obj through slot 2, and // creates and binds a compute scratch buffer before a dispatch only when that value is non-zero (measured in the // DLL's code, docs/d3d12_command_objects.md). The answer is a blob holding 0: none of the 1.0.2.1 DLL's 29 programs // enables scratch (COMPUTE_PGM_RSRC2.SCRATCH_EN clear in all 29) or has a scratch instruction (measured), and a // translated module keeps its private data in SPIR-V, not in a console scratch buffer. With 0 the DLL creates no // scratch buffer and skips list slot 141. The arguments are logged once when they are not the measured zeros. HRESULT STDMETHODCALLTYPE xbox_slot11(UINT64 a, UINT64 b, void** out) override { if (a || b) log_once("console pipeline slot 11 with unexpected arguments; first", int(a ? a : b)); if (!out) return E_POINTER; *out = static_cast(new CachedBlob(std::vector(4, 0))); return S_OK; } void set_pending_stream(bool compute) { pending_stream_kind_=compute?2:1; } bool resolve_type(bool graphics) { if(native_owner_)return native_owner_->resolve_type(graphics); if(pending_stream_kind_) { if(pending_stream_kind_!=(graphics?1u:2u))return false; std::call_once(resolve_stream_once_,[&]{ const auto* record=rt::d3d12_xs::find_pso_record(this); PipelineStream stream{}; HRESULT hr=record?parse_pipeline_stream(record->desc(),stream):E_INVALIDARG; if(SUCCEEDED(hr))hr=stream.has_cs?create_compute(stream.compute):create_graphics(stream.graphics,&stream.ms,&stream.as); }); } return registered_ && (is_graphics_==graphics); } bool compute() const { return pending_stream_kind_==2 || (registered_ && !is_graphics_); } bool graphics() const { return native_owner_ ? native_owner_->graphics() : pending_stream_kind_==1 || (registered_ && is_graphics_); } const std::vector& subgroup_requests() const { return native_owner_ ? native_owner_->subgroup_requests() : subgroup_requests_; } // A VS (+ GS) (+ PS) pipeline for dynamic rendering. Vertex input comes from the input layout matched to the // VS's input signature by semantic name and index: location = the element's register, the translator's rule // (docs/design.md, "Vertex fetch"). Refused with a log: hull and domain stages, stream output, the centre // multisample pattern, two stages that both read their code base, and state that needs a Vulkan feature the // device lacks (including the geometryShader feature a GS needs). A GS takes triangles; the sample count may // be above one. Viewport, scissor, topology, vertex strides, stencil reference and blend factor are dynamic, // set from the list's state at each draw. // With `ms` (a pipeline state stream's MS subobject) it is an MS (+ PS) pipeline on VK_EXT_mesh_shader instead: // no VS, no vertex input or input assembly (the input layout, topology type and strip cut are ignored, as D3D12 // does for mesh PSOs), drawn by DispatchMesh. A nonempty PC AS still needs a task-stage translation. // `back_masks`, from a DEPTH_STENCIL2 subobject, are the back face's stencil masks; without it both faces take // the description's. // LEONIDA_STUB_PIPELINES=1 (diagnostic): a pipeline whose translated shader is missing is created without a // Vulkan pipeline. It is never registered, so SetPipelineState leaves no PSO bound and its draws and dispatches // are recorded as no-ops (D3D-482). No game shader runs; the boot gets past a title that refuses to go on when // pipeline creation fails. static bool stub_pipelines() { wchar_t v[8] = {}; const DWORD n = GetEnvironmentVariableW(L"LEONIDA_STUB_PIPELINES", v, 8); return n > 0 && n < 8 && v[0] != L'0'; } HRESULT stub_or(HRESULT hr, const char* what) { if (!stub_pipelines()) return hr; static std::atomic stubbed{0}; const unsigned n = ++stubbed; if (n == 1 || (n & (n - 1)) == 0) std::fprintf(stderr, "[rt] d3d12: LEONIDA_STUB_PIPELINES: %s pipeline without a translated shader is a " "no-op stub (%u so far)\n", what, n); return S_OK; } // LOCAL DIAGNOSTIC: one line per distinct graphics pipeline that uses a program translated from // game_scarlett_master.exe (/exe), so the passes those inline containers serve can be read off a // boot. LEONIDA_LOG_EXE_PIPELINES=1. static void log_exe_pipeline(const leonida::ShaderEntry* vs, const leonida::ShaderEntry* ps, const D3D12_GRAPHICS_PIPELINE_STATE_DESC& desc) { const auto from_exe = [](const leonida::ShaderEntry* e) { return e && e->name.rfind("exe/", 0) == 0; }; if (!from_exe(vs) && !from_exe(ps)) return; char line[512]; std::snprintf(line, sizeof line, "[rt] d3d12: exe pipeline vs=%s ps=%s rts=%u rt0=%d rt1=%d dsv=%d topo=%d samples=%u", vs ? vs->fssm_sha256.c_str() : "-", ps ? ps->fssm_sha256.c_str() : "-", unsigned(desc.NumRenderTargets), int(desc.RTVFormats[0]), int(desc.RTVFormats[1]), int(desc.DSVFormat), int(desc.PrimitiveTopologyType), unsigned(desc.SampleDesc.Count)); static std::mutex mutex; static std::set seen; std::lock_guard lock(mutex); if (seen.insert(line).second) std::fprintf(stderr, "%s\n", line); } HRESULT create_graphics(const D3D12_GRAPHICS_PIPELINE_STATE_DESC& desc, const D3D12_SHADER_BYTECODE* ms = nullptr, const D3D12_SHADER_BYTECODE* as = nullptr, const StencilFaceMasks* back_masks = nullptr) { auto& vk = device_.context->vk; const VkDevice dev = device_.info.device; const bool mesh = ms && ms->pShaderBytecode && ms->BytecodeLength; if (as && as->pShaderBytecode && as->BytecodeLength) { return stream_unsupported("amplification shaders are not supported; stream subobject", D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS); } if (mesh && (desc.VS.BytecodeLength || desc.HS.BytecodeLength || desc.DS.BytecodeLength || desc.GS.BytecodeLength || desc.StreamOutput.NumEntries)) return E_INVALIDARG; // D3D12: a mesh PSO has no vertex, tessellation or geometry stage if (!mesh && (!desc.VS.pShaderBytecode || !desc.VS.BytecodeLength)) return E_INVALIDARG; if (mesh && (!device_.info.mesh_shader || !vk.vkCmdDrawMeshTasksEXT)) { return stream_unsupported("mesh-shader PSOs need VK_EXT_mesh_shader, which the device has not enabled; stage", 1); } if (desc.NodeMask & ~1u) return E_INVALIDARG; if (static_cast(desc.Flags) & ~kKnownPipelineStateFlags) return E_INVALIDARG; if (!device_.arena.mapped) { return stream_unsupported("pipelines need the GPU address arena (bufferDeviceAddress); stage", 1); } if (!push_constants_fit()) return stream_unsupported("graphics push-constant limit"); if (!vk.graphics_complete()) { return stream_unsupported("graphics pipelines need Vulkan 1.3 dynamic rendering and extended dynamic state; stage", 1); } if (desc.NumRenderTargets > D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT) return E_INVALIDARG; for (UINT i = desc.NumRenderTargets; i < D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT; ++i) if (desc.RTVFormats[i] != DXGI_FORMAT_UNKNOWN) return E_INVALIDARG; if (desc.DSVFormat != DXGI_FORMAT_UNKNOWN) { const Format dsv_fmt = vulkan_format(desc.DSVFormat, true); if (dsv_fmt.format == VK_FORMAT_UNDEFINED || dsv_fmt.typeless || !(dsv_fmt.aspects & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT))) { log_once("depth-stencil format not supported:", desc.DSVFormat); return E_INVALIDARG; } } if (desc.InputLayout.NumElements > D3D12_IA_VERTEX_INPUT_STRUCTURE_ELEMENT_COUNT) return E_INVALIDARG; if (desc.InputLayout.NumElements > 0 && !desc.InputLayout.pInputElementDescs) return E_INVALIDARG; for (UINT i = 0; i < desc.InputLayout.NumElements; ++i) { const D3D12_INPUT_ELEMENT_DESC& element = desc.InputLayout.pInputElementDescs[i]; if (!element.SemanticName) return E_INVALIDARG; if (element.InputSlot >= D3D12_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT) return E_INVALIDARG; if (element.InputSlotClass != D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA && element.InputSlotClass != D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA) return E_INVALIDARG; if (element.InputSlotClass == D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA && element.InstanceDataStepRate != 0) return E_INVALIDARG; } if (desc.BlendState.IndependentBlendEnable) { for (const D3D12_RENDER_TARGET_BLEND_DESC& rt : desc.BlendState.RenderTarget) if (rt.LogicOpEnable) return E_INVALIDARG; } else { const D3D12_RENDER_TARGET_BLEND_DESC& rt0 = desc.BlendState.RenderTarget[0]; if (rt0.BlendEnable && rt0.LogicOpEnable) return E_INVALIDARG; if (rt0.LogicOpEnable && unsigned(rt0.LogicOp) > D3D12_LOGIC_OP_OR_INVERTED) return E_INVALIDARG; } if (desc.HS.BytecodeLength || desc.DS.BytecodeLength || desc.StreamOutput.NumEntries) { return stream_unsupported("graphics pipeline stage not supported yet (hull/domain/stream output):", 0); } // A geometry shader is the translator's Vulkan geometry stage (docs/design.md, "Geometry shaders"): it takes // triangles and emits a triangle strip. It needs the geometryShader feature, and the PSO's topology type must // be its input primitive, as D3D12 requires. const bool geometry = desc.GS.pShaderBytecode && desc.GS.BytecodeLength; if (geometry && !device_.info.features.geometryShader) { return stream_unsupported("geometry shaders need the Vulkan geometryShader feature; stage", 0); } // The console's rectangle topology type (19) draws as triangles through a generated geometry stage that adds // each rectangle's fourth corner (src/rect_list_geometry.h); it needs the same device feature, and no GS of // the application's own. // Decode the ABI field as bits. The console's value is outside the PC enum's range. const auto topology_type = std::bit_cast(desc.PrimitiveTopologyType); const bool rect_list = !mesh && topology_type == leonida::topology_type_rect_list; if (rect_list && (geometry || !device_.info.features.geometryShader)) { log_once("a rectangle-list pipeline needs the geometryShader feature and no geometry shader; stage", 0); return geometry ? E_INVALIDARG : E_NOTIMPL; } if (geometry && topology_type != D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE) { log_once("a translated geometry shader takes triangles; topology type", topology_type); return E_INVALIDARG; } const UINT samples = desc.SampleDesc.Count; if (!samples || samples > D3D12_MAX_MULTISAMPLE_SAMPLE_COUNT || (samples & (samples - 1))) { log_once("invalid graphics pipeline sample count:", int(samples)); return E_INVALIDARG; } // D3D12 takes quality 0 and the two pattern values (measured natively on an RX 7800 XT, a Radeon iGPU and // WARP: 0, D3D12_STANDARD_MULTISAMPLE_PATTERN and D3D12_CENTER_MULTISAMPLE_PATTERN succeed, 1 is // E_INVALIDARG, as NumQualityLevels is 1). The standard pattern is Vulkan's standard sample positions, so it // is quality 0 here. The centre pattern puts every sample at the pixel centre, which needs custom sample // locations: refused with a log until those are set. if (desc.SampleDesc.Quality == DXGI_CENTER_MULTISAMPLE_QUALITY_PATTERN) { return stream_unsupported("D3D12_CENTER_MULTISAMPLE_PATTERN needs custom sample locations (not set yet); samples", int(samples)); } if (desc.SampleDesc.Quality != 0 && desc.SampleDesc.Quality != DXGI_STANDARD_MULTISAMPLE_QUALITY_PATTERN) { log_once("invalid graphics pipeline sample quality:", int(desc.SampleDesc.Quality)); return E_INVALIDARG; } const leonida::ShaderLibrary* library = device_.library(); if (!library) return stub_or(E_FAIL, "graphics"); struct Stage { const char* name; VkShaderStageFlagBits bit; const D3D12_SHADER_BYTECODE& code; const leonida::ShaderEntry* entry = nullptr; std::vector fssm; std::vector words; }; Stage stages[3] = {mesh ? Stage{"ms", VK_SHADER_STAGE_MESH_BIT_EXT, *ms} : Stage{"vs", VK_SHADER_STAGE_VERTEX_BIT, desc.VS}, {"gs", VK_SHADER_STAGE_GEOMETRY_BIT, desc.GS}, {"ps", VK_SHADER_STAGE_FRAGMENT_BIT, desc.PS}}; // stage_infos.size() indexes the recipe's per-stage required-size structs: one for every table entry. static_assert(std::size(stages) <= std::size(decltype(recipe_.required_sizes){}), "Recipe::required_sizes needs an entry per graphics stage"); unsigned packed_color_mask=0; for(unsigned i=0;i stage_infos; // Chained from stage_infos, which the recipe keeps for variants built at draw time: so they live in the recipe. auto& required_sizes = recipe_.required_sizes; const Stage* code_stage = nullptr; // D24_UNORM_S8_UINT stored as D32_SFLOAT_S8_UINT (no D24 on the GPU): the pixel stage writes the depth D24 // would hold, biased in D24 units and quantised (src/depth24_fragment.h, D3D-309), and the rasterizer's own // bias is turned off. Multisampled targets keep the old path: a FragDepth write is per pixel. const bool d24_as_float = desc.DSVFormat != DXGI_FORMAT_UNKNOWN && vulkan_format(desc.DSVFormat, true).format == VK_FORMAT_D24_UNORM_S8_UINT && !device_.depth_usable(VK_FORMAT_D24_UNORM_S8_UINT); const bool packed16_fallback=desc.DSVFormat==xbox_d16s8 && device_.depth_backing(VK_FORMAT_D16_UNORM_S8_UINT)!=VK_FORMAT_D16_UNORM_S8_UINT; if(packed16_fallback && samples>1 && desc.DepthStencilState.DepthEnable) return E_NOTIMPL; bool depth24_fragment = (d24_as_float || packed16_fallback) && desc.DepthStencilState.DepthEnable; if (depth24_fragment && samples > 1) { log_once("D24 depth stored as D32 keeps float depth bias and precision on multisampled targets; samples", int(samples)); depth24_fragment = false; } const leonida::Depth24Bias depth24_bias{desc.RasterizerState.DepthBias, desc.RasterizerState.SlopeScaledDepthBias, desc.RasterizerState.DepthBiasClamp,packed16_fallback?65535.0f:16777215.0f}; for (Stage& stage : stages) { if (!stage.code.pShaderBytecode || !stage.code.BytecodeLength) continue; // no PS: depth only const std::span raw_bytes{ static_cast(stage.code.pShaderBytecode), stage.code.BytecodeLength}; stage.fssm = leonida::fssm_program(raw_bytes); const bool vertex = stage.bit == VK_SHADER_STAGE_VERTEX_BIT; if (!stage.fssm.empty()) { const std::string hash = leonida::sha256_hex(stage.fssm); // Containers with the same program can differ in their input signature or bindings: a VS must have its // inputs fed by this input layout (else the layout check below reports it). stage.entry = pick_entry(library->candidates(stage.name, hash), [&](const leonida::ShaderEntry& e) { return !vertex || layout_feeds(e, desc.InputLayout); }); if (!stage.entry) { std::fprintf(stderr, "[rt] d3d12: no translated %s for FSSM sha256 %s\n", stage.name, hash.c_str()); if (d3d12_trace::enabled()) std::fprintf(stderr, "[rt] d3d12: missing %s in graphics PSO %s (RTs %u, RT0 %d, DSV %d)\n", stage.name, pipeline_key(desc).c_str(), desc.NumRenderTargets, int(desc.RTVFormats[0]), int(desc.DSVFormat)); return stub_or(E_INVALIDARG, "graphics"); } } else if (leonida::fspx_bare_program(raw_bytes)) { // Slot 57 (DeserializeGraphicsPipelineStateX): bare RDNA2 program indexed by fspx_code_sha256 in // /fspx_gfx/index.json. const std::string hash = leonida::sha256_hex(raw_bytes); stage.entry = pick_entry(library->fspx_candidates(stage.name, hash), [&](const leonida::ShaderEntry& e) { return !vertex || layout_feeds(e, desc.InputLayout); }); if (!stage.entry) stage.entry = pick_entry(library->fspx_candidates(stage.name, hash), [](const leonida::ShaderEntry&) { return true; }); if (!stage.entry) { std::fprintf(stderr, "[rt] d3d12: no translated %s for FSPX code sha256 %s (%zu B)\n", stage.name, hash.c_str(), raw_bytes.size()); return stub_or(E_INVALIDARG, "graphics"); } } else { log_once("shader bytecode holds no FSSM or FSPX program; bytes", int(stage.code.BytecodeLength)); return E_INVALIDARG; } if (stage.entry->binding_count) { if (!device_.bindless) { std::fprintf(stderr, "[rt] d3d12: %s uses set-0 bindings; the device has no bindless set 0\n", stage.entry->name.c_str()); return stream_unsupported("graphics shader requires a bindless descriptor set"); } uses_bindless = true; register_literal_samplers(device_, *stage.entry); } if (stage.bit == VK_SHADER_STAGE_MESH_BIT_EXT) { // The SPIR-V's output arrays are sized from PSV0 (the index's max_vertices / max_primitives); Vulkan // has no per-pipeline limit to set, so a mesh shader beyond the device's is refused here // (docs/d3d12_vulkan.md, "Pipelines"). if (const std::string refusal = leonida::mesh_limit_refusal(*stage.entry, device_.mesh_limits()); !refusal.empty()) { std::fprintf(stderr, "[rt] d3d12: %s\n", refusal.c_str()); return stream_unsupported("mesh shader exceeds a device mesh limit"); } // The graphics bind point lays root arguments out from push dword 8, which a mesh shader reads from // its s16 only when translated with the graphics root window (index "root_window", D3D-448). if (!stage.entry->graphics_root_window) { std::fprintf(stderr, "[rt] d3d12: mesh shader %s was translated before the graphics root window; translate " "the shaders again (make_game.py --stages shaders)\n", stage.entry->name.c_str()); return E_INVALIDARG; } } if (stage.entry->uses_code_base) { if (code_stage) { return stream_unsupported("two stages read their code base; one push-constant slot holds one (question 14)", 0); } code_stage = &stage; } stage.words = library->spirv(*stage.entry); if (stage.bit == VK_SHADER_STAGE_FRAGMENT_BIT) { std::string why; if (!rewrite_fragment(stage.words, why)) { if (why.rfind("has no second colour output", 0) == 0) return stream_unsupported("a SRC1 blend factor needs the pixel shader's second colour output; " "this module's outputs do not fit Location 0 Index 1; stage", 0); return E_INVALIDARG; } } if (stage.words.empty()) return E_FAIL; const auto inner = leonida::conservative_raster::inner_coverage_requirements(stage.words); if (!inner.valid) return E_INVALIDARG; if (inner.fully_covered && (stage.bit != VK_SHADER_STAGE_FRAGMENT_BIT || device_.conservative_raster_tier != D3D12_CONSERVATIVE_RASTERIZATION_TIER_3 || (inner.post_depth && !device_.conservative_post_depth_coverage))) { return stream_unsupported("FullyCoveredEXT needs an enabled Tier 3 shader ABI and device properties; stage", int(stage.bit)); } } if (std::getenv("LEONIDA_LOG_EXE_PIPELINES")) log_exe_pipeline(stages[0].entry, stages[2].entry, desc); // --f16-interp-fallback (SHADER-378): align/synthesize VS decoded f16 halves for this (VS, PS) pair before // creating the shader modules so colliding PS and high-param producers link within MoltenVK's 30 locations. // stages[] is {vs, gs, ps} since geometry shaders joined graphics PSOs (#2109): the PS is stages[2], and with a // GS the PS reads the GS's outputs, not the VS's, so the VS/PS halves link only applies without one. Stage& vs_stage = stages[0]; Stage& gs_stage = stages[1]; Stage& ps_stage = stages[2]; if (vs_stage.entry && ps_stage.entry && !ps_stage.entry->f16_halves.empty() && gs_stage.entry) { log_once("--f16-interp-fallback halves are linked VS->PS only; this PSO has a geometry shader", 0); } if (vs_stage.entry && ps_stage.entry && !gs_stage.entry && (!ps_stage.entry->f16_halves.empty() || !vs_stage.entry->f16_halves.empty())) { std::string link_error; if (!leonida::link_f16_halves(vs_stage.words, *vs_stage.entry, ps_stage.words, *ps_stage.entry, &link_error, device_.f16_half_top_location)) { std::fprintf(stderr, "[rt] d3d12: %s\n", link_error.c_str()); return E_FAIL; } f16_linked_ = true; } // A lazy pipeline keeps where each stage's words come from, not the words or a module: build() makes them // again, the same way, and drops them once the pipeline exists. lazy_ = lazy_graphics_pipelines(); depth24_bias_ = depth24_bias; rgba4_mask_ = packed_color_mask; // A stage that declares a storage image or buffer it may write needs a device feature outside compute // (src/spirv_stores.h). Without it the pipeline would be created all the same and break // VUID-RuntimeSpirv-NonWritable-06340 / -06341, so the PSO is refused here with the stage named. for (const Stage& stage : stages) { if (!stage.entry) continue; const bool pixel = stage.bit == VK_SHADER_STAGE_FRAGMENT_BIT; const VkBool32 allowed = pixel ? device_.info.features.fragmentStoresAndAtomics : device_.info.features.vertexPipelineStoresAndAtomics; if (allowed || !leonida::spirv_declares_writable_storage(stage.words)) continue; std::fprintf(stderr, "[rt] d3d12: %s (%s) writes a storage image or buffer, which needs the Vulkan feature %s; " "the device does not have it enabled, so the pipeline is refused\n", stage.entry->name.c_str(), stage.name, pixel ? "fragmentStoresAndAtomics" : "vertexPipelineStoresAndAtomics"); return stream_unsupported("graphics shader requires an unavailable storesAndAtomics feature"); } const auto topology_bits = std::bit_cast(desc.PrimitiveTopologyType); if (!mesh && topology_bits != leonida::topology_type_rect_list) graphics_.rectangle_variant_topology = leonida::topology_rect_list; std::uint64_t spirv_bytes = 0; for (Stage& stage : stages) { if (!stage.entry) continue; // After the f16 link above, which can also edit the pixel shader's words. if (depth24_fragment && stage.bit == VK_SHADER_STAGE_FRAGMENT_BIT) { std::string why; std::vector patched = leonida::depth24_patch_fragment(stage.words, depth24_bias, why); if (patched.empty()) { std::fprintf(stderr, "[rt] d3d12: %s keeps float depth on a D24 target stored as D32: %s\n", stage.entry->name.c_str(), why.c_str()); depth24_fragment = false; } else { stage.words = std::move(patched); } } spirv_bytes += stage.words.size() * sizeof(std::uint32_t); if (trace_pipeline_compile()) { if (!profile_shaders_.empty()) profile_shaders_ += ','; profile_shaders_ += stage.entry->name; stage_bytes_ += stage.words.size() * sizeof(std::uint32_t); } VkShaderModule module = VK_NULL_HANDLE; if (lazy_) { const bool patched = depth24_fragment && stage.bit == VK_SHADER_STAGE_FRAGMENT_BIT; sources_.push_back({StageSource::library, std::uint8_t(&stage - stages), patched, stage.entry}); } else { module = shader_module(stage.words); if (!module) return E_FAIL; } if (stage.bit == VK_SHADER_STAGE_VERTEX_BIT && !geometry && device_.info.features.geometryShader && topology_type == D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE) { rectangle_capable_ = true; if (!lazy_) rectangle_vertex_ = modules_.back(); } VkPipelineShaderStageCreateInfo info{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; info.stage = stage.bit; info.module = module; info.pName = "main"; subgroup_size_for(*stage.entry, required_sizes[stage_infos.size()], info); stage_infos.push_back(info); } if (rect_list) { // the stage that adds each rectangle's fourth corner, from the vertex shader's outputs std::string why; const std::vector words = leonida::rect_list_geometry(vs_stage.words, why); if (words.empty()) { std::fprintf(stderr, "[rt] d3d12: %s cannot be drawn as a rectangle list: %s\n", vs_stage.entry->name.c_str(), why.c_str()); return stream_unsupported("rectangle-list geometry shader generation failed"); } if (trace_pipeline_compile()) stage_bytes_ += words.size() * sizeof(std::uint32_t); VkShaderModule module = VK_NULL_HANDLE; if (lazy_) { sources_.push_back({StageSource::rect_list}); } else { module = shader_module(words); if (!module) return E_FAIL; } VkPipelineShaderStageCreateInfo info{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; info.stage = VK_SHADER_STAGE_GEOMETRY_BIT; info.module = module; info.pName = "main"; stage_infos.push_back(info); } if (depth24_fragment && !ps_stage.entry) { // no pixel shader: a built-in one writes the depth const std::vector words = leonida::depth24_depth_only_fragment(depth24_bias); if (words.empty()) return E_FAIL; if (trace_pipeline_compile()) stage_bytes_ += words.size() * sizeof(std::uint32_t); VkShaderModule module = VK_NULL_HANDLE; if (lazy_) { sources_.push_back({StageSource::depth_only}); } else { module = shader_module(words); if (!module) return E_FAIL; } VkPipelineShaderStageCreateInfo info{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; info.stage = VK_SHADER_STAGE_FRAGMENT_BIT; info.module = module; info.pName = "main"; stage_infos.push_back(info); } // Input layout -> vertex input, by semantic. A mesh pipeline has none. std::vector attributes; std::vector bindings; std::vector divisors; std::uint32_t divisor_slots = 0; UINT slot_end[D3D12_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT] = {}; for (UINT i = 0; !mesh && i < desc.InputLayout.NumElements; ++i) { const D3D12_INPUT_ELEMENT_DESC& element = desc.InputLayout.pInputElementDescs[i]; if (element.InputSlot >= D3D12_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT) return E_INVALIDARG; VkFormat format; UINT bytes; if (!vertex_format(element.Format, format, bytes)) { log_once("vertex attribute format not supported yet:", element.Format); return E_INVALIDARG; } const UINT alignment = std::min(bytes, 4u); const UINT offset = element.AlignedByteOffset == D3D12_APPEND_ALIGNED_ELEMENT ? (slot_end[element.InputSlot] + alignment - 1) / alignment * alignment : element.AlignedByteOffset; slot_end[element.InputSlot] = offset + bytes; const leonida::SignatureElement* input = nullptr; for (const auto& e : stages[0].entry->input_signature) if (e.system_value == 0 && e.semantic_index == element.SemanticIndex && equal_semantic(e.semantic, element.SemanticName)) input = &e; if (!input) continue; // the shader does not read this element attributes.push_back({input->register_index, element.InputSlot, format, offset}); const bool instance = element.InputSlotClass == D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA; // Step rate 0: every instance reads element 0, which a stride of 0 gives (set at each draw). if (instance && element.InstanceDataStepRate == 0) graphics_.zero_step_slots |= 1u << element.InputSlot; if (instance && element.InstanceDataStepRate > 1) { if (!device_.info.vertex_attribute_divisor) { return stream_unsupported("instance step rates above 1 need vertexAttributeInstanceRateDivisor; rate", int(element.InstanceDataStepRate)); } if (!(divisor_slots & (1u << element.InputSlot))) { divisor_slots |= 1u << element.InputSlot; divisors.push_back({element.InputSlot, element.InstanceDataStepRate}); graphics_.nonunit_vertex_divisor = true; } } if (!(graphics_.vertex_slots & (1u << element.InputSlot))) { graphics_.vertex_slots |= 1u << element.InputSlot; bindings.push_back({element.InputSlot, 0, // stride: dynamic, from IASetVertexBuffers instance ? VK_VERTEX_INPUT_RATE_INSTANCE : VK_VERTEX_INPUT_RATE_VERTEX}); } } for (const auto& e : stages[0].entry->input_signature) { if (e.system_value) continue; const bool fed = std::any_of(attributes.begin(), attributes.end(), [&](const auto& a) { return a.location == e.register_index; }); if (!fed) { // D3D12 rejects an input layout that leaves a shader input unfed std::fprintf(stderr, "[rt] d3d12: the input layout does not feed %s%u (register %u)\n", e.semantic.c_str(), e.semantic_index, e.register_index); return E_INVALIDARG; } } VkPipelineInputAssemblyStateCreateInfo assembly{VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO}; // Type 19 is the console's rectangles, drawn as triangle lists through the geometry stage added above. switch (mesh || rect_list ? D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE : topology_type) { // mesh: not used case D3D12_PRIMITIVE_TOPOLOGY_TYPE_POINT: assembly.topology = VK_PRIMITIVE_TOPOLOGY_POINT_LIST; break; case D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE: assembly.topology = VK_PRIMITIVE_TOPOLOGY_LINE_LIST; break; case D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE: assembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; break; default: log_once("primitive topology type not supported:", topology_type); return E_INVALIDARG; } if (!mesh) { // a mesh PSO has no index buffer: its strip cut is ignored if (desc.IBStripCutValue != D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED && desc.IBStripCutValue != D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_0xFFFF && desc.IBStripCutValue != D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_0xFFFFFFFF) { log_once("index-buffer strip cut value not supported:", desc.IBStripCutValue); return E_INVALIDARG; } graphics_.strip_cut = desc.IBStripCutValue; } const D3D12_RASTERIZER_DESC& r = desc.RasterizerState; if (r.ConservativeRaster != D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF && r.ConservativeRaster != D3D12_CONSERVATIVE_RASTERIZATION_MODE_ON) return E_INVALIDARG; if (r.ConservativeRaster == D3D12_CONSERVATIVE_RASTERIZATION_MODE_ON) { if (device_.conservative_raster_tier == D3D12_CONSERVATIVE_RASTERIZATION_TIER_NOT_SUPPORTED) { log_once("conservative rasterization needs enabled VK_EXT_conservative_rasterization and Tier 1 precision", 1); return E_INVALIDARG; } if (r.FillMode != D3D12_FILL_MODE_SOLID || topology_type != D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE) return E_INVALIDARG; // Target-independent rasterization is a separate pipeline path; do not silently ignore its count. if (r.ForcedSampleCount) return stream_unsupported("target-independent rasterization; forced sample count", int(r.ForcedSampleCount)); } VkPipelineRasterizationStateCreateInfo raster{VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO}; raster.polygonMode = r.FillMode == D3D12_FILL_MODE_WIREFRAME ? VK_POLYGON_MODE_LINE : VK_POLYGON_MODE_FILL; raster.cullMode = r.CullMode == D3D12_CULL_MODE_FRONT ? VK_CULL_MODE_FRONT_BIT : r.CullMode == D3D12_CULL_MODE_BACK ? VK_CULL_MODE_BACK_BIT : VK_CULL_MODE_NONE; // With the negative-height viewport, framebuffer winding matches D3D12's screen-space winding. raster.frontFace = r.FrontCounterClockwise ? VK_FRONT_FACE_COUNTER_CLOCKWISE : VK_FRONT_FACE_CLOCKWISE; // The D24-as-D32 pixel stage applies the bias itself, in D24 units (depth24_fragment above): the // rasterizer's bias stays off and zero, so its clamp needs no depthBiasClamp feature either. raster.depthBiasEnable = !depth24_fragment && (r.DepthBias || r.SlopeScaledDepthBias != 0.0f); if (raster.depthBiasEnable) { raster.depthBiasConstantFactor = float(r.DepthBias); raster.depthBiasClamp = r.DepthBiasClamp; raster.depthBiasSlopeFactor = r.SlopeScaledDepthBias; } raster.lineWidth = 1.0f; // No depth clipping: fragments outside the viewport's depth range are kept and their depth clamped to it, as // D3D12 clamps output depth to MinDepth..MaxDepth anyway (needs depthClamp, checked below). raster.depthClampEnable = r.DepthClipEnable ? VK_FALSE : VK_TRUE; VkPipelineMultisampleStateCreateInfo multisample{VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO}; multisample.rasterizationSamples = VkSampleCountFlagBits(samples); const VkSampleMask sample_mask = desc.SampleMask; multisample.pSampleMask = &sample_mask; multisample.alphaToCoverageEnable = desc.BlendState.AlphaToCoverageEnable; const D3D12_DEPTH_STENCIL_DESC& ds = desc.DepthStencilState; VkPipelineDepthStencilStateCreateInfo depth{VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO}; depth.depthTestEnable = ds.DepthEnable; depth.depthWriteEnable = ds.DepthEnable && ds.DepthWriteMask == D3D12_DEPTH_WRITE_MASK_ALL; depth.depthCompareOp = compare_op(ds.DepthFunc); depth.stencilTestEnable = ds.StencilEnable; depth.front = stencil_face(ds.FrontFace, ds.StencilReadMask, ds.StencilWriteMask); depth.back = back_masks ? stencil_face(ds.BackFace, back_masks->read, back_masks->write) : stencil_face(ds.BackFace, ds.StencilReadMask, ds.StencilWriteMask); std::vector blends(desc.NumRenderTargets); for (UINT i = 0; i < desc.NumRenderTargets; ++i) { const D3D12_RENDER_TARGET_BLEND_DESC& b = desc.BlendState.RenderTarget[desc.BlendState.IndependentBlendEnable ? i : 0]; blends[i].blendEnable = b.BlendEnable; blends[i].srcColorBlendFactor = blend_factor(b.SrcBlend); blends[i].dstColorBlendFactor = blend_factor(b.DestBlend); blends[i].colorBlendOp = blend_op(b.BlendOp); blends[i].srcAlphaBlendFactor = blend_factor(b.SrcBlendAlpha); blends[i].dstAlphaBlendFactor = blend_factor(b.DestBlendAlpha); blends[i].alphaBlendOp = blend_op(b.BlendOpAlpha); blends[i].colorWriteMask = b.RenderTargetWriteMask & 0xf; // R, G, B, A in both APIs // B8G8R8X8 has no alpha, so blending reads destination alpha as 1 there (WARP and AMD's D3D12 driver), // where its BGRA8 Vulkan image would read the X byte. For colour SRC_ALPHA_SAT is min(As, 1 - Ad), so 0; // for alpha it is 1 in both APIs already. if (alpha_unused(desc.RTVFormats[i])) { const auto dest_alpha_one = [](VkBlendFactor& factor, bool colour) { if (factor == VK_BLEND_FACTOR_DST_ALPHA) factor = VK_BLEND_FACTOR_ONE; else if (factor == VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA) factor = VK_BLEND_FACTOR_ZERO; else if (colour && factor == VK_BLEND_FACTOR_SRC_ALPHA_SATURATE) factor = VK_BLEND_FACTOR_ZERO; }; dest_alpha_one(blends[i].srcColorBlendFactor, true); dest_alpha_one(blends[i].dstColorBlendFactor, true); dest_alpha_one(blends[i].srcAlphaBlendFactor, false); dest_alpha_one(blends[i].dstAlphaBlendFactor, false); } } VkPipelineColorBlendStateCreateInfo blend{VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO}; blend.attachmentCount = std::uint32_t(blends.size()); blend.pAttachments = blends.data(); // A logic op replaces blending for every target in Vulkan (one per pipeline), and D3D12 takes it from // RenderTarget[0]. Vulkan applies it to integer and normalized formats and skips float ones. const D3D12_RENDER_TARGET_BLEND_DESC& first = desc.BlendState.RenderTarget[0]; if (desc.NumRenderTargets && first.LogicOpEnable) { if (unsigned(first.LogicOp) > D3D12_LOGIC_OP_OR_INVERTED) return E_INVALIDARG; blend.logicOpEnable = VK_TRUE; blend.logicOp = logic_op(first.LogicOp); } // State that needs a Vulkan feature the device did not enable (VulkanDeviceInfo::features) is refused, rather // than handed to the driver against the spec. const VkPhysicalDeviceFeatures& features = device_.info.features; if (raster.polygonMode != VK_POLYGON_MODE_FILL && !features.fillModeNonSolid) return stream_unsupported("wireframe fill needs fillModeNonSolid, which the device lacks; fill mode", r.FillMode); if (raster.depthBiasEnable && raster.depthBiasClamp != 0.0f && !features.depthBiasClamp) return stream_unsupported("a depth-bias clamp needs depthBiasClamp, which the device lacks; clamp x1000", int(raster.depthBiasClamp * 1000)); for (std::size_t i = 1; i < blends.size(); ++i) if (std::memcmp(&blends[i], &blends[0], sizeof(blends[0])) != 0 && !features.independentBlend) return stream_unsupported("per-render-target blend state needs independentBlend, which the device lacks; target", int(i)); const auto src1 = [](VkBlendFactor f) { return f == VK_BLEND_FACTOR_SRC1_COLOR || f == VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR || f == VK_BLEND_FACTOR_SRC1_ALPHA || f == VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA; }; for (const auto& b : blends) if (b.blendEnable && !features.dualSrcBlend && (src1(b.srcColorBlendFactor) || src1(b.dstColorBlendFactor) || src1(b.srcAlphaBlendFactor) || src1(b.dstAlphaBlendFactor))) return stream_unsupported("SRC1 blend factors need dualSrcBlend, which the device lacks; factor", int(b.srcColorBlendFactor)); if (blend.logicOpEnable && !features.logicOp) return stream_unsupported("logic ops need logicOp, which the device lacks; op", int(first.LogicOp)); if (raster.depthClampEnable && !features.depthClamp) return stream_unsupported("DepthClipEnable = FALSE needs depthClamp, which the device lacks; flag", 0); graphics_.viewport_with_count = features.multiViewport && vk.vkCmdSetViewportWithCount && vk.vkCmdSetScissorWithCount; graphics_.color_formats.assign(desc.NumRenderTargets, VK_FORMAT_UNDEFINED); for (UINT i = 0; i < desc.NumRenderTargets; ++i) { if (desc.RTVFormats[i] == DXGI_FORMAT_UNKNOWN) continue; graphics_.color_formats[i] = desc.RTVFormats[i] == DXGI_FORMAT_A8_UNORM && device_.info.a8_render_target ? kA8UnormFormat : desc.RTVFormats[i] == DXGI_FORMAT_R9G9B9E5_SHAREDEXP && device_.r9g9b9e5_target_stand_in ? VK_FORMAT_B10G11R11_UFLOAT_PACK32 // what such a target is made of : vulkan_format(desc.RTVFormats[i], false).format; // B4G4R4A4 targets are RGBA8 images where no 4444 format renders (DeviceState's texture format choice). if (graphics_.color_formats[i] == VK_FORMAT_A4R4G4B4_UNORM_PACK16 && !device_.color_attachment_usable(VK_FORMAT_A4R4G4B4_UNORM_PACK16)) graphics_.color_formats[i] = VK_FORMAT_R8G8B8A8_UNORM; if (graphics_.color_formats[i] == VK_FORMAT_UNDEFINED) { log_once("render-target format not supported yet:", desc.RTVFormats[i]); return E_INVALIDARG; } } if (desc.DSVFormat != DXGI_FORMAT_UNKNOWN) { Format f = vulkan_format(desc.DSVFormat, true); if (f.format == VK_FORMAT_D24_UNORM_S8_UINT && !device_.depth_usable(f.format)) f.format = VK_FORMAT_D32_SFLOAT_S8_UINT; // as CreateCommittedResource does graphics_.depth_format = device_.depth_backing(f.format); graphics_.depth_aspects = f.aspects; } if (samples > 1) { const auto& dinfo = device_.info; const bool has_color = std::any_of(graphics_.color_formats.begin(), graphics_.color_formats.end(), [](VkFormat f) { return f != VK_FORMAT_UNDEFINED; }); const bool has_depth = graphics_.depth_format != VK_FORMAT_UNDEFINED; if (const auto get_props = reinterpret_cast( dinfo.get_instance_proc ? dinfo.get_instance_proc(dinfo.instance, "vkGetPhysicalDeviceProperties") : nullptr)) { VkPhysicalDeviceProperties props{}; get_props(dinfo.physical, &props); VkSampleCountFlags supported = ~VkSampleCountFlags(0); if (has_color) supported &= props.limits.framebufferColorSampleCounts; if (has_depth && (graphics_.depth_aspects & VK_IMAGE_ASPECT_DEPTH_BIT)) supported &= props.limits.framebufferDepthSampleCounts; if (has_depth && (graphics_.depth_aspects & VK_IMAGE_ASPECT_STENCIL_BIT)) supported &= props.limits.framebufferStencilSampleCounts; if (!has_color && !has_depth) supported &= props.limits.framebufferNoAttachmentsSampleCounts; if (!(supported & samples)) { log_once("multisample count not supported by framebuffer limits; samples", int(samples)); return E_INVALIDARG; } } if ((has_color || has_depth) && !device_.image_format_properties) { log_once("cannot query per-format multisample support; samples", int(samples)); return E_INVALIDARG; } for (const VkFormat fmt : graphics_.color_formats) { if (fmt == VK_FORMAT_UNDEFINED) continue; VkImageFormatProperties img_props{}; if (device_.image_format_properties(dinfo.physical, fmt, VK_IMAGE_TYPE_2D, VK_IMAGE_TILING_OPTIMAL, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, 0, &img_props) != VK_SUCCESS || !(img_props.sampleCounts & samples)) { log_once("multisample count not supported by color attachment format; samples", int(samples)); return E_INVALIDARG; } } if (has_depth) { VkImageFormatProperties img_props{}; if (device_.image_format_properties(dinfo.physical, graphics_.depth_format, VK_IMAGE_TYPE_2D, VK_IMAGE_TILING_OPTIMAL, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, 0, &img_props) != VK_SUCCESS || !(img_props.sampleCounts & samples)) { log_once("multisample count not supported by depth/stencil attachment format; samples", int(samples)); return E_INVALIDARG; } } } // Every stage this path accepts reads the user SGPRs, so the range covers the whole stage table, not only the // stages present. A stage added to the table (geometry, mesh) is covered without touching this. // (The geometry bit only where the device has the stage: a range may not name a stage it cannot run.) for (const Stage& stage : stages) if (stage.bit != VK_SHADER_STAGE_GEOMETRY_BIT || device_.info.features.geometryShader) graphics_.push_stages |= stage.bit; const VkPushConstantRange push{graphics_.push_stages, 0, sizeof(leonida::ShaderUserData)}; VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; layout_info.pushConstantRangeCount = 1; layout_info.pPushConstantRanges = &push; VkDescriptorSetLayout set0_layout = VK_NULL_HANDLE; if (uses_bindless) { set0_layout = device_.bindless->layout(); layout_info.setLayoutCount = 1; layout_info.pSetLayouts = &set0_layout; graphics_.bindless_set = device_.bindless->set(); } if (vk.vkCreatePipelineLayout(dev, &layout_info, nullptr, &graphics_.layout) != VK_SUCCESS) return E_FAIL; // Kept for variants: a draw that leaves a slot unbound needs this pipeline with that format undefined. graphics_.mesh = mesh; recipe_.mesh = mesh; recipe_.stages = std::move(stage_infos); recipe_.attributes = std::move(attributes); recipe_.bindings = std::move(bindings); recipe_.divisors = std::move(divisors); recipe_.assembly = assembly; recipe_.raster = raster; recipe_.conservative = r.ConservativeRaster == D3D12_CONSERVATIVE_RASTERIZATION_MODE_ON; recipe_.multisample = multisample; graphics_.samples = samples; recipe_.sample_mask = sample_mask; recipe_.depth = depth; recipe_.blends = std::move(blends); recipe_.blend = blend; if (!lazy_) { VkResult compile_status = VK_SUCCESS; const bool cache_only = device_.info.cold_graphics_compile; graphics_.pipeline = build(0, "graphics-create", cache_only ? VK_PIPELINE_CREATE_FAIL_ON_PIPELINE_COMPILE_REQUIRED_BIT : 0, &compile_status); // A cache-only create that the driver would have to compile stays null: the first draw builds it. if (!graphics_.pipeline && !(cache_only && compile_status == VK_PIPELINE_COMPILE_REQUIRED)) return E_FAIL; } // lazy: graphics_.pipeline stays null and the first draw builds it as variant 0 graphics_.async_build = async_replay_compile(); graphics_.variant = [this](std::uint32_t unbound) { return replay_pipeline("draw", [&] { return graphics_.async_build ? queue_build(false, unbound) : variant(unbound, "draw"); }); }; graphics_.built = [this](std::uint32_t unbound) { std::unique_lock lock(variants_mutex_, std::try_to_lock); // held: another thread is compiling one if (!lock.owns_lock()) return VkPipeline(VK_NULL_HANDLE); const auto it = variants_.find(unbound); return it == variants_.end() ? VkPipeline(VK_NULL_HANDLE) : it->second; }; graphics_.large = spirv_bytes >= leonida::PipelineCompiles::large_spirv_bytes && big_compiles() != BigCompiles::unlimited; graphics_.estimate = leonida::large_module_estimate(spirv_bytes); if (code_stage) { VkDeviceSize offset = 0; if (!device_.arena_allocate(code_stage->fssm.size(), 256, offset, DeviceState::arena_shader)) return E_OUTOFMEMORY; std::memcpy(device_.arena.mapped + offset, code_stage->fssm.data(), code_stage->fssm.size()); code_bytes_ = code_stage->fssm.size(); code_base_ = offset; graphics_.code_base = offset; } // LOCAL DIAGNOSTIC: what this pipeline is, for the fsdraw probe's draw lines if (leonida::local_diagnostics()) { const auto& rt0 = desc.BlendState.RenderTarget[0]; char text[640]; std::snprintf(text, sizeof text, "vs %s (fssm %.16s) ps %s (fssm %.16s) rootsig %p rts %u fmt0 %d fmt1 %d dsv %d depth %d " "blend0 en %d src %d dst %d op %d srcA %d dstA %d opA %d logic %d wm 0x%x alpha2cov %d " "independent %d sample_mask 0x%x cull %d fill %d topo %d samples %u", stages[0].entry ? stages[0].entry->name.c_str() : "-", stages[0].entry ? stages[0].entry->fssm_sha256.c_str() : "-", stages[2].entry ? stages[2].entry->name.c_str() : "-", stages[2].entry ? stages[2].entry->fssm_sha256.c_str() : "-", static_cast(desc.pRootSignature), desc.NumRenderTargets, int(desc.RTVFormats[0]), int(desc.RTVFormats[1]), int(desc.DSVFormat), int(desc.DepthStencilState.DepthEnable), int(rt0.BlendEnable), int(rt0.SrcBlend), int(rt0.DestBlend), int(rt0.BlendOp), int(rt0.SrcBlendAlpha), int(rt0.DestBlendAlpha), int(rt0.BlendOpAlpha), int(rt0.LogicOpEnable), unsigned(rt0.RenderTargetWriteMask), int(desc.BlendState.AlphaToCoverageEnable), int(desc.BlendState.IndependentBlendEnable), unsigned(desc.SampleMask), int(desc.RasterizerState.CullMode), int(desc.RasterizerState.FillMode), int(desc.PrimitiveTopologyType), desc.SampleDesc.Count); leonida::fsdraw::note_pipeline(id(), text); } if (device_.info.device_checkpoints) { leonida::CheckpointShaders shaders{}; for (std::size_t i = 0; i < std::size(stages); ++i) if (stages[i].entry) shaders[i] = stages[i].entry->name.c_str(); device_.context->add_graphics_pipeline(id(), graphics_, &shaders); } else { device_.context->add_graphics_pipeline(id(), graphics_); } registered_ = true; is_graphics_ = true; return S_OK; } HRESULT create_compute(const D3D12_COMPUTE_PIPELINE_STATE_DESC& desc) { auto& vk = device_.context->vk; const VkDevice dev = device_.info.device; if (!desc.CS.pShaderBytecode || !desc.CS.BytecodeLength) return E_INVALIDARG; if (desc.NodeMask & ~1u) return E_INVALIDARG; if (static_cast(desc.Flags) & ~kKnownPipelineStateFlags) return E_INVALIDARG; if (!device_.arena.mapped) { return stream_unsupported("pipelines need the GPU address arena (bufferDeviceAddress); stage", 0); } if (!push_constants_fit()) return stream_unsupported("compute push-constant limit"); // The game's FSSM program, or the FidelityFX DLL's FSPX kind-6 program: in a DXBC container's ACCC part at // slot 62, bare from a slot-67 description (docs/fspx.md, "Run-time lookup"). const leonida::ComputeProgram program = leonida::compute_program( {static_cast(desc.CS.pShaderBytecode), desc.CS.BytecodeLength}); if (program.kind == leonida::ComputeProgram::Kind::none) { log_once("compute shader bytecode holds no FSSM or FSPX program; bytes", int(desc.CS.BytecodeLength)); return E_INVALIDARG; } const leonida::ShaderLibrary* library = device_.library(); if (!library) return stub_or(E_FAIL, "compute"); // A binding-free entry wins over one with bindings for the same program (pick_entry). // An FSPX program from a container is matched on its kind-0 state too; a bare kind-6 program whose // translations differ is ambiguous without that state and is refused (program_candidates). bool ambiguous = false; const leonida::ShaderEntry* entry = pick_entry(library->program_candidates("cs", program, &ambiguous), [](const leonida::ShaderEntry&) { return true; }); if (!entry) { const bool fspx = program.kind == leonida::ComputeProgram::Kind::fspx; if (ambiguous) { // Ambiguous is not missing: translations exist, so it is refused even with LEONIDA_STUB_PIPELINES. std::fprintf(stderr, "[rt] d3d12: FSPX kind-6 program sha256 %s is ambiguous without its kind-0 " "state: its translations differ\n", leonida::sha256_hex(program.bytes).c_str()); return E_INVALIDARG; } std::fprintf(stderr, "[rt] d3d12: no translated compute shader for %s sha256 %s\n", fspx ? (program.state.empty() ? "FSPX kind-6" : "FSPX kind-6 and kind-0") : "FSSM", leonida::sha256_hex(program.bytes).c_str()); return stub_or(E_INVALIDARG, "compute"); } // Set 0 (bindless images, samplers, the descriptor hash table): the device keeps it, and a pipeline whose // shader declares bindings has it in its layout and has it bound at every dispatch. if (entry->binding_count && !device_.bindless) { std::fprintf(stderr, "[rt] d3d12: %s uses set-0 bindings; the device has no bindless set 0\n", entry->name.c_str()); return stream_unsupported("compute shader requires a bindless descriptor set"); } if (entry->binding_count) register_literal_samplers(device_, *entry); // SHADER-309: a module over the device's maxComputeSharedMemorySize is invalid usage that spirv-val accepts // and RADV dies on (#1721); some drivers report 32768. Refuse it here instead of creating the pipeline. if (entry->lds_bytes) { const auto& dinfo = device_.info; if (const auto get_props = reinterpret_cast( dinfo.get_instance_proc ? dinfo.get_instance_proc(dinfo.instance, "vkGetPhysicalDeviceProperties") : nullptr)) { VkPhysicalDeviceProperties props{}; get_props(dinfo.physical, &props); if (entry->lds_bytes > props.limits.maxComputeSharedMemorySize) { std::fprintf(stderr, "[rt] d3d12: %s declares %u bytes of workgroup memory, over the device's " "maxComputeSharedMemorySize %u\n", entry->name.c_str(), unsigned(entry->lds_bytes), unsigned(props.limits.maxComputeSharedMemorySize)); return stream_unsupported("compute shader exceeds shared memory limit"); } } } const std::size_t spirv_bytes = library->spirv_bytes(*entry); if (!spirv_bytes) { std::fprintf(stderr, "[rt] d3d12: %s.spv is missing\n", entry->name.c_str()); return E_FAIL; } const VkPushConstantRange push{VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(leonida::ShaderUserData)}; VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; layout_info.pushConstantRangeCount = 1; layout_info.pPushConstantRanges = &push; VkDescriptorSetLayout set0_layout = VK_NULL_HANDLE; if (entry->binding_count) { set0_layout = device_.bindless->layout(); layout_info.setLayoutCount = 1; layout_info.pSetLayouts = &set0_layout; pipeline_.bindless_set = device_.bindless->set(); } if (vk.vkCreatePipelineLayout(dev, &layout_info, nullptr, &pipeline_.layout) != VK_SUCCESS) return E_FAIL; compute_entry_ = entry; stage_bytes_ = spirv_bytes; pipeline_.estimate = leonida::large_module_estimate(spirv_bytes); // The title creates hundreds of compute pipelines from job threads during startup and one of its init tasks // waits for all of them; some modules (wave64-emulated ray-tracing resolves, 4 MiB of SPIR-V) take the driver // minutes each. So the Vulkan pipeline is built on first use (build_compute): at the first dispatch that names // it, or earlier by the warm-up thread. CreateComputePipelineState answers at once, as it does on the console // where these are precompiled. LEONIDA_LAZY_COMPUTE=0: built here, as before. static const bool lazy_compute = [] { wchar_t v[2]{}; return !(GetEnvironmentVariableW(L"LEONIDA_LAZY_COMPUTE", v, 2) == 1 && v[0] == L'0'); }(); if (skip_compute(entry->name)) { // Never built. Replay drops each dispatch (ComputePipeline::skipped); the first one is logged, so a // boot's log lists the skipped programs the title actually ran. pipeline_.skipped = true; pipeline_.build = [](void* self) -> VkPipeline { auto* pso = static_cast(self); if (!pso->skip_logged_.exchange(true)) std::fprintf(stderr, "[rt] d3d12: compute program %s is skipped (LEONIDA_SKIP_COMPUTE): its " "dispatches are dropped\n", pso->compute_entry_->name.c_str()); return VK_NULL_HANDLE; }; pipeline_.build_context = this; } else if (lazy_compute) { pipeline_.async_build = async_replay_compile(); pipeline_.build = [](void* self) { auto* pso = static_cast(self); return replay_pipeline("dispatch", [&] { return pso->pipeline_.async_build ? pso->queue_build(true, 0) : pso->build_compute("dispatch"); }); }; pipeline_.build_context = this; pipeline_.built = [](void* self) { auto* pso = static_cast(self); std::unique_lock lock(pso->variants_mutex_, std::try_to_lock); // held: another thread is compiling it return lock.owns_lock() ? pso->pipeline_.pipeline : VkPipeline(VK_NULL_HANDLE); }; pipeline_.large = big_compute(spirv_bytes) && big_compiles() != BigCompiles::unlimited; } else if (!build_compute("compute-create")) { return E_FAIL; } // The code base: shaders read constant tables embedded in their own program through s_getpc_b64. The // translator's code offsets are into the bytes the key hashes (the FSSM blob, or the kind-6 program). if (entry->uses_code_base || !entry->code_base_known) { const auto& code = program.bytes; if (!device_.arena_allocate(code.size(), 256, code_base_, DeviceState::arena_shader)) return E_OUTOFMEMORY; std::memcpy(device_.arena.mapped + code_base_, code.data(), code.size()); code_bytes_ = code.size(); pipeline_.code_base = code_base_; } device_.context->add_pipeline(id(), pipeline_, device_.info.device_fault_diagnostics ? entry->name.c_str() : nullptr); registered_ = true; if (pipeline_.build && !pipeline_.skipped) warmup_enqueue(this, spirv_bytes); return S_OK; } private: using Work = leonida::LargeModuleGate::Work; // Locks the PSO (`lock`, on variants_mutex_) for a build and, with an `estimate`, takes the build's place at the gate. A // thread that waits for its place holds no PSO's lock, and one that has its place waits for none: another thread may be // building that PSO, with a place of its own. Returns without a place when the PSO is `built` already. template leonida::LargeModuleGate::Ticket enter_build(std::unique_lock& lock, std::uint64_t estimate, Work work, Built&& built) { for (;;) { lock.lock(); if (!estimate || built()) return {}; lock.unlock(); leonida::LargeModuleGate::Ticket place(big_compile_gate(), estimate, work); if (lock.try_lock()) return place; } } // The compute pipeline, built once: by create_compute (LEONIDA_LAZY_COMPUTE=0), by the first dispatch that names // it (the replay layer calls ComputePipeline::build) or by the warm-up thread. Null when it cannot be built; the // failure is logged and not retried. VkPipeline build_compute(const char* trigger, Work work = Work::demand) { CompileActivity activity(device_.active_compiles); std::unique_lock lock(variants_mutex_, std::defer_lock); const bool budgeted = big_compute(stage_bytes_) && big_compiles() == BigCompiles::budget; auto place = enter_build(lock, budgeted ? pipeline_.estimate : 0, work, [this] { return pipeline_.pipeline || compute_failed_; }); if (pipeline_.pipeline || compute_failed_) return pipeline_.pipeline; compute_failed_ = true; // until the pipeline exists auto& vk = device_.context->vk; const VkDevice dev = device_.info.device; const leonida::ShaderLibrary* library = device_.library(); const leonida::ShaderEntry* entry = compute_entry_; if (!library || !entry) return VK_NULL_HANDLE; static std::mutex big_compile; std::unique_lock big_lock(big_compile, std::defer_lock); if (big_compute(stage_bytes_) && big_compiles() == BigCompiles::serial) big_lock.lock(); auto words = library->spirv(*entry); if (words.empty()) { std::fprintf(stderr, "[rt] d3d12: %s.spv is missing or not SPIR-V\n", entry->name.c_str()); return VK_NULL_HANDLE; } VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; module_info.codeSize = words.size() * 4; module_info.pCode = words.data(); VkShaderModule module = VK_NULL_HANDLE; { const leonida::aftermath::ShaderName named(entry->name); if (vk.vkCreateShaderModule(dev, &module_info, nullptr, &module) != VK_SUCCESS) return VK_NULL_HANDLE; } const auto bytes = module_info.codeSize; std::vector().swap(words); // vkCreateShaderModule consumed pCode VkComputePipelineCreateInfo pipeline_info{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; pipeline_info.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; pipeline_info.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; pipeline_info.stage.module = module; pipeline_info.stage.pName = "main"; VkPipelineShaderStageRequiredSubgroupSizeCreateInfo required_size{}; subgroup_size_for(*entry, required_size, pipeline_info.stage); pipeline_info.layout = pipeline_.layout; const VkPipelineCache cache = device_.pipeline_cache(); const ULONGLONG started = GetTickCount64(); VkPipeline built = VK_NULL_HANDLE; CompileTrace trace; trace.begin(pipeline_info, device_.info.pipeline_creation_feedback, trigger, entry->name.c_str(), 0, bytes, cache_key_); const leonida::pipeline_profile::DriverCall profile("cs", trigger, entry->name.c_str()); const VkResult created = vk.vkCreateComputePipelines(dev, cache, 1, &pipeline_info, nullptr, &built); profile.finish(int(created)); trace.end(trigger, entry->name.c_str(), 0, bytes, created); if (big_lock.owns_lock()) big_lock.unlock(); place.release(); vk.vkDestroyShaderModule(dev, module, nullptr); // Vulkan lets a module go once the pipeline exists const ULONGLONG took = GetTickCount64() - started; if (created != VK_SUCCESS || !built) { std::fprintf(stderr, "[rt] d3d12: compute pipeline %s could not be built (VkResult %d); its dispatches are " "dropped\n", entry->name.c_str(), int(created)); return VK_NULL_HANDLE; } if (took >= 2000) std::fprintf(stderr, "[rt] d3d12: compute pipeline %s took %.1f s to build (%zu B SPIR-V)\n", entry->name.c_str(), double(took) / 1000.0, bytes); maybe_checkpoint(cache); pipeline_.pipeline = built; compute_failed_ = false; return built; } // Lazy compute pipelines are also built in the background, smallest module first, so most exist before their // first dispatch. One low-priority thread; modules over LEONIDA_COMPUTE_WARMUP_MAX_BYTES of SPIR-V (default // 1 MiB) are left to their first dispatch, since some take the driver minutes each. LEONIDA_COMPUTE_WARMUP=0 // turns the thread off. A queued build holds no reference: a PSO released first drops it (last_release). // The startup cache checkpoint is the device's job, not this PSO's: ~Device cancels it before the cache goes. void maybe_checkpoint(VkPipelineCache cache) { if (!cache || !startup_cache_checkpoints_enabled()) return; auto now = GetTickCount64(); auto next = device_.next_checkpoint.load(); if (now < next || !device_.next_checkpoint.compare_exchange_strong(next, ULLONG_MAX)) return; DeviceState* const state = &device_; bool queued = false; try { queued = PipelineCompiler::instance().submit(state, state, SIZE_MAX, [state, cache] { try { if (!state->active_compiles.load() && !PipelineCompiler::instance().has_compile_waiter()) save_session_pipeline_cache(state->context->vk, state->info.device, cache, true); } catch (const std::exception& e) { std::fprintf(stderr, "[rt] pipeline cache checkpoint failed: %s\n", e.what()); } state->next_checkpoint.store(GetTickCount64() + 120000); }); } catch (...) { } if (!queued) device_.next_checkpoint.store(now + 120000); // refused after an exit stop, or out of memory } VkPipeline queue_build(bool compute, std::uint32_t unbound, std::size_t warm_bytes = 0) { static std::mutex publication; // ready handles only; no compiler call holds this lock const bool warm = warm_bytes != 0; // After an exit stop (stop_pipeline_compiles) nothing is queued: a warm-up is skipped, and a draw or dispatch // builds in place, as without LEONIDA_ASYNC_PIPELINES, rather than waiting for a build that never comes. if (PipelineCompiler::instance().closed()) { if (warm) return VK_NULL_HANDLE; return compute ? build_compute("dispatch") : variant(unbound, "draw"); } std::lock_guard lock(publication); if (!warm) { if (!requested_) requested_ = std::make_unique(); auto [it, inserted] = requested_->try_emplace(unbound); if (!it->second.handle) ++it->second.skips; if (!inserted) return it->second.handle; } bool queued = false; try { queued = PipelineCompiler::instance().submit(compile_owner(), &device_, warm_bytes, [this, compute, warm, unbound] { VkPipeline built{}; try { built = compute ? build_compute(warm ? "warmup" : "dispatch-worker", warm ? Work::speculative : Work::demand) : variant(unbound, "draw-worker"); if (async_replay_compile()) { unsigned long long skipped = 0; { std::lock_guard publish(publication); if (!requested_) requested_ = std::make_unique(); auto& entry = (*requested_)[unbound]; if (!entry.handle) skipped = entry.skips; entry.handle = built; } if (skipped && trace_pipeline_compile()) std::fprintf(stderr, "[rt] pipeline-deferred type=%s skipped=%llu ready=%d\n", compute ? "compute" : "graphics", skipped, int(built != VK_NULL_HANDLE)); } } catch (const std::exception& e) { std::fprintf(stderr, "[rt] pipeline compile worker failed: %s\n", e.what()); } }); } catch (...) { } // Not queued (refused by a stop that came after the check above, or out of memory): no request stays // recorded, so the next use asks again instead of waiting for a build that never comes. if (!queued && !warm) requested_->erase(unbound); return VK_NULL_HANDLE; } static void warmup_enqueue(PipelineState* pso, std::size_t bytes) { static const std::size_t max_bytes = [] { char text[32]{}; const DWORD n = GetEnvironmentVariableA("LEONIDA_COMPUTE_WARMUP_MAX_BYTES", text, sizeof(text)); const unsigned long long v = (n > 0 && n < sizeof(text)) ? std::strtoull(text, nullptr, 10) : 0; return v ? static_cast(v) : std::size_t{1} << 20; }(); static const bool on = [] { wchar_t v[2]{}; return !(GetEnvironmentVariableW(L"LEONIDA_COMPUTE_WARMUP", v, 2) == 1 && v[0] == L'0'); }(); if (on && bytes && bytes <= max_bytes) pso->queue_build(true, 0, bytes); } // What a graphics pipeline is made from, so variants can be built at draw time. struct Recipe { bool mesh = false; // no vertex input or input assembly state, and no dynamic topology or strides std::vector stages; // One per entry of create_graphics's stage table (VS, GS, PS), static_assert there; what `stages` chain. VkPipelineShaderStageRequiredSubgroupSizeCreateInfo required_sizes[3]{}; std::vector attributes; std::vector bindings; std::vector divisors; VkPipelineInputAssemblyStateCreateInfo assembly{}; VkPipelineRasterizationStateCreateInfo raster{}; bool conservative = false; VkPipelineMultisampleStateCreateInfo multisample{}; VkSampleMask sample_mask = ~0u; VkPipelineDepthStencilStateCreateInfo depth{}; std::vector blends; VkPipelineColorBlendStateCreateInfo blend{}; }; // The graphics pipeline with the formats of the `unbound` slots (leonida::GraphicsPipeline::variant) undefined. VkPipeline build(std::uint32_t unbound, const char* trigger, VkPipelineCreateFlags flags = 0, VkResult* status = nullptr) { CompileActivity activity(device_.active_compiles); const Recipe& r = recipe_; std::vector colors = graphics_.color_formats; for (std::size_t slot = 0; slot < colors.size(); ++slot) if (unbound & (1u << slot)) colors[slot] = VK_FORMAT_UNDEFINED; const bool depth_bound = !(unbound & leonida::GraphicsPipeline::unbound_depth); VkPipelineRenderingCreateInfo rendering{VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO}; rendering.colorAttachmentCount = std::uint32_t(colors.size()); rendering.pColorAttachmentFormats = colors.data(); if (depth_bound && (graphics_.depth_aspects & VK_IMAGE_ASPECT_DEPTH_BIT)) rendering.depthAttachmentFormat = graphics_.depth_format; if (depth_bound && (graphics_.depth_aspects & VK_IMAGE_ASPECT_STENCIL_BIT)) rendering.stencilAttachmentFormat = graphics_.depth_format; VkPipelineVertexInputStateCreateInfo vertex_input{VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO}; VkPipelineVertexInputDivisorStateCreateInfoEXT divisor_state{ VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_DIVISOR_STATE_CREATE_INFO_EXT}; if (!r.divisors.empty()) { divisor_state.vertexBindingDivisorCount = std::uint32_t(r.divisors.size()); divisor_state.pVertexBindingDivisors = r.divisors.data(); vertex_input.pNext = &divisor_state; } vertex_input.vertexBindingDescriptionCount = std::uint32_t(r.bindings.size()); vertex_input.pVertexBindingDescriptions = r.bindings.data(); vertex_input.vertexAttributeDescriptionCount = std::uint32_t(r.attributes.size()); vertex_input.pVertexAttributeDescriptions = r.attributes.data(); VkPipelineViewportStateCreateInfo viewport{VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO}; if (!graphics_.viewport_with_count) { viewport.viewportCount = 1; viewport.scissorCount = 1; } VkPipelineMultisampleStateCreateInfo multisample = r.multisample; VkPipelineRasterizationStateCreateInfo raster = r.raster; VkPipelineRasterizationConservativeStateCreateInfoEXT conservative{ VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_CONSERVATIVE_STATE_CREATE_INFO_EXT}; if (r.conservative) { conservative.conservativeRasterizationMode = VK_CONSERVATIVE_RASTERIZATION_MODE_OVERESTIMATE_EXT; conservative.extraPrimitiveOverestimationSize = 0.0f; conservative.pNext = raster.pNext; raster.pNext = &conservative; } multisample.pSampleMask = &r.sample_mask; VkPipelineColorBlendStateCreateInfo blend = r.blend; blend.attachmentCount = std::uint32_t(r.blends.size()); blend.pAttachments = r.blends.data(); // A mesh pipeline takes neither the topology nor the strides as dynamic state // (VUID-VkGraphicsPipelineCreateInfo-pDynamicStates-07065 and -07066). // With multiViewport enabled, VIEWPORT_WITH_COUNT / SCISSOR_WITH_COUNT allow 1..16 dynamic viewports/scissors. VkDynamicState dyn_list[8]{}; std::uint32_t dyn_count = 0; dyn_list[dyn_count++] = graphics_.viewport_with_count ? VK_DYNAMIC_STATE_VIEWPORT_WITH_COUNT : VK_DYNAMIC_STATE_VIEWPORT; dyn_list[dyn_count++] = graphics_.viewport_with_count ? VK_DYNAMIC_STATE_SCISSOR_WITH_COUNT : VK_DYNAMIC_STATE_SCISSOR; if (!r.mesh) { dyn_list[dyn_count++] = VK_DYNAMIC_STATE_PRIMITIVE_TOPOLOGY; dyn_list[dyn_count++] = VK_DYNAMIC_STATE_PRIMITIVE_RESTART_ENABLE; } dyn_list[dyn_count++] = VK_DYNAMIC_STATE_STENCIL_REFERENCE; dyn_list[dyn_count++] = VK_DYNAMIC_STATE_BLEND_CONSTANTS; if (!r.mesh && !r.bindings.empty()) dyn_list[dyn_count++] = VK_DYNAMIC_STATE_VERTEX_INPUT_BINDING_STRIDE; VkPipelineDynamicStateCreateInfo dynamic{VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO}; dynamic.dynamicStateCount = dyn_count; dynamic.pDynamicStates = dyn_list; // A lazy pipeline's stages get their modules here, for this one call (Vulkan lets a module go once the // pipeline exists), so the driver holds no SPIR-V for pipelines that are not drawn. auto bytes = stage_bytes_; std::vector stages; std::vector made; const auto drop_modules = [&] { for (VkShaderModule module : made) device_.context->vk.vkDestroyShaderModule(device_.info.device, module, nullptr); }; std::vector> words; if (lazy_) { std::string why; if (!stage_words(words, why) || words.size() != r.stages.size()) { std::fprintf(stderr, "[rt] d3d12: a pipeline built at its first draw lost its SPIR-V: %s\n", why.empty() ? "stage count" : why.c_str()); return VK_NULL_HANDLE; } bytes = 0; stages = r.stages; for (std::size_t i = 0; i < stages.size(); ++i) { VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; module_info.codeSize = words[i].size() * 4; bytes += module_info.codeSize; module_info.pCode = words[i].data(); VkShaderModule module = VK_NULL_HANDLE; const leonida::aftermath::ShaderName named( sources_[i].entry ? sources_[i].entry->name.c_str() : sources_[i].kind == StageSource::rect_list ? "(rect-list geometry)" : "(depth24 depth-only fragment)"); if (device_.context->vk.vkCreateShaderModule(device_.info.device, &module_info, nullptr, &module) != VK_SUCCESS) { drop_modules(); return VK_NULL_HANDLE; } made.push_back(module); stages[i].module = module; } } VkGraphicsPipelineCreateInfo info{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, &rendering}; // A triangle-family pipeline drawn as a rectangle list: the same stages plus the generated geometry stage. std::vector rectangle_stages; if (unbound & leonida::GraphicsPipeline::rectangle_stage) { VkShaderModule rectangle = VK_NULL_HANDLE; if (!rectangle_capable_) { drop_modules(); return VK_NULL_HANDLE; } if (lazy_) { std::size_t vs = SIZE_MAX; for (std::size_t i = 0; i < sources_.size(); ++i) if (sources_[i].kind == StageSource::library && sources_[i].slot == 0) vs = i; std::string why; const std::vector geometry_words = vs == SIZE_MAX ? std::vector{} : leonida::rect_list_geometry(words[vs], why); VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; module_info.codeSize = geometry_words.size() * 4; module_info.pCode = geometry_words.data(); if (geometry_words.empty() || device_.context->vk.vkCreateShaderModule(device_.info.device, &module_info, nullptr, &rectangle) != VK_SUCCESS) { std::fprintf(stderr, "[rt] d3d12: cannot draw rectangle list: %s\n", why.c_str()); drop_modules(); return VK_NULL_HANDLE; } made.push_back(rectangle); bytes += module_info.codeSize; rectangle_stages = stages; } else { if (!rectangle_vertex_) return VK_NULL_HANDLE; if (!rectangle_module_) { std::string why; const auto geometry_words = leonida::rect_list_geometry(rectangle_vertex_->words, why); if (geometry_words.empty()) { std::fprintf(stderr, "[rt] d3d12: cannot draw rectangle list: %s\n", why.c_str()); return VK_NULL_HANDLE; } rectangle_module_ = shader_module(geometry_words); if (!rectangle_module_) return VK_NULL_HANDLE; } rectangle = rectangle_module_; rectangle_stages = r.stages; } VkPipelineShaderStageCreateInfo geometry{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; geometry.stage = VK_SHADER_STAGE_GEOMETRY_BIT; geometry.module = rectangle; geometry.pName = "main"; rectangle_stages.push_back(geometry); } const auto& pipeline_stages = !rectangle_stages.empty() ? rectangle_stages : lazy_ ? stages : r.stages; info.stageCount = std::uint32_t(pipeline_stages.size()); info.pStages = pipeline_stages.data(); info.pVertexInputState = r.mesh ? nullptr : &vertex_input; // ignored with a mesh stage; null for clarity info.pInputAssemblyState = r.mesh ? nullptr : &r.assembly; info.pViewportState = &viewport; info.pRasterizationState = &raster; info.pMultisampleState = &multisample; info.pDepthStencilState = &r.depth; info.pColorBlendState = &blend; info.pDynamicState = &dynamic; info.flags=flags; info.layout = graphics_.layout; VkPipeline pipeline = VK_NULL_HANDLE; const auto cache = device_.pipeline_cache(); const char* program = "-", *fragment = "-"; if (leonida::pipeline_profile::enabled()) { for (const auto& source : sources_) { if (!source.entry) continue; if (source.slot == 0) program = source.entry->name.c_str(); if (source.slot == 2) fragment = source.entry->name.c_str(); } } CompileTrace trace; trace.begin(info, device_.info.pipeline_creation_feedback, trigger, profile_shaders_.c_str(), unbound, bytes, cache_key_); const leonida::pipeline_profile::DriverCall profile(r.mesh ? "ms" : "vs", lazy_ ? "lazy" : "eager", program, fragment, unbound); const auto result = device_.context->vk.vkCreateGraphicsPipelines(device_.info.device, cache, 1, &info, nullptr, &pipeline); if (status) *status = result; profile.finish(int(result)); trace.end(trigger, profile_shaders_.c_str(), unbound, bytes, result); if (result != VK_SUCCESS) { if (pipeline) device_.context->vk.vkDestroyPipeline(device_.info.device, pipeline, nullptr); pipeline = VK_NULL_HANDLE; } drop_modules(); if (pipeline) maybe_checkpoint(cache); return pipeline; } // A lazy pipeline's SPIR-V, one module's words per recipe stage, made as create_graphics made them: the library // stages (VS or MS, GS, PS) read again, the f16 halves linked, the D24 fragment patch, then the generated stages // (the rectangle-list geometry stage from the vertex stage, the depth-only fragment stage). False with `why` when // a file went missing since. // The rewrites a pixel shader's words get for this pipeline, the same at creation and in a lazy build(): // quantising B4G4R4A4 targets stored as RGBA8, then moving SV_Target1 to Location 0, Index 1 for a SRC1 blend // factor (RT-DUAL-SOURCE-BLEND). bool rewrite_fragment(std::vector& words, std::string& why) const { if (rgba4_mask_ && !leonida::rgba4::quantize(words, rgba4_mask_)) { why = "could not be quantised for a B4G4R4A4 target stored as RGBA8"; return false; } if (dual_source_ && !leonida::dual_source::remap(words)) { why = "has no second colour output at Location 1 for a SRC1 blend factor"; return false; } return true; } bool stage_words(std::vector>& words, std::string& why) const { const leonida::ShaderLibrary* library = device_.library(); if (!library) { why = "no shader library"; return false; } words.assign(sources_.size(), {}); std::size_t vs = SIZE_MAX, ps = SIZE_MAX; for (std::size_t i = 0; i < sources_.size(); ++i) { const StageSource& source = sources_[i]; if (source.kind != StageSource::library) continue; words[i] = library->spirv(*source.entry); if (words[i].empty()) { why = source.entry->name + ".spv is missing or not SPIR-V"; return false; } if (source.slot == 2 && !rewrite_fragment(words[i], why)) { why = source.entry->name + ": " + why; return false; } if (source.slot == 0) vs = i; if (source.slot == 2) ps = i; } if (f16_linked_) { if (vs == SIZE_MAX || ps == SIZE_MAX || !leonida::link_f16_halves(words[vs], *sources_[vs].entry, words[ps], *sources_[ps].entry, &why)) return false; } for (std::size_t i = 0; i < sources_.size(); ++i) { if (!sources_[i].depth24) continue; std::vector patched = leonida::depth24_patch_fragment(words[i], depth24_bias_, why); if (patched.empty()) return false; words[i] = std::move(patched); } for (std::size_t i = 0; i < sources_.size(); ++i) { if (sources_[i].kind == StageSource::rect_list) { if (vs == SIZE_MAX) return false; words[i] = leonida::rect_list_geometry(words[vs], why); } else if (sources_[i].kind == StageSource::depth_only) { words[i] = leonida::depth24_depth_only_fragment(depth24_bias_); } else { continue; } if (words[i].empty()) return false; } return true; } // Built on first use and kept until the PSO is released (replay may call this from any queue). VkPipeline variant(std::uint32_t unbound, const char* trigger) { std::unique_lock lock(variants_mutex_, std::defer_lock); const bool budgeted = graphics_.large && big_compiles() == BigCompiles::budget; const auto place = enter_build(lock, budgeted ? graphics_.estimate : 0, Work::demand, [&] { return variants_.contains(unbound); }); if (const auto it = variants_.find(unbound); it != variants_.end()) return it->second; const VkPipeline pipeline = build(unbound, trigger); if (!pipeline) { if (leonida::pipeline_profile::enabled()) std::fprintf(stderr, "[rt] pso-variant failed stage=%s mask=%u\n", recipe_.mesh ? "ms" : "vs", unbound); log_once("a pipeline variant for unbound attachment slots could not be built; slots", int(unbound)); return VK_NULL_HANDLE; } variants_.emplace(unbound, pipeline); return pipeline; } // Where a lazy graphics pipeline's stage modules come from, in recipe_.stages order (stage_words). struct StageSource { enum Kind : std::uint8_t { library, rect_list, depth_only } kind = library; std::uint8_t slot = 0; // library: the create_graphics stage table entry (0 VS or MS, 1 GS, 2 PS) bool depth24 = false; // library: the D24 fragment patch applies const leonida::ShaderEntry* entry = nullptr; // library: the translated shader }; DeviceState& device_; leonida::ComputePipeline pipeline_; leonida::GraphicsPipeline graphics_; Recipe recipe_; const leonida::ShaderEntry* compute_entry_ = nullptr; // compute: the translated shader build_compute reads bool compute_failed_ = false; // compute: could not be built; not retried std::atomic skip_logged_{false}; // compute: the skipped program's first dispatch was logged bool lazy_ = false; // graphics: built at the first draw (lazy_graphics_pipelines) bool f16_linked_ = false; // graphics: the VS and PS words had their f16 halves linked leonida::Depth24Bias depth24_bias_{}; unsigned rgba4_mask_ = 0; // graphics: the B4G4R4A4 targets stored as RGBA8 that the pixel shader is quantised for bool dual_source_ = false; // graphics: a SRC1 blend factor; the pixel shader's SV_Target1 is Location 0, Index 1 std::vector sources_; struct Request { VkPipeline handle{}; unsigned long long skips = 0; }; using Requests = std::map; std::unique_ptr requested_; std::string profile_shaders_; // populated only with compile tracing enabled std::size_t stage_bytes_ = 0; std::mutex variants_mutex_; std::map variants_; VkShaderModule module_ = VK_NULL_HANDLE; std::vector modules_; leonida::GraphicsShaderModules::Reference rectangle_vertex_; VkShaderModule rectangle_module_ = VK_NULL_HANDLE; bool rectangle_capable_ = false; // graphics: a vertex stage the rectangle-list geometry stage can follow VkShaderModule shader_module(std::span words) { auto& vk=device_.context->vk; auto object = device_.graphics_modules.acquire(device_.info.device, vk.vkCreateShaderModule, vk.vkDestroyShaderModule, words); if(!object)return VK_NULL_HANDLE; const auto h=object->handle;modules_.push_back(std::move(object)); return h; } VkDeviceSize code_base_ = 0; VkDeviceSize code_bytes_ = 0; bool registered_ = false; bool unregistered_ = false; // taken out of the context's registry (unregister) bool is_graphics_ = false; std::vector subgroup_requests_; // one per stage, in creation order unsigned pending_stream_kind_=0; std::once_flag resolve_stream_once_; std::once_flag native_source_once_; bool native_source_ready_ = false; std::shared_ptr native_owner_; leonida::cached_pso::Key cache_key_; }; void key_root_signature(leonida::cached_pso::KeyBuilder& key, ID3D12RootSignature* signature) { if (!signature) { key.tag("no root signature"); } else if (const RootSignature* own = RootSignature::from(signature)) { key.tag("root signature").text(own->content().c_str()); } else { const auto address = reinterpret_cast(signature); key.tag("foreign root signature").bytes(&address, sizeof(address)); } } // A view of a texture as Create*View describes it, before the resource's own shape is applied. struct TextureView { DXGI_FORMAT format = DXGI_FORMAT_UNKNOWN; // UNKNOWN: the resource's leonida::gfx10::ImageType type = leonida::gfx10::ImageType::image_2d; UINT first_mip = 0; UINT mip_count = ~0u; // ~0: to the last UINT first_layer = 0; UINT layer_count = ~0u; UINT mapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; UINT plane = 0; float min_lod = 0.0f; }; // The existing mutable Vulkan formats come from these DXGI typeless families. A typed resource cannot be // reinterpreted by the 1D/3D UAV path; equal texel sizes alone don't make a cast legal. bool uav_format_compatible(DXGI_FORMAT resource, DXGI_FORMAT view) { if (view == DXGI_FORMAT_R8G8B8A8_UNORM_SRGB || view == DXGI_FORMAT_B8G8R8A8_UNORM_SRGB) return false; if (resource == DXGI_FORMAT_R8G8B8A8_UNORM_SRGB) return view == DXGI_FORMAT_R8G8B8A8_UNORM; if (resource == DXGI_FORMAT_B8G8R8A8_UNORM_SRGB) return view == DXGI_FORMAT_B8G8R8A8_UNORM; if (resource == view) return true; switch (resource) { case DXGI_FORMAT_R32G32B32A32_TYPELESS: return view >= DXGI_FORMAT_R32G32B32A32_FLOAT && view <= DXGI_FORMAT_R32G32B32A32_SINT; case DXGI_FORMAT_R16G16B16A16_TYPELESS: return view >= DXGI_FORMAT_R16G16B16A16_FLOAT && view <= DXGI_FORMAT_R16G16B16A16_SINT; case DXGI_FORMAT_R32G32_TYPELESS: return view >= DXGI_FORMAT_R32G32_FLOAT && view <= DXGI_FORMAT_R32G32_SINT; case DXGI_FORMAT_R10G10B10A2_TYPELESS: return view == DXGI_FORMAT_R10G10B10A2_UNORM || view == DXGI_FORMAT_R10G10B10A2_UINT; case DXGI_FORMAT_R8G8B8A8_TYPELESS: return view >= DXGI_FORMAT_R8G8B8A8_UNORM && view <= DXGI_FORMAT_R8G8B8A8_SINT; case DXGI_FORMAT_R16G16_TYPELESS: return view >= DXGI_FORMAT_R16G16_FLOAT && view <= DXGI_FORMAT_R16G16_SINT; case DXGI_FORMAT_R8G8_TYPELESS: return view >= DXGI_FORMAT_R8G8_UNORM && view <= DXGI_FORMAT_R8G8_SINT; case DXGI_FORMAT_R32_TYPELESS: return view >= DXGI_FORMAT_R32_FLOAT && view <= DXGI_FORMAT_R32_SINT; case DXGI_FORMAT_R16_TYPELESS: return view >= DXGI_FORMAT_R16_FLOAT && view <= DXGI_FORMAT_R16_SINT; case DXGI_FORMAT_B8G8R8A8_TYPELESS: return view == DXGI_FORMAT_B8G8R8A8_UNORM; default: return false; } } // In-memory pipeline library (docs/d3d12_vulkan.md sections 3.6 and 4). D3D12 cached blobs are driver-specific // and ignored across runs; Serialize writes a versioned header so CreatePipelineLibrary recognizes our own blobs. // As on the host runtime (d3d12_pipeline_library_host_test), a foreign, truncated or corrupt blob is E_INVALIDARG; // one of ours from another version is D3D12_ERROR_DRIVER_VERSION_MISMATCH. A pipeline library is a device child, // not a pageable object: the host answers E_NOINTERFACE for ID3D12Pageable. class PipelineLibrary final : public Child { public: // {6e2a9d41-7b5f-4c83-8e14-2a9d6f3c5b10} static constexpr GUID kTag{0x6e2a9d41, 0x7b5f, 0x4c83, {0x8e, 0x14, 0x2a, 0x9d, 0x6f, 0x3c, 0x5b, 0x10}}; struct Header { std::uint32_t magic; std::uint32_t version; std::uint32_t count; std::uint32_t reserved; }; static constexpr std::uint32_t kMagic = 0x314C504Cu; // "LPL1" static constexpr std::uint32_t kVersion = 1; ~PipelineLibrary() override { std::lock_guard lock(mutex_); for (auto& [name, pso] : entries_) if (pso) pso->Release(); entries_.clear(); } // S_OK for a blob of ours, D3D12_ERROR_DRIVER_VERSION_MISMATCH for one of ours from another version, // E_INVALIDARG for anything else (foreign, truncated or corrupt). static HRESULT check_blob(const void* data, SIZE_T size) { if (!data || size < sizeof(Header)) return E_INVALIDARG; Header h{}; std::memcpy(&h, data, sizeof(h)); if (h.magic != kMagic || h.reserved != 0) return E_INVALIDARG; return h.version == kVersion ? S_OK : D3D12_ERROR_DRIVER_VERSION_MISMATCH; } HRESULT STDMETHODCALLTYPE StorePipeline(LPCWSTR name, ID3D12PipelineState* pipeline) override { if (!name || !*name || !pipeline) return E_INVALIDARG; if (!PipelineState::from(pipeline)) return E_INVALIDARG; std::lock_guard lock(mutex_); auto [it, inserted] = entries_.emplace(name, pipeline); if (!inserted) return E_INVALIDARG; pipeline->AddRef(); return S_OK; } HRESULT STDMETHODCALLTYPE LoadGraphicsPipeline(LPCWSTR name, const D3D12_GRAPHICS_PIPELINE_STATE_DESC* desc, REFIID riid, void** out) override { if (!out) return E_INVALIDARG; // the host runtime's answer (not E_POINTER) *out = nullptr; if (!name || !*name || !desc) return E_INVALIDARG; return load_entry(name, false, true, riid, out); } HRESULT STDMETHODCALLTYPE LoadComputePipeline(LPCWSTR name, const D3D12_COMPUTE_PIPELINE_STATE_DESC* desc, REFIID riid, void** out) override { if (!out) return E_INVALIDARG; // the host runtime's answer (not E_POINTER) *out = nullptr; if (!name || !*name || !desc) return E_INVALIDARG; return load_entry(name, true, false, riid, out); } HRESULT STDMETHODCALLTYPE LoadPipeline(LPCWSTR name, const D3D12_PIPELINE_STATE_STREAM_DESC* desc, REFIID riid, void** out) override { if (!out) return E_INVALIDARG; // the host runtime's answer (not E_POINTER) *out = nullptr; if (!name || !*name || !desc || !desc->SizeInBytes || !desc->pPipelineStateSubobjectStream) return E_INVALIDARG; return load_entry(name, false, false, riid, out); } SIZE_T STDMETHODCALLTYPE GetSerializedSize() override { return sizeof(Header); } HRESULT STDMETHODCALLTYPE Serialize(void* data, SIZE_T size) override { if (!data || size < sizeof(Header)) return E_INVALIDARG; std::lock_guard lock(mutex_); const Header h{kMagic, kVersion, static_cast(entries_.size()), 0}; std::memcpy(data, &h, sizeof(h)); return S_OK; } private: HRESULT load_entry(LPCWSTR name, bool require_compute, bool require_graphics, REFIID riid, void** out) { std::lock_guard lock(mutex_); const auto it = entries_.find(name); if (it == entries_.end()) return E_INVALIDARG; PipelineState* ps = PipelineState::from(it->second); if (!ps) return E_INVALIDARG; if (require_compute && !ps->compute()) return E_INVALIDARG; if (require_graphics && !ps->graphics()) return E_INVALIDARG; return it->second->QueryInterface(riid, out); } std::mutex mutex_; std::unordered_map entries_; }; // Process-wide backing for ID3D12Device9::CreateShaderCacheSession and ID3D12ShaderCacheSession (D3D-34). // Sessions in the same process sharing (Identifier, Mode, disk_path) share their entries; a live session with a // different Version returns DXGI_ERROR_ALREADY_EXISTS, while reopening after all sessions close clears and recreates // the cache. MODE_MEMORY discards its entries when the final session is released; MODE_DISK persists entries to a // versioned binary file via unique per-writer temp files and atomic replacement. struct ShaderCacheKey { GUID identifier{}; D3D12_SHADER_CACHE_MODE mode = D3D12_SHADER_CACHE_MODE_MEMORY; std::wstring disk_path; // empty for MODE_MEMORY bool operator<(const ShaderCacheKey& other) const { const int cmp = std::memcmp(&identifier, &other.identifier, sizeof(GUID)); if (cmp != 0) return cmp < 0; if (mode != other.mode) return mode < other.mode; return disk_path < other.disk_path; } }; struct ShaderCacheStore { static constexpr std::uint32_t kDiskMagic = 0x3143534Cu; // "LSC1" static constexpr std::uint32_t kDiskFormatVersion = 2; static constexpr UINT kDefaultMaxMemoryBytes = 1024u; static constexpr UINT kDefaultMaxMemoryEntries = 128u; static constexpr UINT kDefaultMaxValueFileBytes = 128u * 1024u * 1024u; struct DiskHeader { std::uint32_t magic; std::uint32_t format_version; std::uint32_t entry_count; std::uint32_t reserved; std::uint64_t cache_version; }; std::mutex mutex; std::map> entries; std::size_t total_bytes = 0; std::uint32_t live_sessions = 0; UINT64 version = 0; bool delete_on_destroy = false; std::filesystem::path disk_path; void load_from_disk_locked(UINT64 expected_version, UINT max_file_bytes) { if (disk_path.empty()) return; std::error_code ec; const std::uintmax_t file_size = std::filesystem::file_size(disk_path, ec); if (ec || file_size < sizeof(DiskHeader)) return; std::ifstream in(disk_path, std::ios::binary); if (!in) return; DiskHeader header{}; if (!in.read(reinterpret_cast(&header), sizeof(header))) return; if (header.magic != kDiskMagic || header.format_version != kDiskFormatVersion || header.reserved != 0) return; if (header.cache_version != expected_version) { in.close(); std::filesystem::remove(disk_path, ec); return; } std::uint64_t remaining = static_cast(file_size) - sizeof(DiskHeader); if (header.entry_count > remaining / 8u) return; std::map> loaded; std::size_t bytes = 0; for (std::uint32_t i = 0; i < header.entry_count; ++i) { if (remaining < 8u) return; std::uint32_t lens[2]{}; if (!in.read(reinterpret_cast(lens), sizeof(lens))) return; remaining -= 8u; const std::uint64_t key_len = lens[0]; const std::uint64_t val_len = lens[1]; if (!key_len || !val_len || key_len > remaining || val_len > remaining - key_len) return; if (val_len > max_file_bytes || bytes > max_file_bytes - val_len) return; std::string k(static_cast(key_len), '\0'); std::vector v(static_cast(val_len)); if (!in.read(k.data(), static_cast(key_len)) || !in.read(reinterpret_cast(v.data()), static_cast(val_len))) return; remaining -= key_len + val_len; loaded.emplace(std::move(k), std::move(v)); bytes += static_cast(val_len); } entries = std::move(loaded); total_bytes = bytes; } bool save_to_disk_locked() const { if (disk_path.empty()) return true; std::error_code ec; std::filesystem::create_directories(disk_path.parent_path(), ec); static std::atomic write_seq{0}; const std::uint64_t seq = write_seq.fetch_add(1, std::memory_order_relaxed); wchar_t suffix[64]{}; std::swprintf(suffix, std::size(suffix), L".%lu.%lu.%llu.tmp", static_cast(GetCurrentProcessId()), static_cast(GetCurrentThreadId()), static_cast(seq)); std::filesystem::path tmp = disk_path; tmp += suffix; { std::ofstream out(tmp, std::ios::binary | std::ios::trunc); if (!out) return false; const DiskHeader header{kDiskMagic, kDiskFormatVersion, static_cast(entries.size()), 0, version}; out.write(reinterpret_cast(&header), sizeof(header)); for (const auto& [k, v] : entries) { const std::uint32_t lens[2] = {static_cast(k.size()), static_cast(v.size())}; out.write(reinterpret_cast(lens), sizeof(lens)); out.write(k.data(), static_cast(k.size())); out.write(reinterpret_cast(v.data()), static_cast(v.size())); } if (!out.good()) return false; } if (!MoveFileExW(tmp.c_str(), disk_path.c_str(), MOVEFILE_REPLACE_EXISTING)) { std::filesystem::remove(tmp, ec); return false; } return true; } void clear() { std::lock_guard lock(mutex); entries.clear(); total_bytes = 0; if (!disk_path.empty()) { std::error_code ec; std::filesystem::remove(disk_path, ec); } } }; std::filesystem::path default_shader_cache_dir() { std::error_code ec; const auto tmp = std::filesystem::temp_directory_path(ec); if (ec || tmp.empty()) return {}; return tmp / L"leonida_shader_cache"; } struct ShaderCacheRegistry { std::mutex mutex; std::map> stores; std::atomic disabled{false}; HRESULT acquire(const ShaderCacheKey& key, UINT64 version, UINT max_file_bytes, std::shared_ptr& out) { if (disabled.load(std::memory_order_relaxed)) return DXGI_ERROR_NOT_CURRENTLY_AVAILABLE; std::lock_guard lock(mutex); if (disabled.load(std::memory_order_relaxed)) return DXGI_ERROR_NOT_CURRENTLY_AVAILABLE; auto it = stores.find(key); if (it != stores.end()) { if (it->second->version != version) return DXGI_ERROR_ALREADY_EXISTS; ++it->second->live_sessions; out = it->second; return S_OK; } auto store = std::make_shared(); store->version = version; if (key.mode == D3D12_SHADER_CACHE_MODE_DISK && !key.disk_path.empty()) { store->disk_path = key.disk_path; std::lock_guard store_lock(store->mutex); store->load_from_disk_locked(version, max_file_bytes); } store->live_sessions = 1; stores.emplace(key, store); out = std::move(store); return S_OK; } void mark_delete_on_destroy(const std::shared_ptr& store) { std::lock_guard lock(mutex); if (store) store->delete_on_destroy = true; } void release(const ShaderCacheKey& key, const std::shared_ptr& store) { std::lock_guard lock(mutex); if (!store) return; if (store->live_sessions > 0) --store->live_sessions; if (store->live_sessions == 0) { if (store->delete_on_destroy && !store->disk_path.empty()) { std::error_code ec; std::filesystem::remove(store->disk_path, ec); } // Discard both idle MEMORY stores (per D3D12 spec) and idle DISK stores (so reopening reloads from disk). const auto it = stores.find(key); if (it != stores.end() && it->second == store) stores.erase(it); } } void clear_all() { std::vector> snapshot; { std::lock_guard lock(mutex); snapshot.reserve(stores.size()); for (const auto& [k, v] : stores) snapshot.push_back(v); } for (const auto& store : snapshot) store->clear(); // Also remove inactive and prior-run disk caches stored in the default cache directory (non-USE_WORKING_DIR). const auto default_dir = default_shader_cache_dir(); if (!default_dir.empty()) { std::error_code ec; if (std::filesystem::exists(default_dir, ec)) { for (const auto& entry : std::filesystem::directory_iterator(default_dir, ec)) { if (ec) break; if (!entry.is_regular_file(ec)) continue; const auto fname = entry.path().filename().wstring(); if (fname.rfind(L"leonida_sc_", 0) == 0) std::filesystem::remove(entry.path(), ec); } } } } }; ShaderCacheRegistry& process_shader_cache_registry() { static auto* registry = new ShaderCacheRegistry(); return *registry; } std::filesystem::path shader_cache_disk_path(const D3D12_SHADER_CACHE_SESSION_DESC& desc, const VkPhysicalDeviceProperties& gpu_props) { std::error_code ec; std::filesystem::path dir = (desc.Flags & D3D12_SHADER_CACHE_FLAG_USE_WORKING_DIR) ? std::filesystem::current_path(ec) : default_shader_cache_dir(); if (ec || dir.empty()) return {}; wchar_t name[160]{}; const auto& g = desc.Identifier; if (desc.Flags & D3D12_SHADER_CACHE_FLAG_DRIVER_VERSIONED) { std::swprintf(name, std::size(name), L"leonida_sc_%08lx%04x%04x%02x%02x%02x%02x%02x%02x%02x%02x_d%04x_%04x_%08x.bin", static_cast(g.Data1), g.Data2, g.Data3, g.Data4[0], g.Data4[1], g.Data4[2], g.Data4[3], g.Data4[4], g.Data4[5], g.Data4[6], g.Data4[7], gpu_props.vendorID, gpu_props.deviceID, gpu_props.driverVersion); } else { std::swprintf(name, std::size(name), L"leonida_sc_%08lx%04x%04x%02x%02x%02x%02x%02x%02x%02x%02x.bin", static_cast(g.Data1), g.Data2, g.Data3, g.Data4[0], g.Data4[1], g.Data4[2], g.Data4[3], g.Data4[4], g.Data4[5], g.Data4[6], g.Data4[7]); } return dir / name; } class ShaderCacheSession final : public Child { public: // {9a4f1b2c-8d6e-43a7-b152-7e3c9f0d4a81} static constexpr GUID kTag{0x9a4f1b2c, 0x8d6e, 0x43a7, {0xb1, 0x52, 0x7e, 0x3c, 0x9f, 0x0d, 0x4a, 0x81}}; ShaderCacheSession(const D3D12_SHADER_CACHE_SESSION_DESC& desc, const ShaderCacheKey& key, ShaderCacheRegistry& registry, std::shared_ptr store) : desc_(desc), key_(key), registry_(®istry), store_(std::move(store)) {} ~ShaderCacheSession() override { if (registry_) registry_->release(key_, store_); } HRESULT STDMETHODCALLTYPE FindValue(const void* key, UINT key_size, void* value, UINT* value_size) override { if (!key || !key_size || !value_size) return E_INVALIDARG; if (registry_ && registry_->disabled.load(std::memory_order_relaxed)) return DXGI_ERROR_NOT_CURRENTLY_AVAILABLE; std::lock_guard lock(store_->mutex); const std::string k(static_cast(key), key_size); const auto it = store_->entries.find(k); if (it == store_->entries.end()) return DXGI_ERROR_NOT_FOUND; const UINT stored_size = static_cast(it->second.size()); if (!value) { *value_size = stored_size; return S_OK; } if (*value_size < stored_size) { *value_size = stored_size; return DXGI_ERROR_MORE_DATA; } std::memcpy(value, it->second.data(), stored_size); *value_size = stored_size; return S_OK; } HRESULT STDMETHODCALLTYPE StoreValue(const void* key, UINT key_size, const void* value, UINT value_size) override { if (!key || !key_size || !value || !value_size) return E_INVALIDARG; if (registry_ && registry_->disabled.load(std::memory_order_relaxed)) return DXGI_ERROR_NOT_CURRENTLY_AVAILABLE; std::lock_guard lock(store_->mutex); const std::string k(static_cast(key), key_size); if (store_->entries.find(k) != store_->entries.end()) return DXGI_ERROR_ALREADY_EXISTS; if (desc_.Mode == D3D12_SHADER_CACHE_MODE_MEMORY) { const UINT max_entries = desc_.MaximumInMemoryCacheEntries ? desc_.MaximumInMemoryCacheEntries : ShaderCacheStore::kDefaultMaxMemoryEntries; const UINT max_bytes = desc_.MaximumInMemoryCacheSizeBytes ? desc_.MaximumInMemoryCacheSizeBytes : ShaderCacheStore::kDefaultMaxMemoryBytes; if (store_->entries.size() >= max_entries || value_size > max_bytes || store_->total_bytes > max_bytes - value_size) return DXGI_ERROR_CACHE_FULL; } else { const UINT max_file_bytes = desc_.MaximumValueFileSizeBytes ? desc_.MaximumValueFileSizeBytes : ShaderCacheStore::kDefaultMaxValueFileBytes; if (value_size > max_file_bytes || store_->total_bytes > max_file_bytes - value_size) return DXGI_ERROR_CACHE_FULL; } const auto* bytes = static_cast(value); auto [it, inserted] = store_->entries.emplace(k, std::vector(bytes, bytes + value_size)); store_->total_bytes += value_size; if (desc_.Mode == D3D12_SHADER_CACHE_MODE_DISK && !store_->save_to_disk_locked()) { store_->total_bytes -= value_size; store_->entries.erase(it); return E_FAIL; } return S_OK; } void STDMETHODCALLTYPE SetDeleteOnDestroy() override { if (registry_) registry_->mark_delete_on_destroy(store_); } #if defined(_MSC_VER) || !defined(_WIN32) D3D12_SHADER_CACHE_SESSION_DESC STDMETHODCALLTYPE GetDesc() override { return desc_; } #else D3D12_SHADER_CACHE_SESSION_DESC* STDMETHODCALLTYPE GetDesc(D3D12_SHADER_CACHE_SESSION_DESC* out) override { *out = desc_; return out; } #endif private: D3D12_SHADER_CACHE_SESSION_DESC desc_{}; ShaderCacheKey key_{}; ShaderCacheRegistry* registry_ = nullptr; std::shared_ptr store_; }; // A texture the title keeps in its own memory (gfxres notes, section 5): asset and UI textures it reads from its // archives straight into that memory in the console's tiled layout and names only through device slot 70 views // (resource words with the explicit XG Layout, view words, the address), and slot-133 textures it fills itself, // through XG copies into the memory or the pointer Map gives it. The PC GPU cannot sample the console layout, so each // has an image filled from the memory by detiling it with the layout of the slot-70 resource words (XG, // xg_xs_layout.h), and filled again when the bytes change (Device::refresh_title_textures). Textures the GPU writes // (render targets, depth, unordered access) are never filled from memory. The approach is five-star-recomp's // (docs/gpu-resources.md "Textures", GpuTextures.cs / GpuTextureUploader.cs, GPL-3.0-or-later): a registry by // address, refreshed at every slot-70 view and once a frame for textures the title maps. struct TitleTexture { std::uint64_t address = 0; // the GPU address the title names it by std::uint64_t cpu = 0; // where the CPU reads its bytes (title_gpu_views::to_cpu) std::array desc{}; // the console resource words the layout was built from rt::xg_xs::Texture layout{}; // valid when layout_known bool layout_known = false; bool layout_guessed = false; // a slot-133 texture's own description (Layout 0), no slot-70 view yet bool layout_from_xg = false; // the title's XG computer of its shape (title_xg_layout) std::chrono::steady_clock::time_point view_checked{}; // refresh_title_texture's last look (a view's), throttled Resource* resource = nullptr; // Snapshot at registration. A diagnostic census then need not fault in each Resource to count its image memory. VkDeviceSize backing_bytes = 0, unbound_bytes = 0; bool device_local = false; void set_resource(Resource* r) { resource = r; backing_bytes = r->image_backing_bytes(); unbound_bytes = r->unbound_bytes(); device_local = (r->memory_flags() & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) != 0; } bool owned = false; // made here for slot-70 views (a reference is held); else slot 133's bool attachment_4k = false; // slot 133: 3840x2160 color or depth attachment bool gpu_written = false; // render target, depth or unordered access: never filled bool mapped = false; // a slot-133 texture the title mapped: checked before submissions bool stale = false; // changed bytes not uploaded yet (budget, or no host copy then) leonida::TextureReadability memory; // protected by title_texture_mutex std::vector formats; // owned: the image's format and castable view formats std::uint64_t hash = 0; // hash_guarded (sampled) of the bytes the image was last filled from bool hashed = false; // A mapped texture up to 4 MiB is also hashed in full, every few passes: the title writes into it in small // pieces (a glyph in a font cache, measured: Map once, many writes, no Unmap between them) that the sampling hash // misses. Video planes, rewritten whole every frame, are caught by the sampled one first. std::uint64_t full_hash = 0; bool full_hashed = false; bool every_byte() const { return mapped && layout.layout.size <= (4u << 20); } std::uint64_t fills = 0; }; // The layout of a slot-133 texture as the title's own XG computer for its shape says (title_xg_layouts): how the title // lays out what it writes through Map. False when the title made none, or its layout does not fit the image. bool title_xg_layout(const Resource& r, rt::xg_xs::Texture& out, std::array& words) { const D3D12_RESOURCE_DESC& d = r.desc(); std::uint32_t layout = 0; if (!leonida::title_xg_layouts::find({std::uint32_t(d.Dimension), std::uint32_t(d.Format), d.Height, d.DepthOrArraySize, d.MipLevels, d.Width}, layout)) return false; rt::xg_xs::ResourceDesc x{}; x.dimension = std::uint32_t(d.Dimension); x.width = d.Width; x.height = d.Height; x.depth_or_array = d.DepthOrArraySize; x.mips = d.MipLevels; x.format = std::uint32_t(d.Format); x.samples = 1; x.layout = layout; rt::xg_xs::Texture t; if (!rt::xg_xs::build_texture(x, t) || t.layout.mips != d.MipLevels) return false; const leonida::BlockFormat element = r.copy_element(); if (element.bytes != t.format.bytes || element.block != t.format.side) return false; out = t; std::memcpy(words.data(), &x, sizeof(x)); return true; } void DeviceState::title_texture_mapped(const void* resource, std::uint64_t address) { std::lock_guard lock(title_texture_mutex); const auto it = title_textures.find(address); if (it == title_textures.end() || it->second->resource != resource) return; TitleTexture& t = *it->second; t.mapped = true; t.memory.retry(); // The title computes the layout of what it writes right before it maps: take it when no view gave one. if (!t.gpu_written && (t.layout_guessed || !t.layout_known) && title_xg_layout(*static_cast(resource), t.layout, t.desc)) { t.layout_known = true; t.layout_guessed = false; t.layout_from_xg = true; t.hashed = false; } static std::atomic logged{0}; if (logged.fetch_add(1, std::memory_order_relaxed) < 48) { const auto& r = *static_cast(resource); const D3D12_RESOURCE_DESC& d = r.desc(); std::fprintf(stderr, "[rt] d3d12: the title maps slot-133 texture 0x%llx (CPU 0x%llx): dimension %d %llux%ux%u mips %u " "format %d flags 0x%x; layout %s, %s\n", static_cast(address), static_cast(t.cpu), int(d.Dimension), static_cast(d.Width), d.Height, unsigned(d.DepthOrArraySize), unsigned(d.MipLevels), int(d.Format), unsigned(d.Flags), t.gpu_written ? "none (GPU-written)" : !t.layout_known ? "unknown" : t.layout_guessed ? "guessed (no slot-70 view, no XG computer of its shape)" : t.layout_from_xg ? (t.layout.mode == rt::xg_xs::kLinear ? "the title's XG computer's (linear)" : "the title's XG computer's (swizzled)") : "from a slot-70 view", t.fills ? "filled before" : "not filled yet"); } } void DeviceState::title_texture_unmapped(const void* resource, std::uint64_t address) { std::lock_guard lock(title_texture_mutex); const auto it = title_textures.find(address); if (it != title_textures.end() && it->second->resource == resource) { it->second->stale = true; it->second->memory.retry(); } } void DeviceState::title_texture_gone(const void* resource, std::uint64_t address) { if (t_in_title_textures) { // this thread holds title_texture_mutex { // Never held here: ~Resource takes descriptor_mutex itself (image_owner, forget_image). The submit path // reads gpu_placements under descriptor_mutex alone, so the placement must not outlive the resource. std::lock_guard descriptors(descriptor_mutex); gpu_placements.remove(address, resource); } const auto it = title_textures.find(address); if (it != title_textures.end() && it->second->resource == resource) it->second->resource = nullptr; titles_gone.push_back({resource, address}); titles_gone_pending.store(true, std::memory_order_release); return; } std::lock_guard lock(title_texture_mutex); { std::lock_guard descriptors(descriptor_mutex); gpu_placements.remove(address, resource); } const auto it = title_textures.find(address); if (it != title_textures.end() && it->second->resource == resource) title_textures.erase(it); } void DeviceState::drain_titles_gone() { if (!titles_gone_pending.load(std::memory_order_acquire)) return; std::lock_guard lock(title_texture_mutex); for (const auto& [resource, address] : titles_gone) { const auto it = title_textures.find(address); if (it != title_textures.end() && !it->second->resource) title_textures.erase(it); } titles_gone.clear(); titles_gone_pending.store(false, std::memory_order_release); } // The T# of a view: what the shader gets to know about it, in the structure the console's shaders read. // False (with a log) for a view set 0 cannot show yet. // A T# the title wrote into a console descriptor heap itself (DeviceState::fix_console_slots). Translated shaders // find an image by the T#'s exact eight dwords, so one that no Create*View wrote is decoded here, its texture looked // up by the base address it names (Resource::image_address, the only texture addresses the title can know: it // learns them from descriptors the layer wrote), and the image is given a view and a hash-table entry for exactly // these words, as write_image_descriptor does. Every field the layer does not encode (tiling, compression, // performance hints) only makes the key differ, so a title-built T# still finds its texture. Checked against the // texture first: a view of mips, layers or a dimension it lacks would be an invalid Vulkan view. TitleImage bind_title_image(DeviceState& device, const leonida::gfx10::ImageWords& words, const char** why) { namespace g = leonida::gfx10; const auto refuse = [why](const char* reason) { if (why) *why = reason; return TitleImage::refused; }; g::Image image{}; if (!g::decode(words, image)) { if (why) *why = "not a valid T# (swizzle, levels or layers)"; return TitleImage::not_tsharp; } leonida::ResourceId sparse = 0; { std::lock_guard lock(device.descriptor_mutex); if (!device.bindless) return refuse("no bindless set"); if (device.image_entries.count(words)) return TitleImage::known; if (g::has_hardware_volume_uav_slice_offset(words, image)) return refuse("a title-written 3D UAV with a slice offset is not supported"); auto found = device.images_by_address.find(image.address); // Memory of the texture stream pool has two addresses, the CPU view's and the GPU-only alias the title hands // to the GPU (title_gpu_views): a T# naming either finds a texture registered under the other. if (found == device.images_by_address.end()) if (const std::uint64_t other = leonida::title_gpu_views::other_view(image.address)) found = device.images_by_address.find(other); const Resource* owner = found == device.images_by_address.end() ? nullptr : static_cast(found->second); const auto matches = [&](const Resource& r) { return TitleGpuPlacements::matches(image, r.desc()); }; if (!owner || !matches(*owner)) { const auto alias = leonida::title_gpu_views::other_view(image.address); if (auto* candidate = device.gpu_placements.find(image.address, alias, matches)) owner = candidate; } if (!owner) { if (why) *why = "no texture at T# address"; return TitleImage::unknown; } const Resource& r = *owner; image.address = r.image_address(); // release this key with its actual owner const D3D12_RESOURCE_DESC& d = r.desc(); const bool volume = d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D; const bool line = d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D; const bool msaa = d.SampleDesc.Count > 1; const UINT layers = volume ? 1 : d.DepthOrArraySize; const bool type_fits = image.type == g::ImageType::image_3d ? volume : image.type == g::ImageType::image_1d ? line && image.layer_count == 1 : g::multisampled(image.type) ? msaa && !volume && !line && image.samples == d.SampleDesc.Count : !volume && !line && !msaa; if (!r.descriptor_image()) return refuse("the texture has no image"); if (!type_fits) return refuse("T# type or samples do not fit the texture"); if (!msaa && image.first_mip + image.mip_count > d.MipLevels) return refuse("T# names mips the texture lacks"); if (image.type == g::ImageType::cube && !(r.format() && layers >= 6)) return refuse("cube T# on fewer than six layers"); if (!volume && image.first_layer + image.layer_count > layers) return refuse("T# names layers the texture lacks"); const bool storage = (d.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) && !msaa && r.aspects() == VK_IMAGE_ASPECT_COLOR_BIT; if (!device.bind_image_locked(words, image, r.descriptor_image(), r.format(), r.aspects(), storage, r.has_view_format_list(), r.uint_backed())) return refuse("no view for the T#'s format or range"); r.note_shader_view(); // Include descriptors written directly into title heaps. if (r.sparse_image()) sparse = r.id(); } if (sparse) device.context->note_shader_image(sparse); return TitleImage::bound; } bool image_descriptor(const Resource& resource, const TextureView& asked, bool storage, leonida::gfx10::Image& out, VkFormat& view_format, DeviceState::VolumeSlices& slices) { TextureView view = asked; view.format = pc_format(view.format); // the console's D16S8 plane views as D24S8's namespace g = leonida::gfx10; const D3D12_RESOURCE_DESC& desc = resource.desc(); if (storage && (resource.aspects() & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT))) { log_once("storage view not supported for depth-stencil texture:", int(desc.Format)); return false; } // Plane 1 of a depth-stencil texture is its stencil, viewed as X24_TYPELESS_G8_UINT (D24S8) or // X32_TYPELESS_G8X24_UINT (D32S8): eight unsigned bits in G, as D3D12 returns them. The T# is 8_UINT, the // format of the console's separate stencil surface, and bind_image views the stencil aspect for it. const bool stencil = view.plane == 1; if (view.plane > 1 || (stencil && !(resource.aspects() & VK_IMAGE_ASPECT_STENCIL_BIT))) { log_once("no such plane in this texture; plane", int(view.plane)); return false; } // Each stencil view format belongs to its own DXGI family only, as in D3D12: the family is the texture's DXGI // format, not the Vulkan format behind it (a D24 texture may be D32_SFLOAT_S8_UINT underneath). const bool stencil_format_fits = (view.format==xbox_s8_plane && desc.Format==xbox_d16s8) || (view.format == DXGI_FORMAT_X24_TYPELESS_G8_UINT && (desc.Format == DXGI_FORMAT_R24G8_TYPELESS || desc.Format == DXGI_FORMAT_D24_UNORM_S8_UINT)) || (view.format == DXGI_FORMAT_X32_TYPELESS_G8X24_UINT && (desc.Format == DXGI_FORMAT_R32G8X24_TYPELESS || desc.Format == DXGI_FORMAT_D32_FLOAT_S8X24_UINT)); if (stencil && !stencil_format_fits) { log_once("a stencil-plane view needs its texture family's stencil view format; format", int(view.format)); return false; } const bool volume = view.type == g::ImageType::image_3d; const bool line = view.type == g::ImageType::image_1d; const bool line_array = view.type == g::ImageType::image_1d_array; const bool one_d = line || line_array; const bool msaa = g::multisampled(view.type); const auto dimension = volume ? D3D12_RESOURCE_DIMENSION_TEXTURE3D : one_d ? D3D12_RESOURCE_DIMENSION_TEXTURE1D : D3D12_RESOURCE_DIMENSION_TEXTURE2D; if (desc.Dimension != dimension || (msaa ? desc.SampleDesc.Count <= 1 : desc.SampleDesc.Count != 1) || (storage ? msaa : line_array) || (line && view.layer_count != 1)) { log_once("view type incompatible with texture dimension or sample count; view type", int(view.type)); return false; } if (msaa) { // The MS bindings expose typed colour SRVs. An MS view has one mip and can name an array slice range. const Format format = texture_storage_format(desc.Format, false); if (resource.aspects() != VK_IMAGE_ASPECT_COLOR_BIT || format.typeless || (view.format != DXGI_FORMAT_UNKNOWN && view.format != desc.Format)) { log_once("multisample shader view requires a matching typed colour format:", int(desc.Format)); return false; } // Four 3-bit selectors followed by D3D12's always-set bit. if ((view.mapping >> 12) != 1) { log_once("invalid multisample shader view component mapping:", int(view.mapping)); return false; } } const VkFormat resource_format = resource.uint_backed() ? resource.uint_backed() : resource.format(); VkFormat named = resource_format; // A B4G4R4A4 render target stored as an RGBA8 image (no 4444 colour attachment on the device): its T# names // 4_4_4_4 as on the console, and bind_image views the RGBA8 image with the 4444 view's channels. const bool rgba8_4444 = desc.Format == DXGI_FORMAT_B4G4R4A4_UNORM && resource.format() == VK_FORMAT_R8G8B8A8_UNORM; if (rgba8_4444) named = VK_FORMAT_A4R4G4B4_UNORM_PACK16; if (volume && !storage) { const bool compatible = vulkan_format(desc.Format, false).typeless ? desc.Format == DXGI_FORMAT_R8G8B8A8_TYPELESS && (view.format == DXGI_FORMAT_R8G8B8A8_UNORM || view.format == DXGI_FORMAT_R8G8B8A8_UNORM_SRGB) : view.format == DXGI_FORMAT_UNKNOWN || view.format == desc.Format || (view.format == DXGI_FORMAT_R9G9B9E5_SHAREDEXP && resource.lists_castable_format(view.format)); if (!compatible) { log_once("unsupported volume SRV format for this resource:", int(view.format)); return false; } } // Depth and depth-stencil textures can only be viewed through their own family's depth-plane SRV format (or // UNKNOWN on typed depth textures): in Vulkan a depth image's view format must equal the image's own depth // format (VUID-VkImageViewCreateInfo-image-01762 / 09594), so colour view formats such as R16_FLOAT on D16 or // R32_UINT on D32 must be rejected. Each view format belongs to its own DXGI family only, whatever format // backs the texture (a D24 texture may be D32_SFLOAT_S8_UINT underneath). const bool depth_plane = (resource.aspects() & VK_IMAGE_ASPECT_DEPTH_BIT) && !stencil; if (depth_plane) { const bool depth_format_fits = (desc.Format == xbox_d16s8 && (view.format == DXGI_FORMAT_UNKNOWN || view.format == xbox_d16_plane)) || (desc.Format == DXGI_FORMAT_D16_UNORM && (view.format == DXGI_FORMAT_UNKNOWN || view.format == DXGI_FORMAT_R16_UNORM)) || (desc.Format == DXGI_FORMAT_R16_TYPELESS && view.format == DXGI_FORMAT_R16_UNORM) || (desc.Format == DXGI_FORMAT_D32_FLOAT && (view.format == DXGI_FORMAT_UNKNOWN || view.format == DXGI_FORMAT_R32_FLOAT)) || (desc.Format == DXGI_FORMAT_R32_TYPELESS && view.format == DXGI_FORMAT_R32_FLOAT) || (desc.Format == DXGI_FORMAT_D24_UNORM_S8_UINT && (view.format == DXGI_FORMAT_UNKNOWN || view.format == DXGI_FORMAT_R24_UNORM_X8_TYPELESS)) || (desc.Format == DXGI_FORMAT_R24G8_TYPELESS && view.format == DXGI_FORMAT_R24_UNORM_X8_TYPELESS) || (desc.Format == DXGI_FORMAT_D32_FLOAT_S8X24_UINT && (view.format == DXGI_FORMAT_UNKNOWN || view.format == DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS)) || (desc.Format == DXGI_FORMAT_R32G8X24_TYPELESS && view.format == DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS); if (!depth_format_fits) { log_once("incompatible depth shader-resource view format:", int(view.format)); return false; } } const bool new_uav = storage && (volume || one_d); if (new_uav) { const DXGI_FORMAT dxgi = view.format == DXGI_FORMAT_UNKNOWN ? desc.Format : view.format; const Format format = texture_storage_format(dxgi, false); if (format.typeless || format.aspects != VK_IMAGE_ASPECT_COLOR_BIT || !uav_format_compatible(desc.Format, dxgi)) { log_once("unordered-access view format is not compatible with the resource:", dxgi); return false; } named = format.format; } else if (view.format != DXGI_FORMAT_UNKNOWN && !stencil && !depth_plane) { if ((view.format == DXGI_FORMAT_A8_UNORM) != (desc.Format == DXGI_FORMAT_A8_UNORM)) { log_once("incompatible typed A8 view format:", int(view.format)); return false; } // Only a castable-format list that names the view's format lets a view cross the two families, as WARP and // AMD's D3D12 driver accept (relaxed casting). if (alpha_unused(view.format) != alpha_unused(desc.Format) && !resource.lists_castable_format(view.format)) { log_once("view format from another typeless family (B8G8R8X8 and B8G8R8A8):", int(view.format)); return false; } // A 32-bit texture that lists R9G9B9E5 as castable (a slot-133 R32 unordered-access target the title packs // E5 values into, create_at_host_address) is viewed as E5B9G9R9. if ((view.format == DXGI_FORMAT_R9G9B9E5_SHAREDEXP) != (desc.Format == DXGI_FORMAT_R9G9B9E5_SHAREDEXP) && !(view.format == DXGI_FORMAT_R9G9B9E5_SHAREDEXP && resource.lists_castable_format(view.format))) { log_once("incompatible R9G9B9E5 view format:", int(view.format)); return false; } // An A8 render target is viewed in its own A8 format (Format::a8_as_alpha), other A8 textures through R8. named = resource.a8_as_alpha() ? resource_format : texture_storage_format(view.format, false).format; if (g::is_depth_stencil_format(named)) { log_once("depth-stencil view format on a colour texture:", int(view.format)); return false; } } // A 96-bit texture takes views of its own family only (and a four-channel texture none of it), and only the // TYPELESS one is cast between FLOAT, UINT and SINT. Its T# names the three-channel format (alpha reads as // one), but the format list and Vulkan view use the RGBA32 format that backs it. const bool rgb96 = resource.rgb96(); if (!stencil && !depth_plane) { const bool view_rgb96 = view.format != DXGI_FORMAT_UNKNOWN ? vulkan_format(view.format, false).rgb96 : rgb96; if (view_rgb96 != rgb96 || (rgb96 && desc.Format != DXGI_FORMAT_R32G32B32_TYPELESS && named != resource.format())) { log_once("view format outside the texture's 96-bit family:", int(view.format)); return false; } } if (named == VK_FORMAT_UNDEFINED || (rgba8_4444 ? named != VK_FORMAT_A4R4G4B4_UNORM_PACK16 : !resource.allows_view_format(named))) { log_once("view format not in the resource's castable list:", int(view.format)); return false; } const std::uint32_t code = stencil ? g::stencil_format : g::format_from_vulkan(rgb96 ? rgb96_named_format(named) : named); view_format = VK_FORMAT_UNDEFINED; if (stencil) { view_format = resource.format(); } else if (code && (new_uav || rgb96)) { view_format = rgb96 ? rgb96_view_format(resource.format(), code) : named; } else if (code && rgba8_4444) { view_format = resource.format(); } else if (code) { view_format = g::vulkan_view_format(resource_format, code, resource.has_view_format_list()); } if (!storage && resource.rgba4_render_backing() && (view.format == DXGI_FORMAT_B4G4R4A4_UNORM || view.format == DXGI_FORMAT_UNKNOWN)) view_format = resource.format(); if (view_format == VK_FORMAT_UNDEFINED || !resource.allows_view_format(view_format)) { log_once("view format not supported for this texture:", int(view.format)); return false; } if (view.first_mip >= desc.MipLevels) { log_once("view starts past the texture's mips; first mip", int(view.first_mip)); return false; } // SRVs address an entire volume; only a UAV descriptor can specify a W range within its mip. const UINT layers = volume ? (storage ? std::max(1u, UINT(desc.DepthOrArraySize) >> view.first_mip) : 1u) : desc.DepthOrArraySize; if (view.first_layer >= layers) { log_once("view starts past the texture's mips or layers; first mip", int(view.first_mip)); return false; } const UINT remaining = layers - view.first_layer; const UINT layer_count = view.layer_count == ~0u ? remaining : view.layer_count; if (new_uav && (!layer_count || layer_count > remaining)) { log_once("unordered-access view slice count is outside the selected mip:", int(view.layer_count)); return false; } if (msaa && layer_count > remaining) { log_once("multisample shader view ends past the texture array; layers", int(view.layer_count)); return false; } out = {}; out.address = resource.image_address(); out.format = code; out.type = view.type; out.width = std::uint32_t(desc.Width); out.height = desc.Height; out.depth = volume ? desc.DepthOrArraySize : 1; out.samples = desc.SampleDesc.Count; out.first_mip = view.first_mip; out.mip_count = std::min(view.mip_count, desc.MipLevels - view.first_mip); if (volume) { if (storage && (view.first_layer != 0 || layer_count != layers)) slices = {view.first_layer, layer_count}; } else { out.first_layer = view.first_layer; out.layer_count = std::min(layer_count, remaining); } if (view.type == g::ImageType::cube) out.layer_count -= out.layer_count % 6; // whole cubes out.resource_mips = desc.MipLevels; out.min_lod = view.min_lod; if (!out.mip_count || !out.layer_count) { log_once("view of no mips or no layers; type", int(view.type)); return false; } // D3D12's component mapping picks, for each of R, G, B, A, a channel of the format or a constant; the T# // says the same about the hardware's channels, which the format places. // A stencil view's format has its eight bits in G and no R, B or A of its own (0, 0, 1 when read). // B8G8R8X8 has no alpha: a view in its family reads 1, and a B8G8R8A8 view of a B8G8R8X8 texture (through a // castable-format list) the stored byte. The view's format decides, as on WARP and AMD's D3D12 driver. // The T#'s format code is the same for both channel orders of a colour format (R8G8B8A8 and B8G8R8A8 are one // 8_8_8_8 code), and the image view keeps the image's format; a castable-format list may still ask for the other // order, so then the view's own format places the channels. Depth images keep their own format's channels. const bool other_order = view.format != DXGI_FORMAT_UNKNOWN && !stencil && !depth_plane && !rgb96 && named != view_format && !g::is_depth_stencil_format(view_format); const VkFormat channels_format = rgb96 ? rgb96_named_format(view_format) : other_order ? named : view_format; g::Swizzle channels = g::format_swizzle(channels_format); if (stencil) channels = {g::select_zero, g::select_x, g::select_zero, g::select_one}; else if (desc.Format == DXGI_FORMAT_A8_UNORM) channels = {g::select_zero, g::select_zero, g::select_zero, g::select_x}; else if (alpha_unused(view.format != DXGI_FORMAT_UNKNOWN ? view.format : desc.Format)) channels[3] = g::select_one; for (UINT i = 0; i < 4; ++i) { const UINT from = D3D12_DECODE_SHADER_4_COMPONENT_MAPPING(i, view.mapping); if (msaa && from > D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_1) { log_once("invalid multisample shader view component selector:", from); return false; } out.swizzle[i] = from < 4 ? channels[from] : from == D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_0 ? g::select_zero : g::select_one; } return true; } // The S# of a D3D12 sampler. leonida::gfx10::Sampler sampler_descriptor(const D3D12_SAMPLER_DESC& desc, DeviceState* state = nullptr) { namespace g = leonida::gfx10; const auto address = [](D3D12_TEXTURE_ADDRESS_MODE mode) { switch (mode) { case D3D12_TEXTURE_ADDRESS_MODE_MIRROR: return g::AddressMode::mirror; case D3D12_TEXTURE_ADDRESS_MODE_CLAMP: return g::AddressMode::clamp_last_texel; case D3D12_TEXTURE_ADDRESS_MODE_BORDER: return g::AddressMode::clamp_border; case D3D12_TEXTURE_ADDRESS_MODE_MIRROR_ONCE: return g::AddressMode::mirror_once_last_texel; default: return g::AddressMode::wrap; } }; const bool anisotropic = D3D12_DECODE_IS_ANISOTROPIC_FILTER(desc.Filter); const auto filter = [&](D3D12_FILTER_TYPE type) { if (anisotropic) return type == D3D12_FILTER_TYPE_LINEAR ? g::Filter::aniso_bilinear : g::Filter::aniso_point; return type == D3D12_FILTER_TYPE_LINEAR ? g::Filter::bilinear : g::Filter::point; }; g::Sampler out{}; out.address_u = address(desc.AddressU); out.address_v = address(desc.AddressV); out.address_w = address(desc.AddressW); out.mag_filter = filter(D3D12_DECODE_MAG_FILTER(desc.Filter)); out.min_filter = filter(D3D12_DECODE_MIN_FILTER(desc.Filter)); out.mip_filter = D3D12_DECODE_MIP_FILTER(desc.Filter) == D3D12_FILTER_TYPE_LINEAR ? g::MipFilter::linear : g::MipFilter::point; out.max_anisotropy = anisotropic ? std::clamp(desc.MaxAnisotropy, 1, 16) : 1; const D3D12_FILTER_REDUCTION_TYPE reduction = D3D12_DECODE_FILTER_REDUCTION(desc.Filter); // D3D12's comparison functions are 1 (NEVER) to 8 (ALWAYS); the S#'s are 0 to 7 in the same order. if (reduction == D3D12_FILTER_REDUCTION_TYPE_COMPARISON && desc.ComparisonFunc >= D3D12_COMPARISON_FUNC_NEVER) out.compare = g::CompareFunction(desc.ComparisonFunc - D3D12_COMPARISON_FUNC_NEVER); out.compare_never = reduction == D3D12_FILTER_REDUCTION_TYPE_COMPARISON && desc.ComparisonFunc == D3D12_COMPARISON_FUNC_NEVER; if (reduction == D3D12_FILTER_REDUCTION_TYPE_MINIMUM) out.filter_mode = g::FilterMode::minimum; if (reduction == D3D12_FILTER_REDUCTION_TYPE_MAXIMUM) out.filter_mode = g::FilterMode::maximum; out.min_lod = desc.MinLOD; out.max_lod = desc.MaxLOD; out.lod_bias = desc.MipLODBias; const FLOAT* border = desc.BorderColor; const bool black = border[0] == 0 && border[1] == 0 && border[2] == 0; if (black && border[3] == 0) { out.border_color = g::BorderColor::transparent_black; } else if (black && border[3] == 1) { out.border_color = g::BorderColor::opaque_black; } else if (border[0] == 1 && border[1] == 1 && border[2] == 1 && border[3] == 1) { out.border_color = g::BorderColor::opaque_white; } else { out.border_color = g::BorderColor::table; if (state) out.border_color_index = state->register_border_color(false, border); } return out; } // A query heap: one VkQueryPool, registered with the context so that lists can resolve it by ID // (docs/d3d12_vulkan.md section 4.6). Occlusion heaps hold both OCCLUSION and BINARY_OCCLUSION queries; timestamp // and copy-queue timestamp heaps are timestamp pools; pipeline-statistics heaps count all eleven Vulkan // statistics, whose result order is the field order of D3D12_QUERY_DATA_PIPELINE_STATISTICS. Stream-output // statistics heaps have no pool: without stream output every such query is zero. class QueryHeap final : public Child { public: // {6e2b9a41-d83c-4f17-b5e9-0a7c3d1f8b62} static constexpr GUID kTag{0x6e2b9a41, 0xd83c, 0x4f17, {0xb5, 0xe9, 0x0a, 0x7c, 0x3d, 0x1f, 0x8b, 0x62}}; explicit QueryHeap(DeviceState& device) : device_(device) {} ~QueryHeap() override { if (!registered_) return; device_.context->remove_query_pool(id()); if (pool_) device_.context->vk.vkDestroyQueryPool(device_.info.device, pool_, nullptr); } leonida::QueryHeapId id() const { return query_heap_id(this); } HRESULT create(const D3D12_QUERY_HEAP_DESC& desc) { namespace h = leonida::d3d12_query_heap; auto& vk = device_.context->vk; if (!vk.vkCreateQueryPool || !vk.vkDestroyQueryPool) return E_NOTIMPL; VkQueryPoolCreateInfo info{VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO}; info.queryCount = desc.Count; switch (desc.Type) { case h::occlusion: info.queryType = VK_QUERY_TYPE_OCCLUSION; break; case h::timestamp: case h::copy_queue_timestamp: { const bool supported = desc.Type == D3D12_QUERY_HEAP_TYPE_COPY_QUEUE_TIMESTAMP ? device_.copy_timestamps_supported() : device_.context->timestamp_period() > 0; if (!supported) { log_once("timestamp query heap: the queue writes no timestamps; type", desc.Type); return E_NOTIMPL; } info.queryType = VK_QUERY_TYPE_TIMESTAMP; break; } case h::so_statistics: // D3D-302: with VK_EXT_transform_feedback enabled, an SO_STATISTICS heap is a real transform-feedback // pool whose queries begin/end on a stream (vkCmdBeginQueryIndexedEXT); a resolve copies 16 bytes per // query (NumPrimitivesWritten, PrimitivesStorageNeeded), in the same order. StreamOutput PSOs are still // refused and SOSetTargets is still not implemented, so no primitive reaches a stream yet and every // query counts 0. The pool needs the transformFeedbackQueries property and at least one stream; without // them (or without the feature) the heap is made without a pool and every query resolves to zero. if (!device_.info.transform_feedback || !device_.info.transform_feedback_queries || !device_.info.max_transform_feedback_streams) return register_pool(desc); info.queryType = VK_QUERY_TYPE_TRANSFORM_FEEDBACK_STREAM_EXT; break; case h::pipeline_statistics: if (!device_.info.pipeline_statistics_query) { log_once("pipeline-statistics query heap: pipelineStatisticsQuery not enabled; type", desc.Type); return E_NOTIMPL; } info.queryType = VK_QUERY_TYPE_PIPELINE_STATISTICS; info.pipelineStatistics = kPipelineStatistics; break; default: // Video decode and mesh-shader statistics (PIPELINE_STATISTICS1) have no path yet. log_once("query heap type not supported:", desc.Type); return E_NOTIMPL; } if (vk.vkCreateQueryPool(device_.info.device, &info, nullptr, &pool_) != VK_SUCCESS) { pool_ = VK_NULL_HANDLE; return E_OUTOFMEMORY; } return register_pool(desc); } private: HRESULT register_pool(const D3D12_QUERY_HEAP_DESC& desc) { leonida::QueryPool pool{}; pool.pool = pool_; pool.heap_type = desc.Type; pool.count = desc.Count; pool.precise = device_.info.occlusion_query_precise; pool.ended.assign(desc.Count, false); // D3D-302: a real transform-feedback pool queries streams below maxTransformFeedbackStreams; D3D12 has four. if (pool_ && desc.Type == leonida::d3d12_query_heap::so_statistics) pool.streams = std::min(4, device_.info.max_transform_feedback_streams); device_.context->add_query_pool(id(), pool); registered_ = true; return S_OK; } // VK_QUERY_PIPELINE_STATISTIC_INPUT_ASSEMBLY_VERTICES_BIT through COMPUTE_SHADER_INVOCATIONS_BIT (0x1-0x400): // IAVertices, IAPrimitives, VSInvocations, GSInvocations, GSPrimitives, CInvocations, CPrimitives, // PSInvocations, HSInvocations (patches), DSInvocations, CSInvocations. static constexpr VkQueryPipelineStatisticFlags kPipelineStatistics = 0x7ff; static_assert(sizeof(D3D12_QUERY_DATA_PIPELINE_STATISTICS) == 11 * sizeof(UINT64)); DeviceState& device_; VkQueryPool pool_ = VK_NULL_HANDLE; // null for a stream-output heap (no Vulkan query behind it) bool registered_ = false; // added to the context, so removed from it on destruction }; // The live devices whose session pipeline cache an ending process writes (save_pipeline_caches_at_exit). A title // never releases its device, so ~Device, the only other writer, does not run in a real boot: without this, a run that // ends (normally, at a console close or in a crash) keeps none of what it compiled. Timed, so a crash handler that // finds it held gives up instead of hanging the process. std::timed_mutex exit_cache_mutex; std::vector exit_cache_devices; std::atomic exit_cache_saved{false}; // The Vulkan objects create_vulkan_device_standalone made, destroyed with the device. struct OwnedRuntime { PFN_vkDestroyDevice destroy_device = nullptr; PFN_vkDestroyInstance destroy_instance = nullptr; VkDevice device = VK_NULL_HANDLE; VkInstance instance = VK_NULL_HANDLE; }; class Device final : public Object { public: // {c58e1d27-3a96-4b4f-9e72-6d0a8b5f3c61} static constexpr GUID kTag{0xc58e1d27, 0x3a96, 0x4b4f, {0x9e, 0x72, 0x6d, 0x0a, 0x8b, 0x5f, 0x3c, 0x61}}; explicit Device(const VulkanDeviceInfo& info) { // Every Vulkan device serves Xbox device slot 133, whichever entry made it: create_vulkan_device and the // standalone device gta6rt --run uses both come through here (found in review: registering only in // create_vulkan_device left the retail path without it). rt::d3d12_xs::set_placed_at_va_handler(&create_buffer_at_host_address); rt::d3d12_xs::set_console_descriptor_heap_handler(&rt::d3d12::create_console_descriptor_heap); // A queued pipeline build holds its PipelineState, which holds the device: a reference count read while the // worker still has a warm-up to run is one too high. The proxy's count waits for the pool. rt::d3d12_xs::set_reference_settler([] { PipelineCompiler::instance().wait_idle(); }); state_.info = info; { std::lock_guard lock(exit_cache_mutex); exit_cache_devices.push_back(&state_); } queue_users_.resize(info.command_queues.size(), 0); compute_users_.resize(info.compute_queues.size(), 0); copy_users_.resize(info.copy_queues.size(), 0); for (std::uint32_t f : {info.queue_family, info.compute_family, info.copy_family}) if (f != UINT32_MAX && std::find(state_.families.begin(), state_.families.end(), f) == state_.families.end()) state_.families.push_back(f); // LEONIDA_AFTERMATH: every function table loaded through it (the context's, the helpers' own) creates its // shader modules through the wrapper that maps Aftermath shader hashes to names (src/vulkan_aftermath.h). const auto get_device = leonida::aftermath::wrap_get_device_proc_addr(reinterpret_cast( info.get_instance_proc(info.instance, "vkGetDeviceProcAddr"))); state_.format_properties = reinterpret_cast( info.get_instance_proc(info.instance, "vkGetPhysicalDeviceFormatProperties")); state_.format_properties2 = reinterpret_cast( info.get_instance_proc(info.instance, "vkGetPhysicalDeviceFormatProperties2")); state_.image_format_properties = reinterpret_cast( info.get_instance_proc(info.instance, "vkGetPhysicalDeviceImageFormatProperties")); state_.image_format_properties2 = reinterpret_cast( info.get_instance_proc(info.instance, "vkGetPhysicalDeviceImageFormatProperties2")); if (!state_.image_format_properties2) { state_.image_format_properties2 = reinterpret_cast( info.get_instance_proc(info.instance, "vkGetPhysicalDeviceImageFormatProperties2KHR")); } const auto memory_properties = reinterpret_cast( info.get_instance_proc(info.instance, "vkGetPhysicalDeviceMemoryProperties")); const auto device_properties = reinterpret_cast( info.get_instance_proc(info.instance, "vkGetPhysicalDeviceProperties")); const auto queue_families = reinterpret_cast( info.get_instance_proc(info.instance, "vkGetPhysicalDeviceQueueFamilyProperties")); if (!get_device || !state_.format_properties || !state_.image_format_properties || !memory_properties || !device_properties || !queue_families) return; state_.r9g9b9e5_uav_emulated = state_.probe_uint_backed_uav(VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, VK_FORMAT_R32_UINT); state_.b5g5r5a1_uav_emulated = state_.probe_uint_backed_uav(VK_FORMAT_A1R5G5B5_UNORM_PACK16, VK_FORMAT_R16_UINT); state_.rgba8_srgb_uav_emulated = state_.probe_uint_backed_uav(VK_FORMAT_R8G8B8A8_SRGB, VK_FORMAT_R8G8B8A8_UNORM); state_.bgra8_srgb_uav_emulated = state_.probe_uint_backed_uav(VK_FORMAT_B8G8R8A8_SRGB, VK_FORMAT_B8G8R8A8_UNORM); { // The console's D16S8 family (pc_format): as D24S8 where the GPU has that format, as itself where not. const char* asked = std::getenv("LEONIDA_CONSOLE_D16S8"); const bool d24 = state_.depth_usable(VK_FORMAT_D24_UNORM_S8_UINT); const bool native = asked && std::strcmp(asked, "native") == 0 ? true : asked && std::strcmp(asked, "d24") == 0 ? false : !d24; g_console_d16s8_native.store(native, std::memory_order_relaxed); static std::atomic logged{false}; if (!logged.exchange(true, std::memory_order_relaxed)) std::fprintf(stderr, "[rt] d3d12: console D16S8 textures are %s (D24_UNORM_S8_UINT attachments: %s, " "D16_UNORM_S8_UINT: %s%s)\n", native ? "kept as D16+S8" : "made as D24S8", d24 ? "yes" : "no", state_.depth_usable(VK_FORMAT_D16_UNORM_S8_UINT) ? "yes" : "no", asked ? ", LEONIDA_CONSOLE_D16S8 set" : ""); } if (console_format_stand_ins()) { state_.r9g9b9e5_target_stand_in = !state_.color_attachment_usable(VK_FORMAT_E5B9G9R9_UFLOAT_PACK32) && state_.color_attachment_usable(VK_FORMAT_B10G11R11_UFLOAT_PACK32) && state_.storage_usable(VK_FORMAT_B10G11R11_UFLOAT_PACK32) && state_.sampled_usable(VK_FORMAT_B10G11R11_UFLOAT_PACK32); std::fprintf(stderr, "[rt] d3d12: console format stand-ins: R9G9B9E5 target as R11G11B10F %d, sRGB UAV as UNORM " "rgba %d bgra %d\n", int(state_.r9g9b9e5_target_stand_in), int(state_.rgba8_srgb_uav_emulated), int(state_.bgra8_srgb_uav_emulated)); } memory_properties(info.physical, &state_.memory); { char text[4] = {}; size_t length = 0; const bool sysmem = getenv_s(&length, text, "LEONIDA_UPLOAD_SYSMEM") == 0 && length > 1 && text[0] != '0'; state_.upload_in_vram = leonida::resizable_bar(state_.memory) && !sysmem; std::fprintf(stderr, "[rt] d3d12: upload heaps in %s\n", state_.upload_in_vram ? "VRAM (DEVICE_LOCAL | HOST_VISIBLE, Resizable BAR)" : sysmem ? "system memory (LEONIDA_UPLOAD_SYSMEM)" : "system memory (no Resizable BAR)"); } if (get_device) state_.bound_image_requirements = reinterpret_cast( get_device(info.device, "vkGetImageMemoryRequirements2")); for (const char* name : {"vkGetDeviceImageMemoryRequirements", "vkGetDeviceImageMemoryRequirementsKHR"}) if (!state_.image_requirements) state_.image_requirements = reinterpret_cast(get_device(info.device, name)); if (info.physical && info.get_instance_proc) { const auto get_props = reinterpret_cast( info.get_instance_proc(info.instance, "vkGetPhysicalDeviceProperties")); if (get_props) { VkPhysicalDeviceProperties props{}; get_props(info.physical, &props); state_.pso_identity.vendor = props.vendorID; state_.pso_identity.device = props.deviceID; state_.pso_identity.driver = props.driverVersion; std::memcpy(state_.pso_identity.cache_uuid, props.pipelineCacheUUID, VK_UUID_SIZE); if (state_.info.max_push_constants_size == 0) { state_.info.max_push_constants_size = props.limits.maxPushConstantsSize; state_.info.push_constants_need_fallback = (state_.info.max_push_constants_size < 144); } // The counts D3D12 offers with no outputs are the target-independent-rasterization ones: 1, 4, 8 // and 16 (ForcedSampleCount is 0, 1, 4, 8 or 16; DirectX-Specs VulkanOn12.md "Sample-frequency MSAA // with no render targets bound": a driver reports at least 0b11101). 2x is not one of them, though // framebufferNoAttachmentsSampleCounts has it on every GPU here; reporting it would offer a count the // PC runtime refuses (its hosts report 0x1d). constexpr VkSampleCountFlags kD3D12SampleCounts = VK_SAMPLE_COUNT_1_BIT | VK_SAMPLE_COUNT_4_BIT | VK_SAMPLE_COUNT_8_BIT | VK_SAMPLE_COUNT_16_BIT; state_.no_output_sample_counts = static_cast(props.limits.framebufferNoAttachmentsSampleCounts & kD3D12SampleCounts); state_.f16_half_top_location = leonida::f16_half_top_location( props.limits.maxVertexOutputComponents, props.limits.maxFragmentInputComponents); } if (const auto get_props2 = reinterpret_cast( info.get_instance_proc(info.instance, "vkGetPhysicalDeviceProperties2"))) { VkPhysicalDeviceDepthStencilResolveProperties resolve{ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DEPTH_STENCIL_RESOLVE_PROPERTIES}; VkPhysicalDeviceConservativeRasterizationPropertiesEXT conservative{ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CONSERVATIVE_RASTERIZATION_PROPERTIES_EXT}; if (info.conservative_rasterization) resolve.pNext = &conservative; VkPhysicalDeviceProperties2 props{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &resolve}; get_props2(info.physical, &props); state_.conservative_raster_tier = D3D12_CONSERVATIVE_RASTERIZATION_TIER(leonida::conservative_raster::tier( info.conservative_rasterization, props.properties.limits.subPixelPrecisionBits, conservative.primitiveOverestimationSize, conservative.degenerateTrianglesRasterized == VK_TRUE, conservative.fullyCoveredFragmentShaderInputVariable == VK_TRUE, info.inner_coverage_abi)); state_.conservative_post_depth_coverage = conservative.conservativeRasterizationPostDepthCoverage == VK_TRUE; state_.depth_resolve_modes = resolve.supportedDepthResolveModes; state_.stencil_resolve_modes = resolve.supportedStencilResolveModes; const leonida::ArenaLimits limits = leonida::query_arena_limits(get_props2, info.physical); if (!state_.info.max_buffer_size) state_.info.max_buffer_size = limits.max_buffer_size; if (!state_.info.max_memory_allocation_size) state_.info.max_memory_allocation_size = limits.max_allocation_size; } } const leonida::GraphicsIndirectCapabilities indirect{ .first_instance = info.draw_indirect_first_instance, .multiple = info.multi_draw_indirect, .count_buffer = info.draw_indirect_count_enabled, .max_count = info.max_draw_indirect_count, .robust_index_view = info.robust_index_view, .require_clamp = leonida::indirect_clamp_enabled()}; state_.context = std::make_unique(get_device, info.device, info.separate_depth_stencil_layouts, info.conditional_rendering, info.ray_tracing, info.xdxr_acceleration_structures && info.buffer_device_address, indirect); if (info.device_fault_diagnostics) { state_.context->configure_device_fault(get_device, {info.device_fault_info, info.device_checkpoints, info.device_diagnostics_config}); state_.context->add_diagnostic_queue(info.queue); for (auto queue : info.command_queues) state_.context->add_diagnostic_queue(queue); for (auto queue : info.compute_queues) state_.context->add_diagnostic_queue(queue); for (auto queue : info.copy_queues) state_.context->add_diagnostic_queue(queue); } leonida::mem_probe::install(state_.context->vk); // LOCAL DIAGNOSTIC: before anything allocates if (info.device_fault_diagnostics && rt::compute_probe::enabled()) { state_.context->set_input_probe([this](auto lists, auto sequence, auto queue) { rt::compute_probe::inspect(state_, lists, sequence, queue); }); if (auto* fault = state_.context->device_fault()) fault->set_lost_hook([this] { rt::compute_probe::recheck(state_); }); } state_.context->set_before_execute([this] { namespace phases = leonida::submit_phases; // LEONIDA_REFRESH_PER_FRAME (for runs that only need the title to go on): 1 = the slot-133 shadows, title // windows and geometry copies are brought up to date only by the first submission after each present, // not by every one of the ~24 submissions of a title frame (speed-18: ~30 ms of them a submission, one // title frame a second); 2 = the console heaps too. A GPU read of them is then up to a frame behind the // title's writes: wrong pixels, nothing the title waits for (the copies are one way). 0 (default): all // at every submission, as before. static const int per_frame = [] { const char* v = std::getenv("LEONIDA_REFRESH_PER_FRAME"); return v && *v ? std::atoi(v) : 0; }(); bool full = true; if (per_frame) { const std::uint64_t serial = phases::totals().present_serial.load(std::memory_order_relaxed); full = refreshed_present_.exchange(serial, std::memory_order_relaxed) != serial; } state_.refresh_shadows(full || per_frame < 2, full); // LEONIDA_GEOMETRY_ASYNC=1 (for runs that only need the title to go on): the geometry copies are brought // up to date on a worker of ours, started here and not waited for, instead of on the title's GPU submit // thread (speed-27: 230-330 ms a refresh after the load, a VirtualQuery and VirtualProtect per written // tile under Wine). A draw may then read a copy the worker is still writing: wrong vertices for a frame. static const bool geometry_async = [] { const char* v = std::getenv("LEONIDA_GEOMETRY_ASYNC"); return v && std::strcmp(v, "1") == 0; }(); if (full && geometry_async) { kick_geometry_refresh(); } else if (full) { const phases::Scope timed(phases::geometry); state_.geometry.refresh(DeviceState::copy_geometry); } const phases::Scope timed(phases::textures); refresh_title_textures(); }); { char text[16] = {}; size_t length = 0; if (getenv_s(&length, text, "LEONIDA_TITLE_WINDOWS_MB") == 0 && length > 1) state_.title_window_cap = std::strtoull(text, nullptr, 10) << 20; } leonida::title_va_aliases().set_buffer_maker(this, [](void* device, std::uint64_t va, std::uint64_t bytes) { static_cast*>(device)->make_title_buffer(va, bytes); }); { char text[32] = {}; size_t length = 0; const bool present = getenv_s(&length, text, "LEONIDA_PIPELINE_THREADS") == 0 && length > 1; const auto threads = leonida::pipeline_threads(present ? text : "", std::thread::hardware_concurrency()); if (!threads.valid) std::fprintf(stderr, "[rt] d3d12: LEONIDA_PIPELINE_THREADS=%s is not a number; using %u\n", text, threads.count); if (threads.count) state_.context->set_pipeline_workers(std::make_unique(threads.count)); if (big_compiles() == BigCompiles::budget) state_.context->set_large_compiles( [] { return big_compile_gate().budget(); }, [] { return std::make_shared(big_compile_gate()); }); } leonida::title_va_aliases().set_hooks( &state_, [](void* device, std::uint64_t va, std::uint64_t bytes, std::uint64_t& out) { return static_cast(device)->resolve_title_memory(va, bytes, out); }, [](void* device, std::uint64_t table, std::uint32_t descriptors) { static_cast(device)->scan_title_table(table, descriptors); }); state_.image_memory = std::make_unique( [device = info.device, make = state_.context->vk.vkAllocateMemory](std::uint32_t type, std::uint64_t bytes) { VkMemoryAllocateInfo block{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; block.allocationSize = bytes; block.memoryTypeIndex = type; VkDeviceMemory out = VK_NULL_HANDLE; return make(device, &block, nullptr, &out) == VK_SUCCESS ? out : VkDeviceMemory(VK_NULL_HANDLE); }, [device = info.device, free = state_.context->vk.vkFreeMemory](VkDeviceMemory block) { free(device, block, nullptr); }); state_.context->mesh_queries = info.mesh_shader_queries; state_.context->set_cpu_texture_publisher([this]{return state_.publish_mapped_textures();}); state_.context->set_sample_table_resolver([this](std::uint64_t address, std::uint32_t slots) { return state_.materialize_table(address, slots); }); state_.context->set_table_scanner([this](std::uint64_t table, std::uint32_t descriptors) { state_.scan_title_table(table, descriptors); }); state_.context->set_graphics_family(info.queue_family); #ifdef VK_KHR_MAINTENANCE_10_EXTENSION_NAME if (info.maintenance10 && info.physical) { const auto get_props = reinterpret_cast( info.get_instance_proc(info.instance, "vkGetPhysicalDeviceFormatProperties2")); if (get_props) { const auto aspects = [&](VkFormat format) { VkFormatProperties3 props{VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_3}; VkFormatProperties2 query{VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_2, &props}; get_props(info.physical, format, &query); VkImageAspectFlags mask = 0; if (props.optimalTilingFeatures & VK_FORMAT_FEATURE_2_DEPTH_COPY_ON_COMPUTE_QUEUE_BIT_KHR) mask |= VK_IMAGE_ASPECT_DEPTH_BIT; if (props.optimalTilingFeatures & VK_FORMAT_FEATURE_2_STENCIL_COPY_ON_COMPUTE_QUEUE_BIT_KHR) mask |= VK_IMAGE_ASPECT_STENCIL_BIT; return mask; }; state_.context->set_compute_copy_aspects( [d16 = aspects(VK_FORMAT_D16_UNORM), ds = aspects(VK_FORMAT_D32_SFLOAT_S8_UINT)](VkFormat format) { if (format == VK_FORMAT_D16_UNORM) return d16; if (format == VK_FORMAT_D32_SFLOAT_S8_UINT) return ds; return VkImageAspectFlags{}; }); } } #endif state_.context->set_depth_range_unrestricted(info.depth_range_unrestricted); // The console's value writes (list slots 71 and 72) at an arena offset land in the arena // (src/value_write_sink.h): the list values' pump and the GPU-label path ask this device before any host store. leonida::value_sink::set_arena( [](void* device, std::uint64_t address, const void* bytes, unsigned size) { return static_cast(device)->write_arena_value(address, bytes, size); }, &state_); if (info.physical && state_.format_properties) { state_.context->set_color_attachment_format( [physical = info.physical, get_props = state_.format_properties](VkFormat format) { VkFormatProperties properties{}; get_props(physical, format, &properties); return (properties.optimalTilingFeatures & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT) != 0; }); } if (info.buffer_device_address && state_.context->loaded() && !create_arena()) std::fprintf(stderr, "[rt] d3d12: the GPU address arena could not be created\n"); { // LOCAL DIAGNOSTIC: mem probe (LEONIDA_MEM_PROBE=) leonida::mem_probe::DeviceFacts facts; facts.memory = state_.memory; facts.title_ranges = [] { return leonida::title_va_aliases().title_memory_ranges(); }; facts.describe = [this] { state_.geometry.report(); DeviceState& d = state_; // The driver serializes the whole cache to answer the size: only on request (LEONIDA_MEM_PROBE_CACHE=1). std::size_t cache = 0; static const bool ask_cache = [] { wchar_t value[2]{}; return GetEnvironmentVariableW(L"LEONIDA_MEM_PROBE_CACHE", value, 2) == 1 && value[0] == L'1'; }(); const VkPipelineCache handle = d.pipeline_cache_handle; if (ask_cache && handle && d.context->vk.vkGetPipelineCacheData) d.context->vk.vkGetPipelineCacheData(d.info.device, handle, &cache, nullptr); std::uint64_t title = 0, title_ranges = 0; for (const auto& [begin, end] : leonida::title_va_aliases().title_memory_ranges()) { title += end - begin; ++title_ranges; } std::uint64_t shadows = 0; { std::lock_guard lock(d.shadow_mutex); shadows = d.shadows.size(); } VkDeviceSize in_use = 0, peak = 0, use[4] = {}; { std::lock_guard lock(d.arena.mutex); in_use = d.arena.in_use; peak = d.arena.peak_end; for (int i = 0; i < 4; ++i) use[i] = d.arena.use_in_use[i]; } char text[512]; std::snprintf(text, sizeof text, "pipeline cache %.0f MiB; arena %.0f MiB (type %u), in use %.0f MiB (buffer %.0f, " "descriptor heap %.0f, shader %.0f, heap %.0f), peak end %.0f MiB; title memory %llu " "ranges %.0f MiB reserved/committed VA; shadows %llu; fsdraw pipeline notes %zu", leonida::mem_probe::mib(cache), leonida::mem_probe::mib(d.arena.size), d.arena.memory_type, leonida::mem_probe::mib(in_use), leonida::mem_probe::mib(use[0]), leonida::mem_probe::mib(use[1]), leonida::mem_probe::mib(use[2]), leonida::mem_probe::mib(use[3]), leonida::mem_probe::mib(peak), (unsigned long long)title_ranges, leonida::mem_probe::mib(title), (unsigned long long)shadows, leonida::fsdraw::pipeline_count()); return std::string(text); }; leonida::mem_probe::start(std::move(facts)); } if (info.conditional_rendering) { const auto properties = reinterpret_cast( info.get_instance_proc(info.instance, "vkGetPhysicalDeviceProperties")); const auto families = reinterpret_cast( info.get_instance_proc(info.instance, "vkGetPhysicalDeviceQueueFamilyProperties")); if (properties && families) { VkPhysicalDeviceProperties limits{}; properties(info.physical, &limits); std::uint32_t count = 0; families(info.physical, &count, nullptr); std::vector queues(count); families(info.physical, &count, queues.data()); if (info.copy_family < count && !(queues[info.copy_family].queueFlags & VK_QUEUE_COMPUTE_BIT)) state_.context->set_transfer_only_family(info.copy_family); if (info.queue_family < count && (queues[info.queue_family].queueFlags & VK_QUEUE_COMPUTE_BIT)) { state_.context->configure_predication(get_device, state_.memory, limits.limits.maxStorageBufferRange, info.queue_family); if (info.storage_buffer_8bit) state_.context->configure_predicated_copy(get_device, limits.limits); } } } if (info.host_image_copy) load_host_image_copy(get_device); if (info.host_pointer_alignment) state_.get_host_pointer_properties = reinterpret_cast( get_device(info.device, "vkGetMemoryHostPointerPropertiesEXT")); // Depth <-> colour copies are staged through scratch buffers (vulkan_scratch.h), on every GPU. With buffer // device addresses the same scratch holds the triangle indices of indexed quad lists (quad_index_expand.h): // a compute pass writes them through the chunk's address and the draw binds the chunk as its index buffer. const bool index_scratch = info.buffer_device_address; state_.context->enable_copy_scratch( get_device, [this, index_scratch](const VkMemoryRequirements& requirements) { return state_.allocate(requirements, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, nullptr, index_scratch); }, index_scratch ? VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT : 0, state_.families); if (info.buffer_device_address && info.physical && info.get_instance_proc) { if (const auto get_props = reinterpret_cast( info.get_instance_proc(info.instance, "vkGetPhysicalDeviceProperties"))) { VkPhysicalDeviceProperties props{}; get_props(info.physical, &props); state_.context->configure_counted_dispatch(get_device, state_.memory, props.limits); state_.context->configure_quad_indices(get_device, props.limits); // ExecuteIndirect arguments are clamped on the GPU before every indirect command (vulkan_indirect_clamp.h). // Its record scratch is device-local memory with a device address, like the arena's. state_.context->enable_indirect_clamp(get_device, state_.memory, props.limits, [this](const VkMemoryRequirements& requirements) { return state_.allocate(requirements, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, nullptr, /*device_address=*/true); }, state_.families); } } // The copies of a D24 texture stored as D32 convert on the GPU (vulkan_depth24.h), and so do the copies of // a 96-bit texture, which every GPU stores as RGBA32 (D3D-62): the converter is there whether or not the // GPU has a native D24_UNORM_S8_UINT. It costs nothing until a copy needs it (its pipeline is made on the // first job, and a queue takes the tracker lock for it only when a list has such a copy). { std::uint64_t max_storage_range = 1u << 27; // the least Vulkan allows, if the limit cannot be read if (info.physical && info.get_instance_proc) { if (const auto get_props = reinterpret_cast( info.get_instance_proc(info.instance, "vkGetPhysicalDeviceProperties"))) { VkPhysicalDeviceProperties props{}; get_props(info.physical, &props); max_storage_range = props.limits.maxStorageBufferRange; } } state_.context->enable_depth24(get_device, [this](const VkMemoryRequirements& requirements) { return state_.allocate(requirements, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); }, max_storage_range); } if (info.bindless && state_.context->loaded() && !create_bindless(get_device)) std::fprintf(stderr, "[rt] d3d12: the bindless set 0 could not be created\n"); query_luid_and_clock(get_device); // Timestamps: the device's timestampPeriod, enabled when the graphics family (info.queue_family) has // timestampValidBits. VkPhysicalDeviceProperties properties{}; device_properties(info.physical, &properties); state_.max_sampler_lod_bias = properties.limits.maxSamplerLodBias; std::uint32_t family_count = 0; queue_families(info.physical, &family_count, nullptr); std::vector families(family_count); queue_families(info.physical, &family_count, families.data()); state_.timestamp_bits.reserve(family_count); for (std::uint32_t i = 0; i < family_count; ++i) { // Timestamp writes alone can work on a transfer-only family. Resetting the query and resolving it // with vkCmdCopyQueryPoolResults require a graphics- or compute-capable family as well. const auto& family = families[i]; const bool can_resolve = (family.queueFlags & (VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT)) != 0; state_.timestamp_bits.push_back(can_resolve ? family.timestampValidBits : 0); } if (info.queue_family < family_count) { const auto& family = families[info.queue_family]; if (family.timestampValidBits) state_.context->set_timestamp_period(properties.limits.timestampPeriod); // MoltenVK (1.4.2 and 1.4.3 measured) resolves a timestamp before the write that precedes it lands, unless // something orders the two (docs/d3d12_vulkan.md section 4.6). const auto get_props2 = reinterpret_cast( info.get_instance_proc ? info.get_instance_proc(info.instance, "vkGetPhysicalDeviceProperties2") : nullptr); if (family.timestampValidBits && get_props2) { VkPhysicalDeviceDriverProperties driver{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES}; VkPhysicalDeviceProperties2 props{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &driver}; get_props2(info.physical, &props); if (driver.driverID == VK_DRIVER_ID_MOLTENVK) { state_.context->set_order_timestamp_copies(true); log_once("timestamp resolves wait for the timestamps before them (MoltenVK); driver", int(driver.driverID)); } } if (family.queueFlags & VK_QUEUE_COMPUTE_BIT) state_.context->set_occlusion_resolve_memory(state_.memory); } if (info.debug_utils) { leonida::DebugLabelFunctions labels; const auto load = [&](auto& f, const char* name) { f = reinterpret_cast>(info.get_instance_proc(info.instance, name)); }; load(labels.cmd_insert, "vkCmdInsertDebugUtilsLabelEXT"); load(labels.cmd_begin, "vkCmdBeginDebugUtilsLabelEXT"); load(labels.cmd_end, "vkCmdEndDebugUtilsLabelEXT"); load(labels.queue_insert, "vkQueueInsertDebugUtilsLabelEXT"); load(labels.queue_begin, "vkQueueBeginDebugUtilsLabelEXT"); load(labels.queue_end, "vkQueueEndDebugUtilsLabelEXT"); state_.context->enable_debug_labels(labels); if (!state_.context->debug_labels()) std::fprintf(stderr, "[rt] d3d12: VK_EXT_debug_utils entry points missing; debug markers are off\n"); } const bool sparse_aliasing = state_.context->vk.vkQueueBindSparse && info.features.sparseBinding && info.features.sparseResidencyAliased && properties.sparseProperties.residencyNonResidentStrict && info.queue_family < family_count && (families[info.queue_family].queueFlags & VK_QUEUE_SPARSE_BINDING_BIT); state_.sparse_image_tiles = sparse_aliasing && info.features.sparseResidencyImage2D && state_.context->vk.vkGetImageSparseMemoryRequirements; if (sparse_aliasing && state_.arena.memory && info.features.sparseResidencyBuffer) { auto& vk = state_.context->vk; const auto sparse_info = state_.sparse_buffer_info(leonida::tile_size_in_bytes); VkBuffer sample = VK_NULL_HANDLE; if (vk.vkCreateBuffer(info.device, &sparse_info, nullptr, &sample) == VK_SUCCESS) { VkMemoryRequirements requirements{}; vk.vkGetBufferMemoryRequirements(info.device, sample, &requirements); vk.vkDestroyBuffer(info.device, sample, nullptr); if (!(leonida::tile_size_in_bytes % requirements.alignment)) state_.sparse_buffer_memory_types = requirements.memoryTypeBits; } } } // Set 0 of every translated shader that declares bindings: images, samplers and the descriptor hash table // (docs section 3.4). Each ExecuteCommandLists brings it up to date before its commands are written. bool create_bindless(PFN_vkGetDeviceProcAddr get_device) { leonida::BindlessFeatures features{}; features.update_after_bind = true; // VulkanDeviceInfo::bindless promises it features.partially_bound = state_.info.bindless_partially_bound; features.null_descriptor = state_.info.null_descriptor; // The descriptor-table hash kind every shader of this device probes with, chosen once here, before the table's // first key: each loaded module's index.json meta may say `descriptor_hash` (descriptor_table.h), and when the // library mixes kinds the majority wins; LEONIDA_DESCRIPTOR_HASH overrides. The module index is read here // rather than at the first pipeline so the choice is fixed before any descriptor can be registered. leonida::DescriptorHashCensus hash_modules{}; leonida::DescriptorHashKind descriptor_hash = leonida::DescriptorHashKind::fnv1a; if (const leonida::ShaderLibrary* library = state_.library()) { hash_modules = library->descriptor_hash_census(); descriptor_hash = library->descriptor_hash_kind(); } leonida::DescriptorHashKind override_kind = descriptor_hash; if (leonida::descriptor_hash_kind_from_env(std::getenv("LEONIDA_DESCRIPTOR_HASH"), &override_kind)) { std::fprintf(stderr, "[rt] d3d12: descriptor hash: %s (LEONIDA_DESCRIPTOR_HASH; %zu fnv1a_fmix32 / %zu fnv1a " "modules)\n", leonida::descriptor_hash_kind_name(override_kind), hash_modules.fnv1a_fmix32, hash_modules.fnv1a); descriptor_hash = override_kind; } else if (hash_modules.fnv1a_fmix32 && hash_modules.fnv1a) { std::fprintf(stderr, "[rt] d3d12: descriptor hash: %zu fnv1a_fmix32 / %zu fnv1a modules; using %s\n", hash_modules.fnv1a_fmix32, hash_modules.fnv1a, leonida::descriptor_hash_kind_name(descriptor_hash)); } else { std::fprintf(stderr, "[rt] d3d12: descriptor hash: %s (all %zu modules)\n", leonida::descriptor_hash_kind_name(descriptor_hash), hash_modules.total()); } const auto get_properties = reinterpret_cast( state_.info.get_instance_proc(state_.info.instance, "vkGetPhysicalDeviceProperties2")); if (get_properties) { VkPhysicalDeviceVulkan12Properties indexed{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_PROPERTIES}; VkPhysicalDeviceVulkan11Properties v11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_PROPERTIES, &indexed}; VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &v11}; get_properties(state_.info.physical, &properties); features.ms_samples = {VK_SAMPLE_COUNT_4_BIT, state_.ms_fallback_samples(VK_FORMAT_R32_UINT), state_.ms_fallback_samples(VK_FORMAT_R32_SINT)}; // Past maxPerSetDescriptors, ask the driver about the grown layout (D3D-219: Intel's Xe-LP reports 6159). const auto layout_support = reinterpret_cast( get_device(state_.info.device, "vkGetDescriptorSetLayoutSupport")); std::function layout_supported; // MoltenVK's vkGetDescriptorSetLayoutSupport compares every layout with maxPerSetDescriptors (1212, the // limit without argument buffers) and rejects even 1212 itself, while it creates and samples a 65536-image, // 4096-sampler update-after-bind set correctly (docs/d3d12_vulkan.md section 5). There size_bindings' // per-type update-after-bind limits, which MoltenVK takes from Metal's argument-buffer limits, decide. VkPhysicalDeviceDriverProperties driver{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES}; VkPhysicalDeviceProperties2 driver_properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &driver}; get_properties(state_.info.physical, &driver_properties); if (driver.driverID == VK_DRIVER_ID_MOLTENVK) layout_supported = [](const leonida::BindlessFeatures&) { return true; }; else if (layout_support) layout_supported = [&](const leonida::BindlessFeatures& candidate) { const leonida::bindless::SetLayout layout(candidate); VkDescriptorSetLayoutSupport support{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_SUPPORT}; layout_support(state_.info.device, &layout.info, &support); return support.supported == VK_TRUE; }; if (!leonida::bindless::size_bindings(features, properties.properties.limits, v11, indexed, layout_supported)) std::fprintf(stderr, "[rt] d3d12: the device's descriptor limits are below the bindless set's default " "sizes; it holds less\n"); } namespace b = leonida::bindless; std::fprintf(stderr, "[rt] d3d12: bindless set: %u 2D images, %u samplers, %u 2D-array, %u 3D, %u 1D, " "%u storage indices in 2D\n", features.counts[b::sampled_binding(leonida::ImageDimension::dim_2d)], features.counts[b::sampler_binding], features.counts[b::sampled_binding(leonida::ImageDimension::dim_2d_array)], features.counts[b::sampled_binding(leonida::ImageDimension::dim_3d)], features.counts[b::sampled_binding(leonida::ImageDimension::dim_1d)], features.counts[b::storage_binding(leonida::ImageDimension::dim_2d, 0)]); std::fprintf(stderr, "[rt] d3d12: bindless table policy: spare generations, host-memory fallback, a degraded " "flush instead of a refused submission\n"); // D3D12 promises a shader holds a full shader-visible sampler heap. Past this many distinct S#s, CreateSampler // logs that the array is full and a shader reads the fallback (clamping) sampler. if (features.counts[b::sampler_binding] < D3D12_MAX_SHADER_VISIBLE_SAMPLER_HEAP_SIZE + 1) std::fprintf(stderr, "[rt] d3d12: the bindless set holds fewer samplers than a full shader-visible " "sampler heap (%u of %u besides the fallback): its limits or " "vkGetDescriptorSetLayoutSupport allow no more\n", features.counts[b::sampler_binding] - 1, unsigned(D3D12_MAX_SHADER_VISIBLE_SAMPLER_HEAP_SIZE)); state_.bindless = std::make_unique(get_device, state_.info.device, state_.memory, features, descriptor_hash, state_.families); if (!state_.bindless->ok() || !state_.context->vk.vkCreateSampler) { state_.bindless.reset(); return false; } state_.context->set_bindless_release( [](void* user, std::uint32_t dim, std::uint32_t idx) { auto* st = static_cast(user); std::lock_guard lock(st->descriptor_mutex); if (st->bindless) st->bindless->remove_image(static_cast(dim), idx); }, &state_); state_.context->set_bindless_prepare([this](VkCommandBuffer command_buffer) { std::unique_lock lock(state_.descriptor_mutex); if (!state_.bindless->fallbacks_ready()) state_.bindless->record_fallback_init(command_buffer); auto& context = *state_.context; if (state_.bindless_legacy_idle && state_.bindless->flush_replaces_table()) { // The wait of before D3D-314, kept for comparing frame times: nothing that uses the set still runs // after it, so the generations flush() retires are free at once. { std::lock_guard submit(context.submit_mutex()); context.observe_result(context.vk.vkDeviceWaitIdle(state_.info.device), "vkDeviceWaitIdle"); } state_.bindless_idle_waits.fetch_add(1, std::memory_order_relaxed); state_.bindless->release_retired(); } else if (state_.bindless->has_retired()) { // Generations of the table that an earlier flush replaced: free those whose submissions are done. // Nothing waits; the rest stay for a later submit. completed_retire_ticket() takes submit_mutex_, // which comes after the resource, tracker and descriptor locks held here. state_.bindless->release_retired(context.completed_retire_ticket()); // A queue whose work is stalled (a fence only the CPU signals, long async work) keeps its ticket from // completing, and each replacing flush adds a generation. Past the cap wait, once the oldest is in the // way, for the submissions up to its ticket (the queues' timelines, not the device), with the // descriptor lock released: the thread that signals such a fence may need it. constexpr std::size_t max_retired = 8; if (state_.bindless->retired_count() > max_retired) { if (!state_.bindless_cap_logged.exchange(true)) std::fprintf(stderr, "[rt] d3d12: more than %zu retired bindless table generations: waiting " "for the queues that still use the oldest\n", max_retired); const std::uint64_t oldest = state_.bindless->oldest_retired_ticket(); lock.unlock(); const std::uint64_t completed = context.wait_retire_ticket(oldest); lock.lock(); state_.bindless->release_retired(completed); } } // Under tracker_mutex_ (held from here to the submit) no other ExecuteCommandLists has recorded work that // is not yet submitted, so every submission that can have bound the set being replaced has a ticket up to // the one read here. // A generation that cannot be made (VRAM full) does not fail the submission: the set frees what completed // and retries, rewrites the table in place when nothing runs, or keeps the previous table (vulkan_bindless.h). auto& set = *state_.bindless; const std::uint64_t host_fallbacks = set.table_host_fallbacks(); const bool flushed = set.flush(command_buffer, context.submitted_retire_ticket(), [&context] { return context.completed_retire_ticket(); }); if (flushed && set.last_flush_replaced()) context.note_bindless_upload(); const auto table_state = [&] { return std::to_string(set.table().size()) + " of " + std::to_string(set.table().capacity()) + " slots used, " + std::to_string(set.table_buffer_bytes() / 1024) + " KiB in " + (set.table_in_device_local_memory() ? "device-local" : "host") + " memory; " + std::to_string(set.generations_made()) + " generations made, " + std::to_string(set.retired_count()) + " retired, " + std::to_string(set.spare_count()) + " spare, " + std::to_string(set.spares_reused()) + " reused"; }; if (set.table_buffer_bytes() != state_.bindless_logged_table_bytes) { state_.bindless_logged_table_bytes = set.table_buffer_bytes(); std::fprintf(stderr, "[rt] d3d12: bindless table: %s\n", table_state().c_str()); } if (set.table_host_fallbacks() != host_fallbacks && !state_.bindless_host_logged) { state_.bindless_host_logged = true; std::fprintf(stderr, "[rt] d3d12: bindless table buffer placed in host memory: device-local memory " "is full (%s)\n", table_state().c_str()); } if (set.last_flush_degraded()) { // Logged at the first and each power of two: how often it happens without flooding the log. const std::uint64_t n = set.degraded_flushes(); if ((n & (n - 1)) == 0) std::fprintf(stderr, "[rt] d3d12: bindless table generation not made (%s: %d), %llu times: the " "batch runs with the previous table, keys added since read the fallback " "(%s)\n", set.last_failure() ? set.last_failure() : "?", int(set.last_failure_result()), static_cast(n), table_state().c_str()); } return flushed; }); state_.context->set_bindless_current([this]() { std::lock_guard lock(state_.descriptor_mutex); return state_.bindless ? state_.bindless->set() : VK_NULL_HANDLE; }); { char text[8] = {}; size_t length = 0; state_.bindless_legacy_idle = getenv_s(&length, text, "LEONIDA_BINDLESS_IDLE_WAIT") == 0 && length > 1 && text[0] != '0'; } state_.context->set_bindless_commit([this](bool submitted) { std::lock_guard lock(state_.descriptor_mutex); if (state_.bindless) state_.bindless->table_upload_result(submitted); }); return true; } // LEONIDA_ARENA_MB sets its size (default 256, at most 4095, and no more than the device's maxBufferSize and // maxMemoryAllocationSize allow: src/arena_size.h): it holds every default-heap buffer, shader-visible // descriptor heap and shader program. M0-M3 keep it host-visible (section 3.3, memory type policy). bool create_arena() { auto& vk = state_.context->vk; if (!vk.vkGetBufferDeviceAddress) return false; char text[16] = {}; size_t length = 0; const bool set = getenv_s(&length, text, "LEONIDA_ARENA_MB") == 0 && length > 1; const leonida::ArenaLimits limits{state_.info.max_buffer_size, state_.info.max_memory_allocation_size}; leonida::ArenaSize size = leonida::decide_arena_size(set ? text : nullptr, limits); auto& arena = state_.arena; VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; info.size = size.bytes; info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; // Default-heap buffers live here, and any of them can be a SetPredication buffer. if (state_.info.conditional_rendering) info.usage |= VK_BUFFER_USAGE_CONDITIONAL_RENDERING_BIT_EXT; // With ray tracing, AS result, scratch and build-input buffers are default-heap ranges of the arena. if (state_.info.ray_tracing) info.usage |= VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_STORAGE_BIT_KHR | VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR; state_.share(info); VkMemoryRequirements requirements{}; const auto create_buffer = [&] { if (info.size <= kArenaReserved || vk.vkCreateBuffer(state_.info.device, &info, nullptr, &arena.buffer) != VK_SUCCESS) { arena.buffer = VK_NULL_HANDLE; return false; } vk.vkGetBufferMemoryRequirements(state_.info.device, arena.buffer, &requirements); arena.indirect_arguments = (info.usage & VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT) != 0; return true; }; if (!create_buffer()) return false; // The allocation is requirements.size, which alignment can make larger than the buffer: past // maxMemoryAllocationSize, make the buffer smaller by that much once. if (limits.max_allocation_size && requirements.size > limits.max_allocation_size) { vk.vkDestroyBuffer(state_.info.device, arena.buffer, nullptr); size = leonida::decide_arena_size(set ? text : nullptr, limits, requirements.size - info.size); info.size = size.bytes; if (!create_buffer()) return false; if (requirements.size > limits.max_allocation_size) { vk.vkDestroyBuffer(state_.info.device, arena.buffer, nullptr); arena.buffer = VK_NULL_HANDLE; return false; } } // With Resizable BAR, keep the arena where its buffer may still use DEVICE_LOCAL | HOST_VISIBLE memory // A large buffer can exclude that type, or require more bytes than its heap can hold. if (leonida::resizable_bar(state_.memory)) { const VkDeviceSize asked = info.size; const VkDeviceSize fitted = leonida::device_local_arena_bytes(asked, [&](VkDeviceSize bytes) { if (bytes == asked) return leonida::device_local_arena_fits(state_.memory, requirements); VkBufferCreateInfo probe = info; probe.size = bytes; VkBuffer buffer = VK_NULL_HANDLE; if (vk.vkCreateBuffer(state_.info.device, &probe, nullptr, &buffer) != VK_SUCCESS) return false; VkMemoryRequirements r{}; vk.vkGetBufferMemoryRequirements(state_.info.device, buffer, &r); vk.vkDestroyBuffer(state_.info.device, buffer, nullptr); return (!limits.max_allocation_size || r.size <= limits.max_allocation_size) && leonida::device_local_arena_fits(state_.memory, r); }); if (fitted != asked) { vk.vkDestroyBuffer(state_.info.device, arena.buffer, nullptr); info.size = fitted; if (!create_buffer()) return false; size.bytes = fitted; size.capped |= leonida::arena_cap_bar; } } if (size.capped) std::fprintf(stderr, "[rt] d3d12: GPU address arena: %llu MiB of the %llu MiB asked for, capped by the " "device's %s\n", static_cast(size.bytes >> 20), static_cast(size.requested >> 20), leonida::arena_cap_name(size.capped)); arena.memory = state_.allocate(requirements, leonida::kArenaRequiredMemory, leonida::kArenaPreferredMemory, nullptr, true, &arena.memory_type); void* mapped = nullptr; if (!arena.memory || vk.vkBindBufferMemory(state_.info.device, arena.buffer, arena.memory, 0) != VK_SUCCESS || vk.vkMapMemory(state_.info.device, arena.memory, 0, VK_WHOLE_SIZE, 0, &mapped) != VK_SUCCESS) { // Without an arena every buffer keeps its own memory; a leftover handle would make them addressable // with heap base 0, so their VAs would be raw device addresses above 4 GiB. vk.vkDestroyBuffer(state_.info.device, arena.buffer, nullptr); if (arena.memory) vk.vkFreeMemory(state_.info.device, arena.memory, nullptr); arena.buffer = VK_NULL_HANDLE; arena.memory = VK_NULL_HANDLE; return false; } arena.mapped = static_cast(mapped); // LEONIDA_ARENA_NULL_MB= (for compute-on boots): the first n MiB of the arena, at heap_base + 0, are zeroed // and never handed out, and the zero page and the quad indices move above them. A translated shader whose // address arithmetic starts from a null base (a scalar or flat load the translator does not bounds-check) // reads or writes there, not in a buffer of the title's or the shared zero page and quad indices, which sat // at offset 0 (world-start compute faults read heap_base + ~0 on both platforms). const VkDeviceSize null_bytes = [&] { char text[16] = {}; std::size_t n = 0; if (getenv_s(&n, text, "LEONIDA_ARENA_NULL_MB") != 0 || n <= 1) return VkDeviceSize(0); const VkDeviceSize bytes = VkDeviceSize(std::strtoull(text, nullptr, 10)) << 20; return bytes + kArenaReserved < info.size / 2 ? bytes : VkDeviceSize(0); }(); std::memset(arena.mapped, 0, std::size_t(null_bytes + kZeroPage)); // the null region and the zero page { auto* indices = reinterpret_cast(arena.mapped + null_bytes + kZeroPage); for (std::uint32_t i = 0; i < kQuadIndexCount; i += kQuadIndicesPerQuad) { const std::uint32_t base = i / kQuadIndicesPerQuad * 4; std::transform(leonida::quad_triangle_indices.begin(), leonida::quad_triangle_indices.end(), indices + i, [base](std::uint32_t index) { return base + index; }); } } if (null_bytes) std::fprintf(stderr, "[rt] d3d12: arena null region: the first %llu MiB at heap_base are zeroed and never " "allocated (LEONIDA_ARENA_NULL_MB)\n", static_cast(null_bytes >> 20)); VkBufferDeviceAddressInfo address{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; address.buffer = arena.buffer; arena.address = vk.vkGetBufferDeviceAddress(state_.info.device, &address); arena.size = info.size; // The GPU address arena is the console's address space: the title names it by offset, so the label path // has to find it (src/gpu_label_memory.h). Its address space starts at 0. if (arena.mapped) leonida::label::memory().track(0, static_cast(arena.size), reinterpret_cast(arena.mapped), true); { // Under the arena's lock: an insert rebalances the tree and rewrites child links, which a walk on // another thread must not see half done. std::lock_guard lock(arena.mutex); arena.blocks.reset(null_bytes + kArenaReserved, arena.size); arena.first = null_bytes + kArenaReserved; char check[2] = {}; size_t check_length = 0; arena.check_all = getenv_s(&check_length, check, "LEONIDA_ARENA_CHECK") == 0 && check_length > 1 && check[0] != '0'; } arena.peak_end = null_bytes + kArenaReserved; char log[4] = {}; length = 0; arena.log = getenv_s(&length, log, "LEONIDA_ARENA_LOG") == 0 && length > 1 && log[0] != '0'; state_.context->set_heap_base(arena.address, arena.size); leonida::fsdraw::note_arena(arena.mapped, arena.size); // LOCAL DIAGNOSTIC state_.context->set_zero_page(arena.buffer, null_bytes, kZeroPage); state_.context->set_quad_indices(arena.buffer, null_bytes + kZeroPage, kQuadIndexCount); // Copy only registered title data. Each immutable upload stays alive in the queue command slot // until that submission's timeline value completes; a large indexed frame cannot wrap over itself. state_.context->set_geometry_provider([st=&state_](std::uint64_t va,std::uint64_t bytes, leonida::VulkanContext::GeometryUpload& result) { if (!va || !bytes || bytes>UINTPTR_MAX-va || !st->arena.mapped || bytes>st->arena.size) return false; std::uint64_t lo{},hi{}; if (!leonida::title_va_aliases().title_memory(va,lo,hi) || bytes>hi-va) { return false; } for(std::uint64_t at=va;at(at),®ion,sizeof(region)) || region.State!=MEM_COMMIT || (region.Protect & (PAGE_NOACCESS|PAGE_GUARD)) || !(region.Protect & (PAGE_READONLY|PAGE_READWRITE|PAGE_WRITECOPY))) return false; at=reinterpret_cast(region.BaseAddress)+region.RegionSize; } struct Lease { DeviceState* state{}; VkDeviceSize offset{},bytes{}; ~Lease(){if(bytes)state->arena_release(offset,bytes,DeviceState::arena_buffer);} }; auto lease=std::make_shared(); if (!st->arena_allocate(bytes,256,lease->offset,DeviceState::arena_buffer)) return false; lease->state=st;lease->bytes=bytes; SIZE_T copied{}; if (!ReadProcessMemory(GetCurrentProcess(),reinterpret_cast(va),st->arena.mapped+lease->offset, SIZE_T(bytes),&copied) || copied!=bytes) return false; result={va,bytes,st->arena.buffer,lease->offset,std::move(lease)}; return true; }); return true; } ~Device() override { { // Before anything goes: an exit save in progress finishes with this device first. std::lock_guard lock(exit_cache_mutex); std::erase(exit_cache_devices, &state_); } leonida::value_sink::clear_arena(&state_); // first: it waits for a value write into the arena in progress raw_images_.clear(); geometry_refresher_.reset(); // its refresh uses state_.geometry title_filler_.reset(); // its fills use the title-texture registry // Background pipeline work first, before anything it uses goes. Every PSO is gone (each held this device), // but a PSO released while its build ran is deleted on the worker after that build; the device's startup // cache checkpoint may also be queued or running. cancel() drops what is queued and waits for both. The last // device then stops and joins the compiler's thread. { auto& compiler = PipelineCompiler::instance(); if (compiler.running_here(&state_)) { // A build job of this device released the device's last reference from inside the build, which // goes on using the device when this returns. Nothing does this; stop rather than free under it. std::fprintf(stderr, "[rt] d3d12: device released from inside one of its own pipeline builds\n"); std::abort(); } compiler.cancel(&state_); compiler_use_.release(); } leonida::title_va_aliases().clear_hooks(&state_); { std::lock_guard lock(state_.title_window_mutex); for (const auto& window : state_.title_windows) leonida::title_va_aliases().remove(window.start, window.shader_va); state_.title_windows.clear(); } for (auto& [shape, image] : state_.zero_images) if (image) image->Release(); state_.zero_images.clear(); if (state_.context) { { std::lock_guard lock(state_.context->submit_mutex()); state_.context->observe_result(state_.context->vk.vkDeviceWaitIdle(state_.info.device), "vkDeviceWaitIdle"); } state_.context->drain_deleted_resources(UINT64_MAX); state_.context->set_pipeline_workers(nullptr); // before the pipeline cache is written and destroyed state_.context->set_bindless_release(nullptr, nullptr); state_.context->set_bindless_current(nullptr); // the retired generations go with state_.bindless below } if (state_.context) { state_.geometry.release(state_); state_.external_windows.release(state_); std::lock_guard upload(state_.title_upload_mutex); state_.title_upload.release(state_); } state_.staging_queue.reset(); // it uses the context if (state_.context && state_.bindless) { // Every texture is gone by now (each held this device), and its views with it; samplers remain. std::lock_guard lock(state_.descriptor_mutex); for (const auto& [key, sampler] : state_.sampler_entries) state_.context->vk.vkDestroySampler(state_.info.device, sampler, nullptr); state_.sampler_entries.clear(); state_.bindless.reset(); } state_.report_arena(); if (state_.context && state_.arena.buffer) { leonida::fsdraw::forget_arena(state_.arena.mapped); auto& vk = state_.context->vk; vk.vkDestroyBuffer(state_.info.device, state_.arena.buffer, nullptr); if (state_.arena.memory) vk.vkFreeMemory(state_.info.device, state_.arena.memory, nullptr); } if (state_.pipeline_cache_handle) { // Nothing should be building into the cache now (the compiler's jobs for this device are gone, and so // is every PSO). If something is, its pipelines are half in the cache: keep the previous session file. if (const unsigned building = state_.active_compiles.load()) std::fprintf(stderr, "[rt] d3d12: %u pipeline build(s) still running at device teardown; " "pipeline_cache.session.bin not written\n", building); else save_session_pipeline_cache(state_.context->vk, state_.info.device, state_.pipeline_cache_handle); state_.context->vk.vkDestroyPipelineCache(state_.info.device, state_.pipeline_cache_handle, nullptr); } state_.context.reset(); state_.image_memory.reset(); // the context's deferred queue gave its ranges back if (owned_.device) owned_.destroy_device(owned_.device, nullptr); if (owned_.instance) owned_.destroy_instance(owned_.instance, nullptr); } bool ok() const { return state_.context && state_.context->loaded(); } const VulkanDeviceInfo& info() const { return state_.info; } // Acceleration-structure resources work: KHR builds, or the XDXR records (which need the GPU address arena). bool acceleration_structures() const { return state_.info.ray_tracing || (state_.info.xdxr_acceleration_structures && state_.info.buffer_device_address); } bool upload_in_vram() const { return state_.upload_in_vram; } leonida::VulkanContext& context() { return *state_.context; } const leonida::BindlessSet* bindless() const { return state_.bindless.get(); } DeviceState& state() { return state_; } const DeviceState& state() const { return state_; } HRESULT create_native_graphics(const leonida::native_pso::GraphicsDesc& desc, REFIID iid, void** out) { const auto* shaders = state_.library(); if (!shaders) return E_NOTIMPL; return state_.native_graphics.create(shaders->directory(), desc, out, [&](const auto& pc, const auto& mesh, const auto& containers) { return shared_native_graphics(pc, mesh, containers, iid, out); }); } // A fresh public PSO has its own COM identity, private data and name. Equal native descriptions can // hold one compiled backend PSO while either public object lives. The device only holds weak references. HRESULT prepare_console_stream(const D3D12_PIPELINE_STATE_STREAM_DESC& source, REFIID iid, void** out, std::unique_ptr record) { if (!out)return E_POINTER;*out=nullptr; PipelineStream stream{}; if(const auto hr=parse_pipeline_stream(source,stream);FAILED(hr))return hr; const auto* library=state_.library();if(!library)return E_FAIL; const auto verify=[&](const char* name,const D3D12_SHADER_BYTECODE& code) { if(!code.BytecodeLength)return true; if(!code.pShaderBytecode)return false; const std::span bytes{static_cast(code.pShaderBytecode),code.BytecodeLength}; const std::string identity=std::string(name)+leonida::sha256_hex(bytes); {std::lock_guard lock(verified_program_mutex_);if(verified_programs_.count(identity))return true;} auto program=leonida::compute_program(bytes); if(program.bytes.empty())return false; bool ambiguous=false; const auto candidates=library->program_candidates(name,program,&ambiguous); if(candidates.empty() || ambiguous)return false; {std::lock_guard lock(verified_program_mutex_);verified_programs_.insert(identity);} return true; }; if(stream.has_cs) { if(!stream.compute.CS.BytecodeLength || !verify("cs",stream.compute.CS))return E_INVALIDARG; } else { const auto& g=stream.graphics; if(stream.as.BytecodeLength || g.HS.BytecodeLength || g.DS.BytecodeLength)return E_NOTIMPL; if((bool(g.VS.BytecodeLength)==bool(stream.ms.BytecodeLength)) || g.NumRenderTargets>8 || !verify("vs",g.VS)||!verify("gs",g.GS)||!verify("ms",stream.ms)||!verify("ps",g.PS))return E_INVALIDARG; } if(!record) record=rt::d3d12_xs::PsoStreamRecord::capture(source); if(!record)return E_INVALIDARG; auto* pipeline=new PipelineState(state_); pipeline->attach_device(identity()); pipeline->set_cache_key(stream.has_cs?pipeline_key(stream.compute):pipeline_key(stream.graphics)); if(!rt::d3d12_xs::attach_pso_record(pipeline,std::move(record))){pipeline->Release();return E_OUTOFMEMORY;} pipeline->set_pending_stream(stream.has_cs); return hand_out(pipeline,iid,out); } HRESULT shared_native_graphics(const D3D12_GRAPHICS_PIPELINE_STATE_DESC& pc, D3D12_SHADER_BYTECODE mesh, std::span containers, REFIID iid, void** out) { auto key = pipeline_key(pc); if (mesh.BytecodeLength) key += leonida::sha256_hex({static_cast(mesh.pShaderBytecode), mesh.BytecodeLength}); std::shared_ptr compiled; { std::lock_guard lock(native_pipeline_mutex_); const auto found = native_pipelines_.find(key); if (found != native_pipelines_.end()) compiled = found->second.lock(); } if (!compiled) { ID3D12PipelineState* raw = nullptr; HRESULT hr; if(state_.info.prepare_on_bind) { rt::d3d12_xs::native_pipeline_detail::Stream native; rt::d3d12_xs::native_pipeline_detail::build_stream(pc,mesh,native); const auto source=native.desc(); auto record=rt::d3d12_xs::PsoStreamRecord::capture(source,containers); hr=record?prepare_console_stream(source,__uuidof(ID3D12PipelineState),reinterpret_cast(&raw),std::move(record)):E_INVALIDARG; } else { hr = mesh.BytecodeLength ? rt::d3d12_xs::native_pipeline_detail::create_mesh(this, pc, mesh, __uuidof(ID3D12PipelineState), reinterpret_cast(&raw)) : CreateGraphicsPipelineState(&pc, IID_PPV_ARGS(&raw)); } if (FAILED(hr)) return hr; if (!raw) return E_FAIL; auto* owner = PipelineState::from(raw); if (!owner) { raw->Release(); return E_NOINTERFACE; } compiled = std::shared_ptr(owner, [](PipelineState* p) { p->Release(); }); std::lock_guard lock(native_pipeline_mutex_); if (native_pipelines_.size() >= 16384) native_pipelines_.clear(); auto& cached = native_pipelines_[key]; if (auto concurrent = cached.lock()) compiled = std::move(concurrent); else cached = compiled; } if(!compiled->ensure_native_source(pc,mesh,containers)) return E_FAIL; auto* view = new PipelineState(state_); view->attach_device(identity()); if(!rt::d3d12_xs::share_pso_record(compiled.get(),view)) { view->Release(); return E_OUTOFMEMORY; } view->share_native_graphics(std::move(compiled)); return hand_out(view, iid, out); } IUnknown* holder() { return identity(); } // Console-extended CreateDescriptorHeap (Xbox slot 14): a heap at the title's console address. The proxy's // handler (set_console_descriptor_heap_handler) calls this; a normal PC create never does. HRESULT create_console_descriptor_heap(const D3D12_DESCRIPTOR_HEAP_DESC* desc, D3D12_GPU_VIRTUAL_ADDRESS console_address, std::uint64_t console_size, REFIID riid, void** out) { auto* heap = new DescriptorHeap(state_, *desc, console_address, console_size); heap->attach_device(identity()); if (!heap->ok()) { heap->Release(); return E_OUTOFMEMORY; } return hand_out(heap, riid, out); } bool bind_sampler(const leonida::gfx10::SamplerWords& words) { return state_.bind_sampler(words); } // Xbox device slots 70/71 (rt::d3d12::write_placed_buffer_view): the slot is zeroed first, as Create*View does. bool resolve_xdxr_build(leonida::BuildAccelerationStructure& build) { return state_.resolve_xdxr_build(build); } bool resolve_xdxr_copy(leonida::CopyAccelerationStructure& copy) { return state_.resolve_xdxr_copy(copy); } bool resolve_xdxr_postbuild(leonida::AccelerationStructurePostbuild& info) { return state_.resolve_xdxr_postbuild(info); } bool write_placed_buffer_view(bool unordered, const void* view, std::uint64_t address, std::uint64_t width, D3D12_CPU_DESCRIPTOR_HANDLE destination) { struct PlacedWrite { DeviceState& state; SIZE_T ptr; bool unordered; ~PlacedWrite() { if (rt::compute_probe::enabled()) state.probe_api(ptr, 1, unordered ? "slot71" : "slot70"); } } probe{state_, destination.ptr, unordered}; std::memset(reinterpret_cast(destination.ptr), 0, kDescriptorSize); if (unordered) { D3D12_UNORDERED_ACCESS_VIEW_DESC desc{}; std::memcpy(&desc, view, sizeof(desc)); return write_buffer_uav_at(address, width, &desc, 0, destination); } D3D12_SHADER_RESOURCE_VIEW_DESC desc{}; std::memcpy(&desc, view, sizeof(desc)); return desc.ViewDimension == D3D12_SRV_DIMENSION_BUFFER && write_buffer_srv(address, width, &desc, destination, true); } // ---- Textures the title keeps in its own memory (TitleTexture) ---- // Xbox device slot 70 with a texture description (rt::d3d12::write_placed_texture_view): the view's T#, of the // slot-133 texture placed at `address` or of an image made for that memory and filled from it. False leaves the // slot a null view (zeros); every reason is counted and logged once per format and layout. bool write_placed_texture_view(const std::uint32_t* resource_words, const std::uint32_t* view_words, std::uint64_t address, D3D12_CPU_DESCRIPTOR_HANDLE destination) { std::memset(reinterpret_cast(destination.ptr), 0, kDescriptorSize); rt::xg_xs::ResourceDesc d{}; std::memcpy(&d, resource_words, sizeof(d)); D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; std::memcpy(&srv, view_words, sizeof(srv)); if (!srv.Shader4ComponentMapping) srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; std::array words{}; std::memcpy(words.data(), resource_words, sizeof(words)); words[2] = words[3] = 0; // the alignment says nothing about the texels bool written = false; { std::lock_guard lock(state_.title_texture_mutex); const InTitleTextures inside; TitleTextureStats& stats = title_stats_; ++stats.views; ++stats.asked[{d.format, d.layout, d.dimension, d.mips}]; const std::uint64_t refusals = stats.refusals; written = place_title_view(d, words, srv, address, destination); if (texture_probe()) std::fprintf(stderr, "[rt] texture-probe: SRV dest %llx va %llx %llux%ux%u fmt %u view %u mips %u ok %u\n", (unsigned long long)destination.ptr, (unsigned long long)address, (unsigned long long)d.width, d.height, unsigned(d.depth_or_array), d.format, unsigned(srv.Format), unsigned(d.mips), unsigned(written)); if (!written && stats.refusals == refusals) refuse_title_view("no reason recorded", d, address); if (!written) ++stats.null_views; if (stats.views == 64 || !(stats.views % 2048)) log_title_census("slot-70 texture views"); } state_.drain_titles_gone(); return written; } // Slot 71 names GPU-writable memory. Its contents belong to the existing image. bool write_placed_texture_uav(const std::uint32_t* words, const std::uint32_t* view, std::uint64_t address, D3D12_CPU_DESCRIPTOR_HANDLE dest) { static const bool enabled = [] { const char* v = std::getenv("LEONIDA_PLACED_TEXTURE_UAV"); return !v || std::strcmp(v, "0"); }(); std::memset(reinterpret_cast(dest.ptr), 0, kDescriptorSize); if (!enabled || !address) return false; rt::xg_xs::ResourceDesc d{}; D3D12_UNORDERED_ACCESS_VIEW_DESC uav{}; std::memcpy(&d, words, sizeof(d)); std::memcpy(&uav, view, sizeof(uav)); std::lock_guard lock(state_.title_texture_mutex); auto it = state_.title_textures.find(address); if (it == state_.title_textures.end()) it = state_.title_textures.find(leonida::title_gpu_views::other_view(address)); Resource* candidate = matching_gpu_placement(d, address, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); if (!candidate && it != state_.title_textures.end() && !it->second->owned) candidate = it->second->resource; if (!candidate) return false; Resource& r = *candidate; const auto& rd = r.desc(); if (!TitleGpuPlacements::matches(d, r) || !(rd.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) return false; if (uav.ViewDimension == D3D12_UAV_DIMENSION_TEXTURE3D) { const auto& volume = uav.Texture3D; if (rd.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE3D || volume.MipSlice >= rd.MipLevels) return false; const UINT depth = std::max(1u, UINT(rd.DepthOrArraySize) >> volume.MipSlice); if (volume.FirstWSlice || (volume.WSize != UINT_MAX && volume.WSize != depth)) return false; TextureView v{}; v.type = leonida::gfx10::ImageType::image_3d; v.format = uav.Format; v.first_mip = volume.MipSlice; v.mip_count = 1; write_image_descriptor(r, v, dest, ImageViewUse::storage); } else { CreateUnorderedAccessView(&r, nullptr, &uav, dest); } leonida::gfx10::ImageWords result{}; std::memcpy(result.data(), reinterpret_cast(dest.ptr), sizeof(result)); if (!leonida::gfx10::is_image(result)) return false; std::lock_guard descriptors(state_.descriptor_mutex); if (!state_.bindless) return true; const auto entry = state_.image_entries.find(result); if (entry != state_.image_entries.end() && entry->second.storage) return true; std::memset(reinterpret_cast(dest.ptr), 0, kDescriptorSize); return false; } // A slot-133 texture the title placed at `address` (create_at_host_address): slot-70 views at that address are // of its image; unless the GPU writes it, the image is filled from the memory with the view's layout. void register_title_texture(Resource* texture, std::uint64_t address) { const D3D12_RESOURCE_DESC& desc = texture->desc(); auto entry = std::make_shared(); entry->address = address; entry->cpu = leonida::title_gpu_views::to_cpu(address); entry->set_resource(texture); entry->attachment_4k = desc.Width == 3840 && desc.Height == 2160 && (desc.Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)); entry->gpu_written = (desc.Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) != 0 || desc.SampleDesc.Count > 1; if (!entry->gpu_written) { // Until a slot-70 view says how it is laid out: the description's own (Layout 0, XG's default). rt::xg_xs::ResourceDesc d{}; d.dimension = std::uint32_t(desc.Dimension); d.width = desc.Width; d.height = desc.Height; d.depth_or_array = desc.DepthOrArraySize; d.mips = desc.MipLevels; d.format = std::uint32_t(desc.Format); d.samples = 1; const char* why = nullptr; if (title_xg_layout(*texture, entry->layout, entry->desc)) { entry->layout_known = entry->layout_from_xg = true; } else { entry->layout_known = entry->layout_guessed = title_layout(d, entry->layout, why) && title_layout_fits(entry->layout, d, *texture, why); std::memcpy(entry->desc.data(), &d, sizeof(d)); } } texture->mark_title_texture(); { std::lock_guard lock(state_.title_texture_mutex); if (entry->gpu_written && !(address & 0xff) && texture->image_address() != address) { std::lock_guard descriptors(state_.descriptor_mutex); state_.gpu_placements.add(address, texture); } auto& slot = state_.title_textures[address]; if (slot && slot->owned) retire_title_texture(*slot); slot = std::move(entry); ++title_stats_.registered; } } // Before every submission (VulkanContext::set_before_execute), at most once per LEONIDA_TITLE_TEXTURE_PERIOD_MS // (16 by default, about a frame): the bytes of the textures filled from the title's memory are hashed, round // robin, until LEONIDA_TITLE_TEXTURE_CHECK_KB have been read (4096 by default; all of a small texture, about 3% // of a large one, hash_guarded), mapped slot-133 textures first and every pass; a texture whose bytes changed is // filled again, up // to LEONIDA_TITLE_TEXTURE_FILL_MB a pass (32 by default, OpenScarlett's batch cap), the rest at the next pass. // Host copies and the private full-image uploader are safe here. Generic staging re-enters submission. No write // watch on the title's pages: streaming memory would fault once a page. void refresh_title_textures() { if (t_in_title_textures) return; using clock = std::chrono::steady_clock; static const auto setting = [](const char* name, std::uint64_t fallback) { char text[16] = {}; size_t length = 0; return getenv_s(&length, text, name) == 0 && length > 1 ? std::strtoull(text, nullptr, 10) : fallback; }; static const auto period = std::chrono::milliseconds(setting("LEONIDA_TITLE_TEXTURE_PERIOD_MS", 16)); static const std::uint64_t check_budget = setting("LEONIDA_TITLE_TEXTURE_CHECK_KB", 4096) << 10; static const std::uint64_t fill_budget = setting("LEONIDA_TITLE_TEXTURE_FILL_MB", 32) << 20; // And at most this long filling a pass (0: no limit); a texture already started is finished. static const std::uint64_t fill_budget_ns = setting("LEONIDA_TITLE_TEXTURE_FILL_MS", 8) * 1000000; // Stop the background sweep at a texture boundary. Zero keeps the byte budget alone. static const std::uint64_t hash_budget_us = setting("LEONIDA_TEXTURE_HASH_BUDGET_US", 400); // Residency checks and uploads also cost time. Limit background work between textures; // mapped textures and notified writes have already been serviced when this timer starts. static const auto sweep_budget_us = setting("LEONIDA_TEXTURE_SWEEP_BUDGET_US", 400); const auto now = clock::now(); const std::int64_t ticks = now.time_since_epoch().count(); if (ticks - title_refreshed_.load(std::memory_order_relaxed) < std::chrono::duration_cast(period).count()) return; std::unique_lock lock(state_.title_texture_mutex, std::try_to_lock); if (!lock.owns_lock()) return; // a slot-70 view is filling one; next time title_refreshed_.store(ticks, std::memory_order_relaxed); std::optional inside(std::in_place); TitleTextureStats& stats = title_stats_; ++stats.passes; // A fill this pass makes can submit, and a submission destroys a retired image, whose destructor reaches // title_texture_gone while this thread holds the registry mutex: the entry stops naming the resource and is // erased by drain_titles_gone after the pass. Every walk below visits a snapshot, never an iterator into the // registry, and skips an entry without a resource. const auto entries = leonida::title_texture_snapshot(state_.title_textures); title_pass_ = true; std::uint64_t checked = 0, filled = 0, fill_pass_ns = 0; const auto visit = [&](TitleTexture& t) { // A slot-133 texture's guessed layout (no slot-70 view yet) is only used once the title maps it. if (t.gpu_written || !t.layout_known || !t.resource || ((t.layout_guessed || t.layout_from_xg) && !t.mapped && !t.stale)) return; const std::uint64_t span = t.layout.layout.size; const bool always = t.mapped && refresh_mapped_pages(); // Out of this pass's fill budget (bytes or time): a texture known to need a fill (stale) waits for the // next pass unprobed and unhashed; hashing it now would only find it changed again (measured: 10,000 // deferred textures, 600 MiB hashed a pass, during the story load). const auto out_of_budget = [&] { return (filled && filled + span > fill_budget) || (fill_budget_ns && fill_pass_ns >= fill_budget_ns); }; if (t.stale && !always && out_of_budget()) { ++stats.deferred; return; } std::uint64_t hash = 0; if (!title_texture_readable(t)) return; checked += hashed_bytes(span); ++stats.checked; const auto* bytes = reinterpret_cast(static_cast(t.cpu)); const auto timed_hash = [&](std::uint64_t& out, bool all = false) { const auto start = clock::now(); const bool ok = hash_guarded(bytes, std::size_t(span), out, all); stats.hash_ns += std::chrono::duration_cast(clock::now() - start).count(); return ok; }; if (!timed_hash(hash)) { t.memory.defer(); return; } if (t.hashed && hash == t.hash && !t.stale) { if (!t.every_byte() || stats.passes % 6) return; std::uint64_t full = 0; checked += span; if (!timed_hash(full, true)) { t.memory.defer(); return; } if (t.full_hashed && full == t.full_hash) return; } ++stats.changed; if (!always && out_of_budget()) { t.stale = true; ++stats.deferred; return; } const auto fill_start = clock::now(); filled += fill_title_texture(t, false); const std::uint64_t fill_ns = std::chrono::duration_cast(clock::now() - fill_start).count(); stats.fill_ns += fill_ns; fill_pass_ns += fill_ns; }; bool overflow = false; auto written = leonida::title_texel_writes::take(overflow); // What the title memory map changed since the last pass: a texture over a change is probed again (its pages // may have come or gone), the others keep their last answer (TextureReadability). Every kRetryAll, or when the // journal lost some changes, all are probed again, for whatever no change reports. constexpr auto kRetryAll = std::chrono::seconds(30); title_map_changes_.clear(); std::uint64_t map_now = 0; bool map_all = !leonida::title_memory_map::changes_since( title_map_generation_, map_now, 0, UINTPTR_MAX, [&](std::uintptr_t from, std::uintptr_t to) { title_map_changes_.emplace_back(from, to); }); title_map_generation_ = map_now; if (now - title_retry_all_ >= kRetryAll) map_all = true; if (map_all) title_retry_all_ = now; leonida::merge_title_writes(title_map_changes_); stats.map_ranges += title_map_changes_.size(); stats.map_all += map_all; if (!written.empty() || overflow || map_all || !title_map_changes_.empty()) { stats.written_ranges += written.size(); leonida::merge_title_writes(written); for (const auto& entry : entries) { TitleTexture& t = *entry.second; if (t.gpu_written || !t.layout_known) continue; const std::uint64_t begin = t.cpu, end = t.cpu + t.layout.layout.size; if (map_all || leonida::title_write_overlaps(title_map_changes_, begin, end)) t.memory.retry(); if (leonida::title_write_overlaps(written, begin, end)) { t.memory.retry(); t.stale = true; } if (overflow) { t.memory.retry(); t.hashed = false; } } } const auto every_start = clock::now(); stats.written_ns += std::chrono::duration_cast(every_start - now).count(); for (const auto& entry : entries) if (entry.second->mapped || entry.second->stale) { ++stats.every_pass_visits; visit(*entry.second); } stats.every_pass_ns += std::chrono::duration_cast(clock::now() - every_start).count(); // The budget is the round robin's: mapped and stale textures above are checked every pass whatever it is. const auto first_bytes = checked, first_hash_ns = stats.hash_ns; if (check_budget) { const auto sweep_start = clock::now(); leonida::poll_title_textures(entries, title_refresh_cursor_, visit, [&] { if (checked - first_bytes >= check_budget || (hash_budget_us && (stats.hash_ns - first_hash_ns) / 1000 >= hash_budget_us)) return true; if (!sweep_budget_us) return false; const auto elapsed = std::chrono::duration_cast(clock::now() - sweep_start); return std::uint64_t(elapsed.count()) >= sweep_budget_us; }); } stats.hashed += checked; stats.filled_bytes += filled; stats.max_pass_bytes = std::max(stats.max_pass_bytes, filled); std::vector release; std::erase_if(retired_title_textures_, [&](const auto& r) { if (now - r.first < std::chrono::seconds(3)) return false; // descriptors may still be in flight retired_backing_ -= r.second->image_backing_bytes(); release.push_back(r.second); return true; }); title_pass_ = false; const std::uint64_t pass_ns = std::chrono::duration_cast(clock::now() - now).count(); stats.refresh_ns += pass_ns; stats.max_refresh_ns = std::max(stats.max_refresh_ns, pass_ns); if (now - stats.last_log >= std::chrono::seconds(10)) { stats.last_log = now; log_title_census("refresh"); } inside.reset(); lock.unlock(); state_.drain_titles_gone(); for (Resource* r : release) r->Release(); } private: struct TitleTextureStats { // (format, Layout word, dimension, mips) of the slot-70 texture views -> views std::map, std::uint64_t> asked; std::map refused; // why a view is a null view -> views std::uint64_t views = 0, null_views = 0, of_slot133 = 0, of_cache = 0, made = 0, retired = 0, registered = 0, refusals = 0, written_ranges = 0, unmaps = 0, unreadable = 0, pending_views = 0; std::uint64_t fills = 0, fill_bytes = 0, fill_failures = 0; std::uint64_t staged_fills = 0, staged_ns = 0; // refresh_title_textures, since the last log line std::uint64_t passes = 0, checked = 0, hashed = 0, changed = 0, deferred = 0, filled_bytes = 0, max_pass_bytes = 0, hash_ns = 0, refresh_ns = 0, max_refresh_ns = 0; // Split of refresh_ns: taking and matching the XG-written ranges, the mapped and stale textures visited every // pass (and how many), and the fills inside both. std::uint64_t written_ns = 0, every_pass_ns = 0, every_pass_visits = 0, fill_ns = 0; std::uint64_t map_ranges = 0, map_all = 0; // title memory map changes taken, passes that retried all // Readability probes (texture_memory_readable) since the last log line: [0] in refresh passes, [1] elsewhere // (slot-70 views, new images). A recheck is a probe of a texture whose memory was not readable at its last // probe; readable_now counts the rechecks that found it readable. std::array probes{}, probe_ns{}, rechecks{}, readable_now{}; std::chrono::steady_clock::time_point last_log{}; }; TitleTextureStats title_stats_; // under title_texture_mutex bool title_pass_ = false; // in refresh_title_textures, likewise std::atomic title_refreshed_{0}; // steady_clock ticks of the last pass std::atomic refreshed_present_{~std::uint64_t(0)}; // LEONIDA_REFRESH_PER_FRAME: present of the last full refresh // LEONIDA_TITLE_FILL_ASYNC=1 (for runs that only need the title to go on): slot-70 views no longer fill or hash // the texture they name on the title's thread (speed-26/27: a title thread 68-88 % inside slot 70, in hashing, // copying and staged uploads). The texture's address is queued, and a worker of ours fills it, taking the registry // lock for one texture at a time. Until then a shader samples the image as it is: empty, or a frame behind. static bool title_fill_async() { static const bool on = [] { const char* v = std::getenv("LEONIDA_TITLE_FILL_ASYNC"); return v && std::strcmp(v, "1") == 0; }(); return on; } struct TitleFiller { std::mutex mutex; std::condition_variable wake; std::deque queue; // texture addresses std::unordered_set queued; bool stop = false; std::thread thread; std::uint64_t filled = 0, skipped = 0; std::vector tiled; // the worker's own snapshot of a texture's bytes (fill_unlocked) std::vector columns; // its detiling scratch ~TitleFiller() { { std::lock_guard lock(mutex); stop = true; } wake.notify_one(); if (thread.joinable()) thread.join(); } }; std::unique_ptr title_filler_; std::once_flag title_filler_once_; void queue_title_fill(std::uint64_t address) { std::call_once(title_filler_once_, [this] { title_filler_ = std::make_unique(); TitleFiller* f = title_filler_.get(); f->thread = std::thread([this, f] { run_title_filler(*f); }); }); { std::lock_guard lock(title_filler_->mutex); if (!title_filler_->queued.insert(address).second) return; title_filler_->queue.push_back(address); } title_filler_->wake.notify_one(); } void run_title_filler(TitleFiller& f) { using clock = std::chrono::steady_clock; auto since = clock::now(); for (;;) { std::uint64_t address = 0; { std::unique_lock lock(f.mutex); f.wake.wait(lock, [&] { return f.stop || !f.queue.empty(); }); if (f.stop) return; address = f.queue.front(); f.queue.pop_front(); f.queued.erase(address); } bool filled = false; // A staged texture is filled without the registry lock (the title's threads creating views wait for // it: speed-31, 12 % of the main thread): its bytes, layout and resource are taken under the lock, the // copy, hash and upload are made outside it, and the result is recorded under it again if the texture // still has that resource. Others (host copies, unbound memory) are filled under the lock as before. Resource* r = nullptr; rt::xg_xs::Texture layout{}; std::uint64_t cpu = 0, fills = 0; bool every_byte = false; { std::lock_guard lock(state_.title_texture_mutex); const InTitleTextures inside; const auto it = state_.title_textures.find(address); if (it != state_.title_textures.end()) { TitleTexture& t = *it->second; if (t.resource && t.layout_known && !t.gpu_written && (t.stale || !t.hashed) && title_texture_readable(t)) { t.stale = false; if (t.resource->staged_title() && !t.unbound_bytes) { r = t.resource; r->AddRef(); layout = t.layout; cpu = t.cpu; fills = t.fills; every_byte = t.every_byte(); } else { filled = fill_title_texture(t, true) != 0; } } } } if (r) { filled = fill_unlocked(address, *r, layout, cpu, fills, every_byte, f); r->Release(); } std::size_t left = 0; { std::lock_guard lock(f.mutex); (filled ? f.filled : f.skipped) += 1; left = f.queue.size(); } if (const auto now = clock::now(); now - since >= std::chrono::seconds(10)) { std::fprintf(stderr, "[rt] d3d12: title texture fill worker: %llu filled, %llu skipped in %.0f s, %zu " "queued\n", static_cast(f.filled), static_cast(f.skipped), std::chrono::duration(now - since).count(), left); std::lock_guard lock(f.mutex); f.filled = f.skipped = 0; since = now; } } } // The fill worker's fill of a staged texture: copy, hash and upload without the registry lock, then the result // under it, if the registry still names `r` at `address` and nobody filled it meanwhile. bool fill_unlocked(std::uint64_t address, Resource& r, const rt::xg_xs::Texture& layout, std::uint64_t cpu, std::uint64_t fills, bool every_byte, TitleFiller& f) { const std::uint64_t span = layout.layout.size; f.tiled.resize(std::size_t(span)); const bool copied = copy_guarded(f.tiled.data(), reinterpret_cast(cpu), std::size_t(span), title_memory_write_combined(cpu)); std::uint64_t hash = 0, full = 0; bool full_hashed = false, ok = false, nonzero = false; std::uint64_t staged_ns = 0; if (copied) { hash_guarded(f.tiled.data(), f.tiled.size(), hash); full_hashed = every_byte && hash_guarded(f.tiled.data(), f.tiled.size(), full, true); const auto start = std::chrono::steady_clock::now(); ok = r.upload_staged_title(layout, f.tiled.data(), f.columns, false, nonzero); staged_ns = std::chrono::duration_cast(std::chrono::steady_clock::now() - start) .count(); } std::lock_guard lock(state_.title_texture_mutex); const InTitleTextures inside; const auto it = state_.title_textures.find(address); if (it == state_.title_textures.end() || it->second->resource != &r) return false; // retired meanwhile TitleTexture& t = *it->second; if (!copied) { t.memory.defer(); t.stale = true; return false; } title_stats_.staged_ns += staged_ns; if (!ok) { log_once("staged title texture upload failed, format", int(r.format())); ++title_stats_.fill_failures; t.stale = true; return false; } ++title_stats_.staged_fills; if (t.fills != fills) return true; // another fill recorded itself in between: its hash is as good if (t.owned && !t.fills) r.publish_streamed_texture(); t.hash = hash; t.hashed = true; t.full_hash = full; t.full_hashed = full_hashed; ++t.fills; ++title_stats_.fills; title_stats_.fill_bytes += span; return true; } // LEONIDA_GEOMETRY_ASYNC: one worker runs GeometryViews::refresh whenever a submission asks and none is running. struct GeometryRefresher { std::mutex mutex; std::condition_variable wake; bool kick = false, stop = false; std::thread thread; ~GeometryRefresher() { { std::lock_guard lock(mutex); stop = true; } wake.notify_one(); if (thread.joinable()) thread.join(); } }; std::unique_ptr geometry_refresher_; std::once_flag geometry_refresher_once_; // submissions of several queues may ask at once void kick_geometry_refresh() { std::call_once(geometry_refresher_once_, [this] { geometry_refresher_ = std::make_unique(); GeometryRefresher* r = geometry_refresher_.get(); r->thread = std::thread([this, r] { for (;;) { { std::unique_lock lock(r->mutex); r->wake.wait(lock, [r] { return r->kick || r->stop; }); if (r->stop) return; r->kick = false; } state_.geometry.refresh(DeviceState::copy_geometry); } }); }); { std::lock_guard lock(geometry_refresher_->mutex); geometry_refresher_->kick = true; } geometry_refresher_->wake.notify_one(); } std::uint64_t title_refresh_cursor_ = 0; // under title_texture_mutex std::uint64_t title_map_generation_ = 0; // likewise: the map changes the passes have seen std::chrono::steady_clock::time_point title_retry_all_{}; // likewise leonida::TitleWriteRanges title_map_changes_; // likewise, scratch VkDeviceSize retired_backing_ = 0; std::vector> retired_title_textures_; // likewise std::vector title_tiled_, title_linear_; // scratch, under title_texture_mutex std::vector title_columns_; // The rest under title_texture_mutex. bool refuse_title_view(const char* why, const rt::xg_xs::ResourceDesc& d, std::uint64_t address) { ++title_stats_.refusals; std::uint64_t& n = title_stats_.refused[why]; static std::set> logged; if (!n++ || (logged.size() < 256 && logged.emplace(why, d.format, d.layout).second)) std::fprintf(stderr, "[rt] d3d12: slot-70 texture view is a null view (%s): dimension %u %llux%ux%u mips %u " "format %u samples %u Layout 0x%x flags 0x%x at 0x%llx\n", why, d.dimension, static_cast(d.width), d.height, unsigned(d.depth_or_array), unsigned(d.mips), d.format, d.samples, d.layout, d.flags, static_cast(address)); return false; } // The console layout of a description, as XG lays it out; false with the reason when this XG model lacks it. static bool title_layout(const rt::xg_xs::ResourceDesc& d, rt::xg_xs::Texture& out, const char*& why) { namespace xg = rt::xg_xs; const std::uint32_t mode = xg::select_mode(d); if (d.samples > 1) return why = "multisampled", false; if (mode != xg::kLinear && mode != xg::k4kbS && mode != xg::k64kbS && mode != xg::k64kbD) return why = "swizzle mode the XG model lacks", false; if (!xg::format_info(d.format).bytes) return why = "format the XG model lacks", false; xg::ResourceDesc plain = d; plain.flags &= ~(xg::kRenderTarget | xg::kDepthStencil); if (!xg::build_texture(plain, out)) return why = "description the XG model refuses", false; return true; } // The image a layout fills: the same extent, mips, layers and element (texel or 4x4 block) size. static bool title_layout_fits(const rt::xg_xs::Texture& layout, const rt::xg_xs::ResourceDesc& d, const Resource& r, const char*& why) { const D3D12_RESOURCE_DESC& desc = r.desc(); const leonida::BlockFormat element = r.copy_element(); if (desc.Width != d.width || desc.Height != d.height || desc.DepthOrArraySize != d.depth_or_array || desc.MipLevels != layout.layout.mips || UINT(desc.Dimension) != d.dimension) return why = "texture of another extent, mips or layers at the address", false; if (element.bytes != layout.format.bytes || element.block != layout.format.side) return why = "image element differs from the console's", false; return true; } // Caller holds title_texture_mutex, which the registered resource takes before destruction. Resource* matching_gpu_placement(const rt::xg_xs::ResourceDesc& d, std::uint64_t address, D3D12_RESOURCE_FLAGS required = D3D12_RESOURCE_FLAG_NONE) { std::lock_guard descriptors(state_.descriptor_mutex); return state_.gpu_placements.find(address, leonida::title_gpu_views::other_view(address), [&](const Resource& r) { return (r.desc().Flags & required) == required && TitleGpuPlacements::matches(d, r); }); } bool place_title_view(const rt::xg_xs::ResourceDesc& d, const std::array& words, const D3D12_SHADER_RESOURCE_VIEW_DESC& srv, std::uint64_t address, D3D12_CPU_DESCRIPTOR_HANDLE destination) { if (!address) return refuse_title_view("no address", d, address); const auto write = [&](const TitleTexture& t) { const bool written = write_title_srv(*t.resource, srv, destination, d, address); if (written && !t.gpu_written && t.memory.pending()) ++title_stats_.pending_views; return written; }; auto& textures = state_.title_textures; const auto it = textures.find(address); // An entry without a resource is one destroyed inside the registry, waiting for drain_titles_gone. TitleTexture* t = it == textures.end() || !it->second->resource ? nullptr : it->second.get(); if (!t || !TitleGpuPlacements::matches(d, *t->resource)) { if (Resource* gpu = matching_gpu_placement(d, address)) { ++title_stats_.of_slot133; return write_title_srv(*gpu, srv, destination, d, address); } } if (t && !t->owned) { // the title's slot-133 texture ++title_stats_.of_slot133; if (!t->gpu_written && (t->layout_guessed || t->layout_from_xg || !t->layout_known || t->desc != words)) { const char* why = nullptr; rt::xg_xs::Texture layout; if (title_layout(d, layout, why) && title_layout_fits(layout, d, *t->resource, why)) { static std::atomic logged{0}; if (t->mapped && logged.fetch_add(1, std::memory_order_relaxed) < 32) std::fprintf(stderr, "[rt] d3d12: a slot-70 view gives mapped slot-133 texture 0x%llx its layout: Layout " "0x%x (XG mode %u; was %s)\n", static_cast(address), d.layout, layout.mode, t->layout_guessed ? "guessed" : "unknown"); t->memory.retry(); t->layout = layout; t->desc = words; t->layout_known = true; t->layout_guessed = t->layout_from_xg = false; t->hashed = false; } else { refuse_title_view(why, d, address); // counted; the view of its image is still written } } if (!t->gpu_written && t->layout_known) refresh_title_texture(*t); return write(*t); } if (t && !title_texture_matches(*t, words, srv)) { std::vector formats = t->formats; const bool same_shape = [&] { auto a = t->desc, b = words; a[8] = b[8] = 0; // the format return a == b && rt::xg_xs::format_info(t->desc[8]).bytes == rt::xg_xs::format_info(words[8]).bytes && rt::xg_xs::format_info(t->desc[8]).side == rt::xg_xs::format_info(words[8]).side; }(); retire_title_texture(*t); textures.erase(address); t = make_title_texture(d, words, srv, address, same_shape ? formats : std::vector{}); } else if (t) { ++title_stats_.of_cache; refresh_title_texture(*t); } else { t = make_title_texture(d, words, srv, address, {}); } return t && write(*t); } // An image made for slot-70 views serves another view when it has the description and the view's format. static bool title_texture_matches(const TitleTexture& t, const std::array& words, const D3D12_SHADER_RESOURCE_VIEW_DESC& srv) { const auto has = [&](DXGI_FORMAT f) { return std::find(t.formats.begin(), t.formats.end(), f) != t.formats.end(); }; return t.desc == words && (srv.Format == DXGI_FORMAT_UNKNOWN || has(srv.Format)); } TitleTexture* make_title_texture(const rt::xg_xs::ResourceDesc& d, const std::array& words, const D3D12_SHADER_RESOURCE_VIEW_DESC& srv, std::uint64_t address, std::vector formats) { namespace xg = rt::xg_xs; if (d.flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) return refuse_title_view("GPU-written texture with no slot-133 texture at its address", d, address), nullptr; if (d.dimension < xg::kTexture1D || d.dimension > xg::kTexture3D) return refuse_title_view("dimension", d, address), nullptr; auto entry = std::make_shared(); const char* why = nullptr; if (!title_layout(d, entry->layout, why)) return refuse_title_view(why, d, address), nullptr; const std::uint64_t span = entry->layout.layout.size; entry->cpu = leonida::title_gpu_views::to_cpu(address); // A streamed texture can have views before its pages arrive. Keep the descriptor stable across its first fill. entry->memory.check(0, check_pages_before_read(), [&] { return probe_title_memory(entry->cpu, span, false); }); title_stats_.unreadable += entry->memory.pending(); // The image takes the view's format too when the element is the same size (five-star-recomp does the same); // views in other formats of the same description add theirs (place_title_view). const auto add = [&](DXGI_FORMAT f) { if (f != DXGI_FORMAT_UNKNOWN && std::find(formats.begin(), formats.end(), f) == formats.end()) formats.push_back(f); }; add(DXGI_FORMAT(d.format)); if (srv.Format != DXGI_FORMAT_UNKNOWN && srv.Format != DXGI_FORMAT(d.format)) { const xg::Format a = xg::format_info(d.format), b = xg::format_info(srv.Format); if (a.bytes != b.bytes || a.side != b.side) return refuse_title_view("view format of another element size", d, address), nullptr; add(srv.Format); } D3D12_RESOURCE_DESC pc{}; pc.Dimension = D3D12_RESOURCE_DIMENSION(d.dimension); pc.Width = d.width; pc.Height = d.height; pc.DepthOrArraySize = d.depth_or_array; pc.MipLevels = UINT16(entry->layout.layout.mips); pc.Format = formats.front(); pc.SampleDesc = {1, 0}; pc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; pc.Flags = D3D12_RESOURCE_FLAG_NONE; const Format host = state_.texture_format(pc); if (host.format == VK_FORMAT_UNDEFINED) return refuse_title_view("format the layer lacks", d, address), nullptr; if (host.aspects != VK_IMAGE_ASPECT_COLOR_BIT) return refuse_title_view("depth or stencil format", d, address), nullptr; // Keep CPU-copy semantics. Resource::create_texture selects host copies or staged uploads from Vulkan requirements. const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_CUSTOM, D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, D3D12_MEMORY_POOL_L0, 1, 1}; static const bool defer = [] { const char* value = std::getenv("LEONIDA_TITLE_IMAGE_DEFER"); return !value || std::strcmp(value, "0"); }(); const auto origin = defer && entry->memory.pending() ? TitleImageOrigin::pending_stream : TitleImageOrigin::streamed; void* made = nullptr; const HRESULT hr = create_committed(&heap, D3D12_HEAP_FLAG_NONE, &pc, D3D12_RESOURCE_STATE_COMMON, formats.size() > 1 ? UINT32(formats.size()) : 0, formats.data(), __uuidof(ID3D12Resource), &made, std::nullopt, origin); Resource* r = SUCCEEDED(hr) && made ? Resource::from(static_cast(made)) : nullptr; if (!r) { if (made) static_cast(made)->Release(); log_once("an image for a slot-70 texture view could not be made; HRESULT", int(hr)); return refuse_title_view("image not created", d, address), nullptr; } if (!title_layout_fits(entry->layout, d, *r, why)) { r->Release(); return refuse_title_view(why, d, address), nullptr; } r->place_at_title_address(reinterpret_cast(static_cast(address))); entry->address = address; entry->desc = words; entry->layout_known = true; entry->set_resource(r); entry->owned = true; entry->formats = std::move(formats); if (title_fill_async()) { entry->stale = true; // filled by the fill worker (queued below, once it is in the registry) } else if (!entry->memory.pending()) { fill_title_texture(*entry, true); } ++title_stats_.made; TitleTexture* t = entry.get(); state_.title_textures[address] = std::move(entry); if (title_fill_async() && !t->memory.pending()) queue_title_fill(address); return t; } void retire_title_texture(TitleTexture& t) { if (!t.owned || !t.resource) return; // Its T#s leave the hash table now (a later texture at the address takes them over); the image itself goes // a few seconds later, when no submission can still read it. if (t.resource->image_address()) state_.forget_image(t.resource->image_address()); retired_backing_ += t.resource->image_backing_bytes(); retired_title_textures_.emplace_back(std::chrono::steady_clock::now(), t.resource); t.resource = nullptr; ++title_stats_.retired; } static bool texture_probe() { static const bool enabled = [] { const char* v = std::getenv("LEONIDA_TEXTURE_PROBE"); return v && std::strcmp(v, "0"); }(); return enabled; } static bool check_pages_before_read() { static const bool enabled = [] { const char* v = std::getenv("LEONIDA_TEXTURE_PAGE_CHECK"); return !v || std::strcmp(v, "0"); }(); return enabled; } static bool refresh_mapped_pages() { static const bool enabled = [] { const char* value = std::getenv("LEONIDA_REFRESH_MAPPED_TEXTURES"); return !value || std::strcmp(value, "0"); }(); return enabled; } // texture_memory_readable, timed and counted (TitleTextureStats::probes). bool probe_title_memory(std::uint64_t cpu, std::uint64_t span, bool waited, leonida::TexturePageCommitter commit = nullptr) { const auto start = std::chrono::steady_clock::now(); const bool readable = leonida::texture_memory_readable(cpu, span, commit); const std::size_t where = title_pass_ ? 0 : 1; TitleTextureStats& s = title_stats_; s.probe_ns[where] += std::chrono::duration_cast( std::chrono::steady_clock::now() - start).count(); ++s.probes[where]; s.rechecks[where] += waited; s.readable_now[where] += waited && readable; return readable; } // A mapped texture can lose its pages between views or between refreshes. bool title_texture_readable(TitleTexture& t) { const bool guard = check_pages_before_read(); if (!guard && !t.memory.pending()) return true; const bool mapped = t.mapped && refresh_mapped_pages(); const auto commit = mapped ? leonida::kernel_writes::state().committer.load(std::memory_order_acquire) : nullptr; const bool waited = t.memory.pending(); // The answer is kept (generation 0) until a map change over the texture, a write into it or the periodic // retry of refresh_title_textures asks again. return t.memory.check(0, guard && !mapped, [&] { return probe_title_memory(t.cpu, t.layout.layout.size, waited, commit); }, guard && !mapped); } // LEONIDA_TITLE_VIEW_REFRESH_MS (0 by default: at every view): a texture's bytes are checked when a slot-70 view of // it is written at most this often (the refresh pass still looks at it on its own period, and a stale texture is // checked at once). After the load a title thread spent a fifth of its time hashing textures here, view by view // (speed-24 wait sampler: refresh_title_texture < write_placed_texture_view < slot 70). void refresh_title_texture(TitleTexture& t) { // LEONIDA_TITLE_FILL_ASYNC=1: a view neither hashes nor fills. A texture never filled or known stale goes to // the fill worker; later changes are found by the periodic pass and the write journal, as before. if (title_fill_async()) { if (!t.hashed || t.stale) queue_title_fill(t.address); return; } static const auto period = std::chrono::milliseconds([] { const char* v = std::getenv("LEONIDA_TITLE_VIEW_REFRESH_MS"); return v && *v ? std::strtoll(v, nullptr, 10) : 0ll; }()); if (period.count() && t.hashed && !t.stale) { const auto now = std::chrono::steady_clock::now(); if (now - t.view_checked < period) return; t.view_checked = now; } std::uint64_t hash = 0; if (!title_texture_readable(t)) return; if (!hash_guarded(reinterpret_cast(static_cast(t.cpu)), std::size_t(t.layout.layout.size), hash)) { t.memory.defer(); return; } if (!t.hashed || hash != t.hash || t.stale) fill_title_texture(t, true); } // Snapshot the whole footprint before uploading any subresource. A concurrent unmap defers the fill. // Private title staging bypasses the D3D12 submit callbacks. Generic staged copies require an outer fill. std::uint64_t fill_title_texture(TitleTexture& t, bool staged) { const rt::xg_xs::Texture& layout = t.layout; const std::uint32_t mips = layout.layout.mips, slices = layout.array; if (!staged && !t.unbound_bytes && !t.resource->staged_title()) for (UINT sub = 0; sub < mips * slices; ++sub) if (!t.resource->host_copy_now(sub)) { t.stale = true; return 0; } const std::uint64_t span = layout.layout.size; if (!title_texture_readable(t)) return 0; title_tiled_.resize(std::size_t(span)); if (!copy_guarded(title_tiled_.data(), reinterpret_cast(t.cpu), std::size_t(span), title_memory_write_combined(t.cpu))) { // The section changed after VirtualQuery. Preserve the last complete upload and retry. t.memory.defer(); t.stale = true; return 0; } if (!t.owned && t.unbound_bytes) { if (!t.resource->image()) { t.stale = true; return 0; } t.set_resource(t.resource); } if (t.owned && t.unbound_bytes) { if (!t.resource->back_streamed_texture()) { t.stale = true; return 0; } t.set_resource(t.resource); } std::uint64_t hash = 0; hash_guarded(title_tiled_.data(), title_tiled_.size(), hash); t.full_hashed = t.every_byte() && hash_guarded(title_tiled_.data(), title_tiled_.size(), t.full_hash, true); const bool volume = layout.layout.dimension == rt::xg_xs::kTexture3D; const bool trace_pool = leonida::dstorage::trace_enabled() && leonida::title_gpu_views::other_view(t.cpu); bool nonzero = false; bool ok = true; if (t.resource->staged_title()) { const auto start = std::chrono::steady_clock::now(); ok = t.resource->upload_staged_title(layout, title_tiled_.data(), title_columns_, trace_pool, nonzero); title_stats_.staged_ns += std::chrono::duration_cast( std::chrono::steady_clock::now() - start).count(); if (ok) ++title_stats_.staged_fills; if (!ok) log_once("staged title texture upload failed, format", int(t.resource->format())); } else { for (std::uint32_t slice = 0; slice < slices && ok; ++slice) { for (std::uint32_t level = 0; level < mips && ok; ++level) { const auto& mip = layout.layout.plane[0].mips[level]; const std::uint32_t row_pitch = mip.width_elements * layout.format.bytes; const std::uint32_t slice_pitch = row_pitch * mip.height_elements; title_linear_.resize(std::size_t(slice_pitch) * (volume ? mip.depth : 1)); rt::xg_xs::copy_elements(layout, level, slice, title_tiled_.data(), title_linear_.data(), row_pitch, slice_pitch, title_columns_); if (trace_pool && !nonzero) nonzero = std::any_of(title_linear_.begin(), title_linear_.end(), [](auto byte) { return byte != 0; }); const HRESULT hr = t.resource->upload_title_subresource(level + slice * mips, title_linear_.data(), row_pitch, slice_pitch, staged); if (FAILED(hr)) { log_once("a title texture's subresource could not be filled; HRESULT", int(hr)); ok = false; } } } } if (!ok) { ++title_stats_.fill_failures; t.stale = true; return 0; } if (trace_pool) std::fprintf(stderr, "[rt] ds-pool-fill cpu=%llx size=%llu staged=%d nonzero=%d\n", static_cast(t.cpu), static_cast(span), int(staged), int(nonzero)); if (t.owned && !t.fills) t.resource->publish_streamed_texture(); t.hash = hash; t.hashed = true; t.stale = false; ++t.fills; ++title_stats_.fills; title_stats_.fill_bytes += span; return span; } static bool title_memory_write_combined(std::uint64_t address) { MEMORY_BASIC_INFORMATION region{}; return VirtualQuery(reinterpret_cast(static_cast(address)), ®ion, sizeof(region)) && (region.Protect & PAGE_WRITECOMBINE); } bool write_title_srv(Resource& r, const D3D12_SHADER_RESOURCE_VIEW_DESC& srv, D3D12_CPU_DESCRIPTOR_HANDLE dest, const rt::xg_xs::ResourceDesc& d, std::uint64_t address) { CreateShaderResourceView(static_cast(&r), &srv, dest); const auto* w = reinterpret_cast(dest.ptr); const auto written = [w] { return (w[0] | w[1] | w[2] | w[3] | w[4] | w[5] | w[6] | w[7]) != 0; }; if (written()) return true; // A slot-133 texture made in a stand-in format (an R9G9B9E5 target as R11G11B10F, console_format_stand_ins) // has no view in the console format: the view in the texture's own format reads what it holds. if (srv.Format != DXGI_FORMAT_UNKNOWN && srv.Format == r.desc().Format) { D3D12_SHADER_RESOURCE_VIEW_DESC own = srv; own.Format = DXGI_FORMAT_UNKNOWN; CreateShaderResourceView(static_cast(&r), &own, dest); if (written()) { log_once("a slot-70 view in another format than its texture's reads it in the texture's own format; " "view format", int(srv.Format)); return true; } } static std::atomic logged{0}; if (logged.fetch_add(1, std::memory_order_relaxed) < 16) std::fprintf(stderr, "[rt] d3d12: slot-70 view of a title texture at 0x%llx refused by the SRV checks: view format " "%d dimension %d mapping 0x%x (texture format %d)\n", static_cast(address), int(srv.Format), int(srv.ViewDimension), unsigned(srv.Shader4ComponentMapping), int(r.desc().Format)); return refuse_title_view("SRV refused for the texture", d, address); } // One line of what slot 70 was asked for, and one of what the refresh did since the last line (NOTES: step 4). void log_title_census(const char* when) { TitleTextureStats& s = title_stats_; std::vector>> asked; for (const auto& [key, n] : s.asked) asked.emplace_back(n, key); std::sort(asked.rbegin(), asked.rend()); std::string census; for (std::size_t i = 0; i < asked.size() && i < 24; ++i) { char text[64]; std::snprintf(text, sizeof(text), "%s%u/0x%x/%u/%u:%llu", i ? " " : "", asked[i].second[0], asked[i].second[1], asked[i].second[2], asked[i].second[3], static_cast(asked[i].first)); census += text; } std::string refused; for (const auto& [why, n] : s.refused) refused += (refused.empty() ? "" : "; ") + why + " " + std::to_string(n); std::size_t owned = 0, slot133 = 0, mapped = 0, filled = 0; VkDeviceSize owned_bytes = 0, placed_bytes = 0, host_heap_bytes = 0; for (const auto& [address, t] : state_.title_textures) { (t->owned ? owned : slot133) += 1; if (!t->owned && t->resource && t->unbound_bytes) t->set_resource(t->resource); mapped += t->mapped; filled += t->fills > 0; (t->owned ? owned_bytes : placed_bytes) += t->backing_bytes; if (!t->device_local) host_heap_bytes += t->backing_bytes; } if (leonida::mem_probe::interval_seconds()) log_title_image_uses(state_.title_textures, retired_title_textures_.size(), retired_backing_, state_.zero_image_bytes.load()); if (leonida::mem_probe::interval_seconds()) std::fprintf(stderr, "[rt] mem-probe: registered image backing: %.1f MiB from slot 70, %.1f MiB from slot " "133, %.1f MiB total on non-device-local types; staged fills %llu, %.3f s, buffer %.1f MiB\n", double(owned_bytes) / 1048576.0, double(placed_bytes) / 1048576.0, double(host_heap_bytes) / 1048576.0, static_cast(s.staged_fills), double(s.staged_ns) / 1e9, double(state_.title_upload.capacity()) / 1048576.0); std::fprintf(stderr, "[rt] d3d12: title textures (%s): %llu slot-70 texture views (%zu kinds), %llu of slot-133 textures, " "%llu of images made for them (%llu made, %llu over memory not readable yet, %llu retired), %llu " "null views; registry %zu images " "(%zu made, %zu slot 133 of %llu registered, %zu mapped, %zu filled); %llu fills %.1f MiB, %llu " "failed\n", when, static_cast(s.views), s.asked.size(), static_cast(s.of_slot133), static_cast(s.of_cache), static_cast(s.made), static_cast(s.unreadable), static_cast(s.retired), static_cast(s.null_views), state_.title_textures.size(), owned, slot133, static_cast(s.registered), mapped, filled, static_cast(s.fills), double(s.fill_bytes) / 1048576.0, static_cast(s.fill_failures)); const auto host = state_.context->host_texture_stats(); std::fprintf(stderr, "[rt] d3d12: ordered title host copies %llu, GPU waits %llu; " "slot-70 views awaiting readable memory: %llu\n", static_cast(host.copies), static_cast(host.waits), static_cast(s.pending_views)); std::fprintf(stderr, "[rt] d3d12: title textures census (format/Layout/dimension/mips:views): %s\n", census.c_str()); if (!refused.empty()) std::fprintf(stderr, "[rt] d3d12: title textures null views by reason: %s\n", refused.c_str()); std::string maps; std::size_t listed = 0; for (const auto& [address, t] : state_.title_textures) { if (!t->mapped || !t->resource || listed++ >= 16) continue; const D3D12_RESOURCE_DESC& rd = t->resource->desc(); char text[160]; std::snprintf(text, sizeof(text), "%s0x%llx %llux%u fmt %d layout %s mode %u, %u T#s, %llu fills", maps.empty() ? "" : "; ", static_cast(address), static_cast(rd.Width), rd.Height, int(rd.Format), t->layout_guessed ? "guessed" : t->layout_from_xg ? "XG" : t->layout_known ? "viewed" : "none", t->layout.mode, t->resource->shader_views(), static_cast(t->fills)); maps += text; } if (!maps.empty()) std::fprintf(stderr, "[rt] d3d12: title textures mapped: %s\n", maps.c_str()); if (s.passes) { std::fprintf(stderr, "[rt] d3d12: title texture refresh: %llu passes, %llu XG-written ranges, %llu textures " "checked (%.1f MiB read for hashes), %llu changed, %llu deferred, %.1f MiB filled (%.2f MiB a " "pass on average, %.2f MiB at most)\n", static_cast(s.passes), static_cast(s.written_ranges), static_cast(s.checked), double(s.hashed) / 1048576.0, static_cast(s.changed), static_cast(s.deferred), double(s.filled_bytes) / 1048576.0, double(s.filled_bytes) / 1048576.0 / double(s.passes), double(s.max_pass_bytes) / 1048576.0); const double ms_per_ns_per_pass = 1e-6 / double(s.passes); std::fprintf(stderr, "[rt] title texture hash time %.3f ms/pass; refresh total %.3f ms/pass\n", double(s.hash_ns) * ms_per_ns_per_pass, double(s.refresh_ns) * ms_per_ns_per_pass); // What the passes cost and why: the probes of memory (texture_memory_readable) and the textures that // wait for readable memory, now. std::size_t waiting = 0, waiting_stale = 0, waiting_mapped = 0, stale = 0; for (const auto& [address, t] : state_.title_textures) { if (t->gpu_written || !t->layout_known || !t->resource) continue; stale += t->stale; if (!t->memory.pending()) continue; ++waiting; waiting_stale += t->stale; waiting_mapped += t->mapped; } const double per_pass = 1.0 / double(s.passes); std::fprintf(stderr, "[rt] title texture rechecks: %.1f probes a pass (%.3f ms/pass), %.1f of waiting textures a " "pass (%llu found readable now); %zu textures wait for readable memory (%zu stale, %zu " "mapped), %zu stale in all; max pass %.3f ms; outside passes %llu probes (%.3f ms), %llu of " "waiting textures, %llu found readable\n", double(s.probes[0]) * per_pass, double(s.probe_ns[0]) * ms_per_ns_per_pass, double(s.rechecks[0]) * per_pass, static_cast(s.readable_now[0]), waiting, waiting_stale, waiting_mapped, stale, double(s.max_refresh_ns) * 1e-6, static_cast(s.probes[1]), double(s.probe_ns[1]) * 1e-6, static_cast(s.rechecks[1]), static_cast(s.readable_now[1])); s.passes = s.checked = s.hashed = s.changed = s.deferred = s.filled_bytes = s.max_pass_bytes = 0; std::fprintf(stderr, "[rt] title texture pass split: written ranges and map changes %.3f ms/pass (%.1f map ranges a " "pass, %llu passes probed all), mapped and stale textures %.3f ms/pass (%.1f visited a pass), " "fills %.3f ms/pass\n", double(s.written_ns) * ms_per_ns_per_pass, double(s.map_ranges) * per_pass, static_cast(s.map_all), double(s.every_pass_ns) * ms_per_ns_per_pass, double(s.every_pass_visits) * per_pass, double(s.fill_ns) * ms_per_ns_per_pass); s.written_ns = s.every_pass_ns = s.every_pass_visits = s.fill_ns = s.map_ranges = s.map_all = 0; s.hash_ns = s.refresh_ns = s.max_refresh_ns = 0; s.written_ranges = 0; s.probes = s.probe_ns = s.rechecks = s.readable_now = {}; } } public: void own(const OwnedRuntime& owned) { owned_ = owned; } void set_outer(IUnknown* outer) { outer_ = outer; } // The buffer resource holding console VA `va`, with a reference added for the caller, or null when no resource this // layer made holds it. `start` and `size` are the resource's first VA and byte size. // Only this layer's own buffers have a VA in the registry (the swapchain's are images, a copy's staging binding has // no VA), so an ID found by VA is the ID3D12Resource pointer of a Resource (resource_id). ID3D12Resource* add_ref_buffer_at(std::uint64_t va, std::uint64_t bytes, std::uint64_t& start, std::uint64_t& size) { leonida::ResourceId id = 0; ID3D12Resource* found = nullptr; const bool ok = state_.context->buffer_resource_at(va, bytes, id, start, size, [&](leonida::ResourceId candidate) { auto* resource = static_cast(reinterpret_cast(candidate)); if (!resource->try_add_ref()) return false; found = resource; return true; }); return ok ? found : nullptr; } class RawTileReader { public: RawTileReader(std::uint64_t address, std::size_t size) : address_(address), size_(size), cache_(std::min(size, block_size * slots)) { tags_.fill(SIZE_MAX); } bool copy(std::size_t offset, std::uint8_t* to, std::size_t bytes) { if (offset > size_ || bytes > size_ - offset) return false; while (bytes) { const auto block = offset / block_size; const auto slot = block % slots; const auto base = block * block_size; const auto available = std::min(block_size, size_ - base); auto* window = cache_.data() + slot * block_size; if (tags_[slot] != block) { SIZE_T copied{}; if (!ReadProcessMemory(GetCurrentProcess(),reinterpret_cast(address_+base), window,available,&copied) || copied!=available) return false; tags_[slot]=block; } const auto n=std::min(bytes,available-(offset-base)); std::memcpy(to,window+offset-base,n); offset+=n;to+=n;bytes-=n; } return true; } private: static constexpr std::size_t block_size = 64 * 1024, slots = 8; std::uint64_t address_; std::size_t size_; std::vector cache_; std::array tags_; }; bool raw_texture_view(const D3D12_RESOURCE_DESC& raw, const D3D12_SHADER_RESOURCE_VIEW_DESC& view, std::uint64_t address, D3D12_CPU_DESCRIPTOR_HANDLE destination) { namespace ct = leonida::console_texture; if (!address || !destination.ptr || (address & 255) || raw.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) return false; Resource* placed = nullptr; { std::lock_guard lock(state_.title_image_mutex); auto [begin, end] = state_.title_images.equal_range(address); for (auto it = begin; it != end; ++it) { const auto& shape = it->second->desc(); if (raw.Width == shape.Width && raw.Height == shape.Height && raw.Format == shape.Format && raw.DepthOrArraySize == shape.DepthOrArraySize && raw.MipLevels == shape.MipLevels && raw.SampleDesc.Count == shape.SampleDesc.Count && it->second->try_add_ref()) { placed = it->second; break; } } } if (placed) { CreateShaderResourceView(placed, &view, destination); placed->Release(); return true; } // Raw sampled surfaces have no COM owner. Only consume the full span of a retained title allocation // and a layout the console texture computer can actually untile. if (view.ViewDimension != D3D12_SRV_DIMENSION_TEXTURE2D || raw.DepthOrArraySize != 1 || raw.MipLevels != 1 || raw.SampleDesc.Count != 1 || (unsigned(raw.Flags) & 0x0f) || raw.Width > ct::kMaxExtent || raw.Height > ct::kMaxExtent || (view.Format != raw.Format && view.Format != DXGI_FORMAT_UNKNOWN)) return false; const UINT mode = unsigned(raw.Layout); if (mode != 0 && mode != 1 && (mode & ~255u) != 256u) return false; const UINT swizzle = mode == 0 ? ct::kSw4kbS : mode == 1 ? ct::kLinear : mode & 255u; ct::TextureDesc d{}; d.width = static_cast(raw.Width); d.height = raw.Height; d.format = unsigned(raw.Format); d.swizzle = swizzle; const auto texture = ct::Texture::make(d); if (!texture || texture->planes.size() != 1 || !texture->planes[0].layout.addressable()) return false; const auto fmt = ct::format(d.format); if (!fmt || fmt->stencil) return false; const auto& level = texture->planes[0].layout; const auto& mip = level.mips[0]; const std::size_t row = std::size_t(mip.width) * fmt->bytes, bytes = row * mip.height; std::uint64_t lo = 0, hi = 0; if (!bytes || row > UINT_MAX || bytes > UINT_MAX || texture->size > SIZE_MAX || !leonida::title_va_aliases().title_memory(address, lo, hi) || texture->size > hi - address) return false; // Bound CPU and transfer scratch per upload. The full title surface can be hundreds of // megabytes; the title already owns its source, and the copy on the GPU is the one sampled. RawTileReader source(address,static_cast(texture->size)); constexpr std::size_t stripe_bytes = 2 * 1024 * 1024; const UINT max_rows = static_cast(std::min(mip.height, std::max(1,stripe_bytes/row))); std::vector linear(row*max_rows); std::vector columns; if (swizzle != ct::kLinear) { std::uint64_t origin{}; if (level.offset(0,0,0,0,origin)!=ct::Error::ok) return false; columns.resize(mip.width); for (UINT x=0; x(state_, clean, heap, D3D12_HEAP_FLAG_NONE); const Format backing = state_.texture_format(clean); if (backing.format == VK_FORMAT_UNDEFINED || backing.typeless || FAILED(resource->create_texture(backing))) { raw_images_.erase(key); return false; } resource->set_raw_image_address(address); cached.resource = std::move(resource); } const UINT stripes = (mip.height + max_rows - 1) / max_rows; cached.fingerprints.resize(stripes); for (UINT first=0, strip=0; firstbytes,fmt->bytes)) return false; } } const std::span content(linear.data(),used); const auto digest = leonida::sha256_hex(content); if (cached.fingerprints[strip] == digest) continue; const UINT bottom = std::min(raw.Height,(first+rows)*fmt->block); const D3D12_BOX box{0,first*fmt->block,0,UINT(raw.Width),bottom,1}; const HRESULT hr = cached.resource->WriteToSubresource(0,&box,linear.data(),UINT(row),UINT(used)); if (FAILED(hr)) return false; cached.fingerprints[strip] = digest; } CreateShaderResourceView(cached.resource.get(), &view, destination); return true; } UINT STDMETHODCALLTYPE GetNodeCount() override { return 1; } // The Vulkan physical device's LUID, which is the DXGI adapter's on Windows. Zero (logged) when the driver has // none to report (deviceLUIDValid false). LUID STDMETHODCALLTYPE GetAdapterLuid() override { return state_.luid; } // The CUSTOM equivalent of a standard heap type, from the D3D12 documentation's table for the architecture // D3D12_FEATURE_ARCHITECTURE reports. NUMA (a discrete GPU): DEFAULT is GPU-only memory in L1, UPLOAD // write-combined and READBACK write-back system memory in L0, GPU_UPLOAD write-combined L1. UMA (an integrated // GPU, CacheCoherentUMA FALSE): the same pages, all in L0, as the host runtime answers on a Radeon 780M (AMD // 32.0.13030.13001). The pool only names the answer; memory is chosen by the CPU page property either way. CUSTOM // and unknown types have // no equivalent and get an all-zero answer (D3D12 reports them through the debug layer), with node 0 in both node // masks as the host runtime gives it (d3d12_fence_timing_test compares CUSTOM, an unknown type and node mask 2). D3D12_HEAP_PROPERTIES STDMETHODCALLTYPE GetCustomHeapProperties(UINT node_mask, D3D12_HEAP_TYPE type) override { D3D12_HEAP_PROPERTIES properties{}; properties.CreationNodeMask = properties.VisibleNodeMask = 1; if (node_mask > 1) { log_once("GetCustomHeapProperties node mask", int(node_mask)); return properties; } switch (type) { case D3D12_HEAP_TYPE_DEFAULT: properties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_NOT_AVAILABLE; properties.MemoryPoolPreference = D3D12_MEMORY_POOL_L1; break; case D3D12_HEAP_TYPE_UPLOAD: properties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE; properties.MemoryPoolPreference = D3D12_MEMORY_POOL_L0; break; case D3D12_HEAP_TYPE_READBACK: properties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_WRITE_BACK; properties.MemoryPoolPreference = D3D12_MEMORY_POOL_L0; break; case D3D12_HEAP_TYPE_GPU_UPLOAD: properties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE; properties.MemoryPoolPreference = D3D12_MEMORY_POOL_L1; break; default: log_once("GetCustomHeapProperties heap type without a custom equivalent:", int(type)); return properties; } if (state_.uma) properties.MemoryPoolPreference = D3D12_MEMORY_POOL_L0; properties.Type = D3D12_HEAP_TYPE_CUSTOM; return properties; } HRESULT STDMETHODCALLTYPE SetEventOnMultipleFenceCompletion(ID3D12Fence* const* fences, const UINT64* values, UINT count, D3D12_MULTIPLE_FENCE_WAIT_FLAGS flags, HANDLE event) override { return set_event_on_multiple_fence_completion(*state_.context, fences, values, count, flags, event, identity()); } HRESULT STDMETHODCALLTYPE GetDeviceRemovedReason() override { if (removed_.load(std::memory_order_acquire)) return DXGI_ERROR_DEVICE_REMOVED; return (state_.context && state_.context->is_device_lost()) ? DXGI_ERROR_DEVICE_REMOVED : S_OK; } // Residency and power (D3D-33, docs/d3d12_vulkan.md section 4.1). Vulkan has no residency API: memory from // vkAllocateMemory stays usable by the device until vkFreeMemory, and paging under pressure is the kernel // driver's job (WDDM on Windows), invisible to the application. So every pageable object of this device is // always resident, MakeResident has nothing to do and Evict, which D3D12 documents as a hint the runtime may // defer, can be dropped. Only the arguments are checked; the objects themselves are not touched. HRESULT STDMETHODCALLTYPE MakeResident(UINT count, ID3D12Pageable* const* objects) override { return count && !objects ? E_INVALIDARG : S_OK; } HRESULT STDMETHODCALLTYPE Evict(UINT count, ID3D12Pageable* const* objects) override { return count && !objects ? E_INVALIDARG : S_OK; } // Device1: priorities only order what the OS evicts first under memory pressure. VK_EXT_pageable_device_local_memory // could pass them on, but it is optional and changes no result, so they are accepted and dropped. Any UINT is a // valid priority (the D3D12_RESIDENCY_PRIORITY values are named points, the low 24 bits a refinement). As on the // host runtime (d3d12_residency_test, RTX 3060 / 610.88), only objects that own their memory take one: committed // resources and heaps. A placed resource (a reserved one too, by the same rule; not measured), a descriptor heap, a query heap or a fence is E_INVALIDARG. // The host also removes its device then (DXGI_ERROR_INVALID_CALL); the layer doesn't, since a console title that // sets priorities on its placed resources would lose its device over a hint. HRESULT STDMETHODCALLTYPE SetResidencyPriority(UINT count, ID3D12Pageable* const* objects, const D3D12_RESIDENCY_PRIORITY* priorities) override { if (count && (!objects || !priorities)) return E_INVALIDARG; for (UINT i = 0; i < count; ++i) { if (from(objects[i])) continue; const Resource* resource = from(objects[i]); if (!resource || !resource->committed()) return E_INVALIDARG; } return S_OK; } // Device3: the asynchronous MakeResident. The objects are already resident, so the work is complete at once // and the fence is signalled from the CPU now. The caller's queue Wait on it must not hang, which is why the // signal is kept although the residency part is a no-op. DENY_OVERBUDGET cannot fail: nothing is paged in. A // null fence is accepted, as the host runtime does: there is nothing to signal. HRESULT STDMETHODCALLTYPE EnqueueMakeResident(D3D12_RESIDENCY_FLAGS flags, UINT count, ID3D12Pageable* const* objects, ID3D12Fence* fence, UINT64 value) override { if ((count && !objects) || (flags & ~D3D12_RESIDENCY_FLAG_DENY_OVERBUDGET)) return E_INVALIDARG; return fence ? fence->Signal(value) : S_OK; } // Stable power state pins GPU clocks for profiling, a developer-mode feature on Windows. Vulkan has no clock // control (vendor tools do it outside the API), and the game's frame does not depend on the clocks, so the // request is accepted. Success is what D3D12 returns on a machine where the call is allowed. HRESULT STDMETHODCALLTYPE SetStablePowerState(BOOL) override { return S_OK; } // Device6: lets the driver run background shader recompilation and profiling-guided optimisation. Vulkan // drivers do that, if at all, without an API to steer it, so there is nothing to start or stop. The completion // event is set at once, since no measurement is running, and no further measurements are wanted. HRESULT STDMETHODCALLTYPE SetBackgroundProcessingMode(D3D12_BACKGROUND_PROCESSING_MODE mode, D3D12_MEASUREMENTS_ACTION action, HANDLE event, BOOL* further_measurements) override { if (unsigned(mode) > unsigned(D3D12_BACKGROUND_PROCESSING_MODE_DISABLE_PROFILING_BY_SYSTEM) || unsigned(action) > unsigned(D3D12_MEASUREMENTS_ACTION_DISCARD_PREVIOUS)) return E_INVALIDARG; if (further_measurements) *further_measurements = FALSE; if (event) SetEvent(event); return S_OK; } // STUB HRESULT STDMETHODCALLTYPE EnumerateMetaCommands(UINT* count, D3D12_META_COMMAND_DESC*) override { if (!count) return E_INVALIDARG; *count = 0; return S_OK; } HRESULT STDMETHODCALLTYPE EnumerateMetaCommandParameters(REFGUID, D3D12_META_COMMAND_PARAMETER_STAGE, UINT*, UINT*, D3D12_META_COMMAND_PARAMETER_DESC*) override { return E_INVALIDARG; } HRESULT STDMETHODCALLTYPE CreateMetaCommand(REFGUID, UINT, const void*, SIZE_T, REFIID, void** out) override { if (out) *out = nullptr; return E_INVALIDARG; } // STUB D3D12_DRIVER_MATCHING_IDENTIFIER_STATUS STDMETHODCALLTYPE CheckDriverMatchingIdentifier( D3D12_SERIALIZED_DATA_TYPE type, const D3D12_SERIALIZED_DATA_DRIVER_MATCHING_IDENTIFIER*) override { return type == D3D12_SERIALIZED_DATA_RAYTRACING_ACCELERATION_STRUCTURE ? D3D12_DRIVER_MATCHING_IDENTIFIER_UNRECOGNIZED : D3D12_DRIVER_MATCHING_IDENTIFIER_UNSUPPORTED_TYPE; } // STUB void STDMETHODCALLTYPE RemoveDevice() override { removed_.store(true, std::memory_order_release); } HRESULT STDMETHODCALLTYPE CreateCommandQueue(const D3D12_COMMAND_QUEUE_DESC* desc, REFIID riid, void** out) override { constexpr auto method = "ID3D12Device::CreateCommandQueue"; if (!desc) return d3d12_trace::result(method, E_INVALIDARG); // As the host runtime: no bundle queues, the three D3D12 priorities (realtime refused, below), one flag and // one node. A valid description without an output is E_UNEXPECTED there, not a capability check. if (desc->Type == D3D12_COMMAND_LIST_TYPE_BUNDLE || UINT(desc->Type) > D3D12_COMMAND_LIST_TYPE_VIDEO_ENCODE || (desc->Priority != D3D12_COMMAND_QUEUE_PRIORITY_NORMAL && desc->Priority != D3D12_COMMAND_QUEUE_PRIORITY_HIGH && desc->Priority != D3D12_COMMAND_QUEUE_PRIORITY_GLOBAL_REALTIME) || (desc->Flags & ~D3D12_COMMAND_QUEUE_FLAG_DISABLE_GPU_TIMEOUT) || desc->NodeMask > 1) { log_once("CreateCommandQueue refused (type, priority, flags or node mask), type", desc->Type); return d3d12_trace::result(method, E_INVALIDARG); } // Global realtime priority needs SeIncreaseBasePriorityPrivilege enabled in the effective token, as on the // Windows D3D12 runtime; without it, this answer. Vulkan queue priorities (and VK_KHR_global_priority) are // fixed at vkCreateDevice time before CreateCommandQueue is called, so a privileged request leases from the // device's pre-created VkQueue pool like D3D12_COMMAND_QUEUE_PRIORITY_HIGH and logs the approximation once. if (desc->Priority == D3D12_COMMAND_QUEUE_PRIORITY_GLOBAL_REALTIME && !has_global_realtime_privilege()) { log_once("CreateCommandQueue refused (global realtime priority), type", desc->Type); return d3d12_trace::result(method, DXGI_ERROR_ACCESS_DENIED); } if (!out) return d3d12_trace::result(method, E_UNEXPECTED); *out = nullptr; if (desc->Type != D3D12_COMMAND_LIST_TYPE_DIRECT && desc->Type != D3D12_COMMAND_LIST_TYPE_COMPUTE && desc->Type != D3D12_COMMAND_LIST_TYPE_COPY) return d3d12_trace::result(method, E_INVALIDARG); if (desc->Priority == D3D12_COMMAND_QUEUE_PRIORITY_GLOBAL_REALTIME) log_once("CreateCommandQueue: global realtime priority runs on a standard-priority Vulkan queue, type", desc->Type); // Caller-owned devices that only provide the legacy queue cannot acquire more handles from their VkDevice. if (state_.info.command_queues.empty()) return d3d12_trace::result(method, create_command_queue(*state_.context, state_.info.queue, state_.info.queue_family, *desc, riid, out, identity(), state_.clock_for(state_.info.queue_family))); // A VkQueue of the type's own family first, then the graphics family; shared when every one is in use. const bool compute = desc->Type == D3D12_COMMAND_LIST_TYPE_COMPUTE; const bool copy = desc->Type == D3D12_COMMAND_LIST_TYPE_COPY; auto& own_users = compute ? compute_users_ : copy_users_; const auto& own_queues = compute ? state_.info.compute_queues : state_.info.copy_queues; const std::uint32_t own_family = compute ? state_.info.compute_family : state_.info.copy_family; const std::span own = compute || copy ? std::span(own_users) : std::span(); std::vector* users = nullptr; std::size_t slot = 0; std::uint32_t sharing = 0; // other D3D12 queues already on the chosen VkQueue { std::lock_guard lock(queue_mutex_); const auto chosen = leonida::pick_queue_slot({own, queue_users_}); if (chosen.pool == SIZE_MAX) return d3d12_trace::result(method, E_OUTOFMEMORY); // no VkQueue at all users = chosen.pool == 0 ? &own_users : &queue_users_; slot = chosen.index; sharing = (*users)[slot]++; } const bool own_pool = users != &queue_users_; if (sharing) log_once("CreateCommandQueue: every Vulkan queue of the family is in use; this D3D12 queue shares one with " "the others on it (their batches run in submission order), type", desc->Type); // Child holds a device reference until after the lease has been released. std::shared_ptr lease(nullptr, [this, users, slot](void*) { std::lock_guard lock(queue_mutex_); --(*users)[slot]; }); const VkQueue queue = own_pool ? own_queues[slot] : state_.info.command_queues[slot]; const std::uint32_t family = own_pool ? own_family : state_.info.queue_family; return d3d12_trace::result(method, create_command_queue(*state_.context, queue, family, *desc, riid, out, identity(), state_.clock_for(family), std::move(lease))); } HRESULT STDMETHODCALLTYPE CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE type, REFIID riid, void** out) override { constexpr auto method = "ID3D12Device::CreateCommandAllocator"; return d3d12_trace::result(method, create_command_allocator(type, riid, out, identity())); } HRESULT STDMETHODCALLTYPE CreateCommandList(UINT node_mask, D3D12_COMMAND_LIST_TYPE type, ID3D12CommandAllocator* allocator, ID3D12PipelineState* state, REFIID riid, void** out) override { constexpr auto method = "ID3D12Device::CreateCommandList"; if (out) *out = nullptr; if (node_mask & ~1u) return d3d12_trace::result(method, E_INVALIDARG); // one node, as the host answers // The initial pipeline state is set as SetPipelineState would set it (a bundle's is its first deferred call). HRESULT hr = create_command_list(type, allocator, riid, out, identity(), state); return d3d12_trace::result(method, hr); } // Device4: a list created closed, without an allocator. HRESULT STDMETHODCALLTYPE CreateCommandList1(UINT node_mask, D3D12_COMMAND_LIST_TYPE type, D3D12_COMMAND_LIST_FLAGS, REFIID riid, void** out) override { constexpr auto method = "ID3D12Device4::CreateCommandList1"; // The host runtime's order ("command list1:" cases): one node and a type up to VIDEO_ENCODE (non-zero // D3D12_COMMAND_LIST_FLAGS are ignored by the host runtime), then a null output is E_UNEXPECTED. if (out) *out = nullptr; if ((node_mask & ~1u) || UINT(type) > UINT(D3D12_COMMAND_LIST_TYPE_VIDEO_ENCODE)) return d3d12_trace::result(method, E_INVALIDARG); if (!out) return d3d12_trace::result(method, E_UNEXPECTED); ID3D12CommandAllocator* allocator = nullptr; HRESULT hr = create_command_allocator(type, IID_PPV_ARGS(&allocator), identity()); if (FAILED(hr)) return d3d12_trace::result(method, hr); ID3D12GraphicsCommandList* list = nullptr; hr = create_command_list(type, allocator, IID_PPV_ARGS(&list), identity()); allocator->Release(); if (FAILED(hr)) return d3d12_trace::result(method, hr); list->Close(); hr = list->QueryInterface(riid, out); list->Release(); return d3d12_trace::result(method, hr); } HRESULT STDMETHODCALLTYPE CreateFence(UINT64 initial, D3D12_FENCE_FLAGS flags, REFIID riid, void** out) override { constexpr auto method = "ID3D12Device::CreateFence"; // As the host runtime: known flags only, cross-adapter only when shared, and no non-monitored fences // (refused there even with both sharing flags). A null output is a capability check. constexpr UINT known = D3D12_FENCE_FLAG_SHARED | D3D12_FENCE_FLAG_SHARED_CROSS_ADAPTER | D3D12_FENCE_FLAG_NON_MONITORED; if ((UINT(flags) & ~known) || (flags & D3D12_FENCE_FLAG_NON_MONITORED) || ((flags & D3D12_FENCE_FLAG_SHARED_CROSS_ADAPTER) && !(flags & D3D12_FENCE_FLAG_SHARED))) { log_once("CreateFence refused, flags", int(flags)); return d3d12_trace::result(method, E_INVALIDARG); } if (!out) return d3d12_trace::result(method, S_FALSE); return d3d12_trace::result(method, create_fence(*state_.context, initial, flags, riid, out, identity())); } HRESULT STDMETHODCALLTYPE CreateCommandSignature(const D3D12_COMMAND_SIGNATURE_DESC* desc, ID3D12RootSignature* root_signature, REFIID riid, void** out) override { if (out) *out = nullptr; // The host refuses these with E_INVALIDARG (compare_invalid_arguments, "command signature:"): one node, a // known type per argument, exactly one draw or dispatch and it comes last, a root signature for root // arguments, and a stride that is a multiple of 4 and holds every argument. if (!desc || desc->NumArgumentDescs == 0 || !desc->pArgumentDescs || (desc->NodeMask & ~1u)) return E_INVALIDARG; UINT64 size = 0; // packed bytes; a large Num32BitValuesToSet must not wrap past ByteStride UINT64 creation_padding = 0; for (UINT i = 0; i < desc->NumArgumentDescs; ++i) { const D3D12_INDIRECT_ARGUMENT_DESC& arg = desc->pArgumentDescs[i]; switch (arg.Type) { case D3D12_INDIRECT_ARGUMENT_TYPE_DRAW: size += sizeof(D3D12_DRAW_ARGUMENTS); break; case D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED: size += sizeof(D3D12_DRAW_INDEXED_ARGUMENTS); break; case D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH: size += sizeof(D3D12_DISPATCH_ARGUMENTS); break; case D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_RAYS: size += sizeof(D3D12_DISPATCH_RAYS_DESC); break; case D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH: size += sizeof(D3D12_DISPATCH_MESH_ARGUMENTS); break; case D3D12_INDIRECT_ARGUMENT_TYPE_VERTEX_BUFFER_VIEW: size += sizeof(D3D12_VERTEX_BUFFER_VIEW); break; case D3D12_INDIRECT_ARGUMENT_TYPE_INDEX_BUFFER_VIEW: size += sizeof(D3D12_INDEX_BUFFER_VIEW); break; case D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT: size += UINT64{4} * arg.Constant.Num32BitValuesToSet; break; // Tier 1.1 generates the incrementing value: it occupies no argument-buffer bytes. // Preserve the existing creation-time stride check on this tier-1.0 device; this is not tier-1.1 support. case compat::kIndirectArgumentIncrementingConstant: creation_padding += 4; break; case D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT_BUFFER_VIEW: case D3D12_INDIRECT_ARGUMENT_TYPE_SHADER_RESOURCE_VIEW: case D3D12_INDIRECT_ARGUMENT_TYPE_UNORDERED_ACCESS_VIEW: size += sizeof(D3D12_GPU_VIRTUAL_ADDRESS); break; default: return E_INVALIDARG; } if (size + creation_padding > desc->ByteStride) return E_INVALIDARG; const bool draw = arg.Type <= D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH || arg.Type == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_RAYS || arg.Type == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH; const bool root_argument = !draw && arg.Type != D3D12_INDIRECT_ARGUMENT_TYPE_VERTEX_BUFFER_VIEW && arg.Type != D3D12_INDIRECT_ARGUMENT_TYPE_INDEX_BUFFER_VIEW; if (draw != (i + 1 == desc->NumArgumentDescs) || (root_argument && !root_signature)) return E_INVALIDARG; } if (desc->ByteStride % 4) return E_INVALIDARG; if (!out) return E_UNEXPECTED; // the host's answer for a valid description and no output leonida::IndirectKind kind; switch (desc->pArgumentDescs[desc->NumArgumentDescs - 1].Type) { case D3D12_INDIRECT_ARGUMENT_TYPE_DRAW: kind = leonida::IndirectKind::draw; break; case D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED: kind = leonida::IndirectKind::draw_indexed; break; case D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH: kind = leonida::IndirectKind::dispatch; break; case D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH: // As DispatchMesh: only a device with mesh shaders (MeshShaderTier 1) takes it. if (!state_.info.mesh_shader) return E_NOTIMPL; kind = leonida::IndirectKind::dispatch_mesh; break; default: return E_NOTIMPL; } return create_command_signature(kind, desc->ByteStride, static_cast(size), riid, out, identity(), {desc->pArgumentDescs, desc->NumArgumentDescs - 1}); } void STDMETHODCALLTYPE GetRaytracingAccelerationStructurePrebuildInfo( const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS* desc, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO* out) override { if (!out) return; *out = {}; if (!desc) return; if (desc->Type != D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL && desc->Type != D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL) return; if (desc->DescsLayout != D3D12_ELEMENTS_LAYOUT_ARRAY && desc->DescsLayout != D3D12_ELEMENTS_LAYOUT_ARRAY_OF_POINTERS) return; const bool is_tlas = (desc->Type == D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL); if (!is_tlas && desc->NumDescs > 0) { if (desc->DescsLayout == D3D12_ELEMENTS_LAYOUT_ARRAY) { if (!desc->pGeometryDescs) return; } else { if (!desc->ppGeometryDescs) return; for (UINT i = 0; i < desc->NumDescs; ++i) if (!desc->ppGeometryDescs[i]) return; } } auto& vk = state_.context->vk; if (state_.context->xdxr_acceleration_structures()) { // XDXR records: the layout depends only on the triangle or instance count and on whether the nodes are // BOX16 (MINIMIZE_MEMORY, bottom level; xdxr_build.h). Its size has room for the most nodes a tree of // that many elements can have; a build's own size, in its header, is what COMPACTED_SIZE reports. An // update refits (no sort); the build's scratch size covers it. leonida::BuildAccelerationStructure build{}; build.is_tlas = is_tlas; if (desc->Flags & D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_MINIMIZE_MEMORY) build.build_flags |= VK_BUILD_ACCELERATION_STRUCTURE_LOW_MEMORY_BIT_KHR; if (build.is_tlas) { build.instance_count = desc->NumDescs; } else { for (UINT i = 0; i < desc->NumDescs; ++i) { const D3D12_RAYTRACING_GEOMETRY_DESC* gd = (desc->DescsLayout == D3D12_ELEMENTS_LAYOUT_ARRAY_OF_POINTERS) ? desc->ppGeometryDescs[i] : &desc->pGeometryDescs[i]; if (gd->Type != D3D12_RAYTRACING_GEOMETRY_TYPE_TRIANGLES) continue; leonida::RtTriangleGeometry t{}; t.vertex_count = gd->Triangles.VertexCount; t.index_count = gd->Triangles.IndexCount; t.index_type = gd->Triangles.IndexFormat == DXGI_FORMAT_UNKNOWN ? 0u : 1u; build.triangles.push_back(t); } } leonida::XdxrLayout layout; if (!layout.compute(leonida::VulkanContext::xdxr_elements(build), build.is_tlas, leonida::VulkanContext::xdxr_box16(build))) return; out->ResultDataMaxSizeInBytes = layout.size; out->ScratchDataSizeInBytes = layout.scratch; out->UpdateScratchDataSizeInBytes = layout.scratch; return; } if (!state_.info.ray_tracing || !vk.vkGetAccelerationStructureBuildSizesKHR) return; std::vector geoms; std::vector max_prims; if (is_tlas) { VkAccelerationStructureGeometryKHR g{VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_KHR}; g.geometryType = VK_GEOMETRY_TYPE_INSTANCES_KHR; g.geometry.instances.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_INSTANCES_DATA_KHR; g.geometry.instances.arrayOfPointers = desc->DescsLayout == D3D12_ELEMENTS_LAYOUT_ARRAY_OF_POINTERS ? VK_TRUE : VK_FALSE; geoms.push_back(g); max_prims.push_back(desc->NumDescs); } else { for (UINT i = 0; i < desc->NumDescs; ++i) { const D3D12_RAYTRACING_GEOMETRY_DESC* gd = (desc->DescsLayout == D3D12_ELEMENTS_LAYOUT_ARRAY_OF_POINTERS) ? (desc->ppGeometryDescs ? desc->ppGeometryDescs[i] : nullptr) : (desc->pGeometryDescs ? &desc->pGeometryDescs[i] : nullptr); if (!gd || gd->Type != D3D12_RAYTRACING_GEOMETRY_TYPE_TRIANGLES) continue; VkAccelerationStructureGeometryKHR g{VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_KHR}; g.geometryType = VK_GEOMETRY_TYPE_TRIANGLES_KHR; g.flags = (gd->Flags & D3D12_RAYTRACING_GEOMETRY_FLAG_OPAQUE) ? VK_GEOMETRY_OPAQUE_BIT_KHR : 0u; auto& tr = g.geometry.triangles; tr.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_TRIANGLES_DATA_KHR; tr.vertexFormat = (gd->Triangles.VertexFormat == DXGI_FORMAT_R32G32_FLOAT) ? VK_FORMAT_R32G32_SFLOAT : VK_FORMAT_R32G32B32_SFLOAT; tr.vertexStride = gd->Triangles.VertexBuffer.StrideInBytes; tr.maxVertex = gd->Triangles.VertexCount ? (gd->Triangles.VertexCount - 1u) : 0u; tr.indexType = (gd->Triangles.IndexFormat == DXGI_FORMAT_R16_UINT) ? VK_INDEX_TYPE_UINT16 : ((gd->Triangles.IndexFormat == DXGI_FORMAT_R32_UINT) ? VK_INDEX_TYPE_UINT32 : VK_INDEX_TYPE_NONE_KHR); geoms.push_back(g); const std::uint32_t prims = (gd->Triangles.IndexFormat != DXGI_FORMAT_UNKNOWN && gd->Triangles.IndexCount >= 3) ? (gd->Triangles.IndexCount / 3u) : (gd->Triangles.VertexCount / 3u); max_prims.push_back(prims); } } if (geoms.empty()) return; VkAccelerationStructureBuildGeometryInfoKHR bgi{ VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_BUILD_GEOMETRY_INFO_KHR}; bgi.type = is_tlas ? VK_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL_KHR : VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_KHR; if (desc->Flags & D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_ALLOW_UPDATE) bgi.flags |= VK_BUILD_ACCELERATION_STRUCTURE_ALLOW_UPDATE_BIT_KHR; if (desc->Flags & D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_PREFER_FAST_TRACE) bgi.flags |= VK_BUILD_ACCELERATION_STRUCTURE_PREFER_FAST_TRACE_BIT_KHR; if (desc->Flags & D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_PREFER_FAST_BUILD) bgi.flags |= VK_BUILD_ACCELERATION_STRUCTURE_PREFER_FAST_BUILD_BIT_KHR; if (desc->Flags & D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_MINIMIZE_MEMORY) // as the build gets it bgi.flags |= VK_BUILD_ACCELERATION_STRUCTURE_LOW_MEMORY_BIT_KHR; bgi.geometryCount = static_cast(geoms.size()); bgi.pGeometries = geoms.data(); VkAccelerationStructureBuildSizesInfoKHR sizes{VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_BUILD_SIZES_INFO_KHR}; vk.vkGetAccelerationStructureBuildSizesKHR(state_.info.device, VK_ACCELERATION_STRUCTURE_BUILD_TYPE_DEVICE_KHR, &bgi, max_prims.data(), &sizes); out->ResultDataMaxSizeInBytes = sizes.accelerationStructureSize; out->ScratchDataSizeInBytes = sizes.buildScratchSize; out->UpdateScratchDataSizeInBytes = sizes.updateScratchSize; } HRESULT STDMETHODCALLTYPE CreateDescriptorHeap(const D3D12_DESCRIPTOR_HEAP_DESC* desc, REFIID riid, void** out) override { constexpr auto method = "ID3D12Device::CreateDescriptorHeap"; if (out) *out = nullptr; if (!desc) return d3d12_trace::result(method, E_INVALIDARG); // As the host runtime: a null output is a capability check, answered before the rules below (S_FALSE even // for a shader-visible RTV heap). Zero descriptors are allowed, RTV and DSV heaps are never shader-visible, // one flag and one node. if (!out) return d3d12_trace::result(method, S_FALSE); if ((desc->Flags & ~D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE) || desc->NodeMask > 1 || ((desc->Flags & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE) && (desc->Type == D3D12_DESCRIPTOR_HEAP_TYPE_RTV || desc->Type == D3D12_DESCRIPTOR_HEAP_TYPE_DSV))) { log_once("CreateDescriptorHeap refused (flags or node mask), type", desc->Type); return d3d12_trace::result(method, E_INVALIDARG); } auto* heap = new DescriptorHeap(state_, *desc); heap->attach_device(identity()); if (!heap->ok()) { heap->Release(); return d3d12_trace::result(method, E_OUTOFMEMORY); } return d3d12_trace::result(method, hand_out(heap, riid, out)); } HRESULT STDMETHODCALLTYPE CreateQueryHeap(const D3D12_QUERY_HEAP_DESC* desc, REFIID riid, void** out) override { if (out) *out = nullptr; // The host runtime's order (compare_invalid_arguments, "query heap:"): the description first, refused with // E_INVALIDARG for no queries, a node other than node 0 or a type past PIPELINE_STATISTICS1 (7; 6 has no // name in the SDK but the host takes it), then E_UNEXPECTED for a null output. A known type this layer // can't create stays E_NOTIMPL. if (!desc || !desc->Count || desc->NodeMask > 1 || UINT(desc->Type) > UINT(D3D12_QUERY_HEAP_TYPE_PIPELINE_STATISTICS1)) return E_INVALIDARG; if (!out) return E_UNEXPECTED; auto* heap = new QueryHeap(state_); heap->attach_device(identity()); if (const HRESULT hr = heap->create(*desc); FAILED(hr)) { heap->Release(); return hr; } return hand_out(heap, riid, out); } HRESULT STDMETHODCALLTYPE CreateRootSignature(UINT node_mask, const void* blob, SIZE_T size, REFIID riid, void** out) override { // The host runtime answers a null output with S_FALSE before it looks at the blob or the node mask // (compare_invalid_arguments, "root signature:"). Otherwise it refuses a node other than node 0, and a DXBC // container whose own size (the dword at +24) is not the size passed. if (!out) return S_FALSE; *out = nullptr; if (!blob || !size || (node_mask & ~1u)) return E_INVALIDARG; const auto* bytes = static_cast(blob); if (size >= 28 && std::memcmp(bytes, "DXBC", 4) == 0) { std::uint32_t container_size = 0; std::memcpy(&container_size, bytes + 24, sizeof(container_size)); if (container_size != size) return E_INVALIDARG; } // The repository's root-signature model (runtime/src/root_signature.h): parse the RTS0 blob, then pack // the parameters into the 32 user-data dwords in the console layout. pack_stage() refuses what it cannot // place (past s31: the console spills those to memory, in a layout that is still open), and so does this. const rt::rootsig::DecodeResult parsed = rt::rootsig::parse_rts0(bytes, size); if (!parsed.ok) { std::fprintf(stderr, "[rt] d3d12: root signature not understood: %s\n", parsed.error.c_str()); return E_INVALIDARG; } // Two layouts, one per bind point (RootArgumentLayout): graphics takes the console layout of vertex and // pixel shaders (s8, one dword per table) where it fits without a spill and keeps pack() otherwise, compute // the console layout pack_stage() measured (D3D-448). The signature is refused only when neither can place it. // A mesh shader reads the same graphics block from its s16 (the translator's root window, push dword 8 = s16), // so its 16-dword window only needs checking (D3D-448-GRAPHICS). const rt::rootsig::PackResult packed = rt::rootsig::pack(parsed.sig); // LEONIDA_GRAPHICS_STAGE_LAYOUT=0 keeps pack() for every graphics signature. const rt::rootsig::StagePackResult pixel = local_graphics_stage_layout() ? rt::rootsig::pack_stage(parsed.sig, rt::rootsig::Stage::Pixel) : rt::rootsig::StagePackResult{}; const rt::rootsig::StagePackResult mesh = rt::rootsig::pack_stage(parsed.sig, rt::rootsig::Stage::Mesh); const rt::rootsig::StagePackResult compute = rt::rootsig::pack_stage(parsed.sig, rt::rootsig::Stage::Compute); if (!pixel.ok && packed.ok && local_graphics_stage_layout()) { static std::atomic kept{0}; const unsigned n = ++kept; if (n == 1 || (n & (n - 1)) == 0) std::fprintf(stderr, "[rt] d3d12: root signature keeps the s0 graphics layout: %s (%u so far)\n", pixel.error.c_str(), n); } const bool graphics_ok = pixel.ok || packed.ok; if (!graphics_ok && !compute.ok) { std::fprintf(stderr, "[rt] d3d12: root signature refused: %s (compute: %s)\n", packed.error.c_str(), compute.error.c_str()); return E_INVALIDARG; } if (!graphics_ok) std::fprintf(stderr, "[rt] d3d12: root signature usable for compute only: %s\n", packed.error.c_str()); else if (pixel.ok && !mesh.ok) { static std::atomic too_large{0}; const unsigned n = ++too_large; if (n == 1 || (n & (n - 1)) == 0) std::fprintf(stderr, "[rt] d3d12: root signature too large for a mesh shader's root window: %s (%u so far)\n", mesh.error.c_str(), n); } if (!compute.ok) std::fprintf(stderr, "[rt] d3d12: root signature usable for graphics only: %s\n", compute.error.c_str()); RootArgumentLayout layout; layout.flags = parsed.sig.flags; layout.graphics_console = pixel.ok; layout.graphics_ok = graphics_ok; layout.mesh_ok = pixel.ok && mesh.ok; layout.compute_ok = compute.ok; if (compute.ok && !compute.spill_dwords) layout.compute_arguments_end = compute.end_sgpr; // Vertex, pixel and geometry shaders share the s8 layout and one user-data block (a non-compute stage // refuses a spill, so pixel.ok means every argument is inline). if (pixel.ok) layout.graphics_arguments_end = pixel.end_sgpr; for (std::size_t i = 0; i < parsed.sig.params.size(); ++i) { std::uint32_t first = UINT32_MAX; if (pixel.ok) { first = pixel.first_sgpr[i]; } else { for (std::uint32_t d = 0; packed.ok && d < packed.dword_count; ++d) if (packed.provenance[d].param_index == i) { first = d; break; } } layout.parameters.push_back({parsed.sig.params[i].type, first, parsed.sig.params[i].num_values, compute.ok ? compute.first_sgpr[i] : rt::rootsig::kNoSgpr, table_descriptor_count(parsed.sig.params[i])}); } register_static_samplers(parsed.sig); auto* signature = new RootSignature( std::move(layout), leonida::sha256_hex({static_cast(blob), size})); signature->attach_device(identity()); return hand_out(signature, riid, out); } // PC slot 11; the Xbox ABI reaches it through device slots 62 and 67 (the proxy forwards). HRESULT STDMETHODCALLTYPE CreateComputePipelineState(const D3D12_COMPUTE_PIPELINE_STATE_DESC* desc, REFIID riid, void** out) override { if (!out) return E_POINTER; *out = nullptr; if (!desc) return E_INVALIDARG; leonida::cached_pso::Key key = pipeline_key(*desc); if (const HRESULT hr = check_cached_pso(state_.pso_identity, key, desc->CachedPSO); FAILED(hr)) return hr; auto* pipeline = new PipelineState(state_); pipeline->attach_device(identity()); pipeline->set_cache_key(std::move(key)); if (const HRESULT hr = pipeline->create_compute(*desc); FAILED(hr)) { pipeline->Release(); return hr; } return hand_out(pipeline, riid, out); } HRESULT STDMETHODCALLTYPE CreateGraphicsPipelineState(const D3D12_GRAPHICS_PIPELINE_STATE_DESC* desc, REFIID riid, void** out) override { if (!out) return E_POINTER; *out = nullptr; if (!desc) return E_INVALIDARG; leonida::cached_pso::Key key = pipeline_key(*desc); if (const HRESULT hr = check_cached_pso(state_.pso_identity, key, desc->CachedPSO); FAILED(hr)) return hr; auto* pipeline = new PipelineState(state_); pipeline->attach_device(identity()); pipeline->set_cache_key(std::move(key)); if (const HRESULT hr = pipeline->create_graphics(*desc); FAILED(hr)) { pipeline->Release(); return hr; } return hand_out(pipeline, riid, out); } // Device1: in-memory pipeline library (docs/d3d12_vulkan.md sections 3.6 and 4). HRESULT STDMETHODCALLTYPE CreatePipelineLibrary(const void* blob, SIZE_T size, REFIID riid, void** out) override { constexpr auto method = "ID3D12Device1::CreatePipelineLibrary"; // A refused blob leaves *out as it was, as the host runtime does; a wrong interface nulls it (hand_out). if (size > 0) { const HRESULT checked = PipelineLibrary::check_blob(blob, size); if (FAILED(checked)) return d3d12_trace::result(method, checked); } if (!out) return d3d12_trace::result(method, S_FALSE); *out = nullptr; auto* lib = new PipelineLibrary(); lib->attach_device(identity()); return d3d12_trace::result(method, hand_out(lib, riid, out)); } // Device9: process-wide shader cache sessions (in-memory and disk-backed) and control (D3D-34). HRESULT STDMETHODCALLTYPE CreateShaderCacheSession(const D3D12_SHADER_CACHE_SESSION_DESC* desc, REFIID riid, void** out) override { constexpr auto method = "ID3D12Device9::CreateShaderCacheSession"; if (out) *out = nullptr; if (!desc) return d3d12_trace::result(method, E_INVALIDARG); const GUID zero_guid{}; if (std::memcmp(&desc->Identifier, &zero_guid, sizeof(GUID)) == 0) return d3d12_trace::result(method, E_INVALIDARG); if (desc->Mode != D3D12_SHADER_CACHE_MODE_MEMORY && desc->Mode != D3D12_SHADER_CACHE_MODE_DISK) return d3d12_trace::result(method, E_INVALIDARG); constexpr UINT kKnownFlags = D3D12_SHADER_CACHE_FLAG_DRIVER_VERSIONED | D3D12_SHADER_CACHE_FLAG_USE_WORKING_DIR; if (UINT(desc->Flags) & ~kKnownFlags) return d3d12_trace::result(method, E_INVALIDARG); if (!out) return d3d12_trace::result(method, S_FALSE); std::wstring disk_path; if (desc->Mode == D3D12_SHADER_CACHE_MODE_DISK) { VkPhysicalDeviceProperties props{}; if (state_.info.get_instance_proc && state_.info.instance && state_.info.physical) { if (const auto get_props = reinterpret_cast( state_.info.get_instance_proc(state_.info.instance, "vkGetPhysicalDeviceProperties"))) get_props(state_.info.physical, &props); } const auto path = shader_cache_disk_path(*desc, props); if (path.empty()) return d3d12_trace::result(method, E_FAIL); disk_path = path.wstring(); } const ShaderCacheKey key{desc->Identifier, desc->Mode, std::move(disk_path)}; auto& registry = process_shader_cache_registry(); const UINT max_file_bytes = desc->MaximumValueFileSizeBytes ? desc->MaximumValueFileSizeBytes : ShaderCacheStore::kDefaultMaxValueFileBytes; std::shared_ptr store; if (const HRESULT hr = registry.acquire(key, desc->Version, max_file_bytes, store); FAILED(hr)) return d3d12_trace::result(method, hr); auto* session = new ShaderCacheSession(*desc, key, registry, std::move(store)); session->attach_device(identity()); return d3d12_trace::result(method, hand_out(session, riid, out)); } HRESULT STDMETHODCALLTYPE ShaderCacheControl(D3D12_SHADER_CACHE_KIND_FLAGS kinds, D3D12_SHADER_CACHE_CONTROL_FLAGS control) override { constexpr auto method = "ID3D12Device9::ShaderCacheControl"; constexpr UINT kKnownKinds = D3D12_SHADER_CACHE_KIND_FLAG_IMPLICIT_D3D_CACHE_FOR_DRIVER | D3D12_SHADER_CACHE_KIND_FLAG_IMPLICIT_D3D_CONVERSIONS | D3D12_SHADER_CACHE_KIND_FLAG_IMPLICIT_DRIVER_MANAGED | D3D12_SHADER_CACHE_KIND_FLAG_APPLICATION_MANAGED; constexpr UINT kKnownControls = D3D12_SHADER_CACHE_CONTROL_FLAG_DISABLE | D3D12_SHADER_CACHE_CONTROL_FLAG_ENABLE | D3D12_SHADER_CACHE_CONTROL_FLAG_CLEAR; if (!kinds || (UINT(kinds) & ~kKnownKinds) || !control || (UINT(control) & ~kKnownControls)) return d3d12_trace::result(method, E_INVALIDARG); if ((control & D3D12_SHADER_CACHE_CONTROL_FLAG_ENABLE) && (control & D3D12_SHADER_CACHE_CONTROL_FLAG_DISABLE)) return d3d12_trace::result(method, E_INVALIDARG); auto& registry = process_shader_cache_registry(); if (kinds & D3D12_SHADER_CACHE_KIND_FLAG_APPLICATION_MANAGED) { if (control & D3D12_SHADER_CACHE_CONTROL_FLAG_CLEAR) registry.clear_all(); if (control & D3D12_SHADER_CACHE_CONTROL_FLAG_DISABLE) registry.disabled.store(true, std::memory_order_relaxed); if (control & D3D12_SHADER_CACHE_CONTROL_FLAG_ENABLE) registry.disabled.store(false, std::memory_order_relaxed); } return d3d12_trace::result(method, S_OK); } // ID3D12Device2: a PSO from a pipeline state stream. A CS makes a compute PSO, an MS a mesh PSO, a VS the same // graphics PSO CreateGraphicsPipelineState makes (parse_pipeline_stream). HRESULT STDMETHODCALLTYPE CreatePipelineState(const D3D12_PIPELINE_STATE_STREAM_DESC* desc, REFIID riid, void** out) override { constexpr const char* method = "ID3D12Device2::CreatePipelineState"; d3d12_trace::stream_refusal = nullptr; d3d12_xs::used_console_stream = false; const auto finish = [&](HRESULT hr) { if (hr == E_NOTIMPL) d3d12_trace::record("PipelineStream::Refused", d3d12_trace::stream_refusal ? d3d12_trace::stream_refusal : "other backend state"); return d3d12_trace::result(method, hr); }; if (!out) return finish(E_POINTER); *out = nullptr; if (!desc) return finish(E_INVALIDARG); PipelineStream stream; HRESULT parsed = parse_pipeline_stream(*desc, stream); // A stream the PC reading refuses, or leaves with an AS and no MS (no valid PC stream), is read again with the // console's numbering (parse_pipeline_stream), and that reading is taken when it holds a mesh shader (its 24) // and no AS. A stream the PC reading accepts as valid is never read differently. LEONIDA_XS_STREAM_ENUM=pc // keeps the PC reading alone (such PSOs are then refused, as before). if ((FAILED(parsed) || (stream.as.pShaderBytecode && !stream.ms.pShaderBytecode)) && console_stream_enum_enabled()) { const char* pc_reason = d3d12_trace::stream_refusal; PipelineStream console; if (SUCCEEDED(parse_pipeline_stream(*desc, console, true)) && !console.as.pShaderBytecode && is_mesh_container(console.ms)) { log_once("console pipeline stream: type 24 contains a mesh shader; DXIL kind", 13); d3d12_xs::used_console_stream = true; d3d12_trace::stream_refusal = nullptr; stream = console; parsed = S_OK; } else { d3d12_trace::stream_refusal = pc_reason; } } if (FAILED(parsed)) return finish(parsed); auto* pipeline = new PipelineState(state_); pipeline->attach_device(identity()); const HRESULT hr = stream.has_cs ? pipeline->create_compute(stream.compute) : pipeline->create_graphics(stream.graphics, &stream.ms, &stream.as, stream.back_masks ? &stream.back_stencil : nullptr); if (FAILED(hr)) { pipeline->Release(); return finish(hr); } const HRESULT result = hand_out(pipeline, riid, out); if (SUCCEEDED(result) && stream.ms.pShaderBytecode) d3d12_trace::record("PipelineStream::Mesh", "accepted"); return finish(result); } UINT STDMETHODCALLTYPE GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE) override { return kDescriptorSize; } void STDMETHODCALLTYPE CreateRenderTargetView(ID3D12Resource* resource, const D3D12_RENDER_TARGET_VIEW_DESC* desc, D3D12_CPU_DESCRIPTOR_HANDLE destination) override { d3d12_trace::record("ID3D12Device::CreateRenderTargetView"); if (!destination.ptr) return; leonida::TargetView view{}; leonida::ResourceId rid = 0; D3D12_RESOURCE_DESC rd{}; const Resource* r = Resource::from(resource); if (r) { rid = r->id(); rd = const_cast(r)->GetDesc(); } else if (resource && state_.context->has_resource(resource_id(resource))) { rid = resource_id(resource); rd = resource->GetDesc(); } if (rid) { view = {rid, 0, 0, rd.DepthOrArraySize}; if (rd.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D) { view = volume_rtv(rid, rd, desc); } else if (desc && desc->ViewDimension == D3D12_RTV_DIMENSION_TEXTURE1D) { view = line_target_view(rid, rd, desc->Texture1D.MipSlice, 0, 1); } else if (desc && desc->ViewDimension == D3D12_RTV_DIMENSION_TEXTURE1DARRAY) { view = line_target_view(rid, rd, desc->Texture1DArray.MipSlice, desc->Texture1DArray.FirstArraySlice, desc->Texture1DArray.ArraySize); } else if (desc && desc->ViewDimension == D3D12_RTV_DIMENSION_TEXTURE2D) { view = {rid, desc->Texture2D.MipSlice, 0, 1}; } else if (desc && desc->ViewDimension == D3D12_RTV_DIMENSION_TEXTURE2DMS) { view = {rid, 0, 0, 1}; } else if (desc && desc->ViewDimension == D3D12_RTV_DIMENSION_TEXTURE2DARRAY) { view = {rid, desc->Texture2DArray.MipSlice, desc->Texture2DArray.FirstArraySlice, view_slices(rd, desc->Texture2DArray.FirstArraySlice, desc->Texture2DArray.ArraySize)}; } else if (desc && desc->ViewDimension == D3D12_RTV_DIMENSION_TEXTURE2DMSARRAY) { // Multisample textures have one mip, so only the slice range is chosen (as for the DSV). view = {rid, 0, desc->Texture2DMSArray.FirstArraySlice, view_slices(rd, desc->Texture2DMSArray.FirstArraySlice, desc->Texture2DMSArray.ArraySize)}; } else if (desc) { log_once("render-target view dimension not supported:", desc->ViewDimension); view = {}; } // A TYPELESS color texture of any family takes RTVs in its family's formats (D3D-275; RGBA8 only before). const bool typeless_color = vulkan_format(rd.Format, false).typeless && !(rd.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL); const bool typed_rgba8 = rd.Format == DXGI_FORMAT_R8G8B8A8_UNORM || rd.Format == DXGI_FORMAT_R8G8B8A8_UNORM_SRGB || rd.Format == DXGI_FORMAT_R8G8B8A8_UINT; // An RGBA8 or BGRA8 texture whose castable list names the RTV's format in the other channel order, or // across B8G8R8X8 and B8G8R8A8, gets an RTV in that format. const DXGI_FORMAT asked = desc && desc->Format != DXGI_FORMAT_UNKNOWN ? desc->Format : rd.Format; const bool cast_listed = r && asked != rd.Format && rgba8_any_order(rd.Format) && rgba8_any_order(asked) && r->lists_castable_format(asked); // A typed BGRA8 or B8G8R8X8 texture with a castable list refuses an RTV in another format the list // doesn't name, as a typed RGBA8 texture does. Without a list it keeps the image's format, as before. const bool typed_bgra8_listed = r && !typed_rgba8 && rgba8_any_order(rd.Format) && r->has_castable_formats(); if (rd.Format == DXGI_FORMAT_A8_UNORM || (desc && desc->Format == DXGI_FORMAT_A8_UNORM)) { // Only an A8 render target stored as VK_FORMAT_A8_UNORM_KHR takes an RTV, in its own format: the // attachment view is the image's. const bool plain_2d = !desc || desc->ViewDimension == D3D12_RTV_DIMENSION_TEXTURE2D || desc->ViewDimension == D3D12_RTV_DIMENSION_TEXTURE2DARRAY; if (!r || !r->a8_as_alpha() || rd.Format != DXGI_FORMAT_A8_UNORM || !plain_2d || (desc && desc->Format != DXGI_FORMAT_UNKNOWN && desc->Format != DXGI_FORMAT_A8_UNORM)) view = {}; } else if (r && rd.Format==DXGI_FORMAT_B4G4R4A4_UNORM && r->format()==VK_FORMAT_R8G8B8A8_UNORM) { if(!desc || desc->Format==DXGI_FORMAT_UNKNOWN || desc->Format==rd.Format) view.format=leonida::ColorViewFormat::resource; } else if (r && r->uint_backed() == VK_FORMAT_A1R5G5B5_UNORM_PACK16) { // An R16_UINT-backed B5G5R5A1 UAV texture (Format::uint_backed) renders through an A1R5G5B5 view, in // its own format only. if (desc && desc->Format != DXGI_FORMAT_UNKNOWN && desc->Format != rd.Format) view = {}; else view.format = static_cast(VK_FORMAT_A1R5G5B5_UNORM_PACK16); } else if (r && (r->uint_backed() == VK_FORMAT_R8G8B8A8_SRGB || r->uint_backed() == VK_FORMAT_B8G8R8A8_SRGB)) { // A UNORM-backed sRGB UAV texture (texture_format) renders and clears through its sRGB view, or // through the UNORM twin it is made of when the view asks for that (the console allows the cast). const VkFormat wanted = desc && desc->Format != DXGI_FORMAT_UNKNOWN ? vulkan_format(desc->Format, false).format : r->uint_backed(); if (wanted == r->uint_backed() || wanted == r->format()) view.format = static_cast(wanted); else view = {}; } else if (rd.Format == DXGI_FORMAT_R9G9B9E5_SHAREDEXP || (desc && desc->Format == DXGI_FORMAT_R9G9B9E5_SHAREDEXP)) { if (rd.Format != DXGI_FORMAT_R9G9B9E5_SHAREDEXP || !(rd.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) || (desc && desc->Format != DXGI_FORMAT_UNKNOWN && desc->Format != rd.Format)) view = {}; } else if (typeless_color || typed_rgba8 || cast_listed || typed_bgra8_listed) { const DXGI_FORMAT requested = asked; // A typed UNORM RGBA8 resource with a castable list may be viewed in a listed family format // (D3D-85's committed path, D3D-90's placed one): its image is mutable and lists the view // format, so the reinterpretation is the typeless path's. Only a UNORM image is advertised, // as that is what the clear path reinterprets. const bool listed = requested == rd.Format || (r && r->has_view_format_list() && r->allows_view_format(vulkan_format(requested, false).format)); if (typeless_color || cast_listed || (requested != rd.Format && listed && (rd.Format == DXGI_FORMAT_R8G8B8A8_UNORM || rd.Format == DXGI_FORMAT_R8G8B8A8_UNORM_SRGB))) { const bool msaa = rd.SampleDesc.Count > 1; const bool plain_1d = !msaa && desc && desc->ViewDimension == D3D12_RTV_DIMENSION_TEXTURE1D; const bool array_1d = !msaa && desc && desc->ViewDimension == D3D12_RTV_DIMENSION_TEXTURE1DARRAY; const bool plain_2d = !msaa && desc && desc->ViewDimension == D3D12_RTV_DIMENSION_TEXTURE2D; const bool array_2d = !msaa && desc && desc->ViewDimension == D3D12_RTV_DIMENSION_TEXTURE2DARRAY; const bool ms = msaa && desc && desc->ViewDimension == D3D12_RTV_DIMENSION_TEXTURE2DMS; const bool ms_array = msaa && desc && desc->ViewDimension == D3D12_RTV_DIMENSION_TEXTURE2DMSARRAY; const UINT plane = plain_2d ? desc->Texture2D.PlaneSlice : array_2d ? desc->Texture2DArray.PlaneSlice : 0; const bool dim_ok = ((plain_1d || array_1d) && rd.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D) || ((plain_2d || array_2d || ms || ms_array) && rd.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D); // Subtraction keeps malformed layer ranges from overflowing during validation. if (!dim_ok || plane || !view.resource || view.mip >= rd.MipLevels || !view.layer_count || view.first_layer >= rd.DepthOrArraySize || view.layer_count > rd.DepthOrArraySize - view.first_layer || !(rd.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET)) { view = {}; } else { // The view's own format, of the resource's family (B8G8R8X8 and B8G8R8A8 are two families // that share Vulkan formats) or named by its castable list; the clear and the attachment // view reinterpret the image in it. const Format named = vulkan_format(requested, false); const int family = leonida::detail::typeless_view_family(named.format); const bool same_family = alpha_unused(requested) == alpha_unused(rd.Format) && family == leonida::detail::typeless_view_family(vulkan_format(rd.Format, false).format); if (named.typeless || named.rgb96 || !family || !(same_family || cast_listed)) view = {}; else view.format = static_cast(named.format); if (view.resource) { const auto format = vulkan_format(requested, false); VkFormatProperties properties{}; state_.format_properties(state_.info.physical, format.format, &properties); if (!(properties.optimalTilingFeatures & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT)) view = {}; } } } else if (requested != rd.Format) { view = {}; // No typed-resource format casting is advertised by this backend. } if (!view.resource) log_once("unsupported typeless or RGBA8 RTV format/subresource:", int(requested)); } } else if (resource) { stub("ID3D12Device::CreateRenderTargetView(resource from another device)"); } std::memcpy(reinterpret_cast(destination.ptr), &view, sizeof(view)); } void STDMETHODCALLTYPE CreateDepthStencilView(ID3D12Resource* resource, const D3D12_DEPTH_STENCIL_VIEW_DESC* desc, D3D12_CPU_DESCRIPTOR_HANDLE destination) override { d3d12_trace::record("ID3D12Device::CreateDepthStencilView"); if (!destination.ptr) return; leonida::TargetView view{}; if (const Resource* r = Resource::from(resource)) { const D3D12_RESOURCE_DESC rd = const_cast(r)->GetDesc(); view = {r->id(), 0, 0, rd.DepthOrArraySize}; if (desc && desc->ViewDimension == D3D12_DSV_DIMENSION_TEXTURE1D) { view = line_target_view(r->id(), rd, desc->Texture1D.MipSlice, 0, 1); } else if (desc && desc->ViewDimension == D3D12_DSV_DIMENSION_TEXTURE1DARRAY) { view = line_target_view(r->id(), rd, desc->Texture1DArray.MipSlice, desc->Texture1DArray.FirstArraySlice, desc->Texture1DArray.ArraySize); } else if (desc && desc->ViewDimension == D3D12_DSV_DIMENSION_TEXTURE2D) { view = {r->id(), desc->Texture2D.MipSlice, 0, 1}; } else if (desc && desc->ViewDimension == D3D12_DSV_DIMENSION_TEXTURE2DMS) { view = {r->id(), 0, 0, 1}; } else if (desc && desc->ViewDimension == D3D12_DSV_DIMENSION_TEXTURE2DARRAY) { view = {r->id(), desc->Texture2DArray.MipSlice, desc->Texture2DArray.FirstArraySlice, view_slices(rd, desc->Texture2DArray.FirstArraySlice, desc->Texture2DArray.ArraySize)}; } else if (desc && desc->ViewDimension == D3D12_DSV_DIMENSION_TEXTURE2DMSARRAY) { // Multisample textures have one mip, so only the slice range is chosen. view = {r->id(), 0, desc->Texture2DMSArray.FirstArraySlice, view_slices(rd, desc->Texture2DMSArray.FirstArraySlice, desc->Texture2DMSArray.ArraySize)}; } else if (desc) { log_once("depth-stencil view dimension not supported:", desc->ViewDimension); view = {}; } if (r->desc().Format == DXGI_FORMAT_A8_UNORM || (desc && desc->Format == DXGI_FORMAT_A8_UNORM)) view = {}; } else if (resource) { stub("ID3D12Device::CreateDepthStencilView(resource from another device)"); } std::memcpy(reinterpret_cast(destination.ptr), &view, sizeof(view)); } // A descriptor is its slot's bytes (a TargetView in RTV and DSV heaps, otherwise what the shader loads), so a // copy is a byte copy. D3D12 walks the destination and source ranges together, one descriptor at a time; a // null size array means every range holds one descriptor. Whichever side runs out first ends the copy. void STDMETHODCALLTYPE CopyDescriptors(UINT destination_ranges, const D3D12_CPU_DESCRIPTOR_HANDLE* destinations, const UINT* destination_sizes, UINT source_ranges, const D3D12_CPU_DESCRIPTOR_HANDLE* sources, const UINT* source_sizes, D3D12_DESCRIPTOR_HEAP_TYPE) override { if (!destinations || !sources) return; UINT d = 0, s = 0, d_at = 0, s_at = 0; // the range on each side, and the position in it while (d < destination_ranges && s < source_ranges) { if (d_at >= (destination_sizes ? destination_sizes[d] : 1) || !destinations[d].ptr) { ++d; d_at = 0; } else if (s_at >= (source_sizes ? source_sizes[s] : 1) || !sources[s].ptr) { ++s; s_at = 0; } else { std::memmove(reinterpret_cast(destinations[d].ptr) + std::size_t(d_at) * kDescriptorSize, reinterpret_cast(sources[s].ptr) + std::size_t(s_at++) * kDescriptorSize, kDescriptorSize); state_.probe_api(destinations[d].ptr + SIZE_T(d_at++) * kDescriptorSize, 1); // LOCAL DIAGNOSTIC } } } void STDMETHODCALLTYPE CopyDescriptorsSimple(UINT count, D3D12_CPU_DESCRIPTOR_HANDLE destination, D3D12_CPU_DESCRIPTOR_HANDLE source, D3D12_DESCRIPTOR_HEAP_TYPE) override { if (!destination.ptr || !source.ptr) return; std::memmove(reinterpret_cast(destination.ptr), reinterpret_cast(source.ptr), std::size_t(count) * kDescriptorSize); state_.probe_api(destination.ptr, count); // LOCAL DIAGNOSTIC state_.probe_view("CopyDescriptorsSimple", destination.ptr, count); } // A constant-buffer view is a 16-byte GFX10 raw buffer V# in the first half of the slot (zeros in the rest). // A null description, zero address, or zero size leaves the whole slot zeroed (null V#: reads return 0). void STDMETHODCALLTYPE CreateConstantBufferView(const D3D12_CONSTANT_BUFFER_VIEW_DESC* desc, D3D12_CPU_DESCRIPTOR_HANDLE destination) override { write_constant_buffer_view(desc,destination,false); } void write_constant_buffer_view(const D3D12_CONSTANT_BUFFER_VIEW_DESC* desc, D3D12_CPU_DESCRIPTOR_HANDLE destination, bool vector_rows) { d3d12_trace::record("ID3D12Device::CreateConstantBufferView"); if (!destination.ptr) return; ProbeApiWrite probe_note{state_, destination.ptr, 1, "CreateConstantBufferView"}; // LOCAL DIAGNOSTIC std::memset(reinterpret_cast(destination.ptr), 0, kDescriptorSize); if (!desc || !desc->BufferLocation || !desc->SizeInBytes) return; leonida::gfx10::Buffer buffer{}; buffer.address = desc->BufferLocation; const bool indexed = vector_rows && desc->SizeInBytes % 16 == 0; // A vector ALU fetch selects a 16-byte constant register with IDXEN. Scalar SMEM // still sees the very same byte extent, NUM_RECORDS * STRIDE. buffer.stride = indexed ? 16u : 0u; buffer.num_records = indexed ? desc->SizeInBytes / 16u : desc->SizeInBytes; buffer.format = leonida::gfx10::format_from_vulkan(VK_FORMAT_R32_UINT); buffer.oob_select = indexed ? leonida::gfx10::OobSelect::structured_with_offset : leonida::gfx10::OobSelect::raw; static const bool console_form = [] { wchar_t value[2]{}; return !(GetEnvironmentVariableW(L"LEONIDA_CBV_RAW", value, 2) == 1 && value[0] == L'1'); }(); const uint64_t rows = (uint64_t(desc->SizeInBytes) + 15) / 16; buffer.address = state_.vsharp_address(buffer.address, console_form ? rows * 16 : desc->SizeInBytes); // No backing for the title's memory: a zero-size V# (loads 0, stores dropped), never the raw address. const bool backed = buffer.address != 0; if (!backed) { buffer.stride = 0, buffer.num_records = 0; leonida::note_unbacked_view("constant-buffer view", desc->BufferLocation, desc->SizeInBytes); } leonida::gfx10::BufferWords words = leonida::gfx10::encode(buffer); // The console's constant-buffer V# is a table of 16-byte rows: the title's own inline form of this descriptor // (it writes one itself instead of calling here, depending on a device flag) is {base, stride 16, records // (size + 15) / 16, fourth word 0x0002403C} (docs/re/notes/gfxgeom.md), and its shaders index rows through // the stride: the batched Scaleform vertex shader reads its X and Y transform rows as base + index * stride. // With the raw form (stride 0) both rows are the same 16 bytes and every batched triangle collapses onto the // line x = y. LEONIDA_CBV_RAW=1 restores the raw form. if (console_form && backed) { words[1] = (words[1] & 0xFFFFu) | (16u << 16); words[2] = UINT(rows); words[3] = 0x0002403Cu; } std::memcpy(reinterpret_cast(destination.ptr), words.data(), sizeof(words)); // LOCAL DIAGNOSTIC: the CBVs the title makes, where they go and what V# they get if (leonida::local_diagnostics()) { static std::atomic made{0}; const std::uint64_t n = ++made; if (n <= 8 || n % 600 == 0 || n % 600 == 1) std::fprintf(stderr, "[rt] fsdraw: CBV #%llu dest 0x%llx location 0x%llx size %u -> V# base 0x%llx [%s]\n", static_cast(n), static_cast(destination.ptr), static_cast(desc->BufferLocation), desc->SizeInBytes, static_cast(buffer.address), leonida::fsdraw::hex_words(words.data(), words.size()).c_str()); } leonida::fsdraw::note_cbv(buffer.address, desc->BufferLocation, desc->SizeInBytes); // LOCAL DIAGNOSTIC } // A buffer shader-resource view of the `width` bytes at console VA `base_va`: a 16-byte GFX10 V# in the first // half of the slot (raw, structured, or typed). False, the slot left as it was (zeros), for a view the layer // cannot write. A resource's VA, or memory the title placed itself (Xbox device slot 70). bool write_buffer_srv(UINT64 base_va, UINT64 width, const D3D12_SHADER_RESOURCE_VIEW_DESC* desc, D3D12_CPU_DESCRIPTOR_HANDLE destination, bool placed = false) { if (!base_va || !desc->Buffer.NumElements || (desc->Buffer.Flags & ~D3D12_BUFFER_SRV_FLAG_RAW)) return false; leonida::gfx10::Buffer buffer{}; if (desc->Buffer.Flags & D3D12_BUFFER_SRV_FLAG_RAW) { if (desc->Format != DXGI_FORMAT_R32_TYPELESS || desc->Buffer.StructureByteStride != 0) return false; if (desc->Buffer.FirstElement > width / 4) return false; const UINT64 byte_off = desc->Buffer.FirstElement * 4; const UINT64 byte_size = UINT64(desc->Buffer.NumElements) * 4; if (byte_size > width - byte_off || byte_size > UINT32_MAX) return false; buffer.address = base_va + byte_off; buffer.stride = 0; buffer.num_records = std::uint32_t(byte_size); buffer.format = leonida::gfx10::format_from_vulkan(VK_FORMAT_R32_UINT); buffer.oob_select = leonida::gfx10::OobSelect::raw; } else if (desc->Buffer.StructureByteStride != 0) { if (desc->Format != DXGI_FORMAT_UNKNOWN || desc->Buffer.StructureByteStride > 16383) return false; const UINT64 stride = desc->Buffer.StructureByteStride; if (desc->Buffer.FirstElement > width / stride) return false; const UINT64 byte_off = desc->Buffer.FirstElement * stride; const UINT64 byte_size = UINT64(desc->Buffer.NumElements) * stride; if (byte_size > width - byte_off) return false; buffer.address = base_va + byte_off; buffer.stride = std::uint32_t(stride); buffer.num_records = desc->Buffer.NumElements; buffer.format = leonida::gfx10::format_from_vulkan(VK_FORMAT_R32_UINT); // Check the field offset against the record stride, as for structured UAVs (five-star-recomp 3d287ab). buffer.oob_select = leonida::gfx10::OobSelect::structured_with_offset; } else { const Format fmt = vulkan_format(desc->Format, false); if (fmt.format == VK_FORMAT_UNDEFINED || fmt.typeless || !(fmt.aspects & VK_IMAGE_ASPECT_COLOR_BIT)) { log_once("buffer SRV format not supported:", int(desc->Format)); return false; } const VkFormat named = fmt.rgb96 ? rgb96_named_format(fmt.format) : fmt.format; const std::uint32_t code = leonida::gfx10::format_from_vulkan(named); const leonida::BlockFormat bf = footprint_block(fmt, VK_IMAGE_ASPECT_COLOR_BIT); if (!code || bf.block != 1 || !bf.bytes || bf.bytes > 16383) { log_once("buffer SRV format not supported:", int(desc->Format)); return false; } const UINT64 stride = bf.bytes; if (desc->Buffer.FirstElement > width / stride) return false; const UINT64 byte_off = desc->Buffer.FirstElement * stride; const UINT64 byte_size = UINT64(desc->Buffer.NumElements) * stride; if (byte_size > width - byte_off) return false; buffer.address = base_va + byte_off; buffer.stride = std::uint32_t(stride); buffer.num_records = desc->Buffer.NumElements; buffer.format = code; const leonida::gfx10::Swizzle channels = leonida::gfx10::format_swizzle(named); for (unsigned i = 0; i < 4; ++i) { const UINT from = D3D12_DECODE_SHADER_4_COMPONENT_MAPPING(i, desc->Shader4ComponentMapping); buffer.swizzle[i] = from < 4 ? channels[from] : from == D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_0 ? leonida::gfx10::select_zero : leonida::gfx10::select_one; } buffer.oob_select = leonida::gfx10::OobSelect::structured; } const auto bytes = std::uint64_t(buffer.num_records) * (buffer.stride ? buffer.stride : 1); const auto copy = placed ? state_.geometry_va(buffer.address, bytes, true) : 0; if (copy) { // CPU readers and descriptor copies retain the guest address. The heap's shader mirror // rewrites it at the original slot, just as it does for a descriptor written by the title. if (!state_.has_console_descriptor_copy(destination.ptr)) buffer.address = copy; } else { const std::uint64_t target = buffer.address; buffer.address = state_.vsharp_address(buffer.address, bytes); // No backing: no records, so loads return 0 and stores are dropped (never a raw title base). if (!buffer.address) { buffer.stride = 0, buffer.num_records = 0; leonida::note_unbacked_view("buffer SRV", target, bytes); } } const leonida::gfx10::BufferWords words = leonida::gfx10::encode(buffer); std::memcpy(reinterpret_cast(destination.ptr), words.data(), sizeof(words)); return true; } // A shader-resource view of a texture is a T# in the slot (docs section 3.4): the shader loads those eight // dwords through its descriptor table and finds the image by them. A buffer SRV writes a 16-byte GFX10 V# in the // first half of the slot (raw, structured, or typed). A slot left as zeros is a null descriptor. void STDMETHODCALLTYPE CreateShaderResourceView(ID3D12Resource* resource, const D3D12_SHADER_RESOURCE_VIEW_DESC* desc, D3D12_CPU_DESCRIPTOR_HANDLE destination) override { d3d12_trace::record("ID3D12Device::CreateShaderResourceView"); using leonida::gfx10::ImageType; if (!destination.ptr) return; ProbeApiWrite probe_note{state_, destination.ptr, 1, "CreateShaderResourceView"}; // LOCAL DIAGNOSTIC std::memset(reinterpret_cast(destination.ptr), 0, kDescriptorSize); const Resource* r = Resource::from(resource); if (!r) { if (resource) stub("ID3D12Device::CreateShaderResourceView(resource from another device)"); return; } if (r->desc().Flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) { log_once("shader-resource view denied by resource flags; format", int(r->desc().Format)); return; } // A placed texture whose memory waits for its first use is a texture all the same, and asking for its image // would bind that memory here, before write_image_descriptor can remember the view (prepare_on_bind). if (!r->deferrable_sample() && !r->descriptor_image()) { if (!desc) { log_once("buffer SRV requires a description; width", int(r->desc().Width)); return; } if (desc->ViewDimension != D3D12_SRV_DIMENSION_BUFFER) { log_once("shader-resource view dimension not supported for buffer:", desc->ViewDimension); return; } write_buffer_srv(const_cast(r)->GetGPUVirtualAddress(), r->desc().Width, desc, destination); return; } TextureView view{}; if (!desc) { const bool array = r->desc().DepthOrArraySize > 1; if (r->desc().Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D && !array) { view.type = ImageType::image_1d; view.layer_count = 1; } else if (r->desc().Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D) view.type = ImageType::image_3d; else if (r->desc().SampleDesc.Count > 1) view.type = array ? ImageType::image_2d_msaa_array : ImageType::image_2d_msaa; else if (array) view.type = ImageType::image_2d_array; } else { view.format = desc->Format; view.mapping = desc->Shader4ComponentMapping; switch (desc->ViewDimension) { case D3D12_SRV_DIMENSION_TEXTURE1D: view.type = ImageType::image_1d; view.first_mip = desc->Texture1D.MostDetailedMip; view.mip_count = desc->Texture1D.MipLevels; view.layer_count = 1; view.min_lod = desc->Texture1D.ResourceMinLODClamp; break; case D3D12_SRV_DIMENSION_TEXTURE3D: view.type = leonida::gfx10::ImageType::image_3d; view.first_mip = desc->Texture3D.MostDetailedMip; view.mip_count = desc->Texture3D.MipLevels; view.min_lod = desc->Texture3D.ResourceMinLODClamp; break; case D3D12_SRV_DIMENSION_TEXTURE2DMS: view.type = ImageType::image_2d_msaa; view.layer_count = 1; break; case D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY: view.type = ImageType::image_2d_msaa_array; view.first_layer = desc->Texture2DMSArray.FirstArraySlice; view.layer_count = desc->Texture2DMSArray.ArraySize; break; case D3D12_SRV_DIMENSION_TEXTURE2D: view.first_mip = desc->Texture2D.MostDetailedMip; view.mip_count = desc->Texture2D.MipLevels; view.layer_count = 1; view.plane = desc->Texture2D.PlaneSlice; view.min_lod = desc->Texture2D.ResourceMinLODClamp; break; case D3D12_SRV_DIMENSION_TEXTURE2DARRAY: view.type = ImageType::image_2d_array; view.first_mip = desc->Texture2DArray.MostDetailedMip; view.mip_count = desc->Texture2DArray.MipLevels; view.first_layer = desc->Texture2DArray.FirstArraySlice; view.layer_count = desc->Texture2DArray.ArraySize; view.plane = desc->Texture2DArray.PlaneSlice; view.min_lod = desc->Texture2DArray.ResourceMinLODClamp; break; case D3D12_SRV_DIMENSION_TEXTURECUBE: view.type = ImageType::cube; view.first_mip = desc->TextureCube.MostDetailedMip; view.mip_count = desc->TextureCube.MipLevels; view.layer_count = 6; view.min_lod = desc->TextureCube.ResourceMinLODClamp; break; case D3D12_SRV_DIMENSION_TEXTURECUBEARRAY: view.type = ImageType::cube; view.first_mip = desc->TextureCubeArray.MostDetailedMip; view.mip_count = desc->TextureCubeArray.MipLevels; view.first_layer = desc->TextureCubeArray.First2DArrayFace; view.layer_count = desc->TextureCubeArray.NumCubes < ~0u / 6 ? desc->TextureCubeArray.NumCubes * 6 : ~0u; view.min_lod = desc->TextureCubeArray.ResourceMinLODClamp; break; default: log_once("shader-resource view dimension not supported:", desc->ViewDimension); return; } } write_image_descriptor(*r, view, destination, ImageViewUse::sampled); // LOCAL DIAGNOSTIC: the texture SRVs the title makes, where they go and the T# they get if (leonida::local_diagnostics()) { static std::atomic made{0}; const std::uint64_t n = ++made; if (n <= 8 || n % 600 == 0 || n % 600 == 1) { std::uint32_t w[8]; std::memcpy(w, reinterpret_cast(destination.ptr), sizeof w); std::fprintf(stderr, "[rt] fsdraw: SRV #%llu dest 0x%llx resource 0x%llx format %d dim %d -> [%s] bindless %s\n", static_cast(n), static_cast(destination.ptr), static_cast(r->id()), desc ? int(desc->Format) : -1, desc ? int(desc->ViewDimension) : -1, leonida::fsdraw::hex_words(w, 8).c_str(), leonida::fsdraw::has_tsharp(w) ? "yes" : "NO"); } } } // An unordered-access view of a buffer is a V# in the slot (docs section 3.4): the shader loads those four dwords // through its descriptor table and reaches the bytes by the console VA in them. A structured view (format // UNKNOWN and a stride) is `stride` and a record count, a raw one (R32_TYPELESS with the RAW flag) is a byte count, // a typed one (any other format) is the format's GFX10_FORMAT code with the element size as the stride and an // element count: the V# a buffer_load_format / buffer_store_format / buffer_atomic reads (OOB_SELECT 1, so the // index is checked against NUM_RECORDS, docs/buffer_bounds.md). A slot left as zeros is a null descriptor. // A UAV counter (docs section 3.4, "UAV counters") is a second, raw V# of 4 bytes in the slot's upper 16 bytes: the // counter resource's address plus CounterOffsetInBytes. Append and consume are atomics a shader does on it. void write_buffer_uav(ID3D12Resource* resource, ID3D12Resource* counter, const D3D12_UNORDERED_ACCESS_VIEW_DESC* desc, D3D12_CPU_DESCRIPTOR_HANDLE destination) { namespace g = leonida::gfx10; const D3D12_RESOURCE_DESC& rd = Resource::from(resource)->desc(); if (!(rd.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) { log_once("unordered-access view of a buffer created without ALLOW_UNORDERED_ACCESS; flags", int(rd.Flags)); return; } if (!desc || desc->ViewDimension != D3D12_UAV_DIMENSION_BUFFER) { log_once("unordered-access view of a buffer needs a buffer view description; dimension", desc ? int(desc->ViewDimension) : -1); return; } // D3D12: a counter belongs to a structured view and sits in a buffer that allows unordered access, 4096-byte // aligned with room for its 4 bytes; with no counter resource the offset is 0. if (counter || desc->Buffer.CounterOffsetInBytes) { const Resource* c = counter ? Resource::from(counter) : nullptr; const bool valid = c && !c->image() && desc->Format == DXGI_FORMAT_UNKNOWN && (c->desc().Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) && !(desc->Buffer.CounterOffsetInBytes % D3D12_UAV_COUNTER_PLACEMENT_ALIGNMENT) && UINT64(desc->Buffer.CounterOffsetInBytes) + 4 <= c->desc().Width; if (!valid) { log_once("unordered-access view counter refused (a structured view, a buffer that allows unordered " "access, a 4096-aligned offset inside it); offset", int(desc->Buffer.CounterOffsetInBytes)); return; } } const UINT64 va = resource->GetGPUVirtualAddress(); const UINT64 counter_va = counter ? counter->GetGPUVirtualAddress() : 0; if (!va || (counter && !counter_va)) return; write_buffer_uav_at(va, rd.Width, desc, counter ? counter_va + desc->Buffer.CounterOffsetInBytes : 0, destination); } // A buffer unordered-access view of the `width` bytes at console VA `va` (a resource's, or memory the title // placed itself: Xbox device slot 71), with its counter's V# when `counter_va` is not 0. False, the slot left as // it was (zeros), for a view the layer cannot write. bool write_buffer_uav_at(UINT64 va, UINT64 width, const D3D12_UNORDERED_ACCESS_VIEW_DESC* desc, UINT64 counter_va, D3D12_CPU_DESCRIPTOR_HANDLE destination) { namespace g = leonida::gfx10; if (!va || !desc || desc->ViewDimension != D3D12_UAV_DIMENSION_BUFFER) return false; const D3D12_BUFFER_UAV& view = desc->Buffer; const bool structured = desc->Format == DXGI_FORMAT_UNKNOWN; const bool raw = desc->Format == DXGI_FORMAT_R32_TYPELESS && (view.Flags & D3D12_BUFFER_UAV_FLAG_RAW); const bool typed = !structured && !raw; std::uint32_t format_code = 0, element_bytes = 0; g::Swizzle channels = g::identity_swizzle; if (typed) { // D3D12: a typed view has no RAW flag; its format is one of the typed-UAV formats the layer can name. const Format mapped = vulkan_format(desc->Format, false); const auto* layout = mapped.format != VK_FORMAT_UNDEFINED && !mapped.typeless && !mapped.rgb96 && !(view.Flags & D3D12_BUFFER_UAV_FLAG_RAW) ? leonida::uav_clear::layout(mapped.format) : nullptr; format_code = layout ? g::format_from_vulkan(mapped.format) : 0; if (!format_code || format_code >= 128) { // the V#'s FORMAT is 7 bits log_once("typed buffer unordered-access view format not supported; format", int(desc->Format)); return false; } element_bytes = layout->bytes; channels = g::format_swizzle(mapped.format); } const UINT64 unit = structured ? view.StructureByteStride : typed ? element_bytes : 4; if (!unit || unit > 0x3fff || view.FirstElement > width / unit || (UINT64(view.FirstElement) + view.NumElements) > width / unit || UINT64(view.NumElements) * (structured || typed ? 1 : 4) > ~0u) { log_once("unordered-access view of a buffer outside the resource or with a bad stride; elements", int(view.NumElements)); return false; } g::Buffer buffer{}; buffer.address = va + view.FirstElement * unit; buffer.stride = structured || typed ? std::uint32_t(unit) : 0; buffer.num_records = std::uint32_t(structured || typed ? view.NumElements : UINT64(view.NumElements) * 4); buffer.format = format_code; buffer.swizzle = channels; buffer.oob_select = typed ? g::OobSelect::structured : structured ? g::OobSelect::structured_with_offset : g::OobSelect::raw; const std::uint64_t target = buffer.address; buffer.address = state_.vsharp_address(buffer.address, std::uint64_t(buffer.num_records) * (buffer.stride ? buffer.stride : 1)); // No backing: no records, so loads return 0 and stores are dropped (never a raw title base). if (!buffer.address) { buffer.stride = 0, buffer.num_records = 0; leonida::note_unbacked_view("buffer UAV", target, std::uint64_t(view.NumElements) * (unit ? unit : 1)); } const g::BufferWords words = g::encode(buffer); std::memcpy(reinterpret_cast(destination.ptr), words.data(), sizeof(words)); if (counter_va) { g::Buffer counter_buffer{}; counter_buffer.address = state_.vsharp_address(counter_va, 4); counter_buffer.num_records = counter_buffer.address ? 4 : 0; if (!counter_buffer.address) leonida::note_unbacked_view("UAV counter", counter_va, 4); counter_buffer.oob_select = g::OobSelect::raw; const g::BufferWords counter_words = g::encode(counter_buffer); std::memcpy(reinterpret_cast(destination.ptr) + sizeof(words), counter_words.data(), sizeof(counter_words)); } return true; } // An unordered-access view of a texture is a T# too, of one mip; set 0 also holds it as a storage image. void STDMETHODCALLTYPE CreateUnorderedAccessView(ID3D12Resource* resource, ID3D12Resource* counter, const D3D12_UNORDERED_ACCESS_VIEW_DESC* desc, D3D12_CPU_DESCRIPTOR_HANDLE destination) override { d3d12_trace::record("ID3D12Device::CreateUnorderedAccessView"); if (!destination.ptr) return; ProbeApiWrite probe_note{state_, destination.ptr, 1, "CreateUnorderedAccessView"}; // LOCAL DIAGNOSTIC std::memset(reinterpret_cast(destination.ptr), 0, kDescriptorSize); const Resource* r = Resource::from(resource); if (!r || !r->belongs_to(state_)) { if (resource) stub("ID3D12Device::CreateUnorderedAccessView(resource from another device)"); return; } if (r->storage_image()) r = r->storage_image(); if (!r->image()) return write_buffer_uav(resource, counter, desc, destination); if (counter) { log_once("unordered-access view of a texture with a counter resource; dimension", int(r->desc().Dimension)); return; } const bool depth_uav = r->depth_stencil_uav(0) != nullptr; if (!depth_uav && !(r->desc().Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) { log_once("unordered-access view of a texture created without ALLOW_UNORDERED_ACCESS; flags", int(r->desc().Flags)); return; } TextureView view{}; view.mip_count = 1; namespace g = leonida::gfx10; if (!desc) { const auto& shape = r->desc(); if (shape.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D) view.type = g::ImageType::image_3d; else if (shape.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D) { view.type = shape.DepthOrArraySize > 1 ? g::ImageType::image_1d_array : g::ImageType::image_1d; if (view.type == g::ImageType::image_1d) view.layer_count = 1; } else if (shape.DepthOrArraySize > 1) view.type = g::ImageType::image_2d_array; } else { view.format = desc->Format; switch (desc->ViewDimension) { case D3D12_UAV_DIMENSION_TEXTURE1D: view.type = g::ImageType::image_1d; view.first_mip = desc->Texture1D.MipSlice; view.layer_count = 1; break; case D3D12_UAV_DIMENSION_TEXTURE1DARRAY: view.type = g::ImageType::image_1d_array; view.first_mip = desc->Texture1DArray.MipSlice; view.first_layer = desc->Texture1DArray.FirstArraySlice; view.layer_count = desc->Texture1DArray.ArraySize; break; case D3D12_UAV_DIMENSION_TEXTURE2D: view.first_mip = desc->Texture2D.MipSlice; view.layer_count = 1; view.plane = desc->Texture2D.PlaneSlice; break; case D3D12_UAV_DIMENSION_TEXTURE2DARRAY: view.type = g::ImageType::image_2d_array; view.first_mip = desc->Texture2DArray.MipSlice; view.first_layer = desc->Texture2DArray.FirstArraySlice; view.layer_count = desc->Texture2DArray.ArraySize; view.plane = desc->Texture2DArray.PlaneSlice; break; case D3D12_UAV_DIMENSION_TEXTURE3D: view.type = g::ImageType::image_3d; view.first_mip = desc->Texture3D.MipSlice; view.first_layer = desc->Texture3D.FirstWSlice; view.layer_count = desc->Texture3D.WSize; break; default: log_once("unordered-access view dimension not supported:", desc->ViewDimension); return; } } if (depth_uav) { const UINT layers = r->desc().DepthOrArraySize; if (!desc || !(desc->ViewDimension == D3D12_UAV_DIMENSION_TEXTURE2DARRAY || (desc->ViewDimension == D3D12_UAV_DIMENSION_TEXTURE2D && layers == 1)) || view.first_mip || !view.layer_count || view.first_layer >= layers || (view.layer_count != UINT_MAX && view.layer_count > layers - view.first_layer)) { log_once("Xbox depth-stencil UAV requires a valid mip-zero 2D or array view; dimension", desc ? int(desc->ViewDimension) : 0); return; } const Resource* storage = r->depth_stencil_uav(view.plane); const bool raw_narrow = storage && r->desc().Format == xbox_d16s8 && view.plane == 0 && (view.format == DXGI_FORMAT_R16_UINT || (storage->desc().Format == DXGI_FORMAT_R16_TYPELESS && view.format == DXGI_FORMAT_R16_UNORM)); if (!storage || (!raw_narrow && view.format != storage->desc().Format)) { log_once("unsupported Xbox depth-stencil UAV plane or format; format", int(view.format)); return; } view.plane = 0; // The chosen shadow is a single-plane colour image with the same array layers. write_image_descriptor(*storage, view, destination, ImageViewUse::depth_stencil_uav); return; } // B8G8R8X8 has no typed UAV, so no format of its family gives an unordered-access view. if (alpha_unused(r->desc().Format) || alpha_unused(view.format)) { log_once("unordered-access view of a B8G8R8X8 format; format", int(view.format)); return; } write_image_descriptor(*r, view, destination, ImageViewUse::storage); state_.context->note_shader_image(r->id()); } // A sampler is an S# in the first 16 bytes of the slot; the shader finds the sampler by those four dwords. void STDMETHODCALLTYPE CreateSampler(const D3D12_SAMPLER_DESC* desc, D3D12_CPU_DESCRIPTOR_HANDLE destination) override { d3d12_trace::record("ID3D12Device::CreateSampler"); if (!destination.ptr) return; std::memset(reinterpret_cast(destination.ptr), 0, kDescriptorSize); if (!desc) return; const leonida::gfx10::SamplerWords words = leonida::gfx10::encode(sampler_descriptor(*desc, &state_)); std::memcpy(reinterpret_cast(destination.ptr), words.data(), sizeof(words)); state_.bind_sampler(words); } // CreateSampler with a UINT border colour and non-normalized coordinates (D3D-28). A description the PC runtime // refuses leaves the slot as it was, as the runtime itself does (without the debug layer) on an RTX 4090 and // on WARP: docs/d3d12_vulkan.md section 3.2. void STDMETHODCALLTYPE CreateSampler2(const D3D12_SAMPLER_DESC2* desc, D3D12_CPU_DESCRIPTOR_HANDLE destination) override { d3d12_trace::record("ID3D12Device11::CreateSampler2"); if (!destination.ptr || !desc) return; const char* refusal = sampler2_refusal(*desc); if (refusal) { log_once(refusal, desc->Flags); return; } const leonida::gfx10::SamplerWords words = sampler2_words(*desc); std::memset(reinterpret_cast(destination.ptr), 0, kDescriptorSize); std::memcpy(reinterpret_cast(destination.ptr), words.data(), sizeof(words)); state_.bind_sampler(words); } // The S# of a D3D12_SAMPLER_DESC2 that sampler2_refusal accepts. leonida::gfx10::SamplerWords sampler2_words(const D3D12_SAMPLER_DESC2& desc) { const bool uint_border = desc.Flags & D3D12_SAMPLER_FLAG_UINT_BORDER_COLOR; D3D12_SAMPLER_DESC base{desc.Filter, desc.AddressU, desc.AddressV, desc.AddressW, desc.MipLODBias, desc.MaxAnisotropy, desc.ComparisonFunc, {}, desc.MinLOD, desc.MaxLOD}; if (!uint_border) std::memcpy(base.BorderColor, desc.FloatBorderColor, sizeof(base.BorderColor)); leonida::gfx10::Sampler sampler = sampler_descriptor(base, uint_border ? nullptr : &state_); if (uint_border) { // The S#'s border types are the float ones', plus the layer's integer mark (kIntegerBorderPtr), which // gives the integer border its own key and VK_BORDER_COLOR_INT_* in Vulkan. namespace g = leonida::gfx10; const UINT* c = desc.UintBorderColor; const bool black = c[0] == 0 && c[1] == 0 && c[2] == 0; if (black && c[3] == 0) { sampler.border_color = g::BorderColor::transparent_black; } else if (black && c[3] == 1) { sampler.border_color = g::BorderColor::opaque_black; } else if (c[0] == 1 && c[1] == 1 && c[2] == 1 && c[3] == 1) { sampler.border_color = g::BorderColor::opaque_white; } else { sampler.border_color = g::BorderColor::table; sampler.border_color_index = state_.register_border_color(true, c); } sampler.integer_border = true; } sampler.unnormalized = desc.Flags & D3D12_SAMPLER_FLAG_NON_NORMALIZED_COORDINATES; return leonida::gfx10::encode(sampler); } // A root signature's static samplers take no root argument: a shader that uses one holds its S# by value // (docs/d3d12_vulkan.md section 3.5). So each gets a sampler in set 0 and a key in the hash table here, as // CreateSampler gives a heap slot's S#; without them the shader's lookup misses and it samples through the // fallback sampler. A static sampler is a D3D12_SAMPLER_DESC2 whose border colour is one of five named ones // (D3D12_STATIC_BORDER_COLOR; the two UINT ones can be in a blob of any version, the flags only in 1.2), or // transparent black with the UINT flag. void register_static_samplers(const rt::rootsig::RootSignature& signature) { for (const rt::rootsig::StaticSampler& s : signature.static_samplers) { D3D12_SAMPLER_DESC2 desc{}; desc.Filter = D3D12_FILTER(s.filter); desc.AddressU = D3D12_TEXTURE_ADDRESS_MODE(s.address_u); desc.AddressV = D3D12_TEXTURE_ADDRESS_MODE(s.address_v); desc.AddressW = D3D12_TEXTURE_ADDRESS_MODE(s.address_w); desc.MipLODBias = s.mip_lod_bias; desc.MaxAnisotropy = s.max_anisotropy; desc.ComparisonFunc = D3D12_COMPARISON_FUNC(s.comparison_func); desc.MinLOD = s.min_lod; desc.MaxLOD = s.max_lod; desc.Flags = D3D12_SAMPLER_FLAGS(s.flags); const bool white = s.border_color == D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE || s.border_color == D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE_UINT; if (s.border_color == D3D12_STATIC_BORDER_COLOR_OPAQUE_BLACK_UINT || s.border_color == D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE_UINT) { desc.Flags |= D3D12_SAMPLER_FLAG_UINT_BORDER_COLOR; desc.UintBorderColor[0] = desc.UintBorderColor[1] = desc.UintBorderColor[2] = white ? 1u : 0u; desc.UintBorderColor[3] = 1; } else if (s.border_color == D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK && (desc.Flags & D3D12_SAMPLER_FLAG_UINT_BORDER_COLOR)) { // The integer border the enum has no value for: the 1.2 flag on transparent black is UINT (0,0,0,0), // which D3D12 serializes and creates. UintBorderColor is already zero. } else if (s.border_color > D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE_UINT || (desc.Flags & D3D12_SAMPLER_FLAG_UINT_BORDER_COLOR)) { // A value past the enum, or the UINT flag with the float opaque black or white (D3D12 refuses to // serialize that pair): not a sampler D3D12 defines. log_once("static sampler not registered: border colour and flags do not go together; border colour", int(s.border_color)); continue; } else { desc.FloatBorderColor[0] = desc.FloatBorderColor[1] = desc.FloatBorderColor[2] = white ? 1.0f : 0.0f; desc.FloatBorderColor[3] = s.border_color == D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK ? 0.0f : 1.0f; } if (sampler2_refusal(desc)) { log_once("static sampler not registered: a sampler CreateSampler2 refuses; flags", int(desc.Flags)); continue; } if (!state_.bind_sampler(sampler2_words(desc))) log_once("static sampler not registered: no room in the bindless set; register", int(s.shader_register)); } } // Why the PC runtime refuses a D3D12_SAMPLER_DESC2, or null. The non-normalized rules are its debug layer's // messages, which match Vulkan's for unnormalizedCoordinates; AddressW is free in both. static const char* sampler2_refusal(const D3D12_SAMPLER_DESC2& desc) { if (desc.Flags & ~UINT(D3D12_SAMPLER_FLAG_UINT_BORDER_COLOR | D3D12_SAMPLER_FLAG_NON_NORMALIZED_COORDINATES)) return "CreateSampler2 refused: unknown sampler flags; flags"; if (!(desc.Flags & D3D12_SAMPLER_FLAG_NON_NORMALIZED_COORDINATES)) return nullptr; if (D3D12_DECODE_MIN_FILTER(desc.Filter) != D3D12_DECODE_MAG_FILTER(desc.Filter) || D3D12_DECODE_MIP_FILTER(desc.Filter) != D3D12_FILTER_TYPE_POINT || D3D12_DECODE_IS_ANISOTROPIC_FILTER(desc.Filter) || D3D12_DECODE_FILTER_REDUCTION(desc.Filter) == D3D12_FILTER_REDUCTION_TYPE_COMPARISON) return "CreateSampler2 refused: non-normalized sampler filter; flags"; const auto clamps = [](D3D12_TEXTURE_ADDRESS_MODE m) { return m == D3D12_TEXTURE_ADDRESS_MODE_CLAMP || m == D3D12_TEXTURE_ADDRESS_MODE_BORDER; }; if (!clamps(desc.AddressU) || !clamps(desc.AddressV)) return "CreateSampler2 refused: non-normalized sampler address mode; flags"; if (desc.MinLOD != 0 || desc.MaxLOD != 0 || desc.MipLODBias != 0) return "CreateSampler2 refused: non-normalized sampler LOD; flags"; return nullptr; } HRESULT STDMETHODCALLTYPE CreateCommittedResource(const D3D12_HEAP_PROPERTIES* heap, D3D12_HEAP_FLAGS heap_flags, const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear, REFIID riid, void** out) override { return create_committed_validated("ID3D12Device::CreateCommittedResource", heap, heap_flags, desc, state, clear, 0, nullptr, riid, out); } // Reserved buffers use sparse binding where available. Textures and fallback buffers are fully backed. // The description rules are D3D12's: buffers are ROW_MAJOR, textures 64KB_UNDEFINED_SWIZZLE with a tile shape // (64KB_STANDARD_SWIZZLE needs StandardSwizzle64KBSupported, which CheckFeatureSupport reports as FALSE). The // Xbox tiled layout word 0x101 (slot 76, section 4.2) is accepted as 64KB_UNDEFINED_SWIZZLE; that the console // uses it for reserved resources too is an assumption. HRESULT STDMETHODCALLTYPE CreateReservedResource(const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear, REFIID riid, void** out) override { return create_reserved("ID3D12Device::CreateReservedResource", desc, state, clear, 0, nullptr, riid, out); } // Device4. Protected sessions are not supported. HRESULT STDMETHODCALLTYPE CreateReservedResource1(const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear, ID3D12ProtectedResourceSession* session, REFIID riid, void** out) override { constexpr auto method = "ID3D12Device4::CreateReservedResource1"; if (out) *out = nullptr; if (!desc) return d3d12_trace::result(method, E_INVALIDARG); if (session) return d3d12_trace::result(method, refuse_protected_session("CreateReservedResource1")); return create_reserved(method, desc, state, clear, 0, nullptr, riid, out); } // Device10: an initial layout instead of a state (resources start in their first use's layout here anyway), and a // castable-format list forwarded to the backing texture. HRESULT STDMETHODCALLTYPE CreateReservedResource2(const D3D12_RESOURCE_DESC* desc, D3D12_BARRIER_LAYOUT layout, const D3D12_CLEAR_VALUE* clear, ID3D12ProtectedResourceSession* session, UINT32 castable_formats, const DXGI_FORMAT* castable, REFIID riid, void** out) override { constexpr auto method = "ID3D12Device10::CreateReservedResource2"; if (out) *out = nullptr; if (!desc) return d3d12_trace::result(method, E_INVALIDARG); if (session) return d3d12_trace::result(method, refuse_protected_session("CreateReservedResource2")); if (const char* why = barrier_layout_refusal(*desc, layout)) { log_once((std::string(method) + " refused (" + why + "), layout").c_str(), int(layout)); return d3d12_trace::result(method, E_INVALIDARG); } return create_reserved(method, desc, D3D12_RESOURCE_STATE_COMMON, clear, castable_formats, castable, riid, out); } // Tiling of a reserved resource or a tiled (64KB_UNDEFINED_SWIZZLE) texture (src/resource_tiling.h). Anything // else, as on the PC runtime, has no tiles: every output is zero and no subresource tiling is written. void STDMETHODCALLTYPE GetResourceTiling(ID3D12Resource* resource, UINT* total, D3D12_PACKED_MIP_INFO* packed, D3D12_TILE_SHAPE* shape, UINT* count, UINT first, D3D12_SUBRESOURCE_TILING* tilings) override { leonida::ResourceTiling tiling; Resource* r = Resource::from(resource); const bool ok = r && (r->reserved() || is_tiled_layout(r->GetDesc().Layout)) && resource_tiling(r->GetDesc(), tiling); if (total) *total = ok ? tiling.total_tiles : 0; if (packed) *packed = ok ? D3D12_PACKED_MIP_INFO{UINT8(tiling.standard_mips), UINT8(tiling.packed_mips), tiling.packed_tiles, tiling.packed_start} : D3D12_PACKED_MIP_INFO{}; if (shape) *shape = ok ? D3D12_TILE_SHAPE{tiling.shape.width, tiling.shape.height, tiling.shape.depth} : D3D12_TILE_SHAPE{}; if (!count) return; const UINT available = ok && first < tiling.subresources.size() ? UINT(tiling.subresources.size() - first) : 0; const UINT n = tilings ? std::min(*count, available) : 0; for (UINT i = 0; i < n; ++i) { const leonida::SubresourceTiling& s = tiling.subresources[first + i]; tilings[i] = {s.width, UINT16(s.height), UINT16(s.depth), s.start}; } *count = n; } // The 1/2/3 variants (D3D-28) are the same calls with newer arguments, answered as the PC runtime answers them // (probed on an RTX 4090; docs/d3d12_vulkan.md section 3.2 has the table). The initial state or layout is not // used: new textures are tracked as UNDEFINED and moved on first use, and buffers have no layout. HRESULT STDMETHODCALLTYPE CreateCommittedResource1(const D3D12_HEAP_PROPERTIES* heap, D3D12_HEAP_FLAGS heap_flags, const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear, ID3D12ProtectedResourceSession* session, REFIID riid, void** out) override { if (out) *out = nullptr; if (session) return refuse_protected_session("CreateCommittedResource1"); return CreateCommittedResource(heap, heap_flags, desc, state, clear, riid, out); } HRESULT STDMETHODCALLTYPE CreateCommittedResource2(const D3D12_HEAP_PROPERTIES* heap, D3D12_HEAP_FLAGS heap_flags, const D3D12_RESOURCE_DESC1* desc, D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear, ID3D12ProtectedResourceSession* session, REFIID riid, void** out) override { if (out) *out = nullptr; if (!desc) return E_INVALIDARG; if (session) return refuse_protected_session("CreateCommittedResource2"); if (texture_mip_region(*desc)) return E_INVALIDARG; const D3D12_RESOURCE_DESC base = resource_desc(*desc); return CreateCommittedResource(heap, heap_flags, &base, state, clear, riid, out); } HRESULT STDMETHODCALLTYPE CreateCommittedResource3(const D3D12_HEAP_PROPERTIES* heap, D3D12_HEAP_FLAGS heap_flags, const D3D12_RESOURCE_DESC1* desc, D3D12_BARRIER_LAYOUT layout, const D3D12_CLEAR_VALUE* clear, ID3D12ProtectedResourceSession* session, UINT32 castable_count, const DXGI_FORMAT* castable, REFIID riid, void** out) override { constexpr auto method = "ID3D12Device10::CreateCommittedResource3"; if (out) *out = nullptr; if (!desc) return d3d12_trace::result(method, E_INVALIDARG); if (session) return d3d12_trace::result(method, refuse_protected_session("CreateCommittedResource3")); if (texture_mip_region(*desc)) return d3d12_trace::result(method, E_INVALIDARG); // A count with a null array is no list (as on the PC runtime). The layer reports relaxed format casting, so // a real list is passed through; only buffers are refused. D3D12_RESOURCE_DESC base = resource_desc(*desc); if (const char* why = barrier_layout_refusal(base, layout)) { log_once((std::string(method) + " refused (" + why + "), layout").c_str(), int(layout)); return d3d12_trace::result(method, E_INVALIDARG); } // The Xbox slot-127 bridge forwards the logical texture to Device10. Validate its layout above, // then allocate the depth attachment and enable the typed storage planes before returning it. std::optional storage_heap_flags; if (xbox_depth_uav(base)) { storage_heap_flags = heap_flags & D3D12_HEAP_FLAG_ALLOW_SHADER_ATOMICS; heap_flags &= ~*storage_heap_flags; base.Flags &= ~D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; } // D3D12_BARRIER_LAYOUT has no acceleration-structure value; an AS buffer's state comes through the // legacy CreateCommittedResource path. Buffers here start COMMON, as before. return create_committed_validated(method, heap, heap_flags, &base, D3D12_RESOURCE_STATE_COMMON, clear, castable_count, castable, riid, out, storage_heap_flags); } // Device9. The creator ID only groups queues for tools; one creator is as good as another here. HRESULT STDMETHODCALLTYPE CreateCommandQueue1(const D3D12_COMMAND_QUEUE_DESC* desc, REFIID, REFIID riid, void** out) override { return CreateCommandQueue(desc, riid, out); } // Device8. A texture with a mip region gets the failure answer (every output all ones), as on the PC runtime; // a buffer's mip region is ignored. void STDMETHODCALLTYPE GetCopyableFootprints1(const D3D12_RESOURCE_DESC1* desc, UINT first, UINT count, UINT64 base, D3D12_PLACED_SUBRESOURCE_FOOTPRINT* layouts, UINT* rows, UINT64* row_sizes, UINT64* total) override { const D3D12_RESOURCE_DESC base_desc = desc ? resource_desc(*desc) : D3D12_RESOURCE_DESC{}; const bool usable = desc && !texture_mip_region(*desc); GetCopyableFootprints(usable ? &base_desc : nullptr, first, count, base, layouts, rows, row_sizes, total); } // Heaps and placed resources (section 3.3). A heap reserves its size in the arena, so a buffer placed at a // 64 KiB-aligned offset is simply that offset into the arena, and its console VA is the heap's place plus it. // Existing-memory heaps and lifetime trackers. The host refuses a null address, a file mapping that is not a // handle and a null lifetime owner with E_INVALIDARG on WARP, NVIDIA and Intel (d3d12_existing_heap_test). Docs: // https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device3-openexistingheapfromaddress // // OpenExistingHeapFromAddress answers as the host runtime does on an RTX 4090 and WARP (d3d12_existing_heap_test // open_cases): the address must be the base of a VirtualAlloc allocation that is committed read-write over its // whole size; an address inside it, a partly committed or reserved-only allocation, a read-only one and an // uncached one are E_INVALIDARG. The heap is the allocation's size, 64 KiB aligned, CUSTOM / L0 with WRITE_BACK // (WRITE_COMBINE for a PAGE_WRITECOMBINE range), flags SHARED | // SHARED_CROSS_ADAPTER | ALLOW_SHADER_ATOMICS. Its backing is that memory itself, imported with // VK_EXT_external_memory_host, so the GPU sees the caller's writes. Without the extension, or when the range is // not aligned to minImportedHostPointerAlignment or no memory type takes it, the call stays E_NOTIMPL, and // CheckFeatureSupport(EXISTING_HEAPS) reports the extension's absence. The console title opens the 64 KiB // graphics region it has just committed with XMemVirtualAlloc this way, right after its first queue and fence. HRESULT STDMETHODCALLTYPE OpenExistingHeapFromAddress(const void* address, REFIID riid, void** out) override { constexpr auto method = "ID3D12Device3::OpenExistingHeapFromAddress"; if (out) *out = nullptr; if (!address || !out) return d3d12_trace::result(method, E_INVALIDARG); SIZE_T size = 0; DWORD protect = 0; if (!existing_allocation_size(address, size, protect)) return d3d12_trace::result(method, E_INVALIDARG); if (!state_.get_host_pointer_properties) { log_once("OpenExistingHeapFromAddress (no VK_EXT_external_memory_host; existing heaps are not supported)", 0); return d3d12_trace::result(method, E_NOTIMPL); } const VkDeviceSize alignment = state_.info.host_pointer_alignment; if ((reinterpret_cast(address) | size) & (alignment - 1)) { log_once("OpenExistingHeapFromAddress: range not aligned to minImportedHostPointerAlignment; alignment", int(alignment)); return d3d12_trace::result(method, E_NOTIMPL); } VkMemoryHostPointerPropertiesEXT host{VK_STRUCTURE_TYPE_MEMORY_HOST_POINTER_PROPERTIES_EXT}; if (state_.get_host_pointer_properties(state_.info.device, VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT, address, &host) != VK_SUCCESS || !host.memoryTypeBits) { log_once("OpenExistingHeapFromAddress: no memory type imports this host range", 0); return d3d12_trace::result(method, E_NOTIMPL); } VkImportMemoryHostPointerInfoEXT import{VK_STRUCTURE_TYPE_IMPORT_MEMORY_HOST_POINTER_INFO_EXT}; import.handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT; import.pHostPointer = const_cast(address); VkMemoryAllocateFlagsInfo flags{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO, &import}; flags.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT; VkDeviceMemory memory = VK_NULL_HANDLE; std::uint32_t memory_type = 0; // Host-visible and coherent first, as the caller's pages are; then any type the driver offers. for (const VkMemoryPropertyFlags want : {VkMemoryPropertyFlags(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT), VkMemoryPropertyFlags(0)}) { for (std::uint32_t i = 0; i < state_.memory.memoryTypeCount && !memory; ++i) { if (!(host.memoryTypeBits & (1u << i)) || (state_.memory.memoryTypes[i].propertyFlags & want) != want) continue; VkMemoryAllocateInfo allocate{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, &flags}; allocate.allocationSize = size; allocate.memoryTypeIndex = i; if (state_.context->vk.vkAllocateMemory(state_.info.device, &allocate, nullptr, &memory) == VK_SUCCESS) memory_type = i; else memory = VK_NULL_HANDLE; } if (memory) break; } if (!memory) { log_once("OpenExistingHeapFromAddress: importing the host range failed; size in KiB", int(size / 1024)); return d3d12_trace::result(method, E_OUTOFMEMORY); } D3D12_HEAP_DESC desc{}; desc.SizeInBytes = size; desc.Properties.Type = D3D12_HEAP_TYPE_CUSTOM; desc.Properties.CPUPageProperty = (protect & PAGE_WRITECOMBINE) ? D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE : D3D12_CPU_PAGE_PROPERTY_WRITE_BACK; desc.Properties.MemoryPoolPreference = D3D12_MEMORY_POOL_L0; desc.Alignment = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT; desc.Flags = D3D12_HEAP_FLAG_SHARED | D3D12_HEAP_FLAG_SHARED_CROSS_ADAPTER | D3D12_HEAP_FLAG_ALLOW_SHADER_ATOMICS; auto* heap = new Heap(state_, desc, memory, memory_type, address); heap->attach_device(identity()); return d3d12_trace::result(method, hand_out(heap, riid, out)); } // The size of the VirtualAlloc allocation `address` starts, and its protection, when the whole of it is committed // PAGE_READWRITE, or PAGE_READWRITE | PAGE_WRITECOMBINE: what the host runtime accepts (a write-combined range // opens as a WRITE_COMBINE heap). False for an address inside an allocation, a reserved or free page, another // protection (read-only, PAGE_NOCACHE), or two protections in one allocation. static bool existing_allocation_size(const void* address, SIZE_T& size, DWORD& protect) { MEMORY_BASIC_INFORMATION region{}; if (!VirtualQuery(address, ®ion, sizeof(region)) || region.AllocationBase != address) return false; protect = region.Protect; if (protect != PAGE_READWRITE && protect != (PAGE_READWRITE | PAGE_WRITECOMBINE)) return false; size = 0; const char* at = static_cast(address); while (VirtualQuery(at + size, ®ion, sizeof(region)) && region.AllocationBase == address) { if (region.State != MEM_COMMIT || region.Protect != protect) return false; size += region.RegionSize; } return size != 0; } // create_buffer_at_host_address (Xbox device slot 133). The heap the resource reports is CUSTOM / WRITE_BACK / L0, // what OpenExistingHeapFromAddress gives the same pages, since the CPU keeps writing them. // A D3D12_BARRIER_LAYOUT (what Xbox slot 133 passes, as PC CreatePlacedResource2 does) as the legacy initial state // of an equivalent committed resource. UNDEFINED (0xFFFFFFFF) and anything unlisted give COMMON. static D3D12_RESOURCE_STATES state_for_barrier_layout(std::uint32_t layout) { switch (layout) { case 1: return D3D12_RESOURCE_STATE_GENERIC_READ; case 2: return D3D12_RESOURCE_STATE_RENDER_TARGET; case 3: return D3D12_RESOURCE_STATE_UNORDERED_ACCESS; case 4: return D3D12_RESOURCE_STATE_DEPTH_WRITE; case 5: return D3D12_RESOURCE_STATE_DEPTH_READ; case 6: return D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; case 7: return D3D12_RESOURCE_STATE_COPY_SOURCE; case 8: return D3D12_RESOURCE_STATE_COPY_DEST; case 9: return D3D12_RESOURCE_STATE_RESOLVE_SOURCE; case 10: return D3D12_RESOURCE_STATE_RESOLVE_DEST; default: return D3D12_RESOURCE_STATE_COMMON; } } // TitleVaAliases::want_buffer: a vertex or index view names `va` in the title's own memory and no buffer covers // it. A buffer over the 64 KiB-aligned committed pages around it is made the way slot 133 makes one (the pages // imported, or a shadow copied from them before every submission) and kept until the device goes, up to // LEONIDA_TITLE_BUFFERS_MB (512 by default). void make_title_buffer(std::uint64_t va, std::uint64_t bytes) { if (!state_.context) return; static const bool check_size = [] { wchar_t flag[2]{}; return !(GetEnvironmentVariableW(L"LEONIDA_TITLE_BUFFER_COVERAGE", flag, 2) == 1 && flag[0] == L'0'); }(); // A stream pool's GPU-only alias: the buffer is made over the CPU view of the same pages (rule B), where the // host reads the frames, so it is host-importable and shared with every other view naming that range instead // of leaving a second, queue-mapped copy of it behind. va = leonida::title_gpu_views::to_host_view(static_cast(va), static_cast(std::max(bytes, 1))); const auto covered = [&] { return state_.context->knows_buffer_va(va, check_size ? bytes : 1); }; if (covered()) return; std::uint64_t lo = 0, hi = 0; if (!leonida::title_va_aliases().title_memory(va, lo, hi)) return; std::lock_guard lock(title_buffer_mutex_); if (covered()) return; static const std::uint64_t cap = [] { char text[16] = {}; size_t length = 0; const bool set = getenv_s(&length, text, "LEONIDA_TITLE_BUFFERS_MB") == 0 && length > 1; return (set ? std::strtoull(text, nullptr, 10) : 512ull) << 20; }(); constexpr std::uint64_t align = 65536, most = 64ull << 20; const std::uint64_t start = std::max(va & ~(align - 1), lo); std::uint64_t end = std::min(hi, (va + std::clamp(bytes, 1, most) + align - 1) & ~(align - 1)); for (std::uint64_t at = start; at < end;) { // the committed, readable part only MEMORY_BASIC_INFORMATION region{}; if (!VirtualQuery(reinterpret_cast(static_cast(at)), ®ion, sizeof(region)) || region.State != MEM_COMMIT || !region.Protect || (region.Protect & (PAGE_NOACCESS | PAGE_GUARD))) { end = at; break; } at = reinterpret_cast(region.BaseAddress) + region.RegionSize; } // If the request runs into an uncommitted page or the size limit, reuse its backed prefix. if (end <= va || (check_size && state_.context->knows_buffer_va(va, end - va))) return; if (title_buffer_bytes_ + (end - start) > cap) { log_once("vertex or index data in the title's memory is past LEONIDA_TITLE_BUFFERS_MB, left unresolved; MiB so far:", int(title_buffer_bytes_ >> 20)); return; } D3D12_RESOURCE_DESC desc{}; desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; desc.Width = end - start; desc.Height = 1; desc.DepthOrArraySize = 1; desc.MipLevels = 1; desc.SampleDesc.Count = 1; desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; ID3D12Resource* made = nullptr; const HRESULT hr = create_at_host_address(reinterpret_cast(static_cast(start)), desc, 0xFFFFFFFFu, __uuidof(ID3D12Resource), reinterpret_cast(&made), nullptr); if (FAILED(hr) || !made) { log_once("a buffer over the title's memory for a vertex or index view could not be made; HRESULT", int(hr)); return; } title_buffers_.push_back(made); title_buffer_bytes_ += end - start; if (title_buffers_.size() <= 8 || !(title_buffers_.size() & (title_buffers_.size() - 1))) std::fprintf(stderr, "[rt] d3d12: a %llu KiB buffer over the title's memory at 0x%llx for a vertex or index view " "at 0x%llx (%zu such buffers, %llu MiB)\n", static_cast((end - start) >> 10), static_cast(start), static_cast(va), title_buffers_.size(), static_cast(title_buffer_bytes_ >> 20)); } std::mutex title_buffer_mutex_; std::vector title_buffers_; // kept: the title's views name their addresses frame after frame std::uint64_t title_buffer_bytes_ = 0; HRESULT create_at_host_address(void* address, const D3D12_RESOURCE_DESC& desc, std::uint32_t layout, REFIID riid, void** out, const D3D12_CLEAR_VALUE* clear) { constexpr auto method = "Xbox CreatePlacedResourceX (device slot 133)"; if (desc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER) { // A texture cannot be placed on the title's pages (the PC GPU does not sample the console layout): it gets // a committed texture of the same description, so the title has its resource instead of asserting (found // in review). Its GPU VA is still the title's address: the console answers a placed texture's // GetGPUVirtualAddress with the address the title placed it at, and a title turns that into the CPU // pointer it clears the texture through (docs/d3d12_vulkan.md 3.3). It is registered by that address // (register_title_texture): slot-70 views of the address are of its image, which, unless the GPU writes // it, is filled from the title's memory with the views' layout (TitleTexture). log_once("a title-placed texture (device slot 133) is a committed texture whose GPU VA is the title " "address, filled from the title's pages unless the GPU writes it; dimension", int(desc.Dimension)); // The title's barrier layout (slot 133's third argument, measured by @dracbat) is checked against the // description as CreateCommittedResource checks a state; one it refuses (or UNDEFINED) gives COMMON, so // the title still gets its texture. The image itself starts undefined either way: the first command that // uses it moves it to that command's layout (vulkan_replay.h, initialize), as for every texture here. const D3D12_HEAP_PROPERTIES fallback{D3D12_HEAP_TYPE_DEFAULT}; const D3D12_RESOURCE_STATES initial = state_for_barrier_layout(layout); // The console lets a depth-stencil target allow unordered access too; no PC GPU stores to a depth // format, so the texture is made without it (as slot 25 and slot 76 size and make it). Its UAVs then // write no descriptor. D3D12_RESOURCE_DESC made = desc; if ((made.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) && (made.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) { made.Flags &= ~D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; log_once("a title-placed depth-stencil texture is made without unordered access; format", made.Format); } // A texture the GPU never writes holds what the title writes into its memory (XG copies, Map): its image // is filled from there (TitleTexture), so it is made where host copies reach it (CUSTOM write-back: still // device-local memory, created with host-transfer usage when the format allows). const bool gpu_written = (made.Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) || made.SampleDesc.Count > 1; const D3D12_HEAP_PROPERTIES host_copied{D3D12_HEAP_TYPE_CUSTOM, D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, D3D12_MEMORY_POOL_L0, 1, 1}; const D3D12_HEAP_PROPERTIES* heap = gpu_written ? &fallback : &host_copied; // The title views 32-bit unordered-access targets as R9G9B9E5 (it packs E5 values into them from compute; // seen in its slot-70 views): castable, so that view exists. Made without the list if Vulkan refuses it. const bool r32 = made.Format == DXGI_FORMAT_R32_TYPELESS || made.Format == DXGI_FORMAT_R32_FLOAT || made.Format == DXGI_FORMAT_R32_UINT || made.Format == DXGI_FORMAT_R32_SINT; const DXGI_FORMAT castable[] = {made.Format, DXGI_FORMAT_R9G9B9E5_SHAREDEXP}; const UINT32 cast_count = r32 && (made.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) && made.SampleDesc.Count == 1 ? 2 : 0; HRESULT hr = create_committed_validated(nullptr, heap, D3D12_HEAP_FLAG_NONE, &made, initial, nullptr, cast_count, castable, riid, out, std::nullopt, TitleImageOrigin::placed); if (FAILED(hr) && cast_count) hr = create_committed_validated(nullptr, heap, D3D12_HEAP_FLAG_NONE, &made, initial, nullptr, 0, nullptr, riid, out, std::nullopt, TitleImageOrigin::placed); if (FAILED(hr) && initial != D3D12_RESOURCE_STATE_COMMON) hr = create_committed_validated(nullptr, heap, D3D12_HEAP_FLAG_NONE, &made, D3D12_RESOURCE_STATE_COMMON, nullptr, 0, nullptr, riid, out, std::nullopt, TitleImageOrigin::placed); if (FAILED(hr) && heap != &fallback) { log_once("a title-placed texture the GPU does not write could not be made on a host-copied heap; " "format", made.Format); hr = create_committed_validated(nullptr, &fallback, D3D12_HEAP_FLAG_NONE, &made, D3D12_RESOURCE_STATE_COMMON, nullptr, 0, nullptr, riid, out, std::nullopt, TitleImageOrigin::placed); } if (SUCCEEDED(hr) && out && *out) { // The interface handed out is the Resource itself (hand_out); ask it back and tell it its address. ID3D12Resource* made = nullptr; if (SUCCEEDED(static_cast(*out)->QueryInterface(__uuidof(ID3D12Resource), reinterpret_cast(&made))) && made) { if (auto* texture = Resource::from(made)) { static const bool distinct = [] { const char* v = std::getenv("LEONIDA_PLACED_IMAGE_KEYS"); return !v || std::strcmp(v, "0"); }(); texture->place_at_title_address(address, distinct && gpu_written); register_title_texture(texture, reinterpret_cast(address)); texture->set_title_address(reinterpret_cast(address)); } made->Release(); } } if (FAILED(hr)) { // The title asserts when a texture it places cannot be made: say which one, in full. static std::atomic logged{0}; if (logged.fetch_add(1, std::memory_order_relaxed) < 32) std::fprintf(stderr, "[rt] d3d12: slot 133 texture not created (hr 0x%08x, layout %u): dim %d format %d " "%llux%ux%u mips %u samples %u layout %d flags 0x%x at %p\n", unsigned(hr), unsigned(layout), int(desc.Dimension), int(desc.Format), static_cast(desc.Width), unsigned(desc.Height), unsigned(desc.DepthOrArraySize), unsigned(desc.MipLevels), unsigned(desc.SampleDesc.Count), int(desc.Layout), unsigned(desc.Flags), address); } return d3d12_trace::result(method, hr); } D3D12_HEAP_PROPERTIES heap{}; heap.Type = D3D12_HEAP_TYPE_CUSTOM; heap.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_WRITE_BACK; heap.MemoryPoolPreference = D3D12_MEMORY_POOL_L0; auto* resource = new Resource(state_, desc, heap, D3D12_HEAP_FLAG_NONE); resource->attach_device(identity()); const HRESULT hr = resource->create_host_buffer(address); if (hr == E_INVALIDARG) { resource->Release(); return d3d12_trace::result(method, hr); } if (FAILED(hr)) { // The driver would not import these pages: RADV refuses a view of a pagefile-backed section, the form // xmem's physical pages take (found in review on an RX 9070 XT under Wine), and a device without // VK_EXT_external_memory_host has no import at all; write-combined and uncommitted pages are not tried, // and some drivers stop importing after a budget (create_shadow_buffer). The title then gets a shadow // buffer at its VA, brought up to date from its pages before every submission. resource->Release(); resource = new Resource(state_, desc, heap, D3D12_HEAP_FLAG_NONE); resource->attach_device(identity()); const HRESULT shadow = resource->create_shadow_buffer(address); if (SUCCEEDED(shadow)) { log_once("a title-placed buffer (device slot 133) could not import its pages, so it is a shadow " "copied from them before every submission; HRESULT", int(hr)); return d3d12_trace::result(method, hand_out(resource, riid, out)); } // No memory for the shadow either: the boot goes on with an ordinary DEFAULT buffer of the same // description, as #6915's stand-in did. The title gets a resource, but neither its VA nor its writes at // `address` reach it. resource->Release(); log_once("a title-placed buffer (device slot 133) could neither import its pages nor get a shadow, so it " "is an ordinary buffer the title's writes do not reach; HRESULT", int(shadow)); const D3D12_HEAP_PROPERTIES fallback{D3D12_HEAP_TYPE_DEFAULT}; return d3d12_trace::result(method, create_committed(&fallback, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, 0, nullptr, riid, out, std::nullopt)); } return d3d12_trace::result(method, hand_out(resource, riid, out)); } HRESULT STDMETHODCALLTYPE OpenExistingHeapFromFileMapping(HANDLE file_mapping, REFIID, void** out) override { constexpr auto method = "ID3D12Device3::OpenExistingHeapFromFileMapping"; if (out) *out = nullptr; DWORD flags = 0; if (!file_mapping || !out || !GetHandleInformation(file_mapping, &flags)) return d3d12_trace::result(method, E_INVALIDARG); log_once("OpenExistingHeapFromFileMapping (existing heaps are not supported)", 0); return d3d12_trace::result(method, E_NOTIMPL); } HRESULT STDMETHODCALLTYPE CreateLifetimeTracker(ID3D12LifetimeOwner* owner, REFIID, void** out) override { constexpr auto method = "ID3D12Device5::CreateLifetimeTracker"; if (out) *out = nullptr; if (!owner || !out) return d3d12_trace::result(method, E_INVALIDARG); log_once("CreateLifetimeTracker (not supported)", 0); return d3d12_trace::result(method, E_NOTIMPL); } HRESULT STDMETHODCALLTYPE CreateHeap(const D3D12_HEAP_DESC* desc, REFIID riid, void** out) override { if (out) *out = nullptr; if (!desc) return E_INVALIDARG; if (const char* why = heap_desc_refusal(*desc, state_.uma)) { log_once((std::string("CreateHeap refused (") + why + "), heap type").c_str(), int(desc->Properties.Type)); return E_INVALIDARG; } if (!state_.arena.mapped) { log_once("heaps need the GPU address arena (bufferDeviceAddress); heap size in KiB:", int(desc->SizeInBytes / 1024)); return E_NOTIMPL; } auto* heap = new Heap(state_, *desc); heap->attach_device(identity()); if (!heap->reserved()) { log_once("GPU address arena full (raise LEONIDA_ARENA_MB); heap size in KiB:", int(desc->SizeInBytes / 1024)); heap->Release(); return E_OUTOFMEMORY; } if (!out) { heap->Release(); return S_FALSE; } return hand_out(heap, riid, out); } HRESULT STDMETHODCALLTYPE CreatePlacedResource(ID3D12Heap* heap_interface, UINT64 heap_offset, const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear, REFIID riid, void** out) override { return create_placed("ID3D12Device::CreatePlacedResource", heap_interface, heap_offset, desc, state, clear, 0, nullptr, riid, out); } // Device8: the DESC1 placed variant without a castable list. A texture with a mip region gets the failure // answer, as on the PC runtime; a buffer's mip region is ignored. HRESULT STDMETHODCALLTYPE CreatePlacedResource1(ID3D12Heap* heap_interface, UINT64 heap_offset, const D3D12_RESOURCE_DESC1* desc, D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear, REFIID riid, void** out) override { constexpr auto method = "ID3D12Device8::CreatePlacedResource1"; if (out) *out = nullptr; if (!desc) return d3d12_trace::result(method, E_INVALIDARG); if (texture_mip_region(*desc)) return d3d12_trace::result(method, E_INVALIDARG); const D3D12_RESOURCE_DESC base = resource_desc(*desc); return create_placed(method, heap_interface, heap_offset, &base, state, clear, 0, nullptr, riid, out); } // Device10: an initial layout instead of a state, and the castable-format list, which the placed texture's // Vulkan image takes exactly as the committed path's does. A count with a null array is no list (as on the // PC runtime); the layer reports RelaxedFormatCastingSupported, so a real list is passed through. HRESULT STDMETHODCALLTYPE CreatePlacedResource2(ID3D12Heap* heap_interface, UINT64 heap_offset, const D3D12_RESOURCE_DESC1* desc, D3D12_BARRIER_LAYOUT layout, const D3D12_CLEAR_VALUE* clear, UINT32 castable_count, const DXGI_FORMAT* castable, REFIID riid, void** out) override { constexpr auto method = "ID3D12Device10::CreatePlacedResource2"; if (out) *out = nullptr; if (!desc) return d3d12_trace::result(method, E_INVALIDARG); if (texture_mip_region(*desc)) return d3d12_trace::result(method, E_INVALIDARG); const D3D12_RESOURCE_DESC base = resource_desc(*desc); if (const char* why = barrier_layout_refusal(base, layout)) { log_once((std::string(method) + " refused (" + why + "), layout").c_str(), int(layout)); return d3d12_trace::result(method, E_INVALIDARG); } // An initial layout replaces the state, so the state rules are not this call's. return create_placed(method, heap_interface, heap_offset, &base, D3D12_RESOURCE_STATE_COMMON, clear, castable_count, castable, riid, out); } // The placed path every CreatePlacedResource variant shares. A castable-format list reaches the placed // texture's Vulkan image as the committed path's does (create_committed): a buffer with a list is // E_INVALIDARG, and so is a format with no Vulkan mapping. // The arguments are answered as the host runtime answers them (d3d12_vulkan_device_test's // compare_placed_reserved, RTX 3060 / 610.88): the description, initial state and clear value rules // CreateCommittedResource has, then the placement: a buffer at a 64 KiB-aligned offset, a texture at a // multiple of its GetResourceAllocationInfo alignment (4 KiB for a small texture), in a heap aligned at least // as much, and the whole resource inside the heap. Only then is a null output E_UNEXPECTED, with nothing made. HRESULT create_placed(const char* method, ID3D12Heap* heap_interface, UINT64 heap_offset, const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear, UINT32 castable_count, const DXGI_FORMAT* castable, REFIID riid, void** out) { if (out) *out = nullptr; auto* heap = Heap::from(heap_interface); if (!heap || !desc) return d3d12_trace::result(method, E_INVALIDARG); D3D12_RESOURCE_DESC canonical = *desc; canonical.Format = pc_format(canonical.Format); // the console's D16S8 family as D24S8 desc = &canonical; if (heap->host_address()) { // An existing heap is not an arena range, and the placed path addresses resources by arena offset. log_once("a placed resource in an existing heap (OpenExistingHeapFromAddress) is not supported yet; " "dimension", int(desc->Dimension)); return d3d12_trace::result(method, E_NOTIMPL); } if (castable_count && castable && desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { log_once("castable formats on a placed buffer are invalid; count", int(castable_count)); return d3d12_trace::result(method, E_INVALIDARG); } // The description, state and clear value rules of a committed resource, but on a default heap: the heap's // DENY flags are checked against the resource below, and the host takes any initial state for a buffer in // an upload or readback heap (COPY_DEST in an upload heap, GENERIC_READ in a readback heap), where a // committed buffer must start in GENERIC_READ or COPY_DEST. UAV access is refused there all the same. const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; const char* why = committed_resource_refusal(default_heap, D3D12_HEAP_FLAG_NONE, *desc, state, clear, acceleration_structures(), state_.uma); const D3D12_HEAP_TYPE heap_type = heap->properties().Type; if (!why && (heap_type == D3D12_HEAP_TYPE_UPLOAD || heap_type == D3D12_HEAP_TYPE_READBACK) && (desc->Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) why = "UAV access in an upload or readback heap"; if (why) { log_once((std::string(method) + " refused (" + why + "), dimension").c_str(), int(desc->Dimension)); return d3d12_trace::result(method, E_INVALIDARG); } const bool tiled = is_tiled_layout(desc->Layout); const bool msaa = desc->SampleDesc.Count > 1; if (desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { if (heap->flags() & D3D12_HEAP_FLAG_DENY_BUFFERS) return d3d12_trace::result(method, E_INVALIDARG); if (heap_offset % D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT) { log_once("placed buffer offset not 64 KiB aligned:", int(heap_offset)); return d3d12_trace::result(method, E_INVALIDARG); } if (desc->Width > heap->bytes() || heap_offset > heap->bytes() - desc->Width) return d3d12_trace::result(method, E_INVALIDARG); } else { if (heap->properties().Type == D3D12_HEAP_TYPE_UPLOAD || heap->properties().Type == D3D12_HEAP_TYPE_READBACK) return d3d12_trace::result(method, E_INVALIDARG); const bool rt_ds = (desc->Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) != 0; if (rt_ds && (heap->flags() & D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES)) return d3d12_trace::result(method, E_INVALIDARG); if (!rt_ds && (heap->flags() & D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES)) return d3d12_trace::result(method, E_INVALIDARG); if (tiled && desc->Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D && desc->Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE3D) return d3d12_trace::result(method, E_INVALIDARG); if (msaa && desc->Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) return d3d12_trace::result(method, E_INVALIDARG); // Extents, mips, samples, layout and alignment, as GetResourceAllocationInfo answers them (the sample // quality is the description rules' above, as in CreateCommittedResource). D3D12_RESOURCE_DESC checked = *desc; checked.SampleDesc.Quality = 0; const D3D12_RESOURCE_ALLOCATION_INFO alloc = allocation(checked); if (alloc.SizeInBytes == UINT64_MAX || heap->alignment() < alloc.Alignment || heap_offset % alloc.Alignment) { log_once("placed texture refused (size, alignment or room in the heap), dimension", int(desc->Dimension)); return d3d12_trace::result(method, E_INVALIDARG); } const UINT64 fit_bytes = (tiled || msaa) ? alloc.SizeInBytes : min_placed_texture_bytes(checked, state_.texture_format(checked), alloc.Alignment, alloc.SizeInBytes); if (fit_bytes > heap->bytes() || heap_offset > heap->bytes() - fit_bytes) { log_once("placed texture refused (size, alignment or room in the heap), dimension", int(desc->Dimension)); return d3d12_trace::result(method, E_INVALIDARG); } if (tiled && static_cast(desc->Layout) == kXboxTiledLayout) { log_once("placed resource with the Xbox tiled layout, as 64KB_UNDEFINED_SWIZZLE; dimension", int(desc->Dimension)); } } if (!out) return d3d12_trace::result(method, E_UNEXPECTED); const bool buffer = desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER; if (buffer && !heap->use_as_placed_resource(true)) { log_once("placed buffer refused: heap uses a separate allocation for sparse tiles", 1); return d3d12_trace::result(method, E_NOTIMPL); } // Only buffers are addressable, as in D3D12: a placed texture keeps a null VA and its own Vulkan image, which // create_texture makes for 1D, 2D and 3D alike (arrays and mips included), as for a committed texture. const VkDeviceSize placed_va = desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER ? heap->offset() + heap_offset : 0; auto* resource = new Resource(state_, *desc, heap->properties(), heap->flags(), placed_va); resource->attach_device(identity()); HRESULT hr = E_NOTIMPL; if (buffer) { hr = resource->create_placed_buffer(heap->arena_range()); } else { hr = S_OK; const Format format = state_.texture_format(*desc); if (format.format == VK_FORMAT_UNDEFINED) { hr = E_INVALIDARG; } else { std::vector cast_formats; hr = castable_view_formats(format, desc->Format, castable_count, castable, cast_formats); if (SUCCEEDED(hr)) hr = resource->create_texture(format, cast_formats); if (SUCCEEDED(hr)) resource->keep_castable_formats(castable_count, castable); } } if (SUCCEEDED(hr) && !buffer && !heap->use_as_placed_resource(false)) { log_once("placed resource refused: heap uses a separate allocation for sparse tiles", 1); hr = E_NOTIMPL; } if (FAILED(hr)) { resource->Release(); return d3d12_trace::result(method, hr); } return d3d12_trace::result(method, hand_out(resource, riid, out)); } // Footprints for copies through a buffer: rows padded to D3D12_TEXTURE_DATA_PITCH_ALIGNMENT (512 for planar // depth-stencil), subresources placed at D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT, block-compressed sizes rounded up to whole blocks, depth-stencil // formats as two planes. d3d12_vulkan_device_test compares every output with the PC runtime's. void STDMETHODCALLTYPE GetCopyableFootprints(const D3D12_RESOURCE_DESC* desc, UINT first, UINT count, UINT64 base, D3D12_PLACED_SUBRESOURCE_FOOTPRINT* layouts, UINT* rows, UINT64* row_sizes, UINT64* total) override { const auto fail = [&] { for (UINT i = 0; i < count; ++i) { if (layouts) std::memset(&layouts[i], 0xff, sizeof(layouts[i])); if (rows) rows[i] = ~0u; if (row_sizes) row_sizes[i] = ~0ull; } if (total) *total = ~0ull; }; if (!desc || !xr_bias_compatible(*desc) || rgb96_refused(*desc)) return fail(); const auto align = [](UINT64 value, UINT64 to) { return (value + to - 1) / to * to; }; if (desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { // The PC runtime refuses any buffer field that isn't its one valid value (all measured on WARP, Width, // Height, Format, MipLevels 0, Layout and Count 0 also on an NVIDIA GPU). It doesn't look at Flags, so a // buffer with the render-target flag still gets its footprint (D3D-122). if (first != 0 || count != 1 || !desc->Width || desc->Height != 1 || desc->DepthOrArraySize != 1 || desc->MipLevels != 1 || desc->Format != DXGI_FORMAT_UNKNOWN || desc->Layout != D3D12_TEXTURE_LAYOUT_ROW_MAJOR || desc->SampleDesc.Count != 1 || desc->SampleDesc.Quality != 0 || (desc->Alignment && desc->Alignment != D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT)) return fail(); if (layouts) layouts[0] = {base, {DXGI_FORMAT_UNKNOWN, UINT(desc->Width), 1, 1, UINT(align(desc->Width, D3D12_TEXTURE_DATA_PITCH_ALIGNMENT))}}; if (rows) rows[0] = 1; if (row_sizes) row_sizes[0] = desc->Width; if (total) *total = desc->Width; return; } const bool volume = desc->Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D; const bool one_d = desc->Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D; if (!volume && !one_d && desc->Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) { log_once("GetCopyableFootprints dimension not supported:", desc->Dimension); return fail(); } if (one_d && desc->Height != 1) return fail(); // Structural checks only, as measured on the PC runtime (D3D-122). Not allocation()'s: the footprint path // accepts extra mips, 2D ROW_MAJOR and Quality > 0 at one sample, and extent limits, alignment and // multisample quality differ between adapters, so those stay unchecked. const UINT samples = desc->SampleDesc.Count; const bool multisample_ok = desc->Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && desc->MipLevels == 1 && desc->Layout != D3D12_TEXTURE_LAYOUT_ROW_MAJOR && !(samples & (samples - 1)) && (desc->Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)); if (!desc->Width || !desc->Height || !desc->DepthOrArraySize || !samples || (samples > 1 && !multisample_ok)) return fail(); const Format format = texture_storage_format(desc->Format, true); // typeless depth families are planar either way UINT mips = desc->MipLevels; const UINT depth = volume ? desc->DepthOrArraySize : 1; if (!mips) for (UINT64 size = std::max({desc->Width, desc->Height, depth}); size; size >>= 1) ++mips; const UINT planes = (format.aspects & VK_IMAGE_ASPECT_STENCIL_BIT) ? 2 : 1; const UINT per_plane = mips * (volume ? 1 : desc->DepthOrArraySize); if (!format.format || UINT64(first) + count > UINT64(per_plane) * planes) return fail(); // Subresources are aligned to D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT counting from BaseOffset, not from 0: the // PC runtime moves the whole layout by BaseOffset, so an unaligned base (513) keeps the same relative offsets // and the same total. Measured by compare_footprints in d3d12_vulkan_device_test. UINT64 offset = 0, end = 0; for (UINT i = 0; i < count; ++i) { const UINT index = first + i, plane = index / per_plane, mip = index % mips; const VkImageAspectFlags aspect = planes == 2 ? (plane ? VK_IMAGE_ASPECT_STENCIL_BIT : VK_IMAGE_ASPECT_DEPTH_BIT) : format.aspects; const leonida::BlockFormat block = footprint_block(format, aspect); if (!block.bytes) return fail(); // D3D12 takes any MipLevels, and the PC runtime's own shifts wrap past the type's width: a 16x16 texture // with 40 mips reports subresource 32 as 1x16 and 33 as 1x8, a volume's depth likewise (measured on an // RTX 5060 Ti, compare_footprints). The masks give the same answers without shifting a 32-bit (or the // 64-bit Width) value by its width or more, which C++ leaves undefined. const UINT width = std::max(1, UINT(desc->Width >> (mip & 63))); const UINT height = one_d ? 1 : std::max(1, desc->Height >> (mip & 31)); const UINT blocks_wide = (width + block.block - 1) / block.block; const UINT blocks_high = (height + block.block - 1) / block.block; const UINT64 row_size = UINT64(blocks_wide) * block.bytes; // Measured against the PC runtime (d3d12_vulkan_device_test): planar depth-stencil rows are padded to // 512 bytes, every other format's to D3D12_TEXTURE_DATA_PITCH_ALIGNMENT (256). const UINT pitch = UINT(align(row_size, planes == 2 ? 2 * D3D12_TEXTURE_DATA_PITCH_ALIGNMENT : D3D12_TEXTURE_DATA_PITCH_ALIGNMENT)); offset = align(offset, D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT); DXGI_FORMAT footprint_format = desc->Format; if (planes == 2) footprint_format = plane ? DXGI_FORMAT_R8_TYPELESS : (desc->Format==xbox_d16s8?DXGI_FORMAT_R16_TYPELESS:DXGI_FORMAT_R32_TYPELESS); const UINT slices = std::max(1u, depth >> (mip & 31)); if (layouts) layouts[i] = {base + offset, {footprint_format, blocks_wide * block.block, blocks_high * block.block, slices, pitch}}; if (rows) rows[i] = blocks_high; if (row_sizes) row_sizes[i] = row_size; const UINT64 total_rows = UINT64(blocks_high) * slices; end = offset + (total_rows - 1) * pitch + row_size; offset += total_rows * pitch; } if (total) *total = end; } // How much heap memory resources need and how to align them, for applications that suballocate heaps (section // 4.1). Buffers follow D3D12's fixed rule. A texture's size is what the Vulkan image it becomes needs, rounded up // to D3D12's alignment for it; the alignment itself is D3D12's, since placed textures bind their own memory // (section 4.2). Several resources are laid out one after another, each at its own alignment. An invalid // description gives SizeInBytes = UINT64_MAX, as on D3D12. d3d12_vulkan_device_test compares with the PC runtime. // A visible mask above 1 names a node the single-node adapter lacks: the same invalid answer, also for no // resources at all, and the per-resource array is left untouched (host runtime and WARP, measured). D3D12_RESOURCE_ALLOCATION_INFO STDMETHODCALLTYPE GetResourceAllocationInfo( UINT visible_mask, UINT count, const D3D12_RESOURCE_DESC* descs) override { if (visible_mask > 1) return kInvalidAllocation; return place(count, descs, [&](UINT i) { return descs[i]; }, nullptr); } D3D12_RESOURCE_ALLOCATION_INFO STDMETHODCALLTYPE GetResourceAllocationInfo1( UINT visible_mask, UINT count, const D3D12_RESOURCE_DESC* descs, D3D12_RESOURCE_ALLOCATION_INFO1* each) override { if (visible_mask > 1) return kInvalidAllocation; return place(count, descs, [&](UINT i) { return descs[i]; }, each); } D3D12_RESOURCE_ALLOCATION_INFO STDMETHODCALLTYPE GetResourceAllocationInfo2( UINT visible_mask, UINT count, const D3D12_RESOURCE_DESC1* descs, D3D12_RESOURCE_ALLOCATION_INFO1* each) override { if (visible_mask > 1) return kInvalidAllocation; return place(count, descs, [&](UINT i) { const D3D12_RESOURCE_DESC1& d = descs[i]; if (d.SamplerFeedbackMipRegion.Width || d.SamplerFeedbackMipRegion.Height || d.SamplerFeedbackMipRegion.Depth) { log_once("GetResourceAllocationInfo2 sampler feedback not supported, format", d.Format); return D3D12_RESOURCE_DESC{}; // an unknown dimension: invalid } return D3D12_RESOURCE_DESC{d.Dimension, d.Alignment, d.Width, d.Height, d.DepthOrArraySize, d.MipLevels, d.Format, d.SampleDesc, d.Layout, d.Flags}; }, each); } template static HRESULT write_supported_feature(const char* method, void* data, UINT size, BOOL supported) { if (size != sizeof(FeatureData)) return d3d12_trace::result(method, E_INVALIDARG); static_cast(data)->Supported = supported; return d3d12_trace::result(method, S_OK); } HRESULT STDMETHODCALLTYPE CheckFeatureSupport(D3D12_FEATURE feature, void* data, UINT size) override { constexpr auto method = "ID3D12Device::CheckFeatureSupport"; log_once("CheckFeatureSupport feature", feature); if (!data) return d3d12_trace::result(method, E_INVALIDARG); constexpr VkSampleCountFlags d3d12_multisample_sample_counts = 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; switch (feature) { case D3D12_FEATURE_FEATURE_LEVELS: { if (size != sizeof(D3D12_FEATURE_DATA_FEATURE_LEVELS)) return d3d12_trace::result(method, E_INVALIDARG); auto* levels = static_cast(data); // The host (hardware and WARP) refuses an empty or missing list before reading it. if (!levels->NumFeatureLevels || !levels->pFeatureLevelsRequested) return d3d12_trace::result(method, E_INVALIDARG); D3D_FEATURE_LEVEL best = D3D_FEATURE_LEVEL(0); for (UINT i = 0; i < levels->NumFeatureLevels; ++i) if (levels->pFeatureLevelsRequested[i] <= D3D_FEATURE_LEVEL_12_1) best = std::max(best, levels->pFeatureLevelsRequested[i]); levels->MaxSupportedFeatureLevel = best; // 0 with DXGI_ERROR_UNSUPPORTED, as the host writes it if (!best) return d3d12_trace::result(method, DXGI_ERROR_UNSUPPORTED); return d3d12_trace::result(method, S_OK); } case D3D12_FEATURE_ARCHITECTURE: case D3D12_FEATURE_ARCHITECTURE1: { const bool v1 = feature == D3D12_FEATURE_ARCHITECTURE1; if (size != (v1 ? sizeof(D3D12_FEATURE_DATA_ARCHITECTURE1) : sizeof(D3D12_FEATURE_DATA_ARCHITECTURE))) return d3d12_trace::result(method, E_INVALIDARG); auto* arch = static_cast(data); const UINT node = arch->NodeIndex; if (node != 0) return d3d12_trace::result(method, E_INVALIDARG); // The host GPU's architecture (question 11): not tile-based; UMA on an integrated GPU, as the host runtime // answers there (Radeon 780M, AMD 32.0.13030.13001: UMA 1, CacheCoherentUMA 0), else a discrete one. The // console is UMA; the layer keeps upload heaps host-visible either way, so the game's upload path works. // CacheCoherentUMA stays FALSE: the AMD iGPU measured reports it so, and FALSE only steers an application // to write-combined uploads, which every UMA adapter accepts. arch->TileBasedRenderer = FALSE; arch->UMA = state_.uma ? TRUE : FALSE; arch->CacheCoherentUMA = FALSE; if (v1) arch->IsolatedMMU = TRUE; return d3d12_trace::result(method, S_OK); } case D3D12_FEATURE_D3D12_OPTIONS: { constexpr UINT kConsoleOptionsSize = sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS) + sizeof(UINT); if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS) && size != kConsoleOptionsSize) return d3d12_trace::result(method, E_INVALIDARG); D3D12_FEATURE_DATA_D3D12_OPTIONS pc_opts{}; // Answer what the layer will actually honour, not what the GPU offers: docs/d3d12_vulkan.md 4.1 says a // false "supported" is worse than a false "unsupported" at boot, and the PSO paths refuse these same // features when they are missing (logic ops, per the mapping vkd3d-proton's // d3d12_device_caps_init_feature_options uses). pc_opts.DoublePrecisionFloatShaderOps = state_.info.features.shaderFloat64; pc_opts.OutputMergerLogicOp = state_.info.features.logicOp; pc_opts.MinPrecisionSupport = D3D12_SHADER_MIN_PRECISION_SUPPORT_NONE; pc_opts.TiledResourcesTier = D3D12_TILED_RESOURCES_TIER_NOT_SUPPORTED; pc_opts.ResourceBindingTier = D3D12_RESOURCE_BINDING_TIER_3; // Bindless descriptor indexing supported // No VK_EXT_shader_stencil_export is enabled and the translator emits no stencil-ref write, so a pixel // shader that writes the stencil ref would be refused: answer unsupported, the direction 4.1 prefers. pc_opts.PSSpecifiedStencilRefSupported = FALSE; pc_opts.TypedUAVLoadAdditionalFormats = TRUE; // POPS: the translator only declares PixelInterlockOrderedEXT, enabled exactly when the GPU offers // VK_EXT_fragment_shader_interlock and its fragmentShaderPixelInterlock feature. pc_opts.ROVsSupported = state_.info.fragment_shader_interlock; pc_opts.ConservativeRasterizationTier = state_.conservative_raster_tier; pc_opts.MaxGPUVirtualAddressBitsPerResource = 40; pc_opts.StandardSwizzle64KBSupported = FALSE; pc_opts.CrossNodeSharingTier = D3D12_CROSS_NODE_SHARING_TIER_NOT_SUPPORTED; pc_opts.CrossAdapterRowMajorTextureSupported = FALSE; // A translated vertex shader writing a layer or viewport index needs both Vulkan 1.2 features enabled // (vkCreateShaderModule refuses the module without them, VUID-...-pCode-08740). pc_opts.VPAndRTArrayIndexFromAnyShaderFeedingRasterizerSupportedWithoutGSEmulation = state_.info.shader_output_layer && state_.info.shader_output_viewport_index; pc_opts.ResourceHeapTier = D3D12_RESOURCE_HEAP_TIER_1; std::memcpy(data, &pc_opts, sizeof(pc_opts)); if (size == kConsoleOptionsSize) { // Console titles query D3D12_FEATURE_D3D12_OPTIONS with a 0x40-byte (16-dword) buffer // (docs/d3d12_xs_surface.md §7.1): fill the 0x3C-byte PC prefix and zero the trailing 4 bytes. std::memset(static_cast(data) + sizeof(pc_opts), 0, sizeof(UINT)); } return d3d12_trace::result(method, S_OK); } case D3D12_FEATURE_D3D12_OPTIONS1: { if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS1)) return d3d12_trace::result(method, E_INVALIDARG); auto* opts = static_cast(data); const DeviceState::SubgroupFacts& facts = state_.subgroup_facts(); *opts = {}; opts->WaveOps = facts.wave_ops; opts->WaveLaneCountMin = facts.lane_min; opts->WaveLaneCountMax = facts.lane_max; // D3D12 counts every lane of the device here, and Vulkan has no such number. This is one full wave // (section 4.1): a game that sizes work from it plans for less parallelism than the GPU has, not more. opts->TotalLaneCount = facts.lane_max; opts->ExpandedComputeResourceStates = TRUE; // Vulkan has no resource states to expand return d3d12_trace::result(method, S_OK); } case D3D12_FEATURE_D3D12_OPTIONS8: { if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS8)) return d3d12_trace::result(method, E_INVALIDARG); // Vulkan BC image extents are in texels; only the transfer footprints round up to blocks. auto* opts = static_cast(data); opts->UnalignedBlockTexturesSupported = state_.info.texture_compression_bc; return d3d12_trace::result(method, S_OK); } case D3D12_FEATURE_D3D12_OPTIONS2: { if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS2)) return d3d12_trace::result(method, E_INVALIDARG); auto* opts = static_cast(data); *opts = {}; opts->DepthBoundsTestSupported = FALSE; opts->ProgrammableSamplePositionsTier = D3D12_PROGRAMMABLE_SAMPLE_POSITIONS_TIER_NOT_SUPPORTED; return d3d12_trace::result(method, S_OK); } case D3D12_FEATURE_D3D12_OPTIONS3: { if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS3)) return d3d12_trace::result(method, E_INVALIDARG); auto* opts = static_cast(data); *opts = {}; opts->CopyQueueTimestampQueriesSupported = state_.copy_timestamps_supported(); // Only typeless resources set VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT. opts->CastingFullyTypedFormatSupported = FALSE; opts->WriteBufferImmediateSupportFlags = D3D12_COMMAND_LIST_SUPPORT_FLAG_NONE; opts->ViewInstancingTier = D3D12_VIEW_INSTANCING_TIER_NOT_SUPPORTED; opts->BarycentricsSupported = FALSE; return d3d12_trace::result(method, S_OK); } case D3D12_FEATURE_D3D12_OPTIONS4: { if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS4)) return d3d12_trace::result(method, E_INVALIDARG); auto* opts = static_cast(data); *opts = {}; // GetResourceAllocationInfo implements D3D12_SMALL_MSAA_RESOURCE_PLACEMENT_ALIGNMENT (64 KiB). opts->MSAA64KBAlignedTextureSupported = TRUE; opts->SharedResourceCompatibilityTier = D3D12_SHARED_RESOURCE_COMPATIBILITY_TIER_0; opts->Native16BitShaderOpsSupported = FALSE; return d3d12_trace::result(method, S_OK); } case D3D12_FEATURE_D3D12_OPTIONS5: { if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS5)) return d3d12_trace::result(method, E_INVALIDARG); auto* opts = static_cast(data); *opts = {}; opts->SRVOnlyTiledResourceTier3 = FALSE; opts->RenderPassesTier = D3D12_RENDER_PASS_TIER_0; opts->RaytracingTier = D3D12_RAYTRACING_TIER_NOT_SUPPORTED; return d3d12_trace::result(method, S_OK); } case D3D12_FEATURE_D3D12_OPTIONS7: { if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS7)) return d3d12_trace::result(method, E_INVALIDARG); auto* opts = static_cast(data); *opts = {}; // Tier 1 is mesh PSOs and DispatchMesh, on VK_EXT_mesh_shader. Amplification shaders are part of the tier // but refused at PSO creation (the game has none); OPTIONS9's mesh statistics and full-range render // target array index stay FALSE. opts->MeshShaderTier = state_.info.mesh_shader ? D3D12_MESH_SHADER_TIER_1 : D3D12_MESH_SHADER_TIER_NOT_SUPPORTED; opts->SamplerFeedbackTier = D3D12_SAMPLER_FEEDBACK_TIER_NOT_SUPPORTED; return d3d12_trace::result(method, S_OK); } case D3D12_FEATURE_D3D12_OPTIONS9: { if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS9)) return d3d12_trace::result(method, E_INVALIDARG); auto* opts = static_cast(data); *opts = {}; opts->MeshShaderPipelineStatsSupported = FALSE; opts->MeshShaderSupportsFullRangeRenderTargetArrayIndex = FALSE; opts->AtomicInt64OnTypedResourceSupported = FALSE; opts->AtomicInt64OnGroupSharedSupported = FALSE; opts->DerivativesInMeshAndAmplificationShadersSupported = FALSE; opts->WaveMMATier = D3D12_WAVE_MMA_TIER_NOT_SUPPORTED; return d3d12_trace::result(method, S_OK); } case D3D12_FEATURE_D3D12_OPTIONS11: { if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS11)) return d3d12_trace::result(method, E_INVALIDARG); auto* opts = static_cast(data); *opts = {}; opts->AtomicInt64OnDescriptorHeapResourceSupported = FALSE; return d3d12_trace::result(method, S_OK); } case D3D12_FEATURE_D3D12_OPTIONS13: { if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS13)) return d3d12_trace::result(method, E_INVALIDARG); auto* opts = static_cast(data); *opts = {}; opts->UnrestrictedBufferTextureCopyPitchSupported = FALSE; opts->UnrestrictedVertexElementAlignmentSupported = FALSE; opts->InvertedViewportHeightFlipsYSupported = FALSE; opts->InvertedViewportDepthFlipsZSupported = FALSE; opts->TextureCopyBetweenDimensionsSupported = FALSE; opts->AlphaBlendFactorSupported = FALSE; return d3d12_trace::result(method, S_OK); } case D3D12_FEATURE_D3D12_OPTIONS14: { if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS14)) return d3d12_trace::result(method, E_INVALIDARG); auto* opts = static_cast(data); *opts = {}; opts->AdvancedTextureOpsSupported = FALSE; opts->WriteableMSAATexturesSupported = FALSE; // DEPTH_STENCIL2's per-face masks go to VkStencilOpState, and OMSetFrontAndBackStencilRef sets each // face's reference (VK_DYNAMIC_STATE_STENCIL_REFERENCE with a face mask). opts->IndependentFrontAndBackStencilRefMaskSupported = TRUE; return d3d12_trace::result(method, S_OK); } case D3D12_FEATURE_D3D12_OPTIONS15: { if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS15)) return d3d12_trace::result(method, E_INVALIDARG); auto* opts = static_cast(data); *opts = {}; opts->TriangleFanSupported = FALSE; opts->DynamicIndexBufferStripCutSupported = FALSE; return d3d12_trace::result(method, S_OK); } case D3D12_FEATURE_D3D12_OPTIONS16: { if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS16)) return d3d12_trace::result(method, E_INVALIDARG); auto* opts = static_cast(data); *opts = {}; opts->DynamicDepthBiasSupported = FALSE; opts->GPUUploadHeapSupported = FALSE; return d3d12_trace::result(method, S_OK); } case D3D12_FEATURE_D3D12_OPTIONS12: { // Vulkan 1.3's VkImageFormatListCreateInfo gives a mutable image the same relaxed format casting that // D3D12's castable-format lists describe. The layer also implements enhanced barriers (Barrier). if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS12)) return E_INVALIDARG; auto* opts = static_cast(data); *opts = {}; opts->MSPrimitivesPipelineStatisticIncludesCulledPrimitives = D3D12_TRI_STATE_UNKNOWN; opts->EnhancedBarriersSupported = TRUE; opts->RelaxedFormatCastingSupported = TRUE; return S_OK; } case D3D12_FEATURE_D3D12_OPTIONS17: { // Non-normalized samplers are core Vulkan (unnormalizedCoordinates), with the restrictions // CreateSampler2 checks. No manual write tracking, as the RTX 4090 answers too. if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS17)) return d3d12_trace::result(method, E_INVALIDARG); auto* opts = static_cast(data); *opts = {}; opts->NonNormalizedCoordinateSamplersSupported = TRUE; return d3d12_trace::result(method, S_OK); } case D3D12_FEATURE_D3D12_OPTIONS18: { if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS18)) return d3d12_trace::result(method, E_INVALIDARG); auto* opts = static_cast(data); *opts = {}; opts->RenderPassesValid = FALSE; return d3d12_trace::result(method, S_OK); } case D3D12_FEATURE_D3D12_OPTIONS19: { if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS19)) return d3d12_trace::result(method, E_INVALIDARG); auto* opts = static_cast(data); *opts = {}; opts->MismatchingOutputDimensionsSupported = FALSE; opts->SupportedSampleCountsWithNoOutputs = state_.no_output_sample_counts; opts->PointSamplingAddressesNeverRoundUp = FALSE; opts->RasterizerDesc2Supported = FALSE; opts->NarrowQuadrilateralLinesSupported = FALSE; opts->AnisoFilterWithPointMipSupported = state_.info.sampler_anisotropy ? TRUE : FALSE; opts->MaxSamplerDescriptorHeapSize = D3D12_MAX_SHADER_VISIBLE_SAMPLER_HEAP_SIZE; opts->MaxSamplerDescriptorHeapSizeWithStaticSamplers = D3D12_MAX_SHADER_VISIBLE_SAMPLER_HEAP_SIZE; opts->MaxViewDescriptorHeapSize = D3D12_MAX_SHADER_VISIBLE_DESCRIPTOR_HEAP_SIZE_TIER_2; opts->ComputeOnlyCustomHeapSupported = FALSE; return d3d12_trace::result(method, S_OK); } case compat::kFeatureOptions20: { if (size != sizeof(compat::FeatureDataOptions20)) return d3d12_trace::result(method, E_INVALIDARG); auto* opts = static_cast(data); *opts = {}; opts->ComputeOnlyWriteWatchSupported = FALSE; opts->RecreateAtTier = compat::kRecreateAtTierNotSupported; return d3d12_trace::result(method, S_OK); } case compat::kFeatureOptions21: { if (size != sizeof(compat::FeatureDataOptions21)) return d3d12_trace::result(method, E_INVALIDARG); auto* opts = static_cast(data); *opts = {}; opts->WorkGraphsTier = compat::kWorkGraphsTierNotSupported; opts->ExecuteIndirectTier = compat::kExecuteIndirectTier1_0; opts->SampleCmpGradientAndBiasSupported = FALSE; opts->ExtendedCommandInfoSupported = FALSE; return d3d12_trace::result(method, S_OK); } case D3D12_FEATURE_GPU_VIRTUAL_ADDRESS_SUPPORT: { if (size != sizeof(D3D12_FEATURE_DATA_GPU_VIRTUAL_ADDRESS_SUPPORT)) return d3d12_trace::result(method, E_INVALIDARG); auto* va = static_cast(data); // The console and PC BDA support 48-bit GPU virtual addresses (section 4.1). va->MaxGPUVirtualAddressBitsPerResource = 40; va->MaxGPUVirtualAddressBitsPerProcess = 48; return d3d12_trace::result(method, S_OK); } case D3D12_FEATURE_FORMAT_INFO: { if (size != sizeof(D3D12_FEATURE_DATA_FORMAT_INFO)) return E_INVALIDARG; auto* info = static_cast(data); // Plane count describes the DXGI layout even when the backend cannot create the texture. switch (info->Format) { case DXGI_FORMAT_R32G8X24_TYPELESS: case DXGI_FORMAT_D32_FLOAT_S8X24_UINT: case DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS: case DXGI_FORMAT_X32_TYPELESS_G8X24_UINT: case DXGI_FORMAT_R24G8_TYPELESS: case DXGI_FORMAT_D24_UNORM_S8_UINT: case DXGI_FORMAT_R24_UNORM_X8_TYPELESS: case DXGI_FORMAT_X24_TYPELESS_G8_UINT: case DXGI_FORMAT_NV12: case DXGI_FORMAT_P010: case DXGI_FORMAT_P016: case DXGI_FORMAT_NV11: info->PlaneCount = 2; break; case DXGI_FORMAT_SAMPLER_FEEDBACK_MIN_MIP_OPAQUE: case DXGI_FORMAT_SAMPLER_FEEDBACK_MIP_REGION_USED_OPAQUE: case DXGI_FORMAT_A4B4G4R4_UNORM: info->PlaneCount = 1; break; default: // Native D3D12 accepts UNKNOWN but rejects R1_UNORM and the gaps in the enum. if (UINT(info->Format) > DXGI_FORMAT_B4G4R4A4_UNORM || info->Format == DXGI_FORMAT_R1_UNORM) return E_INVALIDARG; info->PlaneCount = 1; } return S_OK; } case D3D12_FEATURE_FORMAT_SUPPORT: { if (size != sizeof(D3D12_FEATURE_DATA_FORMAT_SUPPORT)) return d3d12_trace::result(method, E_INVALIDARG); auto* fs = static_cast(data); fs->Support1 = D3D12_FORMAT_SUPPORT1_NONE; fs->Support2 = D3D12_FORMAT_SUPPORT2_NONE; // The host runtime's format table (compare_invalid_arguments, "format support:"): a value it has no entry // for is E_FAIL, not unsupported: past B4G4R4A4_UNORM (115) up to 188, which includes the planar video // formats P208/V208/V408 (130-132), and from 192 up; 189-191 are the sampler-feedback formats and // A4B4G4R4. UNKNOWN is a buffer format (raw and structured buffers). const UINT format_value = static_cast(fs->Format); if (format_value > static_cast(DXGI_FORMAT_B4G4R4A4_UNORM) && !(rt::d3d12_xs::console_feature_query() && format_value >= 118 && format_value <= 120) && (format_value < 189 || format_value > 191)) return d3d12_trace::result(method, E_FAIL); if (fs->Format == DXGI_FORMAT_UNKNOWN) { fs->Support1 = D3D12_FORMAT_SUPPORT1_BUFFER; return d3d12_trace::result(method, S_OK); } // The plane formats a shader reads a depth-stencil texture through (CreateShaderResourceView takes them on // R24G8/R32G8X24 and D24S8/D32S8 textures) have no image of their own, so the lookups below find nothing. // The host reports them as sampled 2D and cube textures with mips, the depth plane also filtered and // compared. Left out, as for the depth formats themselves: 1D, and multisample loads. const bool depth_plane = fs->Format == xbox_d16_plane || fs->Format == DXGI_FORMAT_R24_UNORM_X8_TYPELESS || fs->Format == DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS; if (depth_plane || fs->Format == xbox_s8_plane || fs->Format == DXGI_FORMAT_X24_TYPELESS_G8_UINT || fs->Format == DXGI_FORMAT_X32_TYPELESS_G8X24_UINT) { const bool d24 = fs->Format == DXGI_FORMAT_R24_UNORM_X8_TYPELESS || fs->Format == DXGI_FORMAT_X24_TYPELESS_G8_UINT; VkFormat family = vulkan_format(d24 ? DXGI_FORMAT_D24_UNORM_S8_UINT : DXGI_FORMAT_D32_FLOAT_S8X24_UINT, true).format; if(fs->Format==xbox_d16_plane || fs->Format==xbox_s8_plane)family=state_.depth_backing(VK_FORMAT_D16_UNORM_S8_UINT); if (family == VK_FORMAT_D24_UNORM_S8_UINT && !state_.depth_usable(family)) family = VK_FORMAT_D32_SFLOAT_S8_UINT; VkFormatProperties props{}; if (state_.format_properties) state_.format_properties(state_.info.physical, family, &props); if (!(props.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT)) return d3d12_trace::result(method, DXGI_ERROR_UNSUPPORTED); fs->Support1 = D3D12_FORMAT_SUPPORT1_TEXTURE2D | D3D12_FORMAT_SUPPORT1_TEXTURECUBE | D3D12_FORMAT_SUPPORT1_SHADER_LOAD | D3D12_FORMAT_SUPPORT1_MIP; if (depth_plane && (props.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT)) fs->Support1 |= D3D12_FORMAT_SUPPORT1_SHADER_SAMPLE | D3D12_FORMAT_SUPPORT1_SHADER_GATHER | D3D12_FORMAT_SUPPORT1_SHADER_SAMPLE_COMPARISON | D3D12_FORMAT_SUPPORT1_SHADER_GATHER_COMPARISON; return d3d12_trace::result(method, S_OK); } const Format fmt = texture_storage_format(fs->Format, false); const Format depth_fmt = vulkan_format(fs->Format, true); VkFormat vk_fmt = fmt.format != VK_FORMAT_UNDEFINED ? fmt.format : depth_fmt.format; // Report what creation makes: a D24 texture on a GPU without Vulkan D24 (AMD) is a D32_SFLOAT_S8_UINT // image (texture_format), so its features are D32S8's. Asking D24 itself gave Support1 = 0 there, // although CreateCommittedResource(ALLOW_DEPTH_STENCIL) succeeds. vk_fmt=state_.depth_backing(vk_fmt); if (vk_fmt == VK_FORMAT_D24_UNORM_S8_UINT && !state_.depth_usable(vk_fmt)) vk_fmt = VK_FORMAT_D32_SFLOAT_S8_UINT; if (vk_fmt == VK_FORMAT_UNDEFINED || !state_.format_properties) { return d3d12_trace::result(method, DXGI_ERROR_UNSUPPORTED); } if (fs->Format == DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM) { // The host reports this display format as 2D, display, cast-within-bit-layout, back-buffer-cast and // video-processor output, and no shader reads. The layer has the 2D resource and the bit-compatible // view cast; it has no display scan-out or video processor, so it reports only what it provides. fs->Support1 = D3D12_FORMAT_SUPPORT1_TEXTURE2D | D3D12_FORMAT_SUPPORT1_CAST_WITHIN_BIT_LAYOUT; return S_OK; } VkFormatProperties props{}; state_.format_properties(state_.info.physical, vk_fmt, &props); VkFormatFeatureFlags optimal = props.optimalTilingFeatures; VkFormatFeatureFlags buffer = props.bufferFeatures; if (fmt.rgb96) { // Textures are RGBA32 images that are sampled and copied, nothing else yet (no render target, // no unordered access: creation refuses them). Buffers hold the real 12-byte format; the PC // runtime (WARP) has no typed unordered access of these formats, in buffers either. optimal &= VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT | VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT; VkFormatProperties narrow{}; state_.format_properties(state_.info.physical, rgb96_named_format(vk_fmt), &narrow); buffer = narrow.bufferFeatures & ~VkFormatFeatureFlags(VK_FORMAT_FEATURE_STORAGE_TEXEL_BUFFER_BIT | VK_FORMAT_FEATURE_STORAGE_TEXEL_BUFFER_ATOMIC_BIT); } D3D12_FORMAT_SUPPORT1 s1 = D3D12_FORMAT_SUPPORT1_NONE; D3D12_FORMAT_SUPPORT2 s2 = D3D12_FORMAT_SUPPORT2_NONE; if (fs->Format == DXGI_FORMAT_A8_UNORM) { if (optimal & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) { fs->Support1 = D3D12_FORMAT_SUPPORT1_TEXTURE1D | D3D12_FORMAT_SUPPORT1_TEXTURE2D | D3D12_FORMAT_SUPPORT1_TEXTURE3D | D3D12_FORMAT_SUPPORT1_TEXTURECUBE | D3D12_FORMAT_SUPPORT1_SHADER_LOAD; if (optimal & VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT) fs->Support1 |= D3D12_FORMAT_SUPPORT1_SHADER_SAMPLE | D3D12_FORMAT_SUPPORT1_SHADER_GATHER; VkImageFormatProperties limits{}; const VkImageUsageFlags usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; if (state_.image_format_properties && state_.image_format_properties(state_.info.physical, vk_fmt, VK_IMAGE_TYPE_2D, VK_IMAGE_TILING_OPTIMAL, usage, 0, &limits) == VK_SUCCESS && limits.maxMipLevels > 1) fs->Support1 |= D3D12_FORMAT_SUPPORT1_MIP; // Render targets are stored as VK_FORMAT_A8_UNORM_KHR, which the device checked can blend. if (state_.info.a8_render_target) fs->Support1 |= D3D12_FORMAT_SUPPORT1_RENDER_TARGET | D3D12_FORMAT_SUPPORT1_BLENDABLE; } return d3d12_trace::result(method, S_OK); } // D3D12 disallows typed buffer views for the RGBA8 and BGRA8 sRGB formats (including BGRX8). // Vulkan can still advertise buffer features for their backing formats. if (buffer != 0 && vk_fmt != VK_FORMAT_R8G8B8A8_SRGB && vk_fmt != VK_FORMAT_B8G8R8A8_SRGB) s1 |= D3D12_FORMAT_SUPPORT1_BUFFER; // Only what CreateGraphicsPipelineState's input layouts accept (vertex_format). VkFormat vertex_vk = VK_FORMAT_UNDEFINED; UINT vertex_bytes = 0; if ((buffer & VK_FORMAT_FEATURE_VERTEX_BUFFER_BIT) && vertex_format(fs->Format, vertex_vk, vertex_bytes)) s1 |= D3D12_FORMAT_SUPPORT1_IA_VERTEX_BUFFER; if (fs->Format == DXGI_FORMAT_R16_UINT || fs->Format == DXGI_FORMAT_R32_UINT) s1 |= D3D12_FORMAT_SUPPORT1_IA_INDEX_BUFFER; if (optimal & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) { s1 |= D3D12_FORMAT_SUPPORT1_TEXTURE1D | D3D12_FORMAT_SUPPORT1_TEXTURE2D | D3D12_FORMAT_SUPPORT1_TEXTURE3D | D3D12_FORMAT_SUPPORT1_TEXTURECUBE | D3D12_FORMAT_SUPPORT1_SHADER_LOAD; } if (buffer & VK_FORMAT_FEATURE_UNIFORM_TEXEL_BUFFER_BIT) { s1 |= D3D12_FORMAT_SUPPORT1_SHADER_LOAD; } if (optimal & VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT) { s1 |= D3D12_FORMAT_SUPPORT1_SHADER_SAMPLE; } if (optimal & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT) { s1 |= D3D12_FORMAT_SUPPORT1_RENDER_TARGET; // A D3D12 multisample resolve needs the same image usages as TextureCreateInfo: colour // attachment plus transfer source/destination (and the ordinary sampled usage). VkImageFormatProperties image_properties{}; const VkImageUsageFlags usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT; const VkImageCreateFlags flags = fmt.typeless ? VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT : 0; if (state_.image_format_properties && state_.image_format_properties(state_.info.physical, vk_fmt, VK_IMAGE_TYPE_2D, VK_IMAGE_TILING_OPTIMAL, usage, flags, &image_properties) == VK_SUCCESS && (image_properties.sampleCounts & d3d12_multisample_sample_counts)) { s1 |= D3D12_FORMAT_SUPPORT1_MULTISAMPLE_RENDERTARGET | D3D12_FORMAT_SUPPORT1_MULTISAMPLE_RESOLVE; if ((optimal & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) && !fmt.typeless && fmt.aspects == VK_IMAGE_ASPECT_COLOR_BIT && leonida::gfx10::format_from_vulkan(vk_fmt) && state_.bindless && state_.bindless->supports_ms_class(DeviceState::numeric_class(vk_fmt))) s1 |= D3D12_FORMAT_SUPPORT1_MULTISAMPLE_LOAD; } } if(fs->Format==DXGI_FORMAT_B4G4R4A4_UNORM && !(optimal&VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT) && state_.color_attachment_usable(VK_FORMAT_R8G8B8A8_UNORM))s1|=D3D12_FORMAT_SUPPORT1_RENDER_TARGET; if (optimal & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BLEND_BIT) { s1 |= D3D12_FORMAT_SUPPORT1_BLENDABLE; } if (optimal & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT) { s1 |= D3D12_FORMAT_SUPPORT1_DEPTH_STENCIL; } // B8G8R8X8 has no typed UAV in D3D12 (texture_format refuses it), whatever the BGRA8 image could do. if (!alpha_unused(fs->Format) && ((optimal & VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT) || (buffer & VK_FORMAT_FEATURE_STORAGE_TEXEL_BUFFER_BIT))) { s1 |= D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW; // A typed UAV texture read is not a storage-image read: the translator reads it through the // texture's sampled binding with the T#'s numeric type (rdna2spirv.py image_read_typed), so a // format that can be stored can be read. Typed buffer UAVs share the store side's limits: a buffer // UAV is a typed V# the layer writes itself (write_buffer_uav, no VkBufferView), and rdna2spirv.py // FORMATS decodes only some buffer formats. s2 |= D3D12_FORMAT_SUPPORT2_UAV_TYPED_STORE | D3D12_FORMAT_SUPPORT2_UAV_TYPED_LOAD; // Image atomics go through the r32ui storage view, which an R32_UINT UAV view gets // (StorageViews::r32ui). Today that is 2D UAVs only: the translator's image atomics cover 2D and 3D, // the bindless set has r32ui slots for those two, and the layer creates no 3D UAV views yet. There // is no image_atomic_swap, so no exchange. if (vk_fmt == VK_FORMAT_R32_UINT && (optimal & VK_FORMAT_FEATURE_STORAGE_IMAGE_ATOMIC_BIT)) { s2 |= D3D12_FORMAT_SUPPORT2_UAV_ATOMIC_ADD | D3D12_FORMAT_SUPPORT2_UAV_ATOMIC_BITWISE_OPS | D3D12_FORMAT_SUPPORT2_UAV_ATOMIC_COMPARE_STORE_OR_COMPARE_EXCHANGE | D3D12_FORMAT_SUPPORT2_UAV_ATOMIC_SIGNED_MIN_OR_MAX | D3D12_FORMAT_SUPPORT2_UAV_ATOMIC_UNSIGNED_MIN_OR_MAX; } } { // D3D12's per-format rules, as native D3D12 reports them (RX 9070 XT, AMD 26.11.2, and WARP): // the Vulkan feature bits above say what the image can do, not what D3D12 lets the format do. const Format& chosen = fmt.format != VK_FORMAT_UNDEFINED ? fmt : depth_fmt; const bool depth = (chosen.aspects & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) != 0; const bool block_compressed = vk_fmt >= VK_FORMAT_BC1_RGB_UNORM_BLOCK && vk_fmt <= VK_FORMAT_BC7_SRGB_BLOCK; // Gathers read the sampled view like a sample does (OpImageGather); the host reports one with the other. if (s1 & D3D12_FORMAT_SUPPORT1_SHADER_SAMPLE) s1 |= D3D12_FORMAT_SUPPORT1_SHADER_GATHER; // Comparison sampling and gathers (SampleCmp, GatherCmp with a comparison sampler) are D3D12's for the // depth-plane view formats only; R32_FLOAT and R16_UNORM are the views of D32 and D16 textures. if ((s1 & D3D12_FORMAT_SUPPORT1_SHADER_SAMPLE) && (fs->Format == DXGI_FORMAT_R32_FLOAT || fs->Format == DXGI_FORMAT_R16_UNORM)) s1 |= D3D12_FORMAT_SUPPORT1_SHADER_SAMPLE_COMPARISON | D3D12_FORMAT_SUPPORT1_SHADER_GATHER_COMPARISON; // A mip chain where the image can have one (asked with its sampled or depth-stencil usage). if (s1 & (D3D12_FORMAT_SUPPORT1_TEXTURE1D | D3D12_FORMAT_SUPPORT1_TEXTURE2D | D3D12_FORMAT_SUPPORT1_TEXTURE3D | D3D12_FORMAT_SUPPORT1_TEXTURECUBE | D3D12_FORMAT_SUPPORT1_DEPTH_STENCIL)) { const VkImageUsageFlags usage = depth ? VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT : VK_IMAGE_USAGE_SAMPLED_BIT; VkImageFormatProperties limits{}; if (state_.image_format_properties && state_.image_format_properties(state_.info.physical, vk_fmt, VK_IMAGE_TYPE_2D, VK_IMAGE_TILING_OPTIMAL, usage, chosen.typeless ? VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT : 0, &limits) == VK_SUCCESS && limits.maxMipLevels > 1) s1 |= D3D12_FORMAT_SUPPORT1_MIP; // Depth formats multisample as depth-stencil targets; the colour-attachment check above never // sees them. Same usages as MULTISAMPLE_QUALITY_LEVELS and resource creation ask for. if (depth && !chosen.typeless && (s1 & D3D12_FORMAT_SUPPORT1_DEPTH_STENCIL) && state_.image_format_properties && state_.image_format_properties(state_.info.physical, vk_fmt, VK_IMAGE_TYPE_2D, VK_IMAGE_TILING_OPTIMAL, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT, 0, &limits) == VK_SUCCESS && (limits.sampleCounts & d3d12_multisample_sample_counts)) s1 |= D3D12_FORMAT_SUPPORT1_MULTISAMPLE_RENDERTARGET; } // No resolve of integer formats (ResolveSubresource takes float, UNORM and SNORM only). if (DeviceState::numeric_class(vk_fmt) != 0) s1 &= ~D3D12_FORMAT_SUPPORT1_MULTISAMPLE_RESOLVE; // Block-compressed textures are 2D, 3D or cubes: 1D has no 4x4 blocks. if (block_compressed) s1 &= ~D3D12_FORMAT_SUPPORT1_TEXTURE1D; // Depth formats are 2D and cube resources whose shaders read and write them through a colour view // (R32_FLOAT, R24_UNORM_X8_TYPELESS, ...): not 3D, not shader resources or UAVs themselves (NVIDIA // gives D32_SFLOAT and D16_UNORM STORAGE_IMAGE). Native D3D12 also allows 1D, but the layer refuses // 1D depth-stencil resources (CreateCommittedResource). if (depth) { s1 &= ~(D3D12_FORMAT_SUPPORT1_TEXTURE1D | D3D12_FORMAT_SUPPORT1_TEXTURE3D | D3D12_FORMAT_SUPPORT1_SHADER_LOAD | D3D12_FORMAT_SUPPORT1_SHADER_SAMPLE | D3D12_FORMAT_SUPPORT1_SHADER_GATHER | D3D12_FORMAT_SUPPORT1_BUFFER | D3D12_FORMAT_SUPPORT1_IA_VERTEX_BUFFER | D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW); s2 = D3D12_FORMAT_SUPPORT2_NONE; } // A TYPELESS format is only storage: views give it a type, so it is a texture with mips and // nothing a view would do (no buffer, shader, render-target or UAV use of its own). if (chosen.typeless) { s1 &= D3D12_FORMAT_SUPPORT1_TEXTURE1D | D3D12_FORMAT_SUPPORT1_TEXTURE2D | D3D12_FORMAT_SUPPORT1_TEXTURE3D | D3D12_FORMAT_SUPPORT1_TEXTURECUBE | D3D12_FORMAT_SUPPORT1_MIP; s2 = D3D12_FORMAT_SUPPORT2_NONE; } } if (fs->Format == DXGI_FORMAT_R9G9B9E5_SHAREDEXP && state_.r9g9b9e5_uav_emulated) { s1 |= D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW; // Reads go through the sampled E5B9G9R9 view, like every typed UAV read (see above). s2 |= D3D12_FORMAT_SUPPORT2_UAV_TYPED_STORE | D3D12_FORMAT_SUPPORT2_UAV_TYPED_LOAD; } if (fs->Format == DXGI_FORMAT_R9G9B9E5_SHAREDEXP) { // Keep the native attachment and resolve bits. Blending and shader multisample loads remain masked. s1 &= ~(D3D12_FORMAT_SUPPORT1_BLENDABLE | D3D12_FORMAT_SUPPORT1_DEPTH_STENCIL | D3D12_FORMAT_SUPPORT1_MULTISAMPLE_LOAD); } fs->Support1 = s1; fs->Support2 = s2; return d3d12_trace::result(method, S_OK); } case D3D12_FEATURE_MULTISAMPLE_QUALITY_LEVELS: { if (size != sizeof(D3D12_FEATURE_DATA_MULTISAMPLE_QUALITY_LEVELS)) return d3d12_trace::result(method, E_INVALIDARG); auto* levels = static_cast(data); // RTX 5070 / 621.14/621.24: a format outside the runtime's table (and R1_UNORM) fails with the caller's // output untouched; a known format clears it before the sample count is checked. const UINT format_id = UINT(levels->Format); if (levels->Format == DXGI_FORMAT_R1_UNORM || !(format_id <= DXGI_FORMAT_B4G4R4A4_UNORM || (rt::d3d12_xs::console_feature_query() && format_id >= 118 && format_id <= 120) || (format_id >= DXGI_FORMAT_SAMPLER_FEEDBACK_MIN_MIP_OPAQUE && format_id <= DXGI_FORMAT_A4B4G4R4_UNORM))) return d3d12_trace::result(method, E_FAIL); levels->NumQualityLevels = 0; // TILED_RESOURCE asks about tiled (reserved, 64KB_UNDEFINED_SWIZZLE) textures. Measured natively on an // RX 7800 XT, a Radeon iGPU and WARP: 1x and 4x keep the plain answer, every other count has none, and a // format without a tile shape (96-bit) has none at any count. That is GetResourceAllocationInfo's rule // here (tiled MSAA is 4x only). 128-bit formats at 4x: the AMD drivers answer 0, WARP and the RTX 5070 Ti // allocate them; this follows the latter, as the allocation path does. // RTX 5070 / 621.14: undefined flag bits are ignored; bad counts fail, known formats have 1x. const bool tiled = (levels->Flags & D3D12_MULTISAMPLE_QUALITY_LEVELS_FLAG_TILED_RESOURCE) != 0; if (levels->SampleCount == 0 || levels->SampleCount > D3D12_MAX_MULTISAMPLE_SAMPLE_COUNT) return d3d12_trace::result(method, E_FAIL); Format format = texture_storage_format(levels->Format, false); if (levels->SampleCount == 1) { levels->NumQualityLevels = tiled && format.rgb96 ? 0 : 1; return d3d12_trace::result(method, S_OK); } if ((levels->SampleCount & (levels->SampleCount - 1)) != 0) return d3d12_trace::result(method, S_OK); const bool alpha_only = levels->Format == DXGI_FORMAT_A8_UNORM; if (alpha_only && levels->SampleCount != 1) return d3d12_trace::result(method, S_OK); if (levels->Format == DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM && levels->SampleCount != 1) return d3d12_trace::result(method, S_OK); // single-sample 2D only; no quality levels if (format.aspects & VK_IMAGE_ASPECT_DEPTH_BIT) { D3D12_RESOURCE_DESC depth_desc{}; depth_desc.Format = levels->Format; depth_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; format = state_.texture_format(depth_desc); // includes the D24-to-D32 fallback used by creation } if (format.format == VK_FORMAT_UNDEFINED || !state_.image_format_properties) return d3d12_trace::result(method, S_OK); if (format.rgb96) return d3d12_trace::result(method, S_OK); // no 96-bit render targets yet // Vulkan exposes one standard sample pattern per supported count, so each supported count maps to // one D3D12 quality level (quality index 0). Query the matching colour or depth/stencil attachment // usage, plus the transfer and sampled usages used by the resource implementation. VkImageUsageFlags usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT; if (format.aspects & VK_IMAGE_ASPECT_COLOR_BIT) { if (!alpha_only) usage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; } else if (format.aspects & VK_IMAGE_ASPECT_DEPTH_BIT) usage |= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT; else return d3d12_trace::result(method, DXGI_ERROR_UNSUPPORTED); const VkImageCreateFlags flags = format.typeless ? VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT : 0; VkImageFormatProperties image_properties{}; const VkResult result = state_.image_format_properties(state_.info.physical, format.format, VK_IMAGE_TYPE_2D, VK_IMAGE_TILING_OPTIMAL, usage, flags, &image_properties); const VkSampleCountFlagBits samples = VkSampleCountFlagBits(levels->SampleCount); if (result == VK_SUCCESS && (image_properties.sampleCounts & samples)) levels->NumQualityLevels = 1; if (tiled && levels->SampleCount != 1 && levels->SampleCount != 4) levels->NumQualityLevels = 0; return d3d12_trace::result(method, S_OK); } case D3D12_FEATURE_SHADER_MODEL: { if (size != sizeof(D3D12_FEATURE_DATA_SHADER_MODEL)) return E_INVALIDARG; auto* model = static_cast(data); // Measured against the host PC runtime: a request above the supported model is clamped down to it, 5.1 // is echoed because it is D3D12's own baseline (WARP and the RTX 5070 both answer it with S_OK), and a // value below it is refused with E_INVALIDARG (0x5f crashed the host, so the test does not probe it). // Refuse the same way instead of echoing an unrepresentable value back: below 5.1, and between 5.1 and // 6.0, where no runtime defines a model (0x52-0x5f; E_INVALIDARG on the host runtime of an RTX 5070). const UINT requested = static_cast(model->HighestShaderModel); if (requested < D3D_SHADER_MODEL_5_1 || (requested > D3D_SHADER_MODEL_5_1 && requested < D3D_SHADER_MODEL_6_0)) return E_INVALIDARG; if (model->HighestShaderModel > kHighestShaderModel) model->HighestShaderModel = kHighestShaderModel; return S_OK; } case D3D12_FEATURE_ROOT_SIGNATURE: { if (size != sizeof(D3D12_FEATURE_DATA_ROOT_SIGNATURE)) return E_INVALIDARG; auto* root = static_cast(data); // 1.0 to 1.2 are defined (1.2 by number: not every SDK names it). The host refuses anything else and leaves // the value alone (RTX 4070 Laptop 621.24 and WARP), so only 1.2 is clamped. const UINT requested = static_cast(root->HighestVersion); if (requested < static_cast(D3D_ROOT_SIGNATURE_VERSION_1_0) || requested > 0x3) return E_INVALIDARG; if (root->HighestVersion > kHighestRootSignatureVersion) root->HighestVersion = kHighestRootSignatureVersion; return S_OK; } case D3D12_FEATURE_PROTECTED_RESOURCE_SESSION_SUPPORT: { if (size != sizeof(D3D12_FEATURE_DATA_PROTECTED_RESOURCE_SESSION_SUPPORT)) return d3d12_trace::result(method, E_INVALIDARG); auto* prot = static_cast(data); prot->Support = D3D12_PROTECTED_RESOURCE_SESSION_SUPPORT_FLAG_NONE; if (prot->NodeIndex != 0) return d3d12_trace::result(method, E_INVALIDARG); return d3d12_trace::result(method, S_OK); } case D3D12_FEATURE_PROTECTED_RESOURCE_SESSION_TYPE_COUNT: { if (size != sizeof(D3D12_FEATURE_DATA_PROTECTED_RESOURCE_SESSION_TYPE_COUNT)) return d3d12_trace::result(method, E_INVALIDARG); auto* prot_count = static_cast(data); if (prot_count->NodeIndex != 0) return d3d12_trace::result(method, E_INVALIDARG); prot_count->Count = 0; return d3d12_trace::result(method, S_OK); } case D3D12_FEATURE_PROTECTED_RESOURCE_SESSION_TYPES: { if (size != sizeof(D3D12_FEATURE_DATA_PROTECTED_RESOURCE_SESSION_TYPES)) return d3d12_trace::result(method, E_INVALIDARG); const auto* prot_types = static_cast(data); // Zero protected resource session types exist, so only Count == 0 on node 0 matches TYPE_COUNT. if (prot_types->NodeIndex != 0 || prot_types->Count != 0) return d3d12_trace::result(method, E_INVALIDARG); return d3d12_trace::result(method, S_OK); } case D3D12_FEATURE_SHADER_CACHE: { if (size != sizeof(D3D12_FEATURE_DATA_SHADER_CACHE)) return d3d12_trace::result(method, E_INVALIDARG); static_cast(data)->SupportFlags = D3D12_SHADER_CACHE_SUPPORT_NONE; return d3d12_trace::result(method, S_OK); } case D3D12_FEATURE_COMMAND_QUEUE_PRIORITY: { if (size != sizeof(D3D12_FEATURE_DATA_COMMAND_QUEUE_PRIORITY)) return d3d12_trace::result(method, E_INVALIDARG); auto* prio = static_cast(data); prio->PriorityForTypeIsSupported = FALSE; if (UINT(prio->CommandListType) > D3D12_COMMAND_LIST_TYPE_VIDEO_ENCODE || (prio->Priority != D3D12_COMMAND_QUEUE_PRIORITY_NORMAL && prio->Priority != D3D12_COMMAND_QUEUE_PRIORITY_HIGH && prio->Priority != D3D12_COMMAND_QUEUE_PRIORITY_GLOBAL_REALTIME)) return d3d12_trace::result(method, E_INVALIDARG); // DIRECT/COMPUTE/COPY report NORMAL only: all VkQueues share priority 1.0f (HIGH has no distinct scheduling) // and GLOBAL_REALTIME is refused in CreateCommandQueue. const bool supported_type = prio->CommandListType == D3D12_COMMAND_LIST_TYPE_DIRECT || prio->CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE || prio->CommandListType == D3D12_COMMAND_LIST_TYPE_COPY; const bool supported_priority = prio->Priority == D3D12_COMMAND_QUEUE_PRIORITY_NORMAL; prio->PriorityForTypeIsSupported = (supported_type && supported_priority) ? TRUE : FALSE; return d3d12_trace::result(method, S_OK); } case D3D12_FEATURE_EXISTING_HEAPS: return write_supported_feature( method, data, size, state_.get_host_pointer_properties ? TRUE : FALSE); case D3D12_FEATURE_SERIALIZATION: { if (size != sizeof(D3D12_FEATURE_DATA_SERIALIZATION)) return d3d12_trace::result(method, E_INVALIDARG); auto* ser = static_cast(data); ser->HeapSerializationTier = D3D12_HEAP_SERIALIZATION_TIER_0; if (ser->NodeIndex != 0) return d3d12_trace::result(method, E_INVALIDARG); return d3d12_trace::result(method, S_OK); } case D3D12_FEATURE_CROSS_NODE: { if (size != sizeof(D3D12_FEATURE_DATA_CROSS_NODE)) return d3d12_trace::result(method, E_INVALIDARG); auto* cross = static_cast(data); cross->SharingTier = D3D12_CROSS_NODE_SHARING_TIER_NOT_SUPPORTED; cross->AtomicShaderInstructions = FALSE; return d3d12_trace::result(method, S_OK); } case D3D12_FEATURE_DISPLAYABLE: { if (size != sizeof(D3D12_FEATURE_DATA_DISPLAYABLE)) return d3d12_trace::result(method, E_INVALIDARG); auto* disp = static_cast(data); disp->DisplayableTexture = FALSE; disp->SharedResourceCompatibilityTier = D3D12_SHARED_RESOURCE_COMPATIBILITY_TIER_0; return d3d12_trace::result(method, S_OK); } case D3D12_FEATURE_QUERY_META_COMMAND: // EnumerateMetaCommands reports 0 meta-commands, so any query is rejected (as on host D3D12). return d3d12_trace::result(method, E_INVALIDARG); case compat::kFeaturePredication: return write_supported_feature( method, data, size, state_.info.conditional_rendering ? TRUE : FALSE); case compat::kFeatureApplicationSpecificDriverState: return write_supported_feature(method, data, size, FALSE); case compat::kFeatureBytecodeBypassHashSupported: return write_supported_feature(method, data, size, FALSE); default: // Not answered yet. The log above lists every query; answers are added as the trace asks for them. return d3d12_trace::result(method, E_INVALIDARG); } } private: IUnknown* identity() { return outer_ ? outer_ : static_cast(this); } static constexpr D3D12_RESOURCE_ALLOCATION_INFO kInvalidAllocation{UINT64_MAX, D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT}; bool xbox_depth_uav(const D3D12_RESOURCE_DESC& desc) const { return rt::d3d12_xs::depth_uav_description(desc) && rt::d3d12_xs::is_device_proxy(outer_); } // Lays `count` resources out one after another; `each` (optional) gets every resource's offset, size and // alignment. As on the PC runtime, the total is rounded up to the largest alignment (1 for no resources) and // saturates near 2^64 rather than wrapping. template D3D12_RESOURCE_ALLOCATION_INFO place(UINT count, const Desc* descs, Get get, D3D12_RESOURCE_ALLOCATION_INFO1* each) { D3D12_RESOURCE_ALLOCATION_INFO total{0, 1}; bool failed = count && !descs; for (UINT i = 0; i < count; ++i) { D3D12_RESOURCE_ALLOCATION_INFO one = kInvalidAllocation; if (!failed) { auto desc = get(i); // The boot stack charges XMem for the guest placement; storage planes are private to Vulkan. if (xbox_depth_uav(desc)) desc.Flags &= ~D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; one = allocation(desc); if (one.SizeInBytes == UINT64_MAX) log_refused_allocation(get(i)); } failed = failed || one.SizeInBytes == UINT64_MAX; if (failed) { if (each) each[i] = {UINT64_MAX, one.Alignment, UINT64_MAX}; continue; } const UINT64 offset = align_up(total.SizeInBytes, one.Alignment); if (each) each[i] = {offset, one.Alignment, one.SizeInBytes}; total = {one.SizeInBytes > UINT64_MAX - offset ? UINT64_MAX : offset + one.SizeInBytes, std::max(total.Alignment, one.Alignment)}; } return failed ? kInvalidAllocation : D3D12_RESOURCE_ALLOCATION_INFO{align_up(total.SizeInBytes, total.Alignment), total.Alignment}; } // A title that gets "invalid" for a description it believes in usually stops right there (GTA VI asserts on a // size above 4 GiB), so every distinct refused description is logged in full. A small-alignment probe // (Alignment 4096) the title retries without is expected, and marked as such. static void log_refused_allocation(const D3D12_RESOURCE_DESC& desc) { static std::mutex mutex; static std::set seen; char line[256]; std::snprintf(line, sizeof line, "dim %d format %d %llux%ux%u mips %u samples %u/%u layout %d flags 0x%x alignment %llu%s", int(desc.Dimension), int(desc.Format), static_cast(desc.Width), unsigned(desc.Height), unsigned(desc.DepthOrArraySize), unsigned(desc.MipLevels), unsigned(desc.SampleDesc.Count), unsigned(desc.SampleDesc.Quality), int(desc.Layout), unsigned(desc.Flags), static_cast(desc.Alignment), desc.Alignment == D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT ? " (small-alignment probe)" : ""); std::lock_guard lock(mutex); if (seen.size() < 64 && seen.insert(line).second) std::fprintf(stderr, "[rt] d3d12: GetResourceAllocationInfo refused: %s\n", line); } D3D12_RESOURCE_ALLOCATION_INFO allocation(const D3D12_RESOURCE_DESC& asked) const { if (xbox_depth_storage_desc(asked) && outer_ && rt::d3d12_xs::is_device_proxy(outer_)) { const auto depth = allocation(depth_storage_part(asked, false)); const auto colour = allocation(depth_storage_part(asked, true)); if (depth.SizeInBytes == UINT64_MAX || colour.SizeInBytes == UINT64_MAX) return kInvalidAllocation; return {std::max(depth.SizeInBytes, colour.SizeInBytes), std::max(depth.Alignment, colour.Alignment)}; } D3D12_RESOURCE_DESC desc = asked; desc.Format = pc_format(desc.Format); // the console's D16S8 family as D24S8 return allocation_of(desc); } // One resource's size and alignment, or kInvalidAllocation for a description D3D12 (or this device) rejects. D3D12_RESOURCE_ALLOCATION_INFO allocation_of(const D3D12_RESOURCE_DESC& desc) const { constexpr UINT64 align_4k = D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT, align_64k = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT, align_msaa_64k = D3D12_SMALL_MSAA_RESOURCE_PLACEMENT_ALIGNMENT, align_msaa_4m = D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT; constexpr D3D12_RESOURCE_FLAGS attachment = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; if (desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { // Host D3D12 accepts ALLOW_RENDER_TARGET, ALLOW_CROSS_ADAPTER, UAV, DENY_SHADER_RESOURCE, // RAYTRACING_ACCELERATION_STRUCTURE and 0x400 on buffers; refuses ALLOW_DEPTH_STENCIL, // ALLOW_SIMULTANEOUS_ACCESS, VIDEO_DECODE_REFERENCE_ONLY and other flags (D3D-467). constexpr UINT buffer_flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS | D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE | D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER | D3D12_RESOURCE_FLAG_RAYTRACING_ACCELERATION_STRUCTURE | 0x400; if (!desc.Width || desc.Width > UINT64_MAX - align_64k || desc.Height != 1 || desc.DepthOrArraySize != 1 || desc.MipLevels != 1 || desc.Format != DXGI_FORMAT_UNKNOWN || desc.SampleDesc.Count != 1 || desc.SampleDesc.Quality != 0 || desc.Layout != D3D12_TEXTURE_LAYOUT_ROW_MAJOR || (desc.Alignment && desc.Alignment != align_64k) || (UINT(desc.Flags) & ~buffer_flags)) return kInvalidAllocation; return {align_up(desc.Width, align_64k), align_64k}; } const bool volume = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D; const bool one_d = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D; if (!volume && !one_d && desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) { if (desc.Dimension != D3D12_RESOURCE_DIMENSION_UNKNOWN) log_once("GetResourceAllocationInfo dimension not supported:", desc.Dimension); return kInvalidAllocation; } if (one_d && desc.Height != 1) return kInvalidAllocation; const UINT samples = desc.SampleDesc.Count, depth = volume ? desc.DepthOrArraySize : 1; const UINT64 max_extent = volume ? D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION : D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION; const UINT max_layers = volume ? D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION : D3D12_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION; if (!desc.Width || !desc.Height || !desc.DepthOrArraySize || desc.Width > max_extent || desc.Height > max_extent || desc.DepthOrArraySize > max_layers || !samples || samples > D3D12_MAX_MULTISAMPLE_SAMPLE_COUNT || (samples & (samples - 1)) || (samples > 1 && desc.SampleDesc.Quality != 0) || desc.Layout == D3D12_TEXTURE_LAYOUT_ROW_MAJOR) return kInvalidAllocation; const UINT16 full = full_mips(desc.Width, desc.Height, depth); D3D12_RESOURCE_DESC resolved = desc; if (!resolved.MipLevels) resolved.MipLevels = full; if (resolved.MipLevels > full) return kInvalidAllocation; const bool depth_stencil = desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; if ((desc.Flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) && !depth_stencil) return kInvalidAllocation; if (samples > 1 && (volume || one_d || resolved.MipLevels != 1 || !(desc.Flags & attachment) || (desc.Flags & attachment) == attachment || (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS))) return kInvalidAllocation; // The PC runtime: simultaneous access only single-sampled and without depth-stencil, and no volume depth. if (((desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS) && (depth_stencil || samples > 1)) || (volume && depth_stencil)) return kInvalidAllocation; const bool tiled = is_tiled_layout(desc.Layout); if (tiled) { if (one_d || (samples > 1 && samples != 4)) return kInvalidAllocation; if (desc.Alignment && desc.Alignment != align_64k) return kInvalidAllocation; } else if (desc.Layout != D3D12_TEXTURE_LAYOUT_UNKNOWN) { log_once("GetResourceAllocationInfo layout as UNKNOWN:", desc.Layout); } const Format format = state_.texture_format(desc); if (!format.format) { log_once("GetResourceAllocationInfo format not supported yet:", desc.Format); return kInvalidAllocation; } VkMemoryRequirements need{}; const TextureCreateInfo create(resolved, format, state_.color_attachment_usable(format.format)); if (!state_.memory_requirements(create.info, need)) return kInvalidAllocation; if (tiled) { leonida::ResourceTiling tiling; if (!resource_tiling(resolved, tiling)) return kInvalidAllocation; return {UINT64(tiling.total_tiles) * leonida::tile_size_in_bytes, align_64k}; } // D3D12's alignment: 64 KiB, or 4 MiB with MSAA, unless the description asks for a small one (4 KiB, 64 KiB // with MSAA). 4 KiB needs the top mip of one array slice to fit in 16 tiles of 4 KiB and the resource not to // be a render target or depth buffer; mips and array slices don't count. If it doesn't qualify, the PC // runtime calls the description invalid rather than answering with 64 KiB. The MSAA 64 KiB alignment has no // size limit there. Both measured in d3d12_vulkan_device_test. UINT64 alignment = 0; if (samples > 1) { if (desc.Alignment && desc.Alignment != align_msaa_64k && desc.Alignment != align_msaa_4m) return kInvalidAllocation; alignment = desc.Alignment ? desc.Alignment : align_msaa_4m; } else { if (desc.Alignment && desc.Alignment != align_4k && desc.Alignment != align_64k) return kInvalidAllocation; if (desc.Alignment == align_4k && ((desc.Flags & attachment) || !small_tiles_fit(desc, format, need.size))) return kInvalidAllocation; alignment = desc.Alignment ? desc.Alignment : align_64k; } return {align_up(need.size, alignment), alignment}; } // Whether 16 tiles of 4 KiB (leonida::small_tile_shape; 4096 bytes of a row for 1D) cover the top mip of one // array slice, the PC runtime's test for D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT. static bool small_tiles_fit(const D3D12_RESOURCE_DESC& desc, const Format& format, VkDeviceSize vulkan_size) { const leonida::BlockFormat block = leonida::block_format(format.format, VK_IMAGE_ASPECT_COLOR_BIT); const bool volume = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D; leonida::TileShape shape = leonida::small_tile_shape(volume, block.bytes); if (desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D && shape.width) shape = {4096 / block.bytes, 1, 1}; // shortcut: untileable element sizes (3- and 12-byte formats) keep the whole-resource 64 KiB test; measure // them on the PC runtime if a game asks for one. if (!shape.width) return vulkan_size <= D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT; const auto tiles = [](UINT64 texels, UINT64 per_block, UINT64 per_tile) { return ((texels + per_block - 1) / per_block + per_tile - 1) / per_tile; }; return tiles(desc.Width, block.block, shape.width) * tiles(desc.Height, block.block, shape.height) * tiles(volume ? desc.DepthOrArraySize : 1, 1, shape.depth) <= 16; } // Strict lower bound on the heap bytes a non-tiled single-sample texture needs: sums uncompressed texel/block // payload across subresources and rounds to `alignment`, capped at `fallback` (Vulkan allocation size). Avoids // rejecting host-valid placed textures when Vulkan driver padding exceeds D3D12's GetResourceAllocationInfo. static UINT64 min_placed_texture_bytes(const D3D12_RESOURCE_DESC& desc, const Format& format, UINT64 alignment, UINT64 fallback) { const VkImageAspectFlags aspect = (format.aspects & VK_IMAGE_ASPECT_DEPTH_BIT) ? VK_IMAGE_ASPECT_DEPTH_BIT : format.aspects; const leonida::BlockFormat block = footprint_block(format, aspect); if (!block.bytes || !alignment) return fallback; const bool volume = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D; const bool one_d = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D; const UINT depth = volume ? desc.DepthOrArraySize : 1; const UINT slices = volume ? 1 : desc.DepthOrArraySize; const UINT mips = desc.MipLevels ? desc.MipLevels : full_mips(desc.Width, desc.Height, depth); UINT64 per_slice = 0; for (UINT m = 0; m < mips; ++m) { const UINT64 w = std::max(1, desc.Width >> m); const UINT64 h = one_d ? 1 : std::max(1, desc.Height >> m); const UINT64 d = volume ? std::max(1, depth >> m) : 1; const UINT64 bw = (w + block.block - 1) / block.block; const UINT64 bh = (h + block.block - 1) / block.block; if (bw > UINT64_MAX / bh) return fallback; const UINT64 blocks = bw * bh; if (blocks > UINT64_MAX / d) return fallback; const UINT64 count = blocks * d; if (count > UINT64_MAX / block.bytes) return fallback; const UINT64 mip_bytes = count * block.bytes; if (per_slice > UINT64_MAX - mip_bytes) return fallback; per_slice += mip_bytes; } if (slices && per_slice > UINT64_MAX / slices) return fallback; const UINT64 total = per_slice * slices; if (total > UINT64_MAX - (alignment - 1)) return fallback; return std::min(fallback, align_up(total, alignment)); } enum class ImageViewUse { sampled, storage, depth_stencil_uav }; // Writes the view's T# into the slot and makes sure set 0 and the hash table know it. A view that cannot be // shown leaves the slot a null descriptor. void write_image_descriptor(const Resource& resource, const TextureView& view, D3D12_CPU_DESCRIPTOR_HANDLE destination, ImageViewUse use) { const bool storage = use != ImageViewUse::sampled; const bool storage_plane = use == ImageViewUse::depth_stencil_uav; namespace g = leonida::gfx10; g::Image image{}; VkFormat view_format{}; DeviceState::VolumeSlices slices{}; if (!image_descriptor(resource, view, storage, image, view_format, slices)) { return; } const bool sampled = view.type != g::ImageType::image_1d_array && !(resource.desc().Flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE); const bool new_uav = storage && (view.type == g::ImageType::image_3d || view.type == g::ImageType::image_1d || view.type == g::ImageType::image_1d_array); const bool packed_storage = storage && resource.desc().Format == DXGI_FORMAT_R9G9B9E5_SHAREDEXP && resource.uint_backed(); const VkFormat storage_format = storage && resource.uint_backed() ? resource.format() : view_format; if (storage) { if (!state_.storage_usable(storage_format)) { log_once("texture view format does not support storage images:", storage_format); return; } if (new_uav && state_.info.robust_image_access) { if (sampled && !state_.sampled_usable(view_format)) { log_once("texture view format does not support sampled access:", view_format); return; } // All three dimensions use Unknown-format storage writes and can use Unknown-format reads // (image_load glc, or any image_load on a 1D array). Check the actual storage view's format. // Packed RGB9E5 only exposes formatted raw R32_UINT storage, so it does not need these bits. if (!packed_storage) { constexpr auto required = VK_FORMAT_FEATURE_2_STORAGE_READ_WITHOUT_FORMAT_BIT | VK_FORMAT_FEATURE_2_STORAGE_WRITE_WITHOUT_FORMAT_BIT; if ((state_.optimal_features(storage_format) & required) != required) { log_once("texture view format lacks the required formatless storage image access:", storage_format); return; } } } } if (slices.count && !(state_.info.sliced_3d_uav && state_.info.robust_image_access)) { log_once("partial Texture3D UAV requires imageSlicedViewOf3D and robustImageAccess; mip", view.first_mip); return; } g::ImageWords words = g::encode(image); if (storage && view.type == g::ImageType::image_3d) { words[4] |= g::volume_uav_flag; const UINT mip_depth = std::max(1u, image.depth >> image.first_mip); words[7] = g::volume_uav_word(slices.first, slices.count ? slices.count : mip_depth); } if (new_uav && packed_storage) { words[4] |= g::volume_uav_flag; if (view.type != g::ImageType::image_3d) words[7] = g::volume_uav_word(0, 1); words[7] |= g::packed_uav_flag; log_once("packed RGB9E5 UAV: translated storage operations are not implemented; type", int(view.type)); } const VkFormat channels_format = resource.rgba4_render_backing() ? VK_FORMAT_A4R4G4B4_UNORM_PACK16 : (resource.rgb96() ? rgb96_named_format(view_format) : view_format); if (new_uav && !state_.info.robust_image_access) { log_once("shader access to 1D and 3D UAVs requires robustImageAccess; type", int(view.type)); } else { const bool known_heap = state_.known_view_heap(destination.ptr); if (!storage && resource.deferrable_sample() && state_.info.prepare_on_bind && known_heap && !g::multisampled(image.type)) { state_.remember_sample(words,{const_cast(&resource),image,view_format,channels_format}); std::memcpy(reinterpret_cast(destination.ptr),words.data(),sizeof(words)); return; } const auto bound = const_cast(resource).bound_image(); if (!bound) { log_once("unable to make a placed shader image resident; format", int(resource.desc().Format)); return; } const bool registered = state_.bind_image(words, image, bound, view_format, channels_format, storage_format, resource.aspects(), sampled, storage, slices); if (registered && (resource.sparse_image() || storage_plane)) state_.context->note_shader_image(resource.id()); if (!registered && (g::multisampled(image.type) || storage_plane)) return; } // The CPU UAV used by ClearUnorderedAccessView is independent of set 0. std::memcpy(reinterpret_cast(destination.ptr), words.data(), sizeof(words)); resource.note_shader_view(); } // Validation shared by CreateCommittedResource and CreateCommittedResource3; internal callers pass null `method` // to skip trace recording. HRESULT create_committed_validated(const char* method, const D3D12_HEAP_PROPERTIES* heap, D3D12_HEAP_FLAGS heap_flags, const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear, UINT32 castable_count, const DXGI_FORMAT* castable, REFIID riid, void** out, std::optional storage_heap_flags = std::nullopt, TitleImageOrigin origin = TitleImageOrigin::ordinary) { const auto finish = [&](HRESULT hr) { return method ? d3d12_trace::result(method, hr) : hr; }; if (out) *out = nullptr; if (!heap || !desc) return finish(E_INVALIDARG); if (xbox_depth_storage_desc(*desc) && outer_ && rt::d3d12_xs::is_device_proxy(outer_) && heap->Type == D3D12_HEAP_TYPE_DEFAULT && (!castable_count || !castable)) { const auto depth_desc = depth_storage_part(*desc, false), colour_desc = depth_storage_part(*desc, true); const bool initial_uav = state == D3D12_RESOURCE_STATE_UNORDERED_ACCESS; ID3D12Resource *depth = nullptr, *colour = nullptr; HRESULT hr = create_committed_validated(nullptr, heap, heap_flags, &depth_desc, initial_uav ? D3D12_RESOURCE_STATE_COMMON : state, clear, 0, nullptr, IID_PPV_ARGS(&depth)); if (FAILED(hr)) return finish(hr); hr = create_committed_validated(nullptr, heap, heap_flags, &colour_desc, initial_uav ? state : D3D12_RESOURCE_STATE_COMMON, nullptr, 0, nullptr, IID_PPV_ARGS(&colour)); if (SUCCEEDED(hr)) { Resource::from(depth)->adopt_depth_storage(Resource::from(colour)); hr = out ? depth->QueryInterface(riid, out) : S_FALSE; } depth->Release(); return finish(hr); } if (const char* why = committed_resource_refusal(*heap, heap_flags, *desc, state, clear, acceleration_structures(), state_.uma)) { log_once((std::string(method ? method : "CreateCommittedResource") + " refused (" + why + "), dimension") .c_str(), int(desc->Dimension)); return finish(E_INVALIDARG); } // The sample quality is checked above as the host does it here: CreateCommittedResource accepts a quality on a // 1x texture while GetResourceAllocationInfo requires 0; the other texture checks stay shared with allocation. D3D12_RESOURCE_DESC checked = *desc; if (checked.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER) checked.SampleDesc.Quality = 0; if (desc->Dimension != D3D12_RESOURCE_DIMENSION_BUFFER && allocation(checked).SizeInBytes == UINT64_MAX) { log_once((std::string(method ? method : "CreateCommittedResource") + " refused (texture size, mips, samples or alignment), dimension") .c_str(), int(desc->Dimension)); return finish(E_INVALIDARG); } return finish(create_committed(heap, heap_flags, desc, state, castable_count, castable, riid, out, storage_heap_flags, origin)); } // Shared by CreateCommittedResource, CreateCommittedResource3 and CreateReservedResource*. A castable-format list // is only meaningful on textures; the layer reports RelaxedFormatCastingSupported, so each format is mapped and // handed to Vulkan as a VkImageFormatListCreateInfo. A nonzero count with a null list is no list, as on the PC // runtime. HRESULT create_committed(const D3D12_HEAP_PROPERTIES* heap, D3D12_HEAP_FLAGS heap_flags, const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES initial_state, UINT32 castable_count, const DXGI_FORMAT* castable, REFIID riid, void** out, std::optional storage_heap_flags = std::nullopt, TitleImageOrigin origin = TitleImageOrigin::ordinary) { if (out) *out = nullptr; if (!heap || !desc) return E_INVALIDARG; D3D12_RESOURCE_DESC canonical = *desc; canonical.Format = pc_format(canonical.Format); // the console's D16S8 family as D24S8 desc = &canonical; if (castable_count && castable && desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { log_once("castable formats on a buffer are invalid; count", int(castable_count)); return E_INVALIDARG; } auto* resource = new Resource(state_, *desc, *heap, heap_flags); resource->attach_device(identity()); HRESULT hr = E_NOTIMPL; if (desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { hr = desc->SampleDesc.Count == 1 && desc->SampleDesc.Quality == 0 ? resource->create_buffer(initial_state) : E_INVALIDARG; } else if (desc->Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE1D && desc->Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D && desc->Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE3D) { log_once("committed resource dimension not supported:", desc->Dimension); } else if (desc->Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D && desc->Height != 1) { log_once("1D texture height must be 1:", int(desc->Height)); hr = E_INVALIDARG; } else if (desc->Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D && (desc->Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) { log_once("volume depth-stencil resources not supported, flags:", int(desc->Flags)); } else if (heap->Type == D3D12_HEAP_TYPE_UPLOAD || heap->Type == D3D12_HEAP_TYPE_READBACK) { hr = E_INVALIDARG; // D3D12 places textures on default heaps unless they are row-major } else if (const UINT samples = desc->SampleDesc.Count; !samples || samples > D3D12_MAX_MULTISAMPLE_SAMPLE_COUNT || (samples > 1 && desc->SampleDesc.Quality && desc->SampleDesc.Quality != DXGI_STANDARD_MULTISAMPLE_QUALITY_PATTERN && desc->SampleDesc.Quality != DXGI_CENTER_MULTISAMPLE_QUALITY_PATTERN) || (samples > 1 && ((samples & (samples - 1)) || desc->MipLevels != 1 || desc->Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || !(desc->Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL))))) { hr = E_INVALIDARG; // D3D12: nonzero power-of-two sample count up to 32; MSAA needs a single-mip 2D attachment } else { hr = S_OK; const Format format = state_.texture_format(*desc); if (format.format == VK_FORMAT_UNDEFINED) { log_once("texture format not supported yet:", desc->Format); hr = E_INVALIDARG; } else { std::vector cast_formats; hr = castable_view_formats(format, desc->Format, castable_count, castable, cast_formats, storage_heap_flags.has_value()); if (SUCCEEDED(hr)) hr = resource->create_texture(format, cast_formats, origin); if (SUCCEEDED(hr)) resource->keep_castable_formats(castable_count, castable); if (SUCCEEDED(hr) && storage_heap_flags) hr = resource->enable_depth_stencil_uav(*storage_heap_flags); } } if (FAILED(hr)) { resource->Release(); return hr; } if (!out) { // a capability check: D3D12 allows a null output resource->Release(); return S_FALSE; } return hand_out(resource, riid, out); } // GetAdapterLuid's answer, and how queues read the clocks: calibrated timestamps when the caller enabled the // extension and the GPU calibrates its DEVICE domain against QueryPerformanceCounter, else the queue family's // timestamp queries. void query_luid_and_clock(PFN_vkGetDeviceProcAddr get_device) { const VulkanDeviceInfo& info = state_.info; const auto properties2 = reinterpret_cast( info.get_instance_proc(info.instance, "vkGetPhysicalDeviceProperties2")); if (properties2) { VkPhysicalDeviceIDProperties id{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES}; VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &id}; properties2(info.physical, &properties); static_assert(sizeof(LUID) == VK_LUID_SIZE); if (id.deviceLUIDValid) std::memcpy(&state_.luid, id.deviceLUID, sizeof(LUID)); state_.uma = properties.properties.deviceType == VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU; } if (!state_.luid.LowPart && !state_.luid.HighPart) log_once("the Vulkan driver reports no device LUID;", 0); state_.clock.get_device_proc = get_device; if (!info.calibrated_timestamps) return; // The KHR names first; the EXT ones are aliases with the same signatures. auto domains_of = reinterpret_cast( info.get_instance_proc(info.instance, "vkGetPhysicalDeviceCalibrateableTimeDomainsKHR")); auto calibrated = reinterpret_cast( get_device(info.device, "vkGetCalibratedTimestampsKHR")); if (!domains_of || !calibrated) { domains_of = reinterpret_cast( info.get_instance_proc(info.instance, "vkGetPhysicalDeviceCalibrateableTimeDomainsEXT")); calibrated = reinterpret_cast( get_device(info.device, "vkGetCalibratedTimestampsEXT")); } if (!domains_of || !calibrated) return; std::uint32_t count = 0; domains_of(info.physical, &count, nullptr); std::vector domains(count); domains_of(info.physical, &count, domains.data()); const auto has = [&](VkTimeDomainKHR domain) { return std::find(domains.begin(), domains.end(), domain) != domains.end(); }; if (has(VK_TIME_DOMAIN_DEVICE_KHR) && has(VK_TIME_DOMAIN_QUERY_PERFORMANCE_COUNTER_KHR)) state_.clock.calibrated = calibrated; else log_once("calibrated timestamps lack the DEVICE or QueryPerformanceCounter domain; domains:", int(count)); } // D3D12's layout rules for reserved resources. Use sparse backing for buffers and compatible color textures. // The arguments are answered as the host runtime answers them (d3d12_vulkan_device_test's // compare_placed_reserved, RTX 3060 / 610.88): the description, initial state and clear value rules of a // committed resource on a default heap, the reserved layouts below, and only then E_UNEXPECTED for a null // output, with nothing made. HRESULT create_reserved(const char* method, const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear, UINT32 castable_count, const DXGI_FORMAT* castable, REFIID riid, void** out) { if (out) *out = nullptr; if (!desc) return d3d12_trace::result(method, E_INVALIDARG); D3D12_RESOURCE_DESC canonical = *desc; canonical.Format = pc_format(canonical.Format); // the console's D16S8 family as D24S8 desc = &canonical; if (castable_count && castable && desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { log_once("castable formats on a reserved buffer are invalid; count", int(castable_count)); return d3d12_trace::result(method, E_INVALIDARG); } D3D12_RESOURCE_DESC backing = *desc; const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; if (desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { if (desc->Layout != D3D12_TEXTURE_LAYOUT_ROW_MAJOR) return d3d12_trace::result(method, E_INVALIDARG); } else { if (static_cast(desc->Layout) == kXboxTiledLayout) { log_once("reserved resource with the Xbox tiled layout, as 64KB_UNDEFINED_SWIZZLE; dimension", desc->Dimension); } else if (desc->Layout != D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE) { return d3d12_trace::result(method, E_INVALIDARG); // 64KB_STANDARD_SWIZZLE too: CheckFeatureSupport reports it unsupported } backing.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; leonida::ResourceTiling tiling; backing.MipLevels = std::max(desc->MipLevels, 1); // any count: only the format is checked here if (!resource_tiling(backing, tiling)) { log_once("reserved texture format has no tile shape:", desc->Format); return d3d12_trace::result(method, E_INVALIDARG); } backing.MipLevels = desc->MipLevels; } if (const char* why = committed_resource_refusal(heap, D3D12_HEAP_FLAG_NONE, backing, state, clear, acceleration_structures(), state_.uma)) { log_once((std::string(method) + " refused (" + why + "), dimension").c_str(), int(desc->Dimension)); return d3d12_trace::result(method, E_INVALIDARG); } if (desc->Dimension != D3D12_RESOURCE_DIMENSION_BUFFER) { // Extents, mips and samples, as the committed backing below checks them (GetResourceAllocationInfo). D3D12_RESOURCE_DESC checked = backing; checked.SampleDesc.Quality = 0; if (allocation(checked).SizeInBytes == UINT64_MAX) return d3d12_trace::result(method, E_INVALIDARG); } if (!out) return d3d12_trace::result(method, E_UNEXPECTED); ID3D12Resource* resource = nullptr; HRESULT hr = S_OK; if (desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER && state_.sparse_buffer_memory_types) { auto* sparse = new Resource(state_, backing, heap, D3D12_HEAP_FLAG_NONE); sparse->attach_device(identity()); hr = sparse->create_sparse_buffer(); if (FAILED(hr)) { sparse->Release(); return d3d12_trace::result(method, hr); } resource = sparse; } else if (state_.sparse_image_tiles && backing.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && backing.Format == DXGI_FORMAT_R8G8B8A8_UNORM && backing.Width && backing.Width <= UINT32_MAX && backing.Height && backing.DepthOrArraySize == 1 && backing.MipLevels == 1 && backing.SampleDesc.Count == 1 && !backing.SampleDesc.Quality && backing.Flags == D3D12_RESOURCE_FLAG_NONE && !clear && !castable_count) { auto* sparse = new Resource(state_, backing, heap, D3D12_HEAP_FLAG_NONE); sparse->attach_device(identity()); hr = sparse->create_sparse_image(); if (SUCCEEDED(hr)) resource = sparse; else { sparse->Release(); if (hr != E_NOTIMPL) return d3d12_trace::result(method, hr); } } if (!resource) { hr = create_committed_validated(nullptr, &heap, D3D12_HEAP_FLAG_NONE, &backing, D3D12_RESOURCE_STATE_COMMON, clear, castable_count, castable, IID_PPV_ARGS(&resource)); } if (FAILED(hr)) return d3d12_trace::result(method, hr); Resource::from(resource)->make_reserved(desc->Layout); hr = resource->QueryInterface(riid, out); resource->Release(); return d3d12_trace::result(method, hr); } // The tiling of a reserved resource's description; false for formats without a tile shape (three- and // twelve-byte texels, two-plane depth-stencil). static bool resource_tiling(const D3D12_RESOURCE_DESC& desc, leonida::ResourceTiling& out) { leonida::TilingDesc tiling{}; tiling.width = desc.Width; tiling.height = desc.Height; tiling.depth_or_layers = desc.DepthOrArraySize; tiling.mips = desc.MipLevels; if (desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { tiling.kind = leonida::TiledKind::buffer; return leonida::resource_tiling(tiling, out); } if (desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D && desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE3D) return false; tiling.kind = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D ? leonida::TiledKind::texture3d : leonida::TiledKind::texture2d; const Format format = vulkan_format(desc.Format, false); if (!format.format || (format.aspects & VK_IMAGE_ASPECT_STENCIL_BIT)) return false; if (format.rgb96) return false; // the tile shape of a 12-byte texel is not measured const leonida::BlockFormat block = leonida::block_format(format.format, format.aspects); tiling.element_bytes = block.bytes; tiling.block = block.block; tiling.samples = desc.SampleDesc.Count; return leonida::resource_tiling(tiling, out); } // Host image copies are used only on images in GENERAL (D3D12's COMMON), so GENERAL must be a layout the // device copies from and to on the host. Vulkan requires it to be; check rather than assume. void load_host_image_copy(PFN_vkGetDeviceProcAddr get_device) { const VkDevice dev = state_.info.device; const auto properties2 = reinterpret_cast( state_.info.get_instance_proc(state_.info.instance, "vkGetPhysicalDeviceProperties2")); const auto to_image = reinterpret_cast(get_device(dev, "vkCopyMemoryToImageEXT")); const auto to_memory = reinterpret_cast(get_device(dev, "vkCopyImageToMemoryEXT")); const auto transition = reinterpret_cast(get_device(dev, "vkTransitionImageLayoutEXT")); if (!properties2 || !state_.format_properties2 || !to_image || !to_memory || !transition) { std::fprintf(stderr, "[rt] d3d12: VK_EXT_host_image_copy entry points missing; using staging copies\n"); return; } VkPhysicalDeviceHostImageCopyPropertiesEXT host{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_HOST_IMAGE_COPY_PROPERTIES_EXT}; VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &host}; properties2(state_.info.physical, &properties); std::vector src(host.copySrcLayoutCount), dst(host.copyDstLayoutCount); host.pCopySrcLayouts = src.data(); host.pCopyDstLayouts = dst.data(); properties2(state_.info.physical, &properties); const auto general = [](const std::vector& layouts) { return std::find(layouts.begin(), layouts.end(), VK_IMAGE_LAYOUT_GENERAL) != layouts.end(); }; if (!general(src) || !general(dst)) { std::fprintf(stderr, "[rt] d3d12: host image copies do not accept GENERAL; using staging copies\n"); return; } state_.copy_memory_to_image = to_image; state_.copy_image_to_memory = to_memory; state_.transition_image_layout = transition; } // The layer reports no protected-session support, so a session is refused, as D3D12 refuses one on a device // without D3D12_FEATURE_PROTECTED_RESOURCE_SESSION_SUPPORT. static HRESULT refuse_protected_session(const char* method) { log_once((std::string("protected resource session refused (not supported) by ") + method + ':').c_str(), 1); return E_INVALIDARG; } // D3D12_RESOURCE_DESC1 is D3D12_RESOURCE_DESC plus SamplerFeedbackMipRegion. static D3D12_RESOURCE_DESC resource_desc(const D3D12_RESOURCE_DESC1& desc) { return {desc.Dimension, desc.Alignment, desc.Width, desc.Height, desc.DepthOrArraySize, desc.MipLevels, desc.Format, desc.SampleDesc, desc.Layout, desc.Flags}; } // A sampler-feedback mip region on a texture, which needs a DXGI_FORMAT_SAMPLER_FEEDBACK_* resource the layer // does not have. The PC runtime ignores the region on a buffer. static bool texture_mip_region(const D3D12_RESOURCE_DESC1& desc) { const D3D12_MIP_REGION& region = desc.SamplerFeedbackMipRegion; return desc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER && (region.Width || region.Height || region.Depth); } // Holds the pipeline compiler's worker for the device's life (PipelineCompiler::retain). Released early by // ~Device, after its cancel; a constructor that throws releases it through this member's destructor. class CompilerUse { public: CompilerUse() { PipelineCompiler::instance().retain(); } ~CompilerUse() { release(); } CompilerUse(const CompilerUse&) = delete; CompilerUse& operator=(const CompilerUse&) = delete; void release() { if (!held_) return; held_ = false; PipelineCompiler::instance().release(); } private: bool held_ = true; }; CompilerUse compiler_use_; std::mutex queue_mutex_; // Live D3D12 queues per VkQueue of info.command_queues, compute_queues and copy_queues (pick_queue_slot). std::vector queue_users_; std::vector compute_users_; std::vector copy_users_; std::mutex verified_program_mutex_; std::unordered_set verified_programs_; std::mutex native_pipeline_mutex_; std::unordered_map> native_pipelines_; DeviceState state_; struct RawImage { std::unique_ptr resource; std::vector fingerprints; }; std::mutex raw_image_mutex_; using RawKey = std::tuple; std::map raw_images_; std::atomic removed_{false}; OwnedRuntime owned_; IUnknown* outer_ = nullptr; // the Xbox-ABI proxy, which owns a reference to this device }; } // namespace bool stop_pipeline_compiles(unsigned wait_ms) { const bool idle = PipelineCompiler::instance().stop_for_exit(std::chrono::milliseconds(wait_ms)); if (!idle) std::fprintf(stderr, "[rt] d3d12: a background pipeline build was still running after %u ms at exit\n", wait_ms); return idle; } // How long an exit save waits for the write itself (save_session_pipeline_cache): a 77 MiB cache was measured at about // 36 ms (fill and publish), so this only bounds a driver that blocks the read. constexpr unsigned kExitCacheWriteMs = 3000; bool save_pipeline_caches_at_exit(unsigned wait_ms) { if (exit_cache_saved.exchange(true)) return false; // once: a crash during the normal exit's save does not redo it std::unique_lock lock(exit_cache_mutex, std::defer_lock); if (!lock.try_lock_for(std::chrono::milliseconds(wait_ms))) { std::fprintf(stderr, "[rt] d3d12: device list busy for %u ms at exit; pipeline_cache.session.bin not written\n", wait_ms); return false; } bool wrote = false; const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(wait_ms); for (DeviceState* d : exit_cache_devices) { if (!d->context || !d->pipeline_cache_handle) continue; // A build still running (a large one takes minutes; at a crash the faulting thread may be inside one) is // given until the deadline, then the cache is written without it. Unlike at teardown, the previous file is // not kept instead: the process is ending, so waiting longer is not possible and keeping the old file throws // away everything this run compiled (measured: a 1,308 s boot that ended in a title fault with 2 builds // running). The cache is not created EXTERNALLY_SYNCHRONIZED, so reading it during a build is valid; the // snapshot holds the pipelines finished so far. while (d->active_compiles.load() && std::chrono::steady_clock::now() < deadline) std::this_thread::sleep_for(std::chrono::milliseconds(5)); if (const unsigned building = d->active_compiles.load()) std::fprintf(stderr, "[rt] d3d12: %u pipeline build(s) still running at exit; writing the pipelines " "finished so far\n", building); // On a thread of its own: a driver that holds the cache until a build ends would otherwise hold the ending // process too. Past the deadline the process goes on ending; the file is published by a rename // (CacheStagingFile), so a write cut off there leaves the previous file whole. struct Write { std::mutex mutex; std::condition_variable done_cv; bool done = false; }; auto write = std::make_shared(); std::thread([write, d] { save_session_pipeline_cache(d->context->vk, d->info.device, d->pipeline_cache_handle, false, "exit"); std::lock_guard done_lock(write->mutex); write->done = true; write->done_cv.notify_all(); }).detach(); std::unique_lock write_lock(write->mutex); if (!write->done_cv.wait_for(write_lock, std::chrono::milliseconds(kExitCacheWriteMs), [&] { return write->done; })) { std::fprintf(stderr, "[rt] d3d12: pipeline cache still being written after %u ms at exit; the process " "ends without waiting for it\n", kExitCacheWriteMs); return wrote; // the device list stays as it is: the write still uses this device } wrote = true; } return wrote; } HRESULT create_vulkan_device(const VulkanDeviceInfo& info, REFIID riid, void** out) { if (!out) return E_POINTER; *out = nullptr; auto* device = new Device(info); if (!device->ok()) { device->Release(); return E_FAIL; } return hand_out(device, riid, out); } std::shared_ptr tile_heap(ID3D12Heap* heap, const leonida::VulkanContext& context, bool image, std::uint32_t memory_types) { auto* object = Heap::from(heap); return object ? object->tiles(context, image, memory_types) : nullptr; } XboxDepthStorage xbox_depth_storage(ID3D12Resource* resource) { if (!resource || !depth_storage_count.load(std::memory_order_acquire)) return {}; std::lock_guard lock(depth_storage_mutex); const auto it = depth_storage_images.find(resource); return it == depth_storage_images.end() ? XboxDepthStorage{} : it->second; } bool is_sparse_image(ID3D12Resource* resource) { const auto* object = Resource::from(resource); return object && object->sparse_image(); } static HRESULT enable_depth_stencil_uav(ID3D12Resource* resource, D3D12_HEAP_FLAGS storage_heap_flags) { Resource* r = Resource::from(resource); return r ? r->enable_depth_stencil_uav(storage_heap_flags) : E_INVALIDARG; } leonida::ResourceId uav_image_resource(ID3D12Resource* resource, std::uint64_t address) { const Resource* r = Resource::from(resource); if (!r || !r->depth_stencil_uav(0)) return resource_id(resource); for (UINT plane = 0; plane < 2; ++plane) { const Resource* storage = r->depth_stencil_uav(plane); if (storage && storage->image_address() == address) return storage->id(); } return 0; } void set_device_outer(ID3D12Device* device, IUnknown* outer) { Device* d = Device::from(device); if (!d) return; // A caller passes what create_device_proxy returned, which is the proxy's DXGI pointer when the title asked // for IDXGIDevice1: the device's outer identity is the proxy itself either way. if (void* proxy = rt::d3d12_xs::device_proxy_primary(outer)) outer = static_cast(proxy); d->set_outer(outer); // Another job for an outer that is the Xbox-ABI proxy: its device slot 70 names a buffer by console VA only, and // this finds the layer's resource for it. if (rt::d3d12_xs::is_device_proxy(outer)) rt::d3d12_xs::set_device_resource_provider( outer, [](ID3D12Device* real, std::uint64_t va, std::uint64_t bytes, std::uint64_t* start, std::uint64_t* size) -> ID3D12Resource* { Device* device = Device::from(real); return device ? device->add_ref_buffer_at(va, bytes, *start, *size) : nullptr; }); // And for the same outer: its IDXGIDevice1::GetAdapter (d3d12_xs_device.h) hands // out this layer's adapter, the one create_dxgi_factory enumerates, so a title on the Vulkan device never gets // a host DXGI object from it. if (!rt::d3d12_xs::is_device_proxy(outer)) return; rt::d3d12_xs::set_constant_view_provider(outer, [](ID3D12Device* real, const D3D12_CONSTANT_BUFFER_VIEW_DESC* desc, D3D12_CPU_DESCRIPTOR_HANDLE target) { auto* device=Device::from(real); if (!device) return false; device->write_constant_buffer_view(desc,target,true); return true; }); rt::d3d12_xs::set_raw_texture_view_provider(outer, [](ID3D12Device* real, const D3D12_RESOURCE_DESC& desc, const D3D12_SHADER_RESOURCE_VIEW_DESC& view, std::uint64_t va, D3D12_CPU_DESCRIPTOR_HANDLE out) { auto* device = Device::from(real); try { return device && device->raw_texture_view(desc, view, va, out); } catch (const std::bad_alloc&) { return false; } }); rt::d3d12_xs::set_texture_lease_provider(outer, [](IUnknown* object, void* data, std::size_t bytes, UINT layout) { if (auto* resource = Resource::from(object)) resource->use_texture_lease(data, bytes, layout); }); rt::d3d12_xs::set_descriptor_mapping_provider(outer, [](ID3D12DescriptorHeap* heap, SIZE_T start, SIZE_T bytes) { const auto* object = DescriptorHeap::from(heap); return object && object->owns_mapped_span(start, bytes); }); if(d->state().info.prepare_on_bind) { rt::d3d12_xs::set_native_stream_factory(outer,[](ID3D12Device* real,const D3D12_PIPELINE_STATE_STREAM_DESC& desc,REFIID iid,void** out,std::unique_ptr record){ return Device::from(real)->prepare_console_stream(desc,iid,out,std::move(record)); }); } rt::d3d12_xs::set_device_native_graphics_factory(outer, [](ID3D12Device* real, const leonida::native_pso::GraphicsDesc& desc, REFIID iid, void** out) { return Device::from(real)->create_native_graphics(desc, iid, out); }); rt::d3d12_xs::set_depth_stencil_uav_provider(outer, &enable_depth_stencil_uav, [](const D3D12_RESOURCE_DESC& native, std::uint32_t layout, const D3D12_CLEAR_VALUE* clear) { auto logical = native; logical.Flags |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; if (barrier_layout_refusal(logical, static_cast(layout))) return false; D3D12_HEAP_PROPERTIES heap{}; heap.Type = D3D12_HEAP_TYPE_DEFAULT; return !committed_resource_refusal(heap, D3D12_HEAP_FLAG_NONE, native, D3D12_RESOURCE_STATE_COMMON, clear, false, false); }); rt::d3d12_xs::set_device_adapter_provider(outer, [](ID3D12Device* real, REFIID riid, void** out) { IDXGIFactory1* factory = nullptr; HRESULT hr = create_dxgi_factory(real, __uuidof(IDXGIFactory1), reinterpret_cast(&factory)); if (FAILED(hr)) return hr; IDXGIAdapter* adapter = nullptr; hr = factory->EnumAdapters(0, &adapter); factory->Release(); if (FAILED(hr)) return hr; hr = adapter->QueryInterface(riid, out); adapter->Release(); return hr; }); } const RootArgumentLayout* root_signature_layout(ID3D12RootSignature* signature) { const RootSignature* s = RootSignature::from(signature); return s ? &s->layout() : nullptr; } std::uintptr_t compute_pipeline_id(ID3D12PipelineState* pipeline) { auto* p=PipelineState::from(pipeline); return p && p->resolve_type(false) ? p->id() : 0; } std::uintptr_t graphics_pipeline_id(ID3D12PipelineState* pipeline) { auto* p=PipelineState::from(pipeline); return p && p->resolve_type(true) ? p->id() : 0; } const std::vector* pipeline_subgroup_requests(ID3D12PipelineState* pipeline) { const PipelineState* p = PipelineState::from(pipeline); return p && (p->compute() || p->graphics()) ? &p->subgroup_requests() : nullptr; } long live_pipeline_states() { return live_pipeline_state_count.load(); } bool write_placed_buffer_view(ID3D12Device* device, bool unordered, const void* view, std::uint64_t address, std::uint64_t width, D3D12_CPU_DESCRIPTOR_HANDLE destination) { Device* d = Device::from(device); if (!d || !view || !destination.ptr) return false; return d->write_placed_buffer_view(unordered, view, address, width, destination); } bool write_placed_texture_view(ID3D12Device* device, bool unordered, const std::uint32_t* resource_words, const std::uint32_t* view_words, std::uint64_t address, D3D12_CPU_DESCRIPTOR_HANDLE destination) { Device* d = Device::from(device); if (!d || !resource_words || !view_words || !destination.ptr) return false; if (unordered) return d->write_placed_texture_uav(resource_words, view_words, address, destination); return d->write_placed_texture_view(resource_words, view_words, address, destination); } D3D12_GPU_VIRTUAL_ADDRESS console_descriptor_table_va(D3D12_GPU_VIRTUAL_ADDRESS va) { return console_heap_ranges().shader_va(va); } // The device a command list of this module belongs to: its attached device is the d3d12_xs proxy when the title made // the list through one (Device::identity), which does not answer Device's tag itself. Device* list_device(IUnknown* device) { if (!device) return nullptr; if (Device* d = Device::from(device)) return d; if (ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device)) return Device::from(real); static std::atomic logged{false}; if (!logged.exchange(true)) std::fprintf(stderr, "[rt] d3d12: an acceleration-structure command on a list whose device is not this " "layer's: its addresses are left as the title gave them\n"); return nullptr; } // LEONIDA_RT_AS=off (diagnostic): acceleration-structure builds and copies are not recorded at all, so no BVH is // written; traversal finds whatever the structures' memory holds. For telling a device loss in the builds apart from // one elsewhere. bool acceleration_structures_off() { static const bool off = [] { char value[8] = {}; std::size_t length = 0; const bool set = getenv_s(&length, value, "LEONIDA_RT_AS") == 0 && length > 1 && !std::strcmp(value, "off"); if (set) std::fprintf(stderr, "[rt] d3d12: LEONIDA_RT_AS=off: acceleration-structure builds and copies are dropped\n"); return set; }(); return off; } bool resolve_acceleration_structure_build(IUnknown* device, leonida::BuildAccelerationStructure& build) { if (acceleration_structures_off()) return false; Device* d = list_device(device); return !d || d->resolve_xdxr_build(build); } bool resolve_acceleration_structure_copy(IUnknown* device, leonida::CopyAccelerationStructure& copy) { if (acceleration_structures_off()) return false; Device* d = list_device(device); return !d || d->resolve_xdxr_copy(copy); } bool resolve_acceleration_structure_postbuild(IUnknown* device, leonida::AccelerationStructurePostbuild& info) { Device* d = list_device(device); return !d || d->resolve_xdxr_postbuild(info); } IUnknown* descriptor_heap_info(ID3D12DescriptorHeap* heap, D3D12_DESCRIPTOR_HEAP_DESC& desc, D3D12_GPU_VIRTUAL_ADDRESS& gpu_base) { if (!heap) return nullptr; if (ID3D12DescriptorHeap* real = rt::d3d12_xs::heap_proxy_real_heap(heap)) heap = real; const DescriptorHeap* d = DescriptorHeap::from(heap); if (!d) return nullptr; desc = d->raw_desc(); gpu_base = d->gpu_base(); return d->attached_device(); } VkImage vulkan_image(ID3D12Resource* resource) { const Resource* r = Resource::from(resource); return r ? const_cast(r)->bound_image() : VK_NULL_HANDLE; } VkMemoryPropertyFlags vulkan_memory_flags(ID3D12Resource* resource) { const Resource* r = Resource::from(resource); return r ? r->memory_flags() : 0; } bool title_shadow_buffer(ID3D12Resource* resource) { const Resource* r = Resource::from(resource); return r && r->is_shadow(); } VkBuffer vulkan_buffer(ID3D12Resource* resource) { const Resource* r = Resource::from(resource); return r ? r->buffer() : VK_NULL_HANDLE; } leonida::PipelineWorkers::Stats pipeline_worker_stats(ID3D12Device* device) { if (!device) return {}; ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); if (auto* d = Device::from(real ? real : device)) return d->context().pipeline_worker_stats(); return {}; } const VulkanDeviceInfo* vulkan_device_info(ID3D12Device* device) { if (!device) return nullptr; ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); if (auto* d = Device::from(real ? real : device)) return &d->state().info; return nullptr; } std::uint64_t title_shadow_refresh_queries(ID3D12Device* device) { auto* d = Device::from(device); if (!d) return 0; auto& state = d->state(); std::lock_guard lock(state.shadow_mutex); std::uint64_t queries = 0; for (const auto& shadow : state.shadows) queries += shadow->refresh_queries(); return queries; } std::uint64_t title_host_imports(ID3D12Device* device) { auto* d = Device::from(device); return d ? d->state().host_imports.load(std::memory_order_relaxed) : 0; } std::uint64_t title_shadow_trackers(ID3D12Device* device) { auto* d = Device::from(device); if (!d) return 0; auto& state = d->state(); std::lock_guard lock(state.shadow_mutex); return state.shadows.size(); } TitleShadowWatch title_shadow_watch(ID3D12Device* device) { TitleShadowWatch watch; auto* d = Device::from(device); if (!d) return watch; auto& state = d->state(); std::lock_guard lock(state.shadow_mutex); for (const auto& shadow : state.shadows) { watch.asks += shadow->refresh_asks(); watch.written += shadow->refresh_written(); watch.faults += shadow->faults(); watch.watched_bytes += shadow->watched_bytes(); watch.hot_bytes += shadow->hot_bytes(); } return watch; } HRESULT create_buffer_at_host_address(ID3D12Device* device, void* address, const D3D12_RESOURCE_DESC& desc, std::uint32_t layout, REFIID riid, void** out, const D3D12_CLEAR_VALUE* clear) { if (out) *out = nullptr; if (!device || !out) return E_POINTER; ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); auto* d = Device::from(real ? real : device); if (!d) return E_NOTIMPL; return d->create_at_host_address(address, desc, layout, riid, out, clear); } bool device_supports_ray_tracing(ID3D12Device* device) { if (!device) return false; ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); if (auto* d = Device::from(real ? real : device)) return d->context().ray_tracing_supported(); return false; } VkAccelerationStructureKHR vulkan_acceleration_structure(ID3D12Device* device, D3D12_GPU_VIRTUAL_ADDRESS va) { if (!device || !va) return VK_NULL_HANDLE; ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); if (auto* d = Device::from(real ? real : device)) return d->context().resolve_acceleration_structure(va); return VK_NULL_HANDLE; } bool color_resolve_format_is_integer(DXGI_FORMAT format) { return DeviceState::numeric_class(vulkan_format(format, false).format) != 0; } bool color_resolve_format_matches(DXGI_FORMAT format, ID3D12Resource* dst, ID3D12Resource* src) { if (!dst || !src) return false; const Format requested = vulkan_format(format, false); if (requested.typeless || requested.rgb96 || requested.aspects != VK_IMAGE_ASPECT_COLOR_BIT) return false; if (DeviceState::numeric_class(requested.format) != 0) return false; // D3D12 resolves no integer format const auto matches = [&](ID3D12Resource* resource) { const D3D12_RESOURCE_DESC desc = resource->GetDesc(); return vulkan_format(desc.Format, desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL).format == requested.format; }; return matches(dst) && matches(src); } bool depth_stencil_resolve_supported(DXGI_FORMAT format, ID3D12Resource* dst, UINT dst_subresource, UINT x, UINT y, ID3D12Resource* src, UINT src_subresource, const D3D12_RECT* rect, D3D12_RESOLVE_MODE mode) { const Resource* d = Resource::from(dst); const Resource* s = Resource::from(src); if (!d || !s) return false; // The format names the depth format, or one plane by its shader-resource format. Measured on the PC runtime // (RTX 5070 and WARP): Close fails for AVERAGE with the depth format or a stencil plane; the depth plane's // own format (R32_FLOAT, R24_UNORM_X8_TYPELESS) takes AVERAGE as well as MIN and MAX. DXGI_FORMAT family = format; int named_plane = -1; // -1: any plane of the depth format switch (format) { case DXGI_FORMAT_R32_FLOAT: family = DXGI_FORMAT_D32_FLOAT, named_plane = 0; break; case DXGI_FORMAT_R24_UNORM_X8_TYPELESS: family = DXGI_FORMAT_D24_UNORM_S8_UINT, named_plane = 0; break; case DXGI_FORMAT_X24_TYPELESS_G8_UINT: family = DXGI_FORMAT_D24_UNORM_S8_UINT, named_plane = 1; break; case DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS: family = DXGI_FORMAT_D32_FLOAT_S8X24_UINT, named_plane = 0; break; case DXGI_FORMAT_X32_TYPELESS_G8X24_UINT: family = DXGI_FORMAT_D32_FLOAT_S8X24_UINT, named_plane = 1; break; default: break; } const Format requested = vulkan_format(family, true); if (requested.typeless || !(requested.aspects & VK_IMAGE_ASPECT_DEPTH_BIT)) return false; // The plane a subresource index names (0 depth, 1 stencil), or -1. const auto plane = [&](const Resource* r, UINT subresource) { const D3D12_RESOURCE_DESC& desc = r->desc(); if (!(desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) || vulkan_format(desc.Format, true).format != requested.format) return -1; const UINT planes = (requested.aspects & VK_IMAGE_ASPECT_STENCIL_BIT) ? 2 : 1; const UINT per_plane = UINT(desc.MipLevels) * desc.DepthOrArraySize; return per_plane && subresource / per_plane < planes ? int(subresource / per_plane) : -1; }; const int resolved = plane(d, dst_subresource); if (resolved < 0 || resolved != plane(s, src_subresource) || (named_plane >= 0 && resolved != named_plane) || s->desc().SampleDesc.Count <= 1 || d->desc().SampleDesc.Count != 1) return false; VkResolveModeFlagBits wanted = VK_RESOLVE_MODE_MIN_BIT; if (mode == D3D12_RESOLVE_MODE_MAX) wanted = VK_RESOLVE_MODE_MAX_BIT; else if (mode == D3D12_RESOLVE_MODE_AVERAGE && named_plane == 0) wanted = VK_RESOLVE_MODE_AVERAGE_BIT; else if (mode != D3D12_RESOLVE_MODE_MIN) return false; // The rendering scope that replays it resolves pixels in place (vulkan_replay.h). if (rect ? (LONG(x) != rect->left || LONG(y) != rect->top) : (x || y)) return false; const DeviceState& state = d->device_state(); return (resolved ? state.stencil_resolve_modes : state.depth_resolve_modes) & wanted; } std::uint32_t device_max_push_constants_size(ID3D12Device* device) { if (!device) return 0; ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); if (!real) real = device; if (auto* d = Device::from(real)) return d->info().max_push_constants_size; return 0; } bool device_push_constants_need_fallback(ID3D12Device* device) { if (!device) return false; ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); if (!real) real = device; if (auto* d = Device::from(real)) return d->info().push_constants_need_fallback; return false; } bool device_upload_in_vram(ID3D12Device* device) { if (!device) return false; ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); if (!real) real = device; if (auto* d = Device::from(real)) return d->upload_in_vram(); return false; } bool device_sparse_buffer_tiles(ID3D12Device* device) { const Device* d = Device::from(device); return d && d->state().sparse_buffer_memory_types != 0; } std::uint64_t device_arena_size(ID3D12Device* device) { if (!device) return 0; ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); if (!real) real = device; const Device* d = Device::from(real); return d ? d->state().arena.size : 0; } ImageMemoryStats image_memory_stats(ID3D12Device* device) { if (!device) return {}; ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); if (!real) real = device; const Device* d = Device::from(real); if (!d || !d->state().image_memory) return {}; const auto stats = d->state().image_memory->stats(); return {stats.blocks, stats.block_bytes, stats.ranges}; } bool read_arena(ID3D12Device* device, std::uint64_t va, void* out, std::size_t bytes) { if (!device || !out) return false; ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); if (!real) real = device; const Device* d = Device::from(real); if (!d || !d->state().arena.mapped || va > d->state().arena.size || bytes > d->state().arena.size - va) return false; std::memcpy(out, d->state().arena.mapped + va, bytes); return true; } namespace { const leonida::BindlessSet* bindless_of(ID3D12Device* device) { if (!device) return nullptr; ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); const Device* d = Device::from(real ? real : device); return d ? d->bindless() : nullptr; } } // namespace VkDescriptorSet bindless_set(ID3D12Device* device) { const leonida::BindlessSet* set = bindless_of(device); return set ? set->set() : VK_NULL_HANDLE; } BindlessStats bindless_stats(ID3D12Device* device) { BindlessStats stats; if (!device) return stats; ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); const Device* d = Device::from(real ? real : device); if (!d || !d->bindless()) return stats; stats.generations_made = d->bindless()->generations_made(); stats.retired_pending = d->bindless()->retired_count(); stats.device_idle_waits = d->state().bindless_idle_waits.load(std::memory_order_relaxed); return stats; } VkDescriptorSetLayout bindless_set_layout(ID3D12Device* device) { const leonida::BindlessSet* set = bindless_of(device); return set ? set->layout() : VK_NULL_HANDLE; } std::uint32_t bindless_hash_lookup(ID3D12Device* device, const std::uint32_t (&key)[8]) { const leonida::BindlessSet* set = bindless_of(device); return set ? set->table().lookup(key) : 0; } BindlessRoom bindless_room(ID3D12Device* device) { const leonida::BindlessSet* set = bindless_of(device); if (!set) return {}; return {set->free_images(leonida::ImageDimension::dim_2d), set->free_samplers()}; } WindowPresenter::WindowPresenter(IUnknown* device, std::unique_ptr presenter) : device_(device), presenter_(std::move(presenter)) { if (device_) device_->AddRef(); } WindowPresenter::~WindowPresenter() { presenter_.reset(); // before the device it runs on if (device_) device_->Release(); } namespace { HRESULT present_result(VkResult result) { if (result == VK_SUCCESS) return S_OK; std::fprintf(stderr, "[rt] d3d12: present failed (VkResult %d)\n", int(result)); if (result == VK_ERROR_DEVICE_LOST) return DXGI_ERROR_DEVICE_REMOVED; if (result == VK_ERROR_FORMAT_NOT_SUPPORTED) return DXGI_ERROR_UNSUPPORTED; return E_FAIL; } } // namespace HRESULT WindowPresenter::present(ID3D12Resource* back_buffer, UINT sync_interval, const D3D12_RECT* src_rect, bool tear) { if (!back_buffer) return E_INVALIDARG; const leonida::PresentRect rect = src_rect ? leonida::PresentRect{src_rect->left, src_rect->top, src_rect->right, src_rect->bottom} : leonida::PresentRect{}; return present_result(presenter_->present(resource_id(back_buffer), sync_interval > 0, src_rect ? &rect : nullptr, tear)); } bool WindowPresenter::present_splash(ID3D12Resource* image) { if (!image) return false; image->AddRef(); std::shared_ptr owner(image, [](ID3D12Resource* p) { p->Release(); }); return presenter_->present_splash(resource_id(image), std::move(owner)); } bool WindowPresenter::tear_supported() const { return presenter_->tear_supported(); } bool WindowPresenter::last_present_tore() const { return presenter_->last_present_tore(); } std::uint64_t WindowPresenter::tear_presents() const { return presenter_->tear_presents(); } HRESULT WindowPresenter::present_blank(UINT sync_interval) { return present_result(presenter_->present_blank(sync_interval > 0)); } HRESULT WindowPresenter::present_planes(const leonida::PresentPlanes& planes, UINT sync_interval, bool tear) { return present_result(presenter_->present_planes(planes, sync_interval > 0, tear)); } bool WindowPresenter::hdr_active() const { return presenter_->hdr_active(); } void WindowPresenter::force_hdr_encoding(bool on) { presenter_->force_hdr_encoding(on); } std::uint64_t WindowPresenter::composed_presents() const { return presenter_->composed_presents(); } // DISPLAYCONFIG_SDR_WHITE_LEVEL.SDRWhiteLevel is the white level in units of 80/1000 nits: 1000 is 80 nits (the scRGB 1.0), // 2500 is 200 nits (MS Learn, DISPLAYCONFIG_SDR_WHITE_LEVEL). Zero is not a level. float sdr_white_nits_from_level(unsigned long level) { return float(level) / 1000.0f * 80.0f; } float WindowPresenter::display_sdr_white_nits() const { if (!window_) return 0.0f; // The GDI name of the monitor the window is on, matched to a display path's source, whose target has the setting. MONITORINFOEXW monitor{}; monitor.cbSize = sizeof(monitor); if (!GetMonitorInfoW(MonitorFromWindow(window_, MONITOR_DEFAULTTONEAREST), &monitor)) return 0.0f; // The active configuration can change between the size query and the read (a hot-plug): ERROR_INSUFFICIENT_BUFFER asks // for the sizes again (the pattern Microsoft documents for QueryDisplayConfig). UINT32 path_count = 0, mode_count = 0; std::vector paths; std::vector modes; LONG status = ERROR_INSUFFICIENT_BUFFER; for (int attempt = 0; attempt < 8 && status == ERROR_INSUFFICIENT_BUFFER; ++attempt) { if (GetDisplayConfigBufferSizes(QDC_ONLY_ACTIVE_PATHS, &path_count, &mode_count) != ERROR_SUCCESS) return 0.0f; paths.assign(path_count, {}); modes.assign(mode_count, {}); status = QueryDisplayConfig(QDC_ONLY_ACTIVE_PATHS, &path_count, paths.data(), &mode_count, modes.data(), nullptr); } if (status != ERROR_SUCCESS) return 0.0f; // the caller keeps the last good value for (UINT32 i = 0; i < path_count; ++i) { DISPLAYCONFIG_SOURCE_DEVICE_NAME source{}; source.header = {DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME, sizeof(source), paths[i].sourceInfo.adapterId, paths[i].sourceInfo.id}; if (DisplayConfigGetDeviceInfo(&source.header) != ERROR_SUCCESS || std::wcscmp(source.viewGdiDeviceName, monitor.szDevice) != 0) continue; DISPLAYCONFIG_SDR_WHITE_LEVEL level{}; level.header = {DISPLAYCONFIG_DEVICE_INFO_GET_SDR_WHITE_LEVEL, sizeof(level), paths[i].targetInfo.adapterId, paths[i].targetInfo.id}; if (DisplayConfigGetDeviceInfo(&level.header) != ERROR_SUCCESS || level.SDRWhiteLevel == 0) return 0.0f; return sdr_white_nits_from_level(level.SDRWhiteLevel); } return 0.0f; } bool WindowPresenter::enable_capture() { return presenter_->enable_capture(); } void WindowPresenter::set_abort(std::function abort) { presenter_->set_abort(std::move(abort)); } bool WindowPresenter::read_back(std::vector& pixels, VkExtent2D* extent, VkFormat* format) { return presenter_->read_back(pixels, extent, format); } VkExtent2D WindowPresenter::extent() const { return presenter_->extent(); } std::uint64_t WindowPresenter::presented() const { return presenter_->presented(); } bool device_has_swapchain_colorspace(ID3D12Device* device) { ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); Device* d = Device::from(real ? real : device); return d && d->state().info.swapchain_colorspace; } std::unique_ptr create_window_presenter(ID3D12Device* device, HWND window, bool hold_device) { // A title holds the Xbox-ABI proxy, not the layer's device: look behind it, as the helpers above do. ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); Device* d = Device::from(real ? real : device); if (device && !d) std::fprintf(stderr, "[rt] d3d12: create_window_presenter: %p is neither the Xbox device proxy nor a device of " "this layer; no presenter\n", static_cast(device)); if (!d || !window) return nullptr; const VulkanDeviceInfo& info = d->state().info; if (!info.presentation) { std::fprintf(stderr, "[rt] d3d12: the Vulkan device was created without presentation support\n"); return nullptr; } const auto create_surface = reinterpret_cast( info.get_instance_proc(info.instance, "vkCreateWin32SurfaceKHR")); if (!create_surface) return nullptr; VkWin32SurfaceCreateInfoKHR surface_info{VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR}; surface_info.hinstance = GetModuleHandleW(nullptr); surface_info.hwnd = window; VkSurfaceKHR surface = VK_NULL_HANDLE; if (create_surface(info.instance, &surface_info, nullptr, &surface) != VK_SUCCESS) return nullptr; // LEONIDA_PRESENT_NO_TEAR=1 keeps the swapchain FIFO-only (ImmediateThresholdPercent then does nothing). // Any non-empty value other than "0" turns it off. bool tear_allowed = true; { char* value = nullptr; std::size_t length = 0; if (_dupenv_s(&value, &length, "LEONIDA_PRESENT_NO_TEAR") == 0 && value) { tear_allowed = value[0] == '\0' || std::strcmp(value, "0") == 0; std::free(value); } } auto presenter = std::make_unique(*d->state().context, info.get_instance_proc, info.instance, info.physical, info.queue, info.queue_family, surface, // owns the surface info.swapchain_maintenance1 && tear_allowed, [window]() -> VkExtent2D { RECT r{}; if (GetClientRect(window, &r)) { return {static_cast(r.right - r.left), static_cast(r.bottom - r.top)}; } return {0, 0}; }, [create_surface, hinstance = GetModuleHandleW(nullptr), hwnd = window, instance = info.instance]() -> VkSurfaceKHR { // A lost surface (display gone) is remade for the // same window; VulkanSwapchain never retained the // hwnd, this callback does. VkWin32SurfaceCreateInfoKHR surface_info{ VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR}; surface_info.hinstance = hinstance; surface_info.hwnd = hwnd; VkSurfaceKHR made = VK_NULL_HANDLE; if (create_surface(instance, &surface_info, nullptr, &made) != VK_SUCCESS) return VK_NULL_HANDLE; return made; }); if (!presenter->ok()) { std::fprintf(stderr, "[rt] d3d12: cannot present to this window from the device's queue family\n"); return nullptr; } auto window_presenter = std::make_unique(hold_device ? d->holder() : nullptr, std::move(presenter)); window_presenter->set_window(window); return window_presenter; } HRESULT register_samplers(ID3D12Device* device, std::span samplers) { if (!device) return E_INVALIDARG; ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); Device* d = Device::from(real ? real : device); if (!d) return E_INVALIDARG; bool all = true; for (const leonida::gfx10::SamplerWords& words : samplers) all = d->bind_sampler(words) && all; return all ? S_OK : E_FAIL; } HRESULT create_dxgi_factory(ID3D12Device* device, REFIID riid, void** out) { if (!out) return E_POINTER; *out = nullptr; if (!device) return E_INVALIDARG; ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); Device* d = Device::from(real ? real : device); if (!d) return E_INVALIDARG; const auto& i = d->info(); const auto gdpa = reinterpret_cast(i.get_instance_proc(i.instance, "vkGetDeviceProcAddr")); if (!gdpa) return E_FAIL; return rt::dxgi::create_factory(d->context(), i.get_instance_proc, i.instance, i.physical, gdpa, i.queue, i.queue_family, riid, out); } // Creates its own Vulkan instance and a Vulkan 1.3 device, or a 1.2 device with VK_KHR_dynamic_rendering and // VK_KHR_synchronization2 (vulkan13_features.h). LEONIDA_VK_VALIDATION=1 adds VK_LAYER_KHRONOS_validation. HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettings queue_test_settings) { if (!out) return E_POINTER; *out = nullptr; // LEONIDA_AFTERMATH=1: GPU crash dumps on before the Vulkan instance and device exist (src/vulkan_aftermath.h). leonida::aftermath::enable(); static const HMODULE library = LoadLibraryA("vulkan-1.dll"); const auto get = library ? reinterpret_cast( reinterpret_cast(GetProcAddress(library, "vkGetInstanceProcAddr"))) : nullptr; if (!get) { std::fprintf(stderr, "[rt] d3d12: vulkan-1.dll not found\n"); return E_FAIL; } const auto create_instance = reinterpret_cast(get(nullptr, "vkCreateInstance")); const auto enum_inst_exts = reinterpret_cast( get(nullptr, "vkEnumerateInstanceExtensionProperties")); std::vector inst_exts; bool surface_maintenance1_khr = false, surface_maintenance1_ext = false; // enabled on the instance bool swapchain_colorspace_enabled = false; // VK_EXT_swapchain_colorspace on the instance if (enum_inst_exts) { std::uint32_t ext_cnt = 0; enum_inst_exts(nullptr, &ext_cnt, nullptr); std::vector available(ext_cnt); enum_inst_exts(nullptr, &ext_cnt, available.data()); bool has_surface = false, has_win32 = false, has_caps2 = false; for (const auto& e : available) { if (!std::strcmp(e.extensionName, VK_KHR_SURFACE_EXTENSION_NAME)) has_surface = true; if (!std::strcmp(e.extensionName, VK_KHR_WIN32_SURFACE_EXTENSION_NAME)) has_win32 = true; if (!std::strcmp(e.extensionName, VK_KHR_GET_SURFACE_CAPABILITIES_2_EXTENSION_NAME)) has_caps2 = true; if (!std::strcmp(e.extensionName, "VK_KHR_surface_maintenance1")) surface_maintenance1_khr = true; if (!std::strcmp(e.extensionName, "VK_EXT_surface_maintenance1")) surface_maintenance1_ext = true; } if (has_surface && has_win32) { inst_exts.push_back(VK_KHR_SURFACE_EXTENSION_NAME); inst_exts.push_back(VK_KHR_WIN32_SURFACE_EXTENSION_NAME); // Lists the HDR10 (ST.2084) surface formats, which a PresentX plane in HDR10 can use (xbox_present.h); without it // the surface only offers sRGB-nonlinear ones. for (const auto& e : available) if (!std::strcmp(e.extensionName, VK_EXT_SWAPCHAIN_COLOR_SPACE_EXTENSION_NAME)) { inst_exts.push_back(VK_EXT_SWAPCHAIN_COLOR_SPACE_EXTENSION_NAME); swapchain_colorspace_enabled = true; break; } // The surface half of VK_*_swapchain_maintenance1 (the present modes a swapchain can switch between). if (has_caps2 && (surface_maintenance1_khr || surface_maintenance1_ext)) { inst_exts.push_back(VK_KHR_GET_SURFACE_CAPABILITIES_2_EXTENSION_NAME); if (surface_maintenance1_khr) inst_exts.push_back("VK_KHR_surface_maintenance1"); if (surface_maintenance1_ext) inst_exts.push_back("VK_EXT_surface_maintenance1"); } else { surface_maintenance1_khr = surface_maintenance1_ext = false; } } else { surface_maintenance1_khr = surface_maintenance1_ext = false; } } VkApplicationInfo app{VK_STRUCTURE_TYPE_APPLICATION_INFO}; app.pApplicationName = "gta6rt"; app.apiVersion = VK_API_VERSION_1_3; VkInstanceCreateInfo instance_info{VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO}; instance_info.pApplicationInfo = &app; const char* layer = "VK_LAYER_KHRONOS_validation"; const VkValidationFeatureEnableEXT sync_validation = VK_VALIDATION_FEATURE_ENABLE_SYNCHRONIZATION_VALIDATION_EXT; VkValidationFeaturesEXT validation_features{VK_STRUCTURE_TYPE_VALIDATION_FEATURES_EXT}; validation_features.enabledValidationFeatureCount = 1; validation_features.pEnabledValidationFeatures = &sync_validation; char validation[8] = {}; size_t length = 0; if (getenv_s(&length, validation, "LEONIDA_VK_VALIDATION") == 0 && length > 1 && validation[0] != '0') { // Ask for the layer only when the loader lists it, and say so when it does not: an instance that cannot be // made because of a missing layer left the caller with "Vulkan unavailable" and no hint that validation was // the cause. Wine does not list the Linux loader's layers to the program and refuses an explicit request for // one, so there only VK_INSTANCE_LAYERS (which Wine keeps out of the program's environment) loads it. bool layer_listed = false; if (const auto enumerate_layers = reinterpret_cast( get(nullptr, "vkEnumerateInstanceLayerProperties"))) { std::uint32_t layer_count = 0; enumerate_layers(&layer_count, nullptr); std::vector layers(layer_count); if (layer_count && enumerate_layers(&layer_count, layers.data()) >= VK_SUCCESS) for (std::uint32_t i = 0; i < layer_count; ++i) layer_listed = layer_listed || std::strcmp(layers[i].layerName, layer) == 0; } if (layer_listed) { instance_info.pNext = &validation_features; instance_info.enabledLayerCount = 1; instance_info.ppEnabledLayerNames = &layer; } else { std::fprintf(stderr, "[rt] d3d12: LEONIDA_VK_VALIDATION is set but %s is not listed by the Vulkan loader " "(install the Vulkan SDK; under Wine set VK_INSTANCE_LAYERS=%s instead)\n", layer, layer); return E_FAIL; } } // VK_EXT_debug_utils when the loader has it, for the game's debug markers (PIX events) in RenderDoc and the like. const char* debug_utils = VK_EXT_DEBUG_UTILS_EXTENSION_NAME; bool has_debug_utils = false; if (const auto enumerate = reinterpret_cast( get(nullptr, "vkEnumerateInstanceExtensionProperties"))) { std::uint32_t extension_count = 0; enumerate(nullptr, &extension_count, nullptr); std::vector extensions(extension_count); enumerate(nullptr, &extension_count, extensions.data()); for (const auto& e : extensions) has_debug_utils = has_debug_utils || std::strcmp(e.extensionName, debug_utils) == 0; } // One list: the surface extensions above (for DXGI presentation) and debug utils both go on the instance. const bool instance_has_surface = !inst_exts.empty(); if (has_debug_utils) inst_exts.push_back(debug_utils); instance_info.enabledExtensionCount = static_cast(inst_exts.size()); instance_info.ppEnabledExtensionNames = inst_exts.empty() ? nullptr : inst_exts.data(); OwnedRuntime owned{}; if (create_instance(&instance_info, nullptr, &owned.instance) != VK_SUCCESS) { std::fprintf(stderr, "[rt] d3d12: vkCreateInstance (Vulkan 1.3) failed\n"); return E_FAIL; } owned.destroy_instance = reinterpret_cast(get(owned.instance, "vkDestroyInstance")); const auto fail = [&](const char* why) { std::fprintf(stderr, "[rt] d3d12: %s\n", why); owned.destroy_instance(owned.instance, nullptr); return E_FAIL; }; #define LEONIDA_INSTANCE(name) const auto name = reinterpret_cast(get(owned.instance, #name)) LEONIDA_INSTANCE(vkEnumeratePhysicalDevices); LEONIDA_INSTANCE(vkGetPhysicalDeviceProperties); LEONIDA_INSTANCE(vkGetPhysicalDeviceQueueFamilyProperties); LEONIDA_INSTANCE(vkGetPhysicalDeviceFeatures2); LEONIDA_INSTANCE(vkGetPhysicalDeviceFormatProperties); LEONIDA_INSTANCE(vkGetPhysicalDeviceProperties2); LEONIDA_INSTANCE(vkEnumerateDeviceExtensionProperties); LEONIDA_INSTANCE(vkCreateDevice); LEONIDA_INSTANCE(vkGetDeviceProcAddr); #undef LEONIDA_INSTANCE std::uint32_t count = 0; vkEnumeratePhysicalDevices(owned.instance, &count, nullptr); std::vector physicals(count); vkEnumeratePhysicalDevices(owned.instance, &count, physicals.data()); VulkanDeviceInfo info{}; info.get_instance_proc = get; info.instance = owned.instance; info.separate_depth_stencil_layouts = true; info.debug_utils = has_debug_utils; VkPhysicalDeviceProperties chosen{}; bool chosen_bc = false; VkPhysicalDeviceFeatures chosen_features{}; VkPhysicalDeviceVulkan12Features chosen12{}; bool chosen_draw_params = false; leonida::Vulkan13Features v13, candidate13; // The first usable device of the highest vulkan_device_rank: a native driver over Microsoft's Dozen (which says // it is a discrete GPU, #915), then discrete over integrated; the test harnesses (vk_device_pick.h) pick the same. int chosen_rank = -1; for (VkPhysicalDevice candidate : physicals) { VkPhysicalDeviceProperties props{}; vkGetPhysicalDeviceProperties(candidate, &props); if (!leonida::vulkan_device_wanted(props.deviceName)) continue; candidate13.query(candidate, props.apiVersion, vkGetPhysicalDeviceFeatures2, vkEnumerateDeviceExtensionProperties); if (!candidate13.usable()) continue; VkPhysicalDeviceVulkan11Features f11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES}; VkPhysicalDeviceVulkan12Features f12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES, &f11}; VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &f12}; vkGetPhysicalDeviceFeatures2(candidate, &features); const bool bc = features.features.textureCompressionBC; const bool draw_params = f11.shaderDrawParameters; if (!f12.timelineSemaphore || !f12.separateDepthStencilLayouts || !f12.bufferDeviceAddress) continue; std::uint32_t family_count = 0; vkGetPhysicalDeviceQueueFamilyProperties(candidate, &family_count, nullptr); std::vector families(family_count); vkGetPhysicalDeviceQueueFamilyProperties(candidate, &family_count, families.data()); for (std::uint32_t i = 0; i < family_count; ++i) { if (!(families[i].queueFlags & VK_QUEUE_GRAPHICS_BIT)) continue; if (const int rank = leonida::vulkan_device_rank(static_cast(props.deviceType), props.vendorID); rank > chosen_rank) { chosen_rank = rank; info.physical = candidate; info.queue_family = i; chosen = props; chosen_bc = bc; chosen_features = features.features; chosen12 = f12; chosen_draw_params = draw_params; v13.choose(candidate13); } break; } } if (!info.physical) return fail(leonida::vulkan_device_filter().empty() ? "no Vulkan 1.3 GPU (or 1.2 with VK_KHR_dynamic_rendering and VK_KHR_synchronization2) with " "dynamicRendering, synchronization2, timelineSemaphore and separateDepthStencilLayouts" : "no GPU named by LEONIDA_VK_DEVICE has Vulkan 1.3 (or 1.2 with VK_KHR_dynamic_rendering and " "VK_KHR_synchronization2) with dynamicRendering, synchronization2, timelineSemaphore and " "separateDepthStencilLayouts"); if (!v13.core) std::fprintf(stderr, "[rt] d3d12: Vulkan 1.2 device: dynamicRendering and synchronization2 through their KHR " "extensions; %s\n", v13.extended_dynamic_state ? "extended dynamic state through VK_EXT_extended_dynamic_state(2)" : "no extended dynamic state, so no graphics pipelines"); // VK_EXT_conditional_rendering for SetPredication, VK_KHR_swapchain for DXGI presentation, and optional // VK_KHR_acceleration_structure + VK_KHR_ray_query for hardware BVH builds (BLAS + TLAS). VkPhysicalDeviceConditionalRenderingFeaturesEXT conditional{ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CONDITIONAL_RENDERING_FEATURES_EXT}; bool has_swapchain = false; VkPhysicalDeviceAccelerationStructureFeaturesKHR as_features{ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ACCELERATION_STRUCTURE_FEATURES_KHR}; VkPhysicalDeviceRayQueryFeaturesKHR rq_features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_QUERY_FEATURES_KHR}; VkPhysicalDeviceMeshShaderFeaturesEXT mesh_features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT}; VkPhysicalDeviceTransformFeedbackFeaturesEXT transform_feedback_features{ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TRANSFORM_FEEDBACK_FEATURES_EXT}; VkPhysicalDeviceTransformFeedbackPropertiesEXT transform_feedback_properties{ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TRANSFORM_FEEDBACK_PROPERTIES_EXT}; { std::uint32_t extension_count = 0; vkEnumerateDeviceExtensionProperties(info.physical, nullptr, &extension_count, nullptr); std::vector extensions(extension_count); vkEnumerateDeviceExtensionProperties(info.physical, nullptr, &extension_count, extensions.data()); bool has_as = false, has_dho = false, has_rq = false; for (const auto& e : extensions) { if (!std::strcmp(e.extensionName, VK_EXT_CONDITIONAL_RENDERING_EXTENSION_NAME)) { VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &conditional}; vkGetPhysicalDeviceFeatures2(info.physical, &features); info.conditional_rendering = conditional.conditionalRendering == VK_TRUE; } else if (!std::strcmp(e.extensionName, VK_KHR_SWAPCHAIN_EXTENSION_NAME)) { has_swapchain = true; } else if (!std::strcmp(e.extensionName, VK_KHR_ACCELERATION_STRUCTURE_EXTENSION_NAME)) { has_as = true; } else if (!std::strcmp(e.extensionName, VK_KHR_DEFERRED_HOST_OPERATIONS_EXTENSION_NAME)) { has_dho = true; } else if (!std::strcmp(e.extensionName, VK_KHR_RAY_QUERY_EXTENSION_NAME)) { has_rq = true; } else if (!std::strcmp(e.extensionName, VK_EXT_MESH_SHADER_EXTENSION_NAME)) { VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &mesh_features}; vkGetPhysicalDeviceFeatures2(info.physical, &features); info.mesh_shader = mesh_features.meshShader == VK_TRUE; info.mesh_shader_queries = mesh_features.meshShaderQueries == VK_TRUE; } else if (!std::strcmp(e.extensionName, VK_EXT_TRANSFORM_FEEDBACK_EXTENSION_NAME)) { VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &transform_feedback_features}; vkGetPhysicalDeviceFeatures2(info.physical, &features); info.transform_feedback = transform_feedback_features.transformFeedback == VK_TRUE; info.transform_feedback_geometry_streams = transform_feedback_features.geometryStreams == VK_TRUE; // D3D-302: the queries and the stream count are properties, not features. VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &transform_feedback_properties}; vkGetPhysicalDeviceProperties2(info.physical, &properties); info.transform_feedback_queries = transform_feedback_properties.transformFeedbackQueries == VK_TRUE; info.max_transform_feedback_streams = transform_feedback_properties.maxTransformFeedbackStreams; } } if (!info.mesh_shader) std::fprintf(stderr, "[rt] d3d12: the GPU has no VK_EXT_mesh_shader: mesh-shader PSOs are unsupported\n"); if (!info.transform_feedback) std::fprintf(stderr, "[rt] d3d12: the GPU has no VK_EXT_transform_feedback: SO_STATISTICS query pools read zero\n"); else if (!info.transform_feedback_queries || !info.max_transform_feedback_streams) std::fprintf(stderr, "[rt] d3d12: the GPU has no transform-feedback queries (transformFeedbackQueries, " "maxTransformFeedbackStreams): SO_STATISTICS query pools read zero\n"); if (has_as && has_dho && has_rq && chosen12.bufferDeviceAddress) { as_features.pNext = &rq_features; VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &as_features}; vkGetPhysicalDeviceFeatures2(info.physical, &features); info.ray_tracing = as_features.accelerationStructure == VK_TRUE && rq_features.rayQuery == VK_TRUE; } // The game's translated RT shaders read XDXR BVH4 records, which a VkAccelerationStructureKHR is not // (docs/d3d12_vulkan.md 4.8): build those, unless LEONIDA_RT_AS=khr asks for #743's KHR builds instead. char rt_as[8] = {}; std::size_t rt_as_length = 0; const bool khr = getenv_s(&rt_as_length, rt_as, "LEONIDA_RT_AS") == 0 && rt_as_length > 1 && std::strcmp(rt_as, "khr") == 0; if (!khr && chosen12.bufferDeviceAddress) { info.xdxr_acceleration_structures = true; info.ray_tracing = false; // no KHR extensions: AS resources keep their console VAs } if (!info.conditional_rendering) std::fprintf(stderr, "[rt] d3d12: the GPU has no VK_EXT_conditional_rendering: SetPredication is unsupported\n"); } VkPhysicalDeviceConditionalRenderingFeaturesEXT enable_conditional{ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CONDITIONAL_RENDERING_FEATURES_EXT}; enable_conditional.conditionalRendering = VK_TRUE; VkPhysicalDeviceRayQueryFeaturesKHR enable_rq{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_QUERY_FEATURES_KHR}; enable_rq.rayQuery = VK_TRUE; VkPhysicalDeviceAccelerationStructureFeaturesKHR enable_as{ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ACCELERATION_STRUCTURE_FEATURES_KHR}; enable_as.accelerationStructure = VK_TRUE; // Only meshShader: the game has no amplification (task) shaders, and multiview and shading-rate mesh features // are not used. VkPhysicalDeviceMeshShaderFeaturesEXT enable_mesh{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT}; enable_mesh.meshShader = VK_TRUE; // The mesh-primitives query, which counts the primitives a mesh shader emits (D3D-MESH-CLIPPING-COUNTER). enable_mesh.meshShaderQueries = info.mesh_shader_queries ? VK_TRUE : VK_FALSE; // D3D-302: real SO_STATISTICS queries need transformFeedback; geometryStreams is only requested when the device // already offers it, so the enable chain matches vk_pipeline_check's (a driver keys the pipeline cache on it). VkPhysicalDeviceTransformFeedbackFeaturesEXT enable_transform_feedback{ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TRANSFORM_FEEDBACK_FEATURES_EXT}; enable_transform_feedback.transformFeedback = VK_TRUE; enable_transform_feedback.geometryStreams = info.transform_feedback_geometry_streams ? VK_TRUE : VK_FALSE; void* ext_chain = nullptr; if (info.mesh_shader) { enable_mesh.pNext = ext_chain; ext_chain = &enable_mesh; } if (info.transform_feedback) { enable_transform_feedback.pNext = ext_chain; ext_chain = &enable_transform_feedback; } if (info.ray_tracing) { enable_rq.pNext = ext_chain; enable_as.pNext = &enable_rq; ext_chain = &enable_as; } if (info.conditional_rendering) { enable_conditional.pNext = ext_chain; ext_chain = &enable_conditional; } // Subgroup size control: a pipeline stage asks for the size its shader was translated for (src/subgroup_size.h). leonida::query_subgroup_size_caps(vkGetPhysicalDeviceProperties2, info.physical, v13.subgroup_size_control, v13.compute_full_subgroups, info.subgroup); const char* compile_mode = std::getenv("LEONIDA_PIPELINE_COMPILE"); const auto mode = compile_mode ? std::string_view(compile_mode) : std::string_view{}; v13.enable_pipeline_cache_control = mode == "cache-only" && v13.core && v13.pipeline_cache_control; info.cold_graphics_compile = v13.enable_pipeline_cache_control; info.prepare_on_bind = mode == "on-demand"; void* v13_chain = v13.enable(ext_chain); // D3D-78 uses the core robustness and format-feature flags. Leave the Vulkan 1.2 extension path unchanged. if (v13.core) { VkPhysicalDeviceVulkan13Features supported{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES}; VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &supported}; vkGetPhysicalDeviceFeatures2(info.physical, &query); info.robust_image_access = supported.robustImageAccess == VK_TRUE; static_cast(v13_chain)->robustImageAccess = supported.robustImageAccess; } // Translated vertex shaders read BaseVertex / BaseInstance (SPIR-V DrawParameters) to give v0 / v3 the // hardware's zero-based vertex and instance ids (docs/design.md, Inputs and outputs). VkPhysicalDeviceVulkan11Features enable11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES, v13_chain}; enable11.shaderDrawParameters = chosen_draw_params ? VK_TRUE : VK_FALSE; if (!chosen_draw_params) std::fprintf(stderr, "[rt] d3d12: the GPU has no shaderDrawParameters\n"); VkPhysicalDeviceVulkan12Features enable12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES, &enable11}; enable12.timelineSemaphore = VK_TRUE; enable12.drawIndirectCount = chosen12.drawIndirectCount; info.draw_indirect_count_enabled = enable12.drawIndirectCount == VK_TRUE; enable12.separateDepthStencilLayouts = VK_TRUE; info.buffer_device_address = chosen12.bufferDeviceAddress == VK_TRUE; enable12.bufferDeviceAddress = info.buffer_device_address ? VK_TRUE : VK_FALSE; info.storage_buffer_8bit = chosen12.storageBuffer8BitAccess == VK_TRUE; enable12.storageBuffer8BitAccess = info.storage_buffer_8bit; // Where the GPU has them: what the bindless set 0 needs (VulkanDeviceInfo::bindless), and the sampler features // D3D12 samplers can ask for. info.bindless = chosen12.runtimeDescriptorArray && chosen_features.shaderSampledImageArrayDynamicIndexing && chosen_features.shaderStorageImageArrayDynamicIndexing && chosen12.descriptorBindingSampledImageUpdateAfterBind && chosen12.descriptorBindingStorageImageUpdateAfterBind && chosen12.descriptorBindingStorageBufferUpdateAfterBind; info.bindless_partially_bound = info.bindless && chosen12.descriptorBindingPartiallyBound; info.sampler_anisotropy = chosen_features.samplerAnisotropy; info.sampler_mirror_clamp_to_edge = chosen12.samplerMirrorClampToEdge; info.sampler_filter_minmax = chosen12.samplerFilterMinmax; enable12.runtimeDescriptorArray = info.bindless; enable12.descriptorBindingSampledImageUpdateAfterBind = info.bindless; enable12.descriptorBindingStorageImageUpdateAfterBind = info.bindless; enable12.descriptorBindingStorageBufferUpdateAfterBind = info.bindless; enable12.descriptorBindingPartiallyBound = info.bindless_partially_bound; enable12.samplerMirrorClampToEdge = info.sampler_mirror_clamp_to_edge; enable12.samplerFilterMinmax = info.sampler_filter_minmax; info.shader_output_layer = chosen12.shaderOutputLayer == VK_TRUE; info.shader_output_viewport_index = chosen12.shaderOutputViewportIndex == VK_TRUE; enable12.shaderOutputLayer = info.shader_output_layer; enable12.shaderOutputViewportIndex = info.shader_output_viewport_index; if (!info.bindless) std::fprintf(stderr, "[rt] d3d12: the GPU lacks a descriptor-indexing feature the bindless set needs\n"); enable12.bufferDeviceAddress = VK_TRUE; info.buffer_device_address = true; std::uint32_t family_count = 0; vkGetPhysicalDeviceQueueFamilyProperties(info.physical, &family_count, nullptr); std::vector families(family_count); vkGetPhysicalDeviceQueueFamilyProperties(info.physical, &family_count, families.data()); const std::uint32_t queue_cap = max_queues_per_family(queue_test_settings); const std::uint32_t command_queue_count = std::min(queue_cap, families[info.queue_family].queueCount); std::vector priorities(16, 1.0f); std::vector queue_infos; { VkDeviceQueueCreateInfo q{VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO}; q.queueFamilyIndex = info.queue_family; q.queueCount = command_queue_count; q.pQueuePriorities = priorities.data(); queue_infos.push_back(q); } const auto preferred = leonida::pick_queue_families(families, info.queue_family); // D3D12 permits UpdateTileMappings on DIRECT, COMPUTE and COPY queues. Vulkan requires // VK_QUEUE_SPARSE_BINDING_BIT on the VkQueue passed to vkQueueBindSparse. A dedicated // async family without that capability cannot implement all D3D12 queue operations; // fall back to the graphics family when sparse buffers are supported. QueueKind still // enforces the D3D12 COPY/COMPUTE stage restrictions on the more capable family. const bool sparse_buffers = chosen_features.sparseBinding && chosen_features.sparseResidencyBuffer && chosen_features.sparseResidencyAliased; auto picked = leonida::sparse_capable_queue_families(families, preferred, sparse_buffers); if (graphics_family_only(queue_test_settings)) picked = {info.queue_family, info.queue_family, info.queue_family}; std::uint32_t compute_count = 0, copy_count = 0; if (picked.compute != info.queue_family) { info.compute_family = picked.compute; compute_count = std::min(queue_cap, families[picked.compute].queueCount); VkDeviceQueueCreateInfo q{VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO}; q.queueFamilyIndex = picked.compute; q.queueCount = compute_count; q.pQueuePriorities = priorities.data(); queue_infos.push_back(q); } if (picked.copy != info.queue_family) { info.copy_family = picked.copy; if (picked.copy != picked.compute) { copy_count = std::min(queue_cap, families[picked.copy].queueCount); VkDeviceQueueCreateInfo q{VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO}; q.queueFamilyIndex = picked.copy; q.queueCount = copy_count; q.pQueuePriorities = priorities.data(); queue_infos.push_back(q); } } VkPhysicalDeviceFeatures enable{}; enable.sparseBinding = chosen_features.sparseBinding; enable.sparseResidencyBuffer = chosen_features.sparseResidencyBuffer; enable.sparseResidencyImage2D = chosen_features.sparseResidencyImage2D; enable.sparseResidencyAliased = chosen_features.sparseResidencyAliased; info.texture_compression_bc = chosen_bc; enable.textureCompressionBC = chosen_bc ? VK_TRUE : VK_FALSE; // the game's textures are BC1-7 enable.shaderSampledImageArrayDynamicIndexing = info.bindless; enable.shaderStorageImageArrayDynamicIndexing = info.bindless; if (!chosen_features.shaderInt64) std::fprintf(stderr, "[rt] d3d12: the GPU has no shaderInt64; translated shaders (all declare Int64) will not load\n"); enable.samplerAnisotropy = info.sampler_anisotropy; enable.occlusionQueryPrecise = chosen_features.occlusionQueryPrecise; // exact D3D12 occlusion counts enable.pipelineStatisticsQuery = chosen_features.pipelineStatisticsQuery; enable.drawIndirectFirstInstance = chosen_features.drawIndirectFirstInstance; enable.multiDrawIndirect = chosen_features.multiDrawIndirect; info.draw_indirect_first_instance = enable.drawIndirectFirstInstance == VK_TRUE; info.multi_draw_indirect = enable.multiDrawIndirect == VK_TRUE; info.max_draw_indirect_count = chosen.limits.maxDrawIndirectCount; info.occlusion_query_precise = chosen_features.occlusionQueryPrecise == VK_TRUE; info.pipeline_statistics_query = chosen_features.pipelineStatisticsQuery == VK_TRUE; if (!chosen_bc) std::fprintf(stderr, "[rt] d3d12: the GPU has no BC texture support\n"); const char* conditional_extension = VK_EXT_CONDITIONAL_RENDERING_EXTENSION_NAME; // Optional: VK_EXT_host_image_copy lets WriteToSubresource/ReadFromSubresource copy on the CPU. std::uint32_t extension_count = 0; vkEnumerateDeviceExtensionProperties(info.physical, nullptr, &extension_count, nullptr); std::vector extensions(extension_count); vkEnumerateDeviceExtensionProperties(info.physical, nullptr, &extension_count, extensions.data()); info.conservative_rasterization = std::any_of(extensions.begin(), extensions.end(), [](const auto& e) { return std::strcmp(e.extensionName, VK_EXT_CONSERVATIVE_RASTERIZATION_EXTENSION_NAME) == 0; }); const bool has_host_image_copy = std::any_of(extensions.begin(), extensions.end(), [](const auto& e) { return std::strcmp(e.extensionName, VK_EXT_HOST_IMAGE_COPY_EXTENSION_NAME) == 0; }); VkPhysicalDeviceImageViewMinLodFeaturesEXT min_lod{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_VIEW_MIN_LOD_FEATURES_EXT}; if (std::any_of(extensions.begin(), extensions.end(), [](const auto& e) { return std::strcmp(e.extensionName, VK_EXT_IMAGE_VIEW_MIN_LOD_EXTENSION_NAME) == 0; })) { VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &min_lod}; vkGetPhysicalDeviceFeatures2(info.physical, &query); info.image_view_min_lod = min_lod.minLod == VK_TRUE; if (info.image_view_min_lod) { min_lod.pNext = *v13.next(); *v13.next() = &min_lod; } } const char* divisor_extension = nullptr; for (const char* name : {VK_KHR_VERTEX_ATTRIBUTE_DIVISOR_EXTENSION_NAME, VK_EXT_VERTEX_ATTRIBUTE_DIVISOR_EXTENSION_NAME}) { if (std::any_of(extensions.begin(), extensions.end(), [&](const auto& e) { return std::strcmp(e.extensionName, name) == 0; })) { divisor_extension = name; break; } } VkPhysicalDeviceVertexAttributeDivisorFeaturesKHR divisor_khr{ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VERTEX_ATTRIBUTE_DIVISOR_FEATURES_KHR}; VkPhysicalDeviceVertexAttributeDivisorFeaturesEXT divisor_ext{ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VERTEX_ATTRIBUTE_DIVISOR_FEATURES_EXT}; if (divisor_extension) { const bool is_khr = std::strcmp(divisor_extension, VK_KHR_VERTEX_ATTRIBUTE_DIVISOR_EXTENSION_NAME) == 0; VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, is_khr ? static_cast(&divisor_khr) : static_cast(&divisor_ext)}; vkGetPhysicalDeviceFeatures2(info.physical, &query); info.vertex_attribute_divisor = (is_khr ? divisor_khr.vertexAttributeInstanceRateDivisor : divisor_ext.vertexAttributeInstanceRateDivisor) == VK_TRUE; if (info.vertex_attribute_divisor) { if (is_khr) { divisor_khr.pNext = *v13.next(); *v13.next() = &divisor_khr; } else { divisor_ext.pNext = *v13.next(); *v13.next() = &divisor_ext; } } } VkPhysicalDeviceHostImageCopyFeaturesEXT host_copy{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_HOST_IMAGE_COPY_FEATURES_EXT}; if (has_host_image_copy) { VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &host_copy}; vkGetPhysicalDeviceFeatures2(info.physical, &query); } const char* host_image_copy_name = VK_EXT_HOST_IMAGE_COPY_EXTENSION_NAME; info.host_image_copy = has_host_image_copy && host_copy.hostImageCopy; if (info.host_image_copy) { host_copy.pNext = *v13.next(); // after the conditional rendering features, if any *v13.next() = &host_copy; } else { std::fprintf(stderr, "[rt] d3d12: no VK_EXT_host_image_copy; CPU texture copies use a staging submit\n"); } const auto has_device_extension = [&](const char* name) { return std::any_of(extensions.begin(), extensions.end(), [&](const auto& e) { return std::strcmp(e.extensionName, name) == 0; }); }; info.depth_range_unrestricted = has_device_extension(VK_EXT_DEPTH_RANGE_UNRESTRICTED_EXTENSION_NAME); const char* sliced_name = VK_EXT_IMAGE_SLICED_VIEW_OF_3D_EXTENSION_NAME; VkPhysicalDeviceImageSlicedViewOf3DFeaturesEXT sliced{ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_SLICED_VIEW_OF_3D_FEATURES_EXT}; if (info.robust_image_access && has_device_extension(sliced_name)) { VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &sliced}; vkGetPhysicalDeviceFeatures2(info.physical, &query); info.sliced_3d_uav = sliced.imageSlicedViewOf3D == VK_TRUE; if (info.sliced_3d_uav) { sliced.pNext = *v13.next(); *v13.next() = &sliced; } } // The pixel-shader extensions translated shaders can declare (VulkanDeviceInfo::fragment_shader_barycentric and // the two after it). Each is queried, and enabled with its feature where the GPU has it. VkPhysicalDeviceFragmentShaderBarycentricFeaturesKHR barycentric{ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_BARYCENTRIC_FEATURES_KHR}; if (has_device_extension(VK_KHR_FRAGMENT_SHADER_BARYCENTRIC_EXTENSION_NAME)) { VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &barycentric}; vkGetPhysicalDeviceFeatures2(info.physical, &query); info.fragment_shader_barycentric = barycentric.fragmentShaderBarycentric == VK_TRUE; if (info.fragment_shader_barycentric) { barycentric.pNext = *v13.next(); *v13.next() = &barycentric; } } VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT interlock{ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_INTERLOCK_FEATURES_EXT}; if (has_device_extension(VK_EXT_FRAGMENT_SHADER_INTERLOCK_EXTENSION_NAME)) { VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &interlock}; vkGetPhysicalDeviceFeatures2(info.physical, &query); info.fragment_shader_interlock = interlock.fragmentShaderPixelInterlock == VK_TRUE; if (info.fragment_shader_interlock) { interlock.fragmentShaderSampleInterlock = VK_FALSE; // the translator only declares the pixel interlock interlock.fragmentShaderShadingRateInterlock = VK_FALSE; interlock.pNext = *v13.next(); *v13.next() = &interlock; } } #ifdef VK_KHR_MAINTENANCE_8_EXTENSION_NAME VkPhysicalDeviceMaintenance8FeaturesKHR maintenance8{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_8_FEATURES_KHR}; if (has_device_extension(VK_KHR_MAINTENANCE_8_EXTENSION_NAME)) { VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &maintenance8}; vkGetPhysicalDeviceFeatures2(info.physical, &query); info.maintenance8 = maintenance8.maintenance8 == VK_TRUE; if (info.maintenance8) { maintenance8.pNext = *v13.next(); *v13.next() = &maintenance8; } } #endif #ifdef VK_KHR_MAINTENANCE_5_EXTENSION_NAME // VK_KHR_maintenance5 also supplies vkCmdBindIndexBuffer2KHR. A8 support is checked separately: only where // that format can be sampled, copied (every texture is a transfer source and destination) and is a colour // attachment the GPU can blend do we also use that format for A8 render targets. VkPhysicalDeviceMaintenance5FeaturesKHR maintenance5{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_5_FEATURES_KHR}; if (has_device_extension(VK_KHR_MAINTENANCE_5_EXTENSION_NAME)) { VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &maintenance5}; vkGetPhysicalDeviceFeatures2(info.physical, &query); VkFormatProperties a8{}; if (vkGetPhysicalDeviceFormatProperties) vkGetPhysicalDeviceFormatProperties(info.physical, VK_FORMAT_A8_UNORM_KHR, &a8); const VkFormatFeatureFlags needed = VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT | VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT | VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BLEND_BIT | VK_FORMAT_FEATURE_TRANSFER_SRC_BIT | VK_FORMAT_FEATURE_TRANSFER_DST_BIT; info.a8_render_target = maintenance5.maintenance5 == VK_TRUE && (a8.optimalTilingFeatures & needed) == needed; } #endif #ifdef VK_KHR_MAINTENANCE_10_EXTENSION_NAME VkPhysicalDeviceMaintenance10FeaturesKHR maintenance10{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_10_FEATURES_KHR}; // Vulkan 1.3 makes the 64-bit optimal tiling format features used by this path core. if (v13.core && has_device_extension(VK_KHR_MAINTENANCE_10_EXTENSION_NAME)) { VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &maintenance10}; vkGetPhysicalDeviceFeatures2(info.physical, &query); info.maintenance10 = maintenance10.maintenance10 == VK_TRUE; if (info.maintenance10) { maintenance10.pNext = *v13.next(); *v13.next() = &maintenance10; } } #endif #ifdef VK_KHR_SHADER_FMA_EXTENSION_NAME // VK_KHR_shader_fma: OpFmaKHR is a single-rounding multiply-add in SPIR-V (GLSL.std.450 Fma may round twice). // Translated shaders built with `rdna2spirv.py --fma khr` need it (index capability FMAKHR, feature // shaderFmaFloat32); when it is missing they must not be created, so use `--fma glsl` there. VkPhysicalDeviceShaderFmaFeaturesKHR shader_fma{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_FMA_FEATURES_KHR}; if (std::any_of(extensions.begin(), extensions.end(), [](const auto& e) { return std::strcmp(e.extensionName, VK_KHR_SHADER_FMA_EXTENSION_NAME) == 0; })) { VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &shader_fma}; vkGetPhysicalDeviceFeatures2(info.physical, &query); info.shader_fma = shader_fma.shaderFmaFloat32 == VK_TRUE; if (info.shader_fma) { shader_fma.pNext = *v13.next(); *v13.next() = &shader_fma; } } #endif VkPhysicalDeviceShaderClockFeaturesKHR shader_clock{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_CLOCK_FEATURES_KHR}; if (has_device_extension(VK_KHR_SHADER_CLOCK_EXTENSION_NAME)) { VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &shader_clock}; vkGetPhysicalDeviceFeatures2(info.physical, &query); info.shader_subgroup_clock = shader_clock.shaderSubgroupClock == VK_TRUE; info.shader_device_clock = shader_clock.shaderDeviceClock == VK_TRUE; if (info.shader_subgroup_clock || info.shader_device_clock) { shader_clock.pNext = *v13.next(); *v13.next() = &shader_clock; } } // What graphics PSOs may ask for: different blend state per render target, wireframe, a depth-bias clamp and // SRC1 blend factors. Enabled where the GPU has them; a PSO that needs a missing one is refused. enable.independentBlend = chosen_features.independentBlend; enable.fillModeNonSolid = chosen_features.fillModeNonSolid; enable.depthBiasClamp = chosen_features.depthBiasClamp; enable.dualSrcBlend = chosen_features.dualSrcBlend; enable.logicOp = chosen_features.logicOp; enable.depthClamp = chosen_features.depthClamp; enable.multiViewport = chosen_features.multiViewport; enable.geometryShader = chosen_features.geometryShader; // translated geometry shaders (195 in the corpus) // What translated shaders declare (the index's `features`): 64-bit integers in most of the corpus (25,803 of // 26,503 entries), doubles, 16-bit integers, clip and cull distances in a few vertex shaders, formatless image // reads and writes, gather offsets (ImageGatherExtended), LOD-clamped samples (MinLod), and the layer or viewport // a vertex shader writes (above, in Vulkan 1.2). Enabled where the GPU has them; without one, vkCreateShaderModule // reports the capability (VUID-...-pCode-08740). enable.shaderInt64 = chosen_features.shaderInt64; enable.shaderFloat64 = chosen_features.shaderFloat64; enable.shaderInt16 = chosen_features.shaderInt16; enable.shaderClipDistance = chosen_features.shaderClipDistance; enable.shaderCullDistance = chosen_features.shaderCullDistance; enable.shaderStorageImageWriteWithoutFormat = chosen_features.shaderStorageImageWriteWithoutFormat; enable.shaderStorageImageExtendedFormats = chosen_features.shaderStorageImageExtendedFormats; enable.shaderStorageImageReadWithoutFormat = chosen_features.shaderStorageImageReadWithoutFormat; enable.shaderImageGatherExtended = chosen_features.shaderImageGatherExtended; enable.shaderResourceMinLod = chosen_features.shaderResourceMinLod; // A translated pixel shader that stores to an image or does an image atomic declares that storage image without // NonWritable (1,018 of the corpus's 1,038 image-atomic shaders are pixel shaders), and Vulkan allows that outside // a compute shader only with these two features: fragmentStoresAndAtomics for the pixel stage, // vertexPipelineStoresAndAtomics for vertex and geometry shaders. Enabled where the GPU has them; a graphics PSO // whose shader needs a missing one is refused (PipelineState::create_graphics). enable.fragmentStoresAndAtomics = chosen_features.fragmentStoresAndAtomics; enable.vertexPipelineStoresAndAtomics = chosen_features.vertexPipelineStoresAndAtomics; // GetClockCalibration reads both clocks at once with calibrated timestamps (KHR, or the older EXT). const char* calibrated = nullptr; for (const char* name : {VK_KHR_CALIBRATED_TIMESTAMPS_EXTENSION_NAME, VK_EXT_CALIBRATED_TIMESTAMPS_EXTENSION_NAME}) { for (const auto& extension : extensions) if (std::strcmp(extension.extensionName, name) == 0) calibrated = name; if (calibrated) break; } info.calibrated_timestamps = calibrated != nullptr; // Switching a vsync swapchain to IMMEDIATE or FIFO_RELAXED per present (PresentX's ImmediateThresholdPercent): // the KHR extension (promoted from the EXT one, same structures) with the surface extension of the same name // on the instance, else the EXT one. Only enabled where the instance has the surface half and the GPU the feature. const char* swapchain_m1_name = nullptr; #ifdef LEONIDA_SWAPCHAIN_MAINTENANCE1 VkPhysicalDeviceSwapchainMaintenance1FeaturesEXT swapchain_m1{ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SWAPCHAIN_MAINTENANCE_1_FEATURES_EXT}; if (has_swapchain && instance_has_surface) { const auto device_has = [&](const char* name) { return std::any_of(extensions.begin(), extensions.end(), [&](const auto& e) { return std::strcmp(e.extensionName, name) == 0; }); }; if (surface_maintenance1_khr && device_has("VK_KHR_swapchain_maintenance1")) swapchain_m1_name = "VK_KHR_swapchain_maintenance1"; else if (surface_maintenance1_ext && device_has("VK_EXT_swapchain_maintenance1")) swapchain_m1_name = "VK_EXT_swapchain_maintenance1"; if (swapchain_m1_name) { VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &swapchain_m1}; vkGetPhysicalDeviceFeatures2(info.physical, &query); if (swapchain_m1.swapchainMaintenance1 == VK_TRUE) { swapchain_m1.pNext = *v13.next(); *v13.next() = &swapchain_m1; } else { swapchain_m1_name = nullptr; } } } #endif info.swapchain_maintenance1 = swapchain_m1_name != nullptr; // Optional: VK_EXT_custom_border_color lets samplers use custom float and integer border colours. const bool has_custom_border = std::any_of(extensions.begin(), extensions.end(), [](const auto& e) { return std::strcmp(e.extensionName, VK_EXT_CUSTOM_BORDER_COLOR_EXTENSION_NAME) == 0; }); VkPhysicalDeviceCustomBorderColorFeaturesEXT custom_border{ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CUSTOM_BORDER_COLOR_FEATURES_EXT}; if (has_custom_border) { VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &custom_border}; vkGetPhysicalDeviceFeatures2(info.physical, &query); } const char* custom_border_name = VK_EXT_CUSTOM_BORDER_COLOR_EXTENSION_NAME; info.custom_border_color = has_custom_border && custom_border.customBorderColors; info.custom_border_color_without_format = has_custom_border && custom_border.customBorderColorWithoutFormat; if (info.custom_border_color) { custom_border.pNext = *v13.next(); // where later feature structs go since #1706 *v13.next() = &custom_border; } else { std::fprintf(stderr, "[rt] d3d12: no VK_EXT_custom_border_color; custom sampler border colours fall back to transparent black\n"); } // Optional: VK_EXT_robustness2's nullDescriptor makes set 0's storage fallbacks null descriptors, so a store or // atomic through a null UAV (a zero T#, or one the layer refused) is dropped and a load reads zero, as on the // console (vulkan_bindless.h). Robust buffer access is selected independently for bounded indexed indirect draws. VkPhysicalDeviceRobustness2FeaturesEXT robustness2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ROBUSTNESS_2_FEATURES_EXT}; if (std::any_of(extensions.begin(), extensions.end(), [](const auto& e) { return std::strcmp(e.extensionName, VK_EXT_ROBUSTNESS_2_EXTENSION_NAME) == 0; })) { VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &robustness2}; vkGetPhysicalDeviceFeatures2(info.physical, &query); info.null_descriptor = robustness2.nullDescriptor == VK_TRUE; #ifdef VK_KHR_MAINTENANCE_5_EXTENSION_NAME info.robust_index_view = leonida::can_enable_robust_index_view( info.physical, vkGetPhysicalDeviceProperties2, info.draw_indirect_first_instance && maintenance5.maintenance5, chosen_features.robustBufferAccess && robustness2.robustBufferAccess2, info.bindless); #endif if (info.null_descriptor || info.robust_index_view) { robustness2 = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ROBUSTNESS_2_FEATURES_EXT}; robustness2.nullDescriptor = info.null_descriptor; robustness2.robustBufferAccess2 = info.robust_index_view; enable.robustBufferAccess = info.robust_index_view; robustness2.pNext = *v13.next(); *v13.next() = &robustness2; } } #ifdef VK_KHR_MAINTENANCE_5_EXTENSION_NAME if (info.a8_render_target || info.robust_index_view) { maintenance5.pNext = *v13.next(); *v13.next() = &maintenance5; } #endif if (!info.null_descriptor) std::fprintf(stderr, "[rt] d3d12: no VK_EXT_robustness2 nullDescriptor; stores through null UAVs land in " "storage fallback images instead of being dropped\n"); // Optional: VK_EXT_external_memory_host lets OpenExistingHeapFromAddress import the caller's committed memory as // the heap's backing, so the GPU reads what the CPU writes there without a copy. if (std::any_of(extensions.begin(), extensions.end(), [](const auto& e) { return std::strcmp(e.extensionName, VK_EXT_EXTERNAL_MEMORY_HOST_EXTENSION_NAME) == 0; })) { VkPhysicalDeviceExternalMemoryHostPropertiesEXT host_memory{ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_MEMORY_HOST_PROPERTIES_EXT}; VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &host_memory}; vkGetPhysicalDeviceProperties2(info.physical, &properties); info.host_pointer_alignment = host_memory.minImportedHostPointerAlignment; } VkDeviceCreateInfo device_info{VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, &enable12}; device_info.queueCreateInfoCount = std::uint32_t(queue_infos.size()); device_info.pQueueCreateInfos = queue_infos.data(); device_info.pEnabledFeatures = &enable; info.features = enable; std::vector device_extensions; v13.add_extensions(device_extensions); if (info.depth_range_unrestricted) device_extensions.push_back(VK_EXT_DEPTH_RANGE_UNRESTRICTED_EXTENSION_NAME); info.pipeline_creation_feedback = v13.core || has_device_extension(VK_EXT_PIPELINE_CREATION_FEEDBACK_EXTENSION_NAME); if (trace_pipeline_compile() && !v13.core && info.pipeline_creation_feedback) device_extensions.push_back(VK_EXT_PIPELINE_CREATION_FEEDBACK_EXTENSION_NAME); if (info.conservative_rasterization) device_extensions.push_back(VK_EXT_CONSERVATIVE_RASTERIZATION_EXTENSION_NAME); if (info.image_view_min_lod) device_extensions.push_back(VK_EXT_IMAGE_VIEW_MIN_LOD_EXTENSION_NAME); if (info.vertex_attribute_divisor) device_extensions.push_back(divisor_extension); if (info.conditional_rendering) device_extensions.push_back(conditional_extension); if (info.host_image_copy) device_extensions.push_back(host_image_copy_name); if (info.sliced_3d_uav) device_extensions.push_back(sliced_name); if (info.fragment_shader_barycentric) device_extensions.push_back(VK_KHR_FRAGMENT_SHADER_BARYCENTRIC_EXTENSION_NAME); if (info.fragment_shader_interlock) device_extensions.push_back(VK_EXT_FRAGMENT_SHADER_INTERLOCK_EXTENSION_NAME); #ifdef VK_KHR_MAINTENANCE_8_EXTENSION_NAME if (info.maintenance8) device_extensions.push_back(VK_KHR_MAINTENANCE_8_EXTENSION_NAME); #endif // Under its own guard only: headers or a driver without VK_KHR_maintenance8 still have the A8 path, and // a8_render_target is never set without this extension being enabled. #ifdef VK_KHR_MAINTENANCE_5_EXTENSION_NAME if (info.a8_render_target || info.robust_index_view) device_extensions.push_back(VK_KHR_MAINTENANCE_5_EXTENSION_NAME); #endif #ifdef VK_KHR_MAINTENANCE_10_EXTENSION_NAME if (info.maintenance10) device_extensions.push_back(VK_KHR_MAINTENANCE_10_EXTENSION_NAME); #endif #ifdef VK_KHR_SHADER_FMA_EXTENSION_NAME if (info.shader_fma) device_extensions.push_back(VK_KHR_SHADER_FMA_EXTENSION_NAME); #endif if (info.shader_subgroup_clock || info.shader_device_clock) device_extensions.push_back(VK_KHR_SHADER_CLOCK_EXTENSION_NAME); if (calibrated) device_extensions.push_back(calibrated); // VK_KHR_swapchain requires VK_KHR_surface on the instance (VUID-vkCreateDevice-ppEnabledExtensionNames-01387). if (has_swapchain && instance_has_surface) device_extensions.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME); if (swapchain_m1_name) device_extensions.push_back(swapchain_m1_name); if (info.mesh_shader) device_extensions.push_back(VK_EXT_MESH_SHADER_EXTENSION_NAME); if (info.transform_feedback) device_extensions.push_back(VK_EXT_TRANSFORM_FEEDBACK_EXTENSION_NAME); if (info.ray_tracing) { device_extensions.push_back(VK_KHR_ACCELERATION_STRUCTURE_EXTENSION_NAME); device_extensions.push_back(VK_KHR_DEFERRED_HOST_OPERATIONS_EXTENSION_NAME); device_extensions.push_back(VK_KHR_RAY_QUERY_EXTENSION_NAME); } info.presentation = has_swapchain && instance_has_surface; info.swapchain_colorspace = info.presentation && swapchain_colorspace_enabled; if (info.custom_border_color) device_extensions.push_back(custom_border_name); if (info.null_descriptor || info.robust_index_view) device_extensions.push_back(VK_EXT_ROBUSTNESS_2_EXTENSION_NAME); if (info.host_pointer_alignment) device_extensions.push_back(VK_EXT_EXTERNAL_MEMORY_HOST_EXTENSION_NAME); leonida::DeviceFaultFeatures fault_features; const bool aftermath = leonida::aftermath::enable(); // already on, before the instance: see above char device_fault[2]{}; if (GetEnvironmentVariableA("LEONIDA_DEVICE_FAULT", device_fault, sizeof(device_fault)) == 1 && device_fault[0] == '1') { info.device_fault_diagnostics = true; const auto fault = fault_features.enable(info.physical, vkGetPhysicalDeviceFeatures2, extensions, device_extensions, device_info, {true, true, leonida::aftermath::extra_config_flags()}); info.device_fault_info = fault.fault; info.device_checkpoints = fault.checkpoints; info.device_diagnostics_config = fault.diagnostics_config; } else if (aftermath) { // The diagnostics config alone: shader debug info, resource tracking and automatic checkpoints in the dump. const auto fault = fault_features.enable(info.physical, vkGetPhysicalDeviceFeatures2, extensions, device_extensions, device_info, {false, true, leonida::aftermath::extra_config_flags()}); info.device_diagnostics_config = fault.diagnostics_config; } if (aftermath && !info.device_diagnostics_config) std::fprintf(stderr, "[rt] aftermath: VK_NV_device_diagnostics_config unavailable; the dump has no shader " "debug info, resource tracking or checkpoints\n"); device_info.enabledExtensionCount = std::uint32_t(device_extensions.size()); device_info.ppEnabledExtensionNames = device_extensions.empty() ? nullptr : device_extensions.data(); if (vkCreateDevice(info.physical, &device_info, nullptr, &owned.device) != VK_SUCCESS) return fail("vkCreateDevice failed"); info.device = owned.device; owned.destroy_device = reinterpret_cast(vkGetDeviceProcAddr(owned.device, "vkDestroyDevice")); info.command_queues.resize(command_queue_count); const auto get_queue = reinterpret_cast(vkGetDeviceProcAddr(owned.device, "vkGetDeviceQueue")); for (std::uint32_t i = 0; i < command_queue_count; ++i) get_queue(owned.device, info.queue_family, i, &info.command_queues[i]); if (compute_count) { // Copies on the async-compute family split its queues with the compute queues: one VkQueue per live queue. const bool split = info.copy_family == info.compute_family && compute_count > 1; const std::uint32_t for_compute = split ? compute_count / 2 : compute_count; for (std::uint32_t i = 0; i < compute_count; ++i) { VkQueue q = VK_NULL_HANDLE; get_queue(owned.device, info.compute_family, i, &q); (i < for_compute ? info.compute_queues : info.copy_queues).push_back(q); } if (info.copy_family == info.compute_family && !split) info.copy_family = UINT32_MAX; } for (std::uint32_t i = 0; i < copy_count; ++i) { VkQueue q = VK_NULL_HANDLE; get_queue(owned.device, info.copy_family, i, &q); info.copy_queues.push_back(q); } info.queue = info.command_queues[0]; info.max_push_constants_size = chosen.limits.maxPushConstantsSize; info.push_constants_need_fallback = (info.max_push_constants_size < 144); std::fprintf(stderr, "[rt] d3d12: Vulkan device: %s (maxPushConstantsSize: %u bytes)\n", chosen.deviceName, chosen.limits.maxPushConstantsSize); std::fprintf(stderr, "[rt] d3d12: subgroup sizes %u..%u (default %u), requirable in stages 0x%x, subgroupSizeControl %s, " "computeFullSubgroups %s\n", info.subgroup.min_size, info.subgroup.max_size, info.subgroup.default_size, unsigned(info.subgroup.required_stages), info.subgroup.subgroup_size_control ? "on" : "off", info.subgroup.compute_full_subgroups ? "on" : "off"); if (info.push_constants_need_fallback) { std::fprintf(stderr, "[rt] d3d12: WARNING: GPU maxPushConstantsSize (%u bytes) is below the 144 bytes required by " "the shader contract; uniform-buffer fallback required for the 16-byte tail\n", chosen.limits.maxPushConstantsSize); } auto* device = new Device(info); device->own(owned); // destroyed with the device from here on, even on failure if (!device->ok()) { device->Release(); return E_FAIL; } return hand_out(device, riid, out); } bool has_global_realtime_privilege() { const int override_state = g_global_realtime_privilege_override.load(std::memory_order_relaxed); if (override_state >= 0) return override_state != 0; HANDLE token = nullptr; if (!OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, TRUE, &token)) { // Fall back to the process token only when the thread is not impersonating (ERROR_NO_TOKEN); fail closed on // ERROR_CANT_OPEN_ANONYMOUS or any other thread-token error so an impersonated caller cannot inherit the // process token's privilege. if (GetLastError() != ERROR_NO_TOKEN || !OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token)) return false; } LUID luid{}; BOOL enabled = FALSE; if (LookupPrivilegeValueW(nullptr, L"SeIncreaseBasePriorityPrivilege", &luid)) { PRIVILEGE_SET set{}; set.PrivilegeCount = 1; set.Control = PRIVILEGE_SET_ALL_NECESSARY; set.Privilege[0].Luid = luid; set.Privilege[0].Attributes = SE_PRIVILEGE_ENABLED; if (!PrivilegeCheck(token, &set, &enabled)) enabled = FALSE; } CloseHandle(token); return enabled != FALSE; } void set_global_realtime_privilege_override_for_test(int state) { g_global_realtime_privilege_override.store(state, std::memory_order_relaxed); } HRESULT create_console_descriptor_heap(ID3D12Device* device, const D3D12_DESCRIPTOR_HEAP_DESC* desc, D3D12_GPU_VIRTUAL_ADDRESS console_address, std::uint64_t console_size, REFIID riid, void** out) { if (out) *out = nullptr; if (!device || !desc) return E_INVALIDARG; // No output: a capability check, as CreateDescriptorHeap does. if (!out) return S_FALSE; if ((desc->Flags & ~D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE) || desc->NodeMask > 1 || ((desc->Flags & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE) && (desc->Type == D3D12_DESCRIPTOR_HEAP_TYPE_RTV || desc->Type == D3D12_DESCRIPTOR_HEAP_TYPE_DSV))) { return E_INVALIDARG; } ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); auto* d = Device::from(real ? real : device); if (!d) return E_INVALIDARG; return d->create_console_descriptor_heap(desc, console_address, console_size, riid, out); } UnboundTsharpStats unbound_tsharp_stats() { return unbound_tsharp_tracker().stats(); } void reset_unbound_tsharp_stats() { unbound_tsharp_tracker().reset(); } void note_refused_tsharp_for_test(std::uint64_t heap_va, std::size_t offset, const std::array& words, const char* why) { leonida::gfx10::ImageWords w; std::memcpy(w.data(), words.data(), sizeof(w)); unbound_tsharp_tracker().note(heap_va, offset, w, why); } TitleImage test_bind_title_image(ID3D12Device* device, const std::array& words, const char** why) { if (!device) return TitleImage::not_tsharp; ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); Device* d = Device::from(real ? real : device); if (!d) return TitleImage::not_tsharp; leonida::gfx10::ImageWords w; std::memcpy(w.data(), words.data(), sizeof(w)); return bind_title_image(d->state(), w, why); } std::uint64_t resource_image_address(ID3D12Resource* resource) { if (!resource) return 0; const Resource* r = Resource::from(resource); return r ? r->image_address() : 0; } std::filesystem::path configured_shader_directory(std::string* error, const std::filesystem::path& config) { return leonida::shader_paths::configured(error, config); } } // namespace rt::d3d12