IRRMeshLoader.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2020, 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 Implementation of the IrrMesh importer class */
  35. #ifndef ASSIMP_BUILD_NO_IRRMESH_IMPORTER
  36. #include "IRRMeshLoader.h"
  37. #include <assimp/ParsingUtils.h>
  38. #include <assimp/fast_atof.h>
  39. #include <assimp/importerdesc.h>
  40. #include <assimp/material.h>
  41. #include <assimp/mesh.h>
  42. #include <assimp/scene.h>
  43. #include <assimp/DefaultLogger.hpp>
  44. #include <assimp/IOSystem.hpp>
  45. #include <memory>
  46. using namespace Assimp;
  47. static const aiImporterDesc desc = {
  48. "Irrlicht Mesh Reader",
  49. "",
  50. "",
  51. "http://irrlicht.sourceforge.net/",
  52. aiImporterFlags_SupportTextFlavour,
  53. 0,
  54. 0,
  55. 0,
  56. 0,
  57. "xml irrmesh"
  58. };
  59. // ------------------------------------------------------------------------------------------------
  60. // Constructor to be privately used by Importer
  61. IRRMeshImporter::IRRMeshImporter() :
  62. BaseImporter(),
  63. IrrlichtBase() {
  64. // empty
  65. }
  66. // ------------------------------------------------------------------------------------------------
  67. // Destructor, private as well
  68. IRRMeshImporter::~IRRMeshImporter() {}
  69. // ------------------------------------------------------------------------------------------------
  70. // Returns whether the class can handle the format of the given file.
  71. bool IRRMeshImporter::CanRead(const std::string &pFile, IOSystem *pIOHandler, bool checkSig) const {
  72. /* NOTE: A simple check for the file extension is not enough
  73. * here. Irrmesh and irr are easy, but xml is too generic
  74. * and could be collada, too. So we need to open the file and
  75. * search for typical tokens.
  76. */
  77. const std::string extension = GetExtension(pFile);
  78. if (extension == "irrmesh")
  79. return true;
  80. else if (extension == "xml" || checkSig) {
  81. /* If CanRead() is called to check whether the loader
  82. * supports a specific file extension in general we
  83. * must return true here.
  84. */
  85. if (!pIOHandler) return true;
  86. const char *tokens[] = { "irrmesh" };
  87. return SearchFileHeaderForToken(pIOHandler, pFile, tokens, 1);
  88. }
  89. return false;
  90. }
  91. // ------------------------------------------------------------------------------------------------
  92. // Get a list of all file extensions which are handled by this class
  93. const aiImporterDesc *IRRMeshImporter::GetInfo() const {
  94. return &desc;
  95. }
  96. static void releaseMaterial(aiMaterial **mat) {
  97. if (*mat != nullptr) {
  98. delete *mat;
  99. *mat = nullptr;
  100. }
  101. }
  102. static void releaseMesh(aiMesh **mesh) {
  103. if (*mesh != nullptr) {
  104. delete *mesh;
  105. *mesh = nullptr;
  106. }
  107. }
  108. // ------------------------------------------------------------------------------------------------
  109. // Imports the given file into the given scene structure.
  110. void IRRMeshImporter::InternReadFile(const std::string &pFile,
  111. aiScene *pScene, IOSystem *pIOHandler) {
  112. std::unique_ptr<IOStream> file(pIOHandler->Open(pFile));
  113. // Check whether we can read from the file
  114. if (file.get() == NULL)
  115. throw DeadlyImportError("Failed to open IRRMESH file " + pFile + "");
  116. // Construct the irrXML parser
  117. XmlParser parser;
  118. if (!parser.parse( file.get() )) {
  119. return;
  120. }
  121. XmlNode root = parser.getRootNode();
  122. // final data
  123. std::vector<aiMaterial *> materials;
  124. std::vector<aiMesh *> meshes;
  125. materials.reserve(5);
  126. meshes.reserve(5);
  127. // temporary data - current mesh buffer
  128. aiMaterial *curMat = nullptr;
  129. aiMesh *curMesh = nullptr;
  130. unsigned int curMatFlags = 0;
  131. std::vector<aiVector3D> curVertices, curNormals, curTangents, curBitangents;
  132. std::vector<aiColor4D> curColors;
  133. std::vector<aiVector3D> curUVs, curUV2s;
  134. // some temporary variables
  135. int textMeaning = 0;
  136. int vertexFormat = 0; // 0 = normal; 1 = 2 tcoords, 2 = tangents
  137. bool useColors = false;
  138. // Parse the XML file
  139. for (pugi::xml_node child : root.children()) {
  140. if (child.type() == pugi::node_element) {
  141. if (!ASSIMP_stricmp(child.name(), "buffer") && (curMat || curMesh)) {
  142. // end of previous buffer. A material and a mesh should be there
  143. if (!curMat || !curMesh) {
  144. ASSIMP_LOG_ERROR("IRRMESH: A buffer must contain a mesh and a material");
  145. releaseMaterial(&curMat);
  146. releaseMesh(&curMesh);
  147. } else {
  148. materials.push_back(curMat);
  149. meshes.push_back(curMesh);
  150. }
  151. curMat = nullptr;
  152. curMesh = nullptr;
  153. curVertices.clear();
  154. curColors.clear();
  155. curNormals.clear();
  156. curUV2s.clear();
  157. curUVs.clear();
  158. curTangents.clear();
  159. curBitangents.clear();
  160. }
  161. if (!ASSIMP_stricmp(child.name(), "material")) {
  162. if (curMat) {
  163. ASSIMP_LOG_WARN("IRRMESH: Only one material description per buffer, please");
  164. releaseMaterial(&curMat);
  165. }
  166. curMat = ParseMaterial(curMatFlags);
  167. }
  168. /* no else here! */ if (!ASSIMP_stricmp(child.name(), "vertices")) {
  169. pugi::xml_attribute attr = child.attribute("vertexCount");
  170. int num = attr.as_int();
  171. //int num = reader->getAttributeValueAsInt("vertexCount");
  172. if (!num) {
  173. // This is possible ... remove the mesh from the list and skip further reading
  174. ASSIMP_LOG_WARN("IRRMESH: Found mesh with zero vertices");
  175. releaseMaterial(&curMat);
  176. releaseMesh(&curMesh);
  177. textMeaning = 0;
  178. continue;
  179. }
  180. curVertices.reserve(num);
  181. curNormals.reserve(num);
  182. curColors.reserve(num);
  183. curUVs.reserve(num);
  184. // Determine the file format
  185. //const char *t = reader->getAttributeValueSafe("type");
  186. pugi::xml_attribute t = child.attribute("type");
  187. if (!ASSIMP_stricmp("2tcoords", t.name())) {
  188. curUV2s.reserve(num);
  189. vertexFormat = 1;
  190. if (curMatFlags & AI_IRRMESH_EXTRA_2ND_TEXTURE) {
  191. // *********************************************************
  192. // We have a second texture! So use this UV channel
  193. // for it. The 2nd texture can be either a normal
  194. // texture (solid_2layer or lightmap_xxx) or a normal
  195. // map (normal_..., parallax_...)
  196. // *********************************************************
  197. int idx = 1;
  198. aiMaterial *mat = (aiMaterial *)curMat;
  199. if (curMatFlags & AI_IRRMESH_MAT_lightmap) {
  200. mat->AddProperty(&idx, 1, AI_MATKEY_UVWSRC_LIGHTMAP(0));
  201. } else if (curMatFlags & AI_IRRMESH_MAT_normalmap_solid) {
  202. mat->AddProperty(&idx, 1, AI_MATKEY_UVWSRC_NORMALS(0));
  203. } else if (curMatFlags & AI_IRRMESH_MAT_solid_2layer) {
  204. mat->AddProperty(&idx, 1, AI_MATKEY_UVWSRC_DIFFUSE(1));
  205. }
  206. }
  207. } else if (!ASSIMP_stricmp("tangents", t.name())) {
  208. curTangents.reserve(num);
  209. curBitangents.reserve(num);
  210. vertexFormat = 2;
  211. } else if (ASSIMP_stricmp("standard", t.name())) {
  212. releaseMaterial(&curMat);
  213. ASSIMP_LOG_WARN("IRRMESH: Unknown vertex format");
  214. } else
  215. vertexFormat = 0;
  216. textMeaning = 1;
  217. } else if (!ASSIMP_stricmp(child.name(), "indices")) {
  218. if (curVertices.empty() && curMat) {
  219. releaseMaterial(&curMat);
  220. throw DeadlyImportError("IRRMESH: indices must come after vertices");
  221. }
  222. textMeaning = 2;
  223. // start a new mesh
  224. curMesh = new aiMesh();
  225. // allocate storage for all faces
  226. pugi::xml_attribute attr = child.attribute("indexCount");
  227. curMesh->mNumVertices = attr.as_int();
  228. if (!curMesh->mNumVertices) {
  229. // This is possible ... remove the mesh from the list and skip further reading
  230. ASSIMP_LOG_WARN("IRRMESH: Found mesh with zero indices");
  231. // mesh - away
  232. releaseMesh(&curMesh);
  233. // material - away
  234. releaseMaterial(&curMat);
  235. textMeaning = 0;
  236. continue;
  237. }
  238. if (curMesh->mNumVertices % 3) {
  239. ASSIMP_LOG_WARN("IRRMESH: Number if indices isn't divisible by 3");
  240. }
  241. curMesh->mNumFaces = curMesh->mNumVertices / 3;
  242. curMesh->mFaces = new aiFace[curMesh->mNumFaces];
  243. // setup some members
  244. curMesh->mMaterialIndex = (unsigned int)materials.size();
  245. curMesh->mPrimitiveTypes = aiPrimitiveType_TRIANGLE;
  246. // allocate storage for all vertices
  247. curMesh->mVertices = new aiVector3D[curMesh->mNumVertices];
  248. if (curNormals.size() == curVertices.size()) {
  249. curMesh->mNormals = new aiVector3D[curMesh->mNumVertices];
  250. }
  251. if (curTangents.size() == curVertices.size()) {
  252. curMesh->mTangents = new aiVector3D[curMesh->mNumVertices];
  253. }
  254. if (curBitangents.size() == curVertices.size()) {
  255. curMesh->mBitangents = new aiVector3D[curMesh->mNumVertices];
  256. }
  257. if (curColors.size() == curVertices.size() && useColors) {
  258. curMesh->mColors[0] = new aiColor4D[curMesh->mNumVertices];
  259. }
  260. if (curUVs.size() == curVertices.size()) {
  261. curMesh->mTextureCoords[0] = new aiVector3D[curMesh->mNumVertices];
  262. }
  263. if (curUV2s.size() == curVertices.size()) {
  264. curMesh->mTextureCoords[1] = new aiVector3D[curMesh->mNumVertices];
  265. }
  266. }
  267. //break;
  268. //case EXN_TEXT: {
  269. const char *sz = child.child_value();
  270. if (textMeaning == 1) {
  271. textMeaning = 0;
  272. // read vertices
  273. do {
  274. SkipSpacesAndLineEnd(&sz);
  275. aiVector3D temp;
  276. aiColor4D c;
  277. // Read the vertex position
  278. sz = fast_atoreal_move<float>(sz, (float &)temp.x);
  279. SkipSpaces(&sz);
  280. sz = fast_atoreal_move<float>(sz, (float &)temp.y);
  281. SkipSpaces(&sz);
  282. sz = fast_atoreal_move<float>(sz, (float &)temp.z);
  283. SkipSpaces(&sz);
  284. curVertices.push_back(temp);
  285. // Read the vertex normals
  286. sz = fast_atoreal_move<float>(sz, (float &)temp.x);
  287. SkipSpaces(&sz);
  288. sz = fast_atoreal_move<float>(sz, (float &)temp.y);
  289. SkipSpaces(&sz);
  290. sz = fast_atoreal_move<float>(sz, (float &)temp.z);
  291. SkipSpaces(&sz);
  292. curNormals.push_back(temp);
  293. // read the vertex colors
  294. uint32_t clr = strtoul16(sz, &sz);
  295. ColorFromARGBPacked(clr, c);
  296. if (!curColors.empty() && c != *(curColors.end() - 1))
  297. useColors = true;
  298. curColors.push_back(c);
  299. SkipSpaces(&sz);
  300. // read the first UV coordinate set
  301. sz = fast_atoreal_move<float>(sz, (float &)temp.x);
  302. SkipSpaces(&sz);
  303. sz = fast_atoreal_move<float>(sz, (float &)temp.y);
  304. SkipSpaces(&sz);
  305. temp.z = 0.f;
  306. temp.y = 1.f - temp.y; // DX to OGL
  307. curUVs.push_back(temp);
  308. // read the (optional) second UV coordinate set
  309. if (vertexFormat == 1) {
  310. sz = fast_atoreal_move<float>(sz, (float &)temp.x);
  311. SkipSpaces(&sz);
  312. sz = fast_atoreal_move<float>(sz, (float &)temp.y);
  313. temp.y = 1.f - temp.y; // DX to OGL
  314. curUV2s.push_back(temp);
  315. }
  316. // read optional tangent and bitangent vectors
  317. else if (vertexFormat == 2) {
  318. // tangents
  319. sz = fast_atoreal_move<float>(sz, (float &)temp.x);
  320. SkipSpaces(&sz);
  321. sz = fast_atoreal_move<float>(sz, (float &)temp.z);
  322. SkipSpaces(&sz);
  323. sz = fast_atoreal_move<float>(sz, (float &)temp.y);
  324. SkipSpaces(&sz);
  325. temp.y *= -1.0f;
  326. curTangents.push_back(temp);
  327. // bitangents
  328. sz = fast_atoreal_move<float>(sz, (float &)temp.x);
  329. SkipSpaces(&sz);
  330. sz = fast_atoreal_move<float>(sz, (float &)temp.z);
  331. SkipSpaces(&sz);
  332. sz = fast_atoreal_move<float>(sz, (float &)temp.y);
  333. SkipSpaces(&sz);
  334. temp.y *= -1.0f;
  335. curBitangents.push_back(temp);
  336. }
  337. }
  338. /* IMPORTANT: We assume that each vertex is specified in one
  339. line. So we can skip the rest of the line - unknown vertex
  340. elements are ignored.
  341. */
  342. while (SkipLine(&sz));
  343. } else if (textMeaning == 2) {
  344. textMeaning = 0;
  345. // read indices
  346. aiFace *curFace = curMesh->mFaces;
  347. aiFace *const faceEnd = curMesh->mFaces + curMesh->mNumFaces;
  348. aiVector3D *pcV = curMesh->mVertices;
  349. aiVector3D *pcN = curMesh->mNormals;
  350. aiVector3D *pcT = curMesh->mTangents;
  351. aiVector3D *pcB = curMesh->mBitangents;
  352. aiColor4D *pcC0 = curMesh->mColors[0];
  353. aiVector3D *pcT0 = curMesh->mTextureCoords[0];
  354. aiVector3D *pcT1 = curMesh->mTextureCoords[1];
  355. unsigned int curIdx = 0;
  356. unsigned int total = 0;
  357. while (SkipSpacesAndLineEnd(&sz)) {
  358. if (curFace >= faceEnd) {
  359. ASSIMP_LOG_ERROR("IRRMESH: Too many indices");
  360. break;
  361. }
  362. if (!curIdx) {
  363. curFace->mNumIndices = 3;
  364. curFace->mIndices = new unsigned int[3];
  365. }
  366. unsigned int idx = strtoul10(sz, &sz);
  367. if (idx >= curVertices.size()) {
  368. ASSIMP_LOG_ERROR("IRRMESH: Index out of range");
  369. idx = 0;
  370. }
  371. curFace->mIndices[curIdx] = total++;
  372. *pcV++ = curVertices[idx];
  373. if (pcN) *pcN++ = curNormals[idx];
  374. if (pcT) *pcT++ = curTangents[idx];
  375. if (pcB) *pcB++ = curBitangents[idx];
  376. if (pcC0) *pcC0++ = curColors[idx];
  377. if (pcT0) *pcT0++ = curUVs[idx];
  378. if (pcT1) *pcT1++ = curUV2s[idx];
  379. if (++curIdx == 3) {
  380. ++curFace;
  381. curIdx = 0;
  382. }
  383. }
  384. if (curFace != faceEnd)
  385. ASSIMP_LOG_ERROR("IRRMESH: Not enough indices");
  386. // Finish processing the mesh - do some small material workarounds
  387. if (curMatFlags & AI_IRRMESH_MAT_trans_vertex_alpha && !useColors) {
  388. // Take the opacity value of the current material
  389. // from the common vertex color alpha
  390. aiMaterial *mat = (aiMaterial *)curMat;
  391. mat->AddProperty(&curColors[0].a, 1, AI_MATKEY_OPACITY);
  392. }
  393. }
  394. }
  395. }
  396. // End of the last buffer. A material and a mesh should be there
  397. if (curMat || curMesh) {
  398. if (!curMat || !curMesh) {
  399. ASSIMP_LOG_ERROR("IRRMESH: A buffer must contain a mesh and a material");
  400. releaseMaterial(&curMat);
  401. releaseMesh(&curMesh);
  402. } else {
  403. materials.push_back(curMat);
  404. meshes.push_back(curMesh);
  405. }
  406. }
  407. if (materials.empty()) {
  408. throw DeadlyImportError("IRRMESH: Unable to read a mesh from this file");
  409. }
  410. // now generate the output scene
  411. pScene->mNumMeshes = (unsigned int)meshes.size();
  412. pScene->mMeshes = new aiMesh *[pScene->mNumMeshes];
  413. for (unsigned int i = 0; i < pScene->mNumMeshes; ++i) {
  414. pScene->mMeshes[i] = meshes[i];
  415. // clean this value ...
  416. pScene->mMeshes[i]->mNumUVComponents[3] = 0;
  417. }
  418. pScene->mNumMaterials = (unsigned int)materials.size();
  419. pScene->mMaterials = new aiMaterial *[pScene->mNumMaterials];
  420. ::memcpy(pScene->mMaterials, &materials[0], sizeof(void *) * pScene->mNumMaterials);
  421. pScene->mRootNode = new aiNode();
  422. pScene->mRootNode->mName.Set("<IRRMesh>");
  423. pScene->mRootNode->mNumMeshes = pScene->mNumMeshes;
  424. pScene->mRootNode->mMeshes = new unsigned int[pScene->mNumMeshes];
  425. for (unsigned int i = 0; i < pScene->mNumMeshes; ++i) {
  426. pScene->mRootNode->mMeshes[i] = i;
  427. }
  428. }
  429. #endif // !! ASSIMP_BUILD_NO_IRRMESH_IMPORTER