BsD3D11Texture.cpp 25 KB

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