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 docs/startup-runtime.md
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,11 @@ the registers the routine loaded. The routine's code is not in the shader contai

The stand-in reads the `INPUT_LAYOUT` subobject and publishes it next to the request as `req_<key>.ia`, before
`.a`. The file holds `ia1 <count>` and then one line per element: semantic, index, format, slot, offset, class
and step rate. A stream with a non-empty layout includes that text in its cache key; other keys are unchanged.
and step rate. A stream with a non-empty layout includes that text in its cache key; other keys are unchanged. A layout declared
with zero elements publishes nothing by default, so the fetch is refused and not drawn, like an absent or unreadable
layout. With the experimental opt-in `X2W_STREAM_ZERO_FILL=1` it is published as the single line `ia1 0`, and the
translation reads every fetched register as zero. That zero value is an assumption, not a measurement: no independent
reference shows what a fetched input holds for a zero-element layout, so no startup claim rests on it.
One log line per stream gives the element count and, for each element, format, slot, offset and class:
`x2w-draw stream input layout: 2 elements (format/slot/offset/class) 6/0/0/0 6/0/4294967295/0`.

Expand Down
8 changes: 7 additions & 1 deletion src/startup_stubs/d3d12_draw.inl
Original file line number Diff line number Diff line change
Expand Up @@ -451,7 +451,13 @@ bool stream_input_layout(const unsigned char* subobject, std::string& text)
{
D3D12_INPUT_LAYOUT_DESC layout;
std::memcpy(&layout, subobject + 8, sizeof(layout));
if (!layout.NumElements) return true;
if (!layout.NumElements) {
// Declared without elements. The value of a fetched input here is unverified, so the zero-fill translation
// is an experimental opt-in (X2W_STREAM_ZERO_FILL=1); by default nothing is published and the fetch is refused.
const char* zero_fill = std::getenv("X2W_STREAM_ZERO_FILL");
if (zero_fill && zero_fill[0] == '1') text = "ia1 0\n";
return true;
}
if (layout.NumElements > D3D12_IA_VERTEX_INPUT_STRUCTURE_ELEMENT_COUNT ||
!x2w_local::readable(layout.pInputElementDescs, sizeof(D3D12_INPUT_ELEMENT_DESC) * layout.NumElements)) return false;
text = "ia1 " + std::to_string(layout.NumElements) + "\n";
Expand Down
38 changes: 36 additions & 2 deletions tests/startup_stream_fetch_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ def first_difference(actual, want):


class Run:
def __init__(self, directory, consumer, backend, vs_bytes, layout):
def __init__(self, directory, consumer, backend, vs_bytes, layout, zero_fill=False):
self.cache = directory / "cache"
self.cache.mkdir(parents=True)
self.vs, ps, self.root, self.output = (directory / name for name in ("vs", "ps", "root", "pixels"))
Expand All @@ -112,8 +112,11 @@ def __init__(self, directory, consumer, backend, vs_bytes, layout):
self.env = dict(os.environ, X2W_D3D12_PERMISSIVE="1", X2W_D3D12_LIST_NOOP="1", X2W_D3D12_RENDER="1",
X2W_SHADER_CACHE=str(self.cache), X2W_TEST_VERTEX_FETCH="1")
self.env.setdefault("X2W_D3D12_DEBUG", "0")
self.env.pop("X2W_STREAM_ZERO_FILL", None)
if zero_fill:
self.env["X2W_STREAM_ZERO_FILL"] = "1"
if layout:
self.env["X2W_TEST_INPUT_LAYOUT"] = "1"
self.env["X2W_TEST_INPUT_LAYOUT"] = layout if isinstance(layout, str) else "1"
else:
self.env.pop("X2W_TEST_INPUT_LAYOUT", None)
subprocess.run(self.args, env=self.env, check=True)
Expand Down Expand Up @@ -191,6 +194,29 @@ def patched(*args):
if "-> drawn;" in result.stderr:
raise AssertionError("a vertex shader with a fetch call and no layout was drawn")
print(f"{backend} no layout: refused and not drawn")

# empty layout, production default: declared with no elements, nothing is published and the fetch is refused.
refused = Run(directory / "empty_default", consumer, backend, vertex(), "empty")
assert not list(refused.cache.glob("req_*.ia")), "an empty layout was published without the opt-in"
result = refused.draw()
if "-> drawn;" in result.stderr:
raise AssertionError("an empty declared layout was drawn without X2W_STREAM_ZERO_FILL")
print(f"{backend} empty layout, default: refused and not drawn")

# empty layout, experimental opt-in X2W_STREAM_ZERO_FILL=1: every fetched input reads zero (an assumption, not a
# measurement); the vertices collapse and nothing but the blue clear reaches the readback.
empty = Run(directory / "empty", consumer, backend, vertex(), "empty", zero_fill=True)
layout = (empty.cache / ("req_%016x.ia" % empty.key)).read_bytes()
assert layout == b"ia1 0\n", layout
status = gfx2hlsl.translate_request(str(empty.cache), empty.key)
assert status == "ok", status
result = empty.draw()
if result.returncode or "-> drawn;" not in result.stderr:
raise RuntimeError(f"empty layout draw failed on {backend}: {result.returncode}\n{result.stderr}")
difference = first_difference(empty.output.read_bytes(), expected(lambda x, y: False))
if difference:
raise AssertionError(f"empty layout: {difference}")
print(f"{backend} empty layout: zero-fed vertices draw nothing, all {WIDTH * HEIGHT} pixels exact")
return 0


Expand Down Expand Up @@ -252,6 +278,14 @@ def translate_cases(directory):
for line in ("w = ldu(r0, a);", "v4 = w & 255u;", "v5 = (w >> 8) & 255u;", "v6 = (w >> 16) & 255u;"):
assert " %s\n" % line in vs, line + "\n" + vs

# A layout declared with no elements translates: no vertex-buffer load, every fetched register reads zero.
status, vs, manifest = translate(directory / "empty_layout", vertex(), "ia1 0\n")
assert status == "ok", status
for line in ("v4 = 0u;", "v6 = 0u;", "v8 = 0u;", "v10 = 0u;"):
assert " %s\n" % line in vs, line + "\n" + vs
assert "r0.Load(" not in vs and "buf vb" not in manifest, vs + manifest
print("translate: an empty declared layout reads every fetched input as zero")

# Refused: no layout; a register nothing defines; the only write masked off by exec, or bypassed by a branch.
for label, words, layout, want in (
("no layout", None, None, NO_LAYOUT),
Expand Down
5 changes: 4 additions & 1 deletion tests/startup_stream_setup.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,10 @@ int prepare_stream_pipeline(const char* vs_path, const char* ps_path, const char
&stream_alternate_root))) return 7;
}

