IRRLoader.cpp 61 KB

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