BsTexture.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #include "Image/BsTexture.h"
  4. #include "RTTI/BsTextureRTTI.h"
  5. #include "FileSystem/BsDataStream.h"
  6. #include "Error/BsException.h"
  7. #include "Debug/BsDebug.h"
  8. #include "CoreThread/BsCoreThread.h"
  9. #include "Threading/BsAsyncOp.h"
  10. #include "Resources/BsResources.h"
  11. #include "Image/BsPixelUtil.h"
  12. namespace bs
  13. {
  14. TextureProperties::TextureProperties()
  15. { }
  16. TextureProperties::TextureProperties(const TEXTURE_DESC& desc)
  17. :mDesc(desc)
  18. {
  19. }
  20. bool TextureProperties::hasAlpha() const
  21. {
  22. return PixelUtil::hasAlpha(mDesc.format);
  23. }
  24. UINT32 TextureProperties::getNumFaces() const
  25. {
  26. UINT32 facesPerSlice = getTextureType() == TEX_TYPE_CUBE_MAP ? 6 : 1;
  27. return facesPerSlice * mDesc.numArraySlices;
  28. }
  29. void TextureProperties::mapFromSubresourceIdx(UINT32 subresourceIdx, UINT32& face, UINT32& mip) const
  30. {
  31. UINT32 numMipmaps = getNumMipmaps() + 1;
  32. face = Math::floorToInt((subresourceIdx) / (float)numMipmaps);
  33. mip = subresourceIdx % numMipmaps;
  34. }
  35. UINT32 TextureProperties::mapToSubresourceIdx(UINT32 face, UINT32 mip) const
  36. {
  37. return face * (getNumMipmaps() + 1) + mip;
  38. }
  39. SPtr<PixelData> TextureProperties::allocBuffer(UINT32 face, UINT32 mipLevel) const
  40. {
  41. UINT32 width = getWidth();
  42. UINT32 height = getHeight();
  43. UINT32 depth = getDepth();
  44. for (UINT32 j = 0; j < mipLevel; j++)
  45. {
  46. if (width != 1) width /= 2;
  47. if (height != 1) height /= 2;
  48. if (depth != 1) depth /= 2;
  49. }
  50. SPtr<PixelData> dst = bs_shared_ptr_new<PixelData>(width, height, depth, getFormat());
  51. dst->allocateInternalBuffer();
  52. return dst;
  53. }
  54. Texture::Texture()
  55. {
  56. }
  57. Texture::Texture(const TEXTURE_DESC& desc)
  58. :mProperties(desc)
  59. {
  60. }
  61. Texture::Texture(const TEXTURE_DESC& desc, const SPtr<PixelData>& pixelData)
  62. : mProperties(desc), mInitData(pixelData)
  63. {
  64. if (mInitData != nullptr)
  65. mInitData->_lock();
  66. }
  67. void Texture::initialize()
  68. {
  69. mSize = calculateSize();
  70. // Allocate CPU buffers if needed
  71. if ((mProperties.getUsage() & TU_CPUCACHED) != 0)
  72. {
  73. createCPUBuffers();
  74. if (mInitData != nullptr)
  75. updateCPUBuffers(0, *mInitData);
  76. }
  77. Resource::initialize();
  78. }
  79. SPtr<ct::CoreObject> Texture::createCore() const
  80. {
  81. const TextureProperties& props = getProperties();
  82. SPtr<ct::CoreObject> coreObj = ct::TextureManager::instance().createTextureInternal(props.mDesc, mInitData);
  83. if ((mProperties.getUsage() & TU_CPUCACHED) == 0)
  84. mInitData = nullptr;
  85. return coreObj;
  86. }
  87. AsyncOp Texture::writeData(const SPtr<PixelData>& data, UINT32 face, UINT32 mipLevel, bool discardEntireBuffer)
  88. {
  89. UINT32 subresourceIdx = mProperties.mapToSubresourceIdx(face, mipLevel);
  90. updateCPUBuffers(subresourceIdx, *data);
  91. data->_lock();
  92. std::function<void(const SPtr<ct::Texture>&, UINT32, UINT32, const SPtr<PixelData>&, bool, AsyncOp&)> func =
  93. [&](const SPtr<ct::Texture>& texture, UINT32 _face, UINT32 _mipLevel, const SPtr<PixelData>& _pixData,
  94. bool _discardEntireBuffer, AsyncOp& asyncOp)
  95. {
  96. texture->writeData(*_pixData, _mipLevel, _face, _discardEntireBuffer);
  97. _pixData->_unlock();
  98. asyncOp._completeOperation();
  99. };
  100. return gCoreThread().queueReturnCommand(std::bind(func, getCore(), face, mipLevel,
  101. data, discardEntireBuffer, std::placeholders::_1));
  102. }
  103. AsyncOp Texture::readData(const SPtr<PixelData>& data, UINT32 face, UINT32 mipLevel)
  104. {
  105. data->_lock();
  106. std::function<void(const SPtr<ct::Texture>&, UINT32, UINT32, const SPtr<PixelData>&, AsyncOp&)> func =
  107. [&](const SPtr<ct::Texture>& texture, UINT32 _face, UINT32 _mipLevel, const SPtr<PixelData>& _pixData,
  108. AsyncOp& asyncOp)
  109. {
  110. // Make sure any queued command start executing before reading
  111. ct::RenderAPI::instance().submitCommandBuffer(nullptr);
  112. texture->readData(*_pixData, _mipLevel, _face);
  113. _pixData->_unlock();
  114. asyncOp._completeOperation();
  115. };
  116. return gCoreThread().queueReturnCommand(std::bind(func, getCore(), face, mipLevel,
  117. data, std::placeholders::_1));
  118. }
  119. UINT32 Texture::calculateSize() const
  120. {
  121. return mProperties.getNumFaces() * PixelUtil::getMemorySize(mProperties.getWidth(),
  122. mProperties.getHeight(), mProperties.getDepth(), mProperties.getFormat());
  123. }
  124. void Texture::updateCPUBuffers(UINT32 subresourceIdx, const PixelData& pixelData)
  125. {
  126. if ((mProperties.getUsage() & TU_CPUCACHED) == 0)
  127. return;
  128. if (subresourceIdx >= (UINT32)mCPUSubresourceData.size())
  129. {
  130. LOGERR("Invalid subresource index: " + toString(subresourceIdx) + ". Supported range: 0 .. " + toString((UINT32)mCPUSubresourceData.size()));
  131. return;
  132. }
  133. UINT32 mipLevel;
  134. UINT32 face;
  135. mProperties.mapFromSubresourceIdx(subresourceIdx, face, mipLevel);
  136. UINT32 mipWidth, mipHeight, mipDepth;
  137. PixelUtil::getSizeForMipLevel(mProperties.getWidth(), mProperties.getHeight(), mProperties.getDepth(),
  138. mipLevel, mipWidth, mipHeight, mipDepth);
  139. if (pixelData.getWidth() != mipWidth || pixelData.getHeight() != mipHeight ||
  140. pixelData.getDepth() != mipDepth || pixelData.getFormat() != mProperties.getFormat())
  141. {
  142. LOGERR("Provided buffer is not of valid dimensions or format in order to update this texture.");
  143. return;
  144. }
  145. if (mCPUSubresourceData[subresourceIdx]->getSize() != pixelData.getSize())
  146. BS_EXCEPT(InternalErrorException, "Buffer sizes don't match.");
  147. UINT8* dest = mCPUSubresourceData[subresourceIdx]->getData();
  148. UINT8* src = pixelData.getData();
  149. memcpy(dest, src, pixelData.getSize());
  150. }
  151. void Texture::readCachedData(PixelData& dest, UINT32 face, UINT32 mipLevel)
  152. {
  153. if ((mProperties.getUsage() & TU_CPUCACHED) == 0)
  154. {
  155. LOGERR("Attempting to read CPU data from a texture that is created without CPU caching.");
  156. return;
  157. }
  158. UINT32 mipWidth, mipHeight, mipDepth;
  159. PixelUtil::getSizeForMipLevel(mProperties.getWidth(), mProperties.getHeight(), mProperties.getDepth(),
  160. mipLevel, mipWidth, mipHeight, mipDepth);
  161. if (dest.getWidth() != mipWidth || dest.getHeight() != mipHeight ||
  162. dest.getDepth() != mipDepth || dest.getFormat() != mProperties.getFormat())
  163. {
  164. LOGERR("Provided buffer is not of valid dimensions or format in order to read from this texture.");
  165. return;
  166. }
  167. UINT32 subresourceIdx = mProperties.mapToSubresourceIdx(face, mipLevel);
  168. if (subresourceIdx >= (UINT32)mCPUSubresourceData.size())
  169. {
  170. LOGERR("Invalid subresource index: " + toString(subresourceIdx) + ". Supported range: 0 .. " + toString((UINT32)mCPUSubresourceData.size()));
  171. return;
  172. }
  173. if (mCPUSubresourceData[subresourceIdx]->getSize() != dest.getSize())
  174. BS_EXCEPT(InternalErrorException, "Buffer sizes don't match.");
  175. UINT8* srcPtr = mCPUSubresourceData[subresourceIdx]->getData();
  176. UINT8* destPtr = dest.getData();
  177. memcpy(destPtr, srcPtr, dest.getSize());
  178. }
  179. void Texture::createCPUBuffers()
  180. {
  181. UINT32 numFaces = mProperties.getNumFaces();
  182. UINT32 numMips = mProperties.getNumMipmaps() + 1;
  183. UINT32 numSubresources = numFaces * numMips;
  184. mCPUSubresourceData.resize(numSubresources);
  185. for (UINT32 i = 0; i < numFaces; i++)
  186. {
  187. UINT32 curWidth = mProperties.getWidth();
  188. UINT32 curHeight = mProperties.getHeight();
  189. UINT32 curDepth = mProperties.getDepth();
  190. for (UINT32 j = 0; j < numMips; j++)
  191. {
  192. UINT32 subresourceIdx = mProperties.mapToSubresourceIdx(i, j);
  193. mCPUSubresourceData[subresourceIdx] = bs_shared_ptr_new<PixelData>(curWidth, curHeight, curDepth, mProperties.getFormat());
  194. mCPUSubresourceData[subresourceIdx]->allocateInternalBuffer();
  195. if (curWidth > 1)
  196. curWidth = curWidth / 2;
  197. if (curHeight > 1)
  198. curHeight = curHeight / 2;
  199. if (curDepth > 1)
  200. curDepth = curDepth / 2;
  201. }
  202. }
  203. }
  204. SPtr<ct::Texture> Texture::getCore() const
  205. {
  206. return std::static_pointer_cast<ct::Texture>(mCoreSpecific);
  207. }
  208. /************************************************************************/
  209. /* SERIALIZATION */
  210. /************************************************************************/
  211. RTTITypeBase* Texture::getRTTIStatic()
  212. {
  213. return TextureRTTI::instance();
  214. }
  215. RTTITypeBase* Texture::getRTTI() const
  216. {
  217. return Texture::getRTTIStatic();
  218. }
  219. /************************************************************************/
  220. /* STATICS */
  221. /************************************************************************/
  222. HTexture Texture::create(const TEXTURE_DESC& desc)
  223. {
  224. SPtr<Texture> texturePtr = _createPtr(desc);
  225. return static_resource_cast<Texture>(gResources()._createResourceHandle(texturePtr));
  226. }
  227. HTexture Texture::create(const SPtr<PixelData>& pixelData, int usage, bool hwGammaCorrection)
  228. {
  229. SPtr<Texture> texturePtr = _createPtr(pixelData, usage, hwGammaCorrection);
  230. return static_resource_cast<Texture>(gResources()._createResourceHandle(texturePtr));
  231. }
  232. SPtr<Texture> Texture::_createPtr(const TEXTURE_DESC& desc)
  233. {
  234. return TextureManager::instance().createTexture(desc);
  235. }
  236. SPtr<Texture> Texture::_createPtr(const SPtr<PixelData>& pixelData, int usage, bool hwGammaCorrection)
  237. {
  238. TEXTURE_DESC desc;
  239. desc.type = pixelData->getDepth() > 1 ? TEX_TYPE_3D : TEX_TYPE_2D;
  240. desc.width = pixelData->getWidth();
  241. desc.height = pixelData->getHeight();
  242. desc.depth = pixelData->getDepth();
  243. desc.format = pixelData->getFormat();
  244. desc.usage = usage;
  245. desc.hwGamma = hwGammaCorrection;
  246. return TextureManager::instance().createTexture(desc, pixelData);
  247. }
  248. namespace ct
  249. {
  250. SPtr<Texture> Texture::WHITE;
  251. SPtr<Texture> Texture::BLACK;
  252. SPtr<Texture> Texture::NORMAL;
  253. Texture::Texture(const TEXTURE_DESC& desc, const SPtr<PixelData>& initData, GpuDeviceFlags deviceMask)
  254. :mProperties(desc), mInitData(initData)
  255. { }
  256. void Texture::initialize()
  257. {
  258. if (mInitData != nullptr)
  259. {
  260. writeData(*mInitData, 0, 0, true);
  261. mInitData->_unlock();
  262. mInitData = nullptr;
  263. }
  264. CoreObject::initialize();
  265. }
  266. void Texture::writeData(const PixelData& src, UINT32 mipLevel, UINT32 face, bool discardEntireBuffer,
  267. UINT32 queueIdx)
  268. {
  269. THROW_IF_NOT_CORE_THREAD;
  270. if(discardEntireBuffer)
  271. {
  272. if((mProperties.getUsage() & TU_DYNAMIC) == 0)
  273. {
  274. // Buffer discard is enabled but buffer was not created as dynamic. Disabling discard.
  275. discardEntireBuffer = false;
  276. }
  277. }
  278. writeDataImpl(src, mipLevel, face, discardEntireBuffer, queueIdx);
  279. }
  280. void Texture::readData(PixelData& dest, UINT32 mipLevel, UINT32 face, UINT32 deviceIdx, UINT32 queueIdx)
  281. {
  282. THROW_IF_NOT_CORE_THREAD;
  283. PixelData& pixelData = static_cast<PixelData&>(dest);
  284. UINT32 mipWidth, mipHeight, mipDepth;
  285. PixelUtil::getSizeForMipLevel(mProperties.getWidth(), mProperties.getHeight(), mProperties.getDepth(),
  286. mipLevel, mipWidth, mipHeight, mipDepth);
  287. if (pixelData.getWidth() != mipWidth || pixelData.getHeight() != mipHeight ||
  288. pixelData.getDepth() != mipDepth || pixelData.getFormat() != mProperties.getFormat())
  289. {
  290. LOGERR("Provided buffer is not of valid dimensions or format in order to read from this texture.");
  291. return;
  292. }
  293. readDataImpl(pixelData, mipLevel, face, deviceIdx, queueIdx);
  294. }
  295. PixelData Texture::lock(GpuLockOptions options, UINT32 mipLevel, UINT32 face, UINT32 deviceIdx, UINT32 queueIdx)
  296. {
  297. THROW_IF_NOT_CORE_THREAD;
  298. if (mipLevel > mProperties.getNumMipmaps())
  299. {
  300. LOGERR("Invalid mip level: " + toString(mipLevel) + ". Min is 0, max is " + toString(mProperties.getNumMipmaps()));
  301. return PixelData(0, 0, 0, PF_UNKNOWN);
  302. }
  303. if (face >= mProperties.getNumFaces())
  304. {
  305. LOGERR("Invalid face index: " + toString(face) + ". Min is 0, max is " + toString(mProperties.getNumFaces()));
  306. return PixelData(0, 0, 0, PF_UNKNOWN);
  307. }
  308. return lockImpl(options, mipLevel, face, deviceIdx, queueIdx);
  309. }
  310. void Texture::unlock()
  311. {
  312. THROW_IF_NOT_CORE_THREAD;
  313. unlockImpl();
  314. }
  315. void Texture::copy(const SPtr<Texture>& target, UINT32 srcFace, UINT32 srcMipLevel, UINT32 dstFace,
  316. UINT32 dstMipLevel, const SPtr<CommandBuffer>& commandBuffer)
  317. {
  318. THROW_IF_NOT_CORE_THREAD;
  319. if (target->mProperties.getTextureType() != mProperties.getTextureType())
  320. {
  321. LOGERR("Source and destination textures must be of same type and must have the same usage and type.");
  322. return;
  323. }
  324. if (mProperties.getFormat() != target->mProperties.getFormat()) // Note: It might be okay to use different formats of the same size
  325. {
  326. LOGERR("Source and destination texture formats must match.");
  327. return;
  328. }
  329. if (target->mProperties.getNumSamples() > 0 && mProperties.getNumSamples() != target->mProperties.getNumSamples())
  330. {
  331. LOGERR("When copying to a multisampled texture, source texture must have the same number of samples.");
  332. return;
  333. }
  334. if (dstFace >= mProperties.getNumFaces())
  335. {
  336. LOGERR("Invalid destination face index");
  337. return;
  338. }
  339. if (srcFace >= target->mProperties.getNumFaces())
  340. {
  341. LOGERR("Invalid destination face index");
  342. return;
  343. }
  344. if (srcMipLevel > mProperties.getNumMipmaps())
  345. {
  346. LOGERR("Source mip level out of range. Valid range is [0, " + toString(mProperties.getNumMipmaps()) + "]");
  347. return;
  348. }
  349. if (dstMipLevel > target->mProperties.getNumMipmaps())
  350. {
  351. LOGERR("Destination mip level out of range. Valid range is [0, " + toString(target->mProperties.getNumMipmaps()) + "]");
  352. return;
  353. }
  354. UINT32 srcMipWidth = mProperties.getWidth() >> srcMipLevel;
  355. UINT32 srcMipHeight = mProperties.getHeight() >> srcMipLevel;
  356. UINT32 srcMipDepth = mProperties.getDepth() >> srcMipLevel;
  357. UINT32 dstMipWidth = target->mProperties.getWidth() >> dstMipLevel;
  358. UINT32 dstMipHeight = target->mProperties.getHeight() >> dstMipLevel;
  359. UINT32 dstMipDepth = target->mProperties.getDepth() >> dstMipLevel;
  360. if (srcMipWidth != dstMipWidth || srcMipHeight != dstMipHeight || srcMipDepth != dstMipDepth)
  361. {
  362. LOGERR("Source and destination sizes must match");
  363. return;
  364. }
  365. copyImpl(srcFace, srcMipLevel, dstFace, dstMipLevel, target, commandBuffer);
  366. }
  367. /************************************************************************/
  368. /* TEXTURE VIEW */
  369. /************************************************************************/
  370. SPtr<TextureView> Texture::createView(const TEXTURE_VIEW_DESC& desc)
  371. {
  372. return bs_shared_ptr<TextureView>(new (bs_alloc<TextureView>()) TextureView(desc));
  373. }
  374. void Texture::clearBufferViews()
  375. {
  376. mTextureViews.clear();
  377. }
  378. SPtr<TextureView> Texture::requestView(UINT32 mostDetailMip, UINT32 numMips, UINT32 firstArraySlice,
  379. UINT32 numArraySlices, GpuViewUsage usage)
  380. {
  381. THROW_IF_NOT_CORE_THREAD;
  382. const TextureProperties& texProps = getProperties();
  383. TEXTURE_VIEW_DESC key;
  384. key.mostDetailMip = mostDetailMip;
  385. key.numMips = numMips == 0 ? (texProps.getNumMipmaps() + 1) : numMips;
  386. key.firstArraySlice = firstArraySlice;
  387. key.numArraySlices = numArraySlices == 0 ? texProps.getNumFaces() : numArraySlices;
  388. key.usage = usage;
  389. auto iterFind = mTextureViews.find(key);
  390. if (iterFind == mTextureViews.end())
  391. {
  392. mTextureViews[key] = createView(key);
  393. iterFind = mTextureViews.find(key);
  394. }
  395. return iterFind->second;
  396. }
  397. /************************************************************************/
  398. /* STATICS */
  399. /************************************************************************/
  400. SPtr<Texture> Texture::create(const TEXTURE_DESC& desc, GpuDeviceFlags deviceMask)
  401. {
  402. return TextureManager::instance().createTexture(desc, deviceMask);
  403. }
  404. SPtr<Texture> Texture::create(const SPtr<PixelData>& pixelData, int usage, bool hwGammaCorrection,
  405. GpuDeviceFlags deviceMask)
  406. {
  407. TEXTURE_DESC desc;
  408. desc.type = pixelData->getDepth() > 1 ? TEX_TYPE_3D : TEX_TYPE_2D;
  409. desc.width = pixelData->getWidth();
  410. desc.height = pixelData->getHeight();
  411. desc.depth = pixelData->getDepth();
  412. desc.format = pixelData->getFormat();
  413. desc.usage = usage;
  414. desc.hwGamma = hwGammaCorrection;
  415. SPtr<Texture> newTex = TextureManager::instance().createTextureInternal(desc, pixelData, deviceMask);
  416. newTex->initialize();
  417. return newTex;
  418. }
  419. }
  420. }