CalcTangentsProcess.cpp 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  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 calculate
  35. * tangents and bitangents for all imported meshes
  36. */
  37. // STL headers
  38. #include <vector>
  39. #include <assert.h>
  40. // internal headers
  41. #include "CalcTangentsProcess.h"
  42. #include "SpatialSort.h"
  43. // public ASSIMP headers
  44. #include "../include/DefaultLogger.h"
  45. #include "../include/aiPostProcess.h"
  46. #include "../include/aiMesh.h"
  47. #include "../include/aiScene.h"
  48. using namespace Assimp;
  49. // ------------------------------------------------------------------------------------------------
  50. // Constructor to be privately used by Importer
  51. CalcTangentsProcess::CalcTangentsProcess()
  52. {
  53. // nothing to do here
  54. }
  55. // ------------------------------------------------------------------------------------------------
  56. // Destructor, private as well
  57. CalcTangentsProcess::~CalcTangentsProcess()
  58. {
  59. // nothing to do here
  60. }
  61. // ------------------------------------------------------------------------------------------------
  62. // Returns whether the processing step is present in the given flag field.
  63. bool CalcTangentsProcess::IsActive( unsigned int pFlags) const
  64. {
  65. return (pFlags & aiProcess_CalcTangentSpace) != 0;
  66. }
  67. // ------------------------------------------------------------------------------------------------
  68. // Executes the post processing step on the given imported data.
  69. void CalcTangentsProcess::Execute( aiScene* pScene)
  70. {
  71. DefaultLogger::get()->debug("CalcTangentsProcess begin");
  72. bool bHas = false;
  73. for( unsigned int a = 0; a < pScene->mNumMeshes; a++)
  74. if(ProcessMesh( pScene->mMeshes[a]))bHas = true;
  75. if (bHas)DefaultLogger::get()->debug("CalcTangentsProcess finished. Tangents have been calculated");
  76. else DefaultLogger::get()->debug("CalcTangentsProcess finished");
  77. }
  78. // ------------------------------------------------------------------------------------------------
  79. // Calculates tangents and bitangents for the given mesh
  80. bool CalcTangentsProcess::ProcessMesh( aiMesh* pMesh)
  81. {
  82. // we assume that the mesh is still in the verbose vertex format where each face has its own set
  83. // of vertices and no vertices are shared between faces. Sadly I don't know any quick test to
  84. // assert() it here.
  85. //assert( must be verbose, dammit);
  86. // TODO (Aramis)
  87. // If we had a model format in the lib which has native support for
  88. // tangents and bitangents, it would be necessary to add a
  89. // "KillTangentsAndBitangents" flag ...
  90. if (pMesh->mTangents && pMesh->mBitangents)
  91. {
  92. return false;
  93. }
  94. // what we can check, though, is if the mesh has normals and texture coord. That's a requirement
  95. if( pMesh->mNormals == NULL || pMesh->mTextureCoords[0] == NULL)
  96. {
  97. DefaultLogger::get()->error("Unable to compute tangents: UV0 and normals must be there ");
  98. return false;
  99. }
  100. // calculate the position bounds so we have a reliable epsilon to check position differences against
  101. aiVector3D minVec( 1e10f, 1e10f, 1e10f), maxVec( -1e10f, -1e10f, -1e10f);
  102. for( unsigned int a = 0; a < pMesh->mNumVertices; a++)
  103. {
  104. minVec.x = std::min( minVec.x, pMesh->mVertices[a].x);
  105. minVec.y = std::min( minVec.y, pMesh->mVertices[a].y);
  106. minVec.z = std::min( minVec.z, pMesh->mVertices[a].z);
  107. maxVec.x = std::max( maxVec.x, pMesh->mVertices[a].x);
  108. maxVec.y = std::max( maxVec.y, pMesh->mVertices[a].y);
  109. maxVec.z = std::max( maxVec.z, pMesh->mVertices[a].z);
  110. }
  111. // calculate epsilons border
  112. const float epsilon = 1e-5f;
  113. const float posEpsilon = (maxVec - minVec).Length() * epsilon;
  114. const float angleEpsilon = 0.9999f;
  115. // create space for the tangents and bitangents
  116. pMesh->mTangents = new aiVector3D[pMesh->mNumVertices];
  117. pMesh->mBitangents = new aiVector3D[pMesh->mNumVertices];
  118. const aiVector3D* meshPos = pMesh->mVertices;
  119. const aiVector3D* meshNorm = pMesh->mNormals;
  120. const aiVector3D* meshTex = pMesh->mTextureCoords[0];
  121. aiVector3D* meshTang = pMesh->mTangents;
  122. aiVector3D* meshBitang = pMesh->mBitangents;
  123. // calculate the tangent and bitangent for every face
  124. for( unsigned int a = 0; a < pMesh->mNumFaces; a++)
  125. {
  126. const aiFace& face = pMesh->mFaces[a];
  127. // triangle or polygon... we always use only the first three indices. A polygon
  128. // is supposed to be planar anyways....
  129. // FIXME: (thom) create correct calculation for multi-vertex polygons maybe?
  130. const unsigned int p0 = face.mIndices[0], p1 = face.mIndices[1], p2 = face.mIndices[2];
  131. // position differences p1->p2 and p1->p3
  132. aiVector3D v = meshPos[p1] - meshPos[p0], w = meshPos[p2] - meshPos[p0];
  133. // texture offset p1->p2 and p1->p3
  134. float sx = meshTex[p1].x - meshTex[p0].x, sy = meshTex[p1].y - meshTex[p0].y;
  135. float tx = meshTex[p2].x - meshTex[p0].x, ty = meshTex[p2].y - meshTex[p0].y;
  136. float dirCorrection = (tx * sy - ty * sx) < 0.0f ? -1.0f : 1.0f;
  137. // tangent points in the direction where to positive X axis of the texture coords would point in model space
  138. // bitangents points along the positive Y axis of the texture coords, respectively
  139. aiVector3D tangent, bitangent;
  140. tangent.x = (w.x * sy - v.x * ty) * dirCorrection;
  141. tangent.y = (w.y * sy - v.y * ty) * dirCorrection;
  142. tangent.z = (w.z * sy - v.z * ty) * dirCorrection;
  143. bitangent.x = (w.x * sx - v.x * tx) * dirCorrection;
  144. bitangent.y = (w.y * sx - v.y * tx) * dirCorrection;
  145. bitangent.z = (w.z * sx - v.z * tx) * dirCorrection;
  146. // store for every vertex of that face
  147. for( unsigned int b = 0; b < face.mNumIndices; b++)
  148. {
  149. unsigned int p = face.mIndices[b];
  150. // project tangent and bitangent into the plane formed by the vertex' normal
  151. aiVector3D localTangent = tangent - meshNorm[p] * (tangent * meshNorm[p]);
  152. aiVector3D localBitangent = bitangent - meshNorm[p] * (bitangent * meshNorm[p]);
  153. localTangent.Normalize(); localBitangent.Normalize();
  154. // and write it into the mesh.
  155. meshTang[p] = localTangent;
  156. meshBitang[p] = localBitangent;
  157. }
  158. }
  159. // create a helper to quickly find locally close vertices among the vertex array
  160. SpatialSort vertexFinder( meshPos, pMesh->mNumVertices, sizeof( aiVector3D));
  161. std::vector<unsigned int> verticesFound;
  162. // in the second pass we now smooth out all tangents and bitangents at the same local position
  163. // if they are not too far off.
  164. std::vector<bool> vertexDone( pMesh->mNumVertices, false);
  165. for( unsigned int a = 0; a < pMesh->mNumVertices; a++)
  166. {
  167. if( vertexDone[a])
  168. continue;
  169. const aiVector3D& origPos = pMesh->mVertices[a];
  170. const aiVector3D& origNorm = pMesh->mNormals[a];
  171. const aiVector3D& origTang = pMesh->mTangents[a];
  172. const aiVector3D& origBitang = pMesh->mBitangents[a];
  173. std::vector<unsigned int> closeVertices;
  174. closeVertices.push_back( a);
  175. // find all vertices close to that position
  176. vertexFinder.FindPositions( origPos, posEpsilon, verticesFound);
  177. // look among them for other vertices sharing the same normal and a close-enough tangent/bitangent
  178. static const float MAX_DIFF_ANGLE = 0.701f;
  179. for( unsigned int b = 0; b < verticesFound.size(); b++)
  180. {
  181. unsigned int idx = verticesFound[b];
  182. if( vertexDone[idx])
  183. continue;
  184. if( meshNorm[idx] * origNorm < angleEpsilon)
  185. continue;
  186. if( meshTang[idx] * origTang < MAX_DIFF_ANGLE)
  187. continue;
  188. if( meshBitang[idx] * origBitang < MAX_DIFF_ANGLE)
  189. continue;
  190. // it's similar enough -> add it to the smoothing group
  191. closeVertices.push_back( idx);
  192. vertexDone[idx] = true;
  193. }
  194. // smooth the tangents and bitangents of all vertices that were found to be close enough
  195. aiVector3D smoothTangent( 0, 0, 0), smoothBitangent( 0, 0, 0);
  196. for( unsigned int b = 0; b < closeVertices.size(); b++)
  197. {
  198. smoothTangent += meshTang[ closeVertices[b] ];
  199. smoothBitangent += meshBitang[ closeVertices[b] ];
  200. }
  201. smoothTangent.Normalize();
  202. smoothBitangent.Normalize();
  203. // and write it back into all affected tangents
  204. for( unsigned int b = 0; b < closeVertices.size(); b++)
  205. {
  206. meshTang[ closeVertices[b] ] = smoothTangent;
  207. meshBitang[ closeVertices[b] ] = smoothBitangent;
  208. }
  209. }
  210. return true;
  211. }