STLLoader.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2016, 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. #ifndef ASSIMP_BUILD_NO_STL_IMPORTER
  36. // internal headers
  37. #include "STLLoader.h"
  38. #include "ParsingUtils.h"
  39. #include "fast_atof.h"
  40. #include <memory>
  41. #include <assimp/IOSystem.hpp>
  42. #include <assimp/scene.h>
  43. #include <assimp/DefaultLogger.hpp>
  44. using namespace Assimp;
  45. namespace {
  46. static const aiImporterDesc desc = {
  47. "Stereolithography (STL) Importer",
  48. "",
  49. "",
  50. "",
  51. aiImporterFlags_SupportTextFlavour | aiImporterFlags_SupportBinaryFlavour,
  52. 0,
  53. 0,
  54. 0,
  55. 0,
  56. "stl"
  57. };
  58. // A valid binary STL buffer should consist of the following elements, in order:
  59. // 1) 80 byte header
  60. // 2) 4 byte face count
  61. // 3) 50 bytes per face
  62. static bool IsBinarySTL(const char* buffer, unsigned int fileSize) {
  63. if( fileSize < 84 ) {
  64. return false;
  65. }
  66. const uint32_t faceCount = *reinterpret_cast<const uint32_t*>(buffer + 80);
  67. const uint32_t expectedBinaryFileSize = faceCount * 50 + 84;
  68. return expectedBinaryFileSize == fileSize;
  69. }
  70. // An ascii STL buffer will begin with "solid NAME", where NAME is optional.
  71. // Note: The "solid NAME" check is necessary, but not sufficient, to determine
  72. // if the buffer is ASCII; a binary header could also begin with "solid NAME".
  73. static bool IsAsciiSTL(const char* buffer, unsigned int fileSize) {
  74. if (IsBinarySTL(buffer, fileSize))
  75. return false;
  76. const char* bufferEnd = buffer + fileSize;
  77. if (!SkipSpaces(&buffer))
  78. return false;
  79. if (buffer + 5 >= bufferEnd)
  80. return false;
  81. bool isASCII( strncmp( buffer, "solid", 5 ) == 0 );
  82. if( isASCII ) {
  83. // A lot of importers are write solid even if the file is binary. So we have to check for ASCII-characters.
  84. if( fileSize >= 500 ) {
  85. isASCII = true;
  86. for( unsigned int i = 0; i < 500; i++ ) {
  87. if( buffer[ i ] > 127 ) {
  88. isASCII = false;
  89. break;
  90. }
  91. }
  92. }
  93. }
  94. return isASCII;
  95. }
  96. } // namespace
  97. // ------------------------------------------------------------------------------------------------
  98. // Constructor to be privately used by Importer
  99. STLImporter::STLImporter()
  100. : mBuffer(),
  101. fileSize(),
  102. pScene()
  103. {}
  104. // ------------------------------------------------------------------------------------------------
  105. // Destructor, private as well
  106. STLImporter::~STLImporter()
  107. {}
  108. // ------------------------------------------------------------------------------------------------
  109. // Returns whether the class can handle the format of the given file.
  110. bool STLImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler, bool checkSig) const
  111. {
  112. const std::string extension = GetExtension(pFile);
  113. if( extension == "stl" ) {
  114. return true;
  115. } else if (!extension.length() || checkSig) {
  116. if( !pIOHandler ) {
  117. return true;
  118. }
  119. const char* tokens[] = {"STL","solid"};
  120. return SearchFileHeaderForToken(pIOHandler,pFile,tokens,2);
  121. }
  122. return false;
  123. }
  124. // ------------------------------------------------------------------------------------------------
  125. const aiImporterDesc* STLImporter::GetInfo () const {
  126. return &desc;
  127. }
  128. void addFacesToMesh(aiMesh* pMesh)
  129. {
  130. pMesh->mFaces = new aiFace[pMesh->mNumFaces];
  131. for (unsigned int i = 0, p = 0; i < pMesh->mNumFaces;++i) {
  132. aiFace& face = pMesh->mFaces[i];
  133. face.mIndices = new unsigned int[face.mNumIndices = 3];
  134. for (unsigned int o = 0; o < 3;++o,++p) {
  135. face.mIndices[o] = p;
  136. }
  137. }
  138. }
  139. // ------------------------------------------------------------------------------------------------
  140. // Imports the given file into the given scene structure.
  141. void STLImporter::InternReadFile( const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler )
  142. {
  143. std::unique_ptr<IOStream> file( pIOHandler->Open( pFile, "rb"));
  144. // Check whether we can read from the file
  145. if( file.get() == NULL) {
  146. throw DeadlyImportError( "Failed to open STL file " + pFile + ".");
  147. }
  148. fileSize = (unsigned int)file->FileSize();
  149. // allocate storage and copy the contents of the file to a memory buffer
  150. // (terminate it with zero)
  151. std::vector<char> mBuffer2;
  152. TextFileToBuffer(file.get(),mBuffer2);
  153. this->pScene = pScene;
  154. this->mBuffer = &mBuffer2[0];
  155. // the default vertex color is light gray.
  156. clrColorDefault.r = clrColorDefault.g = clrColorDefault.b = clrColorDefault.a = (ai_real) 0.6;
  157. // allocate a single node
  158. pScene->mRootNode = new aiNode();
  159. bool bMatClr = false;
  160. if (IsBinarySTL(mBuffer, fileSize)) {
  161. bMatClr = LoadBinaryFile();
  162. } else if (IsAsciiSTL(mBuffer, fileSize)) {
  163. LoadASCIIFile();
  164. } else {
  165. throw DeadlyImportError( "Failed to determine STL storage representation for " + pFile + ".");
  166. }
  167. // add all created meshes to the single node
  168. pScene->mRootNode->mNumMeshes = pScene->mNumMeshes;
  169. pScene->mRootNode->mMeshes = new unsigned int[pScene->mNumMeshes];
  170. for (unsigned int i = 0; i < pScene->mNumMeshes; i++)
  171. pScene->mRootNode->mMeshes[i] = i;
  172. // create a single default material, using a light gray diffuse color for consistency with
  173. // other geometric types (e.g., PLY).
  174. aiMaterial* pcMat = new aiMaterial();
  175. aiString s;
  176. s.Set(AI_DEFAULT_MATERIAL_NAME);
  177. pcMat->AddProperty(&s, AI_MATKEY_NAME);
  178. aiColor4D clrDiffuse(ai_real(0.6),ai_real(0.6),ai_real(0.6),ai_real(1.0));
  179. if (bMatClr) {
  180. clrDiffuse = clrColorDefault;
  181. }
  182. pcMat->AddProperty(&clrDiffuse,1,AI_MATKEY_COLOR_DIFFUSE);
  183. pcMat->AddProperty(&clrDiffuse,1,AI_MATKEY_COLOR_SPECULAR);
  184. clrDiffuse = aiColor4D( ai_real( 0.05), ai_real( 0.05), ai_real( 0.05), ai_real( 1.0));
  185. pcMat->AddProperty(&clrDiffuse,1,AI_MATKEY_COLOR_AMBIENT);
  186. pScene->mNumMaterials = 1;
  187. pScene->mMaterials = new aiMaterial*[1];
  188. pScene->mMaterials[0] = pcMat;
  189. }
  190. // ------------------------------------------------------------------------------------------------
  191. // Read an ASCII STL file
  192. void STLImporter::LoadASCIIFile()
  193. {
  194. std::vector<aiMesh*> meshes;
  195. const char* sz = mBuffer;
  196. const char* bufferEnd = mBuffer + fileSize;
  197. std::vector<aiVector3D> positionBuffer;
  198. std::vector<aiVector3D> normalBuffer;
  199. // try to guess how many vertices we could have
  200. // assume we'll need 160 bytes for each face
  201. size_t sizeEstimate = std::max(1u, fileSize / 160u ) * 3;
  202. positionBuffer.reserve(sizeEstimate);
  203. normalBuffer.reserve(sizeEstimate);
  204. while (IsAsciiSTL(sz, static_cast<unsigned int>(bufferEnd - sz)))
  205. {
  206. aiMesh* pMesh = new aiMesh();
  207. pMesh->mMaterialIndex = 0;
  208. meshes.push_back(pMesh);
  209. SkipSpaces(&sz);
  210. ai_assert(!IsLineEnd(sz));
  211. sz += 5; // skip the "solid"
  212. SkipSpaces(&sz);
  213. const char* szMe = sz;
  214. while (!::IsSpaceOrNewLine(*sz)) {
  215. sz++;
  216. }
  217. size_t temp;
  218. // setup the name of the node
  219. if ((temp = (size_t)(sz-szMe))) {
  220. if (temp >= MAXLEN) {
  221. throw DeadlyImportError( "STL: Node name too long" );
  222. }
  223. pScene->mRootNode->mName.length = temp;
  224. memcpy(pScene->mRootNode->mName.data,szMe,temp);
  225. pScene->mRootNode->mName.data[temp] = '\0';
  226. }
  227. else pScene->mRootNode->mName.Set("<STL_ASCII>");
  228. unsigned int faceVertexCounter = 3;
  229. for ( ;; )
  230. {
  231. // go to the next token
  232. if(!SkipSpacesAndLineEnd(&sz))
  233. {
  234. // seems we're finished although there was no end marker
  235. DefaultLogger::get()->warn("STL: unexpected EOF. \'endsolid\' keyword was expected");
  236. break;
  237. }
  238. // facet normal -0.13 -0.13 -0.98
  239. if (!strncmp(sz,"facet",5) && IsSpaceOrNewLine(*(sz+5)) && *(sz + 5) != '\0') {
  240. if (faceVertexCounter != 3) {
  241. DefaultLogger::get()->warn("STL: A new facet begins but the old is not yet complete");
  242. }
  243. faceVertexCounter = 0;
  244. normalBuffer.push_back(aiVector3D());
  245. aiVector3D* vn = &normalBuffer.back();
  246. sz += 6;
  247. SkipSpaces(&sz);
  248. if (strncmp(sz,"normal",6)) {
  249. DefaultLogger::get()->warn("STL: a facet normal vector was expected but not found");
  250. }
  251. else
  252. {
  253. if (sz[6] == '\0') {
  254. throw DeadlyImportError("STL: unexpected EOF while parsing facet");
  255. }
  256. sz += 7;
  257. SkipSpaces(&sz);
  258. sz = fast_atoreal_move<ai_real>(sz, (ai_real&)vn->x );
  259. SkipSpaces(&sz);
  260. sz = fast_atoreal_move<ai_real>(sz, (ai_real&)vn->y );
  261. SkipSpaces(&sz);
  262. sz = fast_atoreal_move<ai_real>(sz, (ai_real&)vn->z );
  263. normalBuffer.push_back(*vn);
  264. normalBuffer.push_back(*vn);
  265. }
  266. }
  267. // vertex 1.50000 1.50000 0.00000
  268. else if (!strncmp(sz,"vertex",6) && ::IsSpaceOrNewLine(*(sz+6)))
  269. {
  270. if (faceVertexCounter >= 3) {
  271. DefaultLogger::get()->error("STL: a facet with more than 3 vertices has been found");
  272. ++sz;
  273. }
  274. else
  275. {
  276. if (sz[6] == '\0') {
  277. throw DeadlyImportError("STL: unexpected EOF while parsing facet");
  278. }
  279. sz += 7;
  280. SkipSpaces(&sz);
  281. positionBuffer.push_back(aiVector3D());
  282. aiVector3D* vn = &positionBuffer.back();
  283. sz = fast_atoreal_move<ai_real>(sz, (ai_real&)vn->x );
  284. SkipSpaces(&sz);
  285. sz = fast_atoreal_move<ai_real>(sz, (ai_real&)vn->y );
  286. SkipSpaces(&sz);
  287. sz = fast_atoreal_move<ai_real>(sz, (ai_real&)vn->z );
  288. faceVertexCounter++;
  289. }
  290. }
  291. else if (!::strncmp(sz,"endsolid",8)) {
  292. do {
  293. ++sz;
  294. } while (!::IsLineEnd(*sz));
  295. SkipSpacesAndLineEnd(&sz);
  296. // finished!
  297. break;
  298. }
  299. // else skip the whole identifier
  300. else {
  301. do {
  302. ++sz;
  303. } while (!::IsSpaceOrNewLine(*sz));
  304. }
  305. }
  306. if (positionBuffer.empty()) {
  307. pMesh->mNumFaces = 0;
  308. throw DeadlyImportError("STL: ASCII file is empty or invalid; no data loaded");
  309. }
  310. if (positionBuffer.size() % 3 != 0) {
  311. pMesh->mNumFaces = 0;
  312. throw DeadlyImportError("STL: Invalid number of vertices");
  313. }
  314. if (normalBuffer.size() != positionBuffer.size()) {
  315. pMesh->mNumFaces = 0;
  316. throw DeadlyImportError("Normal buffer size does not match position buffer size");
  317. }
  318. pMesh->mNumFaces = static_cast<unsigned int>(positionBuffer.size() / 3);
  319. pMesh->mNumVertices = static_cast<unsigned int>(positionBuffer.size());
  320. pMesh->mVertices = new aiVector3D[pMesh->mNumVertices];
  321. memcpy(pMesh->mVertices, &positionBuffer[0].x, pMesh->mNumVertices * sizeof(aiVector3D));
  322. positionBuffer.clear();
  323. pMesh->mNormals = new aiVector3D[pMesh->mNumVertices];
  324. memcpy(pMesh->mNormals, &normalBuffer[0].x, pMesh->mNumVertices * sizeof(aiVector3D));
  325. normalBuffer.clear();
  326. // now copy faces
  327. addFacesToMesh(pMesh);
  328. }
  329. // now add the loaded meshes
  330. pScene->mNumMeshes = (unsigned int)meshes.size();
  331. pScene->mMeshes = new aiMesh*[pScene->mNumMeshes];
  332. for (size_t i = 0; i < meshes.size(); i++)
  333. {
  334. pScene->mMeshes[i] = meshes[i];
  335. }
  336. }
  337. // ------------------------------------------------------------------------------------------------
  338. // Read a binary STL file
  339. bool STLImporter::LoadBinaryFile()
  340. {
  341. // allocate one mesh
  342. pScene->mNumMeshes = 1;
  343. pScene->mMeshes = new aiMesh*[1];
  344. aiMesh* pMesh = pScene->mMeshes[0] = new aiMesh();
  345. pMesh->mMaterialIndex = 0;
  346. // skip the first 80 bytes
  347. if (fileSize < 84) {
  348. throw DeadlyImportError("STL: file is too small for the header");
  349. }
  350. bool bIsMaterialise = false;
  351. // search for an occurrence of "COLOR=" in the header
  352. const unsigned char* sz2 = (const unsigned char*)mBuffer;
  353. const unsigned char* const szEnd = sz2+80;
  354. while (sz2 < szEnd) {
  355. if ('C' == *sz2++ && 'O' == *sz2++ && 'L' == *sz2++ &&
  356. 'O' == *sz2++ && 'R' == *sz2++ && '=' == *sz2++) {
  357. // read the default vertex color for facets
  358. bIsMaterialise = true;
  359. DefaultLogger::get()->info("STL: Taking code path for Materialise files");
  360. const ai_real invByte = (ai_real)1.0 / ( ai_real )255.0;
  361. clrColorDefault.r = (*sz2++) * invByte;
  362. clrColorDefault.g = (*sz2++) * invByte;
  363. clrColorDefault.b = (*sz2++) * invByte;
  364. clrColorDefault.a = (*sz2++) * invByte;
  365. break;
  366. }
  367. }
  368. const unsigned char* sz = (const unsigned char*)mBuffer + 80;
  369. // now read the number of facets
  370. pScene->mRootNode->mName.Set("<STL_BINARY>");
  371. pMesh->mNumFaces = *((uint32_t*)sz);
  372. sz += 4;
  373. if (fileSize < 84 + pMesh->mNumFaces*50) {
  374. throw DeadlyImportError("STL: file is too small to hold all facets");
  375. }
  376. if (!pMesh->mNumFaces) {
  377. throw DeadlyImportError("STL: file is empty. There are no facets defined");
  378. }
  379. pMesh->mNumVertices = pMesh->mNumFaces*3;
  380. aiVector3D* vp,*vn;
  381. vp = pMesh->mVertices = new aiVector3D[pMesh->mNumVertices];
  382. vn = pMesh->mNormals = new aiVector3D[pMesh->mNumVertices];
  383. for (unsigned int i = 0; i < pMesh->mNumFaces;++i) {
  384. // NOTE: Blender sometimes writes empty normals ... this is not
  385. // our fault ... the RemoveInvalidData helper step should fix that
  386. *vn = *((aiVector3D*)sz);
  387. sz += sizeof(aiVector3D);
  388. *(vn+1) = *vn;
  389. *(vn+2) = *vn;
  390. vn += 3;
  391. *vp++ = *((aiVector3D*)sz);
  392. sz += sizeof(aiVector3D);
  393. *vp++ = *((aiVector3D*)sz);
  394. sz += sizeof(aiVector3D);
  395. *vp++ = *((aiVector3D*)sz);
  396. sz += sizeof(aiVector3D);
  397. uint16_t color = *((uint16_t*)sz);
  398. sz += 2;
  399. if (color & (1 << 15))
  400. {
  401. // seems we need to take the color
  402. if (!pMesh->mColors[0])
  403. {
  404. pMesh->mColors[0] = new aiColor4D[pMesh->mNumVertices];
  405. for (unsigned int i = 0; i <pMesh->mNumVertices;++i)
  406. *pMesh->mColors[0]++ = this->clrColorDefault;
  407. pMesh->mColors[0] -= pMesh->mNumVertices;
  408. DefaultLogger::get()->info("STL: Mesh has vertex colors");
  409. }
  410. aiColor4D* clr = &pMesh->mColors[0][i*3];
  411. clr->a = 1.0;
  412. const ai_real invVal( (ai_real)1.0 / ( ai_real )31.0 );
  413. if (bIsMaterialise) // this is reversed
  414. {
  415. clr->r = (color & 0x31u) *invVal;
  416. clr->g = ((color & (0x31u<<5))>>5u) *invVal;
  417. clr->b = ((color & (0x31u<<10))>>10u) *invVal;
  418. }
  419. else
  420. {
  421. clr->b = (color & 0x31u) *invVal;
  422. clr->g = ((color & (0x31u<<5))>>5u) *invVal;
  423. clr->r = ((color & (0x31u<<10))>>10u) *invVal;
  424. }
  425. // assign the color to all vertices of the face
  426. *(clr+1) = *clr;
  427. *(clr+2) = *clr;
  428. }
  429. }
  430. // now copy faces
  431. addFacesToMesh(pMesh);
  432. if (bIsMaterialise && !pMesh->mColors[0])
  433. {
  434. // use the color as diffuse material color
  435. return true;
  436. }
  437. return false;
  438. }
  439. #endif // !! ASSIMP_BUILD_NO_STL_IMPORTER