forked from bambulab/BambuStudio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BambuStudio.cpp
6729 lines (6095 loc) · 376 KB
/
BambuStudio.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
#ifdef WIN32
// Why?
#define _WIN32_WINNT 0x0502
// The standard Windows includes.
#define WIN32_LEAN_AND_MEAN
#define NOMINMAX
#include <Windows.h>
#include <wchar.h>
#ifdef SLIC3R_GUI
extern "C"
{
// Let the NVIDIA and AMD know we want to use their graphics card
// on a dual graphics card system.
__declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001;
__declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1;
}
#endif /* SLIC3R_GUI */
#endif /* WIN32 */
#include <cstdio>
#include <string>
#include <cstring>
#include <iostream>
#include <math.h>
#if defined(__linux__) || defined(__LINUX__)
#include <condition_variable>
#include <mutex>
#include <boost/thread.hpp>
//add json logic
#include "nlohmann/json.hpp"
using namespace nlohmann;
#endif
#include <boost/algorithm/string/predicate.hpp>
#include <boost/filesystem.hpp>
#include <boost/nowide/args.hpp>
#include <boost/nowide/cenv.hpp>
#include <boost/nowide/iostream.hpp>
#include <boost/nowide/fstream.hpp>
#include <boost/nowide/integration/filesystem.hpp>
#include <boost/dll/runtime_symbol_info.hpp>
#include <boost/log/trivial.hpp>
#include "unix/fhs.hpp" // Generated by CMake from ../platform/unix/fhs.hpp.in
#include "libslic3r/libslic3r.h"
#include "libslic3r/Config.hpp"
#include "libslic3r/Geometry.hpp"
#include "libslic3r/GCode/PostProcessor.hpp"
#include "libslic3r/Model.hpp"
#include "libslic3r/ModelArrange.hpp"
#include "libslic3r/Platform.hpp"
#include "libslic3r/Print.hpp"
#include "libslic3r/SLAPrint.hpp"
#include "libslic3r/TriangleMesh.hpp"
#include "libslic3r/Format/AMF.hpp"
#include "libslic3r/Format/3mf.hpp"
#include "libslic3r/Format/STL.hpp"
#include "libslic3r/Format/OBJ.hpp"
#include "libslic3r/Format/SL1.hpp"
#include "libslic3r/Utils.hpp"
#include "libslic3r/Time.hpp"
#include "libslic3r/Thread.hpp"
#include "libslic3r/BlacklistedLibraryCheck.hpp"
#include "libslic3r/FlushVolCalc.hpp"
#include "libslic3r/Orient.hpp"
#include "libslic3r/PNGReadWrite.hpp"
#include "libslic3r/ObjColorUtils.hpp"
#include "BambuStudio.hpp"
//BBS: add exception handler for win32
#include <wx/stdpaths.h>
#ifdef WIN32
#include "BaseException.h"
#endif
#include "slic3r/GUI/PartPlate.hpp"
#include "slic3r/GUI/BitmapCache.hpp"
#include "slic3r/GUI/OpenGLManager.hpp"
#include "slic3r/GUI/GLCanvas3D.hpp"
#include "slic3r/GUI/Camera.hpp"
#include "slic3r/GUI/Plater.hpp"
#include "slic3r/GUI/GuiColor.hpp"
#include <GLFW/glfw3.h>
#ifdef __WXGTK__
#include <X11/Xlib.h>
#endif
#ifdef SLIC3R_GUI
#include "slic3r/GUI/GUI_Init.hpp"
#endif /* SLIC3R_GUI */
using namespace Slic3r;
/*typedef struct _error_message{
int code;
std::string message;
}error_message;*/
#define MAX_CLONEABLE_SIZE 512
std::map<int, std::string> cli_errors = {
{CLI_SUCCESS, "Success."},
{CLI_ENVIRONMENT_ERROR, "Failed setting up server environment."},
{CLI_INVALID_PARAMS, "Invalid parameters to the slicer."},
{CLI_FILE_NOTFOUND, "The input files to the slicer are not found."},
{CLI_FILELIST_INVALID_ORDER, "File list order to the slicer is invalid. Please make sure the 3mf in the first place."},
{CLI_CONFIG_FILE_ERROR, "The input preset file is invalid and can not be parsed."},
{CLI_DATA_FILE_ERROR, "The input model file to the slicer can not be parsed."},
{CLI_INVALID_PRINTER_TECH, "Unsupported printer technology (not FDM)."},
{CLI_UNSUPPORTED_OPERATION, "Unsupported CLI instruction."},
{CLI_COPY_OBJECTS_ERROR, "Failed copying objects."},
{CLI_SCALE_TO_FIT_ERROR, "Failed scaling an object to fit the plate."},
{CLI_EXPORT_STL_ERROR, "Failed exporting STL files."},
{CLI_EXPORT_OBJ_ERROR, "Failed exporting OBJ files."},
{CLI_EXPORT_3MF_ERROR, "Failed exporting 3mf files."},
{CLI_OUT_OF_MEMORY, "Out of memory during slicing. Please upload a model with lower geometry resolution and try again."},
{CLI_3MF_NOT_SUPPORT_MACHINE_CHANGE, "The selected printer is not supported."},
{CLI_3MF_NEW_MACHINE_NOT_SUPPORTED, "The selected printer is not compatible with the 3mf."},
{CLI_PROCESS_NOT_COMPATIBLE, "The selected printer is not compatible with the process preset in the 3mf."},
{CLI_INVALID_VALUES_IN_3MF, "Invalid parameter value(s) included in the 3mf file."},
{CLI_POSTPROCESS_NOT_SUPPORTED, "post_process is not supported under CLI."},
{CLI_PRINTABLE_SIZE_REDUCED, "The selected printer's bed size is smaller than the bed size used in the print profile."},
{CLI_OBJECT_ARRANGE_FAILED, "An error occurred when auto-arranging object(s)."},
{CLI_OBJECT_ORIENT_FAILED, "An error occurred when auto-orienting object(s)."},
{CLI_MODIFIED_PARAMS_TO_PRINTER, "You cannot change the Printable Area, Printable Height, and Exclude Area in Printer Settings."},
{CLI_FILE_VERSION_NOT_SUPPORTED, "Unsupported 3MF version. Please make sure the 3MF file was created with the official version of Bambu Studio, not a beta version."},
{CLI_NO_SUITABLE_OBJECTS, "One of the plate is empty or has no object fully inside it. Please check that the 3mf contains no empty plate in Bambu Studio before uploading."},
{CLI_VALIDATE_ERROR, "There are some incorrect slicing parameters in the 3mf. Please verify the slicing of all plates in Bambu Studio before uploading."},
{CLI_OBJECTS_PARTLY_INSIDE, "Some objects are located over the boundary of the heated bed."},
{CLI_EXPORT_CACHE_DIRECTORY_CREATE_FAILED, "Failed creating directory when exporting cache data."},
{CLI_EXPORT_CACHE_WRITE_FAILED, "Failed exporting cache data."},
{CLI_IMPORT_CACHE_NOT_FOUND, "Cache data not found."},
{CLI_IMPORT_CACHE_DATA_CAN_NOT_USE, "Cache data can not be parsed."},
{CLI_IMPORT_CACHE_LOAD_FAILED, "Failed importing cache data."},
{CLI_SLICING_TIME_EXCEEDS_LIMIT, "Slicing time of a certain plate exceeds the limit. Please simplify the model or use a larger slicing layer height."},
{CLI_TRIANGLE_COUNT_EXCEEDS_LIMIT, "Triangle count of single plate exceeds the limit. Please simplify the model and try to upload again."},
{CLI_NO_SUITABLE_OBJECTS_AFTER_SKIP, "No printable objects to slice after skipping."},
{CLI_FILAMENT_NOT_MATCH_BED_TYPE, "Filaments are not compatible with the plate type. Please verify the slicing of all plates in Bambu Studio before uploading."},
{CLI_FILAMENTS_DIFFERENT_TEMP, "The temperature difference of the filaments used is too large. Please verify the slicing of all plates in Bambu Studio before uploading."},
{CLI_OBJECT_COLLISION_IN_SEQ_PRINT, "Object conflicts were detected when using print-by-object mode. Please verify the slicing of all plates in Bambu Studio before uploading."},
{CLI_OBJECT_COLLISION_IN_LAYER_PRINT, "Object conflicts were detected. Please verify the slicing of all plates in Bambu Studio before uploading."},
{CLI_SPIRAL_MODE_INVALID_PARAMS, "Some slicing parameters cannot work with Spiral Vase mode. Please solve the issue in Bambu Studio before uploading."},
{CLI_SLICING_ERROR, "Failed slicing the model. Please verify the slicing of all plates on Bambu Studio before uploading."},
{CLI_GCODE_PATH_CONFLICTS, " G-code conflicts detected after slicing. Please make sure the 3mf file can be successfully sliced in the latest Bambu Studio."}
};
typedef struct _sliced_plate_info{
int plate_id{0};
size_t sliced_time {0};
size_t sliced_time_with_cache {0};
size_t make_perimeters_time {0};
size_t infill_time {0};
size_t generate_support_material_time {0};
size_t triangle_count{0};
std::string warning_message;
}sliced_plate_info_t;
typedef struct _sliced_info {
int plate_count {0};
int plate_to_slice {0};
std::vector<sliced_plate_info_t> sliced_plates;
size_t prepare_time;
size_t export_time;
std::vector<std::string> upward_machines;
std::vector<std::string> downward_machines;
}sliced_info_t;
std::vector<PrintBase::SlicingStatus> g_slicing_warnings;
#if defined(__linux__) || defined(__LINUX__)
#define PIPE_BUFFER_SIZE 512
typedef struct _cli_callback_mgr {
int m_plate_count {0};
int m_plate_index {0};
int m_progress { 0 };
int m_total_progress { 0 };
std::string m_message;
int m_warning_step;
bool m_exit {false};
bool m_data_ready {false};
bool m_started {false};
boost::thread m_thread;
// Mutex and condition variable to synchronize m_thread with the UI thread.
std::mutex m_mutex;
std::condition_variable m_condition;
int m_pipe_fd{-1};
bool is_started()
{
bool result;
std::unique_lock<std::mutex> lck(m_mutex);
result = m_started;
lck.unlock();
return result;
}
void set_plate_info(int index, int count)
{
BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << ": index="<<index<< ", count = "<< count;
std::unique_lock<std::mutex> lck(m_mutex);
m_plate_count = count;
m_plate_index = index;
m_progress = 0;
lck.unlock();
return;
}
void notify()
{
if (m_pipe_fd < 0)
return;
json j;
//record the headers
j["plate_index"] = m_plate_index;
j["plate_count"] = m_plate_count;
j["plate_percent"] = m_progress;
j["total_percent"] = m_total_progress;
if (m_warning_step >= 0)
j["warning"] = m_message;
else
j["message"] = m_message;
std::string notify_message = j.dump();
//notify_message = "Plate "+ std::to_string(m_plate_index) + "/" +std::to_string(m_plate_count)+ ": Percent " + std::to_string(m_progress) + ": "+m_message;
char pipe_message[PIPE_BUFFER_SIZE] = {0};
snprintf(pipe_message, PIPE_BUFFER_SIZE, "%s\n", notify_message.c_str());
int ret = write(m_pipe_fd, pipe_message, strlen(pipe_message));
BOOST_LOG_TRIVIAL(debug) << __FUNCTION__ << ": write returns "<<ret;
return;
}
void thread_proc()
{
std::unique_lock<std::mutex> lck(m_mutex);
m_started = true;
m_data_ready = false;
lck.unlock();
m_condition.notify_one();
boost::this_thread::sleep(boost::posix_time::milliseconds(20));
BOOST_LOG_TRIVIAL(info) << "cli_callback_mgr_t::thread_proc started.";
while(1) {
lck.lock();
m_condition.wait(lck, [this](){ return m_data_ready || m_exit; });
BOOST_LOG_TRIVIAL(debug) << __FUNCTION__ << ": wakup.";
if (m_data_ready) {
notify();
m_data_ready = false;
}
if (m_exit) {
BOOST_LOG_TRIVIAL(info) << "cli_callback_mgr_t::thread_proc will exit.";
break;
}
lck.unlock();
m_condition.notify_one();
}
lck.unlock();
BOOST_LOG_TRIVIAL(info) << "cli_callback_mgr_t::thread_proc exit.";
}
void update(int percent, std::string message, int warning_step)
{
std::unique_lock<std::mutex> lck(m_mutex);
if (!m_started) {
lck.unlock();
return;
}
if ((m_progress >= percent)&&(warning_step == -1)) {
//already update before
lck.unlock();
return;
}
int old_total_progress = m_total_progress;
BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << ": percent="<<percent<< ", warning_step=" << warning_step << ", plate_index = "<< m_plate_index<<", plate_count="<< m_plate_count<<", message="<<message;
if (warning_step == -1) {
m_progress = percent;
if ((m_plate_count <= 1) && (m_plate_index >= 1))
m_total_progress = 3 + 0.9*m_progress;
else if ((m_plate_count > 1) && (m_plate_index >= 1)) {
m_total_progress = 3 + ((float)(m_plate_index - 1)*90)/m_plate_count + ((float)m_progress*0.9)/m_plate_count;
}
else
m_total_progress = m_progress;
}
if (m_total_progress < old_total_progress)
m_total_progress = old_total_progress;
m_message = message;
m_warning_step = warning_step;
m_data_ready = true;
lck.unlock();
m_condition.notify_one();
BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << ": m_total_progress="<<m_total_progress;
return;
}
bool start(std::string pipe_name)
{
int retry_count = 0;
BOOST_LOG_TRIVIAL(info) << "cli_callback_mgr_t::start enter.";
m_pipe_fd = open(pipe_name.c_str(),O_WRONLY|O_NONBLOCK);
while (m_pipe_fd < 0) {
if ((retry_count%10) == 0)
BOOST_LOG_TRIVIAL(warning) << boost::format("could not open pipe for %1%, errno %2%, reason: %3%, retry_count = %4%")%pipe_name %errno %strerror(errno) %retry_count;
retry_count ++;
if (retry_count >= 50) {
BOOST_LOG_TRIVIAL(warning) << boost::format("reach max retry_count, failed to open pipe");
return false;
}
boost::this_thread::sleep(boost::posix_time::milliseconds(20));
m_pipe_fd = open(pipe_name.c_str(),O_WRONLY|O_NONBLOCK);
}
std::unique_lock<std::mutex> lck(m_mutex);
m_thread = create_thread([this]{
this->thread_proc();
});
m_condition.wait(lck, [this](){ return m_started; });
lck.unlock();
m_condition.notify_one();
BOOST_LOG_TRIVIAL(info) << "cli_callback_mgr_t::start successfully.";
return true;
}
void stop()
{
BOOST_LOG_TRIVIAL(info) << "cli_callback_mgr_t::stop enter.";
std::unique_lock<std::mutex> lck(m_mutex);
if (!m_started) {
lck.unlock();
BOOST_LOG_TRIVIAL(info) << "cli_callback_mgr_t::stop not started before, return directly.";
return;
}
m_exit = true;
lck.unlock();
m_condition.notify_one();
// Wait until the worker thread exits.
m_thread.join();
if (m_pipe_fd > 0) {
close(m_pipe_fd);
m_pipe_fd = -1;
}
BOOST_LOG_TRIVIAL(info) << "cli_callback_mgr_t::stop successfully.";
}
}cli_callback_mgr_t;
cli_callback_mgr_t g_cli_callback_mgr;
void cli_status_callback(const PrintBase::SlicingStatus& slicing_status)
{
if (slicing_status.warning_step != -1) {
g_slicing_warnings.push_back(slicing_status);
BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << boost::format(": percent=%1%, warning_step=%2%, message=%3%, message_type=%4%, flag=%5%")
%slicing_status.percent %slicing_status.warning_step %slicing_status.text %(int)(slicing_status.message_type) %slicing_status.flags;
}
g_cli_callback_mgr.update(slicing_status.percent, slicing_status.text, slicing_status.warning_step);
return;
}
#endif
void default_status_callback(const PrintBase::SlicingStatus& slicing_status)
{
if (slicing_status.warning_step != -1) {
g_slicing_warnings.push_back(slicing_status);
}
BOOST_LOG_TRIVIAL(debug) << __FUNCTION__ << boost::format(": percent=%1%, warning_step=%2%, message=%3%, message_type=%4%")%slicing_status.percent %slicing_status.warning_step %slicing_status.text %(int)(slicing_status.message_type);
return;
}
static PrinterTechnology get_printer_technology(const DynamicConfig &config)
{
const ConfigOptionEnum<PrinterTechnology> *opt = config.option<ConfigOptionEnum<PrinterTechnology>>("printer_technology");
return (opt == nullptr) ? ptUnknown : opt->value;
}
//BBS: add flush and exit
#if defined(__linux__) || defined(__LINUX__)
#define flush_and_exit(ret) { boost::nowide::cout << __FUNCTION__ << " found error, return "<<ret<<", exit..." << std::endl;\
g_cli_callback_mgr.stop();\
boost::nowide::cout.flush();\
boost::nowide::cerr.flush();\
for (Model &model : m_models) {\
model.remove_backup_path_if_exist();\
}\
return(ret);}
#else
#define flush_and_exit(ret) { boost::nowide::cout << __FUNCTION__ << " found error, exit" << std::endl;\
boost::nowide::cout.flush();\
boost::nowide::cerr.flush();\
for (Model &model : m_models) {\
model.remove_backup_path_if_exist();\
}\
return(ret);}
#endif
void record_exit_reson(std::string outputdir, int code, int plate_id, std::string error_message, sliced_info_t& sliced_info, std::map<std::string, std::string> key_values = std::map<std::string, std::string>())
{
#if defined(__linux__) || defined(__LINUX__)
std::string result_file;
if (!outputdir.empty())
result_file = outputdir + "/result.json";
else
result_file = "result.json";
try {
json j;
//record the headers
if (sliced_info.downward_machines.size() > 0)
j["downward_compatible_machine"] = sliced_info.downward_machines;
if (sliced_info.upward_machines.size() > 0)
j["upward_compatible_machine"] = sliced_info.upward_machines;
j["plate_index"] = plate_id;
j["return_code"] = code;
j["error_string"] = error_message;
j["prepare_time"] = sliced_info.prepare_time;
j["export_time"] = sliced_info.export_time;
for (size_t index = 0; index < sliced_info.sliced_plates.size(); index++)
{
json plate_json;
plate_json["id"] = sliced_info.sliced_plates[index].plate_id;
plate_json["sliced_time"] = sliced_info.sliced_plates[index].sliced_time;
plate_json["sliced_time_with_cache"] = sliced_info.sliced_plates[index].sliced_time_with_cache;
plate_json["make_perimeters_time"] = sliced_info.sliced_plates[index].make_perimeters_time;
plate_json["infill_time"] = sliced_info.sliced_plates[index].infill_time;
plate_json["generate_support_material_time"] = sliced_info.sliced_plates[index].generate_support_material_time;
plate_json["triangle_count"] = sliced_info.sliced_plates[index].triangle_count;
plate_json["warning_message"] = sliced_info.sliced_plates[index].warning_message;
j["sliced_plates"].push_back(plate_json);
}
for (auto& iter: key_values)
j[iter.first] = iter.second;
boost::nowide::ofstream c;
c.open(result_file, std::ios::out | std::ios::trunc);
c << std::setw(4) << j << std::endl;
c.close();
BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << ":" <<__LINE__ << boost::format(", saved config to %1%\n")%result_file;
}
catch (...) {}
#endif
}
static int decode_png_to_thumbnail(std::string png_file, ThumbnailData& thumbnail_data)
{
if (!boost::filesystem::exists(png_file))
{
BOOST_LOG_TRIVIAL(error) << boost::format("can not find file %1%")%png_file;
return -1;
}
const std::size_t &size = boost::filesystem::file_size(png_file);
std::string png_buffer(size, '\0');
png_buffer.reserve(size);
boost::filesystem::ifstream ifs(png_file, std::ios::binary);
ifs.read(png_buffer.data(), png_buffer.size());
ifs.close();
Slic3r::png::ImageColorscale img;
Slic3r::png::ReadBuf rb{png_buffer.data(), png_buffer.size()};
BOOST_LOG_TRIVIAL(info) << boost::format("read png file %1%, size %2%")%png_file %size;
if ( !Slic3r::png::decode_colored_png(rb, img))
{
BOOST_LOG_TRIVIAL(error) << boost::format("decode png file %1% failed")%png_file;
return -2;
}
thumbnail_data.width = img.cols;
thumbnail_data.height = img.rows;
thumbnail_data.pixels = std::move(img.buf);
return 0;
}
static void glfw_callback(int error_code, const char* description)
{
BOOST_LOG_TRIVIAL(error) << "error_code " <<error_code <<", description: " <<description<< std::endl;
}
const float bed3d_ax3s_default_stem_radius = 0.5f;
const float bed3d_ax3s_default_stem_length = 25.0f;
const float bed3d_ax3s_default_tip_radius = 2.5f * bed3d_ax3s_default_stem_radius;
const float bed3d_ax3s_default_tip_length = 5.0f;
static int load_key_values_from_json(const std::string &file, std::map<std::string, std::string>& key_values)
{
json j;
CNumericLocalesSetter locales_setter;
BOOST_LOG_TRIVIAL(debug) << __FUNCTION__<< ": begin to parse "<<file;
try {
boost::nowide::ifstream ifs(file);
ifs >> j;
ifs.close();
//parse the json elements
for (auto it = j.begin(); it != j.end(); it++) {
if (boost::iequals(it.key(),BBL_JSON_KEY_MODEL_ID)) {
key_values.emplace(BBL_JSON_KEY_MODEL_ID, it.value());
}
else if (boost::iequals(it.key(), BBL_JSON_KEY_NAME)) {
key_values.emplace(BBL_JSON_KEY_NAME, it.value());
}
}
}
catch (const std::ifstream::failure &err) {
BOOST_LOG_TRIVIAL(error) << __FUNCTION__<< ": parse "<<file<<" got a ifstream error, reason = " << err.what();
return -1;
}
catch(nlohmann::detail::parse_error &err) {
BOOST_LOG_TRIVIAL(error) << __FUNCTION__<< ": parse "<<file<<" got a nlohmann::detail::parse_error, reason = " << err.what();
return -2;
}
catch(std::exception &err) {
BOOST_LOG_TRIVIAL(error) << __FUNCTION__<< ": parse "<<file<<" got a generic exception, reason = " << err.what();
return -3;
}
BOOST_LOG_TRIVIAL(debug) << __FUNCTION__<< ": finished parse, key_values size "<<key_values.size();
return 0;
}
static std::set<std::string> gcodes_key_set = {"filament_end_gcode", "filament_start_gcode", "change_filament_gcode", "layer_change_gcode", "machine_end_gcode", "machine_pause_gcode", "machine_start_gcode",
"template_custom_gcode", "printing_by_object_gcode", "before_layer_change_gcode", "time_lapse_gcode"};
static void load_default_gcodes_to_config(DynamicPrintConfig& config, Preset::Type type)
{
if (config.size() == 0) {
BOOST_LOG_TRIVIAL(info) << __FUNCTION__<< ", empty config, return directly";
return;
}
//add those empty gcodes by default
if (type == Preset::TYPE_PRINTER)
{
std::string change_filament_gcode = config.option<ConfigOptionString>("change_filament_gcode", true)->value;
BOOST_LOG_TRIVIAL(trace) << __FUNCTION__<< ", change_filament_gcode: "<< change_filament_gcode;
ConfigOptionString* layer_change_gcode_opt = config.option<ConfigOptionString>("layer_change_gcode", true);
BOOST_LOG_TRIVIAL(trace) << __FUNCTION__<< ", layer_change_gcode: "<<layer_change_gcode_opt->value;
ConfigOptionString* machine_end_gcode_opt = config.option<ConfigOptionString>("machine_end_gcode", true);
BOOST_LOG_TRIVIAL(trace) << __FUNCTION__<< ", machine_end_gcode: "<<machine_end_gcode_opt->value;
ConfigOptionString* machine_pause_gcode_opt = config.option<ConfigOptionString>("machine_pause_gcode", true);
BOOST_LOG_TRIVIAL(trace) << __FUNCTION__<< ", machine_pause_gcode: "<<machine_pause_gcode_opt->value;
ConfigOptionString* machine_start_gcode_opt = config.option<ConfigOptionString>("machine_start_gcode", true);
BOOST_LOG_TRIVIAL(trace) << __FUNCTION__<< ", machine_start_gcode: "<<machine_start_gcode_opt->value;
ConfigOptionString* template_custom_gcode_opt = config.option<ConfigOptionString>("template_custom_gcode", true);
BOOST_LOG_TRIVIAL(trace) << __FUNCTION__<< ", template_custom_gcode: "<<template_custom_gcode_opt->value;
ConfigOptionString* printing_by_object_gcode_opt = config.option<ConfigOptionString>("printing_by_object_gcode", true);
BOOST_LOG_TRIVIAL(trace) << __FUNCTION__<< ", printing_by_object_gcode: "<<printing_by_object_gcode_opt->value;
ConfigOptionString* before_layer_change_gcode_opt = config.option<ConfigOptionString>("before_layer_change_gcode", true);
BOOST_LOG_TRIVIAL(trace) << __FUNCTION__<< ", before_layer_change_gcode: "<<before_layer_change_gcode_opt->value;
ConfigOptionString* timeplase_gcode_opt = config.option<ConfigOptionString>("time_lapse_gcode", true);
BOOST_LOG_TRIVIAL(trace) << __FUNCTION__<< ", time_lapse_gcode: "<<timeplase_gcode_opt->value;
}
else if (type == Preset::TYPE_FILAMENT)
{
std::vector<std::string>& filament_start_gcodes = config.option<ConfigOptionStrings>("filament_start_gcode", true)->values;
if (filament_start_gcodes.empty()) {
filament_start_gcodes.resize(1, std::string());
BOOST_LOG_TRIVIAL(info) << __FUNCTION__<< ", set filament_start_gcodes to empty";
}
else {
BOOST_LOG_TRIVIAL(trace) << __FUNCTION__<< ", filament_start_gcodes: "<<filament_start_gcodes[0];
}
std::vector<std::string>& filament_end_gcodes = config.option<ConfigOptionStrings>("filament_end_gcode", true)->values;
if (filament_end_gcodes.empty()) {
filament_end_gcodes.resize(1, std::string());
BOOST_LOG_TRIVIAL(info) << __FUNCTION__<< ", set filament_end_gcode to empty";
}
else {
BOOST_LOG_TRIVIAL(trace) << __FUNCTION__<< ", filament_end_gcode: "<<filament_end_gcodes[0];
}
}
}
static int load_assemble_plate_list(std::string config_file, std::vector<assemble_plate_info_t> &assemble_plate_info_list)
{
int ret = 0;
boost::filesystem::path directory_path(config_file);
BOOST_LOG_TRIVIAL(info) << boost::format("%1% enter, file %2%")%__FUNCTION__ % config_file;
if (!fs::exists(directory_path)) {
BOOST_LOG_TRIVIAL(error) << boost::format("directory %1% not exist.")%config_file;
return CLI_FILE_NOTFOUND;
}
try {
json root_json;
boost::nowide::ifstream ifs(config_file);
ifs >> root_json;
ifs.close();
int plate_count = root_json[JSON_ASSEMPLE_PLATES].size();
if ((plate_count <= 0) || (plate_count > MAX_PLATE_COUNT)) {
BOOST_LOG_TRIVIAL(error) << __FUNCTION__<< boost::format(": invalid plate count %1%")%plate_count;
return CLI_CONFIG_FILE_ERROR;
}
assemble_plate_info_list.resize(plate_count);
for (int plate_index = 0; plate_index < plate_count; plate_index++)
{
assemble_plate_info_t &assemble_plate = assemble_plate_info_list[plate_index];
const json& plate_json = root_json[JSON_ASSEMPLE_PLATES][plate_index];
assemble_plate.plate_name = plate_json[JSON_ASSEMPLE_PLATE_NAME];
assemble_plate.need_arrange = plate_json[JSON_ASSEMPLE_PLATE_NEED_ARRANGE];
if (plate_json.contains(JSON_ASSEMPLE_PLATE_PARAMS)) {
assemble_plate.plate_params = plate_json[JSON_ASSEMPLE_PLATE_PARAMS].get<std::map<std::string, std::string>>();
BOOST_LOG_TRIVIAL(debug) << boost::format("Plate %1%, has %2% plate params") % (plate_index + 1) % assemble_plate.plate_params.size();
}
int object_count = plate_json[JSON_ASSEMPLE_OBJECTS].size();
if (object_count <= 0) {
BOOST_LOG_TRIVIAL(error) << __FUNCTION__<< boost::format(": invalid object count %1% in plate %2%")%object_count %(plate_index+1);
return CLI_CONFIG_FILE_ERROR;
}
assemble_plate.assemble_obj_list.resize(object_count);
for (int object_index = 0; object_index < object_count; object_index++)
{
assemble_object_info_t& assemble_object = assemble_plate.assemble_obj_list[object_index];
const json& object_json = plate_json[JSON_ASSEMPLE_OBJECTS][object_index];
assemble_object.path = object_json[JSON_ASSEMPLE_OBJECT_PATH];
assemble_object.count = object_json[JSON_ASSEMPLE_OBJECT_COUNT];
if (assemble_object.count <= 0) {
BOOST_LOG_TRIVIAL(error) << __FUNCTION__ << boost::format(": invalid object clone count %1% in plate %2% Object %3%") % assemble_object.count % (plate_index + 1) % assemble_object.path;
return CLI_CONFIG_FILE_ERROR;
}
assemble_object.filaments = object_json.at(JSON_ASSEMPLE_OBJECT_FILAMENTS).get<std::vector<int>>();
if ((assemble_object.filaments.size() > 0) && (assemble_object.filaments.size() != assemble_object.count) && (assemble_object.filaments.size() != 1))
{
BOOST_LOG_TRIVIAL(error) << __FUNCTION__ << boost::format(": object %1%'s filaments count %2% not equal to clone count %3%, also not equal to 1") % assemble_object.path % assemble_object.filaments.size() % assemble_object.count;
return CLI_CONFIG_FILE_ERROR;
}
if (object_json.contains(JSON_ASSEMPLE_OBJECT_ASSEMBLE_INDEX)) {
assemble_object.assemble_index = object_json[JSON_ASSEMPLE_OBJECT_ASSEMBLE_INDEX].get<std::vector<int>>();
if ((assemble_object.assemble_index.size() > 0) && (assemble_object.assemble_index.size() != assemble_object.count) && (assemble_object.assemble_index.size() != 1))
{
BOOST_LOG_TRIVIAL(error) << __FUNCTION__ << boost::format(": object %1%'s assemble_index count %2% not equal to clone count %3%, also not equal to 1") % assemble_object.path % assemble_object.assemble_index.size() % assemble_object.count;
return CLI_CONFIG_FILE_ERROR;
}
}
if (object_json.contains(JSON_ASSEMPLE_OBJECT_POS_X)) {
assemble_object.pos_x = object_json[JSON_ASSEMPLE_OBJECT_POS_X].get<std::vector<float>>();
if ((assemble_object.pos_x.size() > 0) && (assemble_object.pos_x.size() != assemble_object.count) && (assemble_object.pos_x.size() != 1))
{
BOOST_LOG_TRIVIAL(error) << __FUNCTION__ << boost::format(": object %1%'s pos_x count %2% not equal to clone count %3%, also not equal to 1") % assemble_object.path % assemble_object.pos_x.size() % assemble_object.count;
return CLI_CONFIG_FILE_ERROR;
}
}
if (object_json.contains(JSON_ASSEMPLE_OBJECT_POS_Y)) {
assemble_object.pos_y = object_json[JSON_ASSEMPLE_OBJECT_POS_Y].get<std::vector<float>>();
if ((assemble_object.pos_y.size() > 0) && (assemble_object.pos_y.size() != assemble_object.count) && (assemble_object.pos_y.size() != 1))
{
BOOST_LOG_TRIVIAL(error) << __FUNCTION__ << boost::format(": object %1%'s pos_y count %2% not equal to clone count %3%, also not equal to 1") % assemble_object.path % assemble_object.pos_y.size() % assemble_object.count;
return CLI_CONFIG_FILE_ERROR;
}
}
if (object_json.contains(JSON_ASSEMPLE_OBJECT_POS_Z)) {
assemble_object.pos_z = object_json[JSON_ASSEMPLE_OBJECT_POS_Z].get<std::vector<float>>();
if ((assemble_object.pos_z.size() > 0) && (assemble_object.pos_z.size() != assemble_object.count) && (assemble_object.pos_z.size() != 1))
{
BOOST_LOG_TRIVIAL(error) << __FUNCTION__ << boost::format(": object %1%'s pos_z count %2% not equal to clone count %3%, also not equal to 1") % assemble_object.path % assemble_object.pos_z.size() % assemble_object.count;
return CLI_CONFIG_FILE_ERROR;
}
}
if (object_json.contains(JSON_ASSEMPLE_OBJECT_PRINT_PARAMS)) {
assemble_object.print_params = object_json[JSON_ASSEMPLE_OBJECT_PRINT_PARAMS].get<std::map<std::string, std::string>>();
BOOST_LOG_TRIVIAL(debug) << boost::format("Plate %1%, object %2% has %3% print params") % (plate_index + 1) %assemble_object.path % assemble_object.print_params.size();
}
if (object_json.contains(JSON_ASSEMPLE_OBJECT_HEIGHT_RANGES)) {
json height_range_json = object_json[JSON_ASSEMPLE_OBJECT_HEIGHT_RANGES];
int range_count = height_range_json.size();
BOOST_LOG_TRIVIAL(debug) << boost::format("Plate %1%, object %2% has %3% height ranges") % (plate_index + 1) %assemble_object.path % range_count;
assemble_object.height_ranges.resize(range_count);
for (int range_index = 0; range_index < range_count; range_index++)
{
height_range_info_t& height_range = assemble_object.height_ranges[range_index];
height_range.min_z = height_range_json[range_index][JSON_ASSEMPLE_OBJECT_MIN_Z];
height_range.max_z = height_range_json[range_index][JSON_ASSEMPLE_OBJECT_MAX_Z];
height_range.range_params = height_range_json[range_index][JSON_ASSEMPLE_OBJECT_RANGE_PARAMS].get<std::map<std::string, std::string>>();
}
}
}
if (plate_json.contains(JSON_ASSEMPLE_ASSEMBLE_PARAMS)) {
json assemble_params_json = plate_json[JSON_ASSEMPLE_ASSEMBLE_PARAMS];
int assemble_count = assemble_params_json.size();
for (int i = 0; i < assemble_count; i++)
{
assembled_param_info_t assembled_param;
int assemble_index = assemble_params_json[i][JSON_ASSEMPLE_OBJECT_ASSEMBLE_INDEX];
if (assemble_params_json[i].contains(JSON_ASSEMPLE_OBJECT_PRINT_PARAMS)) {
assembled_param.print_params = assemble_params_json[i][JSON_ASSEMPLE_OBJECT_PRINT_PARAMS].get<std::map<std::string, std::string>>();
BOOST_LOG_TRIVIAL(debug) << boost::format("Plate %1%, assemble object %2% has %3% print params") % (plate_index + 1) %i % assembled_param.print_params.size();
}
if (assemble_params_json[i].contains(JSON_ASSEMPLE_OBJECT_HEIGHT_RANGES)) {
json height_range_json = assemble_params_json[i][JSON_ASSEMPLE_OBJECT_HEIGHT_RANGES];
int range_count = height_range_json.size();
BOOST_LOG_TRIVIAL(debug) << boost::format("Plate %1%, assemble object %2% has %3% height ranges") % (plate_index + 1) %i % range_count;
assembled_param.height_ranges.resize(range_count);
for (int range_index = 0; range_index < range_count; range_index++)
{
height_range_info_t& height_range = assembled_param.height_ranges[range_index];
height_range.min_z = height_range_json[range_index][JSON_ASSEMPLE_OBJECT_MIN_Z];
height_range.max_z = height_range_json[range_index][JSON_ASSEMPLE_OBJECT_MAX_Z];
height_range.range_params = height_range_json[range_index][JSON_ASSEMPLE_OBJECT_RANGE_PARAMS].get<std::map<std::string, std::string>>();
}
}
assemble_plate.assembled_param_list.emplace(assemble_index, std::move(assembled_param));
}
BOOST_LOG_TRIVIAL(debug) << boost::format("Plate %1%, has %2% plate params") % (plate_index + 1) % assemble_plate.plate_params.size();
}
}
}
catch(std::exception &err) {
BOOST_LOG_TRIVIAL(error) << __FUNCTION__<< ": parse file "<<config_file<<" got a generic exception, reason = " << err.what();
ret = CLI_CONFIG_FILE_ERROR;
}
return ret;
}
void merge_or_add_object(assemble_plate_info_t& assemble_plate_info, Model &model, int assemble_index, std::map<int, ModelObject*> &merged_objects, ModelObject *ori_object)
{
if (assemble_index > 0) {
auto iter = merged_objects.find(assemble_index);
ModelObject* new_object = nullptr;
if (iter == merged_objects.end()) {
//create the object to merge
new_object = model.add_object();
new_object->name = "assemble_" + std::to_string(assemble_index);
merged_objects[assemble_index] = new_object;
assemble_plate_info.loaded_obj_list.emplace_back(new_object);
new_object->config.assign_config(ori_object->config.get());
}
else
new_object = iter->second;
for (auto volume : ori_object->volumes) {
ModelVolume* new_volume = new_object->add_volume(*volume);
// set extruder id
new_volume->config.set_key_value("extruder", new ConfigOptionInt(ori_object->config.extruder()));
}
BOOST_LOG_TRIVIAL(debug) << boost::format("assemble_index %1%, name %2%, merged to new model %3%") % assemble_index % ori_object->name % new_object->name;
}
else {
ModelObject* new_object = model.add_object(*ori_object);
assemble_plate_info.loaded_obj_list.emplace_back(new_object);
BOOST_LOG_TRIVIAL(debug) << boost::format("assemble_index %1%, name %2%, no need to merge, copy to new model") % assemble_index % ori_object->name;
}
}
bool convert_obj_cluster_colors(std::vector<Slic3r::RGBA>& input_colors, std::vector<RGBA>& all_colours, int max_filament_count, std::vector<unsigned char>& output_filament_ids, int& first_filament_id)
{
using namespace Slic3r::GUI;
BOOST_LOG_TRIVIAL(info) << boost::format("%1%:%2%, got original input obj colors %3%")%__FUNCTION__ %__LINE__ %input_colors.size();
if (input_colors.size() > 0) {
std::vector<Slic3r::RGBA> cluster_colors;
std::vector<int> cluster_labels;
char cluster_number = -1;
obj_color_deal_algo(input_colors, cluster_colors, cluster_labels, cluster_number);
std::vector<int> cluster_color_maps;
BOOST_LOG_TRIVIAL(info) << boost::format("%1%:%2%, after obj_color_deal_algo, cluster_colors size %3%, all_colours size %4%, max_filament_count=%5%")%__FUNCTION__ %__LINE__%cluster_colors.size() %all_colours.size() %max_filament_count;
cluster_color_maps.resize(cluster_colors.size(), 1);
int init_size = all_colours.size();
first_filament_id = max_filament_count;
for (size_t i = 0; i < cluster_colors.size(); i++) {
auto previous_color = std::find(all_colours.begin(), all_colours.end(), cluster_colors[i]);
if (previous_color != all_colours.end()) {
cluster_color_maps[i] = previous_color - all_colours.begin() + 1;
BOOST_LOG_TRIVIAL(info) << boost::format("%1%:%2%, cluster color index %3% RGBA {%4%,%5%,%6%,%7%} found same color before, id %8%")
%__FUNCTION__ %__LINE__%(i+1) %cluster_colors[i][0] %cluster_colors[i][1] %cluster_colors[i][2] %cluster_colors[i][3] %cluster_color_maps[i] ;
}
else {
if ((init_size + i + 1) <= max_filament_count) {
all_colours.push_back(cluster_colors[i]);
cluster_color_maps[i] = all_colours.size();
BOOST_LOG_TRIVIAL(info) << boost::format("%1%:%2%, cluster color index %3% RGBA {%4%,%5%,%6%,%7%} directly inserted, id %8%")
%__FUNCTION__ %__LINE__%(i+1) %cluster_colors[i][0] %cluster_colors[i][1] %cluster_colors[i][2] %cluster_colors[i][3] %cluster_color_maps[i] ;
}
else {
std::vector<ColorDistValue> color_dists;
color_dists.resize(max_filament_count);
for (size_t j = 0; j < max_filament_count; j++) {
color_dists[j].distance = calc_color_distance(cluster_colors[i], all_colours[j]);
color_dists[j].id = j + 1;
}
std::sort(color_dists.begin(), color_dists.end(), [](ColorDistValue &a, ColorDistValue &b) { return a.distance < b.distance; });
cluster_color_maps[i] = color_dists[0].id;
BOOST_LOG_TRIVIAL(info) << boost::format("%1%:%2%, color size reaches to max, cluster color index %3% RGBA {%4%,%5%,%6%,%7%} mapped to id %8%")
%__FUNCTION__ %__LINE__%(i+1) %cluster_colors[i][0] %cluster_colors[i][1] %cluster_colors[i][2] %cluster_colors[i][3] %cluster_color_maps[i] ;
}
}
if (cluster_color_maps[i] < first_filament_id)
first_filament_id = cluster_color_maps[i];
}
//3.generate filament_ids
auto input_colors_size = input_colors.size();
output_filament_ids.resize(input_colors_size);
for (size_t i = 0; i < input_colors_size; i++) {
int label = cluster_labels[i];
output_filament_ids[i] = cluster_color_maps[label];
}
BOOST_LOG_TRIVIAL(info) << boost::format("%1%:%2%, all_colours size changes to %3%, first_filament_id = %4%")%__FUNCTION__ %__LINE__%all_colours.size() %first_filament_id;
return true;
}
return false;
}
#ifdef _WIN32
#define DIR_SEPARATOR '\\'
#else
#define DIR_SEPARATOR '/'
#endif
static int construct_assemble_list(std::vector<assemble_plate_info_t> &assemble_plate_info_list, Model &model, PlateDataPtrs &plate_list, std::vector<RGBA>& all_colours)
{
int ret = 0;
int plate_count = assemble_plate_info_list.size();
ConfigSubstitutionContext config_substitutions(ForwardCompatibilitySubstitutionRule::Enable);
Model temp_model;
const int max_filament_count = size_t(EnforcerBlockerType::ExtruderMax);
plate_list.resize(plate_count);
for (int index = 0; index < plate_count; index++)
{
//each plate has its dependent assemble list
std::map<int, ModelObject*> merged_objects;
std::set<int> used_filaments;
//std::map<ModelObject*, int> to_merge_objects;
assemble_plate_info_t& assemble_plate_info = assemble_plate_info_list[index];
int object_count = assemble_plate_info.assemble_obj_list.size();
BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << boost::format(": Plate %1%, name %2%, obj count %3%, plate params count %4%") % (index + 1) %assemble_plate_info.plate_name %object_count %assemble_plate_info.plate_params.size();
PlateData* plate_data = new PlateData();
plate_list[index] = plate_data;
plate_data->plate_name = assemble_plate_info.plate_name;
plate_data->plate_index = index;
if (!assemble_plate_info.plate_params.empty())
{
for (auto plate_iter = assemble_plate_info.plate_params.begin(); plate_iter != assemble_plate_info.plate_params.end(); plate_iter++)
{
plate_data->config.set_deserialize(plate_iter->first, plate_iter->second, config_substitutions);
BOOST_LOG_TRIVIAL(debug) << __FUNCTION__ << boost::format(": Plate %1%, key %2%, value %3%") % (index + 1) % plate_iter->first % plate_iter->second;
}
}
//construct the object list
for (size_t obj_index = 0; obj_index < object_count; obj_index++)
{
assemble_object_info_t& assemble_object = assemble_plate_info.assemble_obj_list[obj_index];
std::string object_name;
std::string object_1_name;
ModelObject* object = nullptr;
TriangleMesh mesh;
bool skip_filament = false;
boost::filesystem::path object_path(assemble_object.path);
if (!fs::exists(object_path)) {
BOOST_LOG_TRIVIAL(error) << __FUNCTION__ << boost::format(": directory %1% not exist in plate %2%") % assemble_object.path % (index + 1);
return CLI_FILE_NOTFOUND;
}
const char* path_str = assemble_object.path.c_str();
const char* last_slash = strrchr(path_str, DIR_SEPARATOR);
object_name.assign((last_slash == nullptr) ? path_str : last_slash + 1);
if (boost::algorithm::iends_with(assemble_object.path, ".stl"))
{
if (!mesh.ReadSTLFile(path_str, true, nullptr)) {
BOOST_LOG_TRIVIAL(error) << __FUNCTION__ << boost::format(": failed to read stl file from %1%, plate index %2%, object index %3%") % assemble_object.path % (index+1) % (obj_index+1);
return CLI_DATA_FILE_ERROR;
}
if (mesh.empty()) {
BOOST_LOG_TRIVIAL(error) << __FUNCTION__ << boost::format(": found no mesh data from stl file %1%, plate index %2%, object index %3%") % assemble_object.path % (index + 1) % (obj_index + 1);
return CLI_DATA_FILE_ERROR;
}
object_name.erase(object_name.end() - 4, object_name.end());
object_1_name = object_name + "_1";
object = temp_model.add_object(object_1_name.c_str(), path_str, std::move(mesh));
if (!object) {
BOOST_LOG_TRIVIAL(error) << __FUNCTION__ << boost::format(": add_object %1% for stl failed, plate index %2%, object index %3%") % object_1_name % (index + 1) % (obj_index + 1);
return CLI_DATA_FILE_ERROR;
}
}
else if (boost::algorithm::iends_with(assemble_object.path, ".obj"))
{
std::string message;
ObjInfo obj_info;
bool result = load_obj(path_str, &mesh, obj_info, message);
if (!result) {
BOOST_LOG_TRIVIAL(error) << __FUNCTION__ << boost::format(": failed to read a valid mesh from obj file %1%, plate index %2%, object index %3%, error %4%") % assemble_object.path % (index + 1) % (obj_index + 1) % message;
return CLI_DATA_FILE_ERROR;
}
object_name.erase(object_name.end() - 4, object_name.end());
object_1_name = object_name + "_1";
//process colors
Model obj_temp_model;
ModelObject* temp_object = obj_temp_model.add_object(object_1_name.c_str(), path_str, std::move(mesh));
if (!temp_object) {
BOOST_LOG_TRIVIAL(error) << __FUNCTION__ << boost::format(": add_object %1% for obj failed, plate index %2%, object index %3%") % object_1_name % (index + 1) % (obj_index + 1);
return CLI_DATA_FILE_ERROR;
}
std::vector<unsigned char> output_filament_ids;
int first_filament_id;
if (obj_info.vertex_colors.size() > 0) {
convert_obj_cluster_colors(obj_info.vertex_colors, all_colours, max_filament_count, output_filament_ids, first_filament_id);
if (output_filament_ids.size() > 0) {
unsigned char first_eid = (unsigned char)first_filament_id;
result = Model::obj_import_vertex_color_deal(output_filament_ids, first_eid, & obj_temp_model);
}
skip_filament = true;
} else if (obj_info.face_colors.size() > 0 && obj_info.has_uv_png == false) { // mtl file
convert_obj_cluster_colors(obj_info.face_colors, all_colours, max_filament_count, output_filament_ids, first_filament_id);
if (output_filament_ids.size() > 0) {
unsigned char first_eid = (unsigned char)first_filament_id;
result = Model::obj_import_face_color_deal(output_filament_ids, first_eid, & obj_temp_model);
}
skip_filament = true;
}
if (!result) {
BOOST_LOG_TRIVIAL(error) << __FUNCTION__ << boost::format(": failed to convert colors for %1%, plate index %2%, object index %3%, error %4%") % assemble_object.path % (index + 1) % (obj_index + 1) % message;
return CLI_DATA_FILE_ERROR;
}
object = temp_model.add_object(*temp_object);
if (!object) {
BOOST_LOG_TRIVIAL(error) << __FUNCTION__ << boost::format(": add_object %1% for stl failed, plate index %2%, object index %3%") % object_1_name % (index + 1) % (obj_index + 1);
return CLI_DATA_FILE_ERROR;
}
obj_temp_model.clear_objects();
obj_temp_model.clear_materials();
}
else {
BOOST_LOG_TRIVIAL(error) << __FUNCTION__ << boost::format(": unsupported file %1%, plate index %2%, object index %3%") % assemble_object.path % (index + 1) % (obj_index + 1);
return CLI_INVALID_PARAMS;
}
if (!skip_filament) {
object->config.set_key_value("extruder", new ConfigOptionInt(assemble_object.filaments[0]));
used_filaments.emplace(assemble_object.filaments[0]);
}
else {
assemble_object.filaments[0] = 0;
for (const ModelVolume* mv : object->volumes) {
std::vector<int> volume_extruders = mv->get_extruders();
used_filaments.insert(volume_extruders.begin(), volume_extruders.end());
}
}
if (!assemble_object.print_params.empty())
{
for (auto param_iter = assemble_object.print_params.begin(); param_iter != assemble_object.print_params.end(); param_iter++)
{
object->config.set_deserialize(param_iter->first, param_iter->second, config_substitutions);
BOOST_LOG_TRIVIAL(debug) << boost::format("Plate %1%, object %2% key %3%, value %4%") % (index + 1) % object_1_name % param_iter->first % param_iter->second;
}
}