-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
GCodeViewer.cpp
3914 lines (3388 loc) · 178 KB
/
GCodeViewer.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 "GCodeViewer.hpp"
#include "libslic3r/BuildVolume.hpp"
#include "libslic3r/Print.hpp"
#include "libslic3r/Geometry.hpp"
#include "libslic3r/Model.hpp"
#include "libslic3r/Utils.hpp"
#include "libslic3r/LocalesUtils.hpp"
#include "libslic3r/PresetBundle.hpp"
#include "GUI_App.hpp"
#include "MainFrame.hpp"
#include "Plater.hpp"
#include "Camera.hpp"
#include "I18N.hpp"
#include "GUI_Utils.hpp"
#include "GUI.hpp"
#include "DoubleSlider.hpp"
#include "GLCanvas3D.hpp"
#include "GLToolbar.hpp"
#include "GUI_Preview.hpp"
#include "GUI_ObjectManipulation.hpp"
#include <imgui/imgui_internal.h>
#include <GL/glew.h>
#include <boost/log/trivial.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/nowide/cstdio.hpp>
#include <boost/nowide/fstream.hpp>
#include <wx/progdlg.h>
#include <wx/numformatter.h>
#include <array>
#include <algorithm>
#include <chrono>
namespace Slic3r {
namespace GUI {
static unsigned char buffer_id(EMoveType type) {
return static_cast<unsigned char>(type) - static_cast<unsigned char>(EMoveType::Retract);
}
static EMoveType buffer_type(unsigned char id) {
return static_cast<EMoveType>(static_cast<unsigned char>(EMoveType::Retract) + id);
}
static std::array<float, 4> decode_color(const std::string& color) {
static const float INV_255 = 1.0f / 255.0f;
std::array<float, 4> ret = { 0.0f, 0.0f, 0.0f, 1.0f };
const char* c = color.data() + 1;
if (color.size() == 7 && color.front() == '#') {
for (size_t j = 0; j < 3; ++j) {
int digit1 = hex_digit_to_int(*c++);
int digit2 = hex_digit_to_int(*c++);
if (digit1 == -1 || digit2 == -1)
break;
ret[j] = float(digit1 * 16 + digit2) * INV_255;
}
}
return ret;
}
static std::vector<std::array<float, 4>> decode_colors(const std::vector<std::string>& colors) {
std::vector<std::array<float, 4>> output(colors.size(), { 0.0f, 0.0f, 0.0f, 1.0f });
for (size_t i = 0; i < colors.size(); ++i) {
output[i] = decode_color(colors[i]);
}
return output;
}
static float round_to_nearest_percent(float value)
{
return std::round(value * 100.f) * 0.01f;
}
void GCodeViewer::VBuffer::reset()
{
// release gpu memory
if (!vbos.empty()) {
glsafe(::glDeleteBuffers(static_cast<GLsizei>(vbos.size()), static_cast<const GLuint*>(vbos.data())));
vbos.clear();
}
sizes.clear();
count = 0;
}
void GCodeViewer::InstanceVBuffer::Ranges::reset()
{
for (Range& range : ranges) {
// release gpu memory
if (range.vbo > 0)
glsafe(::glDeleteBuffers(1, &range.vbo));
}
ranges.clear();
}
void GCodeViewer::InstanceVBuffer::reset()
{
s_ids.clear();
buffer.clear();
render_ranges.reset();
}
void GCodeViewer::IBuffer::reset()
{
// release gpu memory
if (ibo > 0) {
glsafe(::glDeleteBuffers(1, &ibo));
ibo = 0;
}
vbo = 0;
count = 0;
}
bool GCodeViewer::Path::matches(const GCodeProcessorResult::MoveVertex& move) const
{
auto matches_percent = [](float value1, float value2, float max_percent) {
return std::abs(value2 - value1) / value1 <= max_percent;
};
switch (move.type)
{
case EMoveType::Tool_change:
case EMoveType::Color_change:
case EMoveType::Pause_Print:
case EMoveType::Custom_GCode:
case EMoveType::Retract:
case EMoveType::Unretract:
case EMoveType::Seam:
case EMoveType::Extrude: {
// use rounding to reduce the number of generated paths
return type == move.type && extruder_id == move.extruder_id && cp_color_id == move.cp_color_id && role == move.extrusion_role &&
move.position.z() <= sub_paths.front().first.position.z() && feedrate == move.feedrate && fan_speed == move.fan_speed &&
height == round_to_nearest_percent(move.height) && width == round_to_nearest_percent(move.width) &&
matches_percent(volumetric_rate, move.volumetric_rate(), 0.05f);
}
case EMoveType::Travel: {
return type == move.type && feedrate == move.feedrate && extruder_id == move.extruder_id && cp_color_id == move.cp_color_id;
}
default: { return false; }
}
}
void GCodeViewer::TBuffer::Model::reset()
{
instances.reset();
}
void GCodeViewer::TBuffer::reset()
{
vertices.reset();
for (IBuffer& buffer : indices) {
buffer.reset();
}
indices.clear();
paths.clear();
render_paths.clear();
model.reset();
}
void GCodeViewer::TBuffer::add_path(const GCodeProcessorResult::MoveVertex& move, unsigned int b_id, size_t i_id, size_t s_id)
{
Path::Endpoint endpoint = { b_id, i_id, s_id, move.position };
// use rounding to reduce the number of generated paths
paths.push_back({ move.type, move.extrusion_role, move.delta_extruder,
round_to_nearest_percent(move.height), round_to_nearest_percent(move.width),
move.feedrate, move.fan_speed, move.temperature,
move.volumetric_rate(), move.extruder_id, move.cp_color_id, { { endpoint, endpoint } } });
}
GCodeViewer::Color GCodeViewer::Extrusions::Range::get_color_at(float value) const
{
// Input value scaled to the colors range
const float step = step_size();
const float global_t = (step != 0.0f) ? std::max(0.0f, value - min) / step : 0.0f; // lower limit of 0.0f
const size_t color_max_idx = Range_Colors.size() - 1;
// Compute the two colors just below (low) and above (high) the input value
const size_t color_low_idx = std::clamp<size_t>(static_cast<size_t>(global_t), 0, color_max_idx);
const size_t color_high_idx = std::clamp<size_t>(color_low_idx + 1, 0, color_max_idx);
// Compute how far the value is between the low and high colors so that they can be interpolated
const float local_t = std::clamp(global_t - static_cast<float>(color_low_idx), 0.0f, 1.0f);
// Interpolate between the low and high colors to find exactly which color the input value should get
Color ret = { 0.0f, 0.0f, 0.0f, 1.0f };
for (unsigned int i = 0; i < 3; ++i) {
ret[i] = lerp(Range_Colors[color_low_idx][i], Range_Colors[color_high_idx][i], local_t);
}
return ret;
}
GCodeViewer::SequentialRangeCap::~SequentialRangeCap() {
if (ibo > 0)
glsafe(::glDeleteBuffers(1, &ibo));
}
void GCodeViewer::SequentialRangeCap::reset() {
if (ibo > 0)
glsafe(::glDeleteBuffers(1, &ibo));
buffer = nullptr;
ibo = 0;
vbo = 0;
color = { 0.0f, 0.0f, 0.0f, 1.0f };
}
void GCodeViewer::SequentialView::Marker::init()
{
m_model.init_from(stilized_arrow(16, 2.0f, 4.0f, 1.0f, 8.0f));
m_model.set_color(-1, { 1.0f, 1.0f, 1.0f, 0.5f });
}
void GCodeViewer::SequentialView::Marker::set_world_position(const Vec3f& position)
{
m_world_position = position;
m_world_transform = (Geometry::assemble_transform((position + m_z_offset * Vec3f::UnitZ()).cast<double>()) * Geometry::assemble_transform(m_model.get_bounding_box().size().z() * Vec3d::UnitZ(), { M_PI, 0.0, 0.0 })).cast<float>();
}
void GCodeViewer::SequentialView::Marker::render() const
{
if (!m_visible)
return;
GLShaderProgram* shader = wxGetApp().get_shader("gouraud_light");
if (shader == nullptr)
return;
glsafe(::glEnable(GL_BLEND));
glsafe(::glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA));
shader->start_using();
shader->set_uniform("emission_factor", 0.0f);
glsafe(::glPushMatrix());
glsafe(::glMultMatrixf(m_world_transform.data()));
m_model.render();
glsafe(::glPopMatrix());
shader->stop_using();
glsafe(::glDisable(GL_BLEND));
static float last_window_width = 0.0f;
static size_t last_text_length = 0;
ImGuiWrapper& imgui = *wxGetApp().imgui();
Size cnv_size = wxGetApp().plater()->get_current_canvas3D()->get_canvas_size();
imgui.set_next_window_pos(0.5f * static_cast<float>(cnv_size.get_width()), static_cast<float>(cnv_size.get_height()), ImGuiCond_Always, 0.5f, 1.0f);
ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
ImGui::SetNextWindowBgAlpha(0.25f);
imgui.begin(std::string("ToolPosition"), ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoMove);
imgui.text_colored(ImGuiWrapper::COL_ORANGE_LIGHT, _u8L("Tool position") + ":");
ImGui::SameLine();
char buf[1024];
const Vec3f position = m_world_position + m_world_offset;
sprintf(buf, "X: %.3f, Y: %.3f, Z: %.3f", position.x(), position.y(), position.z());
imgui.text(std::string(buf));
// force extra frame to automatically update window size
float width = ImGui::GetWindowWidth();
size_t length = strlen(buf);
if (width != last_window_width || length != last_text_length) {
last_window_width = width;
last_text_length = length;
#if ENABLE_ENHANCED_IMGUI_SLIDER_FLOAT
imgui.set_requires_extra_frame();
#else
wxGetApp().plater()->get_current_canvas3D()->set_as_dirty();
wxGetApp().plater()->get_current_canvas3D()->request_extra_frame();
#endif // ENABLE_ENHANCED_IMGUI_SLIDER_FLOAT
}
imgui.end();
ImGui::PopStyleVar();
}
void GCodeViewer::SequentialView::GCodeWindow::load_gcode(const std::string& filename, std::vector<size_t> &&lines_ends)
{
assert(! m_file.is_open());
if (m_file.is_open())
return;
m_filename = filename;
m_lines_ends = std::move(lines_ends);
m_selected_line_id = 0;
m_last_lines_size = 0;
try
{
m_file.open(boost::filesystem::path(m_filename));
}
catch (...)
{
BOOST_LOG_TRIVIAL(error) << "Unable to map file " << m_filename << ". Cannot show G-code window.";
reset();
}
}
void GCodeViewer::SequentialView::GCodeWindow::render(float top, float bottom, uint64_t curr_line_id) const
{
auto update_lines = [this](uint64_t start_id, uint64_t end_id) {
std::vector<Line> ret;
ret.reserve(end_id - start_id + 1);
for (uint64_t id = start_id; id <= end_id; ++id) {
// read line from file
const size_t start = id == 1 ? 0 : m_lines_ends[id - 2];
const size_t len = m_lines_ends[id - 1] - start;
std::string gline(m_file.data() + start, len);
std::string command;
std::string parameters;
std::string comment;
// extract comment
std::vector<std::string> tokens;
boost::split(tokens, gline, boost::is_any_of(";"), boost::token_compress_on);
command = tokens.front();
if (tokens.size() > 1)
comment = ";" + tokens.back();
// extract gcode command and parameters
if (!command.empty()) {
boost::split(tokens, command, boost::is_any_of(" "), boost::token_compress_on);
command = tokens.front();
if (tokens.size() > 1) {
for (size_t i = 1; i < tokens.size(); ++i) {
parameters += " " + tokens[i];
}
}
}
ret.push_back({ command, parameters, comment });
}
return ret;
};
static const ImVec4 LINE_NUMBER_COLOR = ImGuiWrapper::COL_ORANGE_LIGHT;
static const ImVec4 SELECTION_RECT_COLOR = ImGuiWrapper::COL_ORANGE_DARK;
static const ImVec4 COMMAND_COLOR = { 0.8f, 0.8f, 0.0f, 1.0f };
static const ImVec4 PARAMETERS_COLOR = { 1.0f, 1.0f, 1.0f, 1.0f };
static const ImVec4 COMMENT_COLOR = { 0.7f, 0.7f, 0.7f, 1.0f };
if (!m_visible || m_filename.empty() || m_lines_ends.empty() || curr_line_id == 0)
return;
// window height
const float wnd_height = bottom - top;
// number of visible lines
const float text_height = ImGui::CalcTextSize("0").y;
const ImGuiStyle& style = ImGui::GetStyle();
const uint64_t lines_count = static_cast<uint64_t>((wnd_height - 2.0f * style.WindowPadding.y + style.ItemSpacing.y) / (text_height + style.ItemSpacing.y));
if (lines_count == 0)
return;
// visible range
const uint64_t half_lines_count = lines_count / 2;
uint64_t start_id = (curr_line_id >= half_lines_count) ? curr_line_id - half_lines_count : 0;
uint64_t end_id = start_id + lines_count - 1;
if (end_id >= static_cast<uint64_t>(m_lines_ends.size())) {
end_id = static_cast<uint64_t>(m_lines_ends.size()) - 1;
start_id = end_id - lines_count + 1;
}
// updates list of lines to show, if needed
if (m_selected_line_id != curr_line_id || m_last_lines_size != end_id - start_id + 1) {
try
{
*const_cast<std::vector<Line>*>(&m_lines) = update_lines(start_id, end_id);
}
catch (...)
{
BOOST_LOG_TRIVIAL(error) << "Error while loading from file " << m_filename << ". Cannot show G-code window.";
return;
}
*const_cast<uint64_t*>(&m_selected_line_id) = curr_line_id;
*const_cast<size_t*>(&m_last_lines_size) = m_lines.size();
}
// line number's column width
const float id_width = ImGui::CalcTextSize(std::to_string(end_id).c_str()).x;
ImGuiWrapper& imgui = *wxGetApp().imgui();
imgui.set_next_window_pos(0.0f, top, ImGuiCond_Always, 0.0f, 0.0f);
imgui.set_next_window_size(0.0f, wnd_height, ImGuiCond_Always);
ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
ImGui::SetNextWindowBgAlpha(0.6f);
imgui.begin(std::string("G-code"), ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoMove);
// center the text in the window by pushing down the first line
const float f_lines_count = static_cast<float>(lines_count);
ImGui::SetCursorPosY(0.5f * (wnd_height - f_lines_count * text_height - (f_lines_count - 1.0f) * style.ItemSpacing.y));
// render text lines
for (uint64_t id = start_id; id <= end_id; ++id) {
const Line& line = m_lines[id - start_id];
// rect around the current selected line
if (id == curr_line_id) {
const float pos_y = ImGui::GetCursorScreenPos().y;
const float half_ItemSpacing_y = 0.5f * style.ItemSpacing.y;
const float half_padding_x = 0.5f * style.WindowPadding.x;
ImGui::GetWindowDrawList()->AddRect({ half_padding_x, pos_y - half_ItemSpacing_y },
{ ImGui::GetCurrentWindow()->Size.x - half_padding_x, pos_y + text_height + half_ItemSpacing_y },
ImGui::GetColorU32(SELECTION_RECT_COLOR));
}
// render line number
const std::string id_str = std::to_string(id);
// spacer to right align text
ImGui::Dummy({ id_width - ImGui::CalcTextSize(id_str.c_str()).x, text_height });
ImGui::SameLine(0.0f, 0.0f);
ImGui::PushStyleColor(ImGuiCol_Text, LINE_NUMBER_COLOR);
imgui.text(id_str);
ImGui::PopStyleColor();
if (!line.command.empty() || !line.comment.empty())
ImGui::SameLine();
// render command
if (!line.command.empty()) {
ImGui::PushStyleColor(ImGuiCol_Text, COMMAND_COLOR);
imgui.text(line.command);
ImGui::PopStyleColor();
}
// render parameters
if (!line.parameters.empty()) {
ImGui::SameLine(0.0f, 0.0f);
ImGui::PushStyleColor(ImGuiCol_Text, PARAMETERS_COLOR);
imgui.text(line.parameters);
ImGui::PopStyleColor();
}
// render comment
if (!line.comment.empty()) {
if (!line.command.empty())
ImGui::SameLine(0.0f, 0.0f);
ImGui::PushStyleColor(ImGuiCol_Text, COMMENT_COLOR);
imgui.text(line.comment);
ImGui::PopStyleColor();
}
}
imgui.end();
ImGui::PopStyleVar();
}
void GCodeViewer::SequentialView::GCodeWindow::stop_mapping_file()
{
if (m_file.is_open())
m_file.close();
}
void GCodeViewer::SequentialView::render(float legend_height) const
{
marker.render();
float bottom = wxGetApp().plater()->get_current_canvas3D()->get_canvas_size().get_height();
if (wxGetApp().is_editor())
bottom -= wxGetApp().plater()->get_view_toolbar().get_height();
gcode_window.render(legend_height, bottom, static_cast<uint64_t>(gcode_ids[current.last]));
}
const std::vector<GCodeViewer::Color> GCodeViewer::Extrusion_Role_Colors {{
{ 0.90f, 0.70f, 0.70f, 1.0f }, // erNone
{ 1.00f, 0.90f, 0.30f, 1.0f }, // erPerimeter
{ 1.00f, 0.49f, 0.22f, 1.0f }, // erExternalPerimeter
{ 0.12f, 0.12f, 1.00f, 1.0f }, // erOverhangPerimeter
{ 0.69f, 0.19f, 0.16f, 1.0f }, // erInternalInfill
{ 0.59f, 0.33f, 0.80f, 1.0f }, // erSolidInfill
{ 0.94f, 0.25f, 0.25f, 1.0f }, // erTopSolidInfill
{ 1.00f, 0.55f, 0.41f, 1.0f }, // erIroning
{ 0.30f, 0.50f, 0.73f, 1.0f }, // erBridgeInfill
{ 1.00f, 1.00f, 1.00f, 1.0f }, // erGapFill
{ 0.00f, 0.53f, 0.43f, 1.0f }, // erSkirt
{ 0.00f, 1.00f, 0.00f, 1.0f }, // erSupportMaterial
{ 0.00f, 0.50f, 0.00f, 1.0f }, // erSupportMaterialInterface
{ 0.70f, 0.89f, 0.67f, 1.0f }, // erWipeTower
{ 0.37f, 0.82f, 0.58f, 1.0f }, // erCustom
{ 0.00f, 0.00f, 0.00f, 1.0f } // erMixed
}};
const std::vector<GCodeViewer::Color> GCodeViewer::Options_Colors {{
{ 0.803f, 0.135f, 0.839f, 1.0f }, // Retractions
{ 0.287f, 0.679f, 0.810f, 1.0f }, // Unretractions
{ 0.900f, 0.900f, 0.900f, 1.0f }, // Seams
{ 0.758f, 0.744f, 0.389f, 1.0f }, // ToolChanges
{ 0.856f, 0.582f, 0.546f, 1.0f }, // ColorChanges
{ 0.322f, 0.942f, 0.512f, 1.0f }, // PausePrints
{ 0.886f, 0.825f, 0.262f, 1.0f } // CustomGCodes
}};
const std::vector<GCodeViewer::Color> GCodeViewer::Travel_Colors {{
{ 0.219f, 0.282f, 0.609f, 1.0f }, // Move
{ 0.112f, 0.422f, 0.103f, 1.0f }, // Extrude
{ 0.505f, 0.064f, 0.028f, 1.0f } // Retract
}};
#if 1
// Normal ranges
const std::vector<GCodeViewer::Color> GCodeViewer::Range_Colors {{
{ 0.043f, 0.173f, 0.478f, 1.0f }, // bluish
{ 0.075f, 0.349f, 0.522f, 1.0f },
{ 0.110f, 0.533f, 0.569f, 1.0f },
{ 0.016f, 0.839f, 0.059f, 1.0f },
{ 0.667f, 0.949f, 0.000f, 1.0f },
{ 0.988f, 0.975f, 0.012f, 1.0f },
{ 0.961f, 0.808f, 0.039f, 1.0f },
{ 0.890f, 0.533f, 0.125f, 1.0f },
{ 0.820f, 0.408f, 0.188f, 1.0f },
{ 0.761f, 0.322f, 0.235f, 1.0f },
{ 0.581f, 0.149f, 0.087f, 1.0f } // reddish
}};
#else
// Detailed ranges
const std::vector<GCodeViewer::Color> GCodeViewer::Range_Colors{ {
{ 0.043f, 0.173f, 0.478f, 1.0f }, // bluish
{ 0.5f * (0.043f + 0.075f), 0.5f * (0.173f + 0.349f), 0.5f * (0.478f + 0.522f), 1.0f },
{ 0.075f, 0.349f, 0.522f, 1.0f },
{ 0.5f * (0.075f + 0.110f), 0.5f * (0.349f + 0.533f), 0.5f * (0.522f + 0.569f), 1.0f },
{ 0.110f, 0.533f, 0.569f, 1.0f },
{ 0.5f * (0.110f + 0.016f), 0.5f * (0.533f + 0.839f), 0.5f * (0.569f + 0.059f), 1.0f },
{ 0.016f, 0.839f, 0.059f, 1.0f },
{ 0.5f * (0.016f + 0.667f), 0.5f * (0.839f + 0.949f), 0.5f * (0.059f + 0.000f), 1.0f },
{ 0.667f, 0.949f, 0.000f, 1.0f },
{ 0.5f * (0.667f + 0.988f), 0.5f * (0.949f + 0.975f), 0.5f * (0.000f + 0.012f), 1.0f },
{ 0.988f, 0.975f, 0.012f, 1.0f },
{ 0.5f * (0.988f + 0.961f), 0.5f * (0.975f + 0.808f), 0.5f * (0.012f + 0.039f), 1.0f },
{ 0.961f, 0.808f, 0.039f, 1.0f },
{ 0.5f * (0.961f + 0.890f), 0.5f * (0.808f + 0.533f), 0.5f * (0.039f + 0.125f), 1.0f },
{ 0.890f, 0.533f, 0.125f, 1.0f },
{ 0.5f * (0.890f + 0.820f), 0.5f * (0.533f + 0.408f), 0.5f * (0.125f + 0.188f), 1.0f },
{ 0.820f, 0.408f, 0.188f, 1.0f },
{ 0.5f * (0.820f + 0.761f), 0.5f * (0.408f + 0.322f), 0.5f * (0.188f + 0.235f), 1.0f },
{ 0.761f, 0.322f, 0.235f, 1.0f },
{ 0.5f * (0.761f + 0.581f), 0.5f * (0.322f + 0.149f), 0.5f * (0.235f + 0.087f), 1.0f },
{ 0.581f, 0.149f, 0.087f, 1.0f } // reddishgit
} };
#endif
const GCodeViewer::Color GCodeViewer::Wipe_Color = { 1.0f, 1.0f, 0.0f, 1.0f };
const GCodeViewer::Color GCodeViewer::Neutral_Color = { 0.25f, 0.25f, 0.25f, 1.0f };
GCodeViewer::GCodeViewer()
{
m_extrusions.reset_role_visibility_flags();
// m_sequential_view.skip_invisible_moves = true;
}
void GCodeViewer::init()
{
if (m_gl_data_initialized)
return;
// initializes opengl data of TBuffers
for (size_t i = 0; i < m_buffers.size(); ++i) {
TBuffer& buffer = m_buffers[i];
EMoveType type = buffer_type(i);
switch (type)
{
default: { break; }
case EMoveType::Tool_change:
case EMoveType::Color_change:
case EMoveType::Pause_Print:
case EMoveType::Custom_GCode:
case EMoveType::Retract:
case EMoveType::Unretract:
case EMoveType::Seam: {
if (wxGetApp().is_gl_version_greater_or_equal_to(3, 3)) {
buffer.render_primitive_type = TBuffer::ERenderPrimitiveType::InstancedModel;
buffer.shader = "gouraud_light_instanced";
buffer.model.model.init_from(diamond(16));
buffer.model.color = option_color(type);
buffer.model.instances.format = InstanceVBuffer::EFormat::InstancedModel;
}
else {
buffer.render_primitive_type = TBuffer::ERenderPrimitiveType::BatchedModel;
buffer.vertices.format = VBuffer::EFormat::PositionNormal3;
buffer.shader = "gouraud_light";
buffer.model.data = diamond(16);
buffer.model.color = option_color(type);
buffer.model.instances.format = InstanceVBuffer::EFormat::BatchedModel;
}
break;
}
case EMoveType::Wipe:
case EMoveType::Extrude: {
buffer.render_primitive_type = TBuffer::ERenderPrimitiveType::Triangle;
buffer.vertices.format = VBuffer::EFormat::PositionNormal3;
buffer.shader = "gouraud_light";
break;
}
case EMoveType::Travel: {
buffer.render_primitive_type = TBuffer::ERenderPrimitiveType::Line;
buffer.vertices.format = VBuffer::EFormat::PositionNormal1;
buffer.shader = "toolpaths_lines";
break;
}
}
set_toolpath_move_type_visible(EMoveType::Extrude, true);
}
// initializes tool marker
m_sequential_view.marker.init();
// initializes point sizes
std::array<int, 2> point_sizes;
::glGetIntegerv(GL_ALIASED_POINT_SIZE_RANGE, point_sizes.data());
m_detected_point_sizes = { static_cast<float>(point_sizes[0]), static_cast<float>(point_sizes[1]) };
m_gl_data_initialized = true;
}
void GCodeViewer::load(const GCodeProcessorResult& gcode_result, const Print& print, bool initialized)
{
// avoid processing if called with the same gcode_result
if (m_last_result_id == gcode_result.id)
return;
m_last_result_id = gcode_result.id;
// release gpu memory, if used
reset();
m_sequential_view.gcode_window.load_gcode(gcode_result.filename,
// Stealing out lines_ends should be safe because this gcode_result is processed only once (see the 1st if in this function).
std::move(const_cast<std::vector<size_t>&>(gcode_result.lines_ends)));
if (wxGetApp().is_gcode_viewer())
m_custom_gcode_per_print_z = gcode_result.custom_gcode_per_print_z;
m_max_print_height = gcode_result.max_print_height;
load_toolpaths(gcode_result);
if (m_layers.empty())
return;
m_settings_ids = gcode_result.settings_ids;
m_filament_diameters = gcode_result.filament_diameters;
m_filament_densities = gcode_result.filament_densities;
if (wxGetApp().is_editor())
load_shells(print, initialized);
else {
Pointfs bed_shape;
std::string texture;
std::string model;
if (!gcode_result.bed_shape.empty()) {
// bed shape detected in the gcode
bed_shape = gcode_result.bed_shape;
const auto bundle = wxGetApp().preset_bundle;
if (bundle != nullptr && !m_settings_ids.printer.empty()) {
const Preset* preset = bundle->printers.find_preset(m_settings_ids.printer);
if (preset != nullptr) {
model = PresetUtils::system_printer_bed_model(*preset);
texture = PresetUtils::system_printer_bed_texture(*preset);
}
}
}
else {
// adjust printbed size in dependence of toolpaths bbox
const double margin = 10.0;
const Vec2d min(m_paths_bounding_box.min.x() - margin, m_paths_bounding_box.min.y() - margin);
const Vec2d max(m_paths_bounding_box.max.x() + margin, m_paths_bounding_box.max.y() + margin);
const Vec2d size = max - min;
bed_shape = {
{ min.x(), min.y() },
{ max.x(), min.y() },
{ max.x(), min.y() + 0.442265 * size.y()},
{ max.x() - 10.0, min.y() + 0.4711325 * size.y()},
{ max.x() + 10.0, min.y() + 0.5288675 * size.y()},
{ max.x(), min.y() + 0.557735 * size.y()},
{ max.x(), max.y() },
{ min.x() + 0.557735 * size.x(), max.y()},
{ min.x() + 0.5288675 * size.x(), max.y() - 10.0},
{ min.x() + 0.4711325 * size.x(), max.y() + 10.0},
{ min.x() + 0.442265 * size.x(), max.y()},
{ min.x(), max.y() } };
}
wxGetApp().plater()->set_bed_shape(bed_shape, gcode_result.max_print_height, texture, model, gcode_result.bed_shape.empty());
}
m_print_statistics = gcode_result.print_statistics;
if (m_time_estimate_mode != PrintEstimatedStatistics::ETimeMode::Normal) {
const float time = m_print_statistics.modes[static_cast<size_t>(m_time_estimate_mode)].time;
if (time == 0.0f ||
short_time(get_time_dhms(time)) == short_time(get_time_dhms(m_print_statistics.modes[static_cast<size_t>(PrintEstimatedStatistics::ETimeMode::Normal)].time)))
m_time_estimate_mode = PrintEstimatedStatistics::ETimeMode::Normal;
}
}
void GCodeViewer::refresh(const GCodeProcessorResult& gcode_result, const std::vector<std::string>& str_tool_colors)
{
#if ENABLE_GCODE_VIEWER_STATISTICS
auto start_time = std::chrono::high_resolution_clock::now();
#endif // ENABLE_GCODE_VIEWER_STATISTICS
if (m_moves_count == 0)
return;
wxBusyCursor busy;
if (m_view_type == EViewType::Tool && !gcode_result.extruder_colors.empty())
// update tool colors from config stored in the gcode
m_tool_colors = decode_colors(gcode_result.extruder_colors);
else
// update tool colors
m_tool_colors = decode_colors(str_tool_colors);
// ensure there are enough colors defined
while (m_tool_colors.size() < std::max(size_t(1), gcode_result.extruders_count))
m_tool_colors.push_back(decode_color("#FF8000"));
// update ranges for coloring / legend
m_extrusions.reset_ranges();
for (size_t i = 0; i < m_moves_count; ++i) {
// skip first vertex
if (i == 0)
continue;
const GCodeProcessorResult::MoveVertex& curr = gcode_result.moves[i];
switch (curr.type)
{
case EMoveType::Extrude:
{
m_extrusions.ranges.height.update_from(round_to_nearest_percent(curr.height));
m_extrusions.ranges.width.update_from(round_to_nearest_percent(curr.width));
m_extrusions.ranges.fan_speed.update_from(curr.fan_speed);
m_extrusions.ranges.temperature.update_from(curr.temperature);
if (curr.extrusion_role != erCustom || is_visible(erCustom))
m_extrusions.ranges.volumetric_rate.update_from(round_to_nearest_percent(curr.volumetric_rate()));
[[fallthrough]];
}
case EMoveType::Travel:
{
if (m_buffers[buffer_id(curr.type)].visible)
m_extrusions.ranges.feedrate.update_from(curr.feedrate);
break;
}
default: { break; }
}
}
#if ENABLE_GCODE_VIEWER_STATISTICS
m_statistics.refresh_time = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - start_time).count();
#endif // ENABLE_GCODE_VIEWER_STATISTICS
// update buffers' render paths
refresh_render_paths();
log_memory_used("Refreshed G-code extrusion paths, ");
}
void GCodeViewer::refresh_render_paths()
{
refresh_render_paths(false, false);
}
void GCodeViewer::update_shells_color_by_extruder(const DynamicPrintConfig* config)
{
if (config != nullptr)
m_shells.volumes.update_colors_by_extruder(config);
}
void GCodeViewer::reset()
{
m_moves_count = 0;
for (TBuffer& buffer : m_buffers) {
buffer.reset();
}
m_paths_bounding_box = BoundingBoxf3();
m_max_bounding_box = BoundingBoxf3();
m_max_print_height = 0.0f;
m_tool_colors = std::vector<Color>();
m_extruders_count = 0;
m_extruder_ids = std::vector<unsigned char>();
m_filament_diameters = std::vector<float>();
m_filament_densities = std::vector<float>();
m_extrusions.reset_ranges();
m_shells.volumes.clear();
m_layers.reset();
m_layers_z_range = { 0, 0 };
m_roles = std::vector<ExtrusionRole>();
m_print_statistics.reset();
m_custom_gcode_per_print_z = std::vector<CustomGCode::Item>();
m_sequential_view.gcode_window.reset();
#if ENABLE_GCODE_VIEWER_STATISTICS
m_statistics.reset_all();
#endif // ENABLE_GCODE_VIEWER_STATISTICS
m_contained_in_bed = true;
}
void GCodeViewer::render()
{
#if ENABLE_GCODE_VIEWER_STATISTICS
m_statistics.reset_opengl();
m_statistics.total_instances_gpu_size = 0;
#endif // ENABLE_GCODE_VIEWER_STATISTICS
if (m_roles.empty())
return;
glsafe(::glEnable(GL_DEPTH_TEST));
render_toolpaths();
render_shells();
float legend_height = 0.0f;
render_legend(legend_height);
if (m_sequential_view.current.last != m_sequential_view.endpoints.last) {
m_sequential_view.marker.set_world_position(m_sequential_view.current_position);
m_sequential_view.marker.set_world_offset(m_sequential_view.current_offset);
m_sequential_view.render(legend_height);
}
#if ENABLE_GCODE_VIEWER_STATISTICS
render_statistics();
#endif // ENABLE_GCODE_VIEWER_STATISTICS
}
bool GCodeViewer::can_export_toolpaths() const
{
return has_data() && m_buffers[buffer_id(EMoveType::Extrude)].render_primitive_type == TBuffer::ERenderPrimitiveType::Triangle;
}
void GCodeViewer::update_sequential_view_current(unsigned int first, unsigned int last)
{
auto is_visible = [this](unsigned int id) {
for (const TBuffer& buffer : m_buffers) {
if (buffer.visible) {
for (const Path& path : buffer.paths) {
if (path.sub_paths.front().first.s_id <= id && id <= path.sub_paths.back().last.s_id)
return true;
}
}
}
return false;
};
const int first_diff = static_cast<int>(first) - static_cast<int>(m_sequential_view.last_current.first);
const int last_diff = static_cast<int>(last) - static_cast<int>(m_sequential_view.last_current.last);
unsigned int new_first = first;
unsigned int new_last = last;
if (m_sequential_view.skip_invisible_moves) {
while (!is_visible(new_first)) {
if (first_diff > 0)
++new_first;
else
--new_first;
}
while (!is_visible(new_last)) {
if (last_diff > 0)
++new_last;
else
--new_last;
}
}
m_sequential_view.current.first = new_first;
m_sequential_view.current.last = new_last;
m_sequential_view.last_current = m_sequential_view.current;
refresh_render_paths(true, true);
if (new_first != first || new_last != last)
wxGetApp().plater()->update_preview_moves_slider();
}
bool GCodeViewer::is_toolpath_move_type_visible(EMoveType type) const
{
size_t id = static_cast<size_t>(buffer_id(type));
return (id < m_buffers.size()) ? m_buffers[id].visible : false;
}
void GCodeViewer::set_toolpath_move_type_visible(EMoveType type, bool visible)
{
size_t id = static_cast<size_t>(buffer_id(type));
if (id < m_buffers.size())
m_buffers[id].visible = visible;
}
unsigned int GCodeViewer::get_options_visibility_flags() const
{
auto set_flag = [](unsigned int flags, unsigned int flag, bool active) {
return active ? (flags | (1 << flag)) : flags;
};
unsigned int flags = 0;
flags = set_flag(flags, static_cast<unsigned int>(Preview::OptionType::Travel), is_toolpath_move_type_visible(EMoveType::Travel));
flags = set_flag(flags, static_cast<unsigned int>(Preview::OptionType::Wipe), is_toolpath_move_type_visible(EMoveType::Wipe));
flags = set_flag(flags, static_cast<unsigned int>(Preview::OptionType::Retractions), is_toolpath_move_type_visible(EMoveType::Retract));
flags = set_flag(flags, static_cast<unsigned int>(Preview::OptionType::Unretractions), is_toolpath_move_type_visible(EMoveType::Unretract));
flags = set_flag(flags, static_cast<unsigned int>(Preview::OptionType::Seams), is_toolpath_move_type_visible(EMoveType::Seam));
flags = set_flag(flags, static_cast<unsigned int>(Preview::OptionType::ToolChanges), is_toolpath_move_type_visible(EMoveType::Tool_change));
flags = set_flag(flags, static_cast<unsigned int>(Preview::OptionType::ColorChanges), is_toolpath_move_type_visible(EMoveType::Color_change));
flags = set_flag(flags, static_cast<unsigned int>(Preview::OptionType::PausePrints), is_toolpath_move_type_visible(EMoveType::Pause_Print));
flags = set_flag(flags, static_cast<unsigned int>(Preview::OptionType::CustomGCodes), is_toolpath_move_type_visible(EMoveType::Custom_GCode));
flags = set_flag(flags, static_cast<unsigned int>(Preview::OptionType::Shells), m_shells.visible);
flags = set_flag(flags, static_cast<unsigned int>(Preview::OptionType::ToolMarker), m_sequential_view.marker.is_visible());
flags = set_flag(flags, static_cast<unsigned int>(Preview::OptionType::Legend), is_legend_enabled());
return flags;
}
void GCodeViewer::set_options_visibility_from_flags(unsigned int flags)
{
auto is_flag_set = [flags](unsigned int flag) {
return (flags & (1 << flag)) != 0;
};
set_toolpath_move_type_visible(EMoveType::Travel, is_flag_set(static_cast<unsigned int>(Preview::OptionType::Travel)));
set_toolpath_move_type_visible(EMoveType::Wipe, is_flag_set(static_cast<unsigned int>(Preview::OptionType::Wipe)));
set_toolpath_move_type_visible(EMoveType::Retract, is_flag_set(static_cast<unsigned int>(Preview::OptionType::Retractions)));
set_toolpath_move_type_visible(EMoveType::Unretract, is_flag_set(static_cast<unsigned int>(Preview::OptionType::Unretractions)));
set_toolpath_move_type_visible(EMoveType::Seam, is_flag_set(static_cast<unsigned int>(Preview::OptionType::Seams)));
set_toolpath_move_type_visible(EMoveType::Tool_change, is_flag_set(static_cast<unsigned int>(Preview::OptionType::ToolChanges)));
set_toolpath_move_type_visible(EMoveType::Color_change, is_flag_set(static_cast<unsigned int>(Preview::OptionType::ColorChanges)));
set_toolpath_move_type_visible(EMoveType::Pause_Print, is_flag_set(static_cast<unsigned int>(Preview::OptionType::PausePrints)));
set_toolpath_move_type_visible(EMoveType::Custom_GCode, is_flag_set(static_cast<unsigned int>(Preview::OptionType::CustomGCodes)));
m_shells.visible = is_flag_set(static_cast<unsigned int>(Preview::OptionType::Shells));
m_sequential_view.marker.set_visible(is_flag_set(static_cast<unsigned int>(Preview::OptionType::ToolMarker)));
enable_legend(is_flag_set(static_cast<unsigned int>(Preview::OptionType::Legend)));
}
void GCodeViewer::set_layers_z_range(const std::array<unsigned int, 2>& layers_z_range)
{
bool keep_sequential_current_first = layers_z_range[0] >= m_layers_z_range[0];
bool keep_sequential_current_last = layers_z_range[1] <= m_layers_z_range[1];
m_layers_z_range = layers_z_range;
refresh_render_paths(keep_sequential_current_first, keep_sequential_current_last);
wxGetApp().plater()->update_preview_moves_slider();
}
void GCodeViewer::export_toolpaths_to_obj(const char* filename) const
{
if (filename == nullptr)
return;
if (!has_data())
return;
wxBusyCursor busy;
// the data needed is contained into the Extrude TBuffer
const TBuffer& t_buffer = m_buffers[buffer_id(EMoveType::Extrude)];
if (!t_buffer.has_data())
return;
if (t_buffer.render_primitive_type != TBuffer::ERenderPrimitiveType::Triangle)
return;
// collect color information to generate materials
std::vector<Color> colors;
for (const RenderPath& path : t_buffer.render_paths) {
colors.push_back(path.color);
}
std::sort(colors.begin(), colors.end());
colors.erase(std::unique(colors.begin(), colors.end()), colors.end());
// save materials file
boost::filesystem::path mat_filename(filename);
mat_filename.replace_extension("mtl");
CNumericLocalesSetter locales_setter;
FILE* fp = boost::nowide::fopen(mat_filename.string().c_str(), "w");
if (fp == nullptr) {
BOOST_LOG_TRIVIAL(error) << "GCodeViewer::export_toolpaths_to_obj: Couldn't open " << mat_filename.string().c_str() << " for writing";
return;
}
fprintf(fp, "# G-Code Toolpaths Materials\n");
fprintf(fp, "# Generated by %s-%s based on Slic3r\n", SLIC3R_APP_NAME, SLIC3R_VERSION);
unsigned int colors_count = 1;
for (const Color& color : colors) {
fprintf(fp, "\nnewmtl material_%d\n", colors_count++);