upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/tests
diff options
context:
space:
mode:
authorDiesel <dev.diesel@proton.me>2026-11-21 22:44:07 +0100
committerDiesel <dev.diesel@proton.me>2026-11-21 22:44:07 +0100
commit5c1a1fbb6bf6f609eb4e61baa4961ce382743a4e (patch)
treeac8ad90058b97ab241fdc65edae3d4628d20ee1e /tests
parentc45309e29f21c1d5b75678db0e2dc2dd11cff25b (diff)
parent4e390e0871d7265e629b51aca8ff99a15a6a6845 (diff)
Merge main to include the compute Y/Z harness test fix
Diffstat (limited to 'tests')
-rw-r--r--tests/conftest.py47
-rw-r--r--tests/semantic/test_mutations.py7
-rw-r--r--tests/semantic/test_scalar_mem_smem.py203
-rw-r--r--tests/test_awc_manifest.py19
-rw-r--r--tests/test_awc_opus.py81
-rw-r--r--tests/test_classify_carve.py152
-rw-r--r--tests/test_gamedata_xml.py211
-rw-r--r--tests/test_gen_d3d12_stubs.py254
-rw-r--r--tests/test_manifest.py34
-rw-r--r--tests/test_mc_command.py61
-rw-r--r--tests/test_rbf0_tree.py321
-rw-r--r--tests/test_root_sig_contract.py110
-rw-r--r--tests/test_rpf9_carve.py33
-rw-r--r--tests/test_rpf_probe.py153
-rw-r--r--tests/test_shader_checks.py6
-rw-r--r--tests/test_shader_ir.py226
-rw-r--r--tests/test_translate.py23
-rw-r--r--tests/test_ttpf_mips.py291
-rw-r--r--tests/test_world_census.py167
19 files changed, 2387 insertions, 12 deletions
diff --git a/tests/conftest.py b/tests/conftest.py
index c78e0209a..f614163c5 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -17,13 +17,46 @@ import pytest
17ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 17ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
18sys.path.insert(0, os.path.join(ROOT, "tools")) 18sys.path.insert(0, os.path.join(ROOT, "tools"))
19 19
20import mc_command # noqa: E402
20import rdna2spirv # noqa: E402 21import rdna2spirv # noqa: E402
21 22
22 23
24def _repair_stdin_handle():
25 """Windows, under pytest's fd capture: give the children the tests start a stdin that is open.
26
27 The capture replaces fd 0 with os.dup2(), which closes the handle fd 0 had, while the process's
28 STD_INPUT_HANDLE keeps that handle's number. subprocess starts from GetStdHandle(), not from fd 0, so a child
29 started without stdin=/input= fails with "[WinError 6] The handle is invalid" or, when the number has been
30 reused meanwhile, gets whatever file now has it. Which one depends on what ran before, so the failures move
31 from run to run. With -s or --capture=sys, and without pytest, the two handles agree and nothing is done.
32 """
33 if sys.platform != "win32":
34 return
35 import ctypes
36 import msvcrt
37 kernel32 = ctypes.WinDLL("kernel32")
38 kernel32.GetStdHandle.restype = ctypes.c_void_p
39 kernel32.GetStdHandle.argtypes = [ctypes.c_uint32]
40 kernel32.SetStdHandle.argtypes = [ctypes.c_uint32, ctypes.c_void_p]
41 std_input = 0xFFFFFFF6 # STD_INPUT_HANDLE, (DWORD)-10
42 handle = kernel32.GetStdHandle(std_input)
43 try:
44 fd0 = msvcrt.get_osfhandle(0)
45 except OSError:
46 fd0 = None
47 if not handle or handle == fd0: # no stdin at all (subprocess copes), or not redirected
48 return
49 # A NUL of our own, never closed: fd 0's handle would go stale again the next time the capture swaps fd 0.
50 kernel32.SetStdHandle(std_input, msvcrt.get_osfhandle(os.open(os.devnull, os.O_RDONLY)))
51
52
53_repair_stdin_handle() # before the llvm-mc probe below, which is the first child
54
55
23def _has_amdgpu(mc): 56def _has_amdgpu(mc):
24 """True if this llvm-mc was built with the AMDGPU target (the official Windows release archives are not).""" 57 """True if this llvm-mc was built with the AMDGPU target (the official Windows release archives are not)."""
25 try: 58 try:
26 r = subprocess.run([mc, "--version"], capture_output=True, text=True, timeout=60) 59 r = subprocess.run(mc + ["--version"], capture_output=True, text=True, timeout=60)
27 except (OSError, subprocess.SubprocessError): 60 except (OSError, subprocess.SubprocessError):
28 return False 61 return False
29 return "amdgcn" in r.stdout 62 return "amdgcn" in r.stdout
@@ -33,12 +66,14 @@ def _find_llvm_mc():
33 candidates = [] 66 candidates = []
34 env = os.environ.get("LLVM_MC") 67 env = os.environ.get("LLVM_MC")
35 if env: 68 if env:
36 candidates.append(shutil.which(env)) # None when the path doesn't exist 69 candidates.append(mc_command.split_command(env))
37 candidates.append(shutil.which("llvm-mc")) 70 found = shutil.which("llvm-mc")
71 if found:
72 candidates.append([found])
38 # Debian/Ubuntu install it versioned, out of PATH. 73 # Debian/Ubuntu install it versioned, out of PATH.
39 candidates += sorted(glob.glob("/usr/lib/llvm-*/bin/llvm-mc"), reverse=True) 74 candidates += [[p] for p in sorted(glob.glob("/usr/lib/llvm-*/bin/llvm-mc"), reverse=True)]
40 # Default location of the official Windows installer, which doesn't add LLVM to PATH unless asked to. 75 # Default location of the official Windows installer, which doesn't add LLVM to PATH unless asked to.
41 candidates += glob.glob(r"C:\Program Files\LLVM\bin\llvm-mc.exe") 76 candidates += [[p] for p in glob.glob(r"C:\Program Files\LLVM\bin\llvm-mc.exe")]
42 for c in candidates: 77 for c in candidates:
43 if c and _has_amdgpu(c): 78 if c and _has_amdgpu(c):
44 return c 79 return c
@@ -126,7 +161,7 @@ class Shader:
126 rsrc2, (lx, ly, lz) = cs_header 161 rsrc2, (lx, ly, lz) = cs_header
127 (workdir / "fssm").mkdir(exist_ok=True) 162 (workdir / "fssm").mkdir(exist_ok=True)
128 (workdir / "fssm" / f"{name}.fssm").write_bytes(bytes(0x138) + struct.pack("<4I", rsrc2, lx, ly, lz)) 163 (workdir / "fssm" / f"{name}.fssm").write_bytes(bytes(0x138) + struct.pack("<4I", rsrc2, lx, ly, lz))
129 cmd = [LLVM_MC, "-triple=amdgcn--amdpal", "-mcpu=gfx1013"] 164 cmd = LLVM_MC + ["-triple=amdgcn--amdpal", "-mcpu=gfx1013"]
130 for ln in asm.splitlines(): 165 for ln in asm.splitlines():
131 s = ln.strip() 166 s = ln.strip()
132 if not s: 167 if not s:
diff --git a/tests/semantic/test_mutations.py b/tests/semantic/test_mutations.py
index cce2b723a..0caca1d46 100644
--- a/tests/semantic/test_mutations.py
+++ b/tests/semantic/test_mutations.py
@@ -103,8 +103,11 @@ MUTATIONS = [
103 103
104 104
105def run_semantics(tools_dir): 105def run_semantics(tools_dir):
106 env = dict(os.environ, LEONIDA_TOOLS_DIR=tools_dir, PYTHONDONTWRITEBYTECODE="1") 106 # The child finds test_ps_semantics through PYTHONPATH, not cwd=HERE: Windows refuses a working directory longer
107 p = subprocess.run([sys.executable, "-m", "unittest", "test_ps_semantics", "-v"], cwd=HERE, env=env, 107 # than 258 characters (WinError 267), which a checkout in a deep folder reaches.
108 path = os.pathsep.join(filter(None, [HERE, os.environ.get("PYTHONPATH")]))
109 env = dict(os.environ, LEONIDA_TOOLS_DIR=tools_dir, PYTHONDONTWRITEBYTECODE="1", PYTHONPATH=path)
110 p = subprocess.run([sys.executable, "-m", "unittest", "test_ps_semantics", "-v"], env=env,
108 capture_output=True, text=True, timeout=300) 111 capture_output=True, text=True, timeout=300)
109 return p.returncode, p.stdout + p.stderr 112 return p.returncode, p.stdout + p.stderr
110 113
diff --git a/tests/semantic/test_scalar_mem_smem.py b/tests/semantic/test_scalar_mem_smem.py
index a8e6cbde1..b9329793d 100644
--- a/tests/semantic/test_scalar_mem_smem.py
+++ b/tests/semantic/test_scalar_mem_smem.py
@@ -13,6 +13,8 @@ Covers AMD RDNA2 / GFX10 SMEM (Scalar Memory) ISA semantics and tools/rdna2spirv
13 * Multi-dword scalar loads (s_load_dword, s_load_dwordx2, x4, x8, x16) with sequential 4-byte address strides 13 * Multi-dword scalar loads (s_load_dword, s_load_dwordx2, x4, x8, x16) with sequential 4-byte address strides
14 * Destination register targeting: SGPR ranges and special registers (vcc_lo, vcc_hi, vcc pair, m0) 14 * Destination register targeting: SGPR ranges and special registers (vcc_lo, vcc_hi, vcc pair, m0)
15 * tools/rdna2spirv.py translator validation (Gen.scalar_load instruction sequences and operand validation) 15 * tools/rdna2spirv.py translator validation (Gen.scalar_load instruction sequences and operand validation)
16 * SMEM loads with a register offset and an immediate at once ("sOFF offset:IMM"): address = base + sOFF + IMM,
17 checked by running the emitted code (SmemBodyEvaluator, SmemSoffsetImmTranslatorTests)
16 * spirv_mini_interp strictness validation (rejecting unmodelled 64-bit types and PhysicalStorageBuffer) 18 * spirv_mini_interp strictness validation (rejecting unmodelled 64-bit types and PhysicalStorageBuffer)
17""" 19"""
18import os 20import os
@@ -372,6 +374,207 @@ class SmemTranslatorGenTests(unittest.TestCase):
372 g.scalar_load(ins_vgpr_base["op"], ins_vgpr_base["args"], ins_vgpr_base["mods"]) 374 g.scalar_load(ins_vgpr_base["op"], ins_vgpr_base["args"], ins_vgpr_base["mods"])
373 375
374 376
377class SmemBodyEvaluator:
378 """Runs the straight-line SPIR-V that Gen.scalar_load emits, against concrete SGPR values and a dword memory.
379
380 spirv_mini_interp refuses 64-bit integers and PhysicalStorageBuffer by design, so the address a scalar load
381 reads cannot be checked there. This evaluator knows only the handful of instructions scalar_load uses and
382 raises on anything else, so a change in the emitted code cannot be approximated silently. The heap base (push
383 constant dwords 32..33) is 0 unless given, which makes every address read an Xbox VA.
384 """
385
386 def __init__(self, gen, sgpr, memory, heap_base=0):
387 self.consts = {name: value for value, name in gen.consts.items()}
388 self.sgpr = dict(sgpr)
389 self.memory = memory
390 self.heap_base = heap_base
391 self.ids = {}
392 self.reads = [] # byte address of every PhysicalStorageBuffer dword load, in order
393 for line in gen.body:
394 self._step(line.split())
395
396 def _value(self, name):
397 if name == "%c64_32":
398 return 32
399 if name in self.ids:
400 return self.ids[name]
401 if name in self.consts:
402 return self.consts[name]
403 raise AssertionError(f"unknown id {name}")
404
405 def _step(self, words):
406 if words[0] == "OpStore":
407 kind, index = self._value(words[1])
408 if kind != "sgpr":
409 raise AssertionError(f"store through {kind}")
410 self.sgpr[index] = self._value(words[2])
411 return
412 if len(words) < 4 or words[1] != "=":
413 raise AssertionError("unmodelled line: " + " ".join(words))
414 result, op, ty, args = words[0], words[2], words[3], words[4:]
415 if op == "OpAccessChain" and ty == "%_ptr_Function_uint" and args[0] == "%sgpr":
416 value = ("sgpr", self._value(args[1]))
417 elif op == "OpAccessChain" and ty == "%_ptr_PSB_uint":
418 kind, address = self._value(args[0])
419 if kind != "psb":
420 raise AssertionError(f"PSB access chain on {kind}")
421 value = ("mem", (address + 4 * self._value(args[1])) & MASK64)
422 elif op == "OpLoad" and ty == "%uint" and args[0] == "%ud_base_lo_p":
423 value = self.heap_base & MASK32
424 elif op == "OpLoad" and ty == "%uint" and args[0] == "%ud_base_hi_p":
425 value = (self.heap_base >> 32) & MASK32
426 elif op == "OpLoad" and ty == "%uint":
427 kind, where = self._value(args[0])
428 if kind == "sgpr":
429 value = self.sgpr.get(where, 0) & MASK32
430 elif kind == "mem" and args[1:] == ["Aligned", "4"]:
431 self.reads.append(where)
432 value = self.memory.read_dword(where)
433 else:
434 raise AssertionError("unmodelled load: " + " ".join(words))
435 elif op == "OpBitwiseAnd" and ty == "%uint":
436 value = self._value(args[0]) & self._value(args[1])
437 elif op == "OpIAdd" and ty == "%uint":
438 value = (self._value(args[0]) + self._value(args[1])) & MASK32
439 elif op == "OpUConvert" and ty == "%ulong":
440 value = self._value(args[0]) & MASK32
441 elif op == "OpShiftLeftLogical" and ty == "%ulong":
442 value = (self._value(args[0]) << self._value(args[1])) & MASK64
443 elif op == "OpBitwiseOr" and ty == "%ulong":
444 value = self._value(args[0]) | self._value(args[1])
445 elif op == "OpIAdd" and ty == "%ulong":
446 value = (self._value(args[0]) + self._value(args[1])) & MASK64
447 elif op == "OpConvertUToPtr" and ty == "%_ptr_PSB_arr":
448 value = ("psb", self._value(args[0]))
449 else:
450 raise AssertionError("unmodelled instruction: " + " ".join(words))
451 self.ids[result] = value
452
453
454class SmemSoffsetImmTranslatorTests(unittest.TestCase):
455 """SMEM loads that carry a register offset and an immediate at once: llvm-mc prints "sOFF offset:IMM".
456
457 Rule: address = base + soffset + imm (+ 4*i for dword i).
458 Measured on an AMD Radeon RX 6800 (gfx1030) by running s_buffer_load_dword/x2/x4/x8 as a raw compute kernel:
459 soffset 8 + imm 4 reads the dword at +12. s_load_dword* with both offsets was not measured; it shares the SMEM
460 encoding (soffset_en + imm), so the same rule is applied to it as an inference.
461 The hardware also truncates base, soffset and imm each to a multiple of 4 and returns 0 past NUM_RECORDS; the
462 translator does neither, so every case here is dword-aligned and in bounds.
463
464 The instruction lines are hand-written. Each case runs the code Gen.scalar_load emits with SmemBodyEvaluator
465 and asserts both the addresses read and the values that land in the destination SGPRs.
466 """
467
468 VSHARP_BASE = 0x0000000200001000 # s24 = 0x00001000, s25 = 0x80040002 (flags above bit 15 are not address)
469 POINTER = 0x0000000300004000 # s[24:25] for s_load
470
471 def run_load(self, line, pointer=False):
472 ins = parse_line(line)
473 g = rdna2spirv.Gen("ps")
474 g.scalar_load(ins["op"], ins["args"], ins["mods"])
475 base = self.POINTER if pointer else self.VSHARP_BASE
476 bank = SmemMemoryBank()
477 for off in range(0, 0x40, 4): # every dword near the base holds its own offset, tagged
478 bank.write_dword(base + off, 0x5EED0000 | off)
479 sgpr = {40: 8} # the register offset used by every case
480 if pointer:
481 sgpr.update({24: 0x00004000, 25: 0x00000003})
482 else:
483 sgpr.update({24: 0x00001000, 25: 0x80040002, 26: 0x00010000, 27: 0x00140000})
484 ev = SmemBodyEvaluator(g, sgpr, bank)
485 return ev, [a - base for a in ev.reads], g
486
487 def test_s_buffer_load_dword_soffset_plus_imm(self):
488 # The measured case: soffset 8 + imm 4 reads the dword at +12 (not +8, which is what dropping the imm gives).
489 ev, offsets, _ = self.run_load("s_buffer_load_dword s12, s[24:27], s40 offset:0x4")
490 self.assertEqual(offsets, [12])
491 self.assertEqual(ev.sgpr[12], 0x5EED000C)
492
493 def test_s_load_dword_soffset_plus_imm(self):
494 # Inferred from the shared SMEM encoding; not measured on hardware.
495 ev, offsets, _ = self.run_load("s_load_dword s12, s[24:25], s40 offset:0x4", pointer=True)
496 self.assertEqual(offsets, [12])
497 self.assertEqual(ev.sgpr[12], 0x5EED000C)
498
499 def test_multi_dword_soffset_plus_imm(self):
500 cases = [
501 ("s_buffer_load_dwordx2 s[12:13], s[24:27], s40 offset:0x4", False, 2, 0x0C),
502 ("s_buffer_load_dwordx4 s[12:15], s[24:27], s40 offset:0x10", False, 4, 0x18),
503 ("s_buffer_load_dwordx8 s[12:19], s[24:27], s40 offset:0x14", False, 8, 0x1C),
504 ("s_load_dwordx2 s[12:13], s[24:25], s40 offset:0x4", True, 2, 0x0C),
505 ("s_load_dwordx4 s[12:15], s[24:25], s40 offset:0x10", True, 4, 0x18),
506 ]
507 for line, pointer, n, first in cases:
508 with self.subTest(line=line):
509 ev, offsets, _ = self.run_load(line, pointer)
510 self.assertEqual(offsets, [first + 4 * i for i in range(n)])
511 self.assertEqual([ev.sgpr[12 + i] for i in range(n)], [0x5EED0000 | (first + 4 * i) for i in range(n)])
512
513 def test_imm_only_and_soffset_only_addresses_unchanged(self):
514 cases = [
515 ("s_buffer_load_dword s12, s[24:27], 0x4", False, [0x04]),
516 ("s_buffer_load_dword s12, s[24:27], s40", False, [0x08]),
517 ("s_buffer_load_dwordx2 s[12:13], s[24:27], 0x10", False, [0x10, 0x14]),
518 ("s_buffer_load_dwordx4 s[12:15], s[24:27], s40", False, [0x08, 0x0C, 0x10, 0x14]),
519 ("s_load_dword s12, s[24:25], 0x4", True, [0x04]),
520 ("s_load_dword s12, s[24:25], s40", True, [0x08]),
521 ("s_load_dwordx2 s[12:13], s[24:25], 0", True, [0x00, 0x04]),
522 ("s_load_dwordx2 s[12:13], s[24:25], s40", True, [0x08, 0x0C]),
523 ]
524 for line, pointer, want in cases:
525 with self.subTest(line=line):
526 ev, offsets, _ = self.run_load(line, pointer)
527 self.assertEqual(offsets, want)
528 self.assertEqual([ev.sgpr[12 + i] for i in range(len(want))], [0x5EED0000 | o for o in want])
529
530 def test_zero_imm_with_soffset_reads_the_soffset_address(self):
531 ev, offsets, _ = self.run_load("s_buffer_load_dword s12, s[24:27], s40 offset:0x0")
532 self.assertEqual(offsets, [8])
533 self.assertEqual(ev.sgpr[12], 0x5EED0008)
534
535 def test_non_sgpr_scalar_register_offset_plus_imm(self):
536 # llvm-mc also accepts m0, vcc_lo or null as the register offset. null reads as zero; m0 is not an SGPR slot,
537 # so only check that the form still translates and that the immediate changes the code.
538 ev, offsets, _ = self.run_load("s_buffer_load_dword s12, s[24:27], null offset:0x14")
539 self.assertEqual(offsets, [0x14])
540 self.assertEqual(ev.sgpr[12], 0x5EED0014)
541 bodies = []
542 for line in ("s_buffer_load_dword s12, s[24:27], m0", "s_buffer_load_dword s12, s[24:27], m0 offset:0x4"):
543 ins = parse_line(line)
544 g = rdna2spirv.Gen("ps")
545 g.scalar_load(ins["op"], ins["args"], ins["mods"])
546 bodies.append(g.body)
547 self.assertNotEqual(bodies[0], bodies[1])
548
549 def test_offset_modifier_changes_the_emitted_code(self):
550 for line, pointer in (("s_buffer_load_dword s12, s[24:27], s40", False),
551 ("s_load_dword s12, s[24:25], s40", True)):
552 with self.subTest(line=line):
553 _, _, plain = self.run_load(line, pointer)
554 _, _, both = self.run_load(line + " offset:0x4", pointer)
555 self.assertNotEqual(plain.body, both.body)
556
557 def test_heap_base_is_added_once(self):
558 ins = parse_line("s_buffer_load_dword s12, s[24:27], s40 offset:0x4")
559 g = rdna2spirv.Gen("ps")
560 g.scalar_load(ins["op"], ins["args"], ins["mods"])
561 ev = SmemBodyEvaluator(g, {24: 0x1000, 25: 0, 40: 8}, SmemMemoryBank(), heap_base=0x0000007F00000000)
562 self.assertEqual(ev.reads, [0x0000007F00000000 + 0x1000 + 12])
563
564 def test_offset_forms_the_assembler_rejects_raise(self):
565 # llvm-mc accepts none of these; hand-written or damaged listings must not translate to a guessed address.
566 for line in ("s_buffer_load_dword s12, s[24:27], 0x8 offset:0x4", # immediate operand and offset modifier
567 "s_buffer_load_dword s12, s[24:27], s40 offset:zz", # unparseable immediate
568 "s_buffer_load_dword s12, s[24:27], s40 offset:0x4 offset:0x8",
569 "s_buffer_load_dword s12, s[24:27], s40, 0x4", # a fourth operand
570 "s_load_dword s12, s[24:25], 0x8 offset:0x4"):
571 with self.subTest(line=line):
572 ins = parse_line(line)
573 g = rdna2spirv.Gen("ps")
574 with self.assertRaises(rdna2spirv.Unsupported):
575 g.scalar_load(ins["op"], ins["args"], ins["mods"])
576
577
375class SmemMiniInterpStrictnessTests(unittest.TestCase): 578class SmemMiniInterpStrictnessTests(unittest.TestCase):
376 """Verifies that spirv_mini_interp rejects storage classes and constructs it does not model. 579 """Verifies that spirv_mini_interp rejects storage classes and constructs it does not model.
377 580
diff --git a/tests/test_awc_manifest.py b/tests/test_awc_manifest.py
index acc8e12a6..651e21155 100644
--- a/tests/test_awc_manifest.py
+++ b/tests/test_awc_manifest.py
@@ -18,8 +18,8 @@ def fmt(samples, rate, codec, channels):
18 return bytes(block) 18 return bytes(block)
19 19
20 20
21def music_blob(ids, samples, rate): 21def music_blob(ids, samples, rate, toc=0xF8):
22 """(descriptor, data) for one block of mono Opus channels.""" 22 """(descriptor, data) for one block of Opus channels. toc is the packet TOC byte."""
23 desc = bytearray(12 + 16 * len(ids)) 23 desc = bytearray(12 + 16 * len(ids))
24 struct.pack_into("<III", desc, 0, 1, 2048, len(ids)) 24 struct.pack_into("<III", desc, 0, 1, 2048, len(ids))
25 for i, cid in enumerate(ids): 25 for i, cid in enumerate(ids):
@@ -31,7 +31,7 @@ def music_blob(ids, samples, rate):
31 for i in range(len(ids)): 31 for i in range(len(ids)):
32 struct.pack_into("<I", data, 24 * i + 4, 1) # subblock count; skip stays 0 32 struct.pack_into("<I", data, 24 * i + 4, 1) # subblock count; skip stays 0
33 struct.pack_into("<H", data, 2048 + 2048 * i, 1) 33 struct.pack_into("<H", data, 2048 + 2048 * i, 1)
34 data[2050 + 2048 * i] = 0xF8 # CELT 20 ms, one frame 34 data[2050 + 2048 * i] = toc # CELT 20 ms, one frame (stereo when bit 2 is set)
35 return bytes(desc), bytes(data) 35 return bytes(desc), bytes(data)
36 36
37 37
@@ -132,6 +132,19 @@ class ManifestTest(unittest.TestCase):
132 self.assertIs(doc["streams"][0]["streamed_music"], False) 132 self.assertIs(doc["streams"][0]["streamed_music"], False)
133 self.assertAlmostEqual(doc["streams"][0]["duration_s"], 0.1, places=6) 133 self.assertAlmostEqual(doc["streams"][0]["duration_s"], 0.1, places=6)
134 134
135 def test_stereo_streamed_music_uses_packet_channels_and_per_channel_samples(self):
136 desc, data = music_blob([0x40], 1920, 48000, toc=0xFC) # 2 x 960 interleaved samples
137 path = os.path.join(self.tmp.name, "stereo.awc")
138 with open(path, "wb") as f:
139 f.write(build_bank([(0x50, [(0x48, desc), (0x55, data)])]))
140 p = self.run_tool(path)
141 self.assertEqual(p.returncode, 0, p.stderr)
142 rows = {r["stream"]: r for r in csv.DictReader(io.StringIO(p.stdout))}
143 row = rows["00000040"]
144 self.assertEqual((row["channels"], row["declared_samples"]), ("2", "960"))
145 self.assertAlmostEqual(float(row["duration_s"]), 0.02, places=6)
146 self.assertEqual(row["streamed_music"], "yes")
147
135 148
136if __name__ == "__main__": 149if __name__ == "__main__":
137 unittest.main(verbosity=2) 150 unittest.main(verbosity=2)
diff --git a/tests/test_awc_opus.py b/tests/test_awc_opus.py
index 654fd85f7..5de874627 100644
--- a/tests/test_awc_opus.py
+++ b/tests/test_awc_opus.py
@@ -116,6 +116,33 @@ def build_bank(streams):
116 return bytes(out) 116 return bytes(out)
117 117
118 118
119def build_music_bank(tocs, samples, rate=48000):
120 """A one-stream AWC with a 0x48 streamed-music descriptor and one 2048-byte block.
121
122 tocs: one Opus TOC byte per descriptor channel, each in its own 2048-byte subblock.
123 samples: the descriptor's interleaved sample count (per-channel frames * packet channels).
124 """
125 channels = len(tocs)
126 desc = bytearray(12 + 16 * channels)
127 struct.pack_into("<III", desc, 0, 1, 2048, channels)
128 for i, toc in enumerate(tocs):
129 base = 12 + 16 * i
130 struct.pack_into("<II", desc, base, 0x100 + i, samples)
131 struct.pack_into("<H", desc, base + 10, rate)
132 desc[base + 12] = 0x0B
133 data = bytearray(2048 + 2048 * channels)
134 for i in range(channels):
135 struct.pack_into("<I", data, 24 * i + 4, 1) # one subblock
136 struct.pack_into("<H", data, 2048 + 2048 * i, 1)
137 data[2050 + 2048 * i] = tocs[i]
138 header = 16 + 4 + 2 * 8
139 out = bytearray(b"ADAT" + struct.pack("<III", 0, 1, header))
140 out += struct.pack("<I", 0x20 | (2 << 29))
141 out += struct.pack("<Q", tag(0x48, header, len(desc)))
142 out += struct.pack("<Q", tag(0x55, header + len(desc), len(data)))
143 return bytes(out + desc + data)
144
145
119class WriteWavTest(unittest.TestCase): 146class WriteWavTest(unittest.TestCase):
120 def setUp(self): 147 def setUp(self):
121 self.tmp = tempfile.TemporaryDirectory() 148 self.tmp = tempfile.TemporaryDirectory()
@@ -259,6 +286,60 @@ class ExportBankTest(unittest.TestCase):
259 self.assertEqual(last["serial"], 3) 286 self.assertEqual(last["serial"], 3)
260 287
261 288
289class StreamedMusicTest(unittest.TestCase):
290 def setUp(self):
291 self.tmp = tempfile.TemporaryDirectory()
292 self.addCleanup(self.tmp.cleanup)
293 self.out = os.path.join(self.tmp.name, "out")
294
295 def export(self, tocs, samples):
296 path = os.path.join(self.tmp.name, "streamed.awc")
297 with open(path, "wb") as f:
298 f.write(build_music_bank(tocs, samples))
299 counts = awc.export_bank(path, self.out)
300 return counts, os.path.join(self.out, "streamed")
301
302 def test_stereo_packets_export_one_stereo_ogg(self):
303 counts, od = self.export([0xFC], 1920) # 2 x 960 interleaved samples
304 self.assertEqual(counts, {"opus": 0, "pcm": 0, "other": 0, "music": 1})
305 with open(os.path.join(od, "00000100.ogg"), "rb") as f:
306 pages = parse_ogg_pages(f.read())
307 version, channels, preskip, in_rate, gain, mapping = struct.unpack_from("<BBHIhB", pages[0]["body"], 8)
308 self.assertEqual((version, channels, preskip, in_rate, gain, mapping), (1, 2, 0, 48000, 0, 0))
309 self.assertEqual(pages[-1]["granule"], 960)
310
311 def test_two_mono_groups_export_two_mono_oggs(self):
312 counts, od = self.export([0x78, 0x78], 960)
313 self.assertEqual(counts, {"opus": 0, "pcm": 0, "other": 0, "music": 2})
314 for sid in ("00000100", "00000101"):
315 with self.subTest(sid=sid):
316 with open(os.path.join(od, sid + ".ogg"), "rb") as f:
317 pages = parse_ogg_pages(f.read())
318 channels = pages[0]["body"][9]
319 self.assertEqual(channels, 1)
320 self.assertEqual(pages[-1]["granule"], 960)
321
322 def test_music_channels_halves_interleaved_samples(self):
323 path = os.path.join(self.tmp.name, "streamed.awc")
324 with open(path, "wb") as f:
325 f.write(build_music_bank([0xFC], 1920))
326 with open(path, "rb") as f:
327 d = f.read()
328 _, music = awc.parse_awc(d)
329 info = awc.music_channels(d, music[0][0], music[0][1])
330 self.assertEqual((info[0][1], info[0][5]), (960, 2))
331
332 def test_music_channels_metadata_only_still_reports_packet_channels(self):
333 path = os.path.join(self.tmp.name, "streamed.awc")
334 with open(path, "wb") as f:
335 f.write(build_music_bank([0xFC], 1920))
336 with open(path, "rb") as f:
337 d = f.read()
338 _, music = awc.parse_awc(d)
339 info = awc.music_channels(d, music[0][0], music[0][1], collect_packets=False)
340 self.assertEqual((info[0][1], info[0][4], info[0][5]), (960, [], 2))
341
342
262class MalformedBankTest(unittest.TestCase): 343class MalformedBankTest(unittest.TestCase):
263 def test_bad_magic_raises_value_error(self): 344 def test_bad_magic_raises_value_error(self):
264 with tempfile.TemporaryDirectory() as tmp: 345 with tempfile.TemporaryDirectory() as tmp:
diff --git a/tests/test_classify_carve.py b/tests/test_classify_carve.py
new file mode 100644
index 000000000..b0af5a543
--- /dev/null
+++ b/tests/test_classify_carve.py
@@ -0,0 +1,152 @@
1"""Tests for tools/classify_carve.py, built from synthetic carve indexes (no game data).
2
3 python -I tests/test_classify_carve.py
4"""
5import contextlib
6import importlib.util
7import io
8import json
9import os
10import tempfile
11import unittest
12from unittest import mock
13
14ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
15
16ZERO_HEAD = "00" * 16
17RBF0_HEAD = "5242463000000000"
18RESPAGE_HEAD = "42400000deadbeef"
19
20
21def load_module():
22 path = os.path.join(ROOT, "tools", "classify_carve.py")
23 spec = importlib.util.spec_from_file_location("classify_carve_under_test", path)
24 module = importlib.util.module_from_spec(spec)
25 spec.loader.exec_module(module)
26 return module
27
28
29carve = load_module()
30
31
32class ClassifyTests(unittest.TestCase):
33 def test_bink2_rows_do_not_need_a_head(self):
34 # rpf9_carve writes bink2 rows with dimensions and no head field.
35 self.assertEqual(carve.classify({"type": "bink2", "size": 12}), "bink2")
36
37 def test_bink2_wins_over_a_signature(self):
38 self.assertEqual(carve.classify({"type": "bink2", "head": RBF0_HEAD, "size": 1}), "bink2")
39
40 def test_rbf0_metadata(self):
41 self.assertEqual(carve.classify({"head": RBF0_HEAD, "size": 1}), "rbf0")
42
43 def test_resource_page(self):
44 self.assertEqual(carve.classify({"head": RESPAGE_HEAD, "size": 1}), "respage")
45
46 def test_gpu_zero_header_needs_sixteen_zero_bytes(self):
47 self.assertEqual(carve.classify({"head": ZERO_HEAD, "size": 1}), "gpu-zerohdr")
48 # Fifteen zero bytes are not enough, and the fallback names four bytes.
49 self.assertEqual(carve.classify({"head": "00" * 15, "size": 1}), "other:00000000")
50
51 def test_other_is_keyed_by_the_first_four_bytes(self):
52 self.assertEqual(carve.classify({"head": "deadbeefcafebabe", "size": 1}), "other:deadbeef")
53
54 def test_short_head_is_used_as_is(self):
55 self.assertEqual(carve.classify({"head": "abcd", "size": 1}), "other:abcd")
56
57 def test_signature_must_be_at_the_start(self):
58 self.assertEqual(carve.classify({"head": "ff" + RBF0_HEAD, "size": 1}), "other:ff524246")
59
60
61class MainTests(unittest.TestCase):
62 def setUp(self):
63 tmp = tempfile.TemporaryDirectory()
64 self.addCleanup(tmp.cleanup)
65 self.root = tmp.name
66
67 def archive(self, name, rows):
68 path = os.path.join(self.root, name)
69 os.makedirs(path, exist_ok=True)
70 with open(os.path.join(path, "index.json"), "w", encoding="utf-8") as f:
71 json.dump({"files": rows}, f)
72 return path
73
74 def run_main(self):
75 out = io.StringIO()
76 with mock.patch("sys.argv", ["classify_carve.py", self.root]), contextlib.redirect_stdout(out):
77 carve.main()
78 return out.getvalue()
79
80 def types(self):
81 with open(os.path.join(self.root, "types.json"), encoding="utf-8") as f:
82 return json.load(f)
83
84 def test_counts_and_bytes_are_aggregated_per_class(self):
85 self.archive("a", [
86 {"head": RBF0_HEAD, "size": 10},
87 {"head": "5242463000000001", "size": 30},
88 {"head": ZERO_HEAD, "size": 5},
89 {"head": "deadbeefcafebabe", "size": 7},
90 {"type": "bink2", "size": 3},
91 ])
92 self.run_main()
93 types = self.types()
94 a = types["per_archive"]["a"]
95 self.assertEqual(a["rbf0"], {"files": 2, "bytes": 40})
96 self.assertEqual(a["gpu-zerohdr"], {"files": 1, "bytes": 5})
97 self.assertEqual(a["other:deadbeef"], {"files": 1, "bytes": 7})
98 self.assertEqual(a["bink2"], {"files": 1, "bytes": 3})
99 self.assertEqual(types["overall"]["rbf0"], {"files": 2, "bytes": 40})
100
101 def test_overall_sums_across_archives(self):
102 self.archive("a", [{"head": RBF0_HEAD, "size": 10}])
103 self.archive("b", [{"head": RBF0_HEAD, "size": 25}])
104 self.run_main()
105 types = self.types()
106 self.assertEqual(types["overall"]["rbf0"], {"files": 2, "bytes": 35})
107 self.assertEqual(types["per_archive"]["a"]["rbf0"], {"files": 1, "bytes": 10})
108
109 def test_archives_are_listed_in_name_order(self):
110 self.archive("b", [{"head": RBF0_HEAD, "size": 1}])
111 self.archive("a", [{"head": RBF0_HEAD, "size": 1}])
112 self.run_main()
113 self.assertEqual(list(self.types()["per_archive"]), ["a", "b"])
114
115 def test_classes_are_ordered_by_bytes_descending(self):
116 self.archive("a", [
117 {"head": RBF0_HEAD, "size": 50},
118 {"head": ZERO_HEAD, "size": 500},
119 ])
120 self.run_main()
121 types = self.types()
122 self.assertEqual(list(types["per_archive"]["a"]), ["gpu-zerohdr", "rbf0"])
123 self.assertEqual(list(types["overall"]), ["gpu-zerohdr", "rbf0"])
124
125 def test_directory_without_an_index_is_skipped(self):
126 self.archive("a", [{"head": RBF0_HEAD, "size": 1}])
127 os.makedirs(os.path.join(self.root, "empty"), exist_ok=True)
128 self.run_main()
129 self.assertEqual(list(self.types()["per_archive"]), ["a"])
130
131 def test_stdout_summary(self):
132 self.archive("a", [{"head": RBF0_HEAD, "size": 1}, {"head": ZERO_HEAD, "size": 2}])
133 out = self.run_main()
134 self.assertIn("GiB", out)
135 self.assertIn("rbf0", out)
136 self.assertIn("2 classes in total", out)
137
138 def test_empty_root(self):
139 out = self.run_main()
140 self.assertEqual(self.types(), {"overall": {}, "per_archive": {}})
141 self.assertIn("0 classes in total", out)
142
143 def test_types_json_uses_one_space_indent(self):
144 self.archive("a", [{"head": RBF0_HEAD, "size": 1}])
145 self.run_main()
146 with open(os.path.join(self.root, "types.json"), encoding="utf-8") as f:
147 text = f.read()
148 self.assertTrue(text.startswith('{\n "overall": {'))
149
150
151if __name__ == "__main__":
152 unittest.main()
diff --git a/tests/test_gamedata_xml.py b/tests/test_gamedata_xml.py
new file mode 100644
index 000000000..2d0678684
--- /dev/null
+++ b/tests/test_gamedata_xml.py
@@ -0,0 +1,211 @@
1"""gamedata_xml.py must catalog synthetic XML without reading any game file.
2
3 python -I tests/test_gamedata_xml.py
4
5Fixtures are hand-written documents: nested elements, attributes, macro and platform references,
6an include-like manifest, a tail-only fragment and a malformed document. No game data is used.
7"""
8import csv
9import json
10import os
11import subprocess
12import sys
13import tempfile
14import unittest
15
16ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
17TOOL = os.path.join(ROOT, "tools", "gamedata_xml.py")
18
19ALPHA = (
20 b'\xef\xbb\xbf<?xml version="1.0" encoding="utf-8"?>\n'
21 b'<CDataFileMgr__ContentChangeSetDef version="1">\n'
22 b' <id>fixture</id>\n'
23 b' <fileList>\n'
24 b' <Item type="file"><filename>$(common)/movies/fixture.bk2</filename>'
25 b'<fileType>bk2</fileType></Item>\n'
26 b' <Item type="file"><filename>platform:/levels/fixture.xml</filename>'
27 b'<fileType>xml</fileType></Item>\n'
28 b' <Item type="file"><filename>$(target)/data/fixture.xml</filename>'
29 b'<fileType>xml</fileType></Item>\n'
30 b' <Item type="file"><filename>platform:/data/fixture.xml</filename>'
31 b'<fileType>xml</fileType></Item>\n'
32 b' </fileList>\n'
33 b' <includedSets><Item ref="synthetic_set"><loadPath>$(root)/fixture</loadPath></Item>'
34 b'</includedSets>\n'
35 b' <!-- synthetic note -->\n'
36 b'</CDataFileMgr__ContentChangeSetDef>'
37)
38BETA = (
39 b'<timecycle_modifier_data version="1"><modifier name="fixture">'
40 b'<postfx_exposure>0 1</postfx_exposure></modifier></timecycle_modifier_data>'
41)
42TAIL = b'<Item type="x"/>\n</TailRoot>'
43BAD = b'<?xml version="1.0"?><Root><Item></Root>'
44ROOTLESS = b'plain text, not an XML document\n'
45
46
47class GamedataXmlTest(unittest.TestCase):
48 def setUp(self):
49 self.tmp = tempfile.TemporaryDirectory()
50 self.root = self.tmp.name
51
52 def tearDown(self):
53 self.tmp.cleanup()
54
55 def write(self, name, data):
56 path = os.path.join(self.root, name)
57 with open(path, "wb") as f:
58 f.write(data)
59 return path
60
61 def run_tool(self, *args):
62 return subprocess.run([sys.executable, "-I", TOOL, *args], cwd=self.root,
63 capture_output=True, text=True, encoding="utf-8", errors="replace")
64
65 def test_files_catalog_roots_elements_references_and_values(self):
66 alpha = self.write("alpha.xml", ALPHA)
67 beta = self.write("beta.xml", BETA)
68 out = os.path.join(self.root, "catalog.json")
69 csv_path = os.path.join(self.root, "catalog.csv")
70 p = self.run_tool(alpha, beta, "--json", out, "--csv", csv_path, "--check")
71 self.assertEqual(p.returncode, 0, p.stdout + p.stderr)
72
73 with open(out, encoding="utf-8") as f:
74 data = json.load(f)
75 s = data["summary"]
76 self.assertEqual(s["documents"], 2)
77 self.assertEqual(s["well_formed"], 2)
78 self.assertEqual(s["fragments"], 0)
79 self.assertEqual(s["truncated"], 0)
80 self.assertEqual(s["malformed"], 0)
81 self.assertEqual(s["root_count"], 2)
82 self.assertEqual(s["elements"], 21)
83 self.assertEqual(s["max_depth"], 4)
84 self.assertEqual(s["comments"], 1)
85 self.assertEqual(s["comments_header"], 1)
86 self.assertEqual(s["references"], {"$(common)": 1, "$(root)": 1, "$(target)": 1})
87 self.assertEqual(s["platform"], {"levels": 1, "other": 1})
88 self.assertEqual(s["platform_total"], 2)
89 self.assertEqual(s["filename"], 4)
90 self.assertEqual(s["include_like"]["fileList"], 1)
91 self.assertEqual(s["include_like"]["includedSets"], 1)
92 self.assertEqual(s["include_like"]["loadPath"], 1)
93 self.assertEqual(s["xi_include"], 0)
94
95 rows = {row["source"]: row for row in data["rows"]}
96 first = rows["alpha.xml"]
97 self.assertEqual(first["root"], "CDataFileMgr__ContentChangeSetDef")
98 self.assertEqual(first["category"], "mount / content manifests")
99 self.assertEqual(first["element_count"], 18)
100 self.assertEqual(first["max_depth"], 4)
101 self.assertEqual(first["attributes"], ["ref", "type", "version"])
102 self.assertEqual(first["refs"], {"$(common)": 1, "$(root)": 1, "$(target)": 1})
103 self.assertEqual(first["platform"], {"levels": 1, "other": 1})
104 self.assertEqual(first["filename"], 4)
105 self.assertTrue(first["header"])
106 self.assertTrue(first["well_formed"])
107 self.assertFalse(first["fragment"])
108
109 second = rows["beta.xml"]
110 self.assertEqual(second["root"], "timecycle_modifier_data")
111 self.assertEqual(second["category"], "time, weather, sky, water")
112 self.assertEqual(second["element_count"], 3)
113 self.assertEqual(second["max_depth"], 3)
114 self.assertEqual(second["attributes"], ["name", "version"])
115 self.assertFalse(second["header"])
116
117 root = data["roots"]["CDataFileMgr__ContentChangeSetDef"]
118 self.assertEqual(root["files"], 1)
119 self.assertEqual(root["category"], "mount / content manifests")
120 self.assertEqual(root["elements"], 18)
121 self.assertEqual(root["element_names"]["filename"], 4)
122 self.assertEqual(root["element_names"]["Item"], 5)
123 self.assertEqual(root["attributes"]["type"], 4)
124 self.assertEqual(root["attributes"]["ref"], 1)
125 self.assertEqual(root["refs"], {"$(common)": 1, "$(root)": 1, "$(target)": 1})
126 self.assertEqual(root["platform"], {"levels": 1, "other": 1})
127 self.assertEqual(root["filename"], 4)
128
129 with open(csv_path, newline="", encoding="utf-8") as f:
130 csv_rows = list(csv.DictReader(f))
131 self.assertEqual(len(csv_rows), 2)
132 self.assertEqual(csv_rows[0]["root"], "CDataFileMgr__ContentChangeSetDef")
133 self.assertEqual(csv_rows[0]["refs"], "$(common)=1;$(root)=1;$(target)=1")
134 self.assertEqual(csv_rows[0]["well_formed"], "true")
135
136 # Values, text and comments must not leak into the catalog; names and counts are fine.
137 with open(out, encoding="utf-8") as f:
138 blob = f.read()
139 for value in ("fixture.bk2", "synthetic note", "synthetic_set", "0 1", "fixture.xml"):
140 self.assertNotIn(value, blob)
141
142 def test_check_reports_tail_only_fragment_and_malformed(self):
143 tail = self.write("tail.xml", TAIL)
144 p = self.run_tool(tail, "--check")
145 self.assertEqual(p.returncode, 0, p.stdout + p.stderr)
146 self.assertIn("1 truncated at the start", p.stdout)
147 self.assertIn("0 rootless fragments", p.stdout)
148 self.assertIn("0 malformed", p.stdout)
149 self.assertIn("TailRoot", p.stdout)
150
151 rootless = self.write("rootless.xml", ROOTLESS)
152 p = self.run_tool(rootless, "--check")
153 self.assertEqual(p.returncode, 0, p.stdout + p.stderr)
154 self.assertIn("1 rootless fragment", p.stdout)
155
156 bad = self.write("bad.xml", BAD)
157 p = self.run_tool(bad, "--check")
158 self.assertEqual(p.returncode, 1, p.stdout + p.stderr)
159 self.assertIn("1 malformed", p.stdout)
160 self.assertIn("line 1", p.stdout)
161
162 def test_carve_directory_joins_chunks_and_marks_fragment(self):
163 carve = os.path.join(self.root, "carve")
164 os.makedirs(carve)
165 doc = b'<?xml version="1.0"?>\n<RootA>' + b"<Item value=\"1\"/>" * 20 + b"</RootA>"
166 split = doc.index(b"<Item")
167 parts = [doc[:split], doc[split:]]
168 rows = []
169 off = 0x1000
170 for part in parts:
171 with open(os.path.join(carve, f"{off:012x}.bin"), "wb") as f:
172 f.write(part)
173 rows.append({"off": off, "stored": len(part), "size": len(part),
174 "head": part[:16].hex(), "pre": ""})
175 off += 0x1000
176 with open(os.path.join(carve, f"{off:012x}.bin"), "wb") as f:
177 f.write(TAIL)
178 rows.append({"off": off, "stored": len(TAIL), "size": len(TAIL),
179 "head": TAIL[:16].hex(), "pre": ""})
180 with open(os.path.join(carve, "index.json"), "w", encoding="utf-8") as f:
181 json.dump({"summary": {"archive": "synthetic", "files": len(rows)}, "files": rows}, f)
182
183 out = os.path.join(self.root, "carve.json")
184 p = self.run_tool(carve, "--json", out, "--check")
185 self.assertEqual(p.returncode, 0, p.stdout + p.stderr)
186 with open(out, encoding="utf-8") as f:
187 data = json.load(f)
188 s = data["summary"]
189 self.assertEqual(s["mode"], "carve")
190 self.assertEqual(s["documents"], 2)
191 self.assertEqual(s["well_formed"], 1)
192 self.assertEqual(s["tail_only"], 1)
193 self.assertEqual(s["truncated"], 1)
194 self.assertEqual(s["fragments"], 0)
195 self.assertEqual(s["root_count"], 2)
196 first = data["rows"][0]
197 self.assertEqual(first["root"], "RootA")
198 self.assertEqual(first["chunks"], 2)
199 self.assertEqual(first["bytes"], len(doc))
200 self.assertEqual(first["offset_hex"], "1000")
201 self.assertEqual(first["element_count"], 21)
202 self.assertEqual(first["max_depth"], 2)
203 tail = data["rows"][1]
204 self.assertEqual(tail["root"], "TailRoot")
205 self.assertTrue(tail["tail_only"])
206 self.assertTrue(tail["truncated"])
207 self.assertFalse(tail["malformed"])
208
209
210if __name__ == "__main__":
211 unittest.main()
diff --git a/tests/test_gen_d3d12_stubs.py b/tests/test_gen_d3d12_stubs.py
new file mode 100644
index 000000000..d03a1dd5f
--- /dev/null
+++ b/tests/test_gen_d3d12_stubs.py
@@ -0,0 +1,254 @@
1"""Tests for tools/gen_d3d12_stubs.py, driven by a synthetic d3d12.h (no Windows SDK).
2
3 python -I tests/test_gen_d3d12_stubs.py
4"""
5import importlib.util
6import os
7import tempfile
8import unittest
9from unittest import mock
10
11ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
12
13
14def load_module():
15 path = os.path.join(ROOT, "tools", "gen_d3d12_stubs.py")
16 spec = importlib.util.spec_from_file_location("gen_d3d12_stubs_under_test", path)
17 module = importlib.util.module_from_spec(spec)
18 spec.loader.exec_module(module)
19 return module
20
21
22gen = load_module()
23
24GOOD_HEADER = """\
25MIDL_INTERFACE("11111111-2222-3333-4444-555555555555")
26IBase : public IUnknown
27{
28public:
29 virtual void STDMETHODCALLTYPE DoThing(UINT a, UINT b) = 0;
30 virtual HRESULT STDMETHODCALLTYPE Multi(
31 UINT first,
32 UINT second) = 0;
33 /* virtual void STDMETHODCALLTYPE Removed() = 0; */
34 virtual HRESULT STDMETHODCALLTYPE AfterComment(void) = 0; /* trailing note */
35};
36
37MIDL_INTERFACE("66666666-7777-8888-9999-AAAAAAAAAAAA")
38IChild : public IBase
39{
40public:
41 virtual HRESULT STDMETHODCALLTYPE GetThing(UINT index, _Out_ ID3D12Thing **ppThing) const = 0;
42 virtual UINT64 STDMETHODCALLTYPE Size(void) = 0;
43};
44"""
45
46GUARDED_HEADER = """\
47MIDL_INTERFACE("22222222-2222-2222-2222-222222222222")
48IGuarded : public IUnknown
49{
50public:
51#if 0
52 virtual void STDMETHODCALLTYPE Gone(void) = 0;
53#endif
54 virtual void STDMETHODCALLTYPE Kept(void) = 0;
55};
56"""
57
58ORPHAN_HEADER = """\
59MIDL_INTERFACE("33333333-3333-3333-3333-333333333333")
60IOrphan : public IMissing
61{
62public:
63 virtual void STDMETHODCALLTYPE Nothing(void) = 0;
64};
65"""
66
67BROKEN_HEADER = """\
68MIDL_INTERFACE("44444444-4444-4444-4444-444444444444")
69IBroken : public IUnknown
70{
71public:
72 virtual void STDMETHODCALLTYPE NotAMethod = 0;
73};
74"""
75
76UNTERMINATED_HEADER = """\
77MIDL_INTERFACE("55555555-5555-5555-5555-555555555555")
78IHalf : public IUnknown
79{
80public:
81 virtual void STDMETHODCALLTYPE Missing(void);
82};
83"""
84
85IFACES = gen.parse_interfaces(GOOD_HEADER)
86
87
88class ParseInterfacesTests(unittest.TestCase):
89 def test_names_bases_and_methods(self):
90 self.assertEqual(sorted(IFACES), ["IBase", "IChild"])
91 self.assertEqual(IFACES["IBase"][0], "IUnknown")
92 self.assertEqual(IFACES["IChild"][0], "IBase")
93 methods = [item for item in IFACES["IBase"][1] if item[0] == "m"]
94 self.assertEqual([m[2] for m in methods], ["DoThing", "Multi", "AfterComment"])
95 self.assertEqual(methods[0], ("m", "void", "DoThing", "UINT a, UINT b", ""))
96
97 def test_multiline_declaration_is_joined(self):
98 methods = [item for item in IFACES["IBase"][1] if item[0] == "m"]
99 self.assertEqual(methods[1][3], "UINT first, UINT second")
100
101 def test_const_method_is_marked(self):
102 methods = [item for item in IFACES["IChild"][1] if item[0] == "m"]
103 self.assertEqual(methods[0][4], "const")
104 self.assertEqual(methods[0][2], "GetThing")
105
106 def test_commented_out_method_is_dropped(self):
107 names = [item[2] for item in IFACES["IBase"][1] if item[0] == "m"]
108 self.assertNotIn("Removed", names)
109
110 def test_inline_comment_after_a_declaration_keeps_it(self):
111 names = [item[2] for item in IFACES["IBase"][1] if item[0] == "m"]
112 self.assertIn("AfterComment", names)
113
114 def test_preprocessor_lines_pass_through(self):
115 items = gen.parse_interfaces(GUARDED_HEADER)["IGuarded"][1]
116 self.assertEqual(items[0], ("#", "#if 0"))
117 self.assertEqual(items[1][0], "m")
118 self.assertEqual(items[1][2], "Gone")
119 self.assertEqual(items[2], ("#", "#endif"))
120 self.assertEqual(items[3][2], "Kept")
121
122 def test_text_without_interfaces(self):
123 self.assertEqual(gen.parse_interfaces("// nothing here\n"), {})
124
125 def test_unterminated_declaration_raises(self):
126 with self.assertRaises(SystemExit):
127 gen.parse_interfaces(UNTERMINATED_HEADER)
128
129 def test_unparseable_declaration_raises(self):
130 with self.assertRaises(SystemExit):
131 gen.parse_interfaces(BROKEN_HEADER)
132
133
134class ChainTests(unittest.TestCase):
135 def test_leaf_comes_last(self):
136 self.assertEqual(gen.chain(IFACES, "IChild"), ["IBase", "IChild"])
137
138 def test_root_interface(self):
139 self.assertEqual(gen.chain(IFACES, "IBase"), ["IBase"])
140
141 def test_unknown_base_raises(self):
142 orphan = gen.parse_interfaces(ORPHAN_HEADER)
143 with self.assertRaises(SystemExit):
144 gen.chain(orphan, "IOrphan")
145
146
147class EmitClassTests(unittest.TestCase):
148 def test_class_skeleton_and_method_order(self):
149 text = gen.emit_class(IFACES, "IChild")
150 self.assertTrue(text.startswith("class IChildStubs : public IChild {\npublic:"))
151 self.assertTrue(text.endswith("};"))
152 self.assertLess(text.index("// IBase"), text.index("// IChild"))
153 self.assertLess(text.index("DoThing"), text.index("GetThing"))
154 self.assertNotIn("Removed", text)
155
156 def test_return_conventions_and_stub_names(self):
157 text = gen.emit_class(IFACES, "IChild")
158 self.assertIn(
159 ' void STDMETHODCALLTYPE DoThing(UINT a, UINT b) override '
160 '{ ::rt::d3d12::stub("IBase::DoThing"); }',
161 text,
162 )
163 self.assertIn(
164 ' HRESULT STDMETHODCALLTYPE Multi(UINT first, UINT second) override '
165 '{ ::rt::d3d12::stub("IBase::Multi"); return E_NOTIMPL; }',
166 text,
167 )
168 self.assertIn(
169 ' HRESULT STDMETHODCALLTYPE GetThing(UINT index, _Out_ ID3D12Thing **ppThing) const override '
170 '{ ::rt::d3d12::stub("IChild::GetThing"); return E_NOTIMPL; }',
171 text,
172 )
173 self.assertIn(
174 ' UINT64 STDMETHODCALLTYPE Size(void) override '
175 '{ ::rt::d3d12::stub("IChild::Size"); return {}; }',
176 text,
177 )
178
179 def test_directives_are_emitted_verbatim(self):
180 text = gen.emit_class(gen.parse_interfaces(GUARDED_HEADER), "IGuarded")
181 self.assertIn("\n#if 0\n", text)
182 self.assertIn("\n#endif\n", text)
183 self.assertIn('stub("IGuarded::Gone")', text)
184
185
186class MainTests(unittest.TestCase):
187 def setUp(self):
188 tmp = tempfile.TemporaryDirectory()
189 self.addCleanup(tmp.cleanup)
190 self.dir = tmp.name
191 self.header = os.path.join(self.dir, "d3d12.h")
192 with open(self.header, "w", encoding="utf-8") as f:
193 f.write(GOOD_HEADER)
194 self.out = os.path.join(self.dir, "generated", "d3d12_stubs.h")
195
196 def run_main(self, *interfaces, include_header=True):
197 args = ["gen_d3d12_stubs.py", "--out", self.out]
198 if include_header:
199 args += ["--header", self.header]
200 with mock.patch("sys.argv", args + list(interfaces)):
201 return gen.main()
202
203 def test_writes_header_and_class(self):
204 self.assertEqual(self.run_main("IChild"), 0)
205 self.assertTrue(os.path.isdir(os.path.dirname(self.out)))
206 with open(self.out, encoding="utf-8") as f:
207 text = f.read()
208 self.assertTrue(
209 text.startswith(
210 "// Generated by tools/gen_d3d12_stubs.py from d3d12.h. Do not edit.\n"
211 )
212 )
213 for line in (
214 "#pragma once",
215 "#include <d3d12.h>",
216 "namespace rt::d3d12 { void stub(const char* method); }",
217 "#pragma warning(push)",
218 "#pragma warning(disable : 4100) // unreferenced parameters",
219 "class IChildStubs : public IChild {",
220 "#pragma warning(pop)",
221 ):
222 self.assertIn(line, text)
223 self.assertTrue(text.endswith("\n"))
224 self.assertNotIn("\r\n", text)
225
226 def test_second_run_does_not_rewrite(self):
227 self.assertEqual(self.run_main("IChild"), 0)
228 before = os.stat(self.out).st_mtime_ns
229 self.assertEqual(self.run_main("IChild"), 0)
230 self.assertEqual(os.stat(self.out).st_mtime_ns, before)
231
232 def test_two_interfaces_keep_their_order(self):
233 self.assertEqual(self.run_main("IBase", "IChild"), 0)
234 with open(self.out, encoding="utf-8") as f:
235 text = f.read()
236 self.assertLess(text.index("class IBaseStubs"), text.index("class IChildStubs"))
237
238 def test_unknown_interface_raises(self):
239 with self.assertRaises(SystemExit):
240 self.run_main("IWho")
241
242 def test_find_header_uses_the_include_environment(self):
243 with mock.patch.dict(os.environ, {"INCLUDE": self.dir}, clear=False):
244 self.assertEqual(gen.find_header(), self.header)
245 self.assertEqual(self.run_main("IChild", include_header=False), 0)
246 self.assertTrue(os.path.isfile(self.out))
247
248 def test_find_header_without_include_returns_none(self):
249 with mock.patch.dict(os.environ, {"INCLUDE": ""}, clear=False):
250 self.assertIsNone(gen.find_header())
251
252
253if __name__ == "__main__":
254 unittest.main()
diff --git a/tests/test_manifest.py b/tests/test_manifest.py
index bfd00622a..16b5a03c3 100644
--- a/tests/test_manifest.py
+++ b/tests/test_manifest.py
@@ -11,6 +11,7 @@ import subprocess
11import sys 11import sys
12import tempfile 12import tempfile
13import unittest 13import unittest
14from unittest.mock import patch
14 15
15ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 16ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
16TOOL = os.path.join(ROOT, "tools", "manifest.py") 17TOOL = os.path.join(ROOT, "tools", "manifest.py")
@@ -69,6 +70,19 @@ class ManifestWalkTest(unittest.TestCase):
69 self.assertTrue(os.path.isabs(abs_path)) 70 self.assertTrue(os.path.isabs(abs_path))
70 self.assertTrue(os.path.exists(abs_path)) 71 self.assertTrue(os.path.exists(abs_path))
71 72
73 def test_walk_reports_an_unreadable_subdirectory(self):
74 blocked = os.path.join(self.pkg, "sub", "deep")
75 scandir = os.scandir
76
77 def scan(path):
78 if path == blocked:
79 raise PermissionError(f"cannot read {path}")
80 return scandir(path)
81
82 with patch.object(os, "scandir", side_effect=scan):
83 with self.assertRaises(PermissionError):
84 list(manifest.walk(self.pkg))
85
72 86
73class ManifestCreateVerifyTest(unittest.TestCase): 87class ManifestCreateVerifyTest(unittest.TestCase):
74 def setUp(self): 88 def setUp(self):
@@ -293,6 +307,26 @@ class ManifestCliTest(unittest.TestCase):
293 self.assertEqual(p_verify.returncode, 1) 307 self.assertEqual(p_verify.returncode, 1)
294 self.assertIn("problem(s)", p_verify.stdout) 308 self.assertIn("problem(s)", p_verify.stdout)
295 309
310 def test_cli_rejects_invalid_game_directories(self):
311 # Start with a valid empty manifest, which would otherwise verify even if the scan never ran.
312 empty = os.path.join(self.tmp.name, "empty")
313 os.mkdir(empty)
314 self.assertEqual(self.run_cli("create", empty, "--out", self.out_manifest).returncode, 0)
315 self.assertEqual(self.run_cli("verify", empty, "--manifest", self.out_manifest).returncode, 0)
316 with open(self.out_manifest, "rb") as f:
317 original = f.read()
318
319 for game_dir in (os.path.join(self.tmp.name, "missing"), os.path.join(self.pkg, "sample.dat")):
320 for command, option in (("create", "--out"), ("verify", "--manifest")):
321 with self.subTest(game_dir=game_dir, command=command):
322 result = self.run_cli(command, game_dir, option, self.out_manifest)
323 self.assertEqual(result.returncode, 2)
324 self.assertIn(os.path.basename(game_dir), result.stderr)
325 self.assertNotIn("Traceback", result.stderr)
326 self.assertEqual(result.stdout, "")
327 with open(self.out_manifest, "rb") as f:
328 self.assertEqual(f.read(), original)
329
296 330
297class ManifestBelowNormalTest(unittest.TestCase): 331class ManifestBelowNormalTest(unittest.TestCase):
298 def test_below_normal_callable(self): 332 def test_below_normal_callable(self):
diff --git a/tests/test_mc_command.py b/tests/test_mc_command.py
new file mode 100644
index 000000000..0e3c84e53
--- /dev/null
+++ b/tests/test_mc_command.py
@@ -0,0 +1,61 @@
1"""LLVM_MC is one executable path or a whole command line, in every tool that reads it.
2
3Windows runs llvm-mc through WSL (the official Windows LLVM build has no AMDGPU target):
4
5 set LLVM_MC=wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc
6
7 python -I tests/test_mc_command.py
8"""
9import os
10import sys
11import tempfile
12import unittest
13from unittest import mock
14
15ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
16sys.path.insert(0, os.path.join(ROOT, "tools"))
17
18import mc_command # noqa: E402
19
20
21class SplitCommandTest(unittest.TestCase):
22 def test_bare_name(self):
23 self.assertEqual(mc_command.split_command("llvm-mc"), ["llvm-mc"])
24
25 def test_empty(self):
26 self.assertEqual(mc_command.split_command(""), [])
27 self.assertEqual(mc_command.split_command(" "), [])
28
29 def test_command_line(self):
30 self.assertEqual(mc_command.split_command("wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc"),
31 ["wsl", "-d", "Ubuntu", "-e", "/usr/lib/llvm-21/bin/llvm-mc"])
32
33 def test_quoted_arguments(self):
34 if os.name == "nt":
35 raw = '"C:\\Program Files\\LLVM\\bin\\llvm-mc.exe" --version'
36 want = ["C:\\Program Files\\LLVM\\bin\\llvm-mc.exe", "--version"]
37 else:
38 raw = '"/opt/llvm 21/bin/llvm-mc" --version'
39 want = ["/opt/llvm 21/bin/llvm-mc", "--version"]
40 self.assertEqual(mc_command.split_command(raw), want)
41
42 def test_path_with_spaces_is_kept_whole(self):
43 with tempfile.TemporaryDirectory() as tmp:
44 path = os.path.join(tmp, "llvm mc")
45 with open(path, "w", encoding="utf-8") as f:
46 f.write("")
47 self.assertEqual(mc_command.split_command(path), [path])
48 self.assertEqual(mc_command.split_command(f'"{path}"'), [path])
49
50 def test_mc_command_reads_the_environment(self):
51 with mock.patch.dict(os.environ, {"LLVM_MC": "wsl -d Ubuntu -e /opt/llvm-21/bin/llvm-mc"}):
52 self.assertEqual(mc_command.mc_command(),
53 ["wsl", "-d", "Ubuntu", "-e", "/opt/llvm-21/bin/llvm-mc"])
54
55 def test_mc_command_falls_back_to_the_path_name(self):
56 with mock.patch.dict(os.environ, {"LLVM_MC": ""}):
57 self.assertEqual(mc_command.mc_command(), ["llvm-mc"])
58
59
60if __name__ == "__main__":
61 unittest.main()
diff --git a/tests/test_rbf0_tree.py b/tests/test_rbf0_tree.py
new file mode 100644
index 000000000..cb54b9ebf
--- /dev/null
+++ b/tests/test_rbf0_tree.py
@@ -0,0 +1,321 @@
1"""Synthetic-tree tests for tools/rbf0_tree.py.
2
3 python -I tests/test_rbf0_tree.py
4
5Every byte here is built by the test. No game file, game asset path or game name is used.
6"""
7import json
8import os
9import struct
10import sys
11import tempfile
12import unittest
13from xml.etree import ElementTree as ET
14
15ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
16sys.path.insert(0, os.path.join(ROOT, "tools"))
17
18import rbf0_tree # noqa: E402
19
20WIDE = b"RBF0" + rbf0_tree.PROLOGUE
21CLOSE = b"\xff\xff"
22
23
24def _name(name):
25 return struct.pack("<H", len(name)) + name
26
27
28def _open(index, name=None, attrs=0):
29 out = bytes([index, 0x00])
30 if name is not None:
31 out += _name(name)
32 return out + struct.pack("<HHH", 0, 0, attrs)
33
34
35def _value(index, kind, payload=b"", name=None):
36 out = bytes([index, kind])
37 if name is not None:
38 out += _name(name)
39 return out + payload
40
41
42def _text(text, nul=True):
43 raw = text + (b"\x00" if nul else b"")
44 return b"\xfd\xff" + struct.pack("<I", len(raw)) + raw
45
46
47def wide_blob():
48 """Root -> Item(attrs=2) -> Child(text), then a value after the child."""
49 b = bytearray(WIDE)
50 b += _open(0, b"TestRoot")
51 b += _open(1, b"Item", attrs=2)
52 b += _value(2, 0x10, struct.pack("<Q", 7), b"count")
53 b += _value(3, 0x60, struct.pack("<H", 5) + b"alpha", b"label")
54 b += _open(4, b"Child")
55 b += _text(b"body")
56 b += CLOSE
57 b += _value(5, 0x40, struct.pack("<d", 0.5), b"ratio")
58 b += CLOSE
59 b += _open(6, b"Empty")
60 b += CLOSE
61 b += CLOSE
62 return bytes(b)
63
64
65def narrow_blob():
66 b = bytearray(b"RBF0")
67 b += _open(0, b"TestRoot")
68 b += _value(1, 0x10, struct.pack("<I", 7), b"count")
69 b += _value(2, 0x40, struct.pack("<f", 0.5), b"ratio")
70 b += CLOSE
71 return bytes(b)
72
73
74def other_blob():
75 b = bytearray(WIDE)
76 b += _open(0, b"OtherRoot")
77 b += _value(1, 0x20, b"", b"flag")
78 b += CLOSE
79 return bytes(b)
80
81
82class ParseTest(unittest.TestCase):
83 def test_tree_offsets_and_nesting(self):
84 blob = wide_blob()
85 doc = rbf0_tree.parse_resource(blob)
86 self.assertEqual(doc["status"], "ok")
87 self.assertEqual(doc["root_name"], "TestRoot")
88 self.assertEqual(doc["layout"], "wide-64")
89 self.assertEqual(doc["size"], len(blob))
90 self.assertEqual(doc["end"], len(blob))
91 self.assertEqual((doc["counts"]["elements"], doc["counts"]["values"], doc["counts"]["texts"]),
92 (4, 3, 1))
93 root = doc["tree"]
94 self.assertEqual(root["offset"], 8)
95 self.assertEqual(root["header_offset"], 20)
96 self.assertEqual(root["end"], len(blob))
97 item = root["content"][0]
98 self.assertEqual(item["name"], "Item")
99 self.assertEqual(item["offset"], 26)
100 self.assertEqual(item["header_offset"], 34)
101 self.assertEqual(item["depth"], 2)
102 self.assertEqual(item["attrs_declared"], 2)
103 self.assertEqual([a["name"] for a in item["attributes"]], ["count", "label"])
104 self.assertEqual([a["value"] for a in item["attributes"]], [7, "alpha"])
105 self.assertEqual([n["kind"] for n in item["content"]], ["element", "value"])
106 child = item["content"][0]
107 self.assertEqual(child["name"], "Child")
108 self.assertEqual(child["depth"], 3)
109 self.assertEqual(child["content"][0]["kind"], "text")
110 self.assertEqual(child["content"][0]["depth"], 4)
111 self.assertEqual(child["content"][0]["text"], "body")
112 self.assertTrue(child["content"][0]["nul_terminated"])
113 self.assertEqual(item["content"][1]["name"], "ratio")
114 self.assertEqual(item["content"][1]["value"], 0.5)
115 self.assertTrue(item["value_after_child"])
116 self.assertEqual(doc["attribute_mismatches"], 0)
117 self.assertEqual(doc["attribute_order_violations"], 0)
118 self.assertEqual(doc["max_depth"], 3) # elements only; the text child is at element depth 4
119
120 def test_descriptor_table(self):
121 doc = rbf0_tree.parse_resource(wide_blob())
122 self.assertEqual(doc["descriptor_count"], 7)
123 table = {d["index"]: d for d in doc["descriptors"]}
124 self.assertEqual(table[0]["name"], "TestRoot")
125 self.assertEqual(table[0]["first_type"], "open")
126 self.assertEqual(table[2]["name"], "count")
127 self.assertEqual(table[2]["first_type"], "int")
128 self.assertEqual(table[3]["name"], "label")
129 self.assertEqual(table[3]["first_type"], "string")
130 self.assertEqual(table[5]["types"], {"float": 1})
131 self.assertEqual(table[3]["uses"], 1)
132 self.assertEqual(doc["distinct_descriptor_names"], 7)
133
134 def test_descriptor_is_a_name_index_not_a_type(self):
135 b = bytearray(WIDE)
136 b += _open(0, b"TestRoot")
137 b += _open(1, b"Item", attrs=2)
138 b += _value(2, 0x10, struct.pack("<Q", 5), b"value")
139 b += _value(2, 0x40, struct.pack("<d", 1.5))
140 b += CLOSE
141 b += CLOSE
142 doc = rbf0_tree.parse_resource(bytes(b))
143 self.assertEqual(doc["status"], "ok")
144 desc = {d["index"]: d for d in doc["descriptors"]}[2]
145 self.assertEqual(desc["name"], "value")
146 self.assertEqual(desc["first_type"], "int")
147 self.assertEqual(desc["types"], {"int": 1, "float": 1})
148 item = doc["tree"]["content"][0]
149 self.assertEqual([a["type"] for a in item["attributes"]], ["int", "float"])
150
151 def test_narrow_widths(self):
152 doc = rbf0_tree.parse_resource(narrow_blob())
153 self.assertEqual(doc["status"], "ok")
154 self.assertEqual(doc["layout"], "narrow-32")
155 item = doc["tree"]
156 self.assertEqual(item["content"][0]["value"], 7)
157 self.assertEqual(item["content"][0]["size"], 4)
158 self.assertEqual(item["content"][1]["value"], 0.5)
159 self.assertEqual(item["content"][1]["size"], 4)
160
161 def test_text_and_string_framing(self):
162 doc = rbf0_tree.parse_resource(wide_blob())
163 item = doc["tree"]["content"][0]
164 label = item["attributes"][1]
165 self.assertEqual(label["type"], "string")
166 self.assertEqual(label["byte_length"], 5)
167 self.assertFalse(label["nul_terminated"])
168 self.assertEqual(label["payload_offset"] + label["size"], label["payload_offset"] + 5)
169 text = item["content"][0]["content"][0]
170 self.assertEqual(text["length"], 5)
171 self.assertTrue(text["nul_terminated"])
172 self.assertEqual(text["payload_offset"] + text["length"], text["offset"] + 2 + 4 + 5)
173
174 def test_trailing_bytes(self):
175 blob = wide_blob() + b"\x00\x00"
176 doc = rbf0_tree.parse_resource(blob)
177 self.assertEqual(doc["status"], "trailing")
178 self.assertEqual(doc["tree"]["end"], len(blob) - 2)
179 self.assertIn("after the root closed", doc["error"])
180
181 def test_truncated(self):
182 doc = rbf0_tree.parse_resource(wide_blob()[:30])
183 self.assertEqual(doc["status"], "truncated")
184 self.assertIn("truncated", doc["error"])
185
186 def test_unknown_descriptor_fails_closed(self):
187 b = WIDE + _open(0, b"TestRoot") + bytes([9, 0x10]) + struct.pack("<Q", 1) + CLOSE
188 doc = rbf0_tree.parse_resource(b)
189 self.assertEqual(doc["status"], "bad")
190 self.assertIn("descriptor index 9 of 1", doc["error"])
191 self.assertEqual(doc["descriptor_count"], 1)
192 self.assertEqual(doc["tree"]["name"], "TestRoot")
193 self.assertEqual(doc["tree"]["content"], [])
194 self.assertEqual(doc["counts"].get("values", 0), 0)
195
196 def test_unknown_record_type_fails_closed(self):
197 b = WIDE + _open(0, b"TestRoot") + bytes([1, 0x99]) + _name(b"weird") + CLOSE
198 doc = rbf0_tree.parse_resource(b)
199 self.assertEqual(doc["status"], "bad")
200 self.assertIn("unknown record type 0x99", doc["error"])
201 self.assertEqual([d["name"] for d in doc["descriptors"]], ["TestRoot", "weird"])
202 self.assertEqual(doc["tree"]["content"], [])
203
204 def test_bad_element_word_fails_closed(self):
205 b = WIDE + bytes([0, 0x00]) + _name(b"TestRoot") + struct.pack("<HHH", 1, 0, 0) + CLOSE
206 doc = rbf0_tree.parse_resource(b)
207 self.assertEqual(doc["status"], "bad")
208 self.assertIn("word is not zero", doc["error"])
209 self.assertIsNone(doc["tree"])
210
211 def test_not_rbf0(self):
212 with self.assertRaises(rbf0_tree.TreeError):
213 rbf0_tree.parse_resource(b"PSIN" + bytes(16))
214
215
216class JoinTest(unittest.TestCase):
217 def setUp(self):
218 self.tmp = tempfile.TemporaryDirectory()
219 self.root = self.tmp.name
220
221 def tearDown(self):
222 self.tmp.cleanup()
223
224 def test_join_at_64k(self):
225 b = bytearray(WIDE)
226 b += _open(0, b"BigRoot")
227 filler = b"x" * 4000
228 b += _value(1, 0x60, struct.pack("<H", len(filler)) + filler, b"filler")
229 while len(b) < 70000:
230 b += _value(1, 0x60, struct.pack("<H", len(filler)) + filler)
231 b += CLOSE
232 blob = bytes(b)
233 self.assertGreater(len(blob), 65536)
234 with open(os.path.join(self.root, "00000000.bin"), "wb") as f:
235 f.write(blob[:65536])
236 with open(os.path.join(self.root, "00010000.bin"), "wb") as f:
237 f.write(blob[65536:])
238 docs, summary = rbf0_tree.decode_source(self.root)
239 self.assertEqual(len(docs), 1)
240 self.assertEqual(docs[0]["chunks"], 2)
241 self.assertEqual(docs[0]["size"], len(blob))
242 self.assertEqual(docs[0]["status"], "ok")
243 self.assertEqual(docs[0]["root_name"], "BigRoot")
244 self.assertEqual(summary["resources"], 1)
245 self.assertEqual(summary["ok"], 1)
246
247 def test_single_resource_file(self):
248 path = os.path.join(self.root, "resource.bin")
249 with open(path, "wb") as f:
250 f.write(wide_blob())
251 docs, summary = rbf0_tree.decode_source(path)
252 self.assertEqual(len(docs), 1)
253 self.assertEqual(docs[0]["root_name"], "TestRoot")
254 self.assertEqual(summary["ok"], 1)
255
256
257class OutputTest(unittest.TestCase):
258 def setUp(self):
259 self.tmp = tempfile.TemporaryDirectory()
260 self.root = self.tmp.name
261
262 def tearDown(self):
263 self.tmp.cleanup()
264
265 def test_json_and_xml(self):
266 blob = bytearray(WIDE)
267 blob += _open(0, b"TestRoot", attrs=1)
268 blob += _value(1, 0x60, struct.pack("<H", 3) + b"a &", b"xmlns:xi")
269 blob += _open(2, b"Text")
270 blob += _text(b"a < b & c")
271 blob += CLOSE
272 blob += _open(3, b"Ctrl")
273 blob += _text(b"a\x01b")
274 blob += CLOSE
275 blob += CLOSE
276 with open(os.path.join(self.root, "00000000.bin"), "wb") as f:
277 f.write(blob)
278 out = os.path.join(self.root, "tree.json")
279 xml_dir = os.path.join(self.root, "xml")
280 self.assertEqual(rbf0_tree.main([self.root, out, "--xml", xml_dir, "--quiet"]), 0)
281 with open(out, encoding="utf-8") as f:
282 doc = json.load(f)
283 self.assertEqual(doc["summary"]["resources"], 1)
284 self.assertEqual(doc["summary"]["elements"], 3)
285 self.assertEqual(doc["resources"][0]["tree"]["attributes"][0]["name"], "xmlns:xi")
286 xml_path = os.path.join(xml_dir, "00000000.xml")
287 self.assertTrue(os.path.exists(xml_path))
288 tree = ET.parse(xml_path)
289 root = tree.getroot()
290 self.assertEqual(root.tag, "rbf0")
291 attr = root.find(".//attr")
292 self.assertEqual(attr.get("name"), "xmlns:xi")
293 self.assertEqual(attr.text, "a &")
294 texts = root.findall(".//text")
295 self.assertEqual(texts[0].text, "a < b & c")
296 self.assertEqual(texts[1].text, "a\ufffdb") # XML 1.0 control bytes are replaced, not emitted
297
298 def test_root_filter_and_limit(self):
299 with open(os.path.join(self.root, "00000000.bin"), "wb") as f:
300 f.write(wide_blob())
301 with open(os.path.join(self.root, "00001000.bin"), "wb") as f:
302 f.write(other_blob())
303 docs, summary = rbf0_tree.decode_source(self.root, roots=["OtherRoot"])
304 self.assertEqual(len(docs), 1)
305 self.assertEqual(docs[0]["root_name"], "OtherRoot")
306 self.assertEqual(summary["roots"], {"OtherRoot": 1})
307 docs, _ = rbf0_tree.decode_source(self.root, limit=1)
308 self.assertEqual(len(docs), 1)
309
310 def test_bad_resource_exit_code(self):
311 with open(os.path.join(self.root, "00000000.bin"), "wb") as f:
312 f.write(WIDE + _open(0, b"TestRoot") + bytes([9, 0x10]) + struct.pack("<Q", 1))
313 out = os.path.join(self.root, "tree.json")
314 self.assertEqual(rbf0_tree.main([self.root, out, "--quiet"]), 1)
315 with open(out, encoding="utf-8") as f:
316 doc = json.load(f)
317 self.assertEqual(doc["summary"]["bad"], 1)
318
319
320if __name__ == "__main__":
321 unittest.main()
diff --git a/tests/test_root_sig_contract.py b/tests/test_root_sig_contract.py
new file mode 100644
index 000000000..8b1ca221b
--- /dev/null
+++ b/tests/test_root_sig_contract.py
@@ -0,0 +1,110 @@
1"""Contract tests for tools/root_sig_contract.py (no game data, no GPU).
2
3Run from the repository root: python -m pytest tests/test_root_sig_contract.py
4Everything is hand-built: synthetic root signatures and synthetic index
5entries, so these run on every CI leg including Windows without llvm-mc.
6"""
7import json
8import os
9import subprocess
10import sys
11
12import pytest
13
14import root_sig_contract as rsc
15
16ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
17TOOL = os.path.join(ROOT, "tools", "root_sig_contract.py")
18
19ROOT_SIG = {
20 "version": "1.1",
21 "flags": 0,
22 "params": [
23 {"type": "constants", "count": 4, "visibility": "all"},
24 {"type": "cbv", "visibility": "vertex"},
25 {"type": "table", "ranges": [{"kind": "srv", "count": 8}],
26 "visibility": "pixel"},
27 ],
28}
29
30
31def test_pack_layout_order_and_provenance():
32 dwords, error = rsc.pack_layout(ROOT_SIG)
33 assert error == ""
34 assert len(dwords) == 8
35 assert [d["param"] for d in dwords] == [0, 0, 0, 0, 1, 1, 2, 2]
36 assert [d["sub"] for d in dwords] == [0, 1, 2, 3, 0, 1, 0, 1]
37 assert dwords[0]["ptype"] == "constants"
38 assert dwords[4]["ptype"] == "descriptor"
39 assert dwords[6]["ptype"] == "table"
40
41
42def test_pack_layout_static_samplers_free():
43 sig = dict(ROOT_SIG, static_samplers=[{"filter": 21}])
44 dwords, error = rsc.pack_layout(sig)
45 assert error == "" and len(dwords) == 8
46
47
48def test_pack_layout_spill_refused():
49 sig = {"version": "1.1", "flags": 0,
50 "params": [{"type": "cbv"} for _ in range(17)]}
51 dwords, error = rsc.pack_layout(sig)
52 assert dwords == [] and "spill" in error
53
54
55def test_pack_layout_cost_limit():
56 sig = {"version": "1.1", "flags": 0,
57 "params": [{"type": "constants", "count": 65}]}
58 dwords, error = rsc.pack_layout(sig)
59 assert dwords == [] and "64-dword" in error
60
61
62def test_pack_layout_unknown_type():
63 sig = {"version": "1.1", "flags": 0, "params": [{"type": "ufo"}]}
64 dwords, error = rsc.pack_layout(sig)
65 assert dwords == [] and "unknown type" in error
66
67
68def test_reconcile_compatible():
69 dwords, _ = rsc.pack_layout(ROOT_SIG)
70 reads = [{"sgpr": 0, "kind": "const32"},
71 {"sgpr": 4, "kind": "ptr64_lo"},
72 {"sgpr": 5, "kind": "ptr64_hi"},
73 {"sgpr": 6, "kind": "tsharp"}]
74 assert rsc.reconcile(reads, dwords) == []
75
76
77@pytest.mark.parametrize(("sgpr", "kind", "needle"), [
78 (0, "ptr64_lo", "incompatible"), # s0 is a constant dword, not a VA
79 (31, "const32", "8 dwords"), # layout ends at s7
80 (4, "ptr64_hi", "paired lo"), # s4 is sub 0 of the CBV pair
81 (0, "nope", "unknown read kind"),
82])
83def test_reconcile_contradictions(sgpr, kind, needle):
84 dwords, _ = rsc.pack_layout(ROOT_SIG)
85 issues = rsc.reconcile([{"sgpr": sgpr, "kind": kind}], dwords)
86 assert len(issues) == 1 and needle in issues[0]
87
88
89def test_cluster_groups_shapes():
90 index = {
91 "a": {"user_sgpr_reads": [{"sgpr": 0, "kind": "const32"}]},
92 "b": {"user_sgpr_reads": [{"sgpr": 0, "kind": "const32"}]},
93 "c": {"user_sgpr_reads": [{"sgpr": 4, "kind": "ptr64_lo"}]},
94 }
95 ranked = rsc.cluster(index)
96 assert ranked[0][1] == 2 and ranked[1][1] == 1
97
98
99def test_cli_hard_fail_on_contradiction(tmp_path):
100 index = {"bad": {"user_sgpr_reads": [{"sgpr": 31, "kind": "const32"}]}}
101 index_path = tmp_path / "index.json"
102 index_path.write_text(json.dumps(index), encoding="utf-8")
103 sig_path = tmp_path / "sig.json"
104 sig_path.write_text(json.dumps(ROOT_SIG), encoding="utf-8")
105 r = subprocess.run(
106 [sys.executable, "-I", TOOL, str(index_path),
107 "--rootsig", str(sig_path)],
108 capture_output=True, text=True)
109 assert r.returncode == 1
110 assert "CONTRADICTION bad" in r.stdout
diff --git a/tests/test_rpf9_carve.py b/tests/test_rpf9_carve.py
index b5407a12b..c7a11d82b 100644
--- a/tests/test_rpf9_carve.py
+++ b/tests/test_rpf9_carve.py
@@ -43,5 +43,38 @@ class CarveTrailingStreamTest(unittest.TestCase):
43 self.assertEqual(doc["files"][1]["off"], 0x40 + len(a)) 43 self.assertEqual(doc["files"][1]["off"], 0x40 + len(a))
44 44
45 45
46def carve(test, data):
47 """Run rpf9_carve.py on `data`; return its index.json after checking it exited cleanly."""
48 with tempfile.TemporaryDirectory() as tmp:
49 arc = os.path.join(tmp, "x.rpf")
50 out = os.path.join(tmp, "out")
51 with open(arc, "wb") as f:
52 f.write(data)
53 p = subprocess.run([sys.executable, "-I", TOOL, arc, out, "--index-only"], capture_output=True, text=True)
54 test.assertEqual(p.returncode, 0, p.stderr)
55 with open(os.path.join(out, "index.json"), encoding="utf-8") as f:
56 return json.load(f)
57
58
59class CarveEdgeTest(unittest.TestCase):
60 def test_bink_signature_cut_off_by_end_of_file(self):
61 # A truncated copy can end inside what looks like a Bink 2 header: its fields lie past the end of the file.
62 a = zlib.compress(b"A" * 1000)
63 data = bytearray(0x40) + a + b"KB2a" + bytes(8)
64 data[0:4] = b"RPF9"
65 struct.pack_into("<I", data, 4, 0x40)
66 doc = carve(self, bytes(data))
67 self.assertEqual(doc["summary"]["files"], 1, doc["summary"])
68 self.assertEqual(doc["summary"]["unread_bytes"], 12)
69
70 def test_empty_data_area(self):
71 data = bytearray(0x40)
72 data[0:4] = b"RPF9"
73 struct.pack_into("<I", data, 4, 0x40) # data starts at the end of the file
74 doc = carve(self, bytes(data))
75 self.assertEqual(doc["summary"]["files"], 0)
76 self.assertEqual(doc["summary"]["span"], 0)
77
78
46if __name__ == "__main__": 79if __name__ == "__main__":
47 unittest.main() 80 unittest.main()
diff --git a/tests/test_rpf_probe.py b/tests/test_rpf_probe.py
new file mode 100644
index 000000000..205a77103
--- /dev/null
+++ b/tests/test_rpf_probe.py
@@ -0,0 +1,153 @@
1"""Tests for tools/rpf_probe.py, built from synthetic archive headers (no game data).
2
3 python -I tests/test_rpf_probe.py
4"""
5import contextlib
6import importlib.util
7import io
8import json
9import os
10import struct
11import tempfile
12import unittest
13from unittest import mock
14
15ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
16
17
18def load_module():
19 path = os.path.join(ROOT, "tools", "rpf_probe.py")
20 spec = importlib.util.spec_from_file_location("rpf_probe_under_test", path)
21 module = importlib.util.module_from_spec(spec)
22 spec.loader.exec_module(module)
23 return module
24
25
26probe = load_module()
27
28
29def archive_bytes(version=b"4FPR", words=(0x10, 0x20, 0x30, 0x40), pad_to=None, tail=b""):
30 """Little-endian 'RPF4' magic, four header words, then optional padding and payload."""
31 data = version + struct.pack("<4I", *words)
32 if pad_to is not None and len(data) < pad_to:
33 data += b"\x00" * (pad_to - len(data))
34 return data + tail
35
36
37class EntropyTests(unittest.TestCase):
38 def test_empty_is_zero(self):
39 self.assertEqual(probe.entropy(b""), 0.0)
40
41 def test_single_symbol_is_zero(self):
42 self.assertEqual(probe.entropy(b"\x00" * 16), 0.0)
43
44 def test_two_equally_frequent_symbols(self):
45 self.assertEqual(probe.entropy(b"\x00\x01" * 8), 1.0)
46
47 def test_all_byte_values_once(self):
48 self.assertEqual(probe.entropy(bytes(range(256))), 8.0)
49
50
51class ProbeTests(unittest.TestCase):
52 def setUp(self):
53 tmp = tempfile.TemporaryDirectory()
54 self.addCleanup(tmp.cleanup)
55 self.dir = tmp.name
56
57 def write(self, data, name="a.rpf"):
58 path = os.path.join(self.dir, name)
59 os.makedirs(os.path.dirname(path), exist_ok=True)
60 with open(path, "wb") as f:
61 f.write(data)
62 return path
63
64 def test_version_and_header_words(self):
65 row = probe.probe(self.write(archive_bytes(words=(0x0, 0xFFFFFFFF, 0x1234, 0x10))))
66 self.assertEqual(row["version"], "RPF4")
67 self.assertEqual(row["header_words"], ["0x0", "0xffffffff", "0x1234", "0x10"])
68
69 def test_natural_order_magic_is_not_a_version(self):
70 self.assertEqual(probe.probe(self.write(b"RPF4" + b"\x00" * 16))["version"], None)
71
72 def test_other_magic_has_no_version(self):
73 self.assertEqual(probe.probe(self.write(b"DDS " + b"\x00" * 30))["version"], None)
74
75 def test_short_file_has_no_words(self):
76 row = probe.probe(self.write(b"4FPR" + b"\x00" * 4))
77 self.assertEqual(row["version"], "RPF4")
78 self.assertEqual(row["header_words"], [])
79 self.assertEqual(row["head_entropy"], 0.0)
80 self.assertFalse(row["looks_encrypted"])
81
82 def test_zero_filled_body_is_not_flagged(self):
83 row = probe.probe(self.write(archive_bytes(words=(0, 0, 0, 0), pad_to=1024)))
84 self.assertEqual(row["head_entropy"], 0.0)
85 self.assertFalse(row["looks_encrypted"])
86
87 def test_dense_body_is_flagged(self):
88 row = probe.probe(self.write(archive_bytes(tail=bytes(range(256)) * 16)))
89 self.assertGreater(row["head_entropy"], 7.9)
90 self.assertTrue(row["looks_encrypted"])
91
92 def test_only_the_first_64_kib_is_read(self):
93 path = self.write(archive_bytes(pad_to=0x10000, tail=bytes(range(256)) * 16))
94 row = probe.probe(path)
95 self.assertEqual(row["size"], 0x10000 + 4096)
96 self.assertEqual(row["head_entropy"], 0.0)
97 self.assertFalse(row["looks_encrypted"])
98
99 def test_size_is_the_full_file(self):
100 self.assertEqual(probe.probe(self.write(archive_bytes(pad_to=0x10000)))["size"], 0x10000)
101
102
103class MainTests(unittest.TestCase):
104 def setUp(self):
105 tmp = tempfile.TemporaryDirectory()
106 self.addCleanup(tmp.cleanup)
107 self.tmp = tmp.name
108 self.game = os.path.join(self.tmp, "game")
109 os.makedirs(self.game)
110 self.out = os.path.join(self.tmp, "reports", "rpf.json")
111
112 def write(self, rel, data):
113 path = os.path.join(self.game, rel)
114 os.makedirs(os.path.dirname(path), exist_ok=True)
115 with open(path, "wb") as f:
116 f.write(data)
117 return path
118
119 def run_main(self):
120 out = io.StringIO()
121 with mock.patch("sys.argv", ["rpf_probe.py", self.game, "--out", self.out]), contextlib.redirect_stdout(out):
122 self.assertEqual(probe.main(), 0)
123 return out.getvalue()
124
125 def rows(self):
126 with open(self.out, encoding="utf-8") as f:
127 return json.load(f)
128
129 def test_collects_rpf_files_recursively_and_sorts_by_size(self):
130 small = self.write("a.rpf", archive_bytes())
131 large = self.write("sub/b.RPF", archive_bytes(pad_to=4096))
132 self.write("sub/notes.txt", b"ignored")
133 out = self.run_main()
134 rows = self.rows()
135 self.assertEqual([os.path.basename(r["file"]) for r in rows], ["b.RPF", "a.rpf"])
136 self.assertEqual(os.path.normpath(rows[0]["file"]), os.path.normpath(large))
137 self.assertEqual(os.path.normpath(rows[1]["file"]), os.path.normpath(small))
138 self.assertIn("2 archives", out)
139 self.assertIn("'RPF4': 2", out)
140
141 def test_creates_the_output_directory(self):
142 self.write("a.rpf", archive_bytes())
143 self.run_main()
144 self.assertTrue(os.path.isfile(self.out))
145
146 def test_empty_game_directory(self):
147 out = self.run_main()
148 self.assertEqual(self.rows(), [])
149 self.assertIn("0 archives", out)
150
151
152if __name__ == "__main__":
153 unittest.main()
diff --git a/tests/test_shader_checks.py b/tests/test_shader_checks.py
index 68de87947..748c780d5 100644
--- a/tests/test_shader_checks.py
+++ b/tests/test_shader_checks.py
@@ -13,7 +13,7 @@ import check
13 13
14# The other wave64-only dump tests (#73's cs_wm_*, the cs_w64x_* cross-half tests): name -> expected out[] words. 14# The other wave64-only dump tests (#73's cs_wm_*, the cs_w64x_* cross-half tests): name -> expected out[] words.
15WAVE64_DUMPS = {n: w for n, w in check.CS_DUMPS + check.W64X_DUMPS + check.W64X_PARTIAL 15WAVE64_DUMPS = {n: w for n, w in check.CS_DUMPS + check.W64X_DUMPS + check.W64X_PARTIAL
16 if n not in ("cs_store", "cs_wave64_ballot")} 16 if n not in (*check.WAVE32_DUMPS, "cs_wave64_ballot")}
17# A group smaller than a wave can't ask for full subgroups: it asks for subgroup size 64 and reads the device's range. 17# A group smaller than a wave can't ask for full subgroups: it asks for subgroup size 64 and reads the device's range.
18PARTIAL = {n for n, _ in check.W64X_PARTIAL} 18PARTIAL = {n for n, _ in check.W64X_PARTIAL}
19 19
@@ -57,6 +57,10 @@ class Wave64Checks(unittest.TestCase):
57 self.assertNotIn("--require-wave64", args) 57 self.assertNotIn("--require-wave64", args)
58 if name == "cs_store": 58 if name == "cs_store":
59 return 0, "out[0..7] = 1073774847 3758097407 1006649344 4008636142 1073757184 3154130944 0 0\n" 59 return 0, "out[0..7] = 1073774847 3758097407 1006649344 4008636142 1073757184 3154130944 0 0\n"
60 if name == "cs_smem_soffset_imm":
61 return 0, "out[0..7] = " + " ".join(map(str, check.CS_SMEM)) + "\n"
62 if name == "cs_workgroup_yz": # #186: vk_compute_test's 2x3x4 Y/Z histogram line
63 return 0, "2x3x4 workgroup Y/Z: 0 mismatches\n"
60 if name in ("cs_imgstore", "cs_imgload"): 64 if name in ("cs_imgstore", "cs_imgload"):
61 return 0, "0 bad\n0 bad\n0 bad\n" 65 return 0, "0 bad\n0 bad\n0 bad\n"
62 return 0, "0 mismatches\n" 66 return 0, "0 mismatches\n"
diff --git a/tests/test_shader_ir.py b/tests/test_shader_ir.py
new file mode 100644
index 000000000..b4655f533
--- /dev/null
+++ b/tests/test_shader_ir.py
@@ -0,0 +1,226 @@
1"""Tests for tools/shader_ir.py, built from synthetic AMDGPU disassembly (no game data).
2
3 python -I tests/test_shader_ir.py
4"""
5import importlib.util
6import os
7import tempfile
8import unittest
9
10ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
11
12
13def load_module():
14 path = os.path.join(ROOT, "tools", "shader_ir.py")
15 spec = importlib.util.spec_from_file_location("shader_ir_under_test", path)
16 module = importlib.util.module_from_spec(spec)
17 spec.loader.exec_module(module)
18 return module
19
20
21shader_ir = load_module()
22
23
24class OperandTests(unittest.TestCase):
25 def test_single_registers(self):
26 self.assertEqual(
27 shader_ir.operand("s5"),
28 {"k": "sgpr", "r": 5, "n": 1, "neg": False, "abs": False},
29 )
30 self.assertEqual(
31 shader_ir.operand("v3"),
32 {"k": "vgpr", "r": 3, "n": 1, "neg": False, "abs": False},
33 )
34
35 def test_register_ranges(self):
36 self.assertEqual(
37 shader_ir.operand("s[4:7]"),
38 {"k": "sgpr", "r": 4, "n": 4, "neg": False, "abs": False},
39 )
40 self.assertEqual(
41 shader_ir.operand("v[0:0]"),
42 {"k": "vgpr", "r": 0, "n": 1, "neg": False, "abs": False},
43 )
44
45 def test_negation_and_absolute_value(self):
46 self.assertTrue(shader_ir.operand("-v2")["neg"])
47 self.assertTrue(shader_ir.operand("|s1|")["abs"])
48 both = shader_ir.operand("-|v2|")
49 self.assertTrue(both["neg"])
50 self.assertTrue(both["abs"])
51
52 def test_inline_and_float_constants(self):
53 self.assertEqual(shader_ir.operand("0x10"), {"k": "imm", "v": 16})
54 self.assertEqual(shader_ir.operand("-5"), {"k": "imm", "v": -5})
55 self.assertEqual(shader_ir.operand("1.5"), {"k": "fimm", "v": 1.5, "abs": False})
56 self.assertEqual(shader_ir.operand("-2.5e1"), {"k": "fimm", "v": -25.0, "abs": False})
57 self.assertEqual(shader_ir.operand("|1.0|"), {"k": "fimm", "v": 1.0, "abs": True})
58
59 def test_hardware_negation_of_constants(self):
60 # The disassembler prints VOP3 inline negation as neg(0) / neg(5).
61 self.assertEqual(shader_ir.operand("neg(0)"), {"k": "fimm", "v": -0.0, "abs": False})
62 self.assertEqual(shader_ir.operand("neg(5)"), {"k": "imm", "v": -5})
63 self.assertEqual(shader_ir.operand("neg(1.0)"), {"k": "fimm", "v": -1.0, "abs": False})
64
65 def test_negation_of_registers_toggles(self):
66 self.assertTrue(shader_ir.operand("neg(v1)")["neg"])
67 self.assertFalse(shader_ir.operand("neg(neg(v1))")["neg"])
68
69 def test_sign_extension(self):
70 self.assertTrue(shader_ir.operand("sext(v1)")["sext"])
71 self.assertFalse(shader_ir.operand("sext(v1)")["neg"])
72 self.assertTrue(shader_ir.operand("-sext(v1)")["neg"])
73 self.assertTrue(shader_ir.operand("sext(neg(v1))")["neg"])
74
75 def test_ttmp_registers(self):
76 self.assertEqual(shader_ir.operand("ttmp5"), {"k": "ttmp", "t": "ttmp5"})
77 self.assertEqual(shader_ir.operand("ttmp[4:5]"), {"k": "ttmp", "t": "ttmp[4:5]"})
78
79 def test_non_contiguous_vgpr_list(self):
80 self.assertEqual(shader_ir.operand("[v1, v2, v3]"), {"k": "vlist", "r": [1, 2, 3]})
81
82 def test_attribute_and_interpolation(self):
83 self.assertEqual(shader_ir.operand("attr2.w"), {"k": "attr", "a": 2, "c": 3})
84 self.assertEqual(shader_ir.operand("p10"), {"k": "interp", "t": "p10"})
85
86 def test_export_targets(self):
87 self.assertEqual(shader_ir.operand("pos0"), {"k": "target", "t": "pos0"})
88 self.assertEqual(shader_ir.operand("mrt1"), {"k": "target", "t": "mrt1"})
89 self.assertEqual(shader_ir.operand("mrtz"), {"k": "target", "t": "mrtz"})
90
91 def test_special_registers_including_null(self):
92 for name in ("vcc_lo", "exec", "m0", "scc", "null", "off"):
93 with self.subTest(name=name):
94 self.assertEqual(shader_ir.operand(name)["k"], "special")
95 self.assertEqual(shader_ir.operand(name)["t"], name)
96
97 def test_hardware_register_and_counter_forms(self):
98 self.assertEqual(shader_ir.operand("hwreg(0x1234)")["k"], "special")
99 self.assertEqual(shader_ir.operand("vmcnt(3)")["k"], "special")
100 self.assertEqual(shader_ir.operand("sendmsg(MSG_GS)")["k"], "special")
101
102 def test_unknown_operand_falls_back_to_raw(self):
103 self.assertEqual(shader_ir.operand("weirdthing"), {"k": "raw", "t": "weirdthing"})
104
105
106class SplitArgsTests(unittest.TestCase):
107 def test_commas_inside_parentheses_stay_together(self):
108 self.assertEqual(
109 shader_ir.split_args("a, b(1, 2), c"),
110 ["a", " b(1, 2)", " c"],
111 )
112
113 def test_commas_inside_brackets_stay_together(self):
114 self.assertEqual(shader_ir.split_args("[v1, v2], v3"), ["[v1, v2]", " v3"])
115
116 def test_trailing_comma_is_dropped(self):
117 self.assertEqual(shader_ir.split_args("v0,"), ["v0"])
118
119 def test_empty_text(self):
120 self.assertEqual(shader_ir.split_args(""), [])
121
122
123class ParseLineTests(unittest.TestCase):
124 def test_operation_and_operands(self):
125 ins = shader_ir.parse_line("\tv_add_f32 v0, v1, v2")
126 self.assertEqual(ins["op"], "v_add_f32")
127 self.assertEqual([a["k"] for a in ins["args"]], ["vgpr", "vgpr", "vgpr"])
128 self.assertEqual(ins["mods"], [])
129 self.assertIsNone(ins["enc"])
130
131 def test_encoding_bytes(self):
132 ins = shader_ir.parse_line("\tv_mov_b32 v0, v1 ; encoding: [0x0a,0xff]")
133 self.assertEqual(ins["enc"], "0aff")
134 self.assertEqual(len(ins["args"]), 2)
135
136 def test_comment_or_blank_lines_are_skipped(self):
137 self.assertIsNone(shader_ir.parse_line("; only a comment"))
138 self.assertIsNone(shader_ir.parse_line(""))
139 self.assertIsNone(shader_ir.parse_line(" \t "))
140
141 def test_modifiers_are_removed_from_the_operands(self):
142 ins = shader_ir.parse_line(
143 "\tbuffer_load_dword v5, v[0:3], s[4:7], 0 offen offset:8 glc slc"
144 )
145 self.assertEqual(ins["mods"], ["offen", "offset:8", "glc", "slc"])
146 self.assertEqual([a["k"] for a in ins["args"]], ["vgpr", "vgpr", "sgpr", "imm"])
147 self.assertEqual(ins["args"][1]["n"], 4)
148 self.assertEqual(ins["args"][2]["n"], 4)
149
150 def test_dpp_modifiers_keep_their_bracket_lists(self):
151 ins = shader_ir.parse_line(
152 "\tv_mov_b32_dpp v0, v1 quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf"
153 )
154 self.assertEqual(
155 ins["mods"],
156 ["quad_perm:[1,0,3,2]", "row_mask:0xf", "bank_mask:0xf"],
157 )
158 self.assertEqual(len(ins["args"]), 2)
159
160 def test_exp_target_is_split_from_its_operands(self):
161 ins = shader_ir.parse_line("\texp mrt0 v0, v1, v2, v3")
162 self.assertEqual(len(ins["args"]), 5)
163 self.assertEqual(ins["args"][0], {"k": "target", "t": "mrt0"})
164 self.assertEqual(ins["args"][1]["k"], "vgpr")
165
166 def test_exp_null_off_target(self):
167 ins = shader_ir.parse_line("\texp null off, v0, v1, v2")
168 self.assertEqual([a["t"] for a in ins["args"][:2]], ["null", "off"])
169 self.assertEqual(len(ins["args"]), 5)
170
171 def test_sendmsg_commas_stay_in_one_operand(self):
172 ins = shader_ir.parse_line("\ts_sendmsg sendmsg(MSG_GS, GS_OP_NOP)")
173 self.assertEqual(len(ins["args"]), 1)
174 self.assertEqual(ins["args"][0]["k"], "special")
175
176 def test_no_operands(self):
177 self.assertEqual(shader_ir.parse_line("\ts_endpgm")["args"], [])
178
179
180class ParseFileTests(unittest.TestCase):
181 def write(self, text):
182 tmp = tempfile.TemporaryDirectory()
183 self.addCleanup(tmp.cleanup)
184 path = os.path.join(tmp.name, "shader_abc.s")
185 with open(path, "w", encoding="utf-8", newline="\n") as f:
186 f.write(text)
187 return path
188
189 def test_header_start_and_pc_stepping(self):
190 path = self.write(
191 "; shader.cs_5_0 code 0x00000100..0x00000110\n"
192 "\tv_mov_b32 v0, 1.0 ; encoding: [0x01,0x02]\n"
193 "\tv_add_f32 v1, v0, v2 ; encoding: [0x03,0x04]\n"
194 "\tv_sub_f32 v3, v1, v0 ; no encoding bytes here\n"
195 "\t.directive skipped\n"
196 "plain text is not an instruction\n"
197 "; ---\n"
198 "\tv_mul_f32 v4, v3, v2 ; encoding: [0x05,0x06]\n"
199 "; invalid instruction encoding [0xdead]\n"
200 )
201 info = shader_ir.parse_file(path)
202 self.assertEqual(info["name"], "shader_abc")
203 self.assertEqual(info["code_start"], 0x100)
204 self.assertEqual([i["op"] for i in info["insns"]],
205 ["v_mov_b32", "v_add_f32", "v_sub_f32"])
206 # pc advances by the encoding length; an instruction without bytes keeps the offset.
207 self.assertEqual([i["pc"] for i in info["insns"]], [0x100, 0x102, 0x104])
208 self.assertEqual(info["invalid"], 1)
209
210 def test_file_without_a_header_starts_at_zero(self):
211 path = self.write("\tv_mov_b32 v0, v1 ; encoding: [0xaa,0xbb]\n")
212 info = shader_ir.parse_file(path)
213 self.assertEqual(info["code_start"], 0)
214 self.assertEqual(info["insns"][0]["pc"], 0)
215 self.assertEqual(info["insns"][0]["enc"], "aabb")
216
217 def test_header_only_file_has_no_instructions(self):
218 path = self.write("; shader.cs_6_0 code 0x00001000..0x00001008\n")
219 info = shader_ir.parse_file(path)
220 self.assertEqual(info["code_start"], 0x1000)
221 self.assertEqual(info["insns"], [])
222 self.assertEqual(info["invalid"], 0)
223
224
225if __name__ == "__main__":
226 unittest.main()
diff --git a/tests/test_translate.py b/tests/test_translate.py
index b825b5416..4e60193b4 100644
--- a/tests/test_translate.py
+++ b/tests/test_translate.py
@@ -286,6 +286,29 @@ def test_vs_misc_pos1_shifts_clip_to_pos2(make_shader):
286 assert [int(x) for x in clip_chains] == [0, 1] 286 assert [int(x) for x in clip_chains] == [0, 1]
287 287
288 288
289def test_pos1_without_osg1_is_ignored(make_shader):
290 """Without OSG1 declaring SV_ClipDistance/SV_CullDistance, pos1 exports are discarded in both VS and MS."""
291 vs = make_shader(_vs_header_asm("exp pos1 v10, off, off, off done"), name="vs_no_osg1_pos1")
292 vs_spv = vs.translate()
293 vs.validate(vs_spv)
294 assert "OpCapability ClipDistance" not in vs_spv
295 assert "BuiltIn ClipDistance" not in vs_spv
296 vs_meta = rdna2spirv.shader_meta(rdna2spirv.translate.last_gen, vs_spv)
297 assert "shaderClipDistance" not in vs_meta["features"]
298 assert 1 not in vs_meta.get("outputs", [])
299
300 ms = make_shader(_ms_header_asm("exp pos1 v10, off, off, off done"), name="ms_no_osg1_pos1",
301 dxbc=make_dxbc([mesh_psv0_chunk()]))
302 ms_spv = ms.translate()
303 ms.validate(ms_spv, KNOWN_VAL_ISSUES.get("ms_tri"))
304 assert "OpCapability ClipDistance" not in ms_spv
305 assert "BuiltIn ClipDistance" not in ms_spv
306 assert "%ms_out_pos" in ms_spv and "%ms_vtx_blk" not in ms_spv
307 ms_meta = rdna2spirv.shader_meta(rdna2spirv.translate.last_gen, ms_spv)
308 assert "shaderClipDistance" not in ms_meta["features"]
309 assert 1 not in ms_meta.get("params", [])
310
311
289def test_ms_dummy_all_off_pos1_does_not_emit_clip(make_shader): 312def test_ms_dummy_all_off_pos1_does_not_emit_clip(make_shader):
290 """An all-off dummy pos1 export in a mesh shader must not emit ClipDistance or change the output block.""" 313 """An all-off dummy pos1 export in a mesh shader must not emit ClipDistance or change the output block."""
291 dxbc = make_dxbc([mesh_psv0_chunk(), signature_chunk(b"OSG1", [(0, 1, 0xF), (1, 2, 0x1)])]) 314 dxbc = make_dxbc([mesh_psv0_chunk(), signature_chunk(b"OSG1", [(0, 1, 0xF), (1, 2, 0x1)])])
diff --git a/tests/test_ttpf_mips.py b/tests/test_ttpf_mips.py
new file mode 100644
index 000000000..a41f6c0e3
--- /dev/null
+++ b/tests/test_ttpf_mips.py
@@ -0,0 +1,291 @@
1"""Tests for tools/ttpf_mips.py: tile modes, mip-tail layout, BC decode, metric, and a
2synthetic RDS5/ETPF pool round trip. No game data is used.
3
4 python -I tests/test_ttpf_mips.py
5"""
6import importlib.util
7import json
8import os
9import struct
10import sys
11import tempfile
12import unittest
13import zlib
14
15ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
16TOOL = os.path.join(ROOT, "tools", "ttpf_mips.py")
17spec = importlib.util.spec_from_file_location("ttpf_mips", TOOL)
18ttpf = importlib.util.module_from_spec(spec)
19spec.loader.exec_module(ttpf)
20
21
22def rgb565(r, g, b):
23 return ((r * 31 // 255) << 11) | ((g * 63 // 255) << 5) | (b * 31 // 255)
24
25
26def solid_bc1(color):
27 c = rgb565(*color)
28 return struct.pack("<HHI", c, c, 0)
29
30
31def retile_to(layout, mip, linear, out):
32 pat = (ttpf.PATTERNS_4K if layout["tile"] == 4096 else ttp64)[
33 {1: 0, 2: 1, 4: 2, 8: 3, 16: 4}[layout["element_bytes"]]]
34 eb = layout["element_bytes"]
35 bw, bh = layout["block_w"], layout["block_h"]
36 for y in range(mip["blocks_h"]):
37 for x in range(mip["blocks_w"]):
38 off = ((y // bh) * (mip["padded_w"] // bw) + x // bw) * layout["tile"]
39 for bit, s in enumerate(pat):
40 if s > 0:
41 off |= (((x + mip["tile_x"]) >> (s - 1)) & 1) << bit
42 elif s < 0:
43 off |= (((y + mip["tile_y"]) >> (-s - 1)) & 1) << bit
44 at = (y * mip["blocks_w"] + x) * eb
45 out[mip["offset"] + off:mip["offset"] + off + eb] = linear[at:at + eb]
46
47
48ttpf64 = {
49 0: (1, 2, 3, -2, -1, -3, 4, -4, -5, 5, -6, 6, -7, 7, -8, 8),
50 1: (0, 1, 2, 3, -1, -2, -3, 4, -4, 5, -5, 6, -6, 7, -7, 8),
51 2: (0, 0, 1, 2, -1, -2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7),
52 3: (0, 0, 0, 1, -1, 2, 3, -2, -3, 4, -4, 5, -5, 6, -6, 7),
53 4: (0, 0, 0, 0, 1, -1, 2, -2, -3, 3, -4, 4, -5, 5, -6, 6),
54}
55
56
57def solid_chain(layout, fmt=71):
58 """Build block-linear bytes for every mip; each block is one solid BC1 colour."""
59 eb = layout["element_bytes"]
60 out = {}
61 # Smooth gradient at the top level; every lower mip is the 2x2 block mean.
62 top = layout["mips"][0]
63 colours = {}
64 for y in range(top["blocks_h"]):
65 for x in range(top["blocks_w"]):
66 colours[(0, x, y)] = (min(255, x * 255 // max(1, top["blocks_w"] - 1)),
67 min(255, y * 255 // max(1, top["blocks_h"] - 1)), 128)
68 for m in range(1, len(layout["mips"])):
69 pm = layout["mips"][m - 1]
70 cm = layout["mips"][m]
71 for y in range(cm["blocks_h"]):
72 for x in range(cm["blocks_w"]):
73 acc = [0, 0, 0]
74 n = 0
75 for dy in range(2):
76 for dx in range(2):
77 px, py = min(pm["blocks_w"] - 1, 2 * x + dx), min(pm["blocks_h"] - 1, 2 * y + dy)
78 q = colours[(m - 1, px, py)]
79 for k in range(3):
80 acc[k] += q[k]
81 n += 1
82 colours[(m, x, y)] = tuple(a // n for a in acc)
83 for mip in layout["mips"]:
84 buf = bytearray(mip["blocks_w"] * mip["blocks_h"] * eb)
85 for y in range(mip["blocks_h"]):
86 for x in range(mip["blocks_w"]):
87 at = (y * mip["blocks_w"] + x) * eb
88 buf[at:at + eb] = solid_bc1(colours[(mip["index"], x, y)])[:eb].ljust(eb, b"\0")
89 out[mip["index"]] = bytes(buf)
90 return out
91
92
93def build_pool(path, width=256, height=256, mips=7, non_tail=1, fmt=71, mode=4,
94 meta=0x103, extra=0, packed=6):
95 layout = ttpf.surface_layout(width, height, fmt, mips, ttpf.tile_bytes(mode))
96 linear = solid_chain(layout, fmt)
97 payload = bytearray(layout["size"])
98 for mip in layout["mips"]:
99 retile_to(layout, mip, linear[mip["index"]], payload)
100 packed_payload = zlib.compress(bytes(payload), 9)
101 pad = (-len(packed_payload)) % 256
102 count = 3
103 table_end = 24 + (count - 1) * 8
104 etpf = ttpf.align(table_end, 256)
105 metadata = 16 + 24 + 32
106 padded = ttpf.align(metadata, 4096)
107 source = etpf + padded
108 chunk_end = source + len(packed_payload) + pad
109 virt = padded
110 vsize = virt + layout["size"]
111 assert vsize % 4096 == 0
112 entry = (source // 256) | (8 << 26) | ((virt // 4096) << 30) | (pad << 52)
113 sentinel = (chunk_end // 256) | ((vsize // 4096) << 30)
114 header = bytearray(24)
115 header[0:4] = b"RDS5"
116 struct.pack_into("<I", header, 4, count)
117 struct.pack_into("<Q", header, 8, vsize | (22 << 56))
118 struct.pack_into("<I", header, 16, (count + 31) // 32)
119 struct.pack_into("<I", header, 20, 0)
120 a = (width - 1) | ((height - 1) << 14) | ((packed & 0xF) << 28)
121 b = non_tail | (fmt << 3) | (1 << 21) | (mode << 23)
122 c = (virt // 4096) | (meta << 21)
123 record = struct.pack("<IIII", a, b, c, extra) + struct.pack("<Q", 0x1234567890ABCDEF)
124 blob = bytearray(chunk_end)
125 blob[0:24] = header
126 struct.pack_into("<QQ", blob, 24, entry, sentinel)
127 blob[etpf:etpf + 4] = b"ETPF"
128 struct.pack_into("<III", blob, etpf + 4, 634, 1, 24)
129 blob[etpf + 16:etpf + 16 + 24] = record
130 blob[source:source + len(packed_payload)] = packed_payload
131 with open(path, "wb") as f:
132 f.write(blob)
133 return layout
134
135
136class TileModeTest(unittest.TestCase):
137 def test_mode_is_flag_plus_tile_mode(self):
138 self.assertEqual([ttpf.tile_mode(m) for m in (0, 1, 2, 4, 5, 6, 7, 32, 34, 36, 38)],
139 [0, 0, 1, 2, 2, 3, 3, 0, 1, 2, 3])
140 self.assertEqual([ttpf.tile_bytes(m) for m in (0, 1, 2, 4, 32, 34)],
141 [65536, 65536, 4096, 4096, 65536, 4096])
142
143
144class LayoutTest(unittest.TestCase):
145 def test_known_bc1_chain_sizes(self):
146 lay = ttpf.surface_layout(256, 256, 71, 7, 4096)
147 self.assertEqual(lay["first_tail"], 2)
148 self.assertEqual(lay["size"], 45056)
149 self.assertEqual([m["region"] for m in lay["mips"]],
150 [32768, 8192, 4096, 4096, 4096, 4096, 4096])
151 self.assertEqual([m["offset"] for m in lay["mips"][:2]], [12288, 4096])
152 # 16x16 pixels = 4x4 blocks at in-tile origin (16, 0)
153 self.assertEqual((lay["mips"][2]["blocks_w"], lay["mips"][2]["blocks_h"]), (16, 16))
154 self.assertEqual((lay["mips"][2]["tile_x"], lay["mips"][2]["tile_y"]), (16, 0))
155
156 def test_validated_1024_chain(self):
157 lay = ttpf.surface_layout(1024, 1024, 71, 9, 4096)
158 self.assertEqual(lay["first_tail"], 4)
159 self.assertEqual(lay["size"], 700416)
160 self.assertEqual([m["region"] for m in lay["mips"][:4]],
161 [524288, 131072, 32768, 8192])
162 self.assertEqual(lay["mips"][4]["tile_x"], 16)
163 self.assertEqual(lay["mips"][4]["tile_y"], 0)
164
165 def test_64k_tile_mode(self):
166 lay = ttpf.surface_layout(1024, 1024, 98, 9, 65536)
167 self.assertEqual(lay["size"], 1441792)
168 self.assertEqual(lay["first_tail"], 3)
169 self.assertEqual(lay["tile"], 65536)
170
171 def test_bad_mip_count(self):
172 with self.assertRaises(ttpf.LayoutError):
173 ttpf.surface_layout(64, 64, 71, 20, 4096)
174
175
176class BcDecodeTest(unittest.TestCase):
177 def test_bc1_solid_block(self):
178 block = solid_bc1((255, 0, 0))
179 px = ttpf.decode_pixels(71, block, 1, 1)
180 self.assertEqual(len(px), 16)
181 self.assertGreater(px[0][0], 250)
182 self.assertLess(px[0][1], 8)
183
184 def test_bc1_four_colour_mode(self):
185 # c0=white > c1=black: index 0 -> white, index 3 -> (c0 + 2*c1)/3
186 white = ttpf.decode_pixels(71, struct.pack("<HHI", 0xFFFF, 0x0000, 0), 1, 1)
187 self.assertGreater(white[0][0], 250)
188 dark = ttpf.decode_pixels(71, struct.pack("<HHI", 0xFFFF, 0x0000, 0xFFFFFFFF), 1, 1)
189 self.assertLess(dark[0][0], 100)
190
191 def test_metric_rewards_the_true_downsample(self):
192 parent = [(0.0, 0.0, 0.0), (255.0, 0.0, 0.0), (0.0, 255.0, 0.0), (0.0, 0.0, 255.0)]
193 child = [(63.75, 63.75, 63.75)]
194 self.assertLess(ttpf.mean_abs_error(ttpf.downsample2(parent, 2, 2), child), 1.0)
195 wrong = [(0.0, 255.0, 0.0)]
196 self.assertGreater(ttpf.mean_abs_error(ttpf.downsample2(parent, 2, 2), wrong), 50)
197
198
199class SyntheticPoolTest(unittest.TestCase):
200 def setUp(self):
201 self.tmp = tempfile.TemporaryDirectory()
202 self.addCleanup(self.tmp.cleanup)
203 self.path = os.path.join(self.tmp.name, "synthetic.ttpf")
204 self.layout = build_pool(self.path)
205 self.pool = ttpf.Pool(self.path)
206 self.addCleanup(self.pool.close)
207
208 def test_descriptor_and_layout(self):
209 d = self.pool.descriptor(0)
210 self.assertEqual((d["width"], d["height"], d["format"], d["mips"], d["non_tail"]),
211 (256, 256, 71, 7, 1))
212 self.assertEqual(d["mode"], 4)
213 a = ttpf.analyze(self.pool, 0)
214 self.assertTrue(a["span_matches"])
215 self.assertTrue(a["full_chain"])
216 self.assertEqual(a["layout"]["first_tail"], 2)
217
218 def test_detile_round_trip(self):
219 a = ttpf.analyze(self.pool, 0)
220 layout = a["layout"]
221 tiled = self.pool.read_range(a["descriptor"]["base"], layout["size"])
222 linear = solid_chain(layout)
223 for mip in layout["mips"]:
224 data = ttpf.detile(layout, mip, tiled[mip["offset"]:mip["offset"] + mip["region"]])
225 self.assertEqual(data, linear[mip["index"]])
226
227 def test_chain_metric(self):
228 import io
229 from contextlib import redirect_stdout
230 buf = io.StringIO()
231 with redirect_stdout(buf):
232 code = ttpf.check(self.pool, 0)
233 result = json.loads(buf.getvalue())
234 self.assertEqual(code, 0, result)
235 self.assertLess(result["max_error"], 4.0)
236 # a wrong in-tile origin for the first tail mip must be much worse
237 self.assertGreater(result["tail_origin_control"], 5 * result["max_error"])
238
239 def test_export_full_chain(self):
240 out = os.path.join(self.tmp.name, "chain.dds")
241 import io
242 from contextlib import redirect_stdout
243 with redirect_stdout(io.StringIO()):
244 self.assertEqual(ttpf.export(self.pool, 0, out), 0)
245 with open(out, "rb") as f:
246 data = f.read()
247 self.assertEqual(data[:4], b"DDS ")
248 mips = struct.unpack_from("<I", data, 28)[0]
249 self.assertEqual(mips, 7)
250 expected = 148 + sum(m["blocks_w"] * m["blocks_h"] * 8 for m in self.layout["mips"])
251 self.assertEqual(len(data), expected)
252 # payload is exactly the concatenated block-linear chain
253 linear = solid_chain(self.layout)
254 self.assertEqual(data[148:], b"".join(linear[m["index"]] for m in self.layout["mips"]))
255
256 def test_scan_reports_the_whitelist_gate(self):
257 # The synthetic tuple is validated, so it is not gated: the partial export is
258 # the descriptor non_tail limit, not the 319-byte profile table.
259 out = os.path.join(self.tmp.name, "scan.json")
260 import io
261 from contextlib import redirect_stdout
262 with redirect_stdout(io.StringIO()):
263 ttpf.scan_pools([self.path], out)
264 with open(out, encoding="utf-8") as f:
265 result = json.load(f)["total"]
266 self.assertEqual(result["entries"], 1)
267 self.assertEqual(result["whitelist_gated"], 0)
268 self.assertEqual(result["reader_partial"], 1)
269 self.assertEqual(result["compact_partial_rows"], 1)
270 self.assertEqual(result["compact_missing_mips"], 6)
271 self.assertEqual(result["compact_decodable_mips"], 6)
272 self.assertEqual(result["compact_full_rows"], 1)
273
274 def test_scan_counts_an_unlisted_tuple_as_gated(self):
275 path = os.path.join(self.tmp.name, "unlisted.ttpf")
276 build_pool(path, meta=0x599)
277 out = os.path.join(self.tmp.name, "scan2.json")
278 import io
279 from contextlib import redirect_stdout
280 with redirect_stdout(io.StringIO()):
281 ttpf.scan_pools([path], out)
282 with open(out, encoding="utf-8") as f:
283 total = json.load(f)["total"]
284 self.assertEqual(total["whitelist_gated"], 1)
285 self.assertEqual(total["gated_layout_ok"], 1)
286 self.assertEqual(total["gated_full_chain"], 1)
287 self.assertEqual(total["gated_full_mips"], 7)
288
289
290if __name__ == "__main__":
291 unittest.main()
diff --git a/tests/test_world_census.py b/tests/test_world_census.py
new file mode 100644
index 000000000..dc98268ad
--- /dev/null
+++ b/tests/test_world_census.py
@@ -0,0 +1,167 @@
1"""Tests for tools/world_census.py, built from synthetic 0x7a resources and RPF9 streams (no game data).
2
3 python -I tests/test_world_census.py
4"""
5import importlib.util
6import os
7import struct
8import tempfile
9import unittest
10import zlib
11
12ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
13
14
15def load_tool():
16 path = os.path.join(ROOT, "tools", "world_census.py")
17 spec = importlib.util.spec_from_file_location("world_census_under_test", path)
18 module = importlib.util.module_from_spec(spec)
19 spec.loader.exec_module(module)
20 return module
21
22
23WC = load_tool()
24WI = WC.WI
25PTR = 0x50000000
26
27
28def ptr(off):
29 return PTR | off
30
31
32def member(hash_, off, ty, sub=0, ref=0, extra=0):
33 return struct.pack("<IIBBHI", hash_, off, ty, sub, ref, extra)
34
35
36def struct_def(hash_, size, members, at, member_at):
37 return struct.pack("<IIIIQIHH", hash_, 0, 0, 0, ptr(member_at), size, 0, len(members))
38
39
40def make_resource(map_file=True):
41 """A minimal, valid 0x7a resource with one entity and (optionally) a map root."""
42 b = bytearray(0x700)
43 b[0x10:0x14] = b"0DRP"
44 b[0x14] = 0x7A
45 struct.pack_into("<I", b, 0x20, 1)
46 struct.pack_into("<Q", b, 0x28, ptr(0x100))
47 struct.pack_into("<Q", b, 0x38, ptr(0x200))
48 nst = 2 if map_file else 1
49 nbl = 2 if map_file else 1
50 struct.pack_into("<HHHH", b, 0x48, nst, 0, nbl, 0)
51
52 members = [
53 member(WI.FIELD["archetypeName"], 0x44, 0x4A),
54 member(WI.FIELD["position"], 0x38, 0x32),
55 member(WI.FIELD["rotation"], 0x10, 0x34),
56 member(WI.FIELD["scaleXY"], 0x54, 0x21),
57 member(WI.FIELD["scaleZ"], 0x58, 0x21),
58 member(WI.FIELD["flags"], 0x48, 0x15),
59 member(WI.FIELD["guid"], 0x20, 0x4F),
60 member(WI.FIELD["lodLevel"], 0x7E, 0x60),
61 member(WI.FIELD["lodDist"], 0x60, 0x21),
62 ]
63 entity_members = 0x300
64 for i, m in enumerate(members):
65 b[entity_members + 16 * i:entity_members + 16 * (i + 1)] = m
66 b[0x100:0x120] = struct_def(WI.ENTITY, 0x90, members, 0x100, entity_members)
67 struct.pack_into("<IIQ", b, 0x200, WI.ENTITY, 0x90, ptr(0x400))
68
69 e = 0x400
70 struct.pack_into("<4f", b, e + 0x10, 0.0, 0.0, 0.0, 1.0)
71 struct.pack_into("<Q", b, e + 0x20, 0x1122334455667788)
72 struct.pack_into("<3f", b, e + 0x38, 1.5, 2.5, 3.5)
73 struct.pack_into("<I", b, e + 0x44, 0xDEADBEEF)
74 struct.pack_into("<I", b, e + 0x48, 5)
75 struct.pack_into("<2f", b, e + 0x54, 1.0, 1.0)
76 struct.pack_into("<f", b, e + 0x60, 250.0)
77 b[e + 0x7E] = 1
78
79 if map_file:
80 mm = [
81 member(WI.FIELD["name"], 0x08, 0x4A),
82 member(WI.FIELD["parent"], 0x68, 0x4A),
83 member(WI.FIELD["streamingExtentsMin"], 0x70, 0x32),
84 member(WI.FIELD["streamingExtentsMax"], 0x7C, 0x32),
85 member(WI.FIELD["flags_map"], 0x88, 0x15),
86 member(WI.FIELD["contentFlags"], 0x8C, 0x15),
87 ]
88 map_members = 0x3A0
89 for i, m in enumerate(mm):
90 b[map_members + 16 * i:map_members + 16 * (i + 1)] = m
91 b[0x120:0x140] = struct_def(WI.MAPDATA, 0x120, mm, 0x120, map_members)
92 struct.pack_into("<IIQ", b, 0x210, WI.MAPDATA, 0x120, ptr(0x500))
93 root = 0x500
94 struct.pack_into("<I", b, root + 0x08, 0x11223344)
95 struct.pack_into("<I", b, root + 0x68, 0xAABBCCDD)
96 struct.pack_into("<3f", b, root + 0x70, -10.0, -20.0, -30.0)
97 struct.pack_into("<3f", b, root + 0x7C, 10.0, 20.0, 30.0)
98 struct.pack_into("<I", b, root + 0x88, 2)
99 struct.pack_into("<I", b, root + 0x8C, 65)
100 return bytes(b)
101
102
103def make_rpf_streams(parts, start=0x40):
104 """A minimal RPF9-looking file: header word + compressed parts, 16-byte aligned."""
105 out = bytearray(start)
106 out[:4] = b"9FPR"
107 struct.pack_into("<I", out, 4, start)
108 for part in parts:
109 pos = (len(out) + 15) & ~15
110 out.extend(b"\0" * (pos - len(out)))
111 out.extend(zlib.compress(part))
112 return bytes(out)
113
114
115class CensusTest(unittest.TestCase):
116 def setUp(self):
117 self.tmp = tempfile.TemporaryDirectory()
118 self.dir = self.tmp.name
119
120 def tearDown(self):
121 self.tmp.cleanup()
122
123 def test_inflate_keeps_a_map_header(self):
124 resource = make_resource()
125 blob = zlib.compress(resource)
126 data, used, eof, is_meta, inflated, truncated = WC.inflate(blob, 0, len(blob), keep=True)
127 self.assertEqual(data, resource)
128 self.assertEqual(used, len(blob))
129 self.assertTrue(eof)
130 self.assertTrue(is_meta)
131 self.assertEqual(inflated, len(resource))
132 self.assertFalse(truncated)
133
134 def test_assemble_joins_a_split_resource(self):
135 resource = make_resource()
136 blob = make_rpf_streams([resource[:0x150], resource[0x150:]])
137 res = WC.assemble(blob, 0x40, len(blob))
138 self.assertIsNotNone(res)
139 self.assertEqual(res["data"], resource)
140 self.assertTrue(res["joined"])
141 self.assertTrue(res["complete"])
142 self.assertEqual(res["streams"], 2)
143
144 def test_shard_and_summary_count_one_map(self):
145 resource = make_resource()
146 archive = os.path.join(self.dir, "sample.rpf")
147 with open(archive, "wb") as f:
148 f.write(make_rpf_streams([resource]))
149 with open(archive, "rb") as f:
150 data_start = struct.unpack_from("<I", f.read(8), 4)[0]
151 size = os.path.getsize(archive)
152 out = os.path.join(self.dir, "census")
153 os.makedirs(out)
154 result = WC.scan_shard((archive, 0, data_start, size, out, data_start))
155 self.assertEqual((result["maps"], result["entities"]), (1, 1))
156 summary = WC.summarize(archive, out, data_start, size, size - data_start, data_start)
157 self.assertTrue(summary["complete"])
158 self.assertTrue(summary["maps_exact"])
159 self.assertTrue(summary["entities_exact"])
160 self.assertEqual((summary["maps"], summary["entities"]), (1, 1))
161 self.assertEqual(summary["totals"]["entity_unresolved"], 0)
162 self.assertEqual(summary["coverage"]["raw_maps"], 0)
163 self.assertEqual(summary["coverage"]["missed_zlib_meta"], 0)
164
165
166if __name__ == "__main__":
167 unittest.main(verbosity=2)