DXFLoader.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  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 DXF importer class */
  35. #include "AssimpPCH.h"
  36. #ifndef ASSIMP_BUILD_NO_DXF_IMPORTER
  37. #include "DXFLoader.h"
  38. #include "ParsingUtils.h"
  39. #include "fast_atof.h"
  40. using namespace Assimp;
  41. // AutoCAD Binary DXF<CR><LF><SUB><NULL>
  42. #define AI_DXF_BINARY_IDENT ("AutoCAD Binary DXF\r\n\x1a\0")
  43. #define AI_DXF_BINARY_IDENT_LEN (24)
  44. // color indices for DXF - 16 are supported
  45. static aiColor4D g_aclrDxfIndexColors[] =
  46. {
  47. aiColor4D (0.6f, 0.6f, 0.6f, 1.0f),
  48. aiColor4D (1.0f, 0.0f, 0.0f, 1.0f), // red
  49. aiColor4D (0.0f, 1.0f, 0.0f, 1.0f), // green
  50. aiColor4D (0.0f, 0.0f, 1.0f, 1.0f), // blue
  51. aiColor4D (0.3f, 1.0f, 0.3f, 1.0f), // light green
  52. aiColor4D (0.3f, 0.3f, 1.0f, 1.0f), // light blue
  53. aiColor4D (1.0f, 0.3f, 0.3f, 1.0f), // light red
  54. aiColor4D (1.0f, 0.0f, 1.0f, 1.0f), // pink
  55. aiColor4D (1.0f, 0.6f, 0.0f, 1.0f), // orange
  56. aiColor4D (0.6f, 0.3f, 0.0f, 1.0f), // dark orange
  57. aiColor4D (1.0f, 1.0f, 0.0f, 1.0f), // yellow
  58. aiColor4D (0.3f, 0.3f, 0.3f, 1.0f), // dark gray
  59. aiColor4D (0.8f, 0.8f, 0.8f, 1.0f), // light gray
  60. aiColor4D (0.0f, 00.f, 0.0f, 1.0f), // black
  61. aiColor4D (1.0f, 1.0f, 1.0f, 1.0f), // white
  62. aiColor4D (0.6f, 0.0f, 1.0f, 1.0f) // violet
  63. };
  64. #define AI_DXF_NUM_INDEX_COLORS (sizeof(g_aclrDxfIndexColors)/sizeof(g_aclrDxfIndexColors[0]))
  65. // invalid/unassigned color value
  66. aiColor4D g_clrInvalid = aiColor4D(std::numeric_limits<float>::quiet_NaN(),0.f,0.f,1.f);
  67. // ------------------------------------------------------------------------------------------------
  68. // Constructor to be privately used by Importer
  69. DXFImporter::DXFImporter()
  70. {
  71. // nothing to do here
  72. }
  73. // ------------------------------------------------------------------------------------------------
  74. // Destructor, private as well
  75. DXFImporter::~DXFImporter()
  76. {
  77. // nothing to do here
  78. }
  79. // ------------------------------------------------------------------------------------------------
  80. // Returns whether the class can handle the format of the given file.
  81. bool DXFImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler) const
  82. {
  83. // simple check of file extension is enough for the moment
  84. std::string::size_type pos = pFile.find_last_of('.');
  85. // no file extension - can't read
  86. if( pos == std::string::npos)
  87. return false;
  88. std::string extension = pFile.substr( pos);
  89. return !(extension.length() != 4 || extension[0] != '.' ||
  90. extension[1] != 'd' && extension[1] != 'D' ||
  91. extension[2] != 'x' && extension[2] != 'X' ||
  92. extension[3] != 'f' && extension[3] != 'F');
  93. }
  94. // ------------------------------------------------------------------------------------------------
  95. // Get a copy of the next data line, skip strange data
  96. bool DXFImporter::GetNextLine()
  97. {
  98. if(!SkipLine(&buffer))
  99. return false;
  100. if(!SkipSpaces(&buffer))return GetNextLine();
  101. else if (*buffer == '{')
  102. {
  103. // some strange meta data ...
  104. while (true)
  105. {
  106. if(!SkipLine(&buffer))
  107. return false;
  108. if(SkipSpaces(&buffer) && *buffer == '}')
  109. break;
  110. }
  111. return GetNextLine();
  112. }
  113. return true;
  114. }
  115. // ------------------------------------------------------------------------------------------------
  116. // Get the next token in the file
  117. bool DXFImporter::GetNextToken()
  118. {
  119. if (bRepeat)
  120. {
  121. bRepeat = false;
  122. return true;
  123. }
  124. SkipSpaces(&buffer);
  125. groupCode = strtol10s(buffer,&buffer);
  126. if(!GetNextLine())return false;
  127. // copy the data line to a separate buffer
  128. char* m = cursor, *end = &cursor[4096];
  129. while (!IsLineEnd ( *buffer ) && m < end)
  130. *m++ = *buffer++;
  131. *m = '\0';
  132. GetNextLine();
  133. return true;
  134. }
  135. // ------------------------------------------------------------------------------------------------
  136. // Imports the given file into the given scene structure.
  137. void DXFImporter::InternReadFile( const std::string& pFile,
  138. aiScene* pScene, IOSystem* pIOHandler)
  139. {
  140. boost::scoped_ptr<IOStream> file( pIOHandler->Open( pFile));
  141. // Check whether we can read from the file
  142. if( file.get() == NULL)
  143. throw new ImportErrorException( "Failed to open DXF file " + pFile + "");
  144. // read the contents of the file in a buffer
  145. unsigned int m = (unsigned int)file->FileSize();
  146. std::vector<char> buffer2(m+1);
  147. buffer = &buffer2[0];
  148. file->Read( &buffer2[0], m,1);
  149. buffer2[m] = '\0';
  150. bRepeat = false;
  151. mDefaultLayer = NULL;
  152. // check whether this is a binaray DXF file - we can't read binary DXF files :-(
  153. if (!strncmp(AI_DXF_BINARY_IDENT,buffer,AI_DXF_BINARY_IDENT_LEN))
  154. throw new ImportErrorException("DXF: Binary files are not supported at the moment");
  155. // now get all lines of the file
  156. while (GetNextToken())
  157. {
  158. if (2 == groupCode)
  159. {
  160. // ENTITIES and BLOCKS sections - skip the whole rest, no need to waste our time with them
  161. if (!::strcmp(cursor,"ENTITIES") || !::strcmp(cursor,"BLOCKS"))
  162. if (!ParseEntities())break; else bRepeat = true;
  163. // other sections - skip them to make sure there will be no name conflicts
  164. else
  165. {
  166. while (GetNextToken())
  167. {
  168. if (!groupCode && !::strcmp(cursor,"ENDSEC"))break;
  169. }
  170. }
  171. }
  172. // print comment strings
  173. else if (999 == groupCode)
  174. {
  175. DefaultLogger::get()->info(std::string( cursor ));
  176. }
  177. else if (!groupCode && !::strcmp(cursor,"EOF"))
  178. break;
  179. }
  180. // find out how many valud layers we have
  181. for (std::vector<LayerInfo>::const_iterator it = mLayers.begin(),end = mLayers.end();
  182. it != end;++it)
  183. {
  184. if (!(*it).vPositions.empty())++pScene->mNumMeshes;
  185. }
  186. if (!pScene->mNumMeshes)
  187. throw new ImportErrorException("DXF: this file contains no 3d data");
  188. pScene->mMeshes = new aiMesh*[ pScene->mNumMeshes ];
  189. m = 0;
  190. for (std::vector<LayerInfo>::const_iterator it = mLayers.begin(),end = mLayers.end();
  191. it != end;++it)
  192. {
  193. if ((*it).vPositions.empty())continue;
  194. // generate the output mesh
  195. aiMesh* pMesh = pScene->mMeshes[m++] = new aiMesh();
  196. const std::vector<aiVector3D>& vPositions = (*it).vPositions;
  197. const std::vector<aiColor4D>& vColors = (*it).vColors;
  198. // check whether we need vertex colors here
  199. aiColor4D* clrOut = NULL;
  200. const aiColor4D* clr = NULL;
  201. for (std::vector<aiColor4D>::const_iterator it2 = (*it).vColors.begin(), end2 = (*it).vColors.end();
  202. it2 != end2; ++it2)
  203. {
  204. if ((*it2).r == (*it2).r) // check against qnan
  205. {
  206. clrOut = pMesh->mColors[0] = new aiColor4D[vPositions.size()];
  207. for (unsigned int i = 0; i < vPositions.size();++i)
  208. clrOut[i] = aiColor4D(0.6f,0.6f,0.6f,1.0f);
  209. clr = &vColors[0];
  210. break;
  211. }
  212. }
  213. pMesh->mNumFaces = (unsigned int)vPositions.size() / 4u;
  214. pMesh->mFaces = new aiFace[pMesh->mNumFaces];
  215. aiVector3D* vpOut = pMesh->mVertices = new aiVector3D[vPositions.size()];
  216. const aiVector3D* vp = &vPositions[0];
  217. for (unsigned int i = 0; i < pMesh->mNumFaces;++i)
  218. {
  219. aiFace& face = pMesh->mFaces[i];
  220. // check whether we need four, three or two indices here
  221. if (vp[1] == vp[2])
  222. {
  223. face.mNumIndices = 2;
  224. }
  225. else if (vp[3] == vp[2])
  226. {
  227. face.mNumIndices = 3;
  228. }
  229. else face.mNumIndices = 4;
  230. face.mIndices = new unsigned int[face.mNumIndices];
  231. for (unsigned int a = 0; a < face.mNumIndices;++a)
  232. {
  233. *vpOut++ = vp[a];
  234. if (clr)
  235. {
  236. if (is_not_qnan( clr[a].r ))
  237. *clrOut = clr[a];
  238. ++clrOut;
  239. }
  240. face.mIndices[a] = pMesh->mNumVertices++;
  241. }
  242. vp += 4;
  243. }
  244. }
  245. // generate the output scene graph
  246. pScene->mRootNode = new aiNode();
  247. pScene->mRootNode->mName.Set("<DXF_ROOT>");
  248. if (1 == pScene->mNumMeshes)
  249. {
  250. pScene->mRootNode->mMeshes = new unsigned int[ pScene->mRootNode->mNumMeshes = 1 ];
  251. pScene->mRootNode->mMeshes[0] = 0;
  252. }
  253. else
  254. {
  255. pScene->mRootNode->mChildren = new aiNode*[ pScene->mRootNode->mNumChildren = pScene->mNumMeshes ];
  256. for (m = 0; m < pScene->mRootNode->mNumChildren;++m)
  257. {
  258. aiNode* p = pScene->mRootNode->mChildren[m] = new aiNode();
  259. p->mName.length = ::strlen( mLayers[m].name );
  260. ::strcpy(p->mName.data, mLayers[m].name);
  261. p->mMeshes = new unsigned int[p->mNumMeshes = 1];
  262. p->mMeshes[0] = m;
  263. p->mParent = pScene->mRootNode;
  264. }
  265. }
  266. // generate a default material
  267. MaterialHelper* pcMat = new MaterialHelper();
  268. aiString s;
  269. s.Set(AI_DEFAULT_MATERIAL_NAME);
  270. pcMat->AddProperty(&s, AI_MATKEY_NAME);
  271. aiColor4D clrDiffuse(0.6f,0.6f,0.6f,1.0f);
  272. pcMat->AddProperty(&clrDiffuse,1,AI_MATKEY_COLOR_DIFFUSE);
  273. clrDiffuse = aiColor4D(1.0f,1.0f,1.0f,1.0f);
  274. pcMat->AddProperty(&clrDiffuse,1,AI_MATKEY_COLOR_SPECULAR);
  275. clrDiffuse = aiColor4D(0.05f,0.05f,0.05f,1.0f);
  276. pcMat->AddProperty(&clrDiffuse,1,AI_MATKEY_COLOR_AMBIENT);
  277. pScene->mNumMaterials = 1;
  278. pScene->mMaterials = new aiMaterial*[1];
  279. pScene->mMaterials[0] = pcMat;
  280. // --- everything destructs automatically ---
  281. }
  282. // ------------------------------------------------------------------------------------------------
  283. bool DXFImporter::ParseEntities()
  284. {
  285. while (GetNextToken())
  286. {
  287. if (!groupCode)
  288. {
  289. if (!::strcmp(cursor,"3DFACE") || !::strcmp(cursor,"LINE") || !::strcmp(cursor,"3DLINE"))
  290. if (!Parse3DFace()) return false; else bRepeat = true;
  291. if (!::strcmp(cursor,"POLYLINE") || !::strcmp(cursor,"LWPOLYLINE"))
  292. if (!ParsePolyLine()) return false; else bRepeat = true;
  293. if (!::strcmp(cursor,"ENDSEC"))
  294. return true;
  295. }
  296. }
  297. return false;
  298. }
  299. // ------------------------------------------------------------------------------------------------
  300. void DXFImporter::SetLayer(LayerInfo*& out)
  301. {
  302. for (std::vector<LayerInfo>::iterator it = mLayers.begin(),end = mLayers.end();
  303. it != end;++it)
  304. {
  305. if (!::strcmp( (*it).name, cursor ))
  306. {
  307. out = &(*it);
  308. break;
  309. }
  310. }
  311. if (!out)
  312. {
  313. // we don't have this layer yet
  314. mLayers.push_back(LayerInfo());
  315. out = &mLayers.back();
  316. ::strcpy(out->name,cursor);
  317. }
  318. }
  319. // ------------------------------------------------------------------------------------------------
  320. void DXFImporter::SetDefaultLayer(LayerInfo*& out)
  321. {
  322. if (!mDefaultLayer)
  323. {
  324. mLayers.push_back(LayerInfo());
  325. mDefaultLayer = &mLayers.back();
  326. }
  327. out = mDefaultLayer;
  328. }
  329. // ------------------------------------------------------------------------------------------------
  330. bool DXFImporter::ParsePolyLine()
  331. {
  332. bool ret = false;
  333. LayerInfo* out = NULL;
  334. std::vector<aiVector3D> positions;
  335. std::vector<aiColor4D> colors;
  336. std::vector<unsigned int> indices;
  337. unsigned int flags = 0;
  338. while (GetNextToken())
  339. {
  340. switch (groupCode)
  341. {
  342. case 0:
  343. {
  344. if (!::strcmp(cursor,"VERTEX"))
  345. {
  346. aiVector3D v;aiColor4D clr(g_clrInvalid);
  347. unsigned int idx[4] = {0xffffffff,0xffffffff,0xffffffff,0xffffffff};
  348. ParsePolyLineVertex(v, clr, idx);
  349. if (0xffffffff == idx[0])
  350. {
  351. positions.push_back(v);
  352. colors.push_back(clr);
  353. }
  354. else
  355. {
  356. // check whether we have a fourth coordinate
  357. if (0xffffffff == idx[3])
  358. {
  359. idx[3] = idx[2];
  360. }
  361. indices.reserve(indices.size()+4);
  362. for (unsigned int m = 0; m < 4;++m)
  363. indices.push_back(idx[m]);
  364. }
  365. bRepeat = true;
  366. }
  367. else if (!::strcmp(cursor,"ENDSEQ"))
  368. {
  369. ret = true;
  370. }
  371. break;
  372. }
  373. // flags --- important that we know whether it is a polyface mesh
  374. case 70:
  375. {
  376. if (!flags)
  377. {
  378. flags = strtol10(cursor);
  379. }
  380. break;
  381. };
  382. // optional number of vertices
  383. case 71:
  384. {
  385. positions.reserve(strtol10(cursor));
  386. break;
  387. }
  388. // optional number of faces
  389. case 72:
  390. {
  391. indices.reserve(strtol10(cursor));
  392. break;
  393. }
  394. // 8 specifies the layer
  395. case 8:
  396. {
  397. SetLayer(out);
  398. break;
  399. }
  400. }
  401. }
  402. if (!(flags & 64))
  403. {
  404. DefaultLogger::get()->warn("DXF: Only polyface meshes are currently supported");
  405. return ret;
  406. }
  407. if (positions.size() < 3 || indices.size() < 3)
  408. {
  409. DefaultLogger::get()->warn("DXF: Unable to parse POLYLINE element - not enough vertices");
  410. return ret;
  411. }
  412. // use a default layer if necessary
  413. if (!out)SetDefaultLayer(out);
  414. flags = (unsigned int)(out->vPositions.size()+indices.size());
  415. out->vPositions.reserve(flags);
  416. out->vColors.reserve(flags);
  417. // generate unique vertices
  418. for (std::vector<unsigned int>::const_iterator it = indices.begin(), end = indices.end();
  419. it != end; ++it)
  420. {
  421. unsigned int idx = *it;
  422. if (idx > positions.size() || !idx)
  423. {
  424. DefaultLogger::get()->error("DXF: Polyface mesh index os out of range");
  425. idx = (unsigned int) positions.size();
  426. }
  427. out->vPositions.push_back(positions[idx-1]); // indices are one-based.
  428. out->vColors.push_back(colors[idx-1]); // indices are one-based.
  429. }
  430. return ret;
  431. }
  432. // ------------------------------------------------------------------------------------------------
  433. bool DXFImporter::ParsePolyLineVertex(aiVector3D& out,aiColor4D& clr, unsigned int* outIdx)
  434. {
  435. bool ret = false;
  436. while (GetNextToken())
  437. {
  438. switch (groupCode)
  439. {
  440. case 0: ret = true;break;
  441. // todo - handle the correct layer for the vertex
  442. // At the moment it is assumed that all vertices of
  443. // a polyline are placed on the same global layer.
  444. // x position of the first corner
  445. case 10: out.x = fast_atof(cursor);break;
  446. // y position of the first corner
  447. case 20: out.y = -fast_atof(cursor);break;
  448. // z position of the first corner
  449. case 30: out.z = fast_atof(cursor);break;
  450. // POLYFACE vertex indices
  451. case 71: outIdx[0] = strtol10(cursor);break;
  452. case 72: outIdx[1] = strtol10(cursor);break;
  453. case 73: outIdx[2] = strtol10(cursor);break;
  454. // case 74: outIdx[3] = strtol10(cursor);break;
  455. // color
  456. case 62: clr = g_aclrDxfIndexColors[strtol10(cursor) % AI_DXF_NUM_INDEX_COLORS]; break;
  457. };
  458. if (ret)break;
  459. }
  460. return ret;
  461. }
  462. // ------------------------------------------------------------------------------------------------
  463. bool DXFImporter::Parse3DFace()
  464. {
  465. bool ret = false;
  466. LayerInfo* out = NULL;
  467. aiVector3D vip[4]; // -- vectors are initialized to zero
  468. aiColor4D clr(g_clrInvalid);
  469. // this is also used for for parsing line entities
  470. bool bThird = false;
  471. while (GetNextToken())
  472. {
  473. switch (groupCode)
  474. {
  475. case 0: ret = true;break;
  476. // 8 specifies the layer
  477. case 8:
  478. {
  479. SetLayer(out);
  480. break;
  481. }
  482. // x position of the first corner
  483. case 10: vip[0].x = fast_atof(cursor);break;
  484. // y position of the first corner
  485. case 20: vip[0].y = -fast_atof(cursor);break;
  486. // z position of the first corner
  487. case 30: vip[0].z = fast_atof(cursor);break;
  488. // x position of the second corner
  489. case 11: vip[1].x = fast_atof(cursor);break;
  490. // y position of the second corner
  491. case 21: vip[1].y = -fast_atof(cursor);break;
  492. // z position of the second corner
  493. case 31: vip[1].z = fast_atof(cursor);break;
  494. // x position of the third corner
  495. case 12: vip[2].x = fast_atof(cursor);
  496. bThird = true;break;
  497. // y position of the third corner
  498. case 22: vip[2].y = -fast_atof(cursor);
  499. bThird = true;break;
  500. // z position of the third corner
  501. case 32: vip[2].z = fast_atof(cursor);
  502. bThird = true;break;
  503. // x position of the fourth corner
  504. case 13: vip[3].x = fast_atof(cursor);
  505. bThird = true;break;
  506. // y position of the fourth corner
  507. case 23: vip[3].y = -fast_atof(cursor);
  508. bThird = true;break;
  509. // z position of the fourth corner
  510. case 33: vip[3].z = fast_atof(cursor);
  511. bThird = true;break;
  512. // color
  513. case 62: clr = g_aclrDxfIndexColors[strtol10(cursor) % AI_DXF_NUM_INDEX_COLORS]; break;
  514. };
  515. if (ret)break;
  516. }
  517. if (!bThird)vip[2] = vip[1];
  518. // use a default layer if necessary
  519. if (!out)SetDefaultLayer(out);
  520. // add the faces to the face list for this layer
  521. out->vPositions.push_back(vip[0]);
  522. out->vPositions.push_back(vip[1]);
  523. out->vPositions.push_back(vip[2]);
  524. out->vPositions.push_back(vip[3]); // might be equal to the third
  525. for (unsigned int i = 0; i < 4;++i)
  526. out->vColors.push_back(clr);
  527. return ret;
  528. }
  529. #endif // !! ASSIMP_BUILD_NO_DXF_IMPORTER