forked from Ultimaker/CuraEngine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gcodeExport.cpp
587 lines (531 loc) · 17.7 KB
/
gcodeExport.cpp
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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
/** Copyright (C) 2013 David Braam - Released under terms of the AGPLv3 License */
#include <stdarg.h>
#include "gcodeExport.h"
#include "pathOrderOptimizer.h"
#include "timeEstimate.h"
#include "settings.h"
#include "utils/logoutput.h"
#if defined(__APPLE__) && defined(__MACH__)
//On MacOS the file offset functions are always 64bit.
#define off64_t off_t
#define ftello64 ftello
#define fseeko64 fseeko
#endif
GCodeExport::GCodeExport()
: currentPosition(0,0,0)
{
extrusionAmount = 0;
extrusionPerMM = 0;
retractionAmount = 4.5;
minimalExtrusionBeforeRetraction = 0.0;
extrusionAmountAtPreviousRetraction = -10000;
extruderSwitchRetraction = 14.5;
extruderNr = 0;
currentFanSpeed = -1;
totalPrintTime = 0.0;
for(unsigned int e=0; e<MAX_EXTRUDERS; e++)
totalFilament[e] = 0.0;
currentSpeed = 0;
retractionSpeed = 45;
isRetracted = true;
memset(extruderOffset, 0, sizeof(extruderOffset));
f = stdout;
}
GCodeExport::~GCodeExport()
{
if (f && f != stdout)
fclose(f);
}
void GCodeExport::replaceTagInStart(const char* tag, const char* replaceValue)
{
if (f == stdout)
{
log("Replace:%s:%s", tag, replaceValue);
return;
}
off64_t oldPos = ftello64(f);
char buffer[1024];
fseeko64(f, 0, SEEK_SET);
fread(buffer, 1024, 1, f);
char* c = strstr(buffer, tag);
memset(c, ' ', strlen(tag));
if (c) memcpy(c, replaceValue, strlen(replaceValue));
fseeko64(f, 0, SEEK_SET);
fwrite(buffer, 1024, 1, f);
fseeko64(f, oldPos, SEEK_SET);
}
void GCodeExport::setExtruderOffset(int id, Point p)
{
extruderOffset[id] = p;
}
void GCodeExport::setFlavor(int flavor)
{
this->flavor = flavor;
}
int GCodeExport::getFlavor()
{
return this->flavor;
}
void GCodeExport::setFilename(const char* filename)
{
f = fopen(filename, "w+");
}
bool GCodeExport::isValid()
{
return f != NULL;
}
void GCodeExport::setExtrusion(int layerThickness, int filamentDiameter, int flow)
{
double filamentArea = M_PI * (double(filamentDiameter) / 1000.0 / 2.0) * (double(filamentDiameter) / 1000.0 / 2.0);
if (flavor == GCODE_FLAVOR_ULTIGCODE)//UltiGCode uses volume extrusion as E value, and thus does not need the filamentArea in the mix.
extrusionPerMM = double(layerThickness) / 1000.0;
else
extrusionPerMM = double(layerThickness) / 1000.0 / filamentArea * double(flow) / 100.0;
}
void GCodeExport::setRetractionSettings(int retractionAmount, int retractionSpeed, int extruderSwitchRetraction, int minimalExtrusionBeforeRetraction)
{
this->retractionAmount = double(retractionAmount) / 1000.0;
this->retractionSpeed = retractionSpeed;
this->extruderSwitchRetraction = double(extruderSwitchRetraction) / 1000.0;
this->minimalExtrusionBeforeRetraction = double(minimalExtrusionBeforeRetraction) / 1000.0;
}
void GCodeExport::setZ(int z)
{
this->zPos = z;
}
Point GCodeExport::getPositionXY()
{
return Point(currentPosition.x, currentPosition.y);
}
int GCodeExport::getPositionZ()
{
return currentPosition.z;
}
int GCodeExport::getExtruderNr()
{
return extruderNr;
}
double GCodeExport::getTotalFilamentUsed(int e)
{
if (e == extruderNr)
return totalFilament[e] + extrusionAmount;
return totalFilament[e];
}
double GCodeExport::getTotalPrintTime()
{
return totalPrintTime;
}
void GCodeExport::updateTotalPrintTime()
{
totalPrintTime += estimateCalculator.calculate();
estimateCalculator.reset();
}
void GCodeExport::addComment(const char* comment, ...)
{
va_list args;
va_start(args, comment);
fprintf(f, ";");
vfprintf(f, comment, args);
fprintf(f, "\n");
va_end(args);
}
void GCodeExport::addLine(const char* line, ...)
{
va_list args;
va_start(args, line);
vfprintf(f, line, args);
fprintf(f, "\n");
va_end(args);
}
void GCodeExport::resetExtrusionValue()
{
if (extrusionAmount != 0.0)
{
fprintf(f, "G92 E0\n");
totalFilament[extruderNr] += extrusionAmount;
extrusionAmountAtPreviousRetraction -= extrusionAmount;
extrusionAmount = 0.0;
}
}
void GCodeExport::addDelay(double timeAmount)
{
fprintf(f, "G4 P%d\n", int(timeAmount * 1000));
totalPrintTime += timeAmount;
}
void GCodeExport::addMove(Point p, int speed, int lineWidth)
{
if (lineWidth != 0)
{
Point diff = p - getPositionXY();
if (isRetracted)
{
if (flavor == GCODE_FLAVOR_ULTIGCODE)
{
fprintf(f, "G11\n");
}else{
fprintf(f, "G1 F%i E%0.5lf\n", retractionSpeed * 60, extrusionAmount);
currentSpeed = retractionSpeed;
estimateCalculator.plan(TimeEstimateCalculator::Position(double(p.X) / 1000.0, (p.Y) / 1000.0, double(zPos) / 1000.0, extrusionAmount), currentSpeed);
}
if (extrusionAmount > 10000.0) //According to https://github.com/Ultimaker/CuraEngine/issues/14 having more then 21m of extrusion causes inaccuracies. So reset it every 10m, just to be sure.
resetExtrusionValue();
isRetracted = false;
}
extrusionAmount += extrusionPerMM * double(lineWidth) / 1000.0 * vSizeMM(diff);
fprintf(f, "G1");
}else{
fprintf(f, "G0");
}
if (currentSpeed != speed)
{
fprintf(f, " F%i", speed * 60);
currentSpeed = speed;
}
fprintf(f, " X%0.2f Y%0.2f", float(p.X - extruderOffset[extruderNr].X)/1000, float(p.Y - extruderOffset[extruderNr].Y)/1000);
if (zPos != currentPosition.z)
fprintf(f, " Z%0.2f", float(zPos)/1000);
if (lineWidth != 0)
fprintf(f, " E%0.5lf", extrusionAmount);
fprintf(f, "\n");
currentPosition = Point3(p.X, p.Y, zPos);
estimateCalculator.plan(TimeEstimateCalculator::Position(double(currentPosition.x) / 1000.0, (currentPosition.y) / 1000.0, double(currentPosition.z) / 1000.0, extrusionAmount), currentSpeed);
}
void GCodeExport::addRetraction()
{
if (retractionAmount > 0 && !isRetracted && extrusionAmountAtPreviousRetraction + minimalExtrusionBeforeRetraction < extrusionAmount)
{
if (flavor == GCODE_FLAVOR_ULTIGCODE)
{
fprintf(f, "G10\n");
}else{
fprintf(f, "G1 F%i E%0.5lf\n", retractionSpeed * 60, extrusionAmount - retractionAmount);
currentSpeed = retractionSpeed;
estimateCalculator.plan(TimeEstimateCalculator::Position(double(currentPosition.x) / 1000.0, (currentPosition.y) / 1000.0, double(currentPosition.z) / 1000.0, extrusionAmount - retractionAmount), currentSpeed);
}
extrusionAmountAtPreviousRetraction = extrusionAmount;
isRetracted = true;
}
}
void GCodeExport::switchExtruder(int newExtruder)
{
if (extruderNr == newExtruder)
return;
resetExtrusionValue();
extruderNr = newExtruder;
if (flavor == GCODE_FLAVOR_ULTIGCODE)
{
fprintf(f, "G10 S1\n");
}else{
fprintf(f, "G1 F%i E%0.4lf\n", retractionSpeed * 60, extrusionAmount - extruderSwitchRetraction);
currentSpeed = retractionSpeed;
}
isRetracted = true;
if (flavor == GCODE_FLAVOR_MAKERBOT)
fprintf(f, "M135 T%i\n", extruderNr);
else
fprintf(f, "T%i\n", extruderNr);
}
void GCodeExport::addCode(const char* str)
{
fprintf(f, "%s\n", str);
}
void GCodeExport::addFanCommand(int speed)
{
if (currentFanSpeed == speed)
return;
if (speed > 0)
{
if (flavor == GCODE_FLAVOR_MAKERBOT)
fprintf(f, "M126 T0 ; value = %d\n", speed * 255 / 100);
else
fprintf(f, "M106 S%d\n", speed * 255 / 100);
}
else
{
if (flavor == GCODE_FLAVOR_MAKERBOT)
fprintf(f, "M127 T0\n");
else
fprintf(f, "M107\n");
}
currentFanSpeed = speed;
}
int GCodeExport::getFileSize(){
return ftell(f);
}
void GCodeExport::tellFileSize() {
float fsize = (float) ftell(f);
if(fsize > 1024*1024) {
fsize /= 1024.0*1024.0;
log("Wrote %5.1f MB.\n",fsize);
}
if(fsize > 1024) {
fsize /= 1024.0;
log("Wrote %5.1f kilobytes.\n",fsize);
}
}
GCodePath* GCodePlanner::getLatestPathWithConfig(GCodePathConfig* config)
{
if (paths.size() > 0 && paths[paths.size()-1].config == config && !paths[paths.size()-1].done)
return &paths[paths.size()-1];
paths.push_back(GCodePath());
GCodePath* ret = &paths[paths.size()-1];
ret->retract = false;
ret->config = config;
ret->extruder = currentExtruder;
ret->done = false;
return ret;
}
void GCodePlanner::forceNewPathStart()
{
if (paths.size() > 0)
paths[paths.size()-1].done = true;
}
GCodePlanner::GCodePlanner(GCodeExport& gcode, int travelSpeed, int retractionMinimalDistance)
: gcode(gcode), travelConfig(travelSpeed, 0, "travel")
{
lastPosition = gcode.getPositionXY();
comb = NULL;
extrudeSpeedFactor = 100;
travelSpeedFactor = 100;
extraTime = 0.0;
totalPrintTime = 0.0;
forceRetraction = false;
alwaysRetract = false;
currentExtruder = gcode.getExtruderNr();
this->retractionMinimalDistance = retractionMinimalDistance;
}
GCodePlanner::~GCodePlanner()
{
if (comb)
delete comb;
}
void GCodePlanner::addTravel(Point p)
{
GCodePath* path = getLatestPathWithConfig(&travelConfig);
if (forceRetraction)
{
if (!shorterThen(lastPosition - p, retractionMinimalDistance))
{
path->retract = true;
}
forceRetraction = false;
}else if (comb != NULL)
{
vector<Point> pointList;
if (comb->calc(lastPosition, p, pointList))
{
for(unsigned int n=0; n<pointList.size(); n++)
{
path->points.push_back(pointList[n]);
}
}else{
if (!shorterThen(lastPosition - p, retractionMinimalDistance))
path->retract = true;
}
}else if (alwaysRetract)
{
if (!shorterThen(lastPosition - p, retractionMinimalDistance))
path->retract = true;
}
path->points.push_back(p);
lastPosition = p;
}
void GCodePlanner::addExtrusionMove(Point p, GCodePathConfig* config)
{
getLatestPathWithConfig(config)->points.push_back(p);
lastPosition = p;
}
void GCodePlanner::moveInsideCombBoundary(int distance)
{
if (!comb || comb->checkInside(lastPosition)) return;
Point p = lastPosition;
if (comb->moveInside(&p, distance))
{
//Move inside again, so we move out of tight 90deg corners
comb->moveInside(&p, distance);
if (comb->checkInside(p))
{
addTravel(p);
//Make sure the that any retraction happens after this move, not before it by starting a new move path.
forceNewPathStart();
}
}
}
void GCodePlanner::addPolygon(PolygonRef polygon, int startIdx, GCodePathConfig* config)
{
Point p0 = polygon[startIdx];
addTravel(p0);
for(unsigned int i=1; i<polygon.size(); i++)
{
Point p1 = polygon[(startIdx + i) % polygon.size()];
addExtrusionMove(p1, config);
p0 = p1;
}
if (polygon.size() > 2)
addExtrusionMove(polygon[startIdx], config);
}
void GCodePlanner::addPolygonsByOptimizer(Polygons& polygons, GCodePathConfig* config)
{
PathOrderOptimizer orderOptimizer(lastPosition);
for(unsigned int i=0;i<polygons.size();i++)
orderOptimizer.addPolygon(polygons[i]);
orderOptimizer.optimize();
for(unsigned int i=0;i<orderOptimizer.polyOrder.size();i++)
{
int nr = orderOptimizer.polyOrder[i];
addPolygon(polygons[nr], orderOptimizer.polyStart[nr], config);
}
}
void GCodePlanner::forceMinimalLayerTime(double minTime, int minimalSpeed)
{
Point p0 = gcode.getPositionXY();
double travelTime = 0.0;
double extrudeTime = 0.0;
for(unsigned int n=0; n<paths.size(); n++)
{
GCodePath* path = &paths[n];
for(unsigned int i=0; i<path->points.size(); i++)
{
double thisTime = vSizeMM(p0 - path->points[i]) / double(path->config->speed);
if (path->config->lineWidth != 0)
extrudeTime += thisTime;
else
travelTime += thisTime;
p0 = path->points[i];
}
}
double totalTime = extrudeTime + travelTime;
if (totalTime < minTime && extrudeTime > 0.0)
{
double minExtrudeTime = minTime - travelTime;
if (minExtrudeTime < 1)
minExtrudeTime = 1;
double factor = extrudeTime / minExtrudeTime;
for(unsigned int n=0; n<paths.size(); n++)
{
GCodePath* path = &paths[n];
if (path->config->lineWidth == 0)
continue;
int speed = path->config->speed * factor;
if (speed < minimalSpeed)
factor = double(minimalSpeed) / double(path->config->speed);
}
//Only slow down with the minimal time if that will be slower then a factor already set. First layer slowdown also sets the speed factor.
if (factor * 100 < getExtrudeSpeedFactor())
setExtrudeSpeedFactor(factor * 100);
else
factor = getExtrudeSpeedFactor() / 100.0;
if (minTime - (extrudeTime / factor) - travelTime > 0.1)
{
//TODO: Use up this extra time (circle around the print?)
this->extraTime = minTime - (extrudeTime / factor) - travelTime;
}
this->totalPrintTime = (extrudeTime / factor) + travelTime;
}else{
this->totalPrintTime = totalTime;
}
}
void GCodePlanner::writeGCode(bool liftHeadIfNeeded, int layerThickness)
{
GCodePathConfig* lastConfig = NULL;
int extruder = gcode.getExtruderNr();
for(unsigned int n=0; n<paths.size(); n++)
{
GCodePath* path = &paths[n];
if (extruder != path->extruder)
{
extruder = path->extruder;
gcode.switchExtruder(extruder);
}else if (path->retract)
{
gcode.addRetraction();
}
if (path->config != &travelConfig && lastConfig != path->config)
{
gcode.addComment("TYPE:%s", path->config->name);
lastConfig = path->config;
}
int speed = path->config->speed;
if (path->config->lineWidth != 0)// Only apply the extrudeSpeedFactor to extrusion moves
speed = speed * extrudeSpeedFactor / 100;
else
speed = speed * travelSpeedFactor / 100;
if (path->points.size() == 1 && path->config != &travelConfig && shorterThen(gcode.getPositionXY() - path->points[0], path->config->lineWidth * 2))
{
//Check for lots of small moves and combine them into one large line
Point p0 = path->points[0];
unsigned int i = n + 1;
while(i < paths.size() && paths[i].points.size() == 1 && shorterThen(p0 - paths[i].points[0], path->config->lineWidth * 2))
{
p0 = paths[i].points[0];
i ++;
}
if (paths[i-1].config == &travelConfig)
i --;
if (i > n + 2)
{
p0 = gcode.getPositionXY();
for(unsigned int x=n; x<i-1; x+=2)
{
int64_t oldLen = vSize(p0 - paths[x].points[0]);
Point newPoint = (paths[x].points[0] + paths[x+1].points[0]) / 2;
int64_t newLen = vSize(gcode.getPositionXY() - newPoint);
if (newLen > 0)
gcode.addMove(newPoint, speed, path->config->lineWidth * oldLen / newLen);
p0 = paths[x+1].points[0];
}
gcode.addMove(paths[i-1].points[0], speed, path->config->lineWidth);
n = i - 1;
continue;
}
}
bool spiralize = path->config->spiralize;
if (spiralize)
{
//Check if we are the last spiralize path in the list, if not, do not spiralize.
for(unsigned int m=n+1; m<paths.size(); m++)
{
if (paths[m].config->spiralize)
spiralize = false;
}
}
if (spiralize)
{
//If we need to spiralize then raise the head slowly by 1 layer as this path progresses.
float totalLength = 0.0;
int z = gcode.getPositionZ();
Point p0 = gcode.getPositionXY();
for(unsigned int i=0; i<path->points.size(); i++)
{
Point p1 = path->points[i];
totalLength += vSizeMM(p0 - p1);
p0 = p1;
}
float length = 0.0;
p0 = gcode.getPositionXY();
for(unsigned int i=0; i<path->points.size(); i++)
{
Point p1 = path->points[i];
length += vSizeMM(p0 - p1);
p0 = p1;
gcode.setZ(z + layerThickness * length / totalLength);
gcode.addMove(path->points[i], speed, path->config->lineWidth);
}
}else{
for(unsigned int i=0; i<path->points.size(); i++)
{
gcode.addMove(path->points[i], speed, path->config->lineWidth);
}
}
}
gcode.updateTotalPrintTime();
if (liftHeadIfNeeded && extraTime > 0.0)
{
gcode.addComment("Small layer, adding delay of %f", extraTime);
gcode.addRetraction();
gcode.setZ(gcode.getPositionZ() + 3000);
gcode.addMove(gcode.getPositionXY(), travelConfig.speed, 0);
gcode.addMove(gcode.getPositionXY() - Point(-20000, 0), travelConfig.speed, 0);
gcode.addDelay(extraTime);
}
}