DXFLoader.cpp 18 KB

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