You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

415 line
15 KiB

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