Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 
 
 
 

319 rindas
12 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 calculate
  35. * tangents and bitangents for all imported meshes
  36. */
  37. #include "AssimpPCH.h"
  38. // internal headers
  39. #include "CalcTangentsProcess.h"
  40. #include "ProcessHelper.h"
  41. #include "TinyFormatter.h"
  42. using namespace Assimp;
  43. // ------------------------------------------------------------------------------------------------
  44. // Constructor to be privately used by Importer
  45. CalcTangentsProcess::CalcTangentsProcess()
  46. : configMaxAngle( AI_DEG_TO_RAD(45.f) )
  47. , configSourceUV( 0 ) {
  48. // nothing to do here
  49. }
  50. // ------------------------------------------------------------------------------------------------
  51. // Destructor, private as well
  52. CalcTangentsProcess::~CalcTangentsProcess()
  53. {
  54. // nothing to do here
  55. }
  56. // ------------------------------------------------------------------------------------------------
  57. // Returns whether the processing step is present in the given flag field.
  58. bool CalcTangentsProcess::IsActive( unsigned int pFlags) const
  59. {
  60. return (pFlags & aiProcess_CalcTangentSpace) != 0;
  61. }
  62. // ------------------------------------------------------------------------------------------------
  63. // Executes the post processing step on the given imported data.
  64. void CalcTangentsProcess::SetupProperties(const Importer* pImp)
  65. {
  66. ai_assert( NULL != pImp );
  67. // get the current value of the property
  68. configMaxAngle = pImp->GetPropertyFloat(AI_CONFIG_PP_CT_MAX_SMOOTHING_ANGLE,45.f);
  69. configMaxAngle = std::max(std::min(configMaxAngle,45.0f),0.0f);
  70. configMaxAngle = AI_DEG_TO_RAD(configMaxAngle);
  71. configSourceUV = pImp->GetPropertyInteger(AI_CONFIG_PP_CT_TEXTURE_CHANNEL_INDEX,0);
  72. }
  73. // ------------------------------------------------------------------------------------------------
  74. // Executes the post processing step on the given imported data.
  75. void CalcTangentsProcess::Execute( aiScene* pScene)
  76. {
  77. ai_assert( NULL != pScene );
  78. DefaultLogger::get()->debug("CalcTangentsProcess begin");
  79. bool bHas = false;
  80. for ( unsigned int a = 0; a < pScene->mNumMeshes; a++ ) {
  81. if(ProcessMesh( pScene->mMeshes[a],a))bHas = true;
  82. }
  83. if ( bHas ) {
  84. DefaultLogger::get()->info("CalcTangentsProcess finished. Tangents have been calculated");
  85. } else {
  86. DefaultLogger::get()->debug("CalcTangentsProcess finished");
  87. }
  88. }
  89. // ------------------------------------------------------------------------------------------------
  90. // Calculates tangents and bitangents for the given mesh
  91. bool CalcTangentsProcess::ProcessMesh( aiMesh* pMesh, unsigned int meshIndex)
  92. {
  93. // we assume that the mesh is still in the verbose vertex format where each face has its own set
  94. // of vertices and no vertices are shared between faces. Sadly I don't know any quick test to
  95. // assert() it here.
  96. //assert( must be verbose, dammit);
  97. if (pMesh->mTangents) // thisimplies that mBitangents is also there
  98. return false;
  99. // If the mesh consists of lines and/or points but not of
  100. // triangles or higher-order polygons the normal vectors
  101. // are undefined.
  102. if (!(pMesh->mPrimitiveTypes & (aiPrimitiveType_TRIANGLE | aiPrimitiveType_POLYGON)))
  103. {
  104. DefaultLogger::get()->info("Tangents are undefined for line and point meshes");
  105. return false;
  106. }
  107. // what we can check, though, is if the mesh has normals and texture coordinates. That's a requirement
  108. if( pMesh->mNormals == NULL)
  109. {
  110. DefaultLogger::get()->error("Failed to compute tangents; need normals");
  111. return false;
  112. }
  113. if( configSourceUV >= AI_MAX_NUMBER_OF_TEXTURECOORDS || !pMesh->mTextureCoords[configSourceUV] )
  114. {
  115. DefaultLogger::get()->error((Formatter::format("Failed to compute tangents; need UV data in channel"),configSourceUV));
  116. return false;
  117. }
  118. const float angleEpsilon = 0.9999f;
  119. std::vector<bool> vertexDone( pMesh->mNumVertices, false);
  120. const float qnan = get_qnan();
  121. // create space for the tangents and bitangents
  122. pMesh->mTangents = new aiVector3D[pMesh->mNumVertices];
  123. pMesh->mBitangents = new aiVector3D[pMesh->mNumVertices];
  124. const aiVector3D* meshPos = pMesh->mVertices;
  125. const aiVector3D* meshNorm = pMesh->mNormals;
  126. const aiVector3D* meshTex = pMesh->mTextureCoords[configSourceUV];
  127. aiVector3D* meshTang = pMesh->mTangents;
  128. aiVector3D* meshBitang = pMesh->mBitangents;
  129. // calculate the tangent and bitangent for every face
  130. for( unsigned int a = 0; a < pMesh->mNumFaces; a++)
  131. {
  132. const aiFace& face = pMesh->mFaces[a];
  133. if (face.mNumIndices < 3)
  134. {
  135. // There are less than three indices, thus the tangent vector
  136. // is not defined. We are finished with these vertices now,
  137. // their tangent vectors are set to qnan.
  138. for (unsigned int i = 0; i < face.mNumIndices;++i)
  139. {
  140. register unsigned int idx = face.mIndices[i];
  141. vertexDone [idx] = true;
  142. meshTang [idx] = aiVector3D(qnan);
  143. meshBitang [idx] = aiVector3D(qnan);
  144. }
  145. continue;
  146. }
  147. // triangle or polygon... we always use only the first three indices. A polygon
  148. // is supposed to be planar anyways....
  149. // FIXME: (thom) create correct calculation for multi-vertex polygons maybe?
  150. const unsigned int p0 = face.mIndices[0], p1 = face.mIndices[1], p2 = face.mIndices[2];
  151. // position differences p1->p2 and p1->p3
  152. aiVector3D v = meshPos[p1] - meshPos[p0], w = meshPos[p2] - meshPos[p0];
  153. // texture offset p1->p2 and p1->p3
  154. float sx = meshTex[p1].x - meshTex[p0].x, sy = meshTex[p1].y - meshTex[p0].y;
  155. float tx = meshTex[p2].x - meshTex[p0].x, ty = meshTex[p2].y - meshTex[p0].y;
  156. float dirCorrection = (tx * sy - ty * sx) < 0.0f ? -1.0f : 1.0f;
  157. // when t1, t2, t3 in same position in UV space, just use default UV direction.
  158. if ( 0 == sx && 0 ==sy && 0 == tx && 0 == ty ) {
  159. sx = 0.0; sy = 1.0;
  160. tx = 1.0; ty = 0.0;
  161. }
  162. // tangent points in the direction where to positive X axis of the texture coord's would point in model space
  163. // bitangent's points along the positive Y axis of the texture coord's, respectively
  164. aiVector3D tangent, bitangent;
  165. tangent.x = (w.x * sy - v.x * ty) * dirCorrection;
  166. tangent.y = (w.y * sy - v.y * ty) * dirCorrection;
  167. tangent.z = (w.z * sy - v.z * ty) * dirCorrection;
  168. bitangent.x = (w.x * sx - v.x * tx) * dirCorrection;
  169. bitangent.y = (w.y * sx - v.y * tx) * dirCorrection;
  170. bitangent.z = (w.z * sx - v.z * tx) * dirCorrection;
  171. // store for every vertex of that face
  172. for( unsigned int b = 0; b < face.mNumIndices; ++b ) {
  173. unsigned int p = face.mIndices[b];
  174. // project tangent and bitangent into the plane formed by the vertex' normal
  175. aiVector3D localTangent = tangent - meshNorm[p] * (tangent * meshNorm[p]);
  176. aiVector3D localBitangent = bitangent - meshNorm[p] * (bitangent * meshNorm[p]);
  177. localTangent.Normalize(); localBitangent.Normalize();
  178. // reconstruct tangent/bitangent according to normal and bitangent/tangent when it's infinite or NaN.
  179. bool invalid_tangent = is_special_float(localTangent.x) || is_special_float(localTangent.y) || is_special_float(localTangent.z);
  180. bool invalid_bitangent = is_special_float(localBitangent.x) || is_special_float(localBitangent.y) || is_special_float(localBitangent.z);
  181. if (invalid_tangent != invalid_bitangent) {
  182. if (invalid_tangent) {
  183. localTangent = meshNorm[p] ^ localBitangent;
  184. localTangent.Normalize();
  185. } else {
  186. localBitangent = localTangent ^ meshNorm[p];
  187. localBitangent.Normalize();
  188. }
  189. }
  190. // and write it into the mesh.
  191. meshTang[ p ] = localTangent;
  192. meshBitang[ p ] = localBitangent;
  193. }
  194. }
  195. // create a helper to quickly find locally close vertices among the vertex array
  196. // FIX: check whether we can reuse the SpatialSort of a previous step
  197. SpatialSort* vertexFinder = NULL;
  198. SpatialSort _vertexFinder;
  199. float posEpsilon;
  200. if (shared)
  201. {
  202. std::vector<std::pair<SpatialSort,float> >* avf;
  203. shared->GetProperty(AI_SPP_SPATIAL_SORT,avf);
  204. if (avf)
  205. {
  206. std::pair<SpatialSort,float>& blubb = avf->operator [] (meshIndex);
  207. vertexFinder = &blubb.first;
  208. posEpsilon = blubb.second;;
  209. }
  210. }
  211. if (!vertexFinder)
  212. {
  213. _vertexFinder.Fill(pMesh->mVertices, pMesh->mNumVertices, sizeof( aiVector3D));
  214. vertexFinder = &_vertexFinder;
  215. posEpsilon = ComputePositionEpsilon(pMesh);
  216. }
  217. std::vector<unsigned int> verticesFound;
  218. const float fLimit = cosf(configMaxAngle);
  219. std::vector<unsigned int> closeVertices;
  220. // in the second pass we now smooth out all tangents and bitangents at the same local position
  221. // if they are not too far off.
  222. for( unsigned int a = 0; a < pMesh->mNumVertices; a++)
  223. {
  224. if( vertexDone[a])
  225. continue;
  226. const aiVector3D& origPos = pMesh->mVertices[a];
  227. const aiVector3D& origNorm = pMesh->mNormals[a];
  228. const aiVector3D& origTang = pMesh->mTangents[a];
  229. const aiVector3D& origBitang = pMesh->mBitangents[a];
  230. closeVertices.clear();
  231. // find all vertices close to that position
  232. vertexFinder->FindPositions( origPos, posEpsilon, verticesFound);
  233. closeVertices.reserve (verticesFound.size()+5);
  234. closeVertices.push_back( a);
  235. // look among them for other vertices sharing the same normal and a close-enough tangent/bitangent
  236. for( unsigned int b = 0; b < verticesFound.size(); b++)
  237. {
  238. unsigned int idx = verticesFound[b];
  239. if( vertexDone[idx])
  240. continue;
  241. if( meshNorm[idx] * origNorm < angleEpsilon)
  242. continue;
  243. if( meshTang[idx] * origTang < fLimit)
  244. continue;
  245. if( meshBitang[idx] * origBitang < fLimit)
  246. continue;
  247. // it's similar enough -> add it to the smoothing group
  248. closeVertices.push_back( idx);
  249. vertexDone[idx] = true;
  250. }
  251. // smooth the tangents and bitangents of all vertices that were found to be close enough
  252. aiVector3D smoothTangent( 0, 0, 0), smoothBitangent( 0, 0, 0);
  253. for( unsigned int b = 0; b < closeVertices.size(); ++b)
  254. {
  255. smoothTangent += meshTang[ closeVertices[b] ];
  256. smoothBitangent += meshBitang[ closeVertices[b] ];
  257. }
  258. smoothTangent.Normalize();
  259. smoothBitangent.Normalize();
  260. // and write it back into all affected tangents
  261. for( unsigned int b = 0; b < closeVertices.size(); ++b)
  262. {
  263. meshTang[ closeVertices[b] ] = smoothTangent;
  264. meshBitang[ closeVertices[b] ] = smoothBitangent;
  265. }
  266. }
  267. return true;
  268. }