NFFLoader.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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 STL importer class */
  35. // internal headers
  36. #include "NFFLoader.h"
  37. #include "MaterialSystem.h"
  38. #include "ParsingUtils.h"
  39. #include "StandardShapes.h"
  40. #include "fast_atof.h"
  41. // public assimp headers
  42. #include "../include/IOStream.h"
  43. #include "../include/IOSystem.h"
  44. #include "../include/aiScene.h"
  45. #include "../include/aiAssert.h"
  46. #include "../include/DefaultLogger.h"
  47. // boost headers
  48. #include <boost/scoped_ptr.hpp>
  49. using namespace Assimp;
  50. // ------------------------------------------------------------------------------------------------
  51. // Constructor to be privately used by Importer
  52. NFFImporter::NFFImporter()
  53. {
  54. }
  55. // ------------------------------------------------------------------------------------------------
  56. // Destructor, private as well
  57. NFFImporter::~NFFImporter()
  58. {
  59. }
  60. // ------------------------------------------------------------------------------------------------
  61. // Returns whether the class can handle the format of the given file.
  62. bool NFFImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler) const
  63. {
  64. // simple check of file extension is enough for the moment
  65. std::string::size_type pos = pFile.find_last_of('.');
  66. // no file extension - can't read
  67. if( pos == std::string::npos)return false;
  68. std::string extension = pFile.substr( pos);
  69. return !(extension.length() != 4 || extension[0] != '.' ||
  70. extension[1] != 'n' && extension[1] != 'N' ||
  71. extension[2] != 'f' && extension[2] != 'F' ||
  72. extension[3] != 'f' && extension[3] != 'F');
  73. }
  74. // ------------------------------------------------------------------------------------------------
  75. bool GetNextLine(const char*& buffer, char out[4096])
  76. {
  77. char* _out = out;
  78. char* const end = _out+4096;
  79. while (!IsLineEnd( *buffer ) && _out < end)
  80. *_out++ = *buffer++;
  81. *_out = '\0';
  82. if ('\0' == *buffer)return false;
  83. while (IsLineEnd( *buffer ))++buffer;
  84. return true;
  85. }
  86. // ------------------------------------------------------------------------------------------------
  87. #define AI_NFF_PARSE_FLOAT(f) \
  88. SkipSpaces(&sz); \
  89. sz = fast_atof_move(sz, f);
  90. // ------------------------------------------------------------------------------------------------
  91. #define AI_NFF_PARSE_TRIPLE(v) \
  92. AI_NFF_PARSE_FLOAT(v.x) \
  93. AI_NFF_PARSE_FLOAT(v.y) \
  94. AI_NFF_PARSE_FLOAT(v.z)
  95. // ------------------------------------------------------------------------------------------------
  96. // Imports the given file into the given scene structure.
  97. void NFFImporter::InternReadFile( const std::string& pFile,
  98. aiScene* pScene, IOSystem* pIOHandler)
  99. {
  100. boost::scoped_ptr<IOStream> file( pIOHandler->Open( pFile, "rb"));
  101. // Check whether we can read from the file
  102. if( file.get() == NULL)
  103. throw new ImportErrorException( "Failed to open NFF file " + pFile + ".");
  104. unsigned int m = (unsigned int)file->FileSize();
  105. // allocate storage and copy the contents of the file to a memory buffer
  106. // (terminate it with zero)
  107. std::vector<char> mBuffer2(m+1);
  108. file->Read(&mBuffer2[0],m,1);
  109. const char* buffer = &mBuffer2[0];
  110. mBuffer2[m] = '\0';
  111. // mesh arrays - separate here to make the handling of
  112. // the pointers below easier.
  113. std::vector<MeshInfo> meshes;
  114. std::vector<MeshInfo> meshesWithNormals;
  115. std::vector<MeshInfo> meshesLocked;
  116. MeshInfo* currentMeshWithNormals = NULL;
  117. MeshInfo* currentMesh = NULL;
  118. ShadingInfo s; // current material info
  119. char line[4096];
  120. const char* sz;
  121. unsigned int sphere = 0,cylinder = 0,cone = 0,numNamed = 0;
  122. while (GetNextLine(buffer,line))
  123. {
  124. if ('p' == line[0])
  125. {
  126. MeshInfo* out = NULL;
  127. // 'pp' - polygon patch primitive
  128. if ('p' == line[1])
  129. {
  130. if (meshesWithNormals.empty())
  131. {
  132. meshesWithNormals.push_back(MeshInfo(true));
  133. currentMeshWithNormals = &meshesWithNormals.back();
  134. }
  135. sz = &line[2];out = currentMeshWithNormals;
  136. }
  137. // 'p' - polygon primitive
  138. else
  139. {
  140. if (meshes.empty())
  141. {
  142. meshes.push_back(MeshInfo(false));
  143. currentMesh = &meshes.back();
  144. }
  145. sz = &line[1];out = currentMesh;
  146. }
  147. SkipSpaces(sz,&sz);
  148. m = strtol10(sz);
  149. out->faces.push_back(m);
  150. for (unsigned int n = 0; n < m;++n)
  151. {
  152. if(!GetNextLine(buffer,line))
  153. {
  154. DefaultLogger::get()->error("NFF: Unexpected EOF was encountered");
  155. break;
  156. }
  157. aiVector3D v; sz = &line[0];
  158. AI_NFF_PARSE_TRIPLE(v);
  159. out->vertices.push_back(v);
  160. if (&meshesWithNormals.back() == out)
  161. {
  162. AI_NFF_PARSE_TRIPLE(v);
  163. out->normals.push_back(v);
  164. }
  165. }
  166. }
  167. // 'f' - shading information block
  168. else if ('f' == line[0] && IsSpace(line[1]))
  169. {
  170. SkipSpaces(&line[1],&sz);
  171. // read just the RGB colors, the rest is ignored for the moment
  172. sz = fast_atof_move(sz, s.color.r);
  173. SkipSpaces(&sz);
  174. sz = fast_atof_move(sz, s.color.g);
  175. SkipSpaces(&sz);
  176. sz = fast_atof_move(sz, s.color.b);
  177. // check whether we have this material already -
  178. // although we have the RRM-Step, this is necessary here.
  179. // otherwise we would generate hundreds of small meshes
  180. // with just a few faces - this is surely never wanted.
  181. currentMesh = currentMeshWithNormals = NULL;
  182. for (std::vector<MeshInfo>::iterator it = meshes.begin(), end = meshes.end();
  183. it != end;++it)
  184. {
  185. if ((*it).bLocked)continue;
  186. if ((*it).shader == s)
  187. {
  188. if ((*it).bHasNormals)currentMeshWithNormals = &(*it);
  189. else currentMesh = &(*it);
  190. }
  191. }
  192. if (!currentMesh)
  193. {
  194. meshes.push_back(MeshInfo(false));
  195. currentMesh = &meshes.back();
  196. currentMesh->shader = s;
  197. }
  198. if (!currentMeshWithNormals)
  199. {
  200. meshesWithNormals.push_back(MeshInfo(true));
  201. currentMeshWithNormals = &meshesWithNormals.back();
  202. currentMeshWithNormals->shader = s;
  203. }
  204. }
  205. // 's' - sphere
  206. else if ('s' == line[0] && IsSpace(line[1]))
  207. {
  208. meshesLocked.push_back(MeshInfo(false,true));
  209. MeshInfo& currentMesh = meshesLocked.back();
  210. currentMesh.shader = s;
  211. sz = &line[1];
  212. aiVector3D center; float radius;
  213. AI_NFF_PARSE_TRIPLE(center);
  214. AI_NFF_PARSE_FLOAT(radius);
  215. currentMesh.center = center;
  216. // generate the sphere - it consists of simple triangles
  217. StandardShapes::MakeSphere(aiVector3D(), radius, 500.0f, currentMesh.vertices);
  218. currentMesh.faces.resize(currentMesh.vertices.size(),3);
  219. // generate a name for the mesh
  220. ::sprintf(currentMesh.name,"sphere_%i",sphere++);
  221. }
  222. // 'c' - cone
  223. else if ('c' == line[0] && IsSpace(line[1]))
  224. {
  225. meshesLocked.push_back(MeshInfo(false,true));
  226. MeshInfo& currentMesh = meshes.back();
  227. currentMesh.shader = s;
  228. sz = &line[1];
  229. aiVector3D center1, center2; float radius1, radius2;
  230. AI_NFF_PARSE_TRIPLE(center1);
  231. AI_NFF_PARSE_FLOAT(radius1);
  232. AI_NFF_PARSE_TRIPLE(center2);
  233. AI_NFF_PARSE_FLOAT(radius2);
  234. // compute the center point of the cone/cylinder
  235. center2 = (center2-center1)/2.f;
  236. currentMesh.center = center1+center2;
  237. center1 = -center2;
  238. // generate the cone - it consists of simple triangles
  239. StandardShapes::MakeCone(center1, radius1, center2, radius2, 500.0f, currentMesh.vertices);
  240. currentMesh.faces.resize(currentMesh.vertices.size(),3);
  241. // generate a name for the mesh
  242. if (radius1 != radius2)
  243. ::sprintf(currentMesh.name,"cone_%i",cone++);
  244. else ::sprintf(currentMesh.name,"cylinder_%i",cylinder++);
  245. }
  246. // '#' - comment
  247. else if ('#' == line[0])
  248. {
  249. const char* sz;SkipSpaces(&line[1],&sz);
  250. if (!IsLineEnd(*sz))DefaultLogger::get()->info(sz);
  251. }
  252. }
  253. // copy all arrays into one large
  254. meshes.reserve(meshes.size()+meshesLocked.size()+meshesWithNormals.size());
  255. meshes.insert(meshes.end(),meshesLocked.begin(),meshesLocked.end());
  256. meshes.insert(meshes.end(),meshesWithNormals.begin(),meshesWithNormals.end());
  257. // now generate output meshes. first find out how many meshes we'll need
  258. std::vector<MeshInfo>::const_iterator it = meshes.begin(), end = meshes.end();
  259. for (;it != end;++it)
  260. {
  261. if (!(*it).faces.empty())
  262. {
  263. ++pScene->mNumMeshes;
  264. if ((*it).name[0])++numNamed;
  265. }
  266. }
  267. // generate a dummy root node - assign all unnamed elements such
  268. // as polygons and polygon patches to the root node and generate
  269. // sub nodes for named objects such as spheres and cones.
  270. aiNode* const root = new aiNode();
  271. root->mName.Set("<NFF_Root>");
  272. root->mNumChildren = numNamed;
  273. root->mNumMeshes = pScene->mNumMeshes-numNamed;
  274. aiNode** ppcChildren;
  275. unsigned int* pMeshes;
  276. if (root->mNumMeshes)
  277. pMeshes = root->mMeshes = new unsigned int[root->mNumMeshes];
  278. if (root->mNumChildren)
  279. ppcChildren = root->mChildren = new aiNode*[root->mNumChildren];
  280. if (!pScene->mNumMeshes)throw new ImportErrorException("NFF: No meshes loaded");
  281. pScene->mMeshes = new aiMesh*[pScene->mNumMeshes];
  282. pScene->mMaterials = new aiMaterial*[pScene->mNumMaterials = pScene->mNumMeshes];
  283. for (it = meshes.begin(), m = 0; it != end;++it)
  284. {
  285. if ((*it).faces.empty())continue;
  286. const MeshInfo& src = *it;
  287. aiMesh* const mesh = pScene->mMeshes[m] = new aiMesh();
  288. mesh->mNumVertices = (unsigned int)src.vertices.size();
  289. mesh->mNumFaces = (unsigned int)src.faces.size();
  290. // generate sub nodes for named meshes
  291. if (src.name[0])
  292. {
  293. aiNode* const node = *ppcChildren = new aiNode();
  294. node->mParent = root;
  295. node->mNumMeshes = 1;
  296. node->mMeshes = new unsigned int[1];
  297. node->mMeshes[0] = m;
  298. // setup the transformation matrix of the node
  299. node->mTransformation.a4 = src.center.x;
  300. node->mTransformation.b4 = src.center.y;
  301. node->mTransformation.c4 = src.center.z;
  302. ++ppcChildren;
  303. }
  304. else *pMeshes++ = m;
  305. // copy vertex positions
  306. mesh->mVertices = new aiVector3D[mesh->mNumVertices];
  307. ::memcpy(mesh->mVertices,&src.vertices[0],sizeof(aiVector3D)*mesh->mNumVertices);
  308. if (src.bHasNormals)
  309. {
  310. ai_assert(src.normals.size() == src.vertices.size());
  311. // copy normal vectors
  312. mesh->mNormals = new aiVector3D[mesh->mNumVertices];
  313. ::memcpy(mesh->mNormals,&src.normals[0],sizeof(aiVector3D)*mesh->mNumVertices);
  314. }
  315. // generate faces
  316. unsigned int p = 0;
  317. aiFace* pFace = mesh->mFaces = new aiFace[mesh->mNumFaces];
  318. for (std::vector<unsigned int>::const_iterator it2 = src.faces.begin(),
  319. end2 = src.faces.end();
  320. it2 != end2;++it2,++pFace)
  321. {
  322. pFace->mIndices = new unsigned int [ pFace->mNumIndices = *it2 ];
  323. for (unsigned int o = 0; o < pFace->mNumIndices;++o)
  324. pFace->mIndices[o] = p++;
  325. }
  326. // generate a material for the mesh
  327. MaterialHelper* pcMat = (MaterialHelper*)(pScene->
  328. mMaterials[m++] = new MaterialHelper());
  329. aiString s;
  330. s.Set(AI_DEFAULT_MATERIAL_NAME);
  331. pcMat->AddProperty(&s, AI_MATKEY_NAME);
  332. pcMat->AddProperty(&src.shader.color,1,AI_MATKEY_COLOR_DIFFUSE);
  333. pcMat->AddProperty(&src.shader.color,1,AI_MATKEY_COLOR_SPECULAR);
  334. }
  335. pScene->mRootNode = root;
  336. }