XFileImporter.cpp 30 KB

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