ExecutionTest.cpp 140 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579
  1. ///////////////////////////////////////////////////////////////////////////////
  2. // //
  3. // ExecutionTest.cpp //
  4. // Copyright (C) Microsoft Corporation. All rights reserved. //
  5. // This file is distributed under the University of Illinois Open Source //
  6. // License. See LICENSE.TXT for details. //
  7. // //
  8. // These tests run by executing compiled programs, and thus involve more //
  9. // moving parts, like the runtime and drivers. //
  10. // //
  11. ///////////////////////////////////////////////////////////////////////////////
  12. #include <algorithm>
  13. #include <memory>
  14. #include <vector>
  15. #include <string>
  16. #include <map>
  17. #include <unordered_set>
  18. #include <strstream>
  19. #include <iomanip>
  20. #include "CompilationResult.h"
  21. #include "HLSLTestData.h"
  22. #include <Shlwapi.h>
  23. #include <atlcoll.h>
  24. #include <locale>
  25. #include <algorithm>
  26. #undef _read
  27. #include "WexTestClass.h"
  28. #include "HlslTestUtils.h"
  29. #include "DxcTestUtils.h"
  30. #include "dxc/Support/Global.h"
  31. #include "dxc/Support/WinIncludes.h"
  32. #include "dxc/Support/FileIOHelper.h"
  33. #include "dxc/Support/Unicode.h"
  34. //
  35. // d3d12.h and dxgi1_4.h are included in the Windows 10 SDK
  36. // https://msdn.microsoft.com/en-us/library/windows/desktop/dn899120(v=vs.85).aspx
  37. // https://developer.microsoft.com/en-US/windows/downloads/windows-10-sdk
  38. //
  39. #include <d3d12.h>
  40. #include <dxgi1_4.h>
  41. #include <DXGIDebug.h>
  42. #include <D3dx12.h>
  43. #include <DirectXMath.h>
  44. #include <strsafe.h>
  45. #include <d3dcompiler.h>
  46. #include <wincodec.h>
  47. #include "ShaderOpTest.h"
  48. #pragma comment(lib, "d3dcompiler.lib")
  49. #pragma comment(lib, "windowscodecs.lib")
  50. #pragma comment(lib, "dxguid.lib")
  51. // A more recent Windows SDK than currently required is needed for these.
  52. typedef HRESULT(WINAPI *D3D12EnableExperimentalFeaturesFn)(
  53. UINT NumFeatures,
  54. __in_ecount(NumFeatures) const IID* pIIDs,
  55. __in_ecount_opt(NumFeatures) void* pConfigurationStructs,
  56. __in_ecount_opt(NumFeatures) UINT* pConfigurationStructSizes);
  57. static const GUID D3D12ExperimentalShaderModelsID = { /* 76f5573e-f13a-40f5-b297-81ce9e18933f */
  58. 0x76f5573e,
  59. 0xf13a,
  60. 0x40f5,
  61. { 0xb2, 0x97, 0x81, 0xce, 0x9e, 0x18, 0x93, 0x3f }
  62. };
  63. using namespace DirectX;
  64. using namespace hlsl_test;
  65. template <typename TSequence, typename T>
  66. static bool contains(TSequence s, const T &val) {
  67. return std::cend(s) != std::find(std::cbegin(s), std::cend(s), val);
  68. }
  69. template <typename InputIterator, typename T>
  70. static bool contains(InputIterator b, InputIterator e, const T &val) {
  71. return e != std::find(b, e, val);
  72. }
  73. static HRESULT EnableExperimentalShaderModels() {
  74. HMODULE hRuntime = LoadLibraryW(L"d3d12.dll");
  75. if (hRuntime == NULL) {
  76. return HRESULT_FROM_WIN32(GetLastError());
  77. }
  78. D3D12EnableExperimentalFeaturesFn pD3D12EnableExperimentalFeatures =
  79. (D3D12EnableExperimentalFeaturesFn)GetProcAddress(hRuntime, "D3D12EnableExperimentalFeatures");
  80. if (pD3D12EnableExperimentalFeatures == nullptr) {
  81. FreeLibrary(hRuntime);
  82. return HRESULT_FROM_WIN32(GetLastError());
  83. }
  84. HRESULT hr = pD3D12EnableExperimentalFeatures(1, &D3D12ExperimentalShaderModelsID, nullptr, nullptr);
  85. FreeLibrary(hRuntime);
  86. return hr;
  87. }
  88. static HRESULT ReportLiveObjects() {
  89. CComPtr<IDXGIDebug1> pDebug;
  90. IFR(DXGIGetDebugInterface1(0, IID_PPV_ARGS(&pDebug)));
  91. IFR(pDebug->ReportLiveObjects(DXGI_DEBUG_ALL, DXGI_DEBUG_RLO_ALL));
  92. return S_OK;
  93. }
  94. static void WriteInfoQueueMessages(void *pStrCtx, st::OutputStringFn pOutputStrFn, ID3D12InfoQueue *pInfoQueue) {
  95. bool allMessagesOK = true;
  96. UINT64 count = pInfoQueue->GetNumStoredMessages();
  97. CAtlArray<BYTE> message;
  98. for (UINT64 i = 0; i < count; ++i) {
  99. // 'GetMessageA' rather than 'GetMessage' is an artifact of user32 headers.
  100. SIZE_T msgLen = 0;
  101. if (FAILED(pInfoQueue->GetMessageA(i, nullptr, &msgLen))) {
  102. allMessagesOK = false;
  103. continue;
  104. }
  105. if (message.GetCount() < msgLen) {
  106. if (!message.SetCount(msgLen)) {
  107. allMessagesOK = false;
  108. continue;
  109. }
  110. }
  111. D3D12_MESSAGE *pMessage = (D3D12_MESSAGE *)message.GetData();
  112. if (FAILED(pInfoQueue->GetMessageA(i, pMessage, &msgLen))) {
  113. allMessagesOK = false;
  114. continue;
  115. }
  116. CA2W msgW(pMessage->pDescription, CP_ACP);
  117. pOutputStrFn(pStrCtx, msgW.m_psz);
  118. pOutputStrFn(pStrCtx, L"\r\n");
  119. }
  120. if (!allMessagesOK) {
  121. pOutputStrFn(pStrCtx, L"Failed to retrieve some messages.\r\n");
  122. }
  123. }
  124. class CComContext {
  125. private:
  126. bool m_init;
  127. public:
  128. CComContext() : m_init(false) {}
  129. ~CComContext() { Dispose(); }
  130. void Dispose() { if (!m_init) return; m_init = false; CoUninitialize(); }
  131. HRESULT Init() { HRESULT hr = CoInitializeEx(0, COINIT_MULTITHREADED); if (SUCCEEDED(hr)) { m_init = true; } return hr; }
  132. };
  133. static void SavePixelsToFile(LPCVOID pPixels, DXGI_FORMAT format, UINT32 m_width, UINT32 m_height, LPCWSTR pFileName) {
  134. CComContext ctx;
  135. CComPtr<IWICImagingFactory> pFactory;
  136. CComPtr<IWICBitmap> pBitmap;
  137. CComPtr<IWICBitmapEncoder> pEncoder;
  138. CComPtr<IWICBitmapFrameEncode> pFrameEncode;
  139. CComPtr<hlsl::AbstractMemoryStream> pStream;
  140. CComPtr<IMalloc> pMalloc;
  141. struct PF {
  142. DXGI_FORMAT Format;
  143. GUID PixelFormat;
  144. UINT32 PixelSize;
  145. bool operator==(DXGI_FORMAT F) const {
  146. return F == Format;
  147. }
  148. } Vals[] = {
  149. // Add more pixel format mappings as needed.
  150. { DXGI_FORMAT_R8G8B8A8_UNORM, GUID_WICPixelFormat32bppRGBA, 4 }
  151. };
  152. PF *pFormat = std::find(Vals, Vals + _countof(Vals), format);
  153. VERIFY_SUCCEEDED(ctx.Init());
  154. VERIFY_SUCCEEDED(CoCreateInstance(CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER, IID_IWICImagingFactory, (LPVOID*)&pFactory));
  155. VERIFY_SUCCEEDED(CoGetMalloc(1, &pMalloc));
  156. VERIFY_SUCCEEDED(hlsl::CreateMemoryStream(pMalloc, &pStream));
  157. VERIFY_ARE_NOT_EQUAL(pFormat, Vals + _countof(Vals));
  158. VERIFY_SUCCEEDED(pFactory->CreateBitmapFromMemory(m_width, m_height, pFormat->PixelFormat, m_width * pFormat->PixelSize, m_width * m_height * pFormat->PixelSize, (BYTE *)pPixels, &pBitmap));
  159. VERIFY_SUCCEEDED(pFactory->CreateEncoder(GUID_ContainerFormatBmp, nullptr, &pEncoder));
  160. VERIFY_SUCCEEDED(pEncoder->Initialize(pStream, WICBitmapEncoderNoCache));
  161. VERIFY_SUCCEEDED(pEncoder->CreateNewFrame(&pFrameEncode, nullptr));
  162. VERIFY_SUCCEEDED(pFrameEncode->Initialize(nullptr));
  163. VERIFY_SUCCEEDED(pFrameEncode->WriteSource(pBitmap, nullptr));
  164. VERIFY_SUCCEEDED(pFrameEncode->Commit());
  165. VERIFY_SUCCEEDED(pEncoder->Commit());
  166. hlsl::WriteBinaryFile(pFileName, pStream->GetPtr(), pStream->GetPtrSize());
  167. }
  168. class ExecutionTest {
  169. public:
  170. // By default, ignore these tests, which require a recent build to run properly.
  171. BEGIN_TEST_CLASS(ExecutionTest)
  172. TEST_CLASS_PROPERTY(L"Ignore", L"true")
  173. TEST_METHOD_PROPERTY(L"Priority", L"0")
  174. END_TEST_CLASS()
  175. TEST_CLASS_SETUP(ExecutionTestClassSetup)
  176. TEST_METHOD(BasicComputeTest);
  177. TEST_METHOD(BasicTriangleTest);
  178. TEST_METHOD(BasicTriangleOpTest);
  179. TEST_METHOD(OutOfBoundsTest);
  180. TEST_METHOD(SaturateTest);
  181. TEST_METHOD(SignTest);
  182. TEST_METHOD(Int64Test);
  183. TEST_METHOD(WaveIntrinsicsTest);
  184. TEST_METHOD(WaveIntrinsicsInPSTest);
  185. // TAEF data-driven tests.
  186. BEGIN_TEST_METHOD(UnaryFloatOpTest)
  187. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#UnaryFloatOpTable")
  188. END_TEST_METHOD()
  189. BEGIN_TEST_METHOD(BinaryFloatOpTest)
  190. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#BinaryFloatOpTable")
  191. END_TEST_METHOD()
  192. BEGIN_TEST_METHOD(TertiaryFloatOpTest)
  193. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#TertiaryFloatOpTable")
  194. END_TEST_METHOD()
  195. BEGIN_TEST_METHOD(UnaryIntOpTest)
  196. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#UnaryIntOpTable")
  197. END_TEST_METHOD()
  198. BEGIN_TEST_METHOD(BinaryIntOpTest)
  199. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#BinaryIntOpTable")
  200. END_TEST_METHOD()
  201. BEGIN_TEST_METHOD(TertiaryIntOpTest)
  202. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#TertiaryIntOpTable")
  203. END_TEST_METHOD()
  204. BEGIN_TEST_METHOD(UnaryUintOpTest)
  205. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#UnaryUintOpTable")
  206. END_TEST_METHOD()
  207. BEGIN_TEST_METHOD(BinaryUintOpTest)
  208. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#BinaryUintOpTable")
  209. END_TEST_METHOD()
  210. BEGIN_TEST_METHOD(TertiaryUintOpTest)
  211. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#TertiaryUintOpTable")
  212. END_TEST_METHOD()
  213. BEGIN_TEST_METHOD(DotTest)
  214. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#DotOpTable")
  215. END_TEST_METHOD()
  216. BEGIN_TEST_METHOD(Msad4Test)
  217. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#Msad4Table")
  218. END_TEST_METHOD()
  219. dxc::DxcDllSupport m_support;
  220. bool m_ExperimentalModeEnabled = false;
  221. static const float ClearColor[4];
  222. bool UseDxbc() {
  223. return GetTestParamBool(L"DXBC");
  224. }
  225. bool UseDebugIfaces() {
  226. return true;
  227. }
  228. bool SaveImages() {
  229. return GetTestParamBool(L"SaveImages");
  230. }
  231. void CompileFromText(LPCSTR pText, LPCWSTR pEntryPoint, LPCWSTR pTargetProfile, ID3DBlob **ppBlob) {
  232. VERIFY_SUCCEEDED(m_support.Initialize());
  233. CComPtr<IDxcCompiler> pCompiler;
  234. CComPtr<IDxcLibrary> pLibrary;
  235. CComPtr<IDxcBlobEncoding> pTextBlob;
  236. CComPtr<IDxcOperationResult> pResult;
  237. HRESULT resultCode;
  238. VERIFY_SUCCEEDED(m_support.CreateInstance(CLSID_DxcCompiler, &pCompiler));
  239. VERIFY_SUCCEEDED(m_support.CreateInstance(CLSID_DxcLibrary, &pLibrary));
  240. VERIFY_SUCCEEDED(pLibrary->CreateBlobWithEncodingFromPinned((LPBYTE)pText, strlen(pText), CP_UTF8, &pTextBlob));
  241. VERIFY_SUCCEEDED(pCompiler->Compile(pTextBlob, L"hlsl.hlsl", pEntryPoint, pTargetProfile, nullptr, 0, nullptr, 0, nullptr, &pResult));
  242. VERIFY_SUCCEEDED(pResult->GetStatus(&resultCode));
  243. if (FAILED(resultCode)) {
  244. CComPtr<IDxcBlobEncoding> errors;
  245. VERIFY_SUCCEEDED(pResult->GetErrorBuffer(&errors));
  246. LogCommentFmt(L"Failed to compile shader: %s", BlobToUtf16(errors).data());
  247. }
  248. VERIFY_SUCCEEDED(resultCode);
  249. VERIFY_SUCCEEDED(pResult->GetResult((IDxcBlob **)ppBlob));
  250. }
  251. void CreateComputeCommandQueue(ID3D12Device *pDevice, LPCWSTR pName, ID3D12CommandQueue **ppCommandQueue) {
  252. D3D12_COMMAND_QUEUE_DESC queueDesc = {};
  253. queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
  254. queueDesc.Type = D3D12_COMMAND_LIST_TYPE_COMPUTE;
  255. VERIFY_SUCCEEDED(pDevice->CreateCommandQueue(&queueDesc, IID_PPV_ARGS(ppCommandQueue)));
  256. VERIFY_SUCCEEDED((*ppCommandQueue)->SetName(pName));
  257. }
  258. void CreateComputePSO(ID3D12Device *pDevice, ID3D12RootSignature *pRootSignature, LPCSTR pShader, ID3D12PipelineState **ppComputeState) {
  259. CComPtr<ID3DBlob> pComputeShader;
  260. // Load and compile shaders.
  261. if (UseDxbc()) {
  262. DXBCFromText(pShader, L"main", L"cs_6_0", &pComputeShader);
  263. }
  264. else {
  265. CompileFromText(pShader, L"main", L"cs_6_0", &pComputeShader);
  266. }
  267. // Describe and create the compute pipeline state object (PSO).
  268. D3D12_COMPUTE_PIPELINE_STATE_DESC computePsoDesc = {};
  269. computePsoDesc.pRootSignature = pRootSignature;
  270. computePsoDesc.CS = CD3DX12_SHADER_BYTECODE(pComputeShader);
  271. VERIFY_SUCCEEDED(pDevice->CreateComputePipelineState(&computePsoDesc, IID_PPV_ARGS(ppComputeState)));
  272. }
  273. bool CreateDevice(_COM_Outptr_ ID3D12Device **ppDevice) {
  274. const D3D_FEATURE_LEVEL FeatureLevelRequired = D3D_FEATURE_LEVEL_11_0;
  275. CComPtr<IDXGIFactory4> factory;
  276. CComPtr<ID3D12Device> pDevice;
  277. *ppDevice = nullptr;
  278. VERIFY_SUCCEEDED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)));
  279. if (GetTestParamUseWARP(true)) {
  280. CComPtr<IDXGIAdapter> warpAdapter;
  281. VERIFY_SUCCEEDED(factory->EnumWarpAdapter(IID_PPV_ARGS(&warpAdapter)));
  282. HRESULT createHR = D3D12CreateDevice(warpAdapter, FeatureLevelRequired,
  283. IID_PPV_ARGS(&pDevice));
  284. if (FAILED(createHR)) {
  285. LogCommentFmt(L"The available version of WARP does not support d3d12.");
  286. WEX::Logging::Log::Result(WEX::Logging::TestResults::Blocked);
  287. return false;
  288. }
  289. } else {
  290. CComPtr<IDXGIAdapter1> hardwareAdapter;
  291. WEX::Common::String AdapterValue;
  292. IFT(WEX::TestExecution::RuntimeParameters::TryGetValue(L"Adapter",
  293. AdapterValue));
  294. GetHardwareAdapter(factory, AdapterValue, &hardwareAdapter);
  295. if (hardwareAdapter == nullptr) {
  296. WEX::Logging::Log::Error(
  297. L"Unable to find hardware adapter with D3D12 support.");
  298. return false;
  299. }
  300. VERIFY_SUCCEEDED(D3D12CreateDevice(hardwareAdapter, FeatureLevelRequired,
  301. IID_PPV_ARGS(&pDevice)));
  302. DXGI_ADAPTER_DESC1 AdapterDesc;
  303. VERIFY_SUCCEEDED(hardwareAdapter->GetDesc1(&AdapterDesc));
  304. LogCommentFmt(L"Using Adapter: %s", AdapterDesc.Description);
  305. }
  306. if (pDevice == nullptr)
  307. return false;
  308. if (!UseDxbc()) {
  309. // Check for DXIL support.
  310. // This is defined in d3d.h for Windows 10 Anniversary Edition SDK, but we only
  311. // require the Windows 10 SDK.
  312. typedef enum D3D_SHADER_MODEL {
  313. D3D_SHADER_MODEL_5_1 = 0x51,
  314. D3D_SHADER_MODEL_6_0 = 0x60
  315. } D3D_SHADER_MODEL;
  316. typedef struct D3D12_FEATURE_DATA_SHADER_MODEL {
  317. _Inout_ D3D_SHADER_MODEL HighestShaderModel;
  318. } D3D12_FEATURE_DATA_SHADER_MODEL;
  319. const UINT D3D12_FEATURE_SHADER_MODEL = 7;
  320. D3D12_FEATURE_DATA_SHADER_MODEL SMData;
  321. SMData.HighestShaderModel = D3D_SHADER_MODEL_6_0;
  322. VERIFY_SUCCEEDED(pDevice->CheckFeatureSupport(
  323. (D3D12_FEATURE)D3D12_FEATURE_SHADER_MODEL, &SMData, sizeof(SMData)));
  324. if (SMData.HighestShaderModel != D3D_SHADER_MODEL_6_0) {
  325. LogCommentFmt(L"The selected device does not support "
  326. L"shader model 6 (required for DXIL).");
  327. WEX::Logging::Log::Result(WEX::Logging::TestResults::Blocked);
  328. return false;
  329. }
  330. }
  331. if (UseDebugIfaces()) {
  332. CComPtr<ID3D12InfoQueue> pInfoQueue;
  333. if (SUCCEEDED(pDevice->QueryInterface(&pInfoQueue))) {
  334. pInfoQueue->SetMuteDebugOutput(FALSE);
  335. }
  336. }
  337. *ppDevice = pDevice.Detach();
  338. return true;
  339. }
  340. void CreateGraphicsCommandQueue(ID3D12Device *pDevice, ID3D12CommandQueue **ppCommandQueue) {
  341. D3D12_COMMAND_QUEUE_DESC queueDesc = {};
  342. queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
  343. queueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;;
  344. VERIFY_SUCCEEDED(pDevice->CreateCommandQueue(&queueDesc, IID_PPV_ARGS(ppCommandQueue)));
  345. }
  346. void CreateGraphicsCommandQueueAndList(
  347. ID3D12Device *pDevice, ID3D12CommandQueue **ppCommandQueue,
  348. ID3D12CommandAllocator **ppAllocator,
  349. ID3D12GraphicsCommandList **ppCommandList, ID3D12PipelineState *pPSO) {
  350. CreateGraphicsCommandQueue(pDevice, ppCommandQueue);
  351. VERIFY_SUCCEEDED(pDevice->CreateCommandAllocator(
  352. D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(ppAllocator)));
  353. VERIFY_SUCCEEDED(pDevice->CreateCommandList(
  354. 0, D3D12_COMMAND_LIST_TYPE_DIRECT, *ppAllocator, pPSO,
  355. IID_PPV_ARGS(ppCommandList)));
  356. }
  357. void CreateGraphicsPSO(ID3D12Device *pDevice,
  358. D3D12_INPUT_LAYOUT_DESC *pInputLayout,
  359. ID3D12RootSignature *pRootSignature, LPCSTR pShaders,
  360. ID3D12PipelineState **ppPSO) {
  361. CComPtr<ID3DBlob> vertexShader;
  362. CComPtr<ID3DBlob> pixelShader;
  363. if (UseDxbc()) {
  364. DXBCFromText(pShaders, L"VSMain", L"vs_6_0", &vertexShader);
  365. DXBCFromText(pShaders, L"PSMain", L"ps_6_0", &pixelShader);
  366. } else {
  367. CompileFromText(pShaders, L"VSMain", L"vs_6_0", &vertexShader);
  368. CompileFromText(pShaders, L"PSMain", L"ps_6_0", &pixelShader);
  369. }
  370. // Describe and create the graphics pipeline state object (PSO).
  371. D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = {};
  372. psoDesc.InputLayout = *pInputLayout;
  373. psoDesc.pRootSignature = pRootSignature;
  374. psoDesc.VS = CD3DX12_SHADER_BYTECODE(vertexShader);
  375. psoDesc.PS = CD3DX12_SHADER_BYTECODE(pixelShader);
  376. psoDesc.RasterizerState = CD3DX12_RASTERIZER_DESC(D3D12_DEFAULT);
  377. psoDesc.BlendState = CD3DX12_BLEND_DESC(D3D12_DEFAULT);
  378. psoDesc.DepthStencilState.DepthEnable = FALSE;
  379. psoDesc.DepthStencilState.StencilEnable = FALSE;
  380. psoDesc.SampleMask = UINT_MAX;
  381. psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
  382. psoDesc.NumRenderTargets = 1;
  383. psoDesc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;
  384. psoDesc.SampleDesc.Count = 1;
  385. VERIFY_SUCCEEDED(
  386. pDevice->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(ppPSO)));
  387. }
  388. void CreateRenderTargetAndReadback(ID3D12Device *pDevice,
  389. ID3D12DescriptorHeap *pHeap, UINT width,
  390. UINT height,
  391. ID3D12Resource **ppRenderTarget,
  392. ID3D12Resource **ppBuffer) {
  393. const DXGI_FORMAT format = DXGI_FORMAT_R8G8B8A8_UNORM;
  394. const size_t formatElementSize = 4;
  395. CComPtr<ID3D12Resource> pRenderTarget;
  396. CComPtr<ID3D12Resource> pBuffer;
  397. CD3DX12_CPU_DESCRIPTOR_HANDLE rtvHandle(
  398. pHeap->GetCPUDescriptorHandleForHeapStart());
  399. CD3DX12_HEAP_PROPERTIES rtHeap(D3D12_HEAP_TYPE_DEFAULT);
  400. CD3DX12_RESOURCE_DESC rtDesc(
  401. CD3DX12_RESOURCE_DESC::Tex2D(format, width, height));
  402. CD3DX12_CLEAR_VALUE rtClearVal(format, ClearColor);
  403. rtDesc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
  404. VERIFY_SUCCEEDED(pDevice->CreateCommittedResource(
  405. &rtHeap, D3D12_HEAP_FLAG_NONE, &rtDesc, D3D12_RESOURCE_STATE_COPY_DEST,
  406. &rtClearVal, IID_PPV_ARGS(&pRenderTarget)));
  407. pDevice->CreateRenderTargetView(pRenderTarget, nullptr, rtvHandle);
  408. // rtvHandle.Offset(1, rtvDescriptorSize); // Not needed for a single
  409. // resource.
  410. CD3DX12_HEAP_PROPERTIES readHeap(D3D12_HEAP_TYPE_READBACK);
  411. CD3DX12_RESOURCE_DESC readDesc(
  412. CD3DX12_RESOURCE_DESC::Buffer(width * height * formatElementSize));
  413. VERIFY_SUCCEEDED(pDevice->CreateCommittedResource(
  414. &readHeap, D3D12_HEAP_FLAG_NONE, &readDesc,
  415. D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&pBuffer)));
  416. *ppRenderTarget = pRenderTarget.Detach();
  417. *ppBuffer = pBuffer.Detach();
  418. }
  419. void CreateRootSignatureFromDesc(ID3D12Device *pDevice,
  420. const D3D12_ROOT_SIGNATURE_DESC *pDesc,
  421. ID3D12RootSignature **pRootSig) {
  422. CComPtr<ID3DBlob> signature;
  423. CComPtr<ID3DBlob> error;
  424. VERIFY_SUCCEEDED(D3D12SerializeRootSignature(pDesc, D3D_ROOT_SIGNATURE_VERSION_1, &signature, &error));
  425. VERIFY_SUCCEEDED(pDevice->CreateRootSignature(
  426. 0, signature->GetBufferPointer(), signature->GetBufferSize(),
  427. IID_PPV_ARGS(pRootSig)));
  428. }
  429. void CreateRtvDescriptorHeap(ID3D12Device *pDevice, UINT numDescriptors,
  430. ID3D12DescriptorHeap **pRtvHeap, UINT *rtvDescriptorSize) {
  431. D3D12_DESCRIPTOR_HEAP_DESC rtvHeapDesc = {};
  432. rtvHeapDesc.NumDescriptors = numDescriptors;
  433. rtvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV;
  434. rtvHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE;
  435. VERIFY_SUCCEEDED(
  436. pDevice->CreateDescriptorHeap(&rtvHeapDesc, IID_PPV_ARGS(pRtvHeap)));
  437. if (rtvDescriptorSize != nullptr) {
  438. *rtvDescriptorSize = pDevice->GetDescriptorHandleIncrementSize(
  439. D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
  440. }
  441. }
  442. void CreateTestUavs(ID3D12Device *pDevice,
  443. ID3D12GraphicsCommandList *pCommandList, LPCVOID values,
  444. UINT32 valueSizeInBytes, ID3D12Resource **ppUavResource,
  445. ID3D12Resource **ppReadBuffer,
  446. ID3D12Resource **ppUploadResource) {
  447. CComPtr<ID3D12Resource> pUavResource;
  448. CComPtr<ID3D12Resource> pReadBuffer;
  449. CComPtr<ID3D12Resource> pUploadResource;
  450. D3D12_SUBRESOURCE_DATA transferData;
  451. D3D12_HEAP_PROPERTIES defaultHeapProperties = CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT);
  452. D3D12_HEAP_PROPERTIES uploadHeapProperties = CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD);
  453. D3D12_RESOURCE_DESC bufferDesc = CD3DX12_RESOURCE_DESC::Buffer(valueSizeInBytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS);
  454. D3D12_RESOURCE_DESC uploadBufferDesc = CD3DX12_RESOURCE_DESC::Buffer(valueSizeInBytes);
  455. CD3DX12_HEAP_PROPERTIES readHeap(D3D12_HEAP_TYPE_READBACK);
  456. CD3DX12_RESOURCE_DESC readDesc(CD3DX12_RESOURCE_DESC::Buffer(valueSizeInBytes));
  457. VERIFY_SUCCEEDED(pDevice->CreateCommittedResource(
  458. &defaultHeapProperties,
  459. D3D12_HEAP_FLAG_NONE,
  460. &bufferDesc,
  461. D3D12_RESOURCE_STATE_COPY_DEST,
  462. nullptr,
  463. IID_PPV_ARGS(&pUavResource)));
  464. VERIFY_SUCCEEDED(pDevice->CreateCommittedResource(
  465. &uploadHeapProperties,
  466. D3D12_HEAP_FLAG_NONE,
  467. &uploadBufferDesc,
  468. D3D12_RESOURCE_STATE_GENERIC_READ,
  469. nullptr,
  470. IID_PPV_ARGS(&pUploadResource)));
  471. VERIFY_SUCCEEDED(pDevice->CreateCommittedResource(
  472. &readHeap, D3D12_HEAP_FLAG_NONE, &readDesc,
  473. D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&pReadBuffer)));
  474. transferData.pData = values;
  475. transferData.RowPitch = valueSizeInBytes;
  476. transferData.SlicePitch = transferData.RowPitch;
  477. UpdateSubresources<1>(pCommandList, pUavResource.p, pUploadResource.p, 0, 0, 1, &transferData);
  478. RecordTransitionBarrier(pCommandList, pUavResource, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
  479. *ppUavResource = pUavResource.Detach();
  480. *ppReadBuffer = pReadBuffer.Detach();
  481. *ppUploadResource = pUploadResource.Detach();
  482. }
  483. template <typename TVertex, int len>
  484. void CreateVertexBuffer(ID3D12Device *pDevice, TVertex(&vertices)[len],
  485. ID3D12Resource **ppVertexBuffer,
  486. D3D12_VERTEX_BUFFER_VIEW *pVertexBufferView) {
  487. size_t vertexBufferSize = sizeof(vertices);
  488. CComPtr<ID3D12Resource> pVertexBuffer;
  489. CD3DX12_HEAP_PROPERTIES heapProps(D3D12_HEAP_TYPE_UPLOAD);
  490. CD3DX12_RESOURCE_DESC bufferDesc(
  491. CD3DX12_RESOURCE_DESC::Buffer(vertexBufferSize));
  492. VERIFY_SUCCEEDED(pDevice->CreateCommittedResource(
  493. &heapProps, D3D12_HEAP_FLAG_NONE, &bufferDesc,
  494. D3D12_RESOURCE_STATE_GENERIC_READ, nullptr,
  495. IID_PPV_ARGS(&pVertexBuffer)));
  496. UINT8 *pVertexDataBegin;
  497. CD3DX12_RANGE readRange(0, 0);
  498. VERIFY_SUCCEEDED(pVertexBuffer->Map(
  499. 0, &readRange, reinterpret_cast<void **>(&pVertexDataBegin)));
  500. memcpy(pVertexDataBegin, vertices, vertexBufferSize);
  501. pVertexBuffer->Unmap(0, nullptr);
  502. // Initialize the vertex buffer view.
  503. pVertexBufferView->BufferLocation = pVertexBuffer->GetGPUVirtualAddress();
  504. pVertexBufferView->StrideInBytes = sizeof(TVertex);
  505. pVertexBufferView->SizeInBytes = vertexBufferSize;
  506. *ppVertexBuffer = pVertexBuffer.Detach();
  507. }
  508. // Requires Anniversary Edition headers, so simplifying things for current setup.
  509. const UINT D3D12_FEATURE_D3D12_OPTIONS1 = 8;
  510. struct D3D12_FEATURE_DATA_D3D12_OPTIONS1 {
  511. BOOL WaveOps;
  512. UINT WaveLaneCountMin;
  513. UINT WaveLaneCountMax;
  514. UINT TotalLaneCount;
  515. BOOL ExpandedComputeResourceStates;
  516. BOOL Int64ShaderOps;
  517. };
  518. bool DoesDeviceSupportInt64(ID3D12Device *pDevice) {
  519. D3D12_FEATURE_DATA_D3D12_OPTIONS1 O;
  520. if (FAILED(pDevice->CheckFeatureSupport((D3D12_FEATURE)D3D12_FEATURE_D3D12_OPTIONS1, &O, sizeof(O))))
  521. return false;
  522. return O.Int64ShaderOps != FALSE;
  523. }
  524. bool DoesDeviceSupportWaveOps(ID3D12Device *pDevice) {
  525. D3D12_FEATURE_DATA_D3D12_OPTIONS1 O;
  526. if (FAILED(pDevice->CheckFeatureSupport((D3D12_FEATURE)D3D12_FEATURE_D3D12_OPTIONS1, &O, sizeof(O))))
  527. return false;
  528. return O.WaveOps != FALSE;
  529. }
  530. void DXBCFromText(LPCSTR pText, LPCWSTR pEntryPoint, LPCWSTR pTargetProfile, ID3DBlob **ppBlob) {
  531. CW2A pEntryPointA(pEntryPoint, CP_UTF8);
  532. CW2A pTargetProfileA(pTargetProfile, CP_UTF8);
  533. CComPtr<ID3DBlob> pErrors;
  534. D3D_SHADER_MACRO d3dMacro[2];
  535. ZeroMemory(d3dMacro, sizeof(d3dMacro));
  536. d3dMacro[0].Definition = "1";
  537. d3dMacro[0].Name = "USING_DXBC";
  538. HRESULT hr = D3DCompile(pText, strlen(pText), "hlsl.hlsl", d3dMacro, nullptr, pEntryPointA, pTargetProfileA, 0, 0, ppBlob, &pErrors);
  539. if (pErrors != nullptr) {
  540. CA2W errors((char *)pErrors->GetBufferPointer(), CP_ACP);
  541. LogCommentFmt(L"Compilation failure: %s", errors.m_szBuffer);
  542. }
  543. VERIFY_SUCCEEDED(hr);
  544. }
  545. HRESULT EnableDebugLayer() {
  546. // The debug layer does net yet validate DXIL programs that require rewriting,
  547. // but basic logging should work properly.
  548. HRESULT hr = S_FALSE;
  549. if (UseDebugIfaces()) {
  550. CComPtr<ID3D12Debug> debugController;
  551. hr = D3D12GetDebugInterface(IID_PPV_ARGS(&debugController));
  552. if (SUCCEEDED(hr)) {
  553. debugController->EnableDebugLayer();
  554. hr = S_OK;
  555. }
  556. }
  557. return hr;
  558. }
  559. HRESULT EnableExperimentalMode() {
  560. if (m_ExperimentalModeEnabled) {
  561. return S_OK;
  562. }
  563. if (!GetTestParamBool(L"ExperimentalShaders")) {
  564. return S_FALSE;
  565. }
  566. HRESULT hr = EnableExperimentalShaderModels();
  567. if (SUCCEEDED(hr)) {
  568. m_ExperimentalModeEnabled = true;
  569. }
  570. return hr;
  571. }
  572. struct FenceObj {
  573. HANDLE m_fenceEvent = NULL;
  574. CComPtr<ID3D12Fence> m_fence;
  575. UINT64 m_fenceValue;
  576. ~FenceObj() {
  577. if (m_fenceEvent) CloseHandle(m_fenceEvent);
  578. }
  579. };
  580. void InitFenceObj(ID3D12Device *pDevice, FenceObj *pObj) {
  581. pObj->m_fenceValue = 1;
  582. VERIFY_SUCCEEDED(pDevice->CreateFence(0, D3D12_FENCE_FLAG_NONE,
  583. IID_PPV_ARGS(&pObj->m_fence)));
  584. // Create an event handle to use for frame synchronization.
  585. pObj->m_fenceEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr);
  586. if (pObj->m_fenceEvent == nullptr) {
  587. VERIFY_SUCCEEDED(HRESULT_FROM_WIN32(GetLastError()));
  588. }
  589. }
  590. void ReadHlslDataIntoNewStream(LPCWSTR relativePath, IStream **ppStream) {
  591. VERIFY_SUCCEEDED(m_support.Initialize());
  592. CComPtr<IDxcLibrary> pLibrary;
  593. CComPtr<IDxcBlobEncoding> pBlob;
  594. CComPtr<IStream> pStream;
  595. std::wstring path = GetPathToHlslDataFile(relativePath);
  596. VERIFY_SUCCEEDED(m_support.CreateInstance(CLSID_DxcLibrary, &pLibrary));
  597. VERIFY_SUCCEEDED(pLibrary->CreateBlobFromFile(path.c_str(), nullptr, &pBlob));
  598. VERIFY_SUCCEEDED(pLibrary->CreateStreamFromBlobReadOnly(pBlob, &pStream));
  599. *ppStream = pStream.Detach();
  600. }
  601. void RecordRenderAndReadback(ID3D12GraphicsCommandList *pList,
  602. ID3D12DescriptorHeap *pRtvHeap,
  603. UINT rtvDescriptorSize,
  604. UINT instanceCount,
  605. D3D12_VERTEX_BUFFER_VIEW *pVertexBufferView,
  606. ID3D12RootSignature *pRootSig,
  607. ID3D12Resource *pRenderTarget,
  608. ID3D12Resource *pReadBuffer) {
  609. D3D12_RESOURCE_DESC rtDesc = pRenderTarget->GetDesc();
  610. D3D12_VIEWPORT viewport;
  611. D3D12_RECT scissorRect;
  612. memset(&viewport, 0, sizeof(viewport));
  613. viewport.Height = rtDesc.Height;
  614. viewport.Width = rtDesc.Width;
  615. viewport.MaxDepth = 1.0f;
  616. memset(&scissorRect, 0, sizeof(scissorRect));
  617. scissorRect.right = rtDesc.Width;
  618. scissorRect.bottom = rtDesc.Height;
  619. if (pRootSig != nullptr) {
  620. pList->SetGraphicsRootSignature(pRootSig);
  621. }
  622. pList->RSSetViewports(1, &viewport);
  623. pList->RSSetScissorRects(1, &scissorRect);
  624. // Indicate that the buffer will be used as a render target.
  625. RecordTransitionBarrier(pList, pRenderTarget, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_RENDER_TARGET);
  626. CD3DX12_CPU_DESCRIPTOR_HANDLE rtvHandle(pRtvHeap->GetCPUDescriptorHandleForHeapStart(), 0, rtvDescriptorSize);
  627. pList->OMSetRenderTargets(1, &rtvHandle, FALSE, nullptr);
  628. pList->ClearRenderTargetView(rtvHandle, ClearColor, 0, nullptr);
  629. pList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
  630. pList->IASetVertexBuffers(0, 1, pVertexBufferView);
  631. pList->DrawInstanced(3, instanceCount, 0, 0);
  632. // Transition to copy source and copy into read-back buffer.
  633. RecordTransitionBarrier(pList, pRenderTarget, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE);
  634. // Copy into read-back buffer.
  635. UINT rowPitch = rtDesc.Width * 4;
  636. if (rowPitch % D3D12_TEXTURE_DATA_PITCH_ALIGNMENT)
  637. rowPitch += D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - (rowPitch % D3D12_TEXTURE_DATA_PITCH_ALIGNMENT);
  638. D3D12_PLACED_SUBRESOURCE_FOOTPRINT Footprint;
  639. Footprint.Offset = 0;
  640. Footprint.Footprint = CD3DX12_SUBRESOURCE_FOOTPRINT(DXGI_FORMAT_R8G8B8A8_UNORM, rtDesc.Width, rtDesc.Height, 1, rowPitch);
  641. CD3DX12_TEXTURE_COPY_LOCATION DstLoc(pReadBuffer, Footprint);
  642. CD3DX12_TEXTURE_COPY_LOCATION SrcLoc(pRenderTarget, 0);
  643. pList->CopyTextureRegion(&DstLoc, 0, 0, 0, &SrcLoc, nullptr);
  644. }
  645. void RunRWByteBufferComputeTest(ID3D12Device *pDevice, LPCSTR shader, std::vector<uint32_t> &values);
  646. void SetDescriptorHeap(ID3D12GraphicsCommandList *pCommandList, ID3D12DescriptorHeap *pHeap) {
  647. ID3D12DescriptorHeap *const pHeaps[1] = { pHeap };
  648. pCommandList->SetDescriptorHeaps(1, pHeaps);
  649. }
  650. void WaitForSignal(ID3D12CommandQueue *pCQ, FenceObj &FO) {
  651. ::WaitForSignal(pCQ, FO.m_fence, FO.m_fenceEvent, FO.m_fenceValue++);
  652. }
  653. };
  654. const float ExecutionTest::ClearColor[4] = { 0.0f, 0.2f, 0.4f, 1.0f };
  655. #define WAVE_INTRINSIC_DXBC_GUARD \
  656. "#ifdef USING_DXBC\r\n" \
  657. "uint WaveGetLaneIndex() { return 1; }\r\n" \
  658. "uint WaveReadLaneFirst(uint u) { return u; }\r\n" \
  659. "bool WaveIsFirstLane() { return true; }\r\n" \
  660. "uint WaveGetLaneCount() { return 1; }\r\n" \
  661. "uint WaveReadLaneAt(uint n, uint u) { return u; }\r\n" \
  662. "bool WaveActiveAnyTrue(bool b) { return b; }\r\n" \
  663. "bool WaveActiveAllTrue(bool b) { return false; }\r\n" \
  664. "uint WaveActiveAllEqual(uint u) { return u; }\r\n" \
  665. "uint4 WaveActiveBallot(bool b) { return 1; }\r\n" \
  666. "uint WaveActiveCountBits(uint u) { return 1; }\r\n" \
  667. "uint WaveActiveSum(uint u) { return 1; }\r\n" \
  668. "uint WaveActiveProduct(uint u) { return 1; }\r\n" \
  669. "uint WaveActiveBitAnd(uint u) { return 1; }\r\n" \
  670. "uint WaveActiveBitOr(uint u) { return 1; }\r\n" \
  671. "uint WaveActiveBitXor(uint u) { return 1; }\r\n" \
  672. "uint WaveActiveMin(uint u) { return 1; }\r\n" \
  673. "uint WaveActiveMax(uint u) { return 1; }\r\n" \
  674. "uint WavePrefixCountBits(uint u) { return 1; }\r\n" \
  675. "uint WavePrefixSum(uint u) { return 1; }\r\n" \
  676. "uint WavePrefixProduct(uint u) { return 1; }\r\n" \
  677. "uint QuadReadLaneAt(uint a, uint u) { return 1; }\r\n" \
  678. "uint QuadReadAcrossX(uint u) { return 1; }\r\n" \
  679. "uint QuadReadAcrossY(uint u) { return 1; }\r\n" \
  680. "uint QuadReadAcrossDiagonal(uint u) { return 1; }\r\n" \
  681. "#endif\r\n"
  682. static void SetupComputeValuePattern(std::vector<uint32_t> &values, size_t count) {
  683. values.resize(count); // one element per dispatch group, in bytes
  684. for (size_t i = 0; i < count; ++i) {
  685. values[i] = i;
  686. }
  687. }
  688. bool ExecutionTest::ExecutionTestClassSetup() {
  689. HRESULT hr = EnableExperimentalMode();
  690. if (FAILED(hr)) {
  691. LogCommentFmt(L"Unable to enable shader experimental mode - 0x%08x.", hr);
  692. }
  693. else if (hr == S_FALSE) {
  694. LogCommentFmt(L"Experimental mode not enabled.");
  695. }
  696. else {
  697. LogCommentFmt(L"Experimental mode enabled.");
  698. }
  699. hr = EnableDebugLayer();
  700. if (FAILED(hr)) {
  701. LogCommentFmt(L"Unable to enable debug layer - 0x%08x.", hr);
  702. }
  703. else {
  704. LogCommentFmt(L"Debug layer enabled.");
  705. }
  706. return true;
  707. }
  708. void ExecutionTest::RunRWByteBufferComputeTest(ID3D12Device *pDevice, LPCSTR pShader, std::vector<uint32_t> &values) {
  709. static const int DispatchGroupX = 1;
  710. static const int DispatchGroupY = 1;
  711. static const int DispatchGroupZ = 1;
  712. CComPtr<ID3D12GraphicsCommandList> pCommandList;
  713. CComPtr<ID3D12CommandQueue> pCommandQueue;
  714. CComPtr<ID3D12DescriptorHeap> pUavHeap;
  715. CComPtr<ID3D12CommandAllocator> pCommandAllocator;
  716. UINT uavDescriptorSize;
  717. FenceObj FO;
  718. const size_t valueSizeInBytes = values.size() * sizeof(uint32_t);
  719. CreateComputeCommandQueue(pDevice, L"RunRWByteBufferComputeTest Command Queue", &pCommandQueue);
  720. InitFenceObj(pDevice, &FO);
  721. // Describe and create a UAV descriptor heap.
  722. D3D12_DESCRIPTOR_HEAP_DESC heapDesc = {};
  723. heapDesc.NumDescriptors = 1;
  724. heapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
  725. heapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
  726. VERIFY_SUCCEEDED(pDevice->CreateDescriptorHeap(&heapDesc, IID_PPV_ARGS(&pUavHeap)));
  727. uavDescriptorSize = pDevice->GetDescriptorHandleIncrementSize(heapDesc.Type);
  728. // Create root signature.
  729. CComPtr<ID3D12RootSignature> pRootSignature;
  730. {
  731. CD3DX12_DESCRIPTOR_RANGE ranges[1];
  732. ranges[0].Init(D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 1, 0, 0, 0);
  733. CD3DX12_ROOT_PARAMETER rootParameters[1];
  734. rootParameters[0].InitAsDescriptorTable(1, &ranges[0], D3D12_SHADER_VISIBILITY_ALL);
  735. CD3DX12_ROOT_SIGNATURE_DESC rootSignatureDesc;
  736. rootSignatureDesc.Init(_countof(rootParameters), rootParameters, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE);
  737. CreateRootSignatureFromDesc(pDevice, &rootSignatureDesc, &pRootSignature);
  738. }
  739. // Create pipeline state object.
  740. CComPtr<ID3D12PipelineState> pComputeState;
  741. CreateComputePSO(pDevice, pRootSignature, pShader, &pComputeState);
  742. // Create a command allocator and list for compute.
  743. VERIFY_SUCCEEDED(pDevice->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COMPUTE, IID_PPV_ARGS(&pCommandAllocator)));
  744. VERIFY_SUCCEEDED(pDevice->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COMPUTE, pCommandAllocator, pComputeState, IID_PPV_ARGS(&pCommandList)));
  745. pCommandList->SetName(L"ExecutionTest::RunRWByteButterComputeTest Command List");
  746. // Set up UAV resource.
  747. CComPtr<ID3D12Resource> pUavResource;
  748. CComPtr<ID3D12Resource> pReadBuffer;
  749. CComPtr<ID3D12Resource> pUploadResource;
  750. CreateTestUavs(pDevice, pCommandList, values.data(), valueSizeInBytes, &pUavResource, &pReadBuffer, &pUploadResource);
  751. VERIFY_SUCCEEDED(pUavResource->SetName(L"RunRWByteBufferComputeText UAV"));
  752. VERIFY_SUCCEEDED(pReadBuffer->SetName(L"RunRWByteBufferComputeText UAV Read Buffer"));
  753. VERIFY_SUCCEEDED(pUploadResource->SetName(L"RunRWByteBufferComputeText UAV Upload Buffer"));
  754. // Close the command list and execute it to perform the GPU setup.
  755. pCommandList->Close();
  756. ExecuteCommandList(pCommandQueue, pCommandList);
  757. WaitForSignal(pCommandQueue, FO);
  758. VERIFY_SUCCEEDED(pCommandAllocator->Reset());
  759. VERIFY_SUCCEEDED(pCommandList->Reset(pCommandAllocator, pComputeState));
  760. // Run the compute shader and copy the results back to readable memory.
  761. {
  762. D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc = {};
  763. uavDesc.Format = DXGI_FORMAT_R32_TYPELESS;
  764. uavDesc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER;
  765. uavDesc.Buffer.FirstElement = 0;
  766. uavDesc.Buffer.NumElements = values.size();
  767. uavDesc.Buffer.StructureByteStride = 0;
  768. uavDesc.Buffer.CounterOffsetInBytes = 0;
  769. uavDesc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW;
  770. CD3DX12_CPU_DESCRIPTOR_HANDLE uavHandle(pUavHeap->GetCPUDescriptorHandleForHeapStart());
  771. CD3DX12_GPU_DESCRIPTOR_HANDLE uavHandleGpu(pUavHeap->GetGPUDescriptorHandleForHeapStart());
  772. pDevice->CreateUnorderedAccessView(pUavResource, nullptr, &uavDesc, uavHandle);
  773. SetDescriptorHeap(pCommandList, pUavHeap);
  774. pCommandList->SetComputeRootSignature(pRootSignature);
  775. pCommandList->SetComputeRootDescriptorTable(0, uavHandleGpu);
  776. }
  777. pCommandList->Dispatch(DispatchGroupX, DispatchGroupY, DispatchGroupZ);
  778. RecordTransitionBarrier(pCommandList, pUavResource, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE);
  779. pCommandList->CopyResource(pReadBuffer, pUavResource);
  780. pCommandList->Close();
  781. ExecuteCommandList(pCommandQueue, pCommandList);
  782. WaitForSignal(pCommandQueue, FO);
  783. {
  784. MappedData mappedData(pReadBuffer, valueSizeInBytes);
  785. uint32_t *pData = (uint32_t *)mappedData.data();
  786. memcpy(values.data(), pData, valueSizeInBytes);
  787. }
  788. WaitForSignal(pCommandQueue, FO);
  789. }
  790. TEST_F(ExecutionTest, BasicComputeTest) {
  791. //
  792. // BasicComputeTest is a simple compute shader that can be used as the basis
  793. // for more interesting compute execution tests.
  794. // The HLSL is compatible with shader models <=5.1 to allow using the DXBC
  795. // rendering code paths for comparison.
  796. //
  797. static const char pShader[] =
  798. "RWByteAddressBuffer g_bab : register(u0);\r\n"
  799. "[numthreads(8,8,1)]\r\n"
  800. "void main(uint GI : SV_GroupIndex) {"
  801. " uint addr = GI * 4;\r\n"
  802. " uint val = g_bab.Load(addr);\r\n"
  803. " DeviceMemoryBarrierWithGroupSync();\r\n"
  804. " g_bab.Store(addr, val + 1);\r\n"
  805. "}";
  806. static const int NumtheadsX = 8;
  807. static const int NumtheadsY = 8;
  808. static const int NumtheadsZ = 1;
  809. static const int ThreadsPerGroup = NumtheadsX * NumtheadsY * NumtheadsZ;
  810. static const int DispatchGroupCount = 1;
  811. CComPtr<ID3D12Device> pDevice;
  812. if (!CreateDevice(&pDevice))
  813. return;
  814. std::vector<uint32_t> values;
  815. SetupComputeValuePattern(values, ThreadsPerGroup * DispatchGroupCount);
  816. VERIFY_ARE_EQUAL(values[0], 0);
  817. RunRWByteBufferComputeTest(pDevice, pShader, values);
  818. VERIFY_ARE_EQUAL(values[0], 1);
  819. }
  820. TEST_F(ExecutionTest, BasicTriangleTest) {
  821. static const UINT FrameCount = 2;
  822. static const UINT m_width = 320;
  823. static const UINT m_height = 200;
  824. static const float m_aspectRatio = static_cast<float>(m_width) / static_cast<float>(m_height);
  825. struct Vertex {
  826. XMFLOAT3 position;
  827. XMFLOAT4 color;
  828. };
  829. // Pipeline objects.
  830. CComPtr<ID3D12Device> pDevice;
  831. CComPtr<ID3D12Resource> pRenderTarget;
  832. CComPtr<ID3D12CommandAllocator> pCommandAllocator;
  833. CComPtr<ID3D12CommandQueue> pCommandQueue;
  834. CComPtr<ID3D12RootSignature> pRootSig;
  835. CComPtr<ID3D12DescriptorHeap> pRtvHeap;
  836. CComPtr<ID3D12PipelineState> pPipelineState;
  837. CComPtr<ID3D12GraphicsCommandList> pCommandList;
  838. CComPtr<ID3D12Resource> pReadBuffer;
  839. UINT rtvDescriptorSize;
  840. CComPtr<ID3D12Resource> pVertexBuffer;
  841. D3D12_VERTEX_BUFFER_VIEW vertexBufferView;
  842. // Synchronization objects.
  843. FenceObj FO;
  844. // Shaders.
  845. static const char pShaders[] =
  846. "struct PSInput {\r\n"
  847. " float4 position : SV_POSITION;\r\n"
  848. " float4 color : COLOR;\r\n"
  849. "};\r\n\r\n"
  850. "PSInput VSMain(float4 position : POSITION, float4 color : COLOR) {\r\n"
  851. " PSInput result;\r\n"
  852. "\r\n"
  853. " result.position = position;\r\n"
  854. " result.color = color;\r\n"
  855. " return result;\r\n"
  856. "}\r\n\r\n"
  857. "float4 PSMain(PSInput input) : SV_TARGET {\r\n"
  858. " return 1; //input.color;\r\n"
  859. "};\r\n";
  860. if (!CreateDevice(&pDevice))
  861. return;
  862. struct BasicTestChecker {
  863. CComPtr<ID3D12Device> m_pDevice;
  864. CComPtr<ID3D12InfoQueue> m_pInfoQueue;
  865. bool m_OK = false;
  866. void SetOK(bool value) { m_OK = value; }
  867. BasicTestChecker(ID3D12Device *pDevice) : m_pDevice(pDevice) {
  868. if (FAILED(m_pDevice.QueryInterface(&m_pInfoQueue)))
  869. return;
  870. m_pInfoQueue->PushEmptyStorageFilter();
  871. m_pInfoQueue->PushEmptyRetrievalFilter();
  872. }
  873. ~BasicTestChecker() {
  874. if (!m_OK && m_pInfoQueue != nullptr) {
  875. UINT64 count = m_pInfoQueue->GetNumStoredMessages();
  876. bool invalidBytecodeFound = false;
  877. CAtlArray<BYTE> m_pBytes;
  878. for (UINT64 i = 0; i < count; ++i) {
  879. SIZE_T len = 0;
  880. if (FAILED(m_pInfoQueue->GetMessageA(i, nullptr, &len)))
  881. continue;
  882. if (m_pBytes.GetCount() < len && !m_pBytes.SetCount(len))
  883. continue;
  884. D3D12_MESSAGE *pMsg = (D3D12_MESSAGE *)m_pBytes.GetData();
  885. if (FAILED(m_pInfoQueue->GetMessageA(i, pMsg, &len)))
  886. continue;
  887. if (pMsg->ID == D3D12_MESSAGE_ID_CREATEVERTEXSHADER_INVALIDSHADERBYTECODE ||
  888. pMsg->ID == D3D12_MESSAGE_ID_CREATEPIXELSHADER_INVALIDSHADERBYTECODE) {
  889. invalidBytecodeFound = true;
  890. break;
  891. }
  892. }
  893. if (invalidBytecodeFound) {
  894. LogCommentFmt(L"%s", L"Found an invalid bytecode message. This "
  895. L"typically indicates that experimental mode "
  896. L"is not set up properly.");
  897. if (!GetTestParamBool(L"ExperimentalShaders")) {
  898. LogCommentFmt(L"Note that the ExperimentalShaders test parameter isn't set.");
  899. }
  900. }
  901. else {
  902. LogCommentFmt(L"Did not find corrupt pixel or vertex shaders in "
  903. L"queue - dumping complete queue.");
  904. WriteInfoQueueMessages(nullptr, OutputFn, m_pInfoQueue);
  905. }
  906. }
  907. }
  908. static void __stdcall OutputFn(void *pCtx, const wchar_t *pMsg) {
  909. LogCommentFmt(L"%s", pMsg);
  910. }
  911. };
  912. BasicTestChecker BTC(pDevice);
  913. {
  914. InitFenceObj(pDevice, &FO);
  915. CreateRtvDescriptorHeap(pDevice, FrameCount, &pRtvHeap, &rtvDescriptorSize);
  916. CreateRenderTargetAndReadback(pDevice, pRtvHeap, m_width, m_height, &pRenderTarget, &pReadBuffer);
  917. // Create an empty root signature.
  918. CD3DX12_ROOT_SIGNATURE_DESC rootSignatureDesc;
  919. rootSignatureDesc.Init(
  920. 0, nullptr, 0, nullptr,
  921. D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT);
  922. CreateRootSignatureFromDesc(pDevice, &rootSignatureDesc, &pRootSig);
  923. // Create the pipeline state, which includes compiling and loading shaders.
  924. // Define the vertex input layout.
  925. D3D12_INPUT_ELEMENT_DESC inputElementDescs[] = {
  926. {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0,
  927. D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0},
  928. {"COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12,
  929. D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0}};
  930. D3D12_INPUT_LAYOUT_DESC InputLayout = { inputElementDescs, _countof(inputElementDescs) };
  931. CreateGraphicsPSO(pDevice, &InputLayout, pRootSig, pShaders, &pPipelineState);
  932. CreateGraphicsCommandQueueAndList(pDevice, &pCommandQueue,
  933. &pCommandAllocator, &pCommandList,
  934. pPipelineState);
  935. // Define the geometry for a triangle.
  936. Vertex triangleVertices[] = {
  937. { { 0.0f, 0.25f * m_aspectRatio, 0.0f },{ 1.0f, 0.0f, 0.0f, 1.0f } },
  938. { { 0.25f, -0.25f * m_aspectRatio, 0.0f },{ 0.0f, 1.0f, 0.0f, 1.0f } },
  939. { { -0.25f, -0.25f * m_aspectRatio, 0.0f },{ 0.0f, 0.0f, 1.0f, 1.0f } } };
  940. CreateVertexBuffer(pDevice, triangleVertices, &pVertexBuffer, &vertexBufferView);
  941. WaitForSignal(pCommandQueue, FO);
  942. }
  943. // Render and execute the command list.
  944. RecordRenderAndReadback(pCommandList, pRtvHeap, rtvDescriptorSize, 1,
  945. &vertexBufferView, pRootSig, pRenderTarget,
  946. pReadBuffer);
  947. VERIFY_SUCCEEDED(pCommandList->Close());
  948. ExecuteCommandList(pCommandQueue, pCommandList);
  949. // Wait for previous frame.
  950. WaitForSignal(pCommandQueue, FO);
  951. // At this point, we've verified that execution succeeded with DXIL.
  952. BTC.SetOK(true);
  953. // Read back to CPU and examine contents.
  954. {
  955. MappedData data(pReadBuffer, m_width * m_height * 4);
  956. const uint32_t *pPixels = (uint32_t *)data.data();
  957. if (SaveImages()) {
  958. SavePixelsToFile(pPixels, DXGI_FORMAT_R8G8B8A8_UNORM, m_width, m_height, L"basic.bmp");
  959. }
  960. uint32_t top = pPixels[m_width / 2]; // Top center.
  961. uint32_t mid = pPixels[m_width / 2 + m_width * (m_height / 2)]; // Middle center.
  962. VERIFY_ARE_EQUAL(0xff663300, top); // clear color
  963. VERIFY_ARE_EQUAL(0xffffffff, mid); // white
  964. }
  965. }
  966. TEST_F(ExecutionTest, Int64Test) {
  967. static const char pShader[] =
  968. "RWByteAddressBuffer g_bab : register(u0);\r\n"
  969. "[numthreads(8,8,1)]\r\n"
  970. "void main(uint GI : SV_GroupIndex) {"
  971. " uint addr = GI * 4;\r\n"
  972. " uint val = g_bab.Load(addr);\r\n"
  973. " uint64_t u64 = val;\r\n"
  974. " u64 *= val;\r\n"
  975. " g_bab.Store(addr, (uint)(u64 >> 32));\r\n"
  976. "}";
  977. static const int NumtheadsX = 8;
  978. static const int NumtheadsY = 8;
  979. static const int NumtheadsZ = 1;
  980. static const int ThreadsPerGroup = NumtheadsX * NumtheadsY * NumtheadsZ;
  981. static const int DispatchGroupCount = 1;
  982. CComPtr<ID3D12Device> pDevice;
  983. if (!CreateDevice(&pDevice))
  984. return;
  985. if (!DoesDeviceSupportInt64(pDevice)) {
  986. // Optional feature, so it's correct to not support it if declared as such.
  987. WEX::Logging::Log::Comment(L"Device does not support int64 operations.");
  988. return;
  989. }
  990. std::vector<uint32_t> values;
  991. SetupComputeValuePattern(values, ThreadsPerGroup * DispatchGroupCount);
  992. VERIFY_ARE_EQUAL(values[0], 0);
  993. RunRWByteBufferComputeTest(pDevice, pShader, values);
  994. VERIFY_ARE_EQUAL(values[0], 0);
  995. }
  996. TEST_F(ExecutionTest, SignTest) {
  997. static const char pShader[] =
  998. "RWByteAddressBuffer g_bab : register(u0);\r\n"
  999. "[numthreads(8,1,1)]\r\n"
  1000. "void main(uint GI : SV_GroupIndex) {"
  1001. " uint addr = GI * 4;\r\n"
  1002. " int val = g_bab.Load(addr);\r\n"
  1003. " g_bab.Store(addr, (uint)(sign(val)));\r\n"
  1004. "}";
  1005. static const int NumtheadsX = 8;
  1006. static const int NumtheadsY = 1;
  1007. static const int NumtheadsZ = 1;
  1008. static const int ThreadsPerGroup = NumtheadsX * NumtheadsY * NumtheadsZ;
  1009. static const int DispatchGroupCount = 1;
  1010. CComPtr<ID3D12Device> pDevice;
  1011. if (!CreateDevice(&pDevice))
  1012. return;
  1013. std::vector<uint32_t> values = { (uint32_t)-3, (uint32_t)-2, (uint32_t)-1, 0, 1, 2, 3, 4};
  1014. RunRWByteBufferComputeTest(pDevice, pShader, values);
  1015. VERIFY_ARE_EQUAL(values[0], -1);
  1016. VERIFY_ARE_EQUAL(values[1], -1);
  1017. VERIFY_ARE_EQUAL(values[2], -1);
  1018. VERIFY_ARE_EQUAL(values[3], 0);
  1019. VERIFY_ARE_EQUAL(values[4], 1);
  1020. VERIFY_ARE_EQUAL(values[5], 1);
  1021. VERIFY_ARE_EQUAL(values[6], 1);
  1022. VERIFY_ARE_EQUAL(values[7], 1);
  1023. }
  1024. TEST_F(ExecutionTest, WaveIntrinsicsTest) {
  1025. WEX::TestExecution::SetVerifyOutput verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  1026. struct PerThreadData {
  1027. uint32_t id, flags, laneIndex, laneCount, firstLaneId, preds, firstlaneX, lane1X;
  1028. uint32_t allBC, allSum, allProd, allAND, allOR, allXOR, allMin, allMax;
  1029. uint32_t pfBC, pfSum, pfProd;
  1030. uint32_t ballot[4];
  1031. uint32_t diver; // divergent value, used in calculation
  1032. int32_t i_diver; // divergent value, used in calculation
  1033. int32_t i_allMax, i_allMin, i_allSum, i_allProd;
  1034. int32_t i_pfSum, i_pfProd;
  1035. };
  1036. static const char pShader[] =
  1037. WAVE_INTRINSIC_DXBC_GUARD
  1038. "struct PerThreadData {\r\n"
  1039. " uint id, flags, laneIndex, laneCount, firstLaneId, preds, firstlaneX, lane1X;\r\n"
  1040. " uint allBC, allSum, allProd, allAND, allOR, allXOR, allMin, allMax;\r\n"
  1041. " uint pfBC, pfSum, pfProd;\r\n"
  1042. " uint4 ballot;\r\n"
  1043. " uint diver;\r\n"
  1044. " int i_diver;\r\n"
  1045. " int i_allMax, i_allMin, i_allSum, i_allProd;\r\n"
  1046. " int i_pfSum, i_pfProd;\r\n"
  1047. "};\r\n"
  1048. "RWStructuredBuffer<PerThreadData> g_sb : register(u0);\r\n"
  1049. "[numthreads(8,8,1)]\r\n"
  1050. "void main(uint GI : SV_GroupIndex, uint3 GTID : SV_GroupThreadID) {"
  1051. " PerThreadData pts = g_sb[GI];\r\n"
  1052. " uint diver = GTID.x + 2;\r\n"
  1053. " pts.diver = diver;\r\n"
  1054. " pts.flags = 0;\r\n"
  1055. " pts.preds = 0;\r\n"
  1056. " if (WaveIsFirstLane()) pts.flags |= 1;\r\n"
  1057. " pts.laneIndex = WaveGetLaneIndex();\r\n"
  1058. " pts.laneCount = WaveGetLaneCount();\r\n"
  1059. " pts.firstLaneId = WaveReadLaneFirst(pts.id);\r\n"
  1060. " pts.preds |= ((WaveActiveAnyTrue(diver == 1) ? 1 : 0) << 0);\r\n"
  1061. " pts.preds |= ((WaveActiveAllTrue(diver == 1) ? 1 : 0) << 1);\r\n"
  1062. " pts.preds |= ((WaveActiveAllEqual(diver) ? 1 : 0) << 2);\r\n"
  1063. " pts.preds |= ((WaveActiveAllEqual(GTID.z) ? 1 : 0) << 3);\r\n"
  1064. " pts.preds |= ((WaveActiveAllEqual(WaveReadLaneFirst(diver)) ? 1 : 0) << 4);\r\n"
  1065. " pts.ballot = WaveActiveBallot(diver > 3);\r\n"
  1066. " pts.firstlaneX = WaveReadLaneFirst(GTID.x);\r\n"
  1067. " pts.lane1X = WaveReadLaneAt(GTID.x, 1);\r\n"
  1068. "\r\n"
  1069. " pts.allBC = WaveActiveCountBits(diver > 3);\r\n"
  1070. " pts.allSum = WaveActiveSum(diver);\r\n"
  1071. " pts.allProd = WaveActiveProduct(diver);\r\n"
  1072. " pts.allAND = WaveActiveBitAnd(diver);\r\n"
  1073. " pts.allOR = WaveActiveBitOr(diver);\r\n"
  1074. " pts.allXOR = WaveActiveBitXor(diver);\r\n"
  1075. " pts.allMin = WaveActiveMin(diver);\r\n"
  1076. " pts.allMax = WaveActiveMax(diver);\r\n"
  1077. "\r\n"
  1078. " pts.pfBC = WavePrefixCountBits(diver > 3);\r\n"
  1079. " pts.pfSum = WavePrefixSum(diver);\r\n"
  1080. " pts.pfProd = WavePrefixProduct(diver);\r\n"
  1081. "\r\n"
  1082. " int i_diver = pts.i_diver;\r\n"
  1083. " pts.i_allMax = WaveActiveMax(i_diver);\r\n"
  1084. " pts.i_allMin = WaveActiveMin(i_diver);\r\n"
  1085. " pts.i_allSum = WaveActiveSum(i_diver);\r\n"
  1086. " pts.i_allProd = WaveActiveProduct(i_diver);\r\n"
  1087. " pts.i_pfSum = WavePrefixSum(i_diver);\r\n"
  1088. " pts.i_pfProd = WavePrefixProduct(i_diver);\r\n"
  1089. "\r\n"
  1090. " g_sb[GI] = pts;\r\n"
  1091. "}";
  1092. static const int NumtheadsX = 8;
  1093. static const int NumtheadsY = 8;
  1094. static const int NumtheadsZ = 1;
  1095. static const int ThreadsPerGroup = NumtheadsX * NumtheadsY * NumtheadsZ;
  1096. static const int DispatchGroupCount = 1;
  1097. CComPtr<ID3D12Device> pDevice;
  1098. if (!CreateDevice(&pDevice))
  1099. return;
  1100. if (!DoesDeviceSupportWaveOps(pDevice)) {
  1101. // Optional feature, so it's correct to not support it if declared as such.
  1102. WEX::Logging::Log::Comment(L"Device does not support wave operations.");
  1103. return;
  1104. }
  1105. std::vector<PerThreadData> values;
  1106. values.resize(ThreadsPerGroup * DispatchGroupCount);
  1107. for (size_t i = 0; i < values.size(); ++i) {
  1108. memset(&values[i], 0, sizeof(PerThreadData));
  1109. values[i].id = i;
  1110. values[i].i_diver = (int)i;
  1111. values[i].i_diver *= (i % 2) ? 1 : -1;
  1112. }
  1113. static const int DispatchGroupX = 1;
  1114. static const int DispatchGroupY = 1;
  1115. static const int DispatchGroupZ = 1;
  1116. CComPtr<ID3D12GraphicsCommandList> pCommandList;
  1117. CComPtr<ID3D12CommandQueue> pCommandQueue;
  1118. CComPtr<ID3D12DescriptorHeap> pUavHeap;
  1119. CComPtr<ID3D12CommandAllocator> pCommandAllocator;
  1120. UINT uavDescriptorSize;
  1121. FenceObj FO;
  1122. bool dxbc = UseDxbc();
  1123. const size_t valueSizeInBytes = values.size() * sizeof(PerThreadData);
  1124. CreateComputeCommandQueue(pDevice, L"WaveIntrinsicsTest Command Queue", &pCommandQueue);
  1125. InitFenceObj(pDevice, &FO);
  1126. // Describe and create a UAV descriptor heap.
  1127. D3D12_DESCRIPTOR_HEAP_DESC heapDesc = {};
  1128. heapDesc.NumDescriptors = 1;
  1129. heapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
  1130. heapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
  1131. VERIFY_SUCCEEDED(pDevice->CreateDescriptorHeap(&heapDesc, IID_PPV_ARGS(&pUavHeap)));
  1132. uavDescriptorSize = pDevice->GetDescriptorHandleIncrementSize(heapDesc.Type);
  1133. // Create root signature.
  1134. CComPtr<ID3D12RootSignature> pRootSignature;
  1135. {
  1136. CD3DX12_DESCRIPTOR_RANGE ranges[1];
  1137. ranges[0].Init(D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 1, 0, 0, 0);
  1138. CD3DX12_ROOT_PARAMETER rootParameters[1];
  1139. rootParameters[0].InitAsDescriptorTable(1, &ranges[0], D3D12_SHADER_VISIBILITY_ALL);
  1140. CD3DX12_ROOT_SIGNATURE_DESC rootSignatureDesc;
  1141. rootSignatureDesc.Init(_countof(rootParameters), rootParameters, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE);
  1142. CComPtr<ID3DBlob> signature;
  1143. CComPtr<ID3DBlob> error;
  1144. VERIFY_SUCCEEDED(D3D12SerializeRootSignature(&rootSignatureDesc, D3D_ROOT_SIGNATURE_VERSION_1, &signature, &error));
  1145. VERIFY_SUCCEEDED(pDevice->CreateRootSignature(0, signature->GetBufferPointer(), signature->GetBufferSize(), IID_PPV_ARGS(&pRootSignature)));
  1146. }
  1147. // Create pipeline state object.
  1148. CComPtr<ID3D12PipelineState> pComputeState;
  1149. CreateComputePSO(pDevice, pRootSignature, pShader, &pComputeState);
  1150. // Create a command allocator and list for compute.
  1151. VERIFY_SUCCEEDED(pDevice->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COMPUTE, IID_PPV_ARGS(&pCommandAllocator)));
  1152. VERIFY_SUCCEEDED(pDevice->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COMPUTE, pCommandAllocator, pComputeState, IID_PPV_ARGS(&pCommandList)));
  1153. // Set up UAV resource.
  1154. CComPtr<ID3D12Resource> pUavResource;
  1155. CComPtr<ID3D12Resource> pReadBuffer;
  1156. CComPtr<ID3D12Resource> pUploadResource;
  1157. CreateTestUavs(pDevice, pCommandList, values.data(), valueSizeInBytes, &pUavResource, &pReadBuffer, &pUploadResource);
  1158. // Close the command list and execute it to perform the GPU setup.
  1159. pCommandList->Close();
  1160. ExecuteCommandList(pCommandQueue, pCommandList);
  1161. WaitForSignal(pCommandQueue, FO);
  1162. VERIFY_SUCCEEDED(pCommandAllocator->Reset());
  1163. VERIFY_SUCCEEDED(pCommandList->Reset(pCommandAllocator, pComputeState));
  1164. // Run the compute shader and copy the results back to readable memory.
  1165. {
  1166. D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc = {};
  1167. uavDesc.Format = DXGI_FORMAT_UNKNOWN;
  1168. uavDesc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER;
  1169. uavDesc.Buffer.FirstElement = 0;
  1170. uavDesc.Buffer.NumElements = values.size();
  1171. uavDesc.Buffer.StructureByteStride = sizeof(PerThreadData);
  1172. uavDesc.Buffer.CounterOffsetInBytes = 0;
  1173. uavDesc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_NONE;
  1174. CD3DX12_CPU_DESCRIPTOR_HANDLE uavHandle(pUavHeap->GetCPUDescriptorHandleForHeapStart());
  1175. CD3DX12_GPU_DESCRIPTOR_HANDLE uavHandleGpu(pUavHeap->GetGPUDescriptorHandleForHeapStart());
  1176. pDevice->CreateUnorderedAccessView(pUavResource, nullptr, &uavDesc, uavHandle);
  1177. SetDescriptorHeap(pCommandList, pUavHeap);
  1178. pCommandList->SetComputeRootSignature(pRootSignature);
  1179. pCommandList->SetComputeRootDescriptorTable(0, uavHandleGpu);
  1180. }
  1181. pCommandList->Dispatch(DispatchGroupX, DispatchGroupY, DispatchGroupZ);
  1182. RecordTransitionBarrier(pCommandList, pUavResource, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE);
  1183. pCommandList->CopyResource(pReadBuffer, pUavResource);
  1184. pCommandList->Close();
  1185. ExecuteCommandList(pCommandQueue, pCommandList);
  1186. WaitForSignal(pCommandQueue, FO);
  1187. {
  1188. MappedData mappedData(pReadBuffer, valueSizeInBytes);
  1189. PerThreadData *pData = (PerThreadData *)mappedData.data();
  1190. memcpy(values.data(), pData, valueSizeInBytes);
  1191. // Gather some general data.
  1192. // The 'firstLaneId' captures a unique number per first-lane per wave.
  1193. // Counting the number distinct firstLaneIds gives us the number of waves.
  1194. std::vector<uint32_t> firstLaneIds;
  1195. for (size_t i = 0; i < values.size(); ++i) {
  1196. PerThreadData &pts = values[i];
  1197. uint32_t firstLaneId = pts.firstLaneId;
  1198. if (!contains(firstLaneIds, firstLaneId)) {
  1199. firstLaneIds.push_back(firstLaneId);
  1200. }
  1201. }
  1202. // Waves should cover 4 threads or more.
  1203. LogCommentFmt(L"Found %u distinct lane ids: %u", firstLaneIds.size());
  1204. if (!dxbc) {
  1205. VERIFY_IS_GREATER_THAN_OR_EQUAL(values.size() / 4, firstLaneIds.size());
  1206. }
  1207. // Now, group threads into waves.
  1208. std::map<uint32_t, std::unique_ptr<std::vector<PerThreadData *> > > waves;
  1209. for (size_t i = 0; i < firstLaneIds.size(); ++i) {
  1210. waves[firstLaneIds[i]] = std::make_unique<std::vector<PerThreadData *> >();
  1211. }
  1212. for (size_t i = 0; i < values.size(); ++i) {
  1213. PerThreadData &pts = values[i];
  1214. std::unique_ptr<std::vector<PerThreadData *> > &wave = waves[pts.firstLaneId];
  1215. wave->push_back(&pts);
  1216. }
  1217. // Verify that all the wave values are coherent across the wave.
  1218. for (size_t i = 0; i < values.size(); ++i) {
  1219. PerThreadData &pts = values[i];
  1220. std::unique_ptr<std::vector<PerThreadData *> > &wave = waves[pts.firstLaneId];
  1221. // Sort the lanes by increasing lane ID.
  1222. struct LaneIdOrderPred {
  1223. bool operator()(PerThreadData *a, PerThreadData *b) {
  1224. return a->laneIndex < b->laneIndex;
  1225. }
  1226. };
  1227. std::sort(wave.get()->begin(), wave.get()->end(), LaneIdOrderPred());
  1228. // Verify some interesting properties of the first lane.
  1229. uint32_t pfBC, pfSum, pfProd;
  1230. int32_t i_pfSum, i_pfProd;
  1231. int32_t i_allMax, i_allMin;
  1232. {
  1233. PerThreadData *ptdFirst = wave->front();
  1234. VERIFY_IS_TRUE(0 != (ptdFirst->flags & 1)); // FirstLane sets this bit.
  1235. VERIFY_IS_TRUE(0 == ptdFirst->pfBC);
  1236. VERIFY_IS_TRUE(0 == ptdFirst->pfSum);
  1237. VERIFY_IS_TRUE(1 == ptdFirst->pfProd);
  1238. VERIFY_IS_TRUE(0 == ptdFirst->i_pfSum);
  1239. VERIFY_IS_TRUE(1 == ptdFirst->i_pfProd);
  1240. pfBC = (ptdFirst->diver > 3) ? 1 : 0;
  1241. pfSum = ptdFirst->diver;
  1242. pfProd = ptdFirst->diver;
  1243. i_pfSum = ptdFirst->i_diver;
  1244. i_pfProd = ptdFirst->i_diver;
  1245. i_allMax = i_allMin = ptdFirst->i_diver;
  1246. }
  1247. // Calculate values which take into consideration all lanes.
  1248. uint32_t preds = 0;
  1249. preds |= 1 << 1; // AllTrue starts true, switches to false if needed.
  1250. preds |= 1 << 2; // AllEqual starts true, switches to false if needed.
  1251. preds |= 1 << 3; // WaveActiveAllEqual(GTID.z) is always true
  1252. preds |= 1 << 4; // (WaveActiveAllEqual(WaveReadLaneFirst(diver)) is always true
  1253. uint32_t ballot[4] = { 0, 0, 0, 0 };
  1254. int32_t i_allSum = 0, i_allProd = 1;
  1255. for (size_t n = 0; n < wave->size(); ++n) {
  1256. std::vector<PerThreadData *> &lanes = *wave.get();
  1257. // pts.preds |= ((WaveActiveAnyTrue(diver == 1) ? 1 : 0) << 0);
  1258. if (lanes[n]->diver == 1) preds |= (1 << 0);
  1259. // pts.preds |= ((WaveActiveAllTrue(diver == 1) ? 1 : 0) << 1);
  1260. if (lanes[n]->diver != 1) preds &= ~(1 << 1);
  1261. // pts.preds |= ((WaveActiveAllEqual(diver) ? 1 : 0) << 2);
  1262. if (lanes[0]->diver != lanes[n]->diver) preds &= ~(1 << 2);
  1263. // pts.ballot = WaveActiveBallot(diver > 3);\r\n"
  1264. if (lanes[n]->diver > 3) {
  1265. // This is the uint4 result layout:
  1266. // .x -> bits 0 .. 31
  1267. // .y -> bits 32 .. 63
  1268. // .z -> bits 64 .. 95
  1269. // .w -> bits 96 ..127
  1270. uint32_t component = lanes[n]->laneIndex / 32;
  1271. uint32_t bit = lanes[n]->laneIndex % 32;
  1272. ballot[component] |= 1 << bit;
  1273. }
  1274. i_allMax = std::max(lanes[n]->i_diver, i_allMax);
  1275. i_allMin = std::min(lanes[n]->i_diver, i_allMin);
  1276. i_allProd *= lanes[n]->i_diver;
  1277. i_allSum += lanes[n]->i_diver;
  1278. }
  1279. for (size_t n = 1; n < wave->size(); ++n) {
  1280. // 'All' operations are uniform across the wave.
  1281. std::vector<PerThreadData *> &lanes = *wave.get();
  1282. VERIFY_IS_TRUE(0 == (lanes[n]->flags & 1)); // non-firstlanes do not set this bit
  1283. VERIFY_ARE_EQUAL(lanes[0]->allBC, lanes[n]->allBC);
  1284. VERIFY_ARE_EQUAL(lanes[0]->allSum, lanes[n]->allSum);
  1285. VERIFY_ARE_EQUAL(lanes[0]->allProd, lanes[n]->allProd);
  1286. VERIFY_ARE_EQUAL(lanes[0]->allAND, lanes[n]->allAND);
  1287. VERIFY_ARE_EQUAL(lanes[0]->allOR, lanes[n]->allOR);
  1288. VERIFY_ARE_EQUAL(lanes[0]->allXOR, lanes[n]->allXOR);
  1289. VERIFY_ARE_EQUAL(lanes[0]->allMin, lanes[n]->allMin);
  1290. VERIFY_ARE_EQUAL(lanes[0]->allMax, lanes[n]->allMax);
  1291. VERIFY_ARE_EQUAL(i_allMax, lanes[n]->i_allMax);
  1292. VERIFY_ARE_EQUAL(i_allMin, lanes[n]->i_allMin);
  1293. VERIFY_ARE_EQUAL(i_allProd, lanes[n]->i_allProd);
  1294. VERIFY_ARE_EQUAL(i_allSum, lanes[n]->i_allSum);
  1295. // first-lane reads and uniform reads are uniform across the wave.
  1296. VERIFY_ARE_EQUAL(lanes[0]->firstlaneX, lanes[n]->firstlaneX);
  1297. VERIFY_ARE_EQUAL(lanes[0]->lane1X, lanes[n]->lane1X);
  1298. // the lane count is uniform across the wave.
  1299. VERIFY_ARE_EQUAL(lanes[0]->laneCount, lanes[n]->laneCount);
  1300. // The predicates are uniform across the wave.
  1301. VERIFY_ARE_EQUAL(lanes[n]->preds, preds);
  1302. // the lane index is distinct per thread.
  1303. for (size_t prior = 0; prior < n; ++prior) {
  1304. VERIFY_ARE_NOT_EQUAL(lanes[prior]->laneIndex, lanes[n]->laneIndex);
  1305. }
  1306. // Ballot results are uniform across the wave.
  1307. VERIFY_ARE_EQUAL(0, memcmp(ballot, lanes[n]->ballot, sizeof(ballot)));
  1308. // Keep running total of prefix calculation. Prefix values are exclusive to
  1309. // the executing lane.
  1310. VERIFY_ARE_EQUAL(pfBC, lanes[n]->pfBC);
  1311. VERIFY_ARE_EQUAL(pfSum, lanes[n]->pfSum);
  1312. VERIFY_ARE_EQUAL(pfProd, lanes[n]->pfProd);
  1313. VERIFY_ARE_EQUAL(i_pfSum, lanes[n]->i_pfSum);
  1314. VERIFY_ARE_EQUAL(i_pfProd, lanes[n]->i_pfProd);
  1315. pfBC += (lanes[n]->diver > 3) ? 1 : 0;
  1316. pfSum += lanes[n]->diver;
  1317. pfProd *= lanes[n]->diver;
  1318. i_pfSum += lanes[n]->i_diver;
  1319. i_pfProd *= lanes[n]->i_diver;
  1320. }
  1321. // TODO: add divergent branching and verify that the otherwise uniform values properly diverge
  1322. }
  1323. // Compare each value of each per-thread element.
  1324. for (size_t i = 0; i < values.size(); ++i) {
  1325. PerThreadData &pts = values[i];
  1326. VERIFY_ARE_EQUAL(i, pts.id); // ID is unchanged.
  1327. }
  1328. }
  1329. }
  1330. TEST_F(ExecutionTest, WaveIntrinsicsInPSTest) {
  1331. WEX::TestExecution::SetVerifyOutput verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  1332. struct Vertex {
  1333. XMFLOAT3 position;
  1334. };
  1335. struct PerPixelData {
  1336. XMFLOAT4 position;
  1337. uint32_t id, flags, laneIndex, laneCount, firstLaneId, sum1;
  1338. uint32_t id0, id1, id2, id3;
  1339. uint32_t acrossX, acrossY, acrossDiag, quadActiveCount;
  1340. };
  1341. const UINT RTWidth = 128;
  1342. const UINT RTHeight = 128;
  1343. // Shaders.
  1344. static const char pShaders[] =
  1345. WAVE_INTRINSIC_DXBC_GUARD
  1346. "struct PSInput {\r\n"
  1347. " float4 position : SV_POSITION;\r\n"
  1348. "};\r\n\r\n"
  1349. "PSInput VSMain(float4 position : POSITION) {\r\n"
  1350. " PSInput result;\r\n"
  1351. "\r\n"
  1352. " result.position = position;\r\n"
  1353. " return result;\r\n"
  1354. "}\r\n\r\n"
  1355. "typedef uint uint32_t;\r\n"
  1356. "uint pos_to_id(float4 pos) { return pos.x * 128 + pos.y; }\r\n"
  1357. "struct PerPixelData {\r\n"
  1358. " float4 position;\r\n"
  1359. " uint32_t id, flags, laneIndex, laneCount, firstLaneId, sum1;\r\n"
  1360. " uint32_t id0, id1, id2, id3;\r\n"
  1361. " uint32_t acrossX, acrossY, acrossDiag, quadActiveCount;\r\n"
  1362. "};\r\n"
  1363. "AppendStructuredBuffer<PerPixelData> g_sb : register(u1);\r\n"
  1364. "float4 PSMain(PSInput input) : SV_TARGET {\r\n"
  1365. " uint one = 1;\r\n"
  1366. " PerPixelData d;\r\n"
  1367. " d.position = input.position;\r\n"
  1368. " d.id = pos_to_id(input.position);\r\n"
  1369. " d.flags = 0;\r\n"
  1370. " if (WaveIsFirstLane()) d.flags |= 1;\r\n"
  1371. " d.laneIndex = WaveGetLaneIndex();\r\n"
  1372. " d.laneCount = WaveGetLaneCount();\r\n"
  1373. " d.firstLaneId = WaveReadLaneFirst(d.id);\r\n"
  1374. " d.sum1 = WaveActiveSum(one);\r\n"
  1375. " d.id0 = QuadReadLaneAt(d.id, 0);\r\n"
  1376. " d.id1 = QuadReadLaneAt(d.id, 1);\r\n"
  1377. " d.id2 = QuadReadLaneAt(d.id, 2);\r\n"
  1378. " d.id3 = QuadReadLaneAt(d.id, 3);\r\n"
  1379. " d.acrossX = QuadReadAcrossX(d.id);\r\n"
  1380. " d.acrossY = QuadReadAcrossY(d.id);\r\n"
  1381. " d.acrossDiag = QuadReadAcrossDiagonal(d.id);\r\n"
  1382. " d.quadActiveCount = one + QuadReadAcrossX(one) + QuadReadAcrossY(one) + QuadReadAcrossDiagonal(one);\r\n"
  1383. " g_sb.Append(d);\r\n"
  1384. " return 1;\r\n"
  1385. "};\r\n";
  1386. CComPtr<ID3D12Device> pDevice;
  1387. CComPtr<ID3D12CommandQueue> pCommandQueue;
  1388. CComPtr<ID3D12DescriptorHeap> pUavHeap, pRtvHeap;
  1389. CComPtr<ID3D12CommandAllocator> pCommandAllocator;
  1390. CComPtr<ID3D12GraphicsCommandList> pCommandList;
  1391. CComPtr<ID3D12PipelineState> pPSO;
  1392. CComPtr<ID3D12Resource> pRenderTarget, pReadBuffer;
  1393. UINT uavDescriptorSize, rtvDescriptorSize;
  1394. CComPtr<ID3D12Resource> pVertexBuffer;
  1395. D3D12_VERTEX_BUFFER_VIEW vertexBufferView;
  1396. if (!CreateDevice(&pDevice))
  1397. return;
  1398. if (!DoesDeviceSupportWaveOps(pDevice)) {
  1399. // Optional feature, so it's correct to not support it if declared as such.
  1400. WEX::Logging::Log::Comment(L"Device does not support wave operations.");
  1401. return;
  1402. }
  1403. FenceObj FO;
  1404. InitFenceObj(pDevice, &FO);
  1405. // Describe and create a UAV descriptor heap.
  1406. D3D12_DESCRIPTOR_HEAP_DESC heapDesc = {};
  1407. heapDesc.NumDescriptors = 1;
  1408. heapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
  1409. heapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
  1410. VERIFY_SUCCEEDED(pDevice->CreateDescriptorHeap(&heapDesc, IID_PPV_ARGS(&pUavHeap)));
  1411. uavDescriptorSize = pDevice->GetDescriptorHandleIncrementSize(heapDesc.Type);
  1412. CreateRtvDescriptorHeap(pDevice, 1, &pRtvHeap, &rtvDescriptorSize);
  1413. CreateRenderTargetAndReadback(pDevice, pRtvHeap, RTHeight, RTWidth, &pRenderTarget, &pReadBuffer);
  1414. // Create root signature: one UAV.
  1415. CComPtr<ID3D12RootSignature> pRootSignature;
  1416. {
  1417. CD3DX12_DESCRIPTOR_RANGE ranges[1];
  1418. ranges[0].Init(D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 1, 1, 0, 0);
  1419. CD3DX12_ROOT_PARAMETER rootParameters[1];
  1420. rootParameters[0].InitAsDescriptorTable(1, &ranges[0], D3D12_SHADER_VISIBILITY_ALL);
  1421. CD3DX12_ROOT_SIGNATURE_DESC rootSignatureDesc;
  1422. rootSignatureDesc.Init(_countof(rootParameters), rootParameters, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT);
  1423. CreateRootSignatureFromDesc(pDevice, &rootSignatureDesc, &pRootSignature);
  1424. }
  1425. D3D12_INPUT_ELEMENT_DESC elementDesc[] = {
  1426. {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0,
  1427. D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0}};
  1428. D3D12_INPUT_LAYOUT_DESC InputLayout = {elementDesc, _countof(elementDesc)};
  1429. CreateGraphicsPSO(pDevice, &InputLayout, pRootSignature, pShaders, &pPSO);
  1430. CreateGraphicsCommandQueueAndList(pDevice, &pCommandQueue, &pCommandAllocator,
  1431. &pCommandList, pPSO);
  1432. // Single triangle covering half the target.
  1433. Vertex vertices[] = {
  1434. { { -1.0f, 1.0f, 0.0f } },
  1435. { { 1.0f, 1.0f, 0.0f } },
  1436. { { -1.0f, -1.0f, 0.0f } } };
  1437. const UINT TriangleCount = _countof(vertices) / 3;
  1438. CreateVertexBuffer(pDevice, vertices, &pVertexBuffer, &vertexBufferView);
  1439. bool dxbc = UseDxbc();
  1440. // Set up UAV resource.
  1441. std::vector<PerPixelData> values;
  1442. values.resize(RTWidth * RTHeight * 2);
  1443. UINT valueSizeInBytes = values.size() * sizeof(PerPixelData);
  1444. memset(values.data(), 0, valueSizeInBytes);
  1445. CComPtr<ID3D12Resource> pUavResource;
  1446. CComPtr<ID3D12Resource> pUavReadBuffer;
  1447. CComPtr<ID3D12Resource> pUploadResource;
  1448. CreateTestUavs(pDevice, pCommandList, values.data(), valueSizeInBytes, &pUavResource, &pUavReadBuffer, &pUploadResource);
  1449. // Set up the append counter resource.
  1450. CComPtr<ID3D12Resource> pUavCounterResource;
  1451. CComPtr<ID3D12Resource> pReadCounterBuffer;
  1452. CComPtr<ID3D12Resource> pUploadCounterResource;
  1453. BYTE zero[sizeof(UINT)] = { 0 };
  1454. CreateTestUavs(pDevice, pCommandList, zero, sizeof(zero), &pUavCounterResource, &pReadCounterBuffer, &pUploadCounterResource);
  1455. // Close the command list and execute it to perform the GPU setup.
  1456. pCommandList->Close();
  1457. ExecuteCommandList(pCommandQueue, pCommandList);
  1458. WaitForSignal(pCommandQueue, FO);
  1459. VERIFY_SUCCEEDED(pCommandAllocator->Reset());
  1460. VERIFY_SUCCEEDED(pCommandList->Reset(pCommandAllocator, pPSO));
  1461. pCommandList->SetGraphicsRootSignature(pRootSignature);
  1462. SetDescriptorHeap(pCommandList, pUavHeap);
  1463. {
  1464. D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc = {};
  1465. uavDesc.Format = DXGI_FORMAT_UNKNOWN;
  1466. uavDesc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER;
  1467. uavDesc.Buffer.FirstElement = 0;
  1468. uavDesc.Buffer.NumElements = values.size();
  1469. uavDesc.Buffer.StructureByteStride = sizeof(PerPixelData);
  1470. uavDesc.Buffer.CounterOffsetInBytes = 0;
  1471. uavDesc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_NONE;
  1472. CD3DX12_CPU_DESCRIPTOR_HANDLE uavHandle(pUavHeap->GetCPUDescriptorHandleForHeapStart());
  1473. CD3DX12_GPU_DESCRIPTOR_HANDLE uavHandleGpu(pUavHeap->GetGPUDescriptorHandleForHeapStart());
  1474. pDevice->CreateUnorderedAccessView(pUavResource, pUavCounterResource, &uavDesc, uavHandle);
  1475. pCommandList->SetGraphicsRootDescriptorTable(0, uavHandleGpu);
  1476. }
  1477. RecordRenderAndReadback(pCommandList, pRtvHeap, rtvDescriptorSize, TriangleCount, &vertexBufferView, nullptr, pRenderTarget, pReadBuffer);
  1478. RecordTransitionBarrier(pCommandList, pUavResource, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE);
  1479. RecordTransitionBarrier(pCommandList, pUavCounterResource, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE);
  1480. pCommandList->CopyResource(pUavReadBuffer, pUavResource);
  1481. pCommandList->CopyResource(pReadCounterBuffer, pUavCounterResource);
  1482. VERIFY_SUCCEEDED(pCommandList->Close());
  1483. LogCommentFmt(L"Rendering to %u by %u", RTWidth, RTHeight);
  1484. ExecuteCommandList(pCommandQueue, pCommandList);
  1485. WaitForSignal(pCommandQueue, FO);
  1486. {
  1487. MappedData data(pReadBuffer, RTWidth * RTHeight * 4);
  1488. const uint32_t *pPixels = (uint32_t *)data.data();
  1489. if (SaveImages()) {
  1490. SavePixelsToFile(pPixels, DXGI_FORMAT_R8G8B8A8_UNORM, RTWidth, RTHeight, L"psintrin.bmp");
  1491. }
  1492. }
  1493. uint32_t appendCount;
  1494. {
  1495. MappedData mappedData(pReadCounterBuffer, sizeof(uint32_t));
  1496. appendCount = *((uint32_t *)mappedData.data());
  1497. LogCommentFmt(L"%u elements in append buffer", appendCount);
  1498. }
  1499. {
  1500. MappedData mappedData(pUavReadBuffer, values.size());
  1501. PerPixelData *pData = (PerPixelData *)mappedData.data();
  1502. memcpy(values.data(), pData, valueSizeInBytes);
  1503. // DXBC is handy to test pipeline setup, but interesting functions are
  1504. // stubbed out, so there is no point in further validation.
  1505. if (dxbc)
  1506. return;
  1507. uint32_t maxActiveLaneCount = 0;
  1508. uint32_t maxLaneCount = 0;
  1509. for (uint32_t i = 0; i < appendCount; ++i) {
  1510. maxActiveLaneCount = std::max(maxActiveLaneCount, values[i].sum1);
  1511. maxLaneCount = std::max(maxLaneCount, values[i].laneCount);
  1512. }
  1513. uint32_t peerOfHelperLanes = 0;
  1514. for (uint32_t i = 0; i < appendCount; ++i) {
  1515. if (values[i].sum1 != maxActiveLaneCount) {
  1516. ++peerOfHelperLanes;
  1517. }
  1518. }
  1519. LogCommentFmt(
  1520. L"Found: %u threads. Waves reported up to %u total lanes, up "
  1521. L"to %u active lanes, and %u threads had helper/inactive lanes.",
  1522. appendCount, maxLaneCount, maxActiveLaneCount, peerOfHelperLanes);
  1523. // Group threads into quad invocations.
  1524. uint32_t singlePixelCount = 0;
  1525. uint32_t multiPixelCount = 0;
  1526. std::unordered_set<uint32_t> ids;
  1527. std::multimap<uint32_t, PerPixelData *> idGroups;
  1528. std::multimap<uint32_t, PerPixelData *> firstIdGroups;
  1529. for (uint32_t i = 0; i < appendCount; ++i) {
  1530. ids.insert(values[i].id);
  1531. idGroups.insert(std::make_pair(values[i].id, &values[i]));
  1532. firstIdGroups.insert(std::make_pair(values[i].firstLaneId, &values[i]));
  1533. }
  1534. for (uint32_t id : ids) {
  1535. if (idGroups.count(id) == 1)
  1536. ++singlePixelCount;
  1537. else
  1538. ++multiPixelCount;
  1539. }
  1540. LogCommentFmt(L"%u pixels were processed by a single thread. %u invocations were for shared pixels.",
  1541. singlePixelCount, multiPixelCount);
  1542. // Multiple threads may have tried to shade the same pixel.
  1543. // Where every pixel is distinct, it's very straightforward to validate.
  1544. {
  1545. auto cur = firstIdGroups.begin(), end = firstIdGroups.end();
  1546. while (cur != end) {
  1547. bool simpleWave = true;
  1548. uint32_t firstId = (*cur).first;
  1549. auto groupEnd = cur;
  1550. while (groupEnd != end && (*groupEnd).first == firstId) {
  1551. if (idGroups.count((*groupEnd).second->id) > 1)
  1552. simpleWave = false;
  1553. ++groupEnd;
  1554. }
  1555. if (simpleWave) {
  1556. // Break the wave into quads.
  1557. struct QuadData {
  1558. unsigned count;
  1559. PerPixelData *data[4];
  1560. };
  1561. std::map<uint32_t, QuadData> quads;
  1562. for (auto i = cur; i != groupEnd; ++i) {
  1563. uint32_t quadId = (*i).second->id0;
  1564. auto match = quads.find(quadId);
  1565. if (match == quads.end()) {
  1566. QuadData qdata;
  1567. qdata.count = 1;
  1568. qdata.data[0] = (*i).second;
  1569. quads.insert(std::make_pair(quadId, qdata));
  1570. }
  1571. else {
  1572. VERIFY_IS_TRUE((*match).second.count < 4);
  1573. (*match).second.data[(*match).second.count++] = (*i).second;
  1574. }
  1575. }
  1576. for (auto quadPair : quads) {
  1577. unsigned count = quadPair.second.count;
  1578. if (count < 2) continue;
  1579. PerPixelData **data = quadPair.second.data;
  1580. bool isTop[4];
  1581. bool isLeft[4];
  1582. PerPixelData helperData;
  1583. memset(&helperData, sizeof(helperData), 0);
  1584. PerPixelData *layout[4]; // tl,tr,bl,br
  1585. memset(layout, sizeof(layout), 0);
  1586. auto fnToLayout = [&](bool top, bool left) -> PerPixelData ** {
  1587. int idx = top ? 0 : 2;
  1588. idx += left ? 0 : 1;
  1589. return &layout[idx];
  1590. };
  1591. auto fnToLayoutData = [&](bool top, bool left) -> PerPixelData * {
  1592. PerPixelData **pResult = fnToLayout(top, left);
  1593. if (*pResult == nullptr) return &helperData;
  1594. return *pResult;
  1595. };
  1596. VERIFY_IS_TRUE(count <= 4);
  1597. if (count == 2) {
  1598. isTop[0] = data[0]->position.y < data[1]->position.y;
  1599. isTop[1] = (data[0]->position.y == data[1]->position.y) ? isTop[0] : !isTop[0];
  1600. isLeft[0] = data[0]->position.x < data[1]->position.x;
  1601. isLeft[1] = (data[0]->position.x == data[1]->position.x) ? isLeft[0] : !isLeft[0];
  1602. }
  1603. else {
  1604. // with at least three samples, we have distinct x and y coordinates.
  1605. float left = std::min(data[0]->position.x, data[1]->position.x);
  1606. left = std::min(data[2]->position.x, left);
  1607. float top = std::min(data[0]->position.y, data[1]->position.y);
  1608. top = std::min(data[2]->position.y, top);
  1609. for (unsigned i = 0; i < count; ++i) {
  1610. isTop[i] = data[i]->position.y == top;
  1611. isLeft[i] = data[i]->position.x == left;
  1612. }
  1613. }
  1614. for (unsigned i = 0; i < count; ++i) {
  1615. *(fnToLayout(isTop[i], isLeft[i])) = data[i];
  1616. }
  1617. // Finally, we have a proper quad reconstructed. Validate.
  1618. for (unsigned i = 0; i < count; ++i) {
  1619. PerPixelData *d = data[i];
  1620. VERIFY_ARE_EQUAL(d->id0, fnToLayoutData(true, true)->id);
  1621. VERIFY_ARE_EQUAL(d->id1, fnToLayoutData(true, false)->id);
  1622. VERIFY_ARE_EQUAL(d->id2, fnToLayoutData(false, true)->id);
  1623. VERIFY_ARE_EQUAL(d->id3, fnToLayoutData(false, false)->id);
  1624. VERIFY_ARE_EQUAL(d->acrossX, fnToLayoutData(isTop[i], !isLeft[i])->id);
  1625. VERIFY_ARE_EQUAL(d->acrossY, fnToLayoutData(!isTop[i], isLeft[i])->id);
  1626. VERIFY_ARE_EQUAL(d->acrossDiag, fnToLayoutData(!isTop[i], !isLeft[i])->id);
  1627. VERIFY_ARE_EQUAL(d->quadActiveCount, count);
  1628. }
  1629. }
  1630. }
  1631. cur = groupEnd;
  1632. }
  1633. }
  1634. // TODO: provide validation for quads where the same pixel was shaded multiple times
  1635. //
  1636. // Consider: for pixels that were shaded multiple times, check whether
  1637. // some grouping of threads into quads satisfies all value requirements.
  1638. }
  1639. }
  1640. struct ShaderOpTestResult {
  1641. st::ShaderOp *ShaderOp;
  1642. std::shared_ptr<st::ShaderOpSet> ShaderOpSet;
  1643. std::shared_ptr<st::ShaderOpTest> Test;
  1644. };
  1645. struct SPrimitives {
  1646. float f_float;
  1647. float f_float2;
  1648. float f_float_o;
  1649. float f_float2_o;
  1650. };
  1651. static float g_SinCosFloats[] = {
  1652. -(INFINITY),
  1653. -1.0f,
  1654. -(FLT_MIN/2),
  1655. -0.0f,
  1656. 0.0f,
  1657. FLT_MIN / 2,
  1658. 1.0f,
  1659. INFINITY,
  1660. NAN
  1661. };
  1662. std::shared_ptr<ShaderOpTestResult>
  1663. RunShaderOpTest(ID3D12Device *pDevice, dxc::DxcDllSupport &support,
  1664. IStream *pStream, LPCSTR pName,
  1665. st::ShaderOpTest::TInitCallbackFn pInitCallback) {
  1666. DXASSERT_NOMSG(pStream != nullptr);
  1667. std::shared_ptr<st::ShaderOpSet> ShaderOpSet =
  1668. std::make_shared<st::ShaderOpSet>();
  1669. st::ParseShaderOpSetFromStream(pStream, ShaderOpSet.get());
  1670. st::ShaderOp *pShaderOp;
  1671. if (pName == nullptr) {
  1672. if (ShaderOpSet->ShaderOps.size() != 1) {
  1673. VERIFY_FAIL(L"Expected a single shader operation.");
  1674. }
  1675. pShaderOp = ShaderOpSet->ShaderOps[0].get();
  1676. }
  1677. else {
  1678. pShaderOp = ShaderOpSet->GetShaderOp(pName);
  1679. }
  1680. if (pShaderOp == nullptr) {
  1681. std::string msg = "Unable to find shader op ";
  1682. msg += pName;
  1683. msg += "; available ops";
  1684. const char sep = ':';
  1685. for (auto &pAvailOp : ShaderOpSet->ShaderOps) {
  1686. msg += sep;
  1687. msg += pAvailOp->Name ? pAvailOp->Name : "[n/a]";
  1688. }
  1689. CA2W msgWide(msg.c_str());
  1690. VERIFY_FAIL(msgWide.m_psz);
  1691. }
  1692. // This won't actually be used since we're supplying the device,
  1693. // but let's make it consistent.
  1694. pShaderOp->UseWarpDevice = GetTestParamUseWARP(true);
  1695. std::shared_ptr<st::ShaderOpTest> test = std::make_shared<st::ShaderOpTest>();
  1696. test->SetDxcSupport(&support);
  1697. test->SetInitCallback(pInitCallback);
  1698. test->SetDevice(pDevice);
  1699. test->RunShaderOp(pShaderOp);
  1700. std::shared_ptr<ShaderOpTestResult> result =
  1701. std::make_shared<ShaderOpTestResult>();
  1702. result->ShaderOpSet = ShaderOpSet;
  1703. result->Test = test;
  1704. result->ShaderOp = pShaderOp;
  1705. return result;
  1706. }
  1707. static bool isdenorm(float f) {
  1708. return FP_SUBNORMAL == fpclassify(f);
  1709. }
  1710. static bool isdenorm(double d) {
  1711. return FP_SUBNORMAL == fpclassify(d);
  1712. }
  1713. static float ifdenorm_flushf(float a) {
  1714. return isdenorm(a) ? copysign(0.0f, a) : a;
  1715. }
  1716. static bool ifdenorm_flushf_eq(float a, float b) {
  1717. return ifdenorm_flushf(a) == ifdenorm_flushf(b);
  1718. }
  1719. static bool ifdenorm_flushf_eq_or_nans(float a, float b) {
  1720. if (isnan(a) && isnan(b)) return true;
  1721. return ifdenorm_flushf(a) == ifdenorm_flushf(b);
  1722. }
  1723. TEST_F(ExecutionTest, OutOfBoundsTest) {
  1724. WEX::TestExecution::SetVerifyOutput verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  1725. CComPtr<IStream> pStream;
  1726. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  1727. // Single operation test at the moment.
  1728. CComPtr<ID3D12Device> pDevice;
  1729. if (!CreateDevice(&pDevice))
  1730. return;
  1731. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(pDevice, m_support, pStream, "OOB", nullptr);
  1732. MappedData data;
  1733. // Read back to CPU and examine contents - should get pure red.
  1734. {
  1735. MappedData data;
  1736. test->Test->GetReadBackData("RTarget", &data);
  1737. const uint32_t *pPixels = (uint32_t *)data.data();
  1738. uint32_t first = *pPixels;
  1739. VERIFY_ARE_EQUAL(0xff0000ff, first); // pure red - only first component is read
  1740. }
  1741. }
  1742. TEST_F(ExecutionTest, SaturateTest) {
  1743. WEX::TestExecution::SetVerifyOutput verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  1744. CComPtr<IStream> pStream;
  1745. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  1746. // Single operation test at the moment.
  1747. CComPtr<ID3D12Device> pDevice;
  1748. if (!CreateDevice(&pDevice))
  1749. return;
  1750. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(pDevice, m_support, pStream, "Saturate", nullptr);
  1751. MappedData data;
  1752. test->Test->GetReadBackData("U0", &data);
  1753. const float *pValues = (float *)data.data();
  1754. // Everything is zero except for 1.5f and +Inf, which saturate to 1.0f
  1755. const float ExpectedCases[9] = {
  1756. 0.0f, 0.0f, 0.0f, 0.0f, // -inf, -1.5, -denorm, -0
  1757. 0.0f, 0.0f, 1.0f, 1.0f, // 0, denorm, 1.5f, inf
  1758. 0.0f // nan
  1759. };
  1760. for (size_t i = 0; i < _countof(ExpectedCases); ++i) {
  1761. VERIFY_ARE_EQUAL(*pValues, ExpectedCases[i]);
  1762. ++pValues;
  1763. }
  1764. }
  1765. TEST_F(ExecutionTest, BasicTriangleOpTest) {
  1766. WEX::TestExecution::SetVerifyOutput verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  1767. CComPtr<IStream> pStream;
  1768. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  1769. // Single operation test at the moment.
  1770. CComPtr<ID3D12Device> pDevice;
  1771. if (!CreateDevice(&pDevice))
  1772. return;
  1773. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(pDevice, m_support, pStream, "Triangle", nullptr);
  1774. MappedData data;
  1775. D3D12_RESOURCE_DESC &D = test->ShaderOp->GetResourceByName("RTarget")->Desc;
  1776. UINT width = (UINT64)D.Width;
  1777. UINT height = (UINT64)D.Height;
  1778. test->Test->GetReadBackData("RTarget", &data);
  1779. const uint32_t *pPixels = (uint32_t *)data.data();
  1780. if (SaveImages()) {
  1781. SavePixelsToFile(pPixels, DXGI_FORMAT_R8G8B8A8_UNORM, 320, 200, L"basic.bmp");
  1782. }
  1783. uint32_t top = pPixels[width / 2]; // Top center.
  1784. uint32_t mid = pPixels[width / 2 + width * (height / 2)]; // Middle center.
  1785. VERIFY_ARE_EQUAL(0xff663300, top); // clear color
  1786. VERIFY_ARE_EQUAL(0xffffffff, mid); // white
  1787. // This is the basic validation test for shader operations, so it's good to
  1788. // check this here at least for this one test case.
  1789. data.reset();
  1790. test.reset();
  1791. ReportLiveObjects();
  1792. }
  1793. // Resource structure for data-driven tests.
  1794. struct SUnaryFPOp {
  1795. float input;
  1796. float output;
  1797. };
  1798. struct SBinaryFPOp {
  1799. float input1;
  1800. float input2;
  1801. float output1;
  1802. float output2;
  1803. };
  1804. struct STertiaryFPOp {
  1805. float input1;
  1806. float input2;
  1807. float input3;
  1808. float output;
  1809. };
  1810. struct SUnaryIntOp {
  1811. int input;
  1812. int output;
  1813. };
  1814. struct SUnaryUintOp {
  1815. unsigned int input;
  1816. unsigned int output;
  1817. };
  1818. struct SBinaryIntOp {
  1819. int input1;
  1820. int input2;
  1821. int output1;
  1822. int output2;
  1823. };
  1824. struct STertiaryIntOp {
  1825. int input1;
  1826. int input2;
  1827. int input3;
  1828. int output;
  1829. };
  1830. struct SBinaryUintOp {
  1831. unsigned int input1;
  1832. unsigned int input2;
  1833. unsigned int output1;
  1834. unsigned int output2;
  1835. };
  1836. struct STertiaryUintOp {
  1837. unsigned int input1;
  1838. unsigned int input2;
  1839. unsigned int input3;
  1840. unsigned int output;
  1841. };
  1842. // representation for HLSL float vectors
  1843. struct float2 {
  1844. float x;
  1845. float y;
  1846. };
  1847. struct float3 {
  1848. float x;
  1849. float y;
  1850. float z;
  1851. };
  1852. struct float4 {
  1853. float x;
  1854. float y;
  1855. float z;
  1856. float w;
  1857. };
  1858. struct SDotOp {
  1859. float4 input1;
  1860. float4 input2;
  1861. float o_dot2;
  1862. float o_dot3;
  1863. float o_dot4;
  1864. };
  1865. // HLSL representation for unsigned int vectors
  1866. struct uint2 {
  1867. unsigned int x;
  1868. unsigned int y;
  1869. };
  1870. struct uint3 {
  1871. unsigned int x;
  1872. unsigned int y;
  1873. unsigned int z;
  1874. };
  1875. struct uint4 {
  1876. unsigned int x;
  1877. unsigned int y;
  1878. unsigned int z;
  1879. unsigned int w;
  1880. };
  1881. struct SMsad4 {
  1882. unsigned int ref;
  1883. uint2 src;
  1884. uint4 accum;
  1885. uint4 result;
  1886. };
  1887. // Parameter representation for taef data-driven tests
  1888. struct TableParameter {
  1889. LPCWSTR m_name;
  1890. enum TableParameterType {
  1891. INT,
  1892. UINT,
  1893. DOUBLE,
  1894. STRING,
  1895. BOOL,
  1896. INT_TABLE,
  1897. DOUBLE_TABLE,
  1898. STRING_TABLE,
  1899. UINT_TABLE
  1900. };
  1901. TableParameterType m_type;
  1902. bool m_required; // required parameter
  1903. int m_int;
  1904. unsigned int m_uint;
  1905. double m_double;
  1906. bool m_bool;
  1907. WEX::Common::String m_str;
  1908. WEX::TestExecution::TestDataArray<int> m_intTable;
  1909. WEX::TestExecution::TestDataArray<unsigned int> m_uintTable;
  1910. WEX::TestExecution::TestDataArray<double> m_doubleTable;
  1911. WEX::TestExecution::TestDataArray<WEX::Common::String> m_StringTable;
  1912. };
  1913. static TableParameter UnaryFPOpParameters[] = {
  1914. { L"ShaderOp.Name", TableParameter::STRING, true },
  1915. { L"ShaderOp.Target", TableParameter::STRING, true },
  1916. { L"ShaderOp.EntryPoint", TableParameter::STRING, true },
  1917. { L"ShaderOp.Text", TableParameter::STRING, true },
  1918. { L"Validation.Input", TableParameter::STRING_TABLE, true },
  1919. { L"Validation.Expected", TableParameter::STRING_TABLE, true },
  1920. { L"Validation.Type", TableParameter::STRING, true },
  1921. { L"Validation.Tolerance", TableParameter::DOUBLE, true },
  1922. { L"Validation.NumInput", TableParameter::UINT, true }
  1923. };
  1924. static TableParameter BinaryFPOpParameters[] = {
  1925. { L"ShaderOp.Name", TableParameter::STRING, true },
  1926. { L"ShaderOp.Target", TableParameter::STRING, true },
  1927. { L"ShaderOp.EntryPoint", TableParameter::STRING, true },
  1928. { L"ShaderOp.Text", TableParameter::STRING, true },
  1929. { L"Validation.Input1", TableParameter::STRING_TABLE, true },
  1930. { L"Validation.Input2", TableParameter::STRING_TABLE, true },
  1931. { L"Validation.Expected1", TableParameter::STRING_TABLE, true },
  1932. { L"Validation.Expected2", TableParameter::STRING_TABLE, true },
  1933. { L"Validation.Type", TableParameter::STRING, true },
  1934. { L"Validation.Tolerance", TableParameter::DOUBLE, true },
  1935. { L"Validation.NumInput", TableParameter::UINT, true }
  1936. };
  1937. static TableParameter TertiaryFPOpParameters[] = {
  1938. { L"ShaderOp.Name", TableParameter::STRING, true },
  1939. { L"ShaderOp.Target", TableParameter::STRING, true },
  1940. { L"ShaderOp.EntryPoint", TableParameter::STRING, true },
  1941. { L"ShaderOp.Text", TableParameter::STRING, true },
  1942. { L"Validation.Input1", TableParameter::STRING_TABLE, true },
  1943. { L"Validation.Input2", TableParameter::STRING_TABLE, true },
  1944. { L"Validation.Input3", TableParameter::STRING_TABLE, true },
  1945. { L"Validation.Expected", TableParameter::STRING_TABLE, true },
  1946. { L"Validation.Type", TableParameter::STRING, true },
  1947. { L"Validation.Tolerance", TableParameter::DOUBLE, true },
  1948. { L"Validation.NumInput", TableParameter::UINT, true }
  1949. };
  1950. static TableParameter UnaryIntOpParameters[] = {
  1951. { L"ShaderOp.Name", TableParameter::STRING, true },
  1952. { L"ShaderOp.Target", TableParameter::STRING, true },
  1953. { L"ShaderOp.EntryPoint", TableParameter::STRING, true },
  1954. { L"ShaderOp.Text", TableParameter::STRING, true },
  1955. { L"Validation.Input", TableParameter::INT_TABLE, true },
  1956. { L"Validation.Expected", TableParameter::INT_TABLE, true },
  1957. { L"Validation.Tolerance", TableParameter::INT, true },
  1958. { L"Validation.NumInput", TableParameter::UINT, true }
  1959. };
  1960. static TableParameter UnaryUintOpParameters[] = {
  1961. { L"ShaderOp.Name", TableParameter::STRING, true },
  1962. { L"ShaderOp.Target", TableParameter::STRING, true },
  1963. { L"ShaderOp.EntryPoint", TableParameter::STRING, true },
  1964. { L"ShaderOp.Text", TableParameter::STRING, true },
  1965. { L"Validation.Input", TableParameter::UINT_TABLE, true },
  1966. { L"Validation.Expected", TableParameter::UINT_TABLE, true },
  1967. { L"Validation.Tolerance", TableParameter::INT, true },
  1968. { L"Validation.NumInput", TableParameter::UINT, true }
  1969. };
  1970. static TableParameter BinaryIntOpParameters[] = {
  1971. { L"ShaderOp.Name", TableParameter::STRING, true },
  1972. { L"ShaderOp.Target", TableParameter::STRING, true },
  1973. { L"ShaderOp.EntryPoint", TableParameter::STRING, true },
  1974. { L"ShaderOp.Text", TableParameter::STRING, true },
  1975. { L"Validation.NumExpected", TableParameter::INT, true },
  1976. { L"Validation.Input1", TableParameter::INT_TABLE, true },
  1977. { L"Validation.Input2", TableParameter::INT_TABLE, true },
  1978. { L"Validation.Expected1", TableParameter::INT_TABLE, true },
  1979. { L"Validation.Expected2", TableParameter::INT_TABLE, false },
  1980. { L"Validation.Tolerance", TableParameter::INT, true },
  1981. { L"Validation.NumInput", TableParameter::UINT, true }
  1982. };
  1983. static TableParameter TertiaryIntOpParameters[] = {
  1984. { L"ShaderOp.Name", TableParameter::STRING, true },
  1985. { L"ShaderOp.Target", TableParameter::STRING, true },
  1986. { L"ShaderOp.EntryPoint", TableParameter::STRING, true },
  1987. { L"ShaderOp.Text", TableParameter::STRING, true },
  1988. { L"Validation.Input1", TableParameter::INT_TABLE, true },
  1989. { L"Validation.Input2", TableParameter::INT_TABLE, true },
  1990. { L"Validation.Input3", TableParameter::INT_TABLE, true },
  1991. { L"Validation.Expected", TableParameter::INT_TABLE, true },
  1992. { L"Validation.Tolerance", TableParameter::INT, true },
  1993. { L"Validation.NumInput", TableParameter::UINT, true }
  1994. };
  1995. static TableParameter BinaryUintOpParameters[] = {
  1996. { L"ShaderOp.Name", TableParameter::STRING, true },
  1997. { L"ShaderOp.Target", TableParameter::STRING, true },
  1998. { L"ShaderOp.EntryPoint", TableParameter::STRING, true },
  1999. { L"ShaderOp.Text", TableParameter::STRING, true },
  2000. { L"Validation.NumExpected", TableParameter::INT, true },
  2001. { L"Validation.Input1", TableParameter::UINT_TABLE, true },
  2002. { L"Validation.Input2", TableParameter::UINT_TABLE, true },
  2003. { L"Validation.Expected1", TableParameter::UINT_TABLE, true },
  2004. { L"Validation.Expected2", TableParameter::UINT_TABLE, false },
  2005. { L"Validation.Tolerance", TableParameter::INT, true },
  2006. { L"Validation.NumInput", TableParameter::UINT, true }
  2007. };
  2008. static TableParameter TertiaryUintOpParameters[] = {
  2009. { L"ShaderOp.Name", TableParameter::STRING, true },
  2010. { L"ShaderOp.Target", TableParameter::STRING, true },
  2011. { L"ShaderOp.EntryPoint", TableParameter::STRING, true },
  2012. { L"ShaderOp.Text", TableParameter::STRING, true },
  2013. { L"Validation.Input1", TableParameter::UINT_TABLE, true },
  2014. { L"Validation.Input2", TableParameter::UINT_TABLE, true },
  2015. { L"Validation.Input3", TableParameter::UINT_TABLE, true },
  2016. { L"Validation.Expected", TableParameter::UINT_TABLE, true },
  2017. { L"Validation.Tolerance", TableParameter::INT, true },
  2018. { L"Validation.NumInput", TableParameter::UINT, true }
  2019. };
  2020. static TableParameter DotOpParameters[] = {
  2021. { L"ShaderOp.Name", TableParameter::STRING, true },
  2022. { L"ShaderOp.Target", TableParameter::STRING, true },
  2023. { L"ShaderOp.EntryPoint", TableParameter::STRING, true },
  2024. { L"ShaderOp.Text", TableParameter::STRING, true },
  2025. { L"Validation.Input1", TableParameter::STRING_TABLE, true },
  2026. { L"Validation.Input2", TableParameter::STRING_TABLE, true },
  2027. { L"Validation.dot2", TableParameter::STRING_TABLE, true },
  2028. { L"Validation.dot3", TableParameter::STRING_TABLE, true },
  2029. { L"Validation.dot4", TableParameter::STRING_TABLE, true },
  2030. { L"Validation.Type", TableParameter::STRING, true },
  2031. { L"Validation.Tolerance", TableParameter::DOUBLE, true },
  2032. { L"Validation.NumInput", TableParameter::UINT, true }
  2033. };
  2034. static TableParameter Msad4OpParameters[] = {
  2035. { L"ShaderOp.Text", TableParameter::STRING, true },
  2036. { L"Validation.Tolerance", TableParameter::DOUBLE, true },
  2037. { L"Validation.NumInput", TableParameter::UINT, true },
  2038. { L"Validation.Reference", TableParameter::UINT_TABLE, true},
  2039. { L"Validation.Source", TableParameter::STRING_TABLE, true },
  2040. { L"Validation.Accum", TableParameter::STRING_TABLE, true },
  2041. { L"Validation.Expected", TableParameter::STRING_TABLE, true }
  2042. };
  2043. static HRESULT ParseDataToFloat(PCWSTR str, float &value) {
  2044. std::wstring wString(str);
  2045. wString.erase(std::remove(wString.begin(), wString.end(), L' '), wString.end());
  2046. PCWSTR wstr = wString.data();
  2047. if (_wcsicmp(wstr, L"NaN") == 0) {
  2048. value = NAN;
  2049. } else if (_wcsicmp(wstr, L"-inf") == 0) {
  2050. value = -(INFINITY);
  2051. } else if (_wcsicmp(wstr, L"inf") == 0) {
  2052. value = INFINITY;
  2053. } else if (_wcsicmp(wstr, L"-denorm") == 0) {
  2054. value = -(FLT_MIN / 2);
  2055. } else if (_wcsicmp(wstr, L"denorm") == 0) {
  2056. value = FLT_MIN / 2;
  2057. } else if (_wcsicmp(wstr, L"-0.0f") == 0 || _wcsicmp(wstr, L"-0.0") == 0 ||
  2058. _wcsicmp(wstr, L"-0") == 0) {
  2059. value = -0.0f;
  2060. } else if (_wcsicmp(wstr, L"0.0f") == 0 || _wcsicmp(wstr, L"0.0") == 0 ||
  2061. _wcsicmp(wstr, L"0") == 0) {
  2062. value = 0.0f;
  2063. } else {
  2064. // evaluate the expression of wstring
  2065. double val = _wtof(wstr);
  2066. if (val == 0) {
  2067. LogErrorFmt(L"Failed to parse parameter %s to float", wstr);
  2068. return E_FAIL;
  2069. }
  2070. value = val;
  2071. }
  2072. return S_OK;
  2073. }
  2074. static HRESULT ParseDataToInt(PCWSTR str, int &value) {
  2075. std::wstring wString(str);
  2076. wString.erase(std::remove(wString.begin(), wString.end(), L' '), wString.end());
  2077. PCWSTR wstr = wString.data();
  2078. // evaluate the expression of string
  2079. if (_wcsicmp(wstr, L"0.0") == 0 || _wcsicmp(wstr, L"0") == 0) {
  2080. value = 0;
  2081. return S_OK;
  2082. }
  2083. int val = _wtoi(wstr);
  2084. if (val == 0) {
  2085. LogErrorFmt(L"Failed to parse parameter %s to int", wstr);
  2086. return E_FAIL;
  2087. }
  2088. value = val;
  2089. return S_OK;
  2090. }
  2091. static HRESULT ParseDataToUint(PCWSTR str, unsigned int &value) {
  2092. std::wstring wString(str);
  2093. wString.erase(std::remove(wString.begin(), wString.end(), L' '), wString.end());
  2094. PCWSTR wstr = wString.data();
  2095. // evaluate the expression of string
  2096. if (_wcsicmp(wstr, L"0") == 0 || _wcsicmp(wstr, L"0x00000000") == 0) {
  2097. value = 0;
  2098. return S_OK;
  2099. }
  2100. wchar_t *end;
  2101. unsigned int val = std::wcstoul(wstr, &end, 0);
  2102. if (val == 0) {
  2103. LogErrorFmt(L"Failed to parse parameter %s to int", wstr);
  2104. return E_FAIL;
  2105. }
  2106. value = val;
  2107. return S_OK;
  2108. }
  2109. static HRESULT ParseDataToVectorFloat(PCWSTR str, float *ptr, size_t count) {
  2110. std::wstring wstr(str);
  2111. size_t curPosition = 0;
  2112. // parse a string of dot product separated by commas
  2113. for (size_t i = 0; i < count; ++i) {
  2114. size_t nextPosition = wstr.find(L",", curPosition);
  2115. if (FAILED(ParseDataToFloat(
  2116. wstr.substr(curPosition, nextPosition - curPosition).data(),
  2117. *(ptr + i)))) {
  2118. return E_FAIL;
  2119. }
  2120. curPosition = nextPosition + 1;
  2121. }
  2122. return S_OK;
  2123. }
  2124. static HRESULT ParseDataToVectorUint(PCWSTR str, unsigned int *ptr, size_t count) {
  2125. std::wstring wstr(str);
  2126. size_t curPosition = 0;
  2127. // parse a string of dot product separated by commas
  2128. for (size_t i = 0; i < count; ++i) {
  2129. size_t nextPosition = wstr.find(L",", curPosition);
  2130. if (FAILED(ParseDataToUint(
  2131. wstr.substr(curPosition, nextPosition - curPosition).data(),
  2132. *(ptr + i)))) {
  2133. return E_FAIL;
  2134. }
  2135. curPosition = nextPosition + 1;
  2136. }
  2137. return S_OK;
  2138. }
  2139. static HRESULT ParseTableRow(TableParameter *table, unsigned int size) {
  2140. for (unsigned int i = 0; i < size; ++i) {
  2141. switch (table[i].m_type) {
  2142. case TableParameter::INT:
  2143. if (FAILED(WEX::TestExecution::TestData::TryGetValue(table[i].m_name,
  2144. table[i].m_int)) && table[i].m_required) {
  2145. LogErrorFmt(L"Failed to get %s", table[i].m_name);
  2146. return E_FAIL;
  2147. }
  2148. break;
  2149. case TableParameter::UINT:
  2150. if (FAILED(WEX::TestExecution::TestData::TryGetValue(table[i].m_name,
  2151. table[i].m_uint)) && table[i].m_required) {
  2152. LogErrorFmt(L"Failed to get %s", table[i].m_name);
  2153. return E_FAIL;
  2154. }
  2155. break;
  2156. case TableParameter::DOUBLE:
  2157. if (FAILED(WEX::TestExecution::TestData::TryGetValue(
  2158. table[i].m_name, table[i].m_double)) && table[i].m_required) {
  2159. LogErrorFmt(L"Failed to get %s", table[i].m_name);
  2160. return E_FAIL;
  2161. }
  2162. break;
  2163. case TableParameter::STRING:
  2164. if (FAILED(WEX::TestExecution::TestData::TryGetValue(table[i].m_name,
  2165. table[i].m_str)) && table[i].m_required) {
  2166. LogErrorFmt(L"Failed to get %s", table[i].m_name);
  2167. return E_FAIL;
  2168. }
  2169. break;
  2170. case TableParameter::BOOL:
  2171. if (FAILED(WEX::TestExecution::TestData::TryGetValue(table[i].m_name,
  2172. table[i].m_str)) && table[i].m_bool) {
  2173. LogErrorFmt(L"Failed to get %s", table[i].m_name);
  2174. return E_FAIL;
  2175. }
  2176. break;
  2177. case TableParameter::INT_TABLE:
  2178. if (FAILED(WEX::TestExecution::TestData::TryGetValue(
  2179. table[i].m_name, table[i].m_intTable)) && table[i].m_required) {
  2180. LogErrorFmt(L"Failed to get %s", table[i].m_name);
  2181. return E_FAIL;
  2182. }
  2183. break;
  2184. case TableParameter::UINT_TABLE:
  2185. if (FAILED(WEX::TestExecution::TestData::TryGetValue(
  2186. table[i].m_name, table[i].m_uintTable)) && table[i].m_required) {
  2187. LogErrorFmt(L"Failed to get %s", table[i].m_name);
  2188. return E_FAIL;
  2189. }
  2190. break;
  2191. case TableParameter::DOUBLE_TABLE:
  2192. if (FAILED(WEX::TestExecution::TestData::TryGetValue(
  2193. table[i].m_name, table[i].m_doubleTable)) && table[i].m_required) {
  2194. LogErrorFmt(L"Failed to get %s", table[i].m_name);
  2195. return E_FAIL;
  2196. }
  2197. break;
  2198. case TableParameter::STRING_TABLE:
  2199. if (FAILED(WEX::TestExecution::TestData::TryGetValue(
  2200. table[i].m_name, table[i].m_StringTable)) && table[i].m_required) {
  2201. LogErrorFmt(L"Failed to get %s", table[i].m_name);
  2202. return E_FAIL;
  2203. }
  2204. break;
  2205. default:
  2206. DXASSERT_NOMSG("Invalid Parameter Type");
  2207. }
  2208. }
  2209. return S_OK;
  2210. }
  2211. static void VerifyOutputWithExpectedValueInt(int output, int ref, int tolerance) {
  2212. VERIFY_IS_TRUE(output - ref <= tolerance && ref - output <= tolerance);
  2213. }
  2214. static void VerifyOutputWithExpectedValueFloat(float output, float ref, LPCWSTR type, double tolerance) {
  2215. if (_wcsicmp(type, L"Relative") == 0) {
  2216. VERIFY_IS_TRUE(CompareFloatRelativeEpsilon(output, ref, tolerance));
  2217. }
  2218. else if (_wcsicmp(type, L"Epsilon") == 0) {
  2219. VERIFY_IS_TRUE(CompareFloatEpsilon(output, ref, tolerance));
  2220. }
  2221. else if (_wcsicmp(type, L"ULP") == 0) {
  2222. VERIFY_IS_TRUE(CompareFloatULP(output, ref, (int)tolerance));
  2223. }
  2224. else {
  2225. LogErrorFmt(L"Failed to read comparison type %S", type);
  2226. }
  2227. }
  2228. TEST_F(ExecutionTest, UnaryFloatOpTest) {
  2229. WEX::TestExecution::SetVerifyOutput verifySettings(
  2230. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  2231. CComPtr<IStream> pStream;
  2232. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  2233. CComPtr<ID3D12Device> pDevice;
  2234. if (!CreateDevice(&pDevice)) {
  2235. return;
  2236. }
  2237. // Read data from the table
  2238. VERIFY_SUCCEEDED(ParseTableRow(UnaryFPOpParameters, sizeof(UnaryFPOpParameters)/sizeof(TableParameter)));
  2239. st::ShaderOpShader shader;
  2240. CW2A Name(UnaryFPOpParameters[0].m_str);
  2241. CW2A Target(UnaryFPOpParameters[1].m_str);
  2242. CW2A EntryPoint(UnaryFPOpParameters[2].m_str);
  2243. CW2A Text(UnaryFPOpParameters[3].m_str);
  2244. shader.Name = Name.m_psz;
  2245. shader.Target = Target.m_psz;
  2246. shader.EntryPoint = EntryPoint.m_psz;
  2247. shader.Text = Text.m_psz;
  2248. WEX::TestExecution::TestDataArray<WEX::Common::String> *Validation_Input =
  2249. &(UnaryFPOpParameters[4].m_StringTable);
  2250. WEX::TestExecution::TestDataArray<WEX::Common::String> *Validation_Expected =
  2251. &(UnaryFPOpParameters[5].m_StringTable);
  2252. LPCWSTR Validation_Type = UnaryFPOpParameters[6].m_str;
  2253. double Validation_Tolerance = UnaryFPOpParameters[7].m_double;
  2254. size_t count = UnaryFPOpParameters[8].m_uint;
  2255. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  2256. pDevice, m_support, pStream, "UnaryFPOp",
  2257. // this callbacked is called when the test
  2258. // is creating the resource to run the test
  2259. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  2260. VERIFY_IS_TRUE(0 == _stricmp(Name, "SUnaryFPOp"));
  2261. size_t size = sizeof(SUnaryFPOp) * count;
  2262. Data.resize(size);
  2263. SUnaryFPOp *pPrimitives = (SUnaryFPOp *)Data.data();
  2264. for (size_t i = 0; i < count; ++i) {
  2265. SUnaryFPOp *p = &pPrimitives[i];
  2266. PCWSTR str = (*Validation_Input)[i % Validation_Input->GetSize()];
  2267. float val;
  2268. VERIFY_SUCCEEDED(ParseDataToFloat(str, val));
  2269. p->input = val;
  2270. }
  2271. // use shader from data table
  2272. pShaderOp->Shaders.at(0).Text = shader.Text;
  2273. });
  2274. MappedData data;
  2275. test->Test->GetReadBackData("SUnaryFPOp", &data);
  2276. SUnaryFPOp *pPrimitives = (SUnaryFPOp*)data.data();
  2277. WEX::TestExecution::DisableVerifyExceptions dve;
  2278. for (unsigned i = 0; i < count; ++i) {
  2279. SUnaryFPOp *p = &pPrimitives[i];
  2280. LPCWSTR str = (*Validation_Expected)[i % Validation_Expected->GetSize()];
  2281. float val;
  2282. VERIFY_SUCCEEDED(ParseDataToFloat(str, val));
  2283. LogCommentFmt(
  2284. L"element #%u, input = %10f, output = %10f, expected = %10f", i,
  2285. p->input, p->output, val);
  2286. VerifyOutputWithExpectedValueFloat(p->output, val, Validation_Type, Validation_Tolerance);
  2287. }
  2288. }
  2289. TEST_F(ExecutionTest, BinaryFloatOpTest) {
  2290. WEX::TestExecution::SetVerifyOutput verifySettings(
  2291. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  2292. CComPtr<IStream> pStream;
  2293. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  2294. CComPtr<ID3D12Device> pDevice;
  2295. if (!CreateDevice(&pDevice)) {
  2296. return;
  2297. }
  2298. // Read data from the table
  2299. VERIFY_SUCCEEDED(ParseTableRow(BinaryFPOpParameters, sizeof(BinaryFPOpParameters) / sizeof(TableParameter)));
  2300. st::ShaderOpShader shader;
  2301. CW2A Name(BinaryFPOpParameters[0].m_str);
  2302. CW2A Target(BinaryFPOpParameters[1].m_str);
  2303. CW2A EntryPoint(BinaryFPOpParameters[2].m_str);
  2304. CW2A Text(BinaryFPOpParameters[3].m_str);
  2305. shader.Name = Name.m_psz;
  2306. shader.Target = Target.m_psz;
  2307. shader.EntryPoint = EntryPoint.m_psz;
  2308. shader.Text = Text.m_psz;
  2309. WEX::TestExecution::TestDataArray<WEX::Common::String> *Validation_Input1 =
  2310. &(BinaryFPOpParameters[4].m_StringTable);
  2311. WEX::TestExecution::TestDataArray<WEX::Common::String> *Validation_Input2 =
  2312. &(BinaryFPOpParameters[5].m_StringTable);
  2313. WEX::TestExecution::TestDataArray<WEX::Common::String> *Validation_Expected1 =
  2314. &(BinaryFPOpParameters[6].m_StringTable);
  2315. WEX::TestExecution::TestDataArray<WEX::Common::String> *Validation_Expected2 =
  2316. &(BinaryFPOpParameters[7].m_StringTable);
  2317. LPCWSTR Validation_Type = BinaryFPOpParameters[8].m_str;
  2318. double Validation_Tolerance = BinaryFPOpParameters[9].m_double;
  2319. size_t count = BinaryFPOpParameters[10].m_uint;
  2320. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  2321. pDevice, m_support, pStream, "BinaryFPOp",
  2322. // this callbacked is called when the test
  2323. // is creating the resource to run the test
  2324. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  2325. VERIFY_IS_TRUE(0 == _stricmp(Name, "SBinaryFPOp"));
  2326. size_t size = sizeof(SBinaryFPOp) * count;
  2327. Data.resize(size);
  2328. SBinaryFPOp *pPrimitives = (SBinaryFPOp *)Data.data();
  2329. for (size_t i = 0; i < count; ++i) {
  2330. SBinaryFPOp *p = &pPrimitives[i];
  2331. PCWSTR str1 = (*Validation_Input1)[i % Validation_Input1->GetSize()];
  2332. PCWSTR str2 = (*Validation_Input2)[i % Validation_Input2->GetSize()];
  2333. float val1, val2;
  2334. VERIFY_SUCCEEDED(ParseDataToFloat(str1, val1));
  2335. VERIFY_SUCCEEDED(ParseDataToFloat(str2, val2));
  2336. p->input1 = val1;
  2337. p->input2 = val2;
  2338. }
  2339. // use shader from data table
  2340. pShaderOp->Shaders.at(0).Text = shader.Text;
  2341. });
  2342. MappedData data;
  2343. test->Test->GetReadBackData("SBinaryFPOp", &data);
  2344. SBinaryFPOp *pPrimitives = (SBinaryFPOp *)data.data();
  2345. WEX::TestExecution::DisableVerifyExceptions dve;
  2346. for (unsigned i = 0; i < count; ++i) {
  2347. SBinaryFPOp *p = &pPrimitives[i];
  2348. LPCWSTR str1 = (*Validation_Expected1)[i % Validation_Expected1->GetSize()];
  2349. LPCWSTR str2 = (*Validation_Expected2)[i % Validation_Expected2->GetSize()];
  2350. float val1, val2;
  2351. VERIFY_SUCCEEDED(ParseDataToFloat(str1, val1));
  2352. VERIFY_SUCCEEDED(ParseDataToFloat(str2, val2));
  2353. LogCommentFmt(L"element #%u, input1 = %10f, input2 = %10f, output1 = "
  2354. L"%10f, expected1 = %10f, output2 = %10f, expected2 = %10f",
  2355. i, p->input1, p->input2, p->output1, val1, p->output2,
  2356. val2);
  2357. VerifyOutputWithExpectedValueFloat(p->output1, val1, Validation_Type,
  2358. Validation_Tolerance);
  2359. VerifyOutputWithExpectedValueFloat(p->output2, val2, Validation_Type,
  2360. Validation_Tolerance);
  2361. }
  2362. }
  2363. TEST_F(ExecutionTest, TertiaryFloatOpTest) {
  2364. WEX::TestExecution::SetVerifyOutput verifySettings(
  2365. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  2366. CComPtr<IStream> pStream;
  2367. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  2368. CComPtr<ID3D12Device> pDevice;
  2369. if (!CreateDevice(&pDevice)) {
  2370. return;
  2371. }
  2372. // Read data from the table
  2373. VERIFY_SUCCEEDED(ParseTableRow(TertiaryFPOpParameters, sizeof(TertiaryFPOpParameters) / sizeof(TableParameter)));
  2374. st::ShaderOpShader shader;
  2375. CW2A Name(TertiaryFPOpParameters[0].m_str);
  2376. CW2A Target(TertiaryFPOpParameters[1].m_str);
  2377. CW2A EntryPoint(TertiaryFPOpParameters[2].m_str);
  2378. CW2A Text(TertiaryFPOpParameters[3].m_str);
  2379. shader.Name = Name.m_psz;
  2380. shader.Target = Target.m_psz;
  2381. shader.EntryPoint = EntryPoint.m_psz;
  2382. shader.Text = Text.m_psz;
  2383. WEX::TestExecution::TestDataArray<WEX::Common::String> *Validation_Input1 =
  2384. &(TertiaryFPOpParameters[4].m_StringTable);
  2385. WEX::TestExecution::TestDataArray<WEX::Common::String> *Validation_Input2 =
  2386. &(TertiaryFPOpParameters[5].m_StringTable);
  2387. WEX::TestExecution::TestDataArray<WEX::Common::String> *Validation_Input3 =
  2388. &(TertiaryFPOpParameters[6].m_StringTable);
  2389. WEX::TestExecution::TestDataArray<WEX::Common::String> *Validation_Expected =
  2390. &(TertiaryFPOpParameters[7].m_StringTable);
  2391. LPCWSTR Validation_Type = TertiaryFPOpParameters[8].m_str;
  2392. double Validation_Tolerance = TertiaryFPOpParameters[9].m_double;
  2393. size_t count = TertiaryFPOpParameters[10].m_uint;
  2394. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  2395. pDevice, m_support, pStream, "TertiaryFPOp",
  2396. // this callbacked is called when the test
  2397. // is creating the resource to run the test
  2398. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  2399. VERIFY_IS_TRUE(0 == _stricmp(Name, "STertiaryFPOp"));
  2400. size_t size = sizeof(STertiaryFPOp) * count;
  2401. Data.resize(size);
  2402. STertiaryFPOp *pPrimitives = (STertiaryFPOp *)Data.data();
  2403. for (size_t i = 0; i < count; ++i) {
  2404. STertiaryFPOp *p = &pPrimitives[i];
  2405. PCWSTR str1 = (*Validation_Input1)[i % Validation_Input1->GetSize()];
  2406. PCWSTR str2 = (*Validation_Input2)[i % Validation_Input2->GetSize()];
  2407. PCWSTR str3 = (*Validation_Input3)[i % Validation_Input3->GetSize()];
  2408. float val1, val2, val3;
  2409. VERIFY_SUCCEEDED(ParseDataToFloat(str1, val1));
  2410. VERIFY_SUCCEEDED(ParseDataToFloat(str2, val2));
  2411. VERIFY_SUCCEEDED(ParseDataToFloat(str3, val3));
  2412. p->input1 = val1;
  2413. p->input2 = val2;
  2414. p->input3 = val3;
  2415. }
  2416. // use shader from data table
  2417. pShaderOp->Shaders.at(0).Text = shader.Text;
  2418. });
  2419. MappedData data;
  2420. test->Test->GetReadBackData("STertiaryFPOp", &data);
  2421. STertiaryFPOp *pPrimitives = (STertiaryFPOp *)data.data();
  2422. WEX::TestExecution::DisableVerifyExceptions dve;
  2423. for (unsigned i = 0; i < count; ++i) {
  2424. STertiaryFPOp *p = &pPrimitives[i];
  2425. LPCWSTR str = (*Validation_Expected)[i % Validation_Expected->GetSize()];
  2426. float val;
  2427. VERIFY_SUCCEEDED(ParseDataToFloat(str, val));
  2428. LogCommentFmt(L"element #%u, input1 = %10f, input2 = %10f, input3 = %10f, output1 = "
  2429. L"%10f, expected = %10f",
  2430. i, p->input1, p->input2, p->input3, p->output, val);
  2431. VerifyOutputWithExpectedValueFloat(p->output, val, Validation_Type,
  2432. Validation_Tolerance);
  2433. }
  2434. }
  2435. TEST_F(ExecutionTest, UnaryIntOpTest) {
  2436. WEX::TestExecution::SetVerifyOutput verifySettings(
  2437. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  2438. CComPtr<IStream> pStream;
  2439. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  2440. CComPtr<ID3D12Device> pDevice;
  2441. if (!CreateDevice(&pDevice)) {
  2442. return;
  2443. }
  2444. // Read data from the table
  2445. VERIFY_SUCCEEDED(ParseTableRow(UnaryIntOpParameters,
  2446. sizeof(UnaryIntOpParameters) / sizeof(TableParameter)));
  2447. st::ShaderOpShader shader;
  2448. CW2A Name(UnaryIntOpParameters[0].m_str);
  2449. CW2A Target(UnaryIntOpParameters[1].m_str);
  2450. CW2A EntryPoint(UnaryIntOpParameters[2].m_str);
  2451. CW2A Text(UnaryIntOpParameters[3].m_str);
  2452. shader.Name = Name.m_psz;
  2453. shader.Target = Target.m_psz;
  2454. shader.EntryPoint = EntryPoint.m_psz;
  2455. shader.Text = Text.m_psz;
  2456. WEX::TestExecution::TestDataArray<int> *Validation_Input =
  2457. &UnaryIntOpParameters[4].m_intTable;
  2458. WEX::TestExecution::TestDataArray<int> *Validation_Expected =
  2459. &UnaryIntOpParameters[5].m_intTable;
  2460. int Validation_Tolerance = UnaryIntOpParameters[6].m_int;
  2461. size_t count = UnaryIntOpParameters[7].m_uint;
  2462. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  2463. pDevice, m_support, pStream, "UnaryIntOp",
  2464. // this callbacked is called when the test
  2465. // is creating the resource to run the test
  2466. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  2467. VERIFY_IS_TRUE(0 == _stricmp(Name, "SUnaryIntOp"));
  2468. size_t size = sizeof(SUnaryIntOp) * count;
  2469. Data.resize(size);
  2470. SUnaryIntOp *pPrimitives = (SUnaryIntOp *)Data.data();
  2471. for (size_t i = 0; i < count; ++i) {
  2472. SUnaryIntOp *p = &pPrimitives[i];
  2473. int val = (*Validation_Input)[i % Validation_Input->GetSize()];
  2474. p->input = val;
  2475. }
  2476. // use shader data table
  2477. pShaderOp->Shaders.at(0).Text = shader.Text;
  2478. });
  2479. MappedData data;
  2480. test->Test->GetReadBackData("SUnaryIntOp", &data);
  2481. SUnaryIntOp *pPrimitives = (SUnaryIntOp *)data.data();
  2482. WEX::TestExecution::DisableVerifyExceptions dve;
  2483. for (unsigned i = 0; i < count; ++i) {
  2484. SUnaryIntOp *p = &pPrimitives[i];
  2485. int val = (*Validation_Expected)[i % Validation_Expected->GetSize()];
  2486. LogCommentFmt(L"element #%u, input = %11i(0x%08x), output = %11i(0x%08x), "
  2487. L"expected = %11i(0x%08x)",
  2488. i, p->input, p->input, p->output, p->output, val, val);
  2489. VerifyOutputWithExpectedValueInt(p->output, val, Validation_Tolerance);
  2490. }
  2491. }
  2492. TEST_F(ExecutionTest, UnaryUintOpTest) {
  2493. WEX::TestExecution::SetVerifyOutput verifySettings(
  2494. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  2495. CComPtr<IStream> pStream;
  2496. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  2497. CComPtr<ID3D12Device> pDevice;
  2498. if (!CreateDevice(&pDevice)) {
  2499. return;
  2500. }
  2501. // Read data from the table
  2502. VERIFY_SUCCEEDED(ParseTableRow(UnaryUintOpParameters,
  2503. sizeof(UnaryUintOpParameters) / sizeof(TableParameter)));
  2504. st::ShaderOpShader shader;
  2505. CW2A Name(UnaryUintOpParameters[0].m_str);
  2506. CW2A Target(UnaryUintOpParameters[1].m_str);
  2507. CW2A EntryPoint(UnaryUintOpParameters[2].m_str);
  2508. CW2A Text(UnaryUintOpParameters[3].m_str);
  2509. shader.Name = Name.m_psz;
  2510. shader.Target = Target.m_psz;
  2511. shader.EntryPoint = EntryPoint.m_psz;
  2512. shader.Text = Text.m_psz;
  2513. WEX::TestExecution::TestDataArray<unsigned int> *Validation_Input =
  2514. &UnaryUintOpParameters[4].m_uintTable;
  2515. WEX::TestExecution::TestDataArray<unsigned int> *Validation_Expected =
  2516. &UnaryUintOpParameters[5].m_uintTable;
  2517. int Validation_Tolerance = UnaryUintOpParameters[6].m_int;
  2518. size_t count = UnaryUintOpParameters[7].m_uint;
  2519. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  2520. pDevice, m_support, pStream, "UnaryUintOp",
  2521. // this callbacked is called when the test
  2522. // is creating the resource to run the test
  2523. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  2524. VERIFY_IS_TRUE(0 == _stricmp(Name, "SUnaryUintOp"));
  2525. size_t size = sizeof(SUnaryUintOp) * count;
  2526. Data.resize(size);
  2527. SUnaryUintOp *pPrimitives = (SUnaryUintOp *)Data.data();
  2528. for (size_t i = 0; i < count; ++i) {
  2529. SUnaryUintOp *p = &pPrimitives[i];
  2530. unsigned int val = (*Validation_Input)[i % Validation_Input->GetSize()];
  2531. p->input = val;
  2532. }
  2533. // use shader data table
  2534. pShaderOp->Shaders.at(0).Text = shader.Text;
  2535. });
  2536. MappedData data;
  2537. test->Test->GetReadBackData("SUnaryUintOp", &data);
  2538. SUnaryUintOp *pPrimitives = (SUnaryUintOp *)data.data();
  2539. WEX::TestExecution::DisableVerifyExceptions dve;
  2540. for (unsigned i = 0; i < count; ++i) {
  2541. SUnaryUintOp *p = &pPrimitives[i];
  2542. unsigned int val = (*Validation_Expected)[i % Validation_Expected->GetSize()];
  2543. LogCommentFmt(L"element #%u, input = %11u(0x%08x), output = %11u(0x%08x), "
  2544. L"expected = %11u(0x%08x)",
  2545. i, p->input, p->input, p->output, p->output, val, val);
  2546. VerifyOutputWithExpectedValueInt(p->output, val, Validation_Tolerance);
  2547. }
  2548. }
  2549. TEST_F(ExecutionTest, BinaryIntOpTest) {
  2550. WEX::TestExecution::SetVerifyOutput verifySettings(
  2551. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  2552. CComPtr<IStream> pStream;
  2553. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  2554. CComPtr<ID3D12Device> pDevice;
  2555. if (!CreateDevice(&pDevice)) {
  2556. return;
  2557. }
  2558. // Read data from the table
  2559. VERIFY_SUCCEEDED(
  2560. ParseTableRow(BinaryIntOpParameters,
  2561. sizeof(BinaryIntOpParameters) / sizeof(TableParameter)));
  2562. st::ShaderOpShader shader;
  2563. CW2A Name(BinaryIntOpParameters[0].m_str);
  2564. CW2A Target(BinaryIntOpParameters[1].m_str);
  2565. CW2A EntryPoint(BinaryIntOpParameters[2].m_str);
  2566. CW2A Text(BinaryIntOpParameters[3].m_str);
  2567. shader.Name = Name.m_psz;
  2568. shader.Target = Target.m_psz;
  2569. shader.EntryPoint = EntryPoint.m_psz;
  2570. shader.Text = Text.m_psz;
  2571. int numExpected = BinaryIntOpParameters[4].m_int;
  2572. WEX::TestExecution::TestDataArray<int> *Validation_Input1 =
  2573. &BinaryIntOpParameters[5].m_intTable;
  2574. WEX::TestExecution::TestDataArray<int> *Validation_Input2 =
  2575. &BinaryIntOpParameters[6].m_intTable;
  2576. WEX::TestExecution::TestDataArray<int> *Validation_Expected1 =
  2577. &BinaryIntOpParameters[7].m_intTable;
  2578. WEX::TestExecution::TestDataArray<int> *Validation_Expected2 =
  2579. &BinaryIntOpParameters[8].m_intTable;
  2580. int Validation_Tolerance = BinaryIntOpParameters[9].m_int;
  2581. size_t count = BinaryIntOpParameters[10].m_uint;
  2582. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  2583. pDevice, m_support, pStream, "BinaryIntOp",
  2584. // this callbacked is called when the test
  2585. // is creating the resource to run the test
  2586. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  2587. VERIFY_IS_TRUE(0 == _stricmp(Name, "SBinaryIntOp"));
  2588. size_t size = sizeof(SBinaryIntOp) * count;
  2589. Data.resize(size);
  2590. SBinaryIntOp *pPrimitives = (SBinaryIntOp *)Data.data();
  2591. for (size_t i = 0; i < count; ++i) {
  2592. SBinaryIntOp *p = &pPrimitives[i];
  2593. int val1 = (*Validation_Input1)[i % Validation_Input1->GetSize()];
  2594. int val2 = (*Validation_Input2)[i % Validation_Input2->GetSize()];
  2595. p->input1 = val1;
  2596. p->input2 = val2;
  2597. }
  2598. // use shader from data table
  2599. pShaderOp->Shaders.at(0).Text = shader.Text;
  2600. });
  2601. MappedData data;
  2602. test->Test->GetReadBackData("SBinaryIntOp", &data);
  2603. SBinaryIntOp *pPrimitives = (SBinaryIntOp *)data.data();
  2604. WEX::TestExecution::DisableVerifyExceptions dve;
  2605. if (numExpected == 2) {
  2606. for (unsigned i = 0; i < count; ++i) {
  2607. SBinaryIntOp *p = &pPrimitives[i];
  2608. int val1 = (*Validation_Expected1)[i % Validation_Expected1->GetSize()];
  2609. int val2 = (*Validation_Expected2)[i % Validation_Expected2->GetSize()];
  2610. LogCommentFmt(L"element #%u, input1 = %11i(0x%08x), input2 = "
  2611. L"%11i(0x%08x), output1 = "
  2612. L"%11i(0x%08x), expected1 = %11i(0x%08x), output2 = "
  2613. L"%11i(0x%08x), expected2 = %11i(0x%08x)",
  2614. i, p->input1, p->input1, p->input2, p->input2, p->output1,
  2615. p->output1, val1, val1, p->output2, p->output2, val2,
  2616. val2);
  2617. VerifyOutputWithExpectedValueInt(p->output1, val1, Validation_Tolerance);
  2618. VerifyOutputWithExpectedValueInt(p->output2, val2, Validation_Tolerance);
  2619. }
  2620. }
  2621. else if (numExpected == 1) {
  2622. for (unsigned i = 0; i < count; ++i) {
  2623. SBinaryIntOp *p = &pPrimitives[i];
  2624. int val1 = (*Validation_Expected1)[i % Validation_Expected1->GetSize()];
  2625. LogCommentFmt(L"element #%u, input1 = %11i(0x%08x), input2 = "
  2626. L"%11i(0x%08x), output = "
  2627. L"%11i(0x%08x), expected = %11i(0x%08x)", i,
  2628. p->input1, p->input1, p->input2, p->input2,
  2629. p->output1, p->output1, val1, val1);
  2630. VerifyOutputWithExpectedValueInt(p->output1, val1, Validation_Tolerance);
  2631. }
  2632. }
  2633. else {
  2634. LogErrorFmt(L"Unexpected number of expected values for operation %i", numExpected);
  2635. }
  2636. }
  2637. TEST_F(ExecutionTest, TertiaryIntOpTest) {
  2638. WEX::TestExecution::SetVerifyOutput verifySettings(
  2639. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  2640. CComPtr<IStream> pStream;
  2641. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  2642. CComPtr<ID3D12Device> pDevice;
  2643. if (!CreateDevice(&pDevice)) {
  2644. return;
  2645. }
  2646. // Read data from the table
  2647. VERIFY_SUCCEEDED(
  2648. ParseTableRow(TertiaryIntOpParameters,
  2649. sizeof(TertiaryIntOpParameters) / sizeof(TableParameter)));
  2650. st::ShaderOpShader shader;
  2651. CW2A Name(TertiaryIntOpParameters[0].m_str);
  2652. CW2A Target(TertiaryIntOpParameters[1].m_str);
  2653. CW2A EntryPoint(TertiaryIntOpParameters[2].m_str);
  2654. CW2A Text(TertiaryIntOpParameters[3].m_str);
  2655. shader.Name = Name.m_psz;
  2656. shader.Target = Target.m_psz;
  2657. shader.EntryPoint = EntryPoint.m_psz;
  2658. shader.Text = Text.m_psz;
  2659. WEX::TestExecution::TestDataArray<int> *Validation_Input1 =
  2660. &TertiaryIntOpParameters[4].m_intTable;
  2661. WEX::TestExecution::TestDataArray<int> *Validation_Input2 =
  2662. &TertiaryIntOpParameters[5].m_intTable;
  2663. WEX::TestExecution::TestDataArray<int> *Validation_Input3 =
  2664. &TertiaryIntOpParameters[6].m_intTable;
  2665. WEX::TestExecution::TestDataArray<int> *Validation_Expected =
  2666. &TertiaryIntOpParameters[7].m_intTable;
  2667. int Validation_Tolerance = TertiaryIntOpParameters[8].m_int;
  2668. size_t count = TertiaryIntOpParameters[9].m_uint;
  2669. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  2670. pDevice, m_support, pStream, "TertiaryIntOp",
  2671. // this callbacked is called when the test
  2672. // is creating the resource to run the test
  2673. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  2674. VERIFY_IS_TRUE(0 == _stricmp(Name, "STertiaryIntOp"));
  2675. size_t size = sizeof(STertiaryIntOp) * count;
  2676. Data.resize(size);
  2677. STertiaryIntOp *pPrimitives = (STertiaryIntOp *)Data.data();
  2678. for (size_t i = 0; i < count; ++i) {
  2679. STertiaryIntOp *p = &pPrimitives[i];
  2680. int val1 = (*Validation_Input1)[i % Validation_Input1->GetSize()];
  2681. int val2 = (*Validation_Input2)[i % Validation_Input2->GetSize()];
  2682. int val3 = (*Validation_Input3)[i % Validation_Input3->GetSize()];
  2683. p->input1 = val1;
  2684. p->input2 = val2;
  2685. p->input3 = val3;
  2686. }
  2687. // use shader from data table
  2688. pShaderOp->Shaders.at(0).Text = shader.Text;
  2689. });
  2690. MappedData data;
  2691. test->Test->GetReadBackData("STertiaryIntOp", &data);
  2692. STertiaryIntOp *pPrimitives = (STertiaryIntOp *)data.data();
  2693. WEX::TestExecution::DisableVerifyExceptions dve;
  2694. for (unsigned i = 0; i < count; ++i) {
  2695. STertiaryIntOp *p = &pPrimitives[i];
  2696. int val1 = (*Validation_Expected)[i % Validation_Expected->GetSize()];
  2697. LogCommentFmt(L"element #%u, input1 = %11i(0x%08x), input2 = "
  2698. L"%11i(0x%08x), input3= %11i(0x%08x), output = "
  2699. L"%11i(0x%08x), expected = %11i(0x%08x)",
  2700. i, p->input1, p->input1, p->input2, p->input2,
  2701. p->input3, p->input3, p->output, p->output, val1,
  2702. val1);
  2703. VerifyOutputWithExpectedValueInt(p->output, val1, Validation_Tolerance);
  2704. }
  2705. }
  2706. TEST_F(ExecutionTest, BinaryUintOpTest) {
  2707. WEX::TestExecution::SetVerifyOutput verifySettings(
  2708. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  2709. CComPtr<IStream> pStream;
  2710. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  2711. CComPtr<ID3D12Device> pDevice;
  2712. if (!CreateDevice(&pDevice)) {
  2713. return;
  2714. }
  2715. // Read data from the table
  2716. VERIFY_SUCCEEDED(
  2717. ParseTableRow(BinaryUintOpParameters,
  2718. sizeof(BinaryUintOpParameters) / sizeof(TableParameter)));
  2719. st::ShaderOpShader shader;
  2720. CW2A Name(BinaryUintOpParameters[0].m_str);
  2721. CW2A Target(BinaryUintOpParameters[1].m_str);
  2722. CW2A EntryPoint(BinaryUintOpParameters[2].m_str);
  2723. CW2A Text(BinaryUintOpParameters[3].m_str);
  2724. shader.Name = Name.m_psz;
  2725. shader.Target = Target.m_psz;
  2726. shader.EntryPoint = EntryPoint.m_psz;
  2727. shader.Text = Text.m_psz;
  2728. int numExpected = BinaryUintOpParameters[4].m_int;
  2729. WEX::TestExecution::TestDataArray<unsigned int> *Validation_Input1 =
  2730. &BinaryUintOpParameters[5].m_uintTable;
  2731. WEX::TestExecution::TestDataArray<unsigned int> *Validation_Input2 =
  2732. &BinaryUintOpParameters[6].m_uintTable;
  2733. WEX::TestExecution::TestDataArray<unsigned int> *Validation_Expected1 =
  2734. &BinaryUintOpParameters[7].m_uintTable;
  2735. WEX::TestExecution::TestDataArray<unsigned int> *Validation_Expected2 =
  2736. &BinaryUintOpParameters[8].m_uintTable;
  2737. int Validation_Tolerance = BinaryUintOpParameters[9].m_int;
  2738. size_t count = BinaryUintOpParameters[10].m_uint;
  2739. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  2740. pDevice, m_support, pStream, "BinaryUintOp",
  2741. // this callbacked is called when the test
  2742. // is creating the resource to run the test
  2743. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  2744. VERIFY_IS_TRUE(0 == _stricmp(Name, "SBinaryUintOp"));
  2745. size_t size = sizeof(SBinaryUintOp) * count;
  2746. Data.resize(size);
  2747. SBinaryUintOp *pPrimitives = (SBinaryUintOp *)Data.data();
  2748. for (size_t i = 0; i < count; ++i) {
  2749. SBinaryUintOp *p = &pPrimitives[i];
  2750. unsigned int val1 = (*Validation_Input1)[i % Validation_Input1->GetSize()];
  2751. unsigned int val2 = (*Validation_Input2)[i % Validation_Input2->GetSize()];
  2752. p->input1 = val1;
  2753. p->input2 = val2;
  2754. }
  2755. // use shader from data table
  2756. pShaderOp->Shaders.at(0).Text = shader.Text;
  2757. });
  2758. MappedData data;
  2759. test->Test->GetReadBackData("SBinaryUintOp", &data);
  2760. SBinaryUintOp *pPrimitives = (SBinaryUintOp *)data.data();
  2761. WEX::TestExecution::DisableVerifyExceptions dve;
  2762. if (numExpected == 2) {
  2763. for (unsigned i = 0; i < count; ++i) {
  2764. SBinaryUintOp *p = &pPrimitives[i];
  2765. unsigned int val1 = (*Validation_Expected1)[i % Validation_Expected1->GetSize()];
  2766. unsigned int val2 = (*Validation_Expected2)[i % Validation_Expected2->GetSize()];
  2767. LogCommentFmt(L"element #%u, input1 = %11u(0x%08x), input2 = "
  2768. L"%11u(0x%08x), output1 = "
  2769. L"%11u(0x%08x), expected1 = %11u(0x%08x), output2 = "
  2770. L"%11u(0x%08x), expected2 = %11u(0x%08x)",
  2771. i, p->input1, p->input1, p->input2, p->input2, p->output1,
  2772. p->output1, val1, val1, p->output2, p->output2, val2,
  2773. val2);
  2774. VerifyOutputWithExpectedValueInt(p->output1, val1, Validation_Tolerance);
  2775. VerifyOutputWithExpectedValueInt(p->output2, val2, Validation_Tolerance);
  2776. }
  2777. }
  2778. else if (numExpected == 1) {
  2779. for (unsigned i = 0; i < count; ++i) {
  2780. SBinaryUintOp *p = &pPrimitives[i];
  2781. unsigned int val1 = (*Validation_Expected1)[i % Validation_Expected1->GetSize()];
  2782. LogCommentFmt(L"element #%u, input1 = %11u(0x%08x), input2 = "
  2783. L"%11u(0x%08x), output = "
  2784. L"%11u(0x%08x), expected = %11u(0x%08x)", i,
  2785. p->input1, p->input1, p->input2, p->input2,
  2786. p->output1, p->output1, val1, val1);
  2787. VerifyOutputWithExpectedValueInt(p->output1, val1, Validation_Tolerance);
  2788. }
  2789. }
  2790. else {
  2791. LogErrorFmt(L"Unexpected number of expected values for operation %i", numExpected);
  2792. }
  2793. }
  2794. TEST_F(ExecutionTest, TertiaryUintOpTest) {
  2795. WEX::TestExecution::SetVerifyOutput verifySettings(
  2796. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  2797. CComPtr<IStream> pStream;
  2798. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  2799. CComPtr<ID3D12Device> pDevice;
  2800. if (!CreateDevice(&pDevice)) {
  2801. return;
  2802. }
  2803. // Read data from the table
  2804. VERIFY_SUCCEEDED(
  2805. ParseTableRow(TertiaryUintOpParameters,
  2806. sizeof(TertiaryUintOpParameters) / sizeof(TableParameter)));
  2807. st::ShaderOpShader shader;
  2808. CW2A Name(TertiaryUintOpParameters[0].m_str);
  2809. CW2A Target(TertiaryUintOpParameters[1].m_str);
  2810. CW2A EntryPoint(TertiaryUintOpParameters[2].m_str);
  2811. CW2A Text(TertiaryUintOpParameters[3].m_str);
  2812. shader.Name = Name.m_psz;
  2813. shader.Target = Target.m_psz;
  2814. shader.EntryPoint = EntryPoint.m_psz;
  2815. shader.Text = Text.m_psz;
  2816. WEX::TestExecution::TestDataArray<unsigned int> *Validation_Input1 =
  2817. &TertiaryUintOpParameters[4].m_uintTable;
  2818. WEX::TestExecution::TestDataArray<unsigned int> *Validation_Input2 =
  2819. &TertiaryUintOpParameters[5].m_uintTable;
  2820. WEX::TestExecution::TestDataArray<unsigned int> *Validation_Input3 =
  2821. &TertiaryUintOpParameters[6].m_uintTable;
  2822. WEX::TestExecution::TestDataArray<unsigned int> *Validation_Expected =
  2823. &TertiaryUintOpParameters[7].m_uintTable;
  2824. int Validation_Tolerance = TertiaryUintOpParameters[8].m_int;
  2825. size_t count = TertiaryUintOpParameters[9].m_uint;
  2826. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  2827. pDevice, m_support, pStream, "TertiaryUintOp",
  2828. // this callbacked is called when the test
  2829. // is creating the resource to run the test
  2830. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  2831. VERIFY_IS_TRUE(0 == _stricmp(Name, "STertiaryUintOp"));
  2832. size_t size = sizeof(STertiaryUintOp) * count;
  2833. Data.resize(size);
  2834. STertiaryUintOp *pPrimitives = (STertiaryUintOp *)Data.data();
  2835. for (size_t i = 0; i < count; ++i) {
  2836. STertiaryUintOp *p = &pPrimitives[i];
  2837. unsigned int val1 = (*Validation_Input1)[i % Validation_Input1->GetSize()];
  2838. unsigned int val2 = (*Validation_Input2)[i % Validation_Input2->GetSize()];
  2839. unsigned int val3 = (*Validation_Input3)[i % Validation_Input3->GetSize()];
  2840. p->input1 = val1;
  2841. p->input2 = val2;
  2842. p->input3 = val3;
  2843. }
  2844. // use shader from data table
  2845. pShaderOp->Shaders.at(0).Text = shader.Text;
  2846. });
  2847. MappedData data;
  2848. test->Test->GetReadBackData("STertiaryUintOp", &data);
  2849. STertiaryUintOp *pPrimitives = (STertiaryUintOp *)data.data();
  2850. WEX::TestExecution::DisableVerifyExceptions dve;
  2851. for (unsigned i = 0; i < count; ++i) {
  2852. STertiaryUintOp *p = &pPrimitives[i];
  2853. unsigned int val1 = (*Validation_Expected)[i % Validation_Expected->GetSize()];
  2854. LogCommentFmt(L"element #%u, input1 = %11u(0x%08x), input2 = "
  2855. L"%11u(0x%08x), input3 = %11u(0x%08x), output = "
  2856. L"%11u(0x%08x), expected = %11u(0x%08x)", i,
  2857. p->input1, p->input1, p->input2, p->input2, p->input3, p->input3,
  2858. p->output, p->output, val1, val1);
  2859. VerifyOutputWithExpectedValueInt(p->output, val1, Validation_Tolerance);
  2860. }
  2861. }
  2862. TEST_F(ExecutionTest, DotTest) {
  2863. WEX::TestExecution::SetVerifyOutput verifySettings(
  2864. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  2865. CComPtr<IStream> pStream;
  2866. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  2867. CComPtr<ID3D12Device> pDevice;
  2868. if (!CreateDevice(&pDevice)) {
  2869. return;
  2870. }
  2871. VERIFY_SUCCEEDED(ParseTableRow(
  2872. DotOpParameters, sizeof(DotOpParameters) / sizeof(DotOpParameters[0])));
  2873. st::ShaderOpShader shader;
  2874. CW2A Name(DotOpParameters[0].m_str);
  2875. CW2A Target(DotOpParameters[1].m_str);
  2876. CW2A EntryPoint(DotOpParameters[2].m_str);
  2877. CW2A Text(DotOpParameters[3].m_str);
  2878. shader.Name = Name.m_psz;
  2879. shader.Target = Target.m_psz;
  2880. shader.EntryPoint = EntryPoint.m_psz;
  2881. shader.Text = Text.m_psz;
  2882. WEX::TestExecution::TestDataArray<WEX::Common::String> *Validation_Input1 =
  2883. &DotOpParameters[4].m_StringTable;
  2884. WEX::TestExecution::TestDataArray<WEX::Common::String> *Validation_Input2 =
  2885. &DotOpParameters[5].m_StringTable;
  2886. WEX::TestExecution::TestDataArray<WEX::Common::String> *Validation_dot2 =
  2887. &DotOpParameters[6].m_StringTable;
  2888. WEX::TestExecution::TestDataArray<WEX::Common::String> *Validation_dot3 =
  2889. &DotOpParameters[7].m_StringTable;
  2890. WEX::TestExecution::TestDataArray<WEX::Common::String> *Validation_dot4 =
  2891. &DotOpParameters[8].m_StringTable;
  2892. PCWSTR Validation_type = DotOpParameters[9].m_str;
  2893. double tolerance = DotOpParameters[10].m_double;
  2894. unsigned int count = DotOpParameters[11].m_uint;
  2895. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  2896. pDevice, m_support, pStream, "DotOp",
  2897. // this callbacked is called when the test
  2898. // is creating the resource to run the test
  2899. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  2900. VERIFY_IS_TRUE(0 == _stricmp(Name, "SDotOp"));
  2901. size_t size = sizeof(SDotOp) * count;
  2902. Data.resize(size);
  2903. SDotOp *pPrimitives = (SDotOp*)Data.data();
  2904. for (size_t i = 0; i < count; ++i) {
  2905. SDotOp *p = &pPrimitives[i];
  2906. float4 val1,val2;
  2907. VERIFY_SUCCEEDED(ParseDataToVectorFloat((*Validation_Input1)[i],
  2908. (float *)&val1, 4));
  2909. VERIFY_SUCCEEDED(ParseDataToVectorFloat((*Validation_Input2)[i],
  2910. (float *)&val2, 4));
  2911. p->input1 = val1;
  2912. p->input2 = val2;
  2913. }
  2914. // use shader from data table
  2915. pShaderOp->Shaders.at(0).Text = shader.Text;
  2916. });
  2917. MappedData data;
  2918. test->Test->GetReadBackData("SDotOp", &data);
  2919. SDotOp *pPrimitives = (SDotOp*)data.data();
  2920. WEX::TestExecution::DisableVerifyExceptions dve;
  2921. for (size_t i = 0; i < count; ++i) {
  2922. SDotOp *p = &pPrimitives[i];
  2923. float dot2, dot3, dot4;
  2924. VERIFY_SUCCEEDED(ParseDataToFloat((*Validation_dot2)[i], dot2));
  2925. VERIFY_SUCCEEDED(ParseDataToFloat((*Validation_dot3)[i], dot3));
  2926. VERIFY_SUCCEEDED(ParseDataToFloat((*Validation_dot4)[i], dot4));
  2927. LogCommentFmt(
  2928. L"element #%u, input1 = (%f, %f, %f, %f), input2 = (%f, %f, "
  2929. L"%f, %f), \n dot2 = %f, dot2_expected = %f, dot3 = %f, "
  2930. L"dot3_expected = %f, dot4 = %f, dot4_expected = %f",
  2931. i, p->input1.x, p->input1.y, p->input1.z, p->input1.w, p->input2.x,
  2932. p->input2.y, p->input2.z, p->input2.w, p->o_dot2, dot2, p->o_dot3, dot3,
  2933. p->o_dot4, dot4);
  2934. VerifyOutputWithExpectedValueFloat(p->o_dot2, dot2, Validation_type,
  2935. tolerance);
  2936. VerifyOutputWithExpectedValueFloat(p->o_dot3, dot3, Validation_type,
  2937. tolerance);
  2938. VerifyOutputWithExpectedValueFloat(p->o_dot4, dot4, Validation_type,
  2939. tolerance);
  2940. }
  2941. }
  2942. TEST_F(ExecutionTest, Msad4Test) {
  2943. WEX::TestExecution::SetVerifyOutput verifySettings(
  2944. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  2945. CComPtr<IStream> pStream;
  2946. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  2947. CComPtr<ID3D12Device> pDevice;
  2948. if (!CreateDevice(&pDevice)) {
  2949. return;
  2950. }
  2951. VERIFY_SUCCEEDED(ParseTableRow(
  2952. Msad4OpParameters, sizeof(Msad4OpParameters) / sizeof(Msad4OpParameters[0])));
  2953. CW2A Text(Msad4OpParameters[0].m_str);
  2954. double tolerance = Msad4OpParameters[1].m_double;
  2955. unsigned int count = Msad4OpParameters[2].m_uint;
  2956. WEX::TestExecution::TestDataArray<unsigned int> *Validation_Reference =
  2957. &Msad4OpParameters[3].m_uintTable;
  2958. WEX::TestExecution::TestDataArray<WEX::Common::String> *Validation_Source =
  2959. &Msad4OpParameters[4].m_StringTable;
  2960. WEX::TestExecution::TestDataArray<WEX::Common::String> *Validation_Accum =
  2961. &Msad4OpParameters[5].m_StringTable;
  2962. WEX::TestExecution::TestDataArray<WEX::Common::String> *Validation_Expected =
  2963. &Msad4OpParameters[6].m_StringTable;
  2964. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  2965. pDevice, m_support, pStream, "Msad4",
  2966. // this callbacked is called when the test
  2967. // is creating the resource to run the test
  2968. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  2969. VERIFY_IS_TRUE(0 == _stricmp(Name, "SMsad4"));
  2970. size_t size = sizeof(SMsad4) * count;
  2971. Data.resize(size);
  2972. SMsad4 *pPrimitives = (SMsad4*)Data.data();
  2973. for (size_t i = 0; i < count; ++i) {
  2974. SMsad4 *p = &pPrimitives[i];
  2975. uint2 src;
  2976. uint4 accum;
  2977. VERIFY_SUCCEEDED(ParseDataToVectorUint((*Validation_Source)[i], (unsigned int*)&src, 2));
  2978. VERIFY_SUCCEEDED(ParseDataToVectorUint((*Validation_Accum)[i], (unsigned int*)&accum, 4));
  2979. p->ref = (*Validation_Reference)[i];
  2980. p->src = src;
  2981. p->accum = accum;
  2982. }
  2983. // use shader from data table
  2984. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  2985. });
  2986. MappedData data;
  2987. test->Test->GetReadBackData("SMsad4", &data);
  2988. SMsad4 *pPrimitives = (SMsad4*)data.data();
  2989. WEX::TestExecution::DisableVerifyExceptions dve;
  2990. for (size_t i = 0; i < count; ++i) {
  2991. SMsad4 *p = &pPrimitives[i];
  2992. uint4 result;
  2993. VERIFY_SUCCEEDED(ParseDataToVectorUint((*Validation_Expected)[i],
  2994. (unsigned int *)&result, 4));
  2995. LogCommentFmt(
  2996. L"element #%u, ref = %u(0x%08x), src = %u(0x%08x), %u(0x%08x), "
  2997. L"accum = %u(0x%08x), %u(0x%08x), %u(0x%08x), %u(0x%08x),\n"
  2998. L"result = %u(0x%08x), %u(0x%08x), %u(0x%08x), %u(0x%08x),\n"
  2999. L"expected = %u(0x%08x), %u(0x%08x), %u(0x%08x), %u(0x%08x)", i,
  3000. p->ref, p->ref, p->src.x, p->src.x, p->src.y, p->src.y, p->accum.x,
  3001. p->accum.x, p->accum.y, p->accum.y, p->accum.z, p->accum.z,
  3002. p->accum.w, p->accum.w, p->result.x, p->result.x, p->result.y,
  3003. p->result.y, p->result.z, p->result.z, p->result.w, p->result.w,
  3004. result.x, result.x, result.y, result.y, result.z, result.z,
  3005. result.w, result.w);
  3006. VerifyOutputWithExpectedValueInt(p->result.x, result.x, tolerance);
  3007. VerifyOutputWithExpectedValueInt(p->result.y, result.y, tolerance);
  3008. VerifyOutputWithExpectedValueInt(p->result.z, result.z, tolerance);
  3009. VerifyOutputWithExpectedValueInt(p->result.w, result.w, tolerance);
  3010. }
  3011. }
  3012. static void WriteReadBackDump(st::ShaderOp *pShaderOp, st::ShaderOpTest *pTest,
  3013. char **pReadBackDump) {
  3014. std::stringstream str;
  3015. unsigned count = 0;
  3016. for (auto &R : pShaderOp->Resources) {
  3017. if (!R.ReadBack)
  3018. continue;
  3019. ++count;
  3020. str << "Resource: " << R.Name << "\r\n";
  3021. // Find a descriptor that can tell us how to dump this resource.
  3022. bool found = false;
  3023. for (auto &Heaps : pShaderOp->DescriptorHeaps) {
  3024. for (auto &D : Heaps.Descriptors) {
  3025. if (_stricmp(D.ResName, R.Name) != 0) {
  3026. continue;
  3027. }
  3028. found = true;
  3029. if (_stricmp(D.Kind, "UAV") != 0) {
  3030. str << "Resource dump for kind " << D.Kind << " not implemented yet.\r\n";
  3031. break;
  3032. }
  3033. if (D.UavDesc.ViewDimension != D3D12_UAV_DIMENSION_BUFFER) {
  3034. str << "Resource dump for this kind of view dimension not implemented yet.\r\n";
  3035. break;
  3036. }
  3037. // We can map back to the structure if a structured buffer via the shader, but
  3038. // we'll keep this simple and simply dump out 32-bit uint/float representations.
  3039. MappedData data;
  3040. pTest->GetReadBackData(R.Name, &data);
  3041. uint32_t *pData = (uint32_t *)data.data();
  3042. size_t u32_count = R.Desc.Width / sizeof(uint32_t);
  3043. for (size_t i = 0; i < u32_count; ++i) {
  3044. float f = *(float *)pData;
  3045. str << i << ": 0n" << *pData << " 0x" << std::hex << *pData
  3046. << std::dec << " " << f << "\r\n";
  3047. ++pData;
  3048. }
  3049. break;
  3050. }
  3051. if (found) break;
  3052. }
  3053. if (!found) {
  3054. str << "Unable to find a view for the resource.\r\n";
  3055. }
  3056. }
  3057. str << "Resources read back: " << count << "\r\n";
  3058. std::string s(str.str());
  3059. CComHeapPtr<char> pDump;
  3060. if (!pDump.Allocate(s.size() + 1))
  3061. throw std::bad_alloc();
  3062. memcpy(pDump.m_pData, s.data(), s.size());
  3063. pDump.m_pData[s.size()] = '\0';
  3064. *pReadBackDump = pDump.Detach();
  3065. }
  3066. // This is the exported interface by use from HLSLHost.exe.
  3067. // It's exclusive with the use of the DLL as a TAEF target.
  3068. extern "C" {
  3069. __declspec(dllexport) HRESULT WINAPI InitializeOpTests(void *pStrCtx, st::OutputStringFn pOutputStrFn) {
  3070. HRESULT hr = EnableExperimentalShaderModels();
  3071. if (FAILED(hr)) {
  3072. pOutputStrFn(pStrCtx, L"Unable to enable experimental shader models.\r\n.");
  3073. }
  3074. return S_OK;
  3075. }
  3076. __declspec(dllexport) HRESULT WINAPI
  3077. RunOpTest(void *pStrCtx, st::OutputStringFn pOutputStrFn, LPCSTR pText,
  3078. ID3D12Device *pDevice, ID3D12CommandQueue *pCommandQueue,
  3079. ID3D12Resource *pRenderTarget, char **pReadBackDump) {
  3080. HRESULT hr;
  3081. if (pReadBackDump) *pReadBackDump = nullptr;
  3082. st::SetOutputFn(pStrCtx, pOutputStrFn);
  3083. CComPtr<ID3D12InfoQueue> pInfoQueue;
  3084. CComHeapPtr<char> pDump;
  3085. bool FilterCreation = false;
  3086. if (SUCCEEDED(pDevice->QueryInterface(&pInfoQueue))) {
  3087. // Creation is largely driven by inputs, so don't log create/destroy messages.
  3088. pInfoQueue->PushEmptyStorageFilter();
  3089. pInfoQueue->PushEmptyRetrievalFilter();
  3090. if (FilterCreation) {
  3091. D3D12_INFO_QUEUE_FILTER filter;
  3092. D3D12_MESSAGE_CATEGORY denyCategories[] = { D3D12_MESSAGE_CATEGORY_STATE_CREATION };
  3093. ZeroMemory(&filter, sizeof(filter));
  3094. filter.DenyList.NumCategories = _countof(denyCategories);
  3095. filter.DenyList.pCategoryList = denyCategories;
  3096. pInfoQueue->PushStorageFilter(&filter);
  3097. }
  3098. }
  3099. else {
  3100. pOutputStrFn(pStrCtx, L"Unable to enable info queue for D3D.\r\n.");
  3101. }
  3102. try {
  3103. dxc::DxcDllSupport m_support;
  3104. m_support.Initialize();
  3105. const char *pName = nullptr;
  3106. CComPtr<IStream> pStream = SHCreateMemStream((BYTE *)pText, strlen(pText));
  3107. std::shared_ptr<st::ShaderOpSet> ShaderOpSet =
  3108. std::make_shared<st::ShaderOpSet>();
  3109. st::ParseShaderOpSetFromStream(pStream, ShaderOpSet.get());
  3110. st::ShaderOp *pShaderOp;
  3111. if (pName == nullptr) {
  3112. if (ShaderOpSet->ShaderOps.size() != 1) {
  3113. pOutputStrFn(pStrCtx, L"Expected a single shader operation.\r\n");
  3114. return E_FAIL;
  3115. }
  3116. pShaderOp = ShaderOpSet->ShaderOps[0].get();
  3117. }
  3118. else {
  3119. pShaderOp = ShaderOpSet->GetShaderOp(pName);
  3120. }
  3121. if (pShaderOp == nullptr) {
  3122. std::string msg = "Unable to find shader op ";
  3123. msg += pName;
  3124. msg += "; available ops";
  3125. const char sep = ':';
  3126. for (auto &pAvailOp : ShaderOpSet->ShaderOps) {
  3127. msg += sep;
  3128. msg += pAvailOp->Name ? pAvailOp->Name : "[n/a]";
  3129. }
  3130. CA2W msgWide(msg.c_str());
  3131. pOutputStrFn(pStrCtx, msgWide);
  3132. return E_FAIL;
  3133. }
  3134. std::shared_ptr<st::ShaderOpTest> test = std::make_shared<st::ShaderOpTest>();
  3135. test->SetupRenderTarget(pShaderOp, pDevice, pCommandQueue, pRenderTarget);
  3136. test->SetDxcSupport(&m_support);
  3137. test->RunShaderOp(pShaderOp);
  3138. test->PresentRenderTarget(pShaderOp, pCommandQueue, pRenderTarget);
  3139. pOutputStrFn(pStrCtx, L"Rendering complete.\r\n");
  3140. if (!pShaderOp->IsCompute()) {
  3141. D3D12_QUERY_DATA_PIPELINE_STATISTICS stats;
  3142. test->GetPipelineStats(&stats);
  3143. wchar_t statsText[400];
  3144. StringCchPrintfW(statsText, _countof(statsText),
  3145. L"Vertices/primitives read by input assembler: %I64u/%I64u\r\n"
  3146. L"Vertex shader invocations: %I64u\r\n"
  3147. L"Geometry shader invocations/output primitive: %I64u/%I64u\r\n"
  3148. L"Primitives sent to rasterizer/rendered: %I64u/%I64u\r\n"
  3149. L"PS/HS/DS/CS invocations: %I64u/%I64u/%I64u/%I64u\r\n",
  3150. stats.IAVertices, stats.IAPrimitives, stats.VSInvocations,
  3151. stats.GSInvocations, stats.GSPrimitives, stats.CInvocations,
  3152. stats.CPrimitives, stats.PSInvocations, stats.HSInvocations,
  3153. stats.DSInvocations, stats.CSInvocations);
  3154. pOutputStrFn(pStrCtx, statsText);
  3155. }
  3156. if (pReadBackDump) {
  3157. WriteReadBackDump(pShaderOp, test.get(), &pDump);
  3158. }
  3159. hr = S_OK;
  3160. }
  3161. catch (const CAtlException &E)
  3162. {
  3163. hr = E.m_hr;
  3164. }
  3165. catch (const std::bad_alloc &)
  3166. {
  3167. hr = E_OUTOFMEMORY;
  3168. }
  3169. catch (const std::exception &)
  3170. {
  3171. hr = E_FAIL;
  3172. }
  3173. // Drain the device message queue if available.
  3174. if (pInfoQueue != nullptr) {
  3175. wchar_t buf[200];
  3176. StringCchPrintfW(buf, _countof(buf),
  3177. L"NumStoredMessages=%u limit/discarded by limit=%u/%u "
  3178. L"allowed/denied by storage filter=%u/%u "
  3179. L"NumStoredMessagesAllowedByRetrievalFilter=%u\r\n",
  3180. (unsigned)pInfoQueue->GetNumStoredMessages(),
  3181. (unsigned)pInfoQueue->GetMessageCountLimit(),
  3182. (unsigned)pInfoQueue->GetNumMessagesDiscardedByMessageCountLimit(),
  3183. (unsigned)pInfoQueue->GetNumMessagesAllowedByStorageFilter(),
  3184. (unsigned)pInfoQueue->GetNumMessagesDeniedByStorageFilter(),
  3185. (unsigned)pInfoQueue->GetNumStoredMessagesAllowedByRetrievalFilter());
  3186. pOutputStrFn(pStrCtx, buf);
  3187. WriteInfoQueueMessages(pStrCtx, pOutputStrFn, pInfoQueue);
  3188. pInfoQueue->ClearStoredMessages();
  3189. pInfoQueue->PopRetrievalFilter();
  3190. pInfoQueue->PopStorageFilter();
  3191. if (FilterCreation) {
  3192. pInfoQueue->PopStorageFilter();
  3193. }
  3194. }
  3195. if (pReadBackDump) *pReadBackDump = pDump.Detach();
  3196. return hr;
  3197. }
  3198. }