assimpAppMesh.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  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. void AssimpAppMesh::computeBounds(Box3F& bounds)
  43. {
  44. bounds = Box3F::Invalid;
  45. if (isSkin())
  46. {
  47. // Compute bounds for skinned mesh
  48. Vector<MatrixF> boneTransforms;
  49. boneTransforms.setSize(nodeIndex.size());
  50. // Calculate bone transformations
  51. for (S32 iBone = 0; iBone < boneTransforms.size(); iBone++) {
  52. MatrixF nodeMat = bones[iBone]->getNodeTransform(TSShapeLoader::DefaultTime);
  53. TSShapeLoader::zapScale(nodeMat); // Remove scaling to ensure uniform transformation
  54. boneTransforms[iBone].mul(nodeMat, initialTransforms[iBone]);
  55. }
  56. // Transform vertices using weighted bone transformations
  57. Vector<Point3F> transformedVerts;
  58. transformedVerts.setSize(initialVerts.size());
  59. transformedVerts.fill(Point3F::Zero);
  60. for (S32 iWeight = 0; iWeight < vertexIndex.size(); iWeight++) {
  61. const S32 vertIndex = vertexIndex[iWeight];
  62. const MatrixF& deltaTransform = boneTransforms[boneIndex[iWeight]];
  63. Point3F weightedVert;
  64. deltaTransform.mulP(initialVerts[vertIndex], &weightedVert);
  65. weightedVert *= weight[iWeight];
  66. transformedVerts[vertIndex] += weightedVert;
  67. }
  68. // Extend bounds using the transformed vertices
  69. for (const auto& vert : transformedVerts) {
  70. bounds.extend(vert);
  71. }
  72. }
  73. else
  74. {
  75. MatrixF transform = getMeshTransform(TSShapeLoader::DefaultTime);
  76. TSShapeLoader::zapScale(transform);
  77. for (S32 iVert = 0; iVert < points.size(); iVert++)
  78. {
  79. Point3F p;
  80. transform.mulP(points[iVert], &p);
  81. bounds.extend(p);
  82. }
  83. }
  84. }
  85. TSMesh* AssimpAppMesh::constructTSMesh()
  86. {
  87. TSMesh* tsmesh;
  88. if (isSkin())
  89. {
  90. TSSkinMesh* tsskin = new TSSkinMesh();
  91. tsmesh = tsskin;
  92. // Copy skin elements
  93. tsskin->weight = weight;
  94. tsskin->boneIndex = boneIndex;
  95. tsskin->vertexIndex = vertexIndex;
  96. tsskin->batchData.nodeIndex = nodeIndex;
  97. tsskin->batchData.initialTransforms = initialTransforms;
  98. tsskin->batchData.initialVerts = initialVerts;
  99. tsskin->batchData.initialNorms = initialNorms;
  100. }
  101. else
  102. {
  103. tsmesh = new TSMesh();
  104. }
  105. // Copy mesh elements
  106. tsmesh->mVerts = points;
  107. tsmesh->mNorms = normals;
  108. tsmesh->mTverts = uvs;
  109. tsmesh->mPrimitives = primitives;
  110. tsmesh->mIndices = indices;
  111. tsmesh->mColors = colors;
  112. tsmesh->mTverts2 = uv2s;
  113. // Finish initializing the shape
  114. computeBounds(tsmesh->mBounds);
  115. tsmesh->setFlags(flags);
  116. tsmesh->updateMeshFlags();
  117. //tsmesh->computeBounds();
  118. tsmesh->numFrames = numFrames;
  119. tsmesh->numMatFrames = numMatFrames;
  120. tsmesh->vertsPerFrame = vertsPerFrame;
  121. tsmesh->createTangents(tsmesh->mVerts, tsmesh->mNorms);
  122. tsmesh->mEncodedNorms.set(NULL, 0);
  123. return tsmesh;
  124. }
  125. AssimpAppMesh::AssimpAppMesh(const struct aiMesh* mesh, AssimpAppNode* node)
  126. : mMeshData(mesh), appNode(node)
  127. {
  128. Con::printf("[ASSIMP] Mesh Created: %s for Node: %s", getName(), node->getName());
  129. // See if it's a skinned mesh
  130. mIsSkinMesh = false;
  131. for (U32 b = 0; b < mesh->mNumBones; b++)
  132. if (mMeshData->mBones[b]->mNumWeights > 0)
  133. {
  134. mIsSkinMesh = true;
  135. break;
  136. }
  137. }
  138. const char* AssimpAppMesh::getName(bool allowFixed)
  139. {
  140. // Some exporters add a 'PIVOT' or unnamed node between the mesh and the
  141. // actual object node. Detect this and return the object node name instead
  142. // of the pivot node.
  143. const char* nodeName = appNode->getName();
  144. if ( dStrEqual(nodeName, "null") || dStrEndsWith(nodeName, "PIVOT") )
  145. nodeName = appNode->getParentName();
  146. // If all geometry is being fixed to the same size, append the size
  147. // to the name
  148. return allowFixed && fixedSizeEnabled ? avar("%s %d", nodeName, fixedSize) : nodeName;
  149. }
  150. MatrixF AssimpAppMesh::getMeshTransform(F32 time)
  151. {
  152. return appNode->getNodeTransform(time);
  153. }
  154. void AssimpAppMesh::lockMesh(F32 t, const MatrixF& objOffset)
  155. {
  156. // After this function, the following are expected to be populated:
  157. // points, normals, uvs, primitives, indices
  158. // There is also colors and uv2s but those don't seem to be required.
  159. points.reserve(mMeshData->mNumVertices);
  160. uvs.reserve(mMeshData->mNumVertices);
  161. normals.reserve(mMeshData->mNumVertices);
  162. bool flipNormals = ColladaUtils::getOptions().invertNormals;
  163. bool noUVFound = false;
  164. for (U32 i = 0; i<mMeshData->mNumVertices; i++)
  165. {
  166. // Points and Normals
  167. aiVector3D pt = mMeshData->mVertices[i];
  168. aiVector3D nrm;
  169. if (mMeshData->HasNormals())
  170. nrm = mMeshData->mNormals[i];
  171. else
  172. nrm.Set(0, 0, 0);
  173. Point3F tmpVert;
  174. Point3F tmpNormal;
  175. tmpVert = Point3F(pt.x, pt.y, pt.z);
  176. tmpNormal = Point3F(nrm.x, nrm.y, nrm.z);
  177. if (flipNormals)
  178. tmpNormal *= -1.0f;
  179. objOffset.mulP(tmpVert);
  180. points.push_back(tmpVert);
  181. if (mMeshData->HasTextureCoords(0))
  182. {
  183. uvs.push_back(Point2F(mMeshData->mTextureCoords[0][i].x, mMeshData->mTextureCoords[0][i].y));
  184. }
  185. else
  186. {
  187. // I don't know if there's any solution to this issue.
  188. // If it's not mapped, it's not mapped.
  189. noUVFound = true;
  190. uvs.push_back(Point2F(1, 1));
  191. }
  192. // UV2s
  193. if (mMeshData->HasTextureCoords(1))
  194. {
  195. uv2s.push_back(Point2F(mMeshData->mTextureCoords[1][i].x, mMeshData->mTextureCoords[1][i].y));
  196. }
  197. // Vertex Colors
  198. if (mMeshData->HasVertexColors(0))
  199. {
  200. LinearColorF vColor(mMeshData->mColors[0][i].r,
  201. mMeshData->mColors[0][i].g,
  202. mMeshData->mColors[0][i].b,
  203. mMeshData->mColors[0][i].a);
  204. colors.push_back(vColor.toColorI());
  205. }
  206. //uvs.push_back(mModel->mVerts[i].texcoord);
  207. normals.push_back(tmpNormal);
  208. //edgeVerts.push_back(mModel->mVerts[i].edge);
  209. }
  210. U32 numFaces = mMeshData->mNumFaces;
  211. //primitives.reserve(numFaces);
  212. //Fetch the number of indices
  213. U32 indicesCount = 0;
  214. for (U32 i = 0; i < numFaces; i++)
  215. {
  216. indicesCount += mMeshData->mFaces[i].mNumIndices;
  217. }
  218. indices.reserve(indicesCount);
  219. // Create TSMesh primitive
  220. primitives.increment();
  221. TSDrawPrimitive& primitive = primitives.last();
  222. primitive.start = 0;
  223. primitive.matIndex = (TSDrawPrimitive::Triangles | TSDrawPrimitive::Indexed) | (S32)mMeshData->mMaterialIndex;
  224. primitive.numElements = indicesCount;
  225. for ( U32 n = 0; n < mMeshData->mNumFaces; ++n)
  226. {
  227. const struct aiFace* face = &mMeshData->mFaces[n];
  228. if ( face->mNumIndices == 3 )
  229. {
  230. U32 indexCount = face->mNumIndices;
  231. for (U32 ind = 0; ind < indexCount; ind++)
  232. {
  233. U32 index = face->mIndices[ind];
  234. indices.push_back(index);
  235. }
  236. }
  237. else
  238. {
  239. Con::printf("[ASSIMP] Non-Triangle Face Found. Indices: %d", face->mNumIndices);
  240. }
  241. }
  242. U32 boneCount = mMeshData->mNumBones;
  243. bones.setSize(boneCount);
  244. // Count the total number of weights for all of the bones.
  245. U32 totalWeights = 0;
  246. U32 nonZeroWeights = 0;
  247. for (U32 b = 0; b < boneCount; b++)
  248. totalWeights += mMeshData->mBones[b]->mNumWeights;
  249. // Assimp gives weights sorted by bone index. We need them in vertex order.
  250. Vector<F32> tmpWeight;
  251. Vector<S32> tmpBoneIndex;
  252. Vector<S32> tmpVertexIndex;
  253. tmpWeight.setSize(totalWeights);
  254. tmpBoneIndex.setSize(totalWeights);
  255. tmpVertexIndex.setSize(totalWeights);
  256. // Count the total number of weights for all of the bones.
  257. Map<String, aiNode*> boneLookup;
  258. for (U32 b = 0; b < boneCount; b++) {
  259. boneLookup[mMeshData->mBones[b]->mName.C_Str()] =
  260. AssimpAppNode::findChildNodeByName(mMeshData->mBones[b]->mName.C_Str(), appNode->mScene->mRootNode);
  261. }
  262. for (U32 b = 0; b < boneCount; b++)
  263. {
  264. const aiBone* bone = mMeshData->mBones[b];
  265. aiNode* nodePtr = boneLookup[bone->mName.C_Str()];
  266. bones[b] = nodePtr ? new AssimpAppNode(appNode->mScene, nodePtr) : new AssimpAppNode(appNode->mScene, appNode->mNode);
  267. MatrixF boneTransform;
  268. AssimpAppNode::assimpToTorqueMat(mMeshData->mBones[b]->mOffsetMatrix, boneTransform);
  269. Point3F boneScale = boneTransform.getScale();
  270. Point3F bonePos = boneTransform.getPosition();
  271. if (boneScale != Point3F::One && ColladaUtils::getOptions().ignoreNodeScale)
  272. {
  273. Point3F scaleMult = Point3F::One / boneScale;
  274. boneTransform.scale(scaleMult);
  275. bonePos /= scaleMult;
  276. }
  277. bonePos *= ColladaUtils::getOptions().unit * ColladaUtils::getOptions().formatScaleFactor;
  278. boneTransform.setPosition(bonePos);
  279. initialTransforms.push_back(boneTransform);
  280. //Weights
  281. U32 numWeights = mMeshData->mBones[b]->mNumWeights;
  282. for (U32 w = 0; w < numWeights; ++w)
  283. {
  284. aiVertexWeight* aiWeight = &mMeshData->mBones[b]->mWeights[w];
  285. if (aiWeight->mWeight > 0.0f)
  286. {
  287. tmpWeight[nonZeroWeights] = aiWeight->mWeight;
  288. tmpVertexIndex[nonZeroWeights] = aiWeight->mVertexId;
  289. tmpBoneIndex[nonZeroWeights] = b;
  290. nonZeroWeights++;
  291. }
  292. }
  293. }
  294. weight.setSize(nonZeroWeights);
  295. vertexIndex.setSize(nonZeroWeights);
  296. boneIndex.setSize(nonZeroWeights);
  297. // Copy the weights to our vectors in vertex order and
  298. // normalize vertex weights (force weights for each vert to sum to 1)
  299. U32 nextWeight = 0;
  300. for (U32 i = 0; i < mMeshData->mNumVertices; ++i)
  301. {
  302. U32 vertStart = nextWeight;
  303. F32 invTotalWeight = 0;
  304. for (U32 ind = 0; ind < nonZeroWeights; ++ind)
  305. {
  306. if (tmpVertexIndex[ind] == i)
  307. {
  308. weight[nextWeight] = tmpWeight[ind];
  309. invTotalWeight += tmpWeight[ind];
  310. vertexIndex[nextWeight] = tmpVertexIndex[ind];
  311. boneIndex[nextWeight] = tmpBoneIndex[ind];
  312. nextWeight++;
  313. }
  314. }
  315. // Now normalize the vertex weights
  316. if (invTotalWeight > 0.0)
  317. {
  318. invTotalWeight = 1.0f / invTotalWeight;
  319. for (U32 ind = vertStart; ind < nextWeight; ++ind)
  320. weight[ind] *= invTotalWeight;
  321. }
  322. }
  323. if ( noUVFound )
  324. Con::warnf("[ASSIMP] No UV Data for mesh.");
  325. }
  326. void AssimpAppMesh::lookupSkinData()
  327. { // This function is intentionally left blank. The skin data - bones, weights and indexes are
  328. // processed in lockMesh() with the rest of the mesh data.
  329. }
  330. F32 AssimpAppMesh::getVisValue(F32 t)
  331. {
  332. return 1.0f;
  333. }