CmD3D11RenderWindow.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754
  1. #include "CmD3D11RenderWindow.h"
  2. #include "CmCoreThread.h"
  3. #include "Win32/CmPlatformWndProc.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 "CmD3D11VideoModeInfo.h"
  12. #include "CmInput.h"
  13. #include "CmException.h"
  14. namespace BansheeEngine
  15. {
  16. D3D11RenderWindow::D3D11RenderWindow(const RENDER_WINDOW_DESC& desc,D3D11Device& device, IDXGIFactory* DXGIFactory)
  17. : RenderWindow(desc)
  18. , mDevice(device)
  19. , mDXGIFactory(DXGIFactory)
  20. , mIsExternal(false)
  21. , mSizing(false)
  22. , mClosed(false)
  23. , mRenderTargetView(nullptr)
  24. , mBackBuffer(nullptr)
  25. , mSwapChain(nullptr)
  26. , mHWnd(0)
  27. , mDepthStencilView(nullptr)
  28. , mIsChild(false)
  29. {
  30. ZeroMemory(&mSwapChainDesc, sizeof(DXGI_SWAP_CHAIN_DESC));
  31. }
  32. D3D11RenderWindow::~D3D11RenderWindow()
  33. {
  34. }
  35. void D3D11RenderWindow::initialize_internal()
  36. {
  37. mMultisampleType.Count = 1;
  38. mMultisampleType.Quality = 0;
  39. mMultisampleCount = 0;
  40. mMultisampleHint = "";
  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. mIsChild = parentHWnd != 0;
  62. mIsFullScreen = mDesc.fullscreen && !mIsChild;
  63. mColorDepth = mDesc.colorDepth;
  64. mWidth = mHeight = mLeft = mTop = 0;
  65. mActive = true;
  66. mClosed = false;
  67. if (!externalHandle)
  68. {
  69. DWORD dwStyle = (mHidden ? 0 : WS_VISIBLE) | WS_CLIPCHILDREN;
  70. DWORD dwStyleEx = 0;
  71. RECT rc;
  72. MONITORINFO monitorInfo;
  73. // If we specified which adapter we want to use - find it's monitor.
  74. if (mDesc.monitorIndex != -1)
  75. {
  76. RenderSystem* rs = RenderSystem::instancePtr();
  77. D3D11RenderSystem* d3d11rs = static_cast<D3D11RenderSystem*>(rs);
  78. D3D11DriverList* driverList = d3d11rs->getDriverList();
  79. UINT32 curOutput = 0;
  80. for(UINT32 i = 0; i < driverList->count(); i++)
  81. {
  82. D3D11Driver* driver = driverList->item(i);
  83. UINT32 numOutputs = driver->getNumAdapterOutputs();
  84. for(UINT32 j = 0; j < numOutputs; j++)
  85. {
  86. if(curOutput == mDesc.monitorIndex)
  87. {
  88. hMonitor = driver->getOutputDesc(j).Monitor;
  89. break;
  90. }
  91. curOutput++;
  92. }
  93. if(curOutput == mDesc.monitorIndex)
  94. break;
  95. }
  96. }
  97. // If we didn't specified the adapter index, or if it didn't find it
  98. if (hMonitor == NULL)
  99. {
  100. POINT windowAnchorPoint;
  101. // Fill in anchor point.
  102. windowAnchorPoint.x = mDesc.left;
  103. windowAnchorPoint.y = mDesc.top;
  104. // Get the nearest monitor to this window.
  105. hMonitor = MonitorFromPoint(windowAnchorPoint, MONITOR_DEFAULTTOPRIMARY);
  106. }
  107. // Get the target monitor info
  108. memset(&monitorInfo, 0, sizeof(MONITORINFO));
  109. monitorInfo.cbSize = sizeof(MONITORINFO);
  110. GetMonitorInfo(hMonitor, &monitorInfo);
  111. unsigned int winWidth, winHeight;
  112. winWidth = mDesc.width;
  113. winHeight = mDesc.height;
  114. UINT32 left = mDesc.left;
  115. UINT32 top = mDesc.top;
  116. // No specified top left -> Center the window in the middle of the monitor
  117. if (left == -1 || top == -1)
  118. {
  119. int screenw = monitorInfo.rcWork.right - monitorInfo.rcWork.left;
  120. int screenh = monitorInfo.rcWork.bottom - monitorInfo.rcWork.top;
  121. // clamp window dimensions to screen size
  122. int outerw = (int(winWidth) < screenw)? int(winWidth) : screenw;
  123. int outerh = (int(winHeight) < screenh)? int(winHeight) : screenh;
  124. if (left == -1)
  125. left = monitorInfo.rcWork.left + (screenw - outerw) / 2;
  126. else if (mDesc.monitorIndex != -1)
  127. left += monitorInfo.rcWork.left;
  128. if (top == -1)
  129. top = monitorInfo.rcWork.top + (screenh - outerh) / 2;
  130. else if (mDesc.monitorIndex != -1)
  131. top += monitorInfo.rcWork.top;
  132. }
  133. else if (mDesc.monitorIndex != -1)
  134. {
  135. left += monitorInfo.rcWork.left;
  136. top += monitorInfo.rcWork.top;
  137. }
  138. mWidth = mDesc.width;
  139. mHeight = mDesc.height;
  140. mTop = top;
  141. mLeft = left;
  142. if (!mDesc.fullscreen)
  143. {
  144. if (parentHWnd)
  145. {
  146. if(mDesc.toolWindow)
  147. dwStyleEx = WS_EX_TOOLWINDOW;
  148. else
  149. dwStyle |= WS_CHILD;
  150. }
  151. if (!parentHWnd || mDesc.toolWindow)
  152. {
  153. if (mDesc.border == WindowBorder::None)
  154. dwStyle |= WS_POPUP;
  155. else if (mDesc.border == WindowBorder::Fixed)
  156. dwStyle |= WS_OVERLAPPED | WS_BORDER | WS_CAPTION |
  157. WS_SYSMENU | WS_MINIMIZEBOX;
  158. else
  159. dwStyle |= WS_OVERLAPPEDWINDOW;
  160. }
  161. if (!mDesc.outerDimensions)
  162. {
  163. // Calculate window dimensions required
  164. // to get the requested client area
  165. SetRect(&rc, 0, 0, mWidth, mHeight);
  166. AdjustWindowRect(&rc, dwStyle, false);
  167. mWidth = rc.right - rc.left;
  168. mHeight = rc.bottom - rc.top;
  169. // Clamp width and height to the desktop dimensions
  170. int screenw = GetSystemMetrics(SM_CXSCREEN);
  171. int screenh = GetSystemMetrics(SM_CYSCREEN);
  172. if ((int)mWidth > screenw)
  173. mWidth = screenw;
  174. if ((int)mHeight > screenh)
  175. mHeight = screenh;
  176. if (mLeft < 0)
  177. mLeft = (screenw - mWidth) / 2;
  178. if (mTop < 0)
  179. mTop = (screenh - mHeight) / 2;
  180. }
  181. }
  182. else
  183. {
  184. dwStyle |= WS_POPUP;
  185. mTop = mLeft = 0;
  186. }
  187. UINT classStyle = 0;
  188. if (mDesc.enableDoubleClick)
  189. classStyle |= CS_DBLCLKS;
  190. HINSTANCE hInst = NULL;
  191. // Register the window class
  192. // Allow 4 bytes of window data for D3D11RenderWindow pointer
  193. WNDCLASS wc = { classStyle, PlatformWndProc::_win32WndProc, 0, 0, hInst,
  194. LoadIcon(0, IDI_APPLICATION), LoadCursor(NULL, IDC_ARROW),
  195. (HBRUSH)GetStockObject(BLACK_BRUSH), 0, "D3D11Wnd" };
  196. RegisterClass(&wc);
  197. // Create our main window
  198. // Pass pointer to self
  199. mIsExternal = false;
  200. mHWnd = CreateWindowEx(dwStyleEx, "D3D11Wnd", mDesc.title.c_str(), dwStyle,
  201. mLeft, mTop, mWidth, mHeight, parentHWnd, 0, hInst, 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. DestroyWindow(mHWnd);
  231. }
  232. if(mDepthStencilView != nullptr)
  233. {
  234. Texture::releaseView(mDepthStencilView);
  235. mDepthStencilView = nullptr;
  236. }
  237. mHWnd = nullptr;
  238. destroySizeDependedD3DResources();
  239. RenderWindow::destroy_internal();
  240. }
  241. void D3D11RenderWindow::swapBuffers()
  242. {
  243. THROW_IF_NOT_CORE_THREAD;
  244. if(mDevice.getD3D11Device() != nullptr)
  245. {
  246. HRESULT hr = mSwapChain->Present(mVSync ? mVSyncInterval : 0, 0);
  247. if( FAILED(hr) )
  248. CM_EXCEPT(RenderingAPIException, "Error Presenting surfaces");
  249. }
  250. }
  251. void D3D11RenderWindow::move(INT32 top, INT32 left)
  252. {
  253. THROW_IF_NOT_CORE_THREAD;
  254. if (mHWnd && !mIsFullScreen)
  255. {
  256. mTop = top;
  257. mLeft = left;
  258. SetWindowPos(mHWnd, 0, top, left, 0, 0,
  259. SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
  260. }
  261. }
  262. void D3D11RenderWindow::resize(UINT32 width, UINT32 height)
  263. {
  264. THROW_IF_NOT_CORE_THREAD;
  265. if (mHWnd && !mIsFullScreen)
  266. {
  267. mWidth = width;
  268. mHeight = height;
  269. RECT rc = { 0, 0, width, height };
  270. AdjustWindowRect(&rc, GetWindowLong(mHWnd, GWL_STYLE), false);
  271. width = rc.right - rc.left;
  272. height = rc.bottom - rc.top;
  273. SetWindowPos(mHWnd, 0, 0, 0, width, height,
  274. SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE);
  275. }
  276. }
  277. void D3D11RenderWindow::setActive(bool state)
  278. {
  279. THROW_IF_NOT_CORE_THREAD;
  280. if (mHWnd && mSwapChain)
  281. {
  282. if (state)
  283. {
  284. ShowWindow(mHWnd, SW_RESTORE);
  285. mSwapChain->SetFullscreenState(mIsFullScreen, nullptr);
  286. }
  287. else
  288. {
  289. ShowWindow(mHWnd, SW_SHOWMINIMIZED);
  290. mSwapChain->SetFullscreenState(FALSE, nullptr);
  291. }
  292. }
  293. RenderWindow::setActive(state);
  294. }
  295. void D3D11RenderWindow::setHidden(bool hidden)
  296. {
  297. THROW_IF_NOT_CORE_THREAD;
  298. mHidden = hidden;
  299. if (!mIsExternal)
  300. {
  301. if (hidden)
  302. ShowWindow(mHWnd, SW_HIDE);
  303. else
  304. ShowWindow(mHWnd, SW_SHOWNORMAL);
  305. }
  306. }
  307. void D3D11RenderWindow::setFullscreen(UINT32 width, UINT32 height, float refreshRate, UINT32 monitorIdx)
  308. {
  309. THROW_IF_NOT_CORE_THREAD;
  310. if (mIsChild)
  311. return;
  312. const D3D11VideoModeInfo& videoModeInfo = static_cast<const D3D11VideoModeInfo&>(RenderSystem::instance().getVideoModeInfo());
  313. UINT32 numOutputs = videoModeInfo.getNumOutputs();
  314. if (numOutputs == 0)
  315. return;
  316. UINT32 actualMonitorIdx = std::min(monitorIdx, numOutputs - 1);
  317. const D3D11VideoOutputInfo& outputInfo = static_cast<const D3D11VideoOutputInfo&>(videoModeInfo.getOutputInfo(actualMonitorIdx));
  318. DXGI_MODE_DESC modeDesc;
  319. ZeroMemory(&modeDesc, sizeof(modeDesc));
  320. modeDesc.Width = width;
  321. modeDesc.Height = height;
  322. modeDesc.RefreshRate.Numerator = Math::roundToInt(refreshRate);
  323. modeDesc.RefreshRate.Denominator = 1;
  324. modeDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  325. modeDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
  326. modeDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
  327. DXGI_MODE_DESC nearestMode;
  328. ZeroMemory(&nearestMode, sizeof(nearestMode));
  329. outputInfo.getDXGIOutput()->FindClosestMatchingMode(&modeDesc, &nearestMode, nullptr);
  330. mIsFullScreen = true;
  331. mWidth = width;
  332. mHeight = height;
  333. mSwapChain->ResizeTarget(&nearestMode);
  334. mSwapChain->SetFullscreenState(true, outputInfo.getDXGIOutput());
  335. }
  336. void D3D11RenderWindow::setFullscreen(const VideoMode& mode)
  337. {
  338. THROW_IF_NOT_CORE_THREAD;
  339. if (mIsChild)
  340. return;
  341. if (mode.isCustom())
  342. {
  343. setFullscreen(mode.getWidth(), mode.getHeight(), mode.getRefreshRate(), mode.getOutputIdx());
  344. return;
  345. }
  346. const D3D11VideoModeInfo& videoModeInfo = static_cast<const D3D11VideoModeInfo&>(RenderSystem::instance().getVideoModeInfo());
  347. UINT32 numOutputs = videoModeInfo.getNumOutputs();
  348. if (numOutputs == 0)
  349. return;
  350. UINT32 actualMonitorIdx = std::min(mode.getOutputIdx(), numOutputs - 1);
  351. const D3D11VideoOutputInfo& outputInfo = static_cast<const D3D11VideoOutputInfo&>(videoModeInfo.getOutputInfo(actualMonitorIdx));
  352. const D3D11VideoMode& videoMode = static_cast<const D3D11VideoMode&>(mode);
  353. mIsFullScreen = true;
  354. mWidth = mode.getWidth();
  355. mHeight = mode.getHeight();
  356. mSwapChain->ResizeTarget(&videoMode.getDXGIModeDesc());
  357. mSwapChain->SetFullscreenState(true, outputInfo.getDXGIOutput());
  358. }
  359. void D3D11RenderWindow::setWindowed()
  360. {
  361. THROW_IF_NOT_CORE_THREAD;
  362. mIsFullScreen = false;
  363. mSwapChainDesc.Windowed = false;
  364. mSwapChainDesc.BufferDesc.RefreshRate.Numerator = 0;
  365. mSwapChainDesc.BufferDesc.RefreshRate.Denominator = 0;
  366. mSwapChainDesc.BufferDesc.Width = mWidth;
  367. mSwapChainDesc.BufferDesc.Height = mHeight;
  368. DXGI_MODE_DESC modeDesc;
  369. ZeroMemory(&modeDesc, sizeof(modeDesc));
  370. modeDesc.Width = mWidth;
  371. modeDesc.Height = mHeight;
  372. modeDesc.RefreshRate.Numerator = 0;
  373. modeDesc.RefreshRate.Denominator = 0;
  374. modeDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  375. mSwapChain->ResizeTarget(&modeDesc);
  376. mSwapChain->SetFullscreenState(false, nullptr);
  377. }
  378. void D3D11RenderWindow::getCustomAttribute( const String& name, void* pData ) const
  379. {
  380. if(name == "WINDOW")
  381. {
  382. HWND *pWnd = (HWND*)pData;
  383. *pWnd = mHWnd;
  384. return;
  385. }
  386. if(name == "RTV")
  387. {
  388. *static_cast<ID3D11RenderTargetView**>(pData) = mRenderTargetView;
  389. return;
  390. }
  391. else if(name == "DSV")
  392. {
  393. D3D11TextureView* d3d11TextureView = static_cast<D3D11TextureView*>(mDepthStencilView.get());
  394. *static_cast<ID3D11DepthStencilView**>(pData) = d3d11TextureView->getDSV();
  395. return;
  396. }
  397. RenderWindow::getCustomAttribute(name, pData);
  398. }
  399. void D3D11RenderWindow::copyToMemory(const PixelData &dst, FrameBuffer buffer)
  400. {
  401. THROW_IF_NOT_CORE_THREAD;
  402. if(mBackBuffer == nullptr)
  403. return;
  404. // get the backbuffer desc
  405. D3D11_TEXTURE2D_DESC BBDesc;
  406. mBackBuffer->GetDesc(&BBDesc);
  407. ID3D11Texture2D *backbuffer = nullptr;
  408. if(BBDesc.SampleDesc.Quality > 0)
  409. {
  410. D3D11_TEXTURE2D_DESC desc = BBDesc;
  411. desc.Usage = D3D11_USAGE_DEFAULT;
  412. desc.CPUAccessFlags = 0;
  413. desc.BindFlags = 0;
  414. desc.SampleDesc.Quality = 0;
  415. desc.SampleDesc.Count = 1;
  416. HRESULT hr = mDevice.getD3D11Device()->CreateTexture2D(
  417. &desc,
  418. NULL,
  419. &backbuffer);
  420. if (FAILED(hr) || mDevice.hasError())
  421. {
  422. String errorDescription = mDevice.getErrorDescription();
  423. CM_EXCEPT(RenderingAPIException,
  424. "Error creating texture\nError Description:" + errorDescription);
  425. }
  426. mDevice.getImmediateContext()->ResolveSubresource(backbuffer, D3D11CalcSubresource(0, 0, 1), mBackBuffer, D3D11CalcSubresource(0, 0, 1), desc.Format);
  427. }
  428. // change the parameters of the texture so we can read it
  429. BBDesc.Usage = D3D11_USAGE_STAGING;
  430. BBDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
  431. BBDesc.BindFlags = 0;
  432. BBDesc.SampleDesc.Quality = 0;
  433. BBDesc.SampleDesc.Count = 1;
  434. // create a temp buffer to copy to
  435. ID3D11Texture2D * pTempTexture2D;
  436. HRESULT hr = mDevice.getD3D11Device()->CreateTexture2D(
  437. &BBDesc,
  438. NULL,
  439. &pTempTexture2D);
  440. if (FAILED(hr) || mDevice.hasError())
  441. {
  442. String errorDescription = mDevice.getErrorDescription();
  443. CM_EXCEPT(RenderingAPIException,
  444. "Error creating texture\nError Description:" + errorDescription);
  445. }
  446. // copy the back buffer
  447. mDevice.getImmediateContext()->CopyResource(pTempTexture2D, backbuffer != NULL ? backbuffer : mBackBuffer);
  448. // map the copied texture
  449. D3D11_MAPPED_SUBRESOURCE mappedTex2D;
  450. mDevice.getImmediateContext()->Map(pTempTexture2D, 0,D3D11_MAP_READ, 0, &mappedTex2D);
  451. // copy the the texture to the dest
  452. PixelData src(mWidth, mHeight, 1, PF_A8B8G8R8);
  453. src.setExternalBuffer((UINT8*)mappedTex2D.pData);
  454. PixelUtil::bulkPixelConversion(src, dst);
  455. // unmap the temp buffer
  456. mDevice.getImmediateContext()->Unmap(pTempTexture2D, 0);
  457. // Release the temp buffer
  458. SAFE_RELEASE(pTempTexture2D);
  459. SAFE_RELEASE(backbuffer);
  460. }
  461. Vector2I D3D11RenderWindow::screenToWindowPos(const Vector2I& screenPos) const
  462. {
  463. POINT pos;
  464. pos.x = screenPos.x;
  465. pos.y = screenPos.y;
  466. ScreenToClient(mHWnd, &pos);
  467. return Vector2I(pos.x, pos.y);
  468. }
  469. Vector2I D3D11RenderWindow::windowToScreenPos(const Vector2I& windowPos) const
  470. {
  471. POINT pos;
  472. pos.x = windowPos.x;
  473. pos.y = windowPos.y;
  474. ClientToScreen(mHWnd, &pos);
  475. return Vector2I(pos.x, pos.y);
  476. }
  477. void D3D11RenderWindow::_windowMovedOrResized()
  478. {
  479. THROW_IF_NOT_CORE_THREAD;
  480. if (!mHWnd || IsIconic(mHWnd))
  481. return;
  482. RECT rc;
  483. // top and left represent outer window position
  484. GetWindowRect(mHWnd, &rc);
  485. mTop = rc.top;
  486. mLeft = rc.left;
  487. // width and height represent drawable area only
  488. GetClientRect(mHWnd, &rc);
  489. unsigned int width = rc.right - rc.left;
  490. unsigned int height = rc.bottom - rc.top;
  491. if (width == 0)
  492. width = 1;
  493. if (height == 0)
  494. height = 1;
  495. resizeSwapChainBuffers(width, height);
  496. RenderWindow::_windowMovedOrResized();
  497. }
  498. void D3D11RenderWindow::createSwapChain()
  499. {
  500. ZeroMemory(&mSwapChainDesc, sizeof(DXGI_SWAP_CHAIN_DESC));
  501. // get the dxgi device
  502. IDXGIDevice* pDXGIDevice = queryDxgiDevice();
  503. ZeroMemory(&mSwapChainDesc, sizeof(DXGI_SWAP_CHAIN_DESC));
  504. DXGI_FORMAT format = DXGI_FORMAT_R8G8B8A8_UNORM;
  505. mSwapChainDesc.OutputWindow = mHWnd;
  506. mSwapChainDesc.BufferDesc.Width = mWidth;
  507. mSwapChainDesc.BufferDesc.Height = mHeight;
  508. mSwapChainDesc.BufferDesc.Format = format;
  509. mSwapChainDesc.BufferDesc.RefreshRate.Numerator=0;
  510. mSwapChainDesc.BufferDesc.RefreshRate.Denominator = 0;
  511. mSwapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
  512. mSwapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
  513. mSwapChainDesc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH ;
  514. mSwapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
  515. mSwapChainDesc.BufferCount = 1;
  516. mSwapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD ;
  517. mSwapChainDesc.OutputWindow = mHWnd;
  518. mSwapChainDesc.Windowed = !mIsFullScreen;
  519. D3D11RenderSystem* rs = static_cast<D3D11RenderSystem*>(RenderSystem::instancePtr());
  520. rs->determineMultisampleSettings(mMultisampleCount, mMultisampleHint, format, &mMultisampleType);
  521. mSwapChainDesc.SampleDesc.Count = mMultisampleType.Count;
  522. mSwapChainDesc.SampleDesc.Quality = mMultisampleType.Quality;
  523. HRESULT hr;
  524. // Create swap chain
  525. hr = mDXGIFactory->CreateSwapChain(pDXGIDevice, &mSwapChainDesc, &mSwapChain);
  526. if (FAILED(hr))
  527. {
  528. // Try a second time, may fail the first time due to back buffer count,
  529. // which will be corrected by the runtime
  530. hr = mDXGIFactory->CreateSwapChain(pDXGIDevice, &mSwapChainDesc, &mSwapChain);
  531. }
  532. SAFE_RELEASE(pDXGIDevice);
  533. if (FAILED(hr))
  534. CM_EXCEPT(RenderingAPIException, "Unable to create swap chain");
  535. }
  536. void D3D11RenderWindow::createSizeDependedD3DResources()
  537. {
  538. // obtain back buffer
  539. SAFE_RELEASE(mBackBuffer);
  540. HRESULT hr = mSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&mBackBuffer);
  541. if( FAILED(hr) )
  542. CM_EXCEPT(RenderingAPIException, "Unable to Get Back Buffer for swap chain");
  543. // create all other size depended resources
  544. assert(mBackBuffer && !mRenderTargetView);
  545. // get the backbuffer desc
  546. D3D11_TEXTURE2D_DESC BBDesc;
  547. mBackBuffer->GetDesc(&BBDesc);
  548. // create the render target view
  549. D3D11_RENDER_TARGET_VIEW_DESC RTVDesc;
  550. ZeroMemory( &RTVDesc, sizeof(RTVDesc) );
  551. RTVDesc.Format = BBDesc.Format;
  552. RTVDesc.ViewDimension = mMultisampleCount ? D3D11_RTV_DIMENSION_TEXTURE2DMS : D3D11_RTV_DIMENSION_TEXTURE2D;
  553. RTVDesc.Texture2D.MipSlice = 0;
  554. hr = mDevice.getD3D11Device()->CreateRenderTargetView(mBackBuffer, &RTVDesc, &mRenderTargetView);
  555. if( FAILED(hr) )
  556. {
  557. String errorDescription = mDevice.getErrorDescription();
  558. CM_EXCEPT(RenderingAPIException, "Unable to create rendertagert view\nError Description:" + errorDescription);
  559. }
  560. mDepthStencilBuffer = TextureManager::instance().createTexture(TEX_TYPE_2D,
  561. BBDesc.Width, BBDesc.Height, 0, PF_D24S8, TU_DEPTHSTENCIL, false, mMultisampleCount, mMultisampleHint);
  562. if(mDepthStencilView != nullptr)
  563. {
  564. Texture::releaseView(mDepthStencilView);
  565. mDepthStencilView = nullptr;
  566. }
  567. mDepthStencilView = Texture::requestView(mDepthStencilBuffer, 0, 1, 0, 1, GVU_DEPTHSTENCIL);
  568. }
  569. void D3D11RenderWindow::destroySizeDependedD3DResources()
  570. {
  571. SAFE_RELEASE(mBackBuffer);
  572. SAFE_RELEASE(mRenderTargetView);
  573. mDepthStencilBuffer = nullptr;
  574. }
  575. void D3D11RenderWindow::resizeSwapChainBuffers(UINT32 width, UINT32 height)
  576. {
  577. destroySizeDependedD3DResources();
  578. // width and height can be zero to autodetect size, therefore do not rely on them
  579. UINT Flags = mIsFullScreen ? DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH : 0;
  580. HRESULT hr = mSwapChain->ResizeBuffers(mSwapChainDesc.BufferCount, width, height, mSwapChainDesc.BufferDesc.Format, Flags);
  581. if(hr != S_OK)
  582. CM_EXCEPT(InternalErrorException, "Call to ResizeBuffers failed.");
  583. mSwapChain->GetDesc(&mSwapChainDesc);
  584. mWidth = mSwapChainDesc.BufferDesc.Width;
  585. mHeight = mSwapChainDesc.BufferDesc.Height;
  586. mIsFullScreen = (0 == mSwapChainDesc.Windowed); // Alt-Enter together with SetWindowAssociation() can change this state
  587. createSizeDependedD3DResources();
  588. mDevice.getImmediateContext()->OMSetRenderTargets(0, 0, 0);
  589. }
  590. IDXGIDevice* D3D11RenderWindow::queryDxgiDevice()
  591. {
  592. if (mDevice.getD3D11Device() == nullptr)
  593. {
  594. CM_EXCEPT(RenderingAPIException, "D3D11Device is NULL!");
  595. }
  596. IDXGIDevice* pDXGIDevice = nullptr;
  597. HRESULT hr = mDevice.getD3D11Device()->QueryInterface(__uuidof(IDXGIDevice), (void**)&pDXGIDevice);
  598. if(FAILED(hr))
  599. CM_EXCEPT(RenderingAPIException, "Unable to query a DXGIDevice");
  600. return pDXGIDevice;
  601. }
  602. bool D3D11RenderWindow::checkMultiSampleQuality(UINT32 SampleCount, UINT32 *outQuality, DXGI_FORMAT format)
  603. {
  604. if (SUCCEEDED(mDevice.getD3D11Device()->CheckMultisampleQualityLevels(format, SampleCount, outQuality)))
  605. return true;
  606. else
  607. return false;
  608. }
  609. }