/renderdoc/driver/d3d11/d3d11_device.cpp

https://github.com/tgAncel/renderdoc · C++ · 3141 lines · 2447 code · 620 blank · 74 comment · 537 complexity · 271988827e54fda78adb439c44a28c8d MD5 · raw file

  1. /******************************************************************************
  2. * The MIT License (MIT)
  3. *
  4. * Copyright (c) 2014 Crytek
  5. *
  6. * Permission is hereby granted, free of charge, to any person obtaining a copy
  7. * of this software and associated documentation files (the "Software"), to deal
  8. * in the Software without restriction, including without limitation the rights
  9. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. * copies of the Software, and to permit persons to whom the Software is
  11. * furnished to do so, subject to the following conditions:
  12. *
  13. * The above copyright notice and this permission notice shall be included in
  14. * all copies or substantial portions of the Software.
  15. *
  16. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. * THE SOFTWARE.
  23. ******************************************************************************/
  24. #include "core/core.h"
  25. #include "common/string_utils.h"
  26. #include "maths/formatpacking.h"
  27. #include <d3d11shadertracing.h>
  28. #include "driver/dxgi/dxgi_wrapped.h"
  29. #include "driver/d3d11/d3d11_device.h"
  30. #include "driver/d3d11/d3d11_resources.h"
  31. #include "driver/d3d11/d3d11_renderstate.h"
  32. #include "driver/d3d11/d3d11_context.h"
  33. #include "3rdparty/jpeg-compressor/jpge.h"
  34. const char *D3D11ChunkNames[] =
  35. {
  36. "ID3D11Device::Initialisation",
  37. "ID3D11Resource::SetDebugName",
  38. "ID3D11Resource::Release",
  39. "IDXGISwapChain::GetBuffer",
  40. "ID3D11Device::CreateTexture1D",
  41. "ID3D11Device::CreateTexture2D",
  42. "ID3D11Device::CreateTexture3D",
  43. "ID3D11Device::CreateBuffer",
  44. "ID3D11Device::CreateVertexShader",
  45. "ID3D11Device::CreateHullShader",
  46. "ID3D11Device::CreateDomainShader",
  47. "ID3D11Device::CreateGeometryShader",
  48. "ID3D11Device::CreateGeometryShaderWithStreamOut",
  49. "ID3D11Device::CreatePixelShader",
  50. "ID3D11Device::CreateComputeShader",
  51. "ID3D11ClassLinkage::GetClassInstance",
  52. "ID3D11ClassLinkage::CreateClassInstance",
  53. "ID3D11Device::CreateClassLinkage",
  54. "ID3D11Device::CreateShaderResourceView",
  55. "ID3D11Device::CreateRenderTargetView",
  56. "ID3D11Device::CreateDepthStencilView",
  57. "ID3D11Device::CreateUnorderedAccessView",
  58. "ID3D11Device::CreateInputLayout",
  59. "ID3D11Device::CreateBlendState",
  60. "ID3D11Device::CreateDepthStencilState",
  61. "ID3D11Device::CreateRasterizerState",
  62. "ID3D11Device::CreateSamplerState",
  63. "ID3D11Device::CreateQuery",
  64. "ID3D11Device::CreatePredicate",
  65. "ID3D11Device::CreateCounter",
  66. "ID3D11Device::CreateDeferredContext",
  67. "ID3D11Device::SetExceptionMode",
  68. "ID3D11Device::OpenSharedResource",
  69. "Capture",
  70. "ID3D11DeviceContext::IASetInputLayout",
  71. "ID3D11DeviceContext::IASetVertexBuffers",
  72. "ID3D11DeviceContext::IASetIndexBuffer",
  73. "ID3D11DeviceContext::IASetPrimitiveTopology",
  74. "ID3D11DeviceContext::VSSetConstantBuffers",
  75. "ID3D11DeviceContext::VSSetShaderResources",
  76. "ID3D11DeviceContext::VSSetSamplers",
  77. "ID3D11DeviceContext::VSSetShader",
  78. "ID3D11DeviceContext::HSSetConstantBuffers",
  79. "ID3D11DeviceContext::HSSetShaderResources",
  80. "ID3D11DeviceContext::HSSetSamplers",
  81. "ID3D11DeviceContext::HSSetShader",
  82. "ID3D11DeviceContext::DSSetConstantBuffers",
  83. "ID3D11DeviceContext::DSSetShaderResources",
  84. "ID3D11DeviceContext::DSSetSamplers",
  85. "ID3D11DeviceContext::DSSetShader",
  86. "ID3D11DeviceContext::GSSetConstantBuffers",
  87. "ID3D11DeviceContext::GSSetShaderResources",
  88. "ID3D11DeviceContext::GSSetSamplers",
  89. "ID3D11DeviceContext::GSSetShader",
  90. "ID3D11DeviceContext::SOSetTargets",
  91. "ID3D11DeviceContext::PSSetConstantBuffers",
  92. "ID3D11DeviceContext::PSSetShaderResources",
  93. "ID3D11DeviceContext::PSSetSamplers",
  94. "ID3D11DeviceContext::PSSetShader",
  95. "ID3D11DeviceContext::CSSetConstantBuffers",
  96. "ID3D11DeviceContext::CSSetShaderResources",
  97. "ID3D11DeviceContext::CSSetUnorderedAccessViews",
  98. "ID3D11DeviceContext::CSSetSamplers",
  99. "ID3D11DeviceContext::CSSetShader",
  100. "ID3D11DeviceContext::RSSetViewports",
  101. "ID3D11DeviceContext::RSSetScissors",
  102. "ID3D11DeviceContext::RSSetState",
  103. "ID3D11DeviceContext::OMSetRenderTargets",
  104. "ID3D11DeviceContext::OMSetRenderTargetsAndUnorderedAccessViews",
  105. "ID3D11DeviceContext::OMSetBlendState",
  106. "ID3D11DeviceContext::OMSetDepthStencilState",
  107. "ID3D11DeviceContext::DrawIndexedInstanced",
  108. "ID3D11DeviceContext::DrawInstanced",
  109. "ID3D11DeviceContext::DrawIndexed",
  110. "ID3D11DeviceContext::Draw",
  111. "ID3D11DeviceContext::DrawAuto",
  112. "ID3D11DeviceContext::DrawIndexedInstancedIndirect",
  113. "ID3D11DeviceContext::DrawInstancedIndirect",
  114. "ID3D11DeviceContext::Map",
  115. "ID3D11DeviceContext::Unmap",
  116. "ID3D11DeviceContext::CopySubresourceRegion",
  117. "ID3D11DeviceContext::CopyResource",
  118. "ID3D11DeviceContext::UpdateSubresource",
  119. "ID3D11DeviceContext::CopyStructureCount",
  120. "ID3D11DeviceContext::ResolveSubresource",
  121. "ID3D11DeviceContext::GenerateMips",
  122. "ID3D11DeviceContext::ClearDepthStencilView",
  123. "ID3D11DeviceContext::ClearRenderTargetView",
  124. "ID3D11DeviceContext::ClearUnorderedAccessViewInt",
  125. "ID3D11DeviceContext::ClearUnorderedAccessViewFloat",
  126. "ID3D11DeviceContext::ClearState",
  127. "ID3D11DeviceContext::ExecuteCommandList",
  128. "ID3D11DeviceContext::Dispatch",
  129. "ID3D11DeviceContext::DispatchIndirect",
  130. "ID3D11DeviceContext::FinishCommandlist",
  131. "ID3D11DeviceContext::Flush",
  132. "ID3D11DeviceContext::SetPredication",
  133. "ID3D11DeviceContext::SetResourceMinLOD",
  134. "ID3D11DeviceContext::Begin",
  135. "ID3D11DeviceContext::End",
  136. "ID3D11Device1::CreateRasterizerState1",
  137. "ID3D11Device1::CreateBlendState1",
  138. "ID3D11DeviceContext1::CopySubresourceRegion1",
  139. "ID3D11DeviceContext1::UpdateSubresource1",
  140. "ID3D11DeviceContext1::ClearView",
  141. "ID3D11DeviceContext1::VSSetConstantBuffers1",
  142. "ID3D11DeviceContext1::HSSetConstantBuffers1",
  143. "ID3D11DeviceContext1::DSSetConstantBuffers1",
  144. "ID3D11DeviceContext1::GSSetConstantBuffers1",
  145. "ID3D11DeviceContext1::PSSetConstantBuffers1",
  146. "ID3D11DeviceContext1::CSSetConstantBuffers1",
  147. "D3DPERF_PushMarker",
  148. "D3DPERF_SetMarker",
  149. "D3DPERF_PopMarker",
  150. "DebugMessageList",
  151. "ContextBegin",
  152. "ContextEnd",
  153. };
  154. WRAPPED_POOL_INST(WrappedID3D11Device);
  155. WrappedID3D11Device *WrappedID3D11Device::m_pCurrentWrappedDevice = NULL;
  156. D3D11InitParams::D3D11InitParams()
  157. {
  158. SerialiseVersion = D3D11_SERIALISE_VERSION;
  159. DriverType = D3D_DRIVER_TYPE_UNKNOWN;
  160. Flags = 0;
  161. SDKVersion = D3D11_SDK_VERSION;
  162. NumFeatureLevels = 0;
  163. RDCEraseEl(FeatureLevels);
  164. }
  165. ReplayCreateStatus D3D11InitParams::Serialise()
  166. {
  167. SERIALISE_ELEMENT(uint32_t, ver, D3D11_SERIALISE_VERSION); SerialiseVersion = ver;
  168. if(ver != D3D11_SERIALISE_VERSION)
  169. {
  170. RDCERR("Incompatible D3D11 serialise version, expected %d got %d", D3D11_SERIALISE_VERSION, ver);
  171. return eReplayCreate_APIIncompatibleVersion;
  172. }
  173. SERIALISE_ELEMENT(D3D_DRIVER_TYPE, driverType, DriverType); DriverType = driverType;
  174. SERIALISE_ELEMENT(uint32_t, flags, Flags); Flags = flags;
  175. SERIALISE_ELEMENT(uint32_t, sdk, SDKVersion); SDKVersion = sdk;
  176. SERIALISE_ELEMENT(uint32_t, numlevels, NumFeatureLevels); NumFeatureLevels = numlevels;
  177. m_pSerialiser->Serialise<ARRAY_COUNT(FeatureLevels)>("FeatureLevels", FeatureLevels);
  178. return eReplayCreate_Success;
  179. }
  180. void WrappedID3D11Device::SetLogFile(const wchar_t *logfile)
  181. {
  182. #if defined(RELEASE)
  183. const bool debugSerialiser = false;
  184. #else
  185. const bool debugSerialiser = true;
  186. #endif
  187. m_pSerialiser = new Serialiser(logfile, Serialiser::READING, debugSerialiser);
  188. m_pSerialiser->SetChunkNameLookup(&GetChunkName);
  189. m_pImmediateContext->SetSerialiser(m_pSerialiser);
  190. }
  191. WrappedID3D11Device::WrappedID3D11Device(ID3D11Device* realDevice, D3D11InitParams *params)
  192. : m_RefCounter(realDevice, false), m_SoftRefCounter(NULL, false), m_pDevice(realDevice)
  193. {
  194. if(RenderDoc::Inst().GetCrashHandler())
  195. RenderDoc::Inst().GetCrashHandler()->RegisterMemoryRegion(this, sizeof(WrappedID3D11Device));
  196. m_pDevice1 = NULL;
  197. m_pDevice->QueryInterface(__uuidof(ID3D11Device1), (void **)&m_pDevice1);
  198. m_Replay.SetDevice(this);
  199. m_DebugManager = NULL;
  200. m_ResourceManager = new D3D11ResourceManager(this);
  201. // refcounters implicitly construct with one reference, but we don't start with any soft
  202. // references.
  203. m_SoftRefCounter.Release();
  204. m_InternalRefcount = 0;
  205. m_Alive = true;
  206. m_DummyInfo.m_pDevice = this;
  207. m_FrameCounter = 0;
  208. m_FailedFrame = 0;
  209. m_FailedReason = CaptureSucceeded;
  210. m_Failures = 0;
  211. m_SwapChain = NULL;
  212. m_FrameTimer.Restart();
  213. m_TotalTime = m_AvgFrametime = m_MinFrametime = m_MaxFrametime = 0.0;
  214. m_CurFileSize = 0;
  215. #if defined(RELEASE)
  216. const bool debugSerialiser = false;
  217. #else
  218. const bool debugSerialiser = true;
  219. #endif
  220. if(RenderDoc::Inst().IsReplayApp())
  221. {
  222. m_State = READING;
  223. m_pSerialiser = NULL;
  224. m_pDebugSerialiser = NULL;
  225. TrackedResource::SetReplayResourceIDs();
  226. }
  227. else
  228. {
  229. m_State = WRITING_IDLE;
  230. m_pSerialiser = new Serialiser(NULL, Serialiser::WRITING, debugSerialiser);
  231. #ifdef DEBUG_TEXT_SERIALISER
  232. m_pDebugSerialiser = new Serialiser(L"./debuglog.txt", Serialiser::DEBUGWRITING, true);
  233. #else
  234. m_pDebugSerialiser = NULL;
  235. #endif
  236. }
  237. if(m_pSerialiser)
  238. m_pSerialiser->SetChunkNameLookup(&GetChunkName);
  239. // create a temporary and grab its resource ID
  240. m_ResourceID = TrackedResource().GetResourceID();
  241. m_DeviceRecord = NULL;
  242. if(!RenderDoc::Inst().IsReplayApp())
  243. {
  244. m_DeviceRecord = GetResourceManager()->AddResourceRecord(m_ResourceID);
  245. m_DeviceRecord->DataInSerialiser = false;
  246. m_DeviceRecord->SpecialResource = true;
  247. m_DeviceRecord->Length = 0;
  248. m_DeviceRecord->NumSubResources = 0;
  249. m_DeviceRecord->SubResources = NULL;
  250. }
  251. ID3D11DeviceContext *context = NULL;
  252. realDevice->GetImmediateContext(&context);
  253. m_pImmediateContext = new WrappedID3D11DeviceContext(this, context, m_pSerialiser, m_pDebugSerialiser);
  254. SAFE_RELEASE(context);
  255. realDevice->QueryInterface(__uuidof(ID3D11InfoQueue), (void **)&m_pInfoQueue);
  256. if(m_pInfoQueue)
  257. {
  258. m_pInfoQueue->SetMuteDebugOutput(true);
  259. UINT size = m_pInfoQueue->GetStorageFilterStackSize();
  260. while(size > 1)
  261. {
  262. m_pInfoQueue->ClearStorageFilter();
  263. size = m_pInfoQueue->GetStorageFilterStackSize();
  264. }
  265. size = m_pInfoQueue->GetRetrievalFilterStackSize();
  266. while(size > 1)
  267. {
  268. m_pInfoQueue->ClearRetrievalFilter();
  269. size = m_pInfoQueue->GetRetrievalFilterStackSize();
  270. }
  271. m_pInfoQueue->ClearStoredMessages();
  272. if(RenderDoc::Inst().IsReplayApp())
  273. m_pInfoQueue->SetMuteDebugOutput(false);
  274. }
  275. else
  276. {
  277. RDCDEBUG("Couldn't get ID3D11InfoQueue.");
  278. }
  279. m_InitParams = params;
  280. SetContextFilter(ResourceId(), 0, 0);
  281. // ATI workaround - these dlls can get unloaded and cause a crash.
  282. if(GetModuleHandleA("aticfx32.dll"))
  283. LoadLibraryA("aticfx32.dll");
  284. if(GetModuleHandleA("atiuxpag.dll"))
  285. LoadLibraryA("atiuxpag.dll");
  286. if(GetModuleHandleA("atidxx32.dll"))
  287. LoadLibraryA("atidxx32.dll");
  288. if(GetModuleHandleA("aticfx64.dll"))
  289. LoadLibraryA("aticfx64.dll");
  290. if(GetModuleHandleA("atiuxp64.dll"))
  291. LoadLibraryA("atiuxp64.dll");
  292. if(GetModuleHandleA("atidxx64.dll"))
  293. LoadLibraryA("atidxx64.dll");
  294. //////////////////////////////////////////////////////////////////////////
  295. // Compile time asserts
  296. RDCCOMPILE_ASSERT(ARRAY_COUNT(D3D11ChunkNames) == NUM_D3D11_CHUNKS-FIRST_CHUNK_ID, "Not right number of chunk names");
  297. }
  298. WrappedID3D11Device::~WrappedID3D11Device()
  299. {
  300. SAFE_DELETE(m_InitParams);
  301. if(m_pCurrentWrappedDevice == this)
  302. m_pCurrentWrappedDevice = NULL;
  303. for(auto it = m_CachedStateObjects.begin(); it != m_CachedStateObjects.end(); ++it)
  304. if(*it)
  305. (*it)->Release();
  306. m_CachedStateObjects.clear();
  307. SAFE_RELEASE(m_pDevice1);
  308. SAFE_RELEASE(m_pImmediateContext);
  309. for(auto it = m_SwapChains.begin(); it != m_SwapChains.end(); ++it)
  310. SAFE_RELEASE(it->second);
  311. SAFE_DELETE(m_DebugManager);
  312. if(m_DeviceRecord)
  313. {
  314. RDCASSERT(m_DeviceRecord->GetRefCount() == 1);
  315. m_DeviceRecord->Delete(GetResourceManager());
  316. }
  317. m_ResourceManager->Shutdown();
  318. SAFE_DELETE(m_ResourceManager);
  319. SAFE_RELEASE(m_pInfoQueue);
  320. SAFE_RELEASE(m_pDevice);
  321. SAFE_DELETE(m_pSerialiser);
  322. SAFE_DELETE(m_pDebugSerialiser);
  323. for(auto it=m_LayoutDXBC.begin(); it != m_LayoutDXBC.end(); ++it)
  324. SAFE_DELETE(it->second);
  325. m_LayoutDXBC.clear();
  326. m_LayoutDescs.clear();
  327. if(RenderDoc::Inst().GetCrashHandler())
  328. RenderDoc::Inst().GetCrashHandler()->UnregisterMemoryRegion(this);
  329. }
  330. void WrappedID3D11Device::CheckForDeath()
  331. {
  332. if(!m_Alive) return;
  333. if(m_RefCounter.GetRefCount() == 0)
  334. {
  335. RDCASSERT(m_SoftRefCounter.GetRefCount() >= m_InternalRefcount);
  336. if(m_SoftRefCounter.GetRefCount() <= m_InternalRefcount || m_State < WRITING) // MEGA HACK
  337. {
  338. m_Alive = false;
  339. delete this;
  340. }
  341. }
  342. }
  343. ULONG STDMETHODCALLTYPE DummyID3D11InfoQueue::AddRef()
  344. {
  345. m_pDevice->AddRef();
  346. return 1;
  347. }
  348. ULONG STDMETHODCALLTYPE DummyID3D11InfoQueue::Release()
  349. {
  350. m_pDevice->Release();
  351. return 1;
  352. }
  353. HRESULT WrappedID3D11Device::QueryInterface(REFIID riid, void **ppvObject)
  354. {
  355. // DEFINE_GUID(IID_IDirect3DDevice9, 0xd0223b96, 0xbf7a, 0x43fd, 0x92, 0xbd, 0xa4, 0x3b, 0xd, 0x82, 0xb9, 0xeb);
  356. static const GUID IDirect3DDevice9_uuid = { 0xd0223b96, 0xbf7a, 0x43fd, { 0x92, 0xbd, 0xa4, 0x3b, 0xd, 0x82, 0xb9, 0xeb } };
  357. //DEFINE_GUID(IID_ID3D11Device2,0x9d06dffa,0xd1e5,0x4d07,0x83,0xa8,0x1b,0xb1,0x23,0xf2,0xf8,0x41);
  358. static const GUID ID3D11Device2_uuid = { 0x9d06dffa, 0xd1e5, 0x4d07, { 0x83, 0xa8, 0x1b, 0xb1, 0x23, 0xf2, 0xf8, 0x41 } };
  359. //1fbad429-66ab-41cc-9617-667ac10e4459
  360. static const GUID ID3D11ShaderTraceFactory_uuid = { 0x1fbad429, 0x66ab, 0x41cc, { 0x96, 0x17, 0x66, 0x7a, 0xc1, 0x0e, 0x44, 0x59 } };
  361. if(riid == __uuidof(IDXGIDevice))
  362. {
  363. m_pDevice->QueryInterface(riid, ppvObject);
  364. IDXGIDevice *real = (IDXGIDevice *)(*ppvObject);
  365. *ppvObject = new WrappedIDXGIDevice(real, this);
  366. return S_OK;
  367. }
  368. else if(riid == __uuidof(IDXGIDevice1))
  369. {
  370. m_pDevice->QueryInterface(riid, ppvObject);
  371. IDXGIDevice1 *real = (IDXGIDevice1 *)(*ppvObject);
  372. *ppvObject = new WrappedIDXGIDevice1(real, this);
  373. return S_OK;
  374. }
  375. else if(riid == __uuidof(ID3D11Device))
  376. {
  377. AddRef();
  378. *ppvObject = (ID3D11Device *)this;
  379. return S_OK;
  380. }
  381. else if(riid == __uuidof(ID3D10Device))
  382. {
  383. RDCWARN("Trying to get ID3D10Device - not supported.");
  384. *ppvObject = NULL;
  385. return E_NOINTERFACE;
  386. }
  387. else if(riid == IDirect3DDevice9_uuid)
  388. {
  389. RDCWARN("Trying to get IDirect3DDevice9 - not supported.");
  390. *ppvObject = NULL;
  391. return E_NOINTERFACE;
  392. }
  393. else if(riid == __uuidof(ID3D11Device1))
  394. {
  395. AddRef();
  396. *ppvObject = (ID3D11Device1 *)this;
  397. return S_OK;
  398. }
  399. else if(riid == ID3D11Device2_uuid)
  400. {
  401. RDCWARN("Trying to get ID3D11Device2. DX11.2 not supported at this time.");
  402. *ppvObject = NULL;
  403. return E_NOINTERFACE;
  404. }
  405. else if(riid == __uuidof(ID3D11ShaderTraceFactory))
  406. {
  407. RDCWARN("Trying to get ID3D11ShaderTraceFactory. Not supported at this time.");
  408. *ppvObject = NULL;
  409. return E_NOINTERFACE;
  410. }
  411. else if(riid == __uuidof(ID3D11InfoQueue))
  412. {
  413. RDCWARN("Returning a dumy ID3D11InfoQueue that does nothing. This ID3D11InfoQueue will not work!");
  414. *ppvObject = (ID3D11InfoQueue *)&m_DummyInfo;
  415. m_DummyInfo.AddRef();
  416. return S_OK;
  417. }
  418. else
  419. {
  420. string guid = ToStr::Get(riid);
  421. RDCWARN("Querying ID3D11Device for interface: %hs", guid.c_str());
  422. }
  423. return m_RefCounter.QueryInterface(riid, ppvObject);
  424. }
  425. #if defined(ENABLE_NVIDIA_PERFKIT)
  426. #define NVPM_INITGUID
  427. #include STRINGIZE(CONCAT(NVIDIA_PERFKIT_DIR, inc\\NvPmApi.h))
  428. NvPmApi *nvAPI = NULL;
  429. #endif
  430. #if defined(ENABLE_NVIDIA_PERFKIT)
  431. int enumFunc(NVPMCounterID id, const char *name)
  432. {
  433. RDCLOG("(% 4d): %hs", id, name);
  434. return NVPM_OK;
  435. }
  436. #endif
  437. const char *WrappedID3D11Device::GetChunkName(uint32_t idx)
  438. {
  439. if(idx < FIRST_CHUNK_ID || idx >= NUM_D3D11_CHUNKS)
  440. return "<unknown>";
  441. return D3D11ChunkNames[idx-FIRST_CHUNK_ID];
  442. }
  443. void WrappedID3D11Device::LazyInit()
  444. {
  445. if(m_DebugManager == NULL)
  446. {
  447. m_DebugManager = new D3D11DebugManager(this);
  448. #if defined(ENABLE_NVIDIA_PERFKIT)
  449. HMODULE nvapi = LoadLibraryA(STRINGIZE(CONCAT(NVIDIA_PERFKIT_DIR, bin\\win7_x86\\NvPmApi.Core.dll)));
  450. if(nvapi == NULL)
  451. {
  452. RDCERR("Couldn't load perfkit");
  453. return;
  454. }
  455. NVPMGetExportTable_Pfn NVPMGetExportTable = (NVPMGetExportTable_Pfn)GetProcAddress(nvapi, "NVPMGetExportTable");
  456. if(NVPMGetExportTable == NULL)
  457. {
  458. RDCERR("Couldn't Get Symbol 'NVPMGetExportTable'");
  459. return;
  460. }
  461. NVPMRESULT nvResult = NVPMGetExportTable(&ETID_NvPmApi, (void **)&nvAPI);
  462. if(nvResult != NVPM_OK)
  463. {
  464. RDCERR("Couldn't NVPMGetExportTable");
  465. return;
  466. }
  467. nvResult = nvAPI->Init();
  468. if(nvResult != NVPM_OK)
  469. {
  470. RDCERR("Couldn't nvAPI->Init");
  471. return;
  472. }
  473. NVPMContext context(0);
  474. nvResult = nvAPI->CreateContextFromD3D11Device(m_pDevice, &context);
  475. if(nvResult != NVPM_OK)
  476. {
  477. RDCERR("Couldn't nvAPI->CreateContextFromD3D11Device");
  478. return;
  479. }
  480. nvAPI->EnumCountersByContext(context, &enumFunc);
  481. nvAPI->DestroyContext(context);
  482. nvAPI->Shutdown();
  483. nvAPI = NULL;
  484. FreeLibrary(nvapi);
  485. #endif
  486. }
  487. }
  488. vector<DebugMessage> WrappedID3D11Device::GetDebugMessages()
  489. {
  490. vector<DebugMessage> ret;
  491. if(!m_pInfoQueue)
  492. return ret;
  493. UINT64 numMessages = m_pInfoQueue->GetNumStoredMessagesAllowedByRetrievalFilter();
  494. for(UINT64 i=0; i < m_pInfoQueue->GetNumStoredMessagesAllowedByRetrievalFilter(); i++)
  495. {
  496. SIZE_T len = 0;
  497. m_pInfoQueue->GetMessage(i, NULL, &len);
  498. char *msgbuf = new char[len];
  499. D3D11_MESSAGE *message = (D3D11_MESSAGE *)msgbuf;
  500. m_pInfoQueue->GetMessage(i, message, &len);
  501. DebugMessage msg;
  502. msg.category = eDbgCategory_Miscellaneous;
  503. msg.severity = eDbgSeverity_Error;
  504. switch(message->Category)
  505. {
  506. case D3D11_MESSAGE_CATEGORY_APPLICATION_DEFINED:
  507. msg.category = eDbgCategory_Application_Defined;
  508. break;
  509. case D3D11_MESSAGE_CATEGORY_MISCELLANEOUS:
  510. msg.category = eDbgCategory_Miscellaneous;
  511. break;
  512. case D3D11_MESSAGE_CATEGORY_INITIALIZATION:
  513. msg.category = eDbgCategory_Initialization;
  514. break;
  515. case D3D11_MESSAGE_CATEGORY_CLEANUP:
  516. msg.category = eDbgCategory_Cleanup;
  517. break;
  518. case D3D11_MESSAGE_CATEGORY_COMPILATION:
  519. msg.category = eDbgCategory_Compilation;
  520. break;
  521. case D3D11_MESSAGE_CATEGORY_STATE_CREATION:
  522. msg.category = eDbgCategory_State_Creation;
  523. break;
  524. case D3D11_MESSAGE_CATEGORY_STATE_SETTING:
  525. msg.category = eDbgCategory_State_Setting;
  526. break;
  527. case D3D11_MESSAGE_CATEGORY_STATE_GETTING:
  528. msg.category = eDbgCategory_State_Getting;
  529. break;
  530. case D3D11_MESSAGE_CATEGORY_RESOURCE_MANIPULATION:
  531. msg.category = eDbgCategory_Resource_Manipulation;
  532. break;
  533. case D3D11_MESSAGE_CATEGORY_EXECUTION:
  534. msg.category = eDbgCategory_Execution;
  535. break;
  536. case D3D11_MESSAGE_CATEGORY_SHADER:
  537. msg.category = eDbgCategory_Shaders;
  538. break;
  539. default:
  540. RDCWARN("Unexpected message category: %d", message->Category);
  541. break;
  542. }
  543. switch(message->Severity)
  544. {
  545. case D3D11_MESSAGE_SEVERITY_CORRUPTION:
  546. msg.severity = eDbgSeverity_Corruption;
  547. break;
  548. case D3D11_MESSAGE_SEVERITY_ERROR:
  549. msg.severity = eDbgSeverity_Error;
  550. break;
  551. case D3D11_MESSAGE_SEVERITY_WARNING:
  552. msg.severity = eDbgSeverity_Warning;
  553. break;
  554. case D3D11_MESSAGE_SEVERITY_INFO:
  555. msg.severity = eDbgSeverity_Info;
  556. break;
  557. case D3D11_MESSAGE_SEVERITY_MESSAGE:
  558. msg.severity = eDbgSeverity_Info;
  559. break;
  560. default:
  561. RDCWARN("Unexpected message severity: %d", message->Severity);
  562. break;
  563. }
  564. msg.messageID = (uint32_t)message->ID;
  565. msg.description = string(message->pDescription);
  566. ret.push_back(msg);
  567. SAFE_DELETE_ARRAY(msgbuf);
  568. }
  569. // Docs are fuzzy on the thread safety of the info queue, but I'm going to assume it should only
  570. // ever be accessed on one thread since it's tied to the device & immediate context.
  571. // There doesn't seem to be a way to lock it for access and without that there's no way to know
  572. // that a new message won't be added between the time you retrieve the last one and clearing the
  573. // queue. There is also no way to pop a message that I can see, which would presumably be the
  574. // best way if its member functions are thread safe themselves (if the queue is protected internally).
  575. RDCASSERT(numMessages == m_pInfoQueue->GetNumStoredMessagesAllowedByRetrievalFilter());
  576. m_pInfoQueue->ClearStoredMessages();
  577. return ret;
  578. }
  579. void WrappedID3D11Device::ProcessChunk(uint64_t offset, D3D11ChunkType context)
  580. {
  581. switch(context)
  582. {
  583. case DEVICE_INIT:
  584. {
  585. SERIALISE_ELEMENT(ResourceId, immContextId, ResourceId());
  586. // add a reference for the resource manager - normally it takes ownership of the resource on creation and releases it
  587. // to destruction, but we want to control our immediate context ourselves.
  588. m_pImmediateContext->AddRef();
  589. m_ResourceManager->AddLiveResource(immContextId, m_pImmediateContext);
  590. break;
  591. }
  592. case SET_RESOURCE_NAME:
  593. Serialise_SetResourceName(0x0, "");
  594. break;
  595. case RELEASE_RESOURCE:
  596. Serialise_ReleaseResource(0x0);
  597. break;
  598. case CREATE_SWAP_BUFFER:
  599. Serialise_SetSwapChainTexture(0x0, 0x0, 0, 0x0);
  600. break;
  601. case CREATE_TEXTURE_1D:
  602. Serialise_CreateTexture1D(0x0, 0x0, 0x0);
  603. break;
  604. case CREATE_TEXTURE_2D:
  605. Serialise_CreateTexture2D(0x0, 0x0, 0x0);
  606. break;
  607. case CREATE_TEXTURE_3D:
  608. Serialise_CreateTexture3D(0x0, 0x0, 0x0);
  609. break;
  610. case CREATE_BUFFER:
  611. Serialise_CreateBuffer(0x0, 0x0, 0x0);
  612. break;
  613. case CREATE_VERTEX_SHADER:
  614. Serialise_CreateVertexShader(0x0, 0, 0x0, 0x0);
  615. break;
  616. case CREATE_HULL_SHADER:
  617. Serialise_CreateHullShader(0x0, 0, 0x0, 0x0);
  618. break;
  619. case CREATE_DOMAIN_SHADER:
  620. Serialise_CreateDomainShader(0x0, 0, 0x0, 0x0);
  621. break;
  622. case CREATE_GEOMETRY_SHADER:
  623. Serialise_CreateGeometryShader(0x0, 0, 0x0, 0x0);
  624. break;
  625. case CREATE_GEOMETRY_SHADER_WITH_SO:
  626. Serialise_CreateGeometryShaderWithStreamOutput(0x0, 0, 0x0, 0, 0x0, 0, 0, 0x0, 0x0);
  627. break;
  628. case CREATE_PIXEL_SHADER:
  629. Serialise_CreatePixelShader(0x0, 0, 0x0, 0x0);
  630. break;
  631. case CREATE_COMPUTE_SHADER:
  632. Serialise_CreateComputeShader(0x0, 0, 0x0, 0x0);
  633. break;
  634. case GET_CLASS_INSTANCE:
  635. Serialise_GetClassInstance(0x0, 0, 0x0, 0x0);
  636. break;
  637. case CREATE_CLASS_INSTANCE:
  638. Serialise_CreateClassInstance(0x0, 0, 0, 0, 0, 0x0, 0x0);
  639. break;
  640. case CREATE_CLASS_LINKAGE:
  641. Serialise_CreateClassLinkage(0x0);
  642. break;
  643. case CREATE_SRV:
  644. Serialise_CreateShaderResourceView(0x0, 0x0, 0x0);
  645. break;
  646. case CREATE_RTV:
  647. Serialise_CreateRenderTargetView(0x0, 0x0, 0x0);
  648. break;
  649. case CREATE_DSV:
  650. Serialise_CreateDepthStencilView(0x0, 0x0, 0x0);
  651. break;
  652. case CREATE_UAV:
  653. Serialise_CreateUnorderedAccessView(0x0, 0x0, 0x0);
  654. break;
  655. case CREATE_INPUT_LAYOUT:
  656. Serialise_CreateInputLayout(0x0, 0, 0x0, 0, 0x0);
  657. break;
  658. case CREATE_BLEND_STATE:
  659. Serialise_CreateBlendState(0x0, 0x0);
  660. break;
  661. case CREATE_BLEND_STATE1:
  662. Serialise_CreateBlendState1(0x0, 0x0);
  663. break;
  664. case CREATE_DEPTHSTENCIL_STATE:
  665. Serialise_CreateDepthStencilState(0x0, 0x0);
  666. break;
  667. case CREATE_RASTER_STATE:
  668. Serialise_CreateRasterizerState(0x0, 0x0);
  669. break;
  670. case CREATE_RASTER_STATE1:
  671. Serialise_CreateRasterizerState1(0x0, 0x0);
  672. break;
  673. case CREATE_SAMPLER_STATE:
  674. Serialise_CreateSamplerState(0x0, 0x0);
  675. break;
  676. case CREATE_QUERY:
  677. Serialise_CreateQuery(0x0, 0x0);
  678. break;
  679. case CREATE_PREDICATE:
  680. Serialise_CreatePredicate(0x0, 0x0);
  681. break;
  682. case CREATE_COUNTER:
  683. Serialise_CreateCounter(0x0, 0x0);
  684. break;
  685. case CREATE_DEFERRED_CONTEXT:
  686. Serialise_CreateDeferredContext(0, 0x0);
  687. break;
  688. case SET_EXCEPTION_MODE:
  689. Serialise_SetExceptionMode(0);
  690. break;
  691. case OPEN_SHARED_RESOURCE:
  692. {
  693. IID nul;
  694. Serialise_OpenSharedResource(0, nul, NULL);
  695. break;
  696. }
  697. case CAPTURE_SCOPE:
  698. Serialise_CaptureScope(offset);
  699. break;
  700. default:
  701. // ignore system chunks
  702. if(context == INITIAL_CONTENTS)
  703. Serialise_InitialState(NULL);
  704. else if(context < FIRST_CHUNK_ID)
  705. m_pSerialiser->SkipCurrentChunk();
  706. else
  707. m_pImmediateContext->ProcessChunk(offset, context, true);
  708. break;
  709. }
  710. }
  711. void WrappedID3D11Device::Serialise_CaptureScope(uint64_t offset)
  712. {
  713. SERIALISE_ELEMENT(uint32_t, FrameNumber, m_FrameCounter);
  714. if(m_State >= WRITING)
  715. {
  716. GetResourceManager()->Serialise_InitialContentsNeeded(m_pSerialiser);
  717. }
  718. else
  719. {
  720. FetchFrameRecord record;
  721. record.frameInfo.fileOffset = offset;
  722. record.frameInfo.firstEvent = m_pImmediateContext->GetEventID();
  723. record.frameInfo.frameNumber = FrameNumber;
  724. record.frameInfo.immContextId = GetResourceManager()->GetOriginalID(m_pImmediateContext->GetResourceID());
  725. m_FrameRecord.push_back(record);
  726. GetResourceManager()->CreateInitialContents(m_pSerialiser);
  727. }
  728. }
  729. void WrappedID3D11Device::ReadLogInitialisation()
  730. {
  731. uint64_t lastFrame = 0;
  732. uint64_t firstFrame = 0;
  733. LazyInit();
  734. m_pSerialiser->SetDebugText(true);
  735. m_pSerialiser->Rewind();
  736. while(!m_pSerialiser->AtEnd())
  737. {
  738. m_pSerialiser->SkipToChunk(CAPTURE_SCOPE);
  739. // found a capture chunk
  740. if(!m_pSerialiser->AtEnd())
  741. {
  742. lastFrame = m_pSerialiser->GetOffset();
  743. if(firstFrame == 0)
  744. firstFrame = m_pSerialiser->GetOffset();
  745. // skip this chunk
  746. m_pSerialiser->PushContext(NULL, CAPTURE_SCOPE, false);
  747. m_pSerialiser->SkipCurrentChunk();
  748. m_pSerialiser->PopContext(NULL, CAPTURE_SCOPE);
  749. }
  750. }
  751. m_pSerialiser->Rewind();
  752. int chunkIdx = 0;
  753. struct chunkinfo
  754. {
  755. chunkinfo() : count(0), total(0.0) {}
  756. int count;
  757. double total;
  758. };
  759. map<D3D11ChunkType,chunkinfo> chunkInfos;
  760. SCOPED_TIMER("chunk initialisation");
  761. while(1)
  762. {
  763. PerformanceTimer timer;
  764. uint64_t offset = m_pSerialiser->GetOffset();
  765. D3D11ChunkType context = (D3D11ChunkType)m_pSerialiser->PushContext(NULL, 1, false);
  766. chunkIdx++;
  767. ProcessChunk(offset, context);
  768. m_pSerialiser->PopContext(NULL, context);
  769. RenderDoc::Inst().SetProgress(FileInitialRead, float(m_pSerialiser->GetOffset())/float(m_pSerialiser->GetSize()));
  770. if(context == CAPTURE_SCOPE)
  771. {
  772. m_pImmediateContext->ReplayLog(READING, 0, 0, false);
  773. if(m_pSerialiser->GetOffset() > lastFrame)
  774. break;
  775. }
  776. chunkInfos[context].total += timer.GetMilliseconds();
  777. chunkInfos[context].count++;
  778. if(m_pSerialiser->AtEnd())
  779. {
  780. break;
  781. }
  782. }
  783. for(auto it=chunkInfos.begin(); it != chunkInfos.end(); ++it)
  784. {
  785. RDCDEBUG("%hs: %.3f total time in %d chunks - %.3f average",
  786. GetChunkName(it->first), it->second.total, it->second.count,
  787. it->second.total/double(it->second.count));
  788. }
  789. RDCDEBUG("Allocating %llu persistant bytes of memory for the log.", m_pSerialiser->GetSize() - firstFrame);
  790. m_pSerialiser->SetDebugText(false);
  791. m_pSerialiser->SetBase(firstFrame);
  792. }
  793. bool WrappedID3D11Device::Prepare_InitialState(ID3D11DeviceChild *res)
  794. {
  795. ResourceType type = IdentifyTypeByPtr(res);
  796. ResourceId Id = GetIDForResource(res);
  797. RDCASSERT(m_State >= WRITING);
  798. {
  799. RDCDEBUG("Prepare_InitialState(%llu)", Id);
  800. if(type == Resource_Buffer)
  801. RDCDEBUG(" .. buffer");
  802. else if(type == Resource_UnorderedAccessView)
  803. RDCDEBUG(" .. UAV");
  804. else if(type == Resource_Texture1D ||
  805. type == Resource_Texture2D ||
  806. type == Resource_Texture3D)
  807. {
  808. if(type == Resource_Texture1D)
  809. RDCDEBUG(" .. tex1d");
  810. else if(type == Resource_Texture2D)
  811. RDCDEBUG(" .. tex2d");
  812. else if(type == Resource_Texture3D)
  813. RDCDEBUG(" .. tex3d");
  814. }
  815. else
  816. RDCERR(" .. other!");
  817. }
  818. if(type == Resource_UnorderedAccessView)
  819. {
  820. WrappedID3D11UnorderedAccessView *uav = (WrappedID3D11UnorderedAccessView *)res;
  821. D3D11_UNORDERED_ACCESS_VIEW_DESC udesc;
  822. uav->GetDesc(&udesc);
  823. if(udesc.ViewDimension == D3D11_UAV_DIMENSION_BUFFER &&
  824. (udesc.Buffer.Flags & (D3D11_BUFFER_UAV_FLAG_COUNTER|D3D11_BUFFER_UAV_FLAG_APPEND)) != 0)
  825. {
  826. ID3D11Buffer *stage = NULL;
  827. D3D11_BUFFER_DESC desc;
  828. desc.BindFlags = 0;
  829. desc.ByteWidth = 16;
  830. desc.MiscFlags = 0;
  831. desc.StructureByteStride = 0;
  832. desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
  833. desc.Usage = D3D11_USAGE_STAGING;
  834. HRESULT hr = m_pDevice->CreateBuffer(&desc, NULL, &stage);
  835. if(FAILED(hr) || stage == NULL)
  836. {
  837. RDCERR("Failed to create staging buffer for UAV initial contents %08x", hr);
  838. }
  839. else
  840. {
  841. m_pImmediateContext->GetReal()->CopyStructureCount(stage, 0, UNWRAP(WrappedID3D11UnorderedAccessView, uav));
  842. m_ResourceManager->SetInitialContents(Id, stage, 0);
  843. }
  844. }
  845. }
  846. else if(type == Resource_Buffer)
  847. {
  848. WrappedID3D11Buffer *buf = (WrappedID3D11Buffer *)res;
  849. D3D11ResourceRecord *record = m_ResourceManager->GetResourceRecord(Id);
  850. ID3D11Buffer *stage = NULL;
  851. D3D11_BUFFER_DESC desc;
  852. desc.BindFlags = 0;
  853. desc.ByteWidth = record->Length;
  854. desc.MiscFlags = 0;
  855. desc.StructureByteStride = 0;
  856. desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
  857. desc.Usage = D3D11_USAGE_STAGING;
  858. HRESULT hr = m_pDevice->CreateBuffer(&desc, NULL, &stage);
  859. if(FAILED(hr) || stage == NULL)
  860. {
  861. RDCERR("Failed to create staging buffer for buffer initial contents %08x", hr);
  862. }
  863. else
  864. {
  865. m_pImmediateContext->GetReal()->CopyResource(stage, UNWRAP(WrappedID3D11Buffer, buf));
  866. m_ResourceManager->SetInitialContents(Id, stage, 0);
  867. }
  868. }
  869. else if(type == Resource_Texture1D)
  870. {
  871. WrappedID3D11Texture1D *tex1D = (WrappedID3D11Texture1D *)res;
  872. D3D11ResourceRecord *record = m_ResourceManager->GetResourceRecord(Id);
  873. D3D11_TEXTURE1D_DESC desc;
  874. tex1D->GetDesc(&desc);
  875. UINT numSubresources = desc.MipLevels*desc.ArraySize;
  876. D3D11_TEXTURE1D_DESC stageDesc = desc;
  877. ID3D11Texture1D *stage = NULL;
  878. stageDesc.MiscFlags = 0;
  879. stageDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
  880. stageDesc.BindFlags = 0;
  881. stageDesc.Usage = D3D11_USAGE_STAGING;
  882. HRESULT hr = m_pDevice->CreateTexture1D(&stageDesc, NULL, &stage);
  883. if(FAILED(hr))
  884. {
  885. RDCERR("Failed to create initial tex1D %08x", hr);
  886. }
  887. else
  888. {
  889. m_pImmediateContext->GetReal()->CopyResource(stage, UNWRAP(WrappedID3D11Texture1D, tex1D));
  890. m_ResourceManager->SetInitialContents(Id, stage, 0);
  891. }
  892. }
  893. else if(type == Resource_Texture2D)
  894. {
  895. WrappedID3D11Texture2D *tex2D = (WrappedID3D11Texture2D *)res;
  896. D3D11ResourceRecord *record = m_ResourceManager->GetResourceRecord(Id);
  897. D3D11_TEXTURE2D_DESC desc;
  898. tex2D->GetDesc(&desc);
  899. UINT numSubresources = desc.MipLevels*desc.ArraySize;
  900. bool multisampled = desc.SampleDesc.Count > 1 || desc.SampleDesc.Quality > 0;
  901. D3D11_TEXTURE2D_DESC stageDesc = desc;
  902. ID3D11Texture2D *stage = NULL;
  903. stageDesc.MiscFlags = 0;
  904. stageDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
  905. stageDesc.BindFlags = 0;
  906. stageDesc.Usage = D3D11_USAGE_STAGING;
  907. // expand out each sample into an array slice. Hope
  908. // that this doesn't blow over the array size limit
  909. // (that would be pretty insane)
  910. if(multisampled)
  911. {
  912. stageDesc.SampleDesc.Count = 1;
  913. stageDesc.SampleDesc.Quality = 0;
  914. stageDesc.ArraySize *= desc.SampleDesc.Count;
  915. }
  916. HRESULT hr = m_pDevice->CreateTexture2D(&stageDesc, NULL, &stage);
  917. if(FAILED(hr))
  918. {
  919. RDCERR("Failed to create initial tex2D %08x", hr);
  920. }
  921. else
  922. {
  923. IDXGIKeyedMutex *mutex = NULL;
  924. if(desc.MiscFlags & D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX)
  925. {
  926. HRESULT hr = UNWRAP(WrappedID3D11Texture2D, tex2D)->QueryInterface(__uuidof(IDXGIKeyedMutex), (void **)&mutex);
  927. if(SUCCEEDED(hr) && mutex)
  928. {
  929. // complete guess but let's try and acquire key 0 so we can cop this texture out.
  930. mutex->AcquireSync(0, 10);
  931. // if it failed, give up. Otherwise we can release the sync below
  932. if(FAILED(hr))
  933. SAFE_RELEASE(mutex);
  934. }
  935. else
  936. {
  937. SAFE_RELEASE(mutex);
  938. }
  939. }
  940. if(multisampled)
  941. m_DebugManager->CopyTex2DMSToArray(stage, UNWRAP(WrappedID3D11Texture2D, tex2D));
  942. else
  943. m_pImmediateContext->GetReal()->CopyResource(stage, UNWRAP(WrappedID3D11Texture2D, tex2D));
  944. m_pImmediateContext->GetReal()->Flush();
  945. if(mutex)
  946. {
  947. mutex->ReleaseSync(0);
  948. SAFE_RELEASE(mutex);
  949. }
  950. m_ResourceManager->SetInitialContents(Id, stage, 0);
  951. }
  952. }
  953. else if(type == Resource_Texture3D)
  954. {
  955. WrappedID3D11Texture3D *tex3D = (WrappedID3D11Texture3D *)res;
  956. D3D11ResourceRecord *record = m_ResourceManager->GetResourceRecord(Id);
  957. D3D11_TEXTURE3D_DESC desc;
  958. tex3D->GetDesc(&desc);
  959. UINT numSubresources = desc.MipLevels;
  960. D3D11_TEXTURE3D_DESC stageDesc = desc;
  961. ID3D11Texture3D *stage = NULL;
  962. stageDesc.MiscFlags = 0;
  963. stageDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
  964. stageDesc.BindFlags = 0;
  965. stageDesc.Usage = D3D11_USAGE_STAGING;
  966. HRESULT hr = m_pDevice->CreateTexture3D(&stageDesc, NULL, &stage);
  967. if(FAILED(hr))
  968. {
  969. RDCERR("Failed to create initial tex3D %08x", hr);
  970. }
  971. else
  972. {
  973. m_pImmediateContext->GetReal()->CopyResource(stage, UNWRAP(WrappedID3D11Texture3D, tex3D));
  974. m_ResourceManager->SetInitialContents(Id, stage, 0);
  975. }
  976. }
  977. return true;
  978. }
  979. bool WrappedID3D11Device::Serialise_InitialState(ID3D11DeviceChild *res)
  980. {
  981. ResourceType type = Resource_Unknown;
  982. ResourceId Id = ResourceId();
  983. if(m_State >= WRITING)
  984. {
  985. type = IdentifyTypeByPtr(res);
  986. Id = GetIDForResource(res);
  987. if(type != Resource_Buffer)
  988. {
  989. m_pSerialiser->Serialise("type", type);
  990. m_pSerialiser->Serialise("Id", Id);
  991. }
  992. }
  993. else
  994. {
  995. m_pSerialiser->Serialise("type", type);
  996. m_pSerialiser->Serialise("Id", Id);
  997. }
  998. {
  999. RDCDEBUG("Serialise_InitialState(%llu)", Id);
  1000. if(type == Resource_Buffer)
  1001. RDCDEBUG(" .. buffer");
  1002. else if(type == Resource_UnorderedAccessView)
  1003. RDCDEBUG(" .. UAV");
  1004. else if(type == Resource_Texture1D ||
  1005. type == Resource_Texture2D ||
  1006. type == Resource_Texture3D)
  1007. {
  1008. if(type == Resource_Texture1D)
  1009. RDCDEBUG(" .. tex1d");
  1010. else if(type == Resource_Texture2D)
  1011. RDCDEBUG(" .. tex2d");
  1012. else if(type == Resource_Texture3D)
  1013. RDCDEBUG(" .. tex3d");
  1014. }
  1015. else
  1016. RDCERR(" .. other!");
  1017. }
  1018. if(type == Resource_UnorderedAccessView)
  1019. {
  1020. WrappedID3D11UnorderedAccessView *uav = (WrappedID3D11UnorderedAccessView *)res;
  1021. if(m_State < WRITING)
  1022. {
  1023. if(m_ResourceManager->HasLiveResource(Id))
  1024. {
  1025. uav = (WrappedID3D11UnorderedAccessView *)m_ResourceManager->GetLiveResource(Id);
  1026. }
  1027. else
  1028. {
  1029. uav = NULL;
  1030. SERIALISE_ELEMENT(uint32_t, initCount, 0);
  1031. return true;
  1032. }
  1033. }
  1034. D3D11_UNORDERED_ACCESS_VIEW_DESC desc;
  1035. uav->GetDesc(&desc);
  1036. if(desc.ViewDimension == D3D11_UAV_DIMENSION_BUFFER &&
  1037. (desc.Buffer.Flags & (D3D11_BUFFER_UAV_FLAG_COUNTER|D3D11_BUFFER_UAV_FLAG_APPEND)) != 0)
  1038. {
  1039. if(m_State >= WRITING)
  1040. {
  1041. ID3D11Buffer *stage = (ID3D11Buffer *)m_ResourceManager->GetInitialContents(Id);
  1042. D3D11_MAPPED_SUBRESOURCE mapped;
  1043. HRESULT hr = m_pImmediateContext->GetReal()->Map(stage, 0, D3D11_MAP_READ, 0, &mapped);
  1044. uint32_t countData = 0;
  1045. if(FAILED(hr))
  1046. {
  1047. RDCERR("Failed to map while getting initial states %08x", hr);
  1048. }
  1049. else
  1050. {
  1051. countData = *((uint32_t *)mapped.pData);
  1052. m_pImmediateContext->GetReal()->Unmap(stage, 0);
  1053. }
  1054. SERIALISE_ELEMENT(uint32_t, count, countData);
  1055. }
  1056. else
  1057. {
  1058. SERIALISE_ELEMENT(uint32_t, initCount, 0);
  1059. m_ResourceManager->SetInitialContents(Id, NULL, initCount);
  1060. }
  1061. }
  1062. else
  1063. {
  1064. SERIALISE_ELEMENT(uint32_t, initCount, 0);
  1065. }
  1066. }
  1067. else if(type == Resource_Buffer)
  1068. {
  1069. if(m_State >= WRITING)
  1070. {
  1071. WrappedID3D11Buffer *buf = (WrappedID3D11Buffer *)res;
  1072. D3D11ResourceRecord *record = m_ResourceManager->GetResourceRecord(Id);
  1073. D3D11_BUFFER_DESC desc;
  1074. desc.BindFlags = 0;
  1075. desc.ByteWidth = record->Length;
  1076. desc.MiscFlags = 0;
  1077. desc.StructureByteStride = 0;
  1078. ID3D11Buffer *stage = (ID3D11Buffer *)m_ResourceManager->GetInitialContents(Id);
  1079. D3D11_MAPPED_SUBRESOURCE mapped;
  1080. HRESULT hr = m_pImmediateContext->GetReal()->Map(stage, 0, D3D11_MAP_READ, 0, &mapped);
  1081. if(FAILED(hr))
  1082. {
  1083. RDCERR("Failed to map while getting initial states %08x", hr);
  1084. }
  1085. else
  1086. {
  1087. RDCASSERT(record->DataInSerialiser);
  1088. MapIntercept intercept;
  1089. intercept.SetD3D(mapped);
  1090. intercept.Init(buf, record->GetDataPtr());
  1091. intercept.CopyFromD3D();
  1092. m_pImmediateContext->GetReal()->Unmap(stage, 0);
  1093. }
  1094. }
  1095. }
  1096. else if(type == Resource_Texture1D)
  1097. {
  1098. WrappedID3D11Texture1D *tex1D = (WrappedID3D11Texture1D *)res;
  1099. if(m_State < WRITING)
  1100. tex1D = (WrappedID3D11Texture1D *)m_ResourceManager->GetLiveResource(Id);
  1101. D3D11ResourceRecord *record = NULL;
  1102. if(m_State >= WRITING)
  1103. record = m_ResourceManager->GetResourceRecord(Id);
  1104. D3D11_TEXTURE1D_DESC desc;
  1105. tex1D->GetDesc(&desc);
  1106. SERIALISE_ELEMENT(uint32_t, numSubresources, desc.MipLevels*desc.ArraySize);
  1107. {
  1108. if(m_State < WRITING)
  1109. {
  1110. ID3D11Texture1D *contents = (ID3D11Texture1D *)m_ResourceManager->GetInitialContents(Id);
  1111. RDCASSERT(!contents);
  1112. }
  1113. byte *inmemBuffer = NULL;
  1114. D3D11_SUBRESOURCE_DATA *subData = NULL;
  1115. if(m_State >= WRITING)
  1116. {
  1117. inmemBuffer = new byte[GetByteSize(desc.Width, 1, 1, desc.Format, 0)];
  1118. }
  1119. else
  1120. {
  1121. subData = new D3D11_SUBRESOURCE_DATA[numSubresources];
  1122. }
  1123. ID3D11Texture1D *stage = (ID3D11Texture1D *)m_ResourceManager->GetInitialContents(Id);
  1124. for(UINT sub = 0; sub < numSubresources; sub++)
  1125. {
  1126. UINT mip = GetMipForSubresource(tex1D, sub);
  1127. if(m_State >= WRITING)
  1128. {
  1129. D3D11_MAPPED_SUBRESOURCE mapped;
  1130. HRESULT hr = m_pImmediateContext->GetReal()->Map(stage, sub, D3D11_MAP_READ, 0, &mapped);
  1131. size_t dstPitch = GetByteSize(desc.Width, 1, 1, desc.Format, mip);
  1132. if(FAILED(hr))
  1133. {
  1134. RDCERR("Failed to map in initial states %08x", hr);
  1135. }
  1136. else
  1137. {
  1138. uint32_t rowsPerLine = 1;
  1139. byte *dst = inmemBuffer;
  1140. byte *src = (byte *)mapped.pData;
  1141. memcpy(inmemBuffer, mapped.pData, dstPitch);
  1142. }
  1143. size_t len = dstPitch;
  1144. m_pSerialiser->SerialiseBuffer("", inmemBuffer, len);
  1145. if(SUCCEEDED(hr))
  1146. m_pImmediateContext->GetReal()->Unmap(stage, 0);
  1147. }
  1148. else
  1149. {
  1150. byte *data = NULL;
  1151. size_t len = 0;
  1152. m_pSerialiser->SerialiseBuffer("", data, len);
  1153. subData[sub].pSysMem = data;
  1154. subData[sub].SysMemPitch = GetByteSize(desc.Width, 1, 1, desc.Format, mip);
  1155. subData[sub].SysMemSlicePitch = GetByteSize(desc.Width, 1, 1, desc.Format, mip);
  1156. }
  1157. }
  1158. SAFE_DELETE_ARRAY(inmemBuffer);
  1159. if(m_State < WRITING)
  1160. {
  1161. // We don't need to bind this, but IMMUTABLE requires at least one
  1162. // BindFlags.
  1163. desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
  1164. desc.CPUAccessFlags = 0;
  1165. desc.Usage = D3D11_USAGE_IMMUTABLE;
  1166. desc.MiscFlags = 0;
  1167. ID3D11Texture1D *contents = NULL;
  1168. HRESULT hr = m_pDevice->CreateTexture1D(&desc, subData, &contents);
  1169. if(FAILED(hr) || contents == NULL)
  1170. {
  1171. RDCERR("Failed to create staging resource for Texture1D initial contents %08x", hr);
  1172. }
  1173. else
  1174. {
  1175. m_ResourceManager->SetInitialContents(Id, contents, 0);
  1176. }
  1177. for(UINT sub = 0; sub < numSubresources; sub++)
  1178. SAFE_DELETE_ARRAY(subData[sub].pSysMem);
  1179. SAFE_DELETE_ARRAY(subData);
  1180. }
  1181. }
  1182. }
  1183. else if(type == Resource_Texture2D)
  1184. {
  1185. WrappedID3D11Texture2D *tex2D = (WrappedID3D11Texture2D *)res;
  1186. if(m_State < WRITING)
  1187. tex2D = (WrappedID3D11Texture2D *)m_ResourceManager->GetLiveResource(Id);
  1188. D3D11ResourceRecord *record = NULL;
  1189. if(m_State >= WRITING)
  1190. record = m_ResourceManager->GetResourceRecord(Id);
  1191. D3D11_TEXTURE2D_DESC desc;
  1192. tex2D->GetDesc(&desc);
  1193. SERIALISE_ELEMENT(uint32_t, numSubresources, desc.MipLevels*desc.ArraySize);
  1194. bool bigrt = ((desc.BindFlags & D3D11_BIND_RENDER_TARGET) != 0 ||
  1195. (desc.BindFlags & D3D11_BIND_DEPTH_STENCIL) != 0 ||
  1196. (desc.BindFlags & D3D11_BIND_UNORDERED_ACCESS) != 0) && (desc.Width > 64 && desc.Height > 64);
  1197. if(bigrt && m_ResourceManager->ReadBeforeWrite(Id))
  1198. bigrt = false;
  1199. bool multisampled = desc.SampleDesc.Count > 1 || desc.SampleDesc.Quality > 0;
  1200. if(multisampled)
  1201. numSubresources *= desc.SampleDesc.Count;
  1202. SERIALISE_ELEMENT(bool, omitted, bigrt && !RenderDoc::Inst().GetCaptureOptions().SaveAllInitials);
  1203. if(omitted)
  1204. {
  1205. if(m_State >= WRITING)
  1206. {
  1207. RDCWARN("Not serialising texture 2D initial state. ID %llu", Id);
  1208. if(bigrt)
  1209. RDCWARN("Detected Write before Read of this target - assuming initial contents are unneeded.\n" \
  1210. "Capture again with Save All Initials if this is wrong");
  1211. }
  1212. }
  1213. else
  1214. {
  1215. if(m_State < WRITING)
  1216. {
  1217. ID3D11Texture2D *contents = (ID3D11Texture2D *)m_ResourceManager->GetInitialContents(Id);
  1218. RDCASSERT(!contents);
  1219. }
  1220. byte *inmemBuffer = NULL;
  1221. D3D11_SUBRESOURCE_DATA *subData = NULL;
  1222. if(m_State >= WRITING)
  1223. {
  1224. inmemBuffer = new byte[GetByteSize(desc.Width, desc.Height, 1, desc.Format, 0)];
  1225. }
  1226. else
  1227. {
  1228. subData = new D3D11_SUBRESOURCE_DATA[numSubresources];
  1229. }
  1230. ID3D11Texture2D *stage = (ID3D11Texture2D *)m_ResourceManager->GetInitialContents(Id);
  1231. for(UINT sub = 0; sub < numSubresources; sub++)
  1232. {
  1233. UINT mip = GetMipForSubresource(tex2D, sub);
  1234. if(m_State >= WRITING)
  1235. {
  1236. D3D11_MAPPED_SUBRESOURCE mapped;
  1237. HRESULT hr = m_pImmediateContext->GetReal()->Map(stage, sub, D3D11_MAP_READ, 0, &mapped);
  1238. size_t dstPitch = GetByteSize(desc.Width, 1, 1, desc.Format, mip);
  1239. size_t len = GetByteSize(desc.Width, desc.Height, 1, desc.Format, mip);
  1240. uint32_t rowsPerLine = 1;
  1241. if(IsBlockFormat(desc.Format))
  1242. rowsPerLine = 4;
  1243. if(FAILED(hr))
  1244. {
  1245. RDCERR("Failed to map in initial states %08x", hr);
  1246. }
  1247. else
  1248. {
  1249. byte *dst = inmemBuffer;
  1250. byte *src = (byte *)mapped.pData;
  1251. for(uint32_t row=0; row < desc.Height>>mip; row += rowsPerLine)
  1252. {
  1253. memcpy(dst, src, dstPitch);
  1254. dst += dstPitch;
  1255. src += mapped.RowPitch;
  1256. }
  1257. }
  1258. m_pSerialiser->SerialiseBuffer("", inmemBuffer, len);
  1259. m_pImmediateContext->GetReal()->Unmap(stage, sub);
  1260. }
  1261. else
  1262. {
  1263. byte *data = NULL;
  1264. size_t len = 0;
  1265. m_pSerialiser->SerialiseBuffer("", data, len);
  1266. subData[sub].pSysMem = data;
  1267. subData[sub].SysMemPitch = GetByteSize(desc.Width, 1, 1, desc.Format, mip);
  1268. subData[sub].SysMemSlicePitch = GetByteSize(desc.Width, desc.Height, 1, desc.Format, mip);
  1269. }
  1270. }
  1271. SAFE_DELETE_ARRAY(inmemBuffer);
  1272. if(m_State < WRITING)
  1273. {
  1274. // We don't need to bind this, but IMMUTABLE requires at least one
  1275. // BindFlags.
  1276. desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
  1277. desc.CPUAccessFlags = 0;
  1278. desc.MiscFlags = 0;
  1279. switch(desc.Format)
  1280. {
  1281. case DXGI_FORMAT_D32_FLOAT_S8X24_UINT:
  1282. desc.Format = DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS;
  1283. break;
  1284. case DXGI_FORMAT_D32_FLOAT:
  1285. desc.Format = DXGI_FORMAT_R32_FLOAT;
  1286. break;
  1287. case DXGI_FORMAT_D24_UNORM_S8_UINT:
  1288. desc.Format = DXGI_FORMAT_R24_UNORM_X8_TYPELESS;
  1289. break;
  1290. case DXGI_FORMAT_D16_UNORM:
  1291. desc.Format = DXGI_FORMAT_R16_FLOAT;
  1292. break;
  1293. default:
  1294. break;
  1295. }
  1296. D3D11_TEXTURE2D_DESC initialDesc = desc;
  1297. // if multisampled, need to upload subData into an array with slices for each sample.
  1298. if(multisampled)
  1299. {
  1300. initialDesc.SampleDesc.Count = 1;
  1301. initialDesc.SampleDesc.Quality = 0;
  1302. initialDesc.ArraySize *= desc.SampleDesc.Count;
  1303. }
  1304. initialDesc.Usage = D3D11_USAGE_IMMUTABLE;
  1305. ID3D11Texture2D *contents = NULL;
  1306. HRESULT hr = m_pDevice->CreateTexture2D(&initialDesc, subData, &contents);
  1307. if(FAILED(hr) || contents == NULL)
  1308. {
  1309. RDCERR("Failed to create staging resource for Texture2D initial contents %08x", hr);
  1310. }
  1311. else
  1312. {
  1313. // if multisampled, contents is actually an array with slices for each sample.
  1314. // need to copy back out to a real multisampled resource
  1315. if(multisampled)
  1316. {
  1317. desc.BindFlags = IsDepthFormat(desc.Format) ? D3D11_BIND_DEPTH_STENCIL : D3D11_BIND_RENDER_TARGET;
  1318. if(IsDepthFormat(desc.Format))
  1319. desc.Format = GetDepthTypedFormat(desc.Format);
  1320. ID3D11Texture2D *contentsMS = NULL;
  1321. HRESULT hr = m_pDevice->CreateTexture2D(&desc, NULL, &contentsMS);
  1322. m_DebugManager->CopyArrayToTex2DMS(contentsMS, contents);
  1323. SAFE_RELEASE(contents);
  1324. contents = contentsMS;
  1325. }
  1326. m_ResourceManager->SetInitialContents(Id, contents, 0);
  1327. }
  1328. for(UINT sub = 0; sub < numSubresources; sub++)
  1329. SAFE_DELETE_ARRAY(subData[sub].pSysMem);
  1330. SAFE_DELETE_ARRAY(subData);
  1331. }
  1332. }
  1333. }
  1334. else if(type == Resource_Texture3D)
  1335. {
  1336. WrappedID3D11Texture3D *tex3D = (WrappedID3D11Texture3D *)res;
  1337. if(m_State < WRITING)
  1338. tex3D = (WrappedID3D11Texture3D *)m_ResourceManager->GetLiveResource(Id);
  1339. D3D11ResourceRecord *record = NULL;
  1340. if(m_State >= WRITING)
  1341. record = m_ResourceManager->GetResourceRecord(Id);
  1342. D3D11_TEXTURE3D_DESC desc;
  1343. tex3D->GetDesc(&desc);
  1344. SERIALISE_ELEMENT(uint32_t, numSubresources, desc.MipLevels);
  1345. {
  1346. if(m_State < WRITING)
  1347. {
  1348. ID3D11Texture3D *contents = (ID3D11Texture3D *)m_ResourceManager->GetInitialContents(Id);
  1349. RDCASSERT(!contents);
  1350. }
  1351. byte *inmemBuffer = NULL;
  1352. D3D11_SUBRESOURCE_DATA *subData = NULL;
  1353. if(m_State >= WRITING)
  1354. {
  1355. inmemBuffer = new byte[GetByteSize(desc.Width, desc.Height, desc.Depth, desc.Format, 0)];
  1356. }
  1357. else
  1358. {
  1359. subData = new D3D11_SUBRESOURCE_DATA[numSubresources];
  1360. }
  1361. ID3D11Texture3D *stage = (ID3D11Texture3D *)m_ResourceManager->GetInitialContents(Id);
  1362. for(UINT sub = 0; sub < numSubresources; sub++)
  1363. {
  1364. UINT mip = GetMipForSubresource(tex3D, sub);
  1365. if(m_State >= WRITING)
  1366. {
  1367. D3D11_MAPPED_SUBRESOURCE mapped;
  1368. HRESULT hr = m_pImmediateContext->GetReal()->Map(stage, sub, D3D11_MAP_READ, 0, &mapped);
  1369. size_t dstPitch = GetByteSize(desc.Width, 1, 1, desc.Format, mip);
  1370. size_t dstSlicePitch = GetByteSize(desc.Width, desc.Height, 1, desc.Format, mip);
  1371. uint32_t rowsPerLine = 1;
  1372. if(IsBlockFormat(desc.Format))
  1373. rowsPerLine = 4;
  1374. if(FAILED(hr))
  1375. {
  1376. RDCERR("Failed to map in initial states %08x", hr);
  1377. }
  1378. else
  1379. {
  1380. byte *dst = inmemBuffer;
  1381. byte *src = (byte *)mapped.pData;
  1382. for(uint32_t slice=0; slice < RDCMAX(1U,desc.Depth>>mip); slice++)
  1383. {
  1384. byte *sliceDst = dst;
  1385. byte *sliceSrc = src;
  1386. for(uint32_t row=0; row < RDCMAX(1U,desc.Height>>mip); row += rowsPerLine)
  1387. {
  1388. memcpy(sliceDst, sliceSrc, dstPitch);
  1389. sliceDst += dstPitch;
  1390. sliceSrc += mapped.RowPitch;
  1391. }
  1392. dst += dstSlicePitch;
  1393. src += mapped.DepthPitch;
  1394. }
  1395. }
  1396. size_t len = dstSlicePitch*desc.Depth;
  1397. m_pSerialiser->SerialiseBuffer("", inmemBuffer, len);
  1398. m_pImmediateContext->GetReal()->Unmap(stage, 0);
  1399. }
  1400. else
  1401. {
  1402. byte *data = NULL;
  1403. size_t len = 0;
  1404. m_pSerialiser->SerialiseBuffer("", data, len);
  1405. subData[sub].pSysMem = data;
  1406. subData[sub].SysMemPitch = GetByteSize(desc.Width, 1, 1, desc.Format, mip);
  1407. subData[sub].SysMemSlicePitch = GetByteSize(desc.Width, desc.Height, 1, desc.Format, mip);
  1408. }
  1409. }
  1410. SAFE_DELETE_ARRAY(inmemBuffer);
  1411. if(m_State < WRITING)
  1412. {
  1413. // We don't need to bind this, but IMMUTABLE requires at least one
  1414. // BindFlags.
  1415. desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
  1416. desc.CPUAccessFlags = 0;
  1417. desc.Usage = D3D11_USAGE_IMMUTABLE;
  1418. desc.MiscFlags = 0;
  1419. ID3D11Texture3D *contents = NULL;
  1420. HRESULT hr = m_pDevice->CreateTexture3D(&desc, subData, &contents);
  1421. if(FAILED(hr) || contents == NULL)
  1422. {
  1423. RDCERR("Failed to create staging resource for Texture3D initial contents %08x", hr);
  1424. }
  1425. else
  1426. {
  1427. m_ResourceManager->SetInitialContents(Id, contents, 0);
  1428. }
  1429. for(UINT sub = 0; sub < numSubresources; sub++)
  1430. SAFE_DELETE_ARRAY(subData[sub].pSysMem);
  1431. SAFE_DELETE_ARRAY(subData);
  1432. }
  1433. }
  1434. }
  1435. else
  1436. {
  1437. RDCERR("Trying to serialise initial state of unsupported resource type");
  1438. }
  1439. return true;
  1440. }
  1441. void WrappedID3D11Device::Create_InitialState(ResourceId id, ID3D11DeviceChild *live, bool hasData)
  1442. {
  1443. ResourceType type = IdentifyTypeByPtr(live);
  1444. {
  1445. RDCDEBUG("Create_InitialState(%llu)", id);
  1446. if(type == Resource_Buffer)
  1447. RDCDEBUG(" .. buffer");
  1448. else if(type == Resource_UnorderedAccessView)
  1449. RDCDEBUG(" .. UAV");
  1450. else if(type == Resource_Texture1D ||
  1451. type == Resource_Texture2D ||
  1452. type == Resource_Texture3D)
  1453. {
  1454. if(type == Resource_Texture1D)
  1455. RDCDEBUG(" .. tex1d");
  1456. else if(type == Resource_Texture2D)
  1457. RDCDEBUG(" .. tex2d");
  1458. else if(type == Resource_Texture3D)
  1459. RDCDEBUG(" .. tex3d");
  1460. }
  1461. else
  1462. RDCERR(" .. other!");
  1463. }
  1464. if(type == Resource_UnorderedAccessView)
  1465. {
  1466. WrappedID3D11UnorderedAccessView *uav = (WrappedID3D11UnorderedAccessView *)live;
  1467. D3D11_UNORDERED_ACCESS_VIEW_DESC desc;
  1468. uav->GetDesc(&desc);
  1469. if(desc.ViewDimension == D3D11_UAV_DIMENSION_BUFFER &&
  1470. (desc.Buffer.Flags & (D3D11_BUFFER_UAV_FLAG_COUNTER|D3D11_BUFFER_UAV_FLAG_APPEND)) != 0)
  1471. {
  1472. ID3D11Buffer *stage = NULL;
  1473. D3D11_BUFFER_DESC desc;
  1474. desc.BindFlags = 0;
  1475. desc.ByteWidth = 16;
  1476. desc.MiscFlags = 0;
  1477. desc.StructureByteStride = 0;
  1478. desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
  1479. desc.Usage = D3D11_USAGE_STAGING;
  1480. HRESULT hr = m_pDevice->CreateBuffer(&desc, NULL, &stage);
  1481. if(FAILED(hr) || stage == NULL)
  1482. {
  1483. RDCERR("Failed to create staging resource for UAV initial contents %08x", hr);
  1484. }
  1485. else
  1486. {
  1487. m_pImmediateContext->GetReal()->CopyStructureCount(stage, 0, UNWRAP(WrappedID3D11UnorderedAccessView, uav));
  1488. D3D11_MAPPED_SUBRESOURCE mapped;
  1489. hr = m_pImmediateContext->GetReal()->Map(stage, 0, D3D11_MAP_READ, 0, &mapped);
  1490. uint32_t countData = 0;
  1491. if(FAILED(hr))
  1492. {
  1493. RDCERR("Failed to map while creating initial states %08x", hr);
  1494. }
  1495. else
  1496. {
  1497. countData = *((uint32_t *)mapped.pData);
  1498. m_pImmediateContext->GetReal()->Unmap(stage, 0);
  1499. }
  1500. m_ResourceManager->SetInitialContents(id, NULL, countData);
  1501. SAFE_RELEASE(stage);
  1502. }
  1503. }
  1504. }
  1505. else if(type == Resource_Texture1D)
  1506. {
  1507. WrappedID3D11Texture1D *tex1D = (WrappedID3D11Texture1D *)live;
  1508. D3D11_TEXTURE1D_DESC desc;
  1509. tex1D->GetDesc(&desc);
  1510. if(!hasData && desc.MipLevels == 1 && (desc.BindFlags & D3D11_BIND_RENDER_TARGET))
  1511. {
  1512. D3D11_RENDER_TARGET_VIEW_DESC rdesc;
  1513. rdesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE1D;
  1514. rdesc.Format = GetTypedFormat(desc.Format);
  1515. rdesc.Texture1D.MipSlice = 0;
  1516. ID3D11RenderTargetView *initContents = NULL;
  1517. HRESULT hr = m_pDevice->CreateRenderTargetView(UNWRAP(WrappedID3D11Texture1D, tex1D), &rdesc, &initContents);
  1518. if(FAILED(hr))
  1519. {
  1520. RDCERR("Failed to create fast-clear RTV while creating initial states %08x", hr);
  1521. }
  1522. else
  1523. {
  1524. m_ResourceManager->SetInitialContents(id, initContents, 1);
  1525. }
  1526. }
  1527. else if(!hasData && desc.MipLevels == 1 && (desc.BindFlags & D3D11_BIND_DEPTH_STENCIL))
  1528. {
  1529. D3D11_DEPTH_STENCIL_VIEW_DESC ddesc;
  1530. ddesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE1D;
  1531. ddesc.Format = GetDepthTypedFormat(desc.Format);
  1532. ddesc.Texture1D.MipSlice = 0;
  1533. ddesc.Flags = 0;
  1534. ID3D11DepthStencilView *initContents = NULL;
  1535. HRESULT hr = m_pDevice->CreateDepthStencilView(UNWRAP(WrappedID3D11Texture1D, tex1D), &ddesc, &initContents);
  1536. if(FAILED(hr))
  1537. {
  1538. RDCERR("Failed to create fast-clear DSV while creating initial states %08x", hr);
  1539. }
  1540. else
  1541. {
  1542. m_ResourceManager->SetInitialContents(id, initContents, 2);
  1543. }
  1544. }
  1545. else if(desc.Usage != D3D11_USAGE_IMMUTABLE)
  1546. {
  1547. desc.CPUAccessFlags = 0;
  1548. desc.Usage = D3D11_USAGE_DEFAULT;
  1549. desc.BindFlags = 0;
  1550. if(IsDepthFormat(desc.Format))
  1551. desc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
  1552. desc.MiscFlags &= ~D3D11_RESOURCE_MISC_GENERATE_MIPS;
  1553. ID3D11Texture1D *initContents = NULL;
  1554. HRESULT hr = m_pDevice->CreateTexture1D(&desc, NULL, &initContents);
  1555. if(FAILED(hr))
  1556. {
  1557. RDCERR("Failed to create tex3D while creating initial states %08x", hr);
  1558. }
  1559. else
  1560. {
  1561. m_pImmediateContext->GetReal()->CopyResource(initContents, UNWRAP(WrappedID3D11Texture1D, tex1D));
  1562. m_ResourceManager->SetInitialContents(id, initContents, 0);
  1563. }
  1564. }
  1565. }
  1566. else if(type == Resource_Texture2D)
  1567. {
  1568. WrappedID3D11Texture2D *tex2D = (WrappedID3D11Texture2D *)live;
  1569. D3D11_TEXTURE2D_DESC desc;
  1570. tex2D->GetDesc(&desc);
  1571. bool isMS = (desc.SampleDesc.Count > 1 || desc.SampleDesc.Quality > 0);
  1572. if(!hasData && desc.MipLevels == 1 && (desc.BindFlags & D3D11_BIND_RENDER_TARGET))
  1573. {
  1574. D3D11_RENDER_TARGET_VIEW_DESC rdesc;
  1575. rdesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;
  1576. rdesc.Format = GetTypedFormat(desc.Format);
  1577. rdesc.Texture2D.MipSlice = 0;
  1578. if(isMS) rdesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2DMS;
  1579. ID3D11RenderTargetView *initContents = NULL;
  1580. HRESULT hr = m_pDevice->CreateRenderTargetView(UNWRAP(WrappedID3D11Texture2D, tex2D), &rdesc, &initContents);
  1581. if(FAILED(hr))
  1582. {
  1583. RDCERR("Failed to create fast-clear RTV while creating initial states %08x", hr);
  1584. }
  1585. else
  1586. {
  1587. m_ResourceManager->SetInitialContents(id, initContents, 1);
  1588. }
  1589. }
  1590. else if(!hasData && desc.MipLevels == 1 && (desc.BindFlags & D3D11_BIND_DEPTH_STENCIL))
  1591. {
  1592. D3D11_DEPTH_STENCIL_VIEW_DESC ddesc;
  1593. ddesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
  1594. ddesc.Format = GetDepthTypedFormat(desc.Format);
  1595. ddesc.Texture1D.MipSlice = 0;
  1596. ddesc.Flags = 0;
  1597. if(isMS) ddesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2DMS;
  1598. ID3D11DepthStencilView *initContents = NULL;
  1599. HRESULT hr = m_pDevice->CreateDepthStencilView(UNWRAP(WrappedID3D11Texture2D, tex2D), &ddesc, &initContents);
  1600. if(FAILED(hr))
  1601. {
  1602. RDCERR("Failed to create fast-clear DSV while creating initial states %08x", hr);
  1603. }
  1604. else
  1605. {
  1606. m_ResourceManager->SetInitialContents(id, initContents, 2);
  1607. }
  1608. }
  1609. else if(desc.Usage != D3D11_USAGE_IMMUTABLE)
  1610. {
  1611. desc.CPUAccessFlags = 0;
  1612. desc.Usage = D3D11_USAGE_DEFAULT;
  1613. desc.BindFlags = isMS ? D3D11_BIND_SHADER_RESOURCE : 0;
  1614. if(IsDepthFormat(desc.Format))
  1615. desc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
  1616. desc.MiscFlags &= ~D3D11_RESOURCE_MISC_GENERATE_MIPS;
  1617. ID3D11Texture2D *initContents = NULL;
  1618. HRESULT hr = m_pDevice->CreateTexture2D(&desc, NULL, &initContents);
  1619. if(FAILED(hr))
  1620. {
  1621. RDCERR("Failed to create tex2D while creating initial states %08x", hr);
  1622. }
  1623. else
  1624. {
  1625. m_pImmediateContext->GetReal()->CopyResource(initContents, UNWRAP(WrappedID3D11Texture2D, tex2D));
  1626. m_ResourceManager->SetInitialContents(id, initContents, 0);
  1627. }
  1628. }
  1629. }
  1630. else if(type == Resource_Texture3D)
  1631. {
  1632. WrappedID3D11Texture3D *tex3D = (WrappedID3D11Texture3D *)live;
  1633. D3D11_TEXTURE3D_DESC desc;
  1634. tex3D->GetDesc(&desc);
  1635. if(!hasData && desc.MipLevels == 1 && (desc.BindFlags & D3D11_BIND_RENDER_TARGET))
  1636. {
  1637. D3D11_RENDER_TARGET_VIEW_DESC rdesc;
  1638. rdesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE3D;
  1639. rdesc.Format = GetTypedFormat(desc.Format);
  1640. rdesc.Texture3D.FirstWSlice = 0;
  1641. rdesc.Texture3D.MipSlice = 0;
  1642. rdesc.Texture3D.WSize = desc.Depth;
  1643. ID3D11RenderTargetView *initContents = NULL;
  1644. HRESULT hr = m_pDevice->CreateRenderTargetView(UNWRAP(WrappedID3D11Texture3D, tex3D), &rdesc, &initContents);
  1645. if(FAILED(hr))
  1646. {
  1647. RDCERR("Failed to create fast-clear RTV while creating initial states %08x", hr);
  1648. }
  1649. else
  1650. {
  1651. m_ResourceManager->SetInitialContents(id, initContents, 1);
  1652. }
  1653. }
  1654. else if(!hasData && desc.Usage != D3D11_USAGE_IMMUTABLE)
  1655. {
  1656. desc.CPUAccessFlags = 0;
  1657. desc.Usage = D3D11_USAGE_DEFAULT;
  1658. desc.BindFlags = 0;
  1659. desc.MiscFlags &= ~D3D11_RESOURCE_MISC_GENERATE_MIPS;
  1660. ID3D11Texture3D *initContents = NULL;
  1661. HRESULT hr = m_pDevice->CreateTexture3D(&desc, NULL, &initContents);
  1662. if(FAILED(hr))
  1663. {
  1664. RDCERR("Failed to create tex3D while creating initial states %08x", hr);
  1665. }
  1666. else
  1667. {
  1668. m_pImmediateContext->GetReal()->CopyResource(initContents, UNWRAP(WrappedID3D11Texture3D, tex3D));
  1669. m_ResourceManager->SetInitialContents(id, initContents, 0);
  1670. }
  1671. }
  1672. }
  1673. }
  1674. void WrappedID3D11Device::Apply_InitialState(ID3D11DeviceChild *live, ID3D11DeviceChild *initial, uint32_t count)
  1675. {
  1676. ResourceType type = IdentifyTypeByPtr(live);
  1677. if(type == Resource_UnorderedAccessView)
  1678. {
  1679. ID3D11UnorderedAccessView *uav = (ID3D11UnorderedAccessView *)live;
  1680. m_pImmediateContext->CSSetUnorderedAccessViews(0, 1, &uav, &count);
  1681. }
  1682. else
  1683. {
  1684. if(count == 1)
  1685. {
  1686. float emptyCol[] = { 0.0f, 0.0f, 0.0f, 0.0f };
  1687. m_pImmediateContext->GetReal()->ClearRenderTargetView((ID3D11RenderTargetView *)initial, emptyCol);
  1688. }
  1689. else if(count == 2)
  1690. {
  1691. m_pImmediateContext->GetReal()->ClearDepthStencilView((ID3D11DepthStencilView *)initial, D3D11_CLEAR_DEPTH|D3D11_CLEAR_STENCIL, 1.0f, 0);
  1692. }
  1693. else
  1694. {
  1695. ID3D11Resource *liveResource = (ID3D11Resource *)m_ResourceManager->UnwrapResource(live);
  1696. ID3D11Resource *initialResource = (ID3D11Resource *)initial;
  1697. m_pImmediateContext->GetReal()->CopyResource(liveResource, initialResource);
  1698. }
  1699. }
  1700. }
  1701. void WrappedID3D11Device::SetContextFilter(ResourceId id, uint32_t firstDefEv, uint32_t lastDefEv)
  1702. {
  1703. m_ReplayDefCtx = id;
  1704. m_FirstDefEv = firstDefEv;
  1705. m_LastDefEv = lastDefEv;
  1706. }
  1707. void WrappedID3D11Device::ReplayLog(uint32_t frameID, uint32_t startEventID, uint32_t endEventID, ReplayLogType replayType)
  1708. {
  1709. RDCASSERT(frameID < (uint32_t)m_FrameRecord.size());
  1710. uint64_t offs = m_FrameRecord[frameID].frameInfo.fileOffset;
  1711. m_pSerialiser->SetOffset(offs);
  1712. bool partial = true;
  1713. if(startEventID == 0 && (replayType == eReplay_WithoutDraw || replayType == eReplay_Full))
  1714. {
  1715. startEventID = m_FrameRecord[frameID].frameInfo.firstEvent;
  1716. partial = false;
  1717. }
  1718. D3D11ChunkType header = (D3D11ChunkType)m_pSerialiser->PushContext(NULL, 1, false);
  1719. RDCASSERT(header == CAPTURE_SCOPE);
  1720. m_pSerialiser->SkipCurrentChunk();
  1721. m_pSerialiser->PopContext(NULL, header);
  1722. if(!partial)
  1723. {
  1724. GetResourceManager()->ApplyInitialContents();
  1725. GetResourceManager()->ReleaseInFrameResources();
  1726. }
  1727. if(m_ReplayDefCtx == ResourceId())
  1728. {
  1729. if(replayType == eReplay_Full)
  1730. m_pImmediateContext->ReplayLog(EXECUTING, startEventID, endEventID, partial);
  1731. else if(replayType == eReplay_WithoutDraw)
  1732. m_pImmediateContext->ReplayLog(EXECUTING, startEventID, RDCMAX(1U,endEventID)-1, partial);
  1733. else if(replayType == eReplay_OnlyDraw)
  1734. m_pImmediateContext->ReplayLog(EXECUTING, endEventID, endEventID, partial);
  1735. else
  1736. RDCFATAL("Unexpected replay type");
  1737. }
  1738. else
  1739. {
  1740. if(replayType == eReplay_Full || replayType == eReplay_WithoutDraw)
  1741. {
  1742. m_pImmediateContext->ReplayLog(EXECUTING, startEventID, endEventID, partial);
  1743. }
  1744. m_pSerialiser->SetOffset(offs);
  1745. D3D11ChunkType header = (D3D11ChunkType)m_pSerialiser->PushContext(NULL, 1, false);
  1746. m_pSerialiser->SkipCurrentChunk();
  1747. m_pSerialiser->PopContext(NULL, header);
  1748. m_pImmediateContext->ReplayFakeContext(m_ReplayDefCtx);
  1749. if(replayType == eReplay_Full)
  1750. {
  1751. m_pImmediateContext->ClearState();
  1752. m_pImmediateContext->ReplayLog(EXECUTING, m_FirstDefEv, m_LastDefEv, true);
  1753. }
  1754. else if(replayType == eReplay_WithoutDraw && m_LastDefEv-1 >= m_FirstDefEv)
  1755. {
  1756. m_pImmediateContext->ClearState();
  1757. m_pImmediateContext->ReplayLog(EXECUTING, m_FirstDefEv, RDCMAX(m_LastDefEv,1U)-1, true);
  1758. }
  1759. else if(replayType == eReplay_OnlyDraw)
  1760. {
  1761. m_pImmediateContext->ReplayLog(EXECUTING, m_LastDefEv, m_LastDefEv, true);
  1762. }
  1763. m_pImmediateContext->ReplayFakeContext(ResourceId());
  1764. }
  1765. }
  1766. void WrappedID3D11Device::ReleaseSwapchainResources(IDXGISwapChain *swap)
  1767. {
  1768. if(swap)
  1769. {
  1770. DXGI_SWAP_CHAIN_DESC desc;
  1771. swap->GetDesc(&desc);
  1772. Keyboard::RemoveInputWindow(desc.OutputWindow);
  1773. }
  1774. auto it = m_SwapChains.find(swap);
  1775. if(it != m_SwapChains.end())
  1776. {
  1777. SAFE_RELEASE(it->second);
  1778. m_SwapChains.erase(it);
  1779. }
  1780. if(swap == m_SwapChain)
  1781. {
  1782. if(m_SwapChains.empty())
  1783. m_SwapChain = NULL;
  1784. else
  1785. m_SwapChain = m_SwapChains.begin()->first;
  1786. }
  1787. }
  1788. bool WrappedID3D11Device::Serialise_SetSwapChainTexture(IDXGISwapChain *swap, DXGI_SWAP_CHAIN_DESC *swapDesc, UINT buffer, ID3D11Texture2D *pTex)
  1789. {
  1790. SERIALISE_ELEMENT(DXGI_FORMAT, swapFormat, swapDesc->BufferDesc.Format);
  1791. SERIALISE_ELEMENT(uint32_t, BuffNum, buffer);
  1792. SERIALISE_ELEMENT(ResourceId, pTexture, GetIDForResource(pTex));
  1793. if(m_State >= WRITING)
  1794. {
  1795. D3D11_TEXTURE2D_DESC desc;
  1796. pTex->GetDesc(&desc);
  1797. SERIALISE_ELEMENT(D3D11_TEXTURE2D_DESC, Descriptor, desc);
  1798. }
  1799. else
  1800. {
  1801. ID3D11Texture2D *fakeBB;
  1802. SERIALISE_ELEMENT(D3D11_TEXTURE2D_DESC, Descriptor, D3D11_TEXTURE2D_DESC());
  1803. D3D11_TEXTURE2D_DESC realDescriptor = Descriptor;
  1804. // DXGI swap chain back buffers can be freely cast as a special-case.
  1805. // translate the format to a typeless format to allow for this.
  1806. // the original type will be stored in the texture below
  1807. Descriptor.Format = GetTypelessFormat(Descriptor.Format);
  1808. HRESULT hr = m_pDevice->CreateTexture2D(&Descriptor, NULL, &fakeBB);
  1809. if(FAILED(hr))
  1810. {
  1811. RDCERR("Failed to create fake back buffer, HRESULT: 0x%08x", hr);
  1812. }
  1813. else
  1814. {
  1815. WrappedID3D11Texture2D *wrapped = new WrappedID3D11Texture2D(fakeBB, this, TEXDISPLAY_INDIRECT_VIEW);
  1816. fakeBB = wrapped;
  1817. wrapped->m_RealDescriptor = new D3D11_TEXTURE2D_DESC(realDescriptor);
  1818. SetDebugName(fakeBB, "Serialised Swap Chain Buffer");
  1819. GetResourceManager()->AddLiveResource(pTexture, fakeBB);
  1820. }
  1821. }
  1822. return true;
  1823. }
  1824. void WrappedID3D11Device::SetSwapChainTexture(IDXGISwapChain *swap, DXGI_SWAP_CHAIN_DESC *swapDesc, UINT buffer, ID3D11Texture2D *pTex)
  1825. {
  1826. D3D11_TEXTURE2D_DESC desc;
  1827. pTex->GetDesc(&desc);
  1828. ResourceId id = GetIDForResource(pTex);
  1829. LazyInit();
  1830. // there shouldn't be a resource record for this texture as it wasn't created via
  1831. // CreateTexture2D
  1832. RDCASSERT(id != ResourceId() && !GetResourceManager()->HasResourceRecord(id));
  1833. if(m_State >= WRITING)
  1834. {
  1835. D3D11ResourceRecord *record = GetResourceManager()->AddResourceRecord(id);
  1836. record->DataInSerialiser = false;
  1837. record->SpecialResource = true;
  1838. record->Length = 0;
  1839. record->NumSubResources = 0;
  1840. record->SubResources = NULL;
  1841. SCOPED_LOCK(m_D3DLock);
  1842. SCOPED_SERIALISE_CONTEXT(CREATE_SWAP_BUFFER);
  1843. Serialise_SetSwapChainTexture(swap, swapDesc, buffer, pTex);
  1844. record->AddChunk(scope.Get());
  1845. }
  1846. if(buffer == 0 && m_State >= WRITING)
  1847. {
  1848. ID3D11RenderTargetView *rtv = NULL;
  1849. HRESULT hr = m_pDevice->CreateRenderTargetView(UNWRAP(WrappedID3D11Texture2D, pTex), NULL, &rtv);
  1850. if(FAILED(hr))
  1851. RDCERR("Couldn't create RTV for swapchain tex %08x", hr);
  1852. m_SwapChains[swap] = rtv;
  1853. }
  1854. if(swap)
  1855. {
  1856. DXGI_SWAP_CHAIN_DESC desc;
  1857. swap->GetDesc(&desc);
  1858. Keyboard::AddInputWindow(desc.OutputWindow);
  1859. }
  1860. if(m_SwapChain == NULL)
  1861. {
  1862. m_SwapChain = swap;
  1863. GetDebugManager()->SetOutputDimensions(desc.Width, desc.Height);
  1864. }
  1865. }
  1866. void WrappedID3D11Device::SetMarker(uint32_t col, const wchar_t *name)
  1867. {
  1868. if(m_pCurrentWrappedDevice == NULL)
  1869. return;
  1870. m_pCurrentWrappedDevice->m_pImmediateContext->ThreadSafe_SetMarker(col, name);
  1871. }
  1872. int WrappedID3D11Device::BeginEvent(uint32_t col, const wchar_t *name)
  1873. {
  1874. if(m_pCurrentWrappedDevice == NULL)
  1875. return 0;
  1876. return m_pCurrentWrappedDevice->m_pImmediateContext->ThreadSafe_BeginEvent(col, name);
  1877. }
  1878. int WrappedID3D11Device::EndEvent()
  1879. {
  1880. if(m_pCurrentWrappedDevice == NULL)
  1881. return 0;
  1882. return m_pCurrentWrappedDevice->m_pImmediateContext->ThreadSafe_EndEvent();
  1883. }
  1884. HRESULT WrappedID3D11Device::Present(IDXGISwapChain *swap, UINT SyncInterval, UINT Flags)
  1885. {
  1886. if((Flags & DXGI_PRESENT_TEST) != 0)
  1887. return S_OK;
  1888. RenderDoc::Inst().SetCurrentDriver(RDC_D3D11);
  1889. m_pCurrentWrappedDevice = this;
  1890. if(m_State == WRITING_IDLE)
  1891. RenderDoc::Inst().Tick();
  1892. m_pImmediateContext->EndFrame();
  1893. m_FrameCounter++; // first present becomes frame #1, this function is at the end of the frame
  1894. m_pImmediateContext->BeginFrame();
  1895. if(m_State == WRITING_IDLE)
  1896. {
  1897. D3D11RenderState old = *m_pImmediateContext->GetCurrentPipelineState();
  1898. m_FrameTimes.push_back(m_FrameTimer.GetMilliseconds());
  1899. m_TotalTime += m_FrameTimes.back();
  1900. m_FrameTimer.Restart();
  1901. // update every second
  1902. if(m_TotalTime > 1000.0)
  1903. {
  1904. m_MinFrametime = 10000.0;
  1905. m_MaxFrametime = 0.0;
  1906. m_AvgFrametime = 0.0;
  1907. m_TotalTime = 0.0;
  1908. for(size_t i=0; i < m_FrameTimes.size(); i++)
  1909. {
  1910. m_AvgFrametime += m_FrameTimes[i];
  1911. if(m_FrameTimes[i] < m_MinFrametime)
  1912. m_MinFrametime = m_FrameTimes[i];
  1913. if(m_FrameTimes[i] > m_MaxFrametime)
  1914. m_MaxFrametime = m_FrameTimes[i];
  1915. }
  1916. m_AvgFrametime /= double(m_FrameTimes.size());
  1917. m_FrameTimes.clear();
  1918. }
  1919. ID3D11RenderTargetView *rtv = m_SwapChains[swap];
  1920. m_pImmediateContext->GetReal()->OMSetRenderTargets(1, &rtv, NULL);
  1921. int w = GetDebugManager()->GetWidth();
  1922. int h = GetDebugManager()->GetHeight();
  1923. DXGI_SWAP_CHAIN_DESC swapDesc = {0};
  1924. swap->GetDesc(&swapDesc);
  1925. GetDebugManager()->SetOutputDimensions(swapDesc.BufferDesc.Width, swapDesc.BufferDesc.Height);
  1926. if(swap == m_SwapChain)
  1927. {
  1928. GetDebugManager()->RenderText(0.0f, 0.0f, 1.0f, "Frame: %d. F12/PrtScr to capture. %.2lf ms (%.2lf .. %.2lf) (%.0lf FPS)",
  1929. m_FrameCounter, m_AvgFrametime, m_MinFrametime, m_MaxFrametime, 1000.0f/m_AvgFrametime);
  1930. size_t i=0;
  1931. for(i=0; i < m_FrameRecord.size(); i++)
  1932. GetDebugManager()->RenderText(0.0f, (float)(i+1)*18.0f, 1.0f, "Captured frame %d.\n", m_FrameRecord[i].frameInfo.frameNumber);
  1933. if(m_FailedFrame > 0)
  1934. {
  1935. const char *reasonString = "Unknown reason";
  1936. switch(m_FailedReason)
  1937. {
  1938. case CaptureFailed_UncappedCmdlist: reasonString = "Uncapped command list"; break;
  1939. case CaptureFailed_UncappedUnmap: reasonString = "Uncapped Map()/Unmap()"; break;
  1940. default: break;
  1941. }
  1942. GetDebugManager()->RenderText(0.0f, (float)(++i)*18.0f, 1.0f, "Failed capture at frame %d:\n", m_FailedFrame);
  1943. GetDebugManager()->RenderText(0.0f, (float)(++i)*18.0f, 1.0f, " %hs\n", reasonString);
  1944. }
  1945. #if !defined(RELEASE)
  1946. GetDebugManager()->RenderText(0.0f, float(++i)*18.0f, 1.0f, "%llu chunks - %.2f MB", Chunk::NumLiveChunks(), float(Chunk::TotalMem())/1024.0f/1024.0f);
  1947. #endif
  1948. }
  1949. else
  1950. {
  1951. GetDebugManager()->RenderText(0.0f, 0.0f, 1.0f, "Inactive swapchain, F11 to cycle");
  1952. }
  1953. GetDebugManager()->SetOutputDimensions(w, h);
  1954. old.ApplyState(m_pImmediateContext);
  1955. if(RenderDoc::Inst().ShouldFocusToggle())
  1956. {
  1957. IDXGISwapChain *s = m_SwapChain;
  1958. m_SwapChain = NULL;
  1959. for(auto it=m_SwapChains.begin(); it!=m_SwapChains.end(); ++it)
  1960. {
  1961. auto next = it; next++;
  1962. if(it->first == s)
  1963. {
  1964. if(next != m_SwapChains.end())
  1965. m_SwapChain = next->first;
  1966. else
  1967. m_SwapChain = m_SwapChains.begin()->first;
  1968. break;
  1969. }
  1970. }
  1971. if(m_SwapChain == NULL)
  1972. m_SwapChain = swap;
  1973. DXGI_SWAP_CHAIN_DESC swapDesc = {0};
  1974. m_SwapChain->GetDesc(&swapDesc);
  1975. GetDebugManager()->SetOutputDimensions(swapDesc.BufferDesc.Width, swapDesc.BufferDesc.Height);
  1976. }
  1977. }
  1978. if(swap != m_SwapChain)
  1979. {
  1980. return S_OK;
  1981. }
  1982. // kill any current capture
  1983. if(m_State == WRITING_CAPFRAME)
  1984. {
  1985. CaptureFailReason reason;
  1986. if(m_pImmediateContext->HasSuccessfulCapture(reason))
  1987. {
  1988. SCOPED_LOCK(m_D3DLock);
  1989. RDCLOG("Finished capture, Frame %u", m_FrameCounter);
  1990. m_Failures = 0;
  1991. m_FailedFrame = 0;
  1992. m_FailedReason = CaptureSucceeded;
  1993. m_pImmediateContext->EndCaptureFrame();
  1994. m_pImmediateContext->FinishCapture();
  1995. for(auto it = m_DeferredContexts.begin(); it != m_DeferredContexts.end(); ++it)
  1996. {
  1997. WrappedID3D11DeviceContext *context = *it;
  1998. if(context)
  1999. {
  2000. context->FinishCapture();
  2001. }
  2002. else
  2003. {
  2004. RDCERR("NULL deferred context in resource record!");
  2005. }
  2006. }
  2007. const uint32_t maxSize = 1024;
  2008. byte *thpixels = NULL;
  2009. uint32_t thwidth = 0;
  2010. uint32_t thheight = 0;
  2011. {
  2012. ID3D11RenderTargetView *rtv = m_SwapChains[swap];
  2013. ID3D11Resource *res = NULL;
  2014. rtv->GetResource(&res); res->Release();
  2015. ID3D11Texture2D *tex = (ID3D11Texture2D *)res;
  2016. D3D11_TEXTURE2D_DESC desc;
  2017. tex->GetDesc(&desc);
  2018. desc.BindFlags = 0;
  2019. desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
  2020. desc.MiscFlags = 0;
  2021. desc.Usage = D3D11_USAGE_STAGING;
  2022. bool msaa = (desc.SampleDesc.Count > 1) || (desc.SampleDesc.Quality > 0);
  2023. desc.SampleDesc.Count = 1;
  2024. desc.SampleDesc.Quality = 0;
  2025. ID3D11Texture2D *stagingTex = NULL;
  2026. HRESULT hr = m_pDevice->CreateTexture2D(&desc, NULL, &stagingTex);
  2027. if(FAILED(hr))
  2028. {
  2029. RDCERR("Couldn't create staging texture to create thumbnail. %08x", hr);
  2030. }
  2031. else
  2032. {
  2033. if(msaa)
  2034. {
  2035. desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
  2036. desc.CPUAccessFlags = 0;
  2037. desc.Usage = D3D11_USAGE_DEFAULT;
  2038. ID3D11Texture2D *resolveTex = NULL;
  2039. HRESULT hr = m_pDevice->CreateTexture2D(&desc, NULL, &resolveTex);
  2040. if(FAILED(hr))
  2041. {
  2042. RDCERR("Couldn't create resolve texture to create thumbnail. %08x", hr);
  2043. tex = NULL;
  2044. }
  2045. else
  2046. {
  2047. m_pImmediateContext->GetReal()->ResolveSubresource(resolveTex, 0, tex, 0, desc.Format);
  2048. m_pImmediateContext->GetReal()->CopyResource(stagingTex, resolveTex);
  2049. resolveTex->Release();
  2050. }
  2051. }
  2052. else
  2053. {
  2054. m_pImmediateContext->GetReal()->CopyResource(stagingTex, tex);
  2055. }
  2056. if(tex)
  2057. {
  2058. ResourceFormat fmt = MakeResourceFormat(desc.Format);
  2059. D3D11_MAPPED_SUBRESOURCE mapped;
  2060. hr = m_pImmediateContext->GetReal()->Map(stagingTex, 0, D3D11_MAP_READ, 0, &mapped);
  2061. if(FAILED(hr))
  2062. {
  2063. RDCERR("Couldn't map staging texture to create thumbnail. %08x", hr);
  2064. }
  2065. else
  2066. {
  2067. byte *data = (byte *)mapped.pData;
  2068. float aspect = float(desc.Width)/float(desc.Height);
  2069. thwidth = RDCMIN(maxSize, desc.Width);
  2070. thwidth &= ~0x7; // align down to multiple of 8
  2071. thheight = uint32_t(float(thwidth)/aspect);
  2072. thpixels = new byte[3*thwidth*thheight];
  2073. float widthf = float(desc.Width);
  2074. float heightf = float(desc.Height);
  2075. uint32_t stride = fmt.compByteWidth*fmt.compCount;
  2076. bool buf1010102 = false;
  2077. bool bufBGRA = false;
  2078. if(fmt.special && fmt.specialFormat == eSpecial_R10G10B10A2)
  2079. {
  2080. stride = 4;
  2081. buf1010102 = true;
  2082. }
  2083. if(fmt.special && fmt.specialFormat == eSpecial_B8G8R8A8)
  2084. {
  2085. stride = 4;
  2086. bufBGRA = true;
  2087. }
  2088. byte *dst = thpixels;
  2089. for(uint32_t y=0; y < thheight; y++)
  2090. {
  2091. for(uint32_t x=0; x < thwidth; x++)
  2092. {
  2093. float xf = float(x)/float(thwidth);
  2094. float yf = float(y)/float(thheight);
  2095. byte *src = &data[ stride*uint32_t(xf*widthf) + mapped.RowPitch*uint32_t(yf*heightf) ];
  2096. if(buf1010102)
  2097. {
  2098. uint32_t *src1010102 = (uint32_t *)src;
  2099. Vec4f unorm = ConvertFromR10G10B10A2(*src1010102);
  2100. dst[0] = (byte)(unorm.x*255.0f);
  2101. dst[1] = (byte)(unorm.y*255.0f);
  2102. dst[2] = (byte)(unorm.z*255.0f);
  2103. }
  2104. else if(bufBGRA)
  2105. {
  2106. dst[0] = src[2];
  2107. dst[1] = src[1];
  2108. dst[2] = src[0];
  2109. }
  2110. else
  2111. {
  2112. dst[0] = src[0];
  2113. dst[1] = src[1];
  2114. dst[2] = src[2];
  2115. }
  2116. dst += 3;
  2117. }
  2118. }
  2119. m_pImmediateContext->GetReal()->Unmap(stagingTex, 0);
  2120. }
  2121. }
  2122. stagingTex->Release();
  2123. }
  2124. }
  2125. byte *jpgbuf = NULL;
  2126. int len = thwidth*thheight;
  2127. {
  2128. jpgbuf = new byte[len];
  2129. jpge::params p;
  2130. p.m_quality = 40;
  2131. bool success = jpge::compress_image_to_jpeg_file_in_memory(jpgbuf, len, thwidth, thheight, 3, thpixels, p);
  2132. if(!success)
  2133. {
  2134. RDCERR("Failed to compress to jpg");
  2135. SAFE_DELETE_ARRAY(jpgbuf);
  2136. thwidth = 0;
  2137. thheight = 0;
  2138. }
  2139. }
  2140. Serialiser *m_pFileSerialiser = RenderDoc::Inst().OpenWriteSerialiser(m_FrameCounter, m_InitParams, jpgbuf, len, thwidth, thheight);
  2141. SAFE_DELETE_ARRAY(jpgbuf);
  2142. SAFE_DELETE(thpixels);
  2143. {
  2144. SCOPED_SERIALISE_CONTEXT(DEVICE_INIT);
  2145. SERIALISE_ELEMENT(ResourceId, immContextId, m_pImmediateContext->GetResourceID());
  2146. m_pFileSerialiser->Insert(scope.Get(true));
  2147. }
  2148. RDCDEBUG("Inserting Resource Serialisers");
  2149. GetResourceManager()->InsertReferencedChunks(m_pFileSerialiser);
  2150. GetResourceManager()->InsertInitialContentsChunks(m_pSerialiser, m_pFileSerialiser);
  2151. RDCDEBUG("Creating Capture Scope");
  2152. {
  2153. SCOPED_SERIALISE_CONTEXT(CAPTURE_SCOPE);
  2154. Serialise_CaptureScope(0);
  2155. m_pFileSerialiser->Insert(scope.Get(true));
  2156. }
  2157. {
  2158. RDCDEBUG("Getting Resource Record");
  2159. D3D11ResourceRecord *record = m_ResourceManager->GetResourceRecord(m_pImmediateContext->GetResourceID());
  2160. RDCDEBUG("Accumulating context resource list");
  2161. map<int32_t, Chunk *> recordlist;
  2162. record->Insert(recordlist);
  2163. RDCDEBUG("Flushing %u records to file serialiser", (uint32_t)recordlist.size());
  2164. for(auto it = recordlist.begin(); it != recordlist.end(); ++it)
  2165. m_pFileSerialiser->Insert(it->second);
  2166. RDCDEBUG("Done");
  2167. }
  2168. m_CurFileSize += m_pFileSerialiser->FlushToDisk();
  2169. SAFE_DELETE(m_pFileSerialiser);
  2170. RenderDoc::Inst().SuccessfullyWrittenLog();
  2171. m_State = WRITING_IDLE;
  2172. m_pImmediateContext->CleanupCapture();
  2173. m_pImmediateContext->FreeCaptureData();
  2174. for(auto it = m_DeferredContexts.begin(); it != m_DeferredContexts.end(); ++it)
  2175. {
  2176. WrappedID3D11DeviceContext *context = *it;
  2177. if(context)
  2178. context->CleanupCapture();
  2179. else
  2180. RDCERR("NULL deferred context in resource record!");
  2181. }
  2182. GetResourceManager()->MarkUnwrittenResources();
  2183. GetResourceManager()->ClearReferencedResources();
  2184. }
  2185. else
  2186. {
  2187. RDCLOG("Failed to capture, frame %u", m_FrameCounter);
  2188. m_Failures++;
  2189. {
  2190. D3D11RenderState old = *m_pImmediateContext->GetCurrentPipelineState();
  2191. ID3D11RenderTargetView *rtv = m_SwapChains[swap];
  2192. if(rtv)
  2193. {
  2194. m_pImmediateContext->GetReal()->OMSetRenderTargets(1, &rtv, NULL);
  2195. int w = GetDebugManager()->GetWidth();
  2196. int h = GetDebugManager()->GetHeight();
  2197. DXGI_SWAP_CHAIN_DESC swapDesc = {0};
  2198. swap->GetDesc(&swapDesc);
  2199. GetDebugManager()->SetOutputDimensions(swapDesc.BufferDesc.Width, swapDesc.BufferDesc.Height);
  2200. const char *reasonString = "Unknown reason";
  2201. switch(reason)
  2202. {
  2203. case CaptureFailed_UncappedCmdlist: reasonString = "Uncapped command list"; break;
  2204. case CaptureFailed_UncappedUnmap: reasonString = "Uncapped Map()/Unmap()"; break;
  2205. default: break;
  2206. }
  2207. GetDebugManager()->RenderText(0.0f, 0.0f, 1.0f, "Failed to capture frame %u: %hs", m_FrameCounter, reasonString);
  2208. GetDebugManager()->SetOutputDimensions(w, h);
  2209. }
  2210. old.ApplyState(m_pImmediateContext);
  2211. }
  2212. m_FrameRecord.back().frameInfo.frameNumber = m_FrameCounter+1;
  2213. m_pImmediateContext->CleanupCapture();
  2214. for(auto it = m_DeferredContexts.begin(); it != m_DeferredContexts.end(); ++it)
  2215. {
  2216. WrappedID3D11DeviceContext *context = *it;
  2217. if(context)
  2218. context->CleanupCapture();
  2219. else
  2220. RDCERR("NULL deferred context in resource record!");
  2221. }
  2222. GetResourceManager()->ClearReferencedResources();
  2223. if(m_Failures > 5) // failed too many times
  2224. {
  2225. m_pImmediateContext->FinishCapture();
  2226. m_FrameRecord.pop_back();
  2227. for(auto it = m_DeferredContexts.begin(); it != m_DeferredContexts.end(); ++it)
  2228. {
  2229. WrappedID3D11DeviceContext *context = *it;
  2230. if(context)
  2231. {
  2232. context->FinishCapture();
  2233. }
  2234. else
  2235. {
  2236. RDCERR("NULL deferred context in resource record!");
  2237. }
  2238. }
  2239. m_pImmediateContext->FreeCaptureData();
  2240. m_FailedFrame = m_FrameCounter;
  2241. m_FailedReason = reason;
  2242. m_State = WRITING_IDLE;
  2243. for(auto it = m_DeferredContexts.begin(); it != m_DeferredContexts.end(); ++it)
  2244. {
  2245. WrappedID3D11DeviceContext *context = *it;
  2246. if(context)
  2247. context->CleanupCapture();
  2248. else
  2249. RDCERR("NULL deferred context in resource record!");
  2250. }
  2251. GetResourceManager()->MarkUnwrittenResources();
  2252. }
  2253. else
  2254. {
  2255. GetResourceManager()->MarkResourceFrameReferenced(m_ResourceID, eFrameRef_Write);
  2256. GetResourceManager()->PrepareInitialContents();
  2257. m_pImmediateContext->AttemptCapture();
  2258. m_pImmediateContext->BeginCaptureFrame();
  2259. for(auto it = m_DeferredContexts.begin(); it != m_DeferredContexts.end(); ++it)
  2260. {
  2261. WrappedID3D11DeviceContext *context = *it;
  2262. if(context)
  2263. {
  2264. context->AttemptCapture();
  2265. }
  2266. else
  2267. {
  2268. RDCERR("NULL deferred context in resource record!");
  2269. }
  2270. }
  2271. }
  2272. if(m_pInfoQueue)
  2273. m_pInfoQueue->ClearStoredMessages();
  2274. }
  2275. }
  2276. if(RenderDoc::Inst().ShouldTriggerCapture(m_FrameCounter) && m_State == WRITING_IDLE)
  2277. {
  2278. SCOPED_LOCK(m_D3DLock);
  2279. m_State = WRITING_CAPFRAME;
  2280. m_Failures = 0;
  2281. m_FailedFrame = 0;
  2282. m_FailedReason = CaptureSucceeded;
  2283. FetchFrameRecord record;
  2284. record.frameInfo.frameNumber = m_FrameCounter+1;
  2285. m_FrameRecord.push_back(record);
  2286. GetResourceManager()->ClearReferencedResources();
  2287. GetResourceManager()->MarkResourceFrameReferenced(m_ResourceID, eFrameRef_Write);
  2288. m_pImmediateContext->AttemptCapture();
  2289. m_pImmediateContext->BeginCaptureFrame();
  2290. for(auto it = m_DeferredContexts.begin(); it != m_DeferredContexts.end(); ++it)
  2291. {
  2292. WrappedID3D11DeviceContext *context = *it;
  2293. if(context)
  2294. {
  2295. context->AttemptCapture();
  2296. }
  2297. else
  2298. {
  2299. RDCERR("NULL deferred context in resource record!");
  2300. }
  2301. }
  2302. GetResourceManager()->PrepareInitialContents();
  2303. if(m_pInfoQueue)
  2304. m_pInfoQueue->ClearStoredMessages();
  2305. RDCLOG("Starting capture, frame %u", m_FrameCounter);
  2306. }
  2307. return S_OK;
  2308. }
  2309. void WrappedID3D11Device::AddDeferredContext(WrappedID3D11DeviceContext *defctx)
  2310. {
  2311. RDCASSERT(m_DeferredContexts.find(defctx) == m_DeferredContexts.end());
  2312. m_DeferredContexts.insert(defctx);
  2313. }
  2314. void WrappedID3D11Device::RemoveDeferredContext(WrappedID3D11DeviceContext *defctx)
  2315. {
  2316. RDCASSERT(m_DeferredContexts.find(defctx) != m_DeferredContexts.end());
  2317. m_DeferredContexts.erase(defctx);
  2318. }
  2319. bool WrappedID3D11Device::Serialise_SetResourceName(ID3D11DeviceChild *res, const char *nm)
  2320. {
  2321. SERIALISE_ELEMENT(ResourceId, resource, GetIDForResource(res));
  2322. string name = nm ? nm : "";
  2323. m_pSerialiser->Serialise("name", name);
  2324. if(m_State < WRITING && GetResourceManager()->HasLiveResource(resource))
  2325. {
  2326. ID3D11DeviceChild *r = GetResourceManager()->GetLiveResource(resource);
  2327. SetDebugName(r, name.c_str());
  2328. }
  2329. return true;
  2330. }
  2331. void WrappedID3D11Device::SetResourceName(ID3D11DeviceChild *res, const char *name)
  2332. {
  2333. if(m_State >= WRITING)
  2334. {
  2335. ResourceId idx = GetIDForResource(res);
  2336. D3D11ResourceRecord *record = GetResourceManager()->GetResourceRecord(idx);
  2337. if(record == NULL)
  2338. record = m_DeviceRecord;
  2339. RDCASSERT(idx != ResourceId());
  2340. SCOPED_LOCK(m_D3DLock);
  2341. {
  2342. SCOPED_SERIALISE_CONTEXT(SET_RESOURCE_NAME);
  2343. Serialise_SetResourceName(res, name);
  2344. record->AddChunk(scope.Get());
  2345. }
  2346. }
  2347. }
  2348. bool WrappedID3D11Device::Serialise_ReleaseResource(ID3D11DeviceChild *res)
  2349. {
  2350. ResourceType resourceType = Resource_Unknown;
  2351. ResourceId resource = GetIDForResource(res);
  2352. if(m_State >= WRITING)
  2353. {
  2354. resourceType = IdentifyTypeByPtr(res);
  2355. }
  2356. if(m_State == WRITING_IDLE || m_State < WRITING)
  2357. {
  2358. SERIALISE_ELEMENT(ResourceId, serRes, GetIDForResource(res));
  2359. SERIALISE_ELEMENT(ResourceType, serType, resourceType);
  2360. resourceType = serType;
  2361. resource = serRes;
  2362. }
  2363. if(m_State >= WRITING)
  2364. {
  2365. D3D11ResourceRecord *record = GetResourceManager()->GetResourceRecord(resource);
  2366. if(record)
  2367. record->Delete(m_ResourceManager);
  2368. switch(resourceType)
  2369. {
  2370. case Resource_RenderTargetView:
  2371. {
  2372. WrappedID3D11RenderTargetView* view = (WrappedID3D11RenderTargetView *)res;
  2373. D3D11ResourceRecord *viewRecord = view->GetResourceRecord();
  2374. if(viewRecord)
  2375. viewRecord->Delete(m_ResourceManager);
  2376. break;
  2377. }
  2378. case Resource_ShaderResourceView:
  2379. {
  2380. WrappedID3D11ShaderResourceView* view = (WrappedID3D11ShaderResourceView *)res;
  2381. D3D11ResourceRecord *viewRecord = view->GetResourceRecord();
  2382. if(viewRecord)
  2383. viewRecord->Delete(m_ResourceManager);
  2384. break;
  2385. }
  2386. case Resource_DepthStencilView:
  2387. {
  2388. WrappedID3D11DepthStencilView* view = (WrappedID3D11DepthStencilView *)res;
  2389. D3D11ResourceRecord *viewRecord = view->GetResourceRecord();
  2390. if(viewRecord)
  2391. viewRecord->Delete(m_ResourceManager);
  2392. break;
  2393. }
  2394. case Resource_UnorderedAccessView:
  2395. {
  2396. WrappedID3D11UnorderedAccessView* view = (WrappedID3D11UnorderedAccessView *)res;
  2397. D3D11ResourceRecord *viewRecord = view->GetResourceRecord();
  2398. if(viewRecord)
  2399. viewRecord->Delete(m_ResourceManager);
  2400. break;
  2401. }
  2402. }
  2403. }
  2404. if(m_State < WRITING && GetResourceManager()->HasLiveResource(resource))
  2405. {
  2406. ID3D11DeviceChild *res = GetResourceManager()->GetLiveResource(resource);
  2407. GetResourceManager()->EraseLiveResource(resource);
  2408. SAFE_RELEASE(res);
  2409. }
  2410. return true;
  2411. }
  2412. void WrappedID3D11Device::ReleaseResource(ID3D11DeviceChild *res)
  2413. {
  2414. ResourceId idx = GetIDForResource(res);
  2415. // wrapped resources get released all the time, we don't want to
  2416. // try and slerp in a resource release. Just the explicit ones
  2417. if(m_State < WRITING)
  2418. {
  2419. if(GetResourceManager()->HasLiveResource(idx))
  2420. GetResourceManager()->EraseLiveResource(idx);
  2421. return;
  2422. }
  2423. SCOPED_LOCK(m_D3DLock);
  2424. ResourceType type = IdentifyTypeByPtr(res);
  2425. D3D11ResourceRecord *record = m_DeviceRecord;
  2426. bool removegpu = true;
  2427. if(m_State == WRITING_IDLE)
  2428. {
  2429. if(type == Resource_ShaderResourceView ||
  2430. type == Resource_DepthStencilView ||
  2431. type == Resource_UnorderedAccessView ||
  2432. type == Resource_RenderTargetView ||
  2433. type == Resource_Buffer ||
  2434. type == Resource_Texture1D ||
  2435. type == Resource_Texture2D ||
  2436. type == Resource_Texture3D ||
  2437. type == Resource_CommandList)
  2438. {
  2439. if(type == Resource_ShaderResourceView ||
  2440. type == Resource_DepthStencilView ||
  2441. type == Resource_UnorderedAccessView ||
  2442. type == Resource_RenderTargetView
  2443. )
  2444. {
  2445. ID3D11View *view = (ID3D11View *)res;
  2446. ID3D11Resource *viewRes = NULL;
  2447. view->GetResource(&viewRes);
  2448. idx = GetIDForResource(viewRes);
  2449. SAFE_RELEASE(viewRes);
  2450. removegpu = false;
  2451. }
  2452. record = GetResourceManager()->GetResourceRecord(idx);
  2453. RDCASSERT(record);
  2454. if(record->SpecialResource)
  2455. {
  2456. record = m_DeviceRecord;
  2457. }
  2458. else if(record->GetRefCount() == 1)
  2459. {
  2460. // we're about to decrement this chunk out of existance!
  2461. // don't hold onto the record to add the chunk.
  2462. record = NULL;
  2463. }
  2464. }
  2465. }
  2466. if(removegpu)
  2467. GetResourceManager()->MarkCleanResource(idx);
  2468. if(type == Resource_DeviceContext)
  2469. {
  2470. RemoveDeferredContext((WrappedID3D11DeviceContext *)res);
  2471. }
  2472. bool serialiseRelease = true;
  2473. WrappedID3D11CommandList *cmdList = (WrappedID3D11CommandList *)res;
  2474. // don't serialise releases of counters or queries since we ignore them.
  2475. // Also don't serialise releases of command lists that weren't captured,
  2476. // since their creation won't be in the log either.
  2477. if(type == Resource_Counter || type == Resource_Query ||
  2478. (type == Resource_CommandList && !cmdList->IsCaptured())
  2479. )
  2480. serialiseRelease = false;
  2481. if(type == Resource_CommandList && !cmdList->IsCaptured())
  2482. {
  2483. record = GetResourceManager()->GetResourceRecord(idx);
  2484. if(record)
  2485. record->Delete(GetResourceManager());
  2486. }
  2487. if(serialiseRelease)
  2488. {
  2489. if(m_State == WRITING_CAPFRAME)
  2490. {
  2491. Serialise_ReleaseResource(res);
  2492. }
  2493. else
  2494. {
  2495. SCOPED_SERIALISE_CONTEXT(RELEASE_RESOURCE);
  2496. Serialise_ReleaseResource(res);
  2497. if(record)
  2498. {
  2499. record->AddChunk(scope.Get());
  2500. }
  2501. }
  2502. if(record == NULL)
  2503. {
  2504. // if record is NULL then we just deleted a reference-less resource.
  2505. // That means it is not used and can be safely discarded, so just
  2506. // throw away the serialiser contents
  2507. m_pSerialiser->Rewind();
  2508. }
  2509. }
  2510. }
  2511. WrappedID3D11DeviceContext *WrappedID3D11Device::GetDeferredContext( size_t idx )
  2512. {
  2513. auto it = m_DeferredContexts.begin();
  2514. for(size_t i=0; i < idx; i++)
  2515. {
  2516. ++it;
  2517. if(it == m_DeferredContexts.end())
  2518. return NULL;
  2519. }
  2520. return *it;
  2521. }