IRRMeshLoader.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2016, assimp team
  6. All rights reserved.
  7. Redistribution and use of this software in source and binary forms,
  8. with or without modification, are permitted provided that the following
  9. conditions are met:
  10. * Redistributions of source code must retain the above
  11. copyright notice, this list of conditions and the
  12. following disclaimer.
  13. * Redistributions in binary form must reproduce the above
  14. copyright notice, this list of conditions and the
  15. following disclaimer in the documentation and/or other
  16. materials provided with the distribution.
  17. * Neither the name of the assimp team, nor the names of its
  18. contributors may be used to endorse or promote products
  19. derived from this software without specific prior
  20. written permission of the assimp team.
  21. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  22. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  23. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  24. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  25. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  26. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  27. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  28. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  29. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  30. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  31. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  32. ---------------------------------------------------------------------------
  33. */
  34. /** @file Implementation of the IrrMesh importer class */
  35. #ifndef ASSIMP_BUILD_NO_IRRMESH_IMPORTER
  36. #include "IRRMeshLoader.h"
  37. #include "ParsingUtils.h"
  38. #include "fast_atof.h"
  39. #include <memory>
  40. #include <assimp/IOSystem.hpp>
  41. #include <assimp/mesh.h>
  42. #include <assimp/DefaultLogger.hpp>
  43. #include <assimp/material.h>
  44. #include <assimp/scene.h>
  45. #include "Macros.h"
  46. using namespace Assimp;
  47. using namespace irr;
  48. using namespace irr::io;
  49. static const aiImporterDesc desc = {
  50. "Irrlicht Mesh Reader",
  51. "",
  52. "",
  53. "http://irrlicht.sourceforge.net/",
  54. aiImporterFlags_SupportTextFlavour,
  55. 0,
  56. 0,
  57. 0,
  58. 0,
  59. "xml irrmesh"
  60. };
  61. // ------------------------------------------------------------------------------------------------
  62. // Constructor to be privately used by Importer
  63. IRRMeshImporter::IRRMeshImporter()
  64. {}
  65. // ------------------------------------------------------------------------------------------------
  66. // Destructor, private as well
  67. IRRMeshImporter::~IRRMeshImporter()
  68. {}
  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. {
  73. /* NOTE: A simple check for the file extension is not enough
  74. * here. Irrmesh and irr are easy, but xml is too generic
  75. * and could be collada, too. So we need to open the file and
  76. * search for typical tokens.
  77. */
  78. const std::string extension = GetExtension(pFile);
  79. if (extension == "irrmesh")return true;
  80. else if (extension == "xml" || checkSig)
  81. {
  82. /* If CanRead() is called to check whether the loader
  83. * supports a specific file extension in general we
  84. * must return true here.
  85. */
  86. if (!pIOHandler)return true;
  87. const char* tokens[] = {"irrmesh"};
  88. return SearchFileHeaderForToken(pIOHandler,pFile,tokens,1);
  89. }
  90. return false;
  91. }
  92. // ------------------------------------------------------------------------------------------------
  93. // Get a list of all file extensions which are handled by this class
  94. const aiImporterDesc* IRRMeshImporter::GetInfo () const
  95. {
  96. return &desc;
  97. }
  98. static void releaseMaterial( aiMaterial **mat ) {
  99. if(*mat!= nullptr) {
  100. delete *mat;
  101. *mat = nullptr;
  102. }
  103. }
  104. static void releaseMesh( aiMesh **mesh ) {
  105. if (*mesh != nullptr){
  106. delete *mesh;
  107. *mesh = nullptr;
  108. }
  109. }
  110. // ------------------------------------------------------------------------------------------------
  111. // Imports the given file into the given scene structure.
  112. void IRRMeshImporter::InternReadFile( const std::string& pFile,
  113. aiScene* pScene, IOSystem* pIOHandler)
  114. {
  115. std::unique_ptr<IOStream> file( pIOHandler->Open( pFile));
  116. // Check whether we can read from the file
  117. if( file.get() == NULL)
  118. throw DeadlyImportError( "Failed to open IRRMESH file " + pFile + "");
  119. // Construct the irrXML parser
  120. CIrrXML_IOStreamReader st(file.get());
  121. reader = createIrrXMLReader((IFileReadCallBack*) &st);
  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. while (reader->read()) {
  140. switch (reader->getNodeType()) {
  141. case EXN_ELEMENT:
  142. if (!ASSIMP_stricmp(reader->getNodeName(),"buffer") && (curMat || curMesh)) {
  143. // end of previous buffer. A material and a mesh should be there
  144. if ( !curMat || !curMesh) {
  145. DefaultLogger::get()->error("IRRMESH: A buffer must contain a mesh and a material");
  146. releaseMaterial( &curMat );
  147. releaseMesh( &curMesh );
  148. } else {
  149. materials.push_back(curMat);
  150. meshes.push_back(curMesh);
  151. }
  152. curMat = nullptr;
  153. curMesh = nullptr;
  154. curVertices.clear();
  155. curColors.clear();
  156. curNormals.clear();
  157. curUV2s.clear();
  158. curUVs.clear();
  159. curTangents.clear();
  160. curBitangents.clear();
  161. }
  162. if (!ASSIMP_stricmp(reader->getNodeName(),"material")) {
  163. if (curMat) {
  164. DefaultLogger::get()->warn("IRRMESH: Only one material description per buffer, please");
  165. releaseMaterial( &curMat );
  166. }
  167. curMat = ParseMaterial(curMatFlags);
  168. }
  169. /* no else here! */ if (!ASSIMP_stricmp(reader->getNodeName(),"vertices"))
  170. {
  171. int num = reader->getAttributeValueAsInt("vertexCount");
  172. if (!num) {
  173. // This is possible ... remove the mesh from the list and skip further reading
  174. DefaultLogger::get()->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. if (!ASSIMP_stricmp("2tcoords", t)) {
  187. curUV2s.reserve (num);
  188. vertexFormat = 1;
  189. if (curMatFlags & AI_IRRMESH_EXTRA_2ND_TEXTURE) {
  190. // *********************************************************
  191. // We have a second texture! So use this UV channel
  192. // for it. The 2nd texture can be either a normal
  193. // texture (solid_2layer or lightmap_xxx) or a normal
  194. // map (normal_..., parallax_...)
  195. // *********************************************************
  196. int idx = 1;
  197. aiMaterial* mat = ( aiMaterial* ) curMat;
  198. if (curMatFlags & AI_IRRMESH_MAT_lightmap){
  199. mat->AddProperty(&idx,1,AI_MATKEY_UVWSRC_LIGHTMAP(0));
  200. }
  201. else if (curMatFlags & AI_IRRMESH_MAT_normalmap_solid){
  202. mat->AddProperty(&idx,1,AI_MATKEY_UVWSRC_NORMALS(0));
  203. }
  204. else if (curMatFlags & AI_IRRMESH_MAT_solid_2layer) {
  205. mat->AddProperty(&idx,1,AI_MATKEY_UVWSRC_DIFFUSE(1));
  206. }
  207. }
  208. }
  209. else if (!ASSIMP_stricmp("tangents", t)) {
  210. curTangents.reserve (num);
  211. curBitangents.reserve (num);
  212. vertexFormat = 2;
  213. }
  214. else if (ASSIMP_stricmp("standard", t)) {
  215. releaseMaterial( &curMat );
  216. DefaultLogger::get()->warn("IRRMESH: Unknown vertex format");
  217. }
  218. else vertexFormat = 0;
  219. textMeaning = 1;
  220. }
  221. else if (!ASSIMP_stricmp(reader->getNodeName(),"indices")) {
  222. if (curVertices.empty() && curMat) {
  223. releaseMaterial( &curMat );
  224. throw DeadlyImportError("IRRMESH: indices must come after vertices");
  225. }
  226. textMeaning = 2;
  227. // start a new mesh
  228. curMesh = new aiMesh();
  229. // allocate storage for all faces
  230. curMesh->mNumVertices = reader->getAttributeValueAsInt("indexCount");
  231. if (!curMesh->mNumVertices) {
  232. // This is possible ... remove the mesh from the list and skip further reading
  233. DefaultLogger::get()->warn("IRRMESH: Found mesh with zero indices");
  234. // mesh - away
  235. releaseMesh( &curMesh );
  236. // material - away
  237. releaseMaterial( &curMat );
  238. textMeaning = 0;
  239. continue;
  240. }
  241. if (curMesh->mNumVertices % 3) {
  242. DefaultLogger::get()->warn("IRRMESH: Number if indices isn't divisible by 3");
  243. }
  244. curMesh->mNumFaces = curMesh->mNumVertices / 3;
  245. curMesh->mFaces = new aiFace[curMesh->mNumFaces];
  246. // setup some members
  247. curMesh->mMaterialIndex = (unsigned int)materials.size();
  248. curMesh->mPrimitiveTypes = aiPrimitiveType_TRIANGLE;
  249. // allocate storage for all vertices
  250. curMesh->mVertices = new aiVector3D[curMesh->mNumVertices];
  251. if (curNormals.size() == curVertices.size()) {
  252. curMesh->mNormals = new aiVector3D[curMesh->mNumVertices];
  253. }
  254. if (curTangents.size() == curVertices.size()) {
  255. curMesh->mTangents = new aiVector3D[curMesh->mNumVertices];
  256. }
  257. if (curBitangents.size() == curVertices.size()) {
  258. curMesh->mBitangents = new aiVector3D[curMesh->mNumVertices];
  259. }
  260. if (curColors.size() == curVertices.size() && useColors) {
  261. curMesh->mColors[0] = new aiColor4D[curMesh->mNumVertices];
  262. }
  263. if (curUVs.size() == curVertices.size()) {
  264. curMesh->mTextureCoords[0] = new aiVector3D[curMesh->mNumVertices];
  265. }
  266. if (curUV2s.size() == curVertices.size()) {
  267. curMesh->mTextureCoords[1] = new aiVector3D[curMesh->mNumVertices];
  268. }
  269. }
  270. break;
  271. case EXN_TEXT:
  272. {
  273. const char* sz = reader->getNodeData();
  274. if (textMeaning == 1) {
  275. textMeaning = 0;
  276. // read vertices
  277. do {
  278. SkipSpacesAndLineEnd(&sz);
  279. aiVector3D temp;aiColor4D c;
  280. // Read the vertex position
  281. sz = fast_atoreal_move<float>(sz,(float&)temp.x);
  282. SkipSpaces(&sz);
  283. sz = fast_atoreal_move<float>(sz,(float&)temp.y);
  284. SkipSpaces(&sz);
  285. sz = fast_atoreal_move<float>(sz,(float&)temp.z);
  286. SkipSpaces(&sz);
  287. curVertices.push_back(temp);
  288. // Read the vertex normals
  289. sz = fast_atoreal_move<float>(sz,(float&)temp.x);
  290. SkipSpaces(&sz);
  291. sz = fast_atoreal_move<float>(sz,(float&)temp.y);
  292. SkipSpaces(&sz);
  293. sz = fast_atoreal_move<float>(sz,(float&)temp.z);
  294. SkipSpaces(&sz);
  295. curNormals.push_back(temp);
  296. // read the vertex colors
  297. uint32_t clr = strtoul16(sz,&sz);
  298. ColorFromARGBPacked(clr,c);
  299. if (!curColors.empty() && c != *(curColors.end()-1))
  300. useColors = true;
  301. curColors.push_back(c);
  302. SkipSpaces(&sz);
  303. // read the first UV coordinate set
  304. sz = fast_atoreal_move<float>(sz,(float&)temp.x);
  305. SkipSpaces(&sz);
  306. sz = fast_atoreal_move<float>(sz,(float&)temp.y);
  307. SkipSpaces(&sz);
  308. temp.z = 0.f;
  309. temp.y = 1.f - temp.y; // DX to OGL
  310. curUVs.push_back(temp);
  311. // read the (optional) second UV coordinate set
  312. if (vertexFormat == 1) {
  313. sz = fast_atoreal_move<float>(sz,(float&)temp.x);
  314. SkipSpaces(&sz);
  315. sz = fast_atoreal_move<float>(sz,(float&)temp.y);
  316. temp.y = 1.f - temp.y; // DX to OGL
  317. curUV2s.push_back(temp);
  318. }
  319. // read optional tangent and bitangent vectors
  320. else if (vertexFormat == 2) {
  321. // tangents
  322. sz = fast_atoreal_move<float>(sz,(float&)temp.x);
  323. SkipSpaces(&sz);
  324. sz = fast_atoreal_move<float>(sz,(float&)temp.z);
  325. SkipSpaces(&sz);
  326. sz = fast_atoreal_move<float>(sz,(float&)temp.y);
  327. SkipSpaces(&sz);
  328. temp.y *= -1.0f;
  329. curTangents.push_back(temp);
  330. // bitangents
  331. sz = fast_atoreal_move<float>(sz,(float&)temp.x);
  332. SkipSpaces(&sz);
  333. sz = fast_atoreal_move<float>(sz,(float&)temp.z);
  334. SkipSpaces(&sz);
  335. sz = fast_atoreal_move<float>(sz,(float&)temp.y);
  336. SkipSpaces(&sz);
  337. temp.y *= -1.0f;
  338. curBitangents.push_back(temp);
  339. }
  340. }
  341. /* IMPORTANT: We assume that each vertex is specified in one
  342. line. So we can skip the rest of the line - unknown vertex
  343. elements are ignored.
  344. */
  345. while (SkipLine(&sz));
  346. }
  347. else if (textMeaning == 2) {
  348. textMeaning = 0;
  349. // read indices
  350. aiFace* curFace = curMesh->mFaces;
  351. aiFace* const faceEnd = curMesh->mFaces + curMesh->mNumFaces;
  352. aiVector3D* pcV = curMesh->mVertices;
  353. aiVector3D* pcN = curMesh->mNormals;
  354. aiVector3D* pcT = curMesh->mTangents;
  355. aiVector3D* pcB = curMesh->mBitangents;
  356. aiColor4D* pcC0 = curMesh->mColors[0];
  357. aiVector3D* pcT0 = curMesh->mTextureCoords[0];
  358. aiVector3D* pcT1 = curMesh->mTextureCoords[1];
  359. unsigned int curIdx = 0;
  360. unsigned int total = 0;
  361. while(SkipSpacesAndLineEnd(&sz)) {
  362. if (curFace >= faceEnd) {
  363. DefaultLogger::get()->error("IRRMESH: Too many indices");
  364. break;
  365. }
  366. if (!curIdx) {
  367. curFace->mNumIndices = 3;
  368. curFace->mIndices = new unsigned int[3];
  369. }
  370. unsigned int idx = strtoul10(sz,&sz);
  371. if (idx >= curVertices.size()) {
  372. DefaultLogger::get()->error("IRRMESH: Index out of range");
  373. idx = 0;
  374. }
  375. curFace->mIndices[curIdx] = total++;
  376. *pcV++ = curVertices[idx];
  377. if (pcN)*pcN++ = curNormals[idx];
  378. if (pcT)*pcT++ = curTangents[idx];
  379. if (pcB)*pcB++ = curBitangents[idx];
  380. if (pcC0)*pcC0++ = curColors[idx];
  381. if (pcT0)*pcT0++ = curUVs[idx];
  382. if (pcT1)*pcT1++ = curUV2s[idx];
  383. if (++curIdx == 3) {
  384. ++curFace;
  385. curIdx = 0;
  386. }
  387. }
  388. if (curFace != faceEnd)
  389. DefaultLogger::get()->error("IRRMESH: Not enough indices");
  390. // Finish processing the mesh - do some small material workarounds
  391. if (curMatFlags & AI_IRRMESH_MAT_trans_vertex_alpha && !useColors) {
  392. // Take the opacity value of the current material
  393. // from the common vertex color alpha
  394. aiMaterial* mat = (aiMaterial*)curMat;
  395. mat->AddProperty(&curColors[0].a,1,AI_MATKEY_OPACITY);
  396. }
  397. }}
  398. break;
  399. default:
  400. // GCC complains here ...
  401. break;
  402. };
  403. }
  404. // End of the last buffer. A material and a mesh should be there
  405. if (curMat || curMesh) {
  406. if ( !curMat || !curMesh) {
  407. DefaultLogger::get()->error("IRRMESH: A buffer must contain a mesh and a material");
  408. releaseMaterial( &curMat );
  409. releaseMesh( &curMesh );
  410. }
  411. else {
  412. materials.push_back(curMat);
  413. meshes.push_back(curMesh);
  414. }
  415. }
  416. if (materials.empty())
  417. throw DeadlyImportError("IRRMESH: Unable to read a mesh from this file");
  418. // now generate the output scene
  419. pScene->mNumMeshes = (unsigned int)meshes.size();
  420. pScene->mMeshes = new aiMesh*[pScene->mNumMeshes];
  421. for (unsigned int i = 0; i < pScene->mNumMeshes;++i) {
  422. pScene->mMeshes[i] = meshes[i];
  423. // clean this value ...
  424. pScene->mMeshes[i]->mNumUVComponents[3] = 0;
  425. }
  426. pScene->mNumMaterials = (unsigned int)materials.size();
  427. pScene->mMaterials = new aiMaterial*[pScene->mNumMaterials];
  428. ::memcpy(pScene->mMaterials,&materials[0],sizeof(void*)*pScene->mNumMaterials);
  429. pScene->mRootNode = new aiNode();
  430. pScene->mRootNode->mName.Set("<IRRMesh>");
  431. pScene->mRootNode->mNumMeshes = pScene->mNumMeshes;
  432. pScene->mRootNode->mMeshes = new unsigned int[pScene->mNumMeshes];
  433. for (unsigned int i = 0; i < pScene->mNumMeshes;++i)
  434. pScene->mRootNode->mMeshes[i] = i;
  435. // clean up and return
  436. delete reader;
  437. AI_DEBUG_INVALIDATE_PTR(reader);
  438. }
  439. #endif // !! ASSIMP_BUILD_NO_IRRMESH_IMPORTER