BsTexture.cpp 18 KB

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