JoinVerticesProcess.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2022, 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. using namespace Assimp;
  46. // ------------------------------------------------------------------------------------------------
  47. // Constructor to be privately used by Importer
  48. JoinVerticesProcess::JoinVerticesProcess() {
  49. // nothing to do here
  50. }
  51. // ------------------------------------------------------------------------------------------------
  52. // Destructor, private as well
  53. JoinVerticesProcess::~JoinVerticesProcess() {
  54. // nothing to do here
  55. }
  56. // ------------------------------------------------------------------------------------------------
  57. // Returns whether the processing step is present in the given flag field.
  58. bool JoinVerticesProcess::IsActive( unsigned int pFlags) const {
  59. return (pFlags & aiProcess_JoinIdenticalVertices) != 0;
  60. }
  61. // ------------------------------------------------------------------------------------------------
  62. // Executes the post processing step on the given imported data.
  63. void JoinVerticesProcess::Execute( aiScene* pScene) {
  64. ASSIMP_LOG_DEBUG("JoinVerticesProcess begin");
  65. // get the total number of vertices BEFORE the step is executed
  66. int iNumOldVertices = 0;
  67. if (!DefaultLogger::isNullLogger()) {
  68. for( unsigned int a = 0; a < pScene->mNumMeshes; a++) {
  69. iNumOldVertices += pScene->mMeshes[a]->mNumVertices;
  70. }
  71. }
  72. // execute the step
  73. int iNumVertices = 0;
  74. for( unsigned int a = 0; a < pScene->mNumMeshes; a++) {
  75. iNumVertices += ProcessMesh( pScene->mMeshes[a],a);
  76. }
  77. pScene->mFlags |= AI_SCENE_FLAGS_NON_VERBOSE_FORMAT;
  78. // if logging is active, print detailed statistics
  79. if (!DefaultLogger::isNullLogger()) {
  80. if (iNumOldVertices == iNumVertices) {
  81. ASSIMP_LOG_DEBUG("JoinVerticesProcess finished ");
  82. return;
  83. }
  84. // Show statistics
  85. ASSIMP_LOG_INFO("JoinVerticesProcess finished | Verts in: ", iNumOldVertices,
  86. " out: ", iNumVertices, " | ~",
  87. ((iNumOldVertices - iNumVertices) / (float)iNumOldVertices) * 100.f );
  88. }
  89. }
  90. namespace {
  91. bool areVerticesEqual(const Vertex &lhs, const Vertex &rhs, bool complex) {
  92. // A little helper to find locally close vertices faster.
  93. // Try to reuse the lookup table from the last step.
  94. const static float epsilon = 1e-5f;
  95. // Squared because we check against squared length of the vector difference
  96. static const float squareEpsilon = epsilon * epsilon;
  97. // Square compare is useful for animeshes vertices compare
  98. if ((lhs.position - rhs.position).SquareLength() > squareEpsilon) {
  99. return false;
  100. }
  101. // We just test the other attributes even if they're not present in the mesh.
  102. // In this case they're initialized to 0 so the comparison succeeds.
  103. // By this method the non-present attributes are effectively ignored in the comparison.
  104. if ((lhs.normal - rhs.normal).SquareLength() > squareEpsilon) {
  105. return false;
  106. }
  107. if ((lhs.texcoords[0] - rhs.texcoords[0]).SquareLength() > squareEpsilon) {
  108. return false;
  109. }
  110. if ((lhs.tangent - rhs.tangent).SquareLength() > squareEpsilon) {
  111. return false;
  112. }
  113. if ((lhs.bitangent - rhs.bitangent).SquareLength() > squareEpsilon) {
  114. return false;
  115. }
  116. // Usually we won't have vertex colors or multiple UVs, so we can skip from here
  117. // Actually this increases runtime performance slightly, at least if branch
  118. // prediction is on our side.
  119. if (complex) {
  120. for (int i = 0; i < 8; i++) {
  121. if (i > 0 && (lhs.texcoords[i] - rhs.texcoords[i]).SquareLength() > squareEpsilon) {
  122. return false;
  123. }
  124. if (GetColorDifference(lhs.colors[i], rhs.colors[i]) > squareEpsilon) {
  125. return false;
  126. }
  127. }
  128. }
  129. return true;
  130. }
  131. template<class XMesh>
  132. void updateXMeshVertices(XMesh *pMesh, std::vector<Vertex> &uniqueVertices) {
  133. // replace vertex data with the unique data sets
  134. pMesh->mNumVertices = (unsigned int)uniqueVertices.size();
  135. // ----------------------------------------------------------------------------
  136. // NOTE - we're *not* calling Vertex::SortBack() because it would check for
  137. // presence of every single vertex component once PER VERTEX. And our CPU
  138. // dislikes branches, even if they're easily predictable.
  139. // ----------------------------------------------------------------------------
  140. // Position, if present (check made for aiAnimMesh)
  141. if (pMesh->mVertices) {
  142. delete [] pMesh->mVertices;
  143. pMesh->mVertices = new aiVector3D[pMesh->mNumVertices];
  144. for (unsigned int a = 0; a < pMesh->mNumVertices; a++) {
  145. pMesh->mVertices[a] = uniqueVertices[a].position;
  146. }
  147. }
  148. // Normals, if present
  149. if (pMesh->mNormals) {
  150. delete [] pMesh->mNormals;
  151. pMesh->mNormals = new aiVector3D[pMesh->mNumVertices];
  152. for( unsigned int a = 0; a < pMesh->mNumVertices; a++) {
  153. pMesh->mNormals[a] = uniqueVertices[a].normal;
  154. }
  155. }
  156. // Tangents, if present
  157. if (pMesh->mTangents) {
  158. delete [] pMesh->mTangents;
  159. pMesh->mTangents = new aiVector3D[pMesh->mNumVertices];
  160. for (unsigned int a = 0; a < pMesh->mNumVertices; a++) {
  161. pMesh->mTangents[a] = uniqueVertices[a].tangent;
  162. }
  163. }
  164. // Bitangents as well
  165. if (pMesh->mBitangents) {
  166. delete [] pMesh->mBitangents;
  167. pMesh->mBitangents = new aiVector3D[pMesh->mNumVertices];
  168. for (unsigned int a = 0; a < pMesh->mNumVertices; a++) {
  169. pMesh->mBitangents[a] = uniqueVertices[a].bitangent;
  170. }
  171. }
  172. // Vertex colors
  173. for (unsigned int a = 0; pMesh->HasVertexColors(a); a++) {
  174. delete [] pMesh->mColors[a];
  175. pMesh->mColors[a] = new aiColor4D[pMesh->mNumVertices];
  176. for( unsigned int b = 0; b < pMesh->mNumVertices; b++) {
  177. pMesh->mColors[a][b] = uniqueVertices[b].colors[a];
  178. }
  179. }
  180. // Texture coords
  181. for (unsigned int a = 0; pMesh->HasTextureCoords(a); a++) {
  182. delete [] pMesh->mTextureCoords[a];
  183. pMesh->mTextureCoords[a] = new aiVector3D[pMesh->mNumVertices];
  184. for (unsigned int b = 0; b < pMesh->mNumVertices; b++) {
  185. pMesh->mTextureCoords[a][b] = uniqueVertices[b].texcoords[a];
  186. }
  187. }
  188. }
  189. } // namespace
  190. // ------------------------------------------------------------------------------------------------
  191. // Unites identical vertices in the given mesh
  192. // combine hashes
  193. inline void hash_combine(std::size_t &) {
  194. // empty
  195. }
  196. template <typename T, typename... Rest>
  197. inline void hash_combine(std::size_t& seed, const T& v, Rest... rest) {
  198. std::hash<T> hasher;
  199. seed ^= hasher(v) + 0x9e3779b9 + (seed<<6) + (seed>>2);
  200. hash_combine(seed, rest...);
  201. }
  202. //template specialization for std::hash for Vertex
  203. template<>
  204. struct std::hash<Vertex> {
  205. std::size_t operator()(Vertex const& v) const noexcept {
  206. size_t seed = 0;
  207. hash_combine(seed, v.position.x ,v.position.y,v.position.z);
  208. return seed;
  209. }
  210. };
  211. //template specialization for std::equal_to for Vertex
  212. template<>
  213. struct std::equal_to<Vertex> {
  214. bool operator()(const Vertex &lhs, const Vertex &rhs) const {
  215. return areVerticesEqual(lhs, rhs, false);
  216. }
  217. };
  218. // now start the JoinVerticesProcess
  219. int JoinVerticesProcess::ProcessMesh( aiMesh* pMesh, unsigned int meshIndex) {
  220. static_assert( AI_MAX_NUMBER_OF_COLOR_SETS == 8, "AI_MAX_NUMBER_OF_COLOR_SETS == 8");
  221. static_assert( AI_MAX_NUMBER_OF_TEXTURECOORDS == 8, "AI_MAX_NUMBER_OF_TEXTURECOORDS == 8");
  222. // Return early if we don't have any positions
  223. if (!pMesh->HasPositions() || !pMesh->HasFaces()) {
  224. return 0;
  225. }
  226. // We should care only about used vertices, not all of them
  227. // (this can happen due to original file vertices buffer being used by
  228. // multiple meshes)
  229. std::unordered_set<unsigned int> usedVertexIndices;
  230. usedVertexIndices.reserve(pMesh->mNumVertices);
  231. for( unsigned int a = 0; a < pMesh->mNumFaces; a++) {
  232. aiFace& face = pMesh->mFaces[a];
  233. for( unsigned int b = 0; b < face.mNumIndices; b++) {
  234. usedVertexIndices.insert(face.mIndices[b]);
  235. }
  236. }
  237. // We'll never have more vertices afterwards.
  238. std::vector<Vertex> uniqueVertices;
  239. uniqueVertices.reserve( pMesh->mNumVertices);
  240. // For each vertex the index of the vertex it was replaced by.
  241. // Since the maximal number of vertices is 2^31-1, the most significand bit can be used to mark
  242. // whether a new vertex was created for the index (true) or if it was replaced by an existing
  243. // unique vertex (false). This saves an additional std::vector<bool> and greatly enhances
  244. // branching performance.
  245. static_assert(AI_MAX_VERTICES == 0x7fffffff, "AI_MAX_VERTICES == 0x7fffffff");
  246. std::vector<unsigned int> replaceIndex( pMesh->mNumVertices, 0xffffffff);
  247. // float posEpsilonSqr;
  248. SpatialSort *vertexFinder = nullptr;
  249. SpatialSort _vertexFinder;
  250. typedef std::pair<SpatialSort,float> SpatPair;
  251. if (shared) {
  252. std::vector<SpatPair >* avf;
  253. shared->GetProperty(AI_SPP_SPATIAL_SORT,avf);
  254. if (avf) {
  255. SpatPair& blubb = (*avf)[meshIndex];
  256. vertexFinder = &blubb.first;
  257. // posEpsilonSqr = blubb.second;
  258. }
  259. }
  260. if (!vertexFinder) {
  261. // bad, need to compute it.
  262. _vertexFinder.Fill(pMesh->mVertices, pMesh->mNumVertices, sizeof( aiVector3D));
  263. vertexFinder = &_vertexFinder;
  264. // posEpsilonSqr = ComputePositionEpsilon(pMesh);
  265. }
  266. // Again, better waste some bytes than a realloc ...
  267. std::vector<unsigned int> verticesFound;
  268. verticesFound.reserve(10);
  269. // Run an optimized code path if we don't have multiple UVs or vertex colors.
  270. // This should yield false in more than 99% of all imports ...
  271. const bool hasAnimMeshes = pMesh->mNumAnimMeshes > 0;
  272. // We'll never have more vertices afterwards.
  273. std::vector<std::vector<Vertex>> uniqueAnimatedVertices;
  274. if (hasAnimMeshes) {
  275. uniqueAnimatedVertices.resize(pMesh->mNumAnimMeshes);
  276. for (unsigned int animMeshIndex = 0; animMeshIndex < pMesh->mNumAnimMeshes; animMeshIndex++) {
  277. uniqueAnimatedVertices[animMeshIndex].reserve(pMesh->mNumVertices);
  278. }
  279. }
  280. // a map that maps a vertix to its new index
  281. std::unordered_map<Vertex,int> vertex2Index;
  282. // we can not end up with more vertices than we started with
  283. vertex2Index.reserve(pMesh->mNumVertices);
  284. // Now check each vertex if it brings something new to the table
  285. int newIndex = 0;
  286. for( unsigned int a = 0; a < pMesh->mNumVertices; a++) {
  287. // if the vertex is unused Do nothing
  288. if (usedVertexIndices.find(a) == usedVertexIndices.end()) {
  289. continue;
  290. }
  291. // collect the vertex data
  292. Vertex v(pMesh,a);
  293. // is the vertex already in the map?
  294. auto it = vertex2Index.find(v);
  295. // if the vertex is not in the map then it is a new vertex add it.
  296. if (it == vertex2Index.end()) {
  297. // this is a new vertex give it a new index
  298. vertex2Index[v] = newIndex;
  299. //keep track of its index and increment 1
  300. replaceIndex[a] = newIndex++;
  301. // add the vertex to the unique vertices
  302. uniqueVertices.push_back(v);
  303. if (hasAnimMeshes) {
  304. for (unsigned int animMeshIndex = 0; animMeshIndex < pMesh->mNumAnimMeshes; animMeshIndex++) {
  305. Vertex aniMeshVertex(pMesh->mAnimMeshes[animMeshIndex], a);
  306. uniqueAnimatedVertices[animMeshIndex].push_back(v);
  307. }
  308. }
  309. } else{
  310. // if the vertex is already there just find the replace index that is appropriate to it
  311. replaceIndex[a] = it->second;
  312. }
  313. }
  314. if (!DefaultLogger::isNullLogger() && DefaultLogger::get()->getLogSeverity() == Logger::VERBOSE) {
  315. ASSIMP_LOG_VERBOSE_DEBUG(
  316. "Mesh ",meshIndex,
  317. " (",
  318. (pMesh->mName.length ? pMesh->mName.data : "unnamed"),
  319. ") | Verts in: ",pMesh->mNumVertices,
  320. " out: ",
  321. uniqueVertices.size(),
  322. " | ~",
  323. ((pMesh->mNumVertices - uniqueVertices.size()) / (float)pMesh->mNumVertices) * 100.f,
  324. "%"
  325. );
  326. }
  327. updateXMeshVertices(pMesh, uniqueVertices);
  328. if (hasAnimMeshes) {
  329. for (unsigned int animMeshIndex = 0; animMeshIndex < pMesh->mNumAnimMeshes; animMeshIndex++) {
  330. updateXMeshVertices(pMesh->mAnimMeshes[animMeshIndex], uniqueAnimatedVertices[animMeshIndex]);
  331. }
  332. }
  333. // adjust the indices in all faces
  334. for( unsigned int a = 0; a < pMesh->mNumFaces; a++) {
  335. aiFace& face = pMesh->mFaces[a];
  336. for( unsigned int b = 0; b < face.mNumIndices; b++) {
  337. face.mIndices[b] = replaceIndex[face.mIndices[b]] & ~0x80000000;
  338. }
  339. }
  340. // adjust bone vertex weights.
  341. for( int a = 0; a < (int)pMesh->mNumBones; a++) {
  342. aiBone* bone = pMesh->mBones[a];
  343. std::vector<aiVertexWeight> newWeights;
  344. newWeights.reserve( bone->mNumWeights);
  345. if (nullptr != bone->mWeights) {
  346. for ( unsigned int b = 0; b < bone->mNumWeights; b++ ) {
  347. const aiVertexWeight& ow = bone->mWeights[ b ];
  348. // if the vertex is a unique one, translate it
  349. if ( !( replaceIndex[ ow.mVertexId ] & 0x80000000 ) ) {
  350. aiVertexWeight nw;
  351. nw.mVertexId = replaceIndex[ ow.mVertexId ];
  352. nw.mWeight = ow.mWeight;
  353. newWeights.push_back( nw );
  354. }
  355. }
  356. } else {
  357. ASSIMP_LOG_ERROR( "X-Export: aiBone shall contain weights, but pointer to them is nullptr." );
  358. }
  359. if (newWeights.size() > 0) {
  360. // kill the old and replace them with the translated weights
  361. delete [] bone->mWeights;
  362. bone->mNumWeights = (unsigned int)newWeights.size();
  363. bone->mWeights = new aiVertexWeight[bone->mNumWeights];
  364. memcpy( bone->mWeights, &newWeights[0], bone->mNumWeights * sizeof( aiVertexWeight));
  365. }
  366. }
  367. return pMesh->mNumVertices;
  368. }
  369. #endif // !! ASSIMP_BUILD_NO_JOINVERTICES_PROCESS