LayoutStream with_layout{{D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT, {layout_elements, 2}},
wchar_t layout_mode[8] = L"";
GetEnvironmentVariableW(L"X2W_TEST_INPUT_LAYOUT", layout_mode, 8);
const bool empty_layout = std::wcscmp(layout_mode, L"empty") == 0; // declared layout with zero elements
LayoutStream with_layout{{D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT, {layout_elements, empty_layout ? 0u : 2u}},
{{D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, {ps.data(), ps.size()}},
{D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, root},
{D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, {vs.data(), vs.size()}}}};
Expand Down
13 changes: 12 additions & 1 deletion tools/startup/gfx2hlsl.py
Original file line number Diff line number Diff line change
Expand Up @@ -262,7 +262,8 @@ def starts_with_fetch_call(code):
def parse_input_layout(text):
"""'ia1 <n>' then one '<semantic> <index> <format> <slot> <offset> <class> <step>' line per element."""
lines = text.split('\n')
if not re.fullmatch(r'ia1 ([1-9]|[12][0-9]|3[0-2])', lines[0]) or lines[-1] != '' or len(lines) != int(lines[0][4:]) + 2:
# 'ia1 0' is a layout the pipeline declares with no elements: no fetched input has a source.
if not re.fullmatch(r'ia1 (0|[1-9]|[12][0-9]|3[0-2])', lines[0]) or lines[-1] != '' or len(lines) != int(lines[0][4:]) + 2:
raise Unsupported('invalid input layout request')
elements, ends = [], {}
for line in lines[1:-1]:
Expand Down Expand Up @@ -314,6 +315,12 @@ def stream_fetch(vs_container, layout_text):
if register not in inputs:
raise Unsupported('vertex fetch record for input register %d outside the signature' % register)
name, index, _ = inputs[register]
if not layout:
# Declared layout without elements: the input has no vertex buffer; its registers read as zero
# (shortcut: the zero default is an assumption, not a measurement).
fetch.append(dict(vgpr=vgpr, count=count, empty=True))
at += 5
continue
match = [e for e in layout if (e['name'], e['index']) == (name, index)]
if len(match) != 1:
raise Unsupported('input layout has %d elements for vertex input register %d' % (len(match), register))
Expand Down Expand Up @@ -4608,6 +4615,10 @@ def op_s_swappc_b64(self, ops, mods):
raise Unsupported('vertex stage calls a fetch routine and the pipeline declares no input layout')
base = self.pipe.ud(('basevertex',))
for e in self.pipe.vs_fetch:
if e.get('empty'):
for i in range(e['count']):
self.set_v(e['vgpr'] + i, '0u')
continue
key = (('vbtab',), 16 * e['slot'])
buf = self.pipe.resource(key, 'buf')
stride = self.pipe.ud(('stride', self.pipe.resources[key]['index']))
Expand Down
Loading