diff --git a/src/direct_compute_cache.cpp b/src/direct_compute_cache.cpp index 8cceb9747..1df7d88a1 100644 --- a/src/direct_compute_cache.cpp +++ b/src/direct_compute_cache.cpp @@ -778,9 +778,10 @@ DirectGraphicsPair prepare_direct_graphics(std::string_view a, std::string_view if (cache_hit) { try { Reader in{payload}; + const auto physical_table_srvs = in.word(); auto vertex = decode(in.take(in.word())); auto elements = vertex_layout(effective_layout(vertex), vertex); - return verified({std::move(vertex), decode(in.remaining), std::move(elements), targets}); + return verified({std::move(vertex), decode(in.remaining), std::move(elements), targets, physical_table_srvs}); } catch (const UnsupportedComputeShader &) { throw; } catch (const std::runtime_error &) { @@ -950,6 +951,7 @@ DirectGraphicsPair prepare_direct_graphics(std::string_view a, std::string_view } pair.input_layout = vertex_layout(effective_layout(pair.vertex), pair.vertex); if (!root.empty()) { + const bool raw_fixed = fixed_entry && !reflected && a.substr(0, 4) != "DXBC" && b.substr(0, 4) != "DXBC"; for (auto *stage : {&pair.vertex, &pair.pixel}) { const bool vertex = stage == &pair.vertex; const auto visibility = vertex ? D3D12_SHADER_VISIBILITY_VERTEX : D3D12_SHADER_VISIBILITY_PIXEL; @@ -981,8 +983,10 @@ DirectGraphicsPair prepare_direct_graphics(std::string_view a, std::string_view const auto slot = binding.byte_offset / 32; const auto kind = compute_uav(binding.kind) ? D3D12_DESCRIPTOR_RANGE_TYPE_UAV : D3D12_DESCRIPTOR_RANGE_TYPE_SRV; - uint64_t next = 0; + uint64_t next = 0, extent = 0; bool found = false; + bool resource_table = false; + bool in_cbv = false; for (unsigned i = 0; i < p.DescriptorTable.NumDescriptorRanges; ++i) { const auto &range = p.DescriptorTable.pDescriptorRanges[i]; const uint64_t first = @@ -990,6 +994,9 @@ DirectGraphicsPair prepare_direct_graphics(std::string_view a, std::string_view ? next : range.OffsetInDescriptorsFromTableStart; next = first + range.NumDescriptors; + extent = (std::max)(extent, next); + resource_table |= range.RangeType != D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER; + in_cbv |= first <= slot && slot < next && range.RangeType == D3D12_DESCRIPTOR_RANGE_TYPE_CBV; // Scalar buffer loads also consume CBV table records. The // resolver supplies a raw SRV over the recorded CBV window. if (first <= slot && slot < next && (kind == range.RangeType || @@ -1014,6 +1021,22 @@ DirectGraphicsPair prepare_direct_graphics(std::string_view a, std::string_view found |= used; } apply_scalar_table_layout(binding, p.DescriptorTable); + // A raw fixed stage has the guest table address and uses physical + // byte offsets. The runtime must prove an outlying read against + // the bound heap record before using it. The declared range type + // does not reach the shader, so a texture read from a CBV range + // slot gets the same proof: the record must be a typed SRV. + if (!found && raw_fixed && resource_table && extent && (slot >= extent || in_cbv) && + binding.shader_register < 32 && binding.array_count == 1) { + const bool fixed_buffer = binding.kind == ComputeViewKind::buffer_srv && !binding.dynamic_scalar_load && + binding.required_bytes && binding.required_bytes <= (16u << 20); + const bool texture = binding.kind == ComputeViewKind::texture_srv && + (binding.image_dimension <= 2 || binding.image_dimension == 5); + if (fixed_buffer || texture) { + pair.physical_table_srvs |= std::uint32_t{1} << binding.shader_register; + found = true; + } + } if (!found) throw UnsupportedComputeShader(std::string("graphics descriptor range does not cover resource: ") + (vertex ? "VS" : "PS") + " root " + std::to_string(binding.root_parameter) + @@ -1024,6 +1047,7 @@ DirectGraphicsPair prepare_direct_graphics(std::string_view a, std::string_view if (write_cache && !cache.empty()) { auto vertex = encode(pair.vertex); payload.clear(); + word(payload, pair.physical_table_srvs); word(payload, static_cast(vertex.size())); payload += vertex; payload += encode(pair.pixel); @@ -1326,6 +1350,8 @@ std::optional format_graphics_runtime_manifest(const DirectGraphics } else { return std::nullopt; } + if (pair.physical_table_srvs & (std::uint32_t{1} << i)) + srv_lines << "tablecheck " << i << ' ' << (b.kind == ComputeViewKind::buffer_srv ? b.required_bytes : 0) << '\n'; } for (unsigned j = 0; j < uav_count; ++j) { const auto &b = bindings.views[bindings.srv_count + j]; @@ -1363,7 +1389,8 @@ std::optional format_graphics_runtime_manifest(const DirectGraphics params = (std::max)(params, out.index / 4 + 1); std::ostringstream out; - out << "x2w-manifest " << (fixed_stream ? 3 : uav_count ? 2 : 1) << "\nud " << (total_constants ? total_constants : 1u) << '\n'; + const unsigned version = pair.physical_table_srvs ? 4 : fixed_stream ? 3 : uav_count ? 2 : 1; + out << "x2w-manifest " << version << "\nud " << (total_constants ? total_constants : 1u) << '\n'; for (const auto &e : pair.input_layout) out << "fixedvb " << e.offset << ' ' << e.format << '\n'; if (!total_constants) { diff --git a/src/gfx1013_compute_native.h b/src/gfx1013_compute_native.h index dd20f9d62..c66e49a0d 100644 --- a/src/gfx1013_compute_native.h +++ b/src/gfx1013_compute_native.h @@ -93,6 +93,8 @@ struct ComputeViewBinding { enum class ScalarTable { unknown, reflected_cbv, declared_cbv, srv }; ScalarTable scalar_table = ScalarTable::unknown; bool requires_identity_dst_sel = false; + // A graphics scalar buffer load with an SGPR offset has no fixed byte bound. + bool dynamic_scalar_load = false; }; inline bool runtime_root_buffer_uav(const ComputeViewBinding &binding) { return binding.kind == ComputeViewKind::root_buffer_uav && binding.byte_offset == 0 && @@ -216,6 +218,7 @@ struct DirectGraphicsPair { std::vector input_layout; // GuestShaderStage::target_components of the pixel stage: the target types an RTV variant asked for. std::array target_components{}; + std::uint32_t physical_table_srvs = 0; GraphicsConstantLayout constant_layout() const { GraphicsConstantLayout layout; for (auto *stage : {&vertex, &pixel}) diff --git a/src/gfx1013_direct_compute.inl b/src/gfx1013_direct_compute.inl index 749b71c80..8230e6449 100644 --- a/src/gfx1013_direct_compute.inl +++ b/src/gfx1013_direct_compute.inl @@ -518,7 +518,8 @@ struct DirectCompute { } std::set> read_write_raw_views; string resource(const Inst &i, const State &s, unsigned base, ComputeViewKind kind, unsigned bytes, - unsigned *bound_register = nullptr, bool requires_identity_dst_sel = false) { + unsigned *bound_register = nullptr, bool requires_identity_dst_sel = false, + bool scalar_load = false) { const auto &symbol = s.at(base); const bool indexed = symbol.type == Symbol::Type::indexed_descriptor; if (indexed && symbol.value == compute_resource_heap) @@ -544,6 +545,9 @@ struct DirectCompute { if (requires_identity_dst_sel) for (unsigned j = 0; j < count; ++j) it[j].requires_identity_dst_sel = true; + if (graphics_input && scalar_load && (i.b >> 25) != 125) + for (unsigned j = 0; j < count; ++j) + it[j].dynamic_scalar_load = true; if (bound_register) *bound_register = it->shader_register; const bool raw = kind == ComputeViewKind::raw_buffer_uav || kind == ComputeViewKind::buffer_srv || kind == ComputeViewKind::raw_vector_srv || kind == ComputeViewKind::byte_window_srv || @@ -995,7 +999,8 @@ struct DirectCompute { refuse(i.pc, "scalar load exceeds synthesized descriptor byte bound"); h = root_buffer_handle(low.value, span); } else - h = resource(i, s, i.src[0], ComputeViewKind::buffer_srv, so == 125 ? off + 4 * n : 4); + h = resource(i, s, i.src[0], ComputeViewKind::buffer_srv, so == 125 ? off + 4 * n : 4, + nullptr, false, true); auto addr = so == 125 ? to_string(off) : ir.binary("and", ir.binary("add", operand32(i, so, limit), to_string(off)), "4294967292"); for (unsigned j = 0; j < n; j += 4) { diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index d35f13b08..be788172d 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -159,7 +159,13 @@ const char* pixel_uav_view(ID3D12Device* device, const D3D12_RESOURCE_DESC& reso } struct Translation { - struct Srv { int kind, source, a, b; UINT expected_stride{}; }; // kind 0 buffer, 1 2D texture, 2 2D array, 3 3D texture, 4 1D texture, 5 cube; source 0 table(param a, byte b), 1 vertex stream a, 2 root parameter a + // kind 0 buffer, 1 2D texture, 2 2D array, 3 3D texture, 4 1D texture, 5 cube. + // source 0 table (param a, byte b), 1 vertex stream a, 2 root parameter a. + struct Srv { + int kind, source, a, b; + UINT expected_stride{}; + std::optional physical_span; // Required CBV bytes, or zero for a texture SRV. + }; enum UdKind { rect, base_vertex, start_instance, root_constant, stride, mrt_bits, d16_unorm16, desc_word3 }; struct Ud { int kind, a, b; }; int state = 0; // 1 ready, 2 unavailable @@ -169,6 +175,7 @@ struct Translation { #endif x2w_startup::ManifestRetry manifest_retry; // Only an absent manifest can become ready on a later draw. std::vector srvs; + bool physical_tables = false; std::vector uavs; // manifest 'uav N tex2d table P O' (#1996 F): u0.. after the SRVs std::vector uds; std::vector fixed_stream; @@ -711,6 +718,7 @@ void load_translation(Translation& tr, const std::string& rtv_request = {}, std: tr.manifest_retry.found(); bool matched_rtv = false; bool fixed_manifest = false; + bool physical_manifest = false; for (std::size_t at = 0; at < manifest.size();) { std::size_t end = manifest.find('\n', at); if (end == std::string::npos) end = manifest.size(); @@ -727,13 +735,16 @@ void load_translation(Translation& tr, const std::string& rtv_request = {}, std: matched_rtv = true; } else if (line == "x2w-manifest 3") { fixed_manifest = true; + } else if (line == "x2w-manifest 4") { + physical_manifest = true; } else if (line == "fixedrectgs") { if (!fixed_manifest) return; tr.fixed_rectangle_on_disk = true; } else if (line.compare(0, 8, "fixedvb ") == 0) { unsigned offset, format; char extra; - if (!fixed_manifest || std::sscanf(line.c_str(), "fixedvb %u %u %c", &offset, &format, &extra) != 2 || + if ((!fixed_manifest && !physical_manifest) || + std::sscanf(line.c_str(), "fixedvb %u %u %c", &offset, &format, &extra) != 2 || offset >= 2048 || tr.fixed_stream.size() >= 32 || (format != DXGI_FORMAT_R8_UNORM && format != DXGI_FORMAT_R8G8_UNORM && format != DXGI_FORMAT_R8G8B8A8_UNORM && format != DXGI_FORMAT_R32G32_UINT && format != DXGI_FORMAT_R32G32B32_UINT && @@ -742,6 +753,7 @@ void load_translation(Translation& tr, const std::string& rtv_request = {}, std: return; tr.fixed_stream.push_back({"X2W_RAW_VERTEX", offset, static_cast(format), 0, offset, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0}); + fixed_manifest = true; } else if (line.compare(0, 13, "x2w-manifest ") == 0 && line != "x2w-manifest 1" && line != "x2w-manifest 2") { // Version 2 adds `uav` lines. Each one is bound (a pixel-stage tex2d store) or refused by name below, // so a translation whose stores would be silently skipped is never drawn (#1723). @@ -770,6 +782,18 @@ void load_translation(Translation& tr, const std::string& rtv_request = {}, std: !srv.expected_stride || srv.expected_stride % 4 || srv.expected_stride > 2048) return; } if (static_cast(i) == tr.srvs.size()) tr.srvs.push_back(srv); + } else if (line.compare(0, 11, "tablecheck ") == 0) { + unsigned index, span; + char extra; + if (!physical_manifest || std::sscanf(line.c_str(), "tablecheck %u %u %c", &index, &span, &extra) != 2 || + index >= tr.srvs.size()) + return; + auto& srv = tr.srvs[index]; + if (srv.physical_span || srv.source != 0 || srv.a < 0 || srv.a >= 16 || srv.b < 0 || srv.b % 32 || + srv.expected_stride || (srv.kind == 0 ? !span || span % 4 || span > (16u << 20) : span || srv.kind > 4)) + return; + srv.physical_span = span; + tr.physical_tables = true; } else if (line.compare(0, 6, "wmask ") == 0) { if (!tr.write_masks.read_manifest_line(line)) { log("x2w-draw invalid write mask manifest line for %016llx: %s", tr.key, line.c_str()); @@ -797,7 +821,7 @@ void load_translation(Translation& tr, const std::string& rtv_request = {}, std: return; } } - if (fixed_manifest != !tr.fixed_stream.empty()) return; + if (fixed_manifest != !tr.fixed_stream.empty() || physical_manifest != tr.physical_tables) return; if (matched_rtv != !rtv_request.empty()) { log("x2w-draw RTV manifest missing for %016llx", tr.key); return; @@ -3636,6 +3660,14 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI ReleaseSRWLockExclusive(&draw_lock); return false; } + if (tr->physical_tables && (indirect || !bound->guest_root || bound->guest_root != pass.root)) { + const char* reason = indirect ? "physical table reads require a direct draw" + : "physical table reads require the guest pipeline's root signature"; + if (indirect) indirect->set_refusal(reason, indirect_refusal_code::unsupported_resource_or_entry); + note_draw_refusal(tr->key, "physical_table_root_refused", reason); + ReleaseSRWLockExclusive(&draw_lock); + return false; + } const bool fixed_stream = !tr->fixed_stream.empty(); D3D12_VERTEX_BUFFER_VIEW fixed_view{}; ID3D12Resource* fixed_resource = nullptr; @@ -3801,6 +3833,17 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI UINT indexed_vertices = UINT_MAX; for (UINT i = 0; i < n; ++i) { const Translation::Srv& srv = tr->srvs[i]; + const auto refuse_physical = [&](const char* reason) { + note_draw_refusal(tr->key, "physical_table_view_refused", reason); + static LONG refused; + if (first_calls(refused, 32)) + log("x2w-draw %016llx srv %u physical table %d byte %d refused: %s", tr->key, i, srv.a, srv.b, reason); + ReleaseSRWLockExclusive(&draw_lock); + return false; + }; + if (srv.physical_span && (static_cast(srv.a) >= pass.root->size() || + (*pass.root)[srv.a].type != D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE)) + return refuse_physical("parameter is not a descriptor table"); const D3D12_CPU_DESCRIPTOR_HANDLE dest{draw_heap->GetCPUDescriptorHandleForHeapStart().ptr + SIZE_T{first + i} * draw_heap_increment}; u64 address = 0, offset = 0; std::size_t bytes = 0; @@ -3836,8 +3879,12 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI const auto dimension = translated_view_dimension(srv.kind); // A texture: the title's descriptor memory carries the id of the view it created there. ViewRecord record{}; + bool materialized = false; bool known = false; - if (words[0] == view_token_magic) known = token_view(words, record); + if (words[0] == view_token_magic) known = token_view(words, record, srv.physical_span ? &materialized : nullptr); + if (srv.physical_span && (!known || !materialized || record.slot != 18 || + record.desc_bytes < ViewRecord::srv_desc_bytes)) + return refuse_physical("missing typed texture SRV record"); Wrapper* resource = known ? as_wrapper(reinterpret_cast(record.resource)) : nullptr; D3D12_SHADER_RESOURCE_VIEW_DESC desc{}; desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; @@ -3886,6 +3933,12 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI if (pass.bound_targets[t] == tex) return true; return pass.bound_depth == tex && pass.depth_view_writable; }; + if (srv.physical_span && (!texture || desc.ViewDimension != dimension || + !x2w_view_dimension::fits(18, desc.ViewDimension, mismatch_resource.Dimension) || + mismatch_resource.SampleDesc.Count != 1 || desc.Format == DXGI_FORMAT_UNKNOWN || + x2w_view_dimension::typeless(desc.Format) || x2w_view_dimension::depth_format(desc.Format) || + integer_target_format(desc.Format) || aliases_writable_target(texture))) + return refuse_physical("texture SRV does not match the shader or overlaps a written target"); if (indirect && (!texture || record.slot != 18 || aliases_writable_target(texture))) { D3D12_SHADER_RESOURCE_VIEW_DESC title_view{}; const bool described = record.desc_bytes >= 40; @@ -3932,6 +3985,7 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI ReleaseSRWLockExclusive(&draw_lock); return false; } + if (srv.physical_span && !texture) return refuse_physical(mismatch_reason); x2w_local::BindingFacts facts; facts.texture = facts.from_table = true; facts.entry_readable = entry_ok; @@ -4010,7 +4064,7 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI std::memcpy(&address, record.desc, 8); std::memcpy(&size, record.desc + 8, 4); bytes = size; - } else if (record.slot == 18 && record.desc_bytes >= 40) { + } else if (!srv.physical_span && record.slot == 18 && record.desc_bytes >= 40) { D3D12_SHADER_RESOURCE_VIEW_DESC view; std::memcpy(&view, record.desc, 40); Wrapper* resource = as_wrapper(reinterpret_cast(record.resource)); @@ -4024,6 +4078,11 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI } } } + if (srv.physical_span) { + if (!buffer_token_known || !address || bytes < *srv.physical_span) + return refuse_physical("missing CBV record or insufficient CBV span"); + bytes = *srv.physical_span; + } if (srv.source == 0 && words[0] != view_token_magic && entry) { // A hardware buffer descriptor the title wrote itself: base address, stride and record count. address = words[0] | (static_cast(words[1] & 0xffff) << 32); @@ -4115,6 +4174,7 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI ID3D12Resource* chunk = nullptr; const bool readable_range = address && bytes && readable_window(address, bytes) >= bytes; bool have = readable_range && frame_copy(self, address, bytes, &offset, &chunk); + if (srv.physical_span && !have) return refuse_physical("CBV range could not be copied"); if (have) trace_compute_output_use(self, OutputUse::shader_guest_read, "graphics-guest-upload-copied", nullptr, address, 0, bytes, tr->key); // Experiment (X2W_DRAW_NULL_IDENTITY=1): an empty buffer slot reads as repeated identity diff --git a/tests/native_fixed_graphics_psi1_check.py b/tests/native_fixed_graphics_psi1_check.py index 636067a8b..08ef6983b 100644 --- a/tests/native_fixed_graphics_psi1_check.py +++ b/tests/native_fixed_graphics_psi1_check.py @@ -28,6 +28,15 @@ def root_signature(*description): TABLE_ROOT = root_signature(2, 1, 24, 0, 68, 0, 0, 0, 36, 1, 44, 0, 1, 0, 0, 0, 0xffffffff) +SAMPLER_ROOT = root_signature(2, 1, 24, 0, 68, 0, + 0, 0, 36, 1, 44, + 3, 1, 0, 0, 0, 0xffffffff) +CBV_ROOT = root_signature(2, 1, 24, 0, 68, 0, + 0, 0, 36, 1, 44, + 2, 1, 0, 0, 0, 0xffffffff) +UAV_ROOT = root_signature(2, 1, 24, 0, 68, 0, + 0, 0, 36, 1, 44, + 1, 1, 0, 0, 0, 0xffffffff) def interpolate(attr, channel, op, dst, src): @@ -57,6 +66,22 @@ def packed_xy_pixel(prefix=()): return words(*prefix, 0x7E000CF9, 0x00040601, 0xF800180F, 0, END) +def table_pixel(offset, cbv_offset=16): + # Read a scalar window from a physical slot of a descriptor table. + return words(0xBE890380, 0xF4080304, 0xFA000000 | offset, 0xBF8CC07F, + 0xF4280406, 0xFA000000 | cbv_offset, 0xBF8CC07F, 0x7E080210, + 0xF800180F, 0x04040404, END) + + +def table_texture_program(offset=64): + # Sample a 2D image descriptor at a physical byte offset of root table 0. + # The A16 coordinate is the packed XY in v1. The table is one SGPR (s8), so + # s9 must be zero before s[8:9] is a bound table address (as in table_pixel). + return words(0xBE890380, 0xf40c0404, 0xfa000000 | offset, 0xbf8cc07f, + 0xf0000f08, 0x40040401, 0xbf8c3f70, + 0xf800180f, 0x07060504, END) + + def main(compiler, sdk): compiler, sdk = pathlib.Path(compiler), pathlib.Path(sdk) with tempfile.TemporaryDirectory() as tmp: @@ -64,10 +89,11 @@ def main(compiler, sdk): cache = base / "cache" def compile_case(name, pixel, entry, expected=None, expect_hit=None, *, case_cache=cache, vertex_code=VS, - root=ROOT): + root=ROOT, fixed=True): requests = base / (name + "-requests") output = base / (name + "-output") - key = publish(requests, pixel, vertex_code, root, slot57_inputs=entry) + entry_type = {"slot57_inputs": entry} if fixed else {"ps_inputs": (entry[0], entry[0])} + key = publish(requests, pixel, vertex_code, root, **entry_type) result = subprocess.run( [compiler, sdk, case_cache, "gfx1013-container-pair", "--requests", requests, output], capture_output=True, text=True) @@ -103,6 +129,17 @@ def compile_case(name, pixel, entry, expected=None, expect_hit=None, *, case_cac compile_case("wqm-after-vector-write", center_pixel((*save_primitive, 0x7E0802F2, *enter_wqm)), (2, 1), expected="whole-quad mode requires an unmodified pixel entry mask", root=TABLE_ROOT) + for hit in (0, 1): + key, output = compile_case("physical-cbv", table_pixel(64), (2, 1), root=TABLE_ROOT, expect_hit=hit) + manifest = (output / f"{key}.txt").read_text().splitlines() + assert manifest[0] == "x2w-manifest 4" and "srv 0 buf table 0 64" in manifest, manifest + assert "tablecheck 0 32" in manifest, manifest + compile_case("ordinary-table-slot", table_pixel(0), (2, 1), root=TABLE_ROOT) + compile_case("physical-cbv-no-fixed-entry", table_pixel(64), (2, 1), root=TABLE_ROOT, fixed=False, + expected="graphics descriptor range does not cover resource") + compile_case("physical-cbv-sampler-table", table_pixel(64), (2, 1), root=SAMPLER_ROOT, + expected="graphics descriptor range does not cover resource") + # The reviewed interface uses ADDR 0x302 for this captured 0x8002 mask. # Without a sidecar the raw address still allocates the packed XY VGPR. key, output = compile_case("packed", packed_position_pixel(), (0x8002, 1)) @@ -142,6 +179,23 @@ def compile_packed_case(name, pixel, entry=packed_entry, **kwargs): check_screen_position(*compile_packed_case("packed-zero-catalog", raw_pixel, expect_hit=0, case_cache=catalog_cache)) + # A texture read from a slot declared as a CBV takes the physical check: + # the draw must find a texture SRV record there. An SRV range keeps the + # ordinary binding, and a UAV range or a buffer read stays refused. + def table_manifest(name, offset, root): + key, output = compile_packed_case(name, table_texture_program(offset), root=root) + return (output / f"{key}.txt").read_text().splitlines() + + manifest = table_manifest("cbv-range-texture", 0, CBV_ROOT) + assert manifest[0] == "x2w-manifest 4" and "srv 0 tex2d table 0 0" in manifest, manifest + assert "tablecheck 0 0" in manifest, manifest + manifest = table_manifest("srv-range-texture", 0, TABLE_ROOT) + assert "srv 0 tex2d table 0 0" in manifest and not any(line.startswith("tablecheck") for line in manifest), manifest + compile_packed_case("uav-range-texture", table_texture_program(0), root=UAV_ROOT, + expected="graphics descriptor range does not cover resource") + compile_case("uav-range-buffer", table_pixel(0), (2, 1), root=UAV_ROOT, + expected="graphics descriptor range does not cover resource") + compile_packed_case("packed-zero-missing-position", packed_xy_pixel(), (0x0080, 0), expected="unsupported fixed pixel entry layout") compile_packed_case("packed-with-interpolants", packed_xy_pixel(), (0x8080, 1), diff --git a/tests/startup_address_srv.cpp b/tests/startup_address_srv.cpp index 0033e03da..b67e6bde6 100644 --- a/tests/startup_address_srv.cpp +++ b/tests/startup_address_srv.cpp @@ -49,6 +49,74 @@ bool bind_view_table(void* guest, void* list, Word& cpu, UINT count = 1, Word ad } } +// Every texel has a different XY colour. The translated draw reads it through table parameter 0. +int draw_slot57_position_texture(ID3D12Device* desktop, void* guest, void* list, void* root, UINT width, UINT height) +{ + char mode[32]{}; + GetEnvironmentVariableA("X2W_TEST_SLOT57_POSITION_TEXTURE", mode, sizeof(mode)); + const bool physical = !std::strcmp(mode, "physical"); + const bool short_heap = !std::strcmp(mode, "short-heap"); + const bool cbv = !std::strcmp(mode, "physical-cbv"); + // A heap over guest memory that ends at byte 64, where the next 32 bytes hold a valid texture SRV token. + const bool past_heap = !std::strcmp(mode, "past-heap"); + // "cbv-range" declares slot 0 as a CBV (startup_stream_setup.cpp) and stores a texture SRV there. + // "cbv-range-cbv" stores the declared CBV, which a texture read of slot 0 must refuse. + const bool range_cbv = !std::strcmp(mode, "cbv-range-cbv"); + invoke(list, 34, ptr(root)); + const Word increment = invoke(guest, 15, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + // The physical modes read byte 64 of the table: record 2 with a 32-byte increment, record 1 with 64 (WARP). + const Word slot = increment && 64 % increment == 0 ? 64 / increment : 0; + if ((physical || short_heap || cbv || past_heap) && !slot) return 43; + alignas(64) static std::array guest_heap{}; + Word cpu = 0; + if (past_heap) { + if (!bind_view_table(guest, list, cpu, static_cast(slot), ptr(guest_heap.data()), slot * increment) || + cpu != ptr(guest_heap.data())) return 42; + } else if (!bind_view_table(guest, list, cpu, static_cast(physical || cbv ? slot + 1 : short_heap ? slot : 1))) + return 42; + if (cbv || range_cbv) { + auto* upload = reinterpret_cast(invoke(list, 148, 256, 256)); + if (!upload) return 47; + std::memset(upload, 0, 256); + upload[4] = 1.0f; + const D3D12_CONSTANT_BUFFER_VIEW_DESC view{ptr(upload), 256}; + invoke(guest, 17, ptr(&view), cpu + (cbv ? slot : 0) * increment); + invoke(list, 12, 3, 1); + return 0; + } + const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, width, height, 1, 1, + DXGI_FORMAT_R8G8B8A8_UNORM, {1, 0}, D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_NONE}; + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{}; + UINT64 size = 0; + desktop->GetCopyableFootprints(&desc, 0, 1, 0, &footprint, nullptr, nullptr, &size); + if (!size || size == ~UINT64{0}) return 40; + static std::vector texels; + texels.resize(static_cast(size)); + for (UINT y = 0; y < height; ++y) { + auto* row = texels.data() + footprint.Offset + std::size_t{y} * footprint.Footprint.RowPitch; + for (UINT x = 0; x < width; ++x) { + row[4 * x] = static_cast(20 + 17 * x); + row[4 * x + 1] = static_cast(30 + 41 * y); + row[4 * x + 2] = 73; + row[4 * x + 3] = 255; + } + } + void* texture = nullptr; + if (FAILED(static_cast(invoke(guest, 133, ptr(texels.data()), ptr(&desc), D3D12_RESOURCE_STATE_COMMON, + 0, ptr(&__uuidof(ID3D12Resource)), ptr(&texture)))) || !texture) return 41; + D3D12_SHADER_RESOURCE_VIEW_DESC view{}; + view.Format = desc.Format; + view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + view.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + view.Texture2D.MipLevels = 1; + // Populate the last real slot so a check that clamps the offset would draw in the short-heap case. + invoke(guest, 18, ptr(texture), ptr(&view), cpu + (physical ? slot : short_heap || past_heap ? slot - 1 : 0) * increment); + // Copy the accepted 32-byte token to byte 64, just past the heap end. Only the heap bound refuses it. + if (past_heap) std::memcpy(guest_heap.data() + 64, guest_heap.data() + (slot - 1) * increment, 32); + invoke(list, 12, 3, 1); + return 0; +} + // Two separately placed R8 planes have the same descriptor and different row // data. The producer and oracle both use the documented desktop footprint. int draw_address_srvs(ID3D12Device* desktop, void* guest, void* list) diff --git a/tests/startup_native_slot57_packed_position_check.py b/tests/startup_native_slot57_packed_position_check.py index a176d0e29..0d1068ecf 100644 --- a/tests/startup_native_slot57_packed_position_check.py +++ b/tests/startup_native_slot57_packed_position_check.py @@ -9,6 +9,7 @@ import tempfile from native_direct_container_check import patched_pixel, vertex, words +from native_fixed_graphics_psi1_check import table_pixel, table_texture_program from startup_stream_draw_check import vop1, vop2 @@ -77,6 +78,45 @@ def check(folder, consumer, sdk, adapter): actual = pixels.read_bytes() assert actual == expected, f"{case}: actual {actual.hex()} expected {expected.hex()}" print(f"{adapter} {case}: " + ("32 clear pixels" if case == "wrong-address" else "16 XY and 16 clear pixels")) + + cache = folder / "physical-table" + cache.mkdir() + env["X2W_SHADER_CACHE"] = str(cache) + colors = b"".join(bytes((20 + 17 * x, 30 + 41 * y, 73, 255)) for y in range(4) for x in range(8)) + texture_record = "missing typed texture SRV record" + cbv_record = "missing CBV record or insufficient CBV span" + cases = ( + ("physical", table_texture_program(), "58:8080,5c:0", colors, None), + ("short-heap", table_texture_program(), "58:8080,5c:0", None, None), + ("physical-cbv", table_texture_program(), "58:8080,5c:0", None, None), # Wrong descriptor kind. + ("physical-cbv", table_pixel(64), "58:2,5c:1", bytes((255, 255, 255, 255)) * 32, None), + ("physical-cbv", table_pixel(64, cbv_offset=256), "58:2,5c:1", None, None), + # A valid texture token right after a two-record guest heap: only the heap bound refuses it. + ("past-heap", table_texture_program(), "58:8080,5c:0", None, texture_record), + # A 2D texture SRV in the physical slot of a CBV/buffer read. + ("physical", table_pixel(64), "58:2,5c:1", None, cbv_record), + # Slot 0 is declared as a CBV. The shader reads a texture there, so only a texture SRV record draws. + ("cbv-range", table_texture_program(0), "58:8080,5c:0", colors, None), + ("cbv-range-cbv", table_texture_program(0), "58:8080,5c:0", None, texture_record), + ) + for mode, program, entry, expected, reason in cases: + byte = 0 if mode.startswith("cbv-range") else 64 + ps.write_bytes(program) + run = subprocess.run([consumer, vs, ps, root, adapter, pixels, "slot57", entry], + env=dict(env, X2W_TEST_SLOT57_POSITION_TEXTURE=mode), + capture_output=True, text=True, timeout=45) + assert run.returncode == 0 and "ready=1 cache(frontend,vs,ps)=" in run.stderr, run.stderr + assert not re.search(r"x2w-d3d12-debug .* sev=[01] ", run.stderr), run.stderr + if expected is not None: + assert "-> drawn;" in run.stderr, run.stderr + else: + assert f"physical table 0 byte {byte} refused" in run.stderr and "-> drawn;" not in run.stderr, run.stderr + if reason is not None: + assert f"physical table 0 byte {byte} refused: {reason}" in run.stderr, (mode, reason, run.stderr) + expected = CLEAR * 32 + actual = pixels.read_bytes() + assert actual == expected, f"{mode}: actual {actual.hex()} expected {expected.hex()}" + print(f"{adapter} {mode}: {len(actual) // 4} expected pixels" + (f", refused: {reason}" if reason else "")) return 0 diff --git a/tests/startup_stream_consumer.cpp b/tests/startup_stream_consumer.cpp index cd721b46b..8c3452c0c 100644 --- a/tests/startup_stream_consumer.cpp +++ b/tests/startup_stream_consumer.cpp @@ -69,21 +69,23 @@ static bool derive(void* device, void*& pipeline, bool child) // A slot-57 description as the stand-in reads it: 64-bit words 0 (root signature), 1-2 (state block // A and its size), 5-6 and 9-10 (the two shaders). spec lists "offset:word" pairs in hex, written // into state block A. The vertex layout (tag 4 at +0x004) has eight blend words starting at +0xD0. -// The shaders and the root signature are read from the files the stream pipeline was made from, so -// both pipelines share one translation. +// Reuse the stream pipeline's shader files and serialized root. A fixture that binds the root on the list +// can also pass the same wrapped root directly. static bool create_slot57(void* device, const char* vs_path, const char* ps_path, const char* root_path, const char* spec, - void*& pipeline) + void*& pipeline, void* root = nullptr) { static std::vector vs, ps; - std::ifstream vs_file(vs_path, std::ios::binary), ps_file(ps_path, std::ios::binary), root_file(root_path, std::ios::binary); + std::ifstream vs_file(vs_path, std::ios::binary), ps_file(ps_path, std::ios::binary); vs.assign(std::istreambuf_iterator(vs_file), {}); ps.assign(std::istreambuf_iterator(ps_file), {}); - const std::vector blob{std::istreambuf_iterator(root_file), {}}; - if (vs.empty() || ps.empty() || blob.empty()) return false; - using CreateRoot = HRESULT (WINAPI*)(void*, UINT, const void*, SIZE_T, REFIID, void**); - void* root = nullptr; - if (FAILED(reinterpret_cast((*static_cast(device))[16])(device, 0, blob.data(), blob.size(), - __uuidof(ID3D12RootSignature), &root))) return false; + if (vs.empty() || ps.empty()) return false; + if (!root) { + std::ifstream root_file(root_path, std::ios::binary); + const std::vector blob{std::istreambuf_iterator(root_file), {}}; + using CreateRoot = HRESULT (WINAPI*)(void*, UINT, const void*, SIZE_T, REFIID, void**); + if (blob.empty() || FAILED(reinterpret_cast((*static_cast(device))[16])( + device, 0, blob.data(), blob.size(), __uuidof(ID3D12RootSignature), &root))) return false; + } alignas(8) static unsigned char desc[0x300]; alignas(8) static unsigned char state_a[0x200]; const UINT vertex_layout = 4; @@ -1625,7 +1627,8 @@ int main(int argc, char** argv) void* pso = nullptr; const bool hardware = (draw && std::strcmp(argv[4], "hardware") == 0) || GetEnvironmentVariableW(L"X2W_TEST_DISPATCH_HARDWARE", nullptr, 0) != 0; - const bool textured = bc7.blocks != nullptr || GetEnvironmentVariableW(L"X2W_TEST_D16_SRV", nullptr, 0) != 0 || + const bool position_texture = GetEnvironmentVariableW(L"X2W_TEST_SLOT57_POSITION_TEXTURE", nullptr, 0) != 0; + const bool textured = position_texture || bc7.blocks != nullptr || GetEnvironmentVariableW(L"X2W_TEST_D16_SRV", nullptr, 0) != 0 || GetEnvironmentVariableW(L"X2W_TEST_FORMATTED_BUFFER", nullptr, 0) != 0 || GetEnvironmentVariableW(L"X2W_TEST_FORMATTED_VIEW", nullptr, 0) != 0 || GetEnvironmentVariableW(L"X2W_TEST_JOINED_TABLE", nullptr, 0) != 0 || @@ -1692,7 +1695,8 @@ int main(int argc, char** argv) // "slot57-mrt" binds a second RGBA8 target. two_targets = std::strcmp(argv[6], "slot57-mrt") == 0; if (!two_targets && std::strcmp(argv[6], "slot57") != 0) return 2; - if (!create_slot57(device, argv[1], argv[2], argv[3], argv[7], pso)) return 10; + if (!create_slot57(device, argv[1], argv[2], argv[3], argv[7], pso, + position_texture ? stream_root_signature() : nullptr)) return 10; } else if (argc == 7 && !std::isdigit(static_cast(argv[6][0]))) { const std::string mode(argv[6]); if (mode != "parent-a8" && mode != "child-a8" && mode != "child-r8") return 2; diff --git a/tests/startup_stream_draw.cpp b/tests/startup_stream_draw.cpp index d59971e41..4ac150e53 100644 --- a/tests/startup_stream_draw.cpp +++ b/tests/startup_stream_draw.cpp @@ -402,6 +402,7 @@ int check_stream_draw(IDXGIAdapter* adapter, void* guest, void* pso, const char* // The translated MRT formats draw one pixel; the other formats keep the 8x4 target. const bool single = typed; const bool legacy = !single; + const bool position_texture = GetEnvironmentVariableW(L"X2W_TEST_SLOT57_POSITION_TEXTURE", nullptr, 0) != 0; const UINT width = bc_chain ? 384 : bc7 ? (bc7->small4k ? 48 : bc7->width) : bc ? 4 * 128 : single ? 1 : GetEnvironmentVariableW(L"X2W_TEST_ADDRESS_BUFFER_SRV", nullptr, 0) ? 15 : 8; const UINT height = bc_chain ? 32 : bc7 ? bc7->height : bc ? 128 : single ? 1 : 4; ComPtr desktop; @@ -417,7 +418,7 @@ int check_stream_draw(IDXGIAdapter* adapter, void* guest, void* pso, const char* StreamTarget frame; if (two_targets) frame.count = 2; // a second RGBA8 target of the same size, written after the first if (const int rc = open_stream_target(desktop.Get(), guest, pso, width, height, format, - legacy && !bc7 && !bc_chain ? width / 2 : width, frame)) return rc; + legacy && !bc7 && !bc_chain && !position_texture ? width / 2 : width, frame)) return rc; auto* list = frame.list; auto* queue = frame.queue; auto* fence = frame.fence; @@ -537,6 +538,10 @@ int check_stream_draw(IDXGIAdapter* adapter, void* guest, void* pso, const char* } else if (GetEnvironmentVariableW(L"X2W_TEST_D16_SRV", nullptr, 0)) { extern int draw_d16_srvs(ID3D12Device*, void*, void*); if (const int result = draw_d16_srvs(desktop.Get(), guest, list)) return result; + } else if (position_texture) { + extern int draw_slot57_position_texture(ID3D12Device*, void*, void*, void*, UINT, UINT); + if (const int result = draw_slot57_position_texture(desktop.Get(), guest, list, stream_root_signature(), width, height)) + return result; } else if (GetEnvironmentVariableW(L"X2W_TEST_PIXEL_UAV", nullptr, 0)) { extern int draw_pixel_uavs(ID3D12Device*, void*, void*); if (const int result = draw_pixel_uavs(desktop.Get(), guest, list)) return result; diff --git a/tests/startup_stream_setup.cpp b/tests/startup_stream_setup.cpp index e29b3985f..de96d36fa 100644 --- a/tests/startup_stream_setup.cpp +++ b/tests/startup_stream_setup.cpp @@ -163,7 +163,12 @@ int prepare_stream_pipeline(const char* vs_path, const char* ps_path, const char const bool raw_pixel = std::strncmp(pixel_uav_mode, "raw-", 4) == 0; if (raw_pixel) std::printf("raw descriptor stride: %llu\n", static_cast(invoke(device, 15, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV))); - const D3D12_DESCRIPTOR_RANGE srv{raw_pixel ? D3D12_DESCRIPTOR_RANGE_TYPE_UAV : D3D12_DESCRIPTOR_RANGE_TYPE_SRV, + // X2W_TEST_SLOT57_POSITION_TEXTURE=cbv-range* declares the one table slot as a CBV (startup_address_srv.cpp). + char position_mode[32]{}; + GetEnvironmentVariableA("X2W_TEST_SLOT57_POSITION_TEXTURE", position_mode, sizeof(position_mode)); + const bool cbv_range = std::strncmp(position_mode, "cbv-range", 9) == 0; + const D3D12_DESCRIPTOR_RANGE srv{raw_pixel ? D3D12_DESCRIPTOR_RANGE_TYPE_UAV + : cbv_range ? D3D12_DESCRIPTOR_RANGE_TYPE_CBV : D3D12_DESCRIPTOR_RANGE_TYPE_SRV, raw_pixel ? 4u : (joined_table || vertex_srv_pair ? 2u : 1u), 0, 0, 0}; D3D12_ROOT_PARAMETER textured_parameters[2]{}; if (textured) {