BsD3D11Texture.cpp 26 KB

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