Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -1696,6 +1696,10 @@ if(EXISTS "${INTAKE_PYTHON}")
"${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_stream_draw_check.py"
"$<TARGET_FILE:startup_stream_consumer>" "${backend}")
set_tests_properties(startup_stream_draw_${backend} PROPERTIES TIMEOUT 90)
add_test(NAME startup_stream_viewport_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}"
"${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_stream_viewport_check.py"
"$<TARGET_FILE:startup_stream_consumer>" "${backend}")
set_tests_properties(startup_stream_viewport_${backend} PROPERTIES TIMEOUT 90)
add_test(NAME startup_stream_depth_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}"
"${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_stream_depth_check.py"
"$<TARGET_FILE:startup_stream_depth>" "${backend}")
Expand Down Expand Up @@ -1751,7 +1755,7 @@ if(EXISTS "${INTAKE_PYTHON}")
"$<TARGET_FILE:startup_stub_xg_xs>" "$<TARGET_FILE:startup_stream_consumer>" "${backend}")
set_tests_properties(startup_xg_bc_array_${backend} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77)
endforeach()
set_tests_properties(startup_stream_draw_hardware PROPERTIES SKIP_RETURN_CODE 77)
set_tests_properties(startup_stream_draw_hardware startup_stream_viewport_hardware PROPERTIES SKIP_RETURN_CODE 77)
set_tests_properties(startup_stream_request_warp PROPERTIES TIMEOUT 60)

# Startup shader translator: descriptor offsets inside wide scalar loads (no game data).
Expand Down
13 changes: 13 additions & 0 deletions docs/startup-runtime.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,19 @@ It covers what the draw cannot observe: the logged descriptor offset (4 bytes in
a byte-for-byte copy of the descriptor, and refusal of a null list or one that is not whole
records. The control expects the first blend patch to win and must fail.

## Default viewport and scissor

A desktop command list that never sets a viewport or scissor rectangle draws no pixel. A translated
draw therefore covers the whole first render target (its width and height, depth 0 to 1) when the title
set no viewport, and the same rectangle as scissor when it set no scissor. Each default applies on its own,
and a viewport or scissor the title did set is never replaced. A list reset starts without either. A call
with no viewports or no rectangles changes nothing. A draw with no render target bound, for example
depth only, gets no default. The default uses the size of mip 0 of the resource; the render target view's mip slice is not tracked.

Run `ctest --preset dev --no-tests=error -R "^startup_stream_viewport_(hardware|warp)$" -V` after building
`startup_stream_consumer`. On an 8×4 target the cases draw with neither call, inside a 4×2 rectangle (the
rest keeps the clear color), and on a reset list that follows the rectangle (all pixels drawn again).

## Output window and fallback diagnostics

The desktop swap chain has its own top-level window, class `X2WOutputWindow`.
Expand Down
17 changes: 17 additions & 0 deletions src/startup_stubs/d3d12_draw.inl
Original file line number Diff line number Diff line change
Expand Up @@ -1054,6 +1054,23 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI
: ud.kind == Translation::root_constant ? ((ud.a >= 0 && ud.a < 16 && ud.b >= 0 && ud.b < 8) ? pass.constants[ud.a][ud.b] : 0)
: ud.kind == Translation::stride && ud.a >= 0 && ud.a < 32 ? strides[ud.a] : 0;
}
// A desktop list with no viewport or scissor draws nothing: cover the first render target unless the title set its own.
if (pass.target0 && (!pass.viewport_set || !pass.scissor_set)) {
const D3D12_RESOURCE_DESC target = pass.target0->GetDesc();
// Only the title's own calls set the flags; an automatic default is regenerated when render target 0 changes size.
if (!pass.viewport_set && (pass.default_viewport_w != target.Width || pass.default_viewport_h != target.Height)) {
const D3D12_VIEWPORT full{0.0f, 0.0f, static_cast<float>(target.Width), static_cast<float>(target.Height), 0.0f, 1.0f};
list->RSSetViewports(1, &full);
pass.default_viewport_w = target.Width;
pass.default_viewport_h = target.Height;
}
if (!pass.scissor_set && (pass.default_scissor_w != target.Width || pass.default_scissor_h != target.Height)) {
const D3D12_RECT full{0, 0, static_cast<LONG>(target.Width), static_cast<LONG>(target.Height)};
list->RSSetScissorRects(1, &full);
pass.default_scissor_w = target.Width;
pass.default_scissor_h = target.Height;
}
}
list->SetPipelineState(pipeline);
list->SetGraphicsRootSignature(tr->root);
ID3D12DescriptorHeap* samplers = tr->samplers.heap ? pass.sampler_heap.Get() : nullptr;
Expand Down
28 changes: 26 additions & 2 deletions src/startup_stubs/d3d12_xs_device.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -978,6 +978,7 @@ HRESULT __stdcall device_residency(Wrapper* self, UINT count, void* const* objec
// when the desktop GPU finishes, and the presented surface is read back and shown in the window.
// Everything else on a list is still dropped.
void release_targets(Wrapper* self);
void reset_viewport_state(Wrapper* self);
void discard_draw_sampler_heaps(Wrapper* self);
void use_as_target(Wrapper* self, ID3D12Resource* resource);
bool is_container(const void* p);
Expand Down Expand Up @@ -1198,6 +1199,7 @@ HRESULT __stdcall list_reset(Wrapper* self, void* allocator)
}
if (SUCCEEDED(hr)) {
self->own().list_ready = false;
reset_viewport_state(self);
discard_draw_sampler_heaps(self);
if (draw_dump_frame()) draw_dumps().discard(static_cast<ID3D12CommandList*>(self->own().real));
}
Expand Down Expand Up @@ -1648,6 +1650,13 @@ struct Pass {
std::unique_ptr<x2w_startup::SamplerSnapshot> sampler_snapshot;
x2w_startup::ComPtr<ID3D12DescriptorHeap> sampler_heap;
ID3D12DescriptorHeap* bound_sampler_heap = nullptr;
// Whether the title set a viewport / scissor on this list; without them a desktop list draws no pixel.
bool viewport_set = false;
bool scissor_set = false;
// Size of the automatic full-target default already forwarded to the desktop list (0 = none yet). Kept apart from
// the title flags above so a later render target 0 of another size gets a fresh default.
UINT64 default_viewport_w = 0, default_scissor_w = 0;
UINT default_viewport_h = 0, default_scissor_h = 0;
};
LONG render_draws, render_draws_skipped, render_pipelines_real, render_pipelines_missing;

