BsMesh.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. #include "BsMesh.h"
  2. #include "BsMeshRTTI.h"
  3. #include "BsMeshData.h"
  4. #include "BsVector2.h"
  5. #include "BsVector3.h"
  6. #include "BsDebug.h"
  7. #include "BsHardwareBufferManager.h"
  8. #include "BsMeshManager.h"
  9. #include "BsCoreThread.h"
  10. #include "BsAsyncOp.h"
  11. #include "BsAABox.h"
  12. #include "BsVertexDataDesc.h"
  13. #include "BsResources.h"
  14. #include "BsFrameAlloc.h"
  15. namespace BansheeEngine
  16. {
  17. MeshCore::MeshCore(UINT32 numVertices, UINT32 numIndices, const VertexDataDescPtr& vertexDesc,
  18. const Vector<SubMesh>& subMeshes, MeshBufferType bufferType, IndexType indexType, MeshDataPtr initialMeshData)
  19. :MeshCoreBase(numVertices, numIndices, subMeshes), mVertexData(nullptr), mIndexBuffer(nullptr),
  20. mVertexDesc(vertexDesc), mBufferType(bufferType), mIndexType(indexType), mTempInitialMeshData(initialMeshData)
  21. { }
  22. void MeshCore::initialize()
  23. {
  24. THROW_IF_NOT_CORE_THREAD;
  25. mIndexBuffer = HardwareBufferCoreManager::instance().createIndexBuffer(mIndexType,
  26. mProperties.mNumIndices, mBufferType == MeshBufferType::Dynamic ? GBU_DYNAMIC : GBU_STATIC);
  27. mVertexData = std::shared_ptr<VertexData>(bs_new<VertexData, PoolAlloc>());
  28. mVertexData->vertexCount = mProperties.mNumVertices;
  29. mVertexData->vertexDeclaration = mVertexDesc->createDeclaration();
  30. for (UINT32 i = 0; i <= mVertexDesc->getMaxStreamIdx(); i++)
  31. {
  32. if (!mVertexDesc->hasStream(i))
  33. continue;
  34. SPtr<VertexBufferCore> vertexBuffer = HardwareBufferCoreManager::instance().createVertexBuffer(
  35. mVertexData->vertexDeclaration->getVertexSize(i),
  36. mVertexData->vertexCount,
  37. mBufferType == MeshBufferType::Dynamic ? GBU_DYNAMIC : GBU_STATIC);
  38. mVertexData->setBuffer(i, vertexBuffer);
  39. }
  40. // TODO Low priority - DX11 (and maybe OpenGL)? allow an optimization that allows you to set
  41. // buffer data upon buffer construction, instead of setting it in a second step like I do here
  42. if (mTempInitialMeshData != nullptr)
  43. {
  44. writeSubresource(0, *mTempInitialMeshData, mBufferType == MeshBufferType::Dynamic);
  45. mTempInitialMeshData = nullptr;
  46. }
  47. MeshCoreBase::initialize();
  48. }
  49. void MeshCore::destroy()
  50. {
  51. THROW_IF_NOT_CORE_THREAD;
  52. if (mVertexData != nullptr)
  53. {
  54. for (UINT32 i = 0; i < mVertexData->getBufferCount(); i++)
  55. {
  56. if (mVertexData->getBuffer(i) != nullptr)
  57. mVertexData->getBuffer(i)->destroy();
  58. }
  59. }
  60. if (mIndexBuffer != nullptr)
  61. mIndexBuffer->destroy();
  62. mVertexData = nullptr;
  63. mIndexBuffer = nullptr;
  64. mVertexDesc = nullptr;
  65. mTempInitialMeshData = nullptr;
  66. MeshCoreBase::destroy();
  67. }
  68. std::shared_ptr<VertexData> MeshCore::getVertexData() const
  69. {
  70. THROW_IF_NOT_CORE_THREAD;
  71. return mVertexData;
  72. }
  73. SPtr<IndexBufferCore> MeshCore::getIndexBuffer() const
  74. {
  75. THROW_IF_NOT_CORE_THREAD;
  76. return mIndexBuffer;
  77. }
  78. void MeshCore::writeSubresource(UINT32 subresourceIdx, const MeshData& meshData, bool discardEntireBuffer, bool performUpdateBounds)
  79. {
  80. THROW_IF_NOT_CORE_THREAD;
  81. if (discardEntireBuffer)
  82. {
  83. if (mBufferType == MeshBufferType::Static)
  84. {
  85. LOGWRN("Buffer discard is enabled but buffer was not created as dynamic. Disabling discard.");
  86. discardEntireBuffer = false;
  87. }
  88. }
  89. else
  90. {
  91. if (mBufferType == MeshBufferType::Dynamic)
  92. {
  93. LOGWRN("Buffer discard is not enabled but buffer was created as dynamic. Enabling discard.");
  94. discardEntireBuffer = true;
  95. }
  96. }
  97. // Indices
  98. const IndexBufferProperties& ibProps = mIndexBuffer->getProperties();
  99. UINT32 indicesSize = meshData.getIndexBufferSize();
  100. UINT8* srcIdxData = meshData.getIndexData();
  101. if (meshData.getIndexElementSize() != ibProps.getIndexSize())
  102. {
  103. BS_EXCEPT(InvalidParametersException, "Provided index size doesn't match meshes index size. Needed: " +
  104. toString(ibProps.getIndexSize()) + ". Got: " + toString(meshData.getIndexElementSize()));
  105. }
  106. if (indicesSize > mIndexBuffer->getSizeInBytes())
  107. BS_EXCEPT(InvalidParametersException, "Index buffer values are being written out of valid range.");
  108. mIndexBuffer->writeData(0, indicesSize, srcIdxData, discardEntireBuffer ? BufferWriteType::Discard : BufferWriteType::Normal);
  109. // Vertices
  110. for (UINT32 i = 0; i <= mVertexDesc->getMaxStreamIdx(); i++)
  111. {
  112. if (!mVertexDesc->hasStream(i))
  113. continue;
  114. if (!meshData.getVertexDesc()->hasStream(i))
  115. continue;
  116. // Ensure both have the same sized vertices
  117. UINT32 myVertSize = mVertexDesc->getVertexStride(i);
  118. UINT32 otherVertSize = meshData.getVertexDesc()->getVertexStride(i);
  119. if (myVertSize != otherVertSize)
  120. {
  121. BS_EXCEPT(InvalidParametersException, "Provided vertex size for stream " + toString(i) + " doesn't match meshes vertex size. Needed: " +
  122. toString(myVertSize) + ". Got: " + toString(otherVertSize));
  123. }
  124. SPtr<VertexBufferCore> vertexBuffer = mVertexData->getBuffer(i);
  125. const VertexBufferProperties& vbProps = vertexBuffer->getProperties();
  126. UINT32 bufferSize = meshData.getStreamSize(i);
  127. UINT8* srcVertBufferData = meshData.getStreamData(i);
  128. if (bufferSize > vertexBuffer->getSizeInBytes())
  129. BS_EXCEPT(InvalidParametersException, "Vertex buffer values for stream \"" + toString(i) + "\" are being written out of valid range.");
  130. if (RenderSystem::instance().getVertexColorFlipRequired())
  131. {
  132. UINT8* bufferCopy = (UINT8*)bs_alloc(bufferSize);
  133. memcpy(bufferCopy, srcVertBufferData, bufferSize); // TODO Low priority - Attempt to avoid this copy
  134. UINT32 vertexStride = meshData.getVertexDesc()->getVertexStride(i);
  135. for (INT32 semanticIdx = 0; semanticIdx < VertexBuffer::MAX_SEMANTIC_IDX; semanticIdx++)
  136. {
  137. if (!meshData.getVertexDesc()->hasElement(VES_COLOR, semanticIdx, i))
  138. continue;
  139. UINT8* colorData = bufferCopy + mVertexDesc->getElementOffsetFromStream(VES_COLOR, semanticIdx, i);
  140. for (UINT32 j = 0; j < mVertexData->vertexCount; j++)
  141. {
  142. UINT32* curColor = (UINT32*)colorData;
  143. (*curColor) = ((*curColor) & 0xFF00FF00) | ((*curColor >> 16) & 0x000000FF) | ((*curColor << 16) & 0x00FF0000);
  144. colorData += vertexStride;
  145. }
  146. }
  147. vertexBuffer->writeData(0, bufferSize, bufferCopy, discardEntireBuffer ? BufferWriteType::Discard : BufferWriteType::Normal);
  148. bs_free(bufferCopy);
  149. }
  150. else
  151. {
  152. vertexBuffer->writeData(0, bufferSize, srcVertBufferData, discardEntireBuffer ? BufferWriteType::Discard : BufferWriteType::Normal);
  153. }
  154. }
  155. if (performUpdateBounds)
  156. updateBounds(meshData);
  157. }
  158. void MeshCore::readSubresource(UINT32 subresourceIdx, MeshData& meshData)
  159. {
  160. THROW_IF_NOT_CORE_THREAD;
  161. IndexType indexType = IT_32BIT;
  162. if (mIndexBuffer)
  163. indexType = mIndexBuffer->getProperties().getType();
  164. if (mIndexBuffer)
  165. {
  166. const IndexBufferProperties& ibProps = mIndexBuffer->getProperties();
  167. if (meshData.getIndexElementSize() != ibProps.getIndexSize())
  168. {
  169. BS_EXCEPT(InvalidParametersException, "Provided index size doesn't match meshes index size. Needed: " +
  170. toString(ibProps.getIndexSize()) + ". Got: " + toString(meshData.getIndexElementSize()));
  171. }
  172. UINT8* idxData = static_cast<UINT8*>(mIndexBuffer->lock(GBL_READ_ONLY));
  173. UINT32 idxElemSize = ibProps.getIndexSize();
  174. UINT8* indices = nullptr;
  175. if (indexType == IT_16BIT)
  176. indices = (UINT8*)meshData.getIndices16();
  177. else
  178. indices = (UINT8*)meshData.getIndices32();
  179. UINT32 numIndicesToCopy = std::min(mProperties.mNumIndices, meshData.getNumIndices());
  180. UINT32 indicesSize = numIndicesToCopy * idxElemSize;
  181. if (indicesSize > meshData.getIndexBufferSize())
  182. BS_EXCEPT(InvalidParametersException, "Provided buffer doesn't have enough space to store mesh indices.");
  183. memcpy(indices, idxData, numIndicesToCopy * idxElemSize);
  184. mIndexBuffer->unlock();
  185. }
  186. if (mVertexData)
  187. {
  188. auto vertexBuffers = mVertexData->getBuffers();
  189. UINT32 streamIdx = 0;
  190. for (auto iter = vertexBuffers.begin(); iter != vertexBuffers.end(); ++iter)
  191. {
  192. if (!meshData.getVertexDesc()->hasStream(streamIdx))
  193. continue;
  194. SPtr<VertexBufferCore> vertexBuffer = iter->second;
  195. const VertexBufferProperties& vbProps = vertexBuffer->getProperties();
  196. // Ensure both have the same sized vertices
  197. UINT32 myVertSize = mVertexDesc->getVertexStride(streamIdx);
  198. UINT32 otherVertSize = meshData.getVertexDesc()->getVertexStride(streamIdx);
  199. if (myVertSize != otherVertSize)
  200. {
  201. BS_EXCEPT(InvalidParametersException, "Provided vertex size for stream " + toString(streamIdx) + " doesn't match meshes vertex size. Needed: " +
  202. toString(myVertSize) + ". Got: " + toString(otherVertSize));
  203. }
  204. UINT32 numVerticesToCopy = meshData.getNumVertices();
  205. UINT32 bufferSize = vbProps.getVertexSize() * numVerticesToCopy;
  206. if (bufferSize > vertexBuffer->getSizeInBytes())
  207. BS_EXCEPT(InvalidParametersException, "Vertex buffer values for stream \"" + toString(streamIdx) + "\" are being read out of valid range.");
  208. UINT8* vertDataPtr = static_cast<UINT8*>(vertexBuffer->lock(GBL_READ_ONLY));
  209. UINT8* dest = meshData.getStreamData(streamIdx);
  210. memcpy(dest, vertDataPtr, bufferSize);
  211. vertexBuffer->unlock();
  212. streamIdx++;
  213. }
  214. }
  215. }
  216. void MeshCore::updateBounds(const MeshData& meshData)
  217. {
  218. mProperties.mBounds = meshData.calculateBounds();
  219. markCoreDirty();
  220. }
  221. Mesh::Mesh(UINT32 numVertices, UINT32 numIndices, const VertexDataDescPtr& vertexDesc,
  222. MeshBufferType bufferType, DrawOperationType drawOp, IndexType indexType)
  223. :MeshBase(numVertices, numIndices, drawOp), mVertexDesc(vertexDesc), mBufferType(bufferType),
  224. mIndexType(indexType)
  225. {
  226. }
  227. Mesh::Mesh(UINT32 numVertices, UINT32 numIndices, const VertexDataDescPtr& vertexDesc,
  228. const Vector<SubMesh>& subMeshes, MeshBufferType bufferType, IndexType indexType)
  229. :MeshBase(numVertices, numIndices, subMeshes), mVertexDesc(vertexDesc), mBufferType(bufferType),
  230. mIndexType(indexType)
  231. {
  232. }
  233. Mesh::Mesh(const MeshDataPtr& initialMeshData, MeshBufferType bufferType, DrawOperationType drawOp)
  234. :MeshBase(initialMeshData->getNumVertices(), initialMeshData->getNumIndices(), drawOp),
  235. mIndexType(initialMeshData->getIndexType()), mVertexDesc(initialMeshData->getVertexDesc()),
  236. mTempInitialMeshData(initialMeshData)
  237. {
  238. }
  239. Mesh::Mesh(const MeshDataPtr& initialMeshData, const Vector<SubMesh>& subMeshes, MeshBufferType bufferType)
  240. :MeshBase(initialMeshData->getNumVertices(), initialMeshData->getNumIndices(), subMeshes),
  241. mIndexType(initialMeshData->getIndexType()), mVertexDesc(initialMeshData->getVertexDesc()),
  242. mTempInitialMeshData(initialMeshData)
  243. {
  244. }
  245. Mesh::Mesh()
  246. :MeshBase(0, 0, DOT_TRIANGLE_LIST), mBufferType(MeshBufferType::Static), mIndexType(IT_32BIT)
  247. {
  248. }
  249. Mesh::~Mesh()
  250. {
  251. }
  252. AsyncOp Mesh::writeSubresource(CoreAccessor& accessor, UINT32 subresourceIdx, const MeshDataPtr& data, bool discardEntireBuffer)
  253. {
  254. updateBounds(*data);
  255. data->_lock();
  256. std::function<void(const SPtr<MeshCore>&, UINT32, const MeshDataPtr&, bool, AsyncOp&)> func =
  257. [&](const SPtr<MeshCore>& mesh, UINT32 _subresourceIdx, const MeshDataPtr& _meshData, bool _discardEntireBuffer, AsyncOp& asyncOp)
  258. {
  259. mesh->writeSubresource(_subresourceIdx, *_meshData, _discardEntireBuffer, false);
  260. _meshData->_unlock();
  261. asyncOp._completeOperation();
  262. };
  263. return accessor.queueReturnCommand(std::bind(func, getCore(), subresourceIdx,
  264. data, discardEntireBuffer, std::placeholders::_1));
  265. }
  266. AsyncOp Mesh::readSubresource(CoreAccessor& accessor, UINT32 subresourceIdx, const MeshDataPtr& data)
  267. {
  268. data->_lock();
  269. std::function<void(const SPtr<MeshCore>&, UINT32, const MeshDataPtr&, AsyncOp&)> func =
  270. [&](const SPtr<MeshCore>& mesh, UINT32 _subresourceIdx, const MeshDataPtr& _meshData, AsyncOp& asyncOp)
  271. {
  272. mesh->readSubresource(_subresourceIdx, *_meshData);
  273. _meshData->_unlock();
  274. asyncOp._completeOperation();
  275. };
  276. return accessor.queueReturnCommand(std::bind(func, getCore(), subresourceIdx,
  277. data, std::placeholders::_1));
  278. }
  279. MeshDataPtr Mesh::allocateSubresourceBuffer(UINT32 subresourceIdx) const
  280. {
  281. MeshDataPtr meshData = bs_shared_ptr<MeshData>(mProperties.mNumVertices, mProperties.mNumIndices, mVertexDesc, mIndexType);
  282. return meshData;
  283. }
  284. void Mesh::initialize()
  285. {
  286. if (mTempInitialMeshData != nullptr)
  287. {
  288. updateBounds(*mTempInitialMeshData);
  289. }
  290. MeshBase::initialize();
  291. }
  292. void Mesh::updateBounds(const MeshData& meshData)
  293. {
  294. mProperties.mBounds = meshData.calculateBounds();
  295. markCoreDirty();
  296. }
  297. SPtr<MeshCore> Mesh::getCore() const
  298. {
  299. return std::static_pointer_cast<MeshCore>(mCoreSpecific);
  300. }
  301. SPtr<CoreObjectCore> Mesh::createCore() const
  302. {
  303. MeshCore* obj = new (bs_alloc<MeshCore>()) MeshCore(mProperties.mNumVertices, mProperties.mNumIndices,
  304. mVertexDesc, mProperties.mSubMeshes, mBufferType, mIndexType, mTempInitialMeshData);
  305. SPtr<CoreObjectCore> meshCore = bs_shared_ptr<MeshCore, GenAlloc>(obj);
  306. mTempInitialMeshData = nullptr;
  307. return meshCore;
  308. }
  309. HMesh Mesh::dummy()
  310. {
  311. return MeshManager::instance().getDummyMesh();
  312. }
  313. /************************************************************************/
  314. /* SERIALIZATION */
  315. /************************************************************************/
  316. RTTITypeBase* Mesh::getRTTIStatic()
  317. {
  318. return MeshRTTI::instance();
  319. }
  320. RTTITypeBase* Mesh::getRTTI() const
  321. {
  322. return Mesh::getRTTIStatic();
  323. }
  324. /************************************************************************/
  325. /* STATICS */
  326. /************************************************************************/
  327. HMesh Mesh::create(UINT32 numVertices, UINT32 numIndices, const VertexDataDescPtr& vertexDesc,
  328. MeshBufferType bufferType, DrawOperationType drawOp, IndexType indexType)
  329. {
  330. MeshPtr meshPtr = _createPtr(numVertices, numIndices, vertexDesc, bufferType, drawOp, indexType);
  331. return static_resource_cast<Mesh>(gResources()._createResourceHandle(meshPtr));
  332. }
  333. HMesh Mesh::create(UINT32 numVertices, UINT32 numIndices, const VertexDataDescPtr& vertexDesc,
  334. const Vector<SubMesh>& subMeshes, MeshBufferType bufferType, IndexType indexType)
  335. {
  336. MeshPtr meshPtr = _createPtr(numVertices, numIndices, vertexDesc, subMeshes, bufferType, indexType);
  337. return static_resource_cast<Mesh>(gResources()._createResourceHandle(meshPtr));
  338. }
  339. HMesh Mesh::create(const MeshDataPtr& initialMeshData, MeshBufferType bufferType, DrawOperationType drawOp)
  340. {
  341. MeshPtr meshPtr = _createPtr(initialMeshData, bufferType, drawOp);
  342. return static_resource_cast<Mesh>(gResources()._createResourceHandle(meshPtr));
  343. }
  344. HMesh Mesh::create(const MeshDataPtr& initialMeshData, const Vector<SubMesh>& subMeshes, MeshBufferType bufferType)
  345. {
  346. MeshPtr meshPtr = _createPtr(initialMeshData, subMeshes, bufferType);
  347. return static_resource_cast<Mesh>(gResources()._createResourceHandle(meshPtr));
  348. }
  349. MeshPtr Mesh::_createPtr(UINT32 numVertices, UINT32 numIndices, const VertexDataDescPtr& vertexDesc,
  350. MeshBufferType bufferType, DrawOperationType drawOp, IndexType indexType)
  351. {
  352. return MeshManager::instance().create(numVertices, numIndices, vertexDesc, bufferType, drawOp, indexType);
  353. }
  354. MeshPtr Mesh::_createPtr(UINT32 numVertices, UINT32 numIndices, const VertexDataDescPtr& vertexDesc,
  355. const Vector<SubMesh>& subMeshes, MeshBufferType bufferType, IndexType indexType)
  356. {
  357. return MeshManager::instance().create(numVertices, numIndices, vertexDesc, subMeshes, bufferType, indexType);
  358. }
  359. MeshPtr Mesh::_createPtr(const MeshDataPtr& initialMeshData, MeshBufferType bufferType, DrawOperationType drawOp)
  360. {
  361. return MeshManager::instance().create(initialMeshData, bufferType, drawOp);
  362. }
  363. MeshPtr Mesh::_createPtr(const MeshDataPtr& initialMeshData, const Vector<SubMesh>& subMeshes, MeshBufferType bufferType)
  364. {
  365. return MeshManager::instance().create(initialMeshData, subMeshes, bufferType);
  366. }
  367. }