BsTexture.cpp 17 KB

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