DXFLoader.cpp 17 KB

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