-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
GCodeProcessor.cpp
2182 lines (1852 loc) · 85.3 KB
/
GCodeProcessor.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
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "libslic3r/libslic3r.h"
#include "libslic3r/Utils.hpp"
#include "libslic3r/Print.hpp"
#include "GCodeProcessor.hpp"
#include <boost/log/trivial.hpp>
#include <boost/nowide/fstream.hpp>
#include <boost/nowide/cstdio.hpp>
#include <float.h>
#include <assert.h>
#if ENABLE_GCODE_VIEWER
#include <chrono>
static const float INCHES_TO_MM = 25.4f;
static const float MMMIN_TO_MMSEC = 1.0f / 60.0f;
static const float DEFAULT_ACCELERATION = 1500.0f; // Prusa Firmware 1_75mm_MK2
namespace Slic3r {
const std::string GCodeProcessor::Extrusion_Role_Tag = "TYPE:";
const std::string GCodeProcessor::Height_Tag = "HEIGHT:";
const std::string GCodeProcessor::Layer_Change_Tag = "LAYER_CHANGE";
const std::string GCodeProcessor::Color_Change_Tag = "COLOR_CHANGE";
const std::string GCodeProcessor::Pause_Print_Tag = "PAUSE_PRINT";
const std::string GCodeProcessor::Custom_Code_Tag = "CUSTOM_GCODE";
const std::string GCodeProcessor::First_Line_M73_Placeholder_Tag = "; _GP_FIRST_LINE_M73_PLACEHOLDER";
const std::string GCodeProcessor::Last_Line_M73_Placeholder_Tag = "; _GP_LAST_LINE_M73_PLACEHOLDER";
const std::string GCodeProcessor::Estimated_Printing_Time_Placeholder_Tag = "; _GP_ESTIMATED_PRINTING_TIME_PLACEHOLDER";
#if ENABLE_GCODE_VIEWER_DATA_CHECKING
const std::string GCodeProcessor::Width_Tag = "WIDTH:";
const std::string GCodeProcessor::Mm3_Per_Mm_Tag = "MM3_PER_MM:";
#endif // ENABLE_GCODE_VIEWER_DATA_CHECKING
static bool is_valid_extrusion_role(int value)
{
return (static_cast<int>(erNone) <= value) && (value <= static_cast<int>(erMixed));
}
static void set_option_value(ConfigOptionFloats& option, size_t id, float value)
{
if (id < option.values.size())
option.values[id] = static_cast<double>(value);
};
static float get_option_value(const ConfigOptionFloats& option, size_t id)
{
return option.values.empty() ? 0.0f :
((id < option.values.size()) ? static_cast<float>(option.values[id]) : static_cast<float>(option.values.back()));
}
static float estimated_acceleration_distance(float initial_rate, float target_rate, float acceleration)
{
return (acceleration == 0.0f) ? 0.0f : (sqr(target_rate) - sqr(initial_rate)) / (2.0f * acceleration);
}
static float intersection_distance(float initial_rate, float final_rate, float acceleration, float distance)
{
return (acceleration == 0.0f) ? 0.0f : (2.0f * acceleration * distance - sqr(initial_rate) + sqr(final_rate)) / (4.0f * acceleration);
}
static float speed_from_distance(float initial_feedrate, float distance, float acceleration)
{
// to avoid invalid negative numbers due to numerical errors
float value = std::max(0.0f, sqr(initial_feedrate) + 2.0f * acceleration * distance);
return ::sqrt(value);
}
// Calculates the maximum allowable speed at this point when you must be able to reach target_velocity using the
// acceleration within the allotted distance.
static float max_allowable_speed(float acceleration, float target_velocity, float distance)
{
// to avoid invalid negative numbers due to numerical errors
float value = std::max(0.0f, sqr(target_velocity) - 2.0f * acceleration * distance);
return std::sqrt(value);
}
static float acceleration_time_from_distance(float initial_feedrate, float distance, float acceleration)
{
return (acceleration != 0.0f) ? (speed_from_distance(initial_feedrate, distance, acceleration) - initial_feedrate) / acceleration : 0.0f;
}
void GCodeProcessor::CachedPosition::reset()
{
std::fill(position.begin(), position.end(), FLT_MAX);
feedrate = FLT_MAX;
}
void GCodeProcessor::CpColor::reset()
{
counter = 0;
current = 0;
}
float GCodeProcessor::Trapezoid::acceleration_time(float entry_feedrate, float acceleration) const
{
return acceleration_time_from_distance(entry_feedrate, accelerate_until, acceleration);
}
float GCodeProcessor::Trapezoid::cruise_time() const
{
return (cruise_feedrate != 0.0f) ? cruise_distance() / cruise_feedrate : 0.0f;
}
float GCodeProcessor::Trapezoid::deceleration_time(float distance, float acceleration) const
{
return acceleration_time_from_distance(cruise_feedrate, (distance - decelerate_after), -acceleration);
}
float GCodeProcessor::Trapezoid::cruise_distance() const
{
return decelerate_after - accelerate_until;
}
void GCodeProcessor::TimeBlock::calculate_trapezoid()
{
trapezoid.cruise_feedrate = feedrate_profile.cruise;
float accelerate_distance = std::max(0.0f, estimated_acceleration_distance(feedrate_profile.entry, feedrate_profile.cruise, acceleration));
float decelerate_distance = std::max(0.0f, estimated_acceleration_distance(feedrate_profile.cruise, feedrate_profile.exit, -acceleration));
float cruise_distance = distance - accelerate_distance - decelerate_distance;
// Not enough space to reach the nominal feedrate.
// This means no cruising, and we'll have to use intersection_distance() to calculate when to abort acceleration
// and start braking in order to reach the exit_feedrate exactly at the end of this block.
if (cruise_distance < 0.0f) {
accelerate_distance = std::clamp(intersection_distance(feedrate_profile.entry, feedrate_profile.exit, acceleration, distance), 0.0f, distance);
cruise_distance = 0.0f;
trapezoid.cruise_feedrate = speed_from_distance(feedrate_profile.entry, accelerate_distance, acceleration);
}
trapezoid.accelerate_until = accelerate_distance;
trapezoid.decelerate_after = accelerate_distance + cruise_distance;
}
float GCodeProcessor::TimeBlock::time() const
{
return trapezoid.acceleration_time(feedrate_profile.entry, acceleration)
+ trapezoid.cruise_time()
+ trapezoid.deceleration_time(distance, acceleration);
}
void GCodeProcessor::TimeMachine::State::reset()
{
feedrate = 0.0f;
safe_feedrate = 0.0f;
axis_feedrate = { 0.0f, 0.0f, 0.0f, 0.0f };
abs_axis_feedrate = { 0.0f, 0.0f, 0.0f, 0.0f };
}
void GCodeProcessor::TimeMachine::CustomGCodeTime::reset()
{
needed = false;
cache = 0.0f;
times = std::vector<std::pair<CustomGCode::Type, float>>();
}
void GCodeProcessor::TimeMachine::reset()
{
enabled = false;
acceleration = 0.0f;
max_acceleration = 0.0f;
extrude_factor_override_percentage = 1.0f;
time = 0.0f;
curr.reset();
prev.reset();
gcode_time.reset();
blocks = std::vector<TimeBlock>();
g1_times_cache = std::vector<float>();
std::fill(moves_time.begin(), moves_time.end(), 0.0f);
std::fill(roles_time.begin(), roles_time.end(), 0.0f);
layers_time = std::vector<float>();
}
void GCodeProcessor::TimeMachine::simulate_st_synchronize(float additional_time)
{
if (!enabled)
return;
time += additional_time;
gcode_time.cache += additional_time;
calculate_time();
}
static void planner_forward_pass_kernel(GCodeProcessor::TimeBlock& prev, GCodeProcessor::TimeBlock& curr)
{
// If the previous block is an acceleration block, but it is not long enough to complete the
// full speed change within the block, we need to adjust the entry speed accordingly. Entry
// speeds have already been reset, maximized, and reverse planned by reverse planner.
// If nominal length is true, max junction speed is guaranteed to be reached. No need to recheck.
if (!prev.flags.nominal_length) {
if (prev.feedrate_profile.entry < curr.feedrate_profile.entry) {
float entry_speed = std::min(curr.feedrate_profile.entry, max_allowable_speed(-prev.acceleration, prev.feedrate_profile.entry, prev.distance));
// Check for junction speed change
if (curr.feedrate_profile.entry != entry_speed) {
curr.feedrate_profile.entry = entry_speed;
curr.flags.recalculate = true;
}
}
}
}
void planner_reverse_pass_kernel(GCodeProcessor::TimeBlock& curr, GCodeProcessor::TimeBlock& next)
{
// If entry speed is already at the maximum entry speed, no need to recheck. Block is cruising.
// If not, block in state of acceleration or deceleration. Reset entry speed to maximum and
// check for maximum allowable speed reductions to ensure maximum possible planned speed.
if (curr.feedrate_profile.entry != curr.max_entry_speed) {
// If nominal length true, max junction speed is guaranteed to be reached. Only compute
// for max allowable speed if block is decelerating and nominal length is false.
if (!curr.flags.nominal_length && curr.max_entry_speed > next.feedrate_profile.entry)
curr.feedrate_profile.entry = std::min(curr.max_entry_speed, max_allowable_speed(-curr.acceleration, next.feedrate_profile.entry, curr.distance));
else
curr.feedrate_profile.entry = curr.max_entry_speed;
curr.flags.recalculate = true;
}
}
static void recalculate_trapezoids(std::vector<GCodeProcessor::TimeBlock>& blocks)
{
GCodeProcessor::TimeBlock* curr = nullptr;
GCodeProcessor::TimeBlock* next = nullptr;
for (size_t i = 0; i < blocks.size(); ++i) {
GCodeProcessor::TimeBlock& b = blocks[i];
curr = next;
next = &b;
if (curr != nullptr) {
// Recalculate if current block entry or exit junction speed has changed.
if (curr->flags.recalculate || next->flags.recalculate) {
// NOTE: Entry and exit factors always > 0 by all previous logic operations.
GCodeProcessor::TimeBlock block = *curr;
block.feedrate_profile.exit = next->feedrate_profile.entry;
block.calculate_trapezoid();
curr->trapezoid = block.trapezoid;
curr->flags.recalculate = false; // Reset current only to ensure next trapezoid is computed
}
}
}
// Last/newest block in buffer. Always recalculated.
if (next != nullptr) {
GCodeProcessor::TimeBlock block = *next;
block.feedrate_profile.exit = next->safe_feedrate;
block.calculate_trapezoid();
next->trapezoid = block.trapezoid;
next->flags.recalculate = false;
}
}
void GCodeProcessor::TimeMachine::calculate_time(size_t keep_last_n_blocks)
{
if (!enabled || blocks.size() < 2)
return;
assert(keep_last_n_blocks <= blocks.size());
// forward_pass
for (size_t i = 0; i + 1 < blocks.size(); ++i) {
planner_forward_pass_kernel(blocks[i], blocks[i + 1]);
}
// reverse_pass
for (int i = static_cast<int>(blocks.size()) - 1; i > 0; --i)
planner_reverse_pass_kernel(blocks[i - 1], blocks[i]);
recalculate_trapezoids(blocks);
size_t n_blocks_process = blocks.size() - keep_last_n_blocks;
for (size_t i = 0; i < n_blocks_process; ++i) {
const TimeBlock& block = blocks[i];
float block_time = block.time();
time += block_time;
gcode_time.cache += block_time;
moves_time[static_cast<size_t>(block.move_type)] += block_time;
roles_time[static_cast<size_t>(block.role)] += block_time;
if (block.layer_id > 0) {
if (block.layer_id >= layers_time.size()) {
size_t curr_size = layers_time.size();
layers_time.resize(block.layer_id);
for (size_t i = curr_size; i < layers_time.size(); ++i) {
layers_time[i] = 0.0f;
}
}
layers_time[block.layer_id - 1] += block_time;
}
g1_times_cache.push_back(time);
}
if (keep_last_n_blocks)
blocks.erase(blocks.begin(), blocks.begin() + n_blocks_process);
else
blocks.clear();
}
void GCodeProcessor::TimeProcessor::reset()
{
extruder_unloaded = true;
export_remaining_time_enabled = false;
machine_envelope_processing_enabled = false;
machine_limits = MachineEnvelopeConfig();
filament_load_times = std::vector<float>();
filament_unload_times = std::vector<float>();
for (size_t i = 0; i < static_cast<size_t>(PrintEstimatedTimeStatistics::ETimeMode::Count); ++i) {
machines[i].reset();
}
machines[static_cast<size_t>(PrintEstimatedTimeStatistics::ETimeMode::Normal)].enabled = true;
}
void GCodeProcessor::TimeProcessor::post_process(const std::string& filename)
{
boost::nowide::ifstream in(filename);
if (!in.good())
throw Slic3r::RuntimeError(std::string("Time estimator post process export failed.\nCannot open file for reading.\n"));
// temporary file to contain modified gcode
std::string out_path = filename + ".postprocess";
FILE* out = boost::nowide::fopen(out_path.c_str(), "wb");
if (out == nullptr)
throw Slic3r::RuntimeError(std::string("Time estimator post process export failed.\nCannot open file for writing.\n"));
auto time_in_minutes = [](float time_in_seconds) {
return int(::roundf(time_in_seconds / 60.0f));
};
auto format_line_M73 = [](const std::string& mask, int percent, int time) {
char line_M73[64];
sprintf(line_M73, mask.c_str(),
std::to_string(percent).c_str(),
std::to_string(time).c_str());
return std::string(line_M73);
};
GCodeReader parser;
std::string gcode_line;
size_t g1_lines_counter = 0;
// keeps track of last exported pair <percent, remaining time>
std::array<std::pair<int, int>, static_cast<size_t>(PrintEstimatedTimeStatistics::ETimeMode::Count)> last_exported;
for (size_t i = 0; i < static_cast<size_t>(PrintEstimatedTimeStatistics::ETimeMode::Count); ++i) {
last_exported[i] = { 0, time_in_minutes(machines[i].time) };
}
// buffer line to export only when greater than 64K to reduce writing calls
std::string export_line;
// replace placeholder lines with the proper final value
auto process_placeholders = [&](const std::string& gcode_line) {
// remove trailing '\n'
std::string line = gcode_line.substr(0, gcode_line.length() - 1);
std::string ret;
if (line == First_Line_M73_Placeholder_Tag || line == Last_Line_M73_Placeholder_Tag) {
for (size_t i = 0; i < static_cast<size_t>(PrintEstimatedTimeStatistics::ETimeMode::Count); ++i) {
const TimeMachine& machine = machines[i];
if (machine.enabled) {
ret += format_line_M73(machine.line_m73_mask.c_str(),
(line == First_Line_M73_Placeholder_Tag) ? 0 : 100,
(line == First_Line_M73_Placeholder_Tag) ? time_in_minutes(machines[i].time) : 0);
}
}
}
else if (line == Estimated_Printing_Time_Placeholder_Tag) {
for (size_t i = 0; i < static_cast<size_t>(PrintEstimatedTimeStatistics::ETimeMode::Count); ++i) {
const TimeMachine& machine = machines[i];
if (machine.enabled) {
char buf[128];
sprintf(buf, "; estimated printing time (%s mode) = %s\n",
(static_cast<PrintEstimatedTimeStatistics::ETimeMode>(i) == PrintEstimatedTimeStatistics::ETimeMode::Normal) ? "normal" : "silent",
get_time_dhms(machine.time).c_str());
ret += buf;
}
}
}
return std::make_pair(!ret.empty(), ret.empty() ? gcode_line : ret);
};
// check for temporary lines
auto is_temporary_decoration = [](const std::string& gcode_line) {
// remove trailing '\n'
std::string line = gcode_line.substr(0, gcode_line.length() - 1);
if (line == "; " + Layer_Change_Tag)
return true;
else
return false;
};
// add lines M73 to exported gcode
auto process_line_G1 = [&]() {
for (size_t i = 0; i < static_cast<size_t>(PrintEstimatedTimeStatistics::ETimeMode::Count); ++i) {
const TimeMachine& machine = machines[i];
if (machine.enabled && g1_lines_counter < machine.g1_times_cache.size()) {
float elapsed_time = machine.g1_times_cache[g1_lines_counter];
std::pair<int, int> to_export = { int(::roundf(100.0f * elapsed_time / machine.time)),
time_in_minutes(machine.time - elapsed_time) };
if (last_exported[i] != to_export) {
export_line += format_line_M73(machine.line_m73_mask.c_str(),
to_export.first, to_export.second);
last_exported[i] = to_export;
}
}
}
};
// helper function to write to disk
auto write_string = [&](const std::string& str) {
fwrite((const void*)export_line.c_str(), 1, export_line.length(), out);
if (ferror(out)) {
in.close();
fclose(out);
boost::nowide::remove(out_path.c_str());
throw Slic3r::RuntimeError(std::string("Time estimator post process export failed.\nIs the disk full?\n"));
}
export_line.clear();
};
while (std::getline(in, gcode_line)) {
if (!in.good()) {
fclose(out);
throw Slic3r::RuntimeError(std::string("Time estimator post process export failed.\nError while reading from file.\n"));
}
gcode_line += "\n";
// replace placeholder lines
auto [processed, result] = process_placeholders(gcode_line);
gcode_line = result;
if (!processed) {
// remove temporary lines
if (is_temporary_decoration(gcode_line))
continue;
// add lines M73 where needed
parser.parse_line(gcode_line,
[&](GCodeReader& reader, const GCodeReader::GCodeLine& line) {
if (line.cmd_is("G1")) {
process_line_G1();
++g1_lines_counter;
}
});
}
export_line += gcode_line;
if (export_line.length() > 65535)
write_string(export_line);
}
if (!export_line.empty())
write_string(export_line);
fclose(out);
in.close();
if (rename_file(out_path, filename))
throw Slic3r::RuntimeError(std::string("Failed to rename the output G-code file from ") + out_path + " to " + filename + '\n' +
"Is " + out_path + " locked?" + '\n');
}
const std::vector<std::pair<GCodeProcessor::EProducer, std::string>> GCodeProcessor::Producers = {
{ EProducer::PrusaSlicer, "PrusaSlicer" },
{ EProducer::Cura, "Cura_SteamEngine" },
{ EProducer::Simplify3D, "Simplify3D" },
{ EProducer::CraftWare, "CraftWare" },
{ EProducer::ideaMaker, "ideaMaker" }
};
unsigned int GCodeProcessor::s_result_id = 0;
GCodeProcessor::GCodeProcessor()
{
reset();
m_time_processor.machines[static_cast<size_t>(PrintEstimatedTimeStatistics::ETimeMode::Normal)].line_m73_mask = "M73 P%s R%s\n";
m_time_processor.machines[static_cast<size_t>(PrintEstimatedTimeStatistics::ETimeMode::Stealth)].line_m73_mask = "M73 Q%s S%s\n";
}
void GCodeProcessor::apply_config(const PrintConfig& config)
{
m_parser.apply_config(config);
m_flavor = config.gcode_flavor;
size_t extruders_count = config.nozzle_diameter.values.size();
m_extruder_offsets.resize(extruders_count);
for (size_t i = 0; i < extruders_count; ++i) {
Vec2f offset = config.extruder_offset.get_at(i).cast<float>();
m_extruder_offsets[i] = { offset(0), offset(1), 0.0f };
}
m_extruder_colors.resize(extruders_count);
for (size_t i = 0; i < extruders_count; ++i) {
m_extruder_colors[i] = static_cast<unsigned char>(i);
}
m_filament_diameters.resize(config.filament_diameter.values.size());
for (size_t i = 0; i < config.filament_diameter.values.size(); ++i) {
m_filament_diameters[i] = static_cast<float>(config.filament_diameter.values[i]);
}
if (config.machine_limits_usage.value != MachineLimitsUsage::Ignore)
m_time_processor.machine_limits = reinterpret_cast<const MachineEnvelopeConfig&>(config);
// Filament load / unload times are not specific to a firmware flavor. Let anybody use it if they find it useful.
// As of now the fields are shown at the UI dialog in the same combo box as the ramming values, so they
// are considered to be active for the single extruder multi-material printers only.
m_time_processor.filament_load_times.resize(config.filament_load_time.values.size());
for (size_t i = 0; i < config.filament_load_time.values.size(); ++i) {
m_time_processor.filament_load_times[i] = static_cast<float>(config.filament_load_time.values[i]);
}
m_time_processor.filament_unload_times.resize(config.filament_unload_time.values.size());
for (size_t i = 0; i < config.filament_unload_time.values.size(); ++i) {
m_time_processor.filament_unload_times[i] = static_cast<float>(config.filament_unload_time.values[i]);
}
for (size_t i = 0; i < static_cast<size_t>(PrintEstimatedTimeStatistics::ETimeMode::Count); ++i) {
float max_acceleration = get_option_value(m_time_processor.machine_limits.machine_max_acceleration_extruding, i);
m_time_processor.machines[i].max_acceleration = max_acceleration;
m_time_processor.machines[i].acceleration = (max_acceleration > 0.0f) ? max_acceleration : DEFAULT_ACCELERATION;
}
m_time_processor.export_remaining_time_enabled = config.remaining_times.value;
}
void GCodeProcessor::apply_config(const DynamicPrintConfig& config)
{
m_parser.apply_config(config);
const ConfigOptionEnum<GCodeFlavor>* gcode_flavor = config.option<ConfigOptionEnum<GCodeFlavor>>("gcode_flavor");
if (gcode_flavor != nullptr)
m_flavor = gcode_flavor->value;
const ConfigOptionPoints* bed_shape = config.option<ConfigOptionPoints>("bed_shape");
if (bed_shape != nullptr)
m_result.bed_shape = bed_shape->values;
const ConfigOptionString* printer_settings_id = config.option<ConfigOptionString>("printer_settings_id");
if (printer_settings_id != nullptr)
m_result.printer_settings_id = printer_settings_id->value;
const ConfigOptionFloats* filament_diameters = config.option<ConfigOptionFloats>("filament_diameter");
if (filament_diameters != nullptr) {
for (double diam : filament_diameters->values) {
m_filament_diameters.push_back(static_cast<float>(diam));
}
}
const ConfigOptionPoints* extruder_offset = config.option<ConfigOptionPoints>("extruder_offset");
if (extruder_offset != nullptr) {
m_extruder_offsets.resize(extruder_offset->values.size());
for (size_t i = 0; i < extruder_offset->values.size(); ++i) {
Vec2f offset = extruder_offset->values[i].cast<float>();
m_extruder_offsets[i] = { offset(0), offset(1), 0.0f };
}
}
// ensure at least one (default) color is defined
std::string default_color = "#FF8000";
m_result.extruder_colors = std::vector<std::string>(1, default_color);
const ConfigOptionStrings* extruder_colour = config.option<ConfigOptionStrings>("extruder_colour");
if (extruder_colour != nullptr) {
// takes colors from config
m_result.extruder_colors = extruder_colour->values;
// try to replace missing values with filament colors
const ConfigOptionStrings* filament_colour = config.option<ConfigOptionStrings>("filament_colour");
if (filament_colour != nullptr && filament_colour->values.size() == m_result.extruder_colors.size()) {
for (size_t i = 0; i < m_result.extruder_colors.size(); ++i) {
if (m_result.extruder_colors[i].empty())
m_result.extruder_colors[i] = filament_colour->values[i];
}
}
}
// replace missing values with default
for (size_t i = 0; i < m_result.extruder_colors.size(); ++i) {
if (m_result.extruder_colors[i].empty())
m_result.extruder_colors[i] = default_color;
}
m_extruder_colors.resize(m_result.extruder_colors.size());
for (size_t i = 0; i < m_result.extruder_colors.size(); ++i) {
m_extruder_colors[i] = static_cast<unsigned char>(i);
}
const ConfigOptionFloats* filament_load_time = config.option<ConfigOptionFloats>("filament_load_time");
if (filament_load_time != nullptr) {
m_time_processor.filament_load_times.resize(filament_load_time->values.size());
for (size_t i = 0; i < filament_load_time->values.size(); ++i) {
m_time_processor.filament_load_times[i] = static_cast<float>(filament_load_time->values[i]);
}
}
const ConfigOptionFloats* filament_unload_time = config.option<ConfigOptionFloats>("filament_unload_time");
if (filament_unload_time != nullptr) {
m_time_processor.filament_unload_times.resize(filament_unload_time->values.size());
for (size_t i = 0; i < filament_unload_time->values.size(); ++i) {
m_time_processor.filament_unload_times[i] = static_cast<float>(filament_unload_time->values[i]);
}
}
const ConfigOptionFloats* machine_max_acceleration_x = config.option<ConfigOptionFloats>("machine_max_acceleration_x");
if (machine_max_acceleration_x != nullptr)
m_time_processor.machine_limits.machine_max_acceleration_x.values = machine_max_acceleration_x->values;
const ConfigOptionFloats* machine_max_acceleration_y = config.option<ConfigOptionFloats>("machine_max_acceleration_y");
if (machine_max_acceleration_y != nullptr)
m_time_processor.machine_limits.machine_max_acceleration_y.values = machine_max_acceleration_y->values;
const ConfigOptionFloats* machine_max_acceleration_z = config.option<ConfigOptionFloats>("machine_max_acceleration_z");
if (machine_max_acceleration_z != nullptr)
m_time_processor.machine_limits.machine_max_acceleration_z.values = machine_max_acceleration_z->values;
const ConfigOptionFloats* machine_max_acceleration_e = config.option<ConfigOptionFloats>("machine_max_acceleration_e");
if (machine_max_acceleration_e != nullptr)
m_time_processor.machine_limits.machine_max_acceleration_e.values = machine_max_acceleration_e->values;
const ConfigOptionFloats* machine_max_feedrate_x = config.option<ConfigOptionFloats>("machine_max_feedrate_x");
if (machine_max_feedrate_x != nullptr)
m_time_processor.machine_limits.machine_max_feedrate_x.values = machine_max_feedrate_x->values;
const ConfigOptionFloats* machine_max_feedrate_y = config.option<ConfigOptionFloats>("machine_max_feedrate_y");
if (machine_max_feedrate_y != nullptr)
m_time_processor.machine_limits.machine_max_feedrate_y.values = machine_max_feedrate_y->values;
const ConfigOptionFloats* machine_max_feedrate_z = config.option<ConfigOptionFloats>("machine_max_feedrate_z");
if (machine_max_feedrate_z != nullptr)
m_time_processor.machine_limits.machine_max_feedrate_z.values = machine_max_feedrate_z->values;
const ConfigOptionFloats* machine_max_feedrate_e = config.option<ConfigOptionFloats>("machine_max_feedrate_e");
if (machine_max_feedrate_e != nullptr)
m_time_processor.machine_limits.machine_max_feedrate_e.values = machine_max_feedrate_e->values;
const ConfigOptionFloats* machine_max_jerk_x = config.option<ConfigOptionFloats>("machine_max_jerk_x");
if (machine_max_jerk_x != nullptr)
m_time_processor.machine_limits.machine_max_jerk_x.values = machine_max_jerk_x->values;
const ConfigOptionFloats* machine_max_jerk_y = config.option<ConfigOptionFloats>("machine_max_jerk_y");
if (machine_max_jerk_y != nullptr)
m_time_processor.machine_limits.machine_max_jerk_y.values = machine_max_jerk_y->values;
const ConfigOptionFloats* machine_max_jerk_z = config.option<ConfigOptionFloats>("machine_max_jerkz");
if (machine_max_jerk_z != nullptr)
m_time_processor.machine_limits.machine_max_jerk_z.values = machine_max_jerk_z->values;
const ConfigOptionFloats* machine_max_jerk_e = config.option<ConfigOptionFloats>("machine_max_jerk_e");
if (machine_max_jerk_e != nullptr)
m_time_processor.machine_limits.machine_max_jerk_e.values = machine_max_jerk_e->values;
const ConfigOptionFloats* machine_max_acceleration_extruding = config.option<ConfigOptionFloats>("machine_max_acceleration_extruding");
if (machine_max_acceleration_extruding != nullptr)
m_time_processor.machine_limits.machine_max_acceleration_extruding.values = machine_max_acceleration_extruding->values;
const ConfigOptionFloats* machine_max_acceleration_retracting = config.option<ConfigOptionFloats>("machine_max_acceleration_retracting");
if (machine_max_acceleration_retracting != nullptr)
m_time_processor.machine_limits.machine_max_acceleration_retracting.values = machine_max_acceleration_retracting->values;
const ConfigOptionFloats* machine_min_extruding_rate = config.option<ConfigOptionFloats>("machine_min_extruding_rate");
if (machine_min_extruding_rate != nullptr)
m_time_processor.machine_limits.machine_min_extruding_rate.values = machine_min_extruding_rate->values;
const ConfigOptionFloats* machine_min_travel_rate = config.option<ConfigOptionFloats>("machine_min_travel_rate");
if (machine_min_travel_rate != nullptr)
m_time_processor.machine_limits.machine_min_travel_rate.values = machine_min_travel_rate->values;
for (size_t i = 0; i < static_cast<size_t>(PrintEstimatedTimeStatistics::ETimeMode::Count); ++i) {
float max_acceleration = get_option_value(m_time_processor.machine_limits.machine_max_acceleration_extruding, i);
m_time_processor.machines[i].max_acceleration = max_acceleration;
m_time_processor.machines[i].acceleration = (max_acceleration > 0.0f) ? max_acceleration : DEFAULT_ACCELERATION;
}
}
void GCodeProcessor::enable_stealth_time_estimator(bool enabled)
{
m_time_processor.machines[static_cast<size_t>(PrintEstimatedTimeStatistics::ETimeMode::Stealth)].enabled = enabled;
}
void GCodeProcessor::reset()
{
static const size_t Min_Extruder_Count = 5;
m_units = EUnits::Millimeters;
m_global_positioning_type = EPositioningType::Absolute;
m_e_local_positioning_type = EPositioningType::Absolute;
m_extruder_offsets = std::vector<Vec3f>(Min_Extruder_Count, Vec3f::Zero());
m_flavor = gcfRepRap;
m_start_position = { 0.0f, 0.0f, 0.0f, 0.0f };
m_end_position = { 0.0f, 0.0f, 0.0f, 0.0f };
m_origin = { 0.0f, 0.0f, 0.0f, 0.0f };
m_cached_position.reset();
m_feedrate = 0.0f;
m_width = 0.0f;
m_height = 0.0f;
m_mm3_per_mm = 0.0f;
m_fan_speed = 0.0f;
m_extrusion_role = erNone;
m_extruder_id = 0;
m_extruder_colors.resize(Min_Extruder_Count);
for (size_t i = 0; i < Min_Extruder_Count; ++i) {
m_extruder_colors[i] = static_cast<unsigned char>(i);
}
m_filament_diameters = std::vector<float>(Min_Extruder_Count, 1.75f);
m_extruded_last_z = 0.0f;
m_layer_id = 0;
m_cp_color.reset();
m_producer = EProducer::Unknown;
m_producers_enabled = false;
m_time_processor.reset();
m_result.reset();
m_result.id = ++s_result_id;
#if ENABLE_GCODE_VIEWER_DATA_CHECKING
m_mm3_per_mm_compare.reset();
m_height_compare.reset();
m_width_compare.reset();
#endif // ENABLE_GCODE_VIEWER_DATA_CHECKING
}
void GCodeProcessor::process_file(const std::string& filename, std::function<void()> cancel_callback)
{
auto last_cancel_callback_time = std::chrono::high_resolution_clock::now();
#if ENABLE_GCODE_VIEWER_STATISTICS
auto start_time = std::chrono::high_resolution_clock::now();
#endif // ENABLE_GCODE_VIEWER_STATISTICS
// pre-processing
// parse the gcode file to detect its producer
if (m_producers_enabled) {
m_parser.parse_file(filename, [this](GCodeReader& reader, const GCodeReader::GCodeLine& line) {
std::string cmd = line.cmd();
if (cmd.length() == 0) {
std::string comment = line.comment();
if (comment.length() > 1 && detect_producer(comment))
m_parser.quit_parsing_file();
}
});
// if the gcode was produced by PrusaSlicer,
// extract the config from it
if (m_producer == EProducer::PrusaSlicer) {
DynamicPrintConfig config;
config.apply(FullPrintConfig::defaults());
config.load_from_gcode_file(filename);
apply_config(config);
}
}
// process gcode
m_result.id = ++s_result_id;
// 1st move must be a dummy move
m_result.moves.emplace_back(MoveVertex());
m_parser.parse_file(filename, [this, cancel_callback, &last_cancel_callback_time](GCodeReader& reader, const GCodeReader::GCodeLine& line) {
if (cancel_callback != nullptr) {
// call the cancel callback every 100 ms
auto curr_time = std::chrono::high_resolution_clock::now();
if (std::chrono::duration_cast<std::chrono::milliseconds>(curr_time - last_cancel_callback_time).count() > 100) {
cancel_callback();
last_cancel_callback_time = curr_time;
}
}
process_gcode_line(line);
});
// process the time blocks
for (size_t i = 0; i < static_cast<size_t>(PrintEstimatedTimeStatistics::ETimeMode::Count); ++i) {
TimeMachine& machine = m_time_processor.machines[i];
TimeMachine::CustomGCodeTime& gcode_time = machine.gcode_time;
machine.calculate_time();
if (gcode_time.needed && gcode_time.cache != 0.0f)
gcode_time.times.push_back({ CustomGCode::ColorChange, gcode_time.cache });
}
update_estimated_times_stats();
// post-process to add M73 lines into the gcode
if (m_time_processor.export_remaining_time_enabled)
m_time_processor.post_process(filename);
#if ENABLE_GCODE_VIEWER_DATA_CHECKING
std::cout << "\n";
m_mm3_per_mm_compare.output();
m_height_compare.output();
m_width_compare.output();
#endif // ENABLE_GCODE_VIEWER_DATA_CHECKING
#if ENABLE_GCODE_VIEWER_STATISTICS
m_result.time = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - start_time).count();
#endif // ENABLE_GCODE_VIEWER_STATISTICS
}
float GCodeProcessor::get_time(PrintEstimatedTimeStatistics::ETimeMode mode) const
{
return (mode < PrintEstimatedTimeStatistics::ETimeMode::Count) ? m_time_processor.machines[static_cast<size_t>(mode)].time : 0.0f;
}
std::string GCodeProcessor::get_time_dhm(PrintEstimatedTimeStatistics::ETimeMode mode) const
{
return (mode < PrintEstimatedTimeStatistics::ETimeMode::Count) ? short_time(get_time_dhms(m_time_processor.machines[static_cast<size_t>(mode)].time)) : std::string("N/A");
}
std::vector<std::pair<CustomGCode::Type, std::pair<float, float>>> GCodeProcessor::get_custom_gcode_times(PrintEstimatedTimeStatistics::ETimeMode mode, bool include_remaining) const
{
std::vector<std::pair<CustomGCode::Type, std::pair<float, float>>> ret;
if (mode < PrintEstimatedTimeStatistics::ETimeMode::Count) {
const TimeMachine& machine = m_time_processor.machines[static_cast<size_t>(mode)];
float total_time = 0.0f;
for (const auto& [type, time] : machine.gcode_time.times) {
float remaining = include_remaining ? machine.time - total_time : 0.0f;
ret.push_back({ type, { time, remaining } });
total_time += time;
}
}
return ret;
}
std::vector<std::pair<EMoveType, float>> GCodeProcessor::get_moves_time(PrintEstimatedTimeStatistics::ETimeMode mode) const
{
std::vector<std::pair<EMoveType, float>> ret;
if (mode < PrintEstimatedTimeStatistics::ETimeMode::Count) {
for (size_t i = 0; i < m_time_processor.machines[static_cast<size_t>(mode)].moves_time.size(); ++i) {
float time = m_time_processor.machines[static_cast<size_t>(mode)].moves_time[i];
if (time > 0.0f)
ret.push_back({ static_cast<EMoveType>(i), time });
}
}
return ret;
}
std::vector<std::pair<ExtrusionRole, float>> GCodeProcessor::get_roles_time(PrintEstimatedTimeStatistics::ETimeMode mode) const
{
std::vector<std::pair<ExtrusionRole, float>> ret;
if (mode < PrintEstimatedTimeStatistics::ETimeMode::Count) {
for (size_t i = 0; i < m_time_processor.machines[static_cast<size_t>(mode)].roles_time.size(); ++i) {
float time = m_time_processor.machines[static_cast<size_t>(mode)].roles_time[i];
if (time > 0.0f)
ret.push_back({ static_cast<ExtrusionRole>(i), time });
}
}
return ret;
}
std::vector<float> GCodeProcessor::get_layers_time(PrintEstimatedTimeStatistics::ETimeMode mode) const
{
return (mode < PrintEstimatedTimeStatistics::ETimeMode::Count) ?
m_time_processor.machines[static_cast<size_t>(mode)].layers_time :
std::vector<float>();
}
void GCodeProcessor::process_gcode_line(const GCodeReader::GCodeLine& line)
{
/* std::cout << line.raw() << std::endl; */
// update start position
m_start_position = m_end_position;
std::string cmd = line.cmd();
if (cmd.length() > 1) {
// process command lines
switch (::toupper(cmd[0]))
{
case 'G':
{
switch (::atoi(&cmd[1]))
{
case 0: { process_G0(line); break; } // Move
case 1: { process_G1(line); break; } // Move
case 10: { process_G10(line); break; } // Retract
case 11: { process_G11(line); break; } // Unretract
case 20: { process_G20(line); break; } // Set Units to Inches
case 21: { process_G21(line); break; } // Set Units to Millimeters
case 22: { process_G22(line); break; } // Firmware controlled retract
case 23: { process_G23(line); break; } // Firmware controlled unretract
case 90: { process_G90(line); break; } // Set to Absolute Positioning
case 91: { process_G91(line); break; } // Set to Relative Positioning
case 92: { process_G92(line); break; } // Set Position
default: { break; }
}
break;
}
case 'M':
{
switch (::atoi(&cmd[1]))
{
case 1: { process_M1(line); break; } // Sleep or Conditional stop
case 82: { process_M82(line); break; } // Set extruder to absolute mode
case 83: { process_M83(line); break; } // Set extruder to relative mode
case 106: { process_M106(line); break; } // Set fan speed
case 107: { process_M107(line); break; } // Disable fan
case 108: { process_M108(line); break; } // Set tool (Sailfish)
case 132: { process_M132(line); break; } // Recall stored home offsets
case 135: { process_M135(line); break; } // Set tool (MakerWare)
case 201: { process_M201(line); break; } // Set max printing acceleration
case 203: { process_M203(line); break; } // Set maximum feedrate
case 204: { process_M204(line); break; } // Set default acceleration
case 205: { process_M205(line); break; } // Advanced settings
case 221: { process_M221(line); break; } // Set extrude factor override percentage
case 401: { process_M401(line); break; } // Repetier: Store x, y and z position
case 402: { process_M402(line); break; } // Repetier: Go to stored position
case 566: { process_M566(line); break; } // Set allowable instantaneous speed change
case 702: { process_M702(line); break; } // Unload the current filament into the MK3 MMU2 unit at the end of print.
default: { break; }
}
break;
}
case 'T':
{
process_T(line); // Select Tool
break;
}
default: { break; }
}
}
else {
std::string comment = line.comment();
if (comment.length() > 1)
// process tags embedded into comments
process_tags(comment);
}
}
void GCodeProcessor::process_tags(const std::string& comment)
{
// producers tags
if (m_producers_enabled) {
if (m_producer != EProducer::Unknown) {
if (process_producers_tags(comment))
return;
}
}
// extrusion role tag
size_t pos = comment.find(Extrusion_Role_Tag);
if (pos != comment.npos) {
m_extrusion_role = ExtrusionEntity::string_to_role(comment.substr(pos + Extrusion_Role_Tag.length()));
return;
}
if (!m_producers_enabled || m_producer == EProducer::PrusaSlicer) {
// height tag
pos = comment.find(Height_Tag);
if (pos != comment.npos) {
try {
m_height = std::stof(comment.substr(pos + Height_Tag.length()));
}
catch (...) {
BOOST_LOG_TRIVIAL(error) << "GCodeProcessor encountered an invalid value for Height (" << comment << ").";
}
return;
}
}
#if ENABLE_GCODE_VIEWER_DATA_CHECKING
// width tag
pos = comment.find(Width_Tag);
if (pos != comment.npos) {
try {
m_width_compare.last_tag_value = std::stof(comment.substr(pos + Width_Tag.length()));
}
catch (...) {
BOOST_LOG_TRIVIAL(error) << "GCodeProcessor encountered an invalid value for Width (" << comment << ").";
}
return;
}
#endif // ENABLE_GCODE_VIEWER_DATA_CHECKING
// color change tag
pos = comment.find(Color_Change_Tag);
if (pos != comment.npos) {
pos = comment.find_last_of(",T");
try {
unsigned char extruder_id = (pos == comment.npos) ? 0 : static_cast<unsigned char>(std::stoi(comment.substr(pos + 1)));
m_extruder_colors[extruder_id] = static_cast<unsigned char>(m_extruder_offsets.size()) + m_cp_color.counter; // color_change position in list of color for preview
++m_cp_color.counter;
if (m_cp_color.counter == UCHAR_MAX)
m_cp_color.counter = 0;
if (m_extruder_id == extruder_id) {
m_cp_color.current = m_extruder_colors[extruder_id];
store_move_vertex(EMoveType::Color_change);
}
process_custom_gcode_time(CustomGCode::ColorChange);
}
catch (...) {
BOOST_LOG_TRIVIAL(error) << "GCodeProcessor encountered an invalid value for Color_Change (" << comment << ").";