BsD3D11Texture.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #include "BsD3D11Texture.h"
  4. #include "BsD3D11Mappings.h"
  5. #include "BsD3D11Device.h"
  6. #include "BsD3D11RenderAPI.h"
  7. #include "BsD3D11TextureView.h"
  8. #include "BsCoreThread.h"
  9. #include "BsException.h"
  10. #include "BsAsyncOp.h"
  11. #include "BsRenderStats.h"
  12. #include "BsMath.h"
  13. namespace BansheeEngine
  14. {
  15. D3D11TextureCore::D3D11TextureCore(TextureType textureType, UINT32 width, UINT32 height, UINT32 depth, UINT32 numMipmaps,
  16. PixelFormat format, int usage, bool hwGamma, UINT32 multisampleCount, UINT32 numArraySlices, const SPtr<PixelData>& initialData)
  17. : TextureCore(textureType, width, height, depth, numMipmaps, format, usage, hwGamma, multisampleCount, numArraySlices, initialData),
  18. m1DTex(nullptr), m2DTex(nullptr), m3DTex(nullptr), mDXGIFormat(DXGI_FORMAT_UNKNOWN), mDXGIColorFormat(DXGI_FORMAT_UNKNOWN),
  19. mTex(nullptr), mStagingBuffer(nullptr), mDXGIDepthStencilFormat(DXGI_FORMAT_UNKNOWN),
  20. mLockedSubresourceIdx(-1), mLockedForReading(false), mStaticBuffer(nullptr)
  21. { }
  22. D3D11TextureCore::~D3D11TextureCore()
  23. {
  24. SAFE_RELEASE(mTex);
  25. SAFE_RELEASE(m1DTex);
  26. SAFE_RELEASE(m2DTex);
  27. SAFE_RELEASE(m3DTex);
  28. SAFE_RELEASE(mStagingBuffer);
  29. BS_INC_RENDER_STAT_CAT(ResDestroyed, RenderStatObject_Texture);
  30. }
  31. void D3D11TextureCore::initialize()
  32. {
  33. THROW_IF_NOT_CORE_THREAD;
  34. switch (mProperties.getTextureType())
  35. {
  36. case TEX_TYPE_1D:
  37. create1DTex();
  38. break;
  39. case TEX_TYPE_2D:
  40. case TEX_TYPE_CUBE_MAP:
  41. create2DTex();
  42. break;
  43. case TEX_TYPE_3D:
  44. create3DTex();
  45. break;
  46. default:
  47. BS_EXCEPT(RenderingAPIException, "Unknown texture type");
  48. }
  49. BS_INC_RENDER_STAT_CAT(ResCreated, RenderStatObject_Texture);
  50. TextureCore::initialize();
  51. }
  52. void D3D11TextureCore::copyImpl(UINT32 srcFace, UINT32 srcMipLevel, UINT32 destFace, UINT32 destMipLevel, const SPtr<TextureCore>& target)
  53. {
  54. D3D11TextureCore* other = static_cast<D3D11TextureCore*>(target.get());
  55. UINT32 srcResIdx = D3D11CalcSubresource(srcMipLevel, srcFace, mProperties.getNumMipmaps() + 1);
  56. UINT32 destResIdx = D3D11CalcSubresource(destMipLevel, destFace, target->getProperties().getNumMipmaps() + 1);
  57. D3D11RenderAPI* rs = static_cast<D3D11RenderAPI*>(RenderAPICore::instancePtr());
  58. D3D11Device& device = rs->getPrimaryDevice();
  59. bool srcHasMultisample = mProperties.getMultisampleCount() > 1;
  60. bool destHasMultisample = target->getProperties().getMultisampleCount() > 1;
  61. if (srcHasMultisample && destHasMultisample && mProperties.getMultisampleCount() != target->getProperties().getMultisampleCount()) // Resolving from MS to non-MS texture
  62. {
  63. device.getImmediateContext()->ResolveSubresource(other->getDX11Resource(), destResIdx, mTex, srcResIdx, mDXGIFormat);
  64. }
  65. else
  66. {
  67. device.getImmediateContext()->CopySubresourceRegion(other->getDX11Resource(), destResIdx, 0, 0, 0, mTex, srcResIdx, nullptr);
  68. if (device.hasError())
  69. {
  70. String errorDescription = device.getErrorDescription();
  71. BS_EXCEPT(RenderingAPIException, "D3D11 device cannot copy subresource\nError Description:" + errorDescription);
  72. }
  73. }
  74. }
  75. PixelData D3D11TextureCore::lockImpl(GpuLockOptions options, UINT32 mipLevel, UINT32 face)
  76. {
  77. if (mProperties.getMultisampleCount() > 1)
  78. BS_EXCEPT(InvalidStateException, "Multisampled textures cannot be accessed from the CPU directly.");
  79. #if BS_PROFILING_ENABLED
  80. if (options == GBL_READ_ONLY || options == GBL_READ_WRITE)
  81. {
  82. BS_INC_RENDER_STAT_CAT(ResRead, RenderStatObject_Texture);
  83. }
  84. if (options == GBL_READ_WRITE || options == GBL_WRITE_ONLY || options == GBL_WRITE_ONLY_DISCARD || options == GBL_WRITE_ONLY_NO_OVERWRITE)
  85. {
  86. BS_INC_RENDER_STAT_CAT(ResWrite, RenderStatObject_Texture);
  87. }
  88. #endif
  89. UINT32 mipWidth = std::max(1u, mProperties.getWidth() >> mipLevel);
  90. UINT32 mipHeight = std::max(1u, mProperties.getHeight() >> mipLevel);
  91. UINT32 mipDepth = std::max(1u, mProperties.getDepth() >> mipLevel);
  92. PixelData lockedArea(mipWidth, mipHeight, mipDepth, mProperties.getFormat());
  93. D3D11_MAP flags = D3D11Mappings::getLockOptions(options);
  94. UINT32 rowPitch, slicePitch;
  95. if(flags == D3D11_MAP_READ || flags == D3D11_MAP_READ_WRITE)
  96. {
  97. UINT8* data = (UINT8*)mapstagingbuffer(flags, face, mipLevel, rowPitch, slicePitch);
  98. lockedArea.setExternalBuffer(data);
  99. lockedArea.setRowPitch(rowPitch);
  100. lockedArea.setSlicePitch(slicePitch);
  101. mLockedForReading = true;
  102. }
  103. else
  104. {
  105. if (mProperties.getUsage() == TU_DYNAMIC)
  106. {
  107. UINT8* data = (UINT8*)map(mTex, flags, face, mipLevel, rowPitch, slicePitch);
  108. lockedArea.setExternalBuffer(data);
  109. lockedArea.setRowPitch(rowPitch);
  110. lockedArea.setSlicePitch(slicePitch);
  111. }
  112. else
  113. lockedArea.setExternalBuffer((UINT8*)mapstaticbuffer(lockedArea, mipLevel, face));
  114. mLockedForReading = false;
  115. }
  116. return lockedArea;
  117. }
  118. void D3D11TextureCore::unlockImpl()
  119. {
  120. if(mLockedForReading)
  121. unmapstagingbuffer();
  122. else
  123. {
  124. if (mProperties.getUsage() == TU_DYNAMIC)
  125. unmap(mTex);
  126. else
  127. unmapstaticbuffer();
  128. }
  129. }
  130. void D3D11TextureCore::readData(PixelData& dest, UINT32 mipLevel, UINT32 face)
  131. {
  132. if (mProperties.getMultisampleCount() > 1)
  133. BS_EXCEPT(InvalidStateException, "Multisampled textures cannot be accessed from the CPU directly.");
  134. PixelData myData = lock(GBL_READ_ONLY, mipLevel, face);
  135. #if BS_DEBUG_MODE
  136. if(dest.getConsecutiveSize() != myData.getConsecutiveSize())
  137. {
  138. unlock();
  139. BS_EXCEPT(InternalErrorException, "Buffer sizes don't match");
  140. }
  141. #endif
  142. PixelUtil::bulkPixelConversion(myData, dest);
  143. unlock();
  144. }
  145. void D3D11TextureCore::writeData(const PixelData& src, UINT32 mipLevel, UINT32 face, bool discardWholeBuffer)
  146. {
  147. PixelFormat format = mProperties.getFormat();
  148. if (mProperties.getMultisampleCount() > 1)
  149. BS_EXCEPT(InvalidStateException, "Multisampled textures cannot be accessed from the CPU directly.");
  150. mipLevel = Math::clamp(mipLevel, (UINT32)mipLevel, mProperties.getNumMipmaps());
  151. face = Math::clamp(face, (UINT32)0, mProperties.getNumFaces() - 1);
  152. if (face > 0 && mProperties.getTextureType() == TEX_TYPE_3D)
  153. BS_EXCEPT(InvalidStateException, "3D texture arrays are not supported.");
  154. if ((mProperties.getUsage() & TU_DYNAMIC) != 0)
  155. {
  156. PixelData myData = lock(discardWholeBuffer ? GBL_WRITE_ONLY_DISCARD : GBL_WRITE_ONLY, mipLevel, face);
  157. PixelUtil::bulkPixelConversion(src, myData);
  158. unlock();
  159. }
  160. else if ((mProperties.getUsage() & TU_DEPTHSTENCIL) == 0)
  161. {
  162. D3D11RenderAPI* rs = static_cast<D3D11RenderAPI*>(RenderAPICore::instancePtr());
  163. D3D11Device& device = rs->getPrimaryDevice();
  164. UINT subresourceIdx = D3D11CalcSubresource(mipLevel, face, mProperties.getNumMipmaps() + 1);
  165. UINT32 rowWidth = D3D11Mappings::getSizeInBytes(format, src.getWidth());
  166. UINT32 sliceWidth = D3D11Mappings::getSizeInBytes(format, src.getWidth(), src.getHeight());
  167. device.getImmediateContext()->UpdateSubresource(mTex, subresourceIdx, nullptr, src.getData(), rowWidth, sliceWidth);
  168. if (device.hasError())
  169. {
  170. String errorDescription = device.getErrorDescription();
  171. BS_EXCEPT(RenderingAPIException, "D3D11 device cannot map texture\nError Description:" + errorDescription);
  172. }
  173. BS_INC_RENDER_STAT_CAT(ResWrite, RenderStatObject_Texture);
  174. }
  175. else
  176. {
  177. BS_EXCEPT(RenderingAPIException, "Trying to write into a buffer with unsupported usage: " + toString(mProperties.getUsage()));
  178. }
  179. }
  180. void D3D11TextureCore::create1DTex()
  181. {
  182. UINT32 width = mProperties.getWidth();
  183. int usage = mProperties.getUsage();
  184. UINT32 numMips = mProperties.getNumMipmaps();
  185. PixelFormat format = mProperties.getFormat();
  186. bool hwGamma = mProperties.isHardwareGammaEnabled();
  187. PixelFormat closestFormat = D3D11Mappings::getClosestSupportedPF(format, hwGamma);
  188. UINT32 numFaces = mProperties.getNumFaces();
  189. // We must have those defined here
  190. assert(width > 0);
  191. // Determine which D3D11 pixel format we'll use
  192. HRESULT hr;
  193. DXGI_FORMAT d3dPF = D3D11Mappings::getPF(closestFormat, hwGamma);
  194. if (format != D3D11Mappings::getPF(d3dPF))
  195. {
  196. BS_EXCEPT(RenderingAPIException, "Provided pixel format is not supported by the driver: " + toString(format));
  197. }
  198. mDXGIColorFormat = d3dPF;
  199. mDXGIDepthStencilFormat = d3dPF;
  200. // TODO - Consider making this a parameter eventually
  201. bool readableDepth = true;
  202. D3D11_TEXTURE1D_DESC desc;
  203. desc.Width = static_cast<UINT32>(width);
  204. desc.ArraySize = numFaces == 0 ? 1 : numFaces;
  205. desc.Format = d3dPF;
  206. desc.MiscFlags = 0;
  207. if((usage & TU_RENDERTARGET) != 0)
  208. {
  209. desc.Usage = D3D11_USAGE_DEFAULT;
  210. desc.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE;
  211. desc.CPUAccessFlags = 0;
  212. desc.MipLevels = 1;
  213. }
  214. else if ((usage & TU_DEPTHSTENCIL) != 0)
  215. {
  216. desc.Usage = D3D11_USAGE_DEFAULT;
  217. if(readableDepth)
  218. desc.BindFlags = D3D11_BIND_DEPTH_STENCIL | D3D11_BIND_SHADER_RESOURCE;
  219. else
  220. desc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
  221. desc.CPUAccessFlags = 0;
  222. desc.MipLevels = 1;
  223. desc.Format = D3D11Mappings::getTypelessDepthStencilPF(closestFormat);
  224. mDXGIColorFormat = D3D11Mappings::getShaderResourceDepthStencilPF(closestFormat);
  225. mDXGIDepthStencilFormat = d3dPF;
  226. }
  227. else
  228. {
  229. desc.Usage = D3D11Mappings::getUsage((GpuBufferUsage)usage);
  230. desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
  231. desc.CPUAccessFlags = D3D11Mappings::getAccessFlags((GpuBufferUsage)usage);
  232. // Determine total number of mipmaps including main one (d3d11 convention)
  233. desc.MipLevels = (numMips == MIP_UNLIMITED || (1U << numMips) > width) ? 0 : numMips + 1;
  234. }
  235. if ((usage & TU_LOADSTORE) != 0)
  236. desc.BindFlags |= D3D11_BIND_UNORDERED_ACCESS;
  237. // Create the texture
  238. D3D11RenderAPI* rs = static_cast<D3D11RenderAPI*>(RenderAPICore::instancePtr());
  239. D3D11Device& device = rs->getPrimaryDevice();
  240. hr = device.getD3D11Device()->CreateTexture1D(&desc, nullptr, &m1DTex);
  241. // Check result and except if failed
  242. if (FAILED(hr) || device.hasError())
  243. {
  244. String errorDescription = device.getErrorDescription();
  245. BS_EXCEPT(RenderingAPIException, "Error creating texture\nError Description:" + errorDescription);
  246. }
  247. hr = m1DTex->QueryInterface(__uuidof(ID3D11Resource), (void **)&mTex);
  248. if(FAILED(hr) || device.hasError())
  249. {
  250. String errorDescription = device.getErrorDescription();
  251. BS_EXCEPT(RenderingAPIException, "Can't get base texture\nError Description:" + errorDescription);
  252. }
  253. m1DTex->GetDesc(&desc);
  254. if(numMips != (desc.MipLevels - 1))
  255. {
  256. BS_EXCEPT(RenderingAPIException, "Driver returned different number of mip maps than requested. " \
  257. "Requested: " + toString(numMips) + ". Got: " + toString(desc.MipLevels - 1) + ".");
  258. }
  259. mDXGIFormat = desc.Format;
  260. // Create texture view
  261. if ((usage & TU_DEPTHSTENCIL) == 0 || readableDepth)
  262. {
  263. TEXTURE_VIEW_DESC viewDesc;
  264. viewDesc.mostDetailMip = 0;
  265. viewDesc.numMips = desc.MipLevels;
  266. viewDesc.firstArraySlice = 0;
  267. viewDesc.numArraySlices = desc.ArraySize;
  268. viewDesc.usage = GVU_DEFAULT;
  269. SPtr<TextureCore> thisPtr = std::static_pointer_cast<TextureCore>(getThisPtr());
  270. mShaderResourceView = bs_shared_ptr<D3D11TextureView>(new (bs_alloc<D3D11TextureView>()) D3D11TextureView(thisPtr, viewDesc));
  271. }
  272. }
  273. void D3D11TextureCore::create2DTex()
  274. {
  275. UINT32 width = mProperties.getWidth();
  276. UINT32 height = mProperties.getHeight();
  277. int usage = mProperties.getUsage();
  278. UINT32 numMips = mProperties.getNumMipmaps();
  279. PixelFormat format = mProperties.getFormat();
  280. bool hwGamma = mProperties.isHardwareGammaEnabled();
  281. UINT32 sampleCount = mProperties.getMultisampleCount();
  282. TextureType texType = mProperties.getTextureType();
  283. PixelFormat closestFormat = D3D11Mappings::getClosestSupportedPF(format, hwGamma);
  284. UINT32 numFaces = mProperties.getNumFaces();
  285. // TODO - Consider making this a parameter eventually
  286. bool readableDepth = true;
  287. // We must have those defined here
  288. assert(width > 0 || height > 0);
  289. // Determine which D3D11 pixel format we'll use
  290. HRESULT hr;
  291. DXGI_FORMAT d3dPF = D3D11Mappings::getPF(closestFormat, hwGamma);
  292. if (format != D3D11Mappings::getPF(d3dPF))
  293. {
  294. BS_EXCEPT(RenderingAPIException, "Provided pixel format is not supported by the driver: " + toString(format));
  295. }
  296. mDXGIColorFormat = d3dPF;
  297. mDXGIDepthStencilFormat = d3dPF;
  298. D3D11_TEXTURE2D_DESC desc;
  299. desc.Width = static_cast<UINT32>(width);
  300. desc.Height = static_cast<UINT32>(height);
  301. desc.ArraySize = numFaces == 0 ? 1 : numFaces;;
  302. desc.Format = d3dPF;
  303. desc.MiscFlags = 0;
  304. if((usage & TU_RENDERTARGET) != 0)
  305. {
  306. desc.Usage = D3D11_USAGE_DEFAULT;
  307. desc.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE; // TODO - Add flags to allow RT be created without shader resource flags (might be more optimal)
  308. desc.CPUAccessFlags = 0;
  309. desc.MipLevels = 1;
  310. DXGI_SAMPLE_DESC sampleDesc;
  311. D3D11RenderAPI* rs = static_cast<D3D11RenderAPI*>(RenderAPICore::instancePtr());
  312. rs->determineMultisampleSettings(sampleCount, d3dPF, &sampleDesc);
  313. desc.SampleDesc = sampleDesc;
  314. if (texType == TEX_TYPE_CUBE_MAP)
  315. {
  316. BS_EXCEPT(NotImplementedException, "Cube map not yet supported as a render target."); // TODO: Will be once I add proper texture array support
  317. }
  318. }
  319. else if((usage & TU_DEPTHSTENCIL) != 0)
  320. {
  321. desc.Usage = D3D11_USAGE_DEFAULT;
  322. desc.CPUAccessFlags = 0;
  323. desc.MipLevels = 1;
  324. desc.Format = D3D11Mappings::getTypelessDepthStencilPF(closestFormat);
  325. if(readableDepth)
  326. desc.BindFlags = D3D11_BIND_DEPTH_STENCIL | D3D11_BIND_SHADER_RESOURCE;
  327. else
  328. desc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
  329. DXGI_SAMPLE_DESC sampleDesc;
  330. D3D11RenderAPI* rs = static_cast<D3D11RenderAPI*>(RenderAPICore::instancePtr());
  331. rs->determineMultisampleSettings(sampleCount, d3dPF, &sampleDesc);
  332. desc.SampleDesc = sampleDesc;
  333. if (texType == TEX_TYPE_CUBE_MAP)
  334. {
  335. BS_EXCEPT(NotImplementedException, "Cube map not yet supported as a depth stencil target."); // TODO: Will be once I add proper texture array support
  336. }
  337. mDXGIColorFormat = D3D11Mappings::getShaderResourceDepthStencilPF(closestFormat);
  338. mDXGIDepthStencilFormat = d3dPF;
  339. }
  340. else
  341. {
  342. desc.Usage = D3D11Mappings::getUsage((GpuBufferUsage)usage);
  343. desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
  344. desc.CPUAccessFlags = D3D11Mappings::getAccessFlags((GpuBufferUsage)usage);
  345. // Determine total number of mipmaps including main one (d3d11 convention)
  346. desc.MipLevels = (numMips == MIP_UNLIMITED || (1U << numMips) > width) ? 0 : numMips + 1;
  347. DXGI_SAMPLE_DESC sampleDesc;
  348. sampleDesc.Count = 1;
  349. sampleDesc.Quality = 0;
  350. desc.SampleDesc = sampleDesc;
  351. }
  352. if (texType == TEX_TYPE_CUBE_MAP)
  353. desc.MiscFlags |= D3D11_RESOURCE_MISC_TEXTURECUBE;
  354. if ((usage & TU_LOADSTORE) != 0)
  355. desc.BindFlags |= D3D11_BIND_UNORDERED_ACCESS;
  356. // Create the texture
  357. D3D11RenderAPI* rs = static_cast<D3D11RenderAPI*>(RenderAPICore::instancePtr());
  358. D3D11Device& device = rs->getPrimaryDevice();
  359. hr = device.getD3D11Device()->CreateTexture2D(&desc, nullptr, &m2DTex);
  360. // Check result and except if failed
  361. if (FAILED(hr) || device.hasError())
  362. {
  363. String errorDescription = device.getErrorDescription();
  364. BS_EXCEPT(RenderingAPIException, "Error creating texture\nError Description:" + errorDescription);
  365. }
  366. hr = m2DTex->QueryInterface(__uuidof(ID3D11Resource), (void **)&mTex);
  367. if(FAILED(hr) || device.hasError())
  368. {
  369. String errorDescription = device.getErrorDescription();
  370. BS_EXCEPT(RenderingAPIException, "Can't get base texture\nError Description:" + errorDescription);
  371. }
  372. m2DTex->GetDesc(&desc);
  373. if(numMips != (desc.MipLevels - 1))
  374. {
  375. BS_EXCEPT(RenderingAPIException, "Driver returned different number of mip maps than requested. " \
  376. "Requested: " + toString(numMips) + ". Got: " + toString(desc.MipLevels - 1) + ".");
  377. }
  378. mDXGIFormat = desc.Format;
  379. // Create shader texture view
  380. if((usage & TU_DEPTHSTENCIL) == 0 || readableDepth)
  381. {
  382. TEXTURE_VIEW_DESC viewDesc;
  383. viewDesc.mostDetailMip = 0;
  384. viewDesc.numMips = desc.MipLevels;
  385. viewDesc.firstArraySlice = 0;
  386. viewDesc.numArraySlices = desc.ArraySize;
  387. viewDesc.usage = GVU_DEFAULT;
  388. SPtr<TextureCore> thisPtr = std::static_pointer_cast<TextureCore>(getThisPtr());
  389. mShaderResourceView = bs_shared_ptr<D3D11TextureView>(new (bs_alloc<D3D11TextureView>()) D3D11TextureView(thisPtr, viewDesc));
  390. }
  391. }
  392. void D3D11TextureCore::create3DTex()
  393. {
  394. UINT32 width = mProperties.getWidth();
  395. UINT32 height = mProperties.getHeight();
  396. UINT32 depth = mProperties.getDepth();
  397. int usage = mProperties.getUsage();
  398. UINT32 numMips = mProperties.getNumMipmaps();
  399. PixelFormat format = mProperties.getFormat();
  400. bool hwGamma = mProperties.isHardwareGammaEnabled();
  401. PixelFormat closestFormat = D3D11Mappings::getClosestSupportedPF(format, hwGamma);
  402. // TODO - Consider making this a parameter eventually
  403. bool readableDepth = true;
  404. // We must have those defined here
  405. assert(width > 0 && height > 0 && depth > 0);
  406. // Determine which D3D11 pixel format we'll use
  407. HRESULT hr;
  408. DXGI_FORMAT d3dPF = D3D11Mappings::getPF(closestFormat, hwGamma);
  409. if (format != D3D11Mappings::getPF(d3dPF))
  410. {
  411. BS_EXCEPT(RenderingAPIException, "Provided pixel format is not supported by the driver: " + toString(format));
  412. }
  413. mDXGIColorFormat = d3dPF;
  414. mDXGIDepthStencilFormat = d3dPF;
  415. D3D11_TEXTURE3D_DESC desc;
  416. desc.Width = static_cast<UINT32>(width);
  417. desc.Height = static_cast<UINT32>(height);
  418. desc.Depth = static_cast<UINT32>(depth);
  419. desc.Format = d3dPF;
  420. desc.MiscFlags = 0;
  421. if ((mProperties.getUsage() & TU_RENDERTARGET) != 0)
  422. {
  423. desc.Usage = D3D11_USAGE_DEFAULT;
  424. desc.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE;
  425. desc.CPUAccessFlags = 0;
  426. desc.MipLevels = 1;
  427. }
  428. else if ((mProperties.getUsage() & TU_DEPTHSTENCIL) != 0)
  429. {
  430. desc.Usage = D3D11_USAGE_DEFAULT;
  431. desc.CPUAccessFlags = 0;
  432. desc.MipLevels = 1;
  433. if (readableDepth)
  434. desc.BindFlags = D3D11_BIND_DEPTH_STENCIL | D3D11_BIND_SHADER_RESOURCE;
  435. else
  436. desc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
  437. mDXGIColorFormat = D3D11Mappings::getShaderResourceDepthStencilPF(closestFormat);
  438. mDXGIDepthStencilFormat = d3dPF;
  439. }
  440. else
  441. {
  442. desc.Usage = D3D11Mappings::getUsage((GpuBufferUsage)usage);
  443. desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
  444. desc.CPUAccessFlags = D3D11Mappings::getAccessFlags((GpuBufferUsage)usage);
  445. // Determine total number of mipmaps including main one (d3d11 convention)
  446. desc.MipLevels = (numMips == MIP_UNLIMITED || (1U << numMips)
  447. > std::max(std::max(width, height), depth)) ? 0 : numMips + 1;
  448. }
  449. if ((usage & TU_LOADSTORE) != 0)
  450. desc.BindFlags |= D3D11_BIND_UNORDERED_ACCESS;
  451. // Create the texture
  452. D3D11RenderAPI* rs = static_cast<D3D11RenderAPI*>(RenderAPICore::instancePtr());
  453. D3D11Device& device = rs->getPrimaryDevice();
  454. hr = device.getD3D11Device()->CreateTexture3D(&desc, nullptr, &m3DTex);
  455. // Check result and except if failed
  456. if (FAILED(hr) || device.hasError())
  457. {
  458. String errorDescription = device.getErrorDescription();
  459. BS_EXCEPT(RenderingAPIException, "Error creating texture\nError Description:" + errorDescription);
  460. }
  461. hr = m3DTex->QueryInterface(__uuidof(ID3D11Resource), (void **)&mTex);
  462. if(FAILED(hr) || device.hasError())
  463. {
  464. String errorDescription = device.getErrorDescription();
  465. BS_EXCEPT(RenderingAPIException, "Can't get base texture\nError Description:" + errorDescription);
  466. }
  467. // Create texture view
  468. m3DTex->GetDesc(&desc);
  469. if (mProperties.getNumMipmaps() != (desc.MipLevels - 1))
  470. {
  471. BS_EXCEPT(RenderingAPIException, "Driver returned different number of mip maps than requested. " \
  472. "Requested: " + toString(mProperties.getNumMipmaps()) + ". Got: " + toString(desc.MipLevels - 1) + ".");
  473. }
  474. mDXGIFormat = desc.Format;
  475. if ((usage & TU_DEPTHSTENCIL) == 0 || readableDepth)
  476. {
  477. TEXTURE_VIEW_DESC viewDesc;
  478. viewDesc.mostDetailMip = 0;
  479. viewDesc.numMips = desc.MipLevels;
  480. viewDesc.firstArraySlice = 0;
  481. viewDesc.numArraySlices = 1;
  482. viewDesc.usage = GVU_DEFAULT;
  483. SPtr<TextureCore> thisPtr = std::static_pointer_cast<TextureCore>(getThisPtr());
  484. mShaderResourceView = bs_shared_ptr<D3D11TextureView>(new (bs_alloc<D3D11TextureView>()) D3D11TextureView(thisPtr, viewDesc));
  485. }
  486. }
  487. void* D3D11TextureCore::map(ID3D11Resource* res, D3D11_MAP flags, UINT32 mipLevel, UINT32 face, UINT32& rowPitch, UINT32& slicePitch)
  488. {
  489. D3D11_MAPPED_SUBRESOURCE pMappedResource;
  490. pMappedResource.pData = nullptr;
  491. mipLevel = Math::clamp(mipLevel, (UINT32)mipLevel, mProperties.getNumMipmaps());
  492. face = Math::clamp(face, (UINT32)0, mProperties.getNumFaces() - 1);
  493. if (mProperties.getTextureType() == TEX_TYPE_3D)
  494. face = 0;
  495. D3D11RenderAPI* rs = static_cast<D3D11RenderAPI*>(RenderAPICore::instancePtr());
  496. D3D11Device& device = rs->getPrimaryDevice();
  497. mLockedSubresourceIdx = D3D11CalcSubresource(mipLevel, face, mProperties.getNumMipmaps() + 1);
  498. device.getImmediateContext()->Map(res, mLockedSubresourceIdx, flags, 0, &pMappedResource);
  499. if (device.hasError())
  500. {
  501. String errorDescription = device.getErrorDescription();
  502. BS_EXCEPT(RenderingAPIException, "D3D11 device cannot map texture\nError Description:" + errorDescription);
  503. }
  504. UINT32 bytesPerPixel = PixelUtil::getNumElemBytes(mProperties.getFormat());
  505. rowPitch = pMappedResource.RowPitch / bytesPerPixel;
  506. slicePitch = pMappedResource.DepthPitch / bytesPerPixel;
  507. return pMappedResource.pData;
  508. }
  509. void D3D11TextureCore::unmap(ID3D11Resource* res)
  510. {
  511. D3D11RenderAPI* rs = static_cast<D3D11RenderAPI*>(RenderAPICore::instancePtr());
  512. D3D11Device& device = rs->getPrimaryDevice();
  513. device.getImmediateContext()->Unmap(res, mLockedSubresourceIdx);
  514. if (device.hasError())
  515. {
  516. String errorDescription = device.getErrorDescription();
  517. BS_EXCEPT(RenderingAPIException, "D3D11 device unmap resource\nError Description:" + errorDescription);
  518. }
  519. }
  520. void* D3D11TextureCore::mapstagingbuffer(D3D11_MAP flags, UINT32 mipLevel, UINT32 face, UINT32& rowPitch, UINT32& slicePitch)
  521. {
  522. // Note: I am creating and destroying a staging resource every time a texture is read.
  523. // Consider offering a flag on init that will keep this active all the time (at the cost of double memory).
  524. // Reading is slow operation anyway so I don't believe doing it as we are now will influence it much.
  525. if(!mStagingBuffer)
  526. createStagingBuffer();
  527. D3D11RenderAPI* rs = static_cast<D3D11RenderAPI*>(RenderAPICore::instancePtr());
  528. D3D11Device& device = rs->getPrimaryDevice();
  529. device.getImmediateContext()->CopyResource(mStagingBuffer, mTex);
  530. return map(mStagingBuffer, flags, face, mipLevel, rowPitch, slicePitch);
  531. }
  532. void D3D11TextureCore::unmapstagingbuffer()
  533. {
  534. unmap(mStagingBuffer);
  535. SAFE_RELEASE(mStagingBuffer);
  536. }
  537. void* D3D11TextureCore::mapstaticbuffer(PixelData lock, UINT32 mipLevel, UINT32 face)
  538. {
  539. UINT32 sizeOfImage = lock.getConsecutiveSize();
  540. mLockedSubresourceIdx = D3D11CalcSubresource(mipLevel, face, mProperties.getNumMipmaps()+1);
  541. mStaticBuffer = bs_new<PixelData>(lock.getWidth(), lock.getHeight(), lock.getDepth(), lock.getFormat());
  542. mStaticBuffer->allocateInternalBuffer();
  543. return mStaticBuffer->getData();
  544. }
  545. void D3D11TextureCore::unmapstaticbuffer()
  546. {
  547. UINT32 rowWidth = D3D11Mappings::getSizeInBytes(mStaticBuffer->getFormat(), mStaticBuffer->getWidth());
  548. UINT32 sliceWidth = D3D11Mappings::getSizeInBytes(mStaticBuffer->getFormat(), mStaticBuffer->getWidth(), mStaticBuffer->getHeight());
  549. D3D11RenderAPI* rs = static_cast<D3D11RenderAPI*>(RenderAPICore::instancePtr());
  550. D3D11Device& device = rs->getPrimaryDevice();
  551. device.getImmediateContext()->UpdateSubresource(mTex, mLockedSubresourceIdx, nullptr, mStaticBuffer->getData(), rowWidth, sliceWidth);
  552. if (device.hasError())
  553. {
  554. String errorDescription = device.getErrorDescription();
  555. BS_EXCEPT(RenderingAPIException, "D3D11 device cannot map texture\nError Description:" + errorDescription);
  556. }
  557. if(mStaticBuffer != nullptr)
  558. bs_delete(mStaticBuffer);
  559. }
  560. ID3D11ShaderResourceView* D3D11TextureCore::getSRV() const
  561. {
  562. return mShaderResourceView->getSRV();
  563. }
  564. void D3D11TextureCore::createStagingBuffer()
  565. {
  566. D3D11RenderAPI* rs = static_cast<D3D11RenderAPI*>(RenderAPICore::instancePtr());
  567. D3D11Device& device = rs->getPrimaryDevice();
  568. switch (mProperties.getTextureType())
  569. {
  570. case TEX_TYPE_1D:
  571. {
  572. D3D11_TEXTURE1D_DESC desc;
  573. m1DTex->GetDesc(&desc);
  574. desc.BindFlags = 0;
  575. desc.MiscFlags = 0;
  576. desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE | D3D11_CPU_ACCESS_READ;
  577. desc.Usage = D3D11_USAGE_STAGING;
  578. device.getD3D11Device()->CreateTexture1D(&desc, nullptr, (ID3D11Texture1D**)(&mStagingBuffer));
  579. }
  580. break;
  581. case TEX_TYPE_2D:
  582. case TEX_TYPE_CUBE_MAP:
  583. {
  584. D3D11_TEXTURE2D_DESC desc;
  585. m2DTex->GetDesc(&desc);
  586. desc.BindFlags = 0;
  587. desc.MiscFlags = 0;
  588. desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE | D3D11_CPU_ACCESS_READ;
  589. desc.Usage = D3D11_USAGE_STAGING;
  590. device.getD3D11Device()->CreateTexture2D(&desc, nullptr, (ID3D11Texture2D**)(&mStagingBuffer));
  591. }
  592. break;
  593. case TEX_TYPE_3D:
  594. {
  595. D3D11_TEXTURE3D_DESC desc;
  596. m3DTex->GetDesc(&desc);
  597. desc.BindFlags = 0;
  598. desc.MiscFlags = 0;
  599. desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE | D3D11_CPU_ACCESS_READ;
  600. desc.Usage = D3D11_USAGE_STAGING;
  601. device.getD3D11Device()->CreateTexture3D(&desc, nullptr, (ID3D11Texture3D**)(&mStagingBuffer));
  602. }
  603. break;
  604. }
  605. }
  606. SPtr<TextureView> D3D11TextureCore::createView(const SPtr<TextureCore>& texture, const TEXTURE_VIEW_DESC& desc)
  607. {
  608. return bs_shared_ptr<D3D11TextureView>(new (bs_alloc<D3D11TextureView>()) D3D11TextureView(texture, desc));
  609. }
  610. }