diff_tests.rs 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299
  1. //! Differential tests: HLSL compiled by the console's shader compiler and
  2. //! translated, against the same HLSL compiled for PC, both drawn (or
  3. //! dispatched) on the host GPU with the same inputs.
  4. //!
  5. //! Needs `VICTORY_CONSOLE_DXC` (the console SDK's `dxc.exe`) and a PC
  6. //! `dxc.exe` (`VICTORY_PC_DXC`, else the newest Windows SDK's); skipped
  7. //! without them. Set `VICTORY_WARP=1` to draw on WARP.
  8. use std::path::{Path, PathBuf};
  9. use windows::Win32::Graphics::Direct3D12::*;
  10. use windows::Win32::Graphics::Dxgi::Common::*;
  11. use super::host::{Draw, Host, Root};
  12. use super::{HostShader, RootType, translate};
  13. const RS: &str = "RootFlags(ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT), \
  14. RootConstants(num32BitConstants=4, b0), \
  15. DescriptorTable(SRV(t0)), DescriptorTable(Sampler(s0)), \
  16. StaticSampler(s1, filter=FILTER_MIN_MAG_MIP_POINT, \
  17. addressU=TEXTURE_ADDRESS_WRAP, addressV=TEXTURE_ADDRESS_MIRROR), \
  18. StaticSampler(s2, filter=FILTER_MIN_MAG_LINEAR_MIP_POINT, \
  19. addressU=TEXTURE_ADDRESS_BORDER, addressV=TEXTURE_ADDRESS_CLAMP, \
  20. borderColor=STATIC_BORDER_COLOR_OPAQUE_WHITE, mipLODBias=0.5)";
  21. const COMMON: &str = r#"
  22. cbuffer K : register(b0) { float4 k; };
  23. Texture2D tex : register(t0);
  24. SamplerState smp : register(s0);
  25. struct V { float4 pos : SV_Position; float2 uv : TEXCOORD0; float4 col : COLOR0; };
  26. [RootSignature(RS)]
  27. V vs(float4 p : POSITION, float2 uv : TEXCOORD0) {
  28. V o;
  29. o.pos = p;
  30. o.uv = uv;
  31. o.col = float4(uv * k.xy, p.x * k.z, 1);
  32. return o;
  33. }
  34. "#;
  35. /// Pixel shaders, each `ps`.
  36. const CASES: &[(&str, &str)] = &[
  37. (
  38. "constant",
  39. "[RootSignature(RS)] float4 ps(V i) : SV_Target { return float4(0.25, 0.5, 1, 0.75); }",
  40. ),
  41. (
  42. "interpolated",
  43. "[RootSignature(RS)] float4 ps(V i) : SV_Target { return i.col * 2 - float4(i.uv, 0, 0); }",
  44. ),
  45. (
  46. "sample and branch",
  47. r#"[RootSignature(RS)] float4 ps(V i) : SV_Target {
  48. float4 t = tex.Sample(smp, i.uv);
  49. float4 r = t * i.col + k.w;
  50. if (i.uv.x > 0.5) r.xy = sin(r.yx * 3.0);
  51. else r.z = rcp(r.z + 2.0);
  52. return r;
  53. }"#,
  54. ),
  55. // A wave-wide range scalarises a per-pixel loop (as the title's light
  56. // lists do): the console's 64-lane sections become host wave operations;
  57. // the result is the same for any wave the pixel lands in.
  58. (
  59. "wave range",
  60. r#"[RootSignature(RS)] float4 ps(V i) : SV_Target {
  61. uint idx = uint(i.pos.x * 0.37 + i.pos.y * 0.21) & 15;
  62. uint lo = WaveActiveMin(idx), hi = WaveActiveMax(idx);
  63. float s = 0;
  64. for (uint n = lo; n <= hi; n++) if (n == idx) s += n * k.x;
  65. return float4(s, lo <= idx, hi >= idx, WaveActiveCountBits(true) > 0);
  66. }"#,
  67. ),
  68. (
  69. "uniform loop",
  70. r#"[RootSignature(RS)] float4 ps(V i) : SV_Target {
  71. float s = 0;
  72. for (uint n = 0; n < (asuint(k.x) & 7); n++) s += i.uv.y * n;
  73. return float4(s, 0, 0, 1);
  74. }"#,
  75. ),
  76. (
  77. "bit loop",
  78. r#"[RootSignature(RS)] float4 ps(V i) : SV_Target {
  79. uint2 p = uint2(i.pos.xy);
  80. uint s = p.y;
  81. for (uint n = 0; n < (p.x & 7); n++) s = (s ^ (s << 3)) + n;
  82. return float4(s & 255, 0, 0, 1);
  83. }"#,
  84. ),
  85. (
  86. "integer loop",
  87. r#"[RootSignature(RS)] float4 ps(V i) : SV_Target {
  88. uint2 p = uint2(i.pos.xy);
  89. uint s = 0;
  90. for (uint n = 0; n < (p.x & 7); n++) s += n;
  91. return float4(s, 0, 0, 1);
  92. }"#,
  93. ),
  94. (
  95. "loop",
  96. r#"[RootSignature(RS)] float4 ps(V i) : SV_Target {
  97. uint2 p = uint2(i.pos.xy);
  98. float s = 0;
  99. for (uint n = 0; n < (p.x & 7); n++) s += i.uv.y * n + k.x;
  100. return float4(s, 0, 0, 1);
  101. }"#,
  102. ),
  103. (
  104. "discard",
  105. r#"[RootSignature(RS)] float4 ps(V i) : SV_Target {
  106. uint2 p = uint2(i.pos.xy);
  107. if ((p.x ^ p.y) & 1) discard;
  108. return i.col;
  109. }"#,
  110. ),
  111. (
  112. "immediate samplers",
  113. r#"SamplerState point_wrap : register(s1);
  114. SamplerState linear_border : register(s2);
  115. [RootSignature(RS)] float4 ps(V i) : SV_Target {
  116. return tex.Sample(point_wrap, i.uv * 3 - 1) + 2 * tex.Sample(linear_border, i.uv * 2.5 - 0.7);
  117. }"#,
  118. ),
  119. (
  120. "loop, discard and loads",
  121. r#"[RootSignature(RS)] float4 ps(V i) : SV_Target {
  122. uint2 p = uint2(i.pos.xy);
  123. if ((p.x ^ p.y) & 1) discard;
  124. float s = 0;
  125. for (uint n = 0; n < (p.x & 7); n++) s += i.uv.y * n + k.x;
  126. float4 t = tex.Load(int3(p & 3, 0));
  127. return float4(s, frac(i.uv.x * 7.3), max(t.x, t.y) * k.y, sqrt(abs(i.col.x)) + exp2(i.uv.y));
  128. }"#,
  129. ),
  130. (
  131. "level of detail",
  132. r#"[RootSignature(RS)] float4 ps(V i) : SV_Target {
  133. return float4(tex.CalculateLevelOfDetail(smp, i.uv * 4),
  134. tex.CalculateLevelOfDetailUnclamped(smp, i.uv * 7), 0, 1);
  135. }"#,
  136. ),
  137. // 16-bit outputs and inputs (one value per dword with the 2020
  138. // compiler; the title's two per dword cannot be compiled
  139. // here) and the front face.
  140. (
  141. "16-bit varyings and front face",
  142. r#"struct V16 { float4 pos : SV_Position; half2 uv : TEXCOORD0; float4 col : COLOR0; half4 h : TEXCOORD1; };
  143. [RootSignature(RS)] V16 vs16(float4 p : POSITION, float2 uv : TEXCOORD0) {
  144. V16 o;
  145. o.pos = p;
  146. o.uv = half2(uv * k.xy);
  147. o.col = float4(uv, p.x * k.z, 1);
  148. o.h = half4(uv.yx * 3 - 1, k.w, p.y);
  149. return o;
  150. }
  151. [RootSignature(RS)] float4 ps(V16 i, bool f : SV_IsFrontFace) : SV_Target {
  152. float4 c = i.col * float4(i.uv, i.h.xy) + float4(i.h.zw, 0, 0);
  153. return f ? c : -c;
  154. }"#,
  155. ),
  156. ];
  157. const CS_RS: &str = "RootConstants(num32BitConstants=4, b0), \
  158. DescriptorTable(SRV(t0, numDescriptors=4)), DescriptorTable(Sampler(s0)), \
  159. DescriptorTable(UAV(u0, numDescriptors=4)), CBV(b1), SRV(t4), \
  160. DescriptorTable(SRV(t0, space=2, numDescriptors=9)), \
  161. \
  162. StaticSampler(s3, filter=FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT, \
  163. comparisonFunc=COMPARISON_LESS_EQUAL, \
  164. addressU=TEXTURE_ADDRESS_CLAMP, addressV=TEXTURE_ADDRESS_CLAMP)";
  165. const CS_COMMON: &str = r#"
  166. cbuffer K : register(b0) { float4 k; };
  167. Texture2D tex : register(t0);
  168. Buffer<float4> typed : register(t1);
  169. struct S { float a; uint b; float2 c; };
  170. StructuredBuffer<S> structured : register(t2);
  171. ByteAddressBuffer raw : register(t3);
  172. SamplerState smp : register(s0);
  173. SamplerComparisonState cmp : register(s3);
  174. RWByteAddressBuffer outb : register(u0);
  175. RWTexture2D<float4> outt : register(u1);
  176. cbuffer R : register(b1) { float4 table[16]; };
  177. ByteAddressBuffer rootraw : register(t4);
  178. // `raw`'s bytes in typed views (the formats the console's typed loads name).
  179. Buffer<float4> unorm8x4 : register(t0, space2);
  180. Buffer<float4> snorm16x2 : register(t1, space2);
  181. Buffer<uint4> uint8x4 : register(t2, space2);
  182. Buffer<float4> unorm10x3_2 : register(t3, space2);
  183. Buffer<uint4> uint16x4 : register(t4, space2);
  184. Buffer<float> unorm8 : register(t5, space2);
  185. Buffer<float> half16 : register(t6, space2);
  186. Buffer<float4> snorm8x4 : register(t7, space2);
  187. RWTexture2D<uint> ut : register(u2);
  188. TextureCube cubet : register(t8, space2);
  189. #define FMT(numeric, data) ((numeric) << 4 | (data))
  190. #define CS [RootSignature(RS)] [numthreads(8, 8, 1)] \
  191. void cs(uint3 g : SV_GroupID, uint3 t : SV_GroupThreadID, \
  192. uint3 d : SV_DispatchThreadID, uint i : SV_GroupIndex)
  193. "#;
  194. /// Compute shaders, each `cs`, dispatched as 2×2 groups of 8×8 threads
  195. /// over a 16×16 texture and a 256-dword buffer.
  196. const CS_CASES: &[(&str, &str)] = &[
  197. (
  198. "ids and stores",
  199. r#"CS {
  200. outb.Store(4 * (d.y * 16 + d.x), asuint(d.x * k.x + d.y));
  201. outt[d.xy] = float4(g.x, g.y, t.x, t.y + i);
  202. }"#,
  203. ),
  204. (
  205. "shared memory and barrier",
  206. r#"groupshared float lds[64];
  207. groupshared uint cnt;
  208. CS {
  209. if (i == 0) cnt = 0;
  210. lds[i] = d.x * k.x + d.y;
  211. GroupMemoryBarrierWithGroupSync();
  212. InterlockedAdd(cnt, i);
  213. float v = lds[63 - i] + lds[(i + 9) & 63];
  214. GroupMemoryBarrierWithGroupSync();
  215. outb.Store(4 * (d.y * 16 + d.x), asuint(v));
  216. outt[d.xy] = float4(v, cnt, 0, 1);
  217. }"#,
  218. ),
  219. (
  220. "sample and divergent store",
  221. r#"CS {
  222. float4 s = tex.SampleLevel(smp, (d.xy + 0.5) / 16.0, 0);
  223. if ((d.x ^ d.y) & 1) outt[d.xy] = s * k.y;
  224. else outb.Store(4 * (d.y * 16 + d.x), asuint(s.x + s.w));
  225. }"#,
  226. ),
  227. (
  228. "buffers and root views",
  229. r#"CS {
  230. float4 a = typed[i & 15];
  231. S s = structured[(i * 3) & 7];
  232. uint r = raw.Load(4 * (i & 31));
  233. float4 c = table[d.x & 15];
  234. uint q = rootraw.Load(4 * ((i + 5) & 31));
  235. outb.Store(4 * (d.y * 16 + d.x), asuint(a.x + a.w * s.a) ^ s.b ^ r ^ q);
  236. outt[d.xy] = c + float4(s.c, a.yz);
  237. }"#,
  238. ),
  239. // (The 2020 compiler branches around every narrowed region, so these
  240. // become branches, not guards.)
  241. (
  242. "conditional memory access",
  243. r#"CS {
  244. float v = d.x * k.x + d.y;
  245. if (i & 1) v = v * 3 + 1;
  246. if (i & 4) v += tex.Load(int3(d.xy & 3, 0)).y;
  247. if (i & 2) outb.Store(4 * (d.y * 16 + d.x), asuint(v));
  248. if (i & 8) outt[d.xy] = float4(v, 0, 0, 1);
  249. }"#,
  250. ),
  251. // Each side of a per-group branch leaves a compare in VCC; the select
  252. // after the join reads the joined mask (as `postfx_splines` does).
  253. (
  254. "select on joined compares",
  255. r#"CS {
  256. float v = d.x * k.x + d.y;
  257. float r;
  258. bool ok;
  259. [branch] if ((g.x ^ g.y) & 1) {
  260. r = sqrt(v) * k.z + sin(v * k.w);
  261. ok = r < 5;
  262. } else {
  263. r = v * k.y + 1;
  264. ok = r > -4;
  265. }
  266. float o = ok ? r : -1;
  267. outb.Store(4 * (d.y * 16 + d.x), asuint(o));
  268. outt[d.xy] = float4(o, r, v, 1);
  269. }"#,
  270. ),
  271. // One host wave of 32 lanes holds the group, as the console's wave of 64
  272. // does, so lane numbers agree with the PC compile.
  273. (
  274. "lane reads",
  275. r#"[RootSignature(RS)] [numthreads(8, 4, 1)]
  276. void cs(uint3 d : SV_DispatchThreadID) {
  277. float v = d.x * k.x + d.y;
  278. float w = WaveReadLaneAt(v, 5);
  279. uint lane = WaveGetLaneIndex();
  280. uint q = QuadReadAcrossX(lane * 10) + QuadReadAcrossDiagonal(lane);
  281. outb.Store(4 * (d.y * 16 + d.x), q);
  282. outt[d.xy] = float4(v, w, QuadReadAcrossY(v), lane);
  283. }"#,
  284. ),
  285. // Bytes and halves: SDWA operand and result selection, byte permutes,
  286. // f16 conversions.
  287. (
  288. "sub-dword operations",
  289. r#"CS {
  290. uint n = d.y * 16 + d.x;
  291. uint x = raw.Load(4 * (n & 31)), y = raw.Load(4 * ((n * 7) & 31));
  292. float a = float(x >> 16) + float((y >> 8) & 255) * k.x;
  293. float b = f16tof32(x >> 16) + f16tof32(y);
  294. uint p = (x & 0xff) | ((y & 0xff) << 8) | (x & 0xff0000) | ((y >> 8) << 24);
  295. uint q = f32tof16(a) | (f32tof16(b) << 16);
  296. int s = int(x << 24) >> 24;
  297. uint u = (x & 0xffff) + (y >> 16) + ((x >> 24) ^ (y & 0xffff)) + asuint(k.w) * 1000 + 77;
  298. outb.Store4(16 * n, uint4(asuint(a), asuint(b) ^ p, q, asuint(float(s)) + u));
  299. }"#,
  300. ),
  301. // 64-bit additions (VALU carries as lane masks) and explicit gradients.
  302. (
  303. "carries and gradients",
  304. r#"CS {
  305. uint n = d.y * 16 + d.x;
  306. uint64_t a = (uint64_t(raw.Load(4 * (n & 31))) << 32) | raw.Load(4 * ((n * 3) & 31));
  307. uint64_t b = (uint64_t(raw.Load(4 * ((n * 5) & 31))) << 32) | raw.Load(4 * ((n * 7) & 31));
  308. uint64_t s = a + b, u = a - b;
  309. float4 gr = tex.SampleGrad(smp, (d.xy + 0.5) / 16.0, float2(k.x, 0) * 0.1, float2(0, k.z) * 0.1);
  310. outb.Store4(16 * n, uint4(uint(s), uint(s >> 32) ^ uint(u), uint(u >> 32), asuint(gr.x + gr.y * 3)));
  311. }"#,
  312. ),
  313. // Comparison sampling at level 0 with an immediate comparison sampler.
  314. (
  315. "comparison sampling",
  316. r#"CS {
  317. float r = tex.SampleCmpLevelZero(cmp, (d.xy + 0.25) / 15.0, k.x * d.x / 16.0);
  318. outb.Store(4 * (d.y * 16 + d.x), asuint(r));
  319. }"#,
  320. ),
  321. // 16-bit texture results, two channels per register (`d16`).
  322. (
  323. "16-bit texture reads",
  324. r#"Texture2D<half4> htex : register(t0);
  325. CS {
  326. half4 a = htex.SampleLevel(smp, (d.xy + 0.5) / 16.0, 0);
  327. half3 b = htex.Load(int3(d.xy & 3, 0)).xyz;
  328. outb.Store4(16 * (d.y * 16 + d.x), uint4(asuint(float(a.x) + a.w),
  329. asuint(float(a.y) * a.z), asuint(float(b.x)), asuint(float(b.y) - b.z)));
  330. }"#,
  331. ),
  332. // Sizes: the console compiler computes them from descriptor bits
  333. // (width, height, levels, record counts).
  334. (
  335. "sizes from descriptors",
  336. r#"CS {
  337. uint w, h, l, n, b, ns, st;
  338. tex.GetDimensions(0, w, h, l);
  339. typed.GetDimensions(n);
  340. raw.GetDimensions(b);
  341. structured.GetDimensions(ns, st);
  342. // Read too: the translation takes the views' kinds from those reads.
  343. float r = tex.Load(int3(d.xy & 3, 0)).x + typed[i & 15].y + structured[i & 7].a;
  344. outb.Store4(16 * (d.y * 16 + d.x),
  345. uint4(w * 7 + h, l + asuint(r), n * 5 + ns * 3 + st, b + raw.Load(4 * (i & 31))));
  346. }"#,
  347. ),
  348. // Typed loads (`tbuffer_load_format_*`, the title's vertex
  349. // fetch) convert by the format the instruction names: the PC reads the
  350. // same bytes through typed views in those formats. Channels past the
  351. // format's read (0, 0, 0, 1); a byte format at unaligned offsets.
  352. (
  353. "typed loads",
  354. r#"CS {
  355. uint n = d.y * 16 + d.x, e = n & 31, f = n >> 5;
  356. uint4 a, b, c, dd, ee, ff, gg, hh;
  357. #ifdef CONSOLE
  358. a = raw.XB_TypedLoad4(4 * e, FMT(0, 10));
  359. b = raw.XB_TypedLoad4(4 * e, FMT(1, 5));
  360. c = raw.XB_TypedLoad4(4 * e, FMT(4, 10));
  361. dd = raw.XB_TypedLoad4(4 * e, FMT(0, 9));
  362. ee = raw.XB_TypedLoad4(8 * (e & 15), FMT(4, 12));
  363. ff = uint4(raw.XB_TypedLoad((3 * e) & 127, FMT(0, 1)), 0, 0, 0);
  364. gg = uint4(raw.XB_TypedLoad2(2 * e, FMT(7, 2)), 0, 0);
  365. hh = raw.XB_TypedLoad4(4 * e, FMT(1, 10));
  366. #else
  367. a = asuint(unorm8x4[e]);
  368. b = asuint(snorm16x2[e]);
  369. c = uint8x4[e];
  370. dd = asuint(unorm10x3_2[e]);
  371. ee = uint16x4[e & 15];
  372. ff = uint4(asuint(unorm8[(3 * e) & 127]), 0, 0, 0);
  373. gg = uint4(asuint(half16[e]), 0, 0, 0);
  374. hh = asuint(snorm8x4[e]);
  375. #endif
  376. uint4 v = f == 0 ? a : f == 1 ? b : f == 2 ? c : f == 3 ? dd
  377. : f == 4 ? ee : f == 5 ? ff : f == 6 ? gg : hh;
  378. outb.Store4(16 * n, v);
  379. }"#,
  380. ),
  381. // Wave operations: the console expands them into whole-wave sections
  382. // (DPP, `v_permlanex16`, lane reads) and lane masks read as numbers
  383. // (`s_bcnt1`, `s_ff1`, `v_mbcnt`). 32 threads: one wave on the console
  384. // (lanes 32-63 inactive) and on the host; the branch leaves lanes out.
  385. (
  386. "wave operations",
  387. r#"[RootSignature(RS)] [numthreads(8, 4, 1)]
  388. void cs(uint3 d : SV_DispatchThreadID, uint i : SV_GroupIndex) {
  389. uint n = d.y * 16 + d.x;
  390. float v = d.x * k.x + d.y;
  391. uint u = raw.Load(4 * (i & 31));
  392. uint4 o = 0;
  393. if (u & 3) {
  394. o.x = WaveActiveSum(u >> 8) + WaveActiveCountBits((u & 4) != 0);
  395. o.y = asuint(WaveActiveMax(v)) ^ WaveActiveMin(u) ^ WaveActiveBitOr(u)
  396. ^ WaveActiveBitAnd(u | 1) ^ asuint(WaveActiveMin(v)) ^ WaveActiveMax(int(u));
  397. o.z = WavePrefixSum(u & 255) + WavePrefixCountBits(v > 2) * 1000;
  398. // (The PC compile evaluates a wave operation in a `?:` arm
  399. // in that arm's lanes only, so it stays outside.)
  400. o.w = asuint(WaveActiveSum(v)) + (WaveIsFirstLane() ? WaveReadLaneFirst(u) : 0);
  401. }
  402. outb.Store4(16 * n, o);
  403. }"#,
  404. ),
  405. // Atomics the console aggregates per wave (one add of the lane count,
  406. // each lane's offset from `v_mbcnt`), and texture atomics. Results
  407. // that depend on the lanes' order are left out.
  408. (
  409. "aggregated and texture atomics",
  410. r#"CS {
  411. uint u = raw.Load(4 * (i & 31)), r, q;
  412. outb.InterlockedAdd(0, 1, r);
  413. outb.InterlockedAdd(4 * (1 + r % 8), 1);
  414. if (u & 1) outb.InterlockedAdd(64, u & 255);
  415. uint2 p = d.xy & 3;
  416. InterlockedMax(ut[p], u);
  417. InterlockedOr(ut[p + uint2(4, 0)], u >> (i & 7));
  418. InterlockedMin(ut[p + uint2(8, 0)], u);
  419. InterlockedAdd(ut[p + uint2(12, 0)], u & 15, q);
  420. InterlockedXor(ut[p + uint2(0, 4)], u);
  421. }"#,
  422. ),
  423. // A loop whose count comes from a view that reads zeros (as a null or
  424. // not yet mirrored one does) runs four billion times on the console;
  425. // the translation leaves it after `LOOP_LIMIT` iterations. Run on WARP
  426. // only (`VICTORY_WARP=1`), ours only: without the limit it would hang
  427. // the GPU.
  428. (
  429. "terminates on zero data",
  430. r#"CS {
  431. uint cnt = outb.Load(4 * 1000), s = d.x;
  432. for (uint j = 0; j != cnt - 1; j++) s = s * 3 + raw.Load(4 * (j & 31));
  433. outb.Store(4 * (d.y * 16 + d.x), s);
  434. }"#,
  435. ),
  436. // Cube sampling: the console computes face coordinates (`v_cube*`)
  437. // and samples the face; the host samples the direction rebuilt from
  438. // them. Every face and texel: a major axis of ±2 and the others at
  439. // texel centres, so both sides compute them exactly.
  440. (
  441. "cube sampling",
  442. r#"CS {
  443. float sg = (i & 8) ? -2 : 2;
  444. float a = (d.x & 3) - 1.5, b = (d.y & 3) - 1.5;
  445. uint ax = i % 3;
  446. float3 dir = ax == 0 ? float3(sg, a, b) : ax == 1 ? float3(a, sg, b) : float3(a, b, sg);
  447. float4 p = cubet.SampleLevel(smp, dir, 0);
  448. float4 q = cubet.SampleLevel(smp, -dir.zxy, 0);
  449. outb.Store4(16 * (d.y * 16 + d.x), asuint(p + q * 3));
  450. }"#,
  451. ),
  452. // A local array indexed per lane (M0-relative VGPR moves), bit fields
  453. // and first bits from the top.
  454. (
  455. "indexed registers and bit fields",
  456. r#"CS {
  457. uint n = d.y * 16 + d.x;
  458. uint x = raw.Load(4 * (n & 31)), y = raw.Load(4 * ((n * 5) & 31));
  459. uint arr[24];
  460. [unroll] for (uint j = 0; j < 24; j++) arr[j] = x ^ (j * 0x01010101);
  461. [loop] for (uint m = 0; m < (y & 3); m++) arr[(y >> (m * 5)) % 24] = y + m;
  462. uint v = arr[(x >> 3) % 24];
  463. uint w = asuint(k.x) & 31, o = n & 15;
  464. uint bf = (x & ((1u << w) - 1)) << o;
  465. uint fb = firstbithigh(asuint(k.y)) + firstbithigh(x) * 3 + firstbithigh(int(y)) * 7;
  466. outb.Store4(16 * n, uint4(v, bf, fb, arr[n % 24]));
  467. }"#,
  468. ),
  469. // Size queries at a level known per lane (`image_get_resinfo`).
  470. (
  471. "size queries",
  472. r#"CS {
  473. uint w, h, l, cw, ch, cl;
  474. tex.GetDimensions(d.x >> 4, w, h, l);
  475. cubet.GetDimensions(d.y >> 4, cw, ch, cl);
  476. float r = tex.Load(int3(d.xy & 3, 0)).x;
  477. outb.Store4(16 * (d.y * 16 + d.x), uint4(w * 7 + h, l + asuint(r), cw * 3 + ch, cl));
  478. }"#,
  479. ),
  480. // Gathers with offsets computed per lane (programmable offsets).
  481. (
  482. "gather with offsets",
  483. r#"CS {
  484. int2 o = int2(int(d.x & 7) - 4, int(d.y % 5) - 2);
  485. float4 r = tex.GatherRed(smp, (d.xy + 0.5) / 16.0, o);
  486. float4 q = tex.GatherGreen(smp, (d.yx + 0.25) / 16.0, -o);
  487. outb.Store4(16 * (d.y * 16 + d.x), asuint(r + q * 3));
  488. }"#,
  489. ),
  490. // Constant arrays: the console compiler appends them to the code and
  491. // reads them through `s_getpc_b64` (scalar loads for a uniform index,
  492. // global loads per lane, 16-bit ones too).
  493. (
  494. "constant tables",
  495. r#"static const uint tbl[16] = { 3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9, 3 };
  496. static const float ftbl[8] = { 0.5, -1, 2.25, 3, -4.5, 6, 7.75, -8 };
  497. // (16-bit types: compiled with half precision enabled.)
  498. static const uint16_t stbl[12] = { 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 1100, 65535 };
  499. CS {
  500. uint n = d.y * 16 + d.x;
  501. uint u = asuint(k.x) & 15;
  502. uint a = tbl[i & 15] ^ tbl[u] << 8;
  503. float f = ftbl[(i * 3) & 7] * ftbl[u & 7];
  504. uint h = stbl[(n * 5) % 12] + stbl[u % 12];
  505. outb.Store4(16 * n, uint4(a, asuint(f), h, tbl[(n + u) & 15]));
  506. }"#,
  507. ),
  508. // 16-bit arithmetic (scalar and packed), 16-bit compares, typed stores
  509. // of halves (`buffer_store_format_d16`), 64-bit shifts and compares.
  510. (
  511. "16-bit and 64-bit arithmetic",
  512. r#"RWBuffer<half4> hb : register(u3);
  513. CS {
  514. uint n = d.y * 16 + d.x;
  515. uint x = raw.Load(4 * (n & 31)), y = raw.Load(4 * ((n * 7) & 31));
  516. half a = half(d.x * k.x - 2), b = half(d.y + k.y), c = half(k.z);
  517. half2 p = half2(a, b) * half2(b, c) + half2(c, a);
  518. half m = max(a, b) - min(a, c) * a;
  519. bool lt = a < b, ge = p.x >= p.y;
  520. hb[n] = half4(p.x, m, lt ? a : b, ge ? p.y : a - b);
  521. uint64_t q = (uint64_t(x) << (n & 31)) | y, w = uint64_t(y) << 3;
  522. uint z = q < w ? 1 : q == w ? 2 : 3;
  523. outb.Store2(8 * n, uint2(uint(q >> 7) ^ z, uint(w >> (n & 15))));
  524. }"#,
  525. ),
  526. ];
  527. const MS_COMMON: &str = r#"
  528. #define RS "RootConstants(num32BitConstants=4, b0)"
  529. cbuffer K : register(b0) { float4 k; };
  530. struct V { float4 pos : SV_Position; float4 col : COLOR0; float2 uv : TEXCOORD0; };
  531. [RootSignature(RS)] float4 mps(V i) : SV_Target { return i.col + float4(i.uv, 0, 0); }
  532. #define MS_ATTR [RootSignature(RS)] [outputtopology("triangle")]
  533. "#;
  534. /// Mesh shaders, each `ms` (the console runs one thread per output lane, so
  535. /// groups of 32 run as 64 lanes there), with their group counts. Drawn
  536. /// with `mps` into 16×16 targets. The 2020 compiler's containers do not
  537. /// record the thread count, so cases reading the group id keep
  538. /// max(threads, vertices, primitives) at the lane count (see `emit`).
  539. const MS_CASES: &[(&str, u32, &str)] = &[
  540. (
  541. "one triangle",
  542. 1,
  543. r#"MS_ATTR [numthreads(32, 1, 1)]
  544. void ms(uint i : SV_GroupIndex, out vertices V verts[3], out indices uint3 tris[1]) {
  545. SetMeshOutputCounts(3, 1);
  546. if (i < 3) {
  547. verts[i].pos = float4(i == 1 ? 3 : -1, i == 2 ? 3 : -1, 0.5, 1);
  548. verts[i].col = float4(k.x * i, k.y, k.z * (i == 2), 1);
  549. verts[i].uv = float2(i * 0.5, k.w);
  550. }
  551. if (i == 0) tris[0] = uint3(0, 1, 2);
  552. }"#,
  553. ),
  554. // A quad per group in its quadrant; a run-time vertex count, and a
  555. // primitive count per group whose third triangle is culled.
  556. (
  557. "groups, counts and culling",
  558. 4,
  559. r#"struct P { bool cull : SV_CullPrimitive; };
  560. MS_ATTR [numthreads(64, 1, 1)]
  561. void ms(uint i : SV_GroupIndex, uint3 g : SV_GroupID, out vertices V verts[8],
  562. out indices uint3 tris[4], out primitives P prims[4]) {
  563. uint nv = 4 + (k.z > 1);
  564. uint np = 2 + (g.x & 1);
  565. SetMeshOutputCounts(nv, np);
  566. float2 o = float2(g.x & 1, g.x >> 1) - 1;
  567. if (i < nv) {
  568. float2 p = i < 4 ? float2(i & 1, i >> 1) : float2(-0.75, 0.5);
  569. verts[i].pos = float4(o + p, 0.5, 1);
  570. verts[i].col = float4(k.x * i, g.x * 0.25, k.z, 1);
  571. verts[i].uv = float2(i, g.x);
  572. }
  573. if (i < np) {
  574. tris[i] = i == 0 ? uint3(0, 1, 2) : i == 1 ? uint3(1, 3, 2) : uint3(1, 4, 3);
  575. prims[i].cull = i == 2;
  576. }
  577. }"#,
  578. ),
  579. // Two waves per group, as the title's mesh programs run: the
  580. // second wave's lanes are threads 64-127.
  581. (
  582. "two waves",
  583. 1,
  584. r#"MS_ATTR [numthreads(128, 1, 1)]
  585. void ms(uint i : SV_GroupIndex, out vertices V verts[81], out indices uint3 tris[128]) {
  586. SetMeshOutputCounts(81, 128);
  587. if (i < 81) {
  588. float2 p = float2(i % 9, i / 9) / 8.0;
  589. verts[i].pos = float4(p * 2 - 1, 0.5, 1);
  590. verts[i].col = float4(p.x * k.x, p.y, (i & 7) * 0.125, 1);
  591. verts[i].uv = float2(i, k.y);
  592. }
  593. uint c = i / 2 % 8 + i / 16 * 9;
  594. tris[i] = i & 1 ? uint3(c + 1, c + 10, c + 9) : uint3(c, c + 1, c + 9);
  595. }"#,
  596. ),
  597. // Quad reads (DPP quad permutations on the console; the title's
  598. // tessellating mesh programs swizzle within quads too).
  599. (
  600. "quad reads",
  601. 1,
  602. r#"MS_ATTR [numthreads(128, 1, 1)]
  603. void ms(uint i : SV_GroupIndex, out vertices V verts[81], out indices uint3 tris[128]) {
  604. SetMeshOutputCounts(81, 128);
  605. float w = i * k.x + k.y;
  606. float a = QuadReadLaneAt(w, 0);
  607. float b = QuadReadLaneAt(w, 2);
  608. float c = QuadReadAcrossX(w);
  609. if (i < 81) {
  610. float2 p = float2(i % 9, i / 9) / 8.0;
  611. verts[i].pos = float4(p * 2 - 1, 0.5, 1);
  612. verts[i].col = float4(a, b, c, 1);
  613. verts[i].uv = float2(i, k.y);
  614. }
  615. uint cc = i / 2 % 8 + i / 16 * 9;
  616. tris[i] = i & 1 ? uint3(cc + 1, cc + 10, cc + 9) : uint3(cc, cc + 1, cc + 9);
  617. }"#,
  618. ),
  619. // Vertices and indices written by other threads than their lanes: the
  620. // console passes them through shared memory, with a loop and barriers.
  621. (
  622. "grid through shared memory",
  623. 2,
  624. r#"MS_ATTR [numthreads(32, 1, 1)]
  625. void ms(uint i : SV_GroupIndex, uint3 g : SV_GroupID, out vertices V verts[36],
  626. out indices uint3 tris[64]) {
  627. SetMeshOutputCounts(36, 50);
  628. for (uint v = i; v < 36; v += 32) {
  629. float2 p = float2(v % 6, v / 6) / 5.0;
  630. verts[v].pos = float4(p.x - g.x, p.y * 2 - 1, 0.5, 1);
  631. verts[v].col = float4(p * k.x, k.z * g.x, 1);
  632. verts[v].uv = float2(v, k.y);
  633. }
  634. if (i < 25) {
  635. uint c = i % 5 + i / 5 * 6;
  636. tris[2 * i] = uint3(c, c + 1, c + 6);
  637. tris[2 * i + 1] = uint3(c + 1, c + 7, c + 6);
  638. }
  639. }"#,
  640. ),
  641. ];
  642. fn tools() -> Option<(PathBuf, PathBuf)> {
  643. let console = PathBuf::from(std::env::var_os("VICTORY_CONSOLE_DXC")?);
  644. let pc = match std::env::var_os("VICTORY_PC_DXC") {
  645. Some(p) => PathBuf::from(p),
  646. None => super::validator::Validator::default_path()?.with_file_name("dxc.exe"),
  647. };
  648. (console.exists() && pc.exists()).then_some((console, pc))
  649. }
  650. fn compile(dxc: &Path, dir: &Path, src: &str, entry: &str, profile: &str) -> Vec<u8> {
  651. let input = dir.join("t.hlsl");
  652. let output = dir.join(format!("{entry}.bin"));
  653. let text = if entry == "cs" {
  654. format!("#define RS \"{CS_RS}\"\n{CS_COMMON}\n{src}\n")
  655. } else if entry.starts_with('m') {
  656. format!("{MS_COMMON}\n{src}\n")
  657. } else {
  658. format!("#define RS \"{RS}\"\n{COMMON}\n{src}\n")
  659. };
  660. std::fs::write(&input, text).unwrap();
  661. let out = std::process::Command::new(dxc)
  662. .args(["-T", profile, "-E", entry, "-Fo"])
  663. .arg(&output)
  664. .arg(&input)
  665. .args(src.contains("half").then_some("-enable-16bit-types"))
  666. // `CONSOLE` marks the console compile (cases spell console-only
  667. // intrinsics there).
  668. .args(
  669. std::env::var_os("VICTORY_CONSOLE_DXC")
  670. .is_some_and(|c| Path::new(&c) == dxc)
  671. .then_some("-DCONSOLE"),
  672. )
  673. .output()
  674. .unwrap();
  675. assert!(
  676. out.status.success(),
  677. "{}",
  678. String::from_utf8_lossy(&out.stderr)
  679. );
  680. std::fs::read(output).unwrap()
  681. }
  682. /// Root arguments for a translated stage: user data from the root values.
  683. fn user_data(s: &HostShader, k: &[u32; 4]) -> Vec<u32> {
  684. let mut data = vec![0; (s.user_data_dwords() as usize).max(1)];
  685. for u in &s.user_data {
  686. data[u.index as usize] = match (u.root, u.slot) {
  687. (RootType::Constants, 0) => k[u.dword as usize],
  688. // The texture and sampler tables start at heap index 1, the UAV
  689. // table (compute) at 5, in the console's units.
  690. (RootType::Table, 1) => 32,
  691. (RootType::Table, 2) => 16,
  692. (RootType::Table, 3) => 5 * 32,
  693. // The typed views of `raw` (compute) from 9.
  694. (RootType::Table, 6) => 9 * 32,
  695. other => panic!("unexpected user data {other:?}"),
  696. };
  697. }
  698. data
  699. }
  700. #[test]
  701. fn translated_shaders_draw_as_pc_ones() {
  702. let Some((console, pc)) = tools() else {
  703. eprintln!("no console or PC compiler; skipped");
  704. return;
  705. };
  706. let host = match Host::new(false) {
  707. Ok(host) => host,
  708. Err(e) => {
  709. eprintln!("no SM 6.6 device ({e}); skipped");
  710. return;
  711. }
  712. };
  713. let dir = std::env::temp_dir().join(format!("victory-diff-{}", std::process::id()));
  714. std::fs::create_dir_all(&dir).unwrap();
  715. let k = [0.75f32, -1.5, 2.0, 0.125].map(f32::to_bits);
  716. let texels: Vec<[f32; 4]> = (0..16)
  717. .map(|i| {
  718. [
  719. i as f32 / 16.0,
  720. (i % 4) as f32 * 0.3,
  721. 1.0 - i as f32 / 20.0,
  722. 0.5,
  723. ]
  724. })
  725. .collect();
  726. let dummy = [[9.0f32; 4]];
  727. let sampler = |filter, address| D3D12_SAMPLER_DESC {
  728. Filter: filter,
  729. AddressU: address,
  730. AddressV: address,
  731. AddressW: address,
  732. MaxAnisotropy: 1,
  733. MaxLOD: f32::MAX,
  734. ..Default::default()
  735. };
  736. let samplers = [
  737. sampler(
  738. D3D12_FILTER_MIN_MAG_MIP_POINT,
  739. D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
  740. ),
  741. sampler(
  742. D3D12_FILTER_MIN_MAG_MIP_LINEAR,
  743. D3D12_TEXTURE_ADDRESS_MODE_WRAP,
  744. ),
  745. ];
  746. // A full-screen triangle: POSITION (4 floats), TEXCOORD0 (2 floats).
  747. let vertices = [
  748. -1.0, -1.0, 0.5, 1.0, 0.0, 1.0, //
  749. -1.0, 3.0, 0.5, 1.0, 0.0, -1.0, //
  750. 3.0, -1.0, 0.5, 1.0, 2.0, 1.0,
  751. ];
  752. let textures: [(u32, u32, &[[f32; 4]]); 2] = [(1, 1, &dummy), (4, 4, &texels)];
  753. let draw = |roots| Draw {
  754. roots,
  755. textures: &textures,
  756. samplers: &samplers,
  757. vertices: &vertices,
  758. stride: 24,
  759. size: (16, 16),
  760. mesh_groups: 0,
  761. };
  762. let mut failures = Vec::new();
  763. let only = std::env::var("VICTORY_DIFF_ONLY").ok();
  764. for (name, src) in CASES
  765. .iter()
  766. .filter(|c| only.as_ref().is_none_or(|o| o == c.0))
  767. {
  768. // A case may bring its own vertex shader.
  769. let vs = if src.contains(" vs16(") { "vs16" } else { "vs" };
  770. let vs_c = translate(&compile(&console, &dir, src, vs, "vs_6_5")).unwrap();
  771. let ps_c = match translate(&compile(&console, &dir, src, "ps", "ps_6_5")) {
  772. Ok(s) => s,
  773. Err(e) => {
  774. failures.push(format!("{name}: {e}"));
  775. continue;
  776. }
  777. };
  778. if let Ok(out) = std::env::var("VICTORY_EMIT_DUMP") {
  779. let stem = name.replace([' ', ','], "_");
  780. std::fs::write(
  781. format!("{out}/{stem}.ps.cdxil"),
  782. compile(&console, &dir, src, "ps", "ps_6_5"),
  783. )
  784. .unwrap();
  785. std::fs::write(format!("{out}/{stem}.ps.dxil"), &ps_c.dxil).unwrap();
  786. }
  787. if let Ok(mut v) = super::validator::Validator::load(
  788. super::validator::Validator::default_path().as_deref(),
  789. ) {
  790. for s in [&vs_c, &ps_c] {
  791. v.validate(&mut s.dxil.clone())
  792. .unwrap_or_else(|e| panic!("{name}: {e}"));
  793. }
  794. }
  795. let (root_t, pso_t) = host.pipeline(&vs_c, &ps_c).unwrap();
  796. let ours = host
  797. .draw(
  798. &root_t,
  799. &pso_t,
  800. &draw(vec![
  801. (0, Root::Constants(user_data(&vs_c, &k))),
  802. (1, Root::Constants(user_data(&ps_c, &k))),
  803. ]),
  804. )
  805. .unwrap();
  806. let (vs_p, ps_p) = (
  807. compile(&pc, &dir, src, vs, "vs_6_5"),
  808. compile(&pc, &dir, src, "ps", "ps_6_5"),
  809. );
  810. // SAFETY: the PC container carries its root signature.
  811. let root_p: ID3D12RootSignature =
  812. unsafe { host.device.CreateRootSignature(0, &ps_p) }.unwrap();
  813. let pso_p = host.pipeline_with(&root_p, &vs_p, &ps_p).unwrap();
  814. let theirs = host
  815. .draw(
  816. &root_p,
  817. &pso_p,
  818. &draw(vec![
  819. (0, Root::Constants(k.to_vec())),
  820. (
  821. 1,
  822. Root::Table {
  823. sampler: false,
  824. index: 1,
  825. },
  826. ),
  827. (
  828. 2,
  829. Root::Table {
  830. sampler: true,
  831. index: 1,
  832. },
  833. ),
  834. ]),
  835. )
  836. .unwrap();
  837. let worst = ours
  838. .iter()
  839. .flatten()
  840. .zip(theirs.iter().flatten())
  841. .enumerate()
  842. .map(|(i, (a, b))| (((a - b).abs() / b.abs().max(1.0)), i, *a, *b))
  843. .max_by(|x, y| x.0.total_cmp(&y.0))
  844. .unwrap();
  845. eprintln!(
  846. "{name}: worst relative difference {:.2e} (at {}: {} vs {})",
  847. worst.0, worst.1, worst.2, worst.3
  848. );
  849. if worst.0.is_nan() || worst.0 > 1e-3 {
  850. failures.push(format!("{name}: {worst:?}"));
  851. }
  852. }
  853. let _ = std::fs::remove_dir_all(&dir);
  854. assert!(failures.is_empty(), "{failures:#?}");
  855. }
  856. #[test]
  857. fn translated_mesh_shaders_draw_as_pc_ones() {
  858. let Some((console, pc)) = tools() else {
  859. eprintln!("no console or PC compiler; skipped");
  860. return;
  861. };
  862. let host = match Host::new(false) {
  863. Ok(host) => host,
  864. Err(e) => {
  865. eprintln!("no SM 6.6 device ({e}); skipped");
  866. return;
  867. }
  868. };
  869. let dir = std::env::temp_dir().join(format!("victory-diff-ms-{}", std::process::id()));
  870. std::fs::create_dir_all(&dir).unwrap();
  871. let k = [0.75f32, -1.5, 2.0, 0.125].map(f32::to_bits);
  872. let draw = |roots, mesh_groups| Draw {
  873. roots,
  874. textures: &[],
  875. samplers: &[],
  876. vertices: &[],
  877. stride: 0,
  878. size: (16, 16),
  879. mesh_groups,
  880. };
  881. let mut failures = Vec::new();
  882. let only = std::env::var("VICTORY_DIFF_ONLY").ok();
  883. for &(name, groups, src) in MS_CASES
  884. .iter()
  885. .filter(|c| only.as_ref().is_none_or(|o| o == c.0))
  886. {
  887. let console_ms = compile(&console, &dir, src, "ms", "ms_6_5");
  888. let ms_c = match translate(&console_ms) {
  889. Ok(s) => s,
  890. Err(e) => {
  891. failures.push(format!("{name}: {e}"));
  892. continue;
  893. }
  894. };
  895. let ps_c = translate(&compile(&console, &dir, src, "mps", "ps_6_5")).unwrap();
  896. if let Ok(out) = std::env::var("VICTORY_EMIT_DUMP") {
  897. let stem = name.replace([' ', ','], "_");
  898. std::fs::write(format!("{out}/{stem}.ms.cdxil"), &console_ms).unwrap();
  899. std::fs::write(format!("{out}/{stem}.ms.dxil"), &ms_c.dxil).unwrap();
  900. }
  901. if let Ok(mut v) = super::validator::Validator::load(
  902. super::validator::Validator::default_path().as_deref(),
  903. ) {
  904. v.validate(&mut ms_c.dxil.clone())
  905. .unwrap_or_else(|e| panic!("{name}: {e}"));
  906. }
  907. let (root_t, pso_t) = host.mesh_pipeline(&ms_c, &ps_c).unwrap();
  908. let ours = host
  909. .draw(
  910. &root_t,
  911. &pso_t,
  912. &draw(
  913. vec![
  914. (0, Root::Constants(user_data(&ms_c, &k))),
  915. (1, Root::Constants(user_data(&ps_c, &k))),
  916. ],
  917. groups,
  918. ),
  919. )
  920. .unwrap();
  921. let (ms_p, ps_p) = (
  922. compile(&pc, &dir, src, "ms", "ms_6_5"),
  923. compile(&pc, &dir, src, "mps", "ps_6_5"),
  924. );
  925. // SAFETY: the PC container carries its root signature.
  926. let root_p: ID3D12RootSignature =
  927. unsafe { host.device.CreateRootSignature(0, &ms_p) }.unwrap();
  928. let pso_p = host.mesh_pipeline_with(&root_p, &ms_p, &ps_p).unwrap();
  929. let theirs = host
  930. .draw(
  931. &root_p,
  932. &pso_p,
  933. &draw(vec![(0, Root::Constants(k.to_vec()))], groups),
  934. )
  935. .unwrap();
  936. let worst = ours
  937. .iter()
  938. .flatten()
  939. .zip(theirs.iter().flatten())
  940. .enumerate()
  941. .map(|(i, (a, b))| (((a - b).abs() / b.abs().max(1.0)), i, *a, *b))
  942. .max_by(|x, y| x.0.total_cmp(&y.0))
  943. .unwrap();
  944. let drawn = theirs.iter().filter(|t| t[3] != 0.0).count();
  945. eprintln!(
  946. "{name}: {drawn} texels drawn; worst relative difference {:.2e} (at {}: {} vs {})",
  947. worst.0, worst.1, worst.2, worst.3
  948. );
  949. if worst.0.is_nan() || worst.0 > 1e-3 || drawn == 0 {
  950. // Which texels each drew (alpha set), row by row.
  951. for (o, t) in ours.chunks(16).zip(theirs.chunks(16)) {
  952. let row = |r: &[[f32; 4]]| -> String {
  953. r.iter()
  954. .map(|x| if x[3] != 0.0 { '#' } else { '.' })
  955. .collect()
  956. };
  957. eprintln!(" {} {}", row(o), row(t));
  958. }
  959. failures.push(format!("{name}: {worst:?}"));
  960. }
  961. }
  962. let _ = std::fs::remove_dir_all(&dir);
  963. assert!(failures.is_empty(), "{failures:#?}");
  964. }
  965. /// Where PC code and the console differ by design, the translation must
  966. /// give the console's results: float-to-int conversions saturate and give
  967. /// 0 for NaN (`v_cvt_i32/u32_f32`), the legacy multiply the compiler
  968. /// uses for `*` gives 0 for 0 × NaN, `frac` never reaches 1.0 (it gives
  969. /// the largest value below; some hosts' own `frac` gives 1.0), and sine
  970. /// and cosine take turns: the sine of a half turn and the cosine of a
  971. /// quarter turn are exactly +0 (the host's functions of the rounded angle
  972. /// give about 1e-7). The compiler takes whole turns off itself, so large
  973. /// angles cannot be tried from here.
  974. #[test]
  975. fn float_semantics_are_the_consoles() {
  976. use super::host::{Dispatch, View};
  977. let Some((console, _)) = tools() else {
  978. eprintln!("no console compiler; skipped");
  979. return;
  980. };
  981. let host = match Host::new(false) {
  982. Ok(host) => host,
  983. Err(e) => {
  984. eprintln!("no SM 6.6 device ({e}); skipped");
  985. return;
  986. }
  987. };
  988. let dir = std::env::temp_dir().join(format!("victory-float-{}", std::process::id()));
  989. std::fs::create_dir_all(&dir).unwrap();
  990. let src = r#"[RootSignature(RS)] [numthreads(4, 1, 1)]
  991. void cs(uint i : SV_GroupIndex) {
  992. float x = i == 0 ? k.x : i == 1 ? -k.x : i == 2 ? k.y : k.z;
  993. outb.Store(4 * i, asuint(int(x)));
  994. outb.Store(16 + 4 * i, uint(x));
  995. outb.Store(32 + 4 * i, asuint(x * k.w));
  996. float y = i == 0 ? k.w - 1e-10 : i == 1 ? k.z : i == 2 ? k.w - 1e-8 : k.z + 0.25;
  997. outb.Store(48 + 4 * i, asuint(frac(y)));
  998. float r = i == 0 ? k.w + 3.14159274 : i == 1 ? k.w + 1.0
  999. : i == 2 ? k.w - 3.14159274 : k.w + 1.57079637;
  1000. outb.Store(64 + 4 * i, asuint(i == 3 ? cos(r) : sin(r)));
  1001. }"#;
  1002. let cs = translate(&compile(&console, &dir, src, "cs", "cs_6_5")).unwrap();
  1003. let (root, pso) = host.compute_pipeline(&cs).unwrap();
  1004. // 1e30, NaN, 3.5, 0.
  1005. let k = [1e30f32.to_bits(), 0x7FC0_0000, 3.5f32.to_bits(), 0];
  1006. let views = [
  1007. View::Texture(1, 1, &[[0.0; 4]]),
  1008. View::Texture(1, 1, &[[0.0; 4]]),
  1009. View::Texture(1, 1, &[[0.0; 4]]),
  1010. View::Texture(1, 1, &[[0.0; 4]]),
  1011. View::Texture(1, 1, &[[0.0; 4]]),
  1012. View::RawUav(20),
  1013. View::TextureUav(1, 1),
  1014. ];
  1015. let out = host
  1016. .dispatch(
  1017. &root,
  1018. &pso,
  1019. &Dispatch {
  1020. roots: vec![(0, Root::Constants(user_data(&cs, &k)))],
  1021. views: &views,
  1022. samplers: &[],
  1023. groups: [1, 1, 1],
  1024. },
  1025. )
  1026. .unwrap();
  1027. let _ = std::fs::remove_dir_all(&dir);
  1028. assert_eq!(
  1029. out[0][..16],
  1030. [
  1031. 0x7FFF_FFFF,
  1032. 0x8000_0000,
  1033. 0,
  1034. 3, // int
  1035. u32::MAX,
  1036. 0,
  1037. 0,
  1038. 3, // uint
  1039. 0,
  1040. 0,
  1041. 0,
  1042. 0, // x * 0, NaN included
  1043. 0x3F7F_FFFF,
  1044. 0.5f32.to_bits(),
  1045. 0x3F7F_FFFF,
  1046. 0.75f32.to_bits(), // frac
  1047. ]
  1048. );
  1049. // sin(pi), sin(-pi) and cos(pi/2): the compiler turns radians into
  1050. // exactly 0.5, -0.5 and 0.25 turns.
  1051. assert_eq!([out[0][16], out[0][18], out[0][19]], [0, 0, 0]);
  1052. // An ordinary angle is untouched: sin(1 rad).
  1053. let one = f32::from_bits(out[0][17]);
  1054. assert!((one - 0.841_470_96).abs() < 1e-4, "{one}");
  1055. }
  1056. /// Equal bits, both zero (the console's legacy multiply gives +0 where PC
  1057. /// code gives -0), or two normal floats within 1e-3 relative.
  1058. fn close(a: u32, b: u32) -> bool {
  1059. let (x, y) = (f32::from_bits(a), f32::from_bits(b));
  1060. a == b
  1061. || x == 0.0 && y == 0.0
  1062. || x.is_normal() && y.is_normal() && (x - y).abs() <= 1e-3 * y.abs().max(1.0)
  1063. }
  1064. #[test]
  1065. fn translated_compute_matches_pc() {
  1066. use super::host::{Dispatch, Stride, View};
  1067. let Some((console, pc)) = tools() else {
  1068. eprintln!("no console or PC compiler; skipped");
  1069. return;
  1070. };
  1071. let host = match Host::new(false) {
  1072. Ok(host) => host,
  1073. Err(e) => {
  1074. eprintln!("no SM 6.6 device ({e}); skipped");
  1075. return;
  1076. }
  1077. };
  1078. let dir = std::env::temp_dir().join(format!("victory-diff-cs-{}", std::process::id()));
  1079. std::fs::create_dir_all(&dir).unwrap();
  1080. let k = [0.75f32, -1.5, 2.0, 0.125].map(f32::to_bits);
  1081. let texels: Vec<[f32; 4]> = (0..16)
  1082. .map(|i| [i as f32 / 16.0, (i % 4) as f32 * 0.3, 0.5, 1.0])
  1083. .collect();
  1084. let dummy = [[9.0f32; 4]];
  1085. let cube_texels: Vec<[f32; 4]> = (0..96)
  1086. .map(|i| {
  1087. [
  1088. (i / 16) as f32,
  1089. (i % 4) as f32 * 0.25,
  1090. (i / 4 % 4) as f32 * 0.25,
  1091. 1.0,
  1092. ]
  1093. })
  1094. .collect();
  1095. // Buffers: 16 float4, 8 structures of 16 bytes, 32 raw dwords; the
  1096. // root CBV's 16 float4 and the root SRV's 32 dwords.
  1097. let floats = |n: usize, scale: f32| -> Vec<u32> {
  1098. (0..n).map(|i| (i as f32 * scale - 3.0).to_bits()).collect()
  1099. };
  1100. let typed_data = floats(64, 0.25);
  1101. let structured_data: Vec<u32> = (0..32u32)
  1102. .map(|i| {
  1103. if i % 4 == 1 {
  1104. i * 0x0101_0101
  1105. } else {
  1106. (i as f32 * 0.5).to_bits()
  1107. }
  1108. })
  1109. .collect();
  1110. let raw_data: Vec<u32> = (0..32u32).map(|i| i.wrapping_mul(0x9E37_79B9)).collect();
  1111. let views = [
  1112. View::Texture(1, 1, &dummy),
  1113. View::Texture(4, 4, &texels),
  1114. View::Buffer {
  1115. data: &typed_data,
  1116. stride: Stride::Typed,
  1117. },
  1118. View::Buffer {
  1119. data: &structured_data,
  1120. stride: Stride::Structured(16),
  1121. },
  1122. View::Buffer {
  1123. data: &raw_data,
  1124. stride: Stride::Raw,
  1125. },
  1126. View::RawUav(1024),
  1127. View::TextureUav(16, 16),
  1128. View::UintTextureUav(16, 16),
  1129. View::HalfUav(256),
  1130. ];
  1131. let typed_view = |format, bytes| View::Buffer {
  1132. data: &raw_data,
  1133. stride: Stride::Format(format, bytes),
  1134. };
  1135. let views: Vec<View> = views
  1136. .into_iter()
  1137. .chain([
  1138. typed_view(DXGI_FORMAT_R8G8B8A8_UNORM, 4),
  1139. typed_view(DXGI_FORMAT_R16G16_SNORM, 4),
  1140. typed_view(DXGI_FORMAT_R8G8B8A8_UINT, 4),
  1141. typed_view(DXGI_FORMAT_R10G10B10A2_UNORM, 4),
  1142. typed_view(DXGI_FORMAT_R16G16B16A16_UINT, 8),
  1143. typed_view(DXGI_FORMAT_R8_UNORM, 1),
  1144. typed_view(DXGI_FORMAT_R16_FLOAT, 2),
  1145. typed_view(DXGI_FORMAT_R8G8B8A8_SNORM, 4),
  1146. View::Cube(4, &cube_texels),
  1147. ])
  1148. .collect();
  1149. let root_cbv = floats(64, -0.125);
  1150. let root_srv: Vec<u32> = (0..32u32).map(|i| i * 0x0001_0003 + 7).collect();
  1151. let samplers = [D3D12_SAMPLER_DESC {
  1152. Filter: D3D12_FILTER_MIN_MAG_MIP_POINT,
  1153. AddressU: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
  1154. AddressV: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
  1155. AddressW: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
  1156. MaxAnisotropy: 1,
  1157. MaxLOD: f32::MAX,
  1158. ..Default::default()
  1159. }; 2];
  1160. let dispatch = |roots| Dispatch {
  1161. roots,
  1162. views: &views,
  1163. samplers: &samplers,
  1164. groups: [2, 2, 1],
  1165. };
  1166. let mut failures = Vec::new();
  1167. let only = std::env::var("VICTORY_DIFF_ONLY").ok();
  1168. let warp = std::env::var("VICTORY_WARP").is_ok_and(|v| v == "1");
  1169. for (name, src) in CS_CASES
  1170. .iter()
  1171. .filter(|c| only.as_ref().is_none_or(|o| o == c.0))
  1172. .filter(|c| warp || !c.0.starts_with("terminates"))
  1173. {
  1174. let console_cs = compile(&console, &dir, src, "cs", "cs_6_5");
  1175. if let Ok(out) = std::env::var("VICTORY_EMIT_DUMP") {
  1176. let stem = name.replace([' ', ','], "_");
  1177. std::fs::write(format!("{out}/{stem}.cs.cdxil"), &console_cs).unwrap();
  1178. }
  1179. let cs_c = match translate(&console_cs) {
  1180. Ok(s) => s,
  1181. Err(e) => {
  1182. failures.push(format!("{name}: {e}"));
  1183. continue;
  1184. }
  1185. };
  1186. if let Ok(out) = std::env::var("VICTORY_EMIT_DUMP") {
  1187. let stem = name.replace([' ', ','], "_");
  1188. std::fs::write(format!("{out}/{stem}.cs.dxil"), &cs_c.dxil).unwrap();
  1189. }
  1190. if let Ok(mut v) = super::validator::Validator::load(
  1191. super::validator::Validator::default_path().as_deref(),
  1192. ) {
  1193. v.validate(&mut cs_c.dxil.clone())
  1194. .unwrap_or_else(|e| panic!("{name}: {e}"));
  1195. }
  1196. let (root_t, pso_t) = match host.compute_pipeline(&cs_c) {
  1197. Ok(p) => p,
  1198. // WARP runs no fixed wave size of 64.
  1199. Err(e) if std::env::var("VICTORY_WARP").is_ok_and(|v| v == "1") => {
  1200. eprintln!("{name}: skipped on WARP ({e})");
  1201. continue;
  1202. }
  1203. Err(e) => panic!("{name}: {e}"),
  1204. };
  1205. // Our root views follow the user data in root parameter order.
  1206. let mut roots = vec![(0, Root::Constants(user_data(&cs_c, &k)))];
  1207. let mut root_views: Vec<(u8, bool)> = cs_c.root_cbvs.iter().map(|&s| (s, false)).collect();
  1208. root_views.extend(cs_c.root_srvs.iter().map(|&s| (s, true)));
  1209. root_views.sort_unstable();
  1210. for (n, (slot, srv)) in root_views.into_iter().enumerate() {
  1211. assert_eq!(slot, 4 + u8::from(srv), "{name}: root view");
  1212. let data = if srv {
  1213. root_srv.clone()
  1214. } else {
  1215. root_cbv.clone()
  1216. };
  1217. roots.push((1 + n as u32, Root::View { srv, data }));
  1218. }
  1219. let ours = host.dispatch(&root_t, &pso_t, &dispatch(roots));
  1220. if name.starts_with("terminates") {
  1221. match ours {
  1222. Ok(_) => eprintln!("{name}: finished"),
  1223. Err(e) => failures.push(format!("{name}: {e}")),
  1224. }
  1225. continue;
  1226. }
  1227. let ours = ours.unwrap();
  1228. let cs_p = compile(&pc, &dir, src, "cs", "cs_6_5");
  1229. // SAFETY: the PC container carries its root signature.
  1230. let root_p: ID3D12RootSignature =
  1231. unsafe { host.device.CreateRootSignature(0, &cs_p) }.unwrap();
  1232. let pso_p = host.compute_pipeline_with(&root_p, &cs_p).unwrap();
  1233. let table = |sampler, index| Root::Table { sampler, index };
  1234. let theirs = host
  1235. .dispatch(
  1236. &root_p,
  1237. &pso_p,
  1238. &dispatch(vec![
  1239. (0, Root::Constants(k.to_vec())),
  1240. (1, table(false, 1)),
  1241. (2, table(true, 1)),
  1242. (3, table(false, 5)),
  1243. (
  1244. 4,
  1245. Root::View {
  1246. srv: false,
  1247. data: root_cbv.clone(),
  1248. },
  1249. ),
  1250. (
  1251. 5,
  1252. Root::View {
  1253. srv: true,
  1254. data: root_srv.clone(),
  1255. },
  1256. ),
  1257. (6, table(false, 9)),
  1258. ]),
  1259. )
  1260. .unwrap();
  1261. let mismatch = ours
  1262. .iter()
  1263. .flatten()
  1264. .zip(theirs.iter().flatten())
  1265. .enumerate()
  1266. .find(|(_, (a, b))| !close(**a, **b));
  1267. match mismatch {
  1268. None => eprintln!("{name}: equal"),
  1269. Some((at, (a, b))) => failures.push(format!(
  1270. "{name}: word {at}: {a:#x} ({}) vs {b:#x} ({})",
  1271. f32::from_bits(*a),
  1272. f32::from_bits(*b)
  1273. )),
  1274. }
  1275. }
  1276. let _ = std::fs::remove_dir_all(&dir);
  1277. assert!(failures.is_empty(), "{failures:#?}");
  1278. }