STLLoader.cpp 13 KB

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