ExecutionTest.cpp 143 KB

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