IRRMeshLoader.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (ASSIMP)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2008, ASSIMP Development 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 Development 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. // ------------------------------------------------------------------------------------------------
  41. // Constructor to be privately used by Importer
  42. IRRMeshImporter::IRRMeshImporter()
  43. {
  44. // nothing to do here
  45. }
  46. // ------------------------------------------------------------------------------------------------
  47. // Destructor, private as well
  48. IRRMeshImporter::~IRRMeshImporter()
  49. {
  50. // nothing to do here
  51. }
  52. // ------------------------------------------------------------------------------------------------
  53. // Returns whether the class can handle the format of the given file.
  54. bool IRRMeshImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler) const
  55. {
  56. /* NOTE: A simple check for the file extension is not enough
  57. * here. Irrmesh and irr are easy, but xml is too generic
  58. * and could be collada, too. So we need to open the file and
  59. * search for typical tokens.
  60. */
  61. std::string::size_type pos = pFile.find_last_of('.');
  62. // no file extension - can't read
  63. if( pos == std::string::npos)
  64. return false;
  65. std::string extension = pFile.substr( pos);
  66. for (std::string::iterator i = extension.begin(); i != extension.end();++i)
  67. *i = ::tolower(*i);
  68. if (extension == ".irrmesh")return true;
  69. else if (extension == ".xml")
  70. {
  71. /* If CanRead() is called to check whether the loader
  72. * supports a specific file extension in general we
  73. * must return true here.
  74. */
  75. if (!pIOHandler)return true;
  76. const char* tokens[] = {"irrmesh"};
  77. return SearchFileHeaderForToken(pIOHandler,pFile,tokens,1);
  78. }
  79. return false;
  80. }
  81. // ------------------------------------------------------------------------------------------------
  82. // Imports the given file into the given scene structure.
  83. void IRRMeshImporter::InternReadFile( const std::string& pFile,
  84. aiScene* pScene, IOSystem* pIOHandler)
  85. {
  86. boost::scoped_ptr<IOStream> file( pIOHandler->Open( pFile));
  87. // Check whether we can read from the file
  88. if( file.get() == NULL)
  89. throw new ImportErrorException( "Failed to open IRRMESH file " + pFile + "");
  90. // Construct the irrXML parser
  91. CIrrXML_IOStreamReader st(file.get());
  92. reader = createIrrXMLReader((IFileReadCallBack*) &st);
  93. // final data
  94. std::vector<aiMaterial*> materials;
  95. std::vector<aiMesh*> meshes;
  96. materials.reserve (5);
  97. meshes.reserve (5);
  98. // temporary data - current mesh buffer
  99. aiMaterial* curMat = NULL;
  100. aiMesh* curMesh = NULL;
  101. unsigned int curMatFlags;
  102. std::vector<aiVector3D> curVertices,curNormals,curTangents,curBitangents;
  103. std::vector<aiColor4D> curColors;
  104. std::vector<aiVector3D> curUVs,curUV2s;
  105. // some temporary variables
  106. int textMeaning = 0;
  107. int vertexFormat = 0; // 0 = normal; 1 = 2 tcoords, 2 = tangents
  108. bool useColors = false;
  109. bool needLightMap = false;
  110. // Parse the XML file
  111. while (reader->read())
  112. {
  113. switch (reader->getNodeType())
  114. {
  115. case EXN_ELEMENT:
  116. if (!ASSIMP_stricmp(reader->getNodeName(),"buffer") && (curMat || curMesh))
  117. {
  118. // end of previous buffer. A material and a mesh should be there
  119. if ( !curMat || !curMesh)
  120. {
  121. DefaultLogger::get()->error("IRRMESH: A buffer must contain a mesh and a material");
  122. delete curMat;
  123. delete curMesh;
  124. }
  125. else
  126. {
  127. materials.push_back(curMat);
  128. meshes.push_back(curMesh);
  129. }
  130. curMat = NULL;
  131. curMesh = NULL;
  132. curVertices.clear();
  133. curColors.clear();
  134. curNormals.clear();
  135. curUV2s.clear();
  136. curUVs.clear();
  137. curTangents.clear();
  138. curBitangents.clear();
  139. }
  140. if (!ASSIMP_stricmp(reader->getNodeName(),"material"))
  141. {
  142. if (curMat)
  143. {
  144. DefaultLogger::get()->warn("IRRMESH: Only one material description per buffer, please");
  145. delete curMat;curMat = NULL;
  146. }
  147. curMat = ParseMaterial(curMatFlags);
  148. }
  149. /* no else here! */ if (!ASSIMP_stricmp(reader->getNodeName(),"vertices"))
  150. {
  151. int num = reader->getAttributeValueAsInt("vertexCount");
  152. if (!num)
  153. {
  154. // This is possible ... remove the mesh from the list
  155. // 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. {
  170. curUV2s.reserve (num);
  171. vertexFormat = 1;
  172. if (curMatFlags & AI_IRRMESH_EXTRA_2ND_TEXTURE)
  173. {
  174. // *********************************************************
  175. // We have a second texture! So use this UV channel
  176. // for it. The 2nd texture can be either a normal
  177. // texture (solid_2layer or lightmap_xxx) or a normal
  178. // map (normal_..., parallax_...)
  179. // *********************************************************
  180. int idx = 1;
  181. MaterialHelper* mat = ( MaterialHelper* ) curMat;
  182. if (curMatFlags & (AI_IRRMESH_MAT_solid_2layer | AI_IRRMESH_MAT_lightmap))
  183. {
  184. mat->AddProperty(&idx,1,AI_MATKEY_UVWSRC_DIFFUSE(0));
  185. }
  186. else if (curMatFlags & AI_IRRMESH_MAT_normalmap_solid)
  187. {
  188. mat->AddProperty(&idx,1,AI_MATKEY_UVWSRC_NORMALS(0));
  189. }
  190. }
  191. }
  192. else if (!ASSIMP_stricmp("tangents", t))
  193. {
  194. curTangents.reserve (num);
  195. curBitangents.reserve (num);
  196. vertexFormat = 2;
  197. }
  198. else if (ASSIMP_stricmp("standard", t))
  199. {
  200. delete curMat;
  201. DefaultLogger::get()->warn("IRRMESH: Unknown vertex format");
  202. }
  203. else vertexFormat = 0;
  204. textMeaning = 1;
  205. }
  206. else if (!ASSIMP_stricmp(reader->getNodeName(),"indices"))
  207. {
  208. if (curVertices.empty() && curMat)
  209. {
  210. delete curMat;
  211. throw new ImportErrorException("IRRMESH: indices must come after vertices");
  212. }
  213. textMeaning = 2;
  214. // start a new mesh
  215. curMesh = new aiMesh();
  216. // allocate storage for all faces
  217. curMesh->mNumVertices = reader->getAttributeValueAsInt("indexCount");
  218. if (!curMesh->mNumVertices)
  219. {
  220. // This is possible ... remove the mesh from the list
  221. // and skip further reading
  222. DefaultLogger::get()->warn("IRRMESH: Found mesh with zero indices");
  223. // mesh - away
  224. delete curMesh; curMesh = NULL;
  225. // material - away
  226. delete curMat;curMat = NULL;
  227. textMeaning = 0;
  228. continue;
  229. }
  230. if (curMesh->mNumVertices % 3)
  231. {
  232. DefaultLogger::get()->warn("IRRMESH: Number if indices isn't divisible by 3");
  233. }
  234. curMesh->mNumFaces = curMesh->mNumVertices / 3;
  235. curMesh->mFaces = new aiFace[curMesh->mNumFaces];
  236. // setup some members
  237. curMesh->mMaterialIndex = (unsigned int)materials.size();
  238. curMesh->mPrimitiveTypes = aiPrimitiveType_TRIANGLE;
  239. // allocate storage for all vertices
  240. curMesh->mVertices = new aiVector3D[curMesh->mNumVertices];
  241. if (curNormals.size() == curVertices.size())
  242. {
  243. curMesh->mNormals = new aiVector3D[curMesh->mNumVertices];
  244. }
  245. if (curTangents.size() == curVertices.size())
  246. {
  247. curMesh->mTangents = new aiVector3D[curMesh->mNumVertices];
  248. }
  249. if (curBitangents.size() == curVertices.size())
  250. {
  251. curMesh->mBitangents = new aiVector3D[curMesh->mNumVertices];
  252. }
  253. if (curColors.size() == curVertices.size() && useColors)
  254. {
  255. curMesh->mColors[0] = new aiColor4D[curMesh->mNumVertices];
  256. }
  257. if (curUVs.size() == curVertices.size())
  258. {
  259. curMesh->mTextureCoords[0] = new aiVector3D[curMesh->mNumVertices];
  260. }
  261. if (curUV2s.size() == curVertices.size())
  262. {
  263. curMesh->mTextureCoords[1] = new aiVector3D[curMesh->mNumVertices];
  264. }
  265. }
  266. break;
  267. case EXN_TEXT:
  268. {
  269. const char* sz = reader->getNodeData();
  270. if (textMeaning == 1)
  271. {
  272. textMeaning = 0;
  273. // read vertices
  274. do
  275. {
  276. SkipSpacesAndLineEnd(&sz);
  277. aiVector3D temp;aiColor4D c;
  278. // Read the vertex position
  279. sz = fast_atof_move(sz,(float&)temp.x);
  280. SkipSpaces(&sz);
  281. sz = fast_atof_move(sz,(float&)temp.y);
  282. SkipSpaces(&sz);
  283. sz = fast_atof_move(sz,(float&)temp.z);
  284. SkipSpaces(&sz);
  285. curVertices.push_back(temp);
  286. // Read the vertex normals
  287. sz = fast_atof_move(sz,(float&)temp.x);
  288. SkipSpaces(&sz);
  289. sz = fast_atof_move(sz,(float&)temp.y);
  290. SkipSpaces(&sz);
  291. sz = fast_atof_move(sz,(float&)temp.z);
  292. SkipSpaces(&sz);
  293. curNormals.push_back(temp);
  294. // read the vertex colors
  295. uint32_t clr = strtol16(sz,&sz);
  296. ColorFromARGBPacked(clr,c);
  297. if (!curColors.empty() && c != *(curColors.end()-1))
  298. useColors = true;
  299. curColors.push_back(c);
  300. SkipSpaces(&sz);
  301. // read the first UV coordinate set
  302. sz = fast_atof_move(sz,(float&)temp.x);
  303. SkipSpaces(&sz);
  304. sz = fast_atof_move(sz,(float&)temp.y);
  305. SkipSpaces(&sz);
  306. temp.z = 0.f;
  307. temp.y = 1.f - temp.y; // DX to OGL
  308. curUVs.push_back(temp);
  309. // read the (optional) second UV coordinate set
  310. if (vertexFormat == 1)
  311. {
  312. sz = fast_atof_move(sz,(float&)temp.x);
  313. SkipSpaces(&sz);
  314. sz = fast_atof_move(sz,(float&)temp.y);
  315. temp.y = 1.f - temp.y; // DX to OGL
  316. curUV2s.push_back(temp);
  317. }
  318. // read optional tangent and bitangent vectors
  319. else if (vertexFormat == 2)
  320. {
  321. // tangents
  322. sz = fast_atof_move(sz,(float&)temp.x);
  323. SkipSpaces(&sz);
  324. sz = fast_atof_move(sz,(float&)temp.z);
  325. SkipSpaces(&sz);
  326. sz = fast_atof_move(sz,(float&)temp.y);
  327. SkipSpaces(&sz);
  328. temp.y *= -1.0f;
  329. curTangents.push_back(temp);
  330. // bitangents
  331. sz = fast_atof_move(sz,(float&)temp.x);
  332. SkipSpaces(&sz);
  333. sz = fast_atof_move(sz,(float&)temp.z);
  334. SkipSpaces(&sz);
  335. sz = fast_atof_move(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. {
  349. textMeaning = 0;
  350. // read indices
  351. aiFace* curFace = curMesh->mFaces;
  352. aiFace* const faceEnd = curMesh->mFaces + curMesh->mNumFaces;
  353. aiVector3D* pcV = curMesh->mVertices;
  354. aiVector3D* pcN = curMesh->mNormals;
  355. aiVector3D* pcT = curMesh->mTangents;
  356. aiVector3D* pcB = curMesh->mBitangents;
  357. aiColor4D* pcC0 = curMesh->mColors[0];
  358. aiVector3D* pcT0 = curMesh->mTextureCoords[0];
  359. aiVector3D* pcT1 = curMesh->mTextureCoords[1];
  360. unsigned int curIdx = 0;
  361. unsigned int total = 0;
  362. while(SkipSpacesAndLineEnd(&sz))
  363. {
  364. if (curFace >= faceEnd)
  365. {
  366. DefaultLogger::get()->error("IRRMESH: Too many indices");
  367. break;
  368. }
  369. if (!curIdx)
  370. {
  371. curFace->mNumIndices = 3;
  372. curFace->mIndices = new unsigned int[3];
  373. }
  374. unsigned int idx = strtol10(sz,&sz);
  375. if (idx >= curVertices.size())
  376. {
  377. DefaultLogger::get()->error("IRRMESH: Index out of range");
  378. idx = 0;
  379. }
  380. curFace->mIndices[curIdx] = total++;
  381. *pcV++ = curVertices[idx];
  382. if (pcN)*pcN++ = curNormals[idx];
  383. if (pcT)*pcT++ = curTangents[idx];
  384. if (pcB)*pcB++ = curBitangents[idx];
  385. if (pcC0)*pcC0++ = curColors[idx];
  386. if (pcT0)*pcT0++ = curUVs[idx];
  387. if (pcT1)*pcT1++ = curUV2s[idx];
  388. if (++curIdx == 3)
  389. {
  390. ++curFace;
  391. curIdx = 0;
  392. }
  393. }
  394. if (curFace != faceEnd)
  395. DefaultLogger::get()->error("IRRMESH: Not enough indices");
  396. // Finish processing the mesh - do some small material workarounds
  397. if (curMatFlags & AI_IRRMESH_MAT_trans_vertex_alpha && !useColors)
  398. {
  399. // Take the opacity value of the current material
  400. // from the common vertex color alpha
  401. MaterialHelper* mat = (MaterialHelper*)curMat;
  402. mat->AddProperty(&curColors[0].a,1,AI_MATKEY_OPACITY);
  403. }
  404. }}
  405. break;
  406. default:
  407. // GCC complains here ...
  408. break;
  409. };
  410. }
  411. // End of the last buffer. A material and a mesh should be there
  412. if (curMat || curMesh)
  413. {
  414. if ( !curMat || !curMesh)
  415. {
  416. DefaultLogger::get()->error("IRRMESH: A buffer must contain a mesh and a material");
  417. delete curMat;
  418. delete curMesh;
  419. }
  420. else
  421. {
  422. materials.push_back(curMat);
  423. meshes.push_back(curMesh);
  424. }
  425. }
  426. if (materials.empty())
  427. throw new ImportErrorException("IRRMESH: Unable to read a mesh from this file");
  428. // now generate the output scene
  429. pScene->mNumMeshes = (unsigned int)meshes.size();
  430. pScene->mMeshes = new aiMesh*[pScene->mNumMeshes];
  431. for (unsigned int i = 0; i < pScene->mNumMeshes;++i)
  432. {
  433. pScene->mMeshes[i] = meshes[i];
  434. // clean this value ...
  435. pScene->mMeshes[i]->mNumUVComponents[3] = 0;
  436. }
  437. pScene->mNumMaterials = (unsigned int)materials.size();
  438. pScene->mMaterials = new aiMaterial*[pScene->mNumMaterials];
  439. ::memcpy(pScene->mMaterials,&materials[0],sizeof(void*)*pScene->mNumMaterials);
  440. pScene->mRootNode = new aiNode();
  441. pScene->mRootNode->mName.Set("<IRRMesh>");
  442. pScene->mRootNode->mNumMeshes = pScene->mNumMeshes;
  443. pScene->mRootNode->mMeshes = new unsigned int[pScene->mNumMeshes];
  444. for (unsigned int i = 0; i < pScene->mNumMeshes;++i)
  445. pScene->mRootNode->mMeshes[i] = i;
  446. // transformation matrix to convert from IRRMESH to ASSIMP coordinates
  447. pScene->mRootNode->mTransformation *= AI_TO_IRR_MATRIX;
  448. // clean up and return
  449. delete reader;
  450. AI_DEBUG_INVALIDATE_PTR(reader);
  451. }