IRRMeshLoader.cpp 16 KB

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