DXFLoader.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  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 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::string& append)
  87. {
  88. append.append("*.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 new ImportErrorException( "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 new ImportErrorException("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 new ImportErrorException("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. if (!Parse3DFace()) {
  276. return false;
  277. }
  278. else {
  279. bRepeat = true;
  280. }
  281. }
  282. if (!::strcmp(cursor,"POLYLINE") || !::strcmp(cursor,"LWPOLYLINE")){
  283. if (!ParsePolyLine()) {
  284. return false;
  285. }
  286. else {
  287. bRepeat = true;
  288. }
  289. }
  290. if (!::strcmp(cursor,"ENDSEC")) {
  291. return true;
  292. }
  293. }
  294. }
  295. return false;
  296. }
  297. // ------------------------------------------------------------------------------------------------
  298. void DXFImporter::SetLayer(LayerInfo*& out)
  299. {
  300. for (std::vector<LayerInfo>::iterator it = mLayers.begin(),end = mLayers.end();it != end;++it) {
  301. if (!::strcmp( (*it).name, cursor )) {
  302. out = &(*it);
  303. break;
  304. }
  305. }
  306. if (!out) {
  307. // we don't have this layer yet
  308. mLayers.push_back(LayerInfo());
  309. out = &mLayers.back();
  310. ::strcpy(out->name,cursor);
  311. }
  312. }
  313. // ------------------------------------------------------------------------------------------------
  314. void DXFImporter::SetDefaultLayer(LayerInfo*& out)
  315. {
  316. if (!mDefaultLayer) {
  317. mLayers.push_back(LayerInfo());
  318. mDefaultLayer = &mLayers.back();
  319. }
  320. out = mDefaultLayer;
  321. }
  322. // ------------------------------------------------------------------------------------------------
  323. bool DXFImporter::ParsePolyLine()
  324. {
  325. bool ret = false;
  326. LayerInfo* out = NULL;
  327. std::vector<aiVector3D> positions;
  328. std::vector<aiColor4D> colors;
  329. std::vector<unsigned int> indices;
  330. unsigned int flags = 0;
  331. while (GetNextToken()) {
  332. switch (groupCode)
  333. {
  334. case 0:
  335. {
  336. if (!::strcmp(cursor,"VERTEX")) {
  337. aiVector3D v;aiColor4D clr(g_clrInvalid);
  338. unsigned int idx[4] = {0xffffffff,0xffffffff,0xffffffff,0xffffffff};
  339. ParsePolyLineVertex(v, clr, idx);
  340. if (0xffffffff == idx[0]) {
  341. positions.push_back(v);
  342. colors.push_back(clr);
  343. }
  344. else {
  345. // check whether we have a fourth coordinate
  346. if (0xffffffff == idx[3]) {
  347. idx[3] = idx[2];
  348. }
  349. indices.reserve(indices.size()+4);
  350. for (unsigned int m = 0; m < 4;++m)
  351. indices.push_back(idx[m]);
  352. }
  353. bRepeat = true;
  354. }
  355. else if (!::strcmp(cursor,"ENDSEQ")) {
  356. ret = true;
  357. }
  358. break;
  359. }
  360. // flags --- important that we know whether it is a polyface mesh
  361. case 70:
  362. {
  363. if (!flags) {
  364. flags = strtol10(cursor);
  365. }
  366. break;
  367. };
  368. // optional number of vertices
  369. case 71:
  370. {
  371. positions.reserve(strtol10(cursor));
  372. break;
  373. }
  374. // optional number of faces
  375. case 72:
  376. {
  377. indices.reserve(strtol10(cursor));
  378. break;
  379. }
  380. // 8 specifies the layer
  381. case 8:
  382. {
  383. SetLayer(out);
  384. break;
  385. }
  386. }
  387. }
  388. if (!(flags & 64)) {
  389. DefaultLogger::get()->warn("DXF: Only polyface meshes are currently supported");
  390. return ret;
  391. }
  392. if (positions.size() < 3 || indices.size() < 3) {
  393. DefaultLogger::get()->warn("DXF: Unable to parse POLYLINE element - not enough vertices");
  394. return ret;
  395. }
  396. // use a default layer if necessary
  397. if (!out) {
  398. SetDefaultLayer(out);
  399. }
  400. flags = (unsigned int)(out->vPositions.size()+indices.size());
  401. out->vPositions.reserve(flags);
  402. out->vColors.reserve(flags);
  403. // generate unique vertices
  404. for (std::vector<unsigned int>::const_iterator it = indices.begin(), end = indices.end();it != end; ++it) {
  405. unsigned int idx = *it;
  406. if (idx > positions.size() || !idx) {
  407. DefaultLogger::get()->error("DXF: Polyface mesh index os out of range");
  408. idx = (unsigned int) positions.size();
  409. }
  410. out->vPositions.push_back(positions[idx-1]); // indices are one-based.
  411. out->vColors.push_back(colors[idx-1]); // indices are one-based.
  412. }
  413. return ret;
  414. }
  415. // ------------------------------------------------------------------------------------------------
  416. bool DXFImporter::ParsePolyLineVertex(aiVector3D& out,aiColor4D& clr, unsigned int* outIdx)
  417. {
  418. bool ret = false;
  419. while (GetNextToken()) {
  420. switch (groupCode)
  421. {
  422. case 0: ret = true;
  423. break;
  424. // todo - handle the correct layer for the vertex. At the moment it is assumed that all vertices of
  425. // a polyline are placed on the same global layer.
  426. // x position of the first corner
  427. case 10: out.x = fast_atof(cursor);break;
  428. // y position of the first corner
  429. case 20: out.y = -fast_atof(cursor);break;
  430. // z position of the first corner
  431. case 30: out.z = fast_atof(cursor);break;
  432. // POLYFACE vertex indices
  433. case 71: outIdx[0] = strtol10(cursor);break;
  434. case 72: outIdx[1] = strtol10(cursor);break;
  435. case 73: outIdx[2] = strtol10(cursor);break;
  436. // case 74: outIdx[3] = strtol10(cursor);break;
  437. // color
  438. case 62: clr = g_aclrDxfIndexColors[strtol10(cursor) % AI_DXF_NUM_INDEX_COLORS]; break;
  439. };
  440. if (ret) {
  441. break;
  442. }
  443. }
  444. return ret;
  445. }
  446. // ------------------------------------------------------------------------------------------------
  447. bool DXFImporter::Parse3DFace()
  448. {
  449. bool ret = false;
  450. LayerInfo* out = NULL;
  451. aiVector3D vip[4]; // -- vectors are initialized to zero
  452. aiColor4D clr(g_clrInvalid);
  453. // this is also used for for parsing line entities
  454. bool bThird = false;
  455. while (GetNextToken()) {
  456. switch (groupCode) {
  457. case 0:
  458. ret = true;
  459. break;
  460. // 8 specifies the layer
  461. case 8: {
  462. SetLayer(out);
  463. break;
  464. }
  465. // x position of the first corner
  466. case 10: vip[0].x = fast_atof(cursor);break;
  467. // y position of the first corner
  468. case 20: vip[0].y = -fast_atof(cursor);break;
  469. // z position of the first corner
  470. case 30: vip[0].z = fast_atof(cursor);break;
  471. // x position of the second corner
  472. case 11: vip[1].x = fast_atof(cursor);break;
  473. // y position of the second corner
  474. case 21: vip[1].y = -fast_atof(cursor);break;
  475. // z position of the second corner
  476. case 31: vip[1].z = fast_atof(cursor);break;
  477. // x position of the third corner
  478. case 12: vip[2].x = fast_atof(cursor);
  479. bThird = true;break;
  480. // y position of the third corner
  481. case 22: vip[2].y = -fast_atof(cursor);
  482. bThird = true;break;
  483. // z position of the third corner
  484. case 32: vip[2].z = fast_atof(cursor);
  485. bThird = true;break;
  486. // x position of the fourth corner
  487. case 13: vip[3].x = fast_atof(cursor);
  488. bThird = true;break;
  489. // y position of the fourth corner
  490. case 23: vip[3].y = -fast_atof(cursor);
  491. bThird = true;break;
  492. // z position of the fourth corner
  493. case 33: vip[3].z = fast_atof(cursor);
  494. bThird = true;break;
  495. // color
  496. case 62: clr = g_aclrDxfIndexColors[strtol10(cursor) % AI_DXF_NUM_INDEX_COLORS]; break;
  497. };
  498. if (ret)
  499. break;
  500. }
  501. if (!bThird)
  502. vip[2] = vip[1];
  503. // use a default layer if necessary
  504. if (!out) {
  505. SetDefaultLayer(out);
  506. }
  507. // add the faces to the face list for this layer
  508. out->vPositions.push_back(vip[0]);
  509. out->vPositions.push_back(vip[1]);
  510. out->vPositions.push_back(vip[2]);
  511. out->vPositions.push_back(vip[3]); // might be equal to the third
  512. for (unsigned int i = 0; i < 4;++i)
  513. out->vColors.push_back(clr);
  514. return ret;
  515. }
  516. #endif // !! ASSIMP_BUILD_NO_DXF_IMPORTER