Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 
 
 
 

1478 строки
47 KiB

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