assimpAppMesh.cpp 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "platform/platform.h"
  23. #include "ts/collada/colladaExtensions.h"
  24. #include "ts/assimp/assimpAppMesh.h"
  25. #if !defined(TORQUE_DISABLE_MEMORY_MANAGER)
  26. #ifdef new
  27. #undef new
  28. #endif
  29. #endif
  30. // assimp include files.
  31. #include <assimp/cimport.h>
  32. #include <assimp/scene.h>
  33. #include <assimp/postprocess.h>
  34. #include <assimp/types.h>
  35. #if !defined(TORQUE_DISABLE_MEMORY_MANAGER)
  36. # define _new new(__FILE__, __LINE__)
  37. # define new _new
  38. #endif
  39. bool AssimpAppMesh::fixedSizeEnabled = false;
  40. S32 AssimpAppMesh::fixedSize = 2;
  41. //------------------------------------------------------------------------------
  42. AssimpAppMesh::AssimpAppMesh(const struct aiMesh* mesh, AssimpAppNode* node)
  43. : mMeshData(mesh), appNode(node)
  44. {
  45. Con::printf("[ASSIMP] Mesh Created: %s for Node: %s", getName(), node->getName());
  46. // See if it's a skinned mesh
  47. mIsSkinMesh = false;
  48. for (U32 b = 0; b < mesh->mNumBones; b++)
  49. if (mMeshData->mBones[b]->mNumWeights > 0)
  50. {
  51. mIsSkinMesh = true;
  52. break;
  53. }
  54. }
  55. const char* AssimpAppMesh::getName(bool allowFixed)
  56. {
  57. // Some exporters add a 'PIVOT' or unnamed node between the mesh and the
  58. // actual object node. Detect this and return the object node name instead
  59. // of the pivot node.
  60. const char* nodeName = appNode->getName();
  61. if ( dStrEqual(nodeName, "null") || dStrEndsWith(nodeName, "PIVOT") )
  62. nodeName = appNode->getParentName();
  63. // If all geometry is being fixed to the same size, append the size
  64. // to the name
  65. return allowFixed && fixedSizeEnabled ? avar("%s %d", nodeName, fixedSize) : nodeName;
  66. }
  67. MatrixF AssimpAppMesh::getMeshTransform(F32 time)
  68. {
  69. return appNode->getNodeTransform(time);
  70. }
  71. void AssimpAppMesh::lockMesh(F32 t, const MatrixF& objOffset)
  72. {
  73. // After this function, the following are expected to be populated:
  74. // points, normals, uvs, primitives, indices
  75. // There is also colors and uv2s but those don't seem to be required.
  76. points.reserve(mMeshData->mNumVertices);
  77. uvs.reserve(mMeshData->mNumVertices);
  78. normals.reserve(mMeshData->mNumVertices);
  79. bool flipNormals = ColladaUtils::getOptions().invertNormals;
  80. bool noUVFound = false;
  81. for (U32 i = 0; i<mMeshData->mNumVertices; i++)
  82. {
  83. // Points and Normals
  84. aiVector3D pt = mMeshData->mVertices[i];
  85. aiVector3D nrm;
  86. if (mMeshData->HasNormals())
  87. nrm = mMeshData->mNormals[i];
  88. else
  89. nrm.Set(0, 0, 0);
  90. Point3F tmpVert;
  91. Point3F tmpNormal;
  92. tmpVert = Point3F(pt.x, pt.y, pt.z);
  93. tmpNormal = Point3F(nrm.x, nrm.y, nrm.z);
  94. if (flipNormals)
  95. tmpNormal *= -1.0f;
  96. objOffset.mulP(tmpVert);
  97. points.push_back(tmpVert);
  98. if (mMeshData->HasTextureCoords(0))
  99. {
  100. uvs.push_back(Point2F(mMeshData->mTextureCoords[0][i].x, mMeshData->mTextureCoords[0][i].y));
  101. }
  102. else
  103. {
  104. // I don't know if there's any solution to this issue.
  105. // If it's not mapped, it's not mapped.
  106. noUVFound = true;
  107. uvs.push_back(Point2F(1, 1));
  108. }
  109. // UV2s
  110. if (mMeshData->HasTextureCoords(1))
  111. {
  112. uv2s.push_back(Point2F(mMeshData->mTextureCoords[1][i].x, mMeshData->mTextureCoords[1][i].y));
  113. }
  114. // Vertex Colors
  115. if (mMeshData->HasVertexColors(0))
  116. {
  117. LinearColorF vColor(mMeshData->mColors[0][i].r,
  118. mMeshData->mColors[0][i].g,
  119. mMeshData->mColors[0][i].b,
  120. mMeshData->mColors[0][i].a);
  121. colors.push_back(vColor.toColorI());
  122. }
  123. //uvs.push_back(mModel->mVerts[i].texcoord);
  124. normals.push_back(tmpNormal);
  125. //edgeVerts.push_back(mModel->mVerts[i].edge);
  126. }
  127. U32 numFaces = mMeshData->mNumFaces;
  128. //primitives.reserve(numFaces);
  129. //Fetch the number of indices
  130. U32 indicesCount = 0;
  131. for (U32 i = 0; i < numFaces; i++)
  132. {
  133. indicesCount += mMeshData->mFaces[i].mNumIndices;
  134. }
  135. indices.reserve(indicesCount);
  136. // Create TSMesh primitive
  137. primitives.increment();
  138. TSDrawPrimitive& primitive = primitives.last();
  139. primitive.start = 0;
  140. primitive.matIndex = (TSDrawPrimitive::Triangles | TSDrawPrimitive::Indexed) | (S32)mMeshData->mMaterialIndex;
  141. primitive.numElements = indicesCount;
  142. for ( U32 n = 0; n < mMeshData->mNumFaces; ++n)
  143. {
  144. const struct aiFace* face = &mMeshData->mFaces[n];
  145. if ( face->mNumIndices == 3 )
  146. {
  147. U32 indexCount = face->mNumIndices;
  148. for (U32 ind = 0; ind < indexCount; ind++)
  149. {
  150. U32 index = face->mIndices[ind];
  151. indices.push_back(index);
  152. }
  153. }
  154. else
  155. {
  156. Con::printf("[ASSIMP] Non-Triangle Face Found. Indices: %d", face->mNumIndices);
  157. }
  158. }
  159. U32 boneCount = mMeshData->mNumBones;
  160. bones.setSize(boneCount);
  161. // Count the total number of weights for all of the bones.
  162. U32 totalWeights = 0;
  163. U32 nonZeroWeights = 0;
  164. for (U32 b = 0; b < boneCount; b++)
  165. totalWeights += mMeshData->mBones[b]->mNumWeights;
  166. // Assimp gives weights sorted by bone index. We need them in vertex order.
  167. Vector<F32> tmpWeight;
  168. Vector<S32> tmpBoneIndex;
  169. Vector<S32> tmpVertexIndex;
  170. tmpWeight.setSize(totalWeights);
  171. tmpBoneIndex.setSize(totalWeights);
  172. tmpVertexIndex.setSize(totalWeights);
  173. // Count the total number of weights for all of the bones.
  174. Map<String, aiNode*> boneLookup;
  175. for (U32 b = 0; b < boneCount; b++) {
  176. boneLookup[mMeshData->mBones[b]->mName.C_Str()] =
  177. AssimpAppNode::findChildNodeByName(mMeshData->mBones[b]->mName.C_Str(), appNode->mScene->mRootNode);
  178. }
  179. for (U32 b = 0; b < boneCount; b++)
  180. {
  181. const aiBone* bone = mMeshData->mBones[b];
  182. aiNode* nodePtr = boneLookup[bone->mName.C_Str()];
  183. bones[b] = nodePtr ? new AssimpAppNode(appNode->mScene, nodePtr) : new AssimpAppNode(appNode->mScene, appNode->mNode);
  184. MatrixF boneTransform;
  185. AssimpAppNode::assimpToTorqueMat(mMeshData->mBones[b]->mOffsetMatrix, boneTransform);
  186. Point3F boneScale = boneTransform.getScale();
  187. Point3F bonePos = boneTransform.getPosition();
  188. if (boneScale != Point3F::One && ColladaUtils::getOptions().ignoreNodeScale)
  189. {
  190. Point3F scaleMult = Point3F::One / boneScale;
  191. boneTransform.scale(scaleMult);
  192. bonePos /= scaleMult;
  193. }
  194. boneTransform.setPosition(bonePos);
  195. initialTransforms.push_back(boneTransform);
  196. //Weights
  197. U32 numWeights = mMeshData->mBones[b]->mNumWeights;
  198. for (U32 w = 0; w < numWeights; ++w)
  199. {
  200. aiVertexWeight* aiWeight = &mMeshData->mBones[b]->mWeights[w];
  201. if (aiWeight->mWeight > 0.0f)
  202. {
  203. tmpWeight[nonZeroWeights] = aiWeight->mWeight;
  204. tmpVertexIndex[nonZeroWeights] = aiWeight->mVertexId;
  205. tmpBoneIndex[nonZeroWeights] = b;
  206. nonZeroWeights++;
  207. }
  208. }
  209. }
  210. weight.setSize(nonZeroWeights);
  211. vertexIndex.setSize(nonZeroWeights);
  212. boneIndex.setSize(nonZeroWeights);
  213. // Copy the weights to our vectors in vertex order and
  214. // normalize vertex weights (force weights for each vert to sum to 1)
  215. U32 nextWeight = 0;
  216. for (U32 i = 0; i < mMeshData->mNumVertices; ++i)
  217. {
  218. U32 vertStart = nextWeight;
  219. F32 invTotalWeight = 0;
  220. for (U32 ind = 0; ind < nonZeroWeights; ++ind)
  221. {
  222. if (tmpVertexIndex[ind] == i)
  223. {
  224. weight[nextWeight] = tmpWeight[ind];
  225. invTotalWeight += tmpWeight[ind];
  226. vertexIndex[nextWeight] = tmpVertexIndex[ind];
  227. boneIndex[nextWeight] = tmpBoneIndex[ind];
  228. nextWeight++;
  229. }
  230. }
  231. // Now normalize the vertex weights
  232. if (invTotalWeight > 0.0)
  233. {
  234. invTotalWeight = 1.0f / invTotalWeight;
  235. for (U32 ind = vertStart; ind < nextWeight; ++ind)
  236. weight[ind] *= invTotalWeight;
  237. }
  238. }
  239. if ( noUVFound )
  240. Con::warnf("[ASSIMP] No UV Data for mesh.");
  241. }
  242. void AssimpAppMesh::lookupSkinData()
  243. { // This function is intentionally left blank. The skin data - bones, weights and indexes are
  244. // processed in lockMesh() with the rest of the mesh data.
  245. }
  246. F32 AssimpAppMesh::getVisValue(F32 t)
  247. {
  248. return 1.0f;
  249. }