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: 6 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -1954,6 +1954,12 @@ if(TARGET compile_dxil AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${
"${CMAKE_SOURCE_DIR}/tests/native_compute_clear_check.py" "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}")
add_test(NAME native_compute_raw_root COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_SOURCE_DIR}/tests/native_compute_raw_root_check.py" "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}")
foreach(adapter IN ITEMS warp hardware)
add_test(NAME startup_native_graphics_draw_${adapter} COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_SOURCE_DIR}/tests/startup_native_graphics_draw_check.py"
"$<TARGET_FILE:startup_stream_consumer>" "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}" ${adapter})
set_tests_properties(startup_native_graphics_draw_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77)
endforeach()
foreach(backend IN ITEMS hardware warp)
add_test(NAME native_descriptor_scc_${backend} COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_SOURCE_DIR}/tests/native_descriptor_scc_check.py" "$<TARGET_FILE:compile_dxil>"
Expand Down
13 changes: 13 additions & 0 deletions docs/experiments.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,19 @@

New notes go in `docs/experiments/<topic>.md` (see [the folder guide](experiments/README.md)); this file keeps the older notes.

## First native graphics draw through the stand-in

Set `X2W_NATIVE_SHADERS` to the desktop DXC directory and `X2W_SHADER_CACHE` to a writable cache.
The stand-in reads the published graphics request, links the pair, and uses the compiler's persistent
frontend and bytecode caches. The runtime consumes the same supported binding manifest as the offline
compiler. The source-built triangle fixture uses one RGBA8 target and checks all 32 pixels in each
of two processes. A third process supplies an unsupported pixel stage and checks the untouched clear.

```powershell
cmake --build --preset dev --target startup_stream_consumer d3d12_xs_shim compile_dxil
ctest --preset dev --no-tests=error -V -R '^startup_native_graphics_draw_(hardware|warp)$'
```

## Slot 67 wave size in direct compute

