CalcTangentsProcess.cpp 10 KB

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