summaryrefslogtreecommitdiff
path: root/src/import.cc
blob: 3c2cce11cd5e788e5445740f3b7d18cd6f5e298c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
/*
 *  OpenSCAD (www.openscad.org)
 *  Copyright (C) 2009-2011 Clifford Wolf <clifford@clifford.at> and
 *                          Marius Kintel <marius@kintel.net>
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  As a special exception, you have permission to link this program
 *  with the CGAL library and distribute executables, as long as you
 *  follow the requirements of the GNU GPL in regard to all of the
 *  software in the executable aside from CGAL.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 */

#include "importnode.h"

#include "module.h"
#include "polyset.h"
#include "evalcontext.h"
#include "builtin.h"
#include "dxfdata.h"
#include "dxftess.h"
#include "printutils.h"
#include "fileutils.h"
#include "handle_dep.h" // handle_dep()

#ifdef ENABLE_CGAL
#include "cgalutils.h"
#endif

#include <sys/types.h>
#include <fstream>
#include <sstream>
#include <assert.h>
#include <boost/algorithm/string.hpp>
#include <boost/regex.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/filesystem.hpp>
namespace fs = boost::filesystem;
#include <boost/assign/std/vector.hpp>
using namespace boost::assign; // bring 'operator+=()' into scope
#include "boosty.h"

#include <boost/detail/endian.hpp>
#include <boost/cstdint.hpp>

class ImportModule : public AbstractModule
{
public:
	import_type_e type;
	ImportModule(import_type_e type = TYPE_UNKNOWN) : type(type) { }
	virtual AbstractNode *instantiate(const Context *ctx, const ModuleInstantiation *inst, const EvalContext *evalctx) const;
};

AbstractNode *ImportModule::instantiate(const Context *ctx, const ModuleInstantiation *inst, const EvalContext *evalctx) const
{
	AssignmentList args;
	args += Assignment("file", NULL), Assignment("layer", NULL), Assignment("convexity", NULL), Assignment("origin", NULL), Assignment("scale", NULL);
	args += Assignment("filename",NULL), Assignment("layername", NULL);

  // FIXME: This is broken. Tag as deprecated and fix
	// Map old argnames to new argnames for compatibility
	// To fix: 
  // o after c.setVariables()
	//   - if "filename" in evalctx: deprecated-warning && v.set_variable("file", value);
	//   - if "layername" in evalctx: deprecated-warning && v.set_variable("layer", value);
#if 0
	std::vector<std::string> inst_argnames = inst->argnames;
	for (size_t i=0; i<inst_argnames.size(); i++) {
		if (inst_argnames[i] == "filename") inst_argnames[i] = "file";
		if (inst_argnames[i] == "layername") inst_argnames[i] = "layer";
	}
#endif

	Context c(ctx);
	c.setDocumentPath(evalctx->documentPath());
	c.setVariables(args, evalctx);
#if 0 && DEBUG
	c.dump(this, inst);
#endif

	Value v = c.lookup_variable("file");
	if (v.isUndefined()) {
		v = c.lookup_variable("filename");
		if (!v.isUndefined()) {
			PRINT("DEPRECATED: filename= is deprecated. Please use file=");
		}
	}
	std::string filename = lookup_file(v.isUndefined() ? "" : v.toString(), inst->path(), ctx->documentPath());
	import_type_e actualtype = this->type;
	if (actualtype == TYPE_UNKNOWN) {
		std::string extraw = boosty::extension_str( fs::path(filename) );
		std::string ext = boost::algorithm::to_lower_copy( extraw );
		if (ext == ".stl") actualtype = TYPE_STL;
		else if (ext == ".off") actualtype = TYPE_OFF;
		else if (ext == ".dxf") actualtype = TYPE_DXF;
	}

	ImportNode *node = new ImportNode(inst, actualtype);

	node->fn = c.lookup_variable("$fn").toDouble();
	node->fs = c.lookup_variable("$fs").toDouble();
	node->fa = c.lookup_variable("$fa").toDouble();

	node->filename = filename;
	Value layerval = c.lookup_variable("layer", true);
	if (layerval.isUndefined()) {
		layerval = c.lookup_variable("layername");
		if (!layerval.isUndefined()) {
			PRINT("DEPRECATED: layername= is deprecated. Please use layer=");
		}
	}
	node->layername = layerval.isUndefined() ? ""  : layerval.toString();
	node->convexity = c.lookup_variable("convexity", true).toDouble();

	if (node->convexity <= 0) node->convexity = 1;

	Value origin = c.lookup_variable("origin", true);
	node->origin_x = node->origin_y = 0;
	origin.getVec2(node->origin_x, node->origin_y);

	node->scale = c.lookup_variable("scale", true).toDouble();

	if (node->scale <= 0)
		node->scale = 1;

	return node;
}

