IRRMeshLoader.cpp 16 KB

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