IRRLoader.cpp 61 KB

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