#define STL_FACET_NUMBYTES 4*3*4+2
// as there is no 'float32_t' standard, we assume the systems 'float'
// is a 'binary32' aka 'single' standard IEEE 32-bit floating point type
union stl_facet {
	uint8_t data8[ STL_FACET_NUMBYTES ];
	uint32_t data32[4*3];
	struct facet_data {
	  float i, j, k;
	  float x1, y1, z1;
	  float x2, y2, z2;
	  float x3, y3, z3;
	  uint16_t attribute_byte_count;
	} data;
};

void uint32_byte_swap( uint32_t &x )
{
#if __GNUC__ >= 4 && __GNUC_MINOR__ >= 3
	x = __builtin_bswap32( x );
#elif defined(__clang__)
	x = __builtin_bswap32( x );
#elif defined(_MSC_VER)
	x = _byteswap_ulong( x );
#else
	uint32_t b1 = ( 0x000000FF & x ) << 24;
	uint32_t b2 = ( 0x0000FF00 & x ) << 8;
	uint32_t b3 = ( 0x00FF0000 & x ) >> 8;
	uint32_t b4 = ( 0xFF000000 & x ) >> 24;
	x = b1 | b2 | b3 | b4;
#endif
}

void read_stl_facet( std::ifstream &f, stl_facet &facet )
{
	f.read( (char*)facet.data8, STL_FACET_NUMBYTES );
#ifdef BOOST_BIG_ENDIAN
	for ( int i = 0; i < 12; i++ ) {
		uint32_byte_swap( facet.data32[ i ] );
	}
	// we ignore attribute byte count
#endif
}

