CmD3D11RenderWindow.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807
  1. #include "CmD3D11RenderWindow.h"
  2. #include "CmCoreThread.h"
  3. #include "CmWindowEventUtilities.h"
  4. #include "CmD3D11RenderSystem.h"
  5. #include "CmD3D11Device.h"
  6. #include "CmD3D11RenderTexture.h"
  7. #include "CmD3D11TextureView.h"
  8. #include "CmTextureManager.h"
  9. #include "CmD3D11DriverList.h"
  10. #include "CmD3D11Driver.h"
  11. #include "CmException.h"
  12. namespace CamelotFramework
  13. {
  14. D3D11RenderWindow::D3D11RenderWindow(const RENDER_WINDOW_DESC& desc,D3D11Device& device, IDXGIFactory* DXGIFactory)
  15. : RenderWindow(desc)
  16. , mDevice(device)
  17. , mDXGIFactory(DXGIFactory)
  18. , mIsExternal(false)
  19. , mSizing(false)
  20. , mClosed(false)
  21. , mHidden(false)
  22. , mSwitchingFullscreen(false)
  23. , mDisplayFrequency(0)
  24. , mRenderTargetView(nullptr)
  25. , mBackBuffer(nullptr)
  26. , mSwapChain(nullptr)
  27. , mHWnd(0)
  28. , mDepthStencilView(nullptr)
  29. {
  30. ZeroMemory(&mSwapChainDesc, sizeof(DXGI_SWAP_CHAIN_DESC));
  31. }
  32. D3D11RenderWindow::~D3D11RenderWindow()
  33. {
  34. }
  35. void D3D11RenderWindow::initialize_internal()
  36. {
  37. mFSAAType.Count = 1;
  38. mFSAAType.Quality = 0;
  39. mFSAA = 0;
  40. mFSAAHint = "";
  41. mVSync = false;
  42. mVSyncInterval = 1;
  43. HWND parentHWnd = 0;
  44. HWND externalHandle = 0;
  45. HMONITOR hMonitor = NULL;
  46. // Get variable-length params
  47. NameValuePairList::const_iterator opt;
  48. // parentWindowHandle -> parentHWnd
  49. opt = mDesc.platformSpecific.find("parentWindowHandle");
  50. if(opt != mDesc.platformSpecific.end())
  51. parentHWnd = (HWND)parseUnsignedInt(opt->second);
  52. // externalWindowHandle -> externalHandle
  53. opt = mDesc.platformSpecific.find("externalWindowHandle");
  54. if(opt != mDesc.platformSpecific.end())
  55. externalHandle = (HWND)parseUnsignedInt(opt->second);
  56. // monitor handle
  57. opt = mDesc.platformSpecific.find("monitorHandle");
  58. if (opt != mDesc.platformSpecific.end())
  59. hMonitor = (HMONITOR)parseInt(opt->second);
  60. mName = mDesc.title;
  61. mIsFullScreen = mDesc.fullscreen;
  62. mColorDepth = mDesc.colorDepth;
  63. mWidth = mHeight = mLeft = mTop = 0;
  64. mActive = true;
  65. mClosed = false;
  66. if (!externalHandle)
  67. {
  68. DWORD dwStyle = (mHidden ? 0 : WS_VISIBLE) | WS_CLIPCHILDREN;
  69. DWORD dwStyleEx = 0;
  70. RECT rc;
  71. MONITORINFO monitorInfo;
  72. // If we specified which adapter we want to use - find it's monitor.
  73. if (mDesc.monitorIndex != -1)
  74. {
  75. RenderSystem* rs = RenderSystem::instancePtr();
  76. D3D11RenderSystem* d3d11rs = static_cast<D3D11RenderSystem*>(rs);
  77. D3D11DriverList* driverList = d3d11rs->getDriverList();
  78. UINT32 curOutput = 0;
  79. for(UINT32 i = 0; i < driverList->count(); i++)
  80. {
  81. D3D11Driver* driver = driverList->item(i);
  82. UINT32 numOutputs = driver->getNumAdapterOutputs();
  83. for(UINT32 j = 0; j < numOutputs; j++)
  84. {
  85. if(curOutput == mDesc.monitorIndex)
  86. {
  87. hMonitor = driver->getOutputDesc(j).Monitor;
  88. break;
  89. }
  90. curOutput++;
  91. }
  92. if(curOutput == mDesc.monitorIndex)
  93. break;
  94. }
  95. }
  96. // If we didn't specified the adapter index, or if it didn't find it
  97. if (hMonitor == NULL)
  98. {
  99. POINT windowAnchorPoint;
  100. // Fill in anchor point.
  101. windowAnchorPoint.x = mDesc.left;
  102. windowAnchorPoint.y = mDesc.top;
  103. // Get the nearest monitor to this window.
  104. hMonitor = MonitorFromPoint(windowAnchorPoint, MONITOR_DEFAULTTOPRIMARY);
  105. }
  106. // Get the target monitor info
  107. memset(&monitorInfo, 0, sizeof(MONITORINFO));
  108. monitorInfo.cbSize = sizeof(MONITORINFO);
  109. GetMonitorInfo(hMonitor, &monitorInfo);
  110. unsigned int winWidth, winHeight;
  111. winWidth = mDesc.width;
  112. winHeight = mDesc.height;
  113. UINT32 left = mDesc.left;
  114. UINT32 top = mDesc.top;
  115. // No specified top left -> Center the window in the middle of the monitor
  116. if (left == -1 || top == -1)
  117. {
  118. int screenw = monitorInfo.rcWork.right - monitorInfo.rcWork.left;
  119. int screenh = monitorInfo.rcWork.bottom - monitorInfo.rcWork.top;
  120. // clamp window dimensions to screen size
  121. int outerw = (int(winWidth) < screenw)? int(winWidth) : screenw;
  122. int outerh = (int(winHeight) < screenh)? int(winHeight) : screenh;
  123. if (left == -1)
  124. left = monitorInfo.rcWork.left + (screenw - outerw) / 2;
  125. else if (mDesc.monitorIndex != -1)
  126. left += monitorInfo.rcWork.left;
  127. if (top == -1)
  128. top = monitorInfo.rcWork.top + (screenh - outerh) / 2;
  129. else if (mDesc.monitorIndex != -1)
  130. top += monitorInfo.rcWork.top;
  131. }
  132. else if (mDesc.monitorIndex != -1)
  133. {
  134. left += monitorInfo.rcWork.left;
  135. top += monitorInfo.rcWork.top;
  136. }
  137. mWidth = mDesc.width;
  138. mHeight = mDesc.height;
  139. mTop = top;
  140. mLeft = left;
  141. if (!mDesc.fullscreen)
  142. {
  143. if (parentHWnd)
  144. {
  145. if(mDesc.toolWindow)
  146. dwStyleEx = WS_EX_TOOLWINDOW;
  147. else
  148. dwStyle |= WS_CHILD;
  149. }
  150. if (!parentHWnd || mDesc.toolWindow)
  151. {
  152. if (mDesc.border == WindowBorder::None)
  153. dwStyle |= WS_POPUP;
  154. else if (mDesc.border == WindowBorder::Fixed)
  155. dwStyle |= WS_OVERLAPPED | WS_BORDER | WS_CAPTION |
  156. WS_SYSMENU | WS_MINIMIZEBOX;
  157. else
  158. dwStyle |= WS_OVERLAPPEDWINDOW;
  159. }
  160. if (!mDesc.outerDimensions)
  161. {
  162. // Calculate window dimensions required
  163. // to get the requested client area
  164. SetRect(&rc, 0, 0, mWidth, mHeight);
  165. AdjustWindowRect(&rc, dwStyle, false);
  166. mWidth = rc.right - rc.left;
  167. mHeight = rc.bottom - rc.top;
  168. // Clamp width and height to the desktop dimensions
  169. int screenw = GetSystemMetrics(SM_CXSCREEN);
  170. int screenh = GetSystemMetrics(SM_CYSCREEN);
  171. if ((int)mWidth > screenw)
  172. mWidth = screenw;
  173. if ((int)mHeight > screenh)
  174. mHeight = screenh;
  175. if (mLeft < 0)
  176. mLeft = (screenw - mWidth) / 2;
  177. if (mTop < 0)
  178. mTop = (screenh - mHeight) / 2;
  179. }
  180. }
  181. else
  182. {
  183. dwStyle |= WS_POPUP;
  184. mTop = mLeft = 0;
  185. }
  186. UINT classStyle = 0;
  187. if (mDesc.enableDoubleClick)
  188. classStyle |= CS_DBLCLKS;
  189. HINSTANCE hInst = NULL;
  190. // Register the window class
  191. // Allow 4 bytes of window data for D3D11RenderWindow pointer
  192. WNDCLASS wc = { classStyle, WindowEventUtilities::_WndProc, 0, 0, hInst,
  193. LoadIcon(0, IDI_APPLICATION), LoadCursor(NULL, IDC_ARROW),
  194. (HBRUSH)GetStockObject(BLACK_BRUSH), 0, "D3D11Wnd" };
  195. RegisterClass(&wc);
  196. // Create our main window
  197. // Pass pointer to self
  198. mIsExternal = false;
  199. mHWnd = CreateWindowEx(dwStyleEx, "D3D11Wnd", mDesc.title.c_str(), dwStyle,
  200. mLeft, mTop, mWidth, mHeight, parentHWnd, 0, hInst, this);
  201. WindowEventUtilities::_addRenderWindow(this);
  202. }
  203. else
  204. {
  205. mHWnd = externalHandle;
  206. mIsExternal = true;
  207. }
  208. RECT rc;
  209. // top and left represent outer window coordinates
  210. GetWindowRect(mHWnd, &rc);
  211. mTop = rc.top;
  212. mLeft = rc.left;
  213. // width and height represent interior drawable area
  214. GetClientRect(mHWnd, &rc);
  215. mWidth = rc.right;
  216. mHeight = rc.bottom;
  217. createSwapChain();
  218. createSizeDependedD3DResources();
  219. mDXGIFactory->MakeWindowAssociation(mHWnd, NULL);
  220. setHidden(mHidden);
  221. RenderWindow::initialize_internal();
  222. }
  223. void D3D11RenderWindow::destroy_internal()
  224. {
  225. mActive = false;
  226. mClosed = true;
  227. SAFE_RELEASE(mSwapChain);
  228. if (mHWnd && !mIsExternal)
  229. {
  230. WindowEventUtilities::_removeRenderWindow(this);
  231. DestroyWindow(mHWnd);
  232. }
  233. if(mDepthStencilView != nullptr)
  234. {
  235. Texture::releaseView(mDepthStencilView);
  236. mDepthStencilView = nullptr;
  237. }
  238. mHWnd = nullptr;
  239. destroySizeDependedD3DResources();
  240. RenderWindow::destroy_internal();
  241. }
  242. void D3D11RenderWindow::swapBuffers()
  243. {
  244. THROW_IF_NOT_CORE_THREAD;
  245. if(mDevice.getD3D11Device() != nullptr)
  246. {
  247. HRESULT hr = mSwapChain->Present(mVSync ? mVSyncInterval : 0, 0);
  248. if( FAILED(hr) )
  249. CM_EXCEPT(RenderingAPIException, "Error Presenting surfaces");
  250. }
  251. }
  252. void D3D11RenderWindow::reposition(INT32 top, INT32 left)
  253. {
  254. THROW_IF_NOT_CORE_THREAD;
  255. if (mHWnd && !mIsFullScreen)
  256. {
  257. mTop = top;
  258. mLeft = left;
  259. SetWindowPos(mHWnd, 0, top, left, 0, 0,
  260. SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
  261. }
  262. }
  263. void D3D11RenderWindow::resize(UINT32 width, UINT32 height)
  264. {
  265. THROW_IF_NOT_CORE_THREAD;
  266. if (mHWnd && !mIsFullScreen)
  267. {
  268. mWidth = width;
  269. mHeight = height;
  270. RECT rc = { 0, 0, width, height };
  271. AdjustWindowRect(&rc, GetWindowLong(mHWnd, GWL_STYLE), false);
  272. width = rc.right - rc.left;
  273. height = rc.bottom - rc.top;
  274. SetWindowPos(mHWnd, 0, 0, 0, width, height,
  275. SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE);
  276. }
  277. }
  278. void D3D11RenderWindow::setActive(bool state)
  279. {
  280. THROW_IF_NOT_CORE_THREAD;
  281. if (mHWnd && mSwapChain)
  282. {
  283. if (state)
  284. {
  285. ShowWindow(mHWnd, SW_RESTORE);
  286. mSwapChain->SetFullscreenState(mIsFullScreen, nullptr);
  287. }
  288. else
  289. {
  290. ShowWindow(mHWnd, SW_SHOWMINIMIZED);
  291. mSwapChain->SetFullscreenState(FALSE, nullptr);
  292. }
  293. }
  294. RenderWindow::setActive(state);
  295. }
  296. void D3D11RenderWindow::setHidden(bool hidden)
  297. {
  298. THROW_IF_NOT_CORE_THREAD;
  299. mHidden = hidden;
  300. if (!mIsExternal)
  301. {
  302. if (hidden)
  303. ShowWindow(mHWnd, SW_HIDE);
  304. else
  305. ShowWindow(mHWnd, SW_SHOWNORMAL);
  306. }
  307. }
  308. void D3D11RenderWindow::setFullscreen(bool fullScreen, unsigned int width, unsigned int height)
  309. {
  310. THROW_IF_NOT_CORE_THREAD;
  311. if (fullScreen != mIsFullScreen || width != mWidth || height != mHeight)
  312. {
  313. if (fullScreen != mIsFullScreen)
  314. mSwitchingFullscreen = true;
  315. DWORD dwStyle = WS_VISIBLE | WS_CLIPCHILDREN;
  316. bool oldFullscreen = mIsFullScreen;
  317. mIsFullScreen = fullScreen;
  318. if (fullScreen)
  319. {
  320. dwStyle |= WS_POPUP;
  321. mTop = mLeft = 0;
  322. mWidth = width;
  323. mHeight = height;
  324. // need different ordering here
  325. if (oldFullscreen)
  326. {
  327. // was previously fullscreen, just changing the resolution
  328. SetWindowPos(mHWnd, HWND_TOPMOST, 0, 0, width, height, SWP_NOACTIVATE);
  329. }
  330. else
  331. {
  332. SetWindowPos(mHWnd, HWND_TOPMOST, 0, 0, width, height, SWP_NOACTIVATE);
  333. //MoveWindow(mHWnd, mLeft, mTop, mWidth, mHeight, FALSE);
  334. SetWindowLong(mHWnd, GWL_STYLE, dwStyle);
  335. SetWindowPos(mHWnd, 0, 0,0, 0,0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER);
  336. }
  337. }
  338. else
  339. {
  340. dwStyle |= WS_OVERLAPPEDWINDOW;
  341. // Calculate window dimensions required
  342. // to get the requested client area
  343. RECT rc;
  344. SetRect(&rc, 0, 0, width, height);
  345. AdjustWindowRect(&rc, dwStyle, false);
  346. unsigned int winWidth = rc.right - rc.left;
  347. unsigned int winHeight = rc.bottom - rc.top;
  348. SetWindowLong(mHWnd, GWL_STYLE, dwStyle);
  349. SetWindowPos(mHWnd, HWND_NOTOPMOST, 0, 0, winWidth, winHeight,
  350. SWP_DRAWFRAME | SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOACTIVATE);
  351. // Note that we also set the position in the restoreLostDevice method
  352. // via _finishSwitchingFullScreen
  353. }
  354. mSwapChainDesc.Windowed = !fullScreen;
  355. mSwapChainDesc.BufferDesc.RefreshRate.Numerator = 0;
  356. mSwapChainDesc.BufferDesc.RefreshRate.Denominator=0;
  357. mSwapChainDesc.BufferDesc.Height = height;
  358. mSwapChainDesc.BufferDesc.Width = width;
  359. }
  360. }
  361. void D3D11RenderWindow::getCustomAttribute( const String& name, void* pData ) const
  362. {
  363. if(name == "WINDOW")
  364. {
  365. HWND *pWnd = (HWND*)pData;
  366. *pWnd = mHWnd;
  367. return;
  368. }
  369. if(name == "RTV")
  370. {
  371. *static_cast<ID3D11RenderTargetView**>(pData) = mRenderTargetView;
  372. return;
  373. }
  374. else if(name == "DSV")
  375. {
  376. D3D11TextureView* d3d11TextureView = static_cast<D3D11TextureView*>(mDepthStencilView.get());
  377. *static_cast<ID3D11DepthStencilView**>(pData) = d3d11TextureView->getDSV();
  378. return;
  379. }
  380. RenderWindow::getCustomAttribute(name, pData);
  381. }
  382. void D3D11RenderWindow::copyContentsToMemory(const PixelData &dst, FrameBuffer buffer)
  383. {
  384. THROW_IF_NOT_CORE_THREAD;
  385. if(mBackBuffer == nullptr)
  386. return;
  387. // get the backbuffer desc
  388. D3D11_TEXTURE2D_DESC BBDesc;
  389. mBackBuffer->GetDesc(&BBDesc);
  390. ID3D11Texture2D *backbuffer = nullptr;
  391. if(BBDesc.SampleDesc.Quality > 0)
  392. {
  393. D3D11_TEXTURE2D_DESC desc = BBDesc;
  394. desc.Usage = D3D11_USAGE_DEFAULT;
  395. desc.CPUAccessFlags = 0;
  396. desc.BindFlags = 0;
  397. desc.SampleDesc.Quality = 0;
  398. desc.SampleDesc.Count = 1;
  399. HRESULT hr = mDevice.getD3D11Device()->CreateTexture2D(
  400. &desc,
  401. NULL,
  402. &backbuffer);
  403. if (FAILED(hr) || mDevice.hasError())
  404. {
  405. String errorDescription = mDevice.getErrorDescription();
  406. CM_EXCEPT(RenderingAPIException,
  407. "Error creating texture\nError Description:" + errorDescription);
  408. }
  409. mDevice.getImmediateContext()->ResolveSubresource(backbuffer, D3D11CalcSubresource(0, 0, 1), mBackBuffer, D3D11CalcSubresource(0, 0, 1), desc.Format);
  410. }
  411. // change the parameters of the texture so we can read it
  412. BBDesc.Usage = D3D11_USAGE_STAGING;
  413. BBDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
  414. BBDesc.BindFlags = 0;
  415. BBDesc.SampleDesc.Quality = 0;
  416. BBDesc.SampleDesc.Count = 1;
  417. // create a temp buffer to copy to
  418. ID3D11Texture2D * pTempTexture2D;
  419. HRESULT hr = mDevice.getD3D11Device()->CreateTexture2D(
  420. &BBDesc,
  421. NULL,
  422. &pTempTexture2D);
  423. if (FAILED(hr) || mDevice.hasError())
  424. {
  425. String errorDescription = mDevice.getErrorDescription();
  426. CM_EXCEPT(RenderingAPIException,
  427. "Error creating texture\nError Description:" + errorDescription);
  428. }
  429. // copy the back buffer
  430. mDevice.getImmediateContext()->CopyResource(pTempTexture2D, backbuffer != NULL ? backbuffer : mBackBuffer);
  431. // map the copied texture
  432. D3D11_MAPPED_SUBRESOURCE mappedTex2D;
  433. mDevice.getImmediateContext()->Map(pTempTexture2D, 0,D3D11_MAP_READ, 0, &mappedTex2D);
  434. // copy the the texture to the dest
  435. PixelData src(mWidth, mHeight, 1, PF_A8B8G8R8);
  436. src.setExternalBuffer((UINT8*)mappedTex2D.pData);
  437. PixelUtil::bulkPixelConversion(src, dst);
  438. // unmap the temp buffer
  439. mDevice.getImmediateContext()->Unmap(pTempTexture2D, 0);
  440. // Release the temp buffer
  441. SAFE_RELEASE(pTempTexture2D);
  442. SAFE_RELEASE(backbuffer);
  443. }
  444. Int2 D3D11RenderWindow::screenToWindowPos(const Int2& screenPos) const
  445. {
  446. POINT pos;
  447. pos.x = screenPos.x;
  448. pos.y = screenPos.y;
  449. ScreenToClient(mHWnd, &pos);
  450. return Int2(pos.x, pos.y);
  451. }
  452. Int2 D3D11RenderWindow::windowToScreenPos(const Int2& windowPos) const
  453. {
  454. POINT pos;
  455. pos.x = windowPos.x;
  456. pos.y = windowPos.y;
  457. ClientToScreen(mHWnd, &pos);
  458. return Int2(pos.x, pos.y);
  459. }
  460. void D3D11RenderWindow::startResize(WindowResizeDirection direction)
  461. {
  462. WPARAM dir = HTLEFT;
  463. switch(direction)
  464. {
  465. case WindowResizeDirection::Left:
  466. dir = HTLEFT;
  467. break;
  468. case WindowResizeDirection::TopLeft:
  469. dir = HTTOPLEFT;
  470. break;
  471. case WindowResizeDirection::Top:
  472. dir = HTTOP;
  473. break;
  474. case WindowResizeDirection::TopRight:
  475. dir = HTTOPRIGHT;
  476. break;
  477. case WindowResizeDirection::Right:
  478. dir = HTRIGHT;
  479. break;
  480. case WindowResizeDirection::BottomRight:
  481. dir = HTBOTTOMRIGHT;
  482. break;
  483. case WindowResizeDirection::Bottom:
  484. dir = HTBOTTOM;
  485. break;
  486. case WindowResizeDirection::BottomLeft:
  487. dir = HTBOTTOMLEFT;
  488. break;
  489. }
  490. SendMessage(mHWnd, WM_NCLBUTTONDOWN, dir, 0);
  491. }
  492. void D3D11RenderWindow::endResize()
  493. {
  494. }
  495. void D3D11RenderWindow::startMove()
  496. {
  497. SendMessage(mHWnd, WM_NCLBUTTONDOWN, HTCAPTION, 0);
  498. }
  499. void D3D11RenderWindow::endMove()
  500. {
  501. }
  502. void D3D11RenderWindow::_windowMovedOrResized()
  503. {
  504. THROW_IF_NOT_CORE_THREAD;
  505. if (!mHWnd || IsIconic(mHWnd))
  506. return;
  507. RECT rc;
  508. // top and left represent outer window position
  509. GetWindowRect(mHWnd, &rc);
  510. mTop = rc.top;
  511. mLeft = rc.left;
  512. // width and height represent drawable area only
  513. GetClientRect(mHWnd, &rc);
  514. unsigned int width = rc.right - rc.left;
  515. unsigned int height = rc.bottom - rc.top;
  516. if (width == 0)
  517. width = 1;
  518. if (height == 0)
  519. height = 1;
  520. resizeSwapChainBuffers(width, height);
  521. RenderWindow::_windowMovedOrResized();
  522. }
  523. void D3D11RenderWindow::createSwapChain()
  524. {
  525. ZeroMemory(&mSwapChainDesc, sizeof(DXGI_SWAP_CHAIN_DESC));
  526. // get the dxgi device
  527. IDXGIDevice* pDXGIDevice = queryDxgiDevice();
  528. ZeroMemory(&mSwapChainDesc, sizeof(DXGI_SWAP_CHAIN_DESC));
  529. DXGI_FORMAT format = DXGI_FORMAT_R8G8B8A8_UNORM;
  530. mSwapChainDesc.OutputWindow = mHWnd;
  531. mSwapChainDesc.BufferDesc.Width = mWidth;
  532. mSwapChainDesc.BufferDesc.Height = mHeight;
  533. mSwapChainDesc.BufferDesc.Format = format;
  534. mSwapChainDesc.BufferDesc.RefreshRate.Numerator=0;
  535. mSwapChainDesc.BufferDesc.RefreshRate.Denominator = 0;
  536. mSwapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
  537. mSwapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
  538. mSwapChainDesc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH ;
  539. // triple buffer if VSync is on
  540. mSwapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
  541. mSwapChainDesc.BufferCount = mVSync ? 2 : 1;
  542. mSwapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD ;
  543. mSwapChainDesc.OutputWindow = mHWnd;
  544. mSwapChainDesc.Windowed = !mIsFullScreen;
  545. D3D11RenderSystem* rs = static_cast<D3D11RenderSystem*>(RenderSystem::instancePtr());
  546. rs->determineFSAASettings(mFSAA, mFSAAHint, format, &mFSAAType);
  547. mSwapChainDesc.SampleDesc.Count = mFSAAType.Count;
  548. mSwapChainDesc.SampleDesc.Quality = mFSAAType.Quality;
  549. HRESULT hr;
  550. // Create swap chain
  551. hr = mDXGIFactory->CreateSwapChain(pDXGIDevice, &mSwapChainDesc, &mSwapChain);
  552. if (FAILED(hr))
  553. {
  554. // Try a second time, may fail the first time due to back buffer count,
  555. // which will be corrected by the runtime
  556. hr = mDXGIFactory->CreateSwapChain(pDXGIDevice, &mSwapChainDesc, &mSwapChain);
  557. }
  558. SAFE_RELEASE(pDXGIDevice);
  559. if (FAILED(hr))
  560. CM_EXCEPT(RenderingAPIException, "Unable to create swap chain");
  561. }
  562. void D3D11RenderWindow::createSizeDependedD3DResources()
  563. {
  564. // obtain back buffer
  565. SAFE_RELEASE(mBackBuffer);
  566. HRESULT hr = mSwapChain->GetBuffer(0, __uuidof( ID3D11Texture2D ), (LPVOID*)&mBackBuffer);
  567. if( FAILED(hr) )
  568. CM_EXCEPT(RenderingAPIException, "Unable to Get Back Buffer for swap chain");
  569. // create all other size depended resources
  570. assert(mBackBuffer && !mRenderTargetView);
  571. // get the backbuffer desc
  572. D3D11_TEXTURE2D_DESC BBDesc;
  573. mBackBuffer->GetDesc(&BBDesc);
  574. mWidth = BBDesc.Width;
  575. mHeight = BBDesc.Height;
  576. // create the render target view
  577. D3D11_RENDER_TARGET_VIEW_DESC RTVDesc;
  578. ZeroMemory( &RTVDesc, sizeof(RTVDesc) );
  579. RTVDesc.Format = BBDesc.Format;
  580. RTVDesc.ViewDimension = mFSAA ? D3D11_RTV_DIMENSION_TEXTURE2DMS : D3D11_RTV_DIMENSION_TEXTURE2D;
  581. RTVDesc.Texture2D.MipSlice = 0;
  582. hr = mDevice.getD3D11Device()->CreateRenderTargetView(mBackBuffer, &RTVDesc, &mRenderTargetView);
  583. if( FAILED(hr) )
  584. {
  585. String errorDescription = mDevice.getErrorDescription();
  586. CM_EXCEPT(RenderingAPIException, "Unable to create rendertagert view\nError Description:" + errorDescription);
  587. }
  588. mDepthStencilBuffer = TextureManager::instance().createTexture(TEX_TYPE_2D,
  589. BBDesc.Width, BBDesc.Height, 0, PF_D24S8, TU_DEPTHSTENCIL, false, mFSAA, mFSAAHint);
  590. if(mDepthStencilView != nullptr)
  591. {
  592. Texture::releaseView(mDepthStencilView);
  593. mDepthStencilView = nullptr;
  594. }
  595. mDepthStencilView = Texture::requestView(mDepthStencilBuffer, 0, 1, 0, 1, GVU_DEPTHSTENCIL);
  596. }
  597. void D3D11RenderWindow::destroySizeDependedD3DResources()
  598. {
  599. SAFE_RELEASE(mBackBuffer);
  600. SAFE_RELEASE(mRenderTargetView);
  601. mDepthStencilBuffer = nullptr;
  602. }
  603. void D3D11RenderWindow::resizeSwapChainBuffers(unsigned width, unsigned height)
  604. {
  605. destroySizeDependedD3DResources();
  606. // width and height can be zero to autodetect size, therefore do not rely on them
  607. UINT Flags = mIsFullScreen ? DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH : 0;
  608. HRESULT hr = mSwapChain->ResizeBuffers(mSwapChainDesc.BufferCount, width, height, mSwapChainDesc.BufferDesc.Format, Flags);
  609. if(hr != S_OK)
  610. CM_EXCEPT(InternalErrorException, "Call to ResizeBuffers failed.");
  611. mSwapChain->GetDesc(&mSwapChainDesc);
  612. //mWidth = mSwapChainDesc.BufferDesc.Width;
  613. //mHeight = mSwapChainDesc.BufferDesc.Height;
  614. mIsFullScreen = (0 == mSwapChainDesc.Windowed); // Alt-Enter together with SetWindowAssociation() can change this state
  615. createSizeDependedD3DResources();
  616. mDevice.getImmediateContext()->OMSetRenderTargets(0, 0, 0);
  617. }
  618. IDXGIDevice* D3D11RenderWindow::queryDxgiDevice()
  619. {
  620. if (mDevice.getD3D11Device() == nullptr)
  621. {
  622. CM_EXCEPT(RenderingAPIException, "D3D11Device is NULL!");
  623. }
  624. IDXGIDevice* pDXGIDevice = nullptr;
  625. HRESULT hr = mDevice.getD3D11Device()->QueryInterface(__uuidof(IDXGIDevice), (void**)&pDXGIDevice);
  626. if(FAILED(hr))
  627. CM_EXCEPT(RenderingAPIException, "Unable to query a DXGIDevice");
  628. return pDXGIDevice;
  629. }
  630. void D3D11RenderWindow::finishSwitchingFullscreen()
  631. {
  632. if(mIsFullScreen)
  633. {
  634. // Need to reset the region on the window sometimes, when the
  635. // windowed mode was constrained by desktop
  636. HRGN hRgn = CreateRectRgn(0, 0, mSwapChainDesc.BufferDesc.Width, mSwapChainDesc.BufferDesc.Height);
  637. SetWindowRgn(mHWnd, hRgn, FALSE);
  638. }
  639. else
  640. {
  641. // When switching back to windowed mode, need to reset window size
  642. // after device has been restored
  643. RECT rc;
  644. SetRect(&rc, 0, 0, mSwapChainDesc.BufferDesc.Width, mSwapChainDesc.BufferDesc.Height);
  645. AdjustWindowRect(&rc, GetWindowLong(mHWnd, GWL_STYLE), false);
  646. unsigned int winWidth = rc.right - rc.left;
  647. unsigned int winHeight = rc.bottom - rc.top;
  648. int screenw = GetSystemMetrics(SM_CXSCREEN);
  649. int screenh = GetSystemMetrics(SM_CYSCREEN);
  650. int left = (screenw - winWidth) / 2;
  651. int top = (screenh - winHeight) / 2;
  652. SetWindowPos(mHWnd, HWND_NOTOPMOST, left, top, winWidth, winHeight,
  653. SWP_DRAWFRAME | SWP_FRAMECHANGED | SWP_NOACTIVATE);
  654. }
  655. mSwapChain->SetFullscreenState(mIsFullScreen, NULL);
  656. mSwitchingFullscreen = false;
  657. }
  658. bool D3D11RenderWindow::checkMultiSampleQuality(UINT32 SampleCount, UINT32 *outQuality, DXGI_FORMAT format)
  659. {
  660. if (SUCCEEDED(mDevice.getD3D11Device()->CheckMultisampleQualityLevels(format, SampleCount, outQuality)))
  661. return true;
  662. else
  663. return false;
  664. }
  665. }