How to handle DWG files in C++

user3353819 picture user3353819 · Mar 23, 2014 · Viewed 10.5k times · Source

I'm working on a project where I will need to import line data from a .dwg file in C++ and am struggling to know where to start. I've had a look at this http://opendesign.com/files/guestdownloads/OpenDesign_Specification_for_.dwg_files.pdf, and I think it is possibly too hardcore for me unless anyone knows of a way of describing, simply, in code the strategy for decoding it? For instance, presumably every single operation would have to be bit wise?

Other than that, I might have to rely on some third-party libraries, but the question is: Are there any such (open source) libraries which are licensed with a permissive license? I can't use copy left code in this project.

To clarify in response to comments, I'm looking for permissive licensed libraries (see http://en.m.wikipedia.org/wiki/Permissive_free_software_licence). This includes for example MIT and BSD licenses, but not GPL (LGPL would work perhaps, but only if there are exceptions for static linking). And of course public domain would work too. GPL is strongly copyleft, meaning even if you don't alter it, but link to it with separate original code that code has to also be licensed under GPL.

Answer

Drew Chapin picture Drew Chapin · Mar 23, 2014

Why reinvent the wheel? There are plently of DWG libraries available. Try LibDWG. It's licensed under the GNU GPL (i.e. open source). There is also LibreDWG which is based on LibDWG, but available directly from the GNU project website. There is an example of using LibreDWG on github that opens a DWG file, and converts it to an SVG.

Reading the file seems pretty straight forward:

int error;
Dwg_Data dwg;

error = dwg_read_file(filename, &dwg);

if (!error)
{
    model_xmin = dwg_model_x_min(&dwg);
    model_ymin = dwg_model_y_min(&dwg);
    double dx = (dwg_model_x_max(&dwg) - dwg_model_x_min(&dwg));
    double dy = (dwg_model_y_max(&dwg) - dwg_model_y_min(&dwg));
    double scale_x = dx / (dwg_page_x_max(&dwg) - dwg_page_x_min(&dwg));
    double scale_y = dy / (dwg_page_y_max(&dwg) - dwg_page_y_min(&dwg));
    //...
}

dwg_free(&dwg);