DXFLoader.cpp 18 KB

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