BsTexture.cpp 17 KB

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