JoinVerticesProcess.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2025, assimp team
  6. All rights reserved.
  7. Redistribution and use of this software in source and binary forms,
  8. with or without modification, are permitted provided that the following
  9. conditions are met:
  10. * Redistributions of source code must retain the above
  11. copyright notice, this list of conditions and the
  12. following disclaimer.
  13. * Redistributions in binary form must reproduce the above
  14. copyright notice, this list of conditions and the
  15. following disclaimer in the documentation and/or other
  16. materials provided with the distribution.
  17. * Neither the name of the assimp team, nor the names of its
  18. contributors may be used to endorse or promote products
  19. derived from this software without specific prior
  20. written permission of the assimp team.
  21. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  22. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  23. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  24. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  25. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  26. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  27. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  28. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  29. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  30. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  31. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  32. ---------------------------------------------------------------------------
  33. */
  34. /** @file Implementation of the post processing step to join identical vertices
  35. * for all imported meshes
  36. */
  37. #ifndef ASSIMP_BUILD_NO_JOINVERTICES_PROCESS
  38. #include "JoinVerticesProcess.h"
  39. #include "ProcessHelper.h"
  40. #include <assimp/Vertex.h>
  41. #include <assimp/TinyFormatter.h>
  42. #include <stdio.h>
  43. #include <unordered_set>
  44. #include <unordered_map>
  45. #include <memory>
  46. #include <map>
  47. using namespace Assimp;
  48. // ------------------------------------------------------------------------------------------------
  49. // Returns whether the processing step is present in the given flag field.
  50. bool JoinVerticesProcess::IsActive( unsigned int pFlags) const {
  51. return (pFlags & aiProcess_JoinIdenticalVertices) != 0;
  52. }
  53. // ------------------------------------------------------------------------------------------------
  54. // Executes the post processing step on the given imported data.
  55. void JoinVerticesProcess::Execute( aiScene* pScene) {
  56. ASSIMP_LOG_DEBUG("JoinVerticesProcess begin");
  57. // get the total number of vertices BEFORE the step is executed
  58. int iNumOldVertices = 0;
  59. if (!DefaultLogger::isNullLogger()) {
  60. for( unsigned int a = 0; a < pScene->mNumMeshes; a++) {
  61. iNumOldVertices += pScene->mMeshes[a]->mNumVertices;
  62. }
  63. }
  64. // execute the step
  65. int iNumVertices = 0;
  66. for( unsigned int a = 0; a < pScene->mNumMeshes; a++) {
  67. iNumVertices += ProcessMesh( pScene->mMeshes[a],a);
  68. }
  69. pScene->mFlags |= AI_SCENE_FLAGS_NON_VERBOSE_FORMAT;
  70. // if logging is active, print detailed statistics
  71. if (!DefaultLogger::isNullLogger()) {
  72. if (iNumOldVertices == iNumVertices) {
  73. ASSIMP_LOG_DEBUG("JoinVerticesProcess finished ");
  74. return;
  75. }
  76. // Show statistics
  77. ASSIMP_LOG_INFO("JoinVerticesProcess finished | Verts in: ", iNumOldVertices,
  78. " out: ", iNumVertices, " | ~",
  79. ((iNumOldVertices - iNumVertices) / (float)iNumOldVertices) * 100.f );
  80. }
  81. }
  82. namespace {
  83. template<class XMesh>
  84. void updateXMeshVertices(XMesh *pMesh, std::vector<int> &uniqueVertices) {
  85. // replace vertex data with the unique data sets
  86. pMesh->mNumVertices = (unsigned int)uniqueVertices.size();
  87. // ----------------------------------------------------------------------------
  88. // NOTE - we're *not* calling Vertex::SortBack() because it would check for
  89. // presence of every single vertex component once PER VERTEX. And our CPU
  90. // dislikes branches, even if they're easily predictable.
  91. // ----------------------------------------------------------------------------
  92. // Position, if present (check made for aiAnimMesh)
  93. if (pMesh->mVertices) {
  94. std::unique_ptr<aiVector3D[]> oldVertices(pMesh->mVertices);
  95. pMesh->mVertices = new aiVector3D[pMesh->mNumVertices];
  96. for (unsigned int a = 0; a < pMesh->mNumVertices; a++)
  97. pMesh->mVertices[a] = oldVertices[uniqueVertices[a]];
  98. }
  99. // Normals, if present
  100. if (pMesh->mNormals) {
  101. std::unique_ptr<aiVector3D[]> oldNormals(pMesh->mNormals);
  102. pMesh->mNormals = new aiVector3D[pMesh->mNumVertices];
  103. for (unsigned int a = 0; a < pMesh->mNumVertices; a++)
  104. pMesh->mNormals[a] = oldNormals[uniqueVertices[a]];
  105. }
  106. // Tangents, if present
  107. if (pMesh->mTangents) {
  108. std::unique_ptr<aiVector3D[]> oldTangents(pMesh->mTangents);
  109. pMesh->mTangents = new aiVector3D[pMesh->mNumVertices];
  110. for (unsigned int a = 0; a < pMesh->mNumVertices; a++)
  111. pMesh->mTangents[a] = oldTangents[uniqueVertices[a]];
  112. }
  113. // Bitangents as well
  114. if (pMesh->mBitangents) {
  115. std::unique_ptr<aiVector3D[]> oldBitangents(pMesh->mBitangents);
  116. pMesh->mBitangents = new aiVector3D[pMesh->mNumVertices];
  117. for (unsigned int a = 0; a < pMesh->mNumVertices; a++)
  118. pMesh->mBitangents[a] = oldBitangents[uniqueVertices[a]];
  119. }
  120. // Vertex colors
  121. for (unsigned int a = 0; pMesh->HasVertexColors(a); a++) {
  122. std::unique_ptr<aiColor4D[]> oldColors(pMesh->mColors[a]);
  123. pMesh->mColors[a] = new aiColor4D[pMesh->mNumVertices];
  124. for (unsigned int b = 0; b < pMesh->mNumVertices; b++)
  125. pMesh->mColors[a][b] = oldColors[uniqueVertices[b]];
  126. }
  127. // Texture coords
  128. for (unsigned int a = 0; pMesh->HasTextureCoords(a); a++) {
  129. std::unique_ptr<aiVector3D[]> oldTextureCoords(pMesh->mTextureCoords[a]);
  130. pMesh->mTextureCoords[a] = new aiVector3D[pMesh->mNumVertices];
  131. for (unsigned int b = 0; b < pMesh->mNumVertices; b++)
  132. pMesh->mTextureCoords[a][b] = oldTextureCoords[uniqueVertices[b]];
  133. }
  134. }
  135. } // namespace
  136. // ------------------------------------------------------------------------------------------------
  137. static constexpr size_t JOINED_VERTICES_MARK = 0x80000000u;
  138. // now start the JoinVerticesProcess
  139. int JoinVerticesProcess::ProcessMesh( aiMesh* pMesh, unsigned int meshIndex) {
  140. static_assert( AI_MAX_NUMBER_OF_COLOR_SETS == 8, "AI_MAX_NUMBER_OF_COLOR_SETS == 8");
  141. static_assert( AI_MAX_NUMBER_OF_TEXTURECOORDS == 8, "AI_MAX_NUMBER_OF_TEXTURECOORDS == 8");
  142. // Return early if we don't have any positions
  143. if (!pMesh->HasPositions() || !pMesh->HasFaces()) {
  144. return 0;
  145. }
  146. // We should care only about used vertices, not all of them
  147. // (this can happen due to original file vertices buffer being used by
  148. // multiple meshes)
  149. std::vector<bool> usedVertexIndicesMask;
  150. usedVertexIndicesMask.resize(pMesh->mNumVertices, false);
  151. for (unsigned int a = 0; a < pMesh->mNumFaces; a++) {
  152. aiFace& face = pMesh->mFaces[a];
  153. for (unsigned int b = 0; b < face.mNumIndices; b++) {
  154. usedVertexIndicesMask[face.mIndices[b]] = true;
  155. }
  156. }
  157. // We'll never have more vertices afterwards.
  158. std::vector<int> uniqueVertices;
  159. // For each vertex the index of the vertex it was replaced by.
  160. // Since the maximal number of vertices is 2^31-1, the most significand bit can be used to mark
  161. // whether a new vertex was created for the index (true) or if it was replaced by an existing
  162. // unique vertex (false). This saves an additional std::vector<bool> and greatly enhances
  163. // branching performance.
  164. static_assert(AI_MAX_VERTICES == 0x7fffffff, "AI_MAX_VERTICES == 0x7fffffff");
  165. std::vector<unsigned int> replaceIndex( pMesh->mNumVertices, 0xffffffff);
  166. // Run an optimized code path if we don't have multiple UVs or vertex colors.
  167. // This should yield false in more than 99% of all imports ...
  168. const bool hasAnimMeshes = pMesh->mNumAnimMeshes > 0;
  169. // We'll never have more vertices afterwards.
  170. std::vector<std::vector<int>> uniqueAnimatedVertices;
  171. if (hasAnimMeshes) {
  172. uniqueAnimatedVertices.resize(pMesh->mNumAnimMeshes);
  173. for (unsigned int animMeshIndex = 0; animMeshIndex < pMesh->mNumAnimMeshes; animMeshIndex++) {
  174. uniqueAnimatedVertices[animMeshIndex].reserve(pMesh->mNumVertices);
  175. }
  176. }
  177. // a map that maps a vertex to its new index
  178. std::map<Vertex, int> vertex2Index = {};
  179. // we can not end up with more vertices than we started with
  180. // Now check each vertex if it brings something new to the table
  181. int newIndex = 0;
  182. for( unsigned int a = 0; a < pMesh->mNumVertices; a++) {
  183. // if the vertex is unused Do nothing
  184. if (!usedVertexIndicesMask[a]) {
  185. continue;
  186. }
  187. // collect the vertex data
  188. Vertex v(pMesh,a);
  189. // is the vertex already in the map?
  190. auto it = vertex2Index.find(v);
  191. // if the vertex is not in the map then it is a new vertex add it.
  192. if (it == vertex2Index.end()) {
  193. // this is a new vertex give it a new index
  194. vertex2Index.emplace(v, newIndex);
  195. // keep track of its index and increment 1
  196. replaceIndex[a] = newIndex++;
  197. // add the vertex to the unique vertices
  198. uniqueVertices.push_back(a);
  199. if (hasAnimMeshes) {
  200. for (unsigned int animMeshIndex = 0; animMeshIndex < pMesh->mNumAnimMeshes; animMeshIndex++) {
  201. uniqueAnimatedVertices[animMeshIndex].emplace_back(a);
  202. }
  203. }
  204. } else{
  205. // if the vertex is already there just find the replace index that is appropriate to it
  206. // mark it with JOINED_VERTICES_MARK
  207. replaceIndex[a] = it->second | JOINED_VERTICES_MARK;
  208. }
  209. }
  210. if (!DefaultLogger::isNullLogger() && DefaultLogger::get()->getLogSeverity() == Logger::VERBOSE) {
  211. ASSIMP_LOG_VERBOSE_DEBUG(
  212. "Mesh ",meshIndex,
  213. " (",
  214. (pMesh->mName.length ? pMesh->mName.data : "unnamed"),
  215. ") | Verts in: ",pMesh->mNumVertices,
  216. " out: ",
  217. uniqueVertices.size(),
  218. " | ~",
  219. ((pMesh->mNumVertices - uniqueVertices.size()) / (float)pMesh->mNumVertices) * 100.f,
  220. "%"
  221. );
  222. }
  223. updateXMeshVertices(pMesh, uniqueVertices);
  224. if (hasAnimMeshes) {
  225. for (unsigned int animMeshIndex = 0; animMeshIndex < pMesh->mNumAnimMeshes; animMeshIndex++) {
  226. updateXMeshVertices(pMesh->mAnimMeshes[animMeshIndex], uniqueAnimatedVertices[animMeshIndex]);
  227. }
  228. }
  229. // adjust the indices in all faces
  230. for( unsigned int a = 0; a < pMesh->mNumFaces; a++) {
  231. aiFace& face = pMesh->mFaces[a];
  232. for( unsigned int b = 0; b < face.mNumIndices; b++) {
  233. face.mIndices[b] = replaceIndex[face.mIndices[b]] & ~JOINED_VERTICES_MARK;
  234. }
  235. }
  236. // adjust bone vertex weights.
  237. for( int a = 0; a < (int)pMesh->mNumBones; a++) {
  238. aiBone* bone = pMesh->mBones[a];
  239. std::vector<aiVertexWeight> newWeights;
  240. newWeights.reserve( bone->mNumWeights);
  241. if (nullptr != bone->mWeights) {
  242. for ( unsigned int b = 0; b < bone->mNumWeights; b++ ) {
  243. const aiVertexWeight& ow = bone->mWeights[ b ];
  244. // if the vertex is a unique one, translate it
  245. // filter out joined vertices by JOINED_VERTICES_MARK.
  246. if ( !( replaceIndex[ ow.mVertexId ] & JOINED_VERTICES_MARK ) ) {
  247. aiVertexWeight nw;
  248. nw.mVertexId = replaceIndex[ ow.mVertexId ];
  249. nw.mWeight = ow.mWeight;
  250. newWeights.push_back( nw );
  251. }
  252. }
  253. } else {
  254. ASSIMP_LOG_ERROR( "X-Export: aiBone shall contain weights, but pointer to them is nullptr." );
  255. }
  256. if (newWeights.size() > 0) {
  257. // kill the old and replace them with the translated weights
  258. delete [] bone->mWeights;
  259. bone->mNumWeights = (unsigned int)newWeights.size();
  260. bone->mWeights = new aiVertexWeight[bone->mNumWeights];
  261. memcpy( bone->mWeights, &newWeights[0], bone->mNumWeights * sizeof( aiVertexWeight));
  262. }
  263. }
  264. return pMesh->mNumVertices;
  265. }
  266. #endif // !! ASSIMP_BUILD_NO_JOINVERTICES_PROCESS