BsD3D11Texture.cpp 25 KB

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