JoinVerticesProcess.cpp 17 KB

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