IRRLoader.cpp 48 KB

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