Expand Down Expand Up @@ -1690,6 +1699,16 @@ void release_targets(Wrapper* self)
pass = Pass{};
}

// A reset list starts without a viewport or scissor, whatever the previous recording set.
void reset_viewport_state(Wrapper* self)
{
if (!self->own().pass) return;
pass_of(self).viewport_set = false;
pass_of(self).scissor_set = false;
pass_of(self).default_viewport_w = pass_of(self).default_scissor_w = 0;
pass_of(self).default_viewport_h = pass_of(self).default_scissor_h = 0;
}

// List slot 20, IASetPrimitiveTopology. 0x11 is a console-only rectangle list (no desktop draw yet).
void __stdcall list_topology(Wrapper* self, UINT topology)
{
Expand Down Expand Up @@ -1833,13 +1852,18 @@ void __stdcall list_targets(Wrapper* self, UINT count, const D3D12_CPU_DESCRIPTO
// List slots 21 / 22 / 23, RSSetViewports / RSSetScissorRects / OMSetBlendFactor.
void __stdcall list_viewports(Wrapper* self, UINT count, const D3D12_VIEWPORT* viewports)
{
if (auto* list = recording(self); list && count && count <= 16 && x2w_local::readable(viewports, count * sizeof(*viewports)))
// Only a viewport that is forwarded counts as set; a call with no viewports leaves the state as it was.
if (auto* list = recording(self); list && count && count <= 16 && x2w_local::readable(viewports, count * sizeof(*viewports))) {
list->RSSetViewports(count, viewports);
pass_of(self).viewport_set = true;
}
}
void __stdcall list_scissors(Wrapper* self, UINT count, const D3D12_RECT* rects)
{
if (auto* list = recording(self); list && count && count <= 16 && x2w_local::readable(rects, count * sizeof(*rects)))
if (auto* list = recording(self); list && count && count <= 16 && x2w_local::readable(rects, count * sizeof(*rects))) {
list->RSSetScissorRects(count, rects);
pass_of(self).scissor_set = true;
}
}
void __stdcall list_blend_factor(Wrapper* self, const float* factor)
{
Expand Down
63 changes: 57 additions & 6 deletions tests/startup_stream_draw.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <cwchar>
#include <fstream>
#include <iterator>
#include <vector>
Expand Down Expand Up @@ -287,12 +288,62 @@ int check_stream_draw(IDXGIAdapter* adapter, void* guest, void* pso, const char*
extern int draw_bc_address_srvs(void*, void*);
if (const int result = draw_bc_address_srvs(guest, list)) return result;
}
invoke(list, 9);
invoke(queue, 10, 1, arg(&list));
if (FAILED(static_cast<HRESULT>(invoke(queue, 14, arg(fence), 1)))) return 24;
const auto deadline = GetTickCount64() + 10000;
while (invoke(fence, 8) == 0 && GetTickCount64() < deadline) Sleep(1);
if (invoke(fence, 8) != 1) return 25;
const auto submit = [&](UINT64 value) {
invoke(list, 9);
invoke(queue, 10, 1, arg(&list));
if (FAILED(static_cast<HRESULT>(invoke(queue, 14, arg(fence), value)))) return 24;
const auto deadline = GetTickCount64() + 10000;
while (invoke(fence, 8) < value && GetTickCount64() < deadline) Sleep(1);
return invoke(fence, 8) == value ? 0 : 25;
};
// X2W_TEST_VIEWPORT=reset: the list above drew inside a small rectangle. Record a second list on the same
// object after Reset that sets neither a viewport nor a scissor; it must not inherit the first rectangle.
wchar_t viewport_mode[8] = L"";
GetEnvironmentVariableW(L"X2W_TEST_VIEWPORT", viewport_mode, 8);
UINT64 last = 1;
// X2W_TEST_VIEWPORT=grow: no viewport or scissor anywhere. After the draw above on the small target, the same
// list switches to a target twice as large and draws again; the default must follow the new target.
if (std::wcscmp(viewport_mode, L"grow") == 0) {
const struct {
D3D12_DESCRIPTOR_HEAP_DESC desc;
Word backing, bytes;
} big_heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1}, 0, 0};
void* big_heap = nullptr;
if (FAILED(static_cast<HRESULT>(invoke(guest, 14, arg(&big_heap_desc), arg(&__uuidof(ID3D12DescriptorHeap)), arg(&big_heap))))) return 36;
D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT};
const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, width * 2, height * 2, 1, 1,
format, {1, 0}, D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET};
const float clear[] = {0, 0, 1, 1};
const D3D12_CLEAR_VALUE optimized_clear{format, {clear[0], clear[1], clear[2], clear[3]}};
StreamAttachment big;
if (FAILED(desktop->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc,
D3D12_RESOURCE_STATE_COMMON, &optimized_clear, IID_PPV_ARGS(&big.texture)))) return 37;
D3D12_RENDER_TARGET_VIEW_DESC view{format, D3D12_RTV_DIMENSION_TEXTURE2D, {}};
D3D12_CPU_DESCRIPTOR_HANDLE rtv{static_cast<SIZE_T>(invoke(big_heap, 9))};
invoke(guest, 20, arg(big.texture.Get()), arg(&view), rtv.ptr);
big.row_bytes = width * 2 * 4;
invoke(list, 52, rtv.ptr, arg(clear));
invoke(list, 50, 1, arg(&rtv));
invoke(list, 12, 3, 1);
// Read back the larger target only; the small one stays alive in slot 1 until the list has executed.
frame.attachments[1] = std::move(frame.attachments[0]);
frame.attachments[0] = std::move(big);
frame.count = 1;
}
if (std::wcscmp(viewport_mode, L"reset") == 0) {
if (const int rc = submit(1)) return rc;
const float clear[] = {0, 0, 1, 1};
D3D12_CPU_DESCRIPTOR_HANDLE rtv{static_cast<SIZE_T>(invoke(frame.rtv_heap, 9))};
if (FAILED(static_cast<HRESULT>(invoke(frame.allocator, 8))) ||
FAILED(static_cast<HRESULT>(invoke(list, 139, arg(frame.allocator))))) return 35;
invoke(list, 52, rtv.ptr, arg(clear));
invoke(list, 50, 1, arg(&rtv));
invoke(list, 20, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
invoke(list, 25, arg(pso));
invoke(list, 12, 3, 1);
last = 2;
}
if (const int rc = submit(last)) return rc;

return read_stream_target(desktop.Get(), frame, pixels);
}
14 changes: 12 additions & 2 deletions tests/startup_stream_setup.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cwchar>
#include <wrl/client.h>

