IRRLoader.cpp 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2018, 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 IRRLoader.cpp
  35. * @brief Implementation of the Irr importer class
  36. */
  37. #ifndef ASSIMP_BUILD_NO_IRR_IMPORTER
  38. #include "IRRLoader.h"
  39. #include <assimp/ParsingUtils.h>
  40. #include <assimp/fast_atof.h>
  41. #include <assimp/GenericProperty.h>
  42. #include <assimp/SceneCombiner.h>
  43. #include <assimp/StandardShapes.h>
  44. #include "Importer.h"
  45. // We need MathFunctions.h to compute the lcm/gcd of a number
  46. #include <assimp/MathFunctions.h>
  47. #include <memory>
  48. #include <assimp/DefaultLogger.hpp>
  49. #include <assimp/mesh.h>
  50. #include <assimp/material.h>
  51. #include <assimp/scene.h>
  52. #include <assimp/IOSystem.hpp>
  53. #include <assimp/postprocess.h>
  54. #include <assimp/importerdesc.h>
  55. using namespace Assimp;
  56. using namespace irr;
  57. using namespace irr::io;
  58. static const aiImporterDesc desc = {
  59. "Irrlicht Scene Reader",
  60. "",
  61. "",
  62. "http://irrlicht.sourceforge.net/",
  63. aiImporterFlags_SupportTextFlavour,
  64. 0,
  65. 0,
  66. 0,
  67. 0,
  68. "irr xml"
  69. };
  70. // ------------------------------------------------------------------------------------------------
  71. // Constructor to be privately used by Importer
  72. IRRImporter::IRRImporter()
  73. : fps(),
  74. configSpeedFlag()
  75. {}
  76. // ------------------------------------------------------------------------------------------------
  77. // Destructor, private as well
  78. IRRImporter::~IRRImporter()
  79. {}
  80. // ------------------------------------------------------------------------------------------------
  81. // Returns whether the class can handle the format of the given file.
  82. bool IRRImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler, bool checkSig) const {
  83. const std::string extension = GetExtension(pFile);
  84. if ( extension == "irr" ) {
  85. return true;
  86. } else if (extension == "xml" || checkSig) {
  87. /* If CanRead() is called in order to check whether we
  88. * support a specific file extension in general pIOHandler
  89. * might be NULL and it's our duty to return true here.
  90. */
  91. if ( nullptr == pIOHandler ) {
  92. return true;
  93. }
  94. const char* tokens[] = {"irr_scene"};
  95. return SearchFileHeaderForToken(pIOHandler,pFile,tokens,1);
  96. }
  97. return false;
  98. }
  99. // ------------------------------------------------------------------------------------------------
  100. const aiImporterDesc* IRRImporter::GetInfo () const
  101. {
  102. return &desc;
  103. }
  104. // ------------------------------------------------------------------------------------------------
  105. void IRRImporter::SetupProperties(const Importer* pImp)
  106. {
  107. // read the output frame rate of all node animation channels
  108. fps = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_IRR_ANIM_FPS,100);
  109. if (fps < 10.) {
  110. DefaultLogger::get()->error("IRR: Invalid FPS configuration");
  111. fps = 100;
  112. }
  113. // AI_CONFIG_FAVOUR_SPEED
  114. configSpeedFlag = (0 != pImp->GetPropertyInteger(AI_CONFIG_FAVOUR_SPEED,0));
  115. }
  116. // ------------------------------------------------------------------------------------------------
  117. // Build a mesh tha consists of a single squad (a side of a skybox)
  118. aiMesh* IRRImporter::BuildSingleQuadMesh(const SkyboxVertex& v1,
  119. const SkyboxVertex& v2,
  120. const SkyboxVertex& v3,
  121. const SkyboxVertex& v4)
  122. {
  123. // allocate and prepare the mesh
  124. aiMesh* out = new aiMesh();
  125. out->mPrimitiveTypes = aiPrimitiveType_POLYGON;
  126. out->mNumFaces = 1;
  127. // build the face
  128. out->mFaces = new aiFace[1];
  129. aiFace& face = out->mFaces[0];
  130. face.mNumIndices = 4;
  131. face.mIndices = new unsigned int[4];
  132. for (unsigned int i = 0; i < 4;++i)
  133. face.mIndices[i] = i;
  134. out->mNumVertices = 4;
  135. // copy vertex positions
  136. aiVector3D* vec = out->mVertices = new aiVector3D[4];
  137. *vec++ = v1.position;
  138. *vec++ = v2.position;
  139. *vec++ = v3.position;
  140. *vec = v4.position;
  141. // copy vertex normals
  142. vec = out->mNormals = new aiVector3D[4];
  143. *vec++ = v1.normal;
  144. *vec++ = v2.normal;
  145. *vec++ = v3.normal;
  146. *vec = v4.normal;
  147. // copy texture coordinates
  148. vec = out->mTextureCoords[0] = new aiVector3D[4];
  149. *vec++ = v1.uv;
  150. *vec++ = v2.uv;
  151. *vec++ = v3.uv;
  152. *vec = v4.uv;
  153. return out;
  154. }
  155. // ------------------------------------------------------------------------------------------------
  156. void IRRImporter::BuildSkybox(std::vector<aiMesh*>& meshes, std::vector<aiMaterial*> materials)
  157. {
  158. // Update the material of the skybox - replace the name and disable shading for skyboxes.
  159. for (unsigned int i = 0; i < 6;++i) {
  160. aiMaterial* out = ( aiMaterial* ) (*(materials.end()-(6-i)));
  161. aiString s;
  162. s.length = ::ai_snprintf( s.data, MAXLEN, "SkyboxSide_%u",i );
  163. out->AddProperty(&s,AI_MATKEY_NAME);
  164. int shading = aiShadingMode_NoShading;
  165. out->AddProperty(&shading,1,AI_MATKEY_SHADING_MODEL);
  166. }
  167. // Skyboxes are much more difficult. They are represented
  168. // by six single planes with different textures, so we'll
  169. // need to build six meshes.
  170. const ai_real l = 10.0; // the size used by Irrlicht
  171. // FRONT SIDE
  172. meshes.push_back( BuildSingleQuadMesh(
  173. SkyboxVertex(-l,-l,-l, 0, 0, 1, 1.0,1.0),
  174. SkyboxVertex( l,-l,-l, 0, 0, 1, 0.0,1.0),
  175. SkyboxVertex( l, l,-l, 0, 0, 1, 0.0,0.0),
  176. SkyboxVertex(-l, l,-l, 0, 0, 1, 1.0,0.0)) );
  177. meshes.back()->mMaterialIndex = static_cast<unsigned int>(materials.size()-6u);
  178. // LEFT SIDE
  179. meshes.push_back( BuildSingleQuadMesh(
  180. SkyboxVertex( l,-l,-l, -1, 0, 0, 1.0,1.0),
  181. SkyboxVertex( l,-l, l, -1, 0, 0, 0.0,1.0),
  182. SkyboxVertex( l, l, l, -1, 0, 0, 0.0,0.0),
  183. SkyboxVertex( l, l,-l, -1, 0, 0, 1.0,0.0)) );
  184. meshes.back()->mMaterialIndex = static_cast<unsigned int>(materials.size()-5u);
  185. // BACK SIDE
  186. meshes.push_back( BuildSingleQuadMesh(
  187. SkyboxVertex( l,-l, l, 0, 0, -1, 1.0,1.0),
  188. SkyboxVertex(-l,-l, l, 0, 0, -1, 0.0,1.0),
  189. SkyboxVertex(-l, l, l, 0, 0, -1, 0.0,0.0),
  190. SkyboxVertex( l, l, l, 0, 0, -1, 1.0,0.0)) );
  191. meshes.back()->mMaterialIndex = static_cast<unsigned int>(materials.size()-4u);
  192. // RIGHT SIDE
  193. meshes.push_back( BuildSingleQuadMesh(
  194. SkyboxVertex(-l,-l, l, 1, 0, 0, 1.0,1.0),
  195. SkyboxVertex(-l,-l,-l, 1, 0, 0, 0.0,1.0),
  196. SkyboxVertex(-l, l,-l, 1, 0, 0, 0.0,0.0),
  197. SkyboxVertex(-l, l, l, 1, 0, 0, 1.0,0.0)) );
  198. meshes.back()->mMaterialIndex = static_cast<unsigned int>(materials.size()-3u);
  199. // TOP SIDE
  200. meshes.push_back( BuildSingleQuadMesh(
  201. SkyboxVertex( l, l,-l, 0, -1, 0, 1.0,1.0),
  202. SkyboxVertex( l, l, l, 0, -1, 0, 0.0,1.0),
  203. SkyboxVertex(-l, l, l, 0, -1, 0, 0.0,0.0),
  204. SkyboxVertex(-l, l,-l, 0, -1, 0, 1.0,0.0)) );
  205. meshes.back()->mMaterialIndex = static_cast<unsigned int>(materials.size()-2u);
  206. // BOTTOM SIDE
  207. meshes.push_back( BuildSingleQuadMesh(
  208. SkyboxVertex( l,-l, l, 0, 1, 0, 0.0,0.0),
  209. SkyboxVertex( l,-l,-l, 0, 1, 0, 1.0,0.0),
  210. SkyboxVertex(-l,-l,-l, 0, 1, 0, 1.0,1.0),
  211. SkyboxVertex(-l,-l, l, 0, 1, 0, 0.0,1.0)) );
  212. meshes.back()->mMaterialIndex = static_cast<unsigned int>(materials.size()-1u);
  213. }
  214. // ------------------------------------------------------------------------------------------------
  215. void IRRImporter::CopyMaterial(std::vector<aiMaterial*>& materials,
  216. std::vector< std::pair<aiMaterial*, unsigned int> >& inmaterials,
  217. unsigned int& defMatIdx,
  218. aiMesh* mesh)
  219. {
  220. if (inmaterials.empty()) {
  221. // Do we have a default material? If not we need to create one
  222. if (UINT_MAX == defMatIdx)
  223. {
  224. defMatIdx = (unsigned int)materials.size();
  225. //TODO: add this materials to someone?
  226. /*aiMaterial* mat = new aiMaterial();
  227. aiString s;
  228. s.Set(AI_DEFAULT_MATERIAL_NAME);
  229. mat->AddProperty(&s,AI_MATKEY_NAME);
  230. aiColor3D c(0.6f,0.6f,0.6f);
  231. mat->AddProperty(&c,1,AI_MATKEY_COLOR_DIFFUSE);*/
  232. }
  233. mesh->mMaterialIndex = defMatIdx;
  234. return;
  235. }
  236. else if (inmaterials.size() > 1) {
  237. DefaultLogger::get()->info("IRR: Skipping additional materials");
  238. }
  239. mesh->mMaterialIndex = (unsigned int)materials.size();
  240. materials.push_back(inmaterials[0].first);
  241. }
  242. // ------------------------------------------------------------------------------------------------
  243. inline int ClampSpline(int idx, int size)
  244. {
  245. return ( idx<0 ? size+idx : ( idx>=size ? idx-size : idx ) );
  246. }
  247. // ------------------------------------------------------------------------------------------------
  248. inline void FindSuitableMultiple(int& angle)
  249. {
  250. if (angle < 3)angle = 3;
  251. else if (angle < 10) angle = 10;
  252. else if (angle < 20) angle = 20;
  253. else if (angle < 30) angle = 30;
  254. else
  255. {
  256. }
  257. }
  258. // ------------------------------------------------------------------------------------------------
  259. void IRRImporter::ComputeAnimations(Node* root, aiNode* real, std::vector<aiNodeAnim*>& anims)
  260. {
  261. ai_assert(NULL != root && NULL != real);
  262. // XXX totally WIP - doesn't produce proper results, need to evaluate
  263. // whether there's any use for Irrlicht's proprietary scene format
  264. // outside Irrlicht ...
  265. if (root->animators.empty()) {
  266. return;
  267. }
  268. unsigned int total = 0;
  269. for (std::list<Animator>::iterator it = root->animators.begin();it != root->animators.end(); ++it) {
  270. if ((*it).type == Animator::UNKNOWN || (*it).type == Animator::OTHER) {
  271. DefaultLogger::get()->warn("IRR: Skipping unknown or unsupported animator");
  272. continue;
  273. }
  274. ++total;
  275. }
  276. if (!total)return;
  277. else if (1 == total) {
  278. DefaultLogger::get()->warn("IRR: Adding dummy nodes to simulate multiple animators");
  279. }
  280. // NOTE: 1 tick == i millisecond
  281. unsigned int cur = 0;
  282. for (std::list<Animator>::iterator it = root->animators.begin();
  283. it != root->animators.end(); ++it)
  284. {
  285. if ((*it).type == Animator::UNKNOWN || (*it).type == Animator::OTHER)continue;
  286. Animator& in = *it ;
  287. aiNodeAnim* anim = new aiNodeAnim();
  288. if (cur != total-1) {
  289. // Build a new name - a prefix instead of a suffix because it is
  290. // easier to check against
  291. anim->mNodeName.length = ::ai_snprintf(anim->mNodeName.data, MAXLEN,
  292. "$INST_DUMMY_%i_%s",total-1,
  293. (root->name.length() ? root->name.c_str() : ""));
  294. // we'll also need to insert a dummy in the node hierarchy.
  295. aiNode* dummy = new aiNode();
  296. for (unsigned int i = 0; i < real->mParent->mNumChildren;++i)
  297. if (real->mParent->mChildren[i] == real)
  298. real->mParent->mChildren[i] = dummy;
  299. dummy->mParent = real->mParent;
  300. dummy->mName = anim->mNodeName;
  301. dummy->mNumChildren = 1;
  302. dummy->mChildren = new aiNode*[dummy->mNumChildren];
  303. dummy->mChildren[0] = real;
  304. // the transformation matrix of the dummy node is the identity
  305. real->mParent = dummy;
  306. }
  307. else anim->mNodeName.Set(root->name);
  308. ++cur;
  309. switch (in.type) {
  310. case Animator::ROTATION:
  311. {
  312. // -----------------------------------------------------
  313. // find out how long a full rotation will take
  314. // This is the least common multiple of 360.f and all
  315. // three euler angles. Although we'll surely find a
  316. // possible multiple (haha) it could be somewhat large
  317. // for our purposes. So we need to modify the angles
  318. // here in order to get good results.
  319. // -----------------------------------------------------
  320. int angles[3];
  321. angles[0] = (int)(in.direction.x*100);
  322. angles[1] = (int)(in.direction.y*100);
  323. angles[2] = (int)(in.direction.z*100);
  324. angles[0] %= 360;
  325. angles[1] %= 360;
  326. angles[2] %= 360;
  327. if ( (angles[0]*angles[1]) != 0 && (angles[1]*angles[2]) != 0 )
  328. {
  329. FindSuitableMultiple(angles[0]);
  330. FindSuitableMultiple(angles[1]);
  331. FindSuitableMultiple(angles[2]);
  332. }
  333. int lcm = 360;
  334. if (angles[0])
  335. lcm = Math::lcm(lcm,angles[0]);
  336. if (angles[1])
  337. lcm = Math::lcm(lcm,angles[1]);
  338. if (angles[2])
  339. lcm = Math::lcm(lcm,angles[2]);
  340. if (360 == lcm)
  341. break;
  342. #if 0
  343. // This can be a division through zero, but we don't care
  344. float f1 = (float)lcm / angles[0];
  345. float f2 = (float)lcm / angles[1];
  346. float f3 = (float)lcm / angles[2];
  347. #endif
  348. // find out how many time units we'll need for the finest
  349. // track (in seconds) - this defines the number of output
  350. // keys (fps * seconds)
  351. float max = 0.f;
  352. if (angles[0])
  353. max = (float)lcm / angles[0];
  354. if (angles[1])
  355. max = std::max(max, (float)lcm / angles[1]);
  356. if (angles[2])
  357. max = std::max(max, (float)lcm / angles[2]);
  358. anim->mNumRotationKeys = (unsigned int)(max*fps);
  359. anim->mRotationKeys = new aiQuatKey[anim->mNumRotationKeys];
  360. // begin with a zero angle
  361. aiVector3D angle;
  362. for (unsigned int i = 0; i < anim->mNumRotationKeys;++i)
  363. {
  364. // build the quaternion for the given euler angles
  365. aiQuatKey& q = anim->mRotationKeys[i];
  366. q.mValue = aiQuaternion(angle.x, angle.y, angle.z);
  367. q.mTime = (double)i;
  368. // increase the angle
  369. angle += in.direction;
  370. }
  371. // This animation is repeated and repeated ...
  372. anim->mPostState = anim->mPreState = aiAnimBehaviour_REPEAT;
  373. }
  374. break;
  375. case Animator::FLY_CIRCLE:
  376. {
  377. // -----------------------------------------------------
  378. // Find out how much time we'll need to perform a
  379. // full circle.
  380. // -----------------------------------------------------
  381. const double seconds = (1. / in.speed) / 1000.;
  382. const double tdelta = 1000. / fps;
  383. anim->mNumPositionKeys = (unsigned int) (fps * seconds);
  384. anim->mPositionKeys = new aiVectorKey[anim->mNumPositionKeys];
  385. // from Irrlicht, what else should we do than copying it?
  386. aiVector3D vecU,vecV;
  387. if (in.direction.y) {
  388. vecV = aiVector3D(50,0,0) ^ in.direction;
  389. }
  390. else vecV = aiVector3D(0,50,00) ^ in.direction;
  391. vecV.Normalize();
  392. vecU = (vecV ^ in.direction).Normalize();
  393. // build the output keys
  394. for (unsigned int i = 0; i < anim->mNumPositionKeys;++i) {
  395. aiVectorKey& key = anim->mPositionKeys[i];
  396. key.mTime = i * tdelta;
  397. const ai_real t = (ai_real) ( in.speed * key.mTime );
  398. key.mValue = in.circleCenter + in.circleRadius * ((vecU * std::cos(t)) + (vecV * std::sin(t)));
  399. }
  400. // This animation is repeated and repeated ...
  401. anim->mPostState = anim->mPreState = aiAnimBehaviour_REPEAT;
  402. }
  403. break;
  404. case Animator::FLY_STRAIGHT:
  405. {
  406. anim->mPostState = anim->mPreState = (in.loop ? aiAnimBehaviour_REPEAT : aiAnimBehaviour_CONSTANT);
  407. const double seconds = in.timeForWay / 1000.;
  408. const double tdelta = 1000. / fps;
  409. anim->mNumPositionKeys = (unsigned int) (fps * seconds);
  410. anim->mPositionKeys = new aiVectorKey[anim->mNumPositionKeys];
  411. aiVector3D diff = in.direction - in.circleCenter;
  412. const ai_real lengthOfWay = diff.Length();
  413. diff.Normalize();
  414. const double timeFactor = lengthOfWay / in.timeForWay;
  415. // build the output keys
  416. for (unsigned int i = 0; i < anim->mNumPositionKeys;++i) {
  417. aiVectorKey& key = anim->mPositionKeys[i];
  418. key.mTime = i * tdelta;
  419. key.mValue = in.circleCenter + diff * ai_real(timeFactor * key.mTime);
  420. }
  421. }
  422. break;
  423. case Animator::FOLLOW_SPLINE:
  424. {
  425. // repeat outside the defined time range
  426. anim->mPostState = anim->mPreState = aiAnimBehaviour_REPEAT;
  427. const int size = (int)in.splineKeys.size();
  428. if (!size) {
  429. // We have no point in the spline. That's bad. Really bad.
  430. DefaultLogger::get()->warn("IRR: Spline animators with no points defined");
  431. delete anim;anim = NULL;
  432. break;
  433. }
  434. else if (size == 1) {
  435. // We have just one point in the spline so we don't need the full calculation
  436. anim->mNumPositionKeys = 1;
  437. anim->mPositionKeys = new aiVectorKey[anim->mNumPositionKeys];
  438. anim->mPositionKeys[0].mValue = in.splineKeys[0].mValue;
  439. anim->mPositionKeys[0].mTime = 0.f;
  440. break;
  441. }
  442. unsigned int ticksPerFull = 15;
  443. anim->mNumPositionKeys = (unsigned int) ( ticksPerFull * fps );
  444. anim->mPositionKeys = new aiVectorKey[anim->mNumPositionKeys];
  445. for (unsigned int i = 0; i < anim->mNumPositionKeys;++i)
  446. {
  447. aiVectorKey& key = anim->mPositionKeys[i];
  448. const ai_real dt = (i * in.speed * ai_real( 0.001 ) );
  449. const ai_real u = dt - std::floor(dt);
  450. const int idx = (int)std::floor(dt) % size;
  451. // get the 4 current points to evaluate the spline
  452. const aiVector3D& p0 = in.splineKeys[ ClampSpline( idx - 1, size ) ].mValue;
  453. const aiVector3D& p1 = in.splineKeys[ ClampSpline( idx + 0, size ) ].mValue;
  454. const aiVector3D& p2 = in.splineKeys[ ClampSpline( idx + 1, size ) ].mValue;
  455. const aiVector3D& p3 = in.splineKeys[ ClampSpline( idx + 2, size ) ].mValue;
  456. // compute polynomials
  457. const ai_real u2 = u*u;
  458. const ai_real u3 = u2*2;
  459. const ai_real h1 = ai_real( 2.0 ) * u3 - ai_real( 3.0 ) * u2 + ai_real( 1.0 );
  460. const ai_real h2 = ai_real( -2.0 ) * u3 + ai_real( 3.0 ) * u3;
  461. const ai_real h3 = u3 - ai_real( 2.0 ) * u3;
  462. const ai_real h4 = u3 - u2;
  463. // compute the spline tangents
  464. const aiVector3D t1 = ( p2 - p0 ) * in.tightness;
  465. aiVector3D t2 = ( p3 - p1 ) * in.tightness;
  466. // and use them to get the interpolated point
  467. t2 = (h1 * p1 + p2 * h2 + t1 * h3 + h4 * t2);
  468. // build a simple translation matrix from it
  469. key.mValue = t2;
  470. key.mTime = (double) i;
  471. }
  472. }
  473. break;
  474. default:
  475. // UNKNOWN , OTHER
  476. break;
  477. };
  478. if (anim) {
  479. anims.push_back(anim);
  480. ++total;
  481. }
  482. }
  483. }
  484. // ------------------------------------------------------------------------------------------------
  485. // This function is maybe more generic than we'd need it here
  486. void SetupMapping (aiMaterial* mat, aiTextureMapping mode, const aiVector3D& axis = aiVector3D(0.f,0.f,-1.f))
  487. {
  488. // Check whether there are texture properties defined - setup
  489. // the desired texture mapping mode for all of them and ignore
  490. // all UV settings we might encounter. WE HAVE NO UVS!
  491. std::vector<aiMaterialProperty*> p;
  492. p.reserve(mat->mNumProperties+1);
  493. for (unsigned int i = 0; i < mat->mNumProperties;++i)
  494. {
  495. aiMaterialProperty* prop = mat->mProperties[i];
  496. if (!::strcmp( prop->mKey.data, "$tex.file")) {
  497. // Setup the mapping key
  498. aiMaterialProperty* m = new aiMaterialProperty();
  499. m->mKey.Set("$tex.mapping");
  500. m->mIndex = prop->mIndex;
  501. m->mSemantic = prop->mSemantic;
  502. m->mType = aiPTI_Integer;
  503. m->mDataLength = 4;
  504. m->mData = new char[4];
  505. *((int*)m->mData) = mode;
  506. p.push_back(prop);
  507. p.push_back(m);
  508. // Setup the mapping axis
  509. if (mode == aiTextureMapping_CYLINDER || mode == aiTextureMapping_PLANE || mode == aiTextureMapping_SPHERE) {
  510. m = new aiMaterialProperty();
  511. m->mKey.Set("$tex.mapaxis");
  512. m->mIndex = prop->mIndex;
  513. m->mSemantic = prop->mSemantic;
  514. m->mType = aiPTI_Float;
  515. m->mDataLength = 12;
  516. m->mData = new char[12];
  517. *((aiVector3D*)m->mData) = axis;
  518. p.push_back(m);
  519. }
  520. }
  521. else if (! ::strcmp( prop->mKey.data, "$tex.uvwsrc")) {
  522. delete mat->mProperties[i];
  523. }
  524. else p.push_back(prop);
  525. }
  526. if (p.empty())return;
  527. // rebuild the output array
  528. if (p.size() > mat->mNumAllocated) {
  529. delete[] mat->mProperties;
  530. mat->mProperties = new aiMaterialProperty*[p.size()*2];
  531. mat->mNumAllocated = static_cast<unsigned int>(p.size()*2);
  532. }
  533. mat->mNumProperties = (unsigned int)p.size();
  534. ::memcpy(mat->mProperties,&p[0],sizeof(void*)*mat->mNumProperties);
  535. }
  536. // ------------------------------------------------------------------------------------------------
  537. void IRRImporter::GenerateGraph(Node* root,aiNode* rootOut ,aiScene* scene,
  538. BatchLoader& batch,
  539. std::vector<aiMesh*>& meshes,
  540. std::vector<aiNodeAnim*>& anims,
  541. std::vector<AttachmentInfo>& attach,
  542. std::vector<aiMaterial*>& materials,
  543. unsigned int& defMatIdx)
  544. {
  545. unsigned int oldMeshSize = (unsigned int)meshes.size();
  546. //unsigned int meshTrafoAssign = 0;
  547. // Now determine the type of the node
  548. switch (root->type)
  549. {
  550. case Node::ANIMMESH:
  551. case Node::MESH:
  552. {
  553. if (!root->meshPath.length())
  554. break;
  555. // Get the loaded mesh from the scene and add it to
  556. // the list of all scenes to be attached to the
  557. // graph we're currently building
  558. aiScene* scene = batch.GetImport(root->id);
  559. if (!scene) {
  560. DefaultLogger::get()->error("IRR: Unable to load external file: " + root->meshPath);
  561. break;
  562. }
  563. attach.push_back(AttachmentInfo(scene,rootOut));
  564. // Now combine the material we've loaded for this mesh
  565. // with the real materials we got from the file. As we
  566. // don't execute any pp-steps on the file, the numbers
  567. // should be equal. If they are not, we can impossibly
  568. // do this ...
  569. if (root->materials.size() != (unsigned int)scene->mNumMaterials) {
  570. DefaultLogger::get()->warn("IRR: Failed to match imported materials "
  571. "with the materials found in the IRR scene file");
  572. break;
  573. }
  574. for (unsigned int i = 0; i < scene->mNumMaterials;++i) {
  575. // Delete the old material, we don't need it anymore
  576. delete scene->mMaterials[i];
  577. std::pair<aiMaterial*, unsigned int>& src = root->materials[i];
  578. scene->mMaterials[i] = src.first;
  579. }
  580. // NOTE: Each mesh should have exactly one material assigned,
  581. // but we do it in a separate loop if this behaviour changes
  582. // in future.
  583. for (unsigned int i = 0; i < scene->mNumMeshes;++i) {
  584. // Process material flags
  585. aiMesh* mesh = scene->mMeshes[i];
  586. // If "trans_vertex_alpha" mode is enabled, search all vertex colors
  587. // and check whether they have a common alpha value. This is quite
  588. // often the case so we can simply extract it to a shared oacity
  589. // value.
  590. std::pair<aiMaterial*, unsigned int>& src = root->materials[mesh->mMaterialIndex];
  591. aiMaterial* mat = (aiMaterial*)src.first;
  592. if (mesh->HasVertexColors(0) && src.second & AI_IRRMESH_MAT_trans_vertex_alpha)
  593. {
  594. bool bdo = true;
  595. for (unsigned int a = 1; a < mesh->mNumVertices;++a) {
  596. if (mesh->mColors[0][a].a != mesh->mColors[0][a-1].a) {
  597. bdo = false;
  598. break;
  599. }
  600. }
  601. if (bdo) {
  602. DefaultLogger::get()->info("IRR: Replacing mesh vertex alpha with common opacity");
  603. for (unsigned int a = 0; a < mesh->mNumVertices;++a)
  604. mesh->mColors[0][a].a = 1.f;
  605. mat->AddProperty(& mesh->mColors[0][0].a, 1, AI_MATKEY_OPACITY);
  606. }
  607. }
  608. // If we have a second texture coordinate set and a second texture
  609. // (either lightmap, normalmap, 2layered material) we need to
  610. // setup the correct UV index for it. The texture can either
  611. // be diffuse (lightmap & 2layer) or a normal map (normal & parallax)
  612. if (mesh->HasTextureCoords(1)) {
  613. int idx = 1;
  614. if (src.second & (AI_IRRMESH_MAT_solid_2layer | AI_IRRMESH_MAT_lightmap)) {
  615. mat->AddProperty(&idx,1,AI_MATKEY_UVWSRC_DIFFUSE(0));
  616. }
  617. else if (src.second & AI_IRRMESH_MAT_normalmap_solid) {
  618. mat->AddProperty(&idx,1,AI_MATKEY_UVWSRC_NORMALS(0));
  619. }
  620. }
  621. }
  622. }
  623. break;
  624. case Node::LIGHT:
  625. case Node::CAMERA:
  626. // We're already finished with lights and cameras
  627. break;
  628. case Node::SPHERE:
  629. {
  630. // Generate the sphere model. Our input parameter to
  631. // the sphere generation algorithm is the number of
  632. // subdivisions of each triangle - but here we have
  633. // the number of poylgons on a specific axis. Just
  634. // use some hardcoded limits to approximate this ...
  635. unsigned int mul = root->spherePolyCountX*root->spherePolyCountY;
  636. if (mul < 100)mul = 2;
  637. else if (mul < 300)mul = 3;
  638. else mul = 4;
  639. meshes.push_back(StandardShapes::MakeMesh(mul,
  640. &StandardShapes::MakeSphere));
  641. // Adjust scaling
  642. root->scaling *= root->sphereRadius/2;
  643. // Copy one output material
  644. CopyMaterial(materials, root->materials, defMatIdx, meshes.back());
  645. // Now adjust this output material - if there is a first texture
  646. // set, setup spherical UV mapping around the Y axis.
  647. SetupMapping ( (aiMaterial*) materials.back(), aiTextureMapping_SPHERE);
  648. }
  649. break;
  650. case Node::CUBE:
  651. {
  652. // Generate an unit cube first
  653. meshes.push_back(StandardShapes::MakeMesh(
  654. &StandardShapes::MakeHexahedron));
  655. // Adjust scaling
  656. root->scaling *= root->sphereRadius;
  657. // Copy one output material
  658. CopyMaterial(materials, root->materials, defMatIdx, meshes.back());
  659. // Now adjust this output material - if there is a first texture
  660. // set, setup cubic UV mapping
  661. SetupMapping ( (aiMaterial*) materials.back(), aiTextureMapping_BOX );
  662. }
  663. break;
  664. case Node::SKYBOX:
  665. {
  666. // A skybox is defined by six materials
  667. if (root->materials.size() < 6) {
  668. DefaultLogger::get()->error("IRR: There should be six materials for a skybox");
  669. break;
  670. }
  671. // copy those materials and generate 6 meshes for our new skybox
  672. materials.reserve(materials.size() + 6);
  673. for (unsigned int i = 0; i < 6;++i)
  674. materials.insert(materials.end(),root->materials[i].first);
  675. BuildSkybox(meshes,materials);
  676. // *************************************************************
  677. // Skyboxes will require a different code path for rendering,
  678. // so there must be a way for the user to add special support
  679. // for IRR skyboxes. We add a 'IRR.SkyBox_' prefix to the node.
  680. // *************************************************************
  681. root->name = "IRR.SkyBox_" + root->name;
  682. DefaultLogger::get()->info("IRR: Loading skybox, this will "
  683. "require special handling to be displayed correctly");
  684. }
  685. break;
  686. case Node::TERRAIN:
  687. {
  688. // to support terrains, we'd need to have a texture decoder
  689. DefaultLogger::get()->error("IRR: Unsupported node - TERRAIN");
  690. }
  691. break;
  692. default:
  693. // DUMMY
  694. break;
  695. };
  696. // Check whether we added a mesh (or more than one ...). In this case
  697. // we'll also need to attach it to the node
  698. if (oldMeshSize != (unsigned int) meshes.size()) {
  699. rootOut->mNumMeshes = (unsigned int)meshes.size() - oldMeshSize;
  700. rootOut->mMeshes = new unsigned int[rootOut->mNumMeshes];
  701. for (unsigned int a = 0; a < rootOut->mNumMeshes;++a) {
  702. rootOut->mMeshes[a] = oldMeshSize+a;
  703. }
  704. }
  705. // Setup the name of this node
  706. rootOut->mName.Set(root->name);
  707. // Now compute the final local transformation matrix of the
  708. // node from the given translation, rotation and scaling values.
  709. // (the rotation is given in Euler angles, XYZ order)
  710. //std::swap((float&)root->rotation.z,(float&)root->rotation.y);
  711. rootOut->mTransformation.FromEulerAnglesXYZ(AI_DEG_TO_RAD(root->rotation) );
  712. // apply scaling
  713. aiMatrix4x4& mat = rootOut->mTransformation;
  714. mat.a1 *= root->scaling.x;
  715. mat.b1 *= root->scaling.x;
  716. mat.c1 *= root->scaling.x;
  717. mat.a2 *= root->scaling.y;
  718. mat.b2 *= root->scaling.y;
  719. mat.c2 *= root->scaling.y;
  720. mat.a3 *= root->scaling.z;
  721. mat.b3 *= root->scaling.z;
  722. mat.c3 *= root->scaling.z;
  723. // apply translation
  724. mat.a4 += root->position.x;
  725. mat.b4 += root->position.y;
  726. mat.c4 += root->position.z;
  727. // now compute animations for the node
  728. ComputeAnimations(root,rootOut, anims);
  729. // Add all children recursively. First allocate enough storage
  730. // for them, then call us again
  731. rootOut->mNumChildren = (unsigned int)root->children.size();
  732. if (rootOut->mNumChildren) {
  733. rootOut->mChildren = new aiNode*[rootOut->mNumChildren];
  734. for (unsigned int i = 0; i < rootOut->mNumChildren;++i) {
  735. aiNode* node = rootOut->mChildren[i] = new aiNode();
  736. node->mParent = rootOut;
  737. GenerateGraph(root->children[i],node,scene,batch,meshes,
  738. anims,attach,materials,defMatIdx);
  739. }
  740. }
  741. }
  742. // ------------------------------------------------------------------------------------------------
  743. // Imports the given file into the given scene structure.
  744. void IRRImporter::InternReadFile( const std::string& pFile,
  745. aiScene* pScene, IOSystem* pIOHandler)
  746. {
  747. std::unique_ptr<IOStream> file( pIOHandler->Open( pFile));
  748. // Check whether we can read from the file
  749. if( file.get() == NULL)
  750. throw DeadlyImportError( "Failed to open IRR file " + pFile + "");
  751. // Construct the irrXML parser
  752. CIrrXML_IOStreamReader st(file.get());
  753. reader = createIrrXMLReader((IFileReadCallBack*) &st);
  754. // The root node of the scene
  755. Node* root = new Node(Node::DUMMY);
  756. root->parent = NULL;
  757. root->name = "<IRRSceneRoot>";
  758. // Current node parent
  759. Node* curParent = root;
  760. // Scenegraph node we're currently working on
  761. Node* curNode = NULL;
  762. // List of output cameras
  763. std::vector<aiCamera*> cameras;
  764. // List of output lights
  765. std::vector<aiLight*> lights;
  766. // Batch loader used to load external models
  767. BatchLoader batch(pIOHandler);
  768. // batch.SetBasePath(pFile);
  769. cameras.reserve(5);
  770. lights.reserve(5);
  771. bool inMaterials = false, inAnimator = false;
  772. unsigned int guessedAnimCnt = 0, guessedMeshCnt = 0, guessedMatCnt = 0;
  773. // Parse the XML file
  774. while (reader->read()) {
  775. switch (reader->getNodeType()) {
  776. case EXN_ELEMENT:
  777. if (!ASSIMP_stricmp(reader->getNodeName(),"node")) {
  778. // ***********************************************************************
  779. /* What we're going to do with the node depends
  780. * on its type:
  781. *
  782. * "mesh" - Load a mesh from an external file
  783. * "cube" - Generate a cube
  784. * "skybox" - Generate a skybox
  785. * "light" - A light source
  786. * "sphere" - Generate a sphere mesh
  787. * "animatedMesh" - Load an animated mesh from an external file
  788. * and join its animation channels with ours.
  789. * "empty" - A dummy node
  790. * "camera" - A camera
  791. * "terrain" - a terrain node (data comes from a heightmap)
  792. * "billboard", ""
  793. *
  794. * Each of these nodes can be animated and all can have multiple
  795. * materials assigned (except lights, cameras and dummies, of course).
  796. */
  797. // ***********************************************************************
  798. const char* sz = reader->getAttributeValueSafe("type");
  799. Node* nd;
  800. if (!ASSIMP_stricmp(sz,"mesh") || !ASSIMP_stricmp(sz,"octTree")) {
  801. // OctTree's and meshes are treated equally
  802. nd = new Node(Node::MESH);
  803. }
  804. else if (!ASSIMP_stricmp(sz,"cube")) {
  805. nd = new Node(Node::CUBE);
  806. ++guessedMeshCnt;
  807. // meshes.push_back(StandardShapes::MakeMesh(&StandardShapes::MakeHexahedron));
  808. }
  809. else if (!ASSIMP_stricmp(sz,"skybox")) {
  810. nd = new Node(Node::SKYBOX);
  811. guessedMeshCnt += 6;
  812. }
  813. else if (!ASSIMP_stricmp(sz,"camera")) {
  814. nd = new Node(Node::CAMERA);
  815. // Setup a temporary name for the camera
  816. aiCamera* cam = new aiCamera();
  817. cam->mName.Set( nd->name );
  818. cameras.push_back(cam);
  819. }
  820. else if (!ASSIMP_stricmp(sz,"light")) {
  821. nd = new Node(Node::LIGHT);
  822. // Setup a temporary name for the light
  823. aiLight* cam = new aiLight();
  824. cam->mName.Set( nd->name );
  825. lights.push_back(cam);
  826. }
  827. else if (!ASSIMP_stricmp(sz,"sphere")) {
  828. nd = new Node(Node::SPHERE);
  829. ++guessedMeshCnt;
  830. }
  831. else if (!ASSIMP_stricmp(sz,"animatedMesh")) {
  832. nd = new Node(Node::ANIMMESH);
  833. }
  834. else if (!ASSIMP_stricmp(sz,"empty")) {
  835. nd = new Node(Node::DUMMY);
  836. }
  837. else if (!ASSIMP_stricmp(sz,"terrain")) {
  838. nd = new Node(Node::TERRAIN);
  839. }
  840. else if (!ASSIMP_stricmp(sz,"billBoard")) {
  841. // We don't support billboards, so ignore them
  842. DefaultLogger::get()->error("IRR: Billboards are not supported by Assimp");
  843. nd = new Node(Node::DUMMY);
  844. }
  845. else {
  846. DefaultLogger::get()->warn("IRR: Found unknown node: " + std::string(sz));
  847. /* We skip the contents of nodes we don't know.
  848. * We parse the transformation and all animators
  849. * and skip the rest.
  850. */
  851. nd = new Node(Node::DUMMY);
  852. }
  853. /* Attach the newly created node to the scenegraph
  854. */
  855. curNode = nd;
  856. nd->parent = curParent;
  857. curParent->children.push_back(nd);
  858. }
  859. else if (!ASSIMP_stricmp(reader->getNodeName(),"materials")) {
  860. inMaterials = true;
  861. }
  862. else if (!ASSIMP_stricmp(reader->getNodeName(),"animators")) {
  863. inAnimator = true;
  864. }
  865. else if (!ASSIMP_stricmp(reader->getNodeName(),"attributes")) {
  866. /* We should have a valid node here
  867. * FIX: no ... the scene root node is also contained in an attributes block
  868. */
  869. if (!curNode) {
  870. #if 0
  871. DefaultLogger::get()->error("IRR: Encountered <attributes> element, but "
  872. "there is no node active");
  873. #endif
  874. continue;
  875. }
  876. Animator* curAnim = NULL;
  877. // Materials can occur for nearly any type of node
  878. if (inMaterials && curNode->type != Node::DUMMY) {
  879. /* This is a material description - parse it!
  880. */
  881. curNode->materials.push_back(std::pair< aiMaterial*, unsigned int > () );
  882. std::pair< aiMaterial*, unsigned int >& p = curNode->materials.back();
  883. p.first = ParseMaterial(p.second);
  884. ++guessedMatCnt;
  885. continue;
  886. }
  887. else if (inAnimator) {
  888. /* This is an animation path - add a new animator
  889. * to the list.
  890. */
  891. curNode->animators.push_back(Animator());
  892. curAnim = & curNode->animators.back();
  893. ++guessedAnimCnt;
  894. }
  895. /* Parse all elements in the attributes block
  896. * and process them.
  897. */
  898. while (reader->read()) {
  899. if (reader->getNodeType() == EXN_ELEMENT) {
  900. if (!ASSIMP_stricmp(reader->getNodeName(),"vector3d")) {
  901. VectorProperty prop;
  902. ReadVectorProperty(prop);
  903. if (inAnimator) {
  904. if (curAnim->type == Animator::ROTATION && prop.name == "Rotation") {
  905. // We store the rotation euler angles in 'direction'
  906. curAnim->direction = prop.value;
  907. }
  908. else if (curAnim->type == Animator::FOLLOW_SPLINE) {
  909. // Check whether the vector follows the PointN naming scheme,
  910. // here N is the ONE-based index of the point
  911. if (prop.name.length() >= 6 && prop.name.substr(0,5) == "Point") {
  912. // Add a new key to the list
  913. curAnim->splineKeys.push_back(aiVectorKey());
  914. aiVectorKey& key = curAnim->splineKeys.back();
  915. // and parse its properties
  916. key.mValue = prop.value;
  917. key.mTime = strtoul10(&prop.name[5]);
  918. }
  919. }
  920. else if (curAnim->type == Animator::FLY_CIRCLE) {
  921. if (prop.name == "Center") {
  922. curAnim->circleCenter = prop.value;
  923. }
  924. else if (prop.name == "Direction") {
  925. curAnim->direction = prop.value;
  926. // From Irrlicht's source - a workaround for backward compatibility with Irrlicht 1.1
  927. if (curAnim->direction == aiVector3D()) {
  928. curAnim->direction = aiVector3D(0.f,1.f,0.f);
  929. }
  930. else curAnim->direction.Normalize();
  931. }
  932. }
  933. else if (curAnim->type == Animator::FLY_STRAIGHT) {
  934. if (prop.name == "Start") {
  935. // We reuse the field here
  936. curAnim->circleCenter = prop.value;
  937. }
  938. else if (prop.name == "End") {
  939. // We reuse the field here
  940. curAnim->direction = prop.value;
  941. }
  942. }
  943. }
  944. else {
  945. if (prop.name == "Position") {
  946. curNode->position = prop.value;
  947. }
  948. else if (prop.name == "Rotation") {
  949. curNode->rotation = prop.value;
  950. }
  951. else if (prop.name == "Scale") {
  952. curNode->scaling = prop.value;
  953. }
  954. else if (Node::CAMERA == curNode->type)
  955. {
  956. aiCamera* cam = cameras.back();
  957. if (prop.name == "Target") {
  958. cam->mLookAt = prop.value;
  959. }
  960. else if (prop.name == "UpVector") {
  961. cam->mUp = prop.value;
  962. }
  963. }
  964. }
  965. }
  966. else if (!ASSIMP_stricmp(reader->getNodeName(),"bool")) {
  967. BoolProperty prop;
  968. ReadBoolProperty(prop);
  969. if (inAnimator && curAnim->type == Animator::FLY_CIRCLE && prop.name == "Loop") {
  970. curAnim->loop = prop.value;
  971. }
  972. }
  973. else if (!ASSIMP_stricmp(reader->getNodeName(),"float")) {
  974. FloatProperty prop;
  975. ReadFloatProperty(prop);
  976. if (inAnimator) {
  977. // The speed property exists for several animators
  978. if (prop.name == "Speed") {
  979. curAnim->speed = prop.value;
  980. }
  981. else if (curAnim->type == Animator::FLY_CIRCLE && prop.name == "Radius") {
  982. curAnim->circleRadius = prop.value;
  983. }
  984. else if (curAnim->type == Animator::FOLLOW_SPLINE && prop.name == "Tightness") {
  985. curAnim->tightness = prop.value;
  986. }
  987. }
  988. else {
  989. if (prop.name == "FramesPerSecond" && Node::ANIMMESH == curNode->type) {
  990. curNode->framesPerSecond = prop.value;
  991. }
  992. else if (Node::CAMERA == curNode->type) {
  993. /* This is the vertical, not the horizontal FOV.
  994. * We need to compute the right FOV from the
  995. * screen aspect which we don't know yet.
  996. */
  997. if (prop.name == "Fovy") {
  998. cameras.back()->mHorizontalFOV = prop.value;
  999. }
  1000. else if (prop.name == "Aspect") {
  1001. cameras.back()->mAspect = prop.value;
  1002. }
  1003. else if (prop.name == "ZNear") {
  1004. cameras.back()->mClipPlaneNear = prop.value;
  1005. }
  1006. else if (prop.name == "ZFar") {
  1007. cameras.back()->mClipPlaneFar = prop.value;
  1008. }
  1009. }
  1010. else if (Node::LIGHT == curNode->type) {
  1011. /* Additional light information
  1012. */
  1013. if (prop.name == "Attenuation") {
  1014. lights.back()->mAttenuationLinear = prop.value;
  1015. }
  1016. else if (prop.name == "OuterCone") {
  1017. lights.back()->mAngleOuterCone = AI_DEG_TO_RAD( prop.value );
  1018. }
  1019. else if (prop.name == "InnerCone") {
  1020. lights.back()->mAngleInnerCone = AI_DEG_TO_RAD( prop.value );
  1021. }
  1022. }
  1023. // radius of the sphere to be generated -
  1024. // or alternatively, size of the cube
  1025. else if ((Node::SPHERE == curNode->type && prop.name == "Radius")
  1026. || (Node::CUBE == curNode->type && prop.name == "Size" )) {
  1027. curNode->sphereRadius = prop.value;
  1028. }
  1029. }
  1030. }
  1031. else if (!ASSIMP_stricmp(reader->getNodeName(),"int")) {
  1032. IntProperty prop;
  1033. ReadIntProperty(prop);
  1034. if (inAnimator) {
  1035. if (curAnim->type == Animator::FLY_STRAIGHT && prop.name == "TimeForWay") {
  1036. curAnim->timeForWay = prop.value;
  1037. }
  1038. }
  1039. else {
  1040. // sphere polgon numbers in each direction
  1041. if (Node::SPHERE == curNode->type) {
  1042. if (prop.name == "PolyCountX") {
  1043. curNode->spherePolyCountX = prop.value;
  1044. }
  1045. else if (prop.name == "PolyCountY") {
  1046. curNode->spherePolyCountY = prop.value;
  1047. }
  1048. }
  1049. }
  1050. }
  1051. else if (!ASSIMP_stricmp(reader->getNodeName(),"string") ||!ASSIMP_stricmp(reader->getNodeName(),"enum")) {
  1052. StringProperty prop;
  1053. ReadStringProperty(prop);
  1054. if (prop.value.length()) {
  1055. if (prop.name == "Name") {
  1056. curNode->name = prop.value;
  1057. /* If we're either a camera or a light source
  1058. * we need to update the name in the aiLight/
  1059. * aiCamera structure, too.
  1060. */
  1061. if (Node::CAMERA == curNode->type) {
  1062. cameras.back()->mName.Set(prop.value);
  1063. }
  1064. else if (Node::LIGHT == curNode->type) {
  1065. lights.back()->mName.Set(prop.value);
  1066. }
  1067. }
  1068. else if (Node::LIGHT == curNode->type && "LightType" == prop.name)
  1069. {
  1070. if (prop.value == "Spot")
  1071. lights.back()->mType = aiLightSource_SPOT;
  1072. else if (prop.value == "Point")
  1073. lights.back()->mType = aiLightSource_POINT;
  1074. else if (prop.value == "Directional")
  1075. lights.back()->mType = aiLightSource_DIRECTIONAL;
  1076. else
  1077. {
  1078. // We won't pass the validation with aiLightSourceType_UNDEFINED,
  1079. // so we remove the light and replace it with a silly dummy node
  1080. delete lights.back();
  1081. lights.pop_back();
  1082. curNode->type = Node::DUMMY;
  1083. DefaultLogger::get()->error("Ignoring light of unknown type: " + prop.value);
  1084. }
  1085. }
  1086. else if ((prop.name == "Mesh" && Node::MESH == curNode->type) ||
  1087. Node::ANIMMESH == curNode->type)
  1088. {
  1089. /* This is the file name of the mesh - either
  1090. * animated or not. We need to make sure we setup
  1091. * the correct postprocessing settings here.
  1092. */
  1093. unsigned int pp = 0;
  1094. BatchLoader::PropertyMap map;
  1095. /* If the mesh is a static one remove all animations from the impor data
  1096. */
  1097. if (Node::ANIMMESH != curNode->type) {
  1098. pp |= aiProcess_RemoveComponent;
  1099. SetGenericProperty<int>(map.ints,AI_CONFIG_PP_RVC_FLAGS,
  1100. aiComponent_ANIMATIONS | aiComponent_BONEWEIGHTS);
  1101. }
  1102. /* TODO: maybe implement the protection against recursive
  1103. * loading calls directly in BatchLoader? The current
  1104. * implementation is not absolutely safe. A LWS and an IRR
  1105. * file referencing each other *could* cause the system to
  1106. * recurse forever.
  1107. */
  1108. const std::string extension = GetExtension(prop.value);
  1109. if ("irr" == extension) {
  1110. DefaultLogger::get()->error("IRR: Can't load another IRR file recursively");
  1111. }
  1112. else
  1113. {
  1114. curNode->id = batch.AddLoadRequest(prop.value,pp,&map);
  1115. curNode->meshPath = prop.value;
  1116. }
  1117. }
  1118. else if (inAnimator && prop.name == "Type")
  1119. {
  1120. // type of the animator
  1121. if (prop.value == "rotation") {
  1122. curAnim->type = Animator::ROTATION;
  1123. }
  1124. else if (prop.value == "flyCircle") {
  1125. curAnim->type = Animator::FLY_CIRCLE;
  1126. }
  1127. else if (prop.value == "flyStraight") {
  1128. curAnim->type = Animator::FLY_CIRCLE;
  1129. }
  1130. else if (prop.value == "followSpline") {
  1131. curAnim->type = Animator::FOLLOW_SPLINE;
  1132. }
  1133. else {
  1134. DefaultLogger::get()->warn("IRR: Ignoring unknown animator: "
  1135. + prop.value);
  1136. curAnim->type = Animator::UNKNOWN;
  1137. }
  1138. }
  1139. }
  1140. }
  1141. }
  1142. else if (reader->getNodeType() == EXN_ELEMENT_END && !ASSIMP_stricmp(reader->getNodeName(),"attributes")) {
  1143. break;
  1144. }
  1145. }
  1146. }
  1147. break;
  1148. case EXN_ELEMENT_END:
  1149. // If we reached the end of a node, we need to continue processing its parent
  1150. if (!ASSIMP_stricmp(reader->getNodeName(),"node")) {
  1151. if (!curNode) {
  1152. // currently is no node set. We need to go
  1153. // back in the node hierarchy
  1154. if (!curParent) {
  1155. curParent = root;
  1156. DefaultLogger::get()->error("IRR: Too many closing <node> elements");
  1157. }
  1158. else curParent = curParent->parent;
  1159. }
  1160. else curNode = NULL;
  1161. }
  1162. // clear all flags
  1163. else if (!ASSIMP_stricmp(reader->getNodeName(),"materials")) {
  1164. inMaterials = false;
  1165. }
  1166. else if (!ASSIMP_stricmp(reader->getNodeName(),"animators")) {
  1167. inAnimator = false;
  1168. }
  1169. break;
  1170. default:
  1171. // GCC complains that not all enumeration values are handled
  1172. break;
  1173. }
  1174. }
  1175. /* Now iterate through all cameras and compute their final (horizontal) FOV
  1176. */
  1177. for (aiCamera *cam : cameras) {
  1178. // screen aspect could be missing
  1179. if (cam->mAspect) {
  1180. cam->mHorizontalFOV *= cam->mAspect;
  1181. }
  1182. else DefaultLogger::get()->warn("IRR: Camera aspect is not given, can't compute horizontal FOV");
  1183. }
  1184. batch.LoadAll();
  1185. /* Allocate a tempoary scene data structure
  1186. */
  1187. aiScene* tempScene = new aiScene();
  1188. tempScene->mRootNode = new aiNode();
  1189. tempScene->mRootNode->mName.Set("<IRRRoot>");
  1190. /* Copy the cameras to the output array
  1191. */
  1192. if (!cameras.empty()) {
  1193. tempScene->mNumCameras = (unsigned int)cameras.size();
  1194. tempScene->mCameras = new aiCamera*[tempScene->mNumCameras];
  1195. ::memcpy(tempScene->mCameras,&cameras[0],sizeof(void*)*tempScene->mNumCameras);
  1196. }
  1197. /* Copy the light sources to the output array
  1198. */
  1199. if (!lights.empty()) {
  1200. tempScene->mNumLights = (unsigned int)lights.size();
  1201. tempScene->mLights = new aiLight*[tempScene->mNumLights];
  1202. ::memcpy(tempScene->mLights,&lights[0],sizeof(void*)*tempScene->mNumLights);
  1203. }
  1204. // temporary data
  1205. std::vector< aiNodeAnim*> anims;
  1206. std::vector< aiMaterial*> materials;
  1207. std::vector< AttachmentInfo > attach;
  1208. std::vector<aiMesh*> meshes;
  1209. // try to guess how much storage we'll need
  1210. anims.reserve (guessedAnimCnt + (guessedAnimCnt >> 2));
  1211. meshes.reserve (guessedMeshCnt + (guessedMeshCnt >> 2));
  1212. materials.reserve (guessedMatCnt + (guessedMatCnt >> 2));
  1213. /* Now process our scenegraph recursively: generate final
  1214. * meshes and generate animation channels for all nodes.
  1215. */
  1216. unsigned int defMatIdx = UINT_MAX;
  1217. GenerateGraph(root,tempScene->mRootNode, tempScene,
  1218. batch, meshes, anims, attach, materials, defMatIdx);
  1219. if (!anims.empty())
  1220. {
  1221. tempScene->mNumAnimations = 1;
  1222. tempScene->mAnimations = new aiAnimation*[tempScene->mNumAnimations];
  1223. aiAnimation* an = tempScene->mAnimations[0] = new aiAnimation();
  1224. // ***********************************************************
  1225. // This is only the global animation channel of the scene.
  1226. // If there are animated models, they will have separate
  1227. // animation channels in the scene. To display IRR scenes
  1228. // correctly, users will need to combine the global anim
  1229. // channel with all the local animations they want to play
  1230. // ***********************************************************
  1231. an->mName.Set("Irr_GlobalAnimChannel");
  1232. // copy all node animation channels to the global channel
  1233. an->mNumChannels = (unsigned int)anims.size();
  1234. an->mChannels = new aiNodeAnim*[an->mNumChannels];
  1235. ::memcpy(an->mChannels, & anims [0], sizeof(void*)*an->mNumChannels);
  1236. }
  1237. if (!meshes.empty()) {
  1238. // copy all meshes to the temporary scene
  1239. tempScene->mNumMeshes = (unsigned int)meshes.size();
  1240. tempScene->mMeshes = new aiMesh*[tempScene->mNumMeshes];
  1241. ::memcpy(tempScene->mMeshes,&meshes[0],tempScene->mNumMeshes*
  1242. sizeof(void*));
  1243. }
  1244. /* Copy all materials to the output array
  1245. */
  1246. if (!materials.empty()) {
  1247. tempScene->mNumMaterials = (unsigned int)materials.size();
  1248. tempScene->mMaterials = new aiMaterial*[tempScene->mNumMaterials];
  1249. ::memcpy(tempScene->mMaterials,&materials[0],sizeof(void*)*
  1250. tempScene->mNumMaterials);
  1251. }
  1252. /* Now merge all sub scenes and attach them to the correct
  1253. * attachment points in the scenegraph.
  1254. */
  1255. SceneCombiner::MergeScenes(&pScene,tempScene,attach,
  1256. AI_INT_MERGE_SCENE_GEN_UNIQUE_NAMES | (!configSpeedFlag ? (
  1257. AI_INT_MERGE_SCENE_GEN_UNIQUE_NAMES_IF_NECESSARY | AI_INT_MERGE_SCENE_GEN_UNIQUE_MATNAMES) : 0));
  1258. /* If we have no meshes | no materials now set the INCOMPLETE
  1259. * scene flag. This is necessary if we failed to load all
  1260. * models from external files
  1261. */
  1262. if (!pScene->mNumMeshes || !pScene->mNumMaterials) {
  1263. DefaultLogger::get()->warn("IRR: No meshes loaded, setting AI_SCENE_FLAGS_INCOMPLETE");
  1264. pScene->mFlags |= AI_SCENE_FLAGS_INCOMPLETE;
  1265. }
  1266. /* Finished ... everything destructs automatically and all
  1267. * temporary scenes have already been deleted by MergeScenes()
  1268. */
  1269. return;
  1270. }
  1271. #endif // !! ASSIMP_BUILD_NO_IRR_IMPORTER