BsD3D11RenderWindow.cpp 23 KB

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