XFileImporter.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2022, 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 XFileImporter.cpp
  35. * @brief Implementation of the XFile importer class
  36. */
  37. #ifndef ASSIMP_BUILD_NO_X_IMPORTER
  38. #include "AssetLib/X/XFileImporter.h"
  39. #include "AssetLib/X/XFileParser.h"
  40. #include "PostProcessing/ConvertToLHProcess.h"
  41. #include <assimp/TinyFormatter.h>
  42. #include <assimp/IOSystem.hpp>
  43. #include <assimp/scene.h>
  44. #include <assimp/DefaultLogger.hpp>
  45. #include <assimp/importerdesc.h>
  46. #include <cctype>
  47. #include <memory>
  48. namespace Assimp {
  49. using namespace Assimp::Formatter;
  50. static constexpr aiImporterDesc desc = {
  51. "Direct3D XFile Importer",
  52. "",
  53. "",
  54. "",
  55. aiImporterFlags_SupportTextFlavour | aiImporterFlags_SupportBinaryFlavour | aiImporterFlags_SupportCompressedFlavour,
  56. 1,
  57. 3,
  58. 1,
  59. 5,
  60. "x"
  61. };
  62. // ------------------------------------------------------------------------------------------------
  63. // Returns whether the class can handle the format of the given file.
  64. bool XFileImporter::CanRead(const std::string &pFile, IOSystem *pIOHandler, bool /*checkSig*/) const {
  65. static const uint32_t token[] = { AI_MAKE_MAGIC("xof ") };
  66. return CheckMagicToken(pIOHandler, pFile, token, AI_COUNT_OF(token));
  67. }
  68. // ------------------------------------------------------------------------------------------------
  69. // Get file extension list
  70. const aiImporterDesc *XFileImporter::GetInfo() const {
  71. return &desc;
  72. }
  73. // ------------------------------------------------------------------------------------------------
  74. // Imports the given file into the given scene structure.
  75. void XFileImporter::InternReadFile(const std::string &pFile, aiScene *pScene, IOSystem *pIOHandler) {
  76. // read file into memory
  77. std::unique_ptr<IOStream> file(pIOHandler->Open(pFile));
  78. if (file == nullptr) {
  79. throw DeadlyImportError("Failed to open file ", pFile, ".");
  80. }
  81. static const size_t MinSize = 16;
  82. size_t fileSize = file->FileSize();
  83. if (fileSize < MinSize) {
  84. throw DeadlyImportError("XFile is too small.");
  85. }
  86. // in the hope that binary files will never start with a BOM ...
  87. mBuffer.resize(fileSize + 1);
  88. file->Read(&mBuffer.front(), 1, fileSize);
  89. ConvertToUTF8(mBuffer);
  90. // parse the file into a temporary representation
  91. XFileParser parser(mBuffer);
  92. // and create the proper return structures out of it
  93. CreateDataRepresentationFromImport(pScene, parser.GetImportedData());
  94. // if nothing came from it, report it as error
  95. if (!pScene->mRootNode) {
  96. throw DeadlyImportError("XFile is ill-formatted - no content imported.");
  97. }
  98. }
  99. // ------------------------------------------------------------------------------------------------
  100. // Constructs the return data structure out of the imported data.
  101. void XFileImporter::CreateDataRepresentationFromImport(aiScene *pScene, XFile::Scene *pData) {
  102. // Read the global materials first so that meshes referring to them can find them later
  103. ConvertMaterials(pScene, pData->mGlobalMaterials);
  104. // copy nodes, extracting meshes and materials on the way
  105. pScene->mRootNode = CreateNodes(pScene, nullptr, pData->mRootNode);
  106. // extract animations
  107. CreateAnimations(pScene, pData);
  108. // read the global meshes that were stored outside of any node
  109. if (!pData->mGlobalMeshes.empty()) {
  110. // create a root node to hold them if there isn't any, yet
  111. if (pScene->mRootNode == nullptr) {
  112. pScene->mRootNode = new aiNode;
  113. pScene->mRootNode->mName.Set("$dummy_node");
  114. }
  115. // convert all global meshes and store them in the root node.
  116. // If there was one before, the global meshes now suddenly have its transformation matrix...
  117. // Don't know what to do there, I don't want to insert another node under the present root node
  118. // just to avoid this.
  119. CreateMeshes(pScene, pScene->mRootNode, pData->mGlobalMeshes);
  120. }
  121. if (!pScene->mRootNode) {
  122. throw DeadlyImportError("No root node");
  123. }
  124. // Convert everything to OpenGL space... it's the same operation as the conversion back, so we can reuse the step directly
  125. MakeLeftHandedProcess convertProcess;
  126. convertProcess.Execute(pScene);
  127. FlipWindingOrderProcess flipper;
  128. flipper.Execute(pScene);
  129. // finally: create a dummy material if not material was imported
  130. if (pScene->mNumMaterials == 0) {
  131. pScene->mNumMaterials = 1;
  132. // create the Material
  133. aiMaterial *mat = new aiMaterial;
  134. int shadeMode = (int)aiShadingMode_Gouraud;
  135. mat->AddProperty<int>(&shadeMode, 1, AI_MATKEY_SHADING_MODEL);
  136. // material colours
  137. int specExp = 1;
  138. aiColor3D clr = aiColor3D(0, 0, 0);
  139. mat->AddProperty(&clr, 1, AI_MATKEY_COLOR_EMISSIVE);
  140. mat->AddProperty(&clr, 1, AI_MATKEY_COLOR_SPECULAR);
  141. clr = aiColor3D(0.5f, 0.5f, 0.5f);
  142. mat->AddProperty(&clr, 1, AI_MATKEY_COLOR_DIFFUSE);
  143. mat->AddProperty(&specExp, 1, AI_MATKEY_SHININESS);
  144. pScene->mMaterials = new aiMaterial *[1];
  145. pScene->mMaterials[0] = mat;
  146. }
  147. }
  148. // ------------------------------------------------------------------------------------------------
  149. // Recursively creates scene nodes from the imported hierarchy.
  150. aiNode *XFileImporter::CreateNodes(aiScene *pScene, aiNode *pParent, const XFile::Node *pNode) {
  151. if (!pNode) {
  152. return nullptr;
  153. }
  154. // create node
  155. aiNode *node = new aiNode;
  156. node->mName.length = (ai_uint32)pNode->mName.length();
  157. node->mParent = pParent;
  158. memcpy(node->mName.data, pNode->mName.c_str(), pNode->mName.length());
  159. node->mName.data[node->mName.length] = 0;
  160. node->mTransformation = pNode->mTrafoMatrix;
  161. // convert meshes from the source node
  162. CreateMeshes(pScene, node, pNode->mMeshes);
  163. // handle children
  164. if (!pNode->mChildren.empty()) {
  165. node->mNumChildren = (unsigned int)pNode->mChildren.size();
  166. node->mChildren = new aiNode *[node->mNumChildren];
  167. for (unsigned int a = 0; a < pNode->mChildren.size(); ++a) {
  168. node->mChildren[a] = CreateNodes(pScene, node, pNode->mChildren[a]);
  169. }
  170. }
  171. return node;
  172. }
  173. // ------------------------------------------------------------------------------------------------
  174. // Creates the meshes for the given node.
  175. void XFileImporter::CreateMeshes(aiScene *pScene, aiNode *pNode, const std::vector<XFile::Mesh *> &pMeshes) {
  176. if (pMeshes.empty()) {
  177. return;
  178. }
  179. // create a mesh for each mesh-material combination in the source node
  180. std::vector<aiMesh *> meshes;
  181. for (unsigned int a = 0; a < pMeshes.size(); ++a) {
  182. XFile::Mesh *sourceMesh = pMeshes[a];
  183. if (nullptr == sourceMesh) {
  184. continue;
  185. }
  186. // first convert its materials so that we can find them with their index afterwards
  187. ConvertMaterials(pScene, sourceMesh->mMaterials);
  188. unsigned int numMaterials = std::max((unsigned int)sourceMesh->mMaterials.size(), 1u);
  189. for (unsigned int b = 0; b < numMaterials; ++b) {
  190. // collect the faces belonging to this material
  191. std::vector<unsigned int> faces;
  192. unsigned int numVertices = 0;
  193. if (!sourceMesh->mFaceMaterials.empty()) {
  194. // if there is a per-face material defined, select the faces with the corresponding material
  195. for (unsigned int c = 0; c < sourceMesh->mFaceMaterials.size(); ++c) {
  196. if (sourceMesh->mFaceMaterials[c] == b) {
  197. faces.push_back(c);
  198. numVertices += (unsigned int)sourceMesh->mPosFaces[c].mIndices.size();
  199. }
  200. }
  201. } else {
  202. // if there is no per-face material, place everything into one mesh
  203. for (unsigned int c = 0; c < sourceMesh->mPosFaces.size(); ++c) {
  204. faces.push_back(c);
  205. numVertices += (unsigned int)sourceMesh->mPosFaces[c].mIndices.size();
  206. }
  207. }
  208. // no faces/vertices using this material? strange...
  209. if (numVertices == 0) {
  210. continue;
  211. }
  212. // create a submesh using this material
  213. aiMesh *mesh = new aiMesh;
  214. meshes.push_back(mesh);
  215. // find the material in the scene's material list. Either own material
  216. // or referenced material, it should already have a valid index
  217. if (!sourceMesh->mFaceMaterials.empty()) {
  218. mesh->mMaterialIndex = static_cast<unsigned int>(sourceMesh->mMaterials[b].sceneIndex);
  219. } else {
  220. mesh->mMaterialIndex = 0;
  221. }
  222. // Create properly sized data arrays in the mesh. We store unique vertices per face,
  223. // as specified
  224. mesh->mNumVertices = numVertices;
  225. mesh->mVertices = new aiVector3D[numVertices];
  226. mesh->mNumFaces = (unsigned int)faces.size();
  227. mesh->mFaces = new aiFace[mesh->mNumFaces];
  228. // name
  229. mesh->mName.Set(sourceMesh->mName);
  230. // normals?
  231. if (sourceMesh->mNormals.size() > 0) {
  232. mesh->mNormals = new aiVector3D[numVertices];
  233. }
  234. // texture coords
  235. for (unsigned int c = 0; c < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++c) {
  236. if (!sourceMesh->mTexCoords[c].empty()) {
  237. mesh->mTextureCoords[c] = new aiVector3D[numVertices];
  238. }
  239. }
  240. // vertex colors
  241. for (unsigned int c = 0; c < AI_MAX_NUMBER_OF_COLOR_SETS; ++c) {
  242. if (!sourceMesh->mColors[c].empty()) {
  243. mesh->mColors[c] = new aiColor4D[numVertices];
  244. }
  245. }
  246. // now collect the vertex data of all data streams present in the imported mesh
  247. unsigned int newIndex(0);
  248. std::vector<unsigned int> orgPoints; // from which original point each new vertex stems
  249. orgPoints.resize(numVertices, 0);
  250. for (unsigned int c = 0; c < faces.size(); ++c) {
  251. unsigned int f = faces[c]; // index of the source face
  252. const XFile::Face &pf = sourceMesh->mPosFaces[f]; // position source face
  253. // create face. either triangle or triangle fan depending on the index count
  254. aiFace &df = mesh->mFaces[c]; // destination face
  255. df.mNumIndices = (unsigned int)pf.mIndices.size();
  256. df.mIndices = new unsigned int[df.mNumIndices];
  257. // collect vertex data for indices of this face
  258. for (unsigned int d = 0; d < df.mNumIndices; ++d) {
  259. df.mIndices[d] = newIndex;
  260. const unsigned int newIdx = pf.mIndices[d];
  261. if (newIdx >= sourceMesh->mPositions.size()) {
  262. continue;
  263. }
  264. orgPoints[newIndex] = pf.mIndices[d];
  265. // Position
  266. mesh->mVertices[newIndex] = sourceMesh->mPositions[pf.mIndices[d]];
  267. // Normal, if present
  268. if (mesh->HasNormals()) {
  269. if (sourceMesh->mNormFaces[f].mIndices.size() > d) {
  270. const size_t idx(sourceMesh->mNormFaces[f].mIndices[d]);
  271. if (idx < sourceMesh->mNormals.size()) {
  272. mesh->mNormals[newIndex] = sourceMesh->mNormals[idx];
  273. }
  274. }
  275. }
  276. // texture coord sets
  277. for (unsigned int e = 0; e < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++e) {
  278. if (mesh->HasTextureCoords(e)) {
  279. aiVector2D tex = sourceMesh->mTexCoords[e][pf.mIndices[d]];
  280. mesh->mTextureCoords[e][newIndex] = aiVector3D(tex.x, 1.0f - tex.y, 0.0f);
  281. }
  282. }
  283. // vertex color sets
  284. for (unsigned int e = 0; e < AI_MAX_NUMBER_OF_COLOR_SETS; ++e) {
  285. if (mesh->HasVertexColors(e)) {
  286. mesh->mColors[e][newIndex] = sourceMesh->mColors[e][pf.mIndices[d]];
  287. }
  288. }
  289. newIndex++;
  290. }
  291. }
  292. // there should be as much new vertices as we calculated before
  293. ai_assert(newIndex == numVertices);
  294. // convert all bones of the source mesh which influence vertices in this newly created mesh
  295. const std::vector<XFile::Bone> &bones = sourceMesh->mBones;
  296. std::vector<aiBone *> newBones;
  297. for (unsigned int c = 0; c < bones.size(); ++c) {
  298. const XFile::Bone &obone = bones[c];
  299. // set up a vertex-linear array of the weights for quick searching if a bone influences a vertex
  300. std::vector<ai_real> oldWeights(sourceMesh->mPositions.size(), 0.0);
  301. for (unsigned int d = 0; d < obone.mWeights.size(); ++d) {
  302. const unsigned int boneIdx = obone.mWeights[d].mVertex;
  303. if (boneIdx < obone.mWeights.size()) {
  304. oldWeights[obone.mWeights[d].mVertex] = obone.mWeights[d].mWeight;
  305. }
  306. }
  307. // collect all vertex weights that influence a vertex in the new mesh
  308. std::vector<aiVertexWeight> newWeights;
  309. newWeights.reserve(numVertices);
  310. for (unsigned int d = 0; d < orgPoints.size(); ++d) {
  311. // does the new vertex stem from an old vertex which was influenced by this bone?
  312. ai_real w = oldWeights[orgPoints[d]];
  313. if (w > 0.0) {
  314. newWeights.emplace_back(d, w);
  315. }
  316. }
  317. // if the bone has no weights in the newly created mesh, ignore it
  318. if (newWeights.empty()) {
  319. continue;
  320. }
  321. // create
  322. aiBone *nbone = new aiBone;
  323. newBones.push_back(nbone);
  324. // copy name and matrix
  325. nbone->mName.Set(obone.mName);
  326. nbone->mOffsetMatrix = obone.mOffsetMatrix;
  327. nbone->mNumWeights = (unsigned int)newWeights.size();
  328. nbone->mWeights = new aiVertexWeight[nbone->mNumWeights];
  329. for (unsigned int d = 0; d < newWeights.size(); ++d) {
  330. nbone->mWeights[d] = newWeights[d];
  331. }
  332. }
  333. // store the bones in the mesh
  334. mesh->mNumBones = (unsigned int)newBones.size();
  335. if (!newBones.empty()) {
  336. mesh->mBones = new aiBone *[mesh->mNumBones];
  337. std::copy(newBones.begin(), newBones.end(), mesh->mBones);
  338. }
  339. }
  340. }
  341. // reallocate scene mesh array to be large enough
  342. aiMesh **prevArray = pScene->mMeshes;
  343. pScene->mMeshes = new aiMesh *[pScene->mNumMeshes + meshes.size()];
  344. if (prevArray) {
  345. memcpy(pScene->mMeshes, prevArray, pScene->mNumMeshes * sizeof(aiMesh *));
  346. delete[] prevArray;
  347. }
  348. // allocate mesh index array in the node
  349. pNode->mNumMeshes = (unsigned int)meshes.size();
  350. pNode->mMeshes = new unsigned int[pNode->mNumMeshes];
  351. // store all meshes in the mesh library of the scene and store their indices in the node
  352. for (unsigned int a = 0; a < meshes.size(); a++) {
  353. pScene->mMeshes[pScene->mNumMeshes] = meshes[a];
  354. pNode->mMeshes[a] = pScene->mNumMeshes;
  355. pScene->mNumMeshes++;
  356. }
  357. }
  358. // ------------------------------------------------------------------------------------------------
  359. // Converts the animations from the given imported data and creates them in the scene.
  360. void XFileImporter::CreateAnimations(aiScene *pScene, const XFile::Scene *pData) {
  361. std::vector<aiAnimation *> newAnims;
  362. for (unsigned int a = 0; a < pData->mAnims.size(); ++a) {
  363. const XFile::Animation *anim = pData->mAnims[a];
  364. // some exporters mock me with empty animation tags.
  365. if (anim->mAnims.empty()) {
  366. continue;
  367. }
  368. // create a new animation to hold the data
  369. aiAnimation *nanim = new aiAnimation;
  370. newAnims.push_back(nanim);
  371. nanim->mName.Set(anim->mName);
  372. // duration will be determined by the maximum length
  373. nanim->mDuration = 0;
  374. nanim->mTicksPerSecond = pData->mAnimTicksPerSecond;
  375. nanim->mNumChannels = (unsigned int)anim->mAnims.size();
  376. nanim->mChannels = new aiNodeAnim *[nanim->mNumChannels];
  377. for (unsigned int b = 0; b < anim->mAnims.size(); ++b) {
  378. const XFile::AnimBone *bone = anim->mAnims[b];
  379. aiNodeAnim *nbone = new aiNodeAnim;
  380. nbone->mNodeName.Set(bone->mBoneName);
  381. nanim->mChannels[b] = nbone;
  382. // key-frames are given as combined transformation matrix keys
  383. if (!bone->mTrafoKeys.empty()) {
  384. nbone->mNumPositionKeys = (unsigned int)bone->mTrafoKeys.size();
  385. nbone->mPositionKeys = new aiVectorKey[nbone->mNumPositionKeys];
  386. nbone->mNumRotationKeys = (unsigned int)bone->mTrafoKeys.size();
  387. nbone->mRotationKeys = new aiQuatKey[nbone->mNumRotationKeys];
  388. nbone->mNumScalingKeys = (unsigned int)bone->mTrafoKeys.size();
  389. nbone->mScalingKeys = new aiVectorKey[nbone->mNumScalingKeys];
  390. for (unsigned int c = 0; c < bone->mTrafoKeys.size(); ++c) {
  391. // deconstruct each matrix into separate position, rotation and scaling
  392. double time = bone->mTrafoKeys[c].mTime;
  393. aiMatrix4x4 trafo = bone->mTrafoKeys[c].mMatrix;
  394. // extract position
  395. aiVector3D pos(trafo.a4, trafo.b4, trafo.c4);
  396. nbone->mPositionKeys[c].mTime = time;
  397. nbone->mPositionKeys[c].mValue = pos;
  398. // extract scaling
  399. aiVector3D scale;
  400. scale.x = aiVector3D(trafo.a1, trafo.b1, trafo.c1).Length();
  401. scale.y = aiVector3D(trafo.a2, trafo.b2, trafo.c2).Length();
  402. scale.z = aiVector3D(trafo.a3, trafo.b3, trafo.c3).Length();
  403. nbone->mScalingKeys[c].mTime = time;
  404. nbone->mScalingKeys[c].mValue = scale;
  405. // reconstruct rotation matrix without scaling
  406. aiMatrix3x3 rotmat(
  407. trafo.a1 / scale.x, trafo.a2 / scale.y, trafo.a3 / scale.z,
  408. trafo.b1 / scale.x, trafo.b2 / scale.y, trafo.b3 / scale.z,
  409. trafo.c1 / scale.x, trafo.c2 / scale.y, trafo.c3 / scale.z);
  410. // and convert it into a quaternion
  411. nbone->mRotationKeys[c].mTime = time;
  412. nbone->mRotationKeys[c].mValue = aiQuaternion(rotmat);
  413. }
  414. // longest lasting key sequence determines duration
  415. nanim->mDuration = std::max(nanim->mDuration, bone->mTrafoKeys.back().mTime);
  416. } else {
  417. // separate key sequences for position, rotation, scaling
  418. nbone->mNumPositionKeys = (unsigned int)bone->mPosKeys.size();
  419. if (nbone->mNumPositionKeys != 0) {
  420. nbone->mPositionKeys = new aiVectorKey[nbone->mNumPositionKeys];
  421. for (unsigned int c = 0; c < nbone->mNumPositionKeys; ++c) {
  422. aiVector3D pos = bone->mPosKeys[c].mValue;
  423. nbone->mPositionKeys[c].mTime = bone->mPosKeys[c].mTime;
  424. nbone->mPositionKeys[c].mValue = pos;
  425. }
  426. }
  427. // rotation
  428. nbone->mNumRotationKeys = (unsigned int)bone->mRotKeys.size();
  429. if (nbone->mNumRotationKeys != 0) {
  430. nbone->mRotationKeys = new aiQuatKey[nbone->mNumRotationKeys];
  431. for (unsigned int c = 0; c < nbone->mNumRotationKeys; ++c) {
  432. aiMatrix3x3 rotmat = bone->mRotKeys[c].mValue.GetMatrix();
  433. nbone->mRotationKeys[c].mTime = bone->mRotKeys[c].mTime;
  434. nbone->mRotationKeys[c].mValue = aiQuaternion(rotmat);
  435. nbone->mRotationKeys[c].mValue.w *= -1.0f; // needs quat inversion
  436. }
  437. }
  438. // scaling
  439. nbone->mNumScalingKeys = (unsigned int)bone->mScaleKeys.size();
  440. if (nbone->mNumScalingKeys != 0) {
  441. nbone->mScalingKeys = new aiVectorKey[nbone->mNumScalingKeys];
  442. for (unsigned int c = 0; c < nbone->mNumScalingKeys; c++)
  443. nbone->mScalingKeys[c] = bone->mScaleKeys[c];
  444. }
  445. // longest lasting key sequence determines duration
  446. if (bone->mPosKeys.size() > 0)
  447. nanim->mDuration = std::max(nanim->mDuration, bone->mPosKeys.back().mTime);
  448. if (bone->mRotKeys.size() > 0)
  449. nanim->mDuration = std::max(nanim->mDuration, bone->mRotKeys.back().mTime);
  450. if (bone->mScaleKeys.size() > 0)
  451. nanim->mDuration = std::max(nanim->mDuration, bone->mScaleKeys.back().mTime);
  452. }
  453. }
  454. }
  455. // store all converted animations in the scene
  456. if (newAnims.size() > 0) {
  457. pScene->mNumAnimations = (unsigned int)newAnims.size();
  458. pScene->mAnimations = new aiAnimation *[pScene->mNumAnimations];
  459. for (unsigned int a = 0; a < newAnims.size(); a++)
  460. pScene->mAnimations[a] = newAnims[a];
  461. }
  462. }
  463. // ------------------------------------------------------------------------------------------------
  464. // Converts all materials in the given array and stores them in the scene's material list.
  465. void XFileImporter::ConvertMaterials(aiScene *pScene, std::vector<XFile::Material> &pMaterials) {
  466. // count the non-referrer materials in the array
  467. unsigned int numNewMaterials(0);
  468. for (unsigned int a = 0; a < pMaterials.size(); ++a) {
  469. if (!pMaterials[a].mIsReference) {
  470. ++numNewMaterials;
  471. }
  472. }
  473. // resize the scene's material list to offer enough space for the new materials
  474. if (numNewMaterials > 0) {
  475. aiMaterial **prevMats = pScene->mMaterials;
  476. pScene->mMaterials = new aiMaterial *[pScene->mNumMaterials + numNewMaterials];
  477. if (nullptr != prevMats) {
  478. ::memcpy(pScene->mMaterials, prevMats, pScene->mNumMaterials * sizeof(aiMaterial *));
  479. delete[] prevMats;
  480. }
  481. }
  482. // convert all the materials given in the array
  483. for (unsigned int a = 0; a < pMaterials.size(); ++a) {
  484. XFile::Material &oldMat = pMaterials[a];
  485. if (oldMat.mIsReference) {
  486. // find the material it refers to by name, and store its index
  487. for (size_t b = 0; b < pScene->mNumMaterials; ++b) {
  488. aiString name;
  489. pScene->mMaterials[b]->Get(AI_MATKEY_NAME, name);
  490. if (strcmp(name.C_Str(), oldMat.mName.data()) == 0) {
  491. oldMat.sceneIndex = b;
  492. break;
  493. }
  494. }
  495. if (oldMat.sceneIndex == SIZE_MAX) {
  496. ASSIMP_LOG_WARN("Could not resolve global material reference \"", oldMat.mName, "\"");
  497. oldMat.sceneIndex = 0;
  498. }
  499. continue;
  500. }
  501. aiMaterial *mat = new aiMaterial;
  502. aiString name;
  503. name.Set(oldMat.mName);
  504. mat->AddProperty(&name, AI_MATKEY_NAME);
  505. // Shading model: hard-coded to PHONG, there is no such information in an XFile
  506. // FIX (aramis): If the specular exponent is 0, use gouraud shading. This is a bugfix
  507. // for some models in the SDK (e.g. good old tiny.x)
  508. int shadeMode = (int)oldMat.mSpecularExponent == 0.0f ? aiShadingMode_Gouraud : aiShadingMode_Phong;
  509. mat->AddProperty<int>(&shadeMode, 1, AI_MATKEY_SHADING_MODEL);
  510. // material colours
  511. // Unclear: there's no ambient colour, but emissive. What to put for ambient?
  512. // Probably nothing at all, let the user select a suitable default.
  513. mat->AddProperty(&oldMat.mEmissive, 1, AI_MATKEY_COLOR_EMISSIVE);
  514. mat->AddProperty(&oldMat.mDiffuse, 1, AI_MATKEY_COLOR_DIFFUSE);
  515. mat->AddProperty(&oldMat.mSpecular, 1, AI_MATKEY_COLOR_SPECULAR);
  516. mat->AddProperty(&oldMat.mSpecularExponent, 1, AI_MATKEY_SHININESS);
  517. // texture, if there is one
  518. if (1 == oldMat.mTextures.size()) {
  519. const XFile::TexEntry &otex = oldMat.mTextures.back();
  520. if (otex.mName.length()) {
  521. // if there is only one texture assume it contains the diffuse color
  522. aiString tex(otex.mName);
  523. if (otex.mIsNormalMap) {
  524. mat->AddProperty(&tex, AI_MATKEY_TEXTURE_NORMALS(0));
  525. } else {
  526. mat->AddProperty(&tex, AI_MATKEY_TEXTURE_DIFFUSE(0));
  527. }
  528. }
  529. } else {
  530. // Otherwise ... try to search for typical strings in the
  531. // texture's file name like 'bump' or 'diffuse'
  532. unsigned int iHM = 0, iNM = 0, iDM = 0, iSM = 0, iAM = 0, iEM = 0;
  533. for (unsigned int b = 0; b < oldMat.mTextures.size(); ++b) {
  534. const XFile::TexEntry &otex = oldMat.mTextures[b];
  535. std::string sz = otex.mName;
  536. if (!sz.length()) {
  537. continue;
  538. }
  539. // find the file name
  540. std::string::size_type s = sz.find_last_of("\\/");
  541. if (std::string::npos == s) {
  542. s = 0;
  543. }
  544. // cut off the file extension
  545. std::string::size_type sExt = sz.find_last_of('.');
  546. if (std::string::npos != sExt) {
  547. sz[sExt] = '\0';
  548. }
  549. // convert to lower case for easier comparison
  550. for (unsigned int c = 0; c < sz.length(); ++c) {
  551. sz[c] = (char)tolower((unsigned char)sz[c]);
  552. }
  553. // Place texture filename property under the corresponding name
  554. aiString tex(oldMat.mTextures[b].mName);
  555. // bump map
  556. if (std::string::npos != sz.find("bump", s) || std::string::npos != sz.find("height", s)) {
  557. mat->AddProperty(&tex, AI_MATKEY_TEXTURE_HEIGHT(iHM++));
  558. } else if (otex.mIsNormalMap || std::string::npos != sz.find("normal", s) || std::string::npos != sz.find("nm", s)) {
  559. mat->AddProperty(&tex, AI_MATKEY_TEXTURE_NORMALS(iNM++));
  560. } else if (std::string::npos != sz.find("spec", s) || std::string::npos != sz.find("glanz", s)) {
  561. mat->AddProperty(&tex, AI_MATKEY_TEXTURE_SPECULAR(iSM++));
  562. } else if (std::string::npos != sz.find("ambi", s) || std::string::npos != sz.find("env", s)) {
  563. mat->AddProperty(&tex, AI_MATKEY_TEXTURE_AMBIENT(iAM++));
  564. } else if (std::string::npos != sz.find("emissive", s) || std::string::npos != sz.find("self", s)) {
  565. mat->AddProperty(&tex, AI_MATKEY_TEXTURE_EMISSIVE(iEM++));
  566. } else {
  567. // Assume it is a diffuse texture
  568. mat->AddProperty(&tex, AI_MATKEY_TEXTURE_DIFFUSE(iDM++));
  569. }
  570. }
  571. }
  572. pScene->mMaterials[pScene->mNumMaterials] = mat;
  573. oldMat.sceneIndex = pScene->mNumMaterials;
  574. pScene->mNumMaterials++;
  575. }
  576. }
  577. } // namespace Assimp
  578. #endif // !! ASSIMP_BUILD_NO_X_IMPORTER