IRRLoader.cpp 49 KB

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