STLLoader.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 "STLLoader.h"
  37. #include "MaterialSystem.h"
  38. #include "ParsingUtils.h"
  39. #include "fast_atof.h"
  40. // public assimp headers
  41. #include "../include/IOStream.h"
  42. #include "../include/IOSystem.h"
  43. #include "../include/aiMesh.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. STLImporter::STLImporter()
  53. {
  54. }
  55. // ------------------------------------------------------------------------------------------------
  56. // Destructor, private as well
  57. STLImporter::~STLImporter()
  58. {
  59. }
  60. // ------------------------------------------------------------------------------------------------
  61. // Returns whether the class can handle the format of the given file.
  62. bool STLImporter::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. if (extension.length() < 4)return false;
  70. if (extension[0] != '.')return false;
  71. if (extension[1] != 's' && extension[1] != 'S')return false;
  72. if (extension[2] != 't' && extension[2] != 'T')return false;
  73. if (extension[3] != 'l' && extension[3] != 'L')return false;
  74. return true;
  75. }
  76. // ------------------------------------------------------------------------------------------------
  77. // Imports the given file into the given scene structure.
  78. void STLImporter::InternReadFile(
  79. const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler)
  80. {
  81. boost::scoped_ptr<IOStream> file( pIOHandler->Open( pFile, "rb"));
  82. // Check whether we can read from the file
  83. if( file.get() == NULL)
  84. {
  85. throw new ImportErrorException( "Failed to open STL file " + pFile + ".");
  86. }
  87. this->fileSize = (unsigned int)file->FileSize();
  88. // allocate storage and copy the contents of the file to a memory buffer
  89. // (terminate it with zero)
  90. std::vector<char> mBuffer2(fileSize+1);
  91. file->Read(&mBuffer2[0], 1, fileSize);
  92. mBuffer2[fileSize] = '\0';
  93. this->pScene = pScene;
  94. this->mBuffer = &mBuffer2[0];
  95. // the default vertex color is white
  96. clrColorDefault.r = clrColorDefault.g = clrColorDefault.b = clrColorDefault.a = 1.0f;
  97. // allocate one mesh
  98. pScene->mNumMeshes = 1;
  99. pScene->mMeshes = new aiMesh*[1];
  100. aiMesh* pMesh = pScene->mMeshes[0] = new aiMesh();
  101. pMesh->mMaterialIndex = 0;
  102. // allocate a single node
  103. pScene->mRootNode = new aiNode();
  104. pScene->mRootNode->mNumMeshes = 1;
  105. pScene->mRootNode->mMeshes = new unsigned int[1];
  106. pScene->mRootNode->mMeshes[0] = 0;
  107. bool bMatClr = false;
  108. // check whether the file starts with 'solid' -
  109. // in this case we can simply assume it IS a text file. finished.
  110. if (!::strncmp(mBuffer,"solid",5))
  111. this->LoadASCIIFile();
  112. else bMatClr = this->LoadBinaryFile();
  113. // now copy faces
  114. pMesh->mFaces = new aiFace[pMesh->mNumFaces];
  115. for (unsigned int i = 0, p = 0; i < pMesh->mNumFaces;++i)
  116. {
  117. aiFace& face = pMesh->mFaces[i];
  118. face.mIndices = new unsigned int[face.mNumIndices = 3];
  119. for (unsigned int o = 0; o < 3;++o,++p)
  120. face.mIndices[o] = p;
  121. }
  122. // create a single default material - everything white, as we have vertex colors
  123. MaterialHelper* pcMat = new MaterialHelper();
  124. aiString s;
  125. s.Set(AI_DEFAULT_MATERIAL_NAME);
  126. pcMat->AddProperty(&s, AI_MATKEY_NAME);
  127. aiColor4D clrDiffuse(1.0f,1.0f,1.0f,1.0f);
  128. if (bMatClr)clrDiffuse = this->clrColorDefault;
  129. pcMat->AddProperty(&clrDiffuse,1,AI_MATKEY_COLOR_DIFFUSE);
  130. pcMat->AddProperty(&clrDiffuse,1,AI_MATKEY_COLOR_SPECULAR);
  131. clrDiffuse = aiColor4D(0.05f,0.05f,0.05f,1.0f);
  132. pcMat->AddProperty(&clrDiffuse,1,AI_MATKEY_COLOR_AMBIENT);
  133. pScene->mNumMaterials = 1;
  134. pScene->mMaterials = new aiMaterial*[1];
  135. pScene->mMaterials[0] = pcMat;
  136. delete[] this->mBuffer;AI_DEBUG_INVALIDATE_PTR(this->mBuffer);
  137. }
  138. // ------------------------------------------------------------------------------------------------
  139. // Read an ASCII STL file
  140. void STLImporter::LoadASCIIFile()
  141. {
  142. aiMesh* pMesh = pScene->mMeshes[0];
  143. const char* sz = mBuffer + 5; // skip the "solid"
  144. SkipSpaces(&sz);
  145. const char* szMe = sz;
  146. while (!::IsSpaceOrNewLine(*sz))sz++;
  147. unsigned int temp;
  148. // setup the name of the node
  149. if (temp = unsigned int(sz-szMe))
  150. {
  151. pScene->mRootNode->mName.length = temp;
  152. ::memcpy(pScene->mRootNode->mName.data,szMe,temp);
  153. pScene->mRootNode->mName.data[temp] = '\0';
  154. }
  155. else pScene->mRootNode->mName.Set("<STL_ASCII>");
  156. // try to guess how many vertices we could have
  157. // assume we'll need 160 bytes for each face
  158. pMesh->mNumVertices = ( pMesh->mNumFaces = fileSize / 160 ) * 3;
  159. pMesh->mVertices = new aiVector3D[pMesh->mNumVertices];
  160. pMesh->mNormals = new aiVector3D[pMesh->mNumVertices];
  161. unsigned int curFace = 0, curVertex = 0;
  162. while (true)
  163. {
  164. // go to the next token
  165. if(!SkipSpacesAndLineEnd(&sz))
  166. {
  167. // seems we're finished although there was no end marker
  168. DefaultLogger::get()->warn("STL: unexpected EOF. \'endsolid\' keyword was expected");
  169. break;
  170. }
  171. // facet normal -0.13 -0.13 -0.98
  172. if (!::strncmp(sz,"facet",5) && ::IsSpaceOrNewLine(*(sz+5)))
  173. {
  174. if (3 != curVertex)DefaultLogger::get()->warn("STL: A new facet begins but the old is not yet complete");
  175. if (pMesh->mNumFaces == curFace)
  176. {
  177. // need to resize the arrays, our size estimate was wrong
  178. unsigned int iNeededSize = unsigned int(sz-mBuffer) / pMesh->mNumFaces;
  179. if (iNeededSize <= 160)iNeededSize >>= 1; // prevent endless looping
  180. unsigned int add = unsigned int((mBuffer+fileSize)-sz) / iNeededSize;
  181. add += add >> 3; // add 12.5% as buffer
  182. iNeededSize = (pMesh->mNumFaces + add)*3;
  183. aiVector3D* pv = new aiVector3D[iNeededSize];
  184. ::memcpy(pv,pMesh->mVertices,pMesh->mNumVertices*sizeof(aiVector3D));
  185. delete[] pMesh->mVertices;
  186. pMesh->mVertices = pv;
  187. pv = new aiVector3D[iNeededSize];
  188. ::memcpy(pv,pMesh->mNormals,pMesh->mNumVertices*sizeof(aiVector3D));
  189. delete[] pMesh->mNormals;
  190. pMesh->mNormals = pv;
  191. pMesh->mNumVertices = iNeededSize;
  192. pMesh->mNumFaces += add;
  193. }
  194. aiVector3D* vn = &pMesh->mNormals[curFace++*3];
  195. sz += 6;
  196. curVertex = 0;
  197. SkipSpaces(&sz);
  198. if (::strncmp(sz,"normal",6))
  199. {
  200. DefaultLogger::get()->warn("STL: a facet normal vector was expected but not found");
  201. }
  202. else
  203. {
  204. sz += 7;
  205. SkipSpaces(&sz);
  206. sz = fast_atof_move(sz, vn->x );
  207. SkipSpaces(&sz);
  208. sz = fast_atof_move(sz, vn->y );
  209. SkipSpaces(&sz);
  210. sz = fast_atof_move(sz, vn->z );
  211. *(vn+1) = *vn;
  212. *(vn+2) = *vn;
  213. }
  214. }
  215. // vertex 1.50000 1.50000 0.00000
  216. else if (!::strncmp(sz,"vertex",6) && ::IsSpaceOrNewLine(*(sz+6)))
  217. {
  218. if (3 == curVertex)
  219. {
  220. DefaultLogger::get()->error("STL: a facet with more than 3 vertices has been found");
  221. }
  222. else
  223. {
  224. sz += 7;
  225. SkipSpaces(&sz);
  226. aiVector3D* vn = &pMesh->mVertices[(curFace-1)*3 + curVertex++];
  227. sz = fast_atof_move(sz, vn->x );
  228. SkipSpaces(&sz);
  229. sz = fast_atof_move(sz, vn->y );
  230. SkipSpaces(&sz);
  231. sz = fast_atof_move(sz, vn->z );
  232. }
  233. }
  234. else if (!::strncmp(sz,"endsolid",8))
  235. {
  236. // finished!
  237. break;
  238. }
  239. // else skip the whole identifier
  240. else while (!::IsSpaceOrNewLine(*sz))++sz;
  241. }
  242. if (!curFace)
  243. {
  244. pMesh->mNumFaces = 0;
  245. throw new ImportErrorException("STL: ASCII file is empty or invalid; no data loaded");
  246. }
  247. pMesh->mNumFaces = curFace;
  248. pMesh->mNumVertices = curFace*3;
  249. // we are finished!
  250. }
  251. // ------------------------------------------------------------------------------------------------
  252. // Read a binary STL file
  253. bool STLImporter::LoadBinaryFile()
  254. {
  255. // skip the first 80 bytes
  256. if (fileSize < 84)
  257. throw new ImportErrorException("STL: file is too small for the header");
  258. bool bIsMaterialise = false;
  259. // search for an occurence of "COLOR=" in the header
  260. const char* sz2 = (const char*)mBuffer;
  261. const char* const szEnd = sz2+80;
  262. while (sz2 < szEnd)
  263. {
  264. if ('C' == *sz2++ && 'O' == *sz2++ && 'L' == *sz2++ &&
  265. 'O' == *sz2++ && 'R' == *sz2++ && '=' == *sz2++)
  266. {
  267. // read the default vertex color for facets
  268. bIsMaterialise = true;
  269. this->clrColorDefault.r = (*sz2++) / 255.0f;
  270. this->clrColorDefault.g = (*sz2++) / 255.0f;
  271. this->clrColorDefault.b = (*sz2++) / 255.0f;
  272. this->clrColorDefault.a = (*sz2++) / 255.0f;
  273. break;
  274. }
  275. }
  276. const unsigned char* sz = (const unsigned char*)mBuffer + 80;
  277. // now read the number of facets
  278. aiMesh* pMesh = pScene->mMeshes[0];
  279. pScene->mRootNode->mName.Set("<STL_BINARY>");
  280. pMesh->mNumFaces = *((uint32_t*)sz);
  281. sz += 4;
  282. if (fileSize < 84 + pMesh->mNumFaces*50)
  283. throw new ImportErrorException("STL: file is too small to keep all facets");
  284. if (!pMesh->mNumFaces)
  285. throw new ImportErrorException("STL: file is empty. There are no facets defined");
  286. pMesh->mNumVertices = pMesh->mNumFaces*3;
  287. aiVector3D* vp,*vn;
  288. vp = pMesh->mVertices = new aiVector3D[pMesh->mNumVertices];
  289. vn = pMesh->mNormals = new aiVector3D[pMesh->mNumVertices];
  290. for (unsigned int i = 0; i < pMesh->mNumFaces;++i)
  291. {
  292. *vn = *((aiVector3D*)sz);
  293. sz += sizeof(aiVector3D);
  294. *(vn+1) = *vn;
  295. *(vn+2) = *vn;
  296. vn += 3;
  297. *vp++ = *((aiVector3D*)sz);
  298. sz += sizeof(aiVector3D);
  299. *vp++ = *((aiVector3D*)sz);
  300. sz += sizeof(aiVector3D);
  301. *vp++ = *((aiVector3D*)sz);
  302. sz += sizeof(aiVector3D);
  303. uint16_t color = *((uint16_t*)sz);
  304. sz += 2;
  305. if (color & (1 << 15))
  306. {
  307. // seems we need to take the color
  308. if (!pMesh->mColors[0])
  309. {
  310. pMesh->mColors[0] = new aiColor4D[pMesh->mNumVertices];
  311. for (unsigned int i = 0; i <pMesh->mNumVertices;++i)
  312. *pMesh->mColors[0]++ = this->clrColorDefault;
  313. pMesh->mColors[0] -= pMesh->mNumVertices;
  314. }
  315. aiColor4D* clr = &pMesh->mColors[0][pMesh->mNumFaces*3];
  316. clr->a = 1.0f;
  317. if (bIsMaterialise) // fuck, this is reversed
  318. {
  319. clr->r = (color & 0x31u) / 31.0f;
  320. clr->g = ((color & (0x31u<<5))>>5u) / 31.0f;
  321. clr->b = ((color & (0x31u<<10))>>10u) / 31.0f;
  322. }
  323. else
  324. {
  325. clr->b = (color & 0x31u) / 31.0f;
  326. clr->g = ((color & (0x31u<<5))>>5u) / 31.0f;
  327. clr->r = ((color & (0x31u<<10))>>10u) / 31.0f;
  328. }
  329. // assign the color to all vertices of the face
  330. *(clr+1) = *clr;
  331. *(clr+2) = *clr;
  332. }
  333. }
  334. if (bIsMaterialise && !pMesh->mColors[0])
  335. {
  336. // use the color was diffuse material color
  337. return true;
  338. }
  339. return false;
  340. }