2
0

JoinVerticesProcess.cpp 17 KB

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