#include <array>
Expand Down Expand Up @@ -216,8 +217,17 @@ int open_stream_target(ID3D12Device* desktop, void* guest, void* pso, UINT width
invoke(list, 139, arg(allocator));
for (UINT i = 0; i < count; ++i) invoke(list, 52, rtvs[i].ptr, arg(clear));
invoke(list, 50, count, arg(rtvs.data()));
invoke(list, 21, 1, arg(&viewport));
invoke(list, 22, 1, arg(&rect));
// X2W_TEST_VIEWPORT: "none" and "grow" never set a viewport or scissor; "rect" and "reset" set a rectangle smaller than the target.
wchar_t mode[8] = L"";
GetEnvironmentVariableW(L"X2W_TEST_VIEWPORT", mode, 8);
const bool none = std::wcscmp(mode, L"none") == 0 || std::wcscmp(mode, L"grow") == 0;
const bool inset = std::wcscmp(mode, L"rect") == 0 || std::wcscmp(mode, L"reset") == 0;
const D3D12_VIEWPORT inner{2, 1, 4, 2, 0, 1};
const D3D12_RECT inner_rect{2, 1, 6, 3};
if (!none) {
invoke(list, 21, 1, inset ? arg(&inner) : arg(&viewport));
invoke(list, 22, 1, inset ? arg(&inner_rect) : arg(&rect));
}
invoke(list, 20, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
invoke(list, 25, arg(pso));
return 0;
Expand Down
79 changes: 79 additions & 0 deletions tests/startup_stream_viewport_check.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
"""A translated draw covers the render target when the title set no viewport or scissor, and never replaces one it set.

Three cases on an 8x4 RGBA8 target cleared to blue, drawn with a red pixel shader through a slot-86 wrapper:
none: no RSSetViewports and no RSSetScissorRects (list slots 21 and 22) -> every pixel is red.
rect: a viewport and scissor of 4x2 pixels at (2, 1) -> red inside the rectangle, blue outside.
grow: no viewport or scissor; one draw on the 8x4 target, then OMSetRenderTargets to a 16x8 target on the same
list and a second draw -> the 16x8 target is entirely red (the default follows the new target).
reset: the rectangle of 'rect' on one list, then the same list object Reset with no viewport or scissor
-> every pixel red, the rectangle is not inherited.
"""
import os
from pathlib import Path
import subprocess
import sys
import tempfile

from startup_stream_check import gfx2hlsl
from startup_stream_draw_check import pixel, vertex

WIDTH, HEIGHT = 8, 4
RED, BLUE = bytes((255, 0, 0, 255)), bytes((0, 0, 255, 255))


def expected_pixels(inside, scale=1):
"""RGBA bytes of the target; inside(x, y) says whether the pixel belongs to the draw."""
return b"".join(RED if inside(x, y) else BLUE for y in range(HEIGHT * scale) for x in range(WIDTH * scale))


CASES = {
"none": lambda x, y: True,
"rect": lambda x, y: 2 <= x < 6 and 1 <= y < 3,
"reset": lambda x, y: True,
"grow": lambda x, y: True,
}
SCALE = {"grow": 2}


def first_difference(actual, expected, width=WIDTH):
for index in range(0, len(expected), 4):
if actual[index:index + 4] != expected[index:index + 4]:
return index // 4 % width, index // 4 // width, actual[index:index + 4].hex(), expected[index:index + 4].hex()
return None


def check(directory, consumer, backend):
cache = directory / "cache"
cache.mkdir()
vs, ps, root, output = (directory / name for name in ("vs", "ps", "root", "pixels"))
vs.write_bytes(vertex())
ps.write_bytes(pixel(False))
args = [consumer, vs, ps, root]
env = dict(os.environ, X2W_D3D12_PERMISSIVE="1", X2W_D3D12_LIST_NOOP="1", X2W_D3D12_RENDER="1",
X2W_SHADER_CACHE=str(cache))
env.setdefault("X2W_D3D12_DEBUG", "0")
subprocess.run(args, env=env, check=True)
subprocess.run([sys.executable, "-B", gfx2hlsl.__file__, "--pending", cache], env=env, check=True)
for name, inside in CASES.items():
result = subprocess.run(args + [backend, output], env=dict(env, X2W_TEST_VIEWPORT=name),
capture_output=True, text=True)
print(result.stdout, end="")
if backend == "hardware" and result.returncode == 77:
print("No D3D12 feature-level 12 hardware adapter")
return 77
if result.returncode or "-> drawn;" not in result.stderr:
raise RuntimeError(f"{name} draw failed on {backend}: {result.returncode}\n{result.stderr}")
actual = output.read_bytes()
scale = SCALE.get(name, 1)
expected = expected_pixels(inside, scale)
difference = first_difference(actual, expected, WIDTH * scale)
if difference:
x, y, got, want = difference
raise AssertionError(f"{name}: pixel ({x}, {y}) is {got}, expected {want}")
print(f"{backend} viewport {name}: all {WIDTH * HEIGHT * scale * scale} pixels exact")
return 0


if __name__ == "__main__":
with tempfile.TemporaryDirectory() as temp:
sys.exit(check(Path(temp), *sys.argv[1:]))
Loading