BsD3D11Texture.cpp 25 KB

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