CmD3D9Device.cpp 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437
  1. /*
  2. -----------------------------------------------------------------------------
  3. This source file is part of OGRE
  4. (Object-oriented Graphics Rendering Engine)
  5. For the latest info, see http://www.ogre3d.org/
  6. Copyright (c) 2000-2011 Torus Knot Software Ltd
  7. Permission is hereby granted, free of charge, to any person obtaining a copy
  8. of this software and associated documentation files (the "Software"), to deal
  9. in the Software without restriction, including without limitation the rights
  10. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. copies of the Software, and to permit persons to whom the Software is
  12. furnished to do so, subject to the following conditions:
  13. The above copyright notice and this permission notice shall be included in
  14. all copies or substantial portions of the Software.
  15. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. THE SOFTWARE.
  22. -----------------------------------------------------------------------------
  23. */
  24. #include "CmD3D9Device.h"
  25. #include "CmD3D9DeviceManager.h"
  26. #include "CmD3D9Driver.h"
  27. #include "CmD3D9RenderSystem.h"
  28. #include "CmD3D9ResourceManager.h"
  29. #include "CmD3D9RenderWindow.h"
  30. #include "CmHardwareBufferManager.h"
  31. #include "CmException.h"
  32. #include "CmRenderSystemManager.h"
  33. namespace CamelotEngine
  34. {
  35. HWND D3D9Device::msSharedFocusWindow = NULL;
  36. //---------------------------------------------------------------------
  37. D3D9Device::D3D9Device(D3D9DeviceManager* deviceManager,
  38. UINT adapterNumber,
  39. HMONITOR hMonitor,
  40. D3DDEVTYPE devType,
  41. DWORD behaviorFlags)
  42. {
  43. mpDeviceManager = deviceManager;
  44. mpDevice = NULL;
  45. mAdapterNumber = adapterNumber;
  46. mMonitor = hMonitor;
  47. mDeviceType = devType;
  48. mFocusWindow = NULL;
  49. mBehaviorFlags = behaviorFlags;
  50. mD3D9DeviceCapsValid = false;
  51. mDeviceLost = false;
  52. mPresentationParamsCount = 0;
  53. mPresentationParams = NULL;
  54. memset(&mD3D9DeviceCaps, 0, sizeof(mD3D9DeviceCaps));
  55. memset(&mCreationParams, 0, sizeof(mCreationParams));
  56. }
  57. //---------------------------------------------------------------------
  58. D3D9Device::~D3D9Device()
  59. {
  60. }
  61. //---------------------------------------------------------------------
  62. D3D9Device::RenderWindowToResorucesIterator D3D9Device::getRenderWindowIterator(D3D9RenderWindow* renderWindow)
  63. {
  64. RenderWindowToResorucesIterator it = mMapRenderWindowToResoruces.find(renderWindow);
  65. if (it == mMapRenderWindowToResoruces.end())
  66. {
  67. OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
  68. "Render window was not attached to this device !!",
  69. "D3D9Device::getRenderWindowIterator" );
  70. }
  71. return it;
  72. }
  73. //---------------------------------------------------------------------
  74. void D3D9Device::attachRenderWindow(D3D9RenderWindow* renderWindow)
  75. {
  76. RenderWindowToResorucesIterator it = mMapRenderWindowToResoruces.find(renderWindow);
  77. if (it == mMapRenderWindowToResoruces.end())
  78. {
  79. RenderWindowResources* renderWindowResources = new RenderWindowResources;
  80. memset(renderWindowResources, 0, sizeof(RenderWindowResources));
  81. renderWindowResources->adapterOrdinalInGroupIndex = 0;
  82. renderWindowResources->acquired = false;
  83. mMapRenderWindowToResoruces[renderWindow] = renderWindowResources;
  84. }
  85. updateRenderWindowsIndices();
  86. }
  87. //---------------------------------------------------------------------
  88. void D3D9Device::detachRenderWindow(D3D9RenderWindow* renderWindow)
  89. {
  90. RenderWindowToResorucesIterator it = mMapRenderWindowToResoruces.find(renderWindow);
  91. if (it != mMapRenderWindowToResoruces.end())
  92. {
  93. // The focus window in which the d3d9 device created on is detached.
  94. // resources must be acquired again.
  95. if (mFocusWindow == renderWindow->getWindowHandle())
  96. {
  97. mFocusWindow = NULL;
  98. }
  99. // Case this is the shared focus window.
  100. if (renderWindow->getWindowHandle() == msSharedFocusWindow)
  101. setSharedWindowHandle(NULL);
  102. RenderWindowResources* renderWindowResources = it->second;
  103. releaseRenderWindowResources(renderWindowResources);
  104. SAFE_DELETE(renderWindowResources);
  105. mMapRenderWindowToResoruces.erase(it);
  106. }
  107. updateRenderWindowsIndices();
  108. }
  109. //---------------------------------------------------------------------
  110. bool D3D9Device::acquire()
  111. {
  112. updatePresentationParameters();
  113. bool resetDevice = false;
  114. // Create device if need to.
  115. if (mpDevice == NULL)
  116. {
  117. createD3D9Device();
  118. }
  119. // Case device already exists.
  120. else
  121. {
  122. RenderWindowToResorucesIterator itPrimary = getRenderWindowIterator(getPrimaryWindow());
  123. if (itPrimary->second->swapChain != NULL)
  124. {
  125. D3DPRESENT_PARAMETERS currentPresentParams;
  126. HRESULT hr;
  127. hr = itPrimary->second->swapChain->GetPresentParameters(&currentPresentParams);
  128. if (FAILED(hr))
  129. {
  130. OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
  131. "GetPresentParameters failed",
  132. "D3D9RenderWindow::acquire");
  133. }
  134. // Desired parameters are different then current parameters.
  135. // Possible scenario is that primary window resized and in the mean while another
  136. // window attached to this device.
  137. if (memcmp(&currentPresentParams, &mPresentationParams[0], sizeof(D3DPRESENT_PARAMETERS)) != 0)
  138. {
  139. resetDevice = true;
  140. }
  141. }
  142. // Make sure depth stencil is set to valid surface. It is going to be
  143. // grabbed by the primary window using the GetDepthStencilSurface method.
  144. if (resetDevice == false)
  145. {
  146. mpDevice->SetDepthStencilSurface(itPrimary->second->depthBuffer);
  147. }
  148. }
  149. // Reset device will update all render window resources.
  150. if (resetDevice)
  151. {
  152. reset();
  153. }
  154. // No need to reset -> just acquire resources.
  155. else
  156. {
  157. // Update resources of each window.
  158. RenderWindowToResorucesIterator it = mMapRenderWindowToResoruces.begin();
  159. while (it != mMapRenderWindowToResoruces.end())
  160. {
  161. acquireRenderWindowResources(it);
  162. ++it;
  163. }
  164. }
  165. return true;
  166. }
  167. //---------------------------------------------------------------------
  168. void D3D9Device::release()
  169. {
  170. if (mpDevice != NULL)
  171. {
  172. D3D9RenderSystem* renderSystem = static_cast<D3D9RenderSystem*>(CamelotEngine::RenderSystemManager::getActive());
  173. //// Clean up depth stencil surfaces
  174. //renderSystem->_cleanupDepthStencils(mpDevice);
  175. RenderWindowToResorucesIterator it = mMapRenderWindowToResoruces.begin();
  176. while (it != mMapRenderWindowToResoruces.end())
  177. {
  178. RenderWindowResources* renderWindowResources = it->second;
  179. releaseRenderWindowResources(renderWindowResources);
  180. ++it;
  181. }
  182. releaseD3D9Device();
  183. }
  184. }
  185. //---------------------------------------------------------------------
  186. bool D3D9Device::acquire(D3D9RenderWindow* renderWindow)
  187. {
  188. RenderWindowToResorucesIterator it = getRenderWindowIterator(renderWindow);
  189. acquireRenderWindowResources(it);
  190. return true;
  191. }
  192. //---------------------------------------------------------------------
  193. void D3D9Device::notifyDeviceLost()
  194. {
  195. // Case this device is already in lost state.
  196. if (mDeviceLost)
  197. return;
  198. // Case we just moved from valid state to lost state.
  199. mDeviceLost = true;
  200. D3D9RenderSystem* renderSystem = static_cast<D3D9RenderSystem*>(CamelotEngine::RenderSystemManager::getActive());
  201. renderSystem->notifyOnDeviceLost(this);
  202. }
  203. //---------------------------------------------------------------------
  204. IDirect3DSurface9* D3D9Device::getDepthBuffer(D3D9RenderWindow* renderWindow)
  205. {
  206. RenderWindowToResorucesIterator it = getRenderWindowIterator(renderWindow);
  207. return it->second->depthBuffer;
  208. }
  209. //---------------------------------------------------------------------
  210. IDirect3DSurface9* D3D9Device::getBackBuffer(D3D9RenderWindow* renderWindow)
  211. {
  212. RenderWindowToResorucesIterator it = getRenderWindowIterator(renderWindow);
  213. return it->second->backBuffer;
  214. }
  215. //---------------------------------------------------------------------
  216. UINT32 D3D9Device::getRenderWindowCount() const
  217. {
  218. return static_cast<UINT32>(mMapRenderWindowToResoruces.size());
  219. }
  220. //---------------------------------------------------------------------
  221. D3D9RenderWindow* D3D9Device::getRenderWindow(UINT32 index)
  222. {
  223. if (index >= mMapRenderWindowToResoruces.size())
  224. {
  225. OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
  226. "Index of render window is out of bounds!",
  227. "D3D9RenderWindow::getRenderWindow");
  228. }
  229. RenderWindowToResorucesIterator it = mMapRenderWindowToResoruces.begin();
  230. while (it != mMapRenderWindowToResoruces.end())
  231. {
  232. if (index == 0)
  233. break;
  234. --index;
  235. ++it;
  236. }
  237. return it->first;
  238. }
  239. //---------------------------------------------------------------------
  240. void D3D9Device::setAdapterOrdinalIndex(D3D9RenderWindow* renderWindow, UINT32 adapterOrdinalInGroupIndex)
  241. {
  242. RenderWindowToResorucesIterator it = getRenderWindowIterator(renderWindow);
  243. it->second->adapterOrdinalInGroupIndex = adapterOrdinalInGroupIndex;
  244. updateRenderWindowsIndices();
  245. }
  246. //---------------------------------------------------------------------
  247. void D3D9Device::destroy()
  248. {
  249. // Lock access to rendering device.
  250. D3D9RenderSystem::getResourceManager()->lockDeviceAccess();
  251. release();
  252. RenderWindowToResorucesIterator it = mMapRenderWindowToResoruces.begin();
  253. if (it != mMapRenderWindowToResoruces.end())
  254. {
  255. if (it->first->getWindowHandle() == msSharedFocusWindow)
  256. setSharedWindowHandle(NULL);
  257. SAFE_DELETE(it->second);
  258. ++it;
  259. }
  260. mMapRenderWindowToResoruces.clear();
  261. // Reset dynamic attributes.
  262. mFocusWindow = NULL;
  263. mD3D9DeviceCapsValid = false;
  264. SAFE_DELETE_ARRAY(mPresentationParams);
  265. mPresentationParamsCount = 0;
  266. // Notify the device manager on this instance destruction.
  267. mpDeviceManager->notifyOnDeviceDestroy(this);
  268. // UnLock access to rendering device.
  269. D3D9RenderSystem::getResourceManager()->unlockDeviceAccess();
  270. }
  271. //---------------------------------------------------------------------
  272. bool D3D9Device::isDeviceLost()
  273. {
  274. HRESULT hr;
  275. hr = mpDevice->TestCooperativeLevel();
  276. if (hr == D3DERR_DEVICELOST ||
  277. hr == D3DERR_DEVICENOTRESET)
  278. {
  279. return true;
  280. }
  281. return false;
  282. }
  283. //---------------------------------------------------------------------
  284. bool D3D9Device::reset()
  285. {
  286. HRESULT hr;
  287. // Check that device is in valid state for reset.
  288. hr = mpDevice->TestCooperativeLevel();
  289. if (hr == D3DERR_DEVICELOST ||
  290. hr == D3DERR_DRIVERINTERNALERROR)
  291. {
  292. return false;
  293. }
  294. // Lock access to rendering device.
  295. D3D9RenderSystem::getResourceManager()->lockDeviceAccess();
  296. D3D9RenderSystem* renderSystem = static_cast<D3D9RenderSystem*>(CamelotEngine::RenderSystemManager::getActive());
  297. // Inform all resources that device lost.
  298. D3D9RenderSystem::getResourceManager()->notifyOnDeviceLost(mpDevice);
  299. // Notify all listener before device is rested
  300. renderSystem->notifyOnDeviceLost(this);
  301. // Cleanup depth stencils surfaces.
  302. renderSystem->_cleanupDepthStencils(mpDevice);
  303. updatePresentationParameters();
  304. RenderWindowToResorucesIterator it = mMapRenderWindowToResoruces.begin();
  305. while (it != mMapRenderWindowToResoruces.end())
  306. {
  307. RenderWindowResources* renderWindowResources = it->second;
  308. releaseRenderWindowResources(renderWindowResources);
  309. ++it;
  310. }
  311. clearDeviceStreams();
  312. // Reset the device using the presentation parameters.
  313. hr = mpDevice->Reset(mPresentationParams);
  314. if (hr == D3DERR_DEVICELOST)
  315. {
  316. // UnLock access to rendering device.
  317. D3D9RenderSystem::getResourceManager()->unlockDeviceAccess();
  318. // Don't continue
  319. return false;
  320. }
  321. else if (FAILED(hr))
  322. {
  323. OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
  324. "Cannot reset device!",
  325. "D3D9RenderWindow::reset");
  326. }
  327. mDeviceLost = false;
  328. // Initialize device states.
  329. setupDeviceStates();
  330. // Update resources of each window.
  331. it = mMapRenderWindowToResoruces.begin();
  332. while (it != mMapRenderWindowToResoruces.end())
  333. {
  334. acquireRenderWindowResources(it);
  335. ++it;
  336. }
  337. D3D9Device* pCurActiveDevice = mpDeviceManager->getActiveDevice();
  338. mpDeviceManager->setActiveDevice(this);
  339. // Inform all resources that device has been reset.
  340. D3D9RenderSystem::getResourceManager()->notifyOnDeviceReset(mpDevice);
  341. mpDeviceManager->setActiveDevice(pCurActiveDevice);
  342. renderSystem->notifyOnDeviceReset(this);
  343. // UnLock access to rendering device.
  344. D3D9RenderSystem::getResourceManager()->unlockDeviceAccess();
  345. return true;
  346. }
  347. //---------------------------------------------------------------------
  348. bool D3D9Device::isAutoDepthStencil() const
  349. {
  350. const D3DPRESENT_PARAMETERS& primaryPresentationParams = mPresentationParams[0];
  351. // Check if auto depth stencil can be used.
  352. for (unsigned int i = 1; i < mPresentationParamsCount; i++)
  353. {
  354. // disable AutoDepthStencil if these parameters are not all the same.
  355. if(primaryPresentationParams.BackBufferHeight != mPresentationParams[i].BackBufferHeight ||
  356. primaryPresentationParams.BackBufferWidth != mPresentationParams[i].BackBufferWidth ||
  357. primaryPresentationParams.BackBufferFormat != mPresentationParams[i].BackBufferFormat ||
  358. primaryPresentationParams.AutoDepthStencilFormat != mPresentationParams[i].AutoDepthStencilFormat ||
  359. primaryPresentationParams.MultiSampleQuality != mPresentationParams[i].MultiSampleQuality ||
  360. primaryPresentationParams.MultiSampleType != mPresentationParams[i].MultiSampleType)
  361. {
  362. return false;
  363. }
  364. }
  365. return true;
  366. }
  367. //---------------------------------------------------------------------
  368. const D3DCAPS9& D3D9Device::getD3D9DeviceCaps() const
  369. {
  370. if (mD3D9DeviceCapsValid == false)
  371. {
  372. OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
  373. "Device caps are invalid!",
  374. "D3D9Device::getD3D9DeviceCaps" );
  375. }
  376. return mD3D9DeviceCaps;
  377. }
  378. //---------------------------------------------------------------------
  379. D3DFORMAT D3D9Device::getBackBufferFormat() const
  380. {
  381. if (mPresentationParams == NULL || mPresentationParamsCount == 0)
  382. {
  383. OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
  384. "Presentation parameters are invalid!",
  385. "D3D9Device::getBackBufferFormat" );
  386. }
  387. return mPresentationParams[0].BackBufferFormat;
  388. }
  389. //---------------------------------------------------------------------
  390. IDirect3DDevice9* D3D9Device::getD3D9Device()
  391. {
  392. return mpDevice;
  393. }
  394. //---------------------------------------------------------------------
  395. void D3D9Device::updatePresentationParameters()
  396. {
  397. // Clear old presentation parameters.
  398. SAFE_DELETE_ARRAY(mPresentationParams);
  399. mPresentationParamsCount = 0;
  400. if (mMapRenderWindowToResoruces.size() > 0)
  401. {
  402. mPresentationParams = new D3DPRESENT_PARAMETERS[mMapRenderWindowToResoruces.size()];
  403. RenderWindowToResorucesIterator it = mMapRenderWindowToResoruces.begin();
  404. while (it != mMapRenderWindowToResoruces.end())
  405. {
  406. D3D9RenderWindow* renderWindow = it->first;
  407. RenderWindowResources* renderWindowResources = it->second;
  408. // Ask the render window to build it's own parameters.
  409. renderWindow->buildPresentParameters(&renderWindowResources->presentParameters);
  410. // Update shared focus window handle.
  411. if (renderWindow->isFullScreen() &&
  412. renderWindowResources->presentParametersIndex == 0 &&
  413. msSharedFocusWindow == NULL)
  414. setSharedWindowHandle(renderWindow->getWindowHandle());
  415. // This is the primary window or a full screen window that is part of multi head device.
  416. if (renderWindowResources->presentParametersIndex == 0 ||
  417. renderWindow->isFullScreen())
  418. {
  419. mPresentationParams[renderWindowResources->presentParametersIndex] = renderWindowResources->presentParameters;
  420. mPresentationParamsCount++;
  421. }
  422. ++it;
  423. }
  424. }
  425. // Case we have to cancel auto depth stencil.
  426. if (isMultihead() && isAutoDepthStencil() == false)
  427. {
  428. for(unsigned int i = 0; i < mPresentationParamsCount; i++)
  429. {
  430. mPresentationParams[i].EnableAutoDepthStencil = false;
  431. }
  432. }
  433. }
  434. //---------------------------------------------------------------------
  435. UINT D3D9Device::getAdapterNumber() const
  436. {
  437. return mAdapterNumber;
  438. }
  439. //---------------------------------------------------------------------
  440. D3DDEVTYPE D3D9Device::getDeviceType() const
  441. {
  442. return mDeviceType;
  443. }
  444. //---------------------------------------------------------------------
  445. bool D3D9Device::isMultihead() const
  446. {
  447. RenderWindowToResorucesMap::const_iterator it = mMapRenderWindowToResoruces.begin();
  448. while (it != mMapRenderWindowToResoruces.end())
  449. {
  450. RenderWindowResources* renderWindowResources = it->second;
  451. if (renderWindowResources->adapterOrdinalInGroupIndex > 0 &&
  452. it->first->isFullScreen())
  453. {
  454. return true;
  455. }
  456. ++it;
  457. }
  458. return false;
  459. }
  460. //---------------------------------------------------------------------
  461. void D3D9Device::clearDeviceStreams()
  462. {
  463. D3D9RenderSystem* renderSystem = static_cast<D3D9RenderSystem*>(CamelotEngine::RenderSystemManager::getActive());
  464. // Set all texture units to nothing to release texture surfaces
  465. for (DWORD stage = 0; stage < mD3D9DeviceCaps.MaxSimultaneousTextures; ++stage)
  466. {
  467. DWORD dwCurValue = D3DTOP_FORCE_DWORD;
  468. HRESULT hr;
  469. hr = mpDevice->SetTexture(stage, NULL);
  470. if( hr != S_OK )
  471. {
  472. String str = "Unable to disable texture '" + toString((unsigned int)stage) + "' in D3D9";
  473. OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, str, "D3D9Device::clearDeviceStreams" );
  474. }
  475. mpDevice->GetTextureStageState(static_cast<DWORD>(stage), D3DTSS_COLOROP, &dwCurValue);
  476. if (dwCurValue != D3DTOP_DISABLE)
  477. {
  478. hr = mpDevice->SetTextureStageState(static_cast<DWORD>(stage), D3DTSS_COLOROP, D3DTOP_DISABLE);
  479. if( hr != S_OK )
  480. {
  481. String str = "Unable to disable texture '" + toString((unsigned)stage) + "' in D3D9";
  482. OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, str, "D3D9Device::clearDeviceStreams" );
  483. }
  484. }
  485. // set stage desc. to defaults
  486. renderSystem->mTexStageDesc[stage].pTex = 0;
  487. renderSystem->mTexStageDesc[stage].autoTexCoordType = TEXCALC_NONE;
  488. renderSystem->mTexStageDesc[stage].coordIndex = 0;
  489. renderSystem->mTexStageDesc[stage].texType = D3D9Mappings::D3D_TEX_TYPE_NORMAL;
  490. }
  491. // Unbind any vertex streams to avoid memory leaks
  492. for (unsigned int i = 0; i < mD3D9DeviceCaps.MaxStreams; ++i)
  493. {
  494. mpDevice->SetStreamSource(i, NULL, 0, 0);
  495. }
  496. }
  497. //---------------------------------------------------------------------
  498. void D3D9Device::createD3D9Device()
  499. {
  500. // Update focus window.
  501. D3D9RenderWindow* primaryRenderWindow = getPrimaryWindow();
  502. // Case we have to share the same focus window.
  503. if (msSharedFocusWindow != NULL)
  504. mFocusWindow = msSharedFocusWindow;
  505. else
  506. mFocusWindow = primaryRenderWindow->getWindowHandle();
  507. IDirect3D9* pD3D9 = D3D9RenderSystem::getDirect3D9();
  508. HRESULT hr;
  509. if (isMultihead())
  510. {
  511. mBehaviorFlags |= D3DCREATE_ADAPTERGROUP_DEVICE;
  512. }
  513. else
  514. {
  515. mBehaviorFlags &= ~D3DCREATE_ADAPTERGROUP_DEVICE;
  516. }
  517. // Try to create the device with hardware vertex processing.
  518. mBehaviorFlags |= D3DCREATE_HARDWARE_VERTEXPROCESSING;
  519. hr = pD3D9->CreateDevice(mAdapterNumber, mDeviceType, mFocusWindow,
  520. mBehaviorFlags, mPresentationParams, &mpDevice);
  521. if (FAILED(hr))
  522. {
  523. // Try a second time, may fail the first time due to back buffer count,
  524. // which will be corrected down to 1 by the runtime
  525. hr = pD3D9->CreateDevice(mAdapterNumber, mDeviceType, mFocusWindow,
  526. mBehaviorFlags, mPresentationParams, &mpDevice);
  527. }
  528. // Case hardware vertex processing failed.
  529. if( FAILED( hr ) )
  530. {
  531. // Try to create the device with mixed vertex processing.
  532. mBehaviorFlags &= ~D3DCREATE_HARDWARE_VERTEXPROCESSING;
  533. mBehaviorFlags |= D3DCREATE_MIXED_VERTEXPROCESSING;
  534. hr = pD3D9->CreateDevice(mAdapterNumber, mDeviceType, mFocusWindow,
  535. mBehaviorFlags, mPresentationParams, &mpDevice);
  536. }
  537. if( FAILED( hr ) )
  538. {
  539. // try to create the device with software vertex processing.
  540. mBehaviorFlags &= ~D3DCREATE_MIXED_VERTEXPROCESSING;
  541. mBehaviorFlags |= D3DCREATE_SOFTWARE_VERTEXPROCESSING;
  542. hr = pD3D9->CreateDevice(mAdapterNumber, mDeviceType, mFocusWindow,
  543. mBehaviorFlags, mPresentationParams, &mpDevice);
  544. }
  545. if ( FAILED( hr ) )
  546. {
  547. // try reference device
  548. mDeviceType = D3DDEVTYPE_REF;
  549. hr = pD3D9->CreateDevice(mAdapterNumber, mDeviceType, mFocusWindow,
  550. mBehaviorFlags, mPresentationParams, &mpDevice);
  551. if ( FAILED( hr ) )
  552. {
  553. OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
  554. "Cannot create device!",
  555. "D3D9Device::createD3D9Device" );
  556. }
  557. }
  558. // Get current device caps.
  559. hr = mpDevice->GetDeviceCaps(&mD3D9DeviceCaps);
  560. if( FAILED( hr ) )
  561. {
  562. OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
  563. "Cannot get device caps!",
  564. "D3D9Device::createD3D9Device" );
  565. }
  566. // Get current creation parameters caps.
  567. hr = mpDevice->GetCreationParameters(&mCreationParams);
  568. if ( FAILED(hr) )
  569. {
  570. OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
  571. "Error Get Creation Parameters",
  572. "D3D9Device:createD3D9Device" );
  573. }
  574. mD3D9DeviceCapsValid = true;
  575. // Initialize device states.
  576. setupDeviceStates();
  577. // Lock access to rendering device.
  578. D3D9RenderSystem::getResourceManager()->lockDeviceAccess();
  579. D3D9Device* pCurActiveDevice = mpDeviceManager->getActiveDevice();
  580. mpDeviceManager->setActiveDevice(this);
  581. // Inform all resources that new device created.
  582. D3D9RenderSystem::getResourceManager()->notifyOnDeviceCreate(mpDevice);
  583. mpDeviceManager->setActiveDevice(pCurActiveDevice);
  584. // UnLock access to rendering device.
  585. D3D9RenderSystem::getResourceManager()->unlockDeviceAccess();
  586. }
  587. //---------------------------------------------------------------------
  588. void D3D9Device::releaseD3D9Device()
  589. {
  590. if (mpDevice != NULL)
  591. {
  592. // Lock access to rendering device.
  593. D3D9RenderSystem::getResourceManager()->lockDeviceAccess();
  594. D3D9Device* pCurActiveDevice = mpDeviceManager->getActiveDevice();
  595. mpDeviceManager->setActiveDevice(this);
  596. // Inform all resources that device is going to be destroyed.
  597. D3D9RenderSystem::getResourceManager()->notifyOnDeviceDestroy(mpDevice);
  598. mpDeviceManager->setActiveDevice(pCurActiveDevice);
  599. clearDeviceStreams();
  600. // Release device.
  601. SAFE_RELEASE(mpDevice);
  602. // UnLock access to rendering device.
  603. D3D9RenderSystem::getResourceManager()->unlockDeviceAccess();
  604. }
  605. }
  606. //---------------------------------------------------------------------
  607. void D3D9Device::releaseRenderWindowResources(RenderWindowResources* renderWindowResources)
  608. {
  609. SAFE_RELEASE(renderWindowResources->backBuffer);
  610. SAFE_RELEASE(renderWindowResources->depthBuffer);
  611. SAFE_RELEASE(renderWindowResources->swapChain);
  612. renderWindowResources->acquired = false;
  613. }
  614. //---------------------------------------------------------------------
  615. void D3D9Device::invalidate(D3D9RenderWindow* renderWindow)
  616. {
  617. RenderWindowToResorucesIterator it = getRenderWindowIterator(renderWindow);
  618. it->second->acquired = false;
  619. }
  620. //---------------------------------------------------------------------
  621. bool D3D9Device::validate(D3D9RenderWindow* renderWindow)
  622. {
  623. // Validate that the render window should run on this device.
  624. if (false == validateDisplayMonitor(renderWindow))
  625. return false;
  626. // Validate that this device created on the correct target focus window handle
  627. validateFocusWindow();
  628. // Validate that the render window dimensions matches to back buffer dimensions.
  629. validateBackBufferSize(renderWindow);
  630. // Validate that this device is in valid rendering state.
  631. if (false == validateDeviceState(renderWindow))
  632. return false;
  633. return true;
  634. }
  635. //---------------------------------------------------------------------
  636. void D3D9Device::validateFocusWindow()
  637. {
  638. // Focus window changed -> device should be re-acquired.
  639. if ((msSharedFocusWindow != NULL && mCreationParams.hFocusWindow != msSharedFocusWindow) ||
  640. (msSharedFocusWindow == NULL && mCreationParams.hFocusWindow != getPrimaryWindow()->getWindowHandle()))
  641. {
  642. // Lock access to rendering device.
  643. D3D9RenderSystem::getResourceManager()->lockDeviceAccess();
  644. release();
  645. acquire();
  646. // UnLock access to rendering device.
  647. D3D9RenderSystem::getResourceManager()->unlockDeviceAccess();
  648. }
  649. }
  650. //---------------------------------------------------------------------
  651. bool D3D9Device::validateDeviceState(D3D9RenderWindow* renderWindow)
  652. {
  653. RenderWindowToResorucesIterator it = getRenderWindowIterator(renderWindow);
  654. RenderWindowResources* renderWindowResources = it->second;
  655. HRESULT hr;
  656. hr = mpDevice->TestCooperativeLevel();
  657. // Case device is not valid for rendering.
  658. if (FAILED(hr))
  659. {
  660. // device lost, and we can't reset
  661. // can't do anything about it here, wait until we get
  662. // D3DERR_DEVICENOTRESET; rendering calls will silently fail until
  663. // then (except Present, but we ignore device lost there too)
  664. if (hr == D3DERR_DEVICELOST)
  665. {
  666. releaseRenderWindowResources(renderWindowResources);
  667. notifyDeviceLost();
  668. return false;
  669. }
  670. // device lost, and we can reset
  671. else if (hr == D3DERR_DEVICENOTRESET)
  672. {
  673. bool deviceRestored = reset();
  674. // Device was not restored yet.
  675. if (deviceRestored == false)
  676. {
  677. // Wait a while
  678. Sleep(50);
  679. return false;
  680. }
  681. }
  682. }
  683. // Render window resources explicitly invalidated. (Resize or window mode switch)
  684. if (renderWindowResources->acquired == false)
  685. {
  686. if (getPrimaryWindow() == renderWindow)
  687. {
  688. bool deviceRestored = reset();
  689. // Device was not restored yet.
  690. if (deviceRestored == false)
  691. {
  692. // Wait a while
  693. Sleep(50);
  694. return false;
  695. }
  696. }
  697. else
  698. {
  699. acquire(renderWindow);
  700. }
  701. }
  702. return true;
  703. }
  704. //---------------------------------------------------------------------
  705. void D3D9Device::validateBackBufferSize(D3D9RenderWindow* renderWindow)
  706. {
  707. RenderWindowToResorucesIterator it = getRenderWindowIterator(renderWindow);
  708. RenderWindowResources* renderWindowResources = it->second;
  709. // Case size has been changed.
  710. if (renderWindow->getWidth() != renderWindowResources->presentParameters.BackBufferWidth ||
  711. renderWindow->getHeight() != renderWindowResources->presentParameters.BackBufferHeight)
  712. {
  713. if (renderWindow->getWidth() > 0)
  714. renderWindowResources->presentParameters.BackBufferWidth = renderWindow->getWidth();
  715. if (renderWindow->getHeight() > 0)
  716. renderWindowResources->presentParameters.BackBufferHeight = renderWindow->getHeight();
  717. invalidate(renderWindow);
  718. }
  719. }
  720. //---------------------------------------------------------------------
  721. bool D3D9Device::validateDisplayMonitor(D3D9RenderWindow* renderWindow)
  722. {
  723. // Ignore full screen since it doesn't really move and it is possible
  724. // that it created using multi-head adapter so for a subordinate the
  725. // native monitor handle and this device handle will be different.
  726. if (renderWindow->isFullScreen())
  727. return true;
  728. RenderWindowToResorucesIterator it = getRenderWindowIterator(renderWindow);
  729. HMONITOR hRenderWindowMonitor = NULL;
  730. // Find the monitor this render window belongs to.
  731. hRenderWindowMonitor = MonitorFromWindow(renderWindow->getWindowHandle(), MONITOR_DEFAULTTONULL);
  732. // This window doesn't intersect with any of the display monitor
  733. if (hRenderWindowMonitor == NULL)
  734. return false;
  735. // Case this window changed monitor.
  736. if (hRenderWindowMonitor != mMonitor)
  737. {
  738. // Lock access to rendering device.
  739. D3D9RenderSystem::getResourceManager()->lockDeviceAccess();
  740. mpDeviceManager->linkRenderWindow(renderWindow);
  741. // UnLock access to rendering device.
  742. D3D9RenderSystem::getResourceManager()->unlockDeviceAccess();
  743. return false;
  744. }
  745. return true;
  746. }
  747. //---------------------------------------------------------------------
  748. void D3D9Device::present(D3D9RenderWindow* renderWindow)
  749. {
  750. RenderWindowToResorucesIterator it = getRenderWindowIterator(renderWindow);
  751. RenderWindowResources* renderWindowResources = it->second;
  752. // Skip present while current device state is invalid.
  753. if (mDeviceLost ||
  754. renderWindowResources->acquired == false ||
  755. isDeviceLost())
  756. return;
  757. HRESULT hr;
  758. if (isMultihead())
  759. {
  760. // Only the master will call present method results in synchronized
  761. // buffer swap for the rest of the implicit swap chain.
  762. if (getPrimaryWindow() == renderWindow)
  763. hr = mpDevice->Present( NULL, NULL, NULL, NULL );
  764. else
  765. hr = S_OK;
  766. }
  767. else
  768. {
  769. hr = renderWindowResources->swapChain->Present(NULL, NULL, NULL, NULL, 0);
  770. }
  771. if( D3DERR_DEVICELOST == hr)
  772. {
  773. releaseRenderWindowResources(renderWindowResources);
  774. notifyDeviceLost();
  775. }
  776. else if( FAILED(hr) )
  777. {
  778. OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
  779. "Error Presenting surfaces",
  780. "D3D9Device::present" );
  781. }
  782. else
  783. {
  784. // TODO PORT - What is this used for? In any case I don't have Root so just set it to 0
  785. //mLastPresentFrame = Root::getSingleton().getNextFrameNumber();
  786. mLastPresentFrame = 0;
  787. }
  788. }
  789. //---------------------------------------------------------------------
  790. void D3D9Device::acquireRenderWindowResources(RenderWindowToResorucesIterator it)
  791. {
  792. RenderWindowResources* renderWindowResources = it->second;
  793. D3D9RenderWindow* renderWindow = it->first;
  794. releaseRenderWindowResources(renderWindowResources);
  795. // Create additional swap chain
  796. if (isSwapChainWindow(renderWindow) && !isMultihead())
  797. {
  798. // Create swap chain
  799. HRESULT hr = mpDevice->CreateAdditionalSwapChain(&renderWindowResources->presentParameters,
  800. &renderWindowResources->swapChain);
  801. if (FAILED(hr))
  802. {
  803. // Try a second time, may fail the first time due to back buffer count,
  804. // which will be corrected by the runtime
  805. hr = mpDevice->CreateAdditionalSwapChain(&renderWindowResources->presentParameters,
  806. &renderWindowResources->swapChain);
  807. }
  808. if (FAILED(hr))
  809. {
  810. OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
  811. "Unable to create an additional swap chain",
  812. "D3D9RenderWindow::acquireRenderWindowResources");
  813. }
  814. }
  815. else
  816. {
  817. // The swap chain is already created by the device
  818. HRESULT hr = mpDevice->GetSwapChain(renderWindowResources->presentParametersIndex,
  819. &renderWindowResources->swapChain);
  820. if (FAILED(hr))
  821. {
  822. OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
  823. "Unable to get the swap chain",
  824. "D3D9RenderWindow::acquireRenderWindowResources");
  825. }
  826. }
  827. // Store references to buffers for convenience
  828. renderWindowResources->swapChain->GetBackBuffer(0, D3DBACKBUFFER_TYPE_MONO,
  829. &renderWindowResources->backBuffer);
  830. // Additional swap chains need their own depth buffer
  831. // to support resizing them
  832. if (renderWindow->isDepthBuffered())
  833. {
  834. // if multihead is enabled, depth buffer can be created automatically for
  835. // all the adapters. if multihead is not enabled, depth buffer is just
  836. // created for the main swap chain
  837. if (isMultihead() && isAutoDepthStencil() ||
  838. isMultihead() == false && isSwapChainWindow(renderWindow) == false)
  839. {
  840. mpDevice->GetDepthStencilSurface(&renderWindowResources->depthBuffer);
  841. }
  842. else
  843. {
  844. UINT32 targetWidth = renderWindow->getWidth();
  845. UINT32 targetHeight = renderWindow->getHeight();
  846. if (targetWidth == 0)
  847. targetWidth = 1;
  848. if (targetHeight == 0)
  849. targetHeight = 1;
  850. HRESULT hr = mpDevice->CreateDepthStencilSurface(
  851. targetWidth, targetHeight,
  852. renderWindowResources->presentParameters.AutoDepthStencilFormat,
  853. renderWindowResources->presentParameters.MultiSampleType,
  854. renderWindowResources->presentParameters.MultiSampleQuality,
  855. (renderWindowResources->presentParameters.Flags & D3DPRESENTFLAG_DISCARD_DEPTHSTENCIL),
  856. &renderWindowResources->depthBuffer, NULL
  857. );
  858. if (FAILED(hr))
  859. {
  860. OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
  861. "Unable to create a depth buffer for the swap chain",
  862. "D3D9RenderWindow::acquireRenderWindowResources");
  863. }
  864. if (isSwapChainWindow(renderWindow) == false)
  865. {
  866. mpDevice->SetDepthStencilSurface(renderWindowResources->depthBuffer);
  867. }
  868. }
  869. }
  870. renderWindowResources->acquired = true;
  871. }
  872. //---------------------------------------------------------------------
  873. void D3D9Device::setupDeviceStates()
  874. {
  875. HRESULT hr = mpDevice->SetRenderState(D3DRS_SPECULARENABLE, TRUE);
  876. if (FAILED(hr))
  877. {
  878. OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
  879. "Unable to apply render state: D3DRS_SPECULARENABLE <- TRUE",
  880. "D3D9Device::setupDeviceStates");
  881. }
  882. }
  883. //---------------------------------------------------------------------
  884. bool D3D9Device::isSwapChainWindow(D3D9RenderWindow* renderWindow)
  885. {
  886. RenderWindowToResorucesIterator it = getRenderWindowIterator(renderWindow);
  887. if (it->second->presentParametersIndex == 0 || renderWindow->isFullScreen())
  888. return false;
  889. return true;
  890. }
  891. //---------------------------------------------------------------------
  892. D3D9RenderWindow* D3D9Device::getPrimaryWindow()
  893. {
  894. RenderWindowToResorucesIterator it = mMapRenderWindowToResoruces.begin();
  895. while (it != mMapRenderWindowToResoruces.end() && it->second->presentParametersIndex != 0)
  896. ++it;
  897. assert(it != mMapRenderWindowToResoruces.end());
  898. return it->first;
  899. }
  900. //---------------------------------------------------------------------
  901. void D3D9Device::setSharedWindowHandle(HWND hSharedHWND)
  902. {
  903. if (hSharedHWND != msSharedFocusWindow)
  904. msSharedFocusWindow = hSharedHWND;
  905. }
  906. //---------------------------------------------------------------------
  907. void D3D9Device::updateRenderWindowsIndices()
  908. {
  909. // Update present parameters index attribute per render window.
  910. if (isMultihead())
  911. {
  912. RenderWindowToResorucesIterator it = mMapRenderWindowToResoruces.begin();
  913. // Multi head device case -
  914. // Present parameter index is based on adapter ordinal in group index.
  915. while (it != mMapRenderWindowToResoruces.end())
  916. {
  917. it->second->presentParametersIndex = it->second->adapterOrdinalInGroupIndex;
  918. ++it;
  919. }
  920. }
  921. else
  922. {
  923. // Single head device case -
  924. // Just assign index in incremental order -
  925. // NOTE: It suppose to cover both cases that possible here:
  926. // 1. Single full screen window - only one allowed per device (this is not multi-head case).
  927. // 2. Multiple window mode windows.
  928. UINT32 nextPresParamIndex = 0;
  929. RenderWindowToResorucesIterator it;
  930. D3D9RenderWindow* deviceFocusWindow = NULL;
  931. // In case a d3d9 device exists - try to keep the present parameters order
  932. // so that the window that the device is focused on will stay the same and we
  933. // will avoid device re-creation.
  934. if (mpDevice != NULL)
  935. {
  936. it = mMapRenderWindowToResoruces.begin();
  937. while (it != mMapRenderWindowToResoruces.end())
  938. {
  939. if (it->first->getWindowHandle() == mCreationParams.hFocusWindow)
  940. {
  941. deviceFocusWindow = it->first;
  942. it->second->presentParametersIndex = nextPresParamIndex;
  943. ++nextPresParamIndex;
  944. break;
  945. }
  946. ++it;
  947. }
  948. }
  949. it = mMapRenderWindowToResoruces.begin();
  950. while (it != mMapRenderWindowToResoruces.end())
  951. {
  952. if (it->first != deviceFocusWindow)
  953. {
  954. it->second->presentParametersIndex = nextPresParamIndex;
  955. ++nextPresParamIndex;
  956. }
  957. ++it;
  958. }
  959. }
  960. }
  961. //---------------------------------------------------------------------
  962. void D3D9Device::copyContentsToMemory(D3D9RenderWindow* renderWindow,
  963. const PixelData &dst, RenderTarget::FrameBuffer buffer)
  964. {
  965. RenderWindowToResorucesIterator it = getRenderWindowIterator(renderWindow);
  966. RenderWindowResources* resources = it->second;
  967. bool swapChain = isSwapChainWindow(renderWindow);
  968. if ((dst.left < 0) || (dst.right > renderWindow->getWidth()) ||
  969. (dst.top < 0) || (dst.bottom > renderWindow->getHeight()) ||
  970. (dst.front != 0) || (dst.back != 1))
  971. {
  972. OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
  973. "Invalid box.",
  974. "D3D9Device::copyContentsToMemory" );
  975. }
  976. HRESULT hr;
  977. IDirect3DSurface9* pSurf = NULL;
  978. IDirect3DSurface9* pTempSurf = NULL;
  979. D3DSURFACE_DESC desc;
  980. D3DLOCKED_RECT lockedRect;
  981. if (buffer == RenderTarget::FB_AUTO)
  982. {
  983. //buffer = mIsFullScreen? FB_FRONT : FB_BACK;
  984. buffer = RenderTarget::FB_FRONT;
  985. }
  986. if (buffer == RenderTarget::FB_FRONT)
  987. {
  988. D3DDISPLAYMODE dm;
  989. if (FAILED(hr = mpDevice->GetDisplayMode(0, &dm)))
  990. {
  991. OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
  992. "Can't get display mode: TODO PORT NO ERROR", // TODO PORT - Translate HR to error
  993. "D3D9Device::copyContentsToMemory");
  994. }
  995. desc.Width = dm.Width;
  996. desc.Height = dm.Height;
  997. desc.Format = D3DFMT_A8R8G8B8;
  998. if (FAILED(hr = mpDevice->CreateOffscreenPlainSurface(desc.Width, desc.Height,
  999. desc.Format,
  1000. D3DPOOL_SYSTEMMEM,
  1001. &pTempSurf,
  1002. 0)))
  1003. {
  1004. OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
  1005. "Can't create offscreen buffer: TODO PORT NO ERROR", // TODO PORT - Translate HR to error
  1006. "D3D9Device::copyContentsToMemory");
  1007. }
  1008. if (FAILED(hr = swapChain ? resources->swapChain->GetFrontBufferData(pTempSurf) :
  1009. mpDevice->GetFrontBufferData(0, pTempSurf)))
  1010. {
  1011. SAFE_RELEASE(pTempSurf);
  1012. OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
  1013. "Can't get front buffer: TODO PORT NO ERROR", // TODO PORT - Translate HR to error
  1014. "D3D9Device::copyContentsToMemory");
  1015. }
  1016. if(renderWindow->isFullScreen())
  1017. {
  1018. if ((dst.left == 0) && (dst.right == renderWindow->getWidth()) && (dst.top == 0) && (dst.bottom == renderWindow->getHeight()))
  1019. {
  1020. hr = pTempSurf->LockRect(&lockedRect, 0, D3DLOCK_READONLY | D3DLOCK_NOSYSLOCK);
  1021. }
  1022. else
  1023. {
  1024. RECT rect;
  1025. rect.left = static_cast<LONG>(dst.left);
  1026. rect.right = static_cast<LONG>(dst.right);
  1027. rect.top = static_cast<LONG>(dst.top);
  1028. rect.bottom = static_cast<LONG>(dst.bottom);
  1029. hr = pTempSurf->LockRect(&lockedRect, &rect, D3DLOCK_READONLY | D3DLOCK_NOSYSLOCK);
  1030. }
  1031. if (FAILED(hr))
  1032. {
  1033. SAFE_RELEASE(pTempSurf);
  1034. OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
  1035. "Can't lock rect: TODO PORT NO ERROR", // TODO PORT - Translate HR to error
  1036. "D3D9Device::copyContentsToMemory");
  1037. }
  1038. }
  1039. else
  1040. {
  1041. RECT srcRect;
  1042. //GetClientRect(mHWnd, &srcRect);
  1043. srcRect.left = static_cast<LONG>(dst.left);
  1044. srcRect.top = static_cast<LONG>(dst.top);
  1045. srcRect.right = static_cast<LONG>(dst.right);
  1046. srcRect.bottom = static_cast<LONG>(dst.bottom);
  1047. POINT point;
  1048. point.x = srcRect.left;
  1049. point.y = srcRect.top;
  1050. ClientToScreen(renderWindow->getWindowHandle(), &point);
  1051. srcRect.top = point.y;
  1052. srcRect.left = point.x;
  1053. srcRect.bottom += point.y;
  1054. srcRect.right += point.x;
  1055. desc.Width = srcRect.right - srcRect.left;
  1056. desc.Height = srcRect.bottom - srcRect.top;
  1057. if (FAILED(hr = pTempSurf->LockRect(&lockedRect, &srcRect, D3DLOCK_READONLY | D3DLOCK_NOSYSLOCK)))
  1058. {
  1059. SAFE_RELEASE(pTempSurf);
  1060. OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
  1061. "Can't lock rect: TODO PORT NO ERROR", // TODO PORT - Translate HR to error
  1062. "D3D9Device::copyContentsToMemory");
  1063. }
  1064. }
  1065. }
  1066. else
  1067. {
  1068. SAFE_RELEASE(pSurf);
  1069. if(FAILED(hr = swapChain? resources->swapChain->GetBackBuffer(0, D3DBACKBUFFER_TYPE_MONO, &pSurf) :
  1070. mpDevice->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &pSurf)))
  1071. {
  1072. OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
  1073. "Can't get back buffer: TODO PORT NO ERROR", // TODO PORT - Translate HR to error
  1074. "D3D9Device::copyContentsToMemory");
  1075. }
  1076. if(FAILED(hr = pSurf->GetDesc(&desc)))
  1077. {
  1078. OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
  1079. "Can't get description: TODO PORT NO ERROR", // TODO PORT - Translate HR to error
  1080. "D3D9Device::copyContentsToMemory");
  1081. }
  1082. if (FAILED(hr = mpDevice->CreateOffscreenPlainSurface(desc.Width, desc.Height,
  1083. desc.Format,
  1084. D3DPOOL_SYSTEMMEM,
  1085. &pTempSurf,
  1086. 0)))
  1087. {
  1088. OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
  1089. "Can't create offscreen surface: TODO PORT NO ERROR", // TODO PORT - Translate HR to error
  1090. "D3D9Device::copyContentsToMemory");
  1091. }
  1092. if (desc.MultiSampleType == D3DMULTISAMPLE_NONE)
  1093. {
  1094. if (FAILED(hr = mpDevice->GetRenderTargetData(pSurf, pTempSurf)))
  1095. {
  1096. SAFE_RELEASE(pTempSurf);
  1097. OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
  1098. "Can't get render target data: TODO PORT NO ERROR", // TODO PORT - Translate HR to error
  1099. "D3D9Device::copyContentsToMemory");
  1100. }
  1101. }
  1102. else
  1103. {
  1104. IDirect3DSurface9* pStretchSurf = 0;
  1105. if (FAILED(hr = mpDevice->CreateRenderTarget(desc.Width, desc.Height,
  1106. desc.Format,
  1107. D3DMULTISAMPLE_NONE,
  1108. 0,
  1109. false,
  1110. &pStretchSurf,
  1111. 0)))
  1112. {
  1113. SAFE_RELEASE(pTempSurf);
  1114. OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
  1115. "Can't create render target: TODO PORT NO ERROR", // TODO PORT - Translate HR to error
  1116. "D3D9Device::copyContentsToMemory");
  1117. }
  1118. if (FAILED(hr = mpDevice->StretchRect(pSurf, 0, pStretchSurf, 0, D3DTEXF_NONE)))
  1119. {
  1120. SAFE_RELEASE(pTempSurf);
  1121. SAFE_RELEASE(pStretchSurf);
  1122. OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
  1123. "Can't stretch rect: TODO PORT NO ERROR", // TODO PORT - Translate HR to error
  1124. "D3D9Device::copyContentsToMemory");
  1125. }
  1126. if (FAILED(hr = mpDevice->GetRenderTargetData(pStretchSurf, pTempSurf)))
  1127. {
  1128. SAFE_RELEASE(pTempSurf);
  1129. SAFE_RELEASE(pStretchSurf);
  1130. OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
  1131. "Can't get render target data: TODO PORT NO ERROR", // TODO PORT - Translate HR to error
  1132. "D3D9Device::copyContentsToMemory");
  1133. }
  1134. SAFE_RELEASE(pStretchSurf);
  1135. }
  1136. if ((dst.left == 0) && (dst.right == renderWindow->getWidth()) && (dst.top == 0) && (dst.bottom == renderWindow->getHeight()))
  1137. {
  1138. hr = pTempSurf->LockRect(&lockedRect, 0, D3DLOCK_READONLY | D3DLOCK_NOSYSLOCK);
  1139. }
  1140. else
  1141. {
  1142. RECT rect;
  1143. rect.left = static_cast<LONG>(dst.left);
  1144. rect.right = static_cast<LONG>(dst.right);
  1145. rect.top = static_cast<LONG>(dst.top);
  1146. rect.bottom = static_cast<LONG>(dst.bottom);
  1147. hr = pTempSurf->LockRect(&lockedRect, &rect, D3DLOCK_READONLY | D3DLOCK_NOSYSLOCK);
  1148. }
  1149. if (FAILED(hr))
  1150. {
  1151. SAFE_RELEASE(pTempSurf);
  1152. OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
  1153. "Can't lock rect: TODO PORT NO ERROR", // TODO PORT - Translate HR to error
  1154. "D3D9Device::copyContentsToMemory");
  1155. }
  1156. }
  1157. PixelFormat format = CamelotEngine::D3D9Mappings::_getPF(desc.Format);
  1158. if (format == PF_UNKNOWN)
  1159. {
  1160. SAFE_RELEASE(pTempSurf);
  1161. OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
  1162. "Unsupported format", "D3D9Device::copyContentsToMemory");
  1163. }
  1164. PixelData src(dst.getWidth(), dst.getHeight(), 1, format, lockedRect.pBits);
  1165. src.rowPitch = lockedRect.Pitch / PixelUtil::getNumElemBytes(format);
  1166. src.slicePitch = desc.Height * src.rowPitch;
  1167. PixelUtil::bulkPixelConversion(src, dst);
  1168. SAFE_RELEASE(pTempSurf);
  1169. SAFE_RELEASE(pSurf);
  1170. }
  1171. }