State block A bit 20 of dword 4 selects the guest wave size.
Expand Down
71 changes: 66 additions & 5 deletions src/startup_stubs/d3d12_draw.inl
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,9 @@ struct Translation {
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
#ifdef X2W_NATIVE_SHADERS
bool native_graphics_attempted = false;
#endif
x2w_startup::ManifestRetry manifest_retry; // Only an absent manifest can become ready on a later draw.
std::vector<Srv> srvs;
std::vector<PixelUav> uavs; // manifest 'uav N tex2d table P O' (#1996 F): u0.. after the SRVs
Expand Down Expand Up @@ -432,13 +435,13 @@ bool publish_shader_request(u64 key, const wchar_t* ext, const void* data, std::
return GetFileAttributesW(path) != INVALID_FILE_ATTRIBUTES;
}

void load_translation(Translation& tr, const std::string& rtv_request = {})
void load_translation(Translation& tr, const std::string& rtv_request = {}, std::string manifest = {})
{
tr.state = 2;
wchar_t path[MAX_PATH];
std::string manifest;
if (!cache_path(path, L"", tr.key, L".txt")) return;
if (!read_text(path, manifest)) {
const bool provided = !manifest.empty();
if (!provided && !read_text(path, manifest)) {
if (!tr.manifest_retry.pending()) {
InterlockedIncrement(&translation_missing);
static LONG missing;
Expand Down Expand Up @@ -525,8 +528,8 @@ void load_translation(Translation& tr, const std::string& rtv_request = {})
(ud.a < 0 || static_cast<std::size_t>(ud.a) >= tr.srvs.size() || !tr.d16_srvs.requires_exact(static_cast<unsigned>(ud.a))))
return;
}
if (!cache_path(path, L"", tr.key, L".vs.cso") || FAILED(D3DReadFileToBlob(path, &tr.vs))) return;
if (!cache_path(path, L"", tr.key, L".ps.cso") || FAILED(D3DReadFileToBlob(path, &tr.ps))) return;
if (!provided && (!cache_path(path, L"", tr.key, L".vs.cso") || FAILED(D3DReadFileToBlob(path, &tr.vs)))) return;
if (!provided && (!cache_path(path, L"", tr.key, L".ps.cso") || FAILED(D3DReadFileToBlob(path, &tr.ps)))) return;
const HRESULT hr = x2w_startup::create_translated_root(device_of(the_device), static_cast<UINT>(tr.uds.size()),
static_cast<UINT>(tr.srvs.size()), tr.samplers, &tr.root, static_cast<UINT>(tr.uavs.size()));
if (FAILED(hr)) {
Expand All @@ -541,6 +544,58 @@ void load_translation(Translation& tr, const std::string& rtv_request = {})
tr.key, tr.uds.size(), tr.srvs.size(), tr.uavs.size(), tr.samplers.statics.size(), tr.samplers.heap ? 1u : 0u);
}

#ifdef X2W_NATIVE_SHADERS
static bool try_native_graphics(Translation& tr)
{
wchar_t sdk[MAX_PATH], path[MAX_PATH];
const auto length = GetEnvironmentVariableW(L"X2W_NATIVE_SHADERS", sdk, MAX_PATH);
if (!length || length >= MAX_PATH || !cache_path(path, L"req_", tr.key, L".a")) return false;
try {
const auto request = x2w::read_graphics_request(path);
const auto cache = std::filesystem::path(path).parent_path();
bool frontend_hit = false;
const auto pair = x2w::prepare_direct_graphics(request.a, request.b, cache, frontend_hit,
request.root, request.input_layout, request.pixel_entry);
auto manifest = x2w::format_graphics_runtime_manifest(pair);
if (!manifest) throw std::runtime_error("unsupported graphics binding layout");
auto compiler = x2w::ShaderDxilCompiler::runtime_worker(sdk);
auto stage = [&](const std::string& ir, const wchar_t* profile, bool& hit) {
const auto output = compiler.compile(ir, profile, cache, x2w::ShaderSourceFormat::dxil_ir);
hit = output.cache_hit;
x2w_startup::ComPtr<ID3DBlob> blob;
if (FAILED(D3DCreateBlob(output.dxil.size(), &blob))) throw std::bad_alloc();
std::memcpy(blob->GetBufferPointer(), output.dxil.data(), output.dxil.size());
return blob;
};
bool vs_hit, ps_hit;
auto vs = stage(pair.vertex.dxil_ir, L"vs_6_6", vs_hit);
auto ps = stage(pair.pixel.dxil_ir, L"ps_6_6", ps_hit);
Translation candidate;
candidate.key = tr.key;
candidate.manifest_retry = tr.manifest_retry;
candidate.native_graphics_attempted = true;
candidate.vs = vs.Get();
candidate.ps = ps.Get();
// Source-built first-draw fixture: fail after both stages have compiled and
// the local candidate holds both blobs. The later disk load stays valid.
if (GetEnvironmentVariableW(L"X2W_TEST_NATIVE_GRAPHICS_BAD_MANIFEST", nullptr, 0))
*manifest = "x2w-manifest 0\n";
load_translation(candidate, {}, std::move(*manifest));
const bool ready = candidate.state == 1;
log("x2w-draw native graphics %016llx ready=%u cache(frontend,vs,ps)=%u,%u,%u",
tr.key, ready, frontend_hit, vs_hit, ps_hit);
if (!ready) return false;
vs.Detach();
ps.Detach();
tr = std::move(candidate);
return true;
} catch (const std::exception& error) {
log("x2w-draw native graphics %016llx refused: %s", tr.key, error.what());
return false;
}
}
#endif

// draw_lock held. Both pipeline forms use the same request writer and shader cache.
Translation* cached_translation(const void* a, std::size_t a_bytes, const void* b, std::size_t b_bytes,
const std::vector<unsigned char>& root_blob, const std::string& layout = {})
Expand Down Expand Up @@ -1066,6 +1121,12 @@ Translation* translation_for_targets(Translation* base, const Pass& pass)
if (std::none_of(pass.target_formats, pass.target_formats + pass.target_count, needs_rtv_variant)) {
if (base->manifest_retry.due(GetTickCount64()))
load_translation(*base);
#ifdef X2W_NATIVE_SHADERS
if (base->manifest_retry.pending() && !base->native_graphics_attempted) {
base->native_graphics_attempted = true;
try_native_graphics(*base);
}
#endif
return base;
}
std::string request = "rtv1 " + std::to_string(base->key);
Expand Down
1 change: 1 addition & 0 deletions src/startup_stubs/d3d12_xs_device.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@
#ifdef X2W_NATIVE_SHADERS // d3d12_xs_shim only: the C++ shader compiler (startup_stubs/d3d12_compute_dispatch.inl)
#include "gfx1013_compute_native.h"
#include "shader_dxil_compiler.h"
#include "direct_compute_cache.h"
#endif
#include <d3d12sdklayers.h>
#include <d3d12shader.h>
Expand Down
87 changes: 87 additions & 0 deletions tests/startup_native_graphics_draw_check.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
"""Exercise first-use native graphics translation and a fresh-process cache hit."""
import os
import subprocess
import sys
import tempfile
from pathlib import Path

from native_direct_container_check import patched_pixel, vertex
from startup_stream_draw_check import vop1, vop2


def triangle():
code = [vop2(0x1a, 1, 129, 0), vop2(0x1b, 1, 130, 1), vop2(0x1b, 2, 130, 0)]
for v in (1, 2):
code.extend([vop1(6, v, 256 + v), vop2(8, v, 244, v), vop2(3, v, 243, v)])
code.extend([vop1(1, 3, 128), vop1(1, 4, 242), 0xf80008cf, 0x04030201, 0xbf810000])
return vertex(program=code)


def check(folder, consumer, cli, sdk, adapter):
cache = folder / "cache"
cache.mkdir()
vs, ps, root, pixels = [folder / name for name in ("vs", "ps", "root", "pixels")]
vs.write_bytes(triangle())
ps.write_bytes(patched_pixel(2, [vop1(1, 0, 128), vop1(1, 1, 242)], export=(0xf800180f, 0x01000001)))
env = dict(os.environ, X2W_SHADER_CACHE=str(cache), X2W_NATIVE_SHADERS=sdk,
X2W_D3D12_DEBUG="1", X2W_D3D12_RENDER="1", X2W_D3D12_PERMISSIVE="1", X2W_D3D12_LIST_NOOP="1")
env.pop("X2W_TEST_NATIVE_GRAPHICS_BAD_MANIFEST", None)
clear = bytes((0, 0, 255, 255))
red = bytes((255, 0, 0, 255))
args = [consumer, vs, ps, root, adapter, pixels]
for name, hits in (("cold", "0,0,0"), ("hot", "1,1,1")):
run = subprocess.run(args, env=env, capture_output=True, text=True, timeout=45)
if run.returncode == 77:
return 77
if run.returncode or f"ready=1 cache(frontend,vs,ps)={hits}" not in run.stderr or "-> drawn;" not in run.stderr:
raise RuntimeError(run.stderr[-8000:])
for line in run.stderr.splitlines():
if "x2w-d3d12-debug " in line:
assert " sev=0 " not in line and " sev=1 " not in line, line
if "debug layer:" in line:
print(line)
print(run.stdout.strip())
assert pixels.read_bytes() == (red * 4 + clear * 4) * 4
print(f"{adapter} {name}: cache={hits}, 16 red and 16 clear pixels")
# A published disk pair must be used without attempting native compilation.
offline = subprocess.run([cli, "--watch", sdk, folder / "offline", cache, "--once"],
capture_output=True, text=True, timeout=45)
assert offline.returncode == 0 and "compiled graphics" in offline.stdout, (offline.stdout, offline.stderr)
key = next(cache.glob("req_*.a")).stem.removeprefix("req_")
published = [cache / f"{key}{suffix}" for suffix in (".txt", ".vs.cso", ".ps.cso")]
contents = [path.read_bytes() for path in published]
run = subprocess.run(args, env=env, capture_output=True, text=True, timeout=45)
assert run.returncode == 0 and "-> drawn;" in run.stderr, run.stderr
assert "native graphics " not in run.stderr, run.stderr
assert pixels.read_bytes() == (red * 4 + clear * 4) * 4
assert [path.read_bytes() for path in published] == contents
print(f"{adapter} published disk pair: 16 red and 16 clear pixels, cache files unchanged")

manifest = published[0]
retries = (
("unavailable DXC", {"X2W_NATIVE_SHADERS": str(folder / "missing-sdk")},
(f"native graphics {key} refused:",)),
("invalid native manifest", {"X2W_TEST_NATIVE_GRAPHICS_BAD_MANIFEST": "1"},
(f"unsupported manifest version for {key}", f"native graphics {key} ready=0")),
)
for failure, override, diagnostics in retries:
manifest.rename(Path(str(manifest) + ".pending"))
retry_env = dict(env, X2W_TEST_PUBLISH_MANIFEST=str(manifest), **override)
run = subprocess.run(args, env=retry_env, capture_output=True, text=True, timeout=45)
assert run.returncode == 0 and all(text in run.stderr for text in diagnostics), run.stderr
assert Path(str(pixels) + ".first").read_bytes() == clear * 32
assert pixels.read_bytes() == (red * 4 + clear * 4) * 4
assert [path.read_bytes() for path in published] == contents
print(f"{adapter} {failure}: disk publication recovers the next draw in the same process")

ps.write_bytes(patched_pixel(1, [0xffffffff], export=(0xf800180f, 0x01000001)))
run = subprocess.run(args, env=env, capture_output=True, text=True, timeout=45)
assert run.returncode == 0 and "refused:" in run.stderr and "-> drawn;" not in run.stderr, run.stderr
assert pixels.read_bytes() == clear * 32
print("unsupported stage: all 32 pixels retain the clear color")
return 0


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