PolySet *ImportNode::evaluate_polyset(class PolySetEvaluator *) const
{
	PolySet *p = NULL;

	if (this->type == TYPE_STL)
	{
		handle_dep((std::string)this->filename);
		// Open file and position at the end
		std::ifstream f(this->filename.c_str(), std::ios::in | std::ios::binary | std::ios::ate);
		if (!f.good()) {
			PRINTB("WARNING: Can't open import file '%s'.", this->filename);
			return p;
		}

		p = new PolySet();

		boost::regex ex_sfe("solid|facet|endloop");
		boost::regex ex_outer("outer loop");
		boost::regex ex_vertex("vertex");
		boost::regex ex_vertices("\\s*vertex\\s+([^\\s]+)\\s+([^\\s]+)\\s+([^\\s]+)");

		bool binary = false;
		std::streampos file_size = f.tellg();
		f.seekg(80);
		if (!f.eof()) {
			uint32_t facenum = 0;
			f.read((char *)&facenum, sizeof(uint32_t));
#ifdef BOOST_BIG_ENDIAN
			uint32_byte_swap( facenum );
#endif
			if (file_size ==  static_cast<std::streamoff>(80 + 4 + 50*facenum)) {
				binary = true;
			}
		}
		f.seekg(0);

		char data[5];
		f.read(data, 5);
		if (!binary && !f.eof() && !memcmp(data, "solid", 5)) {
			int i = 0;
			double vdata[3][3];
			std::string line;
			std::getline(f, line);
			while (!f.eof()) {
				
				std::getline(f, line);
				boost::trim(line);
				if (boost::regex_search(line, ex_sfe)) {
					continue;
				}
				if (boost::regex_search(line, ex_outer)) {
					i = 0;
					continue;
				}
				boost::smatch results;
				if (boost::regex_search(line, results, ex_vertices)) {
					try {
						for (int v=0;v<3;v++) {
							vdata[i][v] = boost::lexical_cast<double>(results[v+1]);
						}
					}
					catch (const boost::bad_lexical_cast &blc) {
						PRINTB("WARNING: Can't parse vertex line '%s'.", line);
						i = 10;
						continue;
					}
					if (++i == 3) {
						p->append_poly();
						p->append_vertex(vdata[0][0], vdata[0][1], vdata[0][2]);
						p->append_vertex(vdata[1][0], vdata[1][1], vdata[1][2]);
						p->append_vertex(vdata[2][0], vdata[2][1], vdata[2][2]);
					}
				}
			}
		}
		else
		{
			f.ignore(80-5+4);
			while (1) {
				stl_facet facet;
				read_stl_facet( f, facet );
				if (f.eof()) break;
				p->append_poly();
				p->append_vertex(facet.data.x1, facet.data.y1, facet.data.z1);
				p->append_vertex(facet.data.x2, facet.data.y2, facet.data.z2);
				p->append_vertex(facet.data.x3, facet.data.y3, facet.data.z3);
			}
		}
	}

	else if (this->type == TYPE_OFF)
	{
#ifdef ENABLE_CGAL
		CGAL_Polyhedron poly;
		std::ifstream file(this->filename.c_str(), std::ios::in | std::ios::binary);
		if (!file.good()) {
			PRINTB("WARNING: Can't open import file '%s'.", this->filename);
		}
		else {
			file >> poly;
			file.close();
			
			p = new PolySet();
			bool err = createPolySetFromPolyhedron(poly, *p);
			if (err) delete p;
		}
#else
  PRINT("WARNING: OFF import requires CGAL.");
#endif
	}

	else if (this->type == TYPE_DXF)
	{
		p = new PolySet();
		DxfData dd(this->fn, this->fs, this->fa, this->filename, this->layername, this->origin_x, this->origin_y, this->scale);
		p->is2d = true;
		dxf_tesselate(p, dd, 0, Vector2d(1,1), true, false, 0);
		dxf_border_to_ps(p, dd);
	}
	else 
	{
		PRINTB("ERROR: Unsupported file format while trying to import file '%s'", this->filename);
	}

	if (p) p->convexity = this->convexity;
	return p;
}

std::string ImportNode::toString() const
{
	std::stringstream stream;
	fs::path path((std::string)this->filename);

	stream << this->name();
	stream << "(file = " << this->filename << ", "
		"layer = " << QuotedString(this->layername) << ", "
		"origin = [" << std::dec << this->origin_x << ", " << this->origin_y << "], "
		"scale = " << this->scale << ", "
		"convexity = " << this->convexity << ", "
		"$fn = " << this->fn << ", $fa = " << this->fa << ", $fs = " << this->fs
#ifndef OPENSCAD_TESTING
  // timestamp is needed for caching, but disturbs the test framework
				 << ", " "timestamp = " << (fs::exists(path) ? fs::last_write_time(path) : 0)
#endif
				 << ")";


	return stream.str();
}

std::string ImportNode::name() const
{
	return "import";
}

void register_builtin_import()
{
	Builtins::init("import_stl", new ImportModule(TYPE_STL));
	Builtins::init("import_off", new ImportModule(TYPE_OFF));
	Builtins::init("import_dxf", new ImportModule(TYPE_DXF));
	Builtins::init("import", new ImportModule());
}
contact: Jan Huwald // Impressum