BsTexture.cpp 14 KB

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