JoinVerticesProcess.cpp 15 KB

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