BsD3D11RenderWindow.cpp 